diff --git a/assets/卷帘大.glb b/assets/卷帘大.glb index 6f71ecb..9710eb9 100644 Binary files a/assets/卷帘大.glb and b/assets/卷帘大.glb differ diff --git a/assets/卷帘小.glb b/assets/卷帘小.glb index b346f2a..12a2012 100644 Binary files a/assets/卷帘小.glb and b/assets/卷帘小.glb differ diff --git a/assets/小桌.glb b/assets/小桌.glb index d92e917..e0c3abe 100644 Binary files a/assets/小桌.glb and b/assets/小桌.glb differ diff --git a/assets/框架.glb b/assets/框架.glb index a30815e..7aed96e 100644 Binary files a/assets/框架.glb and b/assets/框架.glb differ diff --git a/assets/百叶窗小.glb b/assets/百叶窗小.glb index cf43ec3..8efe915 100644 Binary files a/assets/百叶窗小.glb and b/assets/百叶窗小.glb differ diff --git a/examples/index copy.js b/examples/index copy.js new file mode 100644 index 0000000..5cce4f6 --- /dev/null +++ b/examples/index copy.js @@ -0,0 +1,297813 @@ +const isWeakRefSupported = typeof WeakRef !== "undefined"; +/** + * A class serves as a medium between the observable and its observers + */ +class EventState { + /** + * Create a new EventState + * @param mask defines the mask associated with this state + * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true + * @param target defines the original target of the state + * @param currentTarget defines the current target of the state + */ + constructor(mask, skipNextObservers = false, target, currentTarget) { + this.initialize(mask, skipNextObservers, target, currentTarget); + } + /** + * Initialize the current event state + * @param mask defines the mask associated with this state + * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true + * @param target defines the original target of the state + * @param currentTarget defines the current target of the state + * @returns the current event state + */ + initialize(mask, skipNextObservers = false, target, currentTarget) { + this.mask = mask; + this.skipNextObservers = skipNextObservers; + this.target = target; + this.currentTarget = currentTarget; + return this; + } +} +/** + * Represent an Observer registered to a given Observable object. + */ +class Observer { + /** + * Creates a new observer + * @param callback defines the callback to call when the observer is notified + * @param mask defines the mask of the observer (used to filter notifications) + * @param scope defines the current scope used to restore the JS context + */ + constructor( + /** + * Defines the callback to call when the observer is notified + */ + callback, + /** + * Defines the mask of the observer (used to filter notifications) + */ + mask, + /** + * [null] Defines the current scope used to restore the JS context + */ + scope = null) { + this.callback = callback; + this.mask = mask; + this.scope = scope; + /** @internal */ + this._willBeUnregistered = false; + /** + * Gets or sets a property defining that the observer as to be unregistered after the next notification + */ + this.unregisterOnNextCall = false; + /** + * this function can be used to remove the observer from the observable. + * It will be set by the observable that the observer belongs to. + * @internal + */ + this._remove = null; + } + /** + * Remove the observer from its observable + * This can be used instead of using the observable's remove function. + */ + remove() { + if (this._remove) { + this._remove(); + } + } +} +/** + * The Observable class is a simple implementation of the Observable pattern. + * + * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified. + * This enable a more fine grained execution without having to rely on multiple different Observable objects. + * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08). + * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right. + */ +class Observable { + /** + * Create an observable from a Promise. + * @param promise a promise to observe for fulfillment. + * @param onErrorObservable an observable to notify if a promise was rejected. + * @returns the new Observable + */ + static FromPromise(promise, onErrorObservable) { + const observable = new Observable(); + promise + .then((ret) => { + observable.notifyObservers(ret); + }) + .catch((err) => { + if (onErrorObservable) { + onErrorObservable.notifyObservers(err); + } + else { + throw err; + } + }); + return observable; + } + /** + * Gets the list of observers + * Note that observers that were recently deleted may still be present in the list because they are only really deleted on the next javascript tick! + */ + get observers() { + return this._observers; + } + /** + * Creates a new observable + * @param onObserverAdded defines a callback to call when a new observer is added + * @param notifyIfTriggered If set to true the observable will notify when an observer was added if the observable was already triggered. + */ + constructor(onObserverAdded, + /** + * [false] If set to true the observable will notify when an observer was added if the observable was already triggered. + * This is helpful to single-state observables like the scene onReady or the dispose observable. + */ + notifyIfTriggered = false) { + this.notifyIfTriggered = notifyIfTriggered; + this._observers = new Array(); + this._numObserversMarkedAsDeleted = 0; + this._hasNotified = false; + this._eventState = new EventState(0); + if (onObserverAdded) { + this._onObserverAdded = onObserverAdded; + } + } + add(callback, mask = -1, insertFirst = false, scope = null, unregisterOnFirstCall = false) { + if (!callback) { + return null; + } + const observer = new Observer(callback, mask, scope); + observer.unregisterOnNextCall = unregisterOnFirstCall; + if (insertFirst) { + this._observers.unshift(observer); + } + else { + this._observers.push(observer); + } + if (this._onObserverAdded) { + this._onObserverAdded(observer); + } + // If the observable was already triggered and the observable is set to notify if triggered, notify the new observer + if (this._hasNotified && this.notifyIfTriggered) { + if (this._lastNotifiedValue !== undefined) { + this.notifyObserver(observer, this._lastNotifiedValue); + } + } + // attach the remove function to the observer + const observableWeakRef = isWeakRefSupported ? new WeakRef(this) : { deref: () => this }; + observer._remove = () => { + const observable = observableWeakRef.deref(); + if (observable) { + observable._remove(observer); + } + }; + return observer; + } + addOnce(callback) { + return this.add(callback, undefined, undefined, undefined, true); + } + /** + * Remove an Observer from the Observable object + * @param observer the instance of the Observer to remove + * @returns false if it doesn't belong to this Observable + */ + remove(observer) { + if (!observer) { + return false; + } + observer._remove = null; + const index = this._observers.indexOf(observer); + if (index !== -1) { + this._deferUnregister(observer); + return true; + } + return false; + } + /** + * Remove a callback from the Observable object + * @param callback the callback to remove + * @param scope optional scope. If used only the callbacks with this scope will be removed + * @returns false if it doesn't belong to this Observable + */ + removeCallback(callback, scope) { + for (let index = 0; index < this._observers.length; index++) { + const observer = this._observers[index]; + if (observer._willBeUnregistered) { + continue; + } + if (observer.callback === callback && (!scope || scope === observer.scope)) { + this._deferUnregister(observer); + return true; + } + } + return false; + } + /** + * @internal + */ + _deferUnregister(observer) { + if (observer._willBeUnregistered) { + return; + } + this._numObserversMarkedAsDeleted++; + observer.unregisterOnNextCall = false; + observer._willBeUnregistered = true; + setTimeout(() => { + this._remove(observer); + }, 0); + } + // This should only be called when not iterating over _observers to avoid callback skipping. + // Removes an observer from the _observer Array. + _remove(observer, updateCounter = true) { + if (!observer) { + return false; + } + const index = this._observers.indexOf(observer); + if (index !== -1) { + if (updateCounter) { + this._numObserversMarkedAsDeleted--; + } + this._observers.splice(index, 1); + return true; + } + return false; + } + /** + * Moves the observable to the top of the observer list making it get called first when notified + * @param observer the observer to move + */ + makeObserverTopPriority(observer) { + this._remove(observer, false); + this._observers.unshift(observer); + } + /** + * Moves the observable to the bottom of the observer list making it get called last when notified + * @param observer the observer to move + */ + makeObserverBottomPriority(observer) { + this._remove(observer, false); + this._observers.push(observer); + } + /** + * Notify all Observers by calling their respective callback with the given data + * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute + * @param eventData defines the data to send to all observers + * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified) + * @param target defines the original target of the state + * @param currentTarget defines the current target of the state + * @param userInfo defines any user info to send to observers + * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true) + */ + notifyObservers(eventData, mask = -1, target, currentTarget, userInfo) { + // this prevents potential memory leaks - if an object is disposed but the observable doesn't get cleared. + if (this.notifyIfTriggered) { + this._hasNotified = true; + this._lastNotifiedValue = eventData; + } + if (!this._observers.length) { + return true; + } + const state = this._eventState; + state.mask = mask; + state.target = target; + state.currentTarget = currentTarget; + state.skipNextObservers = false; + state.lastReturnValue = eventData; + state.userInfo = userInfo; + for (const obs of this._observers) { + if (obs._willBeUnregistered) { + continue; + } + if (obs.mask & mask) { + if (obs.unregisterOnNextCall) { + this._deferUnregister(obs); + } + if (obs.scope) { + state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]); + } + else { + state.lastReturnValue = obs.callback(eventData, state); + } + } + if (state.skipNextObservers) { + return false; + } + } + return true; + } + /** + * Notify a specific observer + * @param observer defines the observer to notify + * @param eventData defines the data to be sent to each callback + * @param mask is used to filter observers defaults to -1 + */ + notifyObserver(observer, eventData, mask = -1) { + // this prevents potential memory leaks - if an object is disposed but the observable doesn't get cleared. + if (this.notifyIfTriggered) { + this._hasNotified = true; + this._lastNotifiedValue = eventData; + } + if (observer._willBeUnregistered) { + return; + } + const state = this._eventState; + state.mask = mask; + state.skipNextObservers = false; + if (observer.unregisterOnNextCall) { + this._deferUnregister(observer); + } + observer.callback(eventData, state); + } + /** + * Gets a boolean indicating if the observable has at least one observer + * @returns true is the Observable has at least one Observer registered + */ + hasObservers() { + return this._observers.length - this._numObserversMarkedAsDeleted > 0; + } + /** + * Clear the list of observers + */ + clear() { + while (this._observers.length) { + const o = this._observers.pop(); + if (o) { + o._remove = null; + } + } + this._onObserverAdded = null; + this._numObserversMarkedAsDeleted = 0; + this.cleanLastNotifiedState(); + } + /** + * Clean the last notified state - both the internal last value and the has-notified flag + */ + cleanLastNotifiedState() { + this._hasNotified = false; + this._lastNotifiedValue = undefined; + } + /** + * Clone the current observable + * @returns a new observable + */ + clone() { + const result = new Observable(); + result._observers = this._observers.slice(0); + return result; + } + /** + * Does this observable handles observer registered with a given mask + * @param mask defines the mask to be tested + * @returns whether or not one observer registered with the given mask is handled + **/ + hasSpecificMask(mask = -1) { + for (const obs of this._observers) { + if (obs.mask & mask || obs.mask === mask) { + return true; + } + } + return false; + } +} + +/** + * Class used to store a texture sampler data + */ +class TextureSampler { + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + get wrapU() { + return this._cachedWrapU; + } + set wrapU(value) { + this._cachedWrapU = value; + } + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + get wrapV() { + return this._cachedWrapV; + } + set wrapV(value) { + this._cachedWrapV = value; + } + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + get wrapR() { + return this._cachedWrapR; + } + set wrapR(value) { + this._cachedWrapR = value; + } + /** + * With compliant hardware and browser (supporting anisotropic filtering) + * this defines the level of anisotropic filtering in the texture. + * The higher the better but the slower. + */ + get anisotropicFilteringLevel() { + return this._cachedAnisotropicFilteringLevel; + } + set anisotropicFilteringLevel(value) { + this._cachedAnisotropicFilteringLevel = value; + } + /** + * Gets or sets the comparison function (513, 514, etc). Set 0 to not use a comparison function + */ + get comparisonFunction() { + return this._comparisonFunction; + } + set comparisonFunction(value) { + this._comparisonFunction = value; + } + /** + * Indicates to use the mip maps (if available on the texture). + * Thanks to this flag, you can instruct the sampler to not sample the mipmaps even if they exist (and if the sampling mode is set to a value that normally samples the mipmaps!) + */ + get useMipMaps() { + return this._useMipMaps; + } + set useMipMaps(value) { + this._useMipMaps = value; + } + /** + * Creates a Sampler instance + */ + constructor() { + /** + * Gets the sampling mode of the texture + */ + this.samplingMode = -1; + this._useMipMaps = true; + /** @internal */ + this._cachedWrapU = null; + /** @internal */ + this._cachedWrapV = null; + /** @internal */ + this._cachedWrapR = null; + /** @internal */ + this._cachedAnisotropicFilteringLevel = null; + /** @internal */ + this._comparisonFunction = 0; + } + /** + * Sets all the parameters of the sampler + * @param wrapU u address mode (default: TEXTURE_WRAP_ADDRESSMODE) + * @param wrapV v address mode (default: TEXTURE_WRAP_ADDRESSMODE) + * @param wrapR r address mode (default: TEXTURE_WRAP_ADDRESSMODE) + * @param anisotropicFilteringLevel anisotropic level (default: 1) + * @param samplingMode sampling mode (default: 2) + * @param comparisonFunction comparison function (default: 0 - no comparison function) + * @returns the current sampler instance + */ + setParameters(wrapU = 1, wrapV = 1, wrapR = 1, anisotropicFilteringLevel = 1, samplingMode = 2, comparisonFunction = 0) { + this._cachedWrapU = wrapU; + this._cachedWrapV = wrapV; + this._cachedWrapR = wrapR; + this._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel; + this.samplingMode = samplingMode; + this._comparisonFunction = comparisonFunction; + return this; + } + /** + * Compares this sampler with another one + * @param other sampler to compare with + * @returns true if the samplers have the same parametres, else false + */ + compareSampler(other) { + return (this._cachedWrapU === other._cachedWrapU && + this._cachedWrapV === other._cachedWrapV && + this._cachedWrapR === other._cachedWrapR && + this._cachedAnisotropicFilteringLevel === other._cachedAnisotropicFilteringLevel && + this.samplingMode === other.samplingMode && + this._comparisonFunction === other._comparisonFunction && + this._useMipMaps === other._useMipMaps); + } +} + +/** + * Defines the source of the internal texture + */ +var InternalTextureSource; +(function (InternalTextureSource) { + /** + * The source of the texture data is unknown + */ + InternalTextureSource[InternalTextureSource["Unknown"] = 0] = "Unknown"; + /** + * Texture data comes from an URL + */ + InternalTextureSource[InternalTextureSource["Url"] = 1] = "Url"; + /** + * Texture data is only used for temporary storage + */ + InternalTextureSource[InternalTextureSource["Temp"] = 2] = "Temp"; + /** + * Texture data comes from raw data (ArrayBuffer) + */ + InternalTextureSource[InternalTextureSource["Raw"] = 3] = "Raw"; + /** + * Texture content is dynamic (video or dynamic texture) + */ + InternalTextureSource[InternalTextureSource["Dynamic"] = 4] = "Dynamic"; + /** + * Texture content is generated by rendering to it + */ + InternalTextureSource[InternalTextureSource["RenderTarget"] = 5] = "RenderTarget"; + /** + * Texture content is part of a multi render target process + */ + InternalTextureSource[InternalTextureSource["MultiRenderTarget"] = 6] = "MultiRenderTarget"; + /** + * Texture data comes from a cube data file + */ + InternalTextureSource[InternalTextureSource["Cube"] = 7] = "Cube"; + /** + * Texture data comes from a raw cube data + */ + InternalTextureSource[InternalTextureSource["CubeRaw"] = 8] = "CubeRaw"; + /** + * Texture data come from a prefiltered cube data file + */ + InternalTextureSource[InternalTextureSource["CubePrefiltered"] = 9] = "CubePrefiltered"; + /** + * Texture content is raw 3D data + */ + InternalTextureSource[InternalTextureSource["Raw3D"] = 10] = "Raw3D"; + /** + * Texture content is raw 2D array data + */ + InternalTextureSource[InternalTextureSource["Raw2DArray"] = 11] = "Raw2DArray"; + /** + * Texture content is a depth/stencil texture + */ + InternalTextureSource[InternalTextureSource["DepthStencil"] = 12] = "DepthStencil"; + /** + * Texture data comes from a raw cube data encoded with RGBD + */ + InternalTextureSource[InternalTextureSource["CubeRawRGBD"] = 13] = "CubeRawRGBD"; + /** + * Texture content is a depth texture + */ + InternalTextureSource[InternalTextureSource["Depth"] = 14] = "Depth"; +})(InternalTextureSource || (InternalTextureSource = {})); +/** + * Class used to store data associated with WebGL texture data for the engine + * This class should not be used directly + */ +class InternalTexture extends TextureSampler { + /** + * Gets a boolean indicating if the texture uses mipmaps + * TODO implements useMipMaps as a separate setting from generateMipMaps + */ + get useMipMaps() { + return this.generateMipMaps; + } + set useMipMaps(value) { + this.generateMipMaps = value; + } + /** Gets the unique id of the internal texture */ + get uniqueId() { + return this._uniqueId; + } + /** @internal */ + _setUniqueId(id) { + this._uniqueId = id; + } + /** + * Gets the Engine the texture belongs to. + * @returns The babylon engine + */ + getEngine() { + return this._engine; + } + /** + * Gets the data source type of the texture + */ + get source() { + return this._source; + } + /** + * Creates a new InternalTexture + * @param engine defines the engine to use + * @param source defines the type of data that will be used + * @param delayAllocation if the texture allocation should be delayed (default: false) + */ + constructor(engine, source, delayAllocation = false) { + super(); + /** + * Defines if the texture is ready + */ + this.isReady = false; + /** + * Defines if the texture is a cube texture + */ + this.isCube = false; + /** + * Defines if the texture contains 3D data + */ + this.is3D = false; + /** + * Defines if the texture contains 2D array data + */ + this.is2DArray = false; + /** + * Defines if the texture contains multiview data + */ + this.isMultiview = false; + /** + * Gets the URL used to load this texture + */ + this.url = ""; + /** + * Gets a boolean indicating if the texture needs mipmaps generation + */ + this.generateMipMaps = false; + /** + * Gets the number of samples used by the texture (WebGL2+ only) + */ + this.samples = 0; + /** + * Gets the type of the texture (int, float...) + */ + this.type = -1; + /** + * Gets the format of the texture (RGB, RGBA...) + */ + this.format = -1; + /** + * Observable called when the texture is loaded + */ + this.onLoadedObservable = new Observable(); + /** + * Observable called when the texture load is raising an error + */ + this.onErrorObservable = new Observable(); + /** + * If this callback is defined it will be called instead of the default _rebuild function + */ + this.onRebuildCallback = null; + /** + * Gets the width of the texture + */ + this.width = 0; + /** + * Gets the height of the texture + */ + this.height = 0; + /** + * Gets the depth of the texture + */ + this.depth = 0; + /** + * Gets the initial width of the texture (It could be rescaled if the current system does not support non power of two textures) + */ + this.baseWidth = 0; + /** + * Gets the initial height of the texture (It could be rescaled if the current system does not support non power of two textures) + */ + this.baseHeight = 0; + /** + * Gets the initial depth of the texture (It could be rescaled if the current system does not support non power of two textures) + */ + this.baseDepth = 0; + /** + * Gets a boolean indicating if the texture is inverted on Y axis + */ + this.invertY = false; + // Private + /** @internal */ + this._invertVScale = false; + /** @internal */ + this._associatedChannel = -1; + /** @internal */ + this._source = 0 /* InternalTextureSource.Unknown */; + /** @internal */ + this._buffer = null; + /** @internal */ + this._bufferView = null; + /** @internal */ + this._bufferViewArray = null; + /** @internal */ + this._bufferViewArrayArray = null; + /** @internal */ + this._size = 0; + /** @internal */ + this._extension = ""; + /** @internal */ + this._files = null; + /** @internal */ + this._workingCanvas = null; + /** @internal */ + this._workingContext = null; + /** @internal */ + this._cachedCoordinatesMode = null; + /** @internal */ + this._isDisabled = false; + /** @internal */ + this._compression = null; + /** @internal */ + this._sphericalPolynomial = null; + /** @internal */ + this._sphericalPolynomialPromise = null; + /** @internal */ + this._sphericalPolynomialComputed = false; + /** @internal */ + this._lodGenerationScale = 0; + /** @internal */ + this._lodGenerationOffset = 0; + /** @internal */ + this._useSRGBBuffer = false; + /** @internal */ + this._creationFlags = 0; + // The following three fields helps sharing generated fixed LODs for texture filtering + // In environment not supporting the textureLOD extension like EDGE. They are for internal use only. + // They are at the level of the gl texture to benefit from the cache. + /** @internal */ + this._lodTextureHigh = null; + /** @internal */ + this._lodTextureMid = null; + /** @internal */ + this._lodTextureLow = null; + /** @internal */ + this._isRGBD = false; + /** @internal */ + this._linearSpecularLOD = false; + /** @internal */ + this._irradianceTexture = null; + /** @internal */ + this._hardwareTexture = null; + /** @internal */ + this._maxLodLevel = null; + /** @internal */ + this._references = 1; + /** @internal */ + this._gammaSpace = null; + /** @internal */ + this._premulAlpha = false; + /** @internal */ + this._dynamicTextureSource = null; + /** @internal */ + this._autoMSAAManagement = false; + this._engine = engine; + this._source = source; + this._uniqueId = InternalTexture._Counter++; + if (!delayAllocation) { + this._hardwareTexture = engine._createHardwareTexture(); + } + } + /** + * Increments the number of references (ie. the number of Texture that point to it) + */ + incrementReferences() { + this._references++; + } + /** + * Change the size of the texture (not the size of the content) + * @param width defines the new width + * @param height defines the new height + * @param depth defines the new depth (1 by default) + */ + updateSize(width, height, depth = 1) { + this._engine.updateTextureDimensions(this, width, height, depth); + this.width = width; + this.height = height; + this.depth = depth; + this.baseWidth = width; + this.baseHeight = height; + this.baseDepth = depth; + this._size = width * height * depth; + } + /** @internal */ + _rebuild() { + this.isReady = false; + this._cachedCoordinatesMode = null; + this._cachedWrapU = null; + this._cachedWrapV = null; + this._cachedWrapR = null; + this._cachedAnisotropicFilteringLevel = null; + if (this.onRebuildCallback) { + const data = this.onRebuildCallback(this); + const swapAndSetIsReady = (proxyInternalTexture) => { + proxyInternalTexture._swapAndDie(this, false); + this.isReady = data.isReady; + }; + if (data.isAsync) { + data.proxy.then(swapAndSetIsReady); + } + else { + swapAndSetIsReady(data.proxy); + } + return; + } + let proxy; + switch (this.source) { + case 2 /* InternalTextureSource.Temp */: + break; + case 1 /* InternalTextureSource.Url */: + proxy = this._engine.createTexture(this._originalUrl ?? this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, + // Do not use Proxy here as it could be fully synchronous + // and proxy would be undefined. + (temp) => { + temp._swapAndDie(this, false); + this.isReady = true; + }, null, this._buffer, undefined, this.format, this._extension, undefined, undefined, undefined, this._useSRGBBuffer); + return; + case 3 /* InternalTextureSource.Raw */: + proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type, this._creationFlags, this._useSRGBBuffer); + proxy._swapAndDie(this, false); + this.isReady = true; + break; + case 10 /* InternalTextureSource.Raw3D */: + proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type); + proxy._swapAndDie(this, false); + this.isReady = true; + break; + case 11 /* InternalTextureSource.Raw2DArray */: + proxy = this._engine.createRawTexture2DArray(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type); + proxy._swapAndDie(this, false); + this.isReady = true; + break; + case 4 /* InternalTextureSource.Dynamic */: + proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode); + proxy._swapAndDie(this, false); + if (this._dynamicTextureSource) { + this._engine.updateDynamicTexture(this, this._dynamicTextureSource, this.invertY, this._premulAlpha, this.format, true); + } + // The engine will make sure to update content so no need to flag it as isReady = true + break; + case 7 /* InternalTextureSource.Cube */: + proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, () => { + proxy._swapAndDie(this, false); + this.isReady = true; + }, null, this.format, this._extension, false, 0, 0, null, undefined, this._useSRGBBuffer, ArrayBuffer.isView(this._buffer) ? this._buffer : null); + return; + case 8 /* InternalTextureSource.CubeRaw */: + proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this._originalFormat ?? this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); + proxy._swapAndDie(this, false); + this.isReady = true; + break; + case 13 /* InternalTextureSource.CubeRawRGBD */: + // This case is being handeled by the environment texture tools and is not a part of the rebuild process. + // To use CubeRawRGBD use updateRGBDAsync on the cube texture. + return; + case 9 /* InternalTextureSource.CubePrefiltered */: + proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, (proxy) => { + if (proxy) { + proxy._swapAndDie(this, false); + } + this.isReady = true; + }, null, this.format, this._extension); + proxy._sphericalPolynomial = this._sphericalPolynomial; + return; + } + } + /** + * @internal + */ + _swapAndDie(target, swapAll = true) { + // TODO what about refcount on target? + this._hardwareTexture?.setUsage(target._source, this.generateMipMaps, this.is2DArray, this.isCube, this.is3D, this.width, this.height, this.depth); + target._hardwareTexture = this._hardwareTexture; + if (swapAll) { + target._isRGBD = this._isRGBD; + } + if (this._lodTextureHigh) { + if (target._lodTextureHigh) { + target._lodTextureHigh.dispose(); + } + target._lodTextureHigh = this._lodTextureHigh; + } + if (this._lodTextureMid) { + if (target._lodTextureMid) { + target._lodTextureMid.dispose(); + } + target._lodTextureMid = this._lodTextureMid; + } + if (this._lodTextureLow) { + if (target._lodTextureLow) { + target._lodTextureLow.dispose(); + } + target._lodTextureLow = this._lodTextureLow; + } + if (this._irradianceTexture) { + if (target._irradianceTexture) { + target._irradianceTexture.dispose(); + } + target._irradianceTexture = this._irradianceTexture; + } + const cache = this._engine.getLoadedTexturesCache(); + let index = cache.indexOf(this); + if (index !== -1) { + cache.splice(index, 1); + } + index = cache.indexOf(target); + if (index === -1) { + cache.push(target); + } + } + /** + * Dispose the current allocated resources + */ + dispose() { + this._references--; + if (this._references === 0) { + this.onLoadedObservable.clear(); + this.onErrorObservable.clear(); + this._engine._releaseTexture(this); + this._hardwareTexture = null; + this._dynamicTextureSource = null; + } + } +} +/** @internal */ +InternalTexture._Counter = 0; + +/** + * The engine store class is responsible to hold all the instances of Engine and Scene created + * during the life time of the application. + */ +class EngineStore { + /** + * Gets the latest created engine + */ + static get LastCreatedEngine() { + if (this.Instances.length === 0) { + return null; + } + return this.Instances[this.Instances.length - 1]; + } + /** + * Gets the latest created scene + */ + static get LastCreatedScene() { + return this._LastCreatedScene; + } +} +/** Gets the list of created engines */ +EngineStore.Instances = []; +/** + * Notifies when an engine was disposed. + * Mainly used for static/cache cleanup + */ +EngineStore.OnEnginesDisposedObservable = new Observable(); +/** @internal */ +EngineStore._LastCreatedScene = null; +/** + * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded + * @ignorenaming + */ +EngineStore.UseFallbackTexture = true; +/** + * Texture content used if a texture cannot loaded + * @ignorenaming + */ +EngineStore.FallbackTexture = ""; + +/** @internal */ +class WebGLPipelineContext { + constructor() { + this._valueCache = {}; + this.vertexCompilationError = null; + this.fragmentCompilationError = null; + this.programLinkError = null; + this.programValidationError = null; + /** @internal */ + this._isDisposed = false; + } + get isAsync() { + return this.isParallelCompiled; + } + get isReady() { + if (this.program) { + if (this.isParallelCompiled) { + return this.engine._isRenderingStateCompiled(this); + } + return true; + } + return false; + } + _handlesSpectorRebuildCallback(onCompiled) { + if (onCompiled && this.program) { + onCompiled(this.program); + } + } + setEngine(engine) { + this.engine = engine; + } + _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) { + const engine = this.engine; + if (engine.supportsUniformBuffers) { + for (const name in uniformBuffersNames) { + effect.bindUniformBlock(name, uniformBuffersNames[name]); + } + } + const effectAvailableUniforms = this.engine.getUniforms(this, uniformsNames); + effectAvailableUniforms.forEach((uniform, index) => { + uniforms[uniformsNames[index]] = uniform; + }); + this._uniforms = uniforms; + let index; + for (index = 0; index < samplerList.length; index++) { + const sampler = effect.getUniform(samplerList[index]); + if (sampler == null) { + samplerList.splice(index, 1); + index--; + } + } + samplerList.forEach((name, index) => { + samplers[name] = index; + }); + for (const attr of engine.getAttributes(this, attributesNames)) { + attributes.push(attr); + } + } + /** + * Release all associated resources. + **/ + dispose() { + this._uniforms = {}; + this._isDisposed = true; + } + /** + * @internal + */ + _cacheMatrix(uniformName, matrix) { + const cache = this._valueCache[uniformName]; + const flag = matrix.updateFlag; + if (cache !== undefined && cache === flag) { + return false; + } + this._valueCache[uniformName] = flag; + return true; + } + /** + * @internal + */ + _cacheFloat2(uniformName, x, y) { + let cache = this._valueCache[uniformName]; + if (!cache || cache.length !== 2) { + cache = [x, y]; + this._valueCache[uniformName] = cache; + return true; + } + let changed = false; + if (cache[0] !== x) { + cache[0] = x; + changed = true; + } + if (cache[1] !== y) { + cache[1] = y; + changed = true; + } + return changed; + } + /** + * @internal + */ + _cacheFloat3(uniformName, x, y, z) { + let cache = this._valueCache[uniformName]; + if (!cache || cache.length !== 3) { + cache = [x, y, z]; + this._valueCache[uniformName] = cache; + return true; + } + let changed = false; + if (cache[0] !== x) { + cache[0] = x; + changed = true; + } + if (cache[1] !== y) { + cache[1] = y; + changed = true; + } + if (cache[2] !== z) { + cache[2] = z; + changed = true; + } + return changed; + } + /** + * @internal + */ + _cacheFloat4(uniformName, x, y, z, w) { + let cache = this._valueCache[uniformName]; + if (!cache || cache.length !== 4) { + cache = [x, y, z, w]; + this._valueCache[uniformName] = cache; + return true; + } + let changed = false; + if (cache[0] !== x) { + cache[0] = x; + changed = true; + } + if (cache[1] !== y) { + cache[1] = y; + changed = true; + } + if (cache[2] !== z) { + cache[2] = z; + changed = true; + } + if (cache[3] !== w) { + cache[3] = w; + changed = true; + } + return changed; + } + /** + * Sets an integer value on a uniform variable. + * @param uniformName Name of the variable. + * @param value Value to be set. + */ + setInt(uniformName, value) { + const cache = this._valueCache[uniformName]; + if (cache !== undefined && cache === value) { + return; + } + if (this.engine.setInt(this._uniforms[uniformName], value)) { + this._valueCache[uniformName] = value; + } + } + /** + * Sets a int2 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int2. + * @param y Second int in int2. + */ + setInt2(uniformName, x, y) { + if (this._cacheFloat2(uniformName, x, y)) { + if (!this.engine.setInt2(this._uniforms[uniformName], x, y)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a int3 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int3. + * @param y Second int in int3. + * @param z Third int in int3. + */ + setInt3(uniformName, x, y, z) { + if (this._cacheFloat3(uniformName, x, y, z)) { + if (!this.engine.setInt3(this._uniforms[uniformName], x, y, z)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a int4 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int4. + * @param y Second int in int4. + * @param z Third int in int4. + * @param w Fourth int in int4. + */ + setInt4(uniformName, x, y, z, w) { + if (this._cacheFloat4(uniformName, x, y, z, w)) { + if (!this.engine.setInt4(this._uniforms[uniformName], x, y, z, w)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets an int array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setIntArray(this._uniforms[uniformName], array); + } + /** + * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray2(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setIntArray2(this._uniforms[uniformName], array); + } + /** + * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray3(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setIntArray3(this._uniforms[uniformName], array); + } + /** + * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray4(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setIntArray4(this._uniforms[uniformName], array); + } + /** + * Sets an unsigned integer value on a uniform variable. + * @param uniformName Name of the variable. + * @param value Value to be set. + */ + setUInt(uniformName, value) { + const cache = this._valueCache[uniformName]; + if (cache !== undefined && cache === value) { + return; + } + if (this.engine.setUInt(this._uniforms[uniformName], value)) { + this._valueCache[uniformName] = value; + } + } + /** + * Sets an unsigned int2 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint2. + * @param y Second unsigned int in uint2. + */ + setUInt2(uniformName, x, y) { + if (this._cacheFloat2(uniformName, x, y)) { + if (!this.engine.setUInt2(this._uniforms[uniformName], x, y)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets an unsigned int3 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint3. + * @param y Second unsigned int in uint3. + * @param z Third unsigned int in uint3. + */ + setUInt3(uniformName, x, y, z) { + if (this._cacheFloat3(uniformName, x, y, z)) { + if (!this.engine.setUInt3(this._uniforms[uniformName], x, y, z)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets an unsigned int4 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint4. + * @param y Second unsigned int in uint4. + * @param z Third unsigned int in uint4. + * @param w Fourth unsigned int in uint4. + */ + setUInt4(uniformName, x, y, z, w) { + if (this._cacheFloat4(uniformName, x, y, z, w)) { + if (!this.engine.setUInt4(this._uniforms[uniformName], x, y, z, w)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets an unsigned int array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setUIntArray(this._uniforms[uniformName], array); + } + /** + * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray2(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setUIntArray2(this._uniforms[uniformName], array); + } + /** + * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray3(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setUIntArray3(this._uniforms[uniformName], array); + } + /** + * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray4(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setUIntArray4(this._uniforms[uniformName], array); + } + /** + * Sets an array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setArray(this._uniforms[uniformName], array); + } + /** + * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray2(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setArray2(this._uniforms[uniformName], array); + } + /** + * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray3(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setArray3(this._uniforms[uniformName], array); + } + /** + * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray4(uniformName, array) { + this._valueCache[uniformName] = null; + this.engine.setArray4(this._uniforms[uniformName], array); + } + /** + * Sets matrices on a uniform variable. + * @param uniformName Name of the variable. + * @param matrices matrices to be set. + */ + setMatrices(uniformName, matrices) { + if (!matrices) { + return; + } + this._valueCache[uniformName] = null; + this.engine.setMatrices(this._uniforms[uniformName], matrices); + } + /** + * Sets matrix on a uniform variable. + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + */ + setMatrix(uniformName, matrix) { + if (this._cacheMatrix(uniformName, matrix)) { + if (!this.engine.setMatrices(this._uniforms[uniformName], matrix.asArray())) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix) + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + */ + setMatrix3x3(uniformName, matrix) { + this._valueCache[uniformName] = null; + this.engine.setMatrix3x3(this._uniforms[uniformName], matrix); + } + /** + * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix) + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + */ + setMatrix2x2(uniformName, matrix) { + this._valueCache[uniformName] = null; + this.engine.setMatrix2x2(this._uniforms[uniformName], matrix); + } + /** + * Sets a float on a uniform variable. + * @param uniformName Name of the variable. + * @param value value to be set. + */ + setFloat(uniformName, value) { + const cache = this._valueCache[uniformName]; + if (cache !== undefined && cache === value) { + return; + } + if (this.engine.setFloat(this._uniforms[uniformName], value)) { + this._valueCache[uniformName] = value; + } + } + /** + * Sets a Vector2 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector2 vector2 to be set. + */ + setVector2(uniformName, vector2) { + if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) { + if (!this.engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a float2 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float2. + * @param y Second float in float2. + */ + setFloat2(uniformName, x, y) { + if (this._cacheFloat2(uniformName, x, y)) { + if (!this.engine.setFloat2(this._uniforms[uniformName], x, y)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Vector3 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector3 Value to be set. + */ + setVector3(uniformName, vector3) { + if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) { + if (!this.engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a float3 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float3. + * @param y Second float in float3. + * @param z Third float in float3. + */ + setFloat3(uniformName, x, y, z) { + if (this._cacheFloat3(uniformName, x, y, z)) { + if (!this.engine.setFloat3(this._uniforms[uniformName], x, y, z)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Vector4 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector4 Value to be set. + */ + setVector4(uniformName, vector4) { + if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) { + if (!this.engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Quaternion on a uniform variable. + * @param uniformName Name of the variable. + * @param quaternion Value to be set. + */ + setQuaternion(uniformName, quaternion) { + if (this._cacheFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w)) { + if (!this.engine.setFloat4(this._uniforms[uniformName], quaternion.x, quaternion.y, quaternion.z, quaternion.w)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a float4 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float4. + * @param y Second float in float4. + * @param z Third float in float4. + * @param w Fourth float in float4. + */ + setFloat4(uniformName, x, y, z, w) { + if (this._cacheFloat4(uniformName, x, y, z, w)) { + if (!this.engine.setFloat4(this._uniforms[uniformName], x, y, z, w)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Color3 on a uniform variable. + * @param uniformName Name of the variable. + * @param color3 Value to be set. + */ + setColor3(uniformName, color3) { + if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) { + if (!this.engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Color4 on a uniform variable. + * @param uniformName Name of the variable. + * @param color3 Value to be set. + * @param alpha Alpha value to be set. + */ + setColor4(uniformName, color3, alpha) { + if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) { + if (!this.engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Color4 on a uniform variable + * @param uniformName defines the name of the variable + * @param color4 defines the value to be set + */ + setDirectColor4(uniformName, color4) { + if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) { + if (!this.engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a)) { + this._valueCache[uniformName] = null; + } + } + } + _getVertexShaderCode() { + return this.vertexShader ? this.engine._getShaderSource(this.vertexShader) : null; + } + _getFragmentShaderCode() { + return this.fragmentShader ? this.engine._getShaderSource(this.fragmentShader) : null; + } +} + +const warnedMap = {}; +/** + * @internal + */ +function _WarnImport(name, warnOnce = false) { + if (warnOnce && warnedMap[name]) { + return; + } + warnedMap[name] = true; + return `${name} needs to be imported before as it contains a side-effect required by your code.`; +} + +/* eslint-disable @typescript-eslint/naming-convention */ +/** + * Checks if the window object exists + * @returns true if the window object exists + */ +function IsWindowObjectExist() { + return typeof window !== "undefined"; +} +/** + * Checks if the navigator object exists + * @returns true if the navigator object exists + */ +function IsNavigatorAvailable() { + return typeof navigator !== "undefined"; +} +/** + * Check if the document object exists + * @returns true if the document object exists + */ +function IsDocumentAvailable() { + return typeof document !== "undefined"; +} +/** + * Extracts text content from a DOM element hierarchy + * @param element defines the root element + * @returns a string + */ +function GetDOMTextContent(element) { + let result = ""; + let child = element.firstChild; + while (child) { + if (child.nodeType === 3) { + result += child.textContent; + } + child = child.nextSibling; + } + return result; +} + +const EngineFunctionContext = {}; +/** + * @internal + */ +function _ConcatenateShader(source, defines, shaderVersion = "") { + return shaderVersion + (defines ? defines + "\n" : "") + source; +} +/** + * @internal + */ +function _loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, injectedLoadFile) { + const loadFile = injectedLoadFile || EngineFunctionContext.loadFile; + if (loadFile) { + const request = loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); + return request; + } + throw _WarnImport("FileTools"); +} +/** @internal */ +function _getGlobalDefines(defines, isNDCHalfZRange, useReverseDepthBuffer, useExactSrgbConversions) { + if (defines) { + if (isNDCHalfZRange) { + defines["IS_NDC_HALF_ZRANGE"] = ""; + } + else { + delete defines["IS_NDC_HALF_ZRANGE"]; + } + if (useReverseDepthBuffer) { + defines["USE_REVERSE_DEPTHBUFFER"] = ""; + } + else { + delete defines["USE_REVERSE_DEPTHBUFFER"]; + } + if (useExactSrgbConversions) { + defines["USE_EXACT_SRGB_CONVERSIONS"] = ""; + } + else { + delete defines["USE_EXACT_SRGB_CONVERSIONS"]; + } + return; + } + else { + let s = ""; + if (isNDCHalfZRange) { + s += "#define IS_NDC_HALF_ZRANGE"; + } + if (useReverseDepthBuffer) { + if (s) { + s += "\n"; + } + s += "#define USE_REVERSE_DEPTHBUFFER"; + } + if (useExactSrgbConversions) { + if (s) { + s += "\n"; + } + s += "#define USE_EXACT_SRGB_CONVERSIONS"; + } + return s; + } +} +/** + * Allocate a typed array depending on a texture type. Optionally can copy existing data in the buffer. + * @param type type of the texture + * @param sizeOrDstBuffer size of the array OR an existing buffer that will be used as the destination of the copy (if copyBuffer is provided) + * @param sizeInBytes true if the size of the array is given in bytes, false if it is the number of elements of the array + * @param copyBuffer if provided, buffer to copy into the destination buffer (either a newly allocated buffer if sizeOrDstBuffer is a number or use sizeOrDstBuffer as the destination buffer otherwise) + * @returns the allocated buffer or sizeOrDstBuffer if the latter is an ArrayBuffer + */ +function allocateAndCopyTypedBuffer(type, sizeOrDstBuffer, sizeInBytes = false, copyBuffer) { + switch (type) { + case 3: { + const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int8Array(sizeOrDstBuffer) : new Int8Array(sizeOrDstBuffer); + if (copyBuffer) { + buffer.set(new Int8Array(copyBuffer)); + } + return buffer; + } + case 0: { + const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer); + if (copyBuffer) { + buffer.set(new Uint8Array(copyBuffer)); + } + return buffer; + } + case 4: { + const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int16Array(sizeOrDstBuffer) : new Int16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer); + if (copyBuffer) { + buffer.set(new Int16Array(copyBuffer)); + } + return buffer; + } + case 5: + case 8: + case 9: + case 10: + case 2: { + const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint16Array(sizeOrDstBuffer) : new Uint16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer); + if (copyBuffer) { + buffer.set(new Uint16Array(copyBuffer)); + } + return buffer; + } + case 6: { + const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int32Array(sizeOrDstBuffer) : new Int32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer); + if (copyBuffer) { + buffer.set(new Int32Array(copyBuffer)); + } + return buffer; + } + case 7: + case 11: + case 12: + case 13: + case 14: + case 15: { + const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint32Array(sizeOrDstBuffer) : new Uint32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer); + if (copyBuffer) { + buffer.set(new Uint32Array(copyBuffer)); + } + return buffer; + } + case 1: { + const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Float32Array(sizeOrDstBuffer) : new Float32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer); + if (copyBuffer) { + buffer.set(new Float32Array(copyBuffer)); + } + return buffer; + } + } + const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer); + if (copyBuffer) { + buffer.set(new Uint8Array(copyBuffer)); + } + return buffer; +} + +/** + * @internal + */ +const _stateObject = new WeakMap(); +/** + * This will be used in cases where the engine doesn't have a context (like the nullengine) + */ +const singleStateObject = { + _webGLVersion: 2, + cachedPipelines: {}, +}; +/** + * get or create a state object for the given context + * Note - Used in WebGL only at the moment. + * @param context The context to get the state object from + * @returns the state object + * @internal + */ +function getStateObject(context) { + let state = _stateObject.get(context); + if (!state) { + if (!context) { + return singleStateObject; + } + state = { + // use feature detection. instanceof returns false. This only exists on WebGL2 context + _webGLVersion: context.TEXTURE_BINDING_3D ? 2 : 1, + _context: context, + // when using the function without an engine we need to set it to enable parallel compilation + parallelShaderCompile: context.getExtension("KHR_parallel_shader_compile") || undefined, + cachedPipelines: {}, + }; + _stateObject.set(context, state); + } + return state; +} +/** + * Remove the state object that belongs to the specific context + * @param context the context that is being + */ +function deleteStateObject(context) { + _stateObject.delete(context); +} +/** + * Directly creates a webGL program + * @param pipelineContext defines the pipeline context to attach to + * @param vertexCode defines the vertex shader code to use + * @param fragmentCode defines the fragment shader code to use + * @param context defines the webGL context to use (if not set, the current one will be used) + * @param transformFeedbackVaryings defines the list of transform feedback varyings to use + * @param _createShaderProgramInjection defines an optional injection to use to create the shader program + * @returns the new webGL program + */ +function createRawShaderProgram(pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings, _createShaderProgramInjection) { + const stateObject = getStateObject(context); + if (!_createShaderProgramInjection) { + _createShaderProgramInjection = stateObject._createShaderProgramInjection ?? _createShaderProgram; + } + const vertexShader = _compileRawShader(vertexCode, "vertex", context, stateObject._contextWasLost); + const fragmentShader = _compileRawShader(fragmentCode, "fragment", context, stateObject._contextWasLost); + return _createShaderProgramInjection(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings, stateObject.validateShaderPrograms); +} +/** + * Creates a webGL program + * @param pipelineContext defines the pipeline context to attach to + * @param vertexCode defines the vertex shader code to use + * @param fragmentCode defines the fragment shader code to use + * @param defines defines the string containing the defines to use to compile the shaders + * @param context defines the webGL context to use (if not set, the current one will be used) + * @param transformFeedbackVaryings defines the list of transform feedback varyings to use + * @param _createShaderProgramInjection defines an optional injection to use to create the shader program + * @returns the new webGL program + */ +function createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null, _createShaderProgramInjection) { + const stateObject = getStateObject(context); + if (!_createShaderProgramInjection) { + _createShaderProgramInjection = stateObject._createShaderProgramInjection ?? _createShaderProgram; + } + const shaderVersion = stateObject._webGLVersion > 1 ? "#version 300 es\n#define WEBGL2 \n" : ""; + const vertexShader = _compileShader(vertexCode, "vertex", defines, shaderVersion, context, stateObject._contextWasLost); + const fragmentShader = _compileShader(fragmentCode, "fragment", defines, shaderVersion, context, stateObject._contextWasLost); + return _createShaderProgramInjection(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings, stateObject.validateShaderPrograms); +} +/** + * Creates a new pipeline context. Note, make sure to attach an engine instance to the created context + * @param context defines the webGL context to use (if not set, the current one will be used) + * @param _shaderProcessingContext defines the shader processing context used during the processing if available + * @returns the new pipeline + */ +function createPipelineContext(context, _shaderProcessingContext) { + const pipelineContext = new WebGLPipelineContext(); + const stateObject = getStateObject(context); + if (stateObject.parallelShaderCompile && !stateObject.disableParallelShaderCompile) { + pipelineContext.isParallelCompiled = true; + } + pipelineContext.context = stateObject._context; + return pipelineContext; +} +/** + * @internal + */ +function _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, _transformFeedbackVaryings = null, validateShaderPrograms) { + const shaderProgram = context.createProgram(); + pipelineContext.program = shaderProgram; + if (!shaderProgram) { + throw new Error("Unable to create program"); + } + context.attachShader(shaderProgram, vertexShader); + context.attachShader(shaderProgram, fragmentShader); + context.linkProgram(shaderProgram); + pipelineContext.context = context; + pipelineContext.vertexShader = vertexShader; + pipelineContext.fragmentShader = fragmentShader; + if (!pipelineContext.isParallelCompiled) { + _finalizePipelineContext(pipelineContext, context, validateShaderPrograms); + } + return shaderProgram; +} +/** + * @internal + */ +function _isRenderingStateCompiled(pipelineContext, gl, validateShaderPrograms) { + const webGLPipelineContext = pipelineContext; + if (webGLPipelineContext._isDisposed) { + return false; + } + const stateObject = getStateObject(gl); + if (stateObject && stateObject.parallelShaderCompile && stateObject.parallelShaderCompile.COMPLETION_STATUS_KHR && webGLPipelineContext.program) { + if (gl.getProgramParameter(webGLPipelineContext.program, stateObject.parallelShaderCompile.COMPLETION_STATUS_KHR)) { + _finalizePipelineContext(webGLPipelineContext, gl, validateShaderPrograms); + return true; + } + } + return false; +} +/** + * @internal + */ +function _finalizePipelineContext(pipelineContext, gl, validateShaderPrograms) { + const context = pipelineContext.context; + const vertexShader = pipelineContext.vertexShader; + const fragmentShader = pipelineContext.fragmentShader; + const program = pipelineContext.program; + const linked = context.getProgramParameter(program, context.LINK_STATUS); + if (!linked) { + // Get more info + // Vertex + if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) { + const log = gl.getShaderInfoLog(vertexShader); + if (log) { + pipelineContext.vertexCompilationError = log; + throw new Error("VERTEX SHADER " + log); + } + } + // Fragment + if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) { + const log = gl.getShaderInfoLog(fragmentShader); + if (log) { + pipelineContext.fragmentCompilationError = log; + throw new Error("FRAGMENT SHADER " + log); + } + } + const error = context.getProgramInfoLog(program); + if (error) { + pipelineContext.programLinkError = error; + throw new Error(error); + } + } + if ( /*this.*/validateShaderPrograms) { + context.validateProgram(program); + const validated = context.getProgramParameter(program, context.VALIDATE_STATUS); + if (!validated) { + const error = context.getProgramInfoLog(program); + if (error) { + pipelineContext.programValidationError = error; + throw new Error(error); + } + } + } + context.deleteShader(vertexShader); + context.deleteShader(fragmentShader); + pipelineContext.vertexShader = undefined; + pipelineContext.fragmentShader = undefined; + if (pipelineContext.onCompiled) { + pipelineContext.onCompiled(); + pipelineContext.onCompiled = undefined; + } +} +/** + * @internal + */ +function _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, _rawVertexSourceCode, _rawFragmentSourceCode, rebuildRebind, defines, transformFeedbackVaryings, _key = "", onReady, createRawShaderProgramInjection, createShaderProgramInjection) { + const stateObject = getStateObject(pipelineContext.context); + if (!createRawShaderProgramInjection) { + createRawShaderProgramInjection = stateObject.createRawShaderProgramInjection ?? createRawShaderProgram; + } + if (!createShaderProgramInjection) { + createShaderProgramInjection = stateObject.createShaderProgramInjection ?? createShaderProgram; + } + const webGLRenderingState = pipelineContext; + if (createAsRaw) { + webGLRenderingState.program = createRawShaderProgramInjection(webGLRenderingState, vertexSourceCode, fragmentSourceCode, webGLRenderingState.context, transformFeedbackVaryings); + } + else { + webGLRenderingState.program = createShaderProgramInjection(webGLRenderingState, vertexSourceCode, fragmentSourceCode, defines, webGLRenderingState.context, transformFeedbackVaryings); + } + webGLRenderingState.program.__SPECTOR_rebuildProgram = rebuildRebind; + onReady(); +} +function _compileShader(source, type, defines, shaderVersion, gl, _contextWasLost) { + return _compileRawShader(_ConcatenateShader(source, defines, shaderVersion), type, gl, _contextWasLost); +} +function _compileRawShader(source, type, gl, _contextWasLost) { + const shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER); + if (!shader) { + let error = gl.NO_ERROR; + let tempError = gl.NO_ERROR; + while ((tempError = gl.getError()) !== gl.NO_ERROR) { + error = tempError; + } + throw new Error(`Something went wrong while creating a gl ${type} shader object. gl error=${error}, gl isContextLost=${gl.isContextLost()}, _contextWasLost=${_contextWasLost}`); + } + gl.shaderSource(shader, source); + gl.compileShader(shader); + return shader; +} +/** + * @internal + */ +function _setProgram(program, gl) { + gl.useProgram(program); +} +/** + * @internal + */ +function _executeWhenRenderingStateIsCompiled(pipelineContext, action) { + const webGLPipelineContext = pipelineContext; + if (!webGLPipelineContext.isParallelCompiled) { + action(pipelineContext); + return; + } + const oldHandler = webGLPipelineContext.onCompiled; + webGLPipelineContext.onCompiled = () => { + oldHandler?.(); + action(pipelineContext); + }; +} + +/** + * Detect if the effect is a DrawWrapper + * @param effect defines the entity to test + * @returns if the entity is a DrawWrapper + */ +function IsWrapper(effect) { + return effect.getPipelineContext === undefined; +} + +/* eslint-disable no-console */ +/** + * Logger used throughout the application to allow configuration of + * the log level required for the messages. + */ +class Logger { + static _CheckLimit(message, limit) { + let entry = Logger._LogLimitOutputs[message]; + if (!entry) { + entry = { limit, current: 1 }; + Logger._LogLimitOutputs[message] = entry; + } + else { + entry.current++; + } + return entry.current <= entry.limit; + } + static _GenerateLimitMessage(message, level = 1) { + const entry = Logger._LogLimitOutputs[message]; + if (!entry || !Logger.MessageLimitReached) { + return; + } + const type = this._Levels[level]; + if (entry.current === entry.limit) { + Logger[type.name](Logger.MessageLimitReached.replace(/%LIMIT%/g, "" + entry.limit).replace(/%TYPE%/g, type.name ?? "")); + } + } + static _AddLogEntry(entry) { + Logger._LogCache = entry + Logger._LogCache; + if (Logger.OnNewCacheEntry) { + Logger.OnNewCacheEntry(entry); + } + } + static _FormatMessage(message) { + const padStr = (i) => (i < 10 ? "0" + i : "" + i); + const date = new Date(); + return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static _LogDisabled(message, limit) { + // nothing to do + } + static _LogEnabled(level = 1, message, limit) { + // take first message if array + const msg = Array.isArray(message) ? message[0] : message; + if (limit !== undefined && !Logger._CheckLimit(msg, limit)) { + return; + } + const formattedMessage = Logger._FormatMessage(msg); + const type = this._Levels[level]; + const optionals = Array.isArray(message) ? message.slice(1) : []; + type.logFunc && type.logFunc("BJS - " + formattedMessage, ...optionals); + const entry = `
${formattedMessage}

`; + Logger._AddLogEntry(entry); + Logger._GenerateLimitMessage(msg, level); + } + /** + * Gets current log cache (list of logs) + */ + static get LogCache() { + return Logger._LogCache; + } + /** + * Clears the log cache + */ + static ClearLogCache() { + Logger._LogCache = ""; + Logger._LogLimitOutputs = {}; + Logger.errorsCount = 0; + } + /** + * Sets the current log level. This property is a bit field, allowing you to combine different levels (MessageLogLevel / WarningLogLevel / ErrorLogLevel). + * Use NoneLogLevel to disable logging and AllLogLevel for a quick way to enable all levels. + */ + static set LogLevels(level) { + Logger.Log = Logger._LogDisabled; + Logger.Warn = Logger._LogDisabled; + Logger.Error = Logger._LogDisabled; + [Logger.MessageLogLevel, Logger.WarningLogLevel, Logger.ErrorLogLevel].forEach((l) => { + if ((level & l) === l) { + const type = this._Levels[l]; + Logger[type.name] = Logger._LogEnabled.bind(Logger, l); + } + }); + } +} +/** + * No log + */ +Logger.NoneLogLevel = 0; +/** + * Only message logs + */ +Logger.MessageLogLevel = 1; +/** + * Only warning logs + */ +Logger.WarningLogLevel = 2; +/** + * Only error logs + */ +Logger.ErrorLogLevel = 4; +/** + * All logs + */ +Logger.AllLogLevel = 7; +/** + * Message to display when a message has been logged too many times + */ +Logger.MessageLimitReached = "Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message."; +Logger._LogCache = ""; +Logger._LogLimitOutputs = {}; +// levels according to the (binary) numbering. +Logger._Levels = [ + {}, + { color: "white", logFunc: console.log, name: "Log" }, + { color: "orange", logFunc: console.warn, name: "Warn" }, + {}, + { color: "red", logFunc: console.error, name: "Error" }, +]; +/** + * Gets a value indicating the number of loading errors + * @ignorenaming + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +Logger.errorsCount = 0; +/** + * Log a message to the console + */ +Logger.Log = Logger._LogEnabled.bind(Logger, Logger.MessageLogLevel); +/** + * Write a warning message to the console + */ +Logger.Warn = Logger._LogEnabled.bind(Logger, Logger.WarningLogLevel); +/** + * Write an error message to the console + */ +Logger.Error = Logger._LogEnabled.bind(Logger, Logger.ErrorLogLevel); + +/** @internal */ +class WebGLShaderProcessor { + constructor() { + this.shaderLanguage = 0 /* ShaderLanguage.GLSL */; + } + postProcessor(code, defines, isFragment, processingContext, parameters) { + // Remove extensions + if (parameters.drawBuffersExtensionDisabled) { + // even if enclosed in #if/#endif, IE11 does parse the #extension declaration, so we need to remove it altogether + const regex = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g; + code = code.replace(regex, ""); + } + return code; + } +} + +const varyingRegex$1 = /(flat\s)?\s*varying\s*.*/; +/** @internal */ +class WebGL2ShaderProcessor { + constructor() { + this.shaderLanguage = 0 /* ShaderLanguage.GLSL */; + } + attributeProcessor(attribute) { + return attribute.replace("attribute", "in"); + } + varyingCheck(varying, _isFragment) { + return varyingRegex$1.test(varying); + } + varyingProcessor(varying, isFragment) { + return varying.replace("varying", isFragment ? "in" : "out"); + } + postProcessor(code, defines, isFragment) { + const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1; + // Remove extensions + const regex = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g; + code = code.replace(regex, ""); + // Replace instructions + code = code.replace(/texture2D\s*\(/g, "texture("); + if (isFragment) { + const hasOutput = code.search(/layout *\(location *= *0\) *out/g) !== -1; + code = code.replace(/texture2DLodEXT\s*\(/g, "textureLod("); + code = code.replace(/textureCubeLodEXT\s*\(/g, "textureLod("); + code = code.replace(/textureCube\s*\(/g, "texture("); + code = code.replace(/gl_FragDepthEXT/g, "gl_FragDepth"); + code = code.replace(/gl_FragColor/g, "glFragColor"); + code = code.replace(/gl_FragData/g, "glFragData"); + code = code.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension || hasOutput ? "" : "layout(location = 0) out vec4 glFragColor;\n") + "void main("); + } + else { + const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1; + if (hasMultiviewExtension) { + return "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n" + code; + } + } + return code; + } +} + +/** + * Class used to store gfx data (like WebGLBuffer) + */ +class DataBuffer { + /** + * Gets the underlying buffer + */ + get underlyingResource() { + return null; + } + /** + * Constructs the buffer + */ + constructor() { + /** + * Gets or sets the number of objects referencing this buffer + */ + this.references = 0; + /** Gets or sets the size of the underlying buffer */ + this.capacity = 0; + /** + * Gets or sets a boolean indicating if the buffer contains 32bits indices + */ + this.is32Bits = false; + this.uniqueId = DataBuffer._Counter++; + } +} +DataBuffer._Counter = 0; + +/** @internal */ +class WebGLDataBuffer extends DataBuffer { + constructor(resource) { + super(); + this._buffer = resource; + } + get underlyingResource() { + return this._buffer; + } +} + +/** + * Function indicating if a number is an exponent of 2 + * @param value defines the value to test + * @returns true if the value is an exponent of 2 + */ +function IsExponentOfTwo(value) { + let count = 1; + do { + count *= 2; + } while (count < value); + return count === value; +} +/** + * Interpolates between a and b via alpha + * @param a The lower value (returned when alpha = 0) + * @param b The upper value (returned when alpha = 1) + * @param alpha The interpolation-factor + * @returns The mixed value + */ +function Mix(a, b, alpha) { + return a * (1 - alpha) + b * alpha; +} +/** + * Find the nearest power of two. + * @param x Number to start search from. + * @returns Next nearest power of two. + */ +function NearestPOT(x) { + const c = CeilingPOT(x); + const f = FloorPOT(x); + return c - x > x - f ? f : c; +} +/** + * Find the next highest power of two. + * @param x Number to start search from. + * @returns Next highest power of two. + */ +function CeilingPOT(x) { + x--; + x |= x >> 1; + x |= x >> 2; + x |= x >> 4; + x |= x >> 8; + x |= x >> 16; + x++; + return x; +} +/** + * Find the next lowest power of two. + * @param x Number to start search from. + * @returns Next lowest power of two. + */ +function FloorPOT(x) { + x = x | (x >> 1); + x = x | (x >> 2); + x = x | (x >> 4); + x = x | (x >> 8); + x = x | (x >> 16); + return x - (x >> 1); +} +/** + * Get the closest exponent of two + * @param value defines the value to approximate + * @param max defines the maximum value to return + * @param mode defines how to define the closest value + * @returns closest exponent of two of the given value + */ +function GetExponentOfTwo(value, max, mode = 2) { + let pot; + switch (mode) { + case 1: + pot = FloorPOT(value); + break; + case 2: + pot = NearestPOT(value); + break; + case 3: + default: + pot = CeilingPOT(value); + break; + } + return Math.min(pot, max); +} + +/** + * Defines the shader related stores and directory + */ +class ShaderStore { + /** + * Gets the shaders repository path for a given shader language + * @param shaderLanguage the shader language + * @returns the path to the shaders repository + */ + static GetShadersRepository(shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + return shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? ShaderStore.ShadersRepository : ShaderStore.ShadersRepositoryWGSL; + } + /** + * Gets the shaders store of a given shader language + * @param shaderLanguage the shader language + * @returns the shaders store + */ + static GetShadersStore(shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + return shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? ShaderStore.ShadersStore : ShaderStore.ShadersStoreWGSL; + } + /** + * Gets the include shaders store of a given shader language + * @param shaderLanguage the shader language + * @returns the include shaders store + */ + static GetIncludesShadersStore(shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + return shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? ShaderStore.IncludesShadersStore : ShaderStore.IncludesShadersStoreWGSL; + } +} +/** + * Gets or sets the relative url used to load shaders if using the engine in non-minified mode + */ +ShaderStore.ShadersRepository = "src/Shaders/"; +/** + * Store of each shader (The can be looked up using effect.key) + */ +ShaderStore.ShadersStore = {}; +/** + * Store of each included file for a shader (The can be looked up using effect.key) + */ +ShaderStore.IncludesShadersStore = {}; +/** + * Gets or sets the relative url used to load shaders (WGSL) if using the engine in non-minified mode + */ +ShaderStore.ShadersRepositoryWGSL = "src/ShadersWGSL/"; +/** + * Store of each shader (WGSL) + */ +ShaderStore.ShadersStoreWGSL = {}; +/** + * Store of each included file for a shader (WGSL) + */ +ShaderStore.IncludesShadersStoreWGSL = {}; + +const defaultAttributeKeywordName = "attribute"; +const defaultVaryingKeywordName = "varying"; +/** @internal */ +class ShaderCodeNode { + constructor() { + this.children = []; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + isValid(preprocessors) { + return true; + } + process(preprocessors, options) { + let result = ""; + if (this.line) { + let value = this.line; + const processor = options.processor; + if (processor) { + // This must be done before other replacements to avoid mistakenly changing something that was already changed. + if (processor.lineProcessor) { + value = processor.lineProcessor(value, options.isFragment, options.processingContext); + } + const attributeKeyword = options.processor?.attributeKeywordName ?? defaultAttributeKeywordName; + const varyingKeyword = options.isFragment && options.processor?.varyingFragmentKeywordName + ? options.processor?.varyingFragmentKeywordName + : !options.isFragment && options.processor?.varyingVertexKeywordName + ? options.processor?.varyingVertexKeywordName + : defaultVaryingKeywordName; + if (!options.isFragment && processor.attributeProcessor && this.line.startsWith(attributeKeyword)) { + value = processor.attributeProcessor(this.line, preprocessors, options.processingContext); + } + else if (processor.varyingProcessor && + (processor.varyingCheck?.(this.line, options.isFragment) || (!processor.varyingCheck && this.line.startsWith(varyingKeyword)))) { + value = processor.varyingProcessor(this.line, options.isFragment, preprocessors, options.processingContext); + } + else if (processor.uniformProcessor && processor.uniformRegexp && processor.uniformRegexp.test(this.line)) { + if (!options.lookForClosingBracketForUniformBuffer) { + value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext); + } + } + else if (processor.uniformBufferProcessor && processor.uniformBufferRegexp && processor.uniformBufferRegexp.test(this.line)) { + if (!options.lookForClosingBracketForUniformBuffer) { + value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext); + options.lookForClosingBracketForUniformBuffer = true; + } + } + else if (processor.textureProcessor && processor.textureRegexp && processor.textureRegexp.test(this.line)) { + value = processor.textureProcessor(this.line, options.isFragment, preprocessors, options.processingContext); + } + else if ((processor.uniformProcessor || processor.uniformBufferProcessor) && this.line.startsWith("uniform") && !options.lookForClosingBracketForUniformBuffer) { + const regex = /uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/; + if (regex.test(this.line)) { + // uniform + if (processor.uniformProcessor) { + value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext); + } + } + else { + // Uniform buffer + if (processor.uniformBufferProcessor) { + value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext); + options.lookForClosingBracketForUniformBuffer = true; + } + } + } + if (options.lookForClosingBracketForUniformBuffer && this.line.indexOf("}") !== -1) { + options.lookForClosingBracketForUniformBuffer = false; + if (processor.endOfUniformBufferProcessor) { + value = processor.endOfUniformBufferProcessor(this.line, options.isFragment, options.processingContext); + } + } + } + result += value + "\n"; + } + this.children.forEach((child) => { + result += child.process(preprocessors, options); + }); + if (this.additionalDefineKey) { + preprocessors[this.additionalDefineKey] = this.additionalDefineValue || "true"; + } + return result; + } +} + +/** @internal */ +class ShaderCodeCursor { + constructor() { + this._lines = []; + } + get currentLine() { + return this._lines[this.lineIndex]; + } + get canRead() { + return this.lineIndex < this._lines.length - 1; + } + set lines(value) { + this._lines.length = 0; + for (const line of value) { + // Skip empty lines + if (!line || line === "\r") { + continue; + } + // Prevent removing line break in macros. + if (line[0] === "#") { + this._lines.push(line); + continue; + } + // Do not split single line comments + const trimmedLine = line.trim(); + if (!trimmedLine) { + continue; + } + if (trimmedLine.startsWith("//")) { + this._lines.push(line); + continue; + } + // Work with semicolon in the line + const semicolonIndex = trimmedLine.indexOf(";"); + if (semicolonIndex === -1) { + // No semicolon in the line + this._lines.push(trimmedLine); + } + else if (semicolonIndex === trimmedLine.length - 1) { + // Single semicolon at the end of the line + // If trimmedLine == ";", we must not push, to be backward compatible with the old code! + if (trimmedLine.length > 1) { + this._lines.push(trimmedLine); + } + } + else { + // Semicolon in the middle of the line + const split = line.split(";"); + for (let index = 0; index < split.length; index++) { + let subLine = split[index]; + if (!subLine) { + continue; + } + subLine = subLine.trim(); + if (!subLine) { + continue; + } + this._lines.push(subLine + (index !== split.length - 1 ? ";" : "")); + } + } + } + } +} + +/** @internal */ +class ShaderCodeConditionNode extends ShaderCodeNode { + process(preprocessors, options) { + for (let index = 0; index < this.children.length; index++) { + const node = this.children[index]; + if (node.isValid(preprocessors)) { + return node.process(preprocessors, options); + } + } + return ""; + } +} + +/** @internal */ +class ShaderCodeTestNode extends ShaderCodeNode { + isValid(preprocessors) { + return this.testExpression.isTrue(preprocessors); + } +} + +/* eslint-disable @typescript-eslint/naming-convention */ +/** @internal */ +class ShaderDefineExpression { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + isTrue(preprocessors) { + return true; + } + static postfixToInfix(postfix) { + const stack = []; + for (const c of postfix) { + if (ShaderDefineExpression._OperatorPriority[c] === undefined) { + stack.push(c); + } + else { + const v1 = stack[stack.length - 1], v2 = stack[stack.length - 2]; + stack.length -= 2; + stack.push(`(${v2}${c}${v1})`); + } + } + return stack[stack.length - 1]; + } + /** + * Converts an infix expression to a postfix expression. + * + * This method is used to transform infix expressions, which are more human-readable, + * into postfix expressions, also known as Reverse Polish Notation (RPN), that can be + * evaluated more efficiently by a computer. The conversion is based on the operator + * priority defined in _OperatorPriority. + * + * The function employs a stack-based algorithm for the conversion and caches the result + * to improve performance. The cache keeps track of each converted expression's access time + * to manage the cache size and optimize memory usage. When the cache size exceeds a specified + * limit, the least recently accessed items in the cache are deleted. + * + * The cache mechanism is particularly helpful for shader compilation, where the same infix + * expressions might be encountered repeatedly, hence the caching can speed up the process. + * + * @param infix - The infix expression to be converted. + * @returns The postfix expression as an array of strings. + */ + static infixToPostfix(infix) { + // Is infix already in cache + const cacheItem = ShaderDefineExpression._InfixToPostfixCache.get(infix); + if (cacheItem) { + cacheItem.accessTime = Date.now(); + return cacheItem.result; + } + // Is infix contain any operator + if (!infix.includes("&&") && !infix.includes("||") && !infix.includes(")") && !infix.includes("(")) { + return [infix]; + } + const result = []; + let stackIdx = -1; + const pushOperand = () => { + operand = operand.trim(); + if (operand !== "") { + result.push(operand); + operand = ""; + } + }; + const push = (s) => { + if (stackIdx < ShaderDefineExpression._Stack.length - 1) { + ShaderDefineExpression._Stack[++stackIdx] = s; + } + }; + const peek = () => ShaderDefineExpression._Stack[stackIdx]; + const pop = () => (stackIdx === -1 ? "!!INVALID EXPRESSION!!" : ShaderDefineExpression._Stack[stackIdx--]); + let idx = 0, operand = ""; + while (idx < infix.length) { + const c = infix.charAt(idx), token = idx < infix.length - 1 ? infix.substring(idx, 2 + idx) : ""; + if (c === "(") { + operand = ""; + push(c); + } + else if (c === ")") { + pushOperand(); + while (stackIdx !== -1 && peek() !== "(") { + result.push(pop()); + } + pop(); + } + else if (ShaderDefineExpression._OperatorPriority[token] > 1) { + pushOperand(); + while (stackIdx !== -1 && ShaderDefineExpression._OperatorPriority[peek()] >= ShaderDefineExpression._OperatorPriority[token]) { + result.push(pop()); + } + push(token); + idx++; + } + else { + operand += c; + } + idx++; + } + pushOperand(); + while (stackIdx !== -1) { + if (peek() === "(") { + pop(); + } + else { + result.push(pop()); + } + } + // If the cache is at capacity, clear it before adding a new item + if (ShaderDefineExpression._InfixToPostfixCache.size >= ShaderDefineExpression.InfixToPostfixCacheLimitSize) { + ShaderDefineExpression.ClearCache(); + } + // Add the new item to the cache, including the current time as the last access time + ShaderDefineExpression._InfixToPostfixCache.set(infix, { result, accessTime: Date.now() }); + return result; + } + static ClearCache() { + // Convert the cache to an array and sort by last access time + const sortedCache = Array.from(ShaderDefineExpression._InfixToPostfixCache.entries()).sort((a, b) => a[1].accessTime - b[1].accessTime); + // Remove the least recently accessed half of the cache + for (let i = 0; i < ShaderDefineExpression.InfixToPostfixCacheCleanupSize; i++) { + ShaderDefineExpression._InfixToPostfixCache.delete(sortedCache[i][0]); + } + } +} +/** + * Cache items count limit for the InfixToPostfix cache. + * It uses to improve the performance of the shader compilation. + * For details see PR: https://github.com/BabylonJS/Babylon.js/pull/13936 + */ +ShaderDefineExpression.InfixToPostfixCacheLimitSize = 50000; +/** + * When the cache size is exceeded, a cache cleanup will be triggered + * and the cache will be reduced by the size specified + * in the InfixToPostfixCacheCleanupSize variable, removing entries + * that have not been accessed the longest. + */ +ShaderDefineExpression.InfixToPostfixCacheCleanupSize = 25000; +ShaderDefineExpression._InfixToPostfixCache = new Map(); +ShaderDefineExpression._OperatorPriority = { + ")": 0, + "(": 1, + "||": 2, + "&&": 3, +}; +ShaderDefineExpression._Stack = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]; + +/** @internal */ +class ShaderDefineIsDefinedOperator extends ShaderDefineExpression { + constructor(define, not = false) { + super(); + this.define = define; + this.not = not; + } + isTrue(preprocessors) { + let condition = preprocessors[this.define] !== undefined; + if (this.not) { + condition = !condition; + } + return condition; + } +} + +/** @internal */ +class ShaderDefineOrOperator extends ShaderDefineExpression { + isTrue(preprocessors) { + return this.leftOperand.isTrue(preprocessors) || this.rightOperand.isTrue(preprocessors); + } +} + +/** @internal */ +class ShaderDefineAndOperator extends ShaderDefineExpression { + isTrue(preprocessors) { + return this.leftOperand.isTrue(preprocessors) && this.rightOperand.isTrue(preprocessors); + } +} + +/** @internal */ +class ShaderDefineArithmeticOperator extends ShaderDefineExpression { + constructor(define, operand, testValue) { + super(); + this.define = define; + this.operand = operand; + this.testValue = testValue; + } + isTrue(preprocessors) { + let value = preprocessors[this.define]; + if (value === undefined) { + value = this.define; + } + let condition = false; + const left = parseInt(value); + const right = parseInt(this.testValue); + switch (this.operand) { + case ">": + condition = left > right; + break; + case "<": + condition = left < right; + break; + case "<=": + condition = left <= right; + break; + case ">=": + condition = left >= right; + break; + case "==": + condition = left === right; + break; + case "!=": + condition = left !== right; + break; + } + return condition; + } +} + +/* eslint-disable @typescript-eslint/no-unused-vars */ +const regexSE = /defined\s*?\((.+?)\)/g; +const regexSERevert = /defined\s*?\[(.+?)\]/g; +const regexShaderInclude = /#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g; +const regexShaderDecl = /__decl__/; +const regexLightX = /light\{X\}.(\w*)/g; +const regexX = /\{X\}/g; +const reusableMatches = []; +const _MoveCursorRegex = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/; +/** @internal */ +function Initialize(options) { + if (options.processor && options.processor.initializeShaders) { + options.processor.initializeShaders(options.processingContext); + } +} +/** @internal */ +function Process(sourceCode, options, callback, engine) { + if (options.processor?.preProcessShaderCode) { + sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment); + } + _ProcessIncludes(sourceCode, options, (codeWithIncludes) => { + if (options.processCodeAfterIncludes) { + codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? "fragment" : "vertex", codeWithIncludes, options.defines); + } + const migratedCode = _ProcessShaderConversion(codeWithIncludes, options, engine); + callback(migratedCode, codeWithIncludes); + }); +} +/** @internal */ +function PreProcess(sourceCode, options, callback, engine) { + if (options.processor?.preProcessShaderCode) { + sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment); + } + _ProcessIncludes(sourceCode, options, (codeWithIncludes) => { + if (options.processCodeAfterIncludes) { + codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? "fragment" : "vertex", codeWithIncludes, options.defines); + } + const migratedCode = _ApplyPreProcessing(codeWithIncludes, options, engine); + callback(migratedCode, codeWithIncludes); + }); +} +/** @internal */ +function Finalize(vertexCode, fragmentCode, options) { + if (!options.processor || !options.processor.finalizeShaders) { + return { vertexCode, fragmentCode }; + } + return options.processor.finalizeShaders(vertexCode, fragmentCode, options.processingContext); +} +function _ProcessPrecision(source, options) { + if (options.processor?.noPrecision) { + return source; + } + const shouldUseHighPrecisionShader = options.shouldUseHighPrecisionShader; + if (source.indexOf("precision highp float") === -1) { + if (!shouldUseHighPrecisionShader) { + source = "precision mediump float;\n" + source; + } + else { + source = "precision highp float;\n" + source; + } + } + else { + if (!shouldUseHighPrecisionShader) { + // Moving highp to mediump + source = source.replace("precision highp float", "precision mediump float"); + } + } + return source; +} +function _ExtractOperation(expression) { + const regex = /defined\((.+)\)/; + const match = regex.exec(expression); + if (match && match.length) { + return new ShaderDefineIsDefinedOperator(match[1].trim(), expression[0] === "!"); + } + const operators = ["==", "!=", ">=", "<=", "<", ">"]; + let operator = ""; + let indexOperator = 0; + for (operator of operators) { + indexOperator = expression.indexOf(operator); + if (indexOperator > -1) { + break; + } + } + if (indexOperator === -1) { + return new ShaderDefineIsDefinedOperator(expression); + } + const define = expression.substring(0, indexOperator).trim(); + const value = expression.substring(indexOperator + operator.length).trim(); + return new ShaderDefineArithmeticOperator(define, operator, value); +} +function _BuildSubExpression(expression) { + expression = expression.replace(regexSE, "defined[$1]"); + const postfix = ShaderDefineExpression.infixToPostfix(expression); + const stack = []; + for (const c of postfix) { + if (c !== "||" && c !== "&&") { + stack.push(c); + } + else if (stack.length >= 2) { + let v1 = stack[stack.length - 1], v2 = stack[stack.length - 2]; + stack.length -= 2; + const operator = c == "&&" ? new ShaderDefineAndOperator() : new ShaderDefineOrOperator(); + if (typeof v1 === "string") { + v1 = v1.replace(regexSERevert, "defined($1)"); + } + if (typeof v2 === "string") { + v2 = v2.replace(regexSERevert, "defined($1)"); + } + operator.leftOperand = typeof v2 === "string" ? _ExtractOperation(v2) : v2; + operator.rightOperand = typeof v1 === "string" ? _ExtractOperation(v1) : v1; + stack.push(operator); + } + } + let result = stack[stack.length - 1]; + if (typeof result === "string") { + result = result.replace(regexSERevert, "defined($1)"); + } + // note: stack.length !== 1 if there was an error in the parsing + return typeof result === "string" ? _ExtractOperation(result) : result; +} +function _BuildExpression(line, start) { + const node = new ShaderCodeTestNode(); + const command = line.substring(0, start); + let expression = line.substring(start); + expression = expression.substring(0, (expression.indexOf("//") + 1 || expression.length + 1) - 1).trim(); + if (command === "#ifdef") { + node.testExpression = new ShaderDefineIsDefinedOperator(expression); + } + else if (command === "#ifndef") { + node.testExpression = new ShaderDefineIsDefinedOperator(expression, true); + } + else { + node.testExpression = _BuildSubExpression(expression); + } + return node; +} +function _MoveCursorWithinIf(cursor, rootNode, ifNode) { + let line = cursor.currentLine; + while (_MoveCursor(cursor, ifNode)) { + line = cursor.currentLine; + const first5 = line.substring(0, 5).toLowerCase(); + if (first5 === "#else") { + const elseNode = new ShaderCodeNode(); + rootNode.children.push(elseNode); + _MoveCursor(cursor, elseNode); + return; + } + else if (first5 === "#elif") { + const elifNode = _BuildExpression(line, 5); + rootNode.children.push(elifNode); + ifNode = elifNode; + } + } +} +function _MoveCursor(cursor, rootNode) { + while (cursor.canRead) { + cursor.lineIndex++; + const line = cursor.currentLine; + if (line.indexOf("#") >= 0) { + const matches = _MoveCursorRegex.exec(line); + if (matches && matches.length) { + const keyword = matches[0]; + switch (keyword) { + case "#ifdef": { + const newRootNode = new ShaderCodeConditionNode(); + rootNode.children.push(newRootNode); + const ifNode = _BuildExpression(line, 6); + newRootNode.children.push(ifNode); + _MoveCursorWithinIf(cursor, newRootNode, ifNode); + break; + } + case "#else": + case "#elif": + return true; + case "#endif": + return false; + case "#ifndef": { + const newRootNode = new ShaderCodeConditionNode(); + rootNode.children.push(newRootNode); + const ifNode = _BuildExpression(line, 7); + newRootNode.children.push(ifNode); + _MoveCursorWithinIf(cursor, newRootNode, ifNode); + break; + } + case "#if": { + const newRootNode = new ShaderCodeConditionNode(); + const ifNode = _BuildExpression(line, 3); + rootNode.children.push(newRootNode); + newRootNode.children.push(ifNode); + _MoveCursorWithinIf(cursor, newRootNode, ifNode); + break; + } + } + continue; + } + } + const newNode = new ShaderCodeNode(); + newNode.line = line; + rootNode.children.push(newNode); + // Detect additional defines + if (line[0] === "#" && line[1] === "d") { + const split = line.replace(";", "").split(" "); + newNode.additionalDefineKey = split[1]; + if (split.length === 3) { + newNode.additionalDefineValue = split[2]; + } + } + } + return false; +} +function _EvaluatePreProcessors(sourceCode, preprocessors, options) { + const rootNode = new ShaderCodeNode(); + const cursor = new ShaderCodeCursor(); + cursor.lineIndex = -1; + cursor.lines = sourceCode.split("\n"); + // Decompose (We keep it in 2 steps so it is easier to maintain and perf hit is insignificant) + _MoveCursor(cursor, rootNode); + // Recompose + return rootNode.process(preprocessors, options); +} +function _PreparePreProcessors(options, engine) { + const defines = options.defines; + const preprocessors = {}; + for (const define of defines) { + const keyValue = define.replace("#define", "").replace(";", "").trim(); + const split = keyValue.split(" "); + preprocessors[split[0]] = split.length > 1 ? split[1] : ""; + } + if (options.processor?.shaderLanguage === 0 /* ShaderLanguage.GLSL */) { + preprocessors["GL_ES"] = "true"; + } + preprocessors["__VERSION__"] = options.version; + preprocessors[options.platformName] = "true"; + _getGlobalDefines(preprocessors, engine?.isNDCHalfZRange, engine?.useReverseDepthBuffer, engine?.useExactSrgbConversions); + return preprocessors; +} +function _ProcessShaderConversion(sourceCode, options, engine) { + let preparedSourceCode = _ProcessPrecision(sourceCode, options); + if (!options.processor) { + return preparedSourceCode; + } + // Already converted + if (options.processor.shaderLanguage === 0 /* ShaderLanguage.GLSL */ && preparedSourceCode.indexOf("#version 3") !== -1) { + preparedSourceCode = preparedSourceCode.replace("#version 300 es", ""); + if (!options.processor.parseGLES3) { + return preparedSourceCode; + } + } + const defines = options.defines; + const preprocessors = _PreparePreProcessors(options, engine); + // General pre processing + if (options.processor.preProcessor) { + preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, preprocessors, options.isFragment, options.processingContext); + } + preparedSourceCode = _EvaluatePreProcessors(preparedSourceCode, preprocessors, options); + // Post processing + if (options.processor.postProcessor) { + preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine + ? { + drawBuffersExtensionDisabled: engine.getCaps().drawBuffersExtension ? false : true, + } + : {}); + } + // Inline functions tagged with #define inline + if (engine?._features.needShaderCodeInlining) { + preparedSourceCode = engine.inlineShaderCode(preparedSourceCode); + } + return preparedSourceCode; +} +function _ApplyPreProcessing(sourceCode, options, engine) { + let preparedSourceCode = sourceCode; + const defines = options.defines; + const preprocessors = _PreparePreProcessors(options, engine); + // General pre processing + if (options.processor?.preProcessor) { + preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, preprocessors, options.isFragment, options.processingContext); + } + preparedSourceCode = _EvaluatePreProcessors(preparedSourceCode, preprocessors, options); + // Post processing + if (options.processor?.postProcessor) { + preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine + ? { + drawBuffersExtensionDisabled: engine.getCaps().drawBuffersExtension ? false : true, + } + : {}); + } + // Inline functions tagged with #define inline + if (engine._features.needShaderCodeInlining) { + preparedSourceCode = engine.inlineShaderCode(preparedSourceCode); + } + return preparedSourceCode; +} +/** @internal */ +function _ProcessIncludes(sourceCode, options, callback) { + reusableMatches.length = 0; + let match; + // stay back-compat to the old matchAll syntax + while ((match = regexShaderInclude.exec(sourceCode)) !== null) { + reusableMatches.push(match); + } + let returnValue = String(sourceCode); + let parts = [sourceCode]; + let keepProcessing = false; + for (const match of reusableMatches) { + let includeFile = match[1]; + // Uniform declaration + if (includeFile.indexOf("__decl__") !== -1) { + includeFile = includeFile.replace(regexShaderDecl, ""); + if (options.supportsUniformBuffers) { + includeFile = includeFile.replace("Vertex", "Ubo").replace("Fragment", "Ubo"); + } + includeFile = includeFile + "Declaration"; + } + if (options.includesShadersStore[includeFile]) { + // Substitution + let includeContent = options.includesShadersStore[includeFile]; + if (match[2]) { + const splits = match[3].split(","); + for (let index = 0; index < splits.length; index += 2) { + const source = new RegExp(splits[index], "g"); + const dest = splits[index + 1]; + includeContent = includeContent.replace(source, dest); + } + } + if (match[4]) { + const indexString = match[5]; + if (indexString.indexOf("..") !== -1) { + const indexSplits = indexString.split(".."); + const minIndex = parseInt(indexSplits[0]); + let maxIndex = parseInt(indexSplits[1]); + let sourceIncludeContent = includeContent.slice(0); + includeContent = ""; + if (isNaN(maxIndex)) { + maxIndex = options.indexParameters[indexSplits[1]]; + } + for (let i = minIndex; i < maxIndex; i++) { + if (!options.supportsUniformBuffers) { + // Ubo replacement + sourceIncludeContent = sourceIncludeContent.replace(regexLightX, (str, p1) => { + return p1 + "{X}"; + }); + } + includeContent += sourceIncludeContent.replace(regexX, i.toString()) + "\n"; + } + } + else { + if (!options.supportsUniformBuffers) { + // Ubo replacement + includeContent = includeContent.replace(regexLightX, (str, p1) => { + return p1 + "{X}"; + }); + } + includeContent = includeContent.replace(regexX, indexString); + } + } + // Replace + // Split all parts on match[0] and intersperse the parts with the include content + const newParts = []; + for (const part of parts) { + const splitPart = part.split(match[0]); + for (let i = 0; i < splitPart.length - 1; i++) { + newParts.push(splitPart[i]); + newParts.push(includeContent); + } + newParts.push(splitPart[splitPart.length - 1]); + } + parts = newParts; + keepProcessing = keepProcessing || includeContent.indexOf("#include<") >= 0 || includeContent.indexOf("#include <") >= 0; + } + else { + const includeShaderUrl = options.shadersRepository + "ShadersInclude/" + includeFile + ".fx"; + _functionContainer.loadFile(includeShaderUrl, (fileContent) => { + options.includesShadersStore[includeFile] = fileContent; + _ProcessIncludes(parts.join(""), options, callback); + }); + return; + } + } + reusableMatches.length = 0; + returnValue = parts.join(""); + if (keepProcessing) { + _ProcessIncludes(returnValue.toString(), options, callback); + } + else { + callback(returnValue); + } +} +/** @internal */ +const _functionContainer = { + /** + * Loads a file from a url + * @param url url to load + * @param onSuccess callback called when the file successfully loads + * @param onProgress callback called while file is loading (if the server supports this mode) + * @param offlineProvider defines the offline provider for caching + * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer + * @param onError callback called when the file fails to load + * @returns a file request object + * @internal + */ + loadFile: (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) => { + throw _WarnImport("FileTools"); + }, +}; + +/** + * Get a cached pipeline context + * @param name the pipeline name + * @param context the context to be used when creating the pipeline + * @returns the cached pipeline context if it exists + * @internal + */ +function getCachedPipeline(name, context) { + const stateObject = getStateObject(context); + return stateObject.cachedPipelines[name]; +} +/** + * @internal + */ +function resetCachedPipeline(pipeline) { + const name = pipeline._name; + const context = pipeline.context; + if (name && context) { + const stateObject = getStateObject(context); + const cachedPipeline = stateObject.cachedPipelines[name]; + cachedPipeline?.dispose(); + delete stateObject.cachedPipelines[name]; + } +} +/** @internal */ +function _processShaderCode(processorOptions, baseName, processFinalCode, onFinalCodeReady, shaderLanguage, engine, effectContext) { + let vertexSource; + let fragmentSource; + // const baseName = this.name; + const hostDocument = IsWindowObjectExist() ? engine?.getHostDocument() : null; + if (typeof baseName === "string") { + vertexSource = baseName; + } + else if (baseName.vertexSource) { + vertexSource = "source:" + baseName.vertexSource; + } + else if (baseName.vertexElement) { + vertexSource = hostDocument?.getElementById(baseName.vertexElement) || baseName.vertexElement; + } + else { + vertexSource = baseName.vertex || baseName; + } + if (typeof baseName === "string") { + fragmentSource = baseName; + } + else if (baseName.fragmentSource) { + fragmentSource = "source:" + baseName.fragmentSource; + } + else if (baseName.fragmentElement) { + fragmentSource = hostDocument?.getElementById(baseName.fragmentElement) || baseName.fragmentElement; + } + else { + fragmentSource = baseName.fragment || baseName; + } + const shaderCodes = [undefined, undefined]; + const shadersLoaded = () => { + if (shaderCodes[0] && shaderCodes[1]) { + processorOptions.isFragment = true; + const [migratedVertexCode, fragmentCode] = shaderCodes; + Process(fragmentCode, processorOptions, (migratedFragmentCode, codeBeforeMigration) => { + if (effectContext) { + effectContext._fragmentSourceCodeBeforeMigration = codeBeforeMigration; + } + if (processFinalCode) { + migratedFragmentCode = processFinalCode("fragment", migratedFragmentCode); + } + const finalShaders = Finalize(migratedVertexCode, migratedFragmentCode, processorOptions); + processorOptions = null; + const finalCode = _useFinalCode(finalShaders.vertexCode, finalShaders.fragmentCode, baseName, shaderLanguage); + onFinalCodeReady?.(finalCode.vertexSourceCode, finalCode.fragmentSourceCode); + }, engine); + } + }; + _loadShader(vertexSource, "Vertex", "", (vertexCode) => { + Initialize(processorOptions); + Process(vertexCode, processorOptions, (migratedVertexCode, codeBeforeMigration) => { + if (effectContext) { + effectContext._rawVertexSourceCode = vertexCode; + effectContext._vertexSourceCodeBeforeMigration = codeBeforeMigration; + } + if (processFinalCode) { + migratedVertexCode = processFinalCode("vertex", migratedVertexCode); + } + shaderCodes[0] = migratedVertexCode; + shadersLoaded(); + }, engine); + }, shaderLanguage); + _loadShader(fragmentSource, "Fragment", "Pixel", (fragmentCode) => { + if (effectContext) { + effectContext._rawFragmentSourceCode = fragmentCode; + } + shaderCodes[1] = fragmentCode; + shadersLoaded(); + }, shaderLanguage); +} +function _loadShader(shader, key, optionalKey, callback, shaderLanguage, _loadFileInjection) { + if (typeof HTMLElement !== "undefined") { + // DOM element ? + if (shader instanceof HTMLElement) { + const shaderCode = GetDOMTextContent(shader); + callback(shaderCode); + return; + } + } + // Direct source ? + if (shader.substring(0, 7) === "source:") { + callback(shader.substring(7)); + return; + } + // Base64 encoded ? + if (shader.substring(0, 7) === "base64:") { + const shaderBinary = window.atob(shader.substring(7)); + callback(shaderBinary); + return; + } + const shaderStore = ShaderStore.GetShadersStore(shaderLanguage); + // Is in local store ? + if (shaderStore[shader + key + "Shader"]) { + callback(shaderStore[shader + key + "Shader"]); + return; + } + if (optionalKey && shaderStore[shader + optionalKey + "Shader"]) { + callback(shaderStore[shader + optionalKey + "Shader"]); + return; + } + let shaderUrl; + if (shader[0] === "." || shader[0] === "/" || shader.indexOf("http") > -1) { + shaderUrl = shader; + } + else { + shaderUrl = ShaderStore.GetShadersRepository(shaderLanguage) + shader; + } + _loadFileInjection = _loadFileInjection || _loadFile; + if (!_loadFileInjection) { + // we got to this point and loadFile was not injected - throw an error + throw new Error("loadFileInjection is not defined"); + } + // Vertex shader + _loadFileInjection(shaderUrl + "." + key.toLowerCase() + ".fx", callback); +} +function _useFinalCode(migratedVertexCode, migratedFragmentCode, baseName, shaderLanguage) { + if (baseName) { + const vertex = baseName.vertexElement || baseName.vertex || baseName.spectorName || baseName; + const fragment = baseName.fragmentElement || baseName.fragment || baseName.spectorName || baseName; + return { + vertexSourceCode: (shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "//" : "") + "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode, + fragmentSourceCode: (shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "//" : "") + "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode, + }; + } + else { + return { + vertexSourceCode: migratedVertexCode, + fragmentSourceCode: migratedFragmentCode, + }; + } +} +/** + * Creates and prepares a pipeline context + * @internal + */ +const createAndPreparePipelineContext = (options, createPipelineContext, _preparePipelineContext, _executeWhenRenderingStateIsCompiled) => { + try { + const stateObject = options.context ? getStateObject(options.context) : null; + if (stateObject) { + // will not remove the reference to parallelShaderPrecompile, but will prevent it from being used in the next shader compilation + stateObject.disableParallelShaderCompile = options.disableParallelCompilation; + } + const pipelineContext = options.existingPipelineContext || createPipelineContext(options.shaderProcessingContext); + pipelineContext._name = options.name; + if (options.name && stateObject) { + stateObject.cachedPipelines[options.name] = pipelineContext; + } + // Flagged as async as we may need to delay load some processing tools + // This does not break anything as the execution is waiting for _executeWhenRenderingStateIsCompiled + _preparePipelineContext(pipelineContext, options.vertex, options.fragment, !!options.createAsRaw, "", "", options.rebuildRebind, options.defines, options.transformFeedbackVaryings, "", () => { + _executeWhenRenderingStateIsCompiled(pipelineContext, () => { + options.onRenderingStateCompiled?.(pipelineContext); + }); + }); + return pipelineContext; + } + catch (e) { + Logger.Error("Error compiling effect"); + throw e; + } +}; + +let _immediateQueue = []; +/** + * Class used to provide helper for timing + */ +class TimingTools { + /** + * Execute a function after the current execution block + * @param action defines the action to execute after the current execution block + */ + static SetImmediate(action) { + if (_immediateQueue.length === 0) { + setTimeout(() => { + // Execute all immediate functions + const functionsToCall = _immediateQueue; + _immediateQueue = []; + for (const func of functionsToCall) { + func(); + } + }, 1); + } + _immediateQueue.push(action); + } +} +function _runWithCondition(condition, onSuccess, onError) { + try { + if (condition()) { + onSuccess(); + return true; + } + } + catch (e) { + onError?.(e); + return true; + } + return false; +} +/** + * @internal + */ +const _retryWithInterval = (condition, onSuccess, onError, step = 16, maxTimeout = 30000, checkConditionOnCall = true, additionalStringOnTimeout) => { + // if checkConditionOnCall is true, we check the condition immediately. If it is true, run everything synchronously + if (checkConditionOnCall) { + // that means that one of the two happened - either the condition is true or an exception was thrown when checking the condition + if (_runWithCondition(condition, onSuccess, onError)) { + // don't schedule the interval, no reason to check it again. + return null; + } + } + const int = setInterval(() => { + if (_runWithCondition(condition, onSuccess, onError)) { + clearInterval(int); + } + else { + maxTimeout -= step; + if (maxTimeout < 0) { + clearInterval(int); + onError?.(new Error("Operation timed out after maximum retries. " + (additionalStringOnTimeout || "")), true); + } + } + }, step); + return () => clearInterval(int); +}; + +/** + * Effect containing vertex and fragment shader that can be executed on an object. + */ +class Effect { + /** + * Gets or sets the relative url used to load shaders if using the engine in non-minified mode + */ + static get ShadersRepository() { + return ShaderStore.ShadersRepository; + } + static set ShadersRepository(repo) { + ShaderStore.ShadersRepository = repo; + } + /** + * Gets a boolean indicating that the effect was already disposed + */ + get isDisposed() { + return this._isDisposed; + } + /** + * Observable that will be called when effect is bound. + */ + get onBindObservable() { + if (!this._onBindObservable) { + this._onBindObservable = new Observable(); + } + return this._onBindObservable; + } + /** + * Gets the shader language type used to write vertex and fragment source code. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Instantiates an effect. + * An effect can be used to create/manage/execute vertex and fragment shaders. + * @param baseName Name of the effect. + * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect. + * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect. + * @param samplers List of sampler variables that will be passed to the shader. + * @param engine Engine to be used to render the effect + * @param defines Define statements to be added to the shader. + * @param fallbacks Possible fallbacks for this effect to improve performance when needed. + * @param onCompiled Callback that will be called when the shader is compiled. + * @param onError Callback that will be called if an error occurs during shader compilation. + * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. \{lights: 10\}) + * @param key Effect Key identifying uniquely compiled shader variants + * @param shaderLanguage the language the shader is written in (default: GLSL) + * @param extraInitializationsAsync additional async code to run before preparing the effect + */ + constructor(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers = null, engine, defines = null, fallbacks = null, onCompiled = null, onError = null, indexParameters, key = "", shaderLanguage = 0 /* ShaderLanguage.GLSL */, extraInitializationsAsync) { + /** + * String container all the define statements that should be set on the shader. + */ + this.defines = ""; + /** + * Callback that will be called when the shader is compiled. + */ + this.onCompiled = null; + /** + * Callback that will be called if an error occurs during shader compilation. + */ + this.onError = null; + /** + * Callback that will be called when effect is bound. + */ + this.onBind = null; + /** + * Unique ID of the effect. + */ + this.uniqueId = 0; + /** + * Observable that will be called when the shader is compiled. + * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised. + */ + this.onCompileObservable = new Observable(); + /** + * Observable that will be called if an error occurs during shader compilation. + */ + this.onErrorObservable = new Observable(); + /** @internal */ + this._onBindObservable = null; + this._isDisposed = false; + /** @internal */ + this._refCount = 1; + /** @internal */ + this._bonesComputationForcedToCPU = false; + /** @internal */ + this._uniformBuffersNames = {}; + /** @internal */ + this._multiTarget = false; + /** @internal */ + this._samplers = {}; + this._isReady = false; + this._compilationError = ""; + this._allFallbacksProcessed = false; + /** @internal */ + this._uniforms = {}; + /** + * Key for the effect. + * @internal + */ + this._key = ""; + this._fallbacks = null; + this._vertexSourceCodeOverride = ""; + this._fragmentSourceCodeOverride = ""; + this._transformFeedbackVaryings = null; + this._disableParallelShaderCompilation = false; + /** + * Compiled shader to webGL program. + * @internal + */ + this._pipelineContext = null; + /** @internal */ + this._vertexSourceCode = ""; + /** @internal */ + this._fragmentSourceCode = ""; + /** @internal */ + this._vertexSourceCodeBeforeMigration = ""; + /** @internal */ + this._fragmentSourceCodeBeforeMigration = ""; + /** @internal */ + this._rawVertexSourceCode = ""; + /** @internal */ + this._rawFragmentSourceCode = ""; + this._processCodeAfterIncludes = undefined; + this._processFinalCode = null; + this.name = baseName; + this._key = key; + const pipelineName = this._key.replace(/\r/g, "").replace(/\n/g, "|"); + let cachedPipeline = undefined; + if (attributesNamesOrOptions.attributes) { + const options = attributesNamesOrOptions; + this._engine = uniformsNamesOrEngine; + this._attributesNames = options.attributes; + this._uniformsNames = options.uniformsNames.concat(options.samplers); + this._samplerList = options.samplers.slice(); + this.defines = options.defines; + this.onError = options.onError; + this.onCompiled = options.onCompiled; + this._fallbacks = options.fallbacks; + this._indexParameters = options.indexParameters; + this._transformFeedbackVaryings = options.transformFeedbackVaryings || null; + this._multiTarget = !!options.multiTarget; + this._shaderLanguage = options.shaderLanguage ?? 0 /* ShaderLanguage.GLSL */; + this._disableParallelShaderCompilation = !!options.disableParallelShaderCompilation; + if (options.uniformBuffersNames) { + this._uniformBuffersNamesList = options.uniformBuffersNames.slice(); + for (let i = 0; i < options.uniformBuffersNames.length; i++) { + this._uniformBuffersNames[options.uniformBuffersNames[i]] = i; + } + } + this._processFinalCode = options.processFinalCode ?? null; + this._processCodeAfterIncludes = options.processCodeAfterIncludes ?? undefined; + extraInitializationsAsync = options.extraInitializationsAsync; + cachedPipeline = options.existingPipelineContext; + } + else { + this._engine = engine; + this.defines = defines == null ? "" : defines; + this._uniformsNames = uniformsNamesOrEngine.concat(samplers); + this._samplerList = samplers ? samplers.slice() : []; + this._attributesNames = attributesNamesOrOptions; + this._uniformBuffersNamesList = []; + this._shaderLanguage = shaderLanguage; + this.onError = onError; + this.onCompiled = onCompiled; + this._indexParameters = indexParameters; + this._fallbacks = fallbacks; + } + // Use the cache if we can. For now, WebGL2 only. + if (this._engine.shaderPlatformName === "WEBGL2") { + cachedPipeline = getCachedPipeline(pipelineName, this._engine._gl) ?? cachedPipeline; + } + this._attributeLocationByName = {}; + this.uniqueId = Effect._UniqueIdSeed++; + if (!cachedPipeline) { + this._processShaderCodeAsync(null, false, null, extraInitializationsAsync); + } + else { + this._pipelineContext = cachedPipeline; + this._pipelineContext.setEngine(this._engine); + this._onRenderingStateCompiled(this._pipelineContext); + // rebuildRebind for spector + if (this._pipelineContext.program) { + this._pipelineContext.program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this); + } + } + this._engine.onReleaseEffectsObservable.addOnce(() => { + if (this.isDisposed) { + return; + } + this.dispose(true); + }); + } + /** @internal */ + async _processShaderCodeAsync(shaderProcessor = null, keepExistingPipelineContext = false, shaderProcessingContext = null, extraInitializationsAsync) { + if (extraInitializationsAsync) { + await extraInitializationsAsync(); + } + this._processingContext = shaderProcessingContext || this._engine._getShaderProcessingContext(this._shaderLanguage, false); + const processorOptions = { + defines: this.defines.split("\n"), + indexParameters: this._indexParameters, + isFragment: false, + shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader, + processor: shaderProcessor ?? this._engine._getShaderProcessor(this._shaderLanguage), + supportsUniformBuffers: this._engine.supportsUniformBuffers, + shadersRepository: ShaderStore.GetShadersRepository(this._shaderLanguage), + includesShadersStore: ShaderStore.GetIncludesShadersStore(this._shaderLanguage), + version: (this._engine.version * 100).toString(), + platformName: this._engine.shaderPlatformName, + processingContext: this._processingContext, + isNDCHalfZRange: this._engine.isNDCHalfZRange, + useReverseDepthBuffer: this._engine.useReverseDepthBuffer, + processCodeAfterIncludes: this._processCodeAfterIncludes, + }; + _processShaderCode(processorOptions, this.name, this._processFinalCode, (migratedVertexCode, migratedFragmentCode) => { + this._vertexSourceCode = migratedVertexCode; + this._fragmentSourceCode = migratedFragmentCode; + this._prepareEffect(keepExistingPipelineContext); + }, this._shaderLanguage, this._engine, this); + } + /** + * Unique key for this effect + */ + get key() { + return this._key; + } + /** + * If the effect has been compiled and prepared. + * @returns if the effect is compiled and prepared. + */ + isReady() { + try { + return this._isReadyInternal(); + } + catch { + return false; + } + } + _isReadyInternal() { + if (this._engine.isDisposed) { + // Engine is disposed, we return true to prevent looping over the setTimeout call in _checkIsReady + return true; + } + if (this._isReady) { + return true; + } + if (this._pipelineContext) { + return this._pipelineContext.isReady; + } + return false; + } + /** + * The engine the effect was initialized with. + * @returns the engine. + */ + getEngine() { + return this._engine; + } + /** + * The pipeline context for this effect + * @returns the associated pipeline context + */ + getPipelineContext() { + return this._pipelineContext; + } + /** + * The set of names of attribute variables for the shader. + * @returns An array of attribute names. + */ + getAttributesNames() { + return this._attributesNames; + } + /** + * Returns the attribute at the given index. + * @param index The index of the attribute. + * @returns The location of the attribute. + */ + getAttributeLocation(index) { + return this._attributes[index]; + } + /** + * Returns the attribute based on the name of the variable. + * @param name of the attribute to look up. + * @returns the attribute location. + */ + getAttributeLocationByName(name) { + return this._attributeLocationByName[name]; + } + /** + * The number of attributes. + * @returns the number of attributes. + */ + getAttributesCount() { + return this._attributes.length; + } + /** + * Gets the index of a uniform variable. + * @param uniformName of the uniform to look up. + * @returns the index. + */ + getUniformIndex(uniformName) { + return this._uniformsNames.indexOf(uniformName); + } + /** + * Returns the attribute based on the name of the variable. + * @param uniformName of the uniform to look up. + * @returns the location of the uniform. + */ + getUniform(uniformName) { + return this._uniforms[uniformName]; + } + /** + * Returns an array of sampler variable names + * @returns The array of sampler variable names. + */ + getSamplers() { + return this._samplerList; + } + /** + * Returns an array of uniform variable names + * @returns The array of uniform variable names. + */ + getUniformNames() { + return this._uniformsNames; + } + /** + * Returns an array of uniform buffer variable names + * @returns The array of uniform buffer variable names. + */ + getUniformBuffersNames() { + return this._uniformBuffersNamesList; + } + /** + * Returns the index parameters used to create the effect + * @returns The index parameters object + */ + getIndexParameters() { + return this._indexParameters; + } + /** + * The error from the last compilation. + * @returns the error string. + */ + getCompilationError() { + return this._compilationError; + } + /** + * Gets a boolean indicating that all fallbacks were used during compilation + * @returns true if all fallbacks were used + */ + allFallbacksProcessed() { + return this._allFallbacksProcessed; + } + /** + * Wait until compilation before fulfilling. + * @returns a promise to wait for completion. + */ + whenCompiledAsync() { + return new Promise((resolve) => { + this.executeWhenCompiled(resolve); + }); + } + /** + * Adds a callback to the onCompiled observable and call the callback immediately if already ready. + * @param func The callback to be used. + */ + executeWhenCompiled(func) { + if (this.isReady()) { + func(this); + return; + } + this.onCompileObservable.add((effect) => { + func(effect); + }); + if (!this._pipelineContext || this._pipelineContext.isAsync) { + this._checkIsReady(null); + } + } + _checkIsReady(previousPipelineContext) { + _retryWithInterval(() => { + return this._isReadyInternal() || this._isDisposed; + }, () => { + // no-op - done in the _isReadyInternal call + }, (e) => { + this._processCompilationErrors(e, previousPipelineContext); + }, 16, 120000, true, ` - Effect: ${typeof this.name === "string" ? this.name : this.key}`); + } + /** + * Gets the vertex shader source code of this effect + * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc) + */ + get vertexSourceCode() { + return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride + ? this._vertexSourceCodeOverride + : (this._pipelineContext?._getVertexShaderCode() ?? this._vertexSourceCode); + } + /** + * Gets the fragment shader source code of this effect + * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc) + */ + get fragmentSourceCode() { + return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride + ? this._fragmentSourceCodeOverride + : (this._pipelineContext?._getFragmentShaderCode() ?? this._fragmentSourceCode); + } + /** + * Gets the vertex shader source code before migration. + * This is the source code after the include directives have been replaced by their contents but before the code is migrated, i.e. before ShaderProcess._ProcessShaderConversion is executed. + * This method is, among other things, responsible for parsing #if/#define directives as well as converting GLES2 syntax to GLES3 (in the case of WebGL). + */ + get vertexSourceCodeBeforeMigration() { + return this._vertexSourceCodeBeforeMigration; + } + /** + * Gets the fragment shader source code before migration. + * This is the source code after the include directives have been replaced by their contents but before the code is migrated, i.e. before ShaderProcess._ProcessShaderConversion is executed. + * This method is, among other things, responsible for parsing #if/#define directives as well as converting GLES2 syntax to GLES3 (in the case of WebGL). + */ + get fragmentSourceCodeBeforeMigration() { + return this._fragmentSourceCodeBeforeMigration; + } + /** + * Gets the vertex shader source code before it has been modified by any processing + */ + get rawVertexSourceCode() { + return this._rawVertexSourceCode; + } + /** + * Gets the fragment shader source code before it has been modified by any processing + */ + get rawFragmentSourceCode() { + return this._rawFragmentSourceCode; + } + getPipelineGenerationOptions() { + return { + platformName: this._engine.shaderPlatformName, + shaderLanguage: this._shaderLanguage, + shaderNameOrContent: this.name, + key: this._key, + defines: this.defines.split("\n"), + addGlobalDefines: false, + extendedProcessingOptions: { + indexParameters: this._indexParameters, + isNDCHalfZRange: this._engine.isNDCHalfZRange, + useReverseDepthBuffer: this._engine.useReverseDepthBuffer, + supportsUniformBuffers: this._engine.supportsUniformBuffers, + }, + extendedCreatePipelineOptions: { + transformFeedbackVaryings: this._transformFeedbackVaryings, + createAsRaw: !!(this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride), + }, + }; + } + /** + * Recompiles the webGL program + * @param vertexSourceCode The source code for the vertex shader. + * @param fragmentSourceCode The source code for the fragment shader. + * @param onCompiled Callback called when completed. + * @param onError Callback called on error. + * @internal + */ + _rebuildProgram(vertexSourceCode, fragmentSourceCode, onCompiled, onError) { + this._isReady = false; + this._vertexSourceCodeOverride = vertexSourceCode; + this._fragmentSourceCodeOverride = fragmentSourceCode; + this.onError = (effect, error) => { + if (onError) { + onError(error); + } + }; + this.onCompiled = () => { + const scenes = this.getEngine().scenes; + if (scenes) { + for (let i = 0; i < scenes.length; i++) { + scenes[i].markAllMaterialsAsDirty(127); + } + } + this._pipelineContext._handlesSpectorRebuildCallback?.(onCompiled); + }; + this._fallbacks = null; + this._prepareEffect(); + } + _onRenderingStateCompiled(pipelineContext) { + this._pipelineContext = pipelineContext; + this._pipelineContext.setEngine(this._engine); + this._attributes = []; + this._pipelineContext._fillEffectInformation(this, this._uniformBuffersNames, this._uniformsNames, this._uniforms, this._samplerList, this._samplers, this._attributesNames, this._attributes); + // Caches attribute locations. + if (this._attributesNames) { + for (let i = 0; i < this._attributesNames.length; i++) { + const name = this._attributesNames[i]; + this._attributeLocationByName[name] = this._attributes[i]; + } + } + this._engine.bindSamplers(this); + this._compilationError = ""; + this._isReady = true; + if (this.onCompiled) { + this.onCompiled(this); + } + this.onCompileObservable.notifyObservers(this); + this.onCompileObservable.clear(); + // Unbind mesh reference in fallbacks + if (this._fallbacks) { + this._fallbacks.unBindMesh(); + } + if (Effect.AutomaticallyClearCodeCache) { + this.clearCodeCache(); + } + } + /** + * Prepares the effect + * @internal + */ + _prepareEffect(keepExistingPipelineContext = false) { + const previousPipelineContext = this._pipelineContext; + this._isReady = false; + try { + const overrides = !!(this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride); + const defines = overrides ? null : this.defines; + const vertex = overrides ? this._vertexSourceCodeOverride : this._vertexSourceCode; + const fragment = overrides ? this._fragmentSourceCodeOverride : this._fragmentSourceCode; + const engine = this._engine; + this._pipelineContext = createAndPreparePipelineContext({ + existingPipelineContext: keepExistingPipelineContext ? previousPipelineContext : null, + vertex, + fragment, + context: engine.shaderPlatformName === "WEBGL2" || engine.shaderPlatformName === "WEBGL1" ? engine._gl : undefined, + rebuildRebind: (vertexSourceCode, fragmentSourceCode, onCompiled, onError) => this._rebuildProgram(vertexSourceCode, fragmentSourceCode, onCompiled, onError), + defines, + transformFeedbackVaryings: this._transformFeedbackVaryings, + name: this._key.replace(/\r/g, "").replace(/\n/g, "|"), + createAsRaw: overrides, + disableParallelCompilation: this._disableParallelShaderCompilation, + shaderProcessingContext: this._processingContext, + onRenderingStateCompiled: (pipelineContext) => { + if (previousPipelineContext && !keepExistingPipelineContext) { + this._engine._deletePipelineContext(previousPipelineContext); + } + if (pipelineContext) { + this._onRenderingStateCompiled(pipelineContext); + } + }, + }, this._engine.createPipelineContext.bind(this._engine), this._engine._preparePipelineContext.bind(this._engine), this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)); + if (this._pipelineContext.isAsync) { + this._checkIsReady(previousPipelineContext); + } + } + catch (e) { + this._processCompilationErrors(e, previousPipelineContext); + } + } + _getShaderCodeAndErrorLine(code, error, isFragment) { + const regexp = isFragment ? /FRAGMENT SHADER ERROR: 0:(\d+?):/ : /VERTEX SHADER ERROR: 0:(\d+?):/; + let errorLine = null; + if (error && code) { + const res = error.match(regexp); + if (res && res.length === 2) { + const lineNumber = parseInt(res[1]); + const lines = code.split("\n", -1); + if (lines.length >= lineNumber) { + errorLine = `Offending line [${lineNumber}] in ${isFragment ? "fragment" : "vertex"} code: ${lines[lineNumber - 1]}`; + } + } + } + return [code, errorLine]; + } + _processCompilationErrors(e, previousPipelineContext = null) { + this._compilationError = e.message; + const attributesNames = this._attributesNames; + const fallbacks = this._fallbacks; + // Let's go through fallbacks then + Logger.Error("Unable to compile effect:"); + Logger.Error("Uniforms: " + + this._uniformsNames.map(function (uniform) { + return " " + uniform; + })); + Logger.Error("Attributes: " + + attributesNames.map(function (attribute) { + return " " + attribute; + })); + Logger.Error("Defines:\n" + this.defines); + if (Effect.LogShaderCodeOnCompilationError) { + let lineErrorVertex = null, lineErrorFragment = null, code = null; + if (this._pipelineContext?._getVertexShaderCode()) { + [code, lineErrorVertex] = this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(), this._compilationError, false); + if (code) { + Logger.Error("Vertex code:"); + Logger.Error(code); + } + } + if (this._pipelineContext?._getFragmentShaderCode()) { + [code, lineErrorFragment] = this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(), this._compilationError, true); + if (code) { + Logger.Error("Fragment code:"); + Logger.Error(code); + } + } + if (lineErrorVertex) { + Logger.Error(lineErrorVertex); + } + if (lineErrorFragment) { + Logger.Error(lineErrorFragment); + } + } + Logger.Error("Error: " + this._compilationError); + const notifyErrors = () => { + if (this.onError) { + this.onError(this, this._compilationError); + } + this.onErrorObservable.notifyObservers(this); + this._engine.onEffectErrorObservable.notifyObservers({ effect: this, errors: this._compilationError }); + }; + // In case a previous compilation was successful, we need to restore the previous pipeline context + if (previousPipelineContext) { + this._pipelineContext = previousPipelineContext; + this._isReady = true; + notifyErrors(); + } + // Lets try to compile fallbacks as long as we have some. + if (fallbacks) { + this._pipelineContext = null; + if (fallbacks.hasMoreFallbacks) { + this._allFallbacksProcessed = false; + Logger.Error("Trying next fallback."); + this.defines = fallbacks.reduce(this.defines, this); + this._prepareEffect(); + } + else { + // Sorry we did everything we can + this._allFallbacksProcessed = true; + notifyErrors(); + this.onErrorObservable.clear(); + // Unbind mesh reference in fallbacks + if (this._fallbacks) { + this._fallbacks.unBindMesh(); + } + } + } + else { + this._allFallbacksProcessed = true; + // In case of error, without any prior successful compilation, let s notify observers + if (!previousPipelineContext) { + notifyErrors(); + } + } + } + /** + * Checks if the effect is supported. (Must be called after compilation) + */ + get isSupported() { + return this._compilationError === ""; + } + /** + * Binds a texture to the engine to be used as output of the shader. + * @param channel Name of the output variable. + * @param texture Texture to bind. + * @internal + */ + _bindTexture(channel, texture) { + this._engine._bindTexture(this._samplers[channel], texture, channel); + } + /** + * Sets a texture on the engine to be used in the shader. + * @param channel Name of the sampler variable. + * @param texture Texture to set. + */ + setTexture(channel, texture) { + this._engine.setTexture(this._samplers[channel], this._uniforms[channel], texture, channel); + } + /** + * Sets an array of textures on the engine to be used in the shader. + * @param channel Name of the variable. + * @param textures Textures to set. + */ + setTextureArray(channel, textures) { + const exName = channel + "Ex"; + if (this._samplerList.indexOf(exName + "0") === -1) { + const initialPos = this._samplerList.indexOf(channel); + for (let index = 1; index < textures.length; index++) { + const currentExName = exName + (index - 1).toString(); + this._samplerList.splice(initialPos + index, 0, currentExName); + } + // Reset every channels + let channelIndex = 0; + for (const key of this._samplerList) { + this._samplers[key] = channelIndex; + channelIndex += 1; + } + } + this._engine.setTextureArray(this._samplers[channel], this._uniforms[channel], textures, channel); + } + /** + * Binds a buffer to a uniform. + * @param buffer Buffer to bind. + * @param name Name of the uniform variable to bind to. + */ + bindUniformBuffer(buffer, name) { + const bufferName = this._uniformBuffersNames[name]; + if (bufferName === undefined || (Effect._BaseCache[bufferName] === buffer && this._engine._features.useUBOBindingCache)) { + return; + } + Effect._BaseCache[bufferName] = buffer; + this._engine.bindUniformBufferBase(buffer, bufferName, name); + } + /** + * Binds block to a uniform. + * @param blockName Name of the block to bind. + * @param index Index to bind. + */ + bindUniformBlock(blockName, index) { + this._engine.bindUniformBlock(this._pipelineContext, blockName, index); + } + /** + * Sets an integer value on a uniform variable. + * @param uniformName Name of the variable. + * @param value Value to be set. + * @returns this effect. + */ + setInt(uniformName, value) { + this._pipelineContext.setInt(uniformName, value); + return this; + } + /** + * Sets an int2 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int2. + * @param y Second int in int2. + * @returns this effect. + */ + setInt2(uniformName, x, y) { + this._pipelineContext.setInt2(uniformName, x, y); + return this; + } + /** + * Sets an int3 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int3. + * @param y Second int in int3. + * @param z Third int in int3. + * @returns this effect. + */ + setInt3(uniformName, x, y, z) { + this._pipelineContext.setInt3(uniformName, x, y, z); + return this; + } + /** + * Sets an int4 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int4. + * @param y Second int in int4. + * @param z Third int in int4. + * @param w Fourth int in int4. + * @returns this effect. + */ + setInt4(uniformName, x, y, z, w) { + this._pipelineContext.setInt4(uniformName, x, y, z, w); + return this; + } + /** + * Sets an int array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setIntArray(uniformName, array) { + this._pipelineContext.setIntArray(uniformName, array); + return this; + } + /** + * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setIntArray2(uniformName, array) { + this._pipelineContext.setIntArray2(uniformName, array); + return this; + } + /** + * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setIntArray3(uniformName, array) { + this._pipelineContext.setIntArray3(uniformName, array); + return this; + } + /** + * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setIntArray4(uniformName, array) { + this._pipelineContext.setIntArray4(uniformName, array); + return this; + } + /** + * Sets an unsigned integer value on a uniform variable. + * @param uniformName Name of the variable. + * @param value Value to be set. + * @returns this effect. + */ + setUInt(uniformName, value) { + this._pipelineContext.setUInt(uniformName, value); + return this; + } + /** + * Sets an unsigned int2 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint2. + * @param y Second unsigned int in uint2. + * @returns this effect. + */ + setUInt2(uniformName, x, y) { + this._pipelineContext.setUInt2(uniformName, x, y); + return this; + } + /** + * Sets an unsigned int3 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint3. + * @param y Second unsigned int in uint3. + * @param z Third unsigned int in uint3. + * @returns this effect. + */ + setUInt3(uniformName, x, y, z) { + this._pipelineContext.setUInt3(uniformName, x, y, z); + return this; + } + /** + * Sets an unsigned int4 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint4. + * @param y Second unsigned int in uint4. + * @param z Third unsigned int in uint4. + * @param w Fourth unsigned int in uint4. + * @returns this effect. + */ + setUInt4(uniformName, x, y, z, w) { + this._pipelineContext.setUInt4(uniformName, x, y, z, w); + return this; + } + /** + * Sets an unsigned int array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setUIntArray(uniformName, array) { + this._pipelineContext.setUIntArray(uniformName, array); + return this; + } + /** + * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setUIntArray2(uniformName, array) { + this._pipelineContext.setUIntArray2(uniformName, array); + return this; + } + /** + * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setUIntArray3(uniformName, array) { + this._pipelineContext.setUIntArray3(uniformName, array); + return this; + } + /** + * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setUIntArray4(uniformName, array) { + this._pipelineContext.setUIntArray4(uniformName, array); + return this; + } + /** + * Sets an float array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setFloatArray(uniformName, array) { + this._pipelineContext.setArray(uniformName, array); + return this; + } + /** + * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setFloatArray2(uniformName, array) { + this._pipelineContext.setArray2(uniformName, array); + return this; + } + /** + * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setFloatArray3(uniformName, array) { + this._pipelineContext.setArray3(uniformName, array); + return this; + } + /** + * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setFloatArray4(uniformName, array) { + this._pipelineContext.setArray4(uniformName, array); + return this; + } + /** + * Sets an array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setArray(uniformName, array) { + this._pipelineContext.setArray(uniformName, array); + return this; + } + /** + * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setArray2(uniformName, array) { + this._pipelineContext.setArray2(uniformName, array); + return this; + } + /** + * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setArray3(uniformName, array) { + this._pipelineContext.setArray3(uniformName, array); + return this; + } + /** + * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + setArray4(uniformName, array) { + this._pipelineContext.setArray4(uniformName, array); + return this; + } + /** + * Sets matrices on a uniform variable. + * @param uniformName Name of the variable. + * @param matrices matrices to be set. + * @returns this effect. + */ + setMatrices(uniformName, matrices) { + this._pipelineContext.setMatrices(uniformName, matrices); + return this; + } + /** + * Sets matrix on a uniform variable. + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + * @returns this effect. + */ + setMatrix(uniformName, matrix) { + this._pipelineContext.setMatrix(uniformName, matrix); + return this; + } + /** + * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix) + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + * @returns this effect. + */ + setMatrix3x3(uniformName, matrix) { + // the cast is ok because it is gl.uniformMatrix3fv() which is called at the end, and this function accepts Float32Array and Array + this._pipelineContext.setMatrix3x3(uniformName, matrix); + return this; + } + /** + * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix) + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + * @returns this effect. + */ + setMatrix2x2(uniformName, matrix) { + // the cast is ok because it is gl.uniformMatrix3fv() which is called at the end, and this function accepts Float32Array and Array + this._pipelineContext.setMatrix2x2(uniformName, matrix); + return this; + } + /** + * Sets a float on a uniform variable. + * @param uniformName Name of the variable. + * @param value value to be set. + * @returns this effect. + */ + setFloat(uniformName, value) { + this._pipelineContext.setFloat(uniformName, value); + return this; + } + /** + * Sets a boolean on a uniform variable. + * @param uniformName Name of the variable. + * @param bool value to be set. + * @returns this effect. + */ + setBool(uniformName, bool) { + this._pipelineContext.setInt(uniformName, bool ? 1 : 0); + return this; + } + /** + * Sets a Vector2 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector2 vector2 to be set. + * @returns this effect. + */ + setVector2(uniformName, vector2) { + this._pipelineContext.setVector2(uniformName, vector2); + return this; + } + /** + * Sets a float2 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float2. + * @param y Second float in float2. + * @returns this effect. + */ + setFloat2(uniformName, x, y) { + this._pipelineContext.setFloat2(uniformName, x, y); + return this; + } + /** + * Sets a Vector3 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector3 Value to be set. + * @returns this effect. + */ + setVector3(uniformName, vector3) { + this._pipelineContext.setVector3(uniformName, vector3); + return this; + } + /** + * Sets a float3 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float3. + * @param y Second float in float3. + * @param z Third float in float3. + * @returns this effect. + */ + setFloat3(uniformName, x, y, z) { + this._pipelineContext.setFloat3(uniformName, x, y, z); + return this; + } + /** + * Sets a Vector4 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector4 Value to be set. + * @returns this effect. + */ + setVector4(uniformName, vector4) { + this._pipelineContext.setVector4(uniformName, vector4); + return this; + } + /** + * Sets a Quaternion on a uniform variable. + * @param uniformName Name of the variable. + * @param quaternion Value to be set. + * @returns this effect. + */ + setQuaternion(uniformName, quaternion) { + this._pipelineContext.setQuaternion(uniformName, quaternion); + return this; + } + /** + * Sets a float4 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float4. + * @param y Second float in float4. + * @param z Third float in float4. + * @param w Fourth float in float4. + * @returns this effect. + */ + setFloat4(uniformName, x, y, z, w) { + this._pipelineContext.setFloat4(uniformName, x, y, z, w); + return this; + } + /** + * Sets a Color3 on a uniform variable. + * @param uniformName Name of the variable. + * @param color3 Value to be set. + * @returns this effect. + */ + setColor3(uniformName, color3) { + this._pipelineContext.setColor3(uniformName, color3); + return this; + } + /** + * Sets a Color4 on a uniform variable. + * @param uniformName Name of the variable. + * @param color3 Value to be set. + * @param alpha Alpha value to be set. + * @returns this effect. + */ + setColor4(uniformName, color3, alpha) { + this._pipelineContext.setColor4(uniformName, color3, alpha); + return this; + } + /** + * Sets a Color4 on a uniform variable + * @param uniformName defines the name of the variable + * @param color4 defines the value to be set + * @returns this effect. + */ + setDirectColor4(uniformName, color4) { + this._pipelineContext.setDirectColor4(uniformName, color4); + return this; + } + /** + * Use this wisely: It will remove the cached code from this effect + * It is probably ok to call it if you are not using ShadowDepthWrapper or if everything is already up and running + * DO NOT CALL IT if you want to have support for context lost recovery + */ + clearCodeCache() { + this._vertexSourceCode = ""; + this._fragmentSourceCode = ""; + this._fragmentSourceCodeBeforeMigration = ""; + this._vertexSourceCodeBeforeMigration = ""; + } + /** + * Release all associated resources. + * @param force specifies if the effect must be released no matter what + **/ + dispose(force = false) { + if (force) { + this._refCount = 0; + } + else { + if (Effect.PersistentMode) { + return; + } + this._refCount--; + } + if (this._refCount > 0 || this._isDisposed) { + // Others are still using the effect or the effect was already disposed + return; + } + if (this._pipelineContext) { + resetCachedPipeline(this._pipelineContext); + } + this._engine._releaseEffect(this); + this.clearCodeCache(); + this._isDisposed = true; + } + /** + * This function will add a new shader to the shader store + * @param name the name of the shader + * @param pixelShader optional pixel shader content + * @param vertexShader optional vertex shader content + * @param shaderLanguage the language the shader is written in (default: GLSL) + */ + static RegisterShader(name, pixelShader, vertexShader, shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + if (pixelShader) { + ShaderStore.GetShadersStore(shaderLanguage)[`${name}PixelShader`] = pixelShader; + } + if (vertexShader) { + ShaderStore.GetShadersStore(shaderLanguage)[`${name}VertexShader`] = vertexShader; + } + } + /** + * Resets the cache of effects. + */ + static ResetCache() { + Effect._BaseCache = {}; + } +} +/** + * Enable logging of the shader code when a compilation error occurs + */ +Effect.LogShaderCodeOnCompilationError = true; +/** + * Gets or sets a boolean indicating that effect ref counting is disabled + * If true, the effect will persist in memory until engine is disposed + */ +Effect.PersistentMode = false; +/** + * Use this with caution + * See ClearCodeCache function comments + */ +Effect.AutomaticallyClearCodeCache = false; +Effect._UniqueIdSeed = 0; +Effect._BaseCache = {}; +/** + * Store of each shader (The can be looked up using effect.key) + */ +Effect.ShadersStore = ShaderStore.ShadersStore; +/** + * Store of each included file for a shader (The can be looked up using effect.key) + */ +Effect.IncludesShadersStore = ShaderStore.IncludesShadersStore; + +/** @internal */ +class PerformanceConfigurator { + /** + * @internal + */ + static SetMatrixPrecision(use64bits) { + PerformanceConfigurator.MatrixTrackPrecisionChange = false; + if (use64bits && !PerformanceConfigurator.MatrixUse64Bits) { + if (PerformanceConfigurator.MatrixTrackedMatrices) { + for (let m = 0; m < PerformanceConfigurator.MatrixTrackedMatrices.length; ++m) { + const matrix = PerformanceConfigurator.MatrixTrackedMatrices[m]; + const values = matrix._m; + matrix._m = new Array(16); + for (let i = 0; i < 16; ++i) { + matrix._m[i] = values[i]; + } + } + } + } + PerformanceConfigurator.MatrixUse64Bits = use64bits; + PerformanceConfigurator.MatrixCurrentType = PerformanceConfigurator.MatrixUse64Bits ? Array : Float32Array; + PerformanceConfigurator.MatrixTrackedMatrices = null; // reclaim some memory, as we don't need _TrackedMatrices anymore + } +} +/** @internal */ +PerformanceConfigurator.MatrixUse64Bits = false; +/** @internal */ +PerformanceConfigurator.MatrixTrackPrecisionChange = true; +/** @internal */ +PerformanceConfigurator.MatrixCurrentType = Float32Array; +/** @internal */ +PerformanceConfigurator.MatrixTrackedMatrices = []; + +/** + * Class containing a set of static utilities functions for precision date + */ +class PrecisionDate { + /** + * Gets either window.performance.now() if supported or Date.now() else + */ + static get Now() { + if (IsWindowObjectExist() && window.performance && window.performance.now) { + return window.performance.now(); + } + return Date.now(); + } +} + +/** + * @internal + **/ +class DepthCullingState { + /** + * Initializes the state. + * @param reset + */ + constructor(reset = true) { + this._isDepthTestDirty = false; + this._isDepthMaskDirty = false; + this._isDepthFuncDirty = false; + this._isCullFaceDirty = false; + this._isCullDirty = false; + this._isZOffsetDirty = false; + this._isFrontFaceDirty = false; + if (reset) { + this.reset(); + } + } + get isDirty() { + return (this._isDepthFuncDirty || + this._isDepthTestDirty || + this._isDepthMaskDirty || + this._isCullFaceDirty || + this._isCullDirty || + this._isZOffsetDirty || + this._isFrontFaceDirty); + } + get zOffset() { + return this._zOffset; + } + set zOffset(value) { + if (this._zOffset === value) { + return; + } + this._zOffset = value; + this._isZOffsetDirty = true; + } + get zOffsetUnits() { + return this._zOffsetUnits; + } + set zOffsetUnits(value) { + if (this._zOffsetUnits === value) { + return; + } + this._zOffsetUnits = value; + this._isZOffsetDirty = true; + } + get cullFace() { + return this._cullFace; + } + set cullFace(value) { + if (this._cullFace === value) { + return; + } + this._cullFace = value; + this._isCullFaceDirty = true; + } + get cull() { + return this._cull; + } + set cull(value) { + if (this._cull === value) { + return; + } + this._cull = value; + this._isCullDirty = true; + } + get depthFunc() { + return this._depthFunc; + } + set depthFunc(value) { + if (this._depthFunc === value) { + return; + } + this._depthFunc = value; + this._isDepthFuncDirty = true; + } + get depthMask() { + return this._depthMask; + } + set depthMask(value) { + if (this._depthMask === value) { + return; + } + this._depthMask = value; + this._isDepthMaskDirty = true; + } + get depthTest() { + return this._depthTest; + } + set depthTest(value) { + if (this._depthTest === value) { + return; + } + this._depthTest = value; + this._isDepthTestDirty = true; + } + get frontFace() { + return this._frontFace; + } + set frontFace(value) { + if (this._frontFace === value) { + return; + } + this._frontFace = value; + this._isFrontFaceDirty = true; + } + reset() { + this._depthMask = true; + this._depthTest = true; + this._depthFunc = null; + this._cullFace = null; + this._cull = null; + this._zOffset = 0; + this._zOffsetUnits = 0; + this._frontFace = null; + this._isDepthTestDirty = true; + this._isDepthMaskDirty = true; + this._isDepthFuncDirty = false; + this._isCullFaceDirty = false; + this._isCullDirty = false; + this._isZOffsetDirty = true; + this._isFrontFaceDirty = false; + } + apply(gl) { + if (!this.isDirty) { + return; + } + // Cull + if (this._isCullDirty) { + if (this.cull) { + gl.enable(gl.CULL_FACE); + } + else { + gl.disable(gl.CULL_FACE); + } + this._isCullDirty = false; + } + // Cull face + if (this._isCullFaceDirty) { + gl.cullFace(this.cullFace); + this._isCullFaceDirty = false; + } + // Depth mask + if (this._isDepthMaskDirty) { + gl.depthMask(this.depthMask); + this._isDepthMaskDirty = false; + } + // Depth test + if (this._isDepthTestDirty) { + if (this.depthTest) { + gl.enable(gl.DEPTH_TEST); + } + else { + gl.disable(gl.DEPTH_TEST); + } + this._isDepthTestDirty = false; + } + // Depth func + if (this._isDepthFuncDirty) { + gl.depthFunc(this.depthFunc); + this._isDepthFuncDirty = false; + } + // zOffset + if (this._isZOffsetDirty) { + if (this.zOffset || this.zOffsetUnits) { + gl.enable(gl.POLYGON_OFFSET_FILL); + gl.polygonOffset(this.zOffset, this.zOffsetUnits); + } + else { + gl.disable(gl.POLYGON_OFFSET_FILL); + } + this._isZOffsetDirty = false; + } + // Front face + if (this._isFrontFaceDirty) { + gl.frontFace(this.frontFace); + this._isFrontFaceDirty = false; + } + } +} + +/** + * @internal + **/ +class StencilStateComposer { + get isDirty() { + return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty; + } + get func() { + return this._func; + } + set func(value) { + if (this._func === value) { + return; + } + this._func = value; + this._isStencilFuncDirty = true; + } + get funcRef() { + return this._funcRef; + } + set funcRef(value) { + if (this._funcRef === value) { + return; + } + this._funcRef = value; + this._isStencilFuncDirty = true; + } + get funcMask() { + return this._funcMask; + } + set funcMask(value) { + if (this._funcMask === value) { + return; + } + this._funcMask = value; + this._isStencilFuncDirty = true; + } + get opStencilFail() { + return this._opStencilFail; + } + set opStencilFail(value) { + if (this._opStencilFail === value) { + return; + } + this._opStencilFail = value; + this._isStencilOpDirty = true; + } + get opDepthFail() { + return this._opDepthFail; + } + set opDepthFail(value) { + if (this._opDepthFail === value) { + return; + } + this._opDepthFail = value; + this._isStencilOpDirty = true; + } + get opStencilDepthPass() { + return this._opStencilDepthPass; + } + set opStencilDepthPass(value) { + if (this._opStencilDepthPass === value) { + return; + } + this._opStencilDepthPass = value; + this._isStencilOpDirty = true; + } + get mask() { + return this._mask; + } + set mask(value) { + if (this._mask === value) { + return; + } + this._mask = value; + this._isStencilMaskDirty = true; + } + get enabled() { + return this._enabled; + } + set enabled(value) { + if (this._enabled === value) { + return; + } + this._enabled = value; + this._isStencilTestDirty = true; + } + constructor(reset = true) { + this._isStencilTestDirty = false; + this._isStencilMaskDirty = false; + this._isStencilFuncDirty = false; + this._isStencilOpDirty = false; + this.useStencilGlobalOnly = false; + if (reset) { + this.reset(); + } + } + reset() { + this.stencilMaterial = undefined; + this.stencilGlobal?.reset(); + this._isStencilTestDirty = true; + this._isStencilMaskDirty = true; + this._isStencilFuncDirty = true; + this._isStencilOpDirty = true; + } + apply(gl) { + if (!gl) { + return; + } + const stencilMaterialEnabled = !this.useStencilGlobalOnly && !!this.stencilMaterial?.enabled; + this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled; + this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func; + this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef; + this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask; + this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail; + this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail; + this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass; + this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask; + if (!this.isDirty) { + return; + } + // Stencil test + if (this._isStencilTestDirty) { + if (this.enabled) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + this._isStencilTestDirty = false; + } + // Stencil mask + if (this._isStencilMaskDirty) { + gl.stencilMask(this.mask); + this._isStencilMaskDirty = false; + } + // Stencil func + if (this._isStencilFuncDirty) { + gl.stencilFunc(this.func, this.funcRef, this.funcMask); + this._isStencilFuncDirty = false; + } + // Stencil op + if (this._isStencilOpDirty) { + gl.stencilOp(this.opStencilFail, this.opDepthFail, this.opStencilDepthPass); + this._isStencilOpDirty = false; + } + } +} + +/** + * @internal + **/ +class StencilState { + constructor() { + this.reset(); + } + reset() { + this.enabled = false; + this.mask = 0xff; + this.func = StencilState.ALWAYS; + this.funcRef = 1; + this.funcMask = 0xff; + this.opStencilFail = StencilState.KEEP; + this.opDepthFail = StencilState.KEEP; + this.opStencilDepthPass = StencilState.REPLACE; + } + get stencilFunc() { + return this.func; + } + set stencilFunc(value) { + this.func = value; + } + get stencilFuncRef() { + return this.funcRef; + } + set stencilFuncRef(value) { + this.funcRef = value; + } + get stencilFuncMask() { + return this.funcMask; + } + set stencilFuncMask(value) { + this.funcMask = value; + } + get stencilOpStencilFail() { + return this.opStencilFail; + } + set stencilOpStencilFail(value) { + this.opStencilFail = value; + } + get stencilOpDepthFail() { + return this.opDepthFail; + } + set stencilOpDepthFail(value) { + this.opDepthFail = value; + } + get stencilOpStencilDepthPass() { + return this.opStencilDepthPass; + } + set stencilOpStencilDepthPass(value) { + this.opStencilDepthPass = value; + } + get stencilMask() { + return this.mask; + } + set stencilMask(value) { + this.mask = value; + } + get stencilTest() { + return this.enabled; + } + set stencilTest(value) { + this.enabled = value; + } +} +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */ +StencilState.ALWAYS = 519; +/** Passed to stencilOperation to specify that stencil value must be kept */ +StencilState.KEEP = 7680; +/** Passed to stencilOperation to specify that stencil value must be replaced */ +StencilState.REPLACE = 7681; + +/** + * @internal + **/ +class AlphaState { + /** + * Initializes the state. + */ + constructor() { + this._blendFunctionParameters = new Array(4); + this._blendEquationParameters = new Array(2); + this._blendConstants = new Array(4); + this._isBlendConstantsDirty = false; + this._alphaBlend = false; + this._isAlphaBlendDirty = false; + this._isBlendFunctionParametersDirty = false; + this._isBlendEquationParametersDirty = false; + this.reset(); + } + get isDirty() { + return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty || this._isBlendEquationParametersDirty; + } + get alphaBlend() { + return this._alphaBlend; + } + set alphaBlend(value) { + if (this._alphaBlend === value) { + return; + } + this._alphaBlend = value; + this._isAlphaBlendDirty = true; + } + setAlphaBlendConstants(r, g, b, a) { + if (this._blendConstants[0] === r && this._blendConstants[1] === g && this._blendConstants[2] === b && this._blendConstants[3] === a) { + return; + } + this._blendConstants[0] = r; + this._blendConstants[1] = g; + this._blendConstants[2] = b; + this._blendConstants[3] = a; + this._isBlendConstantsDirty = true; + } + setAlphaBlendFunctionParameters(value0, value1, value2, value3) { + if (this._blendFunctionParameters[0] === value0 && + this._blendFunctionParameters[1] === value1 && + this._blendFunctionParameters[2] === value2 && + this._blendFunctionParameters[3] === value3) { + return; + } + this._blendFunctionParameters[0] = value0; + this._blendFunctionParameters[1] = value1; + this._blendFunctionParameters[2] = value2; + this._blendFunctionParameters[3] = value3; + this._isBlendFunctionParametersDirty = true; + } + setAlphaEquationParameters(rgb, alpha) { + if (this._blendEquationParameters[0] === rgb && this._blendEquationParameters[1] === alpha) { + return; + } + this._blendEquationParameters[0] = rgb; + this._blendEquationParameters[1] = alpha; + this._isBlendEquationParametersDirty = true; + } + reset() { + this._alphaBlend = false; + this._blendFunctionParameters[0] = null; + this._blendFunctionParameters[1] = null; + this._blendFunctionParameters[2] = null; + this._blendFunctionParameters[3] = null; + this._blendEquationParameters[0] = null; + this._blendEquationParameters[1] = null; + this._blendConstants[0] = null; + this._blendConstants[1] = null; + this._blendConstants[2] = null; + this._blendConstants[3] = null; + this._isAlphaBlendDirty = true; + this._isBlendFunctionParametersDirty = false; + this._isBlendEquationParametersDirty = false; + this._isBlendConstantsDirty = false; + } + apply(gl) { + if (!this.isDirty) { + return; + } + // Alpha blend + if (this._isAlphaBlendDirty) { + if (this._alphaBlend) { + gl.enable(gl.BLEND); + } + else { + gl.disable(gl.BLEND); + } + this._isAlphaBlendDirty = false; + } + // Alpha function + if (this._isBlendFunctionParametersDirty) { + gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]); + this._isBlendFunctionParametersDirty = false; + } + // Alpha equation + if (this._isBlendEquationParametersDirty) { + gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]); + this._isBlendEquationParametersDirty = false; + } + // Constants + if (this._isBlendConstantsDirty) { + gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]); + this._isBlendConstantsDirty = false; + } + } +} + +const _registeredTextureLoaders = new Map(); +/** + * Registers a texture loader. + * If a loader for the extension exists in the registry, it will be replaced. + * @param extension The name of the loader extension. + * @param loaderFactory The factory function that creates the loader extension. + */ +function registerTextureLoader(extension, loaderFactory) { + if (unregisterTextureLoader(extension)) { + Logger.Warn(`Extension with the name '${name}' already exists`); + } + _registeredTextureLoaders.set(extension, loaderFactory); +} +/** + * Unregisters a texture loader. + * @param extension The name of the loader extension. + * @returns A boolean indicating whether the extension has been unregistered + */ +function unregisterTextureLoader(extension) { + return _registeredTextureLoaders.delete(extension); +} +/** + * Function used to get the correct texture loader for a specific extension. + * @param extension defines the file extension of the file being loaded + * @param mimeType defines the optional mime type of the file being loaded + * @returns the IInternalTextureLoader or null if it wasn't found + */ +function _GetCompatibleTextureLoader(extension, mimeType) { + if (mimeType === "image/ktx" || mimeType === "image/ktx2") { + extension = ".ktx"; + } + if (!_registeredTextureLoaders.has(extension)) { + if (extension.endsWith(".ies")) { + registerTextureLoader(".ies", () => Promise.resolve().then(() => iesTextureLoader).then((module) => new module._IESTextureLoader())); + } + if (extension.endsWith(".dds")) { + registerTextureLoader(".dds", () => Promise.resolve().then(() => ddsTextureLoader).then((module) => new module._DDSTextureLoader())); + } + if (extension.endsWith(".basis")) { + registerTextureLoader(".basis", () => Promise.resolve().then(() => basisTextureLoader).then((module) => new module._BasisTextureLoader())); + } + if (extension.endsWith(".env")) { + registerTextureLoader(".env", () => Promise.resolve().then(() => envTextureLoader).then((module) => new module._ENVTextureLoader())); + } + if (extension.endsWith(".hdr")) { + registerTextureLoader(".hdr", () => Promise.resolve().then(() => hdrTextureLoader).then((module) => new module._HDRTextureLoader())); + } + // The ".ktx2" file extension is still up for debate: https://github.com/KhronosGroup/KTX-Specification/issues/18 + if (extension.endsWith(".ktx") || extension.endsWith(".ktx2")) { + registerTextureLoader(".ktx", () => Promise.resolve().then(() => ktxTextureLoader).then((module) => new module._KTXTextureLoader())); + registerTextureLoader(".ktx2", () => Promise.resolve().then(() => ktxTextureLoader).then((module) => new module._KTXTextureLoader())); + } + if (extension.endsWith(".tga")) { + registerTextureLoader(".tga", () => Promise.resolve().then(() => tgaTextureLoader).then((module) => new module._TGATextureLoader())); + } + if (extension.endsWith(".exr")) { + registerTextureLoader(".exr", () => Promise.resolve().then(() => exrTextureLoader).then((module) => new module._ExrTextureLoader())); + } + } + const registered = _registeredTextureLoaders.get(extension); + return registered ? Promise.resolve(registered(mimeType)) : null; +} + +/** + * Queue a new function into the requested animation frame pool (ie. this function will be executed by the browser (or the javascript engine) for the next frame) + * @param func - the function to be called + * @param requester - the object that will request the next frame. Falls back to window. + * @returns frame number + */ +function QueueNewFrame(func, requester) { + // Note that there is kind of a typing issue here, as `setTimeout` might return something else than a number (NodeJs returns a NodeJS.Timeout object). + // Also if the global `requestAnimationFrame`'s returnType is number, `requester.requestPostAnimationFrame` and `requester.requestAnimationFrame` types + // are `any`. + if (!IsWindowObjectExist()) { + if (typeof requestAnimationFrame === "function") { + return requestAnimationFrame(func); + } + } + else { + const { requestAnimationFrame } = requester || window; + if (typeof requestAnimationFrame === "function") { + return requestAnimationFrame(func); + } + } + // fallback to the global `setTimeout`. + // In most cases (aka in the browser), `window` is the global object, so instead of calling `window.setTimeout` we could call the global `setTimeout`. + return setTimeout(func, 16); +} +/** + * The parent class for specialized engines (WebGL, WebGPU) + */ +class AbstractEngine { + /** + * Gets the current frame id + */ + get frameId() { + return this._frameId; + } + /** + * Gets a boolean indicating if the engine runs in WebGPU or not. + */ + get isWebGPU() { + return this._isWebGPU; + } + /** + * @internal + */ + _getShaderProcessor(shaderLanguage) { + return this._shaderProcessor; + } + /** + * Gets the shader platform name used by the effects. + */ + get shaderPlatformName() { + return this._shaderPlatformName; + } + _clearEmptyResources() { + this._emptyTexture = null; + this._emptyCubeTexture = null; + this._emptyTexture3D = null; + this._emptyTexture2DArray = null; + } + /** + * Gets or sets a boolean indicating if depth buffer should be reverse, going from far to near. + * This can provide greater z depth for distant objects. + */ + get useReverseDepthBuffer() { + return this._useReverseDepthBuffer; + } + set useReverseDepthBuffer(useReverse) { + if (useReverse === this._useReverseDepthBuffer) { + return; + } + this._useReverseDepthBuffer = useReverse; + if (useReverse) { + this._depthCullingState.depthFunc = 518; + } + else { + this._depthCullingState.depthFunc = 515; + } + } + /** + * Enable or disable color writing + * @param enable defines the state to set + */ + setColorWrite(enable) { + if (enable !== this._colorWrite) { + this._colorWriteChanged = true; + this._colorWrite = enable; + } + } + /** + * Gets a boolean indicating if color writing is enabled + * @returns the current color writing state + */ + getColorWrite() { + return this._colorWrite; + } + /** + * Gets the depth culling state manager + */ + get depthCullingState() { + return this._depthCullingState; + } + /** + * Gets the alpha state manager + */ + get alphaState() { + return this._alphaState; + } + /** + * Gets the stencil state manager + */ + get stencilState() { + return this._stencilState; + } + /** + * Gets the stencil state composer + */ + get stencilStateComposer() { + return this._stencilStateComposer; + } + /** @internal */ + _getGlobalDefines(defines) { + if (defines) { + if (this.isNDCHalfZRange) { + defines["IS_NDC_HALF_ZRANGE"] = ""; + } + else { + delete defines["IS_NDC_HALF_ZRANGE"]; + } + if (this.useReverseDepthBuffer) { + defines["USE_REVERSE_DEPTHBUFFER"] = ""; + } + else { + delete defines["USE_REVERSE_DEPTHBUFFER"]; + } + if (this.useExactSrgbConversions) { + defines["USE_EXACT_SRGB_CONVERSIONS"] = ""; + } + else { + delete defines["USE_EXACT_SRGB_CONVERSIONS"]; + } + return; + } + else { + let s = ""; + if (this.isNDCHalfZRange) { + s += "#define IS_NDC_HALF_ZRANGE"; + } + if (this.useReverseDepthBuffer) { + if (s) { + s += "\n"; + } + s += "#define USE_REVERSE_DEPTHBUFFER"; + } + if (this.useExactSrgbConversions) { + if (s) { + s += "\n"; + } + s += "#define USE_EXACT_SRGB_CONVERSIONS"; + } + return s; + } + } + _rebuildInternalTextures() { + const currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies + for (const internalTexture of currentState) { + internalTexture._rebuild(); + } + } + _rebuildRenderTargetWrappers() { + const currentState = this._renderTargetWrapperCache.slice(); // Do a copy because the rebuild will add proxies + for (const renderTargetWrapper of currentState) { + renderTargetWrapper._rebuild(); + } + } + _rebuildEffects() { + for (const key in this._compiledEffects) { + const effect = this._compiledEffects[key]; + effect._pipelineContext = null; // because _prepareEffect will try to dispose this pipeline before recreating it and that would lead to webgl errors + effect._prepareEffect(); + } + Effect.ResetCache(); + } + _rebuildGraphicsResources() { + // Ensure webgl and engine states are matching + this.wipeCaches(true); + // Rebuild effects + this._rebuildEffects(); + this._rebuildComputeEffects?.(); + // Note: + // The call to _rebuildBuffers must be made before the call to _rebuildInternalTextures because in the process of _rebuildBuffers the buffers used by the post process managers will be rebuilt + // and we may need to use the post process manager of the scene during _rebuildInternalTextures (in WebGL1, non-POT textures are rescaled using a post process + post process manager of the scene) + // Rebuild buffers + this._rebuildBuffers(); + // Rebuild textures + this._rebuildInternalTextures(); + // Rebuild textures + this._rebuildTextures(); + // Rebuild textures + this._rebuildRenderTargetWrappers(); + // Reset engine states after all the buffer/textures/... have been rebuilt + this.wipeCaches(true); + } + _flagContextRestored() { + Logger.Warn(this.name + " context successfully restored."); + this.onContextRestoredObservable.notifyObservers(this); + this._contextWasLost = false; + } + _restoreEngineAfterContextLost(initEngine) { + // Adding a timeout to avoid race condition at browser level + setTimeout(async () => { + this._clearEmptyResources(); + const depthTest = this._depthCullingState.depthTest; // backup those values because the call to initEngine / wipeCaches will reset them + const depthFunc = this._depthCullingState.depthFunc; + const depthMask = this._depthCullingState.depthMask; + const stencilTest = this._stencilState.stencilTest; + // Rebuild context + await initEngine(); + this._rebuildGraphicsResources(); + this._depthCullingState.depthTest = depthTest; + this._depthCullingState.depthFunc = depthFunc; + this._depthCullingState.depthMask = depthMask; + this._stencilState.stencilTest = stencilTest; + this._flagContextRestored(); + }, 0); + } + /** Gets a boolean indicating if the engine was disposed */ + get isDisposed() { + return this._isDisposed; + } + /** + * Enables or disables the snapshot rendering mode + * Note that the WebGL engine does not support snapshot rendering so setting the value won't have any effect for this engine + */ + get snapshotRendering() { + return false; + } + set snapshotRendering(activate) { + // Do nothing + } + /** + * Gets or sets the snapshot rendering mode + */ + get snapshotRenderingMode() { + return 0; + } + set snapshotRenderingMode(mode) { } + /** + * Returns the string "AbstractEngine" + * @returns "AbstractEngine" + */ + getClassName() { + return "AbstractEngine"; + } + /** + * Gets the default empty texture + */ + get emptyTexture() { + if (!this._emptyTexture) { + this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, 5, false, false, 1); + } + return this._emptyTexture; + } + /** + * Gets the default empty 3D texture + */ + get emptyTexture3D() { + if (!this._emptyTexture3D) { + this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, 5, false, false, 1); + } + return this._emptyTexture3D; + } + /** + * Gets the default empty 2D array texture + */ + get emptyTexture2DArray() { + if (!this._emptyTexture2DArray) { + this._emptyTexture2DArray = this.createRawTexture2DArray(new Uint8Array(4), 1, 1, 1, 5, false, false, 1); + } + return this._emptyTexture2DArray; + } + /** + * Gets the default empty cube texture + */ + get emptyCubeTexture() { + if (!this._emptyCubeTexture) { + const faceData = new Uint8Array(4); + const cubeData = [faceData, faceData, faceData, faceData, faceData, faceData]; + this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, 5, 0, false, false, 1); + } + return this._emptyCubeTexture; + } + /** + * Gets the list of current active render loop functions + * @returns a read only array with the current render loop functions + */ + get activeRenderLoops() { + return this._activeRenderLoops; + } + /** + * stop executing a render loop function and remove it from the execution array + * @param renderFunction defines the function to be removed. If not provided all functions will be removed. + */ + stopRenderLoop(renderFunction) { + if (!renderFunction) { + this._activeRenderLoops.length = 0; + this._cancelFrame(); + return; + } + const index = this._activeRenderLoops.indexOf(renderFunction); + if (index >= 0) { + this._activeRenderLoops.splice(index, 1); + if (this._activeRenderLoops.length == 0) { + this._cancelFrame(); + } + } + } + _cancelFrame() { + if (this._frameHandler !== 0) { + const handlerToCancel = this._frameHandler; + this._frameHandler = 0; + if (!IsWindowObjectExist()) { + if (typeof cancelAnimationFrame === "function") { + return cancelAnimationFrame(handlerToCancel); + } + } + else { + const { cancelAnimationFrame } = this.getHostWindow() || window; + if (typeof cancelAnimationFrame === "function") { + return cancelAnimationFrame(handlerToCancel); + } + } + return clearTimeout(handlerToCancel); + } + } + /** + * Begin a new frame + */ + beginFrame() { + this.onBeginFrameObservable.notifyObservers(this); + } + /** + * End the current frame + */ + endFrame() { + this._frameId++; + this.onEndFrameObservable.notifyObservers(this); + } + /** Gets or sets max frame per second allowed. Will return undefined if not capped */ + get maxFPS() { + return this._maxFPS; + } + set maxFPS(value) { + this._maxFPS = value; + if (value === undefined) { + return; + } + if (value <= 0) { + this._minFrameTime = Number.MAX_VALUE; + return; + } + this._minFrameTime = 1000 / (value + 1); // We need to provide a bit of leeway to ensure we don't go under because of vbl sync + } + _isOverFrameTime(timestamp) { + if (!timestamp) { + return false; + } + const elapsedTime = timestamp - this._lastFrameTime; + if (this._maxFPS === undefined || elapsedTime >= this._minFrameTime) { + this._lastFrameTime = timestamp; + return false; + } + return true; + } + _processFrame(timestamp) { + this._frameHandler = 0; + if (!this._contextWasLost && !this._isOverFrameTime(timestamp)) { + let shouldRender = true; + if (this.isDisposed || (!this.renderEvenInBackground && this._windowIsBackground)) { + shouldRender = false; + } + if (shouldRender) { + // Start new frame + this.beginFrame(); + // Child canvases + if (!this.skipFrameRender && !this._renderViews()) { + // Main frame + this._renderFrame(); + } + // Present + this.endFrame(); + } + } + } + /** @internal */ + _renderLoop(timestamp) { + this._processFrame(timestamp); + // The first condition prevents queuing another frame if we no longer have active render loops (e.g., if + // `stopRenderLoop` is called mid frame). The second condition prevents queuing another frame if one has + // already been queued (e.g., if `stopRenderLoop` and `runRenderLoop` is called mid frame). + if (this._activeRenderLoops.length > 0 && this._frameHandler === 0) { + this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()); + } + } + /** @internal */ + _renderFrame() { + for (let index = 0; index < this._activeRenderLoops.length; index++) { + const renderFunction = this._activeRenderLoops[index]; + renderFunction(); + } + } + /** @internal */ + _renderViews() { + return false; + } + /** + * Can be used to override the current requestAnimationFrame requester. + * @internal + */ + _queueNewFrame(bindedRenderFunction, requester) { + return QueueNewFrame(bindedRenderFunction, requester); + } + /** + * Register and execute a render loop. The engine can have more than one render function + * @param renderFunction defines the function to continuously execute + */ + runRenderLoop(renderFunction) { + if (this._activeRenderLoops.indexOf(renderFunction) !== -1) { + return; + } + this._activeRenderLoops.push(renderFunction); + // On the first added function, start the render loop. + if (this._activeRenderLoops.length === 1 && this._frameHandler === 0) { + this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()); + } + } + /** + * Gets a boolean indicating if depth testing is enabled + * @returns the current state + */ + getDepthBuffer() { + return this._depthCullingState.depthTest; + } + /** + * Enable or disable depth buffering + * @param enable defines the state to set + */ + setDepthBuffer(enable) { + this._depthCullingState.depthTest = enable; + } + /** + * Set the z offset Factor to apply to current rendering + * @param value defines the offset to apply + */ + setZOffset(value) { + this._depthCullingState.zOffset = this.useReverseDepthBuffer ? -value : value; + } + /** + * Gets the current value of the zOffset Factor + * @returns the current zOffset Factor state + */ + getZOffset() { + const zOffset = this._depthCullingState.zOffset; + return this.useReverseDepthBuffer ? -zOffset : zOffset; + } + /** + * Set the z offset Units to apply to current rendering + * @param value defines the offset to apply + */ + setZOffsetUnits(value) { + this._depthCullingState.zOffsetUnits = this.useReverseDepthBuffer ? -value : value; + } + /** + * Gets the current value of the zOffset Units + * @returns the current zOffset Units state + */ + getZOffsetUnits() { + const zOffsetUnits = this._depthCullingState.zOffsetUnits; + return this.useReverseDepthBuffer ? -zOffsetUnits : zOffsetUnits; + } + /** + * Gets host window + * @returns the host window object + */ + getHostWindow() { + if (!IsWindowObjectExist()) { + return null; + } + if (this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView) { + return this._renderingCanvas.ownerDocument.defaultView; + } + return window; + } + /** + * (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL). + * Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken. + * See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details + */ + get compatibilityMode() { + return this._compatibilityMode; + } + set compatibilityMode(mode) { + // not supported in WebGL + this._compatibilityMode = true; + } + _rebuildTextures() { + for (const scene of this.scenes) { + scene._rebuildTextures(); + } + for (const scene of this._virtualScenes) { + scene._rebuildTextures(); + } + } + /** + * @internal + */ + _releaseRenderTargetWrapper(rtWrapper) { + const index = this._renderTargetWrapperCache.indexOf(rtWrapper); + if (index !== -1) { + this._renderTargetWrapperCache.splice(index, 1); + } + } + /** + * Gets the current viewport + */ + get currentViewport() { + return this._cachedViewport; + } + /** + * Set the WebGL's viewport + * @param viewport defines the viewport element to be used + * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used + * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used + */ + setViewport(viewport, requiredWidth, requiredHeight) { + const width = requiredWidth || this.getRenderWidth(); + const height = requiredHeight || this.getRenderHeight(); + const x = viewport.x || 0; + const y = viewport.y || 0; + this._cachedViewport = viewport; + this._viewport(x * width, y * height, width * viewport.width, height * viewport.height); + } + /** + * Create an image to use with canvas + * @returns IImage interface + */ + createCanvasImage() { + return document.createElement("img"); + } + /** + * Create a 2D path to use with canvas + * @returns IPath2D interface + * @param d SVG path string + */ + createCanvasPath2D(d) { + return new Path2D(d); + } + /** + * Returns a string describing the current engine + */ + get description() { + let description = this.name + this.version; + if (this._caps.parallelShaderCompile) { + description += " - Parallel shader compilation"; + } + return description; + } + _createTextureBase(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, prepareTexture, prepareTextureProcess, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, useSRGBBuffer) { + url = url || ""; + const fromData = url.substr(0, 5) === "data:"; + const fromBlob = url.substr(0, 5) === "blob:"; + const isBase64 = fromData && url.indexOf(";base64,") !== -1; + const texture = fallback ? fallback : new InternalTexture(this, 1 /* InternalTextureSource.Url */); + if (texture !== fallback) { + texture.label = url.substring(0, 60); // default label, can be overriden by the caller + } + const originalUrl = url; + if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) { + url = this._transformTextureUrl(url); + } + if (originalUrl !== url) { + texture._originalUrl = originalUrl; + } + // establish the file extension, if possible + const lastDot = url.lastIndexOf("."); + let extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : ""; + // Remove query string + const queryStringIndex = extension.indexOf("?"); + if (queryStringIndex > -1) { + extension = extension.split("?")[0]; + } + const loaderPromise = _GetCompatibleTextureLoader(extension, mimeType); + if (scene) { + scene.addPendingData(texture); + } + texture.url = url; + texture.generateMipMaps = !noMipmap; + texture.samplingMode = samplingMode; + texture.invertY = invertY; + texture._useSRGBBuffer = this._getUseSRGBBuffer(!!useSRGBBuffer, noMipmap); + if (!this._doNotHandleContextLost) { + // Keep a link to the buffer only if we plan to handle context lost + texture._buffer = buffer; + } + let onLoadObserver = null; + if (onLoad && !fallback) { + onLoadObserver = texture.onLoadedObservable.add(onLoad); + } + if (!fallback) { + this._internalTexturesCache.push(texture); + } + const onInternalError = (message, exception) => { + if (scene) { + scene.removePendingData(texture); + } + if (url === originalUrl) { + if (onLoadObserver) { + texture.onLoadedObservable.remove(onLoadObserver); + } + if (EngineStore.UseFallbackTexture && url !== EngineStore.FallbackTexture) { + this._createTextureBase(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, prepareTexture, prepareTextureProcess, buffer, texture); + } + message = (message || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""); + texture.onErrorObservable.notifyObservers({ message, exception }); + if (onError) { + onError(message, exception); + } + } + else { + // fall back to the original url if the transformed url fails to load + Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`); + this._createTextureBase(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, prepareTexture, prepareTextureProcess, buffer, texture, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer); + } + }; + // processing for non-image formats + if (loaderPromise) { + const callback = async (data) => { + const loader = await loaderPromise; + loader.loadData(data, texture, (width, height, loadMipmap, isCompressed, done, loadFailed) => { + if (loadFailed) { + onInternalError("TextureLoader failed to load data"); + } + else { + prepareTexture(texture, extension, scene, { width, height }, texture.invertY, !loadMipmap, isCompressed, () => { + done(); + return false; + }, samplingMode); + } + }, loaderOptions); + }; + if (!buffer) { + this._loadFile(url, (data) => callback(new Uint8Array(data)), undefined, scene ? scene.offlineProvider : undefined, true, (request, exception) => { + onInternalError("Unable to load " + (request ? request.responseURL : url, exception)); + }); + } + else { + if (buffer instanceof ArrayBuffer) { + callback(new Uint8Array(buffer)); + } + else if (ArrayBuffer.isView(buffer)) { + callback(buffer); + } + else { + if (onError) { + onError("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null); + } + } + } + } + else { + const onload = (img) => { + if (fromBlob && !this._doNotHandleContextLost) { + // We need to store the image if we need to rebuild the texture + // in case of a webgl context lost + texture._buffer = img; + } + prepareTexture(texture, extension, scene, img, texture.invertY, noMipmap, false, prepareTextureProcess, samplingMode); + }; + // According to the WebGL spec section 6.10, ImageBitmaps must be inverted on creation. + // So, we pass imageOrientation to _FileToolsLoadImage() as it may create an ImageBitmap. + if (!fromData || isBase64) { + if (buffer && (typeof buffer.decoding === "string" || buffer.close)) { + onload(buffer); + } + else { + AbstractEngine._FileToolsLoadImage(url || "", onload, onInternalError, scene ? scene.offlineProvider : null, mimeType, texture.invertY && this._features.needsInvertingBitmap ? { imageOrientation: "flipY" } : undefined, this); + } + } + else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer) || buffer instanceof Blob) { + AbstractEngine._FileToolsLoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType, texture.invertY && this._features.needsInvertingBitmap ? { imageOrientation: "flipY" } : undefined, this); + } + else if (buffer) { + onload(buffer); + } + } + return texture; + } + _rebuildBuffers() { + // Uniforms + for (const uniformBuffer of this._uniformBuffers) { + uniformBuffer._rebuildAfterContextLost(); + } + } + /** @internal */ + get _shouldUseHighPrecisionShader() { + return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed); + } + /** + * Gets host document + * @returns the host document object + */ + getHostDocument() { + if (this._renderingCanvas && this._renderingCanvas.ownerDocument) { + return this._renderingCanvas.ownerDocument; + } + return IsDocumentAvailable() ? document : null; + } + /** + * Gets the list of loaded textures + * @returns an array containing all loaded textures + */ + getLoadedTexturesCache() { + return this._internalTexturesCache; + } + /** + * Clears the list of texture accessible through engine. + * This can help preventing texture load conflict due to name collision. + */ + clearInternalTexturesCache() { + this._internalTexturesCache.length = 0; + } + /** + * Gets the object containing all engine capabilities + * @returns the EngineCapabilities object + */ + getCaps() { + return this._caps; + } + /** + * Reset the texture cache to empty state + */ + resetTextureCache() { + for (const key in this._boundTexturesCache) { + if (!Object.prototype.hasOwnProperty.call(this._boundTexturesCache, key)) { + continue; + } + this._boundTexturesCache[key] = null; + } + this._currentTextureChannel = -1; + } + /** + * Gets or sets the name of the engine + */ + get name() { + return this._name; + } + set name(value) { + this._name = value; + } + /** + * Returns the current npm package of the sdk + */ + // Not mixed with Version for tooling purpose. + static get NpmPackage() { + return "babylonjs@7.54.3"; + } + /** + * Returns the current version of the framework + */ + static get Version() { + return "7.54.3"; + } + /** + * Gets the HTML canvas attached with the current webGL context + * @returns a HTML canvas + */ + getRenderingCanvas() { + return this._renderingCanvas; + } + /** + * Gets the audio context specified in engine initialization options + * @deprecated please use AudioEngineV2 instead + * @returns an Audio Context + */ + getAudioContext() { + return this._audioContext; + } + /** + * Gets the audio destination specified in engine initialization options + * @deprecated please use AudioEngineV2 instead + * @returns an audio destination node + */ + getAudioDestination() { + return this._audioDestination; + } + /** + * Defines the hardware scaling level. + * By default the hardware scaling level is computed from the window device ratio. + * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas. + * @param level defines the level to use + */ + setHardwareScalingLevel(level) { + this._hardwareScalingLevel = level; + this.resize(); + } + /** + * Gets the current hardware scaling level. + * By default the hardware scaling level is computed from the window device ratio. + * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas. + * @returns a number indicating the current hardware scaling level + */ + getHardwareScalingLevel() { + return this._hardwareScalingLevel; + } + /** + * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#handling-webgl-context-lost + */ + get doNotHandleContextLost() { + return this._doNotHandleContextLost; + } + set doNotHandleContextLost(value) { + this._doNotHandleContextLost = value; + } + /** + * Returns true if the stencil buffer has been enabled through the creation option of the context. + */ + get isStencilEnable() { + return this._isStencilEnable; + } + /** + * Gets the options used for engine creation + * @returns EngineOptions object + */ + getCreationOptions() { + return this._creationOptions; + } + /** + * Creates a new engine + * @param antialias defines whether anti-aliasing should be enabled. If undefined, it means that the underlying engine is free to enable it or not + * @param options defines further options to be sent to the creation context + * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false) + */ + constructor(antialias, options, adaptToDeviceRatio) { + // States + /** @internal */ + this._colorWrite = true; + /** @internal */ + this._colorWriteChanged = true; + /** @internal */ + this._depthCullingState = new DepthCullingState(); + /** @internal */ + this._stencilStateComposer = new StencilStateComposer(); + /** @internal */ + this._stencilState = new StencilState(); + /** @internal */ + this._alphaState = new AlphaState(); + /** @internal */ + this._alphaMode = 1; + /** @internal */ + this._alphaEquation = 0; + this._activeRequests = []; + /** @internal */ + this._badOS = false; + /** @internal */ + this._badDesktopOS = false; + this._compatibilityMode = true; + /** @internal */ + this._internalTexturesCache = new Array(); + /** @internal */ + this._currentRenderTarget = null; + /** @internal */ + this._boundTexturesCache = {}; + /** @internal */ + this._activeChannel = 0; + /** @internal */ + this._currentTextureChannel = -1; + /** @internal */ + this._viewportCached = { x: 0, y: 0, z: 0, w: 0 }; + /** @internal */ + this._isWebGPU = false; + /** + * Observable event triggered each time the canvas loses focus + */ + this.onCanvasBlurObservable = new Observable(); + /** + * Observable event triggered each time the canvas gains focus + */ + this.onCanvasFocusObservable = new Observable(); + /** + * Event raised when a new scene is created + */ + this.onNewSceneAddedObservable = new Observable(); + /** + * Observable event triggered each time the rendering canvas is resized + */ + this.onResizeObservable = new Observable(); + /** + * Observable event triggered each time the canvas receives pointerout event + */ + this.onCanvasPointerOutObservable = new Observable(); + /** + * Observable event triggered each time an effect compilation fails + */ + this.onEffectErrorObservable = new Observable(); + /** + * Turn this value on if you want to pause FPS computation when in background + */ + this.disablePerformanceMonitorInBackground = false; + /** + * Gets or sets a boolean indicating that vertex array object must be disabled even if they are supported + */ + this.disableVertexArrayObjects = false; + /** @internal */ + this._frameId = 0; + /** + * Gets information about the current host + */ + this.hostInformation = { + isMobile: false, + }; + /** + * Gets a boolean indicating if the engine is currently rendering in fullscreen mode + */ + this.isFullscreen = false; + /** + * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest + **/ + this.enableOfflineSupport = false; + /** + * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (js will always consider the database is up to date) + **/ + this.disableManifestCheck = false; + /** + * Gets or sets a boolean to enable/disable the context menu (right-click) from appearing on the main canvas + */ + this.disableContextMenu = true; + /** + * Gets or sets the current render pass id + */ + this.currentRenderPassId = 0; + /** + * Gets a boolean indicating if the pointer is currently locked + */ + this.isPointerLock = false; + /** + * Gets the list of created postprocesses + */ + this.postProcesses = []; + /** Gets or sets the tab index to set to the rendering canvas. 1 is the minimum value to set to be able to capture keyboard events */ + this.canvasTabIndex = 1; + /** @internal */ + this._contextWasLost = false; + this._useReverseDepthBuffer = false; + /** + * Indicates if the z range in NDC space is 0..1 (value: true) or -1..1 (value: false) + */ + this.isNDCHalfZRange = false; + /** + * Indicates that the origin of the texture/framebuffer space is the bottom left corner. If false, the origin is top left + */ + this.hasOriginBottomLeft = true; + /** @internal */ + this._renderTargetWrapperCache = new Array(); + /** @internal */ + this._compiledEffects = {}; + /** @internal */ + this._isDisposed = false; + /** + * Gets the list of created scenes + */ + this.scenes = []; + /** @internal */ + this._virtualScenes = new Array(); + /** + * Observable event triggered before each texture is initialized + */ + this.onBeforeTextureInitObservable = new Observable(); + /** + * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foreground + */ + this.renderEvenInBackground = true; + /** + * Gets or sets a boolean indicating that cache can be kept between frames + */ + this.preventCacheWipeBetweenFrames = false; + /** @internal */ + this._frameHandler = 0; + /** @internal */ + this._activeRenderLoops = new Array(); + /** @internal */ + this._windowIsBackground = false; + /** @internal */ + this._boundRenderFunction = (timestamp) => this._renderLoop(timestamp); + this._lastFrameTime = 0; + /** + * Skip frame rendering but keep the frame heartbeat (begin/end frame). + * This is useful if you need all the plumbing but not the rendering work. + * (for instance when capturing a screenshot where you do not want to mix rendering to the screen and to the screenshot) + */ + this.skipFrameRender = false; + /** + * Observable raised when the engine is about to compile a shader + */ + this.onBeforeShaderCompilationObservable = new Observable(); + /** + * Observable raised when the engine has just compiled a shader + */ + this.onAfterShaderCompilationObservable = new Observable(); + /** + * Observable raised when the engine begins a new frame + */ + this.onBeginFrameObservable = new Observable(); + /** + * Observable raised when the engine ends the current frame + */ + this.onEndFrameObservable = new Observable(); + /** @internal */ + this._transformTextureUrl = null; + /** @internal */ + this._uniformBuffers = new Array(); + /** @internal */ + this._storageBuffers = new Array(); + this._highPrecisionShadersAllowed = true; + // Lost context + /** + * Observable signaled when a context lost event is raised + */ + this.onContextLostObservable = new Observable(); + /** + * Observable signaled when a context restored event is raised + */ + this.onContextRestoredObservable = new Observable(); + /** @internal */ + this._name = ""; + /** + * Defines whether the engine has been created with the premultipliedAlpha option on or not. + */ + this.premultipliedAlpha = true; + /** + * If set to true zooming in and out in the browser will rescale the hardware-scaling correctly. + */ + this.adaptToDeviceRatio = false; + /** @internal */ + this._lastDevicePixelRatio = 1.0; + /** @internal */ + this._doNotHandleContextLost = false; + /** + * Gets or sets a boolean indicating if back faces must be culled. If false, front faces are culled instead (true by default) + * If non null, this takes precedence over the value from the material + */ + this.cullBackFaces = null; + /** @internal */ + this._renderPassNames = ["main"]; + // FPS + this._fps = 60; + this._deltaTime = 0; + // Deterministic lockstepMaxSteps + /** @internal */ + this._deterministicLockstep = false; + /** @internal */ + this._lockstepMaxSteps = 4; + /** @internal */ + this._timeStep = 1 / 60; + /** + * An event triggered when the engine is disposed. + */ + this.onDisposeObservable = new Observable(); + /** + * An event triggered when a global cleanup of all effects is required + */ + this.onReleaseEffectsObservable = new Observable(); + EngineStore.Instances.push(this); + this.startTime = PrecisionDate.Now; + this._stencilStateComposer.stencilGlobal = this._stencilState; + PerformanceConfigurator.SetMatrixPrecision(!!options.useHighPrecisionMatrix); + if (IsNavigatorAvailable() && navigator.userAgent) { + // Detect if we are running on a faulty buggy OS. + this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent); + // Detect if we are running on a faulty buggy desktop OS. + this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + } + // Save this off for use in resize(). + this.adaptToDeviceRatio = adaptToDeviceRatio ?? false; + options.antialias = antialias ?? options.antialias; + options.deterministicLockstep = options.deterministicLockstep ?? false; + options.lockstepMaxSteps = options.lockstepMaxSteps ?? 4; + options.timeStep = options.timeStep ?? 1 / 60; + options.stencil = options.stencil ?? true; + this._audioContext = options.audioEngineOptions?.audioContext ?? null; + this._audioDestination = options.audioEngineOptions?.audioDestination ?? null; + this.premultipliedAlpha = options.premultipliedAlpha ?? true; + this._doNotHandleContextLost = !!options.doNotHandleContextLost; + this._isStencilEnable = options.stencil ? true : false; + this.useExactSrgbConversions = options.useExactSrgbConversions ?? false; + const devicePixelRatio = IsWindowObjectExist() ? window.devicePixelRatio || 1.0 : 1.0; + const limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio; + // Viewport + adaptToDeviceRatio = adaptToDeviceRatio || options.adaptToDeviceRatio || false; + this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0; + this._lastDevicePixelRatio = devicePixelRatio; + this._creationOptions = options; + } + /** + * Resize the view according to the canvas' size + * @param forceSetSize true to force setting the sizes of the underlying canvas + */ + resize(forceSetSize = false) { + let width; + let height; + // Re-query hardware scaling level to handle zoomed-in resizing. + if (this.adaptToDeviceRatio) { + const devicePixelRatio = IsWindowObjectExist() ? window.devicePixelRatio || 1.0 : 1.0; + const changeRatio = this._lastDevicePixelRatio / devicePixelRatio; + this._lastDevicePixelRatio = devicePixelRatio; + this._hardwareScalingLevel *= changeRatio; + } + if (IsWindowObjectExist() && IsDocumentAvailable()) { + // make sure it is a Node object, and is a part of the document. + if (this._renderingCanvas) { + const boundingRect = this._renderingCanvas.getBoundingClientRect?.(); + width = this._renderingCanvas.clientWidth || boundingRect?.width || this._renderingCanvas.width * this._hardwareScalingLevel || 100; + height = this._renderingCanvas.clientHeight || boundingRect?.height || this._renderingCanvas.height * this._hardwareScalingLevel || 100; + } + else { + width = window.innerWidth; + height = window.innerHeight; + } + } + else { + width = this._renderingCanvas ? this._renderingCanvas.width : 100; + height = this._renderingCanvas ? this._renderingCanvas.height : 100; + } + this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel, forceSetSize); + } + /** + * Force a specific size of the canvas + * @param width defines the new canvas' width + * @param height defines the new canvas' height + * @param forceSetSize true to force setting the sizes of the underlying canvas + * @returns true if the size was changed + */ + setSize(width, height, forceSetSize = false) { + if (!this._renderingCanvas) { + return false; + } + width = width | 0; + height = height | 0; + if (!forceSetSize && this._renderingCanvas.width === width && this._renderingCanvas.height === height) { + return false; + } + this._renderingCanvas.width = width; + this._renderingCanvas.height = height; + if (this.scenes) { + for (let index = 0; index < this.scenes.length; index++) { + const scene = this.scenes[index]; + for (let camIndex = 0; camIndex < scene.cameras.length; camIndex++) { + const cam = scene.cameras[camIndex]; + cam._currentRenderId = 0; + } + } + if (this.onResizeObservable.hasObservers()) { + this.onResizeObservable.notifyObservers(this); + } + } + return true; + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Creates a raw texture + * @param data defines the data to store in the texture + * @param width defines the width of the texture + * @param height defines the height of the texture + * @param format defines the format of the data + * @param generateMipMaps defines if the engine should generate the mip levels + * @param invertY defines if data must be stored with Y axis inverted + * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default) + * @param compression defines the compression used (null by default) + * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_BYTE by default) + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). + * @returns the raw texture inside an InternalTexture + */ + createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type, creationFlags, useSRGBBuffer) { + throw _WarnImport("engine.rawTexture"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Creates a new raw cube texture + * @param data defines the array of data to use to create each face + * @param size defines the size of the textures + * @param format defines the format of the data + * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_BYTE) + * @param generateMipMaps defines if the engine should generate the mip levels + * @param invertY defines if data must be stored with Y axis inverted + * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) + * @param compression defines the compression used (null by default) + * @returns the cube texture as an InternalTexture + */ + createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression) { + throw _WarnImport("engine.rawTexture"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Creates a new raw 3D texture + * @param data defines the data used to create the texture + * @param width defines the width of the texture + * @param height defines the height of the texture + * @param depth defines the depth of the texture + * @param format defines the format of the texture + * @param generateMipMaps defines if the engine must generate mip levels + * @param invertY defines if data must be stored with Y axis inverted + * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) + * @param compression defines the compressed used (can be null) + * @param textureType defines the compressed used (can be null) + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @returns a new raw 3D texture (stored in an InternalTexture) + */ + createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType, creationFlags) { + throw _WarnImport("engine.rawTexture"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Creates a new raw 2D array texture + * @param data defines the data used to create the texture + * @param width defines the width of the texture + * @param height defines the height of the texture + * @param depth defines the number of layers of the texture + * @param format defines the format of the texture + * @param generateMipMaps defines if the engine must generate mip levels + * @param invertY defines if data must be stored with Y axis inverted + * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) + * @param compression defines the compressed used (can be null) + * @param textureType defines the compressed used (can be null) + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @returns a new raw 2D array texture (stored in an InternalTexture) + */ + createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType, creationFlags) { + throw _WarnImport("engine.rawTexture"); + } + /** + * Shared initialization across engines types. + * @param canvas The canvas associated with this instance of the engine. + */ + _sharedInit(canvas) { + this._renderingCanvas = canvas; + } + _setupMobileChecks() { + if (!(navigator && navigator.userAgent)) { + return; + } + // Function to check if running on mobile device + this._checkForMobile = () => { + const currentUA = navigator.userAgent; + this.hostInformation.isMobile = + currentUA.indexOf("Mobile") !== -1 || + // Needed for iOS 13+ detection on iPad (inspired by solution from https://stackoverflow.com/questions/9038625/detect-if-device-is-ios) + (currentUA.indexOf("Mac") !== -1 && IsDocumentAvailable() && "ontouchend" in document); + }; + // Set initial isMobile value + this._checkForMobile(); + // Set up event listener to check when window is resized (used to get emulator activation to work properly) + if (IsWindowObjectExist()) { + window.addEventListener("resize", this._checkForMobile); + } + } + /** + * creates and returns a new video element + * @param constraints video constraints + * @returns video element + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + createVideoElement(constraints) { + return document.createElement("video"); + } + /** + * @internal + */ + _reportDrawCall(numDrawCalls = 1) { + this._drawCalls?.addCount(numDrawCalls, false); + } + /** + * Gets the current framerate + * @returns a number representing the framerate + */ + getFps() { + return this._fps; + } + /** + * Gets the time spent between current and previous frame + * @returns a number representing the delta time in ms + */ + getDeltaTime() { + return this._deltaTime; + } + /** + * Gets a boolean indicating that the engine is running in deterministic lock step mode + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep + * @returns true if engine is in deterministic lock step mode + */ + isDeterministicLockStep() { + return this._deterministicLockstep; + } + /** + * Gets the max steps when engine is running in deterministic lock step + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep + * @returns the max steps + */ + getLockstepMaxSteps() { + return this._lockstepMaxSteps; + } + /** + * Returns the time in ms between steps when using deterministic lock step. + * @returns time step in (ms) + */ + getTimeStep() { + return this._timeStep * 1000; + } + /** + * Engine abstraction for loading and creating an image bitmap from a given source string. + * @param imageSource source to load the image from. + * @param options An object that sets options for the image's extraction. + */ + _createImageBitmapFromSource(imageSource, options) { + throw new Error("createImageBitmapFromSource is not implemented"); + } + /** + * Engine abstraction for createImageBitmap + * @param image source for image + * @param options An object that sets options for the image's extraction. + * @returns ImageBitmap + */ + createImageBitmap(image, options) { + return createImageBitmap(image, options); + } + /** + * Resize an image and returns the image data as an uint8array + * @param image image to resize + * @param bufferWidth destination buffer width + * @param bufferHeight destination buffer height + */ + resizeImageBitmap(image, bufferWidth, bufferHeight) { + throw new Error("resizeImageBitmap is not implemented"); + } + /** + * Get Font size information + * @param font font name + */ + getFontOffset(font) { + throw new Error("getFontOffset is not implemented"); + } + static _CreateCanvas(width, height) { + if (typeof document === "undefined") { + return new OffscreenCanvas(width, height); + } + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas; + } + /** + * Create a canvas. This method is overridden by other engines + * @param width width + * @param height height + * @returns ICanvas interface + */ + createCanvas(width, height) { + return AbstractEngine._CreateCanvas(width, height); + } + /** + * Loads an image as an HTMLImageElement. + * @param input url string, ArrayBuffer, or Blob to load + * @param onLoad callback called when the image successfully loads + * @param onError callback called when the image fails to load + * @param offlineProvider offline provider for caching + * @param mimeType optional mime type + * @param imageBitmapOptions optional the options to use when creating an ImageBitmap + * @param engine the engine instance to use + * @returns the HTMLImageElement of the loaded image + * @internal + */ + static _FileToolsLoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions, engine) { + throw _WarnImport("FileTools"); + } + /** + * @internal + */ + _loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { + const request = _loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); + this._activeRequests.push(request); + request.onCompleteObservable.add(() => { + const index = this._activeRequests.indexOf(request); + if (index !== -1) { + this._activeRequests.splice(index, 1); + } + }); + return request; + } + /** + * Loads a file from a url + * @param url url to load + * @param onSuccess callback called when the file successfully loads + * @param onProgress callback called while file is loading (if the server supports this mode) + * @param offlineProvider defines the offline provider for caching + * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer + * @param onError callback called when the file fails to load + * @returns a file request object + * @internal + */ + static _FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { + if (EngineFunctionContext.loadFile) { + return EngineFunctionContext.loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); + } + throw _WarnImport("FileTools"); + } + /** + * Dispose and release all associated resources + */ + dispose() { + this.releaseEffects(); + this._isDisposed = true; + this.stopRenderLoop(); + // Empty texture + if (this._emptyTexture) { + this._releaseTexture(this._emptyTexture); + this._emptyTexture = null; + } + if (this._emptyCubeTexture) { + this._releaseTexture(this._emptyCubeTexture); + this._emptyCubeTexture = null; + } + this._renderingCanvas = null; + // Clear observables + if (this.onBeforeTextureInitObservable) { + this.onBeforeTextureInitObservable.clear(); + } + // Release postProcesses + while (this.postProcesses.length) { + this.postProcesses[0].dispose(); + } + // Release scenes + while (this.scenes.length) { + this.scenes[0].dispose(); + } + while (this._virtualScenes.length) { + this._virtualScenes[0].dispose(); + } + // Release effects + this.releaseComputeEffects?.(); + Effect.ResetCache(); + // Abort active requests + for (const request of this._activeRequests) { + request.abort(); + } + this._boundRenderFunction = null; + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + this.onResizeObservable.clear(); + this.onCanvasBlurObservable.clear(); + this.onCanvasFocusObservable.clear(); + this.onCanvasPointerOutObservable.clear(); + this.onNewSceneAddedObservable.clear(); + this.onEffectErrorObservable.clear(); + if (IsWindowObjectExist()) { + window.removeEventListener("resize", this._checkForMobile); + } + // Remove from Instances + const index = EngineStore.Instances.indexOf(this); + if (index >= 0) { + EngineStore.Instances.splice(index, 1); + } + // no more engines left in the engine store? Notify! + if (!EngineStore.Instances.length) { + EngineStore.OnEnginesDisposedObservable.notifyObservers(this); + EngineStore.OnEnginesDisposedObservable.clear(); + } + // Observables + this.onBeginFrameObservable.clear(); + this.onEndFrameObservable.clear(); + } + /** + * Method called to create the default loading screen. + * This can be overridden in your own app. + * @param canvas The rendering canvas element + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static DefaultLoadingScreenFactory(canvas) { + throw _WarnImport("LoadingScreen"); + } + /** + * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation + * @param flag defines which part of the materials must be marked as dirty + * @param predicate defines a predicate used to filter which materials should be affected + */ + static MarkAllMaterialsAsDirty(flag, predicate) { + for (let engineIndex = 0; engineIndex < EngineStore.Instances.length; engineIndex++) { + const engine = EngineStore.Instances[engineIndex]; + for (let sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) { + engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate); + } + } + } +} +// eslint-disable-next-line @typescript-eslint/naming-convention +/** @internal */ +AbstractEngine._RenderPassIdCounter = 0; +/** + * Method called to create the default rescale post process on each engine. + */ +AbstractEngine._RescalePostProcessFactory = null; +// Updatable statics so stick with vars here +/** + * Gets or sets the epsilon value used by collision engine + */ +AbstractEngine.CollisionsEpsilon = 0.001; +/** + * Queue a new function into the requested animation frame pool (ie. this function will be executed by the browser (or the javascript engine) for the next frame) + * @param func - the function to be called + * @param requester - the object that will request the next frame. Falls back to window. + * @returns frame number + */ +AbstractEngine.QueueNewFrame = QueueNewFrame; + +/** @internal */ +class WebGLHardwareTexture { + get underlyingResource() { + return this._webGLTexture; + } + constructor(existingTexture = null, context) { + // There can be multiple buffers for a single WebGL texture because different layers of a 2DArrayTexture / 3DTexture + // or different faces of a cube texture can be bound to different render targets at the same time. + // eslint-disable-next-line @typescript-eslint/naming-convention + this._MSAARenderBuffers = null; + this._context = context; + if (!existingTexture) { + existingTexture = context.createTexture(); + if (!existingTexture) { + throw new Error("Unable to create webGL texture"); + } + } + this.set(existingTexture); + } + setUsage() { } + set(hardwareTexture) { + this._webGLTexture = hardwareTexture; + } + reset() { + this._webGLTexture = null; + this._MSAARenderBuffers = null; + } + addMSAARenderBuffer(buffer) { + if (!this._MSAARenderBuffers) { + this._MSAARenderBuffers = []; + } + this._MSAARenderBuffers.push(buffer); + } + releaseMSAARenderBuffers() { + if (this._MSAARenderBuffers) { + for (const buffer of this._MSAARenderBuffers) { + this._context.deleteRenderbuffer(buffer); + } + this._MSAARenderBuffers = null; + } + } + getMSAARenderBuffer(index = 0) { + return this._MSAARenderBuffers?.[index] ?? null; + } + release() { + this.releaseMSAARenderBuffers(); + if (this._webGLTexture) { + this._context.deleteTexture(this._webGLTexture); + } + this.reset(); + } +} + +/** + * Checks if a given format is a depth texture format + * @param format Format to check + * @returns True if the format is a depth texture format + */ +function IsDepthTexture(format) { + return (format === 13 || + format === 14 || + format === 15 || + format === 16 || + format === 17 || + format === 18 || + format === 19); +} +/** + * Gets the type of a depth texture for a given format + * @param format Format of the texture + * @returns The type of the depth texture + */ +function GetTypeForDepthTexture(format) { + switch (format) { + case 13: + case 17: + case 18: + case 14: + case 16: + return 1; + case 15: + return 5; + case 19: + return 0; + } + return 0; +} +/** + * Checks if a given format has a stencil aspect + * @param format Format to check + * @returns True if the format has a stencil aspect + */ +function HasStencilAspect(format) { + return (format === 13 || + format === 17 || + format === 18 || + format === 19); +} + +/** + * Keeps track of all the buffer info used in engine. + */ +class BufferPointer { +} +/** + * The base engine class (root of all engines) + */ +class ThinEngine extends AbstractEngine { + /** + * Gets or sets the name of the engine + */ + get name() { + return this._name; + } + set name(value) { + this._name = value; + } + /** + * Returns the version of the engine + */ + get version() { + return this._webGLVersion; + } + /** + * Gets or sets the relative url used to load shaders if using the engine in non-minified mode + */ + static get ShadersRepository() { + return Effect.ShadersRepository; + } + static set ShadersRepository(value) { + Effect.ShadersRepository = value; + } + /** + * Gets a boolean indicating that the engine supports uniform buffers + * @see https://doc.babylonjs.com/setup/support/webGL2#uniform-buffer-objets + */ + get supportsUniformBuffers() { + return this.webGLVersion > 1 && !this.disableUniformBuffers; + } + /** + * Gets a boolean indicating that only power of 2 textures are supported + * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them + */ + get needPOTTextures() { + return this._webGLVersion < 2 || this.forcePOTTextures; + } + get _supportsHardwareTextureRescaling() { + return false; + } + /** + * sets the object from which width and height will be taken from when getting render width and height + * Will fallback to the gl object + * @param dimensions the framebuffer width and height that will be used. + */ + set framebufferDimensionsObject(dimensions) { + this._framebufferDimensionsObject = dimensions; + } + /** + * Creates a new snapshot at the next frame using the current snapshotRenderingMode + */ + snapshotRenderingReset() { + this.snapshotRendering = false; + } + /** + * Creates a new engine + * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which already used the WebGL context + * @param antialias defines whether anti-aliasing should be enabled (default value is "undefined", meaning that the browser may or may not enable it) + * @param options defines further options to be sent to the getContext() function + * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false) + */ + constructor(canvasOrContext, antialias, options, adaptToDeviceRatio) { + options = options || {}; + super(antialias ?? options.antialias, options, adaptToDeviceRatio); + /** @internal */ + this._name = "WebGL"; + /** + * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required + */ + this.forcePOTTextures = false; + /** Gets or sets a boolean indicating if the engine should validate programs after compilation */ + this.validateShaderPrograms = false; + /** + * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported + */ + this.disableUniformBuffers = false; + /** @internal */ + this._webGLVersion = 1.0; + this._vertexAttribArraysEnabled = []; + this._uintIndicesCurrentlySet = false; + this._currentBoundBuffer = new Array(); + /** @internal */ + this._currentFramebuffer = null; + /** @internal */ + this._dummyFramebuffer = null; + this._currentBufferPointers = new Array(); + this._currentInstanceLocations = new Array(); + this._currentInstanceBuffers = new Array(); + this._vaoRecordInProgress = false; + this._mustWipeVertexAttributes = false; + this._nextFreeTextureSlots = new Array(); + this._maxSimultaneousTextures = 0; + this._maxMSAASamplesOverride = null; + this._unpackFlipYCached = null; + /** + * In case you are sharing the context with other applications, it might + * be interested to not cache the unpack flip y state to ensure a consistent + * value would be set. + */ + this.enableUnpackFlipYCached = true; + /** + * @internal + */ + this._boundUniforms = {}; + if (!canvasOrContext) { + return; + } + let canvas = null; + if (canvasOrContext.getContext) { + canvas = canvasOrContext; + if (options.preserveDrawingBuffer === undefined) { + options.preserveDrawingBuffer = false; + } + if (options.xrCompatible === undefined) { + options.xrCompatible = false; + } + // Exceptions + if (navigator && navigator.userAgent) { + this._setupMobileChecks(); + const ua = navigator.userAgent; + for (const exception of ThinEngine.ExceptionList) { + const key = exception.key; + const targets = exception.targets; + const check = new RegExp(key); + if (check.test(ua)) { + if (exception.capture && exception.captureConstraint) { + const capture = exception.capture; + const constraint = exception.captureConstraint; + const regex = new RegExp(capture); + const matches = regex.exec(ua); + if (matches && matches.length > 0) { + const capturedValue = parseInt(matches[matches.length - 1]); + if (capturedValue >= constraint) { + continue; + } + } + } + for (const target of targets) { + switch (target) { + case "uniformBuffer": + this.disableUniformBuffers = true; + break; + case "vao": + this.disableVertexArrayObjects = true; + break; + case "antialias": + options.antialias = false; + break; + case "maxMSAASamples": + this._maxMSAASamplesOverride = 1; + break; + } + } + } + } + } + // Context lost + if (!this._doNotHandleContextLost) { + this._onContextLost = (evt) => { + evt.preventDefault(); + this._contextWasLost = true; + deleteStateObject(this._gl); + Logger.Warn("WebGL context lost."); + this.onContextLostObservable.notifyObservers(this); + }; + this._onContextRestored = () => { + this._restoreEngineAfterContextLost(() => this._initGLContext()); + }; + canvas.addEventListener("webglcontextrestored", this._onContextRestored, false); + options.powerPreference = options.powerPreference || "high-performance"; + } + else { + this._onContextLost = () => { + deleteStateObject(this._gl); + }; + } + canvas.addEventListener("webglcontextlost", this._onContextLost, false); + if (this._badDesktopOS) { + options.xrCompatible = false; + } + // GL + if (!options.disableWebGL2Support) { + try { + this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options)); + if (this._gl) { + this._webGLVersion = 2.0; + this._shaderPlatformName = "WEBGL2"; + // Prevent weird browsers to lie (yeah that happens!) + if (!this._gl.deleteQuery) { + this._webGLVersion = 1.0; + this._shaderPlatformName = "WEBGL1"; + } + } + } + catch (e) { + // Do nothing + } + } + if (!this._gl) { + if (!canvas) { + throw new Error("The provided canvas is null or undefined."); + } + try { + this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options)); + } + catch (e) { + throw new Error("WebGL not supported"); + } + } + if (!this._gl) { + throw new Error("WebGL not supported"); + } + } + else { + this._gl = canvasOrContext; + canvas = this._gl.canvas; + if (this._gl.renderbufferStorageMultisample) { + this._webGLVersion = 2.0; + this._shaderPlatformName = "WEBGL2"; + } + else { + this._shaderPlatformName = "WEBGL1"; + } + const attributes = this._gl.getContextAttributes(); + if (attributes) { + options.stencil = attributes.stencil; + } + } + this._sharedInit(canvas); + // Ensures a consistent color space unpacking of textures cross browser. + this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE); + if (options.useHighPrecisionFloats !== undefined) { + this._highPrecisionShadersAllowed = options.useHighPrecisionFloats; + } + this.resize(); + this._initGLContext(); + this._initFeatures(); + // Prepare buffer pointers + for (let i = 0; i < this._caps.maxVertexAttribs; i++) { + this._currentBufferPointers[i] = new BufferPointer(); + } + // Shader processor + this._shaderProcessor = this.webGLVersion > 1 ? new WebGL2ShaderProcessor() : new WebGLShaderProcessor(); + // Starting with iOS 14, we can trust the browser + // let matches = navigator.userAgent.match(/Version\/(\d+)/); + // if (matches && matches.length === 2) { + // if (parseInt(matches[1]) >= 14) { + // this._badOS = false; + // } + // } + const versionToLog = `Babylon.js v${ThinEngine.Version}`; + Logger.Log(versionToLog + ` - ${this.description}`); + // Check setAttribute in case of workers + if (this._renderingCanvas && this._renderingCanvas.setAttribute) { + this._renderingCanvas.setAttribute("data-engine", versionToLog); + } + const stateObject = getStateObject(this._gl); + // update state object with the current engine state + stateObject.validateShaderPrograms = this.validateShaderPrograms; + stateObject.parallelShaderCompile = this._caps.parallelShaderCompile; + } + _clearEmptyResources() { + this._dummyFramebuffer = null; + super._clearEmptyResources(); + } + /** + * @internal + */ + _getShaderProcessingContext(shaderLanguage) { + return null; + } + /** + * Gets a boolean indicating if all created effects are ready + * @returns true if all effects are ready + */ + areAllEffectsReady() { + for (const key in this._compiledEffects) { + const effect = this._compiledEffects[key]; + if (!effect.isReady()) { + return false; + } + } + return true; + } + _initGLContext() { + // Caps + this._caps = { + maxTexturesImageUnits: this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS), + maxCombinedTexturesImageUnits: this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS), + maxVertexTextureImageUnits: this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS), + maxTextureSize: this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE), + maxSamples: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_SAMPLES) : 1, + maxCubemapTextureSize: this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE), + maxRenderTextureSize: this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE), + maxVertexAttribs: this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS), + maxVaryingVectors: this._gl.getParameter(this._gl.MAX_VARYING_VECTORS), + maxFragmentUniformVectors: this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS), + maxVertexUniformVectors: this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS), + parallelShaderCompile: this._gl.getExtension("KHR_parallel_shader_compile") || undefined, + standardDerivatives: this._webGLVersion > 1 || this._gl.getExtension("OES_standard_derivatives") !== null, + maxAnisotropy: 1, + astc: this._gl.getExtension("WEBGL_compressed_texture_astc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"), + bptc: this._gl.getExtension("EXT_texture_compression_bptc") || this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"), + s3tc: this._gl.getExtension("WEBGL_compressed_texture_s3tc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"), + // eslint-disable-next-line @typescript-eslint/naming-convention + s3tc_srgb: this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"), + pvrtc: this._gl.getExtension("WEBGL_compressed_texture_pvrtc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"), + etc1: this._gl.getExtension("WEBGL_compressed_texture_etc1") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"), + etc2: this._gl.getExtension("WEBGL_compressed_texture_etc") || + this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc") || + this._gl.getExtension("WEBGL_compressed_texture_es3_0"), // also a requirement of OpenGL ES 3 + textureAnisotropicFilterExtension: this._gl.getExtension("EXT_texture_filter_anisotropic") || + this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic") || + this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"), + uintIndices: this._webGLVersion > 1 || this._gl.getExtension("OES_element_index_uint") !== null, + fragmentDepthSupported: this._webGLVersion > 1 || this._gl.getExtension("EXT_frag_depth") !== null, + highPrecisionShaderSupported: false, + timerQuery: this._gl.getExtension("EXT_disjoint_timer_query_webgl2") || this._gl.getExtension("EXT_disjoint_timer_query"), + supportOcclusionQuery: this._webGLVersion > 1, + canUseTimestampForTimerQuery: false, + drawBuffersExtension: false, + maxMSAASamples: 1, + colorBufferFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_float")), + supportFloatTexturesResolve: false, + rg11b10ufColorRenderable: false, + colorBufferHalfFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_half_float")), + textureFloat: this._webGLVersion > 1 || this._gl.getExtension("OES_texture_float") ? true : false, + textureHalfFloat: this._webGLVersion > 1 || this._gl.getExtension("OES_texture_half_float") ? true : false, + textureHalfFloatRender: false, + textureFloatLinearFiltering: false, + textureFloatRender: false, + textureHalfFloatLinearFiltering: false, + vertexArrayObject: false, + instancedArrays: false, + textureLOD: this._webGLVersion > 1 || this._gl.getExtension("EXT_shader_texture_lod") ? true : false, + texelFetch: this._webGLVersion !== 1, + blendMinMax: false, + multiview: this._gl.getExtension("OVR_multiview2"), + oculusMultiview: this._gl.getExtension("OCULUS_multiview"), + depthTextureExtension: false, + canUseGLInstanceID: this._webGLVersion > 1, + canUseGLVertexID: this._webGLVersion > 1, + supportComputeShaders: false, + supportSRGBBuffers: false, + supportTransformFeedbacks: this._webGLVersion > 1, + textureMaxLevel: this._webGLVersion > 1, + texture2DArrayMaxLayerCount: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS) : 128, + disableMorphTargetTexture: false, + textureNorm16: this._gl.getExtension("EXT_texture_norm16") ? true : false, + }; + this._caps.supportFloatTexturesResolve = this._caps.colorBufferFloat; + this._caps.rg11b10ufColorRenderable = this._caps.colorBufferFloat; + // Infos + this._glVersion = this._gl.getParameter(this._gl.VERSION); + const rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info"); + if (rendererInfo != null) { + this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL); + this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL); + } + if (!this._glVendor) { + this._glVendor = this._gl.getParameter(this._gl.VENDOR) || "Unknown vendor"; + } + if (!this._glRenderer) { + this._glRenderer = this._gl.getParameter(this._gl.RENDERER) || "Unknown renderer"; + } + // Constants + if (this._gl.HALF_FLOAT_OES !== 0x8d61) { + this._gl.HALF_FLOAT_OES = 0x8d61; // Half floating-point type (16-bit). + } + if (this._gl.RGBA16F !== 0x881a) { + this._gl.RGBA16F = 0x881a; // RGBA 16-bit floating-point color-renderable internal sized format. + } + if (this._gl.RGBA32F !== 0x8814) { + this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format. + } + if (this._gl.DEPTH24_STENCIL8 !== 35056) { + this._gl.DEPTH24_STENCIL8 = 35056; + } + // Extensions + if (this._caps.timerQuery) { + if (this._webGLVersion === 1) { + this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery); + } + // WebGLQuery casted to number to avoid TS error + this._caps.canUseTimestampForTimerQuery = (this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) ?? 0) > 0; + } + this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension + ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) + : 0; + this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension("OES_texture_float_linear") ? true : false; + this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false; + this._caps.textureHalfFloatLinearFiltering = + this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension("OES_texture_half_float_linear")) ? true : false; + if (this._caps.textureNorm16) { + this._gl.R16_EXT = 0x822a; + this._gl.RG16_EXT = 0x822c; + this._gl.RGB16_EXT = 0x8054; + this._gl.RGBA16_EXT = 0x805b; + this._gl.R16_SNORM_EXT = 0x8f98; + this._gl.RG16_SNORM_EXT = 0x8f99; + this._gl.RGB16_SNORM_EXT = 0x8f9a; + this._gl.RGBA16_SNORM_EXT = 0x8f9b; + } + // Compressed formats + if (this._caps.astc) { + this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; + } + if (this._caps.bptc) { + this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT; + } + if (this._caps.s3tc_srgb) { + this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT; + this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } + if (this._caps.etc2) { + this._gl.COMPRESSED_SRGB8_ETC2 = this._caps.etc2.COMPRESSED_SRGB8_ETC2; + this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; + } + // Checks if some of the format renders first to allow the use of webgl inspector. + if (this._webGLVersion > 1) { + if (this._gl.HALF_FLOAT_OES !== 0x140b) { + this._gl.HALF_FLOAT_OES = 0x140b; + } + } + this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer(); + // Draw buffers + if (this._webGLVersion > 1) { + this._caps.drawBuffersExtension = true; + this._caps.maxMSAASamples = this._maxMSAASamplesOverride !== null ? this._maxMSAASamplesOverride : this._gl.getParameter(this._gl.MAX_SAMPLES); + this._caps.maxDrawBuffers = this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS); + } + else { + const drawBuffersExtension = this._gl.getExtension("WEBGL_draw_buffers"); + if (drawBuffersExtension !== null) { + this._caps.drawBuffersExtension = true; + this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension); + this._caps.maxDrawBuffers = this._gl.getParameter(drawBuffersExtension.MAX_DRAW_BUFFERS_WEBGL); + this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER; + for (let i = 0; i < 16; i++) { + this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"]; + } + } + } + // Depth Texture + if (this._webGLVersion > 1) { + this._caps.depthTextureExtension = true; + } + else { + const depthTextureExtension = this._gl.getExtension("WEBGL_depth_texture"); + if (depthTextureExtension != null) { + this._caps.depthTextureExtension = true; + this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL; + } + } + // Vertex array object + if (this.disableVertexArrayObjects) { + this._caps.vertexArrayObject = false; + } + else if (this._webGLVersion > 1) { + this._caps.vertexArrayObject = true; + } + else { + const vertexArrayObjectExtension = this._gl.getExtension("OES_vertex_array_object"); + if (vertexArrayObjectExtension != null) { + this._caps.vertexArrayObject = true; + this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension); + this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension); + this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension); + } + } + // Instances count + if (this._webGLVersion > 1) { + this._caps.instancedArrays = true; + } + else { + const instanceExtension = this._gl.getExtension("ANGLE_instanced_arrays"); + if (instanceExtension != null) { + this._caps.instancedArrays = true; + this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension); + this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension); + this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension); + } + else { + this._caps.instancedArrays = false; + } + } + if (this._gl.getShaderPrecisionFormat) { + const vertexhighp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT); + const fragmenthighp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT); + if (vertexhighp && fragmenthighp) { + this._caps.highPrecisionShaderSupported = vertexhighp.precision !== 0 && fragmenthighp.precision !== 0; + } + } + if (this._webGLVersion > 1) { + this._caps.blendMinMax = true; + } + else { + const blendMinMaxExtension = this._gl.getExtension("EXT_blend_minmax"); + if (blendMinMaxExtension != null) { + this._caps.blendMinMax = true; + this._gl.MAX = blendMinMaxExtension.MAX_EXT; + this._gl.MIN = blendMinMaxExtension.MIN_EXT; + } + } + // sRGB buffers + // only run this if not already set to true (in the constructor, for example) + if (!this._caps.supportSRGBBuffers) { + if (this._webGLVersion > 1) { + this._caps.supportSRGBBuffers = true; + this._glSRGBExtensionValues = { + SRGB: WebGL2RenderingContext.SRGB, + SRGB8: WebGL2RenderingContext.SRGB8, + SRGB8_ALPHA8: WebGL2RenderingContext.SRGB8_ALPHA8, + }; + } + else { + const sRGBExtension = this._gl.getExtension("EXT_sRGB"); + if (sRGBExtension != null) { + this._caps.supportSRGBBuffers = true; + this._glSRGBExtensionValues = { + SRGB: sRGBExtension.SRGB_EXT, + SRGB8: sRGBExtension.SRGB_ALPHA_EXT, + SRGB8_ALPHA8: sRGBExtension.SRGB_ALPHA_EXT, + }; + } + } + // take into account the forced state that was provided in options + if (this._creationOptions) { + const forceSRGBBufferSupportState = this._creationOptions.forceSRGBBufferSupportState; + if (forceSRGBBufferSupportState !== undefined) { + this._caps.supportSRGBBuffers = this._caps.supportSRGBBuffers && forceSRGBBufferSupportState; + } + } + } + // Depth buffer + this._depthCullingState.depthTest = true; + this._depthCullingState.depthFunc = this._gl.LEQUAL; + this._depthCullingState.depthMask = true; + // Texture maps + this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits; + for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) { + this._nextFreeTextureSlots.push(slot); + } + if (this._glRenderer === "Mali-G72") { + // Overcome a bug when using a texture to store morph targets on Mali-G72 + this._caps.disableMorphTargetTexture = true; + } + } + _initFeatures() { + this._features = { + forceBitmapOverHTMLImageElement: typeof HTMLImageElement === "undefined", + supportRenderAndCopyToLodForFloatTextures: this._webGLVersion !== 1, + supportDepthStencilTexture: this._webGLVersion !== 1, + supportShadowSamplers: this._webGLVersion !== 1, + uniformBufferHardCheckMatrix: false, + allowTexturePrefiltering: this._webGLVersion !== 1, + trackUbosInFrame: false, + checkUbosContentBeforeUpload: false, + supportCSM: this._webGLVersion !== 1, + basisNeedsPOT: this._webGLVersion === 1, + support3DTextures: this._webGLVersion !== 1, + needTypeSuffixInShaderConstants: this._webGLVersion !== 1, + supportMSAA: this._webGLVersion !== 1, + supportSSAO2: this._webGLVersion !== 1, + supportIBLShadows: this._webGLVersion !== 1, + supportExtendedTextureFormats: this._webGLVersion !== 1, + supportSwitchCaseInShader: this._webGLVersion !== 1, + supportSyncTextureRead: true, + needsInvertingBitmap: true, + useUBOBindingCache: true, + needShaderCodeInlining: false, + needToAlwaysBindUniformBuffers: false, + supportRenderPasses: false, + supportSpriteInstancing: true, + forceVertexBufferStrideAndOffsetMultiple4Bytes: false, + _checkNonFloatVertexBuffersDontRecreatePipelineContext: false, + _collectUbosUpdatedInFrame: false, + }; + } + /** + * Gets version of the current webGL context + * Keep it for back compat - use version instead + */ + get webGLVersion() { + return this._webGLVersion; + } + /** + * Gets a string identifying the name of the class + * @returns "Engine" string + */ + getClassName() { + return "ThinEngine"; + } + /** @internal */ + _prepareWorkingCanvas() { + if (this._workingCanvas) { + return; + } + this._workingCanvas = this.createCanvas(1, 1); + const context = this._workingCanvas.getContext("2d"); + if (context) { + this._workingContext = context; + } + } + /** + * Gets an object containing information about the current engine context + * @returns an object containing the vendor, the renderer and the version of the current engine context + */ + getInfo() { + return this.getGlInfo(); + } + /** + * Gets an object containing information about the current webGL context + * @returns an object containing the vendor, the renderer and the version of the current webGL context + */ + getGlInfo() { + return { + vendor: this._glVendor, + renderer: this._glRenderer, + version: this._glVersion, + }; + } + /**Gets driver info if available */ + extractDriverInfo() { + const glInfo = this.getGlInfo(); + if (glInfo && glInfo.renderer) { + return glInfo.renderer; + } + return ""; + } + /** + * Gets the current render width + * @param useScreen defines if screen size must be used (or the current render target if any) + * @returns a number defining the current render width + */ + getRenderWidth(useScreen = false) { + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.width; + } + return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferWidth : this._gl.drawingBufferWidth; + } + /** + * Gets the current render height + * @param useScreen defines if screen size must be used (or the current render target if any) + * @returns a number defining the current render height + */ + getRenderHeight(useScreen = false) { + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.height; + } + return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight; + } + /** + * Clear the current render buffer or the current render target (if any is set up) + * @param color defines the color to use + * @param backBuffer defines if the back buffer must be cleared + * @param depth defines if the depth buffer must be cleared + * @param stencil defines if the stencil buffer must be cleared + */ + clear(color, backBuffer, depth, stencil = false) { + const useStencilGlobalOnly = this.stencilStateComposer.useStencilGlobalOnly; + this.stencilStateComposer.useStencilGlobalOnly = true; // make sure the stencil mask is coming from the global stencil and not from a material (effect) which would currently be in effect + this.applyStates(); + this.stencilStateComposer.useStencilGlobalOnly = useStencilGlobalOnly; + let mode = 0; + if (backBuffer && color) { + let setBackBufferColor = true; + if (this._currentRenderTarget) { + const textureFormat = this._currentRenderTarget.texture?.format; + if (textureFormat === 8 || + textureFormat === 9 || + textureFormat === 10 || + textureFormat === 11) { + const textureType = this._currentRenderTarget.texture?.type; + if (textureType === 7 || textureType === 5) { + ThinEngine._TempClearColorUint32[0] = color.r * 255; + ThinEngine._TempClearColorUint32[1] = color.g * 255; + ThinEngine._TempClearColorUint32[2] = color.b * 255; + ThinEngine._TempClearColorUint32[3] = color.a * 255; + this._gl.clearBufferuiv(this._gl.COLOR, 0, ThinEngine._TempClearColorUint32); + setBackBufferColor = false; + } + else { + ThinEngine._TempClearColorInt32[0] = color.r * 255; + ThinEngine._TempClearColorInt32[1] = color.g * 255; + ThinEngine._TempClearColorInt32[2] = color.b * 255; + ThinEngine._TempClearColorInt32[3] = color.a * 255; + this._gl.clearBufferiv(this._gl.COLOR, 0, ThinEngine._TempClearColorInt32); + setBackBufferColor = false; + } + } + } + if (setBackBufferColor) { + this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0); + mode |= this._gl.COLOR_BUFFER_BIT; + } + } + if (depth) { + if (this.useReverseDepthBuffer) { + this._depthCullingState.depthFunc = this._gl.GEQUAL; + this._gl.clearDepth(0.0); + } + else { + this._gl.clearDepth(1.0); + } + mode |= this._gl.DEPTH_BUFFER_BIT; + } + if (stencil) { + this._gl.clearStencil(0); + mode |= this._gl.STENCIL_BUFFER_BIT; + } + this._gl.clear(mode); + } + /** + * @internal + */ + _viewport(x, y, width, height) { + if (x !== this._viewportCached.x || y !== this._viewportCached.y || width !== this._viewportCached.z || height !== this._viewportCached.w) { + this._viewportCached.x = x; + this._viewportCached.y = y; + this._viewportCached.z = width; + this._viewportCached.w = height; + this._gl.viewport(x, y, width, height); + } + } + /** + * End the current frame + */ + endFrame() { + super.endFrame(); + // Force a flush in case we are using a bad OS. + if (this._badOS) { + this.flushFramebuffer(); + } + } + /** + * Gets the performance monitor attached to this engine + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation + */ + get performanceMonitor() { + throw new Error("Not Supported by ThinEngine"); + } + /** + * Binds the frame buffer to the specified texture. + * @param rtWrapper The render target wrapper to render to + * @param faceIndex The face of the texture to render to in case of cube texture and if the render target wrapper is not a multi render target + * @param requiredWidth The width of the target to render to + * @param requiredHeight The height of the target to render to + * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true + * @param lodLevel Defines the lod level to bind to the frame buffer + * @param layer Defines the 2d array index to bind to the frame buffer if the render target wrapper is not a multi render target + */ + bindFramebuffer(rtWrapper, faceIndex = 0, requiredWidth, requiredHeight, forceFullscreenViewport, lodLevel = 0, layer = 0) { + const webglRTWrapper = rtWrapper; + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + this._currentRenderTarget = rtWrapper; + this._bindUnboundFramebuffer(webglRTWrapper._framebuffer); + const gl = this._gl; + if (!rtWrapper.isMulti) { + if (rtWrapper.is2DArray || rtWrapper.is3D) { + gl.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, rtWrapper.texture._hardwareTexture?.underlyingResource, lodLevel, layer); + webglRTWrapper._currentLOD = lodLevel; + } + else if (rtWrapper.isCube) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, rtWrapper.texture._hardwareTexture?.underlyingResource, lodLevel); + } + else if (webglRTWrapper._currentLOD !== lodLevel) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, rtWrapper.texture._hardwareTexture?.underlyingResource, lodLevel); + webglRTWrapper._currentLOD = lodLevel; + } + } + const depthStencilTexture = rtWrapper._depthStencilTexture; + if (depthStencilTexture) { + if (rtWrapper.is3D) { + if (rtWrapper.texture.width !== depthStencilTexture.width || + rtWrapper.texture.height !== depthStencilTexture.height || + rtWrapper.texture.depth !== depthStencilTexture.depth) { + Logger.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment"); + } + } + const attachment = rtWrapper._depthStencilTextureWithStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + if (rtWrapper.is2DArray || rtWrapper.is3D) { + gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, depthStencilTexture._hardwareTexture?.underlyingResource, lodLevel, layer); + } + else if (rtWrapper.isCube) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._hardwareTexture?.underlyingResource, lodLevel); + } + else { + gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, depthStencilTexture._hardwareTexture?.underlyingResource, lodLevel); + } + } + if (webglRTWrapper._MSAAFramebuffer) { + this._bindUnboundFramebuffer(webglRTWrapper._MSAAFramebuffer); + } + if (this._cachedViewport && !forceFullscreenViewport) { + this.setViewport(this._cachedViewport, requiredWidth, requiredHeight); + } + else { + if (!requiredWidth) { + requiredWidth = rtWrapper.width; + if (lodLevel) { + requiredWidth = requiredWidth / Math.pow(2, lodLevel); + } + } + if (!requiredHeight) { + requiredHeight = rtWrapper.height; + if (lodLevel) { + requiredHeight = requiredHeight / Math.pow(2, lodLevel); + } + } + this._viewport(0, 0, requiredWidth, requiredHeight); + } + this.wipeCaches(); + } + setStateCullFaceType(cullBackFaces, force) { + const cullFace = (this.cullBackFaces ?? cullBackFaces ?? true) ? this._gl.BACK : this._gl.FRONT; + if (this._depthCullingState.cullFace !== cullFace || force) { + this._depthCullingState.cullFace = cullFace; + } + } + /** + * Set various states to the webGL context + * @param culling defines culling state: true to enable culling, false to disable it + * @param zOffset defines the value to apply to zOffset (0 by default) + * @param force defines if states must be applied even if cache is up to date + * @param reverseSide defines if culling must be reversed (CCW if false, CW if true) + * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled) + * @param stencil stencil states to set + * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default) + */ + setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) { + // Culling + if (this._depthCullingState.cull !== culling || force) { + this._depthCullingState.cull = culling; + } + // Cull face + this.setStateCullFaceType(cullBackFaces, force); + // Z offset + this.setZOffset(zOffset); + this.setZOffsetUnits(zOffsetUnits); + // Front face + const frontFace = reverseSide ? this._gl.CW : this._gl.CCW; + if (this._depthCullingState.frontFace !== frontFace || force) { + this._depthCullingState.frontFace = frontFace; + } + this._stencilStateComposer.stencilMaterial = stencil; + } + /** + * @internal + */ + _bindUnboundFramebuffer(framebuffer) { + if (this._currentFramebuffer !== framebuffer) { + this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer); + this._currentFramebuffer = framebuffer; + } + } + /** @internal */ + _currentFrameBufferIsDefaultFrameBuffer() { + return this._currentFramebuffer === null; + } + /** + * Generates the mipmaps for a texture + * @param texture texture to generate the mipmaps for + */ + generateMipmaps(texture) { + const target = this._getTextureTarget(texture); + this._bindTextureDirectly(target, texture, true); + this._gl.generateMipmap(target); + this._bindTextureDirectly(target, null); + } + /** + * Unbind the current render target texture from the webGL context + * @param texture defines the render target wrapper to unbind + * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated + * @param onBeforeUnbind defines a function which will be called before the effective unbind + */ + unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) { + const webglRTWrapper = texture; + this._currentRenderTarget = null; + if (!webglRTWrapper.disableAutomaticMSAAResolve) { + if (texture.isMulti) { + this.resolveMultiFramebuffer(texture); + } + else { + this.resolveFramebuffer(texture); + } + } + if (!disableGenerateMipMaps) { + if (texture.isMulti) { + this.generateMipMapsMultiFramebuffer(texture); + } + else { + this.generateMipMapsFramebuffer(texture); + } + } + if (onBeforeUnbind) { + if (webglRTWrapper._MSAAFramebuffer) { + // Bind the correct framebuffer + this._bindUnboundFramebuffer(webglRTWrapper._framebuffer); + } + onBeforeUnbind(); + } + this._bindUnboundFramebuffer(null); + } + /** + * Generates mipmaps for the texture of the (single) render target + * @param texture The render target containing the texture to generate the mipmaps for + */ + generateMipMapsFramebuffer(texture) { + if (!texture.isMulti && texture.texture?.generateMipMaps && !texture.isCube) { + this.generateMipmaps(texture.texture); + } + } + /** + * Resolves the MSAA texture of the (single) render target into its non-MSAA version. + * Note that if "texture" is not a MSAA render target, no resolve is performed. + * @param texture The render target texture containing the MSAA textures to resolve + */ + resolveFramebuffer(texture) { + const rtWrapper = texture; + const gl = this._gl; + if (!rtWrapper._MSAAFramebuffer || rtWrapper.isMulti) { + return; + } + let bufferBits = rtWrapper.resolveMSAAColors ? gl.COLOR_BUFFER_BIT : 0; + bufferBits |= rtWrapper._generateDepthBuffer && rtWrapper.resolveMSAADepth ? gl.DEPTH_BUFFER_BIT : 0; + bufferBits |= rtWrapper._generateStencilBuffer && rtWrapper.resolveMSAAStencil ? gl.STENCIL_BUFFER_BIT : 0; + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, rtWrapper._MSAAFramebuffer); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, rtWrapper._framebuffer); + gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, bufferBits, gl.NEAREST); + } + /** + * Force a webGL flush (ie. a flush of all waiting webGL commands) + */ + flushFramebuffer() { + this._gl.flush(); + } + /** + * Unbind the current render target and bind the default framebuffer + */ + restoreDefaultFramebuffer() { + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + else { + this._bindUnboundFramebuffer(null); + } + if (this._cachedViewport) { + this.setViewport(this._cachedViewport); + } + this.wipeCaches(); + } + // VBOs + /** @internal */ + _resetVertexBufferBinding() { + this.bindArrayBuffer(null); + this._cachedVertexBuffers = null; + } + /** + * Creates a vertex buffer + * @param data the data or size for the vertex buffer + * @param _updatable whether the buffer should be created as updatable + * @param _label defines the label of the buffer (for debug purpose) + * @returns the new WebGL static buffer + */ + createVertexBuffer(data, _updatable, _label) { + return this._createVertexBuffer(data, this._gl.STATIC_DRAW); + } + _createVertexBuffer(data, usage) { + const vbo = this._gl.createBuffer(); + if (!vbo) { + throw new Error("Unable to create vertex buffer"); + } + const dataBuffer = new WebGLDataBuffer(vbo); + this.bindArrayBuffer(dataBuffer); + if (typeof data !== "number") { + if (data instanceof Array) { + this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), usage); + dataBuffer.capacity = data.length * 4; + } + else { + this._gl.bufferData(this._gl.ARRAY_BUFFER, data, usage); + dataBuffer.capacity = data.byteLength; + } + } + else { + this._gl.bufferData(this._gl.ARRAY_BUFFER, new Uint8Array(data), usage); + dataBuffer.capacity = data; + } + this._resetVertexBufferBinding(); + dataBuffer.references = 1; + return dataBuffer; + } + /** + * Creates a dynamic vertex buffer + * @param data the data for the dynamic vertex buffer + * @param _label defines the label of the buffer (for debug purpose) + * @returns the new WebGL dynamic buffer + */ + createDynamicVertexBuffer(data, _label) { + return this._createVertexBuffer(data, this._gl.DYNAMIC_DRAW); + } + _resetIndexBufferBinding() { + this.bindIndexBuffer(null); + this._cachedIndexBuffer = null; + } + /** + * Creates a new index buffer + * @param indices defines the content of the index buffer + * @param updatable defines if the index buffer must be updatable + * @param _label defines the label of the buffer (for debug purpose) + * @returns a new webGL buffer + */ + createIndexBuffer(indices, updatable, _label) { + const vbo = this._gl.createBuffer(); + const dataBuffer = new WebGLDataBuffer(vbo); + if (!vbo) { + throw new Error("Unable to create index buffer"); + } + this.bindIndexBuffer(dataBuffer); + const data = this._normalizeIndexData(indices); + this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, data, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW); + this._resetIndexBufferBinding(); + dataBuffer.references = 1; + dataBuffer.is32Bits = data.BYTES_PER_ELEMENT === 4; + return dataBuffer; + } + _normalizeIndexData(indices) { + const bytesPerElement = indices.BYTES_PER_ELEMENT; + if (bytesPerElement === 2) { + return indices; + } + // Check 32 bit support + if (this._caps.uintIndices) { + if (indices instanceof Uint32Array) { + return indices; + } + else { + // number[] or Int32Array, check if 32 bit is necessary + for (let index = 0; index < indices.length; index++) { + if (indices[index] >= 65535) { + return new Uint32Array(indices); + } + } + return new Uint16Array(indices); + } + } + // No 32 bit support, force conversion to 16 bit (values greater 16 bit are lost) + return new Uint16Array(indices); + } + /** + * Bind a webGL buffer to the webGL context + * @param buffer defines the buffer to bind + */ + bindArrayBuffer(buffer) { + if (!this._vaoRecordInProgress) { + this._unbindVertexArrayObject(); + } + this._bindBuffer(buffer, this._gl.ARRAY_BUFFER); + } + /** + * Bind a specific block at a given index in a specific shader program + * @param pipelineContext defines the pipeline context to use + * @param blockName defines the block name + * @param index defines the index where to bind the block + */ + bindUniformBlock(pipelineContext, blockName, index) { + const program = pipelineContext.program; + const uniformLocation = this._gl.getUniformBlockIndex(program, blockName); + this._gl.uniformBlockBinding(program, uniformLocation, index); + } + // eslint-disable-next-line @typescript-eslint/naming-convention + bindIndexBuffer(buffer) { + if (!this._vaoRecordInProgress) { + this._unbindVertexArrayObject(); + } + this._bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER); + } + _bindBuffer(buffer, target) { + if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) { + this._gl.bindBuffer(target, buffer ? buffer.underlyingResource : null); + this._currentBoundBuffer[target] = buffer; + } + } + /** + * update the bound buffer with the given data + * @param data defines the data to update + */ + updateArrayBuffer(data) { + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); + } + _vertexAttribPointer(buffer, indx, size, type, normalized, stride, offset) { + const pointer = this._currentBufferPointers[indx]; + if (!pointer) { + return; + } + let changed = false; + if (!pointer.active) { + changed = true; + pointer.active = true; + pointer.index = indx; + pointer.size = size; + pointer.type = type; + pointer.normalized = normalized; + pointer.stride = stride; + pointer.offset = offset; + pointer.buffer = buffer; + } + else { + if (pointer.buffer !== buffer) { + pointer.buffer = buffer; + changed = true; + } + if (pointer.size !== size) { + pointer.size = size; + changed = true; + } + if (pointer.type !== type) { + pointer.type = type; + changed = true; + } + if (pointer.normalized !== normalized) { + pointer.normalized = normalized; + changed = true; + } + if (pointer.stride !== stride) { + pointer.stride = stride; + changed = true; + } + if (pointer.offset !== offset) { + pointer.offset = offset; + changed = true; + } + } + if (changed || this._vaoRecordInProgress) { + this.bindArrayBuffer(buffer); + if (type === this._gl.UNSIGNED_INT || type === this._gl.INT) { + this._gl.vertexAttribIPointer(indx, size, type, stride, offset); + } + else { + this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset); + } + } + } + /** + * @internal + */ + _bindIndexBufferWithCache(indexBuffer) { + if (indexBuffer == null) { + return; + } + if (this._cachedIndexBuffer !== indexBuffer) { + this._cachedIndexBuffer = indexBuffer; + this.bindIndexBuffer(indexBuffer); + this._uintIndicesCurrentlySet = indexBuffer.is32Bits; + } + } + _bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers) { + const attributes = effect.getAttributesNames(); + if (!this._vaoRecordInProgress) { + this._unbindVertexArrayObject(); + } + this.unbindAllAttributes(); + for (let index = 0; index < attributes.length; index++) { + const order = effect.getAttributeLocation(index); + if (order >= 0) { + const ai = attributes[index]; + let vertexBuffer = null; + if (overrideVertexBuffers) { + vertexBuffer = overrideVertexBuffers[ai]; + } + if (!vertexBuffer) { + vertexBuffer = vertexBuffers[ai]; + } + if (!vertexBuffer) { + continue; + } + this._gl.enableVertexAttribArray(order); + if (!this._vaoRecordInProgress) { + this._vertexAttribArraysEnabled[order] = true; + } + const buffer = vertexBuffer.getBuffer(); + if (buffer) { + this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset); + if (vertexBuffer.getIsInstanced()) { + this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor()); + if (!this._vaoRecordInProgress) { + this._currentInstanceLocations.push(order); + this._currentInstanceBuffers.push(buffer); + } + } + } + } + } + } + /** + * Records a vertex array object + * @see https://doc.babylonjs.com/setup/support/webGL2#vertex-array-objects + * @param vertexBuffers defines the list of vertex buffers to store + * @param indexBuffer defines the index buffer to store + * @param effect defines the effect to store + * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers + * @returns the new vertex array object + */ + recordVertexArrayObject(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { + const vao = this._gl.createVertexArray(); + if (!vao) { + throw new Error("Unable to create VAO"); + } + this._vaoRecordInProgress = true; + this._gl.bindVertexArray(vao); + this._mustWipeVertexAttributes = true; + this._bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers); + this.bindIndexBuffer(indexBuffer); + this._vaoRecordInProgress = false; + this._gl.bindVertexArray(null); + return vao; + } + /** + * Bind a specific vertex array object + * @see https://doc.babylonjs.com/setup/support/webGL2#vertex-array-objects + * @param vertexArrayObject defines the vertex array object to bind + * @param indexBuffer defines the index buffer to bind + */ + bindVertexArrayObject(vertexArrayObject, indexBuffer) { + if (this._cachedVertexArrayObject !== vertexArrayObject) { + this._cachedVertexArrayObject = vertexArrayObject; + this._gl.bindVertexArray(vertexArrayObject); + this._cachedVertexBuffers = null; + this._cachedIndexBuffer = null; + this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits; + this._mustWipeVertexAttributes = true; + } + } + /** + * Bind webGl buffers directly to the webGL context + * @param vertexBuffer defines the vertex buffer to bind + * @param indexBuffer defines the index buffer to bind + * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer + * @param vertexStrideSize defines the vertex stride of the vertex buffer + * @param effect defines the effect associated with the vertex buffer + */ + bindBuffersDirectly(vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) { + if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) { + this._cachedVertexBuffers = vertexBuffer; + this._cachedEffectForVertexBuffers = effect; + const attributesCount = effect.getAttributesCount(); + this._unbindVertexArrayObject(); + this.unbindAllAttributes(); + let offset = 0; + for (let index = 0; index < attributesCount; index++) { + if (index < vertexDeclaration.length) { + const order = effect.getAttributeLocation(index); + if (order >= 0) { + this._gl.enableVertexAttribArray(order); + this._vertexAttribArraysEnabled[order] = true; + this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset); + } + offset += vertexDeclaration[index] * 4; + } + } + } + this._bindIndexBufferWithCache(indexBuffer); + } + _unbindVertexArrayObject() { + if (!this._cachedVertexArrayObject) { + return; + } + this._cachedVertexArrayObject = null; + this._gl.bindVertexArray(null); + } + /** + * Bind a list of vertex buffers to the webGL context + * @param vertexBuffers defines the list of vertex buffers to bind + * @param indexBuffer defines the index buffer to bind + * @param effect defines the effect associated with the vertex buffers + * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers + */ + bindBuffers(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { + if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) { + this._cachedVertexBuffers = vertexBuffers; + this._cachedEffectForVertexBuffers = effect; + this._bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers); + } + this._bindIndexBufferWithCache(indexBuffer); + } + /** + * Unbind all instance attributes + */ + unbindInstanceAttributes() { + let boundBuffer; + for (let i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) { + const instancesBuffer = this._currentInstanceBuffers[i]; + if (boundBuffer != instancesBuffer && instancesBuffer.references) { + boundBuffer = instancesBuffer; + this.bindArrayBuffer(instancesBuffer); + } + const offsetLocation = this._currentInstanceLocations[i]; + this._gl.vertexAttribDivisor(offsetLocation, 0); + } + this._currentInstanceBuffers.length = 0; + this._currentInstanceLocations.length = 0; + } + /** + * Release and free the memory of a vertex array object + * @param vao defines the vertex array object to delete + */ + releaseVertexArrayObject(vao) { + this._gl.deleteVertexArray(vao); + } + /** + * @internal + */ + _releaseBuffer(buffer) { + buffer.references--; + if (buffer.references === 0) { + this._deleteBuffer(buffer); + return true; + } + return false; + } + _deleteBuffer(buffer) { + this._gl.deleteBuffer(buffer.underlyingResource); + } + /** + * Update the content of a webGL buffer used with instantiation and bind it to the webGL context + * @param instancesBuffer defines the webGL buffer to update and bind + * @param data defines the data to store in the buffer + * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer + */ + updateAndBindInstancesBuffer(instancesBuffer, data, offsetLocations) { + this.bindArrayBuffer(instancesBuffer); + if (data) { + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); + } + if (offsetLocations[0].index !== undefined) { + this.bindInstancesBuffer(instancesBuffer, offsetLocations, true); + } + else { + for (let index = 0; index < 4; index++) { + const offsetLocation = offsetLocations[index]; + if (!this._vertexAttribArraysEnabled[offsetLocation]) { + this._gl.enableVertexAttribArray(offsetLocation); + this._vertexAttribArraysEnabled[offsetLocation] = true; + } + this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16); + this._gl.vertexAttribDivisor(offsetLocation, 1); + this._currentInstanceLocations.push(offsetLocation); + this._currentInstanceBuffers.push(instancesBuffer); + } + } + } + /** + * Bind the content of a webGL buffer used with instantiation + * @param instancesBuffer defines the webGL buffer to bind + * @param attributesInfo defines the offsets or attributes information used to determine where data must be stored in the buffer + * @param computeStride defines Whether to compute the strides from the info or use the default 0 + */ + bindInstancesBuffer(instancesBuffer, attributesInfo, computeStride = true) { + this.bindArrayBuffer(instancesBuffer); + let stride = 0; + if (computeStride) { + for (let i = 0; i < attributesInfo.length; i++) { + const ai = attributesInfo[i]; + stride += ai.attributeSize * 4; + } + } + for (let i = 0; i < attributesInfo.length; i++) { + const ai = attributesInfo[i]; + if (ai.index === undefined) { + ai.index = this._currentEffect.getAttributeLocationByName(ai.attributeName); + } + if (ai.index < 0) { + continue; + } + if (!this._vertexAttribArraysEnabled[ai.index]) { + this._gl.enableVertexAttribArray(ai.index); + this._vertexAttribArraysEnabled[ai.index] = true; + } + this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attributeType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset); + this._gl.vertexAttribDivisor(ai.index, ai.divisor === undefined ? 1 : ai.divisor); + this._currentInstanceLocations.push(ai.index); + this._currentInstanceBuffers.push(instancesBuffer); + } + } + /** + * Disable the instance attribute corresponding to the name in parameter + * @param name defines the name of the attribute to disable + */ + disableInstanceAttributeByName(name) { + if (!this._currentEffect) { + return; + } + const attributeLocation = this._currentEffect.getAttributeLocationByName(name); + this.disableInstanceAttribute(attributeLocation); + } + /** + * Disable the instance attribute corresponding to the location in parameter + * @param attributeLocation defines the attribute location of the attribute to disable + */ + disableInstanceAttribute(attributeLocation) { + let shouldClean = false; + let index; + while ((index = this._currentInstanceLocations.indexOf(attributeLocation)) !== -1) { + this._currentInstanceLocations.splice(index, 1); + this._currentInstanceBuffers.splice(index, 1); + shouldClean = true; + index = this._currentInstanceLocations.indexOf(attributeLocation); + } + if (shouldClean) { + this._gl.vertexAttribDivisor(attributeLocation, 0); + this.disableAttributeByIndex(attributeLocation); + } + } + /** + * Disable the attribute corresponding to the location in parameter + * @param attributeLocation defines the attribute location of the attribute to disable + */ + disableAttributeByIndex(attributeLocation) { + this._gl.disableVertexAttribArray(attributeLocation); + this._vertexAttribArraysEnabled[attributeLocation] = false; + this._currentBufferPointers[attributeLocation].active = false; + } + /** + * Send a draw order + * @param useTriangles defines if triangles must be used to draw (else wireframe will be used) + * @param indexStart defines the starting index + * @param indexCount defines the number of index to draw + * @param instancesCount defines the number of instances to draw (if instantiation is enabled) + */ + draw(useTriangles, indexStart, indexCount, instancesCount) { + this.drawElementsType(useTriangles ? 0 : 1, indexStart, indexCount, instancesCount); + } + /** + * Draw a list of points + * @param verticesStart defines the index of first vertex to draw + * @param verticesCount defines the count of vertices to draw + * @param instancesCount defines the number of instances to draw (if instantiation is enabled) + */ + drawPointClouds(verticesStart, verticesCount, instancesCount) { + this.drawArraysType(2, verticesStart, verticesCount, instancesCount); + } + /** + * Draw a list of unindexed primitives + * @param useTriangles defines if triangles must be used to draw (else wireframe will be used) + * @param verticesStart defines the index of first vertex to draw + * @param verticesCount defines the count of vertices to draw + * @param instancesCount defines the number of instances to draw (if instantiation is enabled) + */ + drawUnIndexed(useTriangles, verticesStart, verticesCount, instancesCount) { + this.drawArraysType(useTriangles ? 0 : 1, verticesStart, verticesCount, instancesCount); + } + /** + * Draw a list of indexed primitives + * @param fillMode defines the primitive to use + * @param indexStart defines the starting index + * @param indexCount defines the number of index to draw + * @param instancesCount defines the number of instances to draw (if instantiation is enabled) + */ + drawElementsType(fillMode, indexStart, indexCount, instancesCount) { + // Apply states + this.applyStates(); + this._reportDrawCall(); + // Render + const drawMode = this._drawMode(fillMode); + const indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT; + const mult = this._uintIndicesCurrentlySet ? 4 : 2; + if (instancesCount) { + this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount); + } + else { + this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult); + } + } + /** + * Draw a list of unindexed primitives + * @param fillMode defines the primitive to use + * @param verticesStart defines the index of first vertex to draw + * @param verticesCount defines the count of vertices to draw + * @param instancesCount defines the number of instances to draw (if instantiation is enabled) + */ + drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) { + // Apply states + this.applyStates(); + this._reportDrawCall(); + const drawMode = this._drawMode(fillMode); + if (instancesCount) { + this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount); + } + else { + this._gl.drawArrays(drawMode, verticesStart, verticesCount); + } + } + _drawMode(fillMode) { + switch (fillMode) { + // Triangle views + case 0: + return this._gl.TRIANGLES; + case 2: + return this._gl.POINTS; + case 1: + return this._gl.LINES; + // Draw modes + case 3: + return this._gl.POINTS; + case 4: + return this._gl.LINES; + case 5: + return this._gl.LINE_LOOP; + case 6: + return this._gl.LINE_STRIP; + case 7: + return this._gl.TRIANGLE_STRIP; + case 8: + return this._gl.TRIANGLE_FAN; + default: + return this._gl.TRIANGLES; + } + } + // Shaders + /** + * @internal + */ + _releaseEffect(effect) { + if (this._compiledEffects[effect._key]) { + delete this._compiledEffects[effect._key]; + } + const pipelineContext = effect.getPipelineContext(); + if (pipelineContext) { + this._deletePipelineContext(pipelineContext); + } + } + /** + * @internal + */ + _deletePipelineContext(pipelineContext) { + const webGLPipelineContext = pipelineContext; + if (webGLPipelineContext && webGLPipelineContext.program) { + webGLPipelineContext.program.__SPECTOR_rebuildProgram = null; + resetCachedPipeline(webGLPipelineContext); + if (this._gl) { + this._gl.deleteProgram(webGLPipelineContext.program); + } + } + } + /** + * @internal + */ + _getGlobalDefines(defines) { + return _getGlobalDefines(defines, this.isNDCHalfZRange, this.useReverseDepthBuffer, this.useExactSrgbConversions); + } + /** + * Create a new effect (used to store vertex/fragment shaders) + * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx) + * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object + * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use + * @param samplers defines an array of string used to represent textures + * @param defines defines the string containing the defines to use to compile the shaders + * @param fallbacks defines the list of potential fallbacks to use if shader compilation fails + * @param onCompiled defines a function to call when the effect creation is successful + * @param onError defines a function to call when the effect creation has failed + * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights) + * @param shaderLanguage the language the shader is written in (default: GLSL) + * @param extraInitializationsAsync additional async code to run before preparing the effect + * @returns the new Effect + */ + createEffect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters, shaderLanguage = 0 /* ShaderLanguage.GLSL */, extraInitializationsAsync) { + const vertex = typeof baseName === "string" ? baseName : baseName.vertexToken || baseName.vertexSource || baseName.vertexElement || baseName.vertex; + const fragment = typeof baseName === "string" ? baseName : baseName.fragmentToken || baseName.fragmentSource || baseName.fragmentElement || baseName.fragment; + const globalDefines = this._getGlobalDefines(); + const isOptions = attributesNamesOrOptions.attributes !== undefined; + let fullDefines = defines ?? attributesNamesOrOptions.defines ?? ""; + if (globalDefines) { + fullDefines += globalDefines; + } + const name = vertex + "+" + fragment + "@" + fullDefines; + if (this._compiledEffects[name]) { + const compiledEffect = this._compiledEffects[name]; + if (onCompiled && compiledEffect.isReady()) { + onCompiled(compiledEffect); + } + compiledEffect._refCount++; + return compiledEffect; + } + if (this._gl) { + getStateObject(this._gl); + } + const effect = new Effect(baseName, attributesNamesOrOptions, isOptions ? this : uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, attributesNamesOrOptions.shaderLanguage ?? shaderLanguage, attributesNamesOrOptions.extraInitializationsAsync ?? extraInitializationsAsync); + this._compiledEffects[name] = effect; + return effect; + } + /** + * @internal + */ + _getShaderSource(shader) { + return this._gl.getShaderSource(shader); + } + /** + * Directly creates a webGL program + * @param pipelineContext defines the pipeline context to attach to + * @param vertexCode defines the vertex shader code to use + * @param fragmentCode defines the fragment shader code to use + * @param context defines the webGL context to use (if not set, the current one will be used) + * @param transformFeedbackVaryings defines the list of transform feedback varyings to use + * @returns the new webGL program + */ + createRawShaderProgram(pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings = null) { + const stateObject = getStateObject(this._gl); + stateObject._contextWasLost = this._contextWasLost; + stateObject.validateShaderPrograms = this.validateShaderPrograms; + return createRawShaderProgram(pipelineContext, vertexCode, fragmentCode, context || this._gl, transformFeedbackVaryings); + } + /** + * Creates a webGL program + * @param pipelineContext defines the pipeline context to attach to + * @param vertexCode defines the vertex shader code to use + * @param fragmentCode defines the fragment shader code to use + * @param defines defines the string containing the defines to use to compile the shaders + * @param context defines the webGL context to use (if not set, the current one will be used) + * @param transformFeedbackVaryings defines the list of transform feedback varyings to use + * @returns the new webGL program + */ + createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) { + const stateObject = getStateObject(this._gl); + // assure the state object is correct + stateObject._contextWasLost = this._contextWasLost; + stateObject.validateShaderPrograms = this.validateShaderPrograms; + return createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context || this._gl, transformFeedbackVaryings); + } + /** + * Inline functions in shader code that are marked to be inlined + * @param code code to inline + * @returns inlined code + */ + inlineShaderCode(code) { + // no inlining needed in the WebGL engine + return code; + } + /** + * Creates a new pipeline context + * @param shaderProcessingContext defines the shader processing context used during the processing if available + * @returns the new pipeline + */ + createPipelineContext(shaderProcessingContext) { + if (this._gl) { + const stateObject = getStateObject(this._gl); + stateObject.parallelShaderCompile = this._caps.parallelShaderCompile; + } + const context = createPipelineContext(this._gl); + context.engine = this; + return context; + } + /** + * Creates a new material context + * @returns the new context + */ + createMaterialContext() { + return undefined; + } + /** + * Creates a new draw context + * @returns the new context + */ + createDrawContext() { + return undefined; + } + _finalizePipelineContext(pipelineContext) { + return _finalizePipelineContext(pipelineContext, this._gl, this.validateShaderPrograms); + } + /** + * @internal + */ + _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, rebuildRebind, defines, transformFeedbackVaryings, key, onReady) { + const stateObject = getStateObject(this._gl); + stateObject._contextWasLost = this._contextWasLost; + stateObject.validateShaderPrograms = this.validateShaderPrograms; + stateObject._createShaderProgramInjection = this._createShaderProgram.bind(this); + stateObject.createRawShaderProgramInjection = this.createRawShaderProgram.bind(this); + stateObject.createShaderProgramInjection = this.createShaderProgram.bind(this); + stateObject.loadFileInjection = this._loadFile.bind(this); + return _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, rebuildRebind, defines, transformFeedbackVaryings, key, onReady); + } + _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings = null) { + return _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings); + } + /** + * @internal + */ + _isRenderingStateCompiled(pipelineContext) { + if (this._isDisposed) { + return false; + } + return _isRenderingStateCompiled(pipelineContext, this._gl, this.validateShaderPrograms); + } + /** + * @internal + */ + _executeWhenRenderingStateIsCompiled(pipelineContext, action) { + _executeWhenRenderingStateIsCompiled(pipelineContext, action); + } + /** + * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names + * @param pipelineContext defines the pipeline context to use + * @param uniformsNames defines the list of uniform names + * @returns an array of webGL uniform locations + */ + getUniforms(pipelineContext, uniformsNames) { + const results = new Array(); + const webGLPipelineContext = pipelineContext; + for (let index = 0; index < uniformsNames.length; index++) { + results.push(this._gl.getUniformLocation(webGLPipelineContext.program, uniformsNames[index])); + } + return results; + } + /** + * Gets the list of active attributes for a given webGL program + * @param pipelineContext defines the pipeline context to use + * @param attributesNames defines the list of attribute names to get + * @returns an array of indices indicating the offset of each attribute + */ + getAttributes(pipelineContext, attributesNames) { + const results = []; + const webGLPipelineContext = pipelineContext; + for (let index = 0; index < attributesNames.length; index++) { + try { + results.push(this._gl.getAttribLocation(webGLPipelineContext.program, attributesNames[index])); + } + catch (e) { + results.push(-1); + } + } + return results; + } + /** + * Activates an effect, making it the current one (ie. the one used for rendering) + * @param effect defines the effect to activate + */ + enableEffect(effect) { + effect = effect !== null && IsWrapper(effect) ? effect.effect : effect; // get only the effect, we don't need a Wrapper in the WebGL engine + if (!effect || effect === this._currentEffect) { + return; + } + this._stencilStateComposer.stencilMaterial = undefined; + effect = effect; + // Use program + this.bindSamplers(effect); + this._currentEffect = effect; + if (effect.onBind) { + effect.onBind(effect); + } + if (effect._onBindObservable) { + effect._onBindObservable.notifyObservers(effect); + } + } + /** + * Set the value of an uniform to a number (int) + * @param uniform defines the webGL uniform location where to store the value + * @param value defines the int number to store + * @returns true if the value was set + */ + setInt(uniform, value) { + if (!uniform) { + return false; + } + this._gl.uniform1i(uniform, value); + return true; + } + /** + * Set the value of an uniform to a int2 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @returns true if the value was set + */ + setInt2(uniform, x, y) { + if (!uniform) { + return false; + } + this._gl.uniform2i(uniform, x, y); + return true; + } + /** + * Set the value of an uniform to a int3 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @param z defines the 3rd component of the value + * @returns true if the value was set + */ + setInt3(uniform, x, y, z) { + if (!uniform) { + return false; + } + this._gl.uniform3i(uniform, x, y, z); + return true; + } + /** + * Set the value of an uniform to a int4 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @param z defines the 3rd component of the value + * @param w defines the 4th component of the value + * @returns true if the value was set + */ + setInt4(uniform, x, y, z, w) { + if (!uniform) { + return false; + } + this._gl.uniform4i(uniform, x, y, z, w); + return true; + } + /** + * Set the value of an uniform to an array of int32 + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of int32 to store + * @returns true if the value was set + */ + setIntArray(uniform, array) { + if (!uniform) { + return false; + } + this._gl.uniform1iv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of int32 (stored as vec2) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of int32 to store + * @returns true if the value was set + */ + setIntArray2(uniform, array) { + if (!uniform || array.length % 2 !== 0) { + return false; + } + this._gl.uniform2iv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of int32 (stored as vec3) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of int32 to store + * @returns true if the value was set + */ + setIntArray3(uniform, array) { + if (!uniform || array.length % 3 !== 0) { + return false; + } + this._gl.uniform3iv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of int32 (stored as vec4) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of int32 to store + * @returns true if the value was set + */ + setIntArray4(uniform, array) { + if (!uniform || array.length % 4 !== 0) { + return false; + } + this._gl.uniform4iv(uniform, array); + return true; + } + /** + * Set the value of an uniform to a number (unsigned int) + * @param uniform defines the webGL uniform location where to store the value + * @param value defines the unsigned int number to store + * @returns true if the value was set + */ + setUInt(uniform, value) { + if (!uniform) { + return false; + } + this._gl.uniform1ui(uniform, value); + return true; + } + /** + * Set the value of an uniform to a unsigned int2 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @returns true if the value was set + */ + setUInt2(uniform, x, y) { + if (!uniform) { + return false; + } + this._gl.uniform2ui(uniform, x, y); + return true; + } + /** + * Set the value of an uniform to a unsigned int3 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @param z defines the 3rd component of the value + * @returns true if the value was set + */ + setUInt3(uniform, x, y, z) { + if (!uniform) { + return false; + } + this._gl.uniform3ui(uniform, x, y, z); + return true; + } + /** + * Set the value of an uniform to a unsigned int4 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @param z defines the 3rd component of the value + * @param w defines the 4th component of the value + * @returns true if the value was set + */ + setUInt4(uniform, x, y, z, w) { + if (!uniform) { + return false; + } + this._gl.uniform4ui(uniform, x, y, z, w); + return true; + } + /** + * Set the value of an uniform to an array of unsigned int32 + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of unsigned int32 to store + * @returns true if the value was set + */ + setUIntArray(uniform, array) { + if (!uniform) { + return false; + } + this._gl.uniform1uiv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of unsigned int32 (stored as vec2) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of unsigned int32 to store + * @returns true if the value was set + */ + setUIntArray2(uniform, array) { + if (!uniform || array.length % 2 !== 0) { + return false; + } + this._gl.uniform2uiv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of unsigned int32 (stored as vec3) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of unsigned int32 to store + * @returns true if the value was set + */ + setUIntArray3(uniform, array) { + if (!uniform || array.length % 3 !== 0) { + return false; + } + this._gl.uniform3uiv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of unsigned int32 (stored as vec4) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of unsigned int32 to store + * @returns true if the value was set + */ + setUIntArray4(uniform, array) { + if (!uniform || array.length % 4 !== 0) { + return false; + } + this._gl.uniform4uiv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of number + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of number to store + * @returns true if the value was set + */ + setArray(uniform, array) { + if (!uniform) { + return false; + } + if (array.length < 1) { + return false; + } + this._gl.uniform1fv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of number (stored as vec2) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of number to store + * @returns true if the value was set + */ + setArray2(uniform, array) { + if (!uniform || array.length % 2 !== 0) { + return false; + } + this._gl.uniform2fv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of number (stored as vec3) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of number to store + * @returns true if the value was set + */ + setArray3(uniform, array) { + if (!uniform || array.length % 3 !== 0) { + return false; + } + this._gl.uniform3fv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of number (stored as vec4) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of number to store + * @returns true if the value was set + */ + setArray4(uniform, array) { + if (!uniform || array.length % 4 !== 0) { + return false; + } + this._gl.uniform4fv(uniform, array); + return true; + } + /** + * Set the value of an uniform to an array of float32 (stored as matrices) + * @param uniform defines the webGL uniform location where to store the value + * @param matrices defines the array of float32 to store + * @returns true if the value was set + */ + setMatrices(uniform, matrices) { + if (!uniform) { + return false; + } + this._gl.uniformMatrix4fv(uniform, false, matrices); + return true; + } + /** + * Set the value of an uniform to a matrix (3x3) + * @param uniform defines the webGL uniform location where to store the value + * @param matrix defines the Float32Array representing the 3x3 matrix to store + * @returns true if the value was set + */ + setMatrix3x3(uniform, matrix) { + if (!uniform) { + return false; + } + this._gl.uniformMatrix3fv(uniform, false, matrix); + return true; + } + /** + * Set the value of an uniform to a matrix (2x2) + * @param uniform defines the webGL uniform location where to store the value + * @param matrix defines the Float32Array representing the 2x2 matrix to store + * @returns true if the value was set + */ + setMatrix2x2(uniform, matrix) { + if (!uniform) { + return false; + } + this._gl.uniformMatrix2fv(uniform, false, matrix); + return true; + } + /** + * Set the value of an uniform to a number (float) + * @param uniform defines the webGL uniform location where to store the value + * @param value defines the float number to store + * @returns true if the value was transferred + */ + setFloat(uniform, value) { + if (!uniform) { + return false; + } + this._gl.uniform1f(uniform, value); + return true; + } + /** + * Set the value of an uniform to a vec2 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @returns true if the value was set + */ + setFloat2(uniform, x, y) { + if (!uniform) { + return false; + } + this._gl.uniform2f(uniform, x, y); + return true; + } + /** + * Set the value of an uniform to a vec3 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @param z defines the 3rd component of the value + * @returns true if the value was set + */ + setFloat3(uniform, x, y, z) { + if (!uniform) { + return false; + } + this._gl.uniform3f(uniform, x, y, z); + return true; + } + /** + * Set the value of an uniform to a vec4 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @param z defines the 3rd component of the value + * @param w defines the 4th component of the value + * @returns true if the value was set + */ + setFloat4(uniform, x, y, z, w) { + if (!uniform) { + return false; + } + this._gl.uniform4f(uniform, x, y, z, w); + return true; + } + // States + /** + * Apply all cached states (depth, culling, stencil and alpha) + */ + applyStates() { + this._depthCullingState.apply(this._gl); + this._stencilStateComposer.apply(this._gl); + this._alphaState.apply(this._gl); + if (this._colorWriteChanged) { + this._colorWriteChanged = false; + const enable = this._colorWrite; + this._gl.colorMask(enable, enable, enable, enable); + } + } + // Textures + /** + * Force the entire cache to be cleared + * You should not have to use this function unless your engine needs to share the webGL context with another engine + * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states) + */ + wipeCaches(bruteForce) { + if (this.preventCacheWipeBetweenFrames && !bruteForce) { + return; + } + this._currentEffect = null; + this._viewportCached.x = 0; + this._viewportCached.y = 0; + this._viewportCached.z = 0; + this._viewportCached.w = 0; + // Done before in case we clean the attributes + this._unbindVertexArrayObject(); + if (bruteForce) { + this._currentProgram = null; + this.resetTextureCache(); + this._stencilStateComposer.reset(); + this._depthCullingState.reset(); + this._depthCullingState.depthFunc = this._gl.LEQUAL; + this._alphaState.reset(); + this._alphaMode = 1; + this._alphaEquation = 0; + this._colorWrite = true; + this._colorWriteChanged = true; + this._unpackFlipYCached = null; + this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE); + this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); + this._mustWipeVertexAttributes = true; + this.unbindAllAttributes(); + } + this._resetVertexBufferBinding(); + this._cachedIndexBuffer = null; + this._cachedEffectForVertexBuffers = null; + this.bindIndexBuffer(null); + } + /** + * @internal + */ + _getSamplingParameters(samplingMode, generateMipMaps) { + const gl = this._gl; + let magFilter = gl.NEAREST; + let minFilter = gl.NEAREST; + switch (samplingMode) { + case 11: + magFilter = gl.LINEAR; + if (generateMipMaps) { + minFilter = gl.LINEAR_MIPMAP_NEAREST; + } + else { + minFilter = gl.LINEAR; + } + break; + case 3: + magFilter = gl.LINEAR; + if (generateMipMaps) { + minFilter = gl.LINEAR_MIPMAP_LINEAR; + } + else { + minFilter = gl.LINEAR; + } + break; + case 8: + magFilter = gl.NEAREST; + if (generateMipMaps) { + minFilter = gl.NEAREST_MIPMAP_LINEAR; + } + else { + minFilter = gl.NEAREST; + } + break; + case 4: + magFilter = gl.NEAREST; + if (generateMipMaps) { + minFilter = gl.NEAREST_MIPMAP_NEAREST; + } + else { + minFilter = gl.NEAREST; + } + break; + case 5: + magFilter = gl.NEAREST; + if (generateMipMaps) { + minFilter = gl.LINEAR_MIPMAP_NEAREST; + } + else { + minFilter = gl.LINEAR; + } + break; + case 6: + magFilter = gl.NEAREST; + if (generateMipMaps) { + minFilter = gl.LINEAR_MIPMAP_LINEAR; + } + else { + minFilter = gl.LINEAR; + } + break; + case 7: + magFilter = gl.NEAREST; + minFilter = gl.LINEAR; + break; + case 1: + magFilter = gl.NEAREST; + minFilter = gl.NEAREST; + break; + case 9: + magFilter = gl.LINEAR; + if (generateMipMaps) { + minFilter = gl.NEAREST_MIPMAP_NEAREST; + } + else { + minFilter = gl.NEAREST; + } + break; + case 10: + magFilter = gl.LINEAR; + if (generateMipMaps) { + minFilter = gl.NEAREST_MIPMAP_LINEAR; + } + else { + minFilter = gl.NEAREST; + } + break; + case 2: + magFilter = gl.LINEAR; + minFilter = gl.LINEAR; + break; + case 12: + magFilter = gl.LINEAR; + minFilter = gl.NEAREST; + break; + } + return { + min: minFilter, + mag: magFilter, + }; + } + /** @internal */ + _createTexture() { + const texture = this._gl.createTexture(); + if (!texture) { + throw new Error("Unable to create texture"); + } + return texture; + } + /** @internal */ + _createHardwareTexture() { + return new WebGLHardwareTexture(this._createTexture(), this._gl); + } + /** + * Creates an internal texture without binding it to a framebuffer + * @internal + * @param size defines the size of the texture + * @param options defines the options used to create the texture + * @param delayGPUTextureCreation true to delay the texture creation the first time it is really needed. false to create it right away + * @param source source type of the texture + * @returns a new internal texture + */ + _createInternalTexture(size, options, delayGPUTextureCreation = true, source = 0 /* InternalTextureSource.Unknown */) { + let generateMipMaps = false; + let createMipMaps = false; + let type = 0; + let samplingMode = 3; + let format = 5; + let useSRGBBuffer = false; + let samples = 1; + let label; + let createMSAATexture = false; + let comparisonFunction = 0; + if (options !== undefined && typeof options === "object") { + generateMipMaps = !!options.generateMipMaps; + createMipMaps = !!options.createMipMaps; + type = options.type === undefined ? 0 : options.type; + samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode; + format = options.format === undefined ? 5 : options.format; + useSRGBBuffer = options.useSRGBBuffer === undefined ? false : options.useSRGBBuffer; + samples = options.samples ?? 1; + label = options.label; + createMSAATexture = !!options.createMSAATexture; + comparisonFunction = options.comparisonFunction || 0; + } + else { + generateMipMaps = !!options; + } + useSRGBBuffer && (useSRGBBuffer = this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU)); + if (type === 1 && !this._caps.textureFloatLinearFiltering) { + // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE + samplingMode = 1; + } + else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { + // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE + samplingMode = 1; + } + if (type === 1 && !this._caps.textureFloat) { + type = 0; + Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"); + } + const isDepthTexture = IsDepthTexture(format); + const hasStencil = HasStencilAspect(format); + const gl = this._gl; + const texture = new InternalTexture(this, source); + const width = size.width || size; + const height = size.height || size; + const depth = size.depth || 0; + const layers = size.layers || 0; + const filters = this._getSamplingParameters(samplingMode, (generateMipMaps || createMipMaps) && !isDepthTexture); + const target = layers !== 0 ? gl.TEXTURE_2D_ARRAY : depth !== 0 ? gl.TEXTURE_3D : gl.TEXTURE_2D; + const sizedFormat = isDepthTexture + ? this._getInternalFormatFromDepthTextureFormat(format, true, hasStencil) + : this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer); + const internalFormat = isDepthTexture ? (hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT) : this._getInternalFormat(format); + const textureType = isDepthTexture ? this._getWebGLTextureTypeFromDepthTextureFormat(format) : this._getWebGLTextureType(type); + // Bind + this._bindTextureDirectly(target, texture); + if (layers !== 0) { + texture.is2DArray = true; + gl.texImage3D(target, 0, sizedFormat, width, height, layers, 0, internalFormat, textureType, null); + } + else if (depth !== 0) { + texture.is3D = true; + gl.texImage3D(target, 0, sizedFormat, width, height, depth, 0, internalFormat, textureType, null); + } + else { + gl.texImage2D(target, 0, sizedFormat, width, height, 0, internalFormat, textureType, null); + } + gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filters.mag); + gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filters.min); + gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + if (isDepthTexture && this.webGLVersion > 1) { + if (comparisonFunction === 0) { + gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, 515); + gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE); + } + else { + gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction); + gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE); + } + } + // MipMaps + if (generateMipMaps || createMipMaps) { + this._gl.generateMipmap(target); + } + this._bindTextureDirectly(target, null); + texture._useSRGBBuffer = useSRGBBuffer; + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.depth = layers || depth; + texture.isReady = true; + texture.samples = samples; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.type = type; + texture.format = format; + texture.label = label; + texture.comparisonFunction = comparisonFunction; + this._internalTexturesCache.push(texture); + if (createMSAATexture) { + let renderBuffer = null; + if (IsDepthTexture(texture.format)) { + renderBuffer = this._setupFramebufferDepthAttachments(HasStencilAspect(texture.format), texture.format !== 19, texture.width, texture.height, samples, texture.format, true); + } + else { + renderBuffer = this._createRenderBuffer(texture.width, texture.height, samples, -1 /* not used */, this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer), -1 /* attachment */); + } + if (!renderBuffer) { + throw new Error("Unable to create render buffer"); + } + texture._autoMSAAManagement = true; + let hardwareTexture = texture._hardwareTexture; + if (!hardwareTexture) { + hardwareTexture = texture._hardwareTexture = this._createHardwareTexture(); + } + hardwareTexture.addMSAARenderBuffer(renderBuffer); + } + return texture; + } + /** + * @internal + */ + _getUseSRGBBuffer(useSRGBBuffer, noMipmap) { + // Generating mipmaps for sRGB textures is not supported in WebGL1 so we must disable the support if mipmaps is enabled + return useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || noMipmap); + } + /** + * Usually called from Texture.ts. + * Passed information to create a WebGLTexture + * @param url defines a value which contains one of the following: + * * A conventional http URL, e.g. 'http://...' or 'file://...' + * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...' + * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg' + * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file + * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx) + * @param scene needed for loading to the correct scene + * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE) + * @param onLoad optional callback to be called upon successful completion + * @param onError optional callback to be called upon failure + * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob + * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities + * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures + * @param forcedExtension defines the extension to use to pick the right loader + * @param mimeType defines an optional mime type + * @param loaderOptions options to be passed to the loader + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). + * @returns a InternalTexture for assignment back into BABYLON.Texture + */ + createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer) { + return this._createTextureBase(url, noMipmap, invertY, scene, samplingMode, onLoad, onError, (...args) => this._prepareWebGLTexture(...args, format), (potWidth, potHeight, img, extension, texture, continuationCallback) => { + const gl = this._gl; + const isPot = img.width === potWidth && img.height === potHeight; + texture._creationFlags = creationFlags ?? 0; + const tip = this._getTexImageParametersForCreateTexture(texture.format, texture._useSRGBBuffer); + if (isPot) { + gl.texImage2D(gl.TEXTURE_2D, 0, tip.internalFormat, tip.format, tip.type, img); + return false; + } + const maxTextureSize = this._caps.maxTextureSize; + if (img.width > maxTextureSize || img.height > maxTextureSize || !this._supportsHardwareTextureRescaling) { + this._prepareWorkingCanvas(); + if (!this._workingCanvas || !this._workingContext) { + return false; + } + this._workingCanvas.width = potWidth; + this._workingCanvas.height = potHeight; + this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight); + gl.texImage2D(gl.TEXTURE_2D, 0, tip.internalFormat, tip.format, tip.type, this._workingCanvas); + texture.width = potWidth; + texture.height = potHeight; + return false; + } + else { + // Using shaders when possible to rescale because canvas.drawImage is lossy + const source = new InternalTexture(this, 2 /* InternalTextureSource.Temp */); + this._bindTextureDirectly(gl.TEXTURE_2D, source, true); + gl.texImage2D(gl.TEXTURE_2D, 0, tip.internalFormat, tip.format, tip.type, img); + this._rescaleTexture(source, texture, scene, tip.format, () => { + this._releaseTexture(source); + this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); + continuationCallback(); + }); + } + return true; + }, buffer, fallback, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer); + } + /** + * Calls to the GL texImage2D and texImage3D functions require three arguments describing the pixel format of the texture. + * createTexture derives these from the babylonFormat and useSRGBBuffer arguments and also the file extension of the URL it's working with. + * This function encapsulates that derivation for easy unit testing. + * @param babylonFormat Babylon's format enum, as specified in ITextureCreationOptions. + * @param fileExtension The file extension including the dot, e.g. .jpg. + * @param useSRGBBuffer Use SRGB not linear. + * @returns The options to pass to texImage2D or texImage3D calls. + * @internal + */ + _getTexImageParametersForCreateTexture(babylonFormat, useSRGBBuffer) { + let format, internalFormat; + if (this.webGLVersion === 1) { + // In WebGL 1, format and internalFormat must be the same and taken from a limited set of values, see https://docs.gl/es2/glTexImage2D. + // The SRGB extension (https://developer.mozilla.org/en-US/docs/Web/API/EXT_sRGB) adds some extra values, hence passing useSRGBBuffer + // to getInternalFormat. + format = this._getInternalFormat(babylonFormat, useSRGBBuffer); + internalFormat = format; + } + else { + // In WebGL 2, format has a wider range of values and internal format can be one of the sized formats, see + // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml. + // SRGB is included in the sized format and should not be passed in "format", hence always passing useSRGBBuffer as false. + format = this._getInternalFormat(babylonFormat, false); + internalFormat = this._getRGBABufferInternalSizedFormat(0, babylonFormat, useSRGBBuffer); + } + return { + internalFormat, + format, + type: this._gl.UNSIGNED_BYTE, + }; + } + /** + * @internal + */ + _rescaleTexture(source, destination, scene, internalFormat, onComplete) { } + /** + * @internal + */ + _unpackFlipY(value) { + if (this._unpackFlipYCached !== value) { + this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0); + if (this.enableUnpackFlipYCached) { + this._unpackFlipYCached = value; + } + } + } + /** @internal */ + _getUnpackAlignement() { + return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT); + } + /** @internal */ + _getTextureTarget(texture) { + if (texture.isCube) { + return this._gl.TEXTURE_CUBE_MAP; + } + else if (texture.is3D) { + return this._gl.TEXTURE_3D; + } + else if (texture.is2DArray || texture.isMultiview) { + return this._gl.TEXTURE_2D_ARRAY; + } + return this._gl.TEXTURE_2D; + } + /** + * Update the sampling mode of a given texture + * @param samplingMode defines the required sampling mode + * @param texture defines the texture to update + * @param generateMipMaps defines whether to generate mipmaps for the texture + */ + updateTextureSamplingMode(samplingMode, texture, generateMipMaps = false) { + const target = this._getTextureTarget(texture); + const filters = this._getSamplingParameters(samplingMode, texture.useMipMaps || generateMipMaps); + this._setTextureParameterInteger(target, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture); + this._setTextureParameterInteger(target, this._gl.TEXTURE_MIN_FILTER, filters.min); + if (generateMipMaps) { + texture.generateMipMaps = true; + this._gl.generateMipmap(target); + } + this._bindTextureDirectly(target, null); + texture.samplingMode = samplingMode; + } + /** + * Update the dimensions of a texture + * @param texture texture to update + * @param width new width of the texture + * @param height new height of the texture + * @param depth new depth of the texture + */ + updateTextureDimensions(texture, width, height, depth = 1) { } + /** + * Update the sampling mode of a given texture + * @param texture defines the texture to update + * @param wrapU defines the texture wrap mode of the u coordinates + * @param wrapV defines the texture wrap mode of the v coordinates + * @param wrapR defines the texture wrap mode of the r coordinates + */ + updateTextureWrappingMode(texture, wrapU, wrapV = null, wrapR = null) { + const target = this._getTextureTarget(texture); + if (wrapU !== null) { + this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(wrapU), texture); + texture._cachedWrapU = wrapU; + } + if (wrapV !== null) { + this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(wrapV), texture); + texture._cachedWrapV = wrapV; + } + if ((texture.is2DArray || texture.is3D) && wrapR !== null) { + this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(wrapR), texture); + texture._cachedWrapR = wrapR; + } + this._bindTextureDirectly(target, null); + } + /** + * @internal + */ + _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) { + const gl = this._gl; + let target = gl.TEXTURE_2D; + if (texture.isCube) { + target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; + } + if (texture._useSRGBBuffer) { + switch (internalFormat) { + case 37492: + case 36196: + // Note, if using ETC1 and sRGB is requested, this will use ETC2 if available. + if (this._caps.etc2) { + internalFormat = gl.COMPRESSED_SRGB8_ETC2; + } + else { + texture._useSRGBBuffer = false; + } + break; + case 37496: + if (this._caps.etc2) { + internalFormat = gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; + } + else { + texture._useSRGBBuffer = false; + } + break; + case 36492: + internalFormat = gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT; + break; + case 37808: + internalFormat = gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; + break; + case 33776: + if (this._caps.s3tc_srgb) { + internalFormat = gl.COMPRESSED_SRGB_S3TC_DXT1_EXT; + } + else { + // S3TC sRGB extension not supported + texture._useSRGBBuffer = false; + } + break; + case 33777: + if (this._caps.s3tc_srgb) { + internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + } + else { + // S3TC sRGB extension not supported + texture._useSRGBBuffer = false; + } + break; + case 33779: + if (this._caps.s3tc_srgb) { + internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } + else { + // S3TC sRGB extension not supported + texture._useSRGBBuffer = false; + } + break; + default: + // We don't support a sRGB format corresponding to internalFormat, so revert to non sRGB format + texture._useSRGBBuffer = false; + break; + } + } + this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data); + } + /** + * @internal + */ + _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0, babylonInternalFormat, useTextureWidthAndHeight = false) { + const gl = this._gl; + const textureType = this._getWebGLTextureType(texture.type); + const format = this._getInternalFormat(texture.format); + const internalFormat = babylonInternalFormat === undefined + ? this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer) + : this._getInternalFormat(babylonInternalFormat, texture._useSRGBBuffer); + this._unpackFlipY(texture.invertY); + let target = gl.TEXTURE_2D; + if (texture.isCube) { + target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; + } + const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E); + const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E); + const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0)); + const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0)); + gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData); + } + /** + * Update a portion of an internal texture + * @param texture defines the texture to update + * @param imageData defines the data to store into the texture + * @param xOffset defines the x coordinates of the update rectangle + * @param yOffset defines the y coordinates of the update rectangle + * @param width defines the width of the update rectangle + * @param height defines the height of the update rectangle + * @param faceIndex defines the face index if texture is a cube (0 by default) + * @param lod defines the lod level to update (0 by default) + * @param generateMipMaps defines whether to generate mipmaps or not + */ + updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) { + const gl = this._gl; + const textureType = this._getWebGLTextureType(texture.type); + const format = this._getInternalFormat(texture.format); + this._unpackFlipY(texture.invertY); + let targetForBinding = gl.TEXTURE_2D; + let target = gl.TEXTURE_2D; + if (texture.isCube) { + target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; + targetForBinding = gl.TEXTURE_CUBE_MAP; + } + this._bindTextureDirectly(targetForBinding, texture, true); + gl.texSubImage2D(target, lod, xOffset, yOffset, width, height, format, textureType, imageData); + if (generateMipMaps) { + this._gl.generateMipmap(target); + } + this._bindTextureDirectly(targetForBinding, null); + } + /** + * @internal + */ + _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) { + const gl = this._gl; + const bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; + this._bindTextureDirectly(bindTarget, texture, true); + this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod); + this._bindTextureDirectly(bindTarget, null, true); + } + _prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode) { + const gl = this._gl; + if (!gl) { + return; + } + const filters = this._getSamplingParameters(samplingMode, !noMipmap); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min); + if (!noMipmap && !isCompressed) { + gl.generateMipmap(gl.TEXTURE_2D); + } + this._bindTextureDirectly(gl.TEXTURE_2D, null); + // this.resetTextureCache(); + if (scene) { + scene.removePendingData(texture); + } + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + } + _prepareWebGLTexture(texture, extension, scene, img, invertY, noMipmap, isCompressed, processFunction, samplingMode, format) { + const maxTextureSize = this.getCaps().maxTextureSize; + const potWidth = Math.min(maxTextureSize, this.needPOTTextures ? GetExponentOfTwo(img.width, maxTextureSize) : img.width); + const potHeight = Math.min(maxTextureSize, this.needPOTTextures ? GetExponentOfTwo(img.height, maxTextureSize) : img.height); + const gl = this._gl; + if (!gl) { + return; + } + if (!texture._hardwareTexture) { + // this.resetTextureCache(); + if (scene) { + scene.removePendingData(texture); + } + return; + } + this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); + this._unpackFlipY(invertY === undefined ? true : invertY ? true : false); + texture.baseWidth = img.width; + texture.baseHeight = img.height; + texture.width = potWidth; + texture.height = potHeight; + texture.isReady = true; + texture.type = texture.type !== -1 ? texture.type : 0; + texture.format = + texture.format !== -1 ? texture.format : (format ?? (extension === ".jpg" && !texture._useSRGBBuffer ? 4 : 5)); + if (processFunction(potWidth, potHeight, img, extension, texture, () => { + this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); + })) { + // Returning as texture needs extra async steps + return; + } + this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); + } + _getInternalFormatFromDepthTextureFormat(textureFormat, hasDepth, hasStencil) { + const gl = this._gl; + if (!hasDepth) { + return gl.STENCIL_INDEX8; + } + const format = hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT; + let internalFormat = format; + if (this.webGLVersion > 1) { + if (textureFormat === 15) { + internalFormat = gl.DEPTH_COMPONENT16; + } + else if (textureFormat === 16) { + internalFormat = gl.DEPTH_COMPONENT24; + } + else if (textureFormat === 17 || textureFormat === 13) { + internalFormat = hasStencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + } + else if (textureFormat === 14) { + internalFormat = gl.DEPTH_COMPONENT32F; + } + else if (textureFormat === 18) { + internalFormat = hasStencil ? gl.DEPTH32F_STENCIL8 : gl.DEPTH_COMPONENT32F; + } + } + else { + internalFormat = gl.DEPTH_COMPONENT16; + } + return internalFormat; + } + _getWebGLTextureTypeFromDepthTextureFormat(textureFormat) { + const gl = this._gl; + let type = gl.UNSIGNED_INT; + if (textureFormat === 15) { + type = gl.UNSIGNED_SHORT; + } + else if (textureFormat === 17 || textureFormat === 13) { + type = gl.UNSIGNED_INT_24_8; + } + else if (textureFormat === 14) { + type = gl.FLOAT; + } + else if (textureFormat === 18) { + type = gl.FLOAT_32_UNSIGNED_INT_24_8_REV; + } + else if (textureFormat === 19) { + type = gl.UNSIGNED_BYTE; + } + return type; + } + /** + * @internal + */ + _setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height, samples = 1, depthTextureFormat, dontBindRenderBufferToFrameBuffer = false) { + const gl = this._gl; + depthTextureFormat = depthTextureFormat ?? (generateStencilBuffer ? 13 : 14); + const internalFormat = this._getInternalFormatFromDepthTextureFormat(depthTextureFormat, generateDepthBuffer, generateStencilBuffer); + // Create the depth/stencil buffer + if (generateStencilBuffer && generateDepthBuffer) { + return this._createRenderBuffer(width, height, samples, gl.DEPTH_STENCIL, internalFormat, dontBindRenderBufferToFrameBuffer ? -1 : gl.DEPTH_STENCIL_ATTACHMENT); + } + if (generateDepthBuffer) { + return this._createRenderBuffer(width, height, samples, internalFormat, internalFormat, dontBindRenderBufferToFrameBuffer ? -1 : gl.DEPTH_ATTACHMENT); + } + if (generateStencilBuffer) { + return this._createRenderBuffer(width, height, samples, internalFormat, internalFormat, dontBindRenderBufferToFrameBuffer ? -1 : gl.STENCIL_ATTACHMENT); + } + return null; + } + /** + * @internal + */ + _createRenderBuffer(width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer = true) { + const gl = this._gl; + const renderBuffer = gl.createRenderbuffer(); + return this._updateRenderBuffer(renderBuffer, width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer); + } + _updateRenderBuffer(renderBuffer, width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer = true) { + const gl = this._gl; + gl.bindRenderbuffer(gl.RENDERBUFFER, renderBuffer); + if (samples > 1 && gl.renderbufferStorageMultisample) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, msInternalFormat, width, height); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, width, height); + } + if (attachment !== -1) { + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, renderBuffer); + } + if (unbindBuffer) { + gl.bindRenderbuffer(gl.RENDERBUFFER, null); + } + return renderBuffer; + } + /** + * @internal + */ + _releaseTexture(texture) { + this._deleteTexture(texture._hardwareTexture); + // Unbind channels + this.unbindAllTextures(); + const index = this._internalTexturesCache.indexOf(texture); + if (index !== -1) { + this._internalTexturesCache.splice(index, 1); + } + // Integrated fixed lod samplers. + if (texture._lodTextureHigh) { + texture._lodTextureHigh.dispose(); + } + if (texture._lodTextureMid) { + texture._lodTextureMid.dispose(); + } + if (texture._lodTextureLow) { + texture._lodTextureLow.dispose(); + } + // Integrated irradiance map. + if (texture._irradianceTexture) { + texture._irradianceTexture.dispose(); + } + } + _deleteTexture(texture) { + texture?.release(); + } + _setProgram(program) { + if (this._currentProgram !== program) { + _setProgram(program, this._gl); + this._currentProgram = program; + } + } + /** + * Binds an effect to the webGL context + * @param effect defines the effect to bind + */ + bindSamplers(effect) { + const webGLPipelineContext = effect.getPipelineContext(); + this._setProgram(webGLPipelineContext.program); + const samplers = effect.getSamplers(); + for (let index = 0; index < samplers.length; index++) { + const uniform = effect.getUniform(samplers[index]); + if (uniform) { + this._boundUniforms[index] = uniform; + } + } + this._currentEffect = null; + } + _activateCurrentTexture() { + if (this._currentTextureChannel !== this._activeChannel) { + this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel); + this._currentTextureChannel = this._activeChannel; + } + } + /** + * @internal + */ + _bindTextureDirectly(target, texture, forTextureDataUpdate = false, force = false) { + let wasPreviouslyBound = false; + const isTextureForRendering = texture && texture._associatedChannel > -1; + if (forTextureDataUpdate && isTextureForRendering) { + this._activeChannel = texture._associatedChannel; + } + const currentTextureBound = this._boundTexturesCache[this._activeChannel]; + if (currentTextureBound !== texture || force) { + this._activateCurrentTexture(); + if (texture && texture.isMultiview) { + //this._gl.bindTexture(target, texture ? texture._colorTextureArray : null); + Logger.Error(["_bindTextureDirectly called with a multiview texture!", target, texture]); + // eslint-disable-next-line no-throw-literal + throw "_bindTextureDirectly called with a multiview texture!"; + } + else { + this._gl.bindTexture(target, texture?._hardwareTexture?.underlyingResource ?? null); + } + this._boundTexturesCache[this._activeChannel] = texture; + if (texture) { + texture._associatedChannel = this._activeChannel; + } + } + else if (forTextureDataUpdate) { + wasPreviouslyBound = true; + this._activateCurrentTexture(); + } + if (isTextureForRendering && !forTextureDataUpdate) { + this._bindSamplerUniformToChannel(texture._associatedChannel, this._activeChannel); + } + return wasPreviouslyBound; + } + /** + * @internal + */ + _bindTexture(channel, texture, name) { + if (channel === undefined) { + return; + } + if (texture) { + texture._associatedChannel = channel; + } + this._activeChannel = channel; + const target = texture ? this._getTextureTarget(texture) : this._gl.TEXTURE_2D; + this._bindTextureDirectly(target, texture); + } + /** + * Unbind all textures from the webGL context + */ + unbindAllTextures() { + for (let channel = 0; channel < this._maxSimultaneousTextures; channel++) { + this._activeChannel = channel; + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); + if (this.webGLVersion > 1) { + this._bindTextureDirectly(this._gl.TEXTURE_3D, null); + this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null); + } + } + } + /** + * Sets a texture to the according uniform. + * @param channel The texture channel + * @param uniform The uniform to set + * @param texture The texture to apply + * @param name The name of the uniform in the effect + */ + setTexture(channel, uniform, texture, name) { + if (channel === undefined) { + return; + } + if (uniform) { + this._boundUniforms[channel] = uniform; + } + this._setTexture(channel, texture); + } + _bindSamplerUniformToChannel(sourceSlot, destination) { + const uniform = this._boundUniforms[sourceSlot]; + if (!uniform || uniform._currentState === destination) { + return; + } + this._gl.uniform1i(uniform, destination); + uniform._currentState = destination; + } + _getTextureWrapMode(mode) { + switch (mode) { + case 1: + return this._gl.REPEAT; + case 0: + return this._gl.CLAMP_TO_EDGE; + case 2: + return this._gl.MIRRORED_REPEAT; + } + return this._gl.REPEAT; + } + _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false, name = "") { + // Not ready? + if (!texture) { + if (this._boundTexturesCache[channel] != null) { + this._activeChannel = channel; + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); + if (this.webGLVersion > 1) { + this._bindTextureDirectly(this._gl.TEXTURE_3D, null); + this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null); + } + } + return false; + } + // Video + if (texture.video) { + this._activeChannel = channel; + const videoInternalTexture = texture.getInternalTexture(); + if (videoInternalTexture) { + videoInternalTexture._associatedChannel = channel; + } + texture.update(); + } + else if (texture.delayLoadState === 4) { + // Delay loading + texture.delayLoad(); + return false; + } + let internalTexture; + if (depthStencilTexture) { + internalTexture = texture.depthStencilTexture; + } + else if (texture.isReady()) { + internalTexture = texture.getInternalTexture(); + } + else if (texture.isCube) { + internalTexture = this.emptyCubeTexture; + } + else if (texture.is3D) { + internalTexture = this.emptyTexture3D; + } + else if (texture.is2DArray) { + internalTexture = this.emptyTexture2DArray; + } + else { + internalTexture = this.emptyTexture; + } + if (!isPartOfTextureArray && internalTexture) { + internalTexture._associatedChannel = channel; + } + let needToBind = true; + if (this._boundTexturesCache[channel] === internalTexture) { + if (!isPartOfTextureArray) { + this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel); + } + needToBind = false; + } + this._activeChannel = channel; + const target = this._getTextureTarget(internalTexture); + if (needToBind) { + this._bindTextureDirectly(target, internalTexture, isPartOfTextureArray); + } + if (internalTexture && !internalTexture.isMultiview) { + // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT. + if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) { + internalTexture._cachedCoordinatesMode = texture.coordinatesMode; + const textureWrapMode = texture.coordinatesMode !== 3 && texture.coordinatesMode !== 5 + ? 1 + : 0; + texture.wrapU = textureWrapMode; + texture.wrapV = textureWrapMode; + } + if (internalTexture._cachedWrapU !== texture.wrapU) { + internalTexture._cachedWrapU = texture.wrapU; + this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture); + } + if (internalTexture._cachedWrapV !== texture.wrapV) { + internalTexture._cachedWrapV = texture.wrapV; + this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture); + } + if (internalTexture.is3D && internalTexture._cachedWrapR !== texture.wrapR) { + internalTexture._cachedWrapR = texture.wrapR; + this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture); + } + this._setAnisotropicLevel(target, internalTexture, texture.anisotropicFilteringLevel); + } + return true; + } + /** + * Sets an array of texture to the webGL context + * @param channel defines the channel where the texture array must be set + * @param uniform defines the associated uniform location + * @param textures defines the array of textures to bind + * @param name name of the channel + */ + setTextureArray(channel, uniform, textures, name) { + if (channel === undefined || !uniform) { + return; + } + if (!this._textureUnits || this._textureUnits.length !== textures.length) { + this._textureUnits = new Int32Array(textures.length); + } + for (let i = 0; i < textures.length; i++) { + const texture = textures[i].getInternalTexture(); + if (texture) { + this._textureUnits[i] = channel + i; + texture._associatedChannel = channel + i; + } + else { + this._textureUnits[i] = -1; + } + } + this._gl.uniform1iv(uniform, this._textureUnits); + for (let index = 0; index < textures.length; index++) { + this._setTexture(this._textureUnits[index], textures[index], true); + } + } + /** + * @internal + */ + _setAnisotropicLevel(target, internalTexture, anisotropicFilteringLevel) { + const anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension; + if (internalTexture.samplingMode !== 11 && + internalTexture.samplingMode !== 3 && + internalTexture.samplingMode !== 2) { + anisotropicFilteringLevel = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear + } + if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) { + this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy), internalTexture); + internalTexture._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel; + } + } + _setTextureParameterFloat(target, parameter, value, texture) { + this._bindTextureDirectly(target, texture, true, true); + this._gl.texParameterf(target, parameter, value); + } + _setTextureParameterInteger(target, parameter, value, texture) { + if (texture) { + this._bindTextureDirectly(target, texture, true, true); + } + this._gl.texParameteri(target, parameter, value); + } + /** + * Unbind all vertex attributes from the webGL context + */ + unbindAllAttributes() { + if (this._mustWipeVertexAttributes) { + this._mustWipeVertexAttributes = false; + for (let i = 0; i < this._caps.maxVertexAttribs; i++) { + this.disableAttributeByIndex(i); + } + return; + } + for (let i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) { + if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) { + continue; + } + this.disableAttributeByIndex(i); + } + } + /** + * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled + */ + releaseEffects() { + this._compiledEffects = {}; + this.onReleaseEffectsObservable.notifyObservers(this); + } + /** + * Dispose and release all associated resources + */ + dispose() { + // Events + if (IsWindowObjectExist()) { + if (this._renderingCanvas) { + this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost); + if (this._onContextRestored) { + this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored); + } + } + } + // Should not be moved up of renderingCanvas will be null. + super.dispose(); + if (this._dummyFramebuffer) { + this._gl.deleteFramebuffer(this._dummyFramebuffer); + } + // Unbind + this.unbindAllAttributes(); + this._boundUniforms = {}; + this._workingCanvas = null; + this._workingContext = null; + this._currentBufferPointers.length = 0; + this._currentProgram = null; + if (this._creationOptions.loseContextOnDispose) { + this._gl.getExtension("WEBGL_lose_context")?.loseContext(); + } + // clear the state object + deleteStateObject(this._gl); + } + /** + * Attach a new callback raised when context lost event is fired + * @param callback defines the callback to call + */ + attachContextLostEvent(callback) { + if (this._renderingCanvas) { + this._renderingCanvas.addEventListener("webglcontextlost", callback, false); + } + } + /** + * Attach a new callback raised when context restored event is fired + * @param callback defines the callback to call + */ + attachContextRestoredEvent(callback) { + if (this._renderingCanvas) { + this._renderingCanvas.addEventListener("webglcontextrestored", callback, false); + } + } + /** + * Get the current error code of the webGL context + * @returns the error code + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError + */ + getError() { + return this._gl.getError(); + } + _canRenderToFloatFramebuffer() { + if (this._webGLVersion > 1) { + return this._caps.colorBufferFloat; + } + return this._canRenderToFramebuffer(1); + } + _canRenderToHalfFloatFramebuffer() { + if (this._webGLVersion > 1) { + return this._caps.colorBufferFloat; + } + return this._canRenderToFramebuffer(2); + } + // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture + _canRenderToFramebuffer(type) { + const gl = this._gl; + //clear existing errors + // eslint-disable-next-line no-empty + while (gl.getError() !== gl.NO_ERROR) { } + let successful = true; + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + const fb = gl.createFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, fb); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); + const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + successful = successful && status === gl.FRAMEBUFFER_COMPLETE; + successful = successful && gl.getError() === gl.NO_ERROR; + //try render by clearing frame buffer's color buffer + if (successful) { + gl.clear(gl.COLOR_BUFFER_BIT); + successful = successful && gl.getError() === gl.NO_ERROR; + } + //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported) + if (successful) { + //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + const readFormat = gl.RGBA; + const readType = gl.UNSIGNED_BYTE; + const buffer = new Uint8Array(4); + gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer); + successful = successful && gl.getError() === gl.NO_ERROR; + } + //clean up + gl.deleteTexture(texture); + gl.deleteFramebuffer(fb); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + //clear accumulated errors + // eslint-disable-next-line no-empty + while (!successful && gl.getError() !== gl.NO_ERROR) { } + return successful; + } + /** + * @internal + */ + _getWebGLTextureType(type) { + if (this._webGLVersion === 1) { + switch (type) { + case 1: + return this._gl.FLOAT; + case 2: + return this._gl.HALF_FLOAT_OES; + case 0: + return this._gl.UNSIGNED_BYTE; + case 8: + return this._gl.UNSIGNED_SHORT_4_4_4_4; + case 9: + return this._gl.UNSIGNED_SHORT_5_5_5_1; + case 10: + return this._gl.UNSIGNED_SHORT_5_6_5; + } + return this._gl.UNSIGNED_BYTE; + } + switch (type) { + case 3: + return this._gl.BYTE; + case 0: + return this._gl.UNSIGNED_BYTE; + case 4: + return this._gl.SHORT; + case 5: + return this._gl.UNSIGNED_SHORT; + case 6: + return this._gl.INT; + case 7: // Refers to UNSIGNED_INT + return this._gl.UNSIGNED_INT; + case 1: + return this._gl.FLOAT; + case 2: + return this._gl.HALF_FLOAT; + case 8: + return this._gl.UNSIGNED_SHORT_4_4_4_4; + case 9: + return this._gl.UNSIGNED_SHORT_5_5_5_1; + case 10: + return this._gl.UNSIGNED_SHORT_5_6_5; + case 11: + return this._gl.UNSIGNED_INT_2_10_10_10_REV; + case 12: + return this._gl.UNSIGNED_INT_24_8; + case 13: + return this._gl.UNSIGNED_INT_10F_11F_11F_REV; + case 14: + return this._gl.UNSIGNED_INT_5_9_9_9_REV; + case 15: + return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV; + } + return this._gl.UNSIGNED_BYTE; + } + /** + * @internal + */ + _getInternalFormat(format, useSRGBBuffer = false) { + let internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA; + switch (format) { + case 0: + internalFormat = this._gl.ALPHA; + break; + case 1: + internalFormat = this._gl.LUMINANCE; + break; + case 2: + internalFormat = this._gl.LUMINANCE_ALPHA; + break; + case 6: + case 33322: + case 36760: + internalFormat = this._gl.RED; + break; + case 7: + case 33324: + case 36761: + internalFormat = this._gl.RG; + break; + case 4: + case 32852: + case 36762: + internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB : this._gl.RGB; + break; + case 5: + case 32859: + case 36763: + internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA; + break; + } + if (this._webGLVersion > 1) { + switch (format) { + case 8: + internalFormat = this._gl.RED_INTEGER; + break; + case 9: + internalFormat = this._gl.RG_INTEGER; + break; + case 10: + internalFormat = this._gl.RGB_INTEGER; + break; + case 11: + internalFormat = this._gl.RGBA_INTEGER; + break; + } + } + return internalFormat; + } + /** + * @internal + */ + _getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer = false) { + if (this._webGLVersion === 1) { + if (format !== undefined) { + switch (format) { + case 0: + return this._gl.ALPHA; + case 1: + return this._gl.LUMINANCE; + case 2: + return this._gl.LUMINANCE_ALPHA; + case 4: + return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB : this._gl.RGB; + } + } + return this._gl.RGBA; + } + switch (type) { + case 3: + switch (format) { + case 6: + return this._gl.R8_SNORM; + case 7: + return this._gl.RG8_SNORM; + case 4: + return this._gl.RGB8_SNORM; + case 8: + return this._gl.R8I; + case 9: + return this._gl.RG8I; + case 10: + return this._gl.RGB8I; + case 11: + return this._gl.RGBA8I; + default: + return this._gl.RGBA8_SNORM; + } + case 0: + switch (format) { + case 6: + return this._gl.R8; + case 7: + return this._gl.RG8; + case 4: + return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8 : this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8. + case 5: + return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8. + case 8: + return this._gl.R8UI; + case 9: + return this._gl.RG8UI; + case 10: + return this._gl.RGB8UI; + case 11: + return this._gl.RGBA8UI; + case 0: + return this._gl.ALPHA; + case 1: + return this._gl.LUMINANCE; + case 2: + return this._gl.LUMINANCE_ALPHA; + default: + return this._gl.RGBA8; + } + case 4: + switch (format) { + case 8: + return this._gl.R16I; + case 36760: + return this._gl.R16_SNORM_EXT; + case 36761: + return this._gl.RG16_SNORM_EXT; + case 36762: + return this._gl.RGB16_SNORM_EXT; + case 36763: + return this._gl.RGBA16_SNORM_EXT; + case 9: + return this._gl.RG16I; + case 10: + return this._gl.RGB16I; + case 11: + return this._gl.RGBA16I; + default: + return this._gl.RGBA16I; + } + case 5: + switch (format) { + case 8: + return this._gl.R16UI; + case 33322: + return this._gl.R16_EXT; + case 33324: + return this._gl.RG16_EXT; + case 32852: + return this._gl.RGB16_EXT; + case 32859: + return this._gl.RGBA16_EXT; + case 9: + return this._gl.RG16UI; + case 10: + return this._gl.RGB16UI; + case 11: + return this._gl.RGBA16UI; + default: + return this._gl.RGBA16UI; + } + case 6: + switch (format) { + case 8: + return this._gl.R32I; + case 9: + return this._gl.RG32I; + case 10: + return this._gl.RGB32I; + case 11: + return this._gl.RGBA32I; + default: + return this._gl.RGBA32I; + } + case 7: // Refers to UNSIGNED_INT + switch (format) { + case 8: + return this._gl.R32UI; + case 9: + return this._gl.RG32UI; + case 10: + return this._gl.RGB32UI; + case 11: + return this._gl.RGBA32UI; + default: + return this._gl.RGBA32UI; + } + case 1: + switch (format) { + case 6: + return this._gl.R32F; // By default. Other possibility is R16F. + case 7: + return this._gl.RG32F; // By default. Other possibility is RG16F. + case 4: + return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5. + case 5: + return this._gl.RGBA32F; // By default. Other possibility is RGBA16F. + default: + return this._gl.RGBA32F; + } + case 2: + switch (format) { + case 6: + return this._gl.R16F; + case 7: + return this._gl.RG16F; + case 4: + return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5. + case 5: + return this._gl.RGBA16F; + default: + return this._gl.RGBA16F; + } + case 10: + return this._gl.RGB565; + case 13: + return this._gl.R11F_G11F_B10F; + case 14: + return this._gl.RGB9_E5; + case 8: + return this._gl.RGBA4; + case 9: + return this._gl.RGB5_A1; + case 11: + switch (format) { + case 5: + return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1. + case 11: + return this._gl.RGB10_A2UI; + default: + return this._gl.RGB10_A2; + } + } + return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA8; + } + /** + * Reads pixels from the current frame buffer. Please note that this function can be slow + * @param x defines the x coordinate of the rectangle where pixels must be read + * @param y defines the y coordinate of the rectangle where pixels must be read + * @param width defines the width of the rectangle where pixels must be read + * @param height defines the height of the rectangle where pixels must be read + * @param hasAlpha defines whether the output should have alpha or not (defaults to true) + * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels + * @param data defines the data to fill with the read pixels (if not provided, a new one will be created) + * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors + */ + readPixels(x, y, width, height, hasAlpha = true, flushRenderer = true, data = null) { + const numChannels = hasAlpha ? 4 : 3; + const format = hasAlpha ? this._gl.RGBA : this._gl.RGB; + const dataLength = width * height * numChannels; + if (!data) { + data = new Uint8Array(dataLength); + } + else if (data.length < dataLength) { + Logger.Error(`Data buffer is too small to store the read pixels (${data.length} should be more than ${dataLength})`); + return Promise.resolve(data); + } + if (flushRenderer) { + this.flushFramebuffer(); + } + this._gl.readPixels(x, y, width, height, format, this._gl.UNSIGNED_BYTE, data); + return Promise.resolve(data); + } + /** + * Gets a Promise indicating if the engine can be instantiated (ie. if a webGL context can be found) + */ + static get IsSupportedAsync() { + return Promise.resolve(this.isSupported()); + } + /** + * Gets a boolean indicating if the engine can be instantiated (ie. if a webGL context can be found) + */ + static get IsSupported() { + return this.isSupported(); // Backward compat + } + /** + * Gets a boolean indicating if the engine can be instantiated (ie. if a webGL context can be found) + * @returns true if the engine can be created + * @ignorenaming + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + static isSupported() { + if (this._HasMajorPerformanceCaveat !== null) { + return !this._HasMajorPerformanceCaveat; // We know it is performant so WebGL is supported + } + if (this._IsSupported === null) { + try { + const tempcanvas = AbstractEngine._CreateCanvas(1, 1); + const gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"); + this._IsSupported = gl != null && !!window.WebGLRenderingContext; + } + catch (e) { + this._IsSupported = false; + } + } + return this._IsSupported; + } + /** + * Gets a boolean indicating if the engine can be instantiated on a performant device (ie. if a webGL context can be found and it does not use a slow implementation) + */ + static get HasMajorPerformanceCaveat() { + if (this._HasMajorPerformanceCaveat === null) { + try { + const tempcanvas = AbstractEngine._CreateCanvas(1, 1); + const gl = tempcanvas.getContext("webgl", { failIfMajorPerformanceCaveat: true }) || + tempcanvas.getContext("experimental-webgl", { failIfMajorPerformanceCaveat: true }); + this._HasMajorPerformanceCaveat = !gl; + } + catch (e) { + this._HasMajorPerformanceCaveat = false; + } + } + return this._HasMajorPerformanceCaveat; + } +} +ThinEngine._TempClearColorUint32 = new Uint32Array(4); +ThinEngine._TempClearColorInt32 = new Int32Array(4); +/** Use this array to turn off some WebGL2 features on known buggy browsers version */ +ThinEngine.ExceptionList = [ + { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] }, + { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }, + { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }, + { key: "Chrome/72.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] }, + { key: "Chrome/73.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] }, + { key: "Chrome/74.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] }, + { key: "Mac OS.+Chrome/71", capture: null, captureConstraint: null, targets: ["vao"] }, + { key: "Mac OS.+Chrome/72", capture: null, captureConstraint: null, targets: ["vao"] }, + { key: "Mac OS.+Chrome", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }, + { key: "Chrome/12\\d\\..+?Mobile", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }, + // desktop osx safari 15.4 + { key: ".*AppleWebKit.*(15.4).*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] }, + // mobile browsers using safari 15.4 on ios + { key: ".*(15.4).*AppleWebKit.*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] }, +]; +// eslint-disable-next-line @typescript-eslint/naming-convention +ThinEngine._ConcatenateShader = _ConcatenateShader; +// Statics +ThinEngine._IsSupported = null; +ThinEngine._HasMajorPerformanceCaveat = null; + +const thinEngine = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + ThinEngine +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window + */ +class PerformanceMonitor { + /** + * constructor + * @param frameSampleSize The number of samples required to saturate the sliding window + */ + constructor(frameSampleSize = 30) { + this._enabled = true; + this._rollingFrameTime = new RollingAverage(frameSampleSize); + } + /** + * Samples current frame + * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames + */ + sampleFrame(timeMs = PrecisionDate.Now) { + if (!this._enabled) { + return; + } + if (this._lastFrameTimeMs != null) { + const dt = timeMs - this._lastFrameTimeMs; + this._rollingFrameTime.add(dt); + } + this._lastFrameTimeMs = timeMs; + } + /** + * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far) + */ + get averageFrameTime() { + return this._rollingFrameTime.average; + } + /** + * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far) + */ + get averageFrameTimeVariance() { + return this._rollingFrameTime.variance; + } + /** + * Returns the frame time of the most recent frame + */ + get instantaneousFrameTime() { + return this._rollingFrameTime.history(0); + } + /** + * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far) + */ + get averageFPS() { + return 1000.0 / this._rollingFrameTime.average; + } + /** + * Returns the average framerate in frames per second using the most recent frame time + */ + get instantaneousFPS() { + const history = this._rollingFrameTime.history(0); + if (history === 0) { + return 0; + } + return 1000.0 / history; + } + /** + * Returns true if enough samples have been taken to completely fill the sliding window + */ + get isSaturated() { + return this._rollingFrameTime.isSaturated(); + } + /** + * Enables contributions to the sliding window sample set + */ + enable() { + this._enabled = true; + } + /** + * Disables contributions to the sliding window sample set + * Samples will not be interpolated over the disabled period + */ + disable() { + this._enabled = false; + //clear last sample to avoid interpolating over the disabled period when next enabled + this._lastFrameTimeMs = null; + } + /** + * Returns true if sampling is enabled + */ + get isEnabled() { + return this._enabled; + } + /** + * Resets performance monitor + */ + reset() { + //clear last sample to avoid interpolating over the disabled period when next enabled + this._lastFrameTimeMs = null; + //wipe record + this._rollingFrameTime.reset(); + } +} +/** + * RollingAverage + * + * Utility to efficiently compute the rolling average and variance over a sliding window of samples + */ +class RollingAverage { + /** + * constructor + * @param length The number of samples required to saturate the sliding window + */ + constructor(length) { + this._samples = new Array(length); + this.reset(); + } + /** + * Adds a sample to the sample set + * @param v The sample value + */ + add(v) { + //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance + let delta; + //we need to check if we've already wrapped round + if (this.isSaturated()) { + //remove bottom of stack from mean + const bottomValue = this._samples[this._pos]; + delta = bottomValue - this.average; + this.average -= delta / (this._sampleCount - 1); + this._m2 -= delta * (bottomValue - this.average); + } + else { + this._sampleCount++; + } + //add new value to mean + delta = v - this.average; + this.average += delta / this._sampleCount; + this._m2 += delta * (v - this.average); + //set the new variance + this.variance = this._m2 / (this._sampleCount - 1); + this._samples[this._pos] = v; + this._pos++; + this._pos %= this._samples.length; //positive wrap around + } + /** + * Returns previously added values or null if outside of history or outside the sliding window domain + * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that + * @returns Value previously recorded with add() or null if outside of range + */ + history(i) { + if (i >= this._sampleCount || i >= this._samples.length) { + return 0; + } + const i0 = this._wrapPosition(this._pos - 1.0); + return this._samples[this._wrapPosition(i0 - i)]; + } + /** + * Returns true if enough samples have been taken to completely fill the sliding window + * @returns true if sample-set saturated + */ + isSaturated() { + return this._sampleCount >= this._samples.length; + } + /** + * Resets the rolling average (equivalent to 0 samples taken so far) + */ + reset() { + this.average = 0; + this.variance = 0; + this._sampleCount = 0; + this._pos = 0; + this._m2 = 0; + } + /** + * Wraps a value around the sample range boundaries + * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned. + * @returns Wrapped position in sample range + */ + _wrapPosition(i) { + const max = this._samples.length; + return ((i % max) + max) % max; + } +} + +ThinEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange = false) { + if (this._alphaMode === mode) { + if (!noDepthWriteChange) { + // Make sure we still have the correct depth mask according to the alpha mode (a transparent material could have forced writting to the depth buffer, for instance) + const depthMask = mode === 0; + if (this.depthCullingState.depthMask !== depthMask) { + this.depthCullingState.depthMask = depthMask; + } + } + return; + } + switch (mode) { + case 0: + this._alphaState.alphaBlend = false; + break; + case 7: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case 8: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); + this._alphaState.alphaBlend = true; + break; + case 2: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case 6: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case 1: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case 3: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case 4: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case 5: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case 9: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA); + this._alphaState.alphaBlend = true; + break; + case 10: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); + this._alphaState.alphaBlend = true; + break; + case 11: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case 12: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ZERO); + this._alphaState.alphaBlend = true; + break; + case 13: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE_MINUS_DST_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA); + this._alphaState.alphaBlend = true; + break; + case 14: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); + this._alphaState.alphaBlend = true; + break; + case 15: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ZERO); + this._alphaState.alphaBlend = true; + break; + case 16: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ZERO, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case 17: + // Same as ALPHA_COMBINE but accumulates (1 - alpha) values in the alpha channel for a later readout in order independant transparency + this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); + this._alphaState.alphaBlend = true; + break; + } + if (!noDepthWriteChange) { + this.depthCullingState.depthMask = mode === 0; + } + this._alphaMode = mode; +}; + +ThinEngine.prototype.updateRawTexture = function (texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) { + if (!texture) { + return; + } + // Babylon's internalSizedFomat but gl's texImage2D internalFormat + const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer); + // Babylon's internalFormat but gl's texImage2D format + const internalFormat = this._getInternalFormat(format); + const textureType = this._getWebGLTextureType(type); + this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); + this._unpackFlipY(invertY === undefined ? true : invertY ? true : false); + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + texture.format = format; + texture.type = type; + texture.invertY = invertY; + texture._compression = compression; + } + if (texture.width % 4 !== 0) { + this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1); + } + if (compression && data) { + this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data); + } + else { + this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data); + } + if (texture.generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_2D); + } + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + // this.resetTextureCache(); + texture.isReady = true; +}; +ThinEngine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, +// eslint-disable-next-line @typescript-eslint/no-unused-vars +creationFlags = 0, useSRGBBuffer = false) { + const texture = new InternalTexture(this, 3 /* InternalTextureSource.Raw */); + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.format = format; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.invertY = invertY; + texture._compression = compression; + texture.type = type; + texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps); + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + } + this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer); + this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); + // Filters + const filters = this._getSamplingParameters(samplingMode, generateMipMaps); + this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag); + this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min); + if (generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_2D); + } + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + this._internalTexturesCache.push(texture); + return texture; +}; +ThinEngine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) { + const gl = this._gl; + const texture = new InternalTexture(this, 8 /* InternalTextureSource.CubeRaw */); + texture.isCube = true; + texture.format = format; + texture.type = type; + if (!this._doNotHandleContextLost) { + texture._bufferViewArray = data; + } + const textureType = this._getWebGLTextureType(type); + let internalFormat = this._getInternalFormat(format); + if (internalFormat === gl.RGB) { + internalFormat = gl.RGBA; + } + // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable + if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) { + generateMipMaps = false; + samplingMode = 1; + Logger.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."); + } + else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) { + generateMipMaps = false; + samplingMode = 1; + Logger.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."); + } + else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) { + generateMipMaps = false; + Logger.Warn("Render to float textures is not supported. Mipmap generation forced to false."); + } + else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) { + generateMipMaps = false; + Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false."); + } + const width = size; + const height = width; + texture.width = width; + texture.height = height; + texture.invertY = invertY; + texture._compression = compression; + // Double check on POT to generate Mips. + const isPot = !this.needPOTTextures || (IsExponentOfTwo(texture.width) && IsExponentOfTwo(texture.height)); + if (!isPot) { + generateMipMaps = false; + } + // Upload data if needed. The texture won't be ready until then. + if (data) { + this.updateRawCubeTexture(texture, data, format, type, invertY, compression); + } + else { + const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); + const level = 0; + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + for (let faceIndex = 0; faceIndex < 6; faceIndex++) { + if (compression) { + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, undefined); + } + else { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, null); + } + } + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); + } + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true); + // Filters + if (data && generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP); + } + const filters = this._getSamplingParameters(samplingMode, generateMipMaps); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.isReady = true; + return texture; +}; +ThinEngine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression = null, level = 0) { + texture._bufferViewArray = data; + texture.format = format; + texture.type = type; + texture.invertY = invertY; + texture._compression = compression; + const gl = this._gl; + const textureType = this._getWebGLTextureType(type); + let internalFormat = this._getInternalFormat(format); + const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); + let needConversion = false; + if (internalFormat === gl.RGB) { + internalFormat = gl.RGBA; + needConversion = true; + } + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + this._unpackFlipY(invertY === undefined ? true : invertY ? true : false); + if (texture.width % 4 !== 0) { + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); + } + // Data are known to be in +X +Y +Z -X -Y -Z + for (let faceIndex = 0; faceIndex < 6; faceIndex++) { + let faceData = data[faceIndex]; + if (compression) { + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData); + } + else { + if (needConversion) { + faceData = _convertRGBtoRGBATextureData$1(faceData, texture.width, texture.height, type); + } + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData); + } + } + const isPot = !this.needPOTTextures || (IsExponentOfTwo(texture.width) && IsExponentOfTwo(texture.height)); + if (isPot && texture.generateMipMaps && level === 0) { + this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP); + } + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); + // this.resetTextureCache(); + texture.isReady = true; +}; +ThinEngine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) { + const gl = this._gl; + const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null); + scene?.addPendingData(texture); + texture.url = url; + texture.isReady = false; + this._internalTexturesCache.push(texture); + const onerror = (request, exception) => { + scene?.removePendingData(texture); + if (onError && request) { + onError(request.status + " " + request.statusText, exception); + } + }; + const internalCallback = (data) => { + // If the texture has been disposed + if (!texture._hardwareTexture) { + return; + } + const width = texture.width; + const faceDataArrays = callback(data); + if (!faceDataArrays) { + return; + } + if (mipmapGenerator) { + const textureType = this._getWebGLTextureType(type); + let internalFormat = this._getInternalFormat(format); + const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); + let needConversion = false; + if (internalFormat === gl.RGB) { + internalFormat = gl.RGBA; + needConversion = true; + } + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + this._unpackFlipY(false); + const mipData = mipmapGenerator(faceDataArrays); + for (let level = 0; level < mipData.length; level++) { + const mipSize = width >> level; + for (let faceIndex = 0; faceIndex < 6; faceIndex++) { + let mipFaceData = mipData[level][faceIndex]; + if (needConversion) { + mipFaceData = _convertRGBtoRGBATextureData$1(mipFaceData, mipSize, mipSize, type); + } + gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData); + } + } + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + } + else { + this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY); + } + texture.isReady = true; + // this.resetTextureCache(); + scene?.removePendingData(texture); + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + if (onLoad) { + onLoad(); + } + }; + this._loadFile(url, (data) => { + internalCallback(data); + }, undefined, scene?.offlineProvider, true, onerror); + return texture; +}; +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function _convertRGBtoRGBATextureData$1(rgbData, width, height, textureType) { + // Create new RGBA data container. + let rgbaData; + let val1 = 1; + if (textureType === 1) { + rgbaData = new Float32Array(width * height * 4); + } + else if (textureType === 2) { + rgbaData = new Uint16Array(width * height * 4); + val1 = 15360; // 15360 is the encoding of 1 in half float + } + else if (textureType === 7) { + rgbaData = new Uint32Array(width * height * 4); + } + else { + rgbaData = new Uint8Array(width * height * 4); + } + // Convert each pixel. + for (let x = 0; x < width; x++) { + for (let y = 0; y < height; y++) { + const index = (y * width + x) * 3; + const newIndex = (y * width + x) * 4; + // Map Old Value to new value. + rgbaData[newIndex + 0] = rgbData[index + 0]; + rgbaData[newIndex + 1] = rgbData[index + 1]; + rgbaData[newIndex + 2] = rgbData[index + 2]; + // Add fully opaque alpha channel. + rgbaData[newIndex + 3] = val1; + } + } + return rgbaData; +} +/** + * Create a function for createRawTexture3D/createRawTexture2DArray + * @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function _makeCreateRawTextureFunction(is3D) { + return function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) { + const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY; + const source = is3D ? 10 /* InternalTextureSource.Raw3D */ : 11 /* InternalTextureSource.Raw2DArray */; + const texture = new InternalTexture(this, source); + texture.baseWidth = width; + texture.baseHeight = height; + texture.baseDepth = depth; + texture.width = width; + texture.height = height; + texture.depth = depth; + texture.format = format; + texture.type = textureType; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + if (is3D) { + texture.is3D = true; + } + else { + texture.is2DArray = true; + } + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + } + if (is3D) { + this.updateRawTexture3D(texture, data, format, invertY, compression, textureType); + } + else { + this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType); + } + this._bindTextureDirectly(target, texture, true); + // Filters + const filters = this._getSamplingParameters(samplingMode, generateMipMaps); + this._gl.texParameteri(target, this._gl.TEXTURE_MAG_FILTER, filters.mag); + this._gl.texParameteri(target, this._gl.TEXTURE_MIN_FILTER, filters.min); + if (generateMipMaps) { + this._gl.generateMipmap(target); + } + this._bindTextureDirectly(target, null); + this._internalTexturesCache.push(texture); + return texture; + }; +} +ThinEngine.prototype.createRawTexture2DArray = _makeCreateRawTextureFunction(false); +ThinEngine.prototype.createRawTexture3D = _makeCreateRawTextureFunction(true); +/** + * Create a function for updateRawTexture3D/updateRawTexture2DArray + * @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function _makeUpdateRawTextureFunction(is3D) { + return function (texture, data, format, invertY, compression = null, textureType = 0) { + const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY; + const internalType = this._getWebGLTextureType(textureType); + const internalFormat = this._getInternalFormat(format); + const internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format); + this._bindTextureDirectly(target, texture, true); + this._unpackFlipY(invertY === undefined ? true : invertY ? true : false); + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + texture.format = format; + texture.invertY = invertY; + texture._compression = compression; + } + if (texture.width % 4 !== 0) { + this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1); + } + if (compression && data) { + this._gl.compressedTexImage3D(target, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data); + } + else { + this._gl.texImage3D(target, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data); + } + if (texture.generateMipMaps) { + this._gl.generateMipmap(target); + } + this._bindTextureDirectly(target, null); + // this.resetTextureCache(); + texture.isReady = true; + }; +} +ThinEngine.prototype.updateRawTexture2DArray = _makeUpdateRawTextureFunction(false); +ThinEngine.prototype.updateRawTexture3D = _makeUpdateRawTextureFunction(true); + +ThinEngine.prototype._readTexturePixelsSync = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) { + const gl = this._gl; + if (!gl) { + throw new Error("Engine does not have gl rendering context."); + } + if (!this._dummyFramebuffer) { + const dummy = gl.createFramebuffer(); + if (!dummy) { + throw new Error("Unable to create dummy framebuffer"); + } + this._dummyFramebuffer = dummy; + } + gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer); + if (faceIndex > -1) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._hardwareTexture?.underlyingResource, level); + } + else { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._hardwareTexture?.underlyingResource, level); + } + let readType = texture.type !== undefined ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE; + if (!noDataConversion) { + switch (readType) { + case gl.UNSIGNED_BYTE: + if (!buffer) { + buffer = new Uint8Array(4 * width * height); + } + readType = gl.UNSIGNED_BYTE; + break; + default: + if (!buffer) { + buffer = new Float32Array(4 * width * height); + } + readType = gl.FLOAT; + break; + } + } + else if (!buffer) { + buffer = allocateAndCopyTypedBuffer(texture.type, 4 * width * height); + } + if (flushRenderer) { + this.flushFramebuffer(); + } + gl.readPixels(x, y, width, height, gl.RGBA, readType, buffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer); + return buffer; +}; +ThinEngine.prototype._readTexturePixels = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) { + return Promise.resolve(this._readTexturePixelsSync(texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y)); +}; + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +ThinEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset = 0) { + // Force cache update + this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null; + this.bindIndexBuffer(indexBuffer); + let view; + if (indexBuffer.is32Bits) { + // anything else than Uint32Array needs to be converted to Uint32Array + view = indices instanceof Uint32Array ? indices : new Uint32Array(indices); + } + else { + // anything else than Uint16Array needs to be converted to Uint16Array + view = indices instanceof Uint16Array ? indices : new Uint16Array(indices); + } + this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, view, this._gl.DYNAMIC_DRAW); + this._resetIndexBufferBinding(); +}; +ThinEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) { + this.bindArrayBuffer(vertexBuffer); + if (byteOffset === undefined) { + byteOffset = 0; + } + const dataLength = data.byteLength || data.length; + if (byteLength === undefined || (byteLength >= dataLength && byteOffset === 0)) { + if (data instanceof Array) { + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data)); + } + else { + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data); + } + } + else { + if (data instanceof Array) { + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data).subarray(0, byteLength / 4)); + } + else { + if (data instanceof ArrayBuffer) { + data = new Uint8Array(data, 0, byteLength); + } + else { + data = new Uint8Array(data.buffer, data.byteOffset, byteLength); + } + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data); + } + } + this._resetVertexBufferBinding(); +}; + +ThinEngine.prototype._createDepthStencilCubeTexture = function (size, options) { + const internalTexture = new InternalTexture(this, 12 /* InternalTextureSource.DepthStencil */); + internalTexture.isCube = true; + if (this.webGLVersion === 1) { + Logger.Error("Depth cube texture is not supported by WebGL 1."); + return internalTexture; + } + const internalOptions = { + bilinearFiltering: false, + comparisonFunction: 0, + generateStencil: false, + ...options, + }; + const gl = this._gl; + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true); + this._setupDepthStencilTexture(internalTexture, size, internalOptions.bilinearFiltering, internalOptions.comparisonFunction); + // Create the depth/stencil buffer + for (let face = 0; face < 6; face++) { + if (internalOptions.generateStencil) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null); + } + else { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null); + } + } + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + this._internalTexturesCache.push(internalTexture); + return internalTexture; +}; +ThinEngine.prototype._setCubeMapTextureParams = function (texture, loadMipmap, maxLevel) { + const gl = this._gl; + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + texture.samplingMode = loadMipmap ? 3 : 2; + if (loadMipmap && this.getCaps().textureMaxLevel && maxLevel !== undefined && maxLevel > 0) { + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAX_LEVEL, maxLevel); + texture._maxLodLevel = maxLevel; + } + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); +}; +ThinEngine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false, buffer = null) { + const gl = this._gl; + return this.createCubeTextureBase(rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, (texture) => this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true), (texture, imgs) => { + const width = this.needPOTTextures ? GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width; + const height = width; + const faces = [ + gl.TEXTURE_CUBE_MAP_POSITIVE_X, + gl.TEXTURE_CUBE_MAP_POSITIVE_Y, + gl.TEXTURE_CUBE_MAP_POSITIVE_Z, + gl.TEXTURE_CUBE_MAP_NEGATIVE_X, + gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, + gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, + ]; + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + this._unpackFlipY(false); + const internalFormat = format ? this._getInternalFormat(format, texture._useSRGBBuffer) : texture._useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : gl.RGBA; + let texelFormat = format ? this._getInternalFormat(format) : gl.RGBA; + if (texture._useSRGBBuffer && this.webGLVersion === 1) { + texelFormat = internalFormat; + } + for (let index = 0; index < faces.length; index++) { + if (imgs[index].width !== width || imgs[index].height !== height) { + this._prepareWorkingCanvas(); + if (!this._workingCanvas || !this._workingContext) { + Logger.Warn("Cannot create canvas to resize texture."); + return; + } + this._workingCanvas.width = width; + this._workingCanvas.height = height; + this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height); + gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, this._workingCanvas); + } + else { + gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, imgs[index]); + } + } + if (!noMipmap) { + gl.generateMipmap(gl.TEXTURE_CUBE_MAP); + } + this._setCubeMapTextureParams(texture, !noMipmap); + texture.width = width; + texture.height = height; + texture.isReady = true; + if (format) { + texture.format = format; + } + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + if (onLoad) { + onLoad(); + } + }, !!useSRGBBuffer, buffer); +}; +ThinEngine.prototype.generateMipMapsForCubemap = function (texture, unbind = true) { + if (texture.generateMipMaps) { + const gl = this._gl; + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + gl.generateMipmap(gl.TEXTURE_CUBE_MAP); + if (unbind) { + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + } + } +}; + +/** + * Wrapper around a render target (either single or multi textures) + */ +class RenderTargetWrapper { + /** + * Gets the depth/stencil texture + */ + get depthStencilTexture() { + return this._depthStencilTexture; + } + /** + * Sets the depth/stencil texture + * @param texture The depth/stencil texture to set + * @param disposeExisting True to dispose the existing depth/stencil texture (if any) before replacing it (default: true) + */ + setDepthStencilTexture(texture, disposeExisting = true) { + if (disposeExisting && this._depthStencilTexture) { + this._depthStencilTexture.dispose(); + } + this._depthStencilTexture = texture; + this._generateDepthBuffer = this._generateStencilBuffer = this._depthStencilTextureWithStencil = false; + if (texture) { + this._generateDepthBuffer = true; + this._generateStencilBuffer = this._depthStencilTextureWithStencil = HasStencilAspect(texture.format); + } + } + /** + * Indicates if the depth/stencil texture has a stencil aspect + */ + get depthStencilTextureWithStencil() { + return this._depthStencilTextureWithStencil; + } + /** + * Defines if the render target wrapper is for a cube texture or if false a 2d texture + */ + get isCube() { + return this._isCube; + } + /** + * Defines if the render target wrapper is for a single or multi target render wrapper + */ + get isMulti() { + return this._isMulti; + } + /** + * Defines if the render target wrapper is for a single or an array of textures + */ + get is2DArray() { + return this.layers > 0; + } + /** + * Defines if the render target wrapper is for a 3D texture + */ + get is3D() { + return this.depth > 0; + } + /** + * Gets the size of the render target wrapper (used for cubes, as width=height in this case) + */ + get size() { + return this.width; + } + /** + * Gets the width of the render target wrapper + */ + get width() { + return this._size.width ?? this._size; + } + /** + * Gets the height of the render target wrapper + */ + get height() { + return this._size.height ?? this._size; + } + /** + * Gets the number of layers of the render target wrapper (only used if is2DArray is true and wrapper is not a multi render target) + */ + get layers() { + return this._size.layers || 0; + } + /** + * Gets the depth of the render target wrapper (only used if is3D is true and wrapper is not a multi render target) + */ + get depth() { + return this._size.depth || 0; + } + /** + * Gets the render texture. If this is a multi render target, gets the first texture + */ + get texture() { + return this._textures?.[0] ?? null; + } + /** + * Gets the list of render textures. If we are not in a multi render target, the list will be null (use the texture getter instead) + */ + get textures() { + return this._textures; + } + /** + * Gets the face indices that correspond to the list of render textures. If we are not in a multi render target, the list will be null + */ + get faceIndices() { + return this._faceIndices; + } + /** + * Gets the layer indices that correspond to the list of render textures. If we are not in a multi render target, the list will be null + */ + get layerIndices() { + return this._layerIndices; + } + /** + * Gets the base array layer of a texture in the textures array + * This is an number that is calculated based on the layer and face indices set for this texture at that index + * @param index The index of the texture in the textures array to get the base array layer for + * @returns the base array layer of the texture at the given index + */ + getBaseArrayLayer(index) { + if (!this._textures) { + return -1; + } + const texture = this._textures[index]; + const layerIndex = this._layerIndices?.[index] ?? 0; + const faceIndex = this._faceIndices?.[index] ?? 0; + return texture.isCube ? layerIndex * 6 + faceIndex : texture.is3D ? 0 : layerIndex; + } + /** + * Gets the sample count of the render target + */ + get samples() { + return this._samples; + } + /** + * Sets the sample count of the render target + * @param value sample count + * @param initializeBuffers If set to true, the engine will make an initializing call to drawBuffers (only used when isMulti=true). + * @param force true to force calling the update sample count engine function even if the current sample count is equal to value + * @returns the sample count that has been set + */ + setSamples(value, initializeBuffers = true, force = false) { + if (this.samples === value && !force) { + return value; + } + const result = this._isMulti + ? this._engine.updateMultipleRenderTargetTextureSampleCount(this, value, initializeBuffers) + : this._engine.updateRenderTargetTextureSampleCount(this, value); + this._samples = value; + return result; + } + /** + * Resolves the MSAA textures into their non-MSAA version. + * Note that if samples equals 1 (no MSAA), no resolve is performed. + */ + resolveMSAATextures() { + if (this.isMulti) { + this._engine.resolveMultiFramebuffer(this); + } + else { + this._engine.resolveFramebuffer(this); + } + } + /** + * Generates mipmaps for each texture of the render target + */ + generateMipMaps() { + if (this._engine._currentRenderTarget === this) { + this._engine.unBindFramebuffer(this, true); + } + if (this.isMulti) { + this._engine.generateMipMapsMultiFramebuffer(this); + } + else { + this._engine.generateMipMapsFramebuffer(this); + } + } + /** + * Initializes the render target wrapper + * @param isMulti true if the wrapper is a multi render target + * @param isCube true if the wrapper should render to a cube texture + * @param size size of the render target (width/height/layers) + * @param engine engine used to create the render target + * @param label defines the label to use for the wrapper (for debugging purpose only) + */ + constructor(isMulti, isCube, size, engine, label) { + this._textures = null; + this._faceIndices = null; + this._layerIndices = null; + /** @internal */ + this._samples = 1; + /** @internal */ + this._attachments = null; + /** @internal */ + this._generateStencilBuffer = false; + /** @internal */ + this._generateDepthBuffer = false; + /** @internal */ + this._depthStencilTextureWithStencil = false; + /** + * Sets this property to true to disable the automatic MSAA resolve that happens when the render target wrapper is unbound (default is false) + */ + this.disableAutomaticMSAAResolve = false; + /** + * Indicates if MSAA color texture(s) should be resolved when a resolve occur (either automatically by the engine or manually by the user) (default is true) + * Note that you can trigger a MSAA resolve at any time by calling resolveMSAATextures() + */ + this.resolveMSAAColors = true; + /** + * Indicates if MSAA depth texture should be resolved when a resolve occur (either automatically by the engine or manually by the user) (default is false) + */ + this.resolveMSAADepth = false; + /** + * Indicates if MSAA stencil texture should be resolved when a resolve occur (either automatically by the engine or manually by the user) (default is false) + */ + this.resolveMSAAStencil = false; + this._isMulti = isMulti; + this._isCube = isCube; + this._size = size; + this._engine = engine; + this._depthStencilTexture = null; + this.label = label; + } + /** + * Sets the render target texture(s) + * @param textures texture(s) to set + */ + setTextures(textures) { + if (Array.isArray(textures)) { + this._textures = textures; + } + else if (textures) { + this._textures = [textures]; + } + else { + this._textures = null; + } + } + /** + * Set a texture in the textures array + * @param texture The texture to set + * @param index The index in the textures array to set + * @param disposePrevious If this function should dispose the previous texture + */ + setTexture(texture, index = 0, disposePrevious = true) { + if (!this._textures) { + this._textures = []; + } + if (this._textures[index] === texture) { + return; + } + if (this._textures[index] && disposePrevious) { + this._textures[index].dispose(); + } + this._textures[index] = texture; + } + /** + * Sets the layer and face indices of every render target texture bound to each color attachment + * @param layers The layers of each texture to be set + * @param faces The faces of each texture to be set + */ + setLayerAndFaceIndices(layers, faces) { + this._layerIndices = layers; + this._faceIndices = faces; + } + /** + * Sets the layer and face indices of a texture in the textures array that should be bound to each color attachment + * @param index The index of the texture in the textures array to modify + * @param layer The layer of the texture to be set + * @param face The face of the texture to be set + */ + setLayerAndFaceIndex(index = 0, layer, face) { + if (!this._layerIndices) { + this._layerIndices = []; + } + if (!this._faceIndices) { + this._faceIndices = []; + } + if (layer !== undefined && layer >= 0) { + this._layerIndices[index] = layer; + } + if (face !== undefined && face >= 0) { + this._faceIndices[index] = face; + } + } + /** + * Creates the depth/stencil texture + * @param comparisonFunction Comparison function to use for the texture + * @param bilinearFiltering true if bilinear filtering should be used when sampling the texture + * @param generateStencil Not used anymore. "format" will be used to determine if stencil should be created + * @param samples sample count to use when creating the texture (default: 1) + * @param format format of the depth texture (default: 14) + * @param label defines the label to use for the texture (for debugging purpose only) + * @returns the depth/stencil created texture + */ + createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) { + this._depthStencilTexture?.dispose(); + this._depthStencilTextureWithStencil = generateStencil; + this._depthStencilTextureLabel = label; + this._depthStencilTexture = this._engine.createDepthStencilTexture(this._size, { + bilinearFiltering, + comparisonFunction, + generateStencil, + isCube: this._isCube, + samples, + depthTextureFormat: format, + label, + }, this); + return this._depthStencilTexture; + } + /** + * @deprecated Use shareDepth instead + * @param renderTarget Destination renderTarget + */ + _shareDepth(renderTarget) { + this.shareDepth(renderTarget); + } + /** + * Shares the depth buffer of this render target with another render target. + * @param renderTarget Destination renderTarget + */ + shareDepth(renderTarget) { + if (this._depthStencilTexture) { + if (renderTarget._depthStencilTexture) { + renderTarget._depthStencilTexture.dispose(); + } + renderTarget._depthStencilTexture = this._depthStencilTexture; + renderTarget._depthStencilTextureWithStencil = this._depthStencilTextureWithStencil; + this._depthStencilTexture.incrementReferences(); + } + } + /** + * @internal + */ + _swapAndDie(target) { + if (this.texture) { + this.texture._swapAndDie(target); + } + this._textures = null; + this.dispose(true); + } + _cloneRenderTargetWrapper() { + let rtw = null; + if (this._isMulti) { + const textureArray = this.textures; + if (textureArray && textureArray.length > 0) { + let generateDepthTexture = false; + let textureCount = textureArray.length; + let depthTextureFormat = -1; + const lastTextureSource = textureArray[textureArray.length - 1]._source; + if (lastTextureSource === 14 /* InternalTextureSource.Depth */ || lastTextureSource === 12 /* InternalTextureSource.DepthStencil */) { + generateDepthTexture = true; + depthTextureFormat = textureArray[textureArray.length - 1].format; + textureCount--; + } + const samplingModes = []; + const types = []; + const formats = []; + const targetTypes = []; + const faceIndex = []; + const layerIndex = []; + const layerCounts = []; + const internalTexture2Index = {}; + for (let i = 0; i < textureCount; ++i) { + const texture = textureArray[i]; + samplingModes.push(texture.samplingMode); + types.push(texture.type); + formats.push(texture.format); + const index = internalTexture2Index[texture.uniqueId]; + if (index !== undefined) { + targetTypes.push(-1); + layerCounts.push(0); + } + else { + internalTexture2Index[texture.uniqueId] = i; + if (texture.is2DArray) { + targetTypes.push(35866); + layerCounts.push(texture.depth); + } + else if (texture.isCube) { + targetTypes.push(34067); + layerCounts.push(0); + } /*else if (texture.isCubeArray) { + targetTypes.push(3735928559); + layerCounts.push(texture.depth); + }*/ + else if (texture.is3D) { + targetTypes.push(32879); + layerCounts.push(texture.depth); + } + else { + targetTypes.push(3553); + layerCounts.push(0); + } + } + if (this._faceIndices) { + faceIndex.push(this._faceIndices[i] ?? 0); + } + if (this._layerIndices) { + layerIndex.push(this._layerIndices[i] ?? 0); + } + } + const optionsMRT = { + samplingModes, + generateMipMaps: textureArray[0].generateMipMaps, + generateDepthBuffer: this._generateDepthBuffer, + generateStencilBuffer: this._generateStencilBuffer, + generateDepthTexture, + depthTextureFormat, + types, + formats, + textureCount, + targetTypes, + faceIndex, + layerIndex, + layerCounts, + label: this.label, + }; + const size = { + width: this.width, + height: this.height, + depth: this.depth, + }; + rtw = this._engine.createMultipleRenderTarget(size, optionsMRT); + for (let i = 0; i < textureCount; ++i) { + if (targetTypes[i] !== -1) { + continue; + } + const index = internalTexture2Index[textureArray[i].uniqueId]; + rtw.setTexture(rtw.textures[index], i); + } + } + } + else { + const options = {}; + options.generateDepthBuffer = this._generateDepthBuffer; + options.generateMipMaps = this.texture?.generateMipMaps ?? false; + options.generateStencilBuffer = this._generateStencilBuffer; + options.samplingMode = this.texture?.samplingMode; + options.type = this.texture?.type; + options.format = this.texture?.format; + options.noColorAttachment = !this._textures; + options.label = this.label; + if (this.isCube) { + rtw = this._engine.createRenderTargetCubeTexture(this.width, options); + } + else { + const size = { + width: this.width, + height: this.height, + layers: this.is2DArray || this.is3D ? this.texture?.depth : undefined, + }; + rtw = this._engine.createRenderTargetTexture(size, options); + } + if (rtw.texture) { + rtw.texture.isReady = true; + } + } + return rtw; + } + _swapRenderTargetWrapper(target) { + if (this._textures && target._textures) { + for (let i = 0; i < this._textures.length; ++i) { + this._textures[i]._swapAndDie(target._textures[i], false); + target._textures[i].isReady = true; + } + } + if (this._depthStencilTexture && target._depthStencilTexture) { + this._depthStencilTexture._swapAndDie(target._depthStencilTexture); + target._depthStencilTexture.isReady = true; + } + this._textures = null; + this._depthStencilTexture = null; + } + /** @internal */ + _rebuild() { + const rtw = this._cloneRenderTargetWrapper(); + if (!rtw) { + return; + } + if (this._depthStencilTexture) { + const samplingMode = this._depthStencilTexture.samplingMode; + const format = this._depthStencilTexture.format; + const bilinear = samplingMode === 2 || + samplingMode === 3 || + samplingMode === 11; + rtw.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction, bilinear, this._depthStencilTextureWithStencil, this._depthStencilTexture.samples, format, this._depthStencilTextureLabel); + } + if (this.samples > 1) { + rtw.setSamples(this.samples); + } + rtw._swapRenderTargetWrapper(this); + rtw.dispose(); + } + /** + * Releases the internal render textures + */ + releaseTextures() { + if (this._textures) { + for (let i = 0; i < this._textures.length; ++i) { + this._textures[i].dispose(); + } + } + this._textures = null; + } + /** + * Disposes the whole render target wrapper + * @param disposeOnlyFramebuffers true if only the frame buffers should be released (used for the WebGL engine). If false, all the textures will also be released + */ + dispose(disposeOnlyFramebuffers = false) { + if (!disposeOnlyFramebuffers) { + this._depthStencilTexture?.dispose(); + this._depthStencilTexture = null; + this.releaseTextures(); + } + this._engine._releaseRenderTargetWrapper(this); + } +} + +/** @internal */ +class WebGLRenderTargetWrapper extends RenderTargetWrapper { + setDepthStencilTexture(texture, disposeExisting = true) { + super.setDepthStencilTexture(texture, disposeExisting); + if (!texture) { + return; + } + const engine = this._engine; + const gl = this._context; + const hardwareTexture = texture._hardwareTexture; + if (hardwareTexture && texture._autoMSAAManagement && this._MSAAFramebuffer) { + const currentFB = engine._currentFramebuffer; + engine._bindUnboundFramebuffer(this._MSAAFramebuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, HasStencilAspect(texture.format) ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, hardwareTexture.getMSAARenderBuffer()); + engine._bindUnboundFramebuffer(currentFB); + } + } + constructor(isMulti, isCube, size, engine, context) { + super(isMulti, isCube, size, engine); + /** + * @internal + */ + this._framebuffer = null; + /** + * @internal + */ + this._depthStencilBuffer = null; + // eslint-disable-next-line @typescript-eslint/naming-convention + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + this._MSAAFramebuffer = null; + // Multiview + /** + * @internal + */ + this._colorTextureArray = null; + /** + * @internal + */ + this._depthStencilTextureArray = null; + /** + * @internal + */ + this._disposeOnlyFramebuffers = false; + /** + * @internal + */ + this._currentLOD = 0; + this._context = context; + } + _cloneRenderTargetWrapper() { + let rtw = null; + if (this._colorTextureArray && this._depthStencilTextureArray) { + rtw = this._engine.createMultiviewRenderTargetTexture(this.width, this.height); + rtw.texture.isReady = true; + } + else { + rtw = super._cloneRenderTargetWrapper(); + } + return rtw; + } + _swapRenderTargetWrapper(target) { + super._swapRenderTargetWrapper(target); + target._framebuffer = this._framebuffer; + target._depthStencilBuffer = this._depthStencilBuffer; + target._MSAAFramebuffer = this._MSAAFramebuffer; + target._colorTextureArray = this._colorTextureArray; + target._depthStencilTextureArray = this._depthStencilTextureArray; + this._framebuffer = this._depthStencilBuffer = this._MSAAFramebuffer = this._colorTextureArray = this._depthStencilTextureArray = null; + } + /** + * Creates the depth/stencil texture + * @param comparisonFunction Comparison function to use for the texture + * @param bilinearFiltering true if bilinear filtering should be used when sampling the texture + * @param generateStencil true if the stencil aspect should also be created + * @param samples sample count to use when creating the texture + * @param format format of the depth texture + * @param label defines the label to use for the texture (for debugging purpose only) + * @returns the depth/stencil created texture + */ + createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) { + if (this._depthStencilBuffer) { + const engine = this._engine; + // Dispose previous depth/stencil render buffers and clear the corresponding attachment. + // Next time this framebuffer is bound, the new depth/stencil texture will be attached. + const currentFrameBuffer = engine._currentFramebuffer; + const gl = this._context; + engine._bindUnboundFramebuffer(this._framebuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, null); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, null); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, null); + engine._bindUnboundFramebuffer(currentFrameBuffer); + gl.deleteRenderbuffer(this._depthStencilBuffer); + this._depthStencilBuffer = null; + } + return super.createDepthStencilTexture(comparisonFunction, bilinearFiltering, generateStencil, samples, format, label); + } + /** + * Shares the depth buffer of this render target with another render target. + * @param renderTarget Destination renderTarget + */ + shareDepth(renderTarget) { + super.shareDepth(renderTarget); + const gl = this._context; + const depthbuffer = this._depthStencilBuffer; + const framebuffer = renderTarget._MSAAFramebuffer || renderTarget._framebuffer; + const engine = this._engine; + if (renderTarget._depthStencilBuffer && renderTarget._depthStencilBuffer !== depthbuffer) { + gl.deleteRenderbuffer(renderTarget._depthStencilBuffer); + } + renderTarget._depthStencilBuffer = depthbuffer; + const attachment = renderTarget._generateStencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + engine._bindUnboundFramebuffer(framebuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, depthbuffer); + engine._bindUnboundFramebuffer(null); + } + /** + * Binds a texture to this render target on a specific attachment + * @param texture The texture to bind to the framebuffer + * @param attachmentIndex Index of the attachment + * @param faceIndexOrLayer The face or layer of the texture to render to in case of cube texture or array texture + * @param lodLevel defines the lod level to bind to the frame buffer + */ + _bindTextureRenderTarget(texture, attachmentIndex = 0, faceIndexOrLayer, lodLevel = 0) { + const hardwareTexture = texture._hardwareTexture; + if (!hardwareTexture) { + return; + } + const framebuffer = this._framebuffer; + const engine = this._engine; + const currentFB = engine._currentFramebuffer; + engine._bindUnboundFramebuffer(framebuffer); + let attachment; + if (engine.webGLVersion > 1) { + const gl = this._context; + attachment = gl["COLOR_ATTACHMENT" + attachmentIndex]; + if (texture.is2DArray || texture.is3D) { + faceIndexOrLayer = faceIndexOrLayer ?? this.layerIndices?.[attachmentIndex] ?? 0; + gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, hardwareTexture.underlyingResource, lodLevel, faceIndexOrLayer); + } + else if (texture.isCube) { + // if face index is not specified, try to query it from faceIndices + // default is face 0 + faceIndexOrLayer = faceIndexOrLayer ?? this.faceIndices?.[attachmentIndex] ?? 0; + gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer, hardwareTexture.underlyingResource, lodLevel); + } + else { + gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, hardwareTexture.underlyingResource, lodLevel); + } + } + else { + // Default behavior (WebGL) + const gl = this._context; + attachment = gl["COLOR_ATTACHMENT" + attachmentIndex + "_WEBGL"]; + const target = faceIndexOrLayer !== undefined ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer : gl.TEXTURE_2D; + gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, target, hardwareTexture.underlyingResource, lodLevel); + } + if (texture._autoMSAAManagement && this._MSAAFramebuffer) { + const gl = this._context; + engine._bindUnboundFramebuffer(this._MSAAFramebuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, hardwareTexture.getMSAARenderBuffer()); + } + engine._bindUnboundFramebuffer(currentFB); + } + /** + * Set a texture in the textures array + * @param texture the texture to set + * @param index the index in the textures array to set + * @param disposePrevious If this function should dispose the previous texture + */ + setTexture(texture, index = 0, disposePrevious = true) { + super.setTexture(texture, index, disposePrevious); + this._bindTextureRenderTarget(texture, index); + } + /** + * Sets the layer and face indices of every render target texture + * @param layers The layer of the texture to be set (make negative to not modify) + * @param faces The face of the texture to be set (make negative to not modify) + */ + setLayerAndFaceIndices(layers, faces) { + super.setLayerAndFaceIndices(layers, faces); + if (!this.textures || !this.layerIndices || !this.faceIndices) { + return; + } + // the length of this._attachments is the right one as it does not count the depth texture, in case we generated it + const textureCount = this._attachments?.length ?? this.textures.length; + for (let index = 0; index < textureCount; index++) { + const texture = this.textures[index]; + if (!texture) { + // The target type was probably -1 at creation time and setTexture has not been called yet for this index + continue; + } + if (texture.is2DArray || texture.is3D) { + this._bindTextureRenderTarget(texture, index, this.layerIndices[index]); + } + else if (texture.isCube) { + this._bindTextureRenderTarget(texture, index, this.faceIndices[index]); + } + else { + this._bindTextureRenderTarget(texture, index); + } + } + } + /** + * Set the face and layer indices of a texture in the textures array + * @param index The index of the texture in the textures array to modify + * @param layer The layer of the texture to be set + * @param face The face of the texture to be set + */ + setLayerAndFaceIndex(index = 0, layer, face) { + super.setLayerAndFaceIndex(index, layer, face); + if (!this.textures || !this.layerIndices || !this.faceIndices) { + return; + } + const texture = this.textures[index]; + if (texture.is2DArray || texture.is3D) { + this._bindTextureRenderTarget(this.textures[index], index, this.layerIndices[index]); + } + else if (texture.isCube) { + this._bindTextureRenderTarget(this.textures[index], index, this.faceIndices[index]); + } + } + resolveMSAATextures() { + const engine = this._engine; + const currentFramebuffer = engine._currentFramebuffer; + engine._bindUnboundFramebuffer(this._MSAAFramebuffer); + super.resolveMSAATextures(); + engine._bindUnboundFramebuffer(currentFramebuffer); + } + dispose(disposeOnlyFramebuffers = this._disposeOnlyFramebuffers) { + const gl = this._context; + if (!disposeOnlyFramebuffers) { + if (this._colorTextureArray) { + this._context.deleteTexture(this._colorTextureArray); + this._colorTextureArray = null; + } + if (this._depthStencilTextureArray) { + this._context.deleteTexture(this._depthStencilTextureArray); + this._depthStencilTextureArray = null; + } + } + if (this._framebuffer) { + gl.deleteFramebuffer(this._framebuffer); + this._framebuffer = null; + } + if (this._depthStencilBuffer) { + gl.deleteRenderbuffer(this._depthStencilBuffer); + this._depthStencilBuffer = null; + } + if (this._MSAAFramebuffer) { + gl.deleteFramebuffer(this._MSAAFramebuffer); + this._MSAAFramebuffer = null; + } + super.dispose(disposeOnlyFramebuffers); + } +} + +AbstractEngine.prototype.createDepthStencilTexture = function (size, options, rtWrapper) { + if (options.isCube) { + const width = size.width || size; + return this._createDepthStencilCubeTexture(width, options); + } + else { + return this._createDepthStencilTexture(size, options, rtWrapper); + } +}; + +ThinEngine.prototype._createHardwareRenderTargetWrapper = function (isMulti, isCube, size) { + const rtWrapper = new WebGLRenderTargetWrapper(isMulti, isCube, size, this, this._gl); + this._renderTargetWrapperCache.push(rtWrapper); + return rtWrapper; +}; +ThinEngine.prototype.createRenderTargetTexture = function (size, options) { + const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size); + let generateDepthBuffer = true; + let generateStencilBuffer = false; + let noColorAttachment = false; + let colorAttachment = undefined; + let samples = 1; + let label = undefined; + if (options !== undefined && typeof options === "object") { + generateDepthBuffer = options.generateDepthBuffer ?? true; + generateStencilBuffer = !!options.generateStencilBuffer; + noColorAttachment = !!options.noColorAttachment; + colorAttachment = options.colorAttachment; + samples = options.samples ?? 1; + label = options.label; + } + const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, 5 /* InternalTextureSource.RenderTarget */)); + const width = size.width || size; + const height = size.height || size; + const currentFrameBuffer = this._currentFramebuffer; + const gl = this._gl; + // Create the framebuffer + const framebuffer = gl.createFramebuffer(); + this._bindUnboundFramebuffer(framebuffer); + rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height); + // No need to rebind on every frame + if (texture && !texture.is2DArray && !texture.is3D) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._hardwareTexture.underlyingResource, 0); + } + this._bindUnboundFramebuffer(currentFrameBuffer); + rtWrapper.label = label ?? "RenderTargetWrapper"; + rtWrapper._framebuffer = framebuffer; + rtWrapper._generateDepthBuffer = generateDepthBuffer; + rtWrapper._generateStencilBuffer = generateStencilBuffer; + rtWrapper.setTextures(texture); + if (!colorAttachment) { + this.updateRenderTargetTextureSampleCount(rtWrapper, samples); + } + else { + rtWrapper._samples = colorAttachment.samples; + if (colorAttachment.samples > 1) { + const msaaRenderBuffer = colorAttachment._hardwareTexture.getMSAARenderBuffer(0); + rtWrapper._MSAAFramebuffer = gl.createFramebuffer(); + this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderBuffer); + this._bindUnboundFramebuffer(null); + } + } + return rtWrapper; +}; +ThinEngine.prototype._createDepthStencilTexture = function (size, options, rtWrapper) { + const gl = this._gl; + const layers = size.layers || 0; + const depth = size.depth || 0; + let target = gl.TEXTURE_2D; + if (layers !== 0) { + target = gl.TEXTURE_2D_ARRAY; + } + else if (depth !== 0) { + target = gl.TEXTURE_3D; + } + const internalTexture = new InternalTexture(this, 12 /* InternalTextureSource.DepthStencil */); + internalTexture.label = options.label; + if (!this._caps.depthTextureExtension) { + Logger.Error("Depth texture is not supported by your browser or hardware."); + return internalTexture; + } + const internalOptions = { + bilinearFiltering: false, + comparisonFunction: 0, + generateStencil: false, + ...options, + }; + this._bindTextureDirectly(target, internalTexture, true); + this._setupDepthStencilTexture(internalTexture, size, internalOptions.comparisonFunction === 0 ? false : internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples); + if (internalOptions.depthTextureFormat !== undefined) { + if (internalOptions.depthTextureFormat !== 15 && + internalOptions.depthTextureFormat !== 16 && + internalOptions.depthTextureFormat !== 17 && + internalOptions.depthTextureFormat !== 13 && + internalOptions.depthTextureFormat !== 14 && + internalOptions.depthTextureFormat !== 18) { + Logger.Error(`Depth texture ${internalOptions.depthTextureFormat} format is not supported.`); + return internalTexture; + } + internalTexture.format = internalOptions.depthTextureFormat; + } + else { + internalTexture.format = internalOptions.generateStencil ? 13 : 16; + } + const hasStencil = HasStencilAspect(internalTexture.format); + const type = this._getWebGLTextureTypeFromDepthTextureFormat(internalTexture.format); + const format = hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT; + const internalFormat = this._getInternalFormatFromDepthTextureFormat(internalTexture.format, true, hasStencil); + if (internalTexture.is2DArray) { + gl.texImage3D(target, 0, internalFormat, internalTexture.width, internalTexture.height, layers, 0, format, type, null); + } + else if (internalTexture.is3D) { + gl.texImage3D(target, 0, internalFormat, internalTexture.width, internalTexture.height, depth, 0, format, type, null); + } + else { + gl.texImage2D(target, 0, internalFormat, internalTexture.width, internalTexture.height, 0, format, type, null); + } + this._bindTextureDirectly(target, null); + this._internalTexturesCache.push(internalTexture); + if (rtWrapper._depthStencilBuffer) { + gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer); + rtWrapper._depthStencilBuffer = null; + } + this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer ?? rtWrapper._framebuffer); + rtWrapper._generateStencilBuffer = hasStencil; + rtWrapper._depthStencilTextureWithStencil = hasStencil; + rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.width, rtWrapper.height, rtWrapper.samples, internalTexture.format); + this._bindUnboundFramebuffer(null); + return internalTexture; +}; +ThinEngine.prototype.updateRenderTargetTextureSampleCount = function (rtWrapper, samples) { + if (this.webGLVersion < 2 || !rtWrapper) { + return 1; + } + if (rtWrapper.samples === samples) { + return samples; + } + const gl = this._gl; + samples = Math.min(samples, this.getCaps().maxMSAASamples); + // Dispose previous render buffers + if (rtWrapper._depthStencilBuffer) { + gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer); + rtWrapper._depthStencilBuffer = null; + } + if (rtWrapper._MSAAFramebuffer) { + gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer); + rtWrapper._MSAAFramebuffer = null; + } + const hardwareTexture = rtWrapper.texture?._hardwareTexture; + hardwareTexture?.releaseMSAARenderBuffers(); + if (rtWrapper.texture && samples > 1 && typeof gl.renderbufferStorageMultisample === "function") { + const framebuffer = gl.createFramebuffer(); + if (!framebuffer) { + throw new Error("Unable to create multi sampled framebuffer"); + } + rtWrapper._MSAAFramebuffer = framebuffer; + this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer); + const colorRenderbuffer = this._createRenderBuffer(rtWrapper.texture.width, rtWrapper.texture.height, samples, -1 /* not used */, this._getRGBABufferInternalSizedFormat(rtWrapper.texture.type, rtWrapper.texture.format, rtWrapper.texture._useSRGBBuffer), gl.COLOR_ATTACHMENT0, false); + if (!colorRenderbuffer) { + throw new Error("Unable to create multi sampled framebuffer"); + } + hardwareTexture?.addMSAARenderBuffer(colorRenderbuffer); + } + this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer ?? rtWrapper._framebuffer); + if (rtWrapper.texture) { + rtWrapper.texture.samples = samples; + } + rtWrapper._samples = samples; + const depthFormat = rtWrapper._depthStencilTexture ? rtWrapper._depthStencilTexture.format : undefined; + rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.width, rtWrapper.height, samples, depthFormat); + this._bindUnboundFramebuffer(null); + return samples; +}; +ThinEngine.prototype._setupDepthStencilTexture = function (internalTexture, size, bilinearFiltering, comparisonFunction, samples = 1) { + const width = size.width ?? size; + const height = size.height ?? size; + const layers = size.layers || 0; + const depth = size.depth || 0; + internalTexture.baseWidth = width; + internalTexture.baseHeight = height; + internalTexture.width = width; + internalTexture.height = height; + internalTexture.is2DArray = layers > 0; + internalTexture.depth = layers || depth; + internalTexture.isReady = true; + internalTexture.samples = samples; + internalTexture.generateMipMaps = false; + internalTexture.samplingMode = bilinearFiltering ? 2 : 1; + internalTexture.type = 0; + internalTexture._comparisonFunction = comparisonFunction; + const gl = this._gl; + const target = this._getTextureTarget(internalTexture); + const samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false); + gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag); + gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min); + gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + // TEXTURE_COMPARE_FUNC/MODE are only availble in WebGL2. + if (this.webGLVersion > 1) { + if (comparisonFunction === 0) { + gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, 515); + gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE); + } + else { + gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction); + gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE); + } + } +}; + +ThinEngine.prototype.setDepthStencilTexture = function (channel, uniform, texture, name) { + if (channel === undefined) { + return; + } + if (uniform) { + this._boundUniforms[channel] = uniform; + } + if (!texture || !texture.depthStencilTexture) { + this._setTexture(channel, null, undefined, undefined, name); + } + else { + this._setTexture(channel, texture, false, true, name); + } +}; + +ThinEngine.prototype.createRenderTargetCubeTexture = function (size, options) { + const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size); + const fullOptions = { + generateMipMaps: true, + generateDepthBuffer: true, + generateStencilBuffer: false, + type: 0, + samplingMode: 3, + format: 5, + ...options, + }; + fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer; + if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) { + // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE + fullOptions.samplingMode = 1; + } + else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) { + // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE + fullOptions.samplingMode = 1; + } + const gl = this._gl; + const texture = new InternalTexture(this, 5 /* InternalTextureSource.RenderTarget */); + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + const filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps); + if (fullOptions.type === 1 && !this._caps.textureFloat) { + fullOptions.type = 0; + Logger.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type"); + } + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + for (let face = 0; face < 6; face++) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null); + } + // Create the framebuffer + const framebuffer = gl.createFramebuffer(); + this._bindUnboundFramebuffer(framebuffer); + rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size); + // MipMaps + if (fullOptions.generateMipMaps) { + gl.generateMipmap(gl.TEXTURE_CUBE_MAP); + } + // Unbind + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + this._bindUnboundFramebuffer(null); + rtWrapper._framebuffer = framebuffer; + rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer; + rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer; + texture.width = size; + texture.height = size; + texture.isReady = true; + texture.isCube = true; + texture.samples = 1; + texture.generateMipMaps = fullOptions.generateMipMaps; + texture.samplingMode = fullOptions.samplingMode; + texture.type = fullOptions.type; + texture.format = fullOptions.format; + this._internalTexturesCache.push(texture); + rtWrapper.setTextures(texture); + return rtWrapper; +}; + +/** + * Constant used to convert a value to gamma space + * @ignorenaming + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +const ToGammaSpace = 1 / 2.2; +/** + * Constant used to convert a value to linear space + * @ignorenaming + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +const ToLinearSpace = 2.2; +/** + * Constant Golden Ratio value in Babylon.js + * @ignorenaming + */ +const PHI = (1 + Math.sqrt(5)) / 2; +/** + * Constant used to define the minimal number value in Babylon.js + * @ignorenaming + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +const Epsilon = 0.001; + +/* eslint-disable @typescript-eslint/naming-convention */ +/** + * Returns an array of the given size filled with elements built from the given constructor and the parameters. + * @param size the number of element to construct and put in the array. + * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry. + * @returns a new array filled with new objects. + */ +function BuildArray(size, itemBuilder) { + const a = []; + for (let i = 0; i < size; ++i) { + a.push(itemBuilder()); + } + return a; +} +/** + * Returns a tuple of the given size filled with elements built from the given constructor and the parameters. + * @param size he number of element to construct and put in the tuple. + * @param itemBuilder a callback responsible for creating new instance of item. Called once per tuple entry. + * @returns a new tuple filled with new objects. + */ +function BuildTuple(size, itemBuilder) { + return BuildArray(size, itemBuilder); +} +/** + * Observes a function and calls the given callback when it is called. + * @param object Defines the object the function to observe belongs to. + * @param functionName Defines the name of the function to observe. + * @param callback Defines the callback to call when the function is called. + * @returns A function to call to stop observing + */ +function _observeArrayfunction(object, functionName, callback) { + // Finds the function to observe + const oldFunction = object[functionName]; + if (typeof oldFunction !== "function") { + return null; + } + // Creates a new function that calls the callback and the old function + const newFunction = function () { + const previousLength = object.length; + const returnValue = newFunction.previous.apply(object, arguments); + callback(functionName, previousLength); + return returnValue; + }; + // Doublishly links the new function and the old function + oldFunction.next = newFunction; + newFunction.previous = oldFunction; + // Replaces the old function with the new function + object[functionName] = newFunction; + // Returns a function to disable the hook + return () => { + // Only unhook if the function is still hooked + const previous = newFunction.previous; + if (!previous) { + return; + } + // Finds the ref to the next function in the chain + const next = newFunction.next; + // If in the middle of the chain, link the previous and next functions + if (next) { + previous.next = next; + next.previous = previous; + } + // If at the end of the chain, remove the reference to the previous function + // and restore the previous function + else { + previous.next = undefined; + object[functionName] = previous; + } + // Lose reference to the previous and next functions + newFunction.next = undefined; + newFunction.previous = undefined; + }; +} +/** + * Defines the list of functions to proxy when observing an array. + * The scope is currently reduced to the common functions used in the render target render list and the scene cameras. + */ +const observedArrayFunctions = ["push", "splice", "pop", "shift", "unshift"]; +/** + * Observes an array and notifies the given observer when the array is modified. + * @param array Defines the array to observe + * @param callback Defines the function to call when the array is modified (in the limit of the observed array functions) + * @returns A function to call to stop observing the array + * @internal + */ +function _ObserveArray(array, callback) { + // Observes all the required array functions and stores the unhook functions + const unObserveFunctions = observedArrayFunctions.map((name) => { + return _observeArrayfunction(array, name, callback); + }); + // Returns a function that unhook all the observed functions + return () => { + unObserveFunctions.forEach((unObserveFunction) => { + unObserveFunction?.(); + }); + }; +} + +/** @internal */ +// eslint-disable-next-line @typescript-eslint/naming-convention +const _RegisteredTypes = {}; +/** + * @internal + */ +function RegisterClass(className, type) { + _RegisteredTypes[className] = type; +} +/** + * @internal + */ +function GetClass(fqdn) { + return _RegisteredTypes[fqdn]; +} + +/** + * Extract int value + * @param value number value + * @returns int value + */ +function ExtractAsInt(value) { + return parseInt(value.toString().replace(/\W/g, "")); +} +/** + * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45) + * @param a number + * @param b number + * @param epsilon (default = 1.401298E-45) + * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45) + */ +function WithinEpsilon(a, b, epsilon = 1.401298e-45) { + return Math.abs(a - b) <= epsilon; +} +/** + * Boolean : true if the number is outside a range + * @param num number + * @param min min value + * @param max max value + * @param epsilon (default = Number.EPSILON) + * @returns true if the number is between min and max values + */ +function OutsideRange(num, min, max, epsilon = 1.401298e-45) { + return num < min - epsilon || num > max + epsilon; +} +/** + * Returns a random float number between and min and max values + * @param min min value of random + * @param max max value of random + * @returns random value + */ +function RandomRange(min, max) { + if (min === max) { + return min; + } + return Math.random() * (max - min) + min; +} +/** + * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar. + * @param start start value + * @param end target value + * @param amount amount to lerp between + * @returns the lerped value + */ +function Lerp(start, end, amount) { + return start + (end - start) * amount; +} +/** + * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees. + * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees. + * @param start start value + * @param end target value + * @param amount amount to lerp between + * @returns the lerped value + */ +function LerpAngle(start, end, amount) { + let num = Repeat(end - start, 360.0); + if (num > 180.0) { + num -= 360.0; + } + return start + num * Clamp(amount); +} +/** + * Calculates the linear parameter t that produces the interpolant value within the range [a, b]. + * @param a start value + * @param b target value + * @param value value between a and b + * @returns the inverseLerp value + */ +function InverseLerp(a, b, value) { + let result = 0; + if (a != b) { + result = Clamp((value - a) / (b - a)); + } + else { + result = 0.0; + } + return result; +} +/** + * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2". + * @see http://mathworld.wolfram.com/HermitePolynomial.html + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param amount defines the amount on the interpolation spline (between 0 and 1) + * @returns hermite result + */ +function Hermite(value1, tangent1, value2, tangent2, amount) { + const squared = amount * amount; + const cubed = amount * squared; + const part1 = 2.0 * cubed - 3.0 * squared + 1.0; + const part2 = -2 * cubed + 3.0 * squared; + const part3 = cubed - 2.0 * squared + amount; + const part4 = cubed - squared; + return value1 * part1 + value2 * part2 + tangent1 * part3 + tangent2 * part4; +} +/** + * Returns a new scalar which is the 1st derivative of the Hermite spline defined by the scalars "value1", "value2", "tangent1", "tangent2". + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @returns 1st derivative + */ +function Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { + const t2 = time * time; + return (t2 - time) * 6 * value1 + (3 * t2 - 4 * time + 1) * tangent1 + (-t2 + time) * 6 * value2 + (3 * t2 - 2 * time) * tangent2; +} +/** + * Returns the value itself if it's between min and max. + * Returns min if the value is lower than min. + * Returns max if the value is greater than max. + * @param value the value to clmap + * @param min the min value to clamp to (default: 0) + * @param max the max value to clamp to (default: 1) + * @returns the clamped value + */ +function Clamp(value, min = 0, max = 1) { + return Math.min(max, Math.max(min, value)); +} +/** + * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians. + * @param angle The angle to normalize in radian. + * @returns The converted angle. + */ +function NormalizeRadians(angle) { + // More precise but slower version kept for reference. + // angle = angle % Tools.TwoPi; + // angle = (angle + Tools.TwoPi) % Tools.TwoPi; + //if (angle > Math.PI) { + // angle -= Tools.TwoPi; + //} + angle -= Math.PI * 2 * Math.floor((angle + Math.PI) / (Math.PI * 2)); + return angle; +} +/** + * Returns a string : the upper case translation of the number i to hexadecimal. + * @param i number + * @returns the upper case translation of the number i to hexadecimal. + */ +function ToHex(i) { + const str = i.toString(16); + if (i <= 15) { + return ("0" + str).toUpperCase(); + } + return str.toUpperCase(); +} +/** + * the floor part of a log2 value. + * @param value the value to compute log2 of + * @returns the log2 of value. + */ +function ILog2(value) { + if (Math.log2) { + return Math.floor(Math.log2(value)); + } + if (value < 0) { + return NaN; + } + else if (value === 0) { + return -Infinity; + } + let n = 0; + if (value < 1) { + while (value < 1) { + n++; + value = value * 2; + } + n = -n; + } + else if (value > 1) { + while (value > 1) { + n++; + value = Math.floor(value / 2); + } + } + return n; +} +/** + * Loops the value, so that it is never larger than length and never smaller than 0. + * + * This is similar to the modulo operator but it works with floating point numbers. + * For example, using 3.0 for t and 2.5 for length, the result would be 0.5. + * With t = 5 and length = 2.5, the result would be 0.0. + * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator + * @param value the value + * @param length the length + * @returns the looped value + */ +function Repeat(value, length) { + return value - Math.floor(value / length) * length; +} +/** + * Normalize the value between 0.0 and 1.0 using min and max values + * @param value value to normalize + * @param min max to normalize between + * @param max min to normalize between + * @returns the normalized value + */ +function Normalize(value, min, max) { + return (value - min) / (max - min); +} +/** + * Denormalize the value from 0.0 and 1.0 using min and max values + * @param normalized value to denormalize + * @param min max to denormalize between + * @param max min to denormalize between + * @returns the denormalized value + */ +function Denormalize(normalized, min, max) { + return normalized * (max - min) + min; +} +/** + * Calculates the shortest difference between two given angles given in degrees. + * @param current current angle in degrees + * @param target target angle in degrees + * @returns the delta + */ +function DeltaAngle(current, target) { + let num = Repeat(target - current, 360.0); + if (num > 180.0) { + num -= 360.0; + } + return num; +} +/** + * PingPongs the value t, so that it is never larger than length and never smaller than 0. + * @param tx value + * @param length length + * @returns The returned value will move back and forth between 0 and length + */ +function PingPong(tx, length) { + const t = Repeat(tx, length * 2.0); + return length - Math.abs(t - length); +} +/** + * Interpolates between min and max with smoothing at the limits. + * + * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up + * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions. + * @param from from + * @param to to + * @param tx value + * @returns the smooth stepped value + */ +function SmoothStep(from, to, tx) { + let t = Clamp(tx); + t = -2 * t * t * t + 3.0 * t * t; + return to * t + from * (1.0 - t); +} +/** + * Moves a value current towards target. + * + * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta. + * Negative values of maxDelta pushes the value away from target. + * @param current current value + * @param target target value + * @param maxDelta max distance to move + * @returns resulting value + */ +function MoveTowards(current, target, maxDelta) { + let result = 0; + if (Math.abs(target - current) <= maxDelta) { + result = target; + } + else { + result = current + Math.sign(target - current) * maxDelta; + } + return result; +} +/** + * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees. + * + * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta + * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead. + * @param current current value + * @param target target value + * @param maxDelta max distance to move + * @returns resulting angle + */ +function MoveTowardsAngle(current, target, maxDelta) { + const num = DeltaAngle(current, target); + let result = 0; + if (-maxDelta < num && num < maxDelta) { + result = target; + } + else { + target = current + num; + result = MoveTowards(current, target, maxDelta); + } + return result; +} +/** + * This function returns percentage of a number in a given range. + * + * RangeToPercent(40,20,60) will return 0.5 (50%) + * RangeToPercent(34,0,100) will return 0.34 (34%) + * @param number to convert to percentage + * @param min min range + * @param max max range + * @returns the percentage + */ +function RangeToPercent(number, min, max) { + return (number - min) / (max - min); +} +/** + * This function returns number that corresponds to the percentage in a given range. + * + * PercentToRange(0.34,0,100) will return 34. + * @param percent to convert to number + * @param min min range + * @param max max range + * @returns the number + */ +function PercentToRange(percent, min, max) { + return (max - min) * percent + min; +} +/** + * Returns the highest common factor of two integers. + * @param a first parameter + * @param b second parameter + * @returns HCF of a and b + */ +function HighestCommonFactor(a, b) { + const r = a % b; + if (r === 0) { + return b; + } + return HighestCommonFactor(b, r); +} + +const functions = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + Clamp, + DeltaAngle, + Denormalize, + ExtractAsInt, + Hermite, + Hermite1stDerivative, + HighestCommonFactor, + ILog2, + InverseLerp, + Lerp, + LerpAngle, + MoveTowards, + MoveTowardsAngle, + Normalize, + NormalizeRadians, + OutsideRange, + PercentToRange, + PingPong, + RandomRange, + RangeToPercent, + Repeat, + SmoothStep, + ToHex, + WithinEpsilon +}, Symbol.toStringTag, { value: 'Module' })); + +/* eslint-disable @typescript-eslint/naming-convention */ +// eslint-disable-next-line @typescript-eslint/naming-convention +const _ExtractAsInt = (value) => { + return parseInt(value.toString().replace(/\W/g, "")); +}; +/** + * Class representing a vector containing 2 coordinates + * Example Playground - Overview - https://playground.babylonjs.com/#QYBWV4#9 + */ +class Vector2 { + /** + * Creates a new Vector2 from the given x and y coordinates + * @param x defines the first coordinate + * @param y defines the second coordinate + */ + constructor( + /** [0] defines the first coordinate */ + x = 0, + /** [0] defines the second coordinate */ + y = 0) { + this.x = x; + this.y = y; + } + /** + * Gets a string with the Vector2 coordinates + * @returns a string with the Vector2 coordinates + */ + toString() { + return `{X: ${this.x} Y: ${this.y}}`; + } + /** + * Gets class name + * @returns the string "Vector2" + */ + getClassName() { + return "Vector2"; + } + /** + * Gets current vector hash code + * @returns the Vector2 hash code as a number + */ + getHashCode() { + const x = _ExtractAsInt(this.x); + const y = _ExtractAsInt(this.y); + let hash = x; + hash = (hash * 397) ^ y; + return hash; + } + // Operators + /** + * Sets the Vector2 coordinates in the given array or Float32Array from the given index. + * Example Playground https://playground.babylonjs.com/#QYBWV4#15 + * @param array defines the source array + * @param index defines the offset in source array + * @returns the current Vector2 + */ + toArray(array, index = 0) { + array[index] = this.x; + array[index + 1] = this.y; + return this; + } + /** + * Update the current vector from an array + * Example Playground https://playground.babylonjs.com/#QYBWV4#39 + * @param array defines the destination array + * @param offset defines the offset in the destination array + * @returns the current Vector2 + */ + fromArray(array, offset = 0) { + Vector2.FromArrayToRef(array, offset, this); + return this; + } + /** + * Copy the current vector to an array + * Example Playground https://playground.babylonjs.com/#QYBWV4#40 + * @returns a new array with 2 elements: the Vector2 coordinates. + */ + asArray() { + return [this.x, this.y]; + } + /** + * Sets the Vector2 coordinates with the given Vector2 coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#24 + * @param source defines the source Vector2 + * @returns the current updated Vector2 + */ + copyFrom(source) { + this.x = source.x; + this.y = source.y; + return this; + } + /** + * Sets the Vector2 coordinates with the given floats + * Example Playground https://playground.babylonjs.com/#QYBWV4#25 + * @param x defines the first coordinate + * @param y defines the second coordinate + * @returns the current updated Vector2 + */ + copyFromFloats(x, y) { + this.x = x; + this.y = y; + return this; + } + /** + * Sets the Vector2 coordinates with the given floats + * Example Playground https://playground.babylonjs.com/#QYBWV4#62 + * @param x defines the first coordinate + * @param y defines the second coordinate + * @returns the current updated Vector2 + */ + set(x, y) { + return this.copyFromFloats(x, y); + } + /** + * Copies the given float to the current Vector2 coordinates + * @param v defines the x and y coordinates of the operand + * @returns the current updated Vector2 + */ + setAll(v) { + return this.copyFromFloats(v, v); + } + /** + * Add another vector with the current one + * Example Playground https://playground.babylonjs.com/#QYBWV4#11 + * @param otherVector defines the other vector + * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates + */ + add(otherVector) { + return new Vector2(this.x + otherVector.x, this.y + otherVector.y); + } + /** + * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#12 + * @param otherVector defines the other vector + * @param result defines the target vector + * @returns result input + */ + addToRef(otherVector, result) { + result.x = this.x + otherVector.x; + result.y = this.y + otherVector.y; + return result; + } + /** + * Set the Vector2 coordinates by adding the given Vector2 coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#13 + * @param otherVector defines the other vector + * @returns the current updated Vector2 + */ + addInPlace(otherVector) { + this.x += otherVector.x; + this.y += otherVector.y; + return this; + } + /** + * Adds the given coordinates to the current Vector2 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @returns the current updated Vector2 + */ + addInPlaceFromFloats(x, y) { + this.x += x; + this.y += y; + return this; + } + /** + * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#14 + * @param otherVector defines the other vector + * @returns a new Vector2 + */ + addVector3(otherVector) { + return new Vector2(this.x + otherVector.x, this.y + otherVector.y); + } + /** + * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2 + * Example Playground https://playground.babylonjs.com/#QYBWV4#61 + * @param otherVector defines the other vector + * @returns a new Vector2 + */ + subtract(otherVector) { + return new Vector2(this.x - otherVector.x, this.y - otherVector.y); + } + /** + * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates. + * Example Playground https://playground.babylonjs.com/#QYBWV4#63 + * @param otherVector defines the other vector + * @param result defines the target vector + * @returns result input + */ + subtractToRef(otherVector, result) { + result.x = this.x - otherVector.x; + result.y = this.y - otherVector.y; + return result; + } + /** + * Sets the current Vector2 coordinates by subtracting from it the given one coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#88 + * @param otherVector defines the other vector + * @returns the current updated Vector2 + */ + subtractInPlace(otherVector) { + this.x -= otherVector.x; + this.y -= otherVector.y; + return this; + } + /** + * Multiplies in place the current Vector2 coordinates by the given ones + * Example Playground https://playground.babylonjs.com/#QYBWV4#43 + * @param otherVector defines the other vector + * @returns the current updated Vector2 + */ + multiplyInPlace(otherVector) { + this.x *= otherVector.x; + this.y *= otherVector.y; + return this; + } + /** + * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#42 + * @param otherVector defines the other vector + * @returns a new Vector2 + */ + multiply(otherVector) { + return new Vector2(this.x * otherVector.x, this.y * otherVector.y); + } + /** + * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#44 + * @param otherVector defines the other vector + * @param result defines the target vector + * @returns result input + */ + multiplyToRef(otherVector, result) { + result.x = this.x * otherVector.x; + result.y = this.y * otherVector.y; + return result; + } + /** + * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats + * Example Playground https://playground.babylonjs.com/#QYBWV4#89 + * @param x defines the first coordinate + * @param y defines the second coordinate + * @returns a new Vector2 + */ + multiplyByFloats(x, y) { + return new Vector2(this.x * x, this.y * y); + } + /** + * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#27 + * @param otherVector defines the other vector + * @returns a new Vector2 + */ + divide(otherVector) { + return new Vector2(this.x / otherVector.x, this.y / otherVector.y); + } + /** + * Sets the "result" coordinates with the Vector2 divided by the given one coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#30 + * @param otherVector defines the other vector + * @param result defines the target vector + * @returns result input + */ + divideToRef(otherVector, result) { + result.x = this.x / otherVector.x; + result.y = this.y / otherVector.y; + return result; + } + /** + * Divides the current Vector2 coordinates by the given ones + * Example Playground https://playground.babylonjs.com/#QYBWV4#28 + * @param otherVector defines the other vector + * @returns the current updated Vector2 + */ + divideInPlace(otherVector) { + this.x = this.x / otherVector.x; + this.y = this.y / otherVector.y; + return this; + } + /** + * Updates the current Vector2 with the minimal coordinate values between its and the given vector ones + * @param other defines the second operand + * @returns the current updated Vector2 + */ + minimizeInPlace(other) { + return this.minimizeInPlaceFromFloats(other.x, other.y); + } + /** + * Updates the current Vector2 with the maximal coordinate values between its and the given vector ones. + * @param other defines the second operand + * @returns the current updated Vector2 + */ + maximizeInPlace(other) { + return this.maximizeInPlaceFromFloats(other.x, other.y); + } + /** + * Updates the current Vector2 with the minimal coordinate values between its and the given coordinates + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @returns the current updated Vector2 + */ + minimizeInPlaceFromFloats(x, y) { + this.x = Math.min(x, this.x); + this.y = Math.min(y, this.y); + return this; + } + /** + * Updates the current Vector2 with the maximal coordinate values between its and the given coordinates. + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @returns the current updated Vector2 + */ + maximizeInPlaceFromFloats(x, y) { + this.x = Math.max(x, this.x); + this.y = Math.max(y, this.y); + return this; + } + /** + * Returns a new Vector2 set with the subtraction of the given floats from the current Vector2 coordinates + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @returns the resulting Vector2 + */ + subtractFromFloats(x, y) { + return new Vector2(this.x - x, this.y - y); + } + /** + * Subtracts the given floats from the current Vector2 coordinates and set the given vector "result" with this result + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param result defines the Vector2 object where to store the result + * @returns the result + */ + subtractFromFloatsToRef(x, y, result) { + result.x = this.x - x; + result.y = this.y - y; + return result; + } + /** + * Gets a new Vector2 with current Vector2 negated coordinates + * @returns a new Vector2 + */ + negate() { + return new Vector2(-this.x, -this.y); + } + /** + * Negate this vector in place + * Example Playground https://playground.babylonjs.com/#QYBWV4#23 + * @returns this + */ + negateInPlace() { + this.x *= -1; + this.y *= -1; + return this; + } + /** + * Negate the current Vector2 and stores the result in the given vector "result" coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#41 + * @param result defines the Vector3 object where to store the result + * @returns the result + */ + negateToRef(result) { + result.x = -this.x; + result.y = -this.y; + return result; + } + /** + * Multiply the Vector2 coordinates by + * Example Playground https://playground.babylonjs.com/#QYBWV4#59 + * @param scale defines the scaling factor + * @returns the current updated Vector2 + */ + scaleInPlace(scale) { + this.x *= scale; + this.y *= scale; + return this; + } + /** + * Returns a new Vector2 scaled by "scale" from the current Vector2 + * Example Playground https://playground.babylonjs.com/#QYBWV4#52 + * @param scale defines the scaling factor + * @returns a new Vector2 + */ + scale(scale) { + return new Vector2(this.x * scale, this.y * scale); + } + /** + * Scale the current Vector2 values by a factor to a given Vector2 + * Example Playground https://playground.babylonjs.com/#QYBWV4#57 + * @param scale defines the scale factor + * @param result defines the Vector2 object where to store the result + * @returns result input + */ + scaleToRef(scale, result) { + result.x = this.x * scale; + result.y = this.y * scale; + return result; + } + /** + * Scale the current Vector2 values by a factor and add the result to a given Vector2 + * Example Playground https://playground.babylonjs.com/#QYBWV4#58 + * @param scale defines the scale factor + * @param result defines the Vector2 object where to store the result + * @returns result input + */ + scaleAndAddToRef(scale, result) { + result.x += this.x * scale; + result.y += this.y * scale; + return result; + } + /** + * Gets a boolean if two vectors are equals + * Example Playground https://playground.babylonjs.com/#QYBWV4#31 + * @param otherVector defines the other vector + * @returns true if the given vector coordinates strictly equal the current Vector2 ones + */ + equals(otherVector) { + return otherVector && this.x === otherVector.x && this.y === otherVector.y; + } + /** + * Gets a boolean if two vectors are equals (using an epsilon value) + * Example Playground https://playground.babylonjs.com/#QYBWV4#32 + * @param otherVector defines the other vector + * @param epsilon defines the minimal distance to consider equality + * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon. + */ + equalsWithEpsilon(otherVector, epsilon = Epsilon) { + return otherVector && WithinEpsilon(this.x, otherVector.x, epsilon) && WithinEpsilon(this.y, otherVector.y, epsilon); + } + /** + * Returns true if the current Vector2 coordinates equals the given floats + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @returns true if both vectors are equal + */ + equalsToFloats(x, y) { + return this.x === x && this.y === y; + } + /** + * Gets a new Vector2 from current Vector2 floored values + * Example Playground https://playground.babylonjs.com/#QYBWV4#35 + * eg (1.2, 2.31) returns (1, 2) + * @returns a new Vector2 + */ + floor() { + return new Vector2(Math.floor(this.x), Math.floor(this.y)); + } + /** + * Gets the current Vector2's floored values and stores them in result + * @param result the Vector2 to store the result in + * @returns the result Vector2 + */ + floorToRef(result) { + result.x = Math.floor(this.x); + result.y = Math.floor(this.y); + return result; + } + /** + * Gets a new Vector2 from current Vector2 fractional values + * Example Playground https://playground.babylonjs.com/#QYBWV4#34 + * eg (1.2, 2.31) returns (0.2, 0.31) + * @returns a new Vector2 + */ + fract() { + return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y)); + } + /** + * Gets the current Vector2's fractional values and stores them in result + * @param result the Vector2 to store the result in + * @returns the result Vector2 + */ + fractToRef(result) { + result.x = this.x - Math.floor(this.x); + result.y = this.y - Math.floor(this.y); + return result; + } + /** + * Rotate the current vector into a given result vector + * Example Playground https://playground.babylonjs.com/#QYBWV4#49 + * @param angle defines the rotation angle + * @param result defines the result vector where to store the rotated vector + * @returns result input + */ + rotateToRef(angle, result) { + const cos = Math.cos(angle); + const sin = Math.sin(angle); + const x = cos * this.x - sin * this.y; + const y = sin * this.x + cos * this.y; + result.x = x; + result.y = y; + return result; + } + // Properties + /** + * Gets the length of the vector + * @returns the vector length (float) + */ + length() { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + /** + * Gets the vector squared length + * @returns the vector squared length (float) + */ + lengthSquared() { + return this.x * this.x + this.y * this.y; + } + // Methods + /** + * Normalize the vector + * Example Playground https://playground.babylonjs.com/#QYBWV4#48 + * @returns the current updated Vector2 + */ + normalize() { + return this.normalizeFromLength(this.length()); + } + /** + * Normalize the current Vector2 with the given input length. + * Please note that this is an in place operation. + * @param len the length of the vector + * @returns the current updated Vector2 + */ + normalizeFromLength(len) { + if (len === 0 || len === 1.0) { + return this; + } + return this.scaleInPlace(1.0 / len); + } + /** + * Normalize the current Vector2 to a new vector + * @returns the new Vector2 + */ + normalizeToNew() { + const normalized = new Vector2(); + this.normalizeToRef(normalized); + return normalized; + } + /** + * Normalize the current Vector2 to the reference + * @param result define the Vector to update + * @returns the updated Vector2 + */ + normalizeToRef(result) { + const len = this.length(); + if (len === 0) { + result.x = this.x; + result.y = this.y; + } + return this.scaleToRef(1.0 / len, result); + } + /** + * Gets a new Vector2 copied from the Vector2 + * Example Playground https://playground.babylonjs.com/#QYBWV4#20 + * @returns a new Vector2 + */ + clone() { + return new Vector2(this.x, this.y); + } + /** + * Gets the dot product of the current vector and the vector "otherVector" + * @param otherVector defines second vector + * @returns the dot product (float) + */ + dot(otherVector) { + return this.x * otherVector.x + this.y * otherVector.y; + } + // Statics + /** + * Gets a new Vector2(0, 0) + * @returns a new Vector2 + */ + static Zero() { + return new Vector2(0, 0); + } + /** + * Gets a new Vector2(1, 1) + * @returns a new Vector2 + */ + static One() { + return new Vector2(1, 1); + } + /** + * Returns a new Vector2 with random values between min and max + * @param min the minimum random value + * @param max the maximum random value + * @returns a Vector2 with random values between min and max + */ + static Random(min = 0, max = 1) { + return new Vector2(RandomRange(min, max), RandomRange(min, max)); + } + /** + * Sets a Vector2 with random values between min and max + * @param min the minimum random value + * @param max the maximum random value + * @param ref the ref to store the values in + * @returns the ref with random values between min and max + */ + static RandomToRef(min = 0, max = 1, ref) { + return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max)); + } + /** + * Gets a zero Vector2 that must not be updated + */ + static get ZeroReadOnly() { + return Vector2._ZeroReadOnly; + } + /** + * Gets a new Vector2 set from the given index element of the given array + * Example Playground https://playground.babylonjs.com/#QYBWV4#79 + * @param array defines the data source + * @param offset defines the offset in the data source + * @returns a new Vector2 + */ + static FromArray(array, offset = 0) { + return new Vector2(array[offset], array[offset + 1]); + } + /** + * Sets "result" from the given index element of the given array + * Example Playground https://playground.babylonjs.com/#QYBWV4#80 + * @param array defines the data source + * @param offset defines the offset in the data source + * @param result defines the target vector + * @returns result input + */ + static FromArrayToRef(array, offset, result) { + result.x = array[offset]; + result.y = array[offset + 1]; + return result; + } + /** + * Sets the given vector "result" with the given floats. + * @param x defines the x coordinate of the source + * @param y defines the y coordinate of the source + * @param result defines the Vector2 where to store the result + * @returns the result vector + */ + static FromFloatsToRef(x, y, result) { + result.copyFromFloats(x, y); + return result; + } + /** + * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2 + * Example Playground https://playground.babylonjs.com/#QYBWV4#65 + * @param value1 defines 1st point of control + * @param value2 defines 2nd point of control + * @param value3 defines 3rd point of control + * @param value4 defines 4th point of control + * @param amount defines the interpolation factor + * @returns a new Vector2 + */ + static CatmullRom(value1, value2, value3, value4, amount) { + const squared = amount * amount; + const cubed = amount * squared; + const x = 0.5 * + (2.0 * value2.x + + (-value1.x + value3.x) * amount + + (2.0 * value1.x - 5.0 * value2.x + 4.0 * value3.x - value4.x) * squared + + (-value1.x + 3.0 * value2.x - 3.0 * value3.x + value4.x) * cubed); + const y = 0.5 * + (2.0 * value2.y + + (-value1.y + value3.y) * amount + + (2.0 * value1.y - 5.0 * value2.y + 4.0 * value3.y - value4.y) * squared + + (-value1.y + 3.0 * value2.y - 3.0 * value3.y + value4.y) * cubed); + return new Vector2(x, y); + } + /** + * Sets reference with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max". + * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate. + * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate + * @param value defines the value to clamp + * @param min defines the lower limit + * @param max defines the upper limit + * @param ref the reference + * @returns the reference + */ + static ClampToRef(value, min, max, ref) { + ref.x = Clamp(value.x, min.x, max.x); + ref.y = Clamp(value.y, min.y, max.y); + return ref; + } + /** + * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max". + * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate. + * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate + * Example Playground https://playground.babylonjs.com/#QYBWV4#76 + * @param value defines the value to clamp + * @param min defines the lower limit + * @param max defines the upper limit + * @returns a new Vector2 + */ + static Clamp(value, min, max) { + const x = Clamp(value.x, min.x, max.x); + const y = Clamp(value.y, min.y, max.y); + return new Vector2(x, y); + } + /** + * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2" + * Example Playground https://playground.babylonjs.com/#QYBWV4#81 + * @param value1 defines the 1st control point + * @param tangent1 defines the outgoing tangent + * @param value2 defines the 2nd control point + * @param tangent2 defines the incoming tangent + * @param amount defines the interpolation factor + * @returns a new Vector2 + */ + static Hermite(value1, tangent1, value2, tangent2, amount) { + const squared = amount * amount; + const cubed = amount * squared; + const part1 = 2.0 * cubed - 3.0 * squared + 1.0; + const part2 = -2 * cubed + 3.0 * squared; + const part3 = cubed - 2.0 * squared + amount; + const part4 = cubed - squared; + const x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4; + const y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4; + return new Vector2(x, y); + } + /** + * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". + * Example Playground https://playground.babylonjs.com/#QYBWV4#82 + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @returns 1st derivative + */ + static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { + return this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, new Vector2()); + } + /** + * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". + * Example Playground https://playground.babylonjs.com/#QYBWV4#83 + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @param result define where the derivative will be stored + * @returns result input + */ + static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { + const t2 = time * time; + result.x = (t2 - time) * 6 * value1.x + (3 * t2 - 4 * time + 1) * tangent1.x + (-t2 + time) * 6 * value2.x + (3 * t2 - 2 * time) * tangent2.x; + result.y = (t2 - time) * 6 * value1.y + (3 * t2 - 4 * time + 1) * tangent1.y + (-t2 + time) * 6 * value2.y + (3 * t2 - 2 * time) * tangent2.y; + return result; + } + /** + * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end". + * Example Playground https://playground.babylonjs.com/#QYBWV4#84 + * @param start defines the start vector + * @param end defines the end vector + * @param amount defines the interpolation factor + * @returns a new Vector2 + */ + static Lerp(start, end, amount) { + return Vector2.LerpToRef(start, end, amount, new Vector2()); + } + /** + * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end" + * @param start defines the start value + * @param end defines the end value + * @param amount max defines amount between both (between 0 and 1) + * @param result defines the Vector2 where to store the result + * @returns result input + */ + static LerpToRef(start, end, amount, result) { + result.x = start.x + (end.x - start.x) * amount; + result.y = start.y + (end.y - start.y) * amount; + return result; + } + /** + * Gets the dot product of the vector "left" and the vector "right" + * Example Playground https://playground.babylonjs.com/#QYBWV4#90 + * @param left defines first vector + * @param right defines second vector + * @returns the dot product (float) + */ + static Dot(left, right) { + return left.x * right.x + left.y * right.y; + } + /** + * Returns a new Vector2 equal to the normalized given vector + * Example Playground https://playground.babylonjs.com/#QYBWV4#46 + * @param vector defines the vector to normalize + * @returns a new Vector2 + */ + static Normalize(vector) { + return Vector2.NormalizeToRef(vector, new Vector2()); + } + /** + * Normalize a given vector into a second one + * Example Playground https://playground.babylonjs.com/#QYBWV4#50 + * @param vector defines the vector to normalize + * @param result defines the vector where to store the result + * @returns result input + */ + static NormalizeToRef(vector, result) { + vector.normalizeToRef(result); + return result; + } + /** + * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors + * Example Playground https://playground.babylonjs.com/#QYBWV4#86 + * @param left defines 1st vector + * @param right defines 2nd vector + * @returns a new Vector2 + */ + static Minimize(left, right) { + const x = left.x < right.x ? left.x : right.x; + const y = left.y < right.y ? left.y : right.y; + return new Vector2(x, y); + } + /** + * Gets a new Vector2 set with the maximal coordinate values from the "left" and "right" vectors + * Example Playground https://playground.babylonjs.com/#QYBWV4#86 + * @param left defines 1st vector + * @param right defines 2nd vector + * @returns a new Vector2 + */ + static Maximize(left, right) { + const x = left.x > right.x ? left.x : right.x; + const y = left.y > right.y ? left.y : right.y; + return new Vector2(x, y); + } + /** + * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix + * Example Playground https://playground.babylonjs.com/#QYBWV4#17 + * @param vector defines the vector to transform + * @param transformation defines the matrix to apply + * @returns a new Vector2 + */ + static Transform(vector, transformation) { + return Vector2.TransformToRef(vector, transformation, new Vector2()); + } + /** + * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates + * Example Playground https://playground.babylonjs.com/#QYBWV4#19 + * @param vector defines the vector to transform + * @param transformation defines the matrix to apply + * @param result defines the target vector + * @returns result input + */ + static TransformToRef(vector, transformation, result) { + const m = transformation.m; + const x = vector.x * m[0] + vector.y * m[4] + m[12]; + const y = vector.x * m[1] + vector.y * m[5] + m[13]; + result.x = x; + result.y = y; + return result; + } + /** + * Determines if a given vector is included in a triangle + * Example Playground https://playground.babylonjs.com/#QYBWV4#87 + * @param p defines the vector to test + * @param p0 defines 1st triangle point + * @param p1 defines 2nd triangle point + * @param p2 defines 3rd triangle point + * @returns true if the point "p" is in the triangle defined by the vectors "p0", "p1", "p2" + */ + static PointInTriangle(p, p0, p1, p2) { + const a = (1 / 2) * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y); + const sign = a < 0 ? -1 : 1; + const s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign; + const t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign; + return s > 0 && t > 0 && s + t < 2 * a * sign; + } + /** + * Gets the distance between the vectors "value1" and "value2" + * Example Playground https://playground.babylonjs.com/#QYBWV4#71 + * @param value1 defines first vector + * @param value2 defines second vector + * @returns the distance between vectors + */ + static Distance(value1, value2) { + return Math.sqrt(Vector2.DistanceSquared(value1, value2)); + } + /** + * Returns the squared distance between the vectors "value1" and "value2" + * Example Playground https://playground.babylonjs.com/#QYBWV4#72 + * @param value1 defines first vector + * @param value2 defines second vector + * @returns the squared distance between vectors + */ + static DistanceSquared(value1, value2) { + const x = value1.x - value2.x; + const y = value1.y - value2.y; + return x * x + y * y; + } + /** + * Gets a new Vector2 located at the center of the vectors "value1" and "value2" + * Example Playground https://playground.babylonjs.com/#QYBWV4#86 + * Example Playground https://playground.babylonjs.com/#QYBWV4#66 + * @param value1 defines first vector + * @param value2 defines second vector + * @returns a new Vector2 + */ + static Center(value1, value2) { + return Vector2.CenterToRef(value1, value2, new Vector2()); + } + /** + * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref" + * Example Playground https://playground.babylonjs.com/#QYBWV4#66 + * @param value1 defines first vector + * @param value2 defines second vector + * @param ref defines third vector + * @returns ref + */ + static CenterToRef(value1, value2, ref) { + return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2); + } + /** + * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB". + * Example Playground https://playground.babylonjs.com/#QYBWV4#77 + * @param p defines the middle point + * @param segA defines one point of the segment + * @param segB defines the other point of the segment + * @returns the shortest distance + */ + static DistanceOfPointFromSegment(p, segA, segB) { + const l2 = Vector2.DistanceSquared(segA, segB); + if (l2 === 0.0) { + return Vector2.Distance(p, segA); + } + const v = segB.subtract(segA); + const t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2)); + const proj = segA.add(v.multiplyByFloats(t, t)); + return Vector2.Distance(p, proj); + } +} +/** + * If the first vector is flagged with integers (as everything is 0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet. + * If subsequent vectors are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers, + * and henceforth it will use floating-point representation for all Vector2 instances that it creates. + * But the original Vector2 instances are unchanged and has a "deprecated map". + * If we keep using the Vector2 instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches. + */ +Vector2._V8PerformanceHack = new Vector2(0.5, 0.5); +Vector2._ZeroReadOnly = Vector2.Zero(); +Object.defineProperties(Vector2.prototype, { + dimension: { value: [2] }, + rank: { value: 1 }, +}); +/** + * Class used to store (x,y,z) vector representation + * A Vector3 is the main object used in 3D geometry + * It can represent either the coordinates of a point the space, either a direction + * Reminder: js uses a left handed forward facing system + * Example Playground - Overview - https://playground.babylonjs.com/#R1F8YU + */ +class Vector3 { + /** Gets or sets the x coordinate */ + get x() { + return this._x; + } + set x(value) { + this._x = value; + this._isDirty = true; + } + /** Gets or sets the y coordinate */ + get y() { + return this._y; + } + set y(value) { + this._y = value; + this._isDirty = true; + } + /** Gets or sets the z coordinate */ + get z() { + return this._z; + } + set z(value) { + this._z = value; + this._isDirty = true; + } + /** + * Creates a new Vector3 object from the given x, y, z (floats) coordinates. + * @param x defines the first coordinates (on X axis) + * @param y defines the second coordinates (on Y axis) + * @param z defines the third coordinates (on Z axis) + */ + constructor(x = 0, y = 0, z = 0) { + /** @internal */ + this._isDirty = true; + this._x = x; + this._y = y; + this._z = z; + } + /** + * Creates a string representation of the Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#67 + * @returns a string with the Vector3 coordinates. + */ + toString() { + return `{X: ${this._x} Y: ${this._y} Z: ${this._z}}`; + } + /** + * Gets the class name + * @returns the string "Vector3" + */ + getClassName() { + return "Vector3"; + } + /** + * Creates the Vector3 hash code + * @returns a number which tends to be unique between Vector3 instances + */ + getHashCode() { + const x = _ExtractAsInt(this._x); + const y = _ExtractAsInt(this._y); + const z = _ExtractAsInt(this._z); + let hash = x; + hash = (hash * 397) ^ y; + hash = (hash * 397) ^ z; + return hash; + } + // Operators + /** + * Creates an array containing three elements : the coordinates of the Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#10 + * @returns a new array of numbers + */ + asArray() { + return [this._x, this._y, this._z]; + } + /** + * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#65 + * @param array defines the destination array + * @param index defines the offset in the destination array + * @returns the current Vector3 + */ + toArray(array, index = 0) { + array[index] = this._x; + array[index + 1] = this._y; + array[index + 2] = this._z; + return this; + } + /** + * Update the current vector from an array + * Example Playground https://playground.babylonjs.com/#R1F8YU#24 + * @param array defines the destination array + * @param offset defines the offset in the destination array + * @returns the current Vector3 + */ + fromArray(array, offset = 0) { + Vector3.FromArrayToRef(array, offset, this); + return this; + } + /** + * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation) + * Example Playground https://playground.babylonjs.com/#R1F8YU#66 + * @returns a new Quaternion object, computed from the Vector3 coordinates + */ + toQuaternion() { + return Quaternion.RotationYawPitchRoll(this._y, this._x, this._z); + } + /** + * Adds the given vector to the current Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#4 + * @param otherVector defines the second operand + * @returns the current updated Vector3 + */ + addInPlace(otherVector) { + this._x += otherVector._x; + this._y += otherVector._y; + this._z += otherVector._z; + this._isDirty = true; + return this; + } + /** + * Adds the given coordinates to the current Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#5 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @returns the current updated Vector3 + */ + addInPlaceFromFloats(x, y, z) { + this._x += x; + this._y += y; + this._z += z; + this._isDirty = true; + return this; + } + /** + * Gets a new Vector3, result of the addition the current Vector3 and the given vector + * Example Playground https://playground.babylonjs.com/#R1F8YU#3 + * @param otherVector defines the second operand + * @returns the resulting Vector3 + */ + add(otherVector) { + return new Vector3(this._x + otherVector._x, this._y + otherVector._y, this._z + otherVector._z); + } + /** + * Adds the current Vector3 to the given one and stores the result in the vector "result" + * Example Playground https://playground.babylonjs.com/#R1F8YU#6 + * @param otherVector defines the second operand + * @param result defines the Vector3 object where to store the result + * @returns the result + */ + addToRef(otherVector, result) { + result._x = this._x + otherVector._x; + result._y = this._y + otherVector._y; + result._z = this._z + otherVector._z; + result._isDirty = true; + return result; + } + /** + * Subtract the given vector from the current Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#61 + * @param otherVector defines the second operand + * @returns the current updated Vector3 + */ + subtractInPlace(otherVector) { + this._x -= otherVector._x; + this._y -= otherVector._y; + this._z -= otherVector._z; + this._isDirty = true; + return this; + } + /** + * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#60 + * @param otherVector defines the second operand + * @returns the resulting Vector3 + */ + subtract(otherVector) { + return new Vector3(this._x - otherVector._x, this._y - otherVector._y, this._z - otherVector._z); + } + /** + * Subtracts the given vector from the current Vector3 and stores the result in the vector "result". + * Example Playground https://playground.babylonjs.com/#R1F8YU#63 + * @param otherVector defines the second operand + * @param result defines the Vector3 object where to store the result + * @returns the result + */ + subtractToRef(otherVector, result) { + return this.subtractFromFloatsToRef(otherVector._x, otherVector._y, otherVector._z, result); + } + /** + * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates + * Example Playground https://playground.babylonjs.com/#R1F8YU#62 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @returns the resulting Vector3 + */ + subtractFromFloats(x, y, z) { + return new Vector3(this._x - x, this._y - y, this._z - z); + } + /** + * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result + * Example Playground https://playground.babylonjs.com/#R1F8YU#64 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @param result defines the Vector3 object where to store the result + * @returns the result + */ + subtractFromFloatsToRef(x, y, z, result) { + result._x = this._x - x; + result._y = this._y - y; + result._z = this._z - z; + result._isDirty = true; + return result; + } + /** + * Gets a new Vector3 set with the current Vector3 negated coordinates + * Example Playground https://playground.babylonjs.com/#R1F8YU#35 + * @returns a new Vector3 + */ + negate() { + return new Vector3(-this._x, -this._y, -this._z); + } + /** + * Negate this vector in place + * Example Playground https://playground.babylonjs.com/#R1F8YU#36 + * @returns this + */ + negateInPlace() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._isDirty = true; + return this; + } + /** + * Negate the current Vector3 and stores the result in the given vector "result" coordinates + * Example Playground https://playground.babylonjs.com/#R1F8YU#37 + * @param result defines the Vector3 object where to store the result + * @returns the result + */ + negateToRef(result) { + result._x = this._x * -1; + result._y = this._y * -1; + result._z = this._z * -1; + result._isDirty = true; + return result; + } + /** + * Multiplies the Vector3 coordinates by the float "scale" + * Example Playground https://playground.babylonjs.com/#R1F8YU#56 + * @param scale defines the multiplier factor + * @returns the current updated Vector3 + */ + scaleInPlace(scale) { + this._x *= scale; + this._y *= scale; + this._z *= scale; + this._isDirty = true; + return this; + } + /** + * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale" + * Example Playground https://playground.babylonjs.com/#R1F8YU#53 + * @param scale defines the multiplier factor + * @returns a new Vector3 + */ + scale(scale) { + return new Vector3(this._x * scale, this._y * scale, this._z * scale); + } + /** + * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates + * Example Playground https://playground.babylonjs.com/#R1F8YU#57 + * @param scale defines the multiplier factor + * @param result defines the Vector3 object where to store the result + * @returns the result + */ + scaleToRef(scale, result) { + result._x = this._x * scale; + result._y = this._y * scale; + result._z = this._z * scale; + result._isDirty = true; + return result; + } + /** + * Creates a vector normal (perpendicular) to the current Vector3 and stores the result in the given vector + * Out of the infinite possibilities the normal chosen is the one formed by rotating the current vector + * 90 degrees about an axis which lies perpendicular to the current vector + * and its projection on the xz plane. In the case of a current vector in the xz plane + * the normal is calculated to be along the y axis. + * Example Playground https://playground.babylonjs.com/#R1F8YU#230 + * Example Playground https://playground.babylonjs.com/#R1F8YU#231 + * @param result defines the Vector3 object where to store the resultant normal + * @returns the result + */ + getNormalToRef(result) { + /** + * Calculates the spherical coordinates of the current vector + * so saves on memory rather than importing whole Spherical Class + */ + const radius = this.length(); + let theta = Math.acos(this.y / radius); + const phi = Math.atan2(this.z, this.x); + //makes angle 90 degs to current vector + if (theta > Math.PI / 2) { + theta -= Math.PI / 2; + } + else { + theta += Math.PI / 2; + } + //Calculates resutant normal vector from spherical coordinate of perpendicular vector + const x = radius * Math.sin(theta) * Math.cos(phi); + const y = radius * Math.cos(theta); + const z = radius * Math.sin(theta) * Math.sin(phi); + result.set(x, y, z); + return result; + } + /** + * Rotates the vector using the given unit quaternion and stores the new vector in result + * Example Playground https://playground.babylonjs.com/#R1F8YU#9 + * @param q the unit quaternion representing the rotation + * @param result the output vector + * @returns the result + */ + applyRotationQuaternionToRef(q, result) { + // Derived from https://raw.org/proof/vector-rotation-using-quaternions/ + const vx = this._x, vy = this._y, vz = this._z; + const qx = q._x, qy = q._y, qz = q._z, qw = q._w; + // t = 2q x v + const tx = 2 * (qy * vz - qz * vy); + const ty = 2 * (qz * vx - qx * vz); + const tz = 2 * (qx * vy - qy * vx); + // v + w t + q x t + result._x = vx + qw * tx + qy * tz - qz * ty; + result._y = vy + qw * ty + qz * tx - qx * tz; + result._z = vz + qw * tz + qx * ty - qy * tx; + result._isDirty = true; + return result; + } + /** + * Rotates the vector in place using the given unit quaternion + * Example Playground https://playground.babylonjs.com/#R1F8YU#8 + * @param q the unit quaternion representing the rotation + * @returns the current updated Vector3 + */ + applyRotationQuaternionInPlace(q) { + return this.applyRotationQuaternionToRef(q, this); + } + /** + * Rotates the vector using the given unit quaternion and returns the new vector + * Example Playground https://playground.babylonjs.com/#R1F8YU#7 + * @param q the unit quaternion representing the rotation + * @returns a new Vector3 + */ + applyRotationQuaternion(q) { + return this.applyRotationQuaternionToRef(q, new Vector3()); + } + /** + * Scale the current Vector3 values by a factor and add the result to a given Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#55 + * @param scale defines the scale factor + * @param result defines the Vector3 object where to store the result + * @returns result input + */ + scaleAndAddToRef(scale, result) { + result._x += this._x * scale; + result._y += this._y * scale; + result._z += this._z * scale; + result._isDirty = true; + return result; + } + /** + * Projects the current point Vector3 to a plane along a ray starting from a specified origin and passing through the current point Vector3. + * Example Playground https://playground.babylonjs.com/#R1F8YU#48 + * @param plane defines the plane to project to + * @param origin defines the origin of the projection ray + * @returns the projected vector3 + */ + projectOnPlane(plane, origin) { + return this.projectOnPlaneToRef(plane, origin, new Vector3()); + } + /** + * Projects the current point Vector3 to a plane along a ray starting from a specified origin and passing through the current point Vector3. + * Example Playground https://playground.babylonjs.com/#R1F8YU#49 + * @param plane defines the plane to project to + * @param origin defines the origin of the projection ray + * @param result defines the Vector3 where to store the result + * @returns result input + */ + projectOnPlaneToRef(plane, origin, result) { + const n = plane.normal; + const d = plane.d; + const V = MathTmp.Vector3[0]; + // ray direction + this.subtractToRef(origin, V); + V.normalize(); + const denom = Vector3.Dot(V, n); + //When the ray is close to parallel to the plane return infinity vector + if (Math.abs(denom) < 0.0000000001) { + result.setAll(Infinity); + } + else { + const t = -(Vector3.Dot(origin, n) + d) / denom; + // P = P0 + t*V + const scaledV = V.scaleInPlace(t); + origin.addToRef(scaledV, result); + } + return result; + } + /** + * Returns true if the current Vector3 and the given vector coordinates are strictly equal + * Example Playground https://playground.babylonjs.com/#R1F8YU#19 + * @param otherVector defines the second operand + * @returns true if both vectors are equals + */ + equals(otherVector) { + return otherVector && this._x === otherVector._x && this._y === otherVector._y && this._z === otherVector._z; + } + /** + * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon + * Example Playground https://playground.babylonjs.com/#R1F8YU#21 + * @param otherVector defines the second operand + * @param epsilon defines the minimal distance to define values as equals + * @returns true if both vectors are distant less than epsilon + */ + equalsWithEpsilon(otherVector, epsilon = Epsilon) { + return otherVector && WithinEpsilon(this._x, otherVector._x, epsilon) && WithinEpsilon(this._y, otherVector._y, epsilon) && WithinEpsilon(this._z, otherVector._z, epsilon); + } + /** + * Returns true if the current Vector3 coordinates equals the given floats + * Example Playground https://playground.babylonjs.com/#R1F8YU#20 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @returns true if both vectors are equal + */ + equalsToFloats(x, y, z) { + return this._x === x && this._y === y && this._z === z; + } + /** + * Multiplies the current Vector3 coordinates by the given ones + * Example Playground https://playground.babylonjs.com/#R1F8YU#32 + * @param otherVector defines the second operand + * @returns the current updated Vector3 + */ + multiplyInPlace(otherVector) { + this._x *= otherVector._x; + this._y *= otherVector._y; + this._z *= otherVector._z; + this._isDirty = true; + return this; + } + /** + * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector + * Example Playground https://playground.babylonjs.com/#R1F8YU#31 + * @param otherVector defines the second operand + * @returns the new Vector3 + */ + multiply(otherVector) { + return this.multiplyByFloats(otherVector._x, otherVector._y, otherVector._z); + } + /** + * Multiplies the current Vector3 by the given one and stores the result in the given vector "result" + * Example Playground https://playground.babylonjs.com/#R1F8YU#33 + * @param otherVector defines the second operand + * @param result defines the Vector3 object where to store the result + * @returns the result + */ + multiplyToRef(otherVector, result) { + result._x = this._x * otherVector._x; + result._y = this._y * otherVector._y; + result._z = this._z * otherVector._z; + result._isDirty = true; + return result; + } + /** + * Returns a new Vector3 set with the result of the multiplication of the current Vector3 coordinates by the given floats + * Example Playground https://playground.babylonjs.com/#R1F8YU#34 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @returns the new Vector3 + */ + multiplyByFloats(x, y, z) { + return new Vector3(this._x * x, this._y * y, this._z * z); + } + /** + * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones + * Example Playground https://playground.babylonjs.com/#R1F8YU#16 + * @param otherVector defines the second operand + * @returns the new Vector3 + */ + divide(otherVector) { + return new Vector3(this._x / otherVector._x, this._y / otherVector._y, this._z / otherVector._z); + } + /** + * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result" + * Example Playground https://playground.babylonjs.com/#R1F8YU#18 + * @param otherVector defines the second operand + * @param result defines the Vector3 object where to store the result + * @returns the result + */ + divideToRef(otherVector, result) { + result._x = this._x / otherVector._x; + result._y = this._y / otherVector._y; + result._z = this._z / otherVector._z; + result._isDirty = true; + return result; + } + /** + * Divides the current Vector3 coordinates by the given ones. + * Example Playground https://playground.babylonjs.com/#R1F8YU#17 + * @param otherVector defines the second operand + * @returns the current updated Vector3 + */ + divideInPlace(otherVector) { + this._x = this._x / otherVector._x; + this._y = this._y / otherVector._y; + this._z = this._z / otherVector._z; + this._isDirty = true; + return this; + } + /** + * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones + * Example Playground https://playground.babylonjs.com/#R1F8YU#29 + * @param other defines the second operand + * @returns the current updated Vector3 + */ + minimizeInPlace(other) { + return this.minimizeInPlaceFromFloats(other._x, other._y, other._z); + } + /** + * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones. + * Example Playground https://playground.babylonjs.com/#R1F8YU#27 + * @param other defines the second operand + * @returns the current updated Vector3 + */ + maximizeInPlace(other) { + return this.maximizeInPlaceFromFloats(other._x, other._y, other._z); + } + /** + * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates + * Example Playground https://playground.babylonjs.com/#R1F8YU#30 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @returns the current updated Vector3 + */ + minimizeInPlaceFromFloats(x, y, z) { + if (x < this._x) { + this.x = x; + } + if (y < this._y) { + this.y = y; + } + if (z < this._z) { + this.z = z; + } + return this; + } + /** + * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates. + * Example Playground https://playground.babylonjs.com/#R1F8YU#28 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @returns the current updated Vector3 + */ + maximizeInPlaceFromFloats(x, y, z) { + if (x > this._x) { + this.x = x; + } + if (y > this._y) { + this.y = y; + } + if (z > this._z) { + this.z = z; + } + return this; + } + /** + * Due to float precision, scale of a mesh could be uniform but float values are off by a small fraction + * Check if is non uniform within a certain amount of decimal places to account for this + * @param epsilon the amount the values can differ + * @returns if the vector is non uniform to a certain number of decimal places + */ + isNonUniformWithinEpsilon(epsilon) { + const absX = Math.abs(this._x); + const absY = Math.abs(this._y); + if (!WithinEpsilon(absX, absY, epsilon)) { + return true; + } + const absZ = Math.abs(this._z); + if (!WithinEpsilon(absX, absZ, epsilon)) { + return true; + } + if (!WithinEpsilon(absY, absZ, epsilon)) { + return true; + } + return false; + } + /** + * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same + */ + get isNonUniform() { + const absX = Math.abs(this._x); + const absY = Math.abs(this._y); + if (absX !== absY) { + return true; + } + const absZ = Math.abs(this._z); + if (absX !== absZ) { + return true; + } + return false; + } + /** + * Gets the current Vector3's floored values and stores them in result + * @param result the vector to store the result in + * @returns the result vector + */ + floorToRef(result) { + result._x = Math.floor(this._x); + result._y = Math.floor(this._y); + result._z = Math.floor(this._z); + result._isDirty = true; + return result; + } + /** + * Gets a new Vector3 from current Vector3 floored values + * Example Playground https://playground.babylonjs.com/#R1F8YU#22 + * @returns a new Vector3 + */ + floor() { + return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z)); + } + /** + * Gets the current Vector3's fractional values and stores them in result + * @param result the vector to store the result in + * @returns the result vector + */ + fractToRef(result) { + result._x = this.x - Math.floor(this._x); + result._y = this.y - Math.floor(this._y); + result._z = this.z - Math.floor(this._z); + result._isDirty = true; + return result; + } + /** + * Gets a new Vector3 from current Vector3 fractional values + * Example Playground https://playground.babylonjs.com/#R1F8YU#23 + * @returns a new Vector3 + */ + fract() { + return new Vector3(this.x - Math.floor(this._x), this.y - Math.floor(this._y), this.z - Math.floor(this._z)); + } + // Properties + /** + * Gets the length of the Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#25 + * @returns the length of the Vector3 + */ + length() { + return Math.sqrt(this.lengthSquared()); + } + /** + * Gets the squared length of the Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#26 + * @returns squared length of the Vector3 + */ + lengthSquared() { + return this._x * this._x + this._y * this._y + this._z * this._z; + } + /** + * Gets a boolean indicating if the vector contains a zero in one of its components + * Example Playground https://playground.babylonjs.com/#R1F8YU#1 + */ + get hasAZeroComponent() { + return this._x * this._y * this._z === 0; + } + /** + * Normalize the current Vector3. + * Please note that this is an in place operation. + * Example Playground https://playground.babylonjs.com/#R1F8YU#122 + * @returns the current updated Vector3 + */ + normalize() { + return this.normalizeFromLength(this.length()); + } + /** + * Reorders the x y z properties of the vector in place + * Example Playground https://playground.babylonjs.com/#R1F8YU#44 + * @param order new ordering of the properties (eg. for vector 1,2,3 with "ZYX" will produce 3,2,1) + * @returns the current updated vector + */ + reorderInPlace(order) { + order = order.toLowerCase(); + if (order === "xyz") { + return this; + } + const tem = MathTmp.Vector3[0].copyFrom(this); + this.x = tem[order[0]]; + this.y = tem[order[1]]; + this.z = tem[order[2]]; + return this; + } + /** + * Rotates the vector around 0,0,0 by a quaternion + * Example Playground https://playground.babylonjs.com/#R1F8YU#47 + * @param quaternion the rotation quaternion + * @param result vector to store the result + * @returns the resulting vector + */ + rotateByQuaternionToRef(quaternion, result) { + quaternion.toRotationMatrix(MathTmp.Matrix[0]); + Vector3.TransformCoordinatesToRef(this, MathTmp.Matrix[0], result); + return result; + } + /** + * Rotates a vector around a given point + * Example Playground https://playground.babylonjs.com/#R1F8YU#46 + * @param quaternion the rotation quaternion + * @param point the point to rotate around + * @param result vector to store the result + * @returns the resulting vector + */ + rotateByQuaternionAroundPointToRef(quaternion, point, result) { + this.subtractToRef(point, MathTmp.Vector3[0]); + MathTmp.Vector3[0].rotateByQuaternionToRef(quaternion, MathTmp.Vector3[0]); + point.addToRef(MathTmp.Vector3[0], result); + return result; + } + /** + * Returns a new Vector3 as the cross product of the current vector and the "other" one + * The cross product is then orthogonal to both current and "other" + * Example Playground https://playground.babylonjs.com/#R1F8YU#14 + * @param other defines the right operand + * @returns the cross product + */ + cross(other) { + return Vector3.CrossToRef(this, other, new Vector3()); + } + /** + * Normalize the current Vector3 with the given input length. + * Please note that this is an in place operation. + * Example Playground https://playground.babylonjs.com/#R1F8YU#123 + * @param len the length of the vector + * @returns the current updated Vector3 + */ + normalizeFromLength(len) { + if (len === 0 || len === 1.0) { + return this; + } + return this.scaleInPlace(1.0 / len); + } + /** + * Normalize the current Vector3 to a new vector + * Example Playground https://playground.babylonjs.com/#R1F8YU#124 + * @returns the new Vector3 + */ + normalizeToNew() { + return this.normalizeToRef(new Vector3()); + } + /** + * Normalize the current Vector3 to the reference + * Example Playground https://playground.babylonjs.com/#R1F8YU#125 + * @param result define the Vector3 to update + * @returns the updated Vector3 + */ + normalizeToRef(result) { + const len = this.length(); + if (len === 0 || len === 1.0) { + result._x = this._x; + result._y = this._y; + result._z = this._z; + result._isDirty = true; + return result; + } + return this.scaleToRef(1.0 / len, result); + } + /** + * Creates a new Vector3 copied from the current Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#11 + * @returns the new Vector3 + */ + clone() { + return new Vector3(this._x, this._y, this._z); + } + /** + * Copies the given vector coordinates to the current Vector3 ones + * Example Playground https://playground.babylonjs.com/#R1F8YU#12 + * @param source defines the source Vector3 + * @returns the current updated Vector3 + */ + copyFrom(source) { + return this.copyFromFloats(source._x, source._y, source._z); + } + /** + * Copies the given floats to the current Vector3 coordinates + * Example Playground https://playground.babylonjs.com/#R1F8YU#13 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @returns the current updated Vector3 + */ + copyFromFloats(x, y, z) { + this._x = x; + this._y = y; + this._z = z; + this._isDirty = true; + return this; + } + /** + * Copies the given floats to the current Vector3 coordinates + * Example Playground https://playground.babylonjs.com/#R1F8YU#58 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @returns the current updated Vector3 + */ + set(x, y, z) { + return this.copyFromFloats(x, y, z); + } + /** + * Copies the given float to the current Vector3 coordinates + * Example Playground https://playground.babylonjs.com/#R1F8YU#59 + * @param v defines the x, y and z coordinates of the operand + * @returns the current updated Vector3 + */ + setAll(v) { + this._x = this._y = this._z = v; + this._isDirty = true; + return this; + } + // Statics + /** + * Get the clip factor between two vectors + * Example Playground https://playground.babylonjs.com/#R1F8YU#126 + * @param vector0 defines the first operand + * @param vector1 defines the second operand + * @param axis defines the axis to use + * @param size defines the size along the axis + * @returns the clip factor + */ + static GetClipFactor(vector0, vector1, axis, size) { + const d0 = Vector3.Dot(vector0, axis); + const d1 = Vector3.Dot(vector1, axis); + return (d0 - size) / (d0 - d1); + } + /** + * Get angle between two vectors + * Example Playground https://playground.babylonjs.com/#R1F8YU#86 + * @param vector0 the starting point + * @param vector1 the ending point + * @param normal direction of the normal + * @returns the angle between vector0 and vector1 + */ + static GetAngleBetweenVectors(vector0, vector1, normal) { + const v0 = vector0.normalizeToRef(MathTmp.Vector3[1]); + const v1 = vector1.normalizeToRef(MathTmp.Vector3[2]); + let dot = Vector3.Dot(v0, v1); + // Vectors are normalized so dot will be in [-1, 1] (aside precision issues enough to break the result which explains the below clamp) + dot = Clamp(dot, -1, 1); + const angle = Math.acos(dot); + const n = MathTmp.Vector3[3]; + Vector3.CrossToRef(v0, v1, n); + if (Vector3.Dot(n, normal) > 0) { + return isNaN(angle) ? 0 : angle; + } + return isNaN(angle) ? -Math.PI : -Math.acos(dot); + } + /** + * Get angle between two vectors projected on a plane + * Example Playground https://playground.babylonjs.com/#R1F8YU#87 + * Expectation compute time: 0.01 ms (median) and 0.02 ms (percentile 95%) + * @param vector0 angle between vector0 and vector1 + * @param vector1 angle between vector0 and vector1 + * @param normal Normal of the projection plane + * @returns the angle in radians (float) between vector0 and vector1 projected on the plane with the specified normal + */ + static GetAngleBetweenVectorsOnPlane(vector0, vector1, normal) { + MathTmp.Vector3[0].copyFrom(vector0); + const v0 = MathTmp.Vector3[0]; + MathTmp.Vector3[1].copyFrom(vector1); + const v1 = MathTmp.Vector3[1]; + MathTmp.Vector3[2].copyFrom(normal); + const vNormal = MathTmp.Vector3[2]; + const right = MathTmp.Vector3[3]; + const forward = MathTmp.Vector3[4]; + v0.normalize(); + v1.normalize(); + vNormal.normalize(); + Vector3.CrossToRef(vNormal, v0, right); + Vector3.CrossToRef(right, vNormal, forward); + const angle = Math.atan2(Vector3.Dot(v1, right), Vector3.Dot(v1, forward)); + return NormalizeRadians(angle); + } + /** + * Gets the rotation that aligns the roll axis (Y) to the line joining the start point to the target point and stores it in the ref Vector3 + * Example PG https://playground.babylonjs.com/#R1F8YU#189 + * @param start the starting point + * @param target the target point + * @param ref the vector3 to store the result + * @returns ref in the form (pitch, yaw, 0) + */ + static PitchYawRollToMoveBetweenPointsToRef(start, target, ref) { + const diff = TmpVectors.Vector3[0]; + target.subtractToRef(start, diff); + ref._y = Math.atan2(diff.x, diff.z) || 0; + ref._x = Math.atan2(Math.sqrt(diff.x ** 2 + diff.z ** 2), diff.y) || 0; + ref._z = 0; + ref._isDirty = true; + return ref; + } + /** + * Gets the rotation that aligns the roll axis (Y) to the line joining the start point to the target point + * Example PG https://playground.babylonjs.com/#R1F8YU#188 + * @param start the starting point + * @param target the target point + * @returns the rotation in the form (pitch, yaw, 0) + */ + static PitchYawRollToMoveBetweenPoints(start, target) { + const ref = Vector3.Zero(); + return Vector3.PitchYawRollToMoveBetweenPointsToRef(start, target, ref); + } + /** + * Slerp between two vectors. See also `SmoothToRef` + * Slerp is a spherical linear interpolation + * giving a slow in and out effect + * Example Playground 1 https://playground.babylonjs.com/#R1F8YU#108 + * Example Playground 2 https://playground.babylonjs.com/#R1F8YU#109 + * @param vector0 Start vector + * @param vector1 End vector + * @param slerp amount (will be clamped between 0 and 1) + * @param result The slerped vector + * @returns The slerped vector + */ + static SlerpToRef(vector0, vector1, slerp, result) { + slerp = Clamp(slerp, 0, 1); + const vector0Dir = MathTmp.Vector3[0]; + const vector1Dir = MathTmp.Vector3[1]; + vector0Dir.copyFrom(vector0); + const vector0Length = vector0Dir.length(); + vector0Dir.normalizeFromLength(vector0Length); + vector1Dir.copyFrom(vector1); + const vector1Length = vector1Dir.length(); + vector1Dir.normalizeFromLength(vector1Length); + const dot = Vector3.Dot(vector0Dir, vector1Dir); + let scale0; + let scale1; + if (dot < 1 - Epsilon) { + const omega = Math.acos(dot); + const invSin = 1 / Math.sin(omega); + scale0 = Math.sin((1 - slerp) * omega) * invSin; + scale1 = Math.sin(slerp * omega) * invSin; + } + else { + // Use linear interpolation + scale0 = 1 - slerp; + scale1 = slerp; + } + vector0Dir.scaleInPlace(scale0); + vector1Dir.scaleInPlace(scale1); + result.copyFrom(vector0Dir).addInPlace(vector1Dir); + result.scaleInPlace(Lerp(vector0Length, vector1Length, slerp)); + return result; + } + /** + * Smooth interpolation between two vectors using Slerp + * Example Playground https://playground.babylonjs.com/#R1F8YU#110 + * @param source source vector + * @param goal goal vector + * @param deltaTime current interpolation frame + * @param lerpTime total interpolation time + * @param result the smoothed vector + * @returns the smoothed vector + */ + static SmoothToRef(source, goal, deltaTime, lerpTime, result) { + Vector3.SlerpToRef(source, goal, lerpTime === 0 ? 1 : deltaTime / lerpTime, result); + return result; + } + /** + * Returns a new Vector3 set from the index "offset" of the given array + * Example Playground https://playground.babylonjs.com/#R1F8YU#83 + * @param array defines the source array + * @param offset defines the offset in the source array + * @returns the new Vector3 + */ + static FromArray(array, offset = 0) { + return new Vector3(array[offset], array[offset + 1], array[offset + 2]); + } + /** + * Returns a new Vector3 set from the index "offset" of the given Float32Array + * @param array defines the source array + * @param offset defines the offset in the source array + * @returns the new Vector3 + * @deprecated Please use FromArray instead. + */ + static FromFloatArray(array, offset) { + return Vector3.FromArray(array, offset); + } + /** + * Sets the given vector "result" with the element values from the index "offset" of the given array + * Example Playground https://playground.babylonjs.com/#R1F8YU#84 + * @param array defines the source array + * @param offset defines the offset in the source array + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static FromArrayToRef(array, offset, result) { + result._x = array[offset]; + result._y = array[offset + 1]; + result._z = array[offset + 2]; + result._isDirty = true; + return result; + } + /** + * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array + * @param array defines the source array + * @param offset defines the offset in the source array + * @param result defines the Vector3 where to store the result + * @deprecated Please use FromArrayToRef instead. + * @returns result input + */ + static FromFloatArrayToRef(array, offset, result) { + return Vector3.FromArrayToRef(array, offset, result); + } + /** + * Sets the given vector "result" with the given floats. + * Example Playground https://playground.babylonjs.com/#R1F8YU#85 + * @param x defines the x coordinate of the source + * @param y defines the y coordinate of the source + * @param z defines the z coordinate of the source + * @param result defines the Vector3 where to store the result + * @returns the result vector + */ + static FromFloatsToRef(x, y, z, result) { + result.copyFromFloats(x, y, z); + return result; + } + /** + * Returns a new Vector3 set to (0.0, 0.0, 0.0) + * @returns a new empty Vector3 + */ + static Zero() { + return new Vector3(0.0, 0.0, 0.0); + } + /** + * Returns a new Vector3 set to (1.0, 1.0, 1.0) + * @returns a new Vector3 + */ + static One() { + return new Vector3(1.0, 1.0, 1.0); + } + /** + * Returns a new Vector3 set to (0.0, 1.0, 0.0) + * Example Playground https://playground.babylonjs.com/#R1F8YU#71 + * @returns a new up Vector3 + */ + static Up() { + return new Vector3(0.0, 1.0, 0.0); + } + /** + * Gets an up Vector3 that must not be updated + */ + static get UpReadOnly() { + return Vector3._UpReadOnly; + } + /** + * Gets a down Vector3 that must not be updated + */ + static get DownReadOnly() { + return Vector3._DownReadOnly; + } + /** + * Gets a right Vector3 that must not be updated + */ + static get RightReadOnly() { + return Vector3._RightReadOnly; + } + /** + * Gets a left Vector3 that must not be updated + */ + static get LeftReadOnly() { + return Vector3._LeftReadOnly; + } + /** + * Gets a forward Vector3 that must not be updated + */ + static get LeftHandedForwardReadOnly() { + return Vector3._LeftHandedForwardReadOnly; + } + /** + * Gets a forward Vector3 that must not be updated + */ + static get RightHandedForwardReadOnly() { + return Vector3._RightHandedForwardReadOnly; + } + /** + * Gets a backward Vector3 that must not be updated + */ + static get LeftHandedBackwardReadOnly() { + return Vector3._LeftHandedBackwardReadOnly; + } + /** + * Gets a backward Vector3 that must not be updated + */ + static get RightHandedBackwardReadOnly() { + return Vector3._RightHandedBackwardReadOnly; + } + /** + * Gets a zero Vector3 that must not be updated + */ + static get ZeroReadOnly() { + return Vector3._ZeroReadOnly; + } + /** + * Gets a one Vector3 that must not be updated + */ + static get OneReadOnly() { + return Vector3._OneReadOnly; + } + /** + * Returns a new Vector3 set to (0.0, -1.0, 0.0) + * Example Playground https://playground.babylonjs.com/#R1F8YU#71 + * @returns a new down Vector3 + */ + static Down() { + return new Vector3(0.0, -1, 0.0); + } + /** + * Returns a new Vector3 set to (0.0, 0.0, 1.0) + * Example Playground https://playground.babylonjs.com/#R1F8YU#71 + * @param rightHandedSystem is the scene right-handed (negative z) + * @returns a new forward Vector3 + */ + static Forward(rightHandedSystem = false) { + return new Vector3(0.0, 0.0, rightHandedSystem ? -1 : 1.0); + } + /** + * Returns a new Vector3 set to (0.0, 0.0, -1.0) + * Example Playground https://playground.babylonjs.com/#R1F8YU#71 + * @param rightHandedSystem is the scene right-handed (negative-z) + * @returns a new Backward Vector3 + */ + static Backward(rightHandedSystem = false) { + return new Vector3(0.0, 0.0, rightHandedSystem ? 1.0 : -1); + } + /** + * Returns a new Vector3 set to (1.0, 0.0, 0.0) + * Example Playground https://playground.babylonjs.com/#R1F8YU#71 + * @returns a new right Vector3 + */ + static Right() { + return new Vector3(1.0, 0.0, 0.0); + } + /** + * Returns a new Vector3 set to (-1.0, 0.0, 0.0) + * Example Playground https://playground.babylonjs.com/#R1F8YU#71 + * @returns a new left Vector3 + */ + static Left() { + return new Vector3(-1, 0.0, 0.0); + } + /** + * Returns a new Vector3 with random values between min and max + * @param min the minimum random value + * @param max the maximum random value + * @returns a Vector3 with random values between min and max + */ + static Random(min = 0, max = 1) { + return new Vector3(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max)); + } + /** + * Sets a Vector3 with random values between min and max + * @param min the minimum random value + * @param max the maximum random value + * @param ref the ref to store the values in + * @returns the ref with random values between min and max + */ + static RandomToRef(min = 0, max = 1, ref) { + return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max)); + } + /** + * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector. + * This method computes transformed coordinates only, not transformed direction vectors (ie. it takes translation in account) + * Example Playground https://playground.babylonjs.com/#R1F8YU#111 + * @param vector defines the Vector3 to transform + * @param transformation defines the transformation matrix + * @returns the transformed Vector3 + */ + static TransformCoordinates(vector, transformation) { + const result = Vector3.Zero(); + Vector3.TransformCoordinatesToRef(vector, transformation, result); + return result; + } + /** + * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector + * This method computes transformed coordinates only, not transformed direction vectors (ie. it takes translation in account) + * Example Playground https://playground.babylonjs.com/#R1F8YU#113 + * @param vector defines the Vector3 to transform + * @param transformation defines the transformation matrix + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static TransformCoordinatesToRef(vector, transformation, result) { + Vector3.TransformCoordinatesFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result); + return result; + } + /** + * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z) + * This method computes transformed coordinates only, not transformed direction vectors + * Example Playground https://playground.babylonjs.com/#R1F8YU#115 + * @param x define the x coordinate of the source vector + * @param y define the y coordinate of the source vector + * @param z define the z coordinate of the source vector + * @param transformation defines the transformation matrix + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static TransformCoordinatesFromFloatsToRef(x, y, z, transformation, result) { + const m = transformation.m; + const rx = x * m[0] + y * m[4] + z * m[8] + m[12]; + const ry = x * m[1] + y * m[5] + z * m[9] + m[13]; + const rz = x * m[2] + y * m[6] + z * m[10] + m[14]; + const rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]); + result._x = rx * rw; + result._y = ry * rw; + result._z = rz * rw; + result._isDirty = true; + return result; + } + /** + * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector + * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) + * Example Playground https://playground.babylonjs.com/#R1F8YU#112 + * @param vector defines the Vector3 to transform + * @param transformation defines the transformation matrix + * @returns the new Vector3 + */ + static TransformNormal(vector, transformation) { + const result = Vector3.Zero(); + Vector3.TransformNormalToRef(vector, transformation, result); + return result; + } + /** + * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector + * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) + * Example Playground https://playground.babylonjs.com/#R1F8YU#114 + * @param vector defines the Vector3 to transform + * @param transformation defines the transformation matrix + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static TransformNormalToRef(vector, transformation, result) { + this.TransformNormalFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result); + return result; + } + /** + * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z) + * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) + * Example Playground https://playground.babylonjs.com/#R1F8YU#116 + * @param x define the x coordinate of the source vector + * @param y define the y coordinate of the source vector + * @param z define the z coordinate of the source vector + * @param transformation defines the transformation matrix + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static TransformNormalFromFloatsToRef(x, y, z, transformation, result) { + const m = transformation.m; + result._x = x * m[0] + y * m[4] + z * m[8]; + result._y = x * m[1] + y * m[5] + z * m[9]; + result._z = x * m[2] + y * m[6] + z * m[10]; + result._isDirty = true; + return result; + } + /** + * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4" + * Example Playground https://playground.babylonjs.com/#R1F8YU#69 + * @param value1 defines the first control point + * @param value2 defines the second control point + * @param value3 defines the third control point + * @param value4 defines the fourth control point + * @param amount defines the amount on the spline to use + * @returns the new Vector3 + */ + static CatmullRom(value1, value2, value3, value4, amount) { + const squared = amount * amount; + const cubed = amount * squared; + const x = 0.5 * + (2.0 * value2._x + + (-value1._x + value3._x) * amount + + (2.0 * value1._x - 5.0 * value2._x + 4.0 * value3._x - value4._x) * squared + + (-value1._x + 3.0 * value2._x - 3.0 * value3._x + value4._x) * cubed); + const y = 0.5 * + (2.0 * value2._y + + (-value1._y + value3._y) * amount + + (2.0 * value1._y - 5.0 * value2._y + 4.0 * value3._y - value4._y) * squared + + (-value1._y + 3.0 * value2._y - 3.0 * value3._y + value4._y) * cubed); + const z = 0.5 * + (2.0 * value2._z + + (-value1._z + value3._z) * amount + + (2.0 * value1._z - 5.0 * value2._z + 4.0 * value3._z - value4._z) * squared + + (-value1._z + 3.0 * value2._z - 3.0 * value3._z + value4._z) * cubed); + return new Vector3(x, y, z); + } + /** + * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" + * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one + * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one + * Example Playground https://playground.babylonjs.com/#R1F8YU#76 + * @param value defines the current value + * @param min defines the lower range value + * @param max defines the upper range value + * @returns the new Vector3 + */ + static Clamp(value, min, max) { + const result = new Vector3(); + Vector3.ClampToRef(value, min, max, result); + return result; + } + /** + * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" + * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one + * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one + * Example Playground https://playground.babylonjs.com/#R1F8YU#77 + * @param value defines the current value + * @param min defines the lower range value + * @param max defines the upper range value + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static ClampToRef(value, min, max, result) { + let x = value._x; + x = x > max._x ? max._x : x; + x = x < min._x ? min._x : x; + let y = value._y; + y = y > max._y ? max._y : y; + y = y < min._y ? min._y : y; + let z = value._z; + z = z > max._z ? max._z : z; + z = z < min._z ? min._z : z; + result.copyFromFloats(x, y, z); + return result; + } + /** + * Checks if a given vector is inside a specific range + * Example Playground https://playground.babylonjs.com/#R1F8YU#75 + * @param v defines the vector to test + * @param min defines the minimum range + * @param max defines the maximum range + */ + static CheckExtends(v, min, max) { + min.minimizeInPlace(v); + max.maximizeInPlace(v); + } + /** + * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2" + * Example Playground https://playground.babylonjs.com/#R1F8YU#89 + * @param value1 defines the first control point + * @param tangent1 defines the first tangent vector + * @param value2 defines the second control point + * @param tangent2 defines the second tangent vector + * @param amount defines the amount on the interpolation spline (between 0 and 1) + * @returns the new Vector3 + */ + static Hermite(value1, tangent1, value2, tangent2, amount) { + const squared = amount * amount; + const cubed = amount * squared; + const part1 = 2.0 * cubed - 3.0 * squared + 1.0; + const part2 = -2 * cubed + 3.0 * squared; + const part3 = cubed - 2.0 * squared + amount; + const part4 = cubed - squared; + const x = value1._x * part1 + value2._x * part2 + tangent1._x * part3 + tangent2._x * part4; + const y = value1._y * part1 + value2._y * part2 + tangent1._y * part3 + tangent2._y * part4; + const z = value1._z * part1 + value2._z * part2 + tangent1._z * part3 + tangent2._z * part4; + return new Vector3(x, y, z); + } + /** + * Returns a new Vector3 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". + * Example Playground https://playground.babylonjs.com/#R1F8YU#90 + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @returns 1st derivative + */ + static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { + const result = new Vector3(); + this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); + return result; + } + /** + * Update a Vector3 with the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". + * Example Playground https://playground.babylonjs.com/#R1F8YU#91 + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @param result define where to store the derivative + * @returns result input + */ + static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { + const t2 = time * time; + result._x = (t2 - time) * 6 * value1._x + (3 * t2 - 4 * time + 1) * tangent1._x + (-t2 + time) * 6 * value2._x + (3 * t2 - 2 * time) * tangent2._x; + result._y = (t2 - time) * 6 * value1._y + (3 * t2 - 4 * time + 1) * tangent1._y + (-t2 + time) * 6 * value2._y + (3 * t2 - 2 * time) * tangent2._y; + result._z = (t2 - time) * 6 * value1._z + (3 * t2 - 4 * time + 1) * tangent1._z + (-t2 + time) * 6 * value2._z + (3 * t2 - 2 * time) * tangent2._z; + result._isDirty = true; + return result; + } + /** + * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end" + * Example Playground https://playground.babylonjs.com/#R1F8YU#95 + * @param start defines the start value + * @param end defines the end value + * @param amount max defines amount between both (between 0 and 1) + * @returns the new Vector3 + */ + static Lerp(start, end, amount) { + const result = new Vector3(0, 0, 0); + Vector3.LerpToRef(start, end, amount, result); + return result; + } + /** + * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end" + * Example Playground https://playground.babylonjs.com/#R1F8YU#93 + * @param start defines the start value + * @param end defines the end value + * @param amount max defines amount between both (between 0 and 1) + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static LerpToRef(start, end, amount, result) { + result._x = start._x + (end._x - start._x) * amount; + result._y = start._y + (end._y - start._y) * amount; + result._z = start._z + (end._z - start._z) * amount; + result._isDirty = true; + return result; + } + /** + * Returns the dot product (float) between the vectors "left" and "right" + * Example Playground https://playground.babylonjs.com/#R1F8YU#82 + * @param left defines the left operand + * @param right defines the right operand + * @returns the dot product + */ + static Dot(left, right) { + return left._x * right._x + left._y * right._y + left._z * right._z; + } + /** + * Returns the dot product (float) between the current vectors and "otherVector" + * @param otherVector defines the right operand + * @returns the dot product + */ + dot(otherVector) { + return this._x * otherVector._x + this._y * otherVector._y + this._z * otherVector._z; + } + /** + * Returns a new Vector3 as the cross product of the vectors "left" and "right" + * The cross product is then orthogonal to both "left" and "right" + * Example Playground https://playground.babylonjs.com/#R1F8YU#15 + * @param left defines the left operand + * @param right defines the right operand + * @returns the cross product + */ + static Cross(left, right) { + const result = new Vector3(); + Vector3.CrossToRef(left, right, result); + return result; + } + /** + * Sets the given vector "result" with the cross product of "left" and "right" + * The cross product is then orthogonal to both "left" and "right" + * Example Playground https://playground.babylonjs.com/#R1F8YU#78 + * @param left defines the left operand + * @param right defines the right operand + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static CrossToRef(left, right, result) { + const x = left._y * right._z - left._z * right._y; + const y = left._z * right._x - left._x * right._z; + const z = left._x * right._y - left._y * right._x; + result.copyFromFloats(x, y, z); + return result; + } + /** + * Returns a new Vector3 as the normalization of the given vector + * Example Playground https://playground.babylonjs.com/#R1F8YU#98 + * @param vector defines the Vector3 to normalize + * @returns the new Vector3 + */ + static Normalize(vector) { + const result = Vector3.Zero(); + Vector3.NormalizeToRef(vector, result); + return result; + } + /** + * Sets the given vector "result" with the normalization of the given first vector + * Example Playground https://playground.babylonjs.com/#R1F8YU#98 + * @param vector defines the Vector3 to normalize + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static NormalizeToRef(vector, result) { + vector.normalizeToRef(result); + return result; + } + /** + * Project a Vector3 onto screen space + * Example Playground https://playground.babylonjs.com/#R1F8YU#101 + * @param vector defines the Vector3 to project + * @param world defines the world matrix to use + * @param transform defines the transform (view x projection) matrix to use + * @param viewport defines the screen viewport to use + * @returns the new Vector3 + */ + static Project(vector, world, transform, viewport) { + const result = new Vector3(); + Vector3.ProjectToRef(vector, world, transform, viewport, result); + return result; + } + /** + * Project a Vector3 onto screen space to reference + * Example Playground https://playground.babylonjs.com/#R1F8YU#102 + * @param vector defines the Vector3 to project + * @param world defines the world matrix to use + * @param transform defines the transform (view x projection) matrix to use + * @param viewport defines the screen viewport to use + * @param result the vector in which the screen space will be stored + * @returns result input + */ + static ProjectToRef(vector, world, transform, viewport, result) { + const cw = viewport.width; + const ch = viewport.height; + const cx = viewport.x; + const cy = viewport.y; + const viewportMatrix = MathTmp.Matrix[1]; + const isNDCHalfZRange = EngineStore.LastCreatedEngine?.isNDCHalfZRange; + const zScale = isNDCHalfZRange ? 1 : 0.5; + const zOffset = isNDCHalfZRange ? 0 : 0.5; + Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zScale, 0, cx + cw / 2.0, ch / 2.0 + cy, zOffset, 1, viewportMatrix); + const matrix = MathTmp.Matrix[0]; + world.multiplyToRef(transform, matrix); + matrix.multiplyToRef(viewportMatrix, matrix); + Vector3.TransformCoordinatesToRef(vector, matrix, result); + return result; + } + /** + * Reflects a vector off the plane defined by a normalized normal + * @param inDirection defines the vector direction + * @param normal defines the normal - Must be normalized + * @returns the resulting vector + */ + static Reflect(inDirection, normal) { + return this.ReflectToRef(inDirection, normal, new Vector3()); + } + /** + * Reflects a vector off the plane defined by a normalized normal to reference + * @param inDirection defines the vector direction + * @param normal defines the normal - Must be normalized + * @param ref defines the Vector3 where to store the result + * @returns the resulting vector + */ + static ReflectToRef(inDirection, normal, ref) { + const tmp = TmpVectors.Vector3[0]; + tmp.copyFrom(normal).scaleInPlace(2 * Vector3.Dot(inDirection, normal)); + return ref.copyFrom(inDirection).subtractInPlace(tmp); + } + /** + * @internal + */ + static _UnprojectFromInvertedMatrixToRef(source, matrix, result) { + Vector3.TransformCoordinatesToRef(source, matrix, result); + const m = matrix.m; + const num = source._x * m[3] + source._y * m[7] + source._z * m[11] + m[15]; + if (WithinEpsilon(num, 1.0)) { + result.scaleInPlace(1.0 / num); + } + return result; + } + /** + * Unproject from screen space to object space + * Example Playground https://playground.babylonjs.com/#R1F8YU#121 + * @param source defines the screen space Vector3 to use + * @param viewportWidth defines the current width of the viewport + * @param viewportHeight defines the current height of the viewport + * @param world defines the world matrix to use (can be set to Identity to go to world space) + * @param transform defines the transform (view x projection) matrix to use + * @returns the new Vector3 + */ + static UnprojectFromTransform(source, viewportWidth, viewportHeight, world, transform) { + return this.Unproject(source, viewportWidth, viewportHeight, world, transform, Matrix.IdentityReadOnly); + } + /** + * Unproject from screen space to object space + * Example Playground https://playground.babylonjs.com/#R1F8YU#117 + * @param source defines the screen space Vector3 to use + * @param viewportWidth defines the current width of the viewport + * @param viewportHeight defines the current height of the viewport + * @param world defines the world matrix to use (can be set to Identity to go to world space) + * @param view defines the view matrix to use + * @param projection defines the projection matrix to use + * @returns the new Vector3 + */ + static Unproject(source, viewportWidth, viewportHeight, world, view, projection) { + const result = new Vector3(); + Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result); + return result; + } + /** + * Unproject from screen space to object space + * Example Playground https://playground.babylonjs.com/#R1F8YU#119 + * @param source defines the screen space Vector3 to use + * @param viewportWidth defines the current width of the viewport + * @param viewportHeight defines the current height of the viewport + * @param world defines the world matrix to use (can be set to Identity to go to world space) + * @param view defines the view matrix to use + * @param projection defines the projection matrix to use + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result) { + Vector3.UnprojectFloatsToRef(source._x, source._y, source._z, viewportWidth, viewportHeight, world, view, projection, result); + return result; + } + /** + * Unproject from screen space to object space + * Example Playground https://playground.babylonjs.com/#R1F8YU#120 + * @param sourceX defines the screen space x coordinate to use + * @param sourceY defines the screen space y coordinate to use + * @param sourceZ defines the screen space z coordinate to use + * @param viewportWidth defines the current width of the viewport + * @param viewportHeight defines the current height of the viewport + * @param world defines the world matrix to use (can be set to Identity to go to world space) + * @param view defines the view matrix to use + * @param projection defines the projection matrix to use + * @param result defines the Vector3 where to store the result + * @returns result input + */ + static UnprojectFloatsToRef(sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) { + const matrix = MathTmp.Matrix[0]; + world.multiplyToRef(view, matrix); + matrix.multiplyToRef(projection, matrix); + matrix.invert(); + const screenSource = MathTmp.Vector3[0]; + screenSource.x = (sourceX / viewportWidth) * 2 - 1; + screenSource.y = -((sourceY / viewportHeight) * 2 - 1); + if (EngineStore.LastCreatedEngine?.isNDCHalfZRange) { + screenSource.z = sourceZ; + } + else { + screenSource.z = 2 * sourceZ - 1.0; + } + Vector3._UnprojectFromInvertedMatrixToRef(screenSource, matrix, result); + return result; + } + /** + * Gets the minimal coordinate values between two Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#97 + * @param left defines the first operand + * @param right defines the second operand + * @returns the new Vector3 + */ + static Minimize(left, right) { + const min = new Vector3(); + min.copyFrom(left); + min.minimizeInPlace(right); + return min; + } + /** + * Gets the maximal coordinate values between two Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#96 + * @param left defines the first operand + * @param right defines the second operand + * @returns the new Vector3 + */ + static Maximize(left, right) { + const max = new Vector3(); + max.copyFrom(left); + max.maximizeInPlace(right); + return max; + } + /** + * Returns the distance between the vectors "value1" and "value2" + * Example Playground https://playground.babylonjs.com/#R1F8YU#81 + * @param value1 defines the first operand + * @param value2 defines the second operand + * @returns the distance + */ + static Distance(value1, value2) { + return Math.sqrt(Vector3.DistanceSquared(value1, value2)); + } + /** + * Returns the squared distance between the vectors "value1" and "value2" + * Example Playground https://playground.babylonjs.com/#R1F8YU#80 + * @param value1 defines the first operand + * @param value2 defines the second operand + * @returns the squared distance + */ + static DistanceSquared(value1, value2) { + const x = value1._x - value2._x; + const y = value1._y - value2._y; + const z = value1._z - value2._z; + return x * x + y * y + z * z; + } + /** + * Projects "vector" on the triangle determined by its extremities "p0", "p1" and "p2", stores the result in "ref" + * and returns the distance to the projected point. + * Example Playground https://playground.babylonjs.com/#R1F8YU#104 + * From http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.104.4264&rep=rep1&type=pdf + * + * @param vector the vector to get distance from + * @param p0 extremity of the triangle + * @param p1 extremity of the triangle + * @param p2 extremity of the triangle + * @param ref variable to store the result to + * @returns The distance between "ref" and "vector" + */ + static ProjectOnTriangleToRef(vector, p0, p1, p2, ref) { + const p1p0 = MathTmp.Vector3[0]; + const p2p0 = MathTmp.Vector3[1]; + const p2p1 = MathTmp.Vector3[2]; + const normal = MathTmp.Vector3[3]; + const vectorp0 = MathTmp.Vector3[4]; + // Triangle vectors + p1.subtractToRef(p0, p1p0); + p2.subtractToRef(p0, p2p0); + p2.subtractToRef(p1, p2p1); + const p1p0L = p1p0.length(); + const p2p0L = p2p0.length(); + const p2p1L = p2p1.length(); + if (p1p0L < Epsilon || p2p0L < Epsilon || p2p1L < Epsilon) { + // This is a degenerate triangle. As we assume this is part of a non-degenerate mesh, + // we will find a better intersection later. + // Let's just return one of the extremities + ref.copyFrom(p0); + return Vector3.Distance(vector, p0); + } + // Compute normal and vector to p0 + vector.subtractToRef(p0, vectorp0); + Vector3.CrossToRef(p1p0, p2p0, normal); + const nl = normal.length(); + if (nl < Epsilon) { + // Extremities are aligned, we are back on the case of a degenerate triangle + ref.copyFrom(p0); + return Vector3.Distance(vector, p0); + } + normal.normalizeFromLength(nl); + let l = vectorp0.length(); + if (l < Epsilon) { + // Vector is p0 + ref.copyFrom(p0); + return 0; + } + vectorp0.normalizeFromLength(l); + // Project to "proj" that lies on the triangle plane + const cosA = Vector3.Dot(normal, vectorp0); + const projVector = MathTmp.Vector3[5]; + const proj = MathTmp.Vector3[6]; + projVector.copyFrom(normal).scaleInPlace(-l * cosA); + proj.copyFrom(vector).addInPlace(projVector); + // Compute barycentric coordinates (v0, v1 and v2 are axis from barycenter to extremities) + const v0 = MathTmp.Vector3[4]; + const v1 = MathTmp.Vector3[5]; + const v2 = MathTmp.Vector3[7]; + const tmp = MathTmp.Vector3[8]; + v0.copyFrom(p1p0).scaleInPlace(1 / p1p0L); + tmp.copyFrom(p2p0).scaleInPlace(1 / p2p0L); + v0.addInPlace(tmp).scaleInPlace(-1); + v1.copyFrom(p1p0).scaleInPlace(-1 / p1p0L); + tmp.copyFrom(p2p1).scaleInPlace(1 / p2p1L); + v1.addInPlace(tmp).scaleInPlace(-1); + v2.copyFrom(p2p1).scaleInPlace(-1 / p2p1L); + tmp.copyFrom(p2p0).scaleInPlace(-1 / p2p0L); + v2.addInPlace(tmp).scaleInPlace(-1); + // Determines which edge of the triangle is closest to "proj" + const projP = MathTmp.Vector3[9]; + let dot; + projP.copyFrom(proj).subtractInPlace(p0); + Vector3.CrossToRef(v0, projP, tmp); + dot = Vector3.Dot(tmp, normal); + const s0 = dot; + projP.copyFrom(proj).subtractInPlace(p1); + Vector3.CrossToRef(v1, projP, tmp); + dot = Vector3.Dot(tmp, normal); + const s1 = dot; + projP.copyFrom(proj).subtractInPlace(p2); + Vector3.CrossToRef(v2, projP, tmp); + dot = Vector3.Dot(tmp, normal); + const s2 = dot; + const edge = MathTmp.Vector3[10]; + let e0, e1; + if (s0 > 0 && s1 < 0) { + edge.copyFrom(p1p0); + e0 = p0; + e1 = p1; + } + else if (s1 > 0 && s2 < 0) { + edge.copyFrom(p2p1); + e0 = p1; + e1 = p2; + } + else { + edge.copyFrom(p2p0).scaleInPlace(-1); + e0 = p2; + e1 = p0; + } + // Determines if "proj" lies inside the triangle + const tmp2 = MathTmp.Vector3[9]; + const tmp3 = MathTmp.Vector3[4]; + e0.subtractToRef(proj, tmp); + e1.subtractToRef(proj, tmp2); + Vector3.CrossToRef(tmp, tmp2, tmp3); + const isOutside = Vector3.Dot(tmp3, normal) < 0; + // If inside, we already found the projected point, "proj" + if (!isOutside) { + ref.copyFrom(proj); + return Math.abs(l * cosA); + } + // If outside, we find "triProj", the closest point from "proj" on the closest edge + const r = MathTmp.Vector3[5]; + Vector3.CrossToRef(edge, tmp3, r); + r.normalize(); + const e0proj = MathTmp.Vector3[9]; + e0proj.copyFrom(e0).subtractInPlace(proj); + const e0projL = e0proj.length(); + if (e0projL < Epsilon) { + // Proj is e0 + ref.copyFrom(e0); + return Vector3.Distance(vector, e0); + } + e0proj.normalizeFromLength(e0projL); + const cosG = Vector3.Dot(r, e0proj); + const triProj = MathTmp.Vector3[7]; + triProj.copyFrom(proj).addInPlace(r.scaleInPlace(e0projL * cosG)); + // Now we clamp "triProj" so it lies between e0 and e1 + tmp.copyFrom(triProj).subtractInPlace(e0); + l = edge.length(); + edge.normalizeFromLength(l); + let t = Vector3.Dot(tmp, edge) / Math.max(l, Epsilon); + t = Clamp(t, 0, 1); + triProj.copyFrom(e0).addInPlace(edge.scaleInPlace(t * l)); + ref.copyFrom(triProj); + return Vector3.Distance(vector, triProj); + } + /** + * Returns a new Vector3 located at the center between "value1" and "value2" + * Example Playground https://playground.babylonjs.com/#R1F8YU#72 + * @param value1 defines the first operand + * @param value2 defines the second operand + * @returns the new Vector3 + */ + static Center(value1, value2) { + return Vector3.CenterToRef(value1, value2, Vector3.Zero()); + } + /** + * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref" + * Example Playground https://playground.babylonjs.com/#R1F8YU#73 + * @param value1 defines first vector + * @param value2 defines second vector + * @param ref defines third vector + * @returns ref + */ + static CenterToRef(value1, value2, ref) { + return ref.copyFromFloats((value1._x + value2._x) / 2, (value1._y + value2._y) / 2, (value1._z + value2._z) / 2); + } + /** + * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system), + * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply + * to something in order to rotate it from its local system to the given target system + * Note: axis1, axis2 and axis3 are normalized during this operation + * Example Playground https://playground.babylonjs.com/#R1F8YU#106 + * @param axis1 defines the first axis + * @param axis2 defines the second axis + * @param axis3 defines the third axis + * @returns a new Vector3 + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/target_align + */ + static RotationFromAxis(axis1, axis2, axis3) { + const rotation = new Vector3(); + Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation); + return rotation; + } + /** + * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3 + * Example Playground https://playground.babylonjs.com/#R1F8YU#107 + * @param axis1 defines the first axis + * @param axis2 defines the second axis + * @param axis3 defines the third axis + * @param ref defines the Vector3 where to store the result + * @returns result input + */ + static RotationFromAxisToRef(axis1, axis2, axis3, ref) { + const quat = MathTmp.Quaternion[0]; + Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat); + quat.toEulerAnglesToRef(ref); + return ref; + } +} +/** + * If the first vector is flagged with integers (as everything is 0,0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet. + * If subsequent vectors are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers, + * and henceforth it will use floating-point representation for all Vector3 instances that it creates. + * But the original Vector3 instances are unchanged and has a "deprecated map". + * If we keep using the Vector3 instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches. + */ +Vector3._V8PerformanceHack = new Vector3(0.5, 0.5, 0.5); +Vector3._UpReadOnly = Vector3.Up(); +Vector3._DownReadOnly = Vector3.Down(); +Vector3._LeftHandedForwardReadOnly = Vector3.Forward(false); +Vector3._RightHandedForwardReadOnly = Vector3.Forward(true); +Vector3._LeftHandedBackwardReadOnly = Vector3.Backward(false); +Vector3._RightHandedBackwardReadOnly = Vector3.Backward(true); +Vector3._RightReadOnly = Vector3.Right(); +Vector3._LeftReadOnly = Vector3.Left(); +Vector3._ZeroReadOnly = Vector3.Zero(); +Vector3._OneReadOnly = Vector3.One(); +Object.defineProperties(Vector3.prototype, { + dimension: { value: [3] }, + rank: { value: 1 }, +}); +/** + * Vector4 class created for EulerAngle class conversion to Quaternion + */ +class Vector4 { + /** + * Creates a Vector4 object from the given floats. + * @param x x value of the vector + * @param y y value of the vector + * @param z z value of the vector + * @param w w value of the vector + */ + constructor( + /** [0] x value of the vector */ + x = 0, + /** [0] y value of the vector */ + y = 0, + /** [0] z value of the vector */ + z = 0, + /** [0] w value of the vector */ + w = 0) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + /** + * Returns the string with the Vector4 coordinates. + * @returns a string containing all the vector values + */ + toString() { + return `{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`; + } + /** + * Returns the string "Vector4". + * @returns "Vector4" + */ + getClassName() { + return "Vector4"; + } + /** + * Returns the Vector4 hash code. + * @returns a unique hash code + */ + getHashCode() { + const x = _ExtractAsInt(this.x); + const y = _ExtractAsInt(this.y); + const z = _ExtractAsInt(this.z); + const w = _ExtractAsInt(this.w); + let hash = x; + hash = (hash * 397) ^ y; + hash = (hash * 397) ^ z; + hash = (hash * 397) ^ w; + return hash; + } + // Operators + /** + * Returns a new array populated with 4 elements : the Vector4 coordinates. + * @returns the resulting array + */ + asArray() { + return [this.x, this.y, this.z, this.w]; + } + /** + * Populates the given array from the given index with the Vector4 coordinates. + * @param array array to populate + * @param index index of the array to start at (default: 0) + * @returns the Vector4. + */ + toArray(array, index) { + if (index === undefined) { + index = 0; + } + array[index] = this.x; + array[index + 1] = this.y; + array[index + 2] = this.z; + array[index + 3] = this.w; + return this; + } + /** + * Update the current vector from an array + * @param array defines the destination array + * @param offset defines the offset in the destination array + * @returns the current Vector3 + */ + fromArray(array, offset = 0) { + Vector4.FromArrayToRef(array, offset, this); + return this; + } + /** + * Adds the given vector to the current Vector4. + * @param otherVector the vector to add + * @returns the updated Vector4. + */ + addInPlace(otherVector) { + this.x += otherVector.x; + this.y += otherVector.y; + this.z += otherVector.z; + this.w += otherVector.w; + return this; + } + /** + * Adds the given coordinates to the current Vector4 + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @param w defines the w coordinate of the operand + * @returns the current updated Vector4 + */ + addInPlaceFromFloats(x, y, z, w) { + this.x += x; + this.y += y; + this.z += z; + this.w += w; + return this; + } + /** + * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one. + * @param otherVector the vector to add + * @returns the resulting vector + */ + add(otherVector) { + return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w); + } + /** + * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one. + * @param otherVector the vector to add + * @param result the vector to store the result + * @returns result input + */ + addToRef(otherVector, result) { + result.x = this.x + otherVector.x; + result.y = this.y + otherVector.y; + result.z = this.z + otherVector.z; + result.w = this.w + otherVector.w; + return result; + } + /** + * Subtract in place the given vector from the current Vector4. + * @param otherVector the vector to subtract + * @returns the updated Vector4. + */ + subtractInPlace(otherVector) { + this.x -= otherVector.x; + this.y -= otherVector.y; + this.z -= otherVector.z; + this.w -= otherVector.w; + return this; + } + /** + * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4. + * @param otherVector the vector to add + * @returns the new vector with the result + */ + subtract(otherVector) { + return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w); + } + /** + * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4. + * @param otherVector the vector to subtract + * @param result the vector to store the result + * @returns result input + */ + subtractToRef(otherVector, result) { + result.x = this.x - otherVector.x; + result.y = this.y - otherVector.y; + result.z = this.z - otherVector.z; + result.w = this.w - otherVector.w; + return result; + } + /** + * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates. + * @param x value to subtract + * @param y value to subtract + * @param z value to subtract + * @param w value to subtract + * @returns new vector containing the result + */ + subtractFromFloats(x, y, z, w) { + return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w); + } + /** + * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates. + * @param x value to subtract + * @param y value to subtract + * @param z value to subtract + * @param w value to subtract + * @param result the vector to store the result in + * @returns result input + */ + subtractFromFloatsToRef(x, y, z, w, result) { + result.x = this.x - x; + result.y = this.y - y; + result.z = this.z - z; + result.w = this.w - w; + return result; + } + /** + * Returns a new Vector4 set with the current Vector4 negated coordinates. + * @returns a new vector with the negated values + */ + negate() { + return new Vector4(-this.x, -this.y, -this.z, -this.w); + } + /** + * Negate this vector in place + * @returns this + */ + negateInPlace() { + this.x *= -1; + this.y *= -1; + this.z *= -1; + this.w *= -1; + return this; + } + /** + * Negate the current Vector4 and stores the result in the given vector "result" coordinates + * @param result defines the Vector3 object where to store the result + * @returns the result + */ + negateToRef(result) { + result.x = -this.x; + result.y = -this.y; + result.z = -this.z; + result.w = -this.w; + return result; + } + /** + * Multiplies the current Vector4 coordinates by scale (float). + * @param scale the number to scale with + * @returns the updated Vector4. + */ + scaleInPlace(scale) { + this.x *= scale; + this.y *= scale; + this.z *= scale; + this.w *= scale; + return this; + } + /** + * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float). + * @param scale the number to scale with + * @returns a new vector with the result + */ + scale(scale) { + return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale); + } + /** + * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float). + * @param scale the number to scale with + * @param result a vector to store the result in + * @returns result input + */ + scaleToRef(scale, result) { + result.x = this.x * scale; + result.y = this.y * scale; + result.z = this.z * scale; + result.w = this.w * scale; + return result; + } + /** + * Scale the current Vector4 values by a factor and add the result to a given Vector4 + * @param scale defines the scale factor + * @param result defines the Vector4 object where to store the result + * @returns result input + */ + scaleAndAddToRef(scale, result) { + result.x += this.x * scale; + result.y += this.y * scale; + result.z += this.z * scale; + result.w += this.w * scale; + return result; + } + /** + * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones. + * @param otherVector the vector to compare against + * @returns true if they are equal + */ + equals(otherVector) { + return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w; + } + /** + * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones. + * @param otherVector vector to compare against + * @param epsilon (Default: very small number) + * @returns true if they are equal + */ + equalsWithEpsilon(otherVector, epsilon = Epsilon) { + return (otherVector && + WithinEpsilon(this.x, otherVector.x, epsilon) && + WithinEpsilon(this.y, otherVector.y, epsilon) && + WithinEpsilon(this.z, otherVector.z, epsilon) && + WithinEpsilon(this.w, otherVector.w, epsilon)); + } + /** + * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates. + * @param x x value to compare against + * @param y y value to compare against + * @param z z value to compare against + * @param w w value to compare against + * @returns true if equal + */ + equalsToFloats(x, y, z, w) { + return this.x === x && this.y === y && this.z === z && this.w === w; + } + /** + * Multiplies in place the current Vector4 by the given one. + * @param otherVector vector to multiple with + * @returns the updated Vector4. + */ + multiplyInPlace(otherVector) { + this.x *= otherVector.x; + this.y *= otherVector.y; + this.z *= otherVector.z; + this.w *= otherVector.w; + return this; + } + /** + * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one. + * @param otherVector vector to multiple with + * @returns resulting new vector + */ + multiply(otherVector) { + return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w); + } + /** + * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one. + * @param otherVector vector to multiple with + * @param result vector to store the result + * @returns result input + */ + multiplyToRef(otherVector, result) { + result.x = this.x * otherVector.x; + result.y = this.y * otherVector.y; + result.z = this.z * otherVector.z; + result.w = this.w * otherVector.w; + return result; + } + /** + * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates. + * @param x x value multiply with + * @param y y value multiply with + * @param z z value multiply with + * @param w w value multiply with + * @returns resulting new vector + */ + multiplyByFloats(x, y, z, w) { + return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w); + } + /** + * Returns a new Vector4 set with the division result of the current Vector4 by the given one. + * @param otherVector vector to devide with + * @returns resulting new vector + */ + divide(otherVector) { + return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w); + } + /** + * Updates the given vector "result" with the division result of the current Vector4 by the given one. + * @param otherVector vector to devide with + * @param result vector to store the result + * @returns result input + */ + divideToRef(otherVector, result) { + result.x = this.x / otherVector.x; + result.y = this.y / otherVector.y; + result.z = this.z / otherVector.z; + result.w = this.w / otherVector.w; + return result; + } + /** + * Divides the current Vector3 coordinates by the given ones. + * @param otherVector vector to devide with + * @returns the updated Vector3. + */ + divideInPlace(otherVector) { + return this.divideToRef(otherVector, this); + } + /** + * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones + * @param other defines the second operand + * @returns the current updated Vector4 + */ + minimizeInPlace(other) { + if (other.x < this.x) { + this.x = other.x; + } + if (other.y < this.y) { + this.y = other.y; + } + if (other.z < this.z) { + this.z = other.z; + } + if (other.w < this.w) { + this.w = other.w; + } + return this; + } + /** + * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones + * @param other defines the second operand + * @returns the current updated Vector4 + */ + maximizeInPlace(other) { + if (other.x > this.x) { + this.x = other.x; + } + if (other.y > this.y) { + this.y = other.y; + } + if (other.z > this.z) { + this.z = other.z; + } + if (other.w > this.w) { + this.w = other.w; + } + return this; + } + /** + * Updates the current Vector4 with the minimal coordinate values between its and the given coordinates + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @param w defines the w coordinate of the operand + * @returns the current updated Vector4 + */ + minimizeInPlaceFromFloats(x, y, z, w) { + this.x = Math.min(x, this.x); + this.y = Math.min(y, this.y); + this.z = Math.min(z, this.z); + this.w = Math.min(w, this.w); + return this; + } + /** + * Updates the current Vector4 with the maximal coordinate values between its and the given coordinates. + * @param x defines the x coordinate of the operand + * @param y defines the y coordinate of the operand + * @param z defines the z coordinate of the operand + * @param w defines the w coordinate of the operand + * @returns the current updated Vector4 + */ + maximizeInPlaceFromFloats(x, y, z, w) { + this.x = Math.max(x, this.x); + this.y = Math.max(y, this.y); + this.z = Math.max(z, this.z); + this.w = Math.max(w, this.w); + return this; + } + /** + * Gets the current Vector4's floored values and stores them in result + * @param result the vector to store the result in + * @returns the result vector + */ + floorToRef(result) { + result.x = Math.floor(this.x); + result.y = Math.floor(this.y); + result.z = Math.floor(this.z); + result.w = Math.floor(this.w); + return result; + } + /** + * Gets a new Vector4 from current Vector4 floored values + * @returns a new Vector4 + */ + floor() { + return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w)); + } + /** + * Gets the current Vector4's fractional values and stores them in result + * @param result the vector to store the result in + * @returns the result vector + */ + fractToRef(result) { + result.x = this.x - Math.floor(this.x); + result.y = this.y - Math.floor(this.y); + result.z = this.z - Math.floor(this.z); + result.w = this.w - Math.floor(this.w); + return result; + } + /** + * Gets a new Vector4 from current Vector4 fractional values + * @returns a new Vector4 + */ + fract() { + return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w)); + } + // Properties + /** + * Returns the Vector4 length (float). + * @returns the length + */ + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + /** + * Returns the Vector4 squared length (float). + * @returns the length squared + */ + lengthSquared() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + // Methods + /** + * Normalizes in place the Vector4. + * @returns the updated Vector4. + */ + normalize() { + return this.normalizeFromLength(this.length()); + } + /** + * Normalize the current Vector4 with the given input length. + * Please note that this is an in place operation. + * @param len the length of the vector + * @returns the current updated Vector4 + */ + normalizeFromLength(len) { + if (len === 0 || len === 1.0) { + return this; + } + return this.scaleInPlace(1.0 / len); + } + /** + * Normalize the current Vector4 to a new vector + * @returns the new Vector4 + */ + normalizeToNew() { + return this.normalizeToRef(new Vector4()); + } + /** + * Normalize the current Vector4 to the reference + * @param reference define the Vector4 to update + * @returns the updated Vector4 + */ + normalizeToRef(reference) { + const len = this.length(); + if (len === 0 || len === 1.0) { + reference.x = this.x; + reference.y = this.y; + reference.z = this.z; + reference.w = this.w; + return reference; + } + return this.scaleToRef(1.0 / len, reference); + } + /** + * Returns a new Vector3 from the Vector4 (x, y, z) coordinates. + * @returns this converted to a new vector3 + */ + toVector3() { + return new Vector3(this.x, this.y, this.z); + } + /** + * Returns a new Vector4 copied from the current one. + * @returns the new cloned vector + */ + clone() { + return new Vector4(this.x, this.y, this.z, this.w); + } + /** + * Updates the current Vector4 with the given one coordinates. + * @param source the source vector to copy from + * @returns the updated Vector4. + */ + copyFrom(source) { + this.x = source.x; + this.y = source.y; + this.z = source.z; + this.w = source.w; + return this; + } + /** + * Updates the current Vector4 coordinates with the given floats. + * @param x float to copy from + * @param y float to copy from + * @param z float to copy from + * @param w float to copy from + * @returns the updated Vector4. + */ + copyFromFloats(x, y, z, w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + return this; + } + /** + * Updates the current Vector4 coordinates with the given floats. + * @param x float to set from + * @param y float to set from + * @param z float to set from + * @param w float to set from + * @returns the updated Vector4. + */ + set(x, y, z, w) { + return this.copyFromFloats(x, y, z, w); + } + /** + * Copies the given float to the current Vector4 coordinates + * @param v defines the x, y, z and w coordinates of the operand + * @returns the current updated Vector4 + */ + setAll(v) { + this.x = this.y = this.z = this.w = v; + return this; + } + /** + * Returns the dot product (float) between the current vectors and "otherVector" + * @param otherVector defines the right operand + * @returns the dot product + */ + dot(otherVector) { + return this.x * otherVector.x + this.y * otherVector.y + this.z * otherVector.z + this.w * otherVector.w; + } + // Statics + /** + * Returns a new Vector4 set from the starting index of the given array. + * @param array the array to pull values from + * @param offset the offset into the array to start at + * @returns the new vector + */ + static FromArray(array, offset) { + if (!offset) { + offset = 0; + } + return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); + } + /** + * Updates the given vector "result" from the starting index of the given array. + * @param array the array to pull values from + * @param offset the offset into the array to start at + * @param result the vector to store the result in + * @returns result input + */ + static FromArrayToRef(array, offset, result) { + result.x = array[offset]; + result.y = array[offset + 1]; + result.z = array[offset + 2]; + result.w = array[offset + 3]; + return result; + } + /** + * Updates the given vector "result" from the starting index of the given Float32Array. + * @param array the array to pull values from + * @param offset the offset into the array to start at + * @param result the vector to store the result in + * @returns result input + */ + static FromFloatArrayToRef(array, offset, result) { + Vector4.FromArrayToRef(array, offset, result); + return result; + } + /** + * Updates the given vector "result" coordinates from the given floats. + * @param x float to set from + * @param y float to set from + * @param z float to set from + * @param w float to set from + * @param result the vector to the floats in + * @returns result input + */ + static FromFloatsToRef(x, y, z, w, result) { + result.x = x; + result.y = y; + result.z = z; + result.w = w; + return result; + } + /** + * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0) + * @returns the new vector + */ + static Zero() { + return new Vector4(0.0, 0.0, 0.0, 0.0); + } + /** + * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0) + * @returns the new vector + */ + static One() { + return new Vector4(1.0, 1.0, 1.0, 1.0); + } + /** + * Returns a new Vector4 with random values between min and max + * @param min the minimum random value + * @param max the maximum random value + * @returns a Vector4 with random values between min and max + */ + static Random(min = 0, max = 1) { + return new Vector4(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max)); + } + /** + * Sets a Vector4 with random values between min and max + * @param min the minimum random value + * @param max the maximum random value + * @param ref the ref to store the values in + * @returns the ref with random values between min and max + */ + static RandomToRef(min = 0, max = 1, ref) { + ref.x = RandomRange(min, max); + ref.y = RandomRange(min, max); + ref.z = RandomRange(min, max); + ref.w = RandomRange(min, max); + return ref; + } + /** + * Returns a new Vector4 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" + * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one + * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one + * @param value defines the current value + * @param min defines the lower range value + * @param max defines the upper range value + * @returns the new Vector4 + */ + static Clamp(value, min, max) { + return Vector4.ClampToRef(value, min, max, new Vector4()); + } + /** + * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" + * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one + * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one + * @param value defines the current value + * @param min defines the lower range value + * @param max defines the upper range value + * @param result defines the Vector4 where to store the result + * @returns result input + */ + static ClampToRef(value, min, max, result) { + result.x = Clamp(value.x, min.x, max.x); + result.y = Clamp(value.y, min.y, max.y); + result.z = Clamp(value.z, min.z, max.z); + result.w = Clamp(value.w, min.w, max.w); + return result; + } + /** + * Checks if a given vector is inside a specific range + * Example Playground https://playground.babylonjs.com/#R1F8YU#75 + * @param v defines the vector to test + * @param min defines the minimum range + * @param max defines the maximum range + */ + static CheckExtends(v, min, max) { + min.minimizeInPlace(v); + max.maximizeInPlace(v); + } + /** + * Gets a zero Vector4 that must not be updated + */ + static get ZeroReadOnly() { + return Vector4._ZeroReadOnly; + } + /** + * Returns a new normalized Vector4 from the given one. + * @param vector the vector to normalize + * @returns the vector + */ + static Normalize(vector) { + return Vector4.NormalizeToRef(vector, new Vector4()); + } + /** + * Updates the given vector "result" from the normalization of the given one. + * @param vector the vector to normalize + * @param result the vector to store the result in + * @returns result input + */ + static NormalizeToRef(vector, result) { + vector.normalizeToRef(result); + return result; + } + /** + * Returns a vector with the minimum values from the left and right vectors + * @param left left vector to minimize + * @param right right vector to minimize + * @returns a new vector with the minimum of the left and right vector values + */ + static Minimize(left, right) { + const min = new Vector4(); + min.copyFrom(left); + min.minimizeInPlace(right); + return min; + } + /** + * Returns a vector with the maximum values from the left and right vectors + * @param left left vector to maximize + * @param right right vector to maximize + * @returns a new vector with the maximum of the left and right vector values + */ + static Maximize(left, right) { + const max = new Vector4(); + max.copyFrom(left); + max.maximizeInPlace(right); + return max; + } + /** + * Returns the distance (float) between the vectors "value1" and "value2". + * @param value1 value to calulate the distance between + * @param value2 value to calulate the distance between + * @returns the distance between the two vectors + */ + static Distance(value1, value2) { + return Math.sqrt(Vector4.DistanceSquared(value1, value2)); + } + /** + * Returns the squared distance (float) between the vectors "value1" and "value2". + * @param value1 value to calulate the distance between + * @param value2 value to calulate the distance between + * @returns the distance between the two vectors squared + */ + static DistanceSquared(value1, value2) { + const x = value1.x - value2.x; + const y = value1.y - value2.y; + const z = value1.z - value2.z; + const w = value1.w - value2.w; + return x * x + y * y + z * z + w * w; + } + /** + * Returns a new Vector4 located at the center between the vectors "value1" and "value2". + * @param value1 value to calulate the center between + * @param value2 value to calulate the center between + * @returns the center between the two vectors + */ + static Center(value1, value2) { + return Vector4.CenterToRef(value1, value2, new Vector4()); + } + /** + * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref" + * @param value1 defines first vector + * @param value2 defines second vector + * @param ref defines third vector + * @returns ref + */ + static CenterToRef(value1, value2, ref) { + ref.x = (value1.x + value2.x) / 2; + ref.y = (value1.y + value2.y) / 2; + ref.z = (value1.z + value2.z) / 2; + ref.w = (value1.w + value2.w) / 2; + return ref; + } + /** + * Returns a new Vector4 set with the result of the transformation by the given matrix of the given vector. + * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account) + * The difference with Vector3.TransformCoordinates is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead + * @param vector defines the Vector3 to transform + * @param transformation defines the transformation matrix + * @returns the transformed Vector4 + */ + static TransformCoordinates(vector, transformation) { + return Vector4.TransformCoordinatesToRef(vector, transformation, new Vector4()); + } + /** + * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector + * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account) + * The difference with Vector3.TransformCoordinatesToRef is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead + * @param vector defines the Vector3 to transform + * @param transformation defines the transformation matrix + * @param result defines the Vector4 where to store the result + * @returns result input + */ + static TransformCoordinatesToRef(vector, transformation, result) { + Vector4.TransformCoordinatesFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result); + return result; + } + /** + * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z) + * This method computes tranformed coordinates only, not transformed direction vectors + * The difference with Vector3.TransformCoordinatesFromFloatsToRef is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead + * @param x define the x coordinate of the source vector + * @param y define the y coordinate of the source vector + * @param z define the z coordinate of the source vector + * @param transformation defines the transformation matrix + * @param result defines the Vector4 where to store the result + * @returns result input + */ + static TransformCoordinatesFromFloatsToRef(x, y, z, transformation, result) { + const m = transformation.m; + const rx = x * m[0] + y * m[4] + z * m[8] + m[12]; + const ry = x * m[1] + y * m[5] + z * m[9] + m[13]; + const rz = x * m[2] + y * m[6] + z * m[10] + m[14]; + const rw = x * m[3] + y * m[7] + z * m[11] + m[15]; + result.x = rx; + result.y = ry; + result.z = rz; + result.w = rw; + return result; + } + /** + * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector. + * This methods computes transformed normalized direction vectors only. + * @param vector the vector to transform + * @param transformation the transformation matrix to apply + * @returns the new vector + */ + static TransformNormal(vector, transformation) { + return Vector4.TransformNormalToRef(vector, transformation, new Vector4()); + } + /** + * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector. + * This methods computes transformed normalized direction vectors only. + * @param vector the vector to transform + * @param transformation the transformation matrix to apply + * @param result the vector to store the result in + * @returns result input + */ + static TransformNormalToRef(vector, transformation, result) { + const m = transformation.m; + const x = vector.x * m[0] + vector.y * m[4] + vector.z * m[8]; + const y = vector.x * m[1] + vector.y * m[5] + vector.z * m[9]; + const z = vector.x * m[2] + vector.y * m[6] + vector.z * m[10]; + result.x = x; + result.y = y; + result.z = z; + result.w = vector.w; + return result; + } + /** + * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w). + * This methods computes transformed normalized direction vectors only. + * @param x value to transform + * @param y value to transform + * @param z value to transform + * @param w value to transform + * @param transformation the transformation matrix to apply + * @param result the vector to store the results in + * @returns result input + */ + static TransformNormalFromFloatsToRef(x, y, z, w, transformation, result) { + const m = transformation.m; + result.x = x * m[0] + y * m[4] + z * m[8]; + result.y = x * m[1] + y * m[5] + z * m[9]; + result.z = x * m[2] + y * m[6] + z * m[10]; + result.w = w; + return result; + } + /** + * Creates a new Vector4 from a Vector3 + * @param source defines the source data + * @param w defines the 4th component (default is 0) + * @returns a new Vector4 + */ + static FromVector3(source, w = 0) { + return new Vector4(source._x, source._y, source._z, w); + } + /** + * Returns the dot product (float) between the vectors "left" and "right" + * @param left defines the left operand + * @param right defines the right operand + * @returns the dot product + */ + static Dot(left, right) { + return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w; + } +} +/** + * If the first vector is flagged with integers (as everything is 0,0,0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet. + * If subsequent vectors are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers, + * and henceforth it will use floating-point representation for all Vector4 instances that it creates. + * But the original Vector4 instances are unchanged and has a "deprecated map". + * If we keep using the Vector4 instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches. + */ +Vector4._V8PerformanceHack = new Vector4(0.5, 0.5, 0.5, 0.5); +Vector4._ZeroReadOnly = Vector4.Zero(); +Object.defineProperties(Vector4.prototype, { + dimension: { value: [4] }, + rank: { value: 1 }, +}); +/** + * Class used to store quaternion data + * Example Playground - Overview - https://playground.babylonjs.com/#L49EJ7#100 + * @see https://en.wikipedia.org/wiki/Quaternion + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms + */ +class Quaternion { + /** Gets or sets the x coordinate */ + get x() { + return this._x; + } + set x(value) { + this._x = value; + this._isDirty = true; + } + /** Gets or sets the y coordinate */ + get y() { + return this._y; + } + set y(value) { + this._y = value; + this._isDirty = true; + } + /** Gets or sets the z coordinate */ + get z() { + return this._z; + } + set z(value) { + this._z = value; + this._isDirty = true; + } + /** Gets or sets the w coordinate */ + get w() { + return this._w; + } + set w(value) { + this._w = value; + this._isDirty = true; + } + /** + * Creates a new Quaternion from the given floats + * @param x defines the first component (0 by default) + * @param y defines the second component (0 by default) + * @param z defines the third component (0 by default) + * @param w defines the fourth component (1.0 by default) + */ + constructor(x = 0.0, y = 0.0, z = 0.0, w = 1.0) { + /** @internal */ + this._isDirty = true; + this._x = x; + this._y = y; + this._z = z; + this._w = w; + } + /** + * Gets a string representation for the current quaternion + * @returns a string with the Quaternion coordinates + */ + toString() { + return `{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`; + } + /** + * Gets the class name of the quaternion + * @returns the string "Quaternion" + */ + getClassName() { + return "Quaternion"; + } + /** + * Gets a hash code for this quaternion + * @returns the quaternion hash code + */ + getHashCode() { + const x = _ExtractAsInt(this._x); + const y = _ExtractAsInt(this._y); + const z = _ExtractAsInt(this._z); + const w = _ExtractAsInt(this._w); + let hash = x; + hash = (hash * 397) ^ y; + hash = (hash * 397) ^ z; + hash = (hash * 397) ^ w; + return hash; + } + /** + * Copy the quaternion to an array + * Example Playground https://playground.babylonjs.com/#L49EJ7#13 + * @returns a new array populated with 4 elements from the quaternion coordinates + */ + asArray() { + return [this._x, this._y, this._z, this._w]; + } + /** + * Stores from the starting index in the given array the Quaternion successive values + * Example Playground https://playground.babylonjs.com/#L49EJ7#59 + * @param array defines the array where to store the x,y,z,w components + * @param index defines an optional index in the target array to define where to start storing values + * @returns the current Quaternion object + */ + toArray(array, index = 0) { + array[index] = this._x; + array[index + 1] = this._y; + array[index + 2] = this._z; + array[index + 3] = this._w; + return this; + } + fromArray(array, index = 0) { + return Quaternion.FromArrayToRef(array, index, this); + } + /** + * Check if two quaternions are equals + * Example Playground https://playground.babylonjs.com/#L49EJ7#38 + * @param otherQuaternion defines the second operand + * @returns true if the current quaternion and the given one coordinates are strictly equals + */ + equals(otherQuaternion) { + return otherQuaternion && this._x === otherQuaternion._x && this._y === otherQuaternion._y && this._z === otherQuaternion._z && this._w === otherQuaternion._w; + } + /** + * Gets a boolean if two quaternions are equals (using an epsilon value) + * Example Playground https://playground.babylonjs.com/#L49EJ7#37 + * @param otherQuaternion defines the other quaternion + * @param epsilon defines the minimal distance to consider equality + * @returns true if the given quaternion coordinates are close to the current ones by a distance of epsilon. + */ + equalsWithEpsilon(otherQuaternion, epsilon = Epsilon) { + return (otherQuaternion && + WithinEpsilon(this._x, otherQuaternion._x, epsilon) && + WithinEpsilon(this._y, otherQuaternion._y, epsilon) && + WithinEpsilon(this._z, otherQuaternion._z, epsilon) && + WithinEpsilon(this._w, otherQuaternion._w, epsilon)); + } + /** + * Gets a boolean if two quaternions are equals (using an epsilon value), taking care of double cover : https://www.reedbeta.com/blog/why-quaternions-double-cover/ + * @param otherQuaternion defines the other quaternion + * @param epsilon defines the minimal distance to consider equality + * @returns true if the given quaternion coordinates are close to the current ones by a distance of epsilon. + */ + isApprox(otherQuaternion, epsilon = Epsilon) { + return (otherQuaternion && + ((WithinEpsilon(this._x, otherQuaternion._x, epsilon) && + WithinEpsilon(this._y, otherQuaternion._y, epsilon) && + WithinEpsilon(this._z, otherQuaternion._z, epsilon) && + WithinEpsilon(this._w, otherQuaternion._w, epsilon)) || + (WithinEpsilon(this._x, -otherQuaternion._x, epsilon) && + WithinEpsilon(this._y, -otherQuaternion._y, epsilon) && + WithinEpsilon(this._z, -otherQuaternion._z, epsilon) && + WithinEpsilon(this._w, -otherQuaternion._w, epsilon)))); + } + /** + * Clone the current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#12 + * @returns a new quaternion copied from the current one + */ + clone() { + return new Quaternion(this._x, this._y, this._z, this._w); + } + /** + * Copy a quaternion to the current one + * Example Playground https://playground.babylonjs.com/#L49EJ7#86 + * @param other defines the other quaternion + * @returns the updated current quaternion + */ + copyFrom(other) { + this._x = other._x; + this._y = other._y; + this._z = other._z; + this._w = other._w; + this._isDirty = true; + return this; + } + /** + * Updates the current quaternion with the given float coordinates + * Example Playground https://playground.babylonjs.com/#L49EJ7#87 + * @param x defines the x coordinate + * @param y defines the y coordinate + * @param z defines the z coordinate + * @param w defines the w coordinate + * @returns the updated current quaternion + */ + copyFromFloats(x, y, z, w) { + this._x = x; + this._y = y; + this._z = z; + this._w = w; + this._isDirty = true; + return this; + } + /** + * Updates the current quaternion from the given float coordinates + * Example Playground https://playground.babylonjs.com/#L49EJ7#56 + * @param x defines the x coordinate + * @param y defines the y coordinate + * @param z defines the z coordinate + * @param w defines the w coordinate + * @returns the updated current quaternion + */ + set(x, y, z, w) { + return this.copyFromFloats(x, y, z, w); + } + setAll(value) { + return this.copyFromFloats(value, value, value, value); + } + /** + * Adds two quaternions + * Example Playground https://playground.babylonjs.com/#L49EJ7#10 + * @param other defines the second operand + * @returns a new quaternion as the addition result of the given one and the current quaternion + */ + add(other) { + return new Quaternion(this._x + other._x, this._y + other._y, this._z + other._z, this._w + other._w); + } + /** + * Add a quaternion to the current one + * Example Playground https://playground.babylonjs.com/#L49EJ7#11 + * @param other defines the quaternion to add + * @returns the current quaternion + */ + addInPlace(other) { + this._x += other._x; + this._y += other._y; + this._z += other._z; + this._w += other._w; + this._isDirty = true; + return this; + } + addToRef(other, result) { + result._x = this._x + other._x; + result._y = this._y + other._y; + result._z = this._z + other._z; + result._w = this._w + other._w; + result._isDirty = true; + return result; + } + addInPlaceFromFloats(x, y, z, w) { + this._x += x; + this._y += y; + this._z += z; + this._w += w; + this._isDirty = true; + return this; + } + subtractToRef(other, result) { + result._x = this._x - other._x; + result._y = this._y - other._y; + result._z = this._z - other._z; + result._w = this._w - other._w; + result._isDirty = true; + return result; + } + subtractFromFloats(x, y, z, w) { + return this.subtractFromFloatsToRef(x, y, z, w, new Quaternion()); + } + subtractFromFloatsToRef(x, y, z, w, result) { + result._x = this._x - x; + result._y = this._y - y; + result._z = this._z - z; + result._w = this._w - w; + result._isDirty = true; + return result; + } + /** + * Subtract two quaternions + * Example Playground https://playground.babylonjs.com/#L49EJ7#57 + * @param other defines the second operand + * @returns a new quaternion as the subtraction result of the given one from the current one + */ + subtract(other) { + return new Quaternion(this._x - other._x, this._y - other._y, this._z - other._z, this._w - other._w); + } + /** + * Subtract a quaternion to the current one + * Example Playground https://playground.babylonjs.com/#L49EJ7#58 + * @param other defines the quaternion to subtract + * @returns the current quaternion + */ + subtractInPlace(other) { + this._x -= other._x; + this._y -= other._y; + this._z -= other._z; + this._w -= other._w; + this._isDirty = true; + return this; + } + /** + * Multiplies the current quaternion by a scale factor + * Example Playground https://playground.babylonjs.com/#L49EJ7#88 + * @param value defines the scale factor + * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale" + */ + scale(value) { + return new Quaternion(this._x * value, this._y * value, this._z * value, this._w * value); + } + /** + * Scale the current quaternion values by a factor and stores the result to a given quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#89 + * @param scale defines the scale factor + * @param result defines the Quaternion object where to store the result + * @returns result input + */ + scaleToRef(scale, result) { + result._x = this._x * scale; + result._y = this._y * scale; + result._z = this._z * scale; + result._w = this._w * scale; + result._isDirty = true; + return result; + } + /** + * Multiplies in place the current quaternion by a scale factor + * Example Playground https://playground.babylonjs.com/#L49EJ7#90 + * @param value defines the scale factor + * @returns the current modified quaternion + */ + scaleInPlace(value) { + this._x *= value; + this._y *= value; + this._z *= value; + this._w *= value; + this._isDirty = true; + return this; + } + /** + * Scale the current quaternion values by a factor and add the result to a given quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#91 + * @param scale defines the scale factor + * @param result defines the Quaternion object where to store the result + * @returns result input + */ + scaleAndAddToRef(scale, result) { + result._x += this._x * scale; + result._y += this._y * scale; + result._z += this._z * scale; + result._w += this._w * scale; + result._isDirty = true; + return result; + } + /** + * Multiplies two quaternions + * Example Playground https://playground.babylonjs.com/#L49EJ7#43 + * @param q1 defines the second operand + * @returns a new quaternion set as the multiplication result of the current one with the given one "q1" + */ + multiply(q1) { + const result = new Quaternion(0, 0, 0, 1.0); + this.multiplyToRef(q1, result); + return result; + } + /** + * Sets the given "result" as the multiplication result of the current one with the given one "q1" + * Example Playground https://playground.babylonjs.com/#L49EJ7#45 + * @param q1 defines the second operand + * @param result defines the target quaternion + * @returns the current quaternion + */ + multiplyToRef(q1, result) { + const x = this._x * q1._w + this._y * q1._z - this._z * q1._y + this._w * q1._x; + const y = -this._x * q1._z + this._y * q1._w + this._z * q1._x + this._w * q1._y; + const z = this._x * q1._y - this._y * q1._x + this._z * q1._w + this._w * q1._z; + const w = -this._x * q1._x - this._y * q1._y - this._z * q1._z + this._w * q1._w; + result.copyFromFloats(x, y, z, w); + return result; + } + /** + * Updates the current quaternion with the multiplication of itself with the given one "q1" + * Example Playground https://playground.babylonjs.com/#L49EJ7#46 + * @param other defines the second operand + * @returns the currentupdated quaternion + */ + multiplyInPlace(other) { + return this.multiplyToRef(other, this); + } + multiplyByFloats(x, y, z, w) { + this._x *= x; + this._y *= y; + this._z *= z; + this._w *= w; + this._isDirty = true; + return this; + } + /** + * @internal + * Do not use + */ + divide(_other) { + throw new ReferenceError("Can not divide a quaternion"); + } + /** + * @internal + * Do not use + */ + divideToRef(_other, _result) { + throw new ReferenceError("Can not divide a quaternion"); + } + /** + * @internal + * Do not use + */ + divideInPlace(_other) { + throw new ReferenceError("Can not divide a quaternion"); + } + /** + * @internal + * Do not use + */ + minimizeInPlace() { + throw new ReferenceError("Can not minimize a quaternion"); + } + /** + * @internal + * Do not use + */ + minimizeInPlaceFromFloats() { + throw new ReferenceError("Can not minimize a quaternion"); + } + /** + * @internal + * Do not use + */ + maximizeInPlace() { + throw new ReferenceError("Can not maximize a quaternion"); + } + /** + * @internal + * Do not use + */ + maximizeInPlaceFromFloats() { + throw new ReferenceError("Can not maximize a quaternion"); + } + negate() { + return this.negateToRef(new Quaternion()); + } + negateInPlace() { + this._x = -this._x; + this._y = -this._y; + this._z = -this._z; + this._w = -this._w; + this._isDirty = true; + return this; + } + negateToRef(result) { + result._x = -this._x; + result._y = -this._y; + result._z = -this._z; + result._w = -this._w; + result._isDirty = true; + return result; + } + equalsToFloats(x, y, z, w) { + return this._x === x && this._y === y && this._z === z && this._w === w; + } + /** + * @internal + * Do not use + */ + floorToRef(_result) { + throw new ReferenceError("Can not floor a quaternion"); + } + /** + * @internal + * Do not use + */ + floor() { + throw new ReferenceError("Can not floor a quaternion"); + } + /** + * @internal + * Do not use + */ + fractToRef(_result) { + throw new ReferenceError("Can not fract a quaternion"); + } + /** + * @internal + * Do not use + */ + fract() { + throw new ReferenceError("Can not fract a quaternion"); + } + /** + * Conjugates the current quaternion and stores the result in the given quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#81 + * @param ref defines the target quaternion + * @returns result input + */ + conjugateToRef(ref) { + ref.copyFromFloats(-this._x, -this._y, -this._z, this._w); + return ref; + } + /** + * Conjugates in place the current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#82 + * @returns the current updated quaternion + */ + conjugateInPlace() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._isDirty = true; + return this; + } + /** + * Conjugates (1-q) the current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#83 + * @returns a new quaternion + */ + conjugate() { + return new Quaternion(-this._x, -this._y, -this._z, this._w); + } + /** + * Returns the inverse of the current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#84 + * @returns a new quaternion + */ + invert() { + const conjugate = this.conjugate(); + const lengthSquared = this.lengthSquared(); + if (lengthSquared == 0 || lengthSquared == 1) { + return conjugate; + } + conjugate.scaleInPlace(1 / lengthSquared); + return conjugate; + } + /** + * Invert in place the current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#85 + * @returns this quaternion + */ + invertInPlace() { + this.conjugateInPlace(); + const lengthSquared = this.lengthSquared(); + if (lengthSquared == 0 || lengthSquared == 1) { + return this; + } + this.scaleInPlace(1 / lengthSquared); + return this; + } + /** + * Gets squared length of current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#29 + * @returns the quaternion length (float) + */ + lengthSquared() { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } + /** + * Gets length of current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#28 + * @returns the quaternion length (float) + */ + length() { + return Math.sqrt(this.lengthSquared()); + } + /** + * Normalize in place the current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#54 + * @returns the current updated quaternion + */ + normalize() { + return this.normalizeFromLength(this.length()); + } + /** + * Normalize the current quaternion with the given input length. + * Please note that this is an in place operation. + * @param len the length of the quaternion + * @returns the current updated Quaternion + */ + normalizeFromLength(len) { + if (len === 0 || len === 1.0) { + return this; + } + return this.scaleInPlace(1.0 / len); + } + /** + * Normalize a copy of the current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#55 + * @returns the normalized quaternion + */ + normalizeToNew() { + const normalized = new Quaternion(0, 0, 0, 1); + this.normalizeToRef(normalized); + return normalized; + } + /** + * Normalize the current Quaternion to the reference + * @param reference define the Quaternion to update + * @returns the updated Quaternion + */ + normalizeToRef(reference) { + const len = this.length(); + if (len === 0 || len === 1.0) { + return reference.copyFromFloats(this._x, this._y, this._z, this._w); + } + return this.scaleToRef(1.0 / len, reference); + } + /** + * Returns a new Vector3 set with the Euler angles translated from the current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#32 + * @returns a new Vector3 containing the Euler angles + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions + */ + toEulerAngles() { + const result = Vector3.Zero(); + this.toEulerAnglesToRef(result); + return result; + } + /** + * Sets the given vector3 "result" with the Euler angles translated from the current quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#31 + * @param result defines the vector which will be filled with the Euler angles + * @returns result input + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions + */ + toEulerAnglesToRef(result) { + const qz = this._z; + const qx = this._x; + const qy = this._y; + const qw = this._w; + const zAxisY = qy * qz - qx * qw; + const limit = 0.4999999; + if (zAxisY < -limit) { + result._y = 2 * Math.atan2(qy, qw); + result._x = Math.PI / 2; + result._z = 0; + result._isDirty = true; + } + else if (zAxisY > limit) { + result._y = 2 * Math.atan2(qy, qw); + result._x = -Math.PI / 2; + result._z = 0; + result._isDirty = true; + } + else { + const sqw = qw * qw; + const sqz = qz * qz; + const sqx = qx * qx; + const sqy = qy * qy; + result._z = Math.atan2(2.0 * (qx * qy + qz * qw), -sqz - sqx + sqy + sqw); + result._x = Math.asin(-2 * zAxisY); + result._y = Math.atan2(2.0 * (qz * qx + qy * qw), sqz - sqx - sqy + sqw); + result._isDirty = true; + } + return result; + } + /** + * Sets the given vector3 "result" with the Alpha, Beta, Gamma Euler angles translated from the current quaternion + * @param result defines the vector which will be filled with the Euler angles + * @returns result input + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions + */ + toAlphaBetaGammaToRef(result) { + const qz = this._z; + const qx = this._x; + const qy = this._y; + const qw = this._w; + // Compute intermediate values + const sinHalfBeta = Math.sqrt(qx * qx + qy * qy); + const cosHalfBeta = Math.sqrt(qz * qz + qw * qw); + // Calculate beta + const beta = 2 * Math.atan2(sinHalfBeta, cosHalfBeta); + // Calculate gamma + alpha + const gammaPlusAlpha = 2 * Math.atan2(qz, qw); + // Calculate gamma - alpha + const gammaMinusAlpha = 2 * Math.atan2(qy, qx); + // Calculate gamma and alpha + const gamma = (gammaPlusAlpha + gammaMinusAlpha) / 2; + const alpha = (gammaPlusAlpha - gammaMinusAlpha) / 2; + result.set(alpha, beta, gamma); + return result; + } + /** + * Updates the given rotation matrix with the current quaternion values + * Example Playground https://playground.babylonjs.com/#L49EJ7#67 + * @param result defines the target matrix + * @returns the updated matrix with the rotation + */ + toRotationMatrix(result) { + Matrix.FromQuaternionToRef(this, result); + return result; + } + /** + * Updates the current quaternion from the given rotation matrix values + * Example Playground https://playground.babylonjs.com/#L49EJ7#41 + * @param matrix defines the source matrix + * @returns the current updated quaternion + */ + fromRotationMatrix(matrix) { + Quaternion.FromRotationMatrixToRef(matrix, this); + return this; + } + /** + * Returns the dot product (float) between the current quaternions and "other" + * @param other defines the right operand + * @returns the dot product + */ + dot(other) { + return this._x * other._x + this._y * other._y + this._z * other._z + this._w * other._w; + } + // Statics + /** + * Creates a new quaternion from a rotation matrix + * Example Playground https://playground.babylonjs.com/#L49EJ7#101 + * @param matrix defines the source matrix + * @returns a new quaternion created from the given rotation matrix values + */ + static FromRotationMatrix(matrix) { + const result = new Quaternion(); + Quaternion.FromRotationMatrixToRef(matrix, result); + return result; + } + /** + * Updates the given quaternion with the given rotation matrix values + * Example Playground https://playground.babylonjs.com/#L49EJ7#102 + * @param matrix defines the source matrix + * @param result defines the target quaternion + * @returns result input + */ + static FromRotationMatrixToRef(matrix, result) { + const data = matrix.m; + const m11 = data[0], m12 = data[4], m13 = data[8]; + const m21 = data[1], m22 = data[5], m23 = data[9]; + const m31 = data[2], m32 = data[6], m33 = data[10]; + const trace = m11 + m22 + m33; + let s; + if (trace > 0) { + s = 0.5 / Math.sqrt(trace + 1.0); + result._w = 0.25 / s; + result._x = (m32 - m23) * s; + result._y = (m13 - m31) * s; + result._z = (m21 - m12) * s; + result._isDirty = true; + } + else if (m11 > m22 && m11 > m33) { + s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33); + result._w = (m32 - m23) / s; + result._x = 0.25 * s; + result._y = (m12 + m21) / s; + result._z = (m13 + m31) / s; + result._isDirty = true; + } + else if (m22 > m33) { + s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33); + result._w = (m13 - m31) / s; + result._x = (m12 + m21) / s; + result._y = 0.25 * s; + result._z = (m23 + m32) / s; + result._isDirty = true; + } + else { + s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22); + result._w = (m21 - m12) / s; + result._x = (m13 + m31) / s; + result._y = (m23 + m32) / s; + result._z = 0.25 * s; + result._isDirty = true; + } + return result; + } + /** + * Returns the dot product (float) between the quaternions "left" and "right" + * Example Playground https://playground.babylonjs.com/#L49EJ7#61 + * @param left defines the left operand + * @param right defines the right operand + * @returns the dot product + */ + static Dot(left, right) { + return left._x * right._x + left._y * right._y + left._z * right._z + left._w * right._w; + } + /** + * Checks if the orientations of two rotation quaternions are close to each other + * Example Playground https://playground.babylonjs.com/#L49EJ7#60 + * @param quat0 defines the first quaternion to check + * @param quat1 defines the second quaternion to check + * @param epsilon defines closeness, 0 same orientation, 1 PI apart, default 0.1 + * @returns true if the two quaternions are close to each other within epsilon + */ + static AreClose(quat0, quat1, epsilon = 0.1) { + const dot = Quaternion.Dot(quat0, quat1); + return 1 - dot * dot <= epsilon; + } + /** + * Smooth interpolation between two quaternions using Slerp + * Example Playground https://playground.babylonjs.com/#L49EJ7#93 + * @param source source quaternion + * @param goal goal quaternion + * @param deltaTime current interpolation frame + * @param lerpTime total interpolation time + * @param result the smoothed quaternion + * @returns the smoothed quaternion + */ + static SmoothToRef(source, goal, deltaTime, lerpTime, result) { + let slerp = lerpTime === 0 ? 1 : deltaTime / lerpTime; + slerp = Clamp(slerp, 0, 1); + Quaternion.SlerpToRef(source, goal, slerp, result); + return result; + } + /** + * Creates an empty quaternion + * @returns a new quaternion set to (0.0, 0.0, 0.0) + */ + static Zero() { + return new Quaternion(0.0, 0.0, 0.0, 0.0); + } + /** + * Inverse a given quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#103 + * @param q defines the source quaternion + * @returns a new quaternion as the inverted current quaternion + */ + static Inverse(q) { + return new Quaternion(-q._x, -q._y, -q._z, q._w); + } + /** + * Inverse a given quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#104 + * @param q defines the source quaternion + * @param result the quaternion the result will be stored in + * @returns the result quaternion + */ + static InverseToRef(q, result) { + result.set(-q._x, -q._y, -q._z, q._w); + return result; + } + /** + * Creates an identity quaternion + * @returns the identity quaternion + */ + static Identity() { + return new Quaternion(0.0, 0.0, 0.0, 1.0); + } + /** + * Gets a boolean indicating if the given quaternion is identity + * @param quaternion defines the quaternion to check + * @returns true if the quaternion is identity + */ + static IsIdentity(quaternion) { + return quaternion && quaternion._x === 0 && quaternion._y === 0 && quaternion._z === 0 && quaternion._w === 1; + } + /** + * Creates a quaternion from a rotation around an axis + * Example Playground https://playground.babylonjs.com/#L49EJ7#72 + * @param axis defines the axis to use + * @param angle defines the angle to use + * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float) + */ + static RotationAxis(axis, angle) { + return Quaternion.RotationAxisToRef(axis, angle, new Quaternion()); + } + /** + * Creates a rotation around an axis and stores it into the given quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#73 + * @param axis defines the axis to use + * @param angle defines the angle to use + * @param result defines the target quaternion + * @returns the target quaternion + */ + static RotationAxisToRef(axis, angle, result) { + result._w = Math.cos(angle / 2); + const sinByLength = Math.sin(angle / 2) / axis.length(); + result._x = axis._x * sinByLength; + result._y = axis._y * sinByLength; + result._z = axis._z * sinByLength; + result._isDirty = true; + return result; + } + /** + * Creates a new quaternion from data stored into an array + * Example Playground https://playground.babylonjs.com/#L49EJ7#63 + * @param array defines the data source + * @param offset defines the offset in the source array where the data starts + * @returns a new quaternion + */ + static FromArray(array, offset) { + if (!offset) { + offset = 0; + } + return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); + } + /** + * Updates the given quaternion "result" from the starting index of the given array. + * Example Playground https://playground.babylonjs.com/#L49EJ7#64 + * @param array the array to pull values from + * @param offset the offset into the array to start at + * @param result the quaternion to store the result in + * @returns result input + */ + static FromArrayToRef(array, offset, result) { + result._x = array[offset]; + result._y = array[offset + 1]; + result._z = array[offset + 2]; + result._w = array[offset + 3]; + result._isDirty = true; + return result; + } + /** + * Sets the given quaternion "result" with the given floats. + * @param x defines the x coordinate of the source + * @param y defines the y coordinate of the source + * @param z defines the z coordinate of the source + * @param w defines the w coordinate of the source + * @param result defines the quaternion where to store the result + * @returns the result quaternion + */ + static FromFloatsToRef(x, y, z, w, result) { + result.copyFromFloats(x, y, z, w); + return result; + } + /** + * Create a quaternion from Euler rotation angles + * Example Playground https://playground.babylonjs.com/#L49EJ7#33 + * @param x Pitch + * @param y Yaw + * @param z Roll + * @returns the new Quaternion + */ + static FromEulerAngles(x, y, z) { + const q = new Quaternion(); + Quaternion.RotationYawPitchRollToRef(y, x, z, q); + return q; + } + /** + * Updates a quaternion from Euler rotation angles + * Example Playground https://playground.babylonjs.com/#L49EJ7#34 + * @param x Pitch + * @param y Yaw + * @param z Roll + * @param result the quaternion to store the result + * @returns the updated quaternion + */ + static FromEulerAnglesToRef(x, y, z, result) { + Quaternion.RotationYawPitchRollToRef(y, x, z, result); + return result; + } + /** + * Create a quaternion from Euler rotation vector + * Example Playground https://playground.babylonjs.com/#L49EJ7#35 + * @param vec the Euler vector (x Pitch, y Yaw, z Roll) + * @returns the new Quaternion + */ + static FromEulerVector(vec) { + const q = new Quaternion(); + Quaternion.RotationYawPitchRollToRef(vec._y, vec._x, vec._z, q); + return q; + } + /** + * Updates a quaternion from Euler rotation vector + * Example Playground https://playground.babylonjs.com/#L49EJ7#36 + * @param vec the Euler vector (x Pitch, y Yaw, z Roll) + * @param result the quaternion to store the result + * @returns the updated quaternion + */ + static FromEulerVectorToRef(vec, result) { + Quaternion.RotationYawPitchRollToRef(vec._y, vec._x, vec._z, result); + return result; + } + /** + * Updates a quaternion so that it rotates vector vecFrom to vector vecTo + * Example Playground - https://playground.babylonjs.com/#L49EJ7#70 + * @param vecFrom defines the direction vector from which to rotate + * @param vecTo defines the direction vector to which to rotate + * @param result the quaternion to store the result + * @param epsilon defines the minimal dot value to define vecs as opposite. Default: `BABYLON.Epsilon` + * @returns the updated quaternion + */ + static FromUnitVectorsToRef(vecFrom, vecTo, result, epsilon = Epsilon) { + const r = Vector3.Dot(vecFrom, vecTo) + 1; + if (r < epsilon) { + if (Math.abs(vecFrom.x) > Math.abs(vecFrom.z)) { + result.set(-vecFrom.y, vecFrom.x, 0, 0); + } + else { + result.set(0, -vecFrom.z, vecFrom.y, 0); + } + } + else { + Vector3.CrossToRef(vecFrom, vecTo, TmpVectors.Vector3[0]); + result.set(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z, r); + } + return result.normalize(); + } + /** + * Creates a new quaternion from the given Euler float angles (y, x, z) + * Example Playground https://playground.babylonjs.com/#L49EJ7#77 + * @param yaw defines the rotation around Y axis + * @param pitch defines the rotation around X axis + * @param roll defines the rotation around Z axis + * @returns the new quaternion + */ + static RotationYawPitchRoll(yaw, pitch, roll) { + const q = new Quaternion(); + Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q); + return q; + } + /** + * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#78 + * @param yaw defines the rotation around Y axis + * @param pitch defines the rotation around X axis + * @param roll defines the rotation around Z axis + * @param result defines the target quaternion + * @returns result input + */ + static RotationYawPitchRollToRef(yaw, pitch, roll, result) { + // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles) + const halfRoll = roll * 0.5; + const halfPitch = pitch * 0.5; + const halfYaw = yaw * 0.5; + const sinRoll = Math.sin(halfRoll); + const cosRoll = Math.cos(halfRoll); + const sinPitch = Math.sin(halfPitch); + const cosPitch = Math.cos(halfPitch); + const sinYaw = Math.sin(halfYaw); + const cosYaw = Math.cos(halfYaw); + result._x = cosYaw * sinPitch * cosRoll + sinYaw * cosPitch * sinRoll; + result._y = sinYaw * cosPitch * cosRoll - cosYaw * sinPitch * sinRoll; + result._z = cosYaw * cosPitch * sinRoll - sinYaw * sinPitch * cosRoll; + result._w = cosYaw * cosPitch * cosRoll + sinYaw * sinPitch * sinRoll; + result._isDirty = true; + return result; + } + /** + * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation + * Example Playground https://playground.babylonjs.com/#L49EJ7#68 + * @param alpha defines the rotation around first axis + * @param beta defines the rotation around second axis + * @param gamma defines the rotation around third axis + * @returns the new quaternion + */ + static RotationAlphaBetaGamma(alpha, beta, gamma) { + const result = new Quaternion(); + Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result); + return result; + } + /** + * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#69 + * @param alpha defines the rotation around first axis + * @param beta defines the rotation around second axis + * @param gamma defines the rotation around third axis + * @param result defines the target quaternion + * @returns result input + */ + static RotationAlphaBetaGammaToRef(alpha, beta, gamma, result) { + // Produces a quaternion from Euler angles in the z-x-z orientation + const halfGammaPlusAlpha = (gamma + alpha) * 0.5; + const halfGammaMinusAlpha = (gamma - alpha) * 0.5; + const halfBeta = beta * 0.5; + result._x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta); + result._y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta); + result._z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta); + result._w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta); + result._isDirty = true; + return result; + } + /** + * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) + * Example Playground https://playground.babylonjs.com/#L49EJ7#75 + * @param axis1 defines the first axis + * @param axis2 defines the second axis + * @param axis3 defines the third axis + * @returns the new quaternion + */ + static RotationQuaternionFromAxis(axis1, axis2, axis3) { + const quat = new Quaternion(0.0, 0.0, 0.0, 0.0); + Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat); + return quat; + } + /** + * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#76 + * @param axis1 defines the first axis + * @param axis2 defines the second axis + * @param axis3 defines the third axis + * @param ref defines the target quaternion + * @returns result input + */ + static RotationQuaternionFromAxisToRef(axis1, axis2, axis3, ref) { + const rotMat = MathTmp.Matrix[0]; + axis1 = axis1.normalizeToRef(MathTmp.Vector3[0]); + axis2 = axis2.normalizeToRef(MathTmp.Vector3[1]); + axis3 = axis3.normalizeToRef(MathTmp.Vector3[2]); + Matrix.FromXYZAxesToRef(axis1, axis2, axis3, rotMat); + Quaternion.FromRotationMatrixToRef(rotMat, ref); + return ref; + } + /** + * Creates a new rotation value to orient an object to look towards the given forward direction, the up direction being oriented like "up". + * This function works in left handed mode + * Example Playground https://playground.babylonjs.com/#L49EJ7#96 + * @param forward defines the forward direction - Must be normalized and orthogonal to up. + * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. + * @returns A new quaternion oriented toward the specified forward and up. + */ + static FromLookDirectionLH(forward, up) { + const quat = new Quaternion(); + Quaternion.FromLookDirectionLHToRef(forward, up, quat); + return quat; + } + /** + * Creates a new rotation value to orient an object to look towards the given forward direction with the up direction being oriented like "up", and stores it in the target quaternion. + * This function works in left handed mode + * Example Playground https://playground.babylonjs.com/#L49EJ7#97 + * @param forward defines the forward direction - Must be normalized and orthogonal to up. + * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. + * @param ref defines the target quaternion. + * @returns result input + */ + static FromLookDirectionLHToRef(forward, up, ref) { + const rotMat = MathTmp.Matrix[0]; + Matrix.LookDirectionLHToRef(forward, up, rotMat); + Quaternion.FromRotationMatrixToRef(rotMat, ref); + return ref; + } + /** + * Creates a new rotation value to orient an object to look towards the given forward direction, the up direction being oriented like "up". + * This function works in right handed mode + * Example Playground https://playground.babylonjs.com/#L49EJ7#98 + * @param forward defines the forward direction - Must be normalized and orthogonal to up. + * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. + * @returns A new quaternion oriented toward the specified forward and up. + */ + static FromLookDirectionRH(forward, up) { + const quat = new Quaternion(); + Quaternion.FromLookDirectionRHToRef(forward, up, quat); + return quat; + } + /** + * Creates a new rotation value to orient an object to look towards the given forward direction with the up direction being oriented like "up", and stores it in the target quaternion. + * This function works in right handed mode + * Example Playground https://playground.babylonjs.com/#L49EJ7#105 + * @param forward defines the forward direction - Must be normalized and orthogonal to up. + * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. + * @param ref defines the target quaternion. + * @returns result input + */ + static FromLookDirectionRHToRef(forward, up, ref) { + const rotMat = MathTmp.Matrix[0]; + Matrix.LookDirectionRHToRef(forward, up, rotMat); + return Quaternion.FromRotationMatrixToRef(rotMat, ref); + } + /** + * Interpolates between two quaternions + * Example Playground https://playground.babylonjs.com/#L49EJ7#79 + * @param left defines first quaternion + * @param right defines second quaternion + * @param amount defines the gradient to use + * @returns the new interpolated quaternion + */ + static Slerp(left, right, amount) { + const result = Quaternion.Identity(); + Quaternion.SlerpToRef(left, right, amount, result); + return result; + } + /** + * Interpolates between two quaternions and stores it into a target quaternion + * Example Playground https://playground.babylonjs.com/#L49EJ7#92 + * @param left defines first quaternion + * @param right defines second quaternion + * @param amount defines the gradient to use + * @param result defines the target quaternion + * @returns result input + */ + static SlerpToRef(left, right, amount, result) { + let num2; + let num3; + let num4 = left._x * right._x + left._y * right._y + left._z * right._z + left._w * right._w; + let flag = false; + if (num4 < 0) { + flag = true; + num4 = -num4; + } + if (num4 > 0.999999) { + num3 = 1 - amount; + num2 = flag ? -amount : amount; + } + else { + const num5 = Math.acos(num4); + const num6 = 1.0 / Math.sin(num5); + num3 = Math.sin((1.0 - amount) * num5) * num6; + num2 = flag ? -Math.sin(amount * num5) * num6 : Math.sin(amount * num5) * num6; + } + result._x = num3 * left._x + num2 * right._x; + result._y = num3 * left._y + num2 * right._y; + result._z = num3 * left._z + num2 * right._z; + result._w = num3 * left._w + num2 * right._w; + result._isDirty = true; + return result; + } + /** + * Interpolate between two quaternions using Hermite interpolation + * Example Playground https://playground.babylonjs.com/#L49EJ7#47 + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#hermite-quaternion-spline + * @param value1 defines first quaternion + * @param tangent1 defines the incoming tangent + * @param value2 defines second quaternion + * @param tangent2 defines the outgoing tangent + * @param amount defines the target quaternion + * @returns the new interpolated quaternion + */ + static Hermite(value1, tangent1, value2, tangent2, amount) { + const squared = amount * amount; + const cubed = amount * squared; + const part1 = 2.0 * cubed - 3.0 * squared + 1.0; + const part2 = -2 * cubed + 3.0 * squared; + const part3 = cubed - 2.0 * squared + amount; + const part4 = cubed - squared; + const x = value1._x * part1 + value2._x * part2 + tangent1._x * part3 + tangent2._x * part4; + const y = value1._y * part1 + value2._y * part2 + tangent1._y * part3 + tangent2._y * part4; + const z = value1._z * part1 + value2._z * part2 + tangent1._z * part3 + tangent2._z * part4; + const w = value1._w * part1 + value2._w * part2 + tangent1._w * part3 + tangent2._w * part4; + return new Quaternion(x, y, z, w); + } + /** + * Returns a new Quaternion which is the 1st derivative of the Hermite spline defined by the quaternions "value1", "value2", "tangent1", "tangent2". + * Example Playground https://playground.babylonjs.com/#L49EJ7#48 + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @returns 1st derivative + */ + static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { + const result = new Quaternion(); + this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); + return result; + } + /** + * Update a Quaternion with the 1st derivative of the Hermite spline defined by the quaternions "value1", "value2", "tangent1", "tangent2". + * Example Playground https://playground.babylonjs.com/#L49EJ7#49 + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @param result define where to store the derivative + * @returns result input + */ + static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { + const t2 = time * time; + result._x = (t2 - time) * 6 * value1._x + (3 * t2 - 4 * time + 1) * tangent1._x + (-t2 + time) * 6 * value2._x + (3 * t2 - 2 * time) * tangent2._x; + result._y = (t2 - time) * 6 * value1._y + (3 * t2 - 4 * time + 1) * tangent1._y + (-t2 + time) * 6 * value2._y + (3 * t2 - 2 * time) * tangent2._y; + result._z = (t2 - time) * 6 * value1._z + (3 * t2 - 4 * time + 1) * tangent1._z + (-t2 + time) * 6 * value2._z + (3 * t2 - 2 * time) * tangent2._z; + result._w = (t2 - time) * 6 * value1._w + (3 * t2 - 4 * time + 1) * tangent1._w + (-t2 + time) * 6 * value2._w + (3 * t2 - 2 * time) * tangent2._w; + result._isDirty = true; + return result; + } + /** + * Returns a new Quaternion as the normalization of the given Quaternion + * @param quat defines the Quaternion to normalize + * @returns the new Quaternion + */ + static Normalize(quat) { + const result = Quaternion.Zero(); + Quaternion.NormalizeToRef(quat, result); + return result; + } + /** + * Sets the given Quaternion "result" with the normalization of the given first Quaternion + * @param quat defines the Quaternion to normalize + * @param result defines the Quaternion where to store the result + * @returns result input + */ + static NormalizeToRef(quat, result) { + quat.normalizeToRef(result); + return result; + } + /** + * Returns a new Quaternion set with the coordinates of "value", if the quaternion "value" is in the cube defined by the quaternions "min" and "max" + * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one + * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one + * @param value defines the current value + * @param min defines the lower range value + * @param max defines the upper range value + * @returns the new Quaternion + */ + static Clamp(value, min, max) { + const result = new Quaternion(); + Quaternion.ClampToRef(value, min, max, result); + return result; + } + /** + * Sets the given quaternion "result" with the coordinates of "value", if the quaternion "value" is in the cube defined by the quaternions "min" and "max" + * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one + * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one + * @param value defines the current value + * @param min defines the lower range value + * @param max defines the upper range value + * @param result defines the Quaternion where to store the result + * @returns result input + */ + static ClampToRef(value, min, max, result) { + return result.copyFromFloats(Clamp(value.x, min.x, max.x), Clamp(value.y, min.y, max.y), Clamp(value.z, min.z, max.z), Clamp(value.w, min.w, max.w)); + } + /** + * Returns a new Quaternion with random values between min and max + * @param min the minimum random value + * @param max the maximum random value + * @returns a Quaternion with random values between min and max + */ + static Random(min = 0, max = 1) { + return new Quaternion(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max)); + } + /** + * Sets a Quaternion with random values between min and max + * @param min the minimum random value + * @param max the maximum random value + * @param ref the ref to store the values in + * @returns the ref with random values between min and max + */ + static RandomToRef(min = 0, max = 1, ref) { + return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max)); + } + /** + * Do not use + * @internal + */ + static Minimize() { + throw new ReferenceError("Quaternion.Minimize does not make sense"); + } + /** + * Do not use + * @internal + */ + static Maximize() { + throw new ReferenceError("Quaternion.Maximize does not make sense"); + } + /** + * Returns the distance (float) between the quaternions "value1" and "value2". + * @param value1 value to calulate the distance between + * @param value2 value to calulate the distance between + * @returns the distance between the two quaternions + */ + static Distance(value1, value2) { + return Math.sqrt(Quaternion.DistanceSquared(value1, value2)); + } + /** + * Returns the squared distance (float) between the quaternions "value1" and "value2". + * @param value1 value to calulate the distance between + * @param value2 value to calulate the distance between + * @returns the distance between the two quaternions squared + */ + static DistanceSquared(value1, value2) { + const x = value1.x - value2.x; + const y = value1.y - value2.y; + const z = value1.z - value2.z; + const w = value1.w - value2.w; + return x * x + y * y + z * z + w * w; + } + /** + * Returns a new Quaternion located at the center between the quaternions "value1" and "value2". + * @param value1 value to calulate the center between + * @param value2 value to calulate the center between + * @returns the center between the two quaternions + */ + static Center(value1, value2) { + return Quaternion.CenterToRef(value1, value2, Quaternion.Zero()); + } + /** + * Gets the center of the quaternions "value1" and "value2" and stores the result in the quaternion "ref" + * @param value1 defines first quaternion + * @param value2 defines second quaternion + * @param ref defines third quaternion + * @returns ref + */ + static CenterToRef(value1, value2, ref) { + return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2, (value1.z + value2.z) / 2, (value1.w + value2.w) / 2); + } +} +/** + * If the first quaternion is flagged with integers (as everything is 0,0,0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet. + * If subsequent quaternion are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers, + * and henceforth it will use floating-point representation for all quaternion instances that it creates. + * But the original quaternion instances are unchanged and has a "deprecated map". + * If we keep using the quaternion instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches. + */ +Quaternion._V8PerformanceHack = new Quaternion(0.5, 0.5, 0.5, 0.5); +Object.defineProperties(Quaternion.prototype, { + dimension: { value: [4] }, + rank: { value: 1 }, +}); +/** + * Class used to store matrix data (4x4) + * Note on matrix definitions in Babylon.js for setting values directly + * rather than using one of the methods available. + * Matrix size is given by rows x columns. + * A Vector3 is a 1 X 3 matrix [x, y, z]. + * + * In Babylon.js multiplying a 1 x 3 matrix by a 4 x 4 matrix + * is done using BABYLON.Vector4.TransformCoordinates(Vector3, Matrix). + * and extending the passed Vector3 to a Vector4, V = [x, y, z, 1]. + * Let M be a matrix with elements m(row, column), so that + * m(2, 3) is the element in row 2 column 3 of M. + * + * Multiplication is of the form VM and has the resulting Vector4 + * VM = [xm(0, 0) + ym(1, 0) + zm(2, 0) + m(3, 0), xm(0, 1) + ym(1, 1) + zm(2, 1) + m(3, 1), xm(0, 2) + ym(1, 2) + zm(2, 2) + m(3, 2), xm(0, 3) + ym(1, 3) + zm(2, 3) + m(3, 3)]. + * On the web you will find many examples that use the opposite convention of MV, + * in which case to make use of the examples you will need to transpose the matrix. + * + * Example Playground - Overview Linear Algebra - https://playground.babylonjs.com/#AV9X17 + * Example Playground - Overview Transformation - https://playground.babylonjs.com/#AV9X17#1 + * Example Playground - Overview Projection - https://playground.babylonjs.com/#AV9X17#2 + */ +class Matrix { + /** + * Gets the precision of matrix computations + */ + static get Use64Bits() { + return PerformanceConfigurator.MatrixUse64Bits; + } + /** + * Gets the internal data of the matrix + */ + get m() { + return this._m; + } + /** + * Update the updateFlag to indicate that the matrix has been updated + */ + markAsUpdated() { + this.updateFlag = Matrix._UpdateFlagSeed++; + this._isIdentity = false; + this._isIdentity3x2 = false; + this._isIdentityDirty = true; + this._isIdentity3x2Dirty = true; + } + _updateIdentityStatus(isIdentity, isIdentityDirty = false, isIdentity3x2 = false, isIdentity3x2Dirty = true) { + this._isIdentity = isIdentity; + this._isIdentity3x2 = isIdentity || isIdentity3x2; + this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty; + this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty; + } + /** + * Creates an empty matrix (filled with zeros) + */ + constructor() { + this._isIdentity = false; + this._isIdentityDirty = true; + this._isIdentity3x2 = true; + this._isIdentity3x2Dirty = true; + /** + * Gets the update flag of the matrix which is an unique number for the matrix. + * It will be incremented every time the matrix data change. + * You can use it to speed the comparison between two versions of the same matrix. + */ + this.updateFlag = -1; + if (PerformanceConfigurator.MatrixTrackPrecisionChange) { + PerformanceConfigurator.MatrixTrackedMatrices.push(this); + } + this._m = new PerformanceConfigurator.MatrixCurrentType(16); + this.markAsUpdated(); + } + // Properties + /** + * Check if the current matrix is identity + * @returns true is the matrix is the identity matrix + */ + isIdentity() { + if (this._isIdentityDirty) { + this._isIdentityDirty = false; + const m = this._m; + this._isIdentity = + m[0] === 1.0 && + m[1] === 0.0 && + m[2] === 0.0 && + m[3] === 0.0 && + m[4] === 0.0 && + m[5] === 1.0 && + m[6] === 0.0 && + m[7] === 0.0 && + m[8] === 0.0 && + m[9] === 0.0 && + m[10] === 1.0 && + m[11] === 0.0 && + m[12] === 0.0 && + m[13] === 0.0 && + m[14] === 0.0 && + m[15] === 1.0; + } + return this._isIdentity; + } + /** + * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4) + * @returns true is the matrix is the identity matrix + */ + isIdentityAs3x2() { + if (this._isIdentity3x2Dirty) { + this._isIdentity3x2Dirty = false; + if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) { + this._isIdentity3x2 = false; + } + else if (this._m[1] !== 0.0 || + this._m[2] !== 0.0 || + this._m[3] !== 0.0 || + this._m[4] !== 0.0 || + this._m[6] !== 0.0 || + this._m[7] !== 0.0 || + this._m[8] !== 0.0 || + this._m[9] !== 0.0 || + this._m[10] !== 0.0 || + this._m[11] !== 0.0 || + this._m[12] !== 0.0 || + this._m[13] !== 0.0 || + this._m[14] !== 0.0) { + this._isIdentity3x2 = false; + } + else { + this._isIdentity3x2 = true; + } + } + return this._isIdentity3x2; + } + /** + * Gets the determinant of the matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#34 + * @returns the matrix determinant + */ + determinant() { + if (this._isIdentity === true) { + return 1; + } + const m = this._m; + const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3]; + const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7]; + const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11]; + const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15]; + // https://en.wikipedia.org/wiki/Laplace_expansion + // to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column, + // then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant + // Cofactor(i, j) = sign(i,j) * det(Minor(i, j)) + // where + // - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1 + // - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix + // + // Here we do that for the 1st row. + const det_22_33 = m22 * m33 - m32 * m23; + const det_21_33 = m21 * m33 - m31 * m23; + const det_21_32 = m21 * m32 - m31 * m22; + const det_20_33 = m20 * m33 - m30 * m23; + const det_20_32 = m20 * m32 - m22 * m30; + const det_20_31 = m20 * m31 - m30 * m21; + const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32); + const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32); + const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31); + const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31); + return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03; + } + // Methods + /** + * Gets a string with the Matrix values + * @returns a string with the Matrix values + */ + toString() { + return `{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`; + } + toArray(array = null, index = 0) { + if (!array) { + return this._m; + } + const m = this._m; + for (let i = 0; i < 16; i++) { + array[index + i] = m[i]; + } + return this; + } + /** + * Returns the matrix as a Float32Array or Array + * Example Playground - https://playground.babylonjs.com/#AV9X17#114 + * @returns the matrix underlying array. + */ + asArray() { + return this._m; + } + fromArray(array, index = 0) { + return Matrix.FromArrayToRef(array, index, this); + } + copyFromFloats(...floats) { + return Matrix.FromArrayToRef(floats, 0, this); + } + set(...values) { + const m = this._m; + for (let i = 0; i < 16; i++) { + m[i] = values[i]; + } + this.markAsUpdated(); + return this; + } + setAll(value) { + const m = this._m; + for (let i = 0; i < 16; i++) { + m[i] = value; + } + this.markAsUpdated(); + return this; + } + /** + * Inverts the current matrix in place + * Example Playground - https://playground.babylonjs.com/#AV9X17#118 + * @returns the current inverted matrix + */ + invert() { + this.invertToRef(this); + return this; + } + /** + * Sets all the matrix elements to zero + * @returns the current matrix + */ + reset() { + Matrix.FromValuesToRef(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, this); + this._updateIdentityStatus(false); + return this; + } + /** + * Adds the current matrix with a second one + * Example Playground - https://playground.babylonjs.com/#AV9X17#44 + * @param other defines the matrix to add + * @returns a new matrix as the addition of the current matrix and the given one + */ + add(other) { + const result = new Matrix(); + this.addToRef(other, result); + return result; + } + /** + * Sets the given matrix "result" to the addition of the current matrix and the given one + * Example Playground - https://playground.babylonjs.com/#AV9X17#45 + * @param other defines the matrix to add + * @param result defines the target matrix + * @returns result input + */ + addToRef(other, result) { + const m = this._m; + const resultM = result._m; + const otherM = other.m; + for (let index = 0; index < 16; index++) { + resultM[index] = m[index] + otherM[index]; + } + result.markAsUpdated(); + return result; + } + /** + * Adds in place the given matrix to the current matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#46 + * @param other defines the second operand + * @returns the current updated matrix + */ + addToSelf(other) { + const m = this._m; + const otherM = other.m; + m[0] += otherM[0]; + m[1] += otherM[1]; + m[2] += otherM[2]; + m[3] += otherM[3]; + m[4] += otherM[4]; + m[5] += otherM[5]; + m[6] += otherM[6]; + m[7] += otherM[7]; + m[8] += otherM[8]; + m[9] += otherM[9]; + m[10] += otherM[10]; + m[11] += otherM[11]; + m[12] += otherM[12]; + m[13] += otherM[13]; + m[14] += otherM[14]; + m[15] += otherM[15]; + this.markAsUpdated(); + return this; + } + addInPlace(other) { + const m = this._m, otherM = other.m; + for (let i = 0; i < 16; i++) { + m[i] += otherM[i]; + } + this.markAsUpdated(); + return this; + } + addInPlaceFromFloats(...floats) { + const m = this._m; + for (let i = 0; i < 16; i++) { + m[i] += floats[i]; + } + this.markAsUpdated(); + return this; + } + subtract(other) { + const m = this._m, otherM = other.m; + for (let i = 0; i < 16; i++) { + m[i] -= otherM[i]; + } + this.markAsUpdated(); + return this; + } + subtractToRef(other, result) { + const m = this._m, otherM = other.m, resultM = result._m; + for (let i = 0; i < 16; i++) { + resultM[i] = m[i] - otherM[i]; + } + result.markAsUpdated(); + return result; + } + subtractInPlace(other) { + const m = this._m, otherM = other.m; + for (let i = 0; i < 16; i++) { + m[i] -= otherM[i]; + } + this.markAsUpdated(); + return this; + } + subtractFromFloats(...floats) { + return this.subtractFromFloatsToRef(...floats, new Matrix()); + } + subtractFromFloatsToRef(...args) { + const result = args.pop(), m = this._m, resultM = result._m, values = args; + for (let i = 0; i < 16; i++) { + resultM[i] = m[i] - values[i]; + } + result.markAsUpdated(); + return result; + } + /** + * Sets the given matrix to the current inverted Matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#119 + * @param other defines the target matrix + * @returns result input + */ + invertToRef(other) { + if (this._isIdentity === true) { + Matrix.IdentityToRef(other); + return other; + } + // the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant + const m = this._m; + const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3]; + const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7]; + const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11]; + const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15]; + const det_22_33 = m22 * m33 - m32 * m23; + const det_21_33 = m21 * m33 - m31 * m23; + const det_21_32 = m21 * m32 - m31 * m22; + const det_20_33 = m20 * m33 - m30 * m23; + const det_20_32 = m20 * m32 - m22 * m30; + const det_20_31 = m20 * m31 - m30 * m21; + const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32); + const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32); + const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31); + const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31); + const det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03; + if (det === 0) { + // not invertible + other.copyFrom(this); + return other; + } + const detInv = 1 / det; + const det_12_33 = m12 * m33 - m32 * m13; + const det_11_33 = m11 * m33 - m31 * m13; + const det_11_32 = m11 * m32 - m31 * m12; + const det_10_33 = m10 * m33 - m30 * m13; + const det_10_32 = m10 * m32 - m30 * m12; + const det_10_31 = m10 * m31 - m30 * m11; + const det_12_23 = m12 * m23 - m22 * m13; + const det_11_23 = m11 * m23 - m21 * m13; + const det_11_22 = m11 * m22 - m21 * m12; + const det_10_23 = m10 * m23 - m20 * m13; + const det_10_22 = m10 * m22 - m20 * m12; + const det_10_21 = m10 * m21 - m20 * m11; + const cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32); + const cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32); + const cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31); + const cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31); + const cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32); + const cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32); + const cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31); + const cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31); + const cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22); + const cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22); + const cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21); + const cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21); + Matrix.FromValuesToRef(cofact_00 * detInv, cofact_10 * detInv, cofact_20 * detInv, cofact_30 * detInv, cofact_01 * detInv, cofact_11 * detInv, cofact_21 * detInv, cofact_31 * detInv, cofact_02 * detInv, cofact_12 * detInv, cofact_22 * detInv, cofact_32 * detInv, cofact_03 * detInv, cofact_13 * detInv, cofact_23 * detInv, cofact_33 * detInv, other); + return other; + } + /** + * add a value at the specified position in the current Matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#47 + * @param index the index of the value within the matrix. between 0 and 15. + * @param value the value to be added + * @returns the current updated matrix + */ + addAtIndex(index, value) { + this._m[index] += value; + this.markAsUpdated(); + return this; + } + /** + * mutiply the specified position in the current Matrix by a value + * @param index the index of the value within the matrix. between 0 and 15. + * @param value the value to be added + * @returns the current updated matrix + */ + multiplyAtIndex(index, value) { + this._m[index] *= value; + this.markAsUpdated(); + return this; + } + /** + * Inserts the translation vector (using 3 floats) in the current matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#120 + * @param x defines the 1st component of the translation + * @param y defines the 2nd component of the translation + * @param z defines the 3rd component of the translation + * @returns the current updated matrix + */ + setTranslationFromFloats(x, y, z) { + this._m[12] = x; + this._m[13] = y; + this._m[14] = z; + this.markAsUpdated(); + return this; + } + /** + * Adds the translation vector (using 3 floats) in the current matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#20 + * Example Playground - https://playground.babylonjs.com/#AV9X17#48 + * @param x defines the 1st component of the translation + * @param y defines the 2nd component of the translation + * @param z defines the 3rd component of the translation + * @returns the current updated matrix + */ + addTranslationFromFloats(x, y, z) { + this._m[12] += x; + this._m[13] += y; + this._m[14] += z; + this.markAsUpdated(); + return this; + } + /** + * Inserts the translation vector in the current matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#121 + * @param vector3 defines the translation to insert + * @returns the current updated matrix + */ + setTranslation(vector3) { + return this.setTranslationFromFloats(vector3._x, vector3._y, vector3._z); + } + /** + * Gets the translation value of the current matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#122 + * @returns a new Vector3 as the extracted translation from the matrix + */ + getTranslation() { + return new Vector3(this._m[12], this._m[13], this._m[14]); + } + /** + * Fill a Vector3 with the extracted translation from the matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#123 + * @param result defines the Vector3 where to store the translation + * @returns the current matrix + */ + getTranslationToRef(result) { + result.x = this._m[12]; + result.y = this._m[13]; + result.z = this._m[14]; + return result; + } + /** + * Remove rotation and scaling part from the matrix + * @returns the updated matrix + */ + removeRotationAndScaling() { + const m = this.m; + Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, m[12], m[13], m[14], m[15], this); + this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1); + return this; + } + /** + * Copy the current matrix from the given one + * Example Playground - https://playground.babylonjs.com/#AV9X17#21 + * @param other defines the source matrix + * @returns the current updated matrix + */ + copyFrom(other) { + other.copyToArray(this._m); + const o = other; + this.updateFlag = o.updateFlag; + this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty); + return this; + } + /** + * Populates the given array from the starting index with the current matrix values + * @param array defines the target array + * @param offset defines the offset in the target array where to start storing values + * @returns the current matrix + */ + copyToArray(array, offset = 0) { + const source = this._m; + array[offset] = source[0]; + array[offset + 1] = source[1]; + array[offset + 2] = source[2]; + array[offset + 3] = source[3]; + array[offset + 4] = source[4]; + array[offset + 5] = source[5]; + array[offset + 6] = source[6]; + array[offset + 7] = source[7]; + array[offset + 8] = source[8]; + array[offset + 9] = source[9]; + array[offset + 10] = source[10]; + array[offset + 11] = source[11]; + array[offset + 12] = source[12]; + array[offset + 13] = source[13]; + array[offset + 14] = source[14]; + array[offset + 15] = source[15]; + return this; + } + /** + * Multiply two matrices + * Example Playground - https://playground.babylonjs.com/#AV9X17#15 + * A.multiply(B) means apply B to A so result is B x A + * @param other defines the second operand + * @returns a new matrix set with the multiplication result of the current Matrix and the given one + */ + multiply(other) { + const result = new Matrix(); + this.multiplyToRef(other, result); + return result; + } + /** + * This method performs component-by-component in-place multiplication, rather than true matrix multiplication. + * Use multiply or multiplyToRef for matrix multiplication. + * @param other defines the second operand + * @returns the current updated matrix + */ + multiplyInPlace(other) { + const m = this._m, otherM = other.m; + for (let i = 0; i < 16; i++) { + m[i] *= otherM[i]; + } + this.markAsUpdated(); + return this; + } + /** + * This method performs a component-by-component multiplication of the current matrix with the array of transmitted numbers. + * Use multiply or multiplyToRef for matrix multiplication. + * @param floats defines the array of numbers to multiply the matrix by + * @returns the current updated matrix + */ + multiplyByFloats(...floats) { + const m = this._m; + for (let i = 0; i < 16; i++) { + m[i] *= floats[i]; + } + this.markAsUpdated(); + return this; + } + /** + * Multiples the current matrix by the given floats and stores them in the given ref + * @param args The floats and ref + * @returns The updated ref + */ + multiplyByFloatsToRef(...args) { + const result = args.pop(), m = this._m, resultM = result._m, values = args; + for (let i = 0; i < 16; i++) { + resultM[i] = m[i] * values[i]; + } + result.markAsUpdated(); + return result; + } + /** + * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one + * A.multiplyToRef(B, R) means apply B to A and store in R and R = B x A + * Example Playground - https://playground.babylonjs.com/#AV9X17#16 + * @param other defines the second operand + * @param result defines the matrix where to store the multiplication + * @returns result input + */ + multiplyToRef(other, result) { + if (this._isIdentity) { + result.copyFrom(other); + return result; + } + if (other._isIdentity) { + result.copyFrom(this); + return result; + } + this.multiplyToArray(other, result._m, 0); + result.markAsUpdated(); + return result; + } + /** + * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one + * @param other defines the second operand + * @param result defines the array where to store the multiplication + * @param offset defines the offset in the target array where to start storing values + * @returns the current matrix + */ + multiplyToArray(other, result, offset) { + const m = this._m; + const otherM = other.m; + const tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3]; + const tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7]; + const tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11]; + const tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15]; + const om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3]; + const om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7]; + const om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11]; + const om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15]; + result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12; + result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13; + result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14; + result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15; + result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12; + result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13; + result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14; + result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15; + result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12; + result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13; + result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14; + result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15; + result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12; + result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13; + result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14; + result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15; + return this; + } + divide(other) { + return this.divideToRef(other, new Matrix()); + } + divideToRef(other, result) { + const m = this._m, otherM = other.m, resultM = result._m; + for (let i = 0; i < 16; i++) { + resultM[i] = m[i] / otherM[i]; + } + result.markAsUpdated(); + return result; + } + divideInPlace(other) { + const m = this._m, otherM = other.m; + for (let i = 0; i < 16; i++) { + m[i] /= otherM[i]; + } + this.markAsUpdated(); + return this; + } + minimizeInPlace(other) { + const m = this._m, otherM = other.m; + for (let i = 0; i < 16; i++) { + m[i] = Math.min(m[i], otherM[i]); + } + this.markAsUpdated(); + return this; + } + minimizeInPlaceFromFloats(...floats) { + const m = this._m; + for (let i = 0; i < 16; i++) { + m[i] = Math.min(m[i], floats[i]); + } + this.markAsUpdated(); + return this; + } + maximizeInPlace(other) { + const m = this._m, otherM = other.m; + for (let i = 0; i < 16; i++) { + m[i] = Math.min(m[i], otherM[i]); + } + this.markAsUpdated(); + return this; + } + maximizeInPlaceFromFloats(...floats) { + const m = this._m; + for (let i = 0; i < 16; i++) { + m[i] = Math.min(m[i], floats[i]); + } + this.markAsUpdated(); + return this; + } + negate() { + return this.negateToRef(new Matrix()); + } + negateInPlace() { + const m = this._m; + for (let i = 0; i < 16; i++) { + m[i] = -m[i]; + } + this.markAsUpdated(); + return this; + } + negateToRef(result) { + const m = this._m, resultM = result._m; + for (let i = 0; i < 16; i++) { + resultM[i] = -m[i]; + } + result.markAsUpdated(); + return result; + } + /** + * Check equality between this matrix and a second one + * @param value defines the second matrix to compare + * @returns true is the current matrix and the given one values are strictly equal + */ + equals(value) { + const other = value; + if (!other) { + return false; + } + if (this._isIdentity || other._isIdentity) { + if (!this._isIdentityDirty && !other._isIdentityDirty) { + return this._isIdentity && other._isIdentity; + } + } + const m = this.m; + const om = other.m; + return (m[0] === om[0] && + m[1] === om[1] && + m[2] === om[2] && + m[3] === om[3] && + m[4] === om[4] && + m[5] === om[5] && + m[6] === om[6] && + m[7] === om[7] && + m[8] === om[8] && + m[9] === om[9] && + m[10] === om[10] && + m[11] === om[11] && + m[12] === om[12] && + m[13] === om[13] && + m[14] === om[14] && + m[15] === om[15]); + } + equalsWithEpsilon(other, epsilon = 0) { + const m = this._m, otherM = other.m; + for (let i = 0; i < 16; i++) { + if (!WithinEpsilon(m[i], otherM[i], epsilon)) { + return false; + } + } + return true; + } + equalsToFloats(...floats) { + const m = this._m; + for (let i = 0; i < 16; i++) { + if (m[i] != floats[i]) { + return false; + } + } + return true; + } + floor() { + return this.floorToRef(new Matrix()); + } + floorToRef(result) { + const m = this._m, resultM = result._m; + for (let i = 0; i < 16; i++) { + resultM[i] = Math.floor(m[i]); + } + result.markAsUpdated(); + return result; + } + fract() { + return this.fractToRef(new Matrix()); + } + fractToRef(result) { + const m = this._m, resultM = result._m; + for (let i = 0; i < 16; i++) { + resultM[i] = m[i] - Math.floor(m[i]); + } + result.markAsUpdated(); + return result; + } + /** + * Clone the current matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#18 + * @returns a new matrix from the current matrix + */ + clone() { + const matrix = new Matrix(); + matrix.copyFrom(this); + return matrix; + } + /** + * Returns the name of the current matrix class + * @returns the string "Matrix" + */ + getClassName() { + return "Matrix"; + } + /** + * Gets the hash code of the current matrix + * @returns the hash code + */ + getHashCode() { + let hash = _ExtractAsInt(this._m[0]); + for (let i = 1; i < 16; i++) { + hash = (hash * 397) ^ _ExtractAsInt(this._m[i]); + } + return hash; + } + /** + * Decomposes the current Matrix into a translation, rotation and scaling components of the provided node + * Example Playground - https://playground.babylonjs.com/#AV9X17#13 + * @param node the node to decompose the matrix to + * @returns true if operation was successful + */ + decomposeToTransformNode(node) { + node.rotationQuaternion = node.rotationQuaternion || new Quaternion(); + return this.decompose(node.scaling, node.rotationQuaternion, node.position); + } + /** + * Decomposes the current Matrix into a translation, rotation and scaling components + * Example Playground - https://playground.babylonjs.com/#AV9X17#12 + * @param scale defines the scale vector3 given as a reference to update + * @param rotation defines the rotation quaternion given as a reference to update + * @param translation defines the translation vector3 given as a reference to update + * @param preserveScalingNode Use scaling sign coming from this node. Otherwise scaling sign might change. + * @param useAbsoluteScaling Use scaling sign coming from this absoluteScaling when true or scaling otherwise. + * @returns true if operation was successful + */ + decompose(scale, rotation, translation, preserveScalingNode, useAbsoluteScaling = true) { + if (this._isIdentity) { + if (translation) { + translation.setAll(0); + } + if (scale) { + scale.setAll(1); + } + if (rotation) { + rotation.copyFromFloats(0, 0, 0, 1); + } + return true; + } + const m = this._m; + if (translation) { + translation.copyFromFloats(m[12], m[13], m[14]); + } + scale = scale || MathTmp.Vector3[0]; + scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]); + scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]); + scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]); + if (preserveScalingNode) { + const signX = (useAbsoluteScaling ? preserveScalingNode.absoluteScaling.x : preserveScalingNode.scaling.x) < 0 ? -1 : 1; + const signY = (useAbsoluteScaling ? preserveScalingNode.absoluteScaling.y : preserveScalingNode.scaling.y) < 0 ? -1 : 1; + const signZ = (useAbsoluteScaling ? preserveScalingNode.absoluteScaling.z : preserveScalingNode.scaling.z) < 0 ? -1 : 1; + scale.x *= signX; + scale.y *= signY; + scale.z *= signZ; + } + else { + if (this.determinant() <= 0) { + scale.y *= -1; + } + } + if (scale._x === 0 || scale._y === 0 || scale._z === 0) { + if (rotation) { + rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0); + } + return false; + } + if (rotation) { + const sx = 1 / scale._x, sy = 1 / scale._y, sz = 1 / scale._z; + Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, MathTmp.Matrix[0]); + Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation); + } + return true; + } + /** + * Gets specific row of the matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#36 + * @param index defines the number of the row to get + * @returns the index-th row of the current matrix as a new Vector4 + */ + getRow(index) { + if (index < 0 || index > 3) { + return null; + } + const i = index * 4; + return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]); + } + /** + * Gets specific row of the matrix to ref + * Example Playground - https://playground.babylonjs.com/#AV9X17#36 + * @param index defines the number of the row to get + * @param rowVector vector to store the index-th row of the current matrix + * @returns result input + */ + getRowToRef(index, rowVector) { + if (index >= 0 && index <= 3) { + const i = index * 4; + rowVector.x = this._m[i + 0]; + rowVector.y = this._m[i + 1]; + rowVector.z = this._m[i + 2]; + rowVector.w = this._m[i + 3]; + } + return rowVector; + } + /** + * Sets the index-th row of the current matrix to the vector4 values + * Example Playground - https://playground.babylonjs.com/#AV9X17#36 + * @param index defines the number of the row to set + * @param row defines the target vector4 + * @returns the updated current matrix + */ + setRow(index, row) { + return this.setRowFromFloats(index, row.x, row.y, row.z, row.w); + } + /** + * Compute the transpose of the matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#40 + * @returns the new transposed matrix + */ + transpose() { + const result = new Matrix(); + Matrix.TransposeToRef(this, result); + return result; + } + /** + * Compute the transpose of the matrix and store it in a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#41 + * @param result defines the target matrix + * @returns result input + */ + transposeToRef(result) { + Matrix.TransposeToRef(this, result); + return result; + } + /** + * Sets the index-th row of the current matrix with the given 4 x float values + * Example Playground - https://playground.babylonjs.com/#AV9X17#36 + * @param index defines the row index + * @param x defines the x component to set + * @param y defines the y component to set + * @param z defines the z component to set + * @param w defines the w component to set + * @returns the updated current matrix + */ + setRowFromFloats(index, x, y, z, w) { + if (index < 0 || index > 3) { + return this; + } + const i = index * 4; + this._m[i + 0] = x; + this._m[i + 1] = y; + this._m[i + 2] = z; + this._m[i + 3] = w; + this.markAsUpdated(); + return this; + } + /** + * Compute a new matrix set with the current matrix values multiplied by scale (float) + * @param scale defines the scale factor + * @returns a new matrix + */ + scale(scale) { + const result = new Matrix(); + this.scaleToRef(scale, result); + return result; + } + /** + * Scale the current matrix values by a factor to a given result matrix + * @param scale defines the scale factor + * @param result defines the matrix to store the result + * @returns result input + */ + scaleToRef(scale, result) { + for (let index = 0; index < 16; index++) { + result._m[index] = this._m[index] * scale; + } + result.markAsUpdated(); + return result; + } + /** + * Scale the current matrix values by a factor and add the result to a given matrix + * @param scale defines the scale factor + * @param result defines the Matrix to store the result + * @returns result input + */ + scaleAndAddToRef(scale, result) { + for (let index = 0; index < 16; index++) { + result._m[index] += this._m[index] * scale; + } + result.markAsUpdated(); + return result; + } + scaleInPlace(scale) { + const m = this._m; + for (let i = 0; i < 16; i++) { + m[i] *= scale; + } + this.markAsUpdated(); + return this; + } + /** + * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column). + * Example Playground - https://playground.babylonjs.com/#AV9X17#17 + * @param ref matrix to store the result + * @returns the reference matrix + */ + toNormalMatrix(ref) { + const tmp = MathTmp.Matrix[0]; + this.invertToRef(tmp); + tmp.transposeToRef(ref); + const m = ref._m; + Matrix.FromValuesToRef(m[0], m[1], m[2], 0.0, m[4], m[5], m[6], 0.0, m[8], m[9], m[10], 0.0, 0.0, 0.0, 0.0, 1.0, ref); + return ref; + } + /** + * Gets only rotation part of the current matrix + * @returns a new matrix sets to the extracted rotation matrix from the current one + */ + getRotationMatrix() { + const result = new Matrix(); + this.getRotationMatrixToRef(result); + return result; + } + /** + * Extracts the rotation matrix from the current one and sets it as the given "result" + * @param result defines the target matrix to store data to + * @returns result input + */ + getRotationMatrixToRef(result) { + const scale = MathTmp.Vector3[0]; + if (!this.decompose(scale)) { + Matrix.IdentityToRef(result); + return result; + } + const m = this._m; + const sx = 1 / scale._x, sy = 1 / scale._y, sz = 1 / scale._z; + Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, result); + return result; + } + /** + * Toggles model matrix from being right handed to left handed in place and vice versa + * @returns the current updated matrix + */ + toggleModelMatrixHandInPlace() { + const m = this._m; + m[2] *= -1; + m[6] *= -1; + m[8] *= -1; + m[9] *= -1; + m[14] *= -1; + this.markAsUpdated(); + return this; + } + /** + * Toggles projection matrix from being right handed to left handed in place and vice versa + * @returns the current updated matrix + */ + toggleProjectionMatrixHandInPlace() { + const m = this._m; + m[8] *= -1; + m[9] *= -1; + m[10] *= -1; + m[11] *= -1; + this.markAsUpdated(); + return this; + } + // Statics + /** + * Creates a matrix from an array + * Example Playground - https://playground.babylonjs.com/#AV9X17#42 + * @param array defines the source array + * @param offset defines an offset in the source array + * @returns a new Matrix set from the starting index of the given array + */ + static FromArray(array, offset = 0) { + const result = new Matrix(); + Matrix.FromArrayToRef(array, offset, result); + return result; + } + /** + * Copy the content of an array into a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#43 + * @param array defines the source array + * @param offset defines an offset in the source array + * @param result defines the target matrix + * @returns result input + */ + static FromArrayToRef(array, offset, result) { + for (let index = 0; index < 16; index++) { + result._m[index] = array[index + offset]; + } + result.markAsUpdated(); + return result; + } + /** + * Stores an array into a matrix after having multiplied each component by a given factor + * Example Playground - https://playground.babylonjs.com/#AV9X17#50 + * @param array defines the source array + * @param offset defines the offset in the source array + * @param scale defines the scaling factor + * @param result defines the target matrix + * @returns result input + */ + static FromFloat32ArrayToRefScaled(array, offset, scale, result) { + result._m[0] = array[0 + offset] * scale; + result._m[1] = array[1 + offset] * scale; + result._m[2] = array[2 + offset] * scale; + result._m[3] = array[3 + offset] * scale; + result._m[4] = array[4 + offset] * scale; + result._m[5] = array[5 + offset] * scale; + result._m[6] = array[6 + offset] * scale; + result._m[7] = array[7 + offset] * scale; + result._m[8] = array[8 + offset] * scale; + result._m[9] = array[9 + offset] * scale; + result._m[10] = array[10 + offset] * scale; + result._m[11] = array[11 + offset] * scale; + result._m[12] = array[12 + offset] * scale; + result._m[13] = array[13 + offset] * scale; + result._m[14] = array[14 + offset] * scale; + result._m[15] = array[15 + offset] * scale; + result.markAsUpdated(); + return result; + } + /** + * Gets an identity matrix that must not be updated + */ + static get IdentityReadOnly() { + return Matrix._IdentityReadOnly; + } + /** + * Stores a list of values (16) inside a given matrix + * @param initialM11 defines 1st value of 1st row + * @param initialM12 defines 2nd value of 1st row + * @param initialM13 defines 3rd value of 1st row + * @param initialM14 defines 4th value of 1st row + * @param initialM21 defines 1st value of 2nd row + * @param initialM22 defines 2nd value of 2nd row + * @param initialM23 defines 3rd value of 2nd row + * @param initialM24 defines 4th value of 2nd row + * @param initialM31 defines 1st value of 3rd row + * @param initialM32 defines 2nd value of 3rd row + * @param initialM33 defines 3rd value of 3rd row + * @param initialM34 defines 4th value of 3rd row + * @param initialM41 defines 1st value of 4th row + * @param initialM42 defines 2nd value of 4th row + * @param initialM43 defines 3rd value of 4th row + * @param initialM44 defines 4th value of 4th row + * @param result defines the target matrix + */ + static FromValuesToRef(initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) { + const m = result._m; + m[0] = initialM11; + m[1] = initialM12; + m[2] = initialM13; + m[3] = initialM14; + m[4] = initialM21; + m[5] = initialM22; + m[6] = initialM23; + m[7] = initialM24; + m[8] = initialM31; + m[9] = initialM32; + m[10] = initialM33; + m[11] = initialM34; + m[12] = initialM41; + m[13] = initialM42; + m[14] = initialM43; + m[15] = initialM44; + result.markAsUpdated(); + } + /** + * Creates new matrix from a list of values (16) + * @param initialM11 defines 1st value of 1st row + * @param initialM12 defines 2nd value of 1st row + * @param initialM13 defines 3rd value of 1st row + * @param initialM14 defines 4th value of 1st row + * @param initialM21 defines 1st value of 2nd row + * @param initialM22 defines 2nd value of 2nd row + * @param initialM23 defines 3rd value of 2nd row + * @param initialM24 defines 4th value of 2nd row + * @param initialM31 defines 1st value of 3rd row + * @param initialM32 defines 2nd value of 3rd row + * @param initialM33 defines 3rd value of 3rd row + * @param initialM34 defines 4th value of 3rd row + * @param initialM41 defines 1st value of 4th row + * @param initialM42 defines 2nd value of 4th row + * @param initialM43 defines 3rd value of 4th row + * @param initialM44 defines 4th value of 4th row + * @returns the new matrix + */ + static FromValues(initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) { + const result = new Matrix(); + const m = result._m; + m[0] = initialM11; + m[1] = initialM12; + m[2] = initialM13; + m[3] = initialM14; + m[4] = initialM21; + m[5] = initialM22; + m[6] = initialM23; + m[7] = initialM24; + m[8] = initialM31; + m[9] = initialM32; + m[10] = initialM33; + m[11] = initialM34; + m[12] = initialM41; + m[13] = initialM42; + m[14] = initialM43; + m[15] = initialM44; + result.markAsUpdated(); + return result; + } + /** + * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3) + * Example Playground - https://playground.babylonjs.com/#AV9X17#24 + * @param scale defines the scale vector3 + * @param rotation defines the rotation quaternion + * @param translation defines the translation vector3 + * @returns a new matrix + */ + static Compose(scale, rotation, translation) { + const result = new Matrix(); + Matrix.ComposeToRef(scale, rotation, translation, result); + return result; + } + /** + * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3) + * Example Playground - https://playground.babylonjs.com/#AV9X17#25 + * @param scale defines the scale vector3 + * @param rotation defines the rotation quaternion + * @param translation defines the translation vector3 + * @param result defines the target matrix + * @returns result input + */ + static ComposeToRef(scale, rotation, translation, result) { + const m = result._m; + const x = rotation._x, y = rotation._y, z = rotation._z, w = rotation._w; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + const sx = scale._x, sy = scale._y, sz = scale._z; + m[0] = (1 - (yy + zz)) * sx; + m[1] = (xy + wz) * sx; + m[2] = (xz - wy) * sx; + m[3] = 0; + m[4] = (xy - wz) * sy; + m[5] = (1 - (xx + zz)) * sy; + m[6] = (yz + wx) * sy; + m[7] = 0; + m[8] = (xz + wy) * sz; + m[9] = (yz - wx) * sz; + m[10] = (1 - (xx + yy)) * sz; + m[11] = 0; + m[12] = translation._x; + m[13] = translation._y; + m[14] = translation._z; + m[15] = 1; + result.markAsUpdated(); + return result; + } + /** + * Creates a new identity matrix + * @returns a new identity matrix + */ + static Identity() { + const identity = Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); + identity._updateIdentityStatus(true); + return identity; + } + /** + * Creates a new identity matrix and stores the result in a given matrix + * @param result defines the target matrix + * @returns result input + */ + static IdentityToRef(result) { + Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result); + result._updateIdentityStatus(true); + return result; + } + /** + * Creates a new zero matrix + * @returns a new zero matrix + */ + static Zero() { + const zero = Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); + zero._updateIdentityStatus(false); + return zero; + } + /** + * Creates a new rotation matrix for "angle" radians around the X axis + * Example Playground - https://playground.babylonjs.com/#AV9X17#97 + * @param angle defines the angle (in radians) to use + * @returns the new matrix + */ + static RotationX(angle) { + const result = new Matrix(); + Matrix.RotationXToRef(angle, result); + return result; + } + /** + * Creates a new matrix as the invert of a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#124 + * @param source defines the source matrix + * @returns the new matrix + */ + static Invert(source) { + const result = new Matrix(); + source.invertToRef(result); + return result; + } + /** + * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#98 + * @param angle defines the angle (in radians) to use + * @param result defines the target matrix + * @returns result input + */ + static RotationXToRef(angle, result) { + const s = Math.sin(angle); + const c = Math.cos(angle); + Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, result); + result._updateIdentityStatus(c === 1 && s === 0); + return result; + } + /** + * Creates a new rotation matrix for "angle" radians around the Y axis + * Example Playground - https://playground.babylonjs.com/#AV9X17#99 + * @param angle defines the angle (in radians) to use + * @returns the new matrix + */ + static RotationY(angle) { + const result = new Matrix(); + Matrix.RotationYToRef(angle, result); + return result; + } + /** + * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#100 + * @param angle defines the angle (in radians) to use + * @param result defines the target matrix + * @returns result input + */ + static RotationYToRef(angle, result) { + const s = Math.sin(angle); + const c = Math.cos(angle); + Matrix.FromValuesToRef(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0, result); + result._updateIdentityStatus(c === 1 && s === 0); + return result; + } + /** + * Creates a new rotation matrix for "angle" radians around the Z axis + * Example Playground - https://playground.babylonjs.com/#AV9X17#101 + * @param angle defines the angle (in radians) to use + * @returns the new matrix + */ + static RotationZ(angle) { + const result = new Matrix(); + Matrix.RotationZToRef(angle, result); + return result; + } + /** + * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#102 + * @param angle defines the angle (in radians) to use + * @param result defines the target matrix + * @returns result input + */ + static RotationZToRef(angle, result) { + const s = Math.sin(angle); + const c = Math.cos(angle); + Matrix.FromValuesToRef(c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result); + result._updateIdentityStatus(c === 1 && s === 0); + return result; + } + /** + * Creates a new rotation matrix for "angle" radians around the given axis + * Example Playground - https://playground.babylonjs.com/#AV9X17#96 + * @param axis defines the axis to use + * @param angle defines the angle (in radians) to use + * @returns the new matrix + */ + static RotationAxis(axis, angle) { + const result = new Matrix(); + Matrix.RotationAxisToRef(axis, angle, result); + return result; + } + /** + * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#94 + * @param axis defines the axis to use + * @param angle defines the angle (in radians) to use + * @param result defines the target matrix + * @returns result input + */ + static RotationAxisToRef(axis, angle, result) { + const s = Math.sin(-angle); + const c = Math.cos(-angle); + const c1 = 1 - c; + axis = axis.normalizeToRef(MathTmp.Vector3[0]); + const m = result._m; + m[0] = axis._x * axis._x * c1 + c; + m[1] = axis._x * axis._y * c1 - axis._z * s; + m[2] = axis._x * axis._z * c1 + axis._y * s; + m[3] = 0.0; + m[4] = axis._y * axis._x * c1 + axis._z * s; + m[5] = axis._y * axis._y * c1 + c; + m[6] = axis._y * axis._z * c1 - axis._x * s; + m[7] = 0.0; + m[8] = axis._z * axis._x * c1 - axis._y * s; + m[9] = axis._z * axis._y * c1 + axis._x * s; + m[10] = axis._z * axis._z * c1 + c; + m[11] = 0.0; + m[12] = 0.0; + m[13] = 0.0; + m[14] = 0.0; + m[15] = 1.0; + result.markAsUpdated(); + return result; + } + /** + * Takes normalised vectors and returns a rotation matrix to align "from" with "to". + * Taken from http://www.iquilezles.org/www/articles/noacos/noacos.htm + * Example Playground - https://playground.babylonjs.com/#AV9X17#93 + * @param from defines the vector to align + * @param to defines the vector to align to + * @param result defines the target matrix + * @param useYAxisForCoplanar defines a boolean indicating that we should favor Y axis for coplanar vectors (default is false) + * @returns result input + */ + static RotationAlignToRef(from, to, result, useYAxisForCoplanar = false) { + const c = Vector3.Dot(to, from); + const m = result._m; + if (c < -1 + Epsilon) { + // from and to are colinear and opposite direction. + // compute a PI rotation on Y axis + m[0] = -1; + m[1] = 0; + m[2] = 0; + m[3] = 0; + m[4] = 0; + m[5] = useYAxisForCoplanar ? 1 : -1; + m[6] = 0; + m[7] = 0; + m[8] = 0; + m[9] = 0; + m[10] = useYAxisForCoplanar ? -1 : 1; + m[11] = 0; + } + else { + const v = Vector3.Cross(to, from); + const k = 1 / (1 + c); + m[0] = v._x * v._x * k + c; + m[1] = v._y * v._x * k - v._z; + m[2] = v._z * v._x * k + v._y; + m[3] = 0; + m[4] = v._x * v._y * k + v._z; + m[5] = v._y * v._y * k + c; + m[6] = v._z * v._y * k - v._x; + m[7] = 0; + m[8] = v._x * v._z * k - v._y; + m[9] = v._y * v._z * k + v._x; + m[10] = v._z * v._z * k + c; + m[11] = 0; + } + m[12] = 0; + m[13] = 0; + m[14] = 0; + m[15] = 1; + result.markAsUpdated(); + return result; + } + /** + * Creates a rotation matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#103 + * Example Playground - https://playground.babylonjs.com/#AV9X17#105 + * @param yaw defines the yaw angle in radians (Y axis) + * @param pitch defines the pitch angle in radians (X axis) + * @param roll defines the roll angle in radians (Z axis) + * @returns the new rotation matrix + */ + static RotationYawPitchRoll(yaw, pitch, roll) { + const result = new Matrix(); + Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result); + return result; + } + /** + * Creates a rotation matrix and stores it in a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#104 + * @param yaw defines the yaw angle in radians (Y axis) + * @param pitch defines the pitch angle in radians (X axis) + * @param roll defines the roll angle in radians (Z axis) + * @param result defines the target matrix + * @returns result input + */ + static RotationYawPitchRollToRef(yaw, pitch, roll, result) { + Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]); + MathTmp.Quaternion[0].toRotationMatrix(result); + return result; + } + /** + * Creates a scaling matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#107 + * @param x defines the scale factor on X axis + * @param y defines the scale factor on Y axis + * @param z defines the scale factor on Z axis + * @returns the new matrix + */ + static Scaling(x, y, z) { + const result = new Matrix(); + Matrix.ScalingToRef(x, y, z, result); + return result; + } + /** + * Creates a scaling matrix and stores it in a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#108 + * @param x defines the scale factor on X axis + * @param y defines the scale factor on Y axis + * @param z defines the scale factor on Z axis + * @param result defines the target matrix + * @returns result input + */ + static ScalingToRef(x, y, z, result) { + Matrix.FromValuesToRef(x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0, result); + result._updateIdentityStatus(x === 1 && y === 1 && z === 1); + return result; + } + /** + * Creates a translation matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#109 + * @param x defines the translation on X axis + * @param y defines the translation on Y axis + * @param z defines the translationon Z axis + * @returns the new matrix + */ + static Translation(x, y, z) { + const result = new Matrix(); + Matrix.TranslationToRef(x, y, z, result); + return result; + } + /** + * Creates a translation matrix and stores it in a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#110 + * @param x defines the translation on X axis + * @param y defines the translation on Y axis + * @param z defines the translationon Z axis + * @param result defines the target matrix + * @returns result input + */ + static TranslationToRef(x, y, z, result) { + Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result); + result._updateIdentityStatus(x === 0 && y === 0 && z === 0); + return result; + } + /** + * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue". + * Example Playground - https://playground.babylonjs.com/#AV9X17#55 + * @param startValue defines the start value + * @param endValue defines the end value + * @param gradient defines the gradient factor + * @returns the new matrix + */ + static Lerp(startValue, endValue, gradient) { + const result = new Matrix(); + Matrix.LerpToRef(startValue, endValue, gradient, result); + return result; + } + /** + * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue". + * Example Playground - https://playground.babylonjs.com/#AV9X17#54 + * @param startValue defines the start value + * @param endValue defines the end value + * @param gradient defines the gradient factor + * @param result defines the Matrix object where to store data + * @returns result input + */ + static LerpToRef(startValue, endValue, gradient, result) { + const resultM = result._m; + const startM = startValue.m; + const endM = endValue.m; + for (let index = 0; index < 16; index++) { + resultM[index] = startM[index] * (1.0 - gradient) + endM[index] * gradient; + } + result.markAsUpdated(); + return result; + } + /** + * Builds a new matrix whose values are computed by: + * * decomposing the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices + * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end + * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices + * Example Playground - https://playground.babylonjs.com/#AV9X17#22 + * Example Playground - https://playground.babylonjs.com/#AV9X17#51 + * @param startValue defines the first matrix + * @param endValue defines the second matrix + * @param gradient defines the gradient between the two matrices + * @returns the new matrix + */ + static DecomposeLerp(startValue, endValue, gradient) { + const result = new Matrix(); + Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result); + return result; + } + /** + * Update a matrix to values which are computed by: + * * decomposing the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices + * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end + * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices + * Example Playground - https://playground.babylonjs.com/#AV9X17#23 + * Example Playground - https://playground.babylonjs.com/#AV9X17#53 + * @param startValue defines the first matrix + * @param endValue defines the second matrix + * @param gradient defines the gradient between the two matrices + * @param result defines the target matrix + * @returns result input + */ + static DecomposeLerpToRef(startValue, endValue, gradient, result) { + const startScale = MathTmp.Vector3[0]; + const startRotation = MathTmp.Quaternion[0]; + const startTranslation = MathTmp.Vector3[1]; + startValue.decompose(startScale, startRotation, startTranslation); + const endScale = MathTmp.Vector3[2]; + const endRotation = MathTmp.Quaternion[1]; + const endTranslation = MathTmp.Vector3[3]; + endValue.decompose(endScale, endRotation, endTranslation); + const resultScale = MathTmp.Vector3[4]; + Vector3.LerpToRef(startScale, endScale, gradient, resultScale); + const resultRotation = MathTmp.Quaternion[2]; + Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation); + const resultTranslation = MathTmp.Vector3[5]; + Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation); + Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result); + return result; + } + /** + * Creates a new matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. + * This function generates a matrix suitable for a left handed coordinate system + * Example Playground - https://playground.babylonjs.com/#AV9X17#58 + * Example Playground - https://playground.babylonjs.com/#AV9X17#59 + * @param eye defines the final position of the entity + * @param target defines where the entity should look at + * @param up defines the up vector for the entity + * @returns the new matrix + */ + static LookAtLH(eye, target, up) { + const result = new Matrix(); + Matrix.LookAtLHToRef(eye, target, up, result); + return result; + } + /** + * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. + * This function generates a matrix suitable for a left handed coordinate system + * Example Playground - https://playground.babylonjs.com/#AV9X17#60 + * Example Playground - https://playground.babylonjs.com/#AV9X17#61 + * @param eye defines the final position of the entity + * @param target defines where the entity should look at + * @param up defines the up vector for the entity + * @param result defines the target matrix + * @returns result input + */ + static LookAtLHToRef(eye, target, up, result) { + const xAxis = MathTmp.Vector3[0]; + const yAxis = MathTmp.Vector3[1]; + const zAxis = MathTmp.Vector3[2]; + // Z axis + target.subtractToRef(eye, zAxis); + zAxis.normalize(); + // X axis + Vector3.CrossToRef(up, zAxis, xAxis); + const xSquareLength = xAxis.lengthSquared(); + if (xSquareLength === 0) { + xAxis.x = 1.0; + } + else { + xAxis.normalizeFromLength(Math.sqrt(xSquareLength)); + } + // Y axis + Vector3.CrossToRef(zAxis, xAxis, yAxis); + yAxis.normalize(); + // Eye angles + const ex = -Vector3.Dot(xAxis, eye); + const ey = -Vector3.Dot(yAxis, eye); + const ez = -Vector3.Dot(zAxis, eye); + Matrix.FromValuesToRef(xAxis._x, yAxis._x, zAxis._x, 0.0, xAxis._y, yAxis._y, zAxis._y, 0.0, xAxis._z, yAxis._z, zAxis._z, 0.0, ex, ey, ez, 1.0, result); + return result; + } + /** + * Creates a new matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. + * This function generates a matrix suitable for a right handed coordinate system + * Example Playground - https://playground.babylonjs.com/#AV9X17#62 + * Example Playground - https://playground.babylonjs.com/#AV9X17#63 + * @param eye defines the final position of the entity + * @param target defines where the entity should look at + * @param up defines the up vector for the entity + * @returns the new matrix + */ + static LookAtRH(eye, target, up) { + const result = new Matrix(); + Matrix.LookAtRHToRef(eye, target, up, result); + return result; + } + /** + * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. + * This function generates a matrix suitable for a right handed coordinate system + * Example Playground - https://playground.babylonjs.com/#AV9X17#64 + * Example Playground - https://playground.babylonjs.com/#AV9X17#65 + * @param eye defines the final position of the entity + * @param target defines where the entity should look at + * @param up defines the up vector for the entity + * @param result defines the target matrix + * @returns result input + */ + static LookAtRHToRef(eye, target, up, result) { + const xAxis = MathTmp.Vector3[0]; + const yAxis = MathTmp.Vector3[1]; + const zAxis = MathTmp.Vector3[2]; + // Z axis + eye.subtractToRef(target, zAxis); + zAxis.normalize(); + // X axis + Vector3.CrossToRef(up, zAxis, xAxis); + const xSquareLength = xAxis.lengthSquared(); + if (xSquareLength === 0) { + xAxis.x = 1.0; + } + else { + xAxis.normalizeFromLength(Math.sqrt(xSquareLength)); + } + // Y axis + Vector3.CrossToRef(zAxis, xAxis, yAxis); + yAxis.normalize(); + // Eye angles + const ex = -Vector3.Dot(xAxis, eye); + const ey = -Vector3.Dot(yAxis, eye); + const ez = -Vector3.Dot(zAxis, eye); + Matrix.FromValuesToRef(xAxis._x, yAxis._x, zAxis._x, 0.0, xAxis._y, yAxis._y, zAxis._y, 0.0, xAxis._z, yAxis._z, zAxis._z, 0.0, ex, ey, ez, 1.0, result); + return result; + } + /** + * Creates a new matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) + * This function generates a matrix suitable for a left handed coordinate system + * Example Playground - https://playground.babylonjs.com/#AV9X17#66 + * @param forward defines the forward direction - Must be normalized and orthogonal to up. + * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. + * @returns the new matrix + */ + static LookDirectionLH(forward, up) { + const result = new Matrix(); + Matrix.LookDirectionLHToRef(forward, up, result); + return result; + } + /** + * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) + * This function generates a matrix suitable for a left handed coordinate system + * Example Playground - https://playground.babylonjs.com/#AV9X17#67 + * @param forward defines the forward direction - Must be normalized and orthogonal to up. + * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. + * @param result defines the target matrix + * @returns result input + */ + static LookDirectionLHToRef(forward, up, result) { + const back = MathTmp.Vector3[0]; + back.copyFrom(forward); + back.scaleInPlace(-1); + const left = MathTmp.Vector3[1]; + Vector3.CrossToRef(up, back, left); + // Generate the rotation matrix. + Matrix.FromValuesToRef(left._x, left._y, left._z, 0.0, up._x, up._y, up._z, 0.0, back._x, back._y, back._z, 0.0, 0, 0, 0, 1.0, result); + return result; + } + /** + * Creates a new matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) + * This function generates a matrix suitable for a right handed coordinate system + * Example Playground - https://playground.babylonjs.com/#AV9X17#68 + * @param forward defines the forward direction - Must be normalized and orthogonal to up. + * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. + * @returns the new matrix + */ + static LookDirectionRH(forward, up) { + const result = new Matrix(); + Matrix.LookDirectionRHToRef(forward, up, result); + return result; + } + /** + * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) + * This function generates a matrix suitable for a right handed coordinate system + * Example Playground - https://playground.babylonjs.com/#AV9X17#69 + * @param forward defines the forward direction - Must be normalized and orthogonal to up. + * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. + * @param result defines the target matrix + * @returns result input + */ + static LookDirectionRHToRef(forward, up, result) { + const right = MathTmp.Vector3[2]; + Vector3.CrossToRef(up, forward, right); + // Generate the rotation matrix. + Matrix.FromValuesToRef(right._x, right._y, right._z, 0.0, up._x, up._y, up._z, 0.0, forward._x, forward._y, forward._z, 0.0, 0, 0, 0, 1.0, result); + return result; + } + /** + * Create a left-handed orthographic projection matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#70 + * @param width defines the viewport width + * @param height defines the viewport height + * @param znear defines the near clip plane + * @param zfar defines the far clip plane + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @returns a new matrix as a left-handed orthographic projection matrix + */ + static OrthoLH(width, height, znear, zfar, halfZRange) { + const matrix = new Matrix(); + Matrix.OrthoLHToRef(width, height, znear, zfar, matrix, halfZRange); + return matrix; + } + /** + * Store a left-handed orthographic projection to a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#71 + * @param width defines the viewport width + * @param height defines the viewport height + * @param znear defines the near clip plane + * @param zfar defines the far clip plane + * @param result defines the target matrix + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @returns result input + */ + static OrthoLHToRef(width, height, znear, zfar, result, halfZRange) { + const n = znear; + const f = zfar; + const a = 2.0 / width; + const b = 2.0 / height; + const c = 2.0 / (f - n); + const d = -(f + n) / (f - n); + Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result); + if (halfZRange) { + result.multiplyToRef(mtxConvertNDCToHalfZRange, result); + } + result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0); + return result; + } + /** + * Create a left-handed orthographic projection matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#72 + * @param left defines the viewport left coordinate + * @param right defines the viewport right coordinate + * @param bottom defines the viewport bottom coordinate + * @param top defines the viewport top coordinate + * @param znear defines the near clip plane + * @param zfar defines the far clip plane + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @returns a new matrix as a left-handed orthographic projection matrix + */ + static OrthoOffCenterLH(left, right, bottom, top, znear, zfar, halfZRange) { + const matrix = new Matrix(); + Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix, halfZRange); + return matrix; + } + /** + * Stores a left-handed orthographic projection into a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#73 + * @param left defines the viewport left coordinate + * @param right defines the viewport right coordinate + * @param bottom defines the viewport bottom coordinate + * @param top defines the viewport top coordinate + * @param znear defines the near clip plane + * @param zfar defines the far clip plane + * @param result defines the target matrix + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @returns result input + */ + static OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange) { + const n = znear; + const f = zfar; + const a = 2.0 / (right - left); + const b = 2.0 / (top - bottom); + const c = 2.0 / (f - n); + const d = -(f + n) / (f - n); + const i0 = (left + right) / (left - right); + const i1 = (top + bottom) / (bottom - top); + Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result); + if (halfZRange) { + result.multiplyToRef(mtxConvertNDCToHalfZRange, result); + } + result.markAsUpdated(); + return result; + } + /** + * Stores a left-handed oblique projection into a given matrix + * @param left defines the viewport left coordinate + * @param right defines the viewport right coordinate + * @param bottom defines the viewport bottom coordinate + * @param top defines the viewport top coordinate + * @param znear defines the near clip plane + * @param zfar defines the far clip plane + * @param length Length of the shear + * @param angle Angle (along X/Y Plane) to apply shear + * @param distance Distance from shear point + * @param result defines the target matrix + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @returns result input + */ + static ObliqueOffCenterLHToRef(left, right, bottom, top, znear, zfar, length, angle, distance, result, halfZRange) { + const a = -length * Math.cos(angle); + const b = -length * Math.sin(angle); + Matrix.TranslationToRef(0, 0, -distance, MathTmp.Matrix[1]); + Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, a, b, 1, 0, 0, 0, 0, 1, MathTmp.Matrix[0]); + MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], MathTmp.Matrix[0]); + Matrix.TranslationToRef(0, 0, distance, MathTmp.Matrix[1]); + MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1], MathTmp.Matrix[0]); + Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange); + MathTmp.Matrix[0].multiplyToRef(result, result); + return result; + } + /** + * Creates a right-handed orthographic projection matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#76 + * @param left defines the viewport left coordinate + * @param right defines the viewport right coordinate + * @param bottom defines the viewport bottom coordinate + * @param top defines the viewport top coordinate + * @param znear defines the near clip plane + * @param zfar defines the far clip plane + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @returns a new matrix as a right-handed orthographic projection matrix + */ + static OrthoOffCenterRH(left, right, bottom, top, znear, zfar, halfZRange) { + const matrix = new Matrix(); + Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix, halfZRange); + return matrix; + } + /** + * Stores a right-handed orthographic projection into a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#77 + * @param left defines the viewport left coordinate + * @param right defines the viewport right coordinate + * @param bottom defines the viewport bottom coordinate + * @param top defines the viewport top coordinate + * @param znear defines the near clip plane + * @param zfar defines the far clip plane + * @param result defines the target matrix + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @returns result input + */ + static OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, result, halfZRange) { + Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange); + result._m[10] *= -1; // No need to call markAsUpdated as previous function already called it and let _isIdentityDirty to true + return result; + } + /** + * Stores a right-handed oblique projection into a given matrix + * @param left defines the viewport left coordinate + * @param right defines the viewport right coordinate + * @param bottom defines the viewport bottom coordinate + * @param top defines the viewport top coordinate + * @param znear defines the near clip plane + * @param zfar defines the far clip plane + * @param length Length of the shear + * @param angle Angle (along X/Y Plane) to apply shear + * @param distance Distance from shear point + * @param result defines the target matrix + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @returns result input + */ + static ObliqueOffCenterRHToRef(left, right, bottom, top, znear, zfar, length, angle, distance, result, halfZRange) { + const a = length * Math.cos(angle); + const b = length * Math.sin(angle); + Matrix.TranslationToRef(0, 0, distance, MathTmp.Matrix[1]); + Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, a, b, 1, 0, 0, 0, 0, 1, MathTmp.Matrix[0]); + MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], MathTmp.Matrix[0]); + Matrix.TranslationToRef(0, 0, -distance, MathTmp.Matrix[1]); + MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1], MathTmp.Matrix[0]); + Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, result, halfZRange); + MathTmp.Matrix[0].multiplyToRef(result, result); + return result; + } + /** + * Creates a left-handed perspective projection matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#85 + * @param width defines the viewport width + * @param height defines the viewport height + * @param znear defines the near clip plane + * @param zfar defines the far clip plane + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) + * @returns a new matrix as a left-handed perspective projection matrix + */ + static PerspectiveLH(width, height, znear, zfar, halfZRange, projectionPlaneTilt = 0) { + const matrix = new Matrix(); + const n = znear; + const f = zfar; + const a = (2.0 * n) / width; + const b = (2.0 * n) / height; + const c = (f + n) / (f - n); + const d = (-2 * f * n) / (f - n); + const rot = Math.tan(projectionPlaneTilt); + Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix); + if (halfZRange) { + matrix.multiplyToRef(mtxConvertNDCToHalfZRange, matrix); + } + matrix._updateIdentityStatus(false); + return matrix; + } + /** + * Creates a left-handed perspective projection matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#78 + * @param fov defines the horizontal field of view + * @param aspect defines the aspect ratio + * @param znear defines the near clip plane + * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) + * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) + * @returns a new matrix as a left-handed perspective projection matrix + */ + static PerspectiveFovLH(fov, aspect, znear, zfar, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { + const matrix = new Matrix(); + Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix, true, halfZRange, projectionPlaneTilt, reverseDepthBufferMode); + return matrix; + } + /** + * Stores a left-handed perspective projection into a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#81 + * @param fov defines the horizontal field of view + * @param aspect defines the aspect ratio + * @param znear defines the near clip plane + * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode + * @param result defines the target matrix + * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) + * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) + * @returns result input + */ + static PerspectiveFovLHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { + const n = znear; + const f = zfar; + const t = 1.0 / Math.tan(fov * 0.5); + const a = isVerticalFovFixed ? t / aspect : t; + const b = isVerticalFovFixed ? t : t * aspect; + const c = reverseDepthBufferMode && n === 0 ? -1 : f !== 0 ? (f + n) / (f - n) : 1; + const d = reverseDepthBufferMode && n === 0 ? 2 * f : f !== 0 ? (-2 * f * n) / (f - n) : -2 * n; + const rot = Math.tan(projectionPlaneTilt); + Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result); + if (halfZRange) { + result.multiplyToRef(mtxConvertNDCToHalfZRange, result); + } + result._updateIdentityStatus(false); + return result; + } + /** + * Stores a left-handed perspective projection into a given matrix with depth reversed + * Example Playground - https://playground.babylonjs.com/#AV9X17#89 + * @param fov defines the horizontal field of view + * @param aspect defines the aspect ratio + * @param znear defines the near clip plane + * @param zfar not used as infinity is used as far clip + * @param result defines the target matrix + * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) + * @returns result input + */ + static PerspectiveFovReverseLHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0) { + const t = 1.0 / Math.tan(fov * 0.5); + const a = isVerticalFovFixed ? t / aspect : t; + const b = isVerticalFovFixed ? t : t * aspect; + const rot = Math.tan(projectionPlaneTilt); + Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, -znear, 1.0, 0.0, 0.0, 1.0, 0.0, result); + if (halfZRange) { + result.multiplyToRef(mtxConvertNDCToHalfZRange, result); + } + result._updateIdentityStatus(false); + return result; + } + /** + * Creates a right-handed perspective projection matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#83 + * @param fov defines the horizontal field of view + * @param aspect defines the aspect ratio + * @param znear defines the near clip plane + * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) + * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) + * @returns a new matrix as a right-handed perspective projection matrix + */ + static PerspectiveFovRH(fov, aspect, znear, zfar, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { + const matrix = new Matrix(); + Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix, true, halfZRange, projectionPlaneTilt, reverseDepthBufferMode); + return matrix; + } + /** + * Stores a right-handed perspective projection into a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#84 + * @param fov defines the horizontal field of view + * @param aspect defines the aspect ratio + * @param znear defines the near clip plane + * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode + * @param result defines the target matrix + * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) + * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) + * @returns result input + */ + static PerspectiveFovRHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { + //alternatively this could be expressed as: + // m = PerspectiveFovLHToRef + // m[10] *= -1.0; + // m[11] *= -1.0; + const n = znear; + const f = zfar; + const t = 1.0 / Math.tan(fov * 0.5); + const a = isVerticalFovFixed ? t / aspect : t; + const b = isVerticalFovFixed ? t : t * aspect; + const c = reverseDepthBufferMode && n === 0 ? 1 : f !== 0 ? -(f + n) / (f - n) : -1; + const d = reverseDepthBufferMode && n === 0 ? 2 * f : f !== 0 ? (-2 * f * n) / (f - n) : -2 * n; + const rot = Math.tan(projectionPlaneTilt); + Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, c, -1, 0.0, 0.0, d, 0.0, result); + if (halfZRange) { + result.multiplyToRef(mtxConvertNDCToHalfZRange, result); + } + result._updateIdentityStatus(false); + return result; + } + /** + * Stores a right-handed perspective projection into a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#90 + * @param fov defines the horizontal field of view + * @param aspect defines the aspect ratio + * @param znear defines the near clip plane + * @param zfar not used as infinity is used as far clip + * @param result defines the target matrix + * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally + * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) + * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) + * @returns result input + */ + static PerspectiveFovReverseRHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0) { + const t = 1.0 / Math.tan(fov * 0.5); + const a = isVerticalFovFixed ? t / aspect : t; + const b = isVerticalFovFixed ? t : t * aspect; + const rot = Math.tan(projectionPlaneTilt); + Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, -znear, -1, 0.0, 0.0, -1, 0.0, result); + if (halfZRange) { + result.multiplyToRef(mtxConvertNDCToHalfZRange, result); + } + result._updateIdentityStatus(false); + return result; + } + /** + * Computes a complete transformation matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#113 + * @param viewport defines the viewport to use + * @param world defines the world matrix + * @param view defines the view matrix + * @param projection defines the projection matrix + * @param zmin defines the near clip plane + * @param zmax defines the far clip plane + * @returns the transformation matrix + */ + static GetFinalMatrix(viewport, world, view, projection, zmin, zmax) { + const cw = viewport.width; + const ch = viewport.height; + const cx = viewport.x; + const cy = viewport.y; + const viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1.0); + const matrix = new Matrix(); + world.multiplyToRef(view, matrix); + matrix.multiplyToRef(projection, matrix); + return matrix.multiplyToRef(viewportMatrix, matrix); + } + /** + * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array + * @param matrix defines the matrix to use + * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix + */ + static GetAsMatrix2x2(matrix) { + const m = matrix.m; + const arr = [m[0], m[1], m[4], m[5]]; + return PerformanceConfigurator.MatrixUse64Bits ? arr : new Float32Array(arr); + } + /** + * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array + * @param matrix defines the matrix to use + * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix + */ + static GetAsMatrix3x3(matrix) { + const m = matrix.m; + const arr = [m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]]; + return PerformanceConfigurator.MatrixUse64Bits ? arr : new Float32Array(arr); + } + /** + * Compute the transpose of a given matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#111 + * @param matrix defines the matrix to transpose + * @returns the new matrix + */ + static Transpose(matrix) { + const result = new Matrix(); + Matrix.TransposeToRef(matrix, result); + return result; + } + /** + * Compute the transpose of a matrix and store it in a target matrix + * Example Playground - https://playground.babylonjs.com/#AV9X17#112 + * @param matrix defines the matrix to transpose + * @param result defines the target matrix + * @returns result input + */ + static TransposeToRef(matrix, result) { + const mm = matrix.m; + const rm0 = mm[0]; + const rm1 = mm[4]; + const rm2 = mm[8]; + const rm3 = mm[12]; + const rm4 = mm[1]; + const rm5 = mm[5]; + const rm6 = mm[9]; + const rm7 = mm[13]; + const rm8 = mm[2]; + const rm9 = mm[6]; + const rm10 = mm[10]; + const rm11 = mm[14]; + const rm12 = mm[3]; + const rm13 = mm[7]; + const rm14 = mm[11]; + const rm15 = mm[15]; + const rm = result._m; + rm[0] = rm0; + rm[1] = rm1; + rm[2] = rm2; + rm[3] = rm3; + rm[4] = rm4; + rm[5] = rm5; + rm[6] = rm6; + rm[7] = rm7; + rm[8] = rm8; + rm[9] = rm9; + rm[10] = rm10; + rm[11] = rm11; + rm[12] = rm12; + rm[13] = rm13; + rm[14] = rm14; + rm[15] = rm15; + result.markAsUpdated(); + // identity-ness does not change when transposing + result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty); + return result; + } + /** + * Computes a reflection matrix from a plane + * Example Playground - https://playground.babylonjs.com/#AV9X17#87 + * @param plane defines the reflection plane + * @returns a new matrix + */ + static Reflection(plane) { + const matrix = new Matrix(); + Matrix.ReflectionToRef(plane, matrix); + return matrix; + } + /** + * Computes a reflection matrix from a plane + * Example Playground - https://playground.babylonjs.com/#AV9X17#88 + * @param plane defines the reflection plane + * @param result defines the target matrix + * @returns result input + */ + static ReflectionToRef(plane, result) { + plane.normalize(); + const x = plane.normal.x; + const y = plane.normal.y; + const z = plane.normal.z; + const temp = -2 * x; + const temp2 = -2 * y; + const temp3 = -2 * z; + Matrix.FromValuesToRef(temp * x + 1, temp2 * x, temp3 * x, 0.0, temp * y, temp2 * y + 1, temp3 * y, 0.0, temp * z, temp2 * z, temp3 * z + 1, 0.0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1.0, result); + return result; + } + /** + * Sets the given matrix as a rotation matrix composed from the 3 left handed axes + * @param xaxis defines the value of the 1st axis + * @param yaxis defines the value of the 2nd axis + * @param zaxis defines the value of the 3rd axis + * @param result defines the target matrix + * @returns result input + */ + static FromXYZAxesToRef(xaxis, yaxis, zaxis, result) { + Matrix.FromValuesToRef(xaxis._x, xaxis._y, xaxis._z, 0.0, yaxis._x, yaxis._y, yaxis._z, 0.0, zaxis._x, zaxis._y, zaxis._z, 0.0, 0.0, 0.0, 0.0, 1.0, result); + return result; + } + /** + * Creates a rotation matrix from a quaternion and stores it in a target matrix + * @param quat defines the quaternion to use + * @param result defines the target matrix + * @returns result input + */ + static FromQuaternionToRef(quat, result) { + const xx = quat._x * quat._x; + const yy = quat._y * quat._y; + const zz = quat._z * quat._z; + const xy = quat._x * quat._y; + const zw = quat._z * quat._w; + const zx = quat._z * quat._x; + const yw = quat._y * quat._w; + const yz = quat._y * quat._z; + const xw = quat._x * quat._w; + result._m[0] = 1.0 - 2.0 * (yy + zz); + result._m[1] = 2.0 * (xy + zw); + result._m[2] = 2.0 * (zx - yw); + result._m[3] = 0.0; + result._m[4] = 2.0 * (xy - zw); + result._m[5] = 1.0 - 2.0 * (zz + xx); + result._m[6] = 2.0 * (yz + xw); + result._m[7] = 0.0; + result._m[8] = 2.0 * (zx + yw); + result._m[9] = 2.0 * (yz - xw); + result._m[10] = 1.0 - 2.0 * (yy + xx); + result._m[11] = 0.0; + result._m[12] = 0.0; + result._m[13] = 0.0; + result._m[14] = 0.0; + result._m[15] = 1.0; + result.markAsUpdated(); + return result; + } +} +Matrix._UpdateFlagSeed = 0; +Matrix._IdentityReadOnly = Matrix.Identity(); +Object.defineProperties(Matrix.prototype, { + dimension: { value: [4, 4] }, + rank: { value: 2 }, +}); +/** + * @internal + * Same as Tmp but not exported to keep it only for math functions to avoid conflicts + */ +class MathTmp { +} +// Temporary Vector3s +MathTmp.Vector3 = BuildTuple(11, Vector3.Zero); +// Temporary Matricies +MathTmp.Matrix = BuildTuple(2, Matrix.Identity); +// Temporary Quaternions +MathTmp.Quaternion = BuildTuple(3, Quaternion.Zero); +/** + * @internal + */ +class TmpVectors { +} +/** 3 temp Vector2 at once should be enough */ +TmpVectors.Vector2 = BuildTuple(3, Vector2.Zero); +/** 13 temp Vector3 at once should be enough */ +TmpVectors.Vector3 = BuildTuple(13, Vector3.Zero); +/** 3 temp Vector4 at once should be enough */ +TmpVectors.Vector4 = BuildTuple(3, Vector4.Zero); +/** 3 temp Quaternion at once should be enough */ +TmpVectors.Quaternion = BuildTuple(3, Quaternion.Zero); +/** 8 temp Matrices at once should be enough */ +TmpVectors.Matrix = BuildTuple(8, Matrix.Identity); +RegisterClass("BABYLON.Vector2", Vector2); +RegisterClass("BABYLON.Vector3", Vector3); +RegisterClass("BABYLON.Vector4", Vector4); +RegisterClass("BABYLON.Matrix", Matrix); +const mtxConvertNDCToHalfZRange = Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1); + +/** Defines supported spaces */ +var Space; +(function (Space) { + /** Local (object) space */ + Space[Space["LOCAL"] = 0] = "LOCAL"; + /** World space */ + Space[Space["WORLD"] = 1] = "WORLD"; + /** Bone space */ + Space[Space["BONE"] = 2] = "BONE"; +})(Space || (Space = {})); +/** Defines the 3 main axes */ +class Axis { +} +/** X axis */ +Axis.X = new Vector3(1.0, 0.0, 0.0); +/** Y axis */ +Axis.Y = new Vector3(0.0, 1.0, 0.0); +/** Z axis */ +Axis.Z = new Vector3(0.0, 0.0, 1.0); +/** + * Defines cartesian components. + */ +var Coordinate; +(function (Coordinate) { + /** X axis */ + Coordinate[Coordinate["X"] = 0] = "X"; + /** Y axis */ + Coordinate[Coordinate["Y"] = 1] = "Y"; + /** Z axis */ + Coordinate[Coordinate["Z"] = 2] = "Z"; +})(Coordinate || (Coordinate = {})); + +function colorChannelToLinearSpace(color) { + return Math.pow(color, ToLinearSpace); +} +function colorChannelToLinearSpaceExact(color) { + if (color <= 0.04045) { + return 0.0773993808 * color; + } + return Math.pow(0.947867299 * (color + 0.055), 2.4); +} +function colorChannelToGammaSpace(color) { + return Math.pow(color, ToGammaSpace); +} +function colorChannelToGammaSpaceExact(color) { + if (color <= 0.0031308) { + return 12.92 * color; + } + return 1.055 * Math.pow(color, 0.41666) - 0.055; +} +/** + * Class used to hold a RGB color + */ +class Color3 { + /** + * Creates a new Color3 object from red, green, blue values, all between 0 and 1 + * @param r defines the red component (between 0 and 1, default is 0) + * @param g defines the green component (between 0 and 1, default is 0) + * @param b defines the blue component (between 0 and 1, default is 0) + */ + constructor( + /** + * [0] Defines the red component (between 0 and 1, default is 0) + */ + r = 0, + /** + * [0] Defines the green component (between 0 and 1, default is 0) + */ + g = 0, + /** + * [0] Defines the blue component (between 0 and 1, default is 0) + */ + b = 0) { + this.r = r; + this.g = g; + this.b = b; + } + /** + * Creates a string with the Color3 current values + * @returns the string representation of the Color3 object + */ + toString() { + return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}"; + } + /** + * Returns the string "Color3" + * @returns "Color3" + */ + getClassName() { + return "Color3"; + } + /** + * Compute the Color3 hash code + * @returns an unique number that can be used to hash Color3 objects + */ + getHashCode() { + let hash = (this.r * 255) | 0; + hash = (hash * 397) ^ ((this.g * 255) | 0); + hash = (hash * 397) ^ ((this.b * 255) | 0); + return hash; + } + // Operators + /** + * Stores in the given array from the given starting index the red, green, blue values as successive elements + * @param array defines the array where to store the r,g,b components + * @param index defines an optional index in the target array to define where to start storing values + * @returns the current Color3 object + */ + toArray(array, index = 0) { + array[index] = this.r; + array[index + 1] = this.g; + array[index + 2] = this.b; + return this; + } + /** + * Update the current color with values stored in an array from the starting index of the given array + * @param array defines the source array + * @param offset defines an offset in the source array + * @returns the current Color3 object + */ + fromArray(array, offset = 0) { + Color3.FromArrayToRef(array, offset, this); + return this; + } + /** + * Returns a new Color4 object from the current Color3 and the given alpha + * @param alpha defines the alpha component on the new Color4 object (default is 1) + * @returns a new Color4 object + */ + toColor4(alpha = 1) { + return new Color4(this.r, this.g, this.b, alpha); + } + /** + * Returns a new array populated with 3 numeric elements : red, green and blue values + * @returns the new array + */ + asArray() { + return [this.r, this.g, this.b]; + } + /** + * Returns the luminance value + * @returns a float value + */ + toLuminance() { + return this.r * 0.3 + this.g * 0.59 + this.b * 0.11; + } + /** + * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object + * @param otherColor defines the second operand + * @returns the new Color3 object + */ + multiply(otherColor) { + return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b); + } + /** + * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result" + * @param otherColor defines the second operand + * @param result defines the Color3 object where to store the result + * @returns the result Color3 + */ + multiplyToRef(otherColor, result) { + result.r = this.r * otherColor.r; + result.g = this.g * otherColor.g; + result.b = this.b * otherColor.b; + return result; + } + /** + * Multiplies the current Color3 coordinates by the given ones + * @param otherColor defines the second operand + * @returns the current updated Color3 + */ + multiplyInPlace(otherColor) { + this.r *= otherColor.r; + this.g *= otherColor.g; + this.b *= otherColor.b; + return this; + } + /** + * Returns a new Color3 set with the result of the multiplication of the current Color3 coordinates by the given floats + * @param r defines the r coordinate of the operand + * @param g defines the g coordinate of the operand + * @param b defines the b coordinate of the operand + * @returns the new Color3 + */ + multiplyByFloats(r, g, b) { + return new Color3(this.r * r, this.g * g, this.b * b); + } + /** + * @internal + * Do not use + */ + divide(_other) { + throw new ReferenceError("Can not divide a color"); + } + /** + * @internal + * Do not use + */ + divideToRef(_other, _result) { + throw new ReferenceError("Can not divide a color"); + } + /** + * @internal + * Do not use + */ + divideInPlace(_other) { + throw new ReferenceError("Can not divide a color"); + } + /** + * Updates the current Color3 with the minimal coordinate values between its and the given color ones + * @param other defines the second operand + * @returns the current updated Color3 + */ + minimizeInPlace(other) { + return this.minimizeInPlaceFromFloats(other.r, other.g, other.b); + } + /** + * Updates the current Color3 with the maximal coordinate values between its and the given color ones. + * @param other defines the second operand + * @returns the current updated Color3 + */ + maximizeInPlace(other) { + return this.maximizeInPlaceFromFloats(other.r, other.g, other.b); + } + /** + * Updates the current Color3 with the minimal coordinate values between its and the given coordinates + * @param r defines the r coordinate of the operand + * @param g defines the g coordinate of the operand + * @param b defines the b coordinate of the operand + * @returns the current updated Color3 + */ + minimizeInPlaceFromFloats(r, g, b) { + this.r = Math.min(r, this.r); + this.g = Math.min(g, this.g); + this.b = Math.min(b, this.b); + return this; + } + /** + * Updates the current Color3 with the maximal coordinate values between its and the given coordinates. + * @param r defines the r coordinate of the operand + * @param g defines the g coordinate of the operand + * @param b defines the b coordinate of the operand + * @returns the current updated Color3 + */ + maximizeInPlaceFromFloats(r, g, b) { + this.r = Math.max(r, this.r); + this.g = Math.max(g, this.g); + this.b = Math.max(b, this.b); + return this; + } + /** + * @internal + * Do not use + */ + floorToRef(_result) { + throw new ReferenceError("Can not floor a color"); + } + /** + * @internal + * Do not use + */ + floor() { + throw new ReferenceError("Can not floor a color"); + } + /** + * @internal + * Do not use + */ + fractToRef(_result) { + throw new ReferenceError("Can not fract a color"); + } + /** + * @internal + * Do not use + */ + fract() { + throw new ReferenceError("Can not fract a color"); + } + /** + * Determines equality between Color3 objects + * @param otherColor defines the second operand + * @returns true if the rgb values are equal to the given ones + */ + equals(otherColor) { + return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b; + } + /** + * Alias for equalsToFloats + * @param r red color component + * @param g green color component + * @param b blue color component + * @returns boolean + */ + equalsFloats(r, g, b) { + return this.equalsToFloats(r, g, b); + } + /** + * Determines equality between the current Color3 object and a set of r,b,g values + * @param r defines the red component to check + * @param g defines the green component to check + * @param b defines the blue component to check + * @returns true if the rgb values are equal to the given ones + */ + equalsToFloats(r, g, b) { + return this.r === r && this.g === g && this.b === b; + } + /** + * Returns true if the current Color3 and the given color coordinates are distant less than epsilon + * @param otherColor defines the second operand + * @param epsilon defines the minimal distance to define values as equals + * @returns true if both colors are distant less than epsilon + */ + equalsWithEpsilon(otherColor, epsilon = Epsilon) { + return WithinEpsilon(this.r, otherColor.r, epsilon) && WithinEpsilon(this.g, otherColor.g, epsilon) && WithinEpsilon(this.b, otherColor.b, epsilon); + } + /** + * @internal + * Do not use + */ + negate() { + throw new ReferenceError("Can not negate a color"); + } + /** + * @internal + * Do not use + */ + negateInPlace() { + throw new ReferenceError("Can not negate a color"); + } + /** + * @internal + * Do not use + */ + negateToRef(_result) { + throw new ReferenceError("Can not negate a color"); + } + /** + * Creates a new Color3 with the current Color3 values multiplied by scale + * @param scale defines the scaling factor to apply + * @returns a new Color3 object + */ + scale(scale) { + return new Color3(this.r * scale, this.g * scale, this.b * scale); + } + /** + * Multiplies the Color3 values by the float "scale" + * @param scale defines the scaling factor to apply + * @returns the current updated Color3 + */ + scaleInPlace(scale) { + this.r *= scale; + this.g *= scale; + this.b *= scale; + return this; + } + /** + * Multiplies the rgb values by scale and stores the result into "result" + * @param scale defines the scaling factor + * @param result defines the Color3 object where to store the result + * @returns the result Color3 + */ + scaleToRef(scale, result) { + result.r = this.r * scale; + result.g = this.g * scale; + result.b = this.b * scale; + return result; + } + /** + * Scale the current Color3 values by a factor and add the result to a given Color3 + * @param scale defines the scale factor + * @param result defines color to store the result into + * @returns the result Color3 + */ + scaleAndAddToRef(scale, result) { + result.r += this.r * scale; + result.g += this.g * scale; + result.b += this.b * scale; + return result; + } + /** + * Clamps the rgb values by the min and max values and stores the result into "result" + * @param min defines minimum clamping value (default is 0) + * @param max defines maximum clamping value (default is 1) + * @param result defines color to store the result into + * @returns the result Color3 + */ + clampToRef(min = 0, max = 1, result) { + result.r = Clamp(this.r, min, max); + result.g = Clamp(this.g, min, max); + result.b = Clamp(this.b, min, max); + return result; + } + /** + * Creates a new Color3 set with the added values of the current Color3 and of the given one + * @param otherColor defines the second operand + * @returns the new Color3 + */ + add(otherColor) { + return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b); + } + /** + * Adds the given color to the current Color3 + * @param otherColor defines the second operand + * @returns the current updated Color3 + */ + addInPlace(otherColor) { + this.r += otherColor.r; + this.g += otherColor.g; + this.b += otherColor.b; + return this; + } + /** + * Adds the given coordinates to the current Color3 + * @param r defines the r coordinate of the operand + * @param g defines the g coordinate of the operand + * @param b defines the b coordinate of the operand + * @returns the current updated Color3 + */ + addInPlaceFromFloats(r, g, b) { + this.r += r; + this.g += g; + this.b += b; + return this; + } + /** + * Stores the result of the addition of the current Color3 and given one rgb values into "result" + * @param otherColor defines the second operand + * @param result defines Color3 object to store the result into + * @returns the unmodified current Color3 + */ + addToRef(otherColor, result) { + result.r = this.r + otherColor.r; + result.g = this.g + otherColor.g; + result.b = this.b + otherColor.b; + return result; + } + /** + * Returns a new Color3 set with the subtracted values of the given one from the current Color3 + * @param otherColor defines the second operand + * @returns the new Color3 + */ + subtract(otherColor) { + return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b); + } + /** + * Stores the result of the subtraction of given one from the current Color3 rgb values into "result" + * @param otherColor defines the second operand + * @param result defines Color3 object to store the result into + * @returns the unmodified current Color3 + */ + subtractToRef(otherColor, result) { + result.r = this.r - otherColor.r; + result.g = this.g - otherColor.g; + result.b = this.b - otherColor.b; + return result; + } + /** + * Subtract the given color from the current Color3 + * @param otherColor defines the second operand + * @returns the current updated Color3 + */ + subtractInPlace(otherColor) { + this.r -= otherColor.r; + this.g -= otherColor.g; + this.b -= otherColor.b; + return this; + } + /** + * Returns a new Color3 set with the subtraction of the given floats from the current Color3 coordinates + * @param r defines the r coordinate of the operand + * @param g defines the g coordinate of the operand + * @param b defines the b coordinate of the operand + * @returns the resulting Color3 + */ + subtractFromFloats(r, g, b) { + return new Color3(this.r - r, this.g - g, this.b - b); + } + /** + * Subtracts the given floats from the current Color3 coordinates and set the given color "result" with this result + * @param r defines the r coordinate of the operand + * @param g defines the g coordinate of the operand + * @param b defines the b coordinate of the operand + * @param result defines the Color3 object where to store the result + * @returns the result + */ + subtractFromFloatsToRef(r, g, b, result) { + result.r = this.r - r; + result.g = this.g - g; + result.b = this.b - b; + return result; + } + /** + * Copy the current object + * @returns a new Color3 copied the current one + */ + clone() { + return new Color3(this.r, this.g, this.b); + } + /** + * Copies the rgb values from the source in the current Color3 + * @param source defines the source Color3 object + * @returns the updated Color3 object + */ + copyFrom(source) { + this.r = source.r; + this.g = source.g; + this.b = source.b; + return this; + } + /** + * Updates the Color3 rgb values from the given floats + * @param r defines the red component to read from + * @param g defines the green component to read from + * @param b defines the blue component to read from + * @returns the current Color3 object + */ + copyFromFloats(r, g, b) { + this.r = r; + this.g = g; + this.b = b; + return this; + } + /** + * Updates the Color3 rgb values from the given floats + * @param r defines the red component to read from + * @param g defines the green component to read from + * @param b defines the blue component to read from + * @returns the current Color3 object + */ + set(r, g, b) { + return this.copyFromFloats(r, g, b); + } + /** + * Copies the given float to the current Color3 coordinates + * @param v defines the r, g and b coordinates of the operand + * @returns the current updated Color3 + */ + setAll(v) { + this.r = this.g = this.b = v; + return this; + } + /** + * Compute the Color3 hexadecimal code as a string + * @returns a string containing the hexadecimal representation of the Color3 object + */ + toHexString() { + const intR = Math.round(this.r * 255); + const intG = Math.round(this.g * 255); + const intB = Math.round(this.b * 255); + return "#" + ToHex(intR) + ToHex(intG) + ToHex(intB); + } + /** + * Updates the Color3 rgb values from the string containing valid hexadecimal values + * @param hex defines a string containing valid hexadecimal values + * @returns the current Color3 object + */ + fromHexString(hex) { + if (hex.substring(0, 1) !== "#" || hex.length !== 7) { + return this; + } + this.r = parseInt(hex.substring(1, 3), 16) / 255; + this.g = parseInt(hex.substring(3, 5), 16) / 255; + this.b = parseInt(hex.substring(5, 7), 16) / 255; + return this; + } + /** + * Converts current color in rgb space to HSV values + * @returns a new color3 representing the HSV values + */ + toHSV() { + return this.toHSVToRef(new Color3()); + } + /** + * Converts current color in rgb space to HSV values + * @param result defines the Color3 where to store the HSV values + * @returns the updated result + */ + toHSVToRef(result) { + const r = this.r; + const g = this.g; + const b = this.b; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + let h = 0; + let s = 0; + const v = max; + const dm = max - min; + if (max !== 0) { + s = dm / max; + } + if (max != min) { + if (max == r) { + h = (g - b) / dm; + if (g < b) { + h += 6; + } + } + else if (max == g) { + h = (b - r) / dm + 2; + } + else if (max == b) { + h = (r - g) / dm + 4; + } + h *= 60; + } + result.r = h; + result.g = s; + result.b = v; + return result; + } + /** + * Computes a new Color3 converted from the current one to linear space + * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) + * @returns a new Color3 object + */ + toLinearSpace(exact = false) { + const convertedColor = new Color3(); + this.toLinearSpaceToRef(convertedColor, exact); + return convertedColor; + } + /** + * Converts the Color3 values to linear space and stores the result in "convertedColor" + * @param convertedColor defines the Color3 object where to store the linear space version + * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) + * @returns the unmodified Color3 + */ + toLinearSpaceToRef(convertedColor, exact = false) { + if (exact) { + convertedColor.r = colorChannelToLinearSpaceExact(this.r); + convertedColor.g = colorChannelToLinearSpaceExact(this.g); + convertedColor.b = colorChannelToLinearSpaceExact(this.b); + } + else { + convertedColor.r = colorChannelToLinearSpace(this.r); + convertedColor.g = colorChannelToLinearSpace(this.g); + convertedColor.b = colorChannelToLinearSpace(this.b); + } + return this; + } + /** + * Computes a new Color3 converted from the current one to gamma space + * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) + * @returns a new Color3 object + */ + toGammaSpace(exact = false) { + const convertedColor = new Color3(); + this.toGammaSpaceToRef(convertedColor, exact); + return convertedColor; + } + /** + * Converts the Color3 values to gamma space and stores the result in "convertedColor" + * @param convertedColor defines the Color3 object where to store the gamma space version + * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) + * @returns the unmodified Color3 + */ + toGammaSpaceToRef(convertedColor, exact = false) { + if (exact) { + convertedColor.r = colorChannelToGammaSpaceExact(this.r); + convertedColor.g = colorChannelToGammaSpaceExact(this.g); + convertedColor.b = colorChannelToGammaSpaceExact(this.b); + } + else { + convertedColor.r = colorChannelToGammaSpace(this.r); + convertedColor.g = colorChannelToGammaSpace(this.g); + convertedColor.b = colorChannelToGammaSpace(this.b); + } + return this; + } + /** + * Converts Hue, saturation and value to a Color3 (RGB) + * @param hue defines the hue (value between 0 and 360) + * @param saturation defines the saturation (value between 0 and 1) + * @param value defines the value (value between 0 and 1) + * @param result defines the Color3 where to store the RGB values + * @returns the updated result + */ + static HSVtoRGBToRef(hue, saturation, value, result) { + const chroma = value * saturation; + const h = hue / 60; + const x = chroma * (1 - Math.abs((h % 2) - 1)); + let r = 0; + let g = 0; + let b = 0; + if (h >= 0 && h <= 1) { + r = chroma; + g = x; + } + else if (h >= 1 && h <= 2) { + r = x; + g = chroma; + } + else if (h >= 2 && h <= 3) { + g = chroma; + b = x; + } + else if (h >= 3 && h <= 4) { + g = x; + b = chroma; + } + else if (h >= 4 && h <= 5) { + r = x; + b = chroma; + } + else if (h >= 5 && h <= 6) { + r = chroma; + b = x; + } + const m = value - chroma; + result.r = r + m; + result.g = g + m; + result.b = b + m; + return result; + } + /** + * Converts Hue, saturation and value to a new Color3 (RGB) + * @param hue defines the hue (value between 0 and 360) + * @param saturation defines the saturation (value between 0 and 1) + * @param value defines the value (value between 0 and 1) + * @returns a new Color3 object + */ + static FromHSV(hue, saturation, value) { + const result = new Color3(0, 0, 0); + Color3.HSVtoRGBToRef(hue, saturation, value, result); + return result; + } + /** + * Creates a new Color3 from the string containing valid hexadecimal values + * @param hex defines a string containing valid hexadecimal values + * @returns a new Color3 object + */ + static FromHexString(hex) { + return new Color3(0, 0, 0).fromHexString(hex); + } + /** + * Creates a new Color3 from the starting index of the given array + * @param array defines the source array + * @param offset defines an offset in the source array + * @returns a new Color3 object + */ + static FromArray(array, offset = 0) { + return new Color3(array[offset], array[offset + 1], array[offset + 2]); + } + /** + * Creates a new Color3 from the starting index element of the given array + * @param array defines the source array to read from + * @param offset defines the offset in the source array + * @param result defines the target Color3 object + */ + static FromArrayToRef(array, offset = 0, result) { + result.r = array[offset]; + result.g = array[offset + 1]; + result.b = array[offset + 2]; + } + /** + * Creates a new Color3 from integer values (\< 256) + * @param r defines the red component to read from (value between 0 and 255) + * @param g defines the green component to read from (value between 0 and 255) + * @param b defines the blue component to read from (value between 0 and 255) + * @returns a new Color3 object + */ + static FromInts(r, g, b) { + return new Color3(r / 255.0, g / 255.0, b / 255.0); + } + /** + * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3 + * @param start defines the start Color3 value + * @param end defines the end Color3 value + * @param amount defines the gradient value between start and end + * @returns a new Color3 object + */ + static Lerp(start, end, amount) { + const result = new Color3(0.0, 0.0, 0.0); + Color3.LerpToRef(start, end, amount, result); + return result; + } + /** + * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3 + * @param left defines the start value + * @param right defines the end value + * @param amount defines the gradient factor + * @param result defines the Color3 object where to store the result + */ + static LerpToRef(left, right, amount, result) { + result.r = left.r + (right.r - left.r) * amount; + result.g = left.g + (right.g - left.g) * amount; + result.b = left.b + (right.b - left.b) * amount; + } + /** + * Returns a new Color3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2" + * @param value1 defines the first control point + * @param tangent1 defines the first tangent Color3 + * @param value2 defines the second control point + * @param tangent2 defines the second tangent Color3 + * @param amount defines the amount on the interpolation spline (between 0 and 1) + * @returns the new Color3 + */ + static Hermite(value1, tangent1, value2, tangent2, amount) { + const squared = amount * amount; + const cubed = amount * squared; + const part1 = 2.0 * cubed - 3.0 * squared + 1.0; + const part2 = -2 * cubed + 3.0 * squared; + const part3 = cubed - 2.0 * squared + amount; + const part4 = cubed - squared; + const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4; + const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4; + const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4; + return new Color3(r, g, b); + } + /** + * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @returns 1st derivative + */ + static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { + const result = Color3.Black(); + this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); + return result; + } + /** + * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @param result define where to store the derivative + */ + static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { + const t2 = time * time; + result.r = (t2 - time) * 6 * value1.r + (3 * t2 - 4 * time + 1) * tangent1.r + (-t2 + time) * 6 * value2.r + (3 * t2 - 2 * time) * tangent2.r; + result.g = (t2 - time) * 6 * value1.g + (3 * t2 - 4 * time + 1) * tangent1.g + (-t2 + time) * 6 * value2.g + (3 * t2 - 2 * time) * tangent2.g; + result.b = (t2 - time) * 6 * value1.b + (3 * t2 - 4 * time + 1) * tangent1.b + (-t2 + time) * 6 * value2.b + (3 * t2 - 2 * time) * tangent2.b; + } + /** + * Returns a Color3 value containing a red color + * @returns a new Color3 object + */ + static Red() { + return new Color3(1, 0, 0); + } + /** + * Returns a Color3 value containing a green color + * @returns a new Color3 object + */ + static Green() { + return new Color3(0, 1, 0); + } + /** + * Returns a Color3 value containing a blue color + * @returns a new Color3 object + */ + static Blue() { + return new Color3(0, 0, 1); + } + /** + * Returns a Color3 value containing a black color + * @returns a new Color3 object + */ + static Black() { + return new Color3(0, 0, 0); + } + /** + * Gets a Color3 value containing a black color that must not be updated + */ + static get BlackReadOnly() { + return Color3._BlackReadOnly; + } + /** + * Returns a Color3 value containing a white color + * @returns a new Color3 object + */ + static White() { + return new Color3(1, 1, 1); + } + /** + * Returns a Color3 value containing a purple color + * @returns a new Color3 object + */ + static Purple() { + return new Color3(0.5, 0, 0.5); + } + /** + * Returns a Color3 value containing a magenta color + * @returns a new Color3 object + */ + static Magenta() { + return new Color3(1, 0, 1); + } + /** + * Returns a Color3 value containing a yellow color + * @returns a new Color3 object + */ + static Yellow() { + return new Color3(1, 1, 0); + } + /** + * Returns a Color3 value containing a gray color + * @returns a new Color3 object + */ + static Gray() { + return new Color3(0.5, 0.5, 0.5); + } + /** + * Returns a Color3 value containing a teal color + * @returns a new Color3 object + */ + static Teal() { + return new Color3(0, 1.0, 1.0); + } + /** + * Returns a Color3 value containing a random color + * @returns a new Color3 object + */ + static Random() { + return new Color3(Math.random(), Math.random(), Math.random()); + } +} +/** + * If the first color is flagged with integers (as everything is 0,0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet. + * If subsequent colors are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers, + * and henceforth it will use floating-point representation for all color instances that it creates. + * But the original color instances are unchanged and has a "deprecated map". + * If we keep using the color instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches. + */ +Color3._V8PerformanceHack = new Color3(0.5, 0.5, 0.5); +// Statics +Color3._BlackReadOnly = Color3.Black(); +Object.defineProperties(Color3.prototype, { + dimension: { value: [3] }, + rank: { value: 1 }, +}); +/** + * Class used to hold a RBGA color + */ +class Color4 { + /** + * Creates a new Color4 object from red, green, blue values, all between 0 and 1 + * @param r defines the red component (between 0 and 1, default is 0) + * @param g defines the green component (between 0 and 1, default is 0) + * @param b defines the blue component (between 0 and 1, default is 0) + * @param a defines the alpha component (between 0 and 1, default is 1) + */ + constructor( + /** + * [0] Defines the red component (between 0 and 1, default is 0) + */ + r = 0, + /** + * [0] Defines the green component (between 0 and 1, default is 0) + */ + g = 0, + /** + * [0] Defines the blue component (between 0 and 1, default is 0) + */ + b = 0, + /** + * [1] Defines the alpha component (between 0 and 1, default is 1) + */ + a = 1) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + } + // Operators + /** + * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values + * @returns the new array + */ + asArray() { + return [this.r, this.g, this.b, this.a]; + } + /** + * Stores from the starting index in the given array the Color4 successive values + * @param array defines the array where to store the r,g,b components + * @param index defines an optional index in the target array to define where to start storing values + * @returns the current Color4 object + */ + toArray(array, index = 0) { + array[index] = this.r; + array[index + 1] = this.g; + array[index + 2] = this.b; + array[index + 3] = this.a; + return this; + } + /** + * Update the current color with values stored in an array from the starting index of the given array + * @param array defines the source array + * @param offset defines an offset in the source array + * @returns the current Color4 object + */ + fromArray(array, offset = 0) { + this.r = array[offset]; + this.g = array[offset + 1]; + this.b = array[offset + 2]; + this.a = array[offset + 3]; + return this; + } + /** + * Determines equality between Color4 objects + * @param otherColor defines the second operand + * @returns true if the rgba values are equal to the given ones + */ + equals(otherColor) { + return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b && this.a === otherColor.a; + } + /** + * Creates a new Color4 set with the added values of the current Color4 and of the given one + * @param otherColor defines the second operand + * @returns a new Color4 object + */ + add(otherColor) { + return new Color4(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b, this.a + otherColor.a); + } + /** + * Updates the given color "result" with the result of the addition of the current Color4 and the given one. + * @param otherColor the color to add + * @param result the color to store the result + * @returns result input + */ + addToRef(otherColor, result) { + result.r = this.r + otherColor.r; + result.g = this.g + otherColor.g; + result.b = this.b + otherColor.b; + result.a = this.a + otherColor.a; + return result; + } + /** + * Adds in place the given Color4 values to the current Color4 object + * @param otherColor defines the second operand + * @returns the current updated Color4 object + */ + addInPlace(otherColor) { + this.r += otherColor.r; + this.g += otherColor.g; + this.b += otherColor.b; + this.a += otherColor.a; + return this; + } + /** + * Adds the given coordinates to the current Color4 + * @param r defines the r coordinate of the operand + * @param g defines the g coordinate of the operand + * @param b defines the b coordinate of the operand + * @param a defines the a coordinate of the operand + * @returns the current updated Color4 + */ + addInPlaceFromFloats(r, g, b, a) { + this.r += r; + this.g += g; + this.b += b; + this.a += a; + return this; + } + /** + * Creates a new Color4 set with the subtracted values of the given one from the current Color4 + * @param otherColor defines the second operand + * @returns a new Color4 object + */ + subtract(otherColor) { + return new Color4(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b, this.a - otherColor.a); + } + /** + * Subtracts the given ones from the current Color4 values and stores the results in "result" + * @param otherColor defines the second operand + * @param result defines the Color4 object where to store the result + * @returns the result Color4 object + */ + subtractToRef(otherColor, result) { + result.r = this.r - otherColor.r; + result.g = this.g - otherColor.g; + result.b = this.b - otherColor.b; + result.a = this.a - otherColor.a; + return result; + } + /** + * Subtract in place the given color from the current Color4. + * @param otherColor the color to subtract + * @returns the updated Color4. + */ + subtractInPlace(otherColor) { + this.r -= otherColor.r; + this.g -= otherColor.g; + this.b -= otherColor.b; + this.a -= otherColor.a; + return this; + } + /** + * Returns a new Color4 set with the result of the subtraction of the given floats from the current Color4 coordinates. + * @param r value to subtract + * @param g value to subtract + * @param b value to subtract + * @param a value to subtract + * @returns new color containing the result + */ + subtractFromFloats(r, g, b, a) { + return new Color4(this.r - r, this.g - g, this.b - b, this.a - a); + } + /** + * Sets the given color "result" set with the result of the subtraction of the given floats from the current Color4 coordinates. + * @param r value to subtract + * @param g value to subtract + * @param b value to subtract + * @param a value to subtract + * @param result the color to store the result in + * @returns result input + */ + subtractFromFloatsToRef(r, g, b, a, result) { + result.r = this.r - r; + result.g = this.g - g; + result.b = this.b - b; + result.a = this.a - a; + return result; + } + /** + * Creates a new Color4 with the current Color4 values multiplied by scale + * @param scale defines the scaling factor to apply + * @returns a new Color4 object + */ + scale(scale) { + return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale); + } + /** + * Multiplies the Color4 values by the float "scale" + * @param scale defines the scaling factor to apply + * @returns the current updated Color4 + */ + scaleInPlace(scale) { + this.r *= scale; + this.g *= scale; + this.b *= scale; + this.a *= scale; + return this; + } + /** + * Multiplies the current Color4 values by scale and stores the result in "result" + * @param scale defines the scaling factor to apply + * @param result defines the Color4 object where to store the result + * @returns the result Color4 + */ + scaleToRef(scale, result) { + result.r = this.r * scale; + result.g = this.g * scale; + result.b = this.b * scale; + result.a = this.a * scale; + return result; + } + /** + * Scale the current Color4 values by a factor and add the result to a given Color4 + * @param scale defines the scale factor + * @param result defines the Color4 object where to store the result + * @returns the result Color4 + */ + scaleAndAddToRef(scale, result) { + result.r += this.r * scale; + result.g += this.g * scale; + result.b += this.b * scale; + result.a += this.a * scale; + return result; + } + /** + * Clamps the rgb values by the min and max values and stores the result into "result" + * @param min defines minimum clamping value (default is 0) + * @param max defines maximum clamping value (default is 1) + * @param result defines color to store the result into. + * @returns the result Color4 + */ + clampToRef(min = 0, max = 1, result) { + result.r = Clamp(this.r, min, max); + result.g = Clamp(this.g, min, max); + result.b = Clamp(this.b, min, max); + result.a = Clamp(this.a, min, max); + return result; + } + /** + * Multiply an Color4 value by another and return a new Color4 object + * @param color defines the Color4 value to multiply by + * @returns a new Color4 object + */ + multiply(color) { + return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a); + } + /** + * Multiply a Color4 value by another and push the result in a reference value + * @param color defines the Color4 value to multiply by + * @param result defines the Color4 to fill the result in + * @returns the result Color4 + */ + multiplyToRef(color, result) { + result.r = this.r * color.r; + result.g = this.g * color.g; + result.b = this.b * color.b; + result.a = this.a * color.a; + return result; + } + /** + * Multiplies in place the current Color4 by the given one. + * @param otherColor color to multiple with + * @returns the updated Color4. + */ + multiplyInPlace(otherColor) { + this.r *= otherColor.r; + this.g *= otherColor.g; + this.b *= otherColor.b; + this.a *= otherColor.a; + return this; + } + /** + * Returns a new Color4 set with the multiplication result of the given floats and the current Color4 coordinates. + * @param r value multiply with + * @param g value multiply with + * @param b value multiply with + * @param a value multiply with + * @returns resulting new color + */ + multiplyByFloats(r, g, b, a) { + return new Color4(this.r * r, this.g * g, this.b * b, this.a * a); + } + /** + * @internal + * Do not use + */ + divide(_other) { + throw new ReferenceError("Can not divide a color"); + } + /** + * @internal + * Do not use + */ + divideToRef(_other, _result) { + throw new ReferenceError("Can not divide a color"); + } + /** + * @internal + * Do not use + */ + divideInPlace(_other) { + throw new ReferenceError("Can not divide a color"); + } + /** + * Updates the Color4 coordinates with the minimum values between its own and the given color ones + * @param other defines the second operand + * @returns the current updated Color4 + */ + minimizeInPlace(other) { + this.r = Math.min(this.r, other.r); + this.g = Math.min(this.g, other.g); + this.b = Math.min(this.b, other.b); + this.a = Math.min(this.a, other.a); + return this; + } + /** + * Updates the Color4 coordinates with the maximum values between its own and the given color ones + * @param other defines the second operand + * @returns the current updated Color4 + */ + maximizeInPlace(other) { + this.r = Math.max(this.r, other.r); + this.g = Math.max(this.g, other.g); + this.b = Math.max(this.b, other.b); + this.a = Math.max(this.a, other.a); + return this; + } + /** + * Updates the current Color4 with the minimal coordinate values between its and the given coordinates + * @param r defines the r coordinate of the operand + * @param g defines the g coordinate of the operand + * @param b defines the b coordinate of the operand + * @param a defines the a coordinate of the operand + * @returns the current updated Color4 + */ + minimizeInPlaceFromFloats(r, g, b, a) { + this.r = Math.min(r, this.r); + this.g = Math.min(g, this.g); + this.b = Math.min(b, this.b); + this.a = Math.min(a, this.a); + return this; + } + /** + * Updates the current Color4 with the maximal coordinate values between its and the given coordinates. + * @param r defines the r coordinate of the operand + * @param g defines the g coordinate of the operand + * @param b defines the b coordinate of the operand + * @param a defines the a coordinate of the operand + * @returns the current updated Color4 + */ + maximizeInPlaceFromFloats(r, g, b, a) { + this.r = Math.max(r, this.r); + this.g = Math.max(g, this.g); + this.b = Math.max(b, this.b); + this.a = Math.max(a, this.a); + return this; + } + /** + * @internal + * Do not use + */ + floorToRef(_result) { + throw new ReferenceError("Can not floor a color"); + } + /** + * @internal + * Do not use + */ + floor() { + throw new ReferenceError("Can not floor a color"); + } + /** + * @internal + * Do not use + */ + fractToRef(_result) { + throw new ReferenceError("Can not fract a color"); + } + /** + * @internal + * Do not use + */ + fract() { + throw new ReferenceError("Can not fract a color"); + } + /** + * @internal + * Do not use + */ + negate() { + throw new ReferenceError("Can not negate a color"); + } + /** + * @internal + * Do not use + */ + negateInPlace() { + throw new ReferenceError("Can not negate a color"); + } + /** + * @internal + * Do not use + */ + negateToRef(_result) { + throw new ReferenceError("Can not negate a color"); + } + /** + * Boolean : True if the current Color4 coordinates are each beneath the distance "epsilon" from the given color ones. + * @param otherColor color to compare against + * @param epsilon (Default: very small number) + * @returns true if they are equal + */ + equalsWithEpsilon(otherColor, epsilon = Epsilon) { + return (WithinEpsilon(this.r, otherColor.r, epsilon) && + WithinEpsilon(this.g, otherColor.g, epsilon) && + WithinEpsilon(this.b, otherColor.b, epsilon) && + WithinEpsilon(this.a, otherColor.a, epsilon)); + } + /** + * Boolean : True if the given floats are strictly equal to the current Color4 coordinates. + * @param x x value to compare against + * @param y y value to compare against + * @param z z value to compare against + * @param w w value to compare against + * @returns true if equal + */ + equalsToFloats(x, y, z, w) { + return this.r === x && this.g === y && this.b === z && this.a === w; + } + /** + * Creates a string with the Color4 current values + * @returns the string representation of the Color4 object + */ + toString() { + return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}"; + } + /** + * Returns the string "Color4" + * @returns "Color4" + */ + getClassName() { + return "Color4"; + } + /** + * Compute the Color4 hash code + * @returns an unique number that can be used to hash Color4 objects + */ + getHashCode() { + let hash = (this.r * 255) | 0; + hash = (hash * 397) ^ ((this.g * 255) | 0); + hash = (hash * 397) ^ ((this.b * 255) | 0); + hash = (hash * 397) ^ ((this.a * 255) | 0); + return hash; + } + /** + * Creates a new Color4 copied from the current one + * @returns a new Color4 object + */ + clone() { + const result = new Color4(); + return result.copyFrom(this); + } + /** + * Copies the given Color4 values into the current one + * @param source defines the source Color4 object + * @returns the current updated Color4 object + */ + copyFrom(source) { + this.r = source.r; + this.g = source.g; + this.b = source.b; + this.a = source.a; + return this; + } + /** + * Copies the given float values into the current one + * @param r defines the red component to read from + * @param g defines the green component to read from + * @param b defines the blue component to read from + * @param a defines the alpha component to read from + * @returns the current updated Color4 object + */ + copyFromFloats(r, g, b, a) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + return this; + } + /** + * Copies the given float values into the current one + * @param r defines the red component to read from + * @param g defines the green component to read from + * @param b defines the blue component to read from + * @param a defines the alpha component to read from + * @returns the current updated Color4 object + */ + set(r, g, b, a) { + return this.copyFromFloats(r, g, b, a); + } + /** + * Copies the given float to the current Vector4 coordinates + * @param v defines the r, g, b, and a coordinates of the operand + * @returns the current updated Vector4 + */ + setAll(v) { + this.r = this.g = this.b = this.a = v; + return this; + } + /** + * Compute the Color4 hexadecimal code as a string + * @param returnAsColor3 defines if the string should only contains RGB values (off by default) + * @returns a string containing the hexadecimal representation of the Color4 object + */ + toHexString(returnAsColor3 = false) { + const intR = Math.round(this.r * 255); + const intG = Math.round(this.g * 255); + const intB = Math.round(this.b * 255); + if (returnAsColor3) { + return "#" + ToHex(intR) + ToHex(intG) + ToHex(intB); + } + const intA = Math.round(this.a * 255); + return "#" + ToHex(intR) + ToHex(intG) + ToHex(intB) + ToHex(intA); + } + /** + * Updates the Color4 rgba values from the string containing valid hexadecimal values. + * + * A valid hex string is either in the format #RRGGBB or #RRGGBBAA. + * + * When a hex string without alpha is passed, the resulting Color4 keeps + * its previous alpha value. + * + * An invalid string does not modify this object + * + * @param hex defines a string containing valid hexadecimal values + * @returns the current updated Color4 object + */ + fromHexString(hex) { + if (hex.substring(0, 1) !== "#" || (hex.length !== 9 && hex.length !== 7)) { + return this; + } + this.r = parseInt(hex.substring(1, 3), 16) / 255; + this.g = parseInt(hex.substring(3, 5), 16) / 255; + this.b = parseInt(hex.substring(5, 7), 16) / 255; + if (hex.length === 9) { + this.a = parseInt(hex.substring(7, 9), 16) / 255; + } + return this; + } + /** + * Computes a new Color4 converted from the current one to linear space + * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) + * @returns a new Color4 object + */ + toLinearSpace(exact = false) { + const convertedColor = new Color4(); + this.toLinearSpaceToRef(convertedColor, exact); + return convertedColor; + } + /** + * Converts the Color4 values to linear space and stores the result in "convertedColor" + * @param convertedColor defines the Color4 object where to store the linear space version + * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) + * @returns the unmodified Color4 + */ + toLinearSpaceToRef(convertedColor, exact = false) { + if (exact) { + convertedColor.r = colorChannelToLinearSpaceExact(this.r); + convertedColor.g = colorChannelToLinearSpaceExact(this.g); + convertedColor.b = colorChannelToLinearSpaceExact(this.b); + } + else { + convertedColor.r = colorChannelToLinearSpace(this.r); + convertedColor.g = colorChannelToLinearSpace(this.g); + convertedColor.b = colorChannelToLinearSpace(this.b); + } + convertedColor.a = this.a; + return this; + } + /** + * Computes a new Color4 converted from the current one to gamma space + * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) + * @returns a new Color4 object + */ + toGammaSpace(exact = false) { + const convertedColor = new Color4(); + this.toGammaSpaceToRef(convertedColor, exact); + return convertedColor; + } + /** + * Converts the Color4 values to gamma space and stores the result in "convertedColor" + * @param convertedColor defines the Color4 object where to store the gamma space version + * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) + * @returns the unmodified Color4 + */ + toGammaSpaceToRef(convertedColor, exact = false) { + if (exact) { + convertedColor.r = colorChannelToGammaSpaceExact(this.r); + convertedColor.g = colorChannelToGammaSpaceExact(this.g); + convertedColor.b = colorChannelToGammaSpaceExact(this.b); + } + else { + convertedColor.r = colorChannelToGammaSpace(this.r); + convertedColor.g = colorChannelToGammaSpace(this.g); + convertedColor.b = colorChannelToGammaSpace(this.b); + } + convertedColor.a = this.a; + return this; + } + // Statics + /** + * Creates a new Color4 from the string containing valid hexadecimal values. + * + * A valid hex string is either in the format #RRGGBB or #RRGGBBAA. + * + * When a hex string without alpha is passed, the resulting Color4 has + * its alpha value set to 1.0. + * + * An invalid string results in a Color with all its channels set to 0.0, + * i.e. "transparent black". + * + * @param hex defines a string containing valid hexadecimal values + * @returns a new Color4 object + */ + static FromHexString(hex) { + if (hex.substring(0, 1) !== "#" || (hex.length !== 9 && hex.length !== 7)) { + return new Color4(0.0, 0.0, 0.0, 0.0); + } + return new Color4(0.0, 0.0, 0.0, 1.0).fromHexString(hex); + } + /** + * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object + * @param left defines the start value + * @param right defines the end value + * @param amount defines the gradient factor + * @returns a new Color4 object + */ + static Lerp(left, right, amount) { + return Color4.LerpToRef(left, right, amount, new Color4()); + } + /** + * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object + * @param left defines the start value + * @param right defines the end value + * @param amount defines the gradient factor + * @param result defines the Color4 object where to store data + * @returns the updated result + */ + static LerpToRef(left, right, amount, result) { + result.r = left.r + (right.r - left.r) * amount; + result.g = left.g + (right.g - left.g) * amount; + result.b = left.b + (right.b - left.b) * amount; + result.a = left.a + (right.a - left.a) * amount; + return result; + } + /** + * Interpolate between two Color4 using Hermite interpolation + * @param value1 defines first Color4 + * @param tangent1 defines the incoming tangent + * @param value2 defines second Color4 + * @param tangent2 defines the outgoing tangent + * @param amount defines the target Color4 + * @returns the new interpolated Color4 + */ + static Hermite(value1, tangent1, value2, tangent2, amount) { + const squared = amount * amount; + const cubed = amount * squared; + const part1 = 2.0 * cubed - 3.0 * squared + 1.0; + const part2 = -2 * cubed + 3.0 * squared; + const part3 = cubed - 2.0 * squared + amount; + const part4 = cubed - squared; + const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4; + const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4; + const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4; + const a = value1.a * part1 + value2.a * part2 + tangent1.a * part3 + tangent2.a * part4; + return new Color4(r, g, b, a); + } + /** + * Returns a new Color4 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @returns 1st derivative + */ + static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { + const result = new Color4(); + this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); + return result; + } + /** + * Update a Color4 with the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". + * @param value1 defines the first control point + * @param tangent1 defines the first tangent + * @param value2 defines the second control point + * @param tangent2 defines the second tangent + * @param time define where the derivative must be done + * @param result define where to store the derivative + */ + static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { + const t2 = time * time; + result.r = (t2 - time) * 6 * value1.r + (3 * t2 - 4 * time + 1) * tangent1.r + (-t2 + time) * 6 * value2.r + (3 * t2 - 2 * time) * tangent2.r; + result.g = (t2 - time) * 6 * value1.g + (3 * t2 - 4 * time + 1) * tangent1.g + (-t2 + time) * 6 * value2.g + (3 * t2 - 2 * time) * tangent2.g; + result.b = (t2 - time) * 6 * value1.b + (3 * t2 - 4 * time + 1) * tangent1.b + (-t2 + time) * 6 * value2.b + (3 * t2 - 2 * time) * tangent2.b; + result.a = (t2 - time) * 6 * value1.a + (3 * t2 - 4 * time + 1) * tangent1.a + (-t2 + time) * 6 * value2.a + (3 * t2 - 2 * time) * tangent2.a; + } + /** + * Creates a new Color4 from a Color3 and an alpha value + * @param color3 defines the source Color3 to read from + * @param alpha defines the alpha component (1.0 by default) + * @returns a new Color4 object + */ + static FromColor3(color3, alpha = 1.0) { + return new Color4(color3.r, color3.g, color3.b, alpha); + } + /** + * Creates a new Color4 from the starting index element of the given array + * @param array defines the source array to read from + * @param offset defines the offset in the source array + * @returns a new Color4 object + */ + static FromArray(array, offset = 0) { + return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); + } + /** + * Creates a new Color4 from the starting index element of the given array + * @param array defines the source array to read from + * @param offset defines the offset in the source array + * @param result defines the target Color4 object + */ + static FromArrayToRef(array, offset = 0, result) { + result.r = array[offset]; + result.g = array[offset + 1]; + result.b = array[offset + 2]; + result.a = array[offset + 3]; + } + /** + * Creates a new Color3 from integer values (less than 256) + * @param r defines the red component to read from (value between 0 and 255) + * @param g defines the green component to read from (value between 0 and 255) + * @param b defines the blue component to read from (value between 0 and 255) + * @param a defines the alpha component to read from (value between 0 and 255) + * @returns a new Color3 object + */ + static FromInts(r, g, b, a) { + return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0); + } + /** + * Check the content of a given array and convert it to an array containing RGBA data + * If the original array was already containing count * 4 values then it is returned directly + * @param colors defines the array to check + * @param count defines the number of RGBA data to expect + * @returns an array containing count * 4 values (RGBA) + */ + static CheckColors4(colors, count) { + // Check if color3 was used + if (colors.length === count * 3) { + const colors4 = []; + for (let index = 0; index < colors.length; index += 3) { + const newIndex = (index / 3) * 4; + colors4[newIndex] = colors[index]; + colors4[newIndex + 1] = colors[index + 1]; + colors4[newIndex + 2] = colors[index + 2]; + colors4[newIndex + 3] = 1.0; + } + return colors4; + } + return colors; + } +} +/** + * If the first color is flagged with integers (as everything is 0,0,0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet. + * If subsequent colors are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers, + * and henceforth it will use floating-point representation for all color instances that it creates. + * But the original color instances are unchanged and has a "deprecated map". + * If we keep using the color instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches. + */ +Color4._V8PerformanceHack = new Color4(0.5, 0.5, 0.5, 0.5); +Object.defineProperties(Color4.prototype, { + dimension: { value: [4] }, + rank: { value: 1 }, +}); +/** + * @internal + */ +class TmpColors { +} +TmpColors.Color3 = BuildArray(3, Color3.Black); +TmpColors.Color4 = BuildArray(3, () => new Color4(0, 0, 0, 0)); +RegisterClass("BABYLON.Color3", Color3); +RegisterClass("BABYLON.Color4", Color4); + +/** + * Represents a plane by the equation ax + by + cz + d = 0 + */ +class Plane { + /** + * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0 + * @param a a component of the plane + * @param b b component of the plane + * @param c c component of the plane + * @param d d component of the plane + */ + constructor(a, b, c, d) { + this.normal = new Vector3(a, b, c); + this.d = d; + } + /** + * @returns the plane coordinates as a new array of 4 elements [a, b, c, d]. + */ + asArray() { + return [this.normal.x, this.normal.y, this.normal.z, this.d]; + } + // Methods + /** + * @returns a new plane copied from the current Plane. + */ + clone() { + return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d); + } + /** + * @returns the string "Plane". + */ + getClassName() { + return "Plane"; + } + /** + * @returns the Plane hash code. + */ + getHashCode() { + let hash = this.normal.getHashCode(); + hash = (hash * 397) ^ (this.d | 0); + return hash; + } + /** + * Normalize the current Plane in place. + * @returns the updated Plane. + */ + normalize() { + const norm = Math.sqrt(this.normal.x * this.normal.x + this.normal.y * this.normal.y + this.normal.z * this.normal.z); + let magnitude = 0.0; + if (norm !== 0) { + magnitude = 1.0 / norm; + } + this.normal.x *= magnitude; + this.normal.y *= magnitude; + this.normal.z *= magnitude; + this.d *= magnitude; + return this; + } + /** + * Applies a transformation the plane and returns the result + * @param transformation the transformation matrix to be applied to the plane + * @returns a new Plane as the result of the transformation of the current Plane by the given matrix. + */ + transform(transformation) { + const invertedMatrix = Plane._TmpMatrix; + transformation.invertToRef(invertedMatrix); + const m = invertedMatrix.m; + const x = this.normal.x; + const y = this.normal.y; + const z = this.normal.z; + const d = this.d; + const normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3]; + const normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7]; + const normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11]; + const finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15]; + return new Plane(normalX, normalY, normalZ, finalD); + } + /** + * Compute the dot product between the point and the plane normal + * @param point point to calculate the dot product with + * @returns the dot product (float) of the point coordinates and the plane normal. + */ + dotCoordinate(point) { + return this.normal.x * point.x + this.normal.y * point.y + this.normal.z * point.z + this.d; + } + /** + * Updates the current Plane from the plane defined by the three given points. + * @param point1 one of the points used to construct the plane + * @param point2 one of the points used to construct the plane + * @param point3 one of the points used to construct the plane + * @returns the updated Plane. + */ + copyFromPoints(point1, point2, point3) { + const x1 = point2.x - point1.x; + const y1 = point2.y - point1.y; + const z1 = point2.z - point1.z; + const x2 = point3.x - point1.x; + const y2 = point3.y - point1.y; + const z2 = point3.z - point1.z; + const yz = y1 * z2 - z1 * y2; + const xz = z1 * x2 - x1 * z2; + const xy = x1 * y2 - y1 * x2; + const pyth = Math.sqrt(yz * yz + xz * xz + xy * xy); + let invPyth; + if (pyth !== 0) { + invPyth = 1.0 / pyth; + } + else { + invPyth = 0.0; + } + this.normal.x = yz * invPyth; + this.normal.y = xz * invPyth; + this.normal.z = xy * invPyth; + this.d = -(this.normal.x * point1.x + this.normal.y * point1.y + this.normal.z * point1.z); + return this; + } + /** + * Checks if the plane is facing a given direction (meaning if the plane's normal is pointing in the opposite direction of the given vector). + * Note that for this function to work as expected you should make sure that: + * - direction and the plane normal are normalized + * - epsilon is a number just bigger than -1, something like -0.99 for eg + * @param direction the direction to check if the plane is facing + * @param epsilon value the dot product is compared against (returns true if dot <= epsilon) + * @returns True if the plane is facing the given direction + */ + isFrontFacingTo(direction, epsilon) { + const dot = Vector3.Dot(this.normal, direction); + return dot <= epsilon; + } + /** + * Calculates the distance to a point + * @param point point to calculate distance to + * @returns the signed distance (float) from the given point to the Plane. + */ + signedDistanceTo(point) { + return Vector3.Dot(point, this.normal) + this.d; + } + // Statics + /** + * Creates a plane from an array + * @param array the array to create a plane from + * @returns a new Plane from the given array. + */ + static FromArray(array) { + return new Plane(array[0], array[1], array[2], array[3]); + } + /** + * Creates a plane from three points + * @param point1 point used to create the plane + * @param point2 point used to create the plane + * @param point3 point used to create the plane + * @returns a new Plane defined by the three given points. + */ + static FromPoints(point1, point2, point3) { + const result = new Plane(0.0, 0.0, 0.0, 0.0); + result.copyFromPoints(point1, point2, point3); + return result; + } + /** + * Creates a plane from an origin point and a normal + * @param origin origin of the plane to be constructed + * @param normal normal of the plane to be constructed + * @returns a new Plane the normal vector to this plane at the given origin point. + */ + static FromPositionAndNormal(origin, normal) { + const plane = new Plane(0.0, 0.0, 0.0, 0.0); + return this.FromPositionAndNormalToRef(origin, normal, plane); + } + /** + * Updates the given Plane "result" from an origin point and a normal. + * @param origin origin of the plane to be constructed + * @param normal the normalized normals of the plane to be constructed + * @param result defines the Plane where to store the result + * @returns result input + */ + static FromPositionAndNormalToRef(origin, normal, result) { + result.normal.copyFrom(normal); + result.normal.normalize(); + result.d = -origin.dot(result.normal); + return result; + } + /** + * Calculates the distance from a plane and a point + * @param origin origin of the plane to be constructed + * @param normal normal of the plane to be constructed + * @param point point to calculate distance to + * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point. + */ + static SignedDistanceToPlaneFromPositionAndNormal(origin, normal, point) { + const d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z); + return Vector3.Dot(point, normal) + d; + } +} +Plane._TmpMatrix = Matrix.Identity(); + +/** + * Represents a camera frustum + */ +class Frustum { + /** + * Gets the planes representing the frustum + * @param transform matrix to be applied to the returned planes + * @returns a new array of 6 Frustum planes computed by the given transformation matrix. + */ + static GetPlanes(transform) { + const frustumPlanes = []; + for (let index = 0; index < 6; index++) { + frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0)); + } + Frustum.GetPlanesToRef(transform, frustumPlanes); + return frustumPlanes; + } + /** + * Gets the near frustum plane transformed by the transform matrix + * @param transform transformation matrix to be applied to the resulting frustum plane + * @param frustumPlane the resulting frustum plane + */ + static GetNearPlaneToRef(transform, frustumPlane) { + const m = transform.m; + frustumPlane.normal.x = m[3] + m[2]; + frustumPlane.normal.y = m[7] + m[6]; + frustumPlane.normal.z = m[11] + m[10]; + frustumPlane.d = m[15] + m[14]; + frustumPlane.normalize(); + } + /** + * Gets the far frustum plane transformed by the transform matrix + * @param transform transformation matrix to be applied to the resulting frustum plane + * @param frustumPlane the resulting frustum plane + */ + static GetFarPlaneToRef(transform, frustumPlane) { + const m = transform.m; + frustumPlane.normal.x = m[3] - m[2]; + frustumPlane.normal.y = m[7] - m[6]; + frustumPlane.normal.z = m[11] - m[10]; + frustumPlane.d = m[15] - m[14]; + frustumPlane.normalize(); + } + /** + * Gets the left frustum plane transformed by the transform matrix + * @param transform transformation matrix to be applied to the resulting frustum plane + * @param frustumPlane the resulting frustum plane + */ + static GetLeftPlaneToRef(transform, frustumPlane) { + const m = transform.m; + frustumPlane.normal.x = m[3] + m[0]; + frustumPlane.normal.y = m[7] + m[4]; + frustumPlane.normal.z = m[11] + m[8]; + frustumPlane.d = m[15] + m[12]; + frustumPlane.normalize(); + } + /** + * Gets the right frustum plane transformed by the transform matrix + * @param transform transformation matrix to be applied to the resulting frustum plane + * @param frustumPlane the resulting frustum plane + */ + static GetRightPlaneToRef(transform, frustumPlane) { + const m = transform.m; + frustumPlane.normal.x = m[3] - m[0]; + frustumPlane.normal.y = m[7] - m[4]; + frustumPlane.normal.z = m[11] - m[8]; + frustumPlane.d = m[15] - m[12]; + frustumPlane.normalize(); + } + /** + * Gets the top frustum plane transformed by the transform matrix + * @param transform transformation matrix to be applied to the resulting frustum plane + * @param frustumPlane the resulting frustum plane + */ + static GetTopPlaneToRef(transform, frustumPlane) { + const m = transform.m; + frustumPlane.normal.x = m[3] - m[1]; + frustumPlane.normal.y = m[7] - m[5]; + frustumPlane.normal.z = m[11] - m[9]; + frustumPlane.d = m[15] - m[13]; + frustumPlane.normalize(); + } + /** + * Gets the bottom frustum plane transformed by the transform matrix + * @param transform transformation matrix to be applied to the resulting frustum plane + * @param frustumPlane the resulting frustum plane + */ + static GetBottomPlaneToRef(transform, frustumPlane) { + const m = transform.m; + frustumPlane.normal.x = m[3] + m[1]; + frustumPlane.normal.y = m[7] + m[5]; + frustumPlane.normal.z = m[11] + m[9]; + frustumPlane.d = m[15] + m[13]; + frustumPlane.normalize(); + } + /** + * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix. + * @param transform transformation matrix to be applied to the resulting frustum planes + * @param frustumPlanes the resulting frustum planes + */ + static GetPlanesToRef(transform, frustumPlanes) { + // Near + Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]); + // Far + Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]); + // Left + Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]); + // Right + Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]); + // Top + Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]); + // Bottom + Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]); + } + /** + * Tests if a point is located between the frustum planes. + * @param point defines the point to test + * @param frustumPlanes defines the frustum planes to test + * @returns true if the point is located between the frustum planes + */ + static IsPointInFrustum(point, frustumPlanes) { + for (let i = 0; i < 6; i++) { + if (frustumPlanes[i].dotCoordinate(point) < 0) { + return false; + } + } + return true; + } +} + +/** + * Defines potential orientation for back face culling + */ +var Orientation; +(function (Orientation) { + /** + * Clockwise + */ + Orientation[Orientation["CW"] = 0] = "CW"; + /** Counter clockwise */ + Orientation[Orientation["CCW"] = 1] = "CCW"; +})(Orientation || (Orientation = {})); +/** Class used to represent a Bezier curve */ +class BezierCurve { + /** + * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats + * @param t defines the time + * @param x1 defines the left coordinate on X axis + * @param y1 defines the left coordinate on Y axis + * @param x2 defines the right coordinate on X axis + * @param y2 defines the right coordinate on Y axis + * @returns the interpolated value + */ + static Interpolate(t, x1, y1, x2, y2) { + if (t === 0) { + return 0; + } + // Extract X (which is equal to time here) + const f0 = 1 - 3 * x2 + 3 * x1; + const f1 = 3 * x2 - 6 * x1; + const f2 = 3 * x1; + let refinedT = t; + for (let i = 0; i < 5; i++) { + const refinedT2 = refinedT * refinedT; + const refinedT3 = refinedT2 * refinedT; + const x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT; + const slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2); + refinedT -= (x - t) * slope; + refinedT = Math.min(1, Math.max(0, refinedT)); + } + // Resolve cubic bezier for the given x + return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3); + } +} +/** + * Defines angle representation + */ +class Angle { + /** + * Creates an Angle object of "radians" radians (float). + * @param radians the angle in radians + */ + constructor(radians) { + this._radians = radians; + if (this._radians < 0.0) { + this._radians += 2.0 * Math.PI; + } + } + /** + * Get value in degrees + * @returns the Angle value in degrees (float) + */ + degrees() { + return (this._radians * 180.0) / Math.PI; + } + /** + * Get value in radians + * @returns the Angle value in radians (float) + */ + radians() { + return this._radians; + } + /** + * Gets a new Angle object with a value of the angle (in radians) between the line connecting the two points and the x-axis + * @param a defines first point as the origin + * @param b defines point + * @returns a new Angle + */ + static BetweenTwoPoints(a, b) { + const delta = b.subtract(a); + const theta = Math.atan2(delta.y, delta.x); + return new Angle(theta); + } + /** + * Gets the angle between the two vectors + * @param a defines first vector + * @param b defines vector + * @returns Returns an new Angle between 0 and PI + */ + static BetweenTwoVectors(a, b) { + let product = a.lengthSquared() * b.lengthSquared(); + if (product === 0) + return new Angle(Math.PI / 2); + product = Math.sqrt(product); + let cosVal = a.dot(b) / product; + cosVal = Clamp(cosVal, -1, 1); + const angle = Math.acos(cosVal); + return new Angle(angle); + } + /** + * Gets a new Angle object from the given float in radians + * @param radians defines the angle value in radians + * @returns a new Angle + */ + static FromRadians(radians) { + return new Angle(radians); + } + /** + * Gets a new Angle object from the given float in degrees + * @param degrees defines the angle value in degrees + * @returns a new Angle + */ + static FromDegrees(degrees) { + return new Angle((degrees * Math.PI) / 180.0); + } +} +/** + * This represents an arc in a 2d space. + */ +class Arc2 { + /** + * Creates an Arc object from the three given points : start, middle and end. + * @param startPoint Defines the start point of the arc + * @param midPoint Defines the middle point of the arc + * @param endPoint Defines the end point of the arc + */ + constructor( + /** Defines the start point of the arc */ + startPoint, + /** Defines the mid point of the arc */ + midPoint, + /** Defines the end point of the arc */ + endPoint) { + this.startPoint = startPoint; + this.midPoint = midPoint; + this.endPoint = endPoint; + const temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2); + const startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2; + const midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2; + const det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y); + this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det); + this.radius = this.centerPoint.subtract(this.startPoint).length(); + this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint); + const a1 = this.startAngle.degrees(); + let a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees(); + let a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees(); + // angles correction + if (a2 - a1 > 180) { + a2 -= 360.0; + } + if (a2 - a1 < -180) { + a2 += 360.0; + } + if (a3 - a2 > 180) { + a3 -= 360.0; + } + if (a3 - a2 < -180) { + a3 += 360.0; + } + this.orientation = a2 - a1 < 0 ? 0 /* Orientation.CW */ : 1 /* Orientation.CCW */; + this.angle = Angle.FromDegrees(this.orientation === 0 /* Orientation.CW */ ? a1 - a3 : a3 - a1); + } +} +/** + * Represents a 2D path made up of multiple 2D points + */ +class Path2 { + /** + * Creates a Path2 object from the starting 2D coordinates x and y. + * @param x the starting points x value + * @param y the starting points y value + */ + constructor(x, y) { + this._points = new Array(); + this._length = 0.0; + /** + * If the path start and end point are the same + */ + this.closed = false; + this._points.push(new Vector2(x, y)); + } + /** + * Adds a new segment until the given coordinates (x, y) to the current Path2. + * @param x the added points x value + * @param y the added points y value + * @returns the updated Path2. + */ + addLineTo(x, y) { + if (this.closed) { + return this; + } + const newPoint = new Vector2(x, y); + const previousPoint = this._points[this._points.length - 1]; + this._points.push(newPoint); + this._length += newPoint.subtract(previousPoint).length(); + return this; + } + /** + * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2. + * @param midX middle point x value + * @param midY middle point y value + * @param endX end point x value + * @param endY end point y value + * @param numberOfSegments (default: 36) + * @returns the updated Path2. + */ + addArcTo(midX, midY, endX, endY, numberOfSegments = 36) { + if (this.closed) { + return this; + } + const startPoint = this._points[this._points.length - 1]; + const midPoint = new Vector2(midX, midY); + const endPoint = new Vector2(endX, endY); + const arc = new Arc2(startPoint, midPoint, endPoint); + let increment = arc.angle.radians() / numberOfSegments; + if (arc.orientation === 0 /* Orientation.CW */) { + increment *= -1; + } + let currentAngle = arc.startAngle.radians() + increment; + for (let i = 0; i < numberOfSegments; i++) { + const x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x; + const y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y; + this.addLineTo(x, y); + currentAngle += increment; + } + return this; + } + /** + * Adds _numberOfSegments_ segments according to the quadratic curve definition to the current Path2. + * @param controlX control point x value + * @param controlY control point y value + * @param endX end point x value + * @param endY end point y value + * @param numberOfSegments (default: 36) + * @returns the updated Path2. + */ + addQuadraticCurveTo(controlX, controlY, endX, endY, numberOfSegments = 36) { + if (this.closed) { + return this; + } + const equation = (t, val0, val1, val2) => { + const res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2; + return res; + }; + const startPoint = this._points[this._points.length - 1]; + for (let i = 0; i <= numberOfSegments; i++) { + const step = i / numberOfSegments; + const x = equation(step, startPoint.x, controlX, endX); + const y = equation(step, startPoint.y, controlY, endY); + this.addLineTo(x, y); + } + return this; + } + /** + * Adds _numberOfSegments_ segments according to the bezier curve definition to the current Path2. + * @param originTangentX tangent vector at the origin point x value + * @param originTangentY tangent vector at the origin point y value + * @param destinationTangentX tangent vector at the destination point x value + * @param destinationTangentY tangent vector at the destination point y value + * @param endX end point x value + * @param endY end point y value + * @param numberOfSegments (default: 36) + * @returns the updated Path2. + */ + addBezierCurveTo(originTangentX, originTangentY, destinationTangentX, destinationTangentY, endX, endY, numberOfSegments = 36) { + if (this.closed) { + return this; + } + const equation = (t, val0, val1, val2, val3) => { + const res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3; + return res; + }; + const startPoint = this._points[this._points.length - 1]; + for (let i = 0; i <= numberOfSegments; i++) { + const step = i / numberOfSegments; + const x = equation(step, startPoint.x, originTangentX, destinationTangentX, endX); + const y = equation(step, startPoint.y, originTangentY, destinationTangentY, endY); + this.addLineTo(x, y); + } + return this; + } + /** + * Defines if a given point is inside the polygon defines by the path + * @param point defines the point to test + * @returns true if the point is inside + */ + isPointInside(point) { + let isInside = false; + const count = this._points.length; + for (let p = count - 1, q = 0; q < count; p = q++) { + let edgeLow = this._points[p]; + let edgeHigh = this._points[q]; + let edgeDx = edgeHigh.x - edgeLow.x; + let edgeDy = edgeHigh.y - edgeLow.y; + if (Math.abs(edgeDy) > Number.EPSILON) { + // Not parallel + if (edgeDy < 0) { + edgeLow = this._points[q]; + edgeDx = -edgeDx; + edgeHigh = this._points[p]; + edgeDy = -edgeDy; + } + if (point.y < edgeLow.y || point.y > edgeHigh.y) { + continue; + } + if (point.y === edgeLow.y && point.x === edgeLow.x) { + return true; + } + else { + const perpEdge = edgeDy * (point.x - edgeLow.x) - edgeDx * (point.y - edgeLow.y); + if (perpEdge === 0) { + return true; + } + if (perpEdge < 0) { + continue; + } + isInside = !isInside; + } + } + else { + // parallel or collinear + if (point.y !== edgeLow.y) { + continue; + } + if ((edgeHigh.x <= point.x && point.x <= edgeLow.x) || (edgeLow.x <= point.x && point.x <= edgeHigh.x)) { + return true; + } + } + } + return isInside; + } + /** + * Closes the Path2. + * @returns the Path2. + */ + close() { + this.closed = true; + return this; + } + /** + * Gets the sum of the distance between each sequential point in the path + * @returns the Path2 total length (float). + */ + length() { + let result = this._length; + if (this.closed) { + const lastPoint = this._points[this._points.length - 1]; + const firstPoint = this._points[0]; + result += firstPoint.subtract(lastPoint).length(); + } + return result; + } + /** + * Gets the area of the polygon defined by the path + * @returns area value + */ + area() { + const n = this._points.length; + let value = 0.0; + for (let p = n - 1, q = 0; q < n; p = q++) { + value += this._points[p].x * this._points[q].y - this._points[q].x * this._points[p].y; + } + return value * 0.5; + } + /** + * Gets the points which construct the path + * @returns the Path2 internal array of points. + */ + getPoints() { + return this._points; + } + /** + * Retrieves the point at the distance aways from the starting point + * @param normalizedLengthPosition the length along the path to retrieve the point from + * @returns a new Vector2 located at a percentage of the Path2 total length on this path. + */ + getPointAtLengthPosition(normalizedLengthPosition) { + if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) { + return Vector2.Zero(); + } + const lengthPosition = normalizedLengthPosition * this.length(); + let previousOffset = 0; + for (let i = 0; i < this._points.length; i++) { + const j = (i + 1) % this._points.length; + const a = this._points[i]; + const b = this._points[j]; + const bToA = b.subtract(a); + const nextOffset = bToA.length() + previousOffset; + if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) { + const dir = bToA.normalize(); + const localOffset = lengthPosition - previousOffset; + return new Vector2(a.x + dir.x * localOffset, a.y + dir.y * localOffset); + } + previousOffset = nextOffset; + } + return Vector2.Zero(); + } + /** + * Creates a new path starting from an x and y position + * @param x starting x value + * @param y starting y value + * @returns a new Path2 starting at the coordinates (x, y). + */ + static StartingAt(x, y) { + return new Path2(x, y); + } +} +/** + * Represents a 3D path made up of multiple 3D points + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D + */ +class Path3D { + /** + * new Path3D(path, normal, raw) + * Creates a Path3D. A Path3D is a logical math object, so not a mesh. + * please read the description in the tutorial : https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D + * @param path an array of Vector3, the curve axis of the Path3D + * @param firstNormal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal. + * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed. + * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path. + */ + constructor( + /** + * an array of Vector3, the curve axis of the Path3D + */ + path, firstNormal = null, raw, alignTangentsWithPath = false) { + this.path = path; + this._curve = new Array(); + this._distances = new Array(); + this._tangents = new Array(); + this._normals = new Array(); + this._binormals = new Array(); + // holds interpolated point data + this._pointAtData = { + id: 0, + point: Vector3.Zero(), + previousPointArrayIndex: 0, + position: 0, + subPosition: 0, + interpolateReady: false, + interpolationMatrix: Matrix.Identity(), + }; + for (let p = 0; p < path.length; p++) { + this._curve[p] = path[p].clone(); // hard copy + } + this._raw = raw || false; + this._alignTangentsWithPath = alignTangentsWithPath; + this._compute(firstNormal, alignTangentsWithPath); + } + /** + * Returns the Path3D array of successive Vector3 designing its curve. + * @returns the Path3D array of successive Vector3 designing its curve. + */ + getCurve() { + return this._curve; + } + /** + * Returns the Path3D array of successive Vector3 designing its curve. + * @returns the Path3D array of successive Vector3 designing its curve. + */ + getPoints() { + return this._curve; + } + /** + * @returns the computed length (float) of the path. + */ + length() { + return this._distances[this._distances.length - 1]; + } + /** + * Returns an array populated with tangent vectors on each Path3D curve point. + * @returns an array populated with tangent vectors on each Path3D curve point. + */ + getTangents() { + return this._tangents; + } + /** + * Returns an array populated with normal vectors on each Path3D curve point. + * @returns an array populated with normal vectors on each Path3D curve point. + */ + getNormals() { + return this._normals; + } + /** + * Returns an array populated with binormal vectors on each Path3D curve point. + * @returns an array populated with binormal vectors on each Path3D curve point. + */ + getBinormals() { + return this._binormals; + } + /** + * Returns an array populated with distances (float) of the i-th point from the first curve point. + * @returns an array populated with distances (float) of the i-th point from the first curve point. + */ + getDistances() { + return this._distances; + } + /** + * Returns an interpolated point along this path + * @param position the position of the point along this path, from 0.0 to 1.0 + * @returns a new Vector3 as the point + */ + getPointAt(position) { + return this._updatePointAtData(position).point; + } + /** + * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path. + * @param position the position of the point along this path, from 0.0 to 1.0 + * @param interpolated (optional, default false) : boolean, if true returns an interpolated tangent instead of the tangent of the previous path point. + * @returns a tangent vector corresponding to the interpolated Path3D curve point, if not interpolated, the tangent is taken from the precomputed tangents array. + */ + getTangentAt(position, interpolated = false) { + this._updatePointAtData(position, interpolated); + return interpolated ? Vector3.TransformCoordinates(Vector3.Forward(), this._pointAtData.interpolationMatrix) : this._tangents[this._pointAtData.previousPointArrayIndex]; + } + /** + * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path. + * @param position the position of the point along this path, from 0.0 to 1.0 + * @param interpolated (optional, default false) : boolean, if true returns an interpolated normal instead of the normal of the previous path point. + * @returns a normal vector corresponding to the interpolated Path3D curve point, if not interpolated, the normal is taken from the precomputed normals array. + */ + getNormalAt(position, interpolated = false) { + this._updatePointAtData(position, interpolated); + return interpolated ? Vector3.TransformCoordinates(Vector3.Right(), this._pointAtData.interpolationMatrix) : this._normals[this._pointAtData.previousPointArrayIndex]; + } + /** + * Returns the binormal vector of an interpolated Path3D curve point at the specified position along this path. + * @param position the position of the point along this path, from 0.0 to 1.0 + * @param interpolated (optional, default false) : boolean, if true returns an interpolated binormal instead of the binormal of the previous path point. + * @returns a binormal vector corresponding to the interpolated Path3D curve point, if not interpolated, the binormal is taken from the precomputed binormals array. + */ + getBinormalAt(position, interpolated = false) { + this._updatePointAtData(position, interpolated); + return interpolated ? Vector3.TransformCoordinates(Vector3.UpReadOnly, this._pointAtData.interpolationMatrix) : this._binormals[this._pointAtData.previousPointArrayIndex]; + } + /** + * Returns the distance (float) of an interpolated Path3D curve point at the specified position along this path. + * @param position the position of the point along this path, from 0.0 to 1.0 + * @returns the distance of the interpolated Path3D curve point at the specified position along this path. + */ + getDistanceAt(position) { + return this.length() * position; + } + /** + * Returns the array index of the previous point of an interpolated point along this path + * @param position the position of the point to interpolate along this path, from 0.0 to 1.0 + * @returns the array index + */ + getPreviousPointIndexAt(position) { + this._updatePointAtData(position); + return this._pointAtData.previousPointArrayIndex; + } + /** + * Returns the position of an interpolated point relative to the two path points it lies between, from 0.0 (point A) to 1.0 (point B) + * @param position the position of the point to interpolate along this path, from 0.0 to 1.0 + * @returns the sub position + */ + getSubPositionAt(position) { + this._updatePointAtData(position); + return this._pointAtData.subPosition; + } + /** + * Returns the position of the closest virtual point on this path to an arbitrary Vector3, from 0.0 to 1.0 + * @param target the vector of which to get the closest position to + * @returns the position of the closest virtual point on this path to the target vector + */ + getClosestPositionTo(target) { + let smallestDistance = Number.MAX_VALUE; + let closestPosition = 0.0; + for (let i = 0; i < this._curve.length - 1; i++) { + const point = this._curve[i + 0]; + const tangent = this._curve[i + 1].subtract(point).normalize(); + const subLength = this._distances[i + 1] - this._distances[i + 0]; + const subPosition = Math.min((Math.max(Vector3.Dot(tangent, target.subtract(point).normalize()), 0.0) * Vector3.Distance(point, target)) / subLength, 1.0); + const distance = Vector3.Distance(point.add(tangent.scale(subPosition * subLength)), target); + if (distance < smallestDistance) { + smallestDistance = distance; + closestPosition = (this._distances[i + 0] + subLength * subPosition) / this.length(); + } + } + return closestPosition; + } + /** + * Returns a sub path (slice) of this path + * @param start the position of the fist path point, from 0.0 to 1.0, or a negative value, which will get wrapped around from the end of the path to 0.0 to 1.0 values + * @param end the position of the last path point, from 0.0 to 1.0, or a negative value, which will get wrapped around from the end of the path to 0.0 to 1.0 values + * @returns a sub path (slice) of this path + */ + slice(start = 0.0, end = 1.0) { + if (start < 0.0) { + start = 1 - ((start * -1) % 1.0); + } + if (end < 0.0) { + end = 1 - ((end * -1) % 1.0); + } + if (start > end) { + const _start = start; + start = end; + end = _start; + } + const curvePoints = this.getCurve(); + const startPoint = this.getPointAt(start); + let startIndex = this.getPreviousPointIndexAt(start); + const endPoint = this.getPointAt(end); + const endIndex = this.getPreviousPointIndexAt(end) + 1; + const slicePoints = []; + if (start !== 0.0) { + startIndex++; + slicePoints.push(startPoint); + } + slicePoints.push(...curvePoints.slice(startIndex, endIndex)); + if (end !== 1.0 || start === 1.0) { + slicePoints.push(endPoint); + } + return new Path3D(slicePoints, this.getNormalAt(start), this._raw, this._alignTangentsWithPath); + } + /** + * Forces the Path3D tangent, normal, binormal and distance recomputation. + * @param path path which all values are copied into the curves points + * @param firstNormal which should be projected onto the curve + * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path + * @returns the same object updated. + */ + update(path, firstNormal = null, alignTangentsWithPath = false) { + for (let p = 0; p < path.length; p++) { + this._curve[p].x = path[p].x; + this._curve[p].y = path[p].y; + this._curve[p].z = path[p].z; + } + this._compute(firstNormal, alignTangentsWithPath); + return this; + } + // private function compute() : computes tangents, normals and binormals + _compute(firstNormal, alignTangentsWithPath = false) { + const l = this._curve.length; + if (l < 2) { + return; + } + // first and last tangents + this._tangents[0] = this._getFirstNonNullVector(0); + if (!this._raw) { + this._tangents[0].normalize(); + } + this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]); + if (!this._raw) { + this._tangents[l - 1].normalize(); + } + // normals and binormals at first point : arbitrary vector with _normalVector() + const tg0 = this._tangents[0]; + const pp0 = this._normalVector(tg0, firstNormal); + this._normals[0] = pp0; + if (!this._raw) { + this._normals[0].normalize(); + } + this._binormals[0] = Vector3.Cross(tg0, this._normals[0]); + if (!this._raw) { + this._binormals[0].normalize(); + } + this._distances[0] = 0.0; + // normals and binormals : next points + let prev; // previous vector (segment) + let cur; // current vector (segment) + let curTang; // current tangent + // previous normal + let prevNor; // previous normal + let prevBinor; // previous binormal + for (let i = 1; i < l; i++) { + // tangents + prev = this._getLastNonNullVector(i); + if (i < l - 1) { + cur = this._getFirstNonNullVector(i); + this._tangents[i] = alignTangentsWithPath ? cur : prev.add(cur); + this._tangents[i].normalize(); + } + this._distances[i] = this._distances[i - 1] + this._curve[i].subtract(this._curve[i - 1]).length(); + // normals and binormals + // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html + curTang = this._tangents[i]; + prevBinor = this._binormals[i - 1]; + this._normals[i] = Vector3.Cross(prevBinor, curTang); + if (!this._raw) { + if (this._normals[i].length() === 0) { + prevNor = this._normals[i - 1]; + this._normals[i] = prevNor.clone(); + } + else { + this._normals[i].normalize(); + } + } + this._binormals[i] = Vector3.Cross(curTang, this._normals[i]); + if (!this._raw) { + this._binormals[i].normalize(); + } + } + this._pointAtData.id = NaN; + } + // private function getFirstNonNullVector(index) + // returns the first non null vector from index : curve[index + N].subtract(curve[index]) + _getFirstNonNullVector(index) { + let i = 1; + let nNVector = this._curve[index + i].subtract(this._curve[index]); + while (nNVector.length() === 0 && index + i + 1 < this._curve.length) { + i++; + nNVector = this._curve[index + i].subtract(this._curve[index]); + } + return nNVector; + } + // private function getLastNonNullVector(index) + // returns the last non null vector from index : curve[index].subtract(curve[index - N]) + _getLastNonNullVector(index) { + let i = 1; + let nLVector = this._curve[index].subtract(this._curve[index - i]); + while (nLVector.length() === 0 && index > i + 1) { + i++; + nLVector = this._curve[index].subtract(this._curve[index - i]); + } + return nLVector; + } + // private function normalVector(v0, vt, va) : + // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane + // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0 + _normalVector(vt, va) { + let normal0; + let tgl = vt.length(); + if (tgl === 0.0) { + tgl = 1.0; + } + if (va === undefined || va === null) { + let point; + if (!WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, Epsilon)) { + // search for a point in the plane + point = new Vector3(0.0, -1, 0.0); + } + else if (!WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, Epsilon)) { + point = new Vector3(1.0, 0.0, 0.0); + } + else if (!WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, Epsilon)) { + point = new Vector3(0.0, 0.0, 1.0); + } + else { + point = Vector3.Zero(); + } + normal0 = Vector3.Cross(vt, point); + } + else { + normal0 = Vector3.Cross(vt, va); + Vector3.CrossToRef(normal0, vt, normal0); + } + normal0.normalize(); + return normal0; + } + /** + * Updates the point at data for an interpolated point along this curve + * @param position the position of the point along this curve, from 0.0 to 1.0 + * @param interpolateTNB + * @interpolateTNB whether to compute the interpolated tangent, normal and binormal + * @returns the (updated) point at data + */ + _updatePointAtData(position, interpolateTNB = false) { + // set an id for caching the result + if (this._pointAtData.id === position) { + if (!this._pointAtData.interpolateReady) { + this._updateInterpolationMatrix(); + } + return this._pointAtData; + } + else { + this._pointAtData.id = position; + } + const curvePoints = this.getPoints(); + // clamp position between 0.0 and 1.0 + if (position <= 0.0) { + return this._setPointAtData(0.0, 0.0, curvePoints[0], 0, interpolateTNB); + } + else if (position >= 1.0) { + return this._setPointAtData(1.0, 1.0, curvePoints[curvePoints.length - 1], curvePoints.length - 1, interpolateTNB); + } + let previousPoint = curvePoints[0]; + let currentPoint; + let currentLength = 0.0; + const targetLength = position * this.length(); + for (let i = 1; i < curvePoints.length; i++) { + currentPoint = curvePoints[i]; + const distance = Vector3.Distance(previousPoint, currentPoint); + currentLength += distance; + if (currentLength === targetLength) { + return this._setPointAtData(position, 1.0, currentPoint, i, interpolateTNB); + } + else if (currentLength > targetLength) { + const toLength = currentLength - targetLength; + const diff = toLength / distance; + const dir = previousPoint.subtract(currentPoint); + const point = currentPoint.add(dir.scaleInPlace(diff)); + return this._setPointAtData(position, 1 - diff, point, i - 1, interpolateTNB); + } + previousPoint = currentPoint; + } + return this._pointAtData; + } + /** + * Updates the point at data from the specified parameters + * @param position where along the path the interpolated point is, from 0.0 to 1.0 + * @param subPosition + * @param point the interpolated point + * @param parentIndex the index of an existing curve point that is on, or else positionally the first behind, the interpolated point + * @param interpolateTNB whether to compute the interpolated tangent, normal and binormal + * @returns the (updated) point at data + */ + _setPointAtData(position, subPosition, point, parentIndex, interpolateTNB) { + this._pointAtData.point = point; + this._pointAtData.position = position; + this._pointAtData.subPosition = subPosition; + this._pointAtData.previousPointArrayIndex = parentIndex; + this._pointAtData.interpolateReady = interpolateTNB; + if (interpolateTNB) { + this._updateInterpolationMatrix(); + } + return this._pointAtData; + } + /** + * Updates the point at interpolation matrix for the tangents, normals and binormals + */ + _updateInterpolationMatrix() { + this._pointAtData.interpolationMatrix = Matrix.Identity(); + const parentIndex = this._pointAtData.previousPointArrayIndex; + if (parentIndex !== this._tangents.length - 1) { + const index = parentIndex + 1; + const tangentFrom = this._tangents[parentIndex].clone(); + const normalFrom = this._normals[parentIndex].clone(); + const binormalFrom = this._binormals[parentIndex].clone(); + const tangentTo = this._tangents[index].clone(); + const normalTo = this._normals[index].clone(); + const binormalTo = this._binormals[index].clone(); + const quatFrom = Quaternion.RotationQuaternionFromAxis(normalFrom, binormalFrom, tangentFrom); + const quatTo = Quaternion.RotationQuaternionFromAxis(normalTo, binormalTo, tangentTo); + const quatAt = Quaternion.Slerp(quatFrom, quatTo, this._pointAtData.subPosition); + quatAt.toRotationMatrix(this._pointAtData.interpolationMatrix); + } + } +} +/** + * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space. + * A Curve3 is designed from a series of successive Vector3. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves + */ +class Curve3 { + /** + * Returns a Curve3 object along a Quadratic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#quadratic-bezier-curve + * @param v0 (Vector3) the origin point of the Quadratic Bezier + * @param v1 (Vector3) the control point + * @param v2 (Vector3) the end point of the Quadratic Bezier + * @param nbPoints (integer) the wanted number of points in the curve + * @returns the created Curve3 + */ + static CreateQuadraticBezier(v0, v1, v2, nbPoints) { + nbPoints = nbPoints > 2 ? nbPoints : 3; + const bez = []; + const equation = (t, val0, val1, val2) => { + const res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2; + return res; + }; + for (let i = 0; i <= nbPoints; i++) { + bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z))); + } + return new Curve3(bez); + } + /** + * Returns a Curve3 object along a Cubic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#cubic-bezier-curve + * @param v0 (Vector3) the origin point of the Cubic Bezier + * @param v1 (Vector3) the first control point + * @param v2 (Vector3) the second control point + * @param v3 (Vector3) the end point of the Cubic Bezier + * @param nbPoints (integer) the wanted number of points in the curve + * @returns the created Curve3 + */ + static CreateCubicBezier(v0, v1, v2, v3, nbPoints) { + nbPoints = nbPoints > 3 ? nbPoints : 4; + const bez = []; + const equation = (t, val0, val1, val2, val3) => { + const res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3; + return res; + }; + for (let i = 0; i <= nbPoints; i++) { + bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z))); + } + return new Curve3(bez); + } + /** + * Returns a Curve3 object along a Hermite Spline curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#hermite-spline + * @param p1 (Vector3) the origin point of the Hermite Spline + * @param t1 (Vector3) the tangent vector at the origin point + * @param p2 (Vector3) the end point of the Hermite Spline + * @param t2 (Vector3) the tangent vector at the end point + * @param nSeg (integer) the number of curve segments or nSeg + 1 points in the array + * @returns the created Curve3 + */ + static CreateHermiteSpline(p1, t1, p2, t2, nSeg) { + const hermite = []; + const step = 1.0 / nSeg; + for (let i = 0; i <= nSeg; i++) { + hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step)); + } + return new Curve3(hermite); + } + /** + * Returns a Curve3 object along a CatmullRom Spline curve : + * @param points (array of Vector3) the points the spline must pass through. At least, four points required + * @param nbPoints (integer) the wanted number of points between each curve control points + * @param closed (boolean) optional with default false, when true forms a closed loop from the points + * @returns the created Curve3 + */ + static CreateCatmullRomSpline(points, nbPoints, closed) { + const catmullRom = []; + const step = 1.0 / nbPoints; + let amount = 0.0; + if (closed) { + const pointsCount = points.length; + for (let i = 0; i < pointsCount; i++) { + amount = 0; + for (let c = 0; c < nbPoints; c++) { + catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount)); + amount += step; + } + } + catmullRom.push(catmullRom[0]); + } + else { + const totalPoints = []; + totalPoints.push(points[0].clone()); + Array.prototype.push.apply(totalPoints, points); + totalPoints.push(points[points.length - 1].clone()); + let i = 0; + for (; i < totalPoints.length - 3; i++) { + amount = 0; + for (let c = 0; c < nbPoints; c++) { + catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount)); + amount += step; + } + } + i--; + catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount)); + } + return new Curve3(catmullRom); + } + /** + * Returns a Curve3 object along an arc through three vector3 points: + * The three points should not be colinear. When they are the Curve3 is empty. + * @param first (Vector3) the first point the arc must pass through. + * @param second (Vector3) the second point the arc must pass through. + * @param third (Vector3) the third point the arc must pass through. + * @param steps (number) the larger the number of steps the more detailed the arc. + * @param closed (boolean) optional with default false, when true forms the chord from the first and third point + * @param fullCircle Circle (boolean) optional with default false, when true forms the complete circle through the three points + * @returns the created Curve3 + */ + static ArcThru3Points(first, second, third, steps = 32, closed = false, fullCircle = false) { + const arc = []; + const vec1 = second.subtract(first); + const vec2 = third.subtract(second); + const vec3 = first.subtract(third); + const zAxis = Vector3.Cross(vec1, vec2); + const len4 = zAxis.length(); + if (len4 < Math.pow(10, -8)) { + return new Curve3(arc); // colinear points arc is empty + } + const len1_sq = vec1.lengthSquared(); + const len2_sq = vec2.lengthSquared(); + const len3_sq = vec3.lengthSquared(); + const len4_sq = zAxis.lengthSquared(); + const len1 = vec1.length(); + const len2 = vec2.length(); + const len3 = vec3.length(); + const radius = (0.5 * len1 * len2 * len3) / len4; + const dot1 = Vector3.Dot(vec1, vec3); + const dot2 = Vector3.Dot(vec1, vec2); + const dot3 = Vector3.Dot(vec2, vec3); + const a = (-0.5 * len2_sq * dot1) / len4_sq; + const b = (-0.5 * len3_sq * dot2) / len4_sq; + const c = (-0.5 * len1_sq * dot3) / len4_sq; + const center = first.scale(a).add(second.scale(b)).add(third.scale(c)); + const radiusVec = first.subtract(center); + const xAxis = radiusVec.normalize(); + const yAxis = Vector3.Cross(zAxis, xAxis).normalize(); + if (fullCircle) { + const dStep = (2 * Math.PI) / steps; + for (let theta = 0; theta <= 2 * Math.PI; theta += dStep) { + arc.push(center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta))))); + } + arc.push(first); + } + else { + const dStep = 1 / steps; + let theta = 0; + let point = Vector3.Zero(); + do { + point = center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta)))); + arc.push(point); + theta += dStep; + } while (!point.equalsWithEpsilon(third, radius * dStep * 1.1)); + arc.push(third); + if (closed) { + arc.push(first); + } + } + return new Curve3(arc); + } + /** + * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space. + * A Curve3 is designed from a series of successive Vector3. + * Tuto : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#curve3-object + * @param points points which make up the curve + */ + constructor(points) { + this._length = 0.0; + this._points = points; + this._length = this._computeLength(points); + } + /** + * @returns the Curve3 stored array of successive Vector3 + */ + getPoints() { + return this._points; + } + /** + * @returns the computed length (float) of the curve. + */ + length() { + return this._length; + } + /** + * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB); + * This new Curve3 is built by translating and sticking the curveB at the end of the curveA. + * curveA and curveB keep unchanged. + * @param curve the curve to continue from this curve + * @returns the newly constructed curve + */ + continue(curve) { + const lastPoint = this._points[this._points.length - 1]; + const continuedPoints = this._points.slice(); + const curvePoints = curve.getPoints(); + for (let i = 1; i < curvePoints.length; i++) { + continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint)); + } + const continuedCurve = new Curve3(continuedPoints); + return continuedCurve; + } + _computeLength(path) { + let l = 0; + for (let i = 1; i < path.length; i++) { + l += path[i].subtract(path[i - 1]).length(); + } + return l; + } +} + +/** + * Size containing width and height + */ +class Size { + /** + * Creates a Size object from the given width and height (floats). + * @param width width of the new size + * @param height height of the new size + */ + constructor(width, height) { + this.width = width; + this.height = height; + } + /** + * Returns a string with the Size width and height + * @returns a string with the Size width and height + */ + toString() { + return `{W: ${this.width}, H: ${this.height}}`; + } + /** + * "Size" + * @returns the string "Size" + */ + getClassName() { + return "Size"; + } + /** + * Returns the Size hash code. + * @returns a hash code for a unique width and height + */ + getHashCode() { + let hash = this.width | 0; + hash = (hash * 397) ^ (this.height | 0); + return hash; + } + /** + * Updates the current size from the given one. + * @param src the given size + */ + copyFrom(src) { + this.width = src.width; + this.height = src.height; + } + /** + * Updates in place the current Size from the given floats. + * @param width width of the new size + * @param height height of the new size + * @returns the updated Size. + */ + copyFromFloats(width, height) { + this.width = width; + this.height = height; + return this; + } + /** + * Updates in place the current Size from the given floats. + * @param width width to set + * @param height height to set + * @returns the updated Size. + */ + set(width, height) { + return this.copyFromFloats(width, height); + } + /** + * Multiplies the width and height by numbers + * @param w factor to multiple the width by + * @param h factor to multiple the height by + * @returns a new Size set with the multiplication result of the current Size and the given floats. + */ + multiplyByFloats(w, h) { + return new Size(this.width * w, this.height * h); + } + /** + * Clones the size + * @returns a new Size copied from the given one. + */ + clone() { + return new Size(this.width, this.height); + } + /** + * True if the current Size and the given one width and height are strictly equal. + * @param other the other size to compare against + * @returns True if the current Size and the given one width and height are strictly equal. + */ + equals(other) { + if (!other) { + return false; + } + return this.width === other.width && this.height === other.height; + } + /** + * The surface of the Size : width * height (float). + */ + get surface() { + return this.width * this.height; + } + /** + * Create a new size of zero + * @returns a new Size set to (0.0, 0.0) + */ + static Zero() { + return new Size(0.0, 0.0); + } + /** + * Sums the width and height of two sizes + * @param otherSize size to add to this size + * @returns a new Size set as the addition result of the current Size and the given one. + */ + add(otherSize) { + const r = new Size(this.width + otherSize.width, this.height + otherSize.height); + return r; + } + /** + * Subtracts the width and height of two + * @param otherSize size to subtract to this size + * @returns a new Size set as the subtraction result of the given one from the current Size. + */ + subtract(otherSize) { + const r = new Size(this.width - otherSize.width, this.height - otherSize.height); + return r; + } + /** + * Scales the width and height + * @param scale the scale to multiply the width and height by + * @returns a new Size set with the multiplication result of the current Size and the given floats. + */ + scale(scale) { + return new Size(this.width * scale, this.height * scale); + } + /** + * Creates a new Size set at the linear interpolation "amount" between "start" and "end" + * @param start starting size to lerp between + * @param end end size to lerp between + * @param amount amount to lerp between the start and end values + * @returns a new Size set at the linear interpolation "amount" between "start" and "end" + */ + static Lerp(start, end, amount) { + const w = start.width + (end.width - start.width) * amount; + const h = start.height + (end.height - start.height) * amount; + return new Size(w, h); + } +} + +/** + * Class used to represent a viewport on screen + */ +class Viewport { + /** + * Creates a Viewport object located at (x, y) and sized (width, height) + * @param x defines viewport left coordinate + * @param y defines viewport top coordinate + * @param width defines the viewport width + * @param height defines the viewport height + */ + constructor( + /** viewport left coordinate */ + x, + /** viewport top coordinate */ + y, + /**viewport width */ + width, + /** viewport height */ + height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + /** + * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1) + * @param renderWidth defines the rendering width + * @param renderHeight defines the rendering height + * @returns a new Viewport + */ + toGlobal(renderWidth, renderHeight) { + return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight); + } + /** + * Stores absolute viewport value into a target viewport (from 0-> width, 0-> height instead of 0->1) + * @param renderWidth defines the rendering width + * @param renderHeight defines the rendering height + * @param ref defines the target viewport + * @returns the current viewport + */ + toGlobalToRef(renderWidth, renderHeight, ref) { + ref.x = this.x * renderWidth; + ref.y = this.y * renderHeight; + ref.width = this.width * renderWidth; + ref.height = this.height * renderHeight; + return this; + } + /** + * Returns a new Viewport copied from the current one + * @returns a new Viewport + */ + clone() { + return new Viewport(this.x, this.y, this.width, this.height); + } +} + +/* eslint-disable @typescript-eslint/naming-convention */ +// https://dickyjim.wordpress.com/2013/09/04/spherical-harmonics-for-beginners/ +// http://silviojemma.com/public/papers/lighting/spherical-harmonic-lighting.pdf +// https://www.ppsloan.org/publications/StupidSH36.pdf +// http://cseweb.ucsd.edu/~ravir/papers/envmap/envmap.pdf +// https://www.ppsloan.org/publications/SHJCGT.pdf +// https://www.ppsloan.org/publications/shdering.pdf +// https://google.github.io/filament/Filament.md.html#annex/sphericalharmonics +// https://patapom.com/blog/SHPortal/ +// https://imdoingitwrong.wordpress.com/2011/04/14/spherical-harmonics-wtf/ +// Using real SH basis: +// m>0 m m +// y = sqrt(2) * K * P * cos(m*phi) * cos(theta) +// l l l +// +// m<0 m |m| +// y = sqrt(2) * K * P * sin(m*phi) * cos(theta) +// l l l +// +// m=0 0 0 +// y = K * P * trigono terms +// l l l +// +// m (2l + 1)(l - |m|)! +// K = sqrt(------------------) +// l 4pi(l + |m|)! +// +// and P by recursion: +// +// P00(x) = 1 +// P01(x) = x +// Pll(x) = (-1^l)(2l - 1)!!(1-x*x)^(1/2) +// ((2l - 1)x[Pl-1/m]-(l + m - 1)[Pl-2/m]) +// Plm(x) = --------------------------------------- +// l - m +// Leaving the trigonometric terms aside we can precompute the constants to : +const SH3ylmBasisConstants = [ + Math.sqrt(1 / (4 * Math.PI)), // l00 + -Math.sqrt(3 / (4 * Math.PI)), // l1_1 + Math.sqrt(3 / (4 * Math.PI)), // l10 + -Math.sqrt(3 / (4 * Math.PI)), // l11 + Math.sqrt(15 / (4 * Math.PI)), // l2_2 + -Math.sqrt(15 / (4 * Math.PI)), // l2_1 + Math.sqrt(5 / (16 * Math.PI)), // l20 + -Math.sqrt(15 / (4 * Math.PI)), // l21 + Math.sqrt(15 / (16 * Math.PI)), // l22 +]; +// cm = cos(m * phi) +// sm = sin(m * phi) +// {x,y,z} = {cos(phi)sin(theta), sin(phi)sin(theta), cos(theta)} +// By recursion on using trigo identities: +const SH3ylmBasisTrigonometricTerms = [ + () => 1, // l00 + (direction) => direction.y, // l1_1 + (direction) => direction.z, // l10 + (direction) => direction.x, // l11 + (direction) => direction.x * direction.y, // l2_2 + (direction) => direction.y * direction.z, // l2_1 + (direction) => 3 * direction.z * direction.z - 1, // l20 + (direction) => direction.x * direction.z, // l21 + (direction) => direction.x * direction.x - direction.y * direction.y, // l22 +]; +// Wrap the full compute +const applySH3 = (lm, direction) => { + return SH3ylmBasisConstants[lm] * SH3ylmBasisTrigonometricTerms[lm](direction); +}; +// Derived from the integration of the a kernel convolution to SH. +// Great explanation here: https://patapom.com/blog/SHPortal/#about-distant-radiance-and-irradiance-environments +const SHCosKernelConvolution = [Math.PI, (2 * Math.PI) / 3, (2 * Math.PI) / 3, (2 * Math.PI) / 3, Math.PI / 4, Math.PI / 4, Math.PI / 4, Math.PI / 4, Math.PI / 4]; +/** + * Class representing spherical harmonics coefficients to the 3rd degree + */ +class SphericalHarmonics { + constructor() { + /** + * Defines whether or not the harmonics have been prescaled for rendering. + */ + this.preScaled = false; + /** + * The l0,0 coefficients of the spherical harmonics + */ + this.l00 = Vector3.Zero(); + /** + * The l1,-1 coefficients of the spherical harmonics + */ + this.l1_1 = Vector3.Zero(); + /** + * The l1,0 coefficients of the spherical harmonics + */ + this.l10 = Vector3.Zero(); + /** + * The l1,1 coefficients of the spherical harmonics + */ + this.l11 = Vector3.Zero(); + /** + * The l2,-2 coefficients of the spherical harmonics + */ + this.l2_2 = Vector3.Zero(); + /** + * The l2,-1 coefficients of the spherical harmonics + */ + this.l2_1 = Vector3.Zero(); + /** + * The l2,0 coefficients of the spherical harmonics + */ + this.l20 = Vector3.Zero(); + /** + * The l2,1 coefficients of the spherical harmonics + */ + this.l21 = Vector3.Zero(); + /** + * The l2,2 coefficients of the spherical harmonics + */ + this.l22 = Vector3.Zero(); + } + /** + * Adds a light to the spherical harmonics + * @param direction the direction of the light + * @param color the color of the light + * @param deltaSolidAngle the delta solid angle of the light + */ + addLight(direction, color, deltaSolidAngle) { + TmpVectors.Vector3[0].set(color.r, color.g, color.b); + const colorVector = TmpVectors.Vector3[0]; + const c = TmpVectors.Vector3[1]; + colorVector.scaleToRef(deltaSolidAngle, c); + c.scaleToRef(applySH3(0, direction), TmpVectors.Vector3[2]); + this.l00.addInPlace(TmpVectors.Vector3[2]); + c.scaleToRef(applySH3(1, direction), TmpVectors.Vector3[2]); + this.l1_1.addInPlace(TmpVectors.Vector3[2]); + c.scaleToRef(applySH3(2, direction), TmpVectors.Vector3[2]); + this.l10.addInPlace(TmpVectors.Vector3[2]); + c.scaleToRef(applySH3(3, direction), TmpVectors.Vector3[2]); + this.l11.addInPlace(TmpVectors.Vector3[2]); + c.scaleToRef(applySH3(4, direction), TmpVectors.Vector3[2]); + this.l2_2.addInPlace(TmpVectors.Vector3[2]); + c.scaleToRef(applySH3(5, direction), TmpVectors.Vector3[2]); + this.l2_1.addInPlace(TmpVectors.Vector3[2]); + c.scaleToRef(applySH3(6, direction), TmpVectors.Vector3[2]); + this.l20.addInPlace(TmpVectors.Vector3[2]); + c.scaleToRef(applySH3(7, direction), TmpVectors.Vector3[2]); + this.l21.addInPlace(TmpVectors.Vector3[2]); + c.scaleToRef(applySH3(8, direction), TmpVectors.Vector3[2]); + this.l22.addInPlace(TmpVectors.Vector3[2]); + } + /** + * Scales the spherical harmonics by the given amount + * @param scale the amount to scale + */ + scaleInPlace(scale) { + this.l00.scaleInPlace(scale); + this.l1_1.scaleInPlace(scale); + this.l10.scaleInPlace(scale); + this.l11.scaleInPlace(scale); + this.l2_2.scaleInPlace(scale); + this.l2_1.scaleInPlace(scale); + this.l20.scaleInPlace(scale); + this.l21.scaleInPlace(scale); + this.l22.scaleInPlace(scale); + } + /** + * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere. + * + * ``` + * E_lm = A_l * L_lm + * ``` + * + * In spherical harmonics this convolution amounts to scaling factors for each frequency band. + * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where + * the scaling factors are given in equation 9. + */ + convertIncidentRadianceToIrradiance() { + // Constant (Band 0) + this.l00.scaleInPlace(SHCosKernelConvolution[0]); + // Linear (Band 1) + this.l1_1.scaleInPlace(SHCosKernelConvolution[1]); + this.l10.scaleInPlace(SHCosKernelConvolution[2]); + this.l11.scaleInPlace(SHCosKernelConvolution[3]); + // Quadratic (Band 2) + this.l2_2.scaleInPlace(SHCosKernelConvolution[4]); + this.l2_1.scaleInPlace(SHCosKernelConvolution[5]); + this.l20.scaleInPlace(SHCosKernelConvolution[6]); + this.l21.scaleInPlace(SHCosKernelConvolution[7]); + this.l22.scaleInPlace(SHCosKernelConvolution[8]); + } + /** + * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation. + * + * ``` + * L = (1/pi) * E * rho + * ``` + * + * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually. + */ + convertIrradianceToLambertianRadiance() { + this.scaleInPlace(1.0 / Math.PI); + // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied + // (The pixel shader must apply albedo after texture fetches, etc). + } + /** + * Integrates the reconstruction coefficients directly in to the SH preventing further + * required operations at run time. + * + * This is simply done by scaling back the SH with Ylm constants parameter. + * The trigonometric part being applied by the shader at run time. + */ + preScaleForRendering() { + this.preScaled = true; + this.l00.scaleInPlace(SH3ylmBasisConstants[0]); + this.l1_1.scaleInPlace(SH3ylmBasisConstants[1]); + this.l10.scaleInPlace(SH3ylmBasisConstants[2]); + this.l11.scaleInPlace(SH3ylmBasisConstants[3]); + this.l2_2.scaleInPlace(SH3ylmBasisConstants[4]); + this.l2_1.scaleInPlace(SH3ylmBasisConstants[5]); + this.l20.scaleInPlace(SH3ylmBasisConstants[6]); + this.l21.scaleInPlace(SH3ylmBasisConstants[7]); + this.l22.scaleInPlace(SH3ylmBasisConstants[8]); + } + /** + * update the spherical harmonics coefficients from the given array + * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22) + * @returns the spherical harmonics (this) + */ + updateFromArray(data) { + Vector3.FromArrayToRef(data[0], 0, this.l00); + Vector3.FromArrayToRef(data[1], 0, this.l1_1); + Vector3.FromArrayToRef(data[2], 0, this.l10); + Vector3.FromArrayToRef(data[3], 0, this.l11); + Vector3.FromArrayToRef(data[4], 0, this.l2_2); + Vector3.FromArrayToRef(data[5], 0, this.l2_1); + Vector3.FromArrayToRef(data[6], 0, this.l20); + Vector3.FromArrayToRef(data[7], 0, this.l21); + Vector3.FromArrayToRef(data[8], 0, this.l22); + return this; + } + /** + * update the spherical harmonics coefficients from the given floats array + * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22) + * @returns the spherical harmonics (this) + */ + updateFromFloatsArray(data) { + Vector3.FromFloatsToRef(data[0], data[1], data[2], this.l00); + Vector3.FromFloatsToRef(data[3], data[4], data[5], this.l1_1); + Vector3.FromFloatsToRef(data[6], data[7], data[8], this.l10); + Vector3.FromFloatsToRef(data[9], data[10], data[11], this.l11); + Vector3.FromFloatsToRef(data[12], data[13], data[14], this.l2_2); + Vector3.FromFloatsToRef(data[15], data[16], data[17], this.l2_1); + Vector3.FromFloatsToRef(data[18], data[19], data[20], this.l20); + Vector3.FromFloatsToRef(data[21], data[22], data[23], this.l21); + Vector3.FromFloatsToRef(data[24], data[25], data[26], this.l22); + return this; + } + /** + * Constructs a spherical harmonics from an array. + * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22) + * @returns the spherical harmonics + */ + static FromArray(data) { + const sh = new SphericalHarmonics(); + return sh.updateFromArray(data); + } + // Keep for references. + /** + * Gets the spherical harmonics from polynomial + * @param polynomial the spherical polynomial + * @returns the spherical harmonics + */ + static FromPolynomial(polynomial) { + const result = new SphericalHarmonics(); + result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126)); + result.l1_1 = polynomial.y.scale(0.977204); + result.l10 = polynomial.z.scale(0.977204); + result.l11 = polynomial.x.scale(0.977204); + result.l2_2 = polynomial.xy.scale(1.16538); + result.l2_1 = polynomial.yz.scale(1.16538); + result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834)); + result.l21 = polynomial.zx.scale(1.16538); + result.l22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538)); + result.l1_1.scaleInPlace(-1); + result.l11.scaleInPlace(-1); + result.l2_1.scaleInPlace(-1); + result.l21.scaleInPlace(-1); + result.scaleInPlace(Math.PI); + return result; + } +} +/** + * Class representing spherical polynomial coefficients to the 3rd degree + */ +class SphericalPolynomial { + constructor() { + /** + * The x coefficients of the spherical polynomial + */ + this.x = Vector3.Zero(); + /** + * The y coefficients of the spherical polynomial + */ + this.y = Vector3.Zero(); + /** + * The z coefficients of the spherical polynomial + */ + this.z = Vector3.Zero(); + /** + * The xx coefficients of the spherical polynomial + */ + this.xx = Vector3.Zero(); + /** + * The yy coefficients of the spherical polynomial + */ + this.yy = Vector3.Zero(); + /** + * The zz coefficients of the spherical polynomial + */ + this.zz = Vector3.Zero(); + /** + * The xy coefficients of the spherical polynomial + */ + this.xy = Vector3.Zero(); + /** + * The yz coefficients of the spherical polynomial + */ + this.yz = Vector3.Zero(); + /** + * The zx coefficients of the spherical polynomial + */ + this.zx = Vector3.Zero(); + } + /** + * The spherical harmonics used to create the polynomials. + */ + get preScaledHarmonics() { + if (!this._harmonics) { + this._harmonics = SphericalHarmonics.FromPolynomial(this); + } + if (!this._harmonics.preScaled) { + this._harmonics.preScaleForRendering(); + } + return this._harmonics; + } + /** + * Adds an ambient color to the spherical polynomial + * @param color the color to add + */ + addAmbient(color) { + TmpVectors.Vector3[0].copyFromFloats(color.r, color.g, color.b); + const colorVector = TmpVectors.Vector3[0]; + this.xx.addInPlace(colorVector); + this.yy.addInPlace(colorVector); + this.zz.addInPlace(colorVector); + } + /** + * Scales the spherical polynomial by the given amount + * @param scale the amount to scale + */ + scaleInPlace(scale) { + this.x.scaleInPlace(scale); + this.y.scaleInPlace(scale); + this.z.scaleInPlace(scale); + this.xx.scaleInPlace(scale); + this.yy.scaleInPlace(scale); + this.zz.scaleInPlace(scale); + this.yz.scaleInPlace(scale); + this.zx.scaleInPlace(scale); + this.xy.scaleInPlace(scale); + } + /** + * Updates the spherical polynomial from harmonics + * @param harmonics the spherical harmonics + * @returns the spherical polynomial + */ + updateFromHarmonics(harmonics) { + this._harmonics = harmonics; + this.x.copyFrom(harmonics.l11); + this.x.scaleInPlace(1.02333).scaleInPlace(-1); + this.y.copyFrom(harmonics.l1_1); + this.y.scaleInPlace(1.02333).scaleInPlace(-1); + this.z.copyFrom(harmonics.l10); + this.z.scaleInPlace(1.02333); + this.xx.copyFrom(harmonics.l00); + TmpVectors.Vector3[0].copyFrom(harmonics.l20).scaleInPlace(0.247708); + TmpVectors.Vector3[1].copyFrom(harmonics.l22).scaleInPlace(0.429043); + this.xx.scaleInPlace(0.886277).subtractInPlace(TmpVectors.Vector3[0]).addInPlace(TmpVectors.Vector3[1]); + this.yy.copyFrom(harmonics.l00); + this.yy.scaleInPlace(0.886277).subtractInPlace(TmpVectors.Vector3[0]).subtractInPlace(TmpVectors.Vector3[1]); + this.zz.copyFrom(harmonics.l00); + TmpVectors.Vector3[0].copyFrom(harmonics.l20).scaleInPlace(0.495417); + this.zz.scaleInPlace(0.886277).addInPlace(TmpVectors.Vector3[0]); + this.yz.copyFrom(harmonics.l2_1); + this.yz.scaleInPlace(0.858086).scaleInPlace(-1); + this.zx.copyFrom(harmonics.l21); + this.zx.scaleInPlace(0.858086).scaleInPlace(-1); + this.xy.copyFrom(harmonics.l2_2); + this.xy.scaleInPlace(0.858086); + this.scaleInPlace(1.0 / Math.PI); + return this; + } + /** + * Gets the spherical polynomial from harmonics + * @param harmonics the spherical harmonics + * @returns the spherical polynomial + */ + static FromHarmonics(harmonics) { + const result = new SphericalPolynomial(); + return result.updateFromHarmonics(harmonics); + } + /** + * Constructs a spherical polynomial from an array. + * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy) + * @returns the spherical polynomial + */ + static FromArray(data) { + const sp = new SphericalPolynomial(); + Vector3.FromArrayToRef(data[0], 0, sp.x); + Vector3.FromArrayToRef(data[1], 0, sp.y); + Vector3.FromArrayToRef(data[2], 0, sp.z); + Vector3.FromArrayToRef(data[3], 0, sp.xx); + Vector3.FromArrayToRef(data[4], 0, sp.yy); + Vector3.FromArrayToRef(data[5], 0, sp.zz); + Vector3.FromArrayToRef(data[6], 0, sp.yz); + Vector3.FromArrayToRef(data[7], 0, sp.zx); + Vector3.FromArrayToRef(data[8], 0, sp.xy); + return sp; + } +} + +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +// eslint-disable-next-line @typescript-eslint/naming-convention +const __mergedStore = {}; +// eslint-disable-next-line @typescript-eslint/naming-convention +const __decoratorInitialStore = {}; +/** @internal */ +function GetDirectStore(target) { + const classKey = target.getClassName(); + if (!__decoratorInitialStore[classKey]) { + __decoratorInitialStore[classKey] = {}; + } + return __decoratorInitialStore[classKey]; +} +/** + * @returns the list of properties flagged as serializable + * @param target host object + */ +function GetMergedStore(target) { + const classKey = target.getClassName(); + if (__mergedStore[classKey]) { + return __mergedStore[classKey]; + } + __mergedStore[classKey] = {}; + const store = __mergedStore[classKey]; + let currentTarget = target; + let currentKey = classKey; + while (currentKey) { + const initialStore = __decoratorInitialStore[currentKey]; + for (const property in initialStore) { + store[property] = initialStore[property]; + } + let parent; + let done = false; + do { + parent = Object.getPrototypeOf(currentTarget); + if (!parent.getClassName) { + done = true; + break; + } + if (parent.getClassName() !== currentKey) { + break; + } + currentTarget = parent; + } while (parent); + if (done) { + break; + } + currentKey = parent.getClassName(); + currentTarget = parent; + } + return store; +} + +function generateSerializableMember(type, sourceName) { + return (target, propertyKey) => { + const classStore = GetDirectStore(target); + if (!classStore[propertyKey]) { + classStore[propertyKey] = { type: type, sourceName: sourceName }; + } + }; +} +function generateExpandMember(setCallback, targetKey = null) { + return (target, propertyKey) => { + const key = targetKey || "_" + propertyKey; + Object.defineProperty(target, propertyKey, { + get: function () { + return this[key]; + }, + set: function (value) { + // does this object (i.e. vector3) has an equals function? use it! + // Note - not using "with epsilon" here, it is expected te behave like the internal cache does. + if (typeof this[key]?.equals === "function") { + if (this[key].equals(value)) { + return; + } + } + if (this[key] === value) { + return; + } + this[key] = value; + target[setCallback].apply(this); + }, + enumerable: true, + configurable: true, + }); + }; +} +function expandToProperty(callback, targetKey = null) { + return generateExpandMember(callback, targetKey); +} +function serialize(sourceName) { + return generateSerializableMember(0, sourceName); // value member +} +function serializeAsTexture(sourceName) { + return generateSerializableMember(1, sourceName); // texture member +} +function serializeAsColor3(sourceName) { + return generateSerializableMember(2, sourceName); // color3 member +} +function serializeAsFresnelParameters(sourceName) { + return generateSerializableMember(3, sourceName); // fresnel parameters member +} +function serializeAsVector2(sourceName) { + return generateSerializableMember(4, sourceName); // vector2 member +} +function serializeAsVector3(sourceName) { + return generateSerializableMember(5, sourceName); // vector3 member +} +function serializeAsMeshReference(sourceName) { + return generateSerializableMember(6, sourceName); // mesh reference member +} +function serializeAsColorCurves(sourceName) { + return generateSerializableMember(7, sourceName); // color curves +} +function serializeAsColor4(sourceName) { + return generateSerializableMember(8, sourceName); // color 4 +} +function serializeAsImageProcessingConfiguration(sourceName) { + return generateSerializableMember(9, sourceName); // image processing +} +function serializeAsQuaternion(sourceName) { + return generateSerializableMember(10, sourceName); // quaternion member +} +function serializeAsMatrix(sourceName) { + return generateSerializableMember(12, sourceName); // matrix member +} +/** + * Decorator used to define property that can be serialized as reference to a camera + * @param sourceName defines the name of the property to decorate + * @returns Property Decorator + */ +function serializeAsCameraReference(sourceName) { + return generateSerializableMember(11, sourceName); // camera reference member +} +/** + * Decorator used to redirect a function to a native implementation if available. + * @internal + */ +function nativeOverride(target, propertyKey, descriptor, predicate) { + // Cache the original JS function for later. + const jsFunc = descriptor.value; + // Override the JS function to check for a native override on first invocation. Setting descriptor.value overrides the function at the early stage of code being loaded/imported. + descriptor.value = (...params) => { + // Assume the resolved function will be the original JS function, then we will check for the Babylon Native context. + let func = jsFunc; + // Check if we are executing in a Babylon Native context (e.g. check the presence of the _native global property) and if so also check if a function override is available. + if (typeof _native !== "undefined" && _native[propertyKey]) { + const nativeFunc = _native[propertyKey]; + // If a predicate was provided, then we'll need to invoke the predicate on each invocation of the underlying function to determine whether to call the native function or the JS function. + if (predicate) { + // The resolved function will execute the predicate and then either execute the native function or the JS function. + func = (...params) => (predicate(...params) ? nativeFunc(...params) : jsFunc(...params)); + } + else { + // The resolved function will directly execute the native function. + func = nativeFunc; + } + } + // Override the JS function again with the final resolved target function. + target[propertyKey] = func; + // The JS function has now been overridden based on whether we're executing in the context of Babylon Native, but we still need to invoke that function. + // Future invocations of the function will just directly invoke the final overridden function, not any of the decorator setup logic above. + return func(...params); + }; +} +/** + * Decorator factory that applies the nativeOverride decorator, but determines whether to redirect to the native implementation based on a filter function that evaluates the function arguments. + * @param predicate + * @example @nativeOverride.filter((...[arg1]: Parameters) => arg1.length > 20) + * public someMethod(arg1: string, arg2: number): string { + * @internal + */ +nativeOverride.filter = function (predicate) { + return (target, propertyKey, descriptor) => nativeOverride(target, propertyKey, descriptor, predicate); +}; + +/** + * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 + * Be aware Math.random() could cause collisions, but: + * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" + * @returns a pseudo random id + */ +function RandomGUID() { + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0, v = c === "x" ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} + +/** @internal */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function createXMLHttpRequest() { + // If running in Babylon Native, then defer to the native XMLHttpRequest, which has the same public contract + if (typeof _native !== "undefined" && _native.XMLHttpRequest) { + return new _native.XMLHttpRequest(); + } + else { + return new XMLHttpRequest(); + } +} +/** + * Extended version of XMLHttpRequest with support for customizations (headers, ...) + */ +class WebRequest { + constructor() { + this._xhr = createXMLHttpRequest(); + this._requestURL = ""; + } + /** + * This function can be called to check if there are request modifiers for network requests + * @returns true if there are any custom requests available + */ + static get IsCustomRequestAvailable() { + return Object.keys(WebRequest.CustomRequestHeaders).length > 0 || WebRequest.CustomRequestModifiers.length > 0; + } + /** + * Returns the requested URL once open has been called + */ + get requestURL() { + return this._requestURL; + } + _injectCustomRequestHeaders() { + if (this._shouldSkipRequestModifications(this._requestURL)) { + return; + } + for (const key in WebRequest.CustomRequestHeaders) { + const val = WebRequest.CustomRequestHeaders[key]; + if (val) { + this._xhr.setRequestHeader(key, val); + } + } + } + _shouldSkipRequestModifications(url) { + return WebRequest.SkipRequestModificationForBabylonCDN && (url.includes("preview.babylonjs.com") || url.includes("cdn.babylonjs.com")); + } + /** + * Gets or sets a function to be called when loading progress changes + */ + get onprogress() { + return this._xhr.onprogress; + } + set onprogress(value) { + this._xhr.onprogress = value; + } + /** + * Returns client's state + */ + get readyState() { + return this._xhr.readyState; + } + /** + * Returns client's status + */ + get status() { + return this._xhr.status; + } + /** + * Returns client's status as a text + */ + get statusText() { + return this._xhr.statusText; + } + /** + * Returns client's response + */ + get response() { + return this._xhr.response; + } + /** + * Returns client's response url + */ + get responseURL() { + return this._xhr.responseURL; + } + /** + * Returns client's response as text + */ + get responseText() { + return this._xhr.responseText; + } + /** + * Gets or sets the expected response type + */ + get responseType() { + return this._xhr.responseType; + } + set responseType(value) { + this._xhr.responseType = value; + } + /** + * Gets or sets the timeout value in milliseconds + */ + get timeout() { + return this._xhr.timeout; + } + set timeout(value) { + this._xhr.timeout = value; + } + addEventListener(type, listener, options) { + this._xhr.addEventListener(type, listener, options); + } + removeEventListener(type, listener, options) { + this._xhr.removeEventListener(type, listener, options); + } + /** + * Cancels any network activity + */ + abort() { + this._xhr.abort(); + } + /** + * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD + * @param body defines an optional request body + */ + send(body) { + if (WebRequest.CustomRequestHeaders) { + this._injectCustomRequestHeaders(); + } + this._xhr.send(body); + } + /** + * Sets the request method, request URL + * @param method defines the method to use (GET, POST, etc..) + * @param url defines the url to connect with + */ + open(method, url) { + for (const update of WebRequest.CustomRequestModifiers) { + if (this._shouldSkipRequestModifications(url)) { + return; + } + url = update(this._xhr, url) || url; + } + // Clean url + url = url.replace("file:http:", "http:"); + url = url.replace("file:https:", "https:"); + this._requestURL = url; + this._xhr.open(method, url, true); + } + /** + * Sets the value of a request header. + * @param name The name of the header whose value is to be set + * @param value The value to set as the body of the header + */ + setRequestHeader(name, value) { + this._xhr.setRequestHeader(name, value); + } + /** + * Get the string containing the text of a particular header's value. + * @param name The name of the header + * @returns The string containing the text of the given header name + */ + getResponseHeader(name) { + return this._xhr.getResponseHeader(name); + } +} +/** + * Custom HTTP Request Headers to be sent with XMLHttpRequests + * i.e. when loading files, where the server/service expects an Authorization header + */ +WebRequest.CustomRequestHeaders = {}; +/** + * Add callback functions in this array to update all the requests before they get sent to the network + */ +WebRequest.CustomRequestModifiers = new Array(); +/** + * If set to true, requests to Babylon.js CDN requests will not be modified + */ +WebRequest.SkipRequestModificationForBabylonCDN = true; + +/** + * Class used to help managing file picking and drag'n'drop + * File Storage + */ +class FilesInputStore { +} +/** + * List of files ready to be loaded + */ +FilesInputStore.FilesToLoad = {}; + +/** + * Class used to define a retry strategy when error happens while loading assets + */ +class RetryStrategy { + /** + * Function used to defines an exponential back off strategy + * @param maxRetries defines the maximum number of retries (3 by default) + * @param baseInterval defines the interval between retries + * @returns the strategy function to use + */ + static ExponentialBackoff(maxRetries = 3, baseInterval = 500) { + return (url, request, retryIndex) => { + if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) { + return -1; + } + return Math.pow(2, retryIndex) * baseInterval; + }; + } +} + +/* eslint-disable @typescript-eslint/naming-convention */ +/** + * Base error. Due to limitations of typedoc-check and missing documentation + * in lib.es5.d.ts, cannot extend Error directly for RuntimeError. + * @ignore + */ +class BaseError extends Error { +} +// See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript +// and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work +// Polyfill for Object.setPrototypeOf if necessary. +BaseError._setPrototypeOf = Object.setPrototypeOf || + ((o, proto) => { + o.__proto__ = proto; + return o; + }); +/* IMP! DO NOT CHANGE THE NUMBERING OF EXISTING ERROR CODES */ +/** + * Error codes for BaseError + */ +const ErrorCodes = { + // Mesh errors 0-999 + /** Invalid or empty mesh vertex positions. */ + MeshInvalidPositionsError: 0, + // Texture errors 1000-1999 + /** Unsupported texture found. */ + UnsupportedTextureError: 1000, + // GLTFLoader errors 2000-2999 + /** Unexpected magic number found in GLTF file header. */ + GLTFLoaderUnexpectedMagicError: 2000, + // SceneLoader errors 3000-3999 + /** SceneLoader generic error code. Ideally wraps the inner exception. */ + SceneLoaderError: 3000, + // File related errors 4000-4999 + /** Load file error */ + LoadFileError: 4000, + /** Request file error */ + RequestFileError: 4001, + /** Read file error */ + ReadFileError: 4002, +}; +/** + * Application runtime error + */ +class RuntimeError extends BaseError { + /** + * Creates a new RuntimeError + * @param message defines the message of the error + * @param errorCode the error code + * @param innerError the error that caused the outer error + */ + constructor(message, errorCode, innerError) { + super(message); + this.errorCode = errorCode; + this.innerError = innerError; + this.name = "RuntimeError"; + BaseError._setPrototypeOf(this, RuntimeError.prototype); + } +} + +/* eslint-disable @typescript-eslint/naming-convention */ +/** + * Checks for a matching suffix at the end of a string (for ES5 and lower) + * @param str Source string + * @param suffix Suffix to search for in the source string + * @returns Boolean indicating whether the suffix was found (true) or not (false) + * @deprecated Please use native string function instead + */ +/** + * Decodes a buffer into a string + * @param buffer The buffer to decode + * @returns The decoded string + */ +const Decode = (buffer) => { + if (typeof TextDecoder !== "undefined") { + return new TextDecoder().decode(buffer); + } + let result = ""; + for (let i = 0; i < buffer.byteLength; i++) { + result += String.fromCharCode(buffer[i]); + } + return result; +}; +/** + * Encode a buffer to a base64 string + * @param buffer defines the buffer to encode + * @returns the encoded string + */ +const EncodeArrayBufferToBase64 = (buffer) => { + const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + let output = ""; + let chr1, chr2, chr3, enc1, enc2, enc3, enc4; + let i = 0; + const bytes = ArrayBuffer.isView(buffer) ? new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) : new Uint8Array(buffer); + while (i < bytes.length) { + chr1 = bytes[i++]; + chr2 = i < bytes.length ? bytes[i++] : Number.NaN; + chr3 = i < bytes.length ? bytes[i++] : Number.NaN; + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } + else if (isNaN(chr3)) { + enc4 = 64; + } + output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); + } + return output; +}; +/** + * Converts a given base64 string as an ASCII encoded stream of data + * @param base64Data The base64 encoded string to decode + * @returns Decoded ASCII string + */ +const DecodeBase64ToString = (base64Data) => { + return atob(base64Data); +}; +/** + * Converts a given base64 string into an ArrayBuffer of raw byte data + * @param base64Data The base64 encoded string to decode + * @returns ArrayBuffer of byte data + */ +const DecodeBase64ToBinary = (base64Data) => { + const decodedString = DecodeBase64ToString(base64Data); + const bufferLength = decodedString.length; + const bufferView = new Uint8Array(new ArrayBuffer(bufferLength)); + for (let i = 0; i < bufferLength; i++) { + bufferView[i] = decodedString.charCodeAt(i); + } + return bufferView.buffer; +}; + +/* eslint-disable @typescript-eslint/naming-convention */ +const Base64DataUrlRegEx = new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i); +/** @ignore */ +class LoadFileError extends RuntimeError { + /** + * Creates a new LoadFileError + * @param message defines the message of the error + * @param object defines the optional web request + */ + constructor(message, object) { + super(message, ErrorCodes.LoadFileError); + this.name = "LoadFileError"; + BaseError._setPrototypeOf(this, LoadFileError.prototype); + if (object instanceof WebRequest) { + this.request = object; + } + else { + this.file = object; + } + } +} +/** @ignore */ +class RequestFileError extends RuntimeError { + /** + * Creates a new LoadFileError + * @param message defines the message of the error + * @param request defines the optional web request + */ + constructor(message, request) { + super(message, ErrorCodes.RequestFileError); + this.request = request; + this.name = "RequestFileError"; + BaseError._setPrototypeOf(this, RequestFileError.prototype); + } +} +/** @ignore */ +class ReadFileError extends RuntimeError { + /** + * Creates a new ReadFileError + * @param message defines the message of the error + * @param file defines the optional file + */ + constructor(message, file) { + super(message, ErrorCodes.ReadFileError); + this.file = file; + this.name = "ReadFileError"; + BaseError._setPrototypeOf(this, ReadFileError.prototype); + } +} +/** + * Removes unwanted characters from an url + * @param url defines the url to clean + * @returns the cleaned url + */ +const CleanUrl = (url) => { + url = url.replace(/#/gm, "%23"); + return url; +}; +/** + * @internal + */ +const FileToolsOptions = { + /** + * Gets or sets the retry strategy to apply when an error happens while loading an asset. + * When defining this function, return the wait time before trying again or return -1 to + * stop retrying and error out. + */ + DefaultRetryStrategy: RetryStrategy.ExponentialBackoff(), + /** + * Gets or sets the base URL to use to load assets + */ + BaseUrl: "", + /** + * Default behaviour for cors in the application. + * It can be a string if the expected behavior is identical in the entire app. + * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance) + */ + CorsBehavior: "anonymous", + /** + * Gets or sets a function used to pre-process url before using them to load assets + * @param url + * @returns the processed url + */ + PreprocessUrl: (url) => url, + /** + * Gets or sets the base URL to use to load scripts + * Used for both JS and WASM + */ + ScriptBaseUrl: "", + /** + * Gets or sets a function used to pre-process script url before using them to load. + * Used for both JS and WASM + * @param url defines the url to process + * @returns the processed url + */ + ScriptPreprocessUrl: (url) => url, + /** + * Gets or sets a function used to clean the url before using it to load assets + * @param url defines the url to clean + * @returns the cleaned url + */ + CleanUrl, +}; +/** + * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element. + * @param url define the url we are trying + * @param element define the dom element where to configure the cors policy + * @internal + */ +const SetCorsBehavior = (url, element) => { + if (url && url.indexOf("data:") === 0) { + return; + } + if (FileToolsOptions.CorsBehavior) { + if (typeof FileToolsOptions.CorsBehavior === "string" || FileToolsOptions.CorsBehavior instanceof String) { + element.crossOrigin = FileToolsOptions.CorsBehavior; + } + else { + const result = FileToolsOptions.CorsBehavior(url); + if (result) { + element.crossOrigin = result; + } + } + } +}; +/** + * Loads an image as an HTMLImageElement. + * @param input url string, ArrayBuffer, or Blob to load + * @param onLoad callback called when the image successfully loads + * @param onError callback called when the image fails to load + * @param offlineProvider offline provider for caching + * @param mimeType optional mime type + * @param imageBitmapOptions + * @param engine the engine instance to use + * @returns the HTMLImageElement of the loaded image + * @internal + */ +const LoadImage = (input, onLoad, onError, offlineProvider, mimeType = "", imageBitmapOptions, engine = EngineStore.LastCreatedEngine) => { + if (typeof HTMLImageElement === "undefined" && !engine?._features.forceBitmapOverHTMLImageElement) { + onError("LoadImage is only supported in web or BabylonNative environments."); + return null; + } + let url; + let usingObjectURL = false; + if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) { + if (typeof Blob !== "undefined" && typeof URL !== "undefined") { + url = URL.createObjectURL(new Blob([input], { type: mimeType })); + usingObjectURL = true; + } + else { + url = `data:${mimeType};base64,` + EncodeArrayBufferToBase64(input); + } + } + else if (input instanceof Blob) { + url = URL.createObjectURL(input); + usingObjectURL = true; + } + else { + url = FileToolsOptions.CleanUrl(input); + url = FileToolsOptions.PreprocessUrl(url); + } + const onErrorHandler = (exception) => { + if (onError) { + const inputText = url || input.toString(); + onError(`Error while trying to load image: ${inputText.indexOf("http") === 0 || inputText.length <= 128 ? inputText : inputText.slice(0, 128) + "..."}`, exception); + } + }; + if (engine?._features.forceBitmapOverHTMLImageElement) { + LoadFile(url, (data) => { + engine + .createImageBitmap(new Blob([data], { type: mimeType }), { premultiplyAlpha: "none", ...imageBitmapOptions }) + .then((imgBmp) => { + onLoad(imgBmp); + if (usingObjectURL) { + URL.revokeObjectURL(url); + } + }) + .catch((reason) => { + if (onError) { + onError("Error while trying to load image: " + input, reason); + } + }); + }, undefined, offlineProvider || undefined, true, (request, exception) => { + onErrorHandler(exception); + }); + return null; + } + const img = new Image(); + SetCorsBehavior(url, img); + const handlersList = []; + const loadHandlersList = () => { + handlersList.forEach((handler) => { + handler.target.addEventListener(handler.name, handler.handler); + }); + }; + const unloadHandlersList = () => { + handlersList.forEach((handler) => { + handler.target.removeEventListener(handler.name, handler.handler); + }); + handlersList.length = 0; + }; + const loadHandler = () => { + unloadHandlersList(); + onLoad(img); + // Must revoke the URL after calling onLoad to avoid security exceptions in + // certain scenarios (e.g. when hosted in vscode). + if (usingObjectURL && img.src) { + URL.revokeObjectURL(img.src); + } + }; + const errorHandler = (err) => { + unloadHandlersList(); + onErrorHandler(err); + if (usingObjectURL && img.src) { + URL.revokeObjectURL(img.src); + } + }; + const cspHandler = (err) => { + if (err.blockedURI !== img.src || err.disposition === "report") { + return; + } + unloadHandlersList(); + const cspException = new Error(`CSP violation of policy ${err.effectiveDirective} ${err.blockedURI}. Current policy is ${err.originalPolicy}`); + EngineStore.UseFallbackTexture = false; + onErrorHandler(cspException); + if (usingObjectURL && img.src) { + URL.revokeObjectURL(img.src); + } + img.src = ""; + }; + handlersList.push({ target: img, name: "load", handler: loadHandler }); + handlersList.push({ target: img, name: "error", handler: errorHandler }); + handlersList.push({ target: document, name: "securitypolicyviolation", handler: cspHandler }); + loadHandlersList(); + const fromBlob = url.substring(0, 5) === "blob:"; + const fromData = url.substring(0, 5) === "data:"; + const noOfflineSupport = () => { + if (fromBlob || fromData || !WebRequest.IsCustomRequestAvailable) { + img.src = url; + } + else { + LoadFile(url, (data, _, contentType) => { + const type = !mimeType && contentType ? contentType : mimeType; + const blob = new Blob([data], { type }); + const url = URL.createObjectURL(blob); + usingObjectURL = true; + img.src = url; + }, undefined, offlineProvider || undefined, true, (_request, exception) => { + onErrorHandler(exception); + }); + } + }; + const loadFromOfflineSupport = () => { + if (offlineProvider) { + offlineProvider.loadImage(url, img); + } + }; + if (!fromBlob && !fromData && offlineProvider && offlineProvider.enableTexturesOffline) { + offlineProvider.open(loadFromOfflineSupport, noOfflineSupport); + } + else { + if (url.indexOf("file:") !== -1) { + const textureName = decodeURIComponent(url.substring(5).toLowerCase()); + if (FilesInputStore.FilesToLoad[textureName] && typeof URL !== "undefined") { + try { + let blobURL; + try { + blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]); + } + catch (ex) { + // Chrome doesn't support oneTimeOnly parameter + blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]); + } + img.src = blobURL; + usingObjectURL = true; + } + catch (e) { + img.src = ""; + } + return img; + } + } + noOfflineSupport(); + } + return img; +}; +/** + * Reads a file from a File object + * @param file defines the file to load + * @param onSuccess defines the callback to call when data is loaded + * @param onProgress defines the callback to call during loading process + * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer + * @param onError defines the callback to call when an error occurs + * @returns a file request object + * @internal + */ +const ReadFile = (file, onSuccess, onProgress, useArrayBuffer, onError) => { + const reader = new FileReader(); + const fileRequest = { + onCompleteObservable: new Observable(), + abort: () => reader.abort(), + }; + reader.onloadend = () => fileRequest.onCompleteObservable.notifyObservers(fileRequest); + if (onError) { + reader.onerror = () => { + onError(new ReadFileError(`Unable to read ${file.name}`, file)); + }; + } + reader.onload = (e) => { + //target doesn't have result from ts 1.3 + onSuccess(e.target["result"]); + }; + if (onProgress) { + reader.onprogress = onProgress; + } + if (!useArrayBuffer) { + // Asynchronous read + reader.readAsText(file); + } + else { + reader.readAsArrayBuffer(file); + } + return fileRequest; +}; +/** + * Loads a file from a url, a data url, or a file url + * @param fileOrUrl file, url, data url, or file url to load + * @param onSuccess callback called when the file successfully loads + * @param onProgress callback called while file is loading (if the server supports this mode) + * @param offlineProvider defines the offline provider for caching + * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer + * @param onError callback called when the file fails to load + * @param onOpened + * @returns a file request object + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +const LoadFile = (fileOrUrl, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => { + if (fileOrUrl.name) { + return ReadFile(fileOrUrl, onSuccess, onProgress, useArrayBuffer, onError + ? (error) => { + onError(undefined, error); + } + : undefined); + } + const url = fileOrUrl; + // If file and file input are set + if (url.indexOf("file:") !== -1) { + let fileName = decodeURIComponent(url.substring(5).toLowerCase()); + if (fileName.indexOf("./") === 0) { + fileName = fileName.substring(2); + } + const file = FilesInputStore.FilesToLoad[fileName]; + if (file) { + return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError ? (error) => onError(undefined, new LoadFileError(error.message, error.file)) : undefined); + } + } + // For a Base64 Data URL + const { match, type } = TestBase64DataUrl(url); + if (match) { + const fileRequest = { + onCompleteObservable: new Observable(), + abort: () => () => { }, + }; + try { + const data = useArrayBuffer ? DecodeBase64UrlToBinary(url) : DecodeBase64UrlToString(url); + onSuccess(data, undefined, type); + } + catch (error) { + if (onError) { + onError(undefined, error); + } + else { + Logger.Error(error.message || "Failed to parse the Data URL"); + } + } + TimingTools.SetImmediate(() => { + fileRequest.onCompleteObservable.notifyObservers(fileRequest); + }); + return fileRequest; + } + return RequestFile(url, (data, request) => { + onSuccess(data, request?.responseURL, request?.getResponseHeader("content-type")); + }, onProgress, offlineProvider, useArrayBuffer, onError + ? (error) => { + onError(error.request, new LoadFileError(error.message, error.request)); + } + : undefined, onOpened); +}; +/** + * Loads a file from a url + * @param url url to load + * @param onSuccess callback called when the file successfully loads + * @param onProgress callback called while file is loading (if the server supports this mode) + * @param offlineProvider defines the offline provider for caching + * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer + * @param onError callback called when the file fails to load + * @param onOpened callback called when the web request is opened + * @returns a file request object + * @internal + */ +const RequestFile = (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => { + url = FileToolsOptions.CleanUrl(url); + url = FileToolsOptions.PreprocessUrl(url); + const loadUrl = FileToolsOptions.BaseUrl + url; + let aborted = false; + const fileRequest = { + onCompleteObservable: new Observable(), + abort: () => (aborted = true), + }; + const requestFile = () => { + let request = new WebRequest(); + let retryHandle = null; + let onReadyStateChange; + const unbindEvents = () => { + if (!request) { + return; + } + if (onProgress) { + request.removeEventListener("progress", onProgress); + } + if (onReadyStateChange) { + request.removeEventListener("readystatechange", onReadyStateChange); + } + request.removeEventListener("loadend", onLoadEnd); + }; + let onLoadEnd = () => { + unbindEvents(); + fileRequest.onCompleteObservable.notifyObservers(fileRequest); + fileRequest.onCompleteObservable.clear(); + onProgress = undefined; + onReadyStateChange = null; + onLoadEnd = null; + onError = undefined; + onOpened = undefined; + onSuccess = undefined; + }; + fileRequest.abort = () => { + aborted = true; + if (onLoadEnd) { + onLoadEnd(); + } + if (request && request.readyState !== (XMLHttpRequest.DONE || 4)) { + request.abort(); + } + if (retryHandle !== null) { + clearTimeout(retryHandle); + retryHandle = null; + } + request = null; + }; + const handleError = (error) => { + const message = error.message || "Unknown error"; + if (onError && request) { + onError(new RequestFileError(message, request)); + } + else { + Logger.Error(message); + } + }; + const retryLoop = (retryIndex) => { + if (!request) { + return; + } + request.open("GET", loadUrl); + if (onOpened) { + try { + onOpened(request); + } + catch (e) { + handleError(e); + return; + } + } + if (useArrayBuffer) { + request.responseType = "arraybuffer"; + } + if (onProgress) { + request.addEventListener("progress", onProgress); + } + if (onLoadEnd) { + request.addEventListener("loadend", onLoadEnd); + } + onReadyStateChange = () => { + if (aborted || !request) { + return; + } + // In case of undefined state in some browsers. + if (request.readyState === (XMLHttpRequest.DONE || 4)) { + // Some browsers have issues where onreadystatechange can be called multiple times with the same value. + if (onReadyStateChange) { + request.removeEventListener("readystatechange", onReadyStateChange); + } + if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!IsWindowObjectExist() || IsFileURL()))) { + // It's possible for the request to have a success status code but null response if the underlying + // underlying HTTP connection was closed prematurely. See _onHttpResponseClose in xhr2.js. In this + // case we will throw an exception if we call the onSuccess handler because "data" will be null + // and that then bypasses the retry strategy. + const data = useArrayBuffer ? request.response : request.responseText; + if (data !== null) { + try { + if (onSuccess) { + onSuccess(data, request); + } + } + catch (e) { + handleError(e); + } + return; + } + } + const retryStrategy = FileToolsOptions.DefaultRetryStrategy; + if (retryStrategy) { + const waitTime = retryStrategy(loadUrl, request, retryIndex); + if (waitTime !== -1) { + // Prevent the request from completing for retry. + unbindEvents(); + request = new WebRequest(); + retryHandle = setTimeout(() => retryLoop(retryIndex + 1), waitTime); + return; + } + } + const error = new RequestFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request); + if (onError) { + onError(error); + } + } + }; + request.addEventListener("readystatechange", onReadyStateChange); + request.send(); + }; + retryLoop(0); + }; + // Caching all files + if (offlineProvider && offlineProvider.enableSceneOffline) { + const noOfflineSupport = (request) => { + if (request && request.status > 400) { + if (onError) { + onError(request); + } + } + else { + requestFile(); + } + }; + const loadFromOfflineSupport = () => { + // TODO: database needs to support aborting and should return a IFileRequest + if (offlineProvider) { + offlineProvider.loadFile(FileToolsOptions.BaseUrl + url, (data) => { + if (!aborted && onSuccess) { + onSuccess(data); + } + fileRequest.onCompleteObservable.notifyObservers(fileRequest); + }, onProgress + ? (event) => { + if (!aborted && onProgress) { + onProgress(event); + } + } + : undefined, noOfflineSupport, useArrayBuffer); + } + }; + offlineProvider.open(loadFromOfflineSupport, noOfflineSupport); + } + else { + requestFile(); + } + return fileRequest; +}; +/** + * Checks if the loaded document was accessed via `file:`-Protocol. + * @returns boolean + * @internal + */ +const IsFileURL = () => { + return typeof location !== "undefined" && location.protocol === "file:"; +}; +/** + * Test if the given uri is a valid base64 data url + * @param uri The uri to test + * @returns True if the uri is a base64 data url or false otherwise + * @internal + */ +const IsBase64DataUrl = (uri) => { + return Base64DataUrlRegEx.test(uri); +}; +const TestBase64DataUrl = (uri) => { + const results = Base64DataUrlRegEx.exec(uri); + if (results === null || results.length === 0) { + return { match: false, type: "" }; + } + else { + const type = results[0].replace("data:", "").replace("base64,", ""); + return { match: true, type }; + } +}; +/** + * Decode the given base64 uri. + * @param uri The uri to decode + * @returns The decoded base64 data. + * @internal + */ +function DecodeBase64UrlToBinary(uri) { + return DecodeBase64ToBinary(uri.split(",")[1]); +} +/** + * Decode the given base64 uri into a UTF-8 encoded string. + * @param uri The uri to decode + * @returns The decoded base64 data. + * @internal + */ +const DecodeBase64UrlToString = (uri) => { + return DecodeBase64ToString(uri.split(",")[1]); +}; +/** + * This will be executed automatically for UMD and es5. + * If esm dev wants the side effects to execute they will have to run it manually + * Once we build native modules those need to be exported. + * @internal + */ +const initSideEffects$2 = () => { + AbstractEngine._FileToolsLoadImage = LoadImage; + EngineFunctionContext.loadFile = LoadFile; + _functionContainer.loadFile = LoadFile; +}; +initSideEffects$2(); +// deprecated +/** + * FileTools defined as any. + * This should not be imported or used in future releases or in any module in the framework + * @internal + * @deprecated import the needed function from fileTools.ts + */ +let FileTools; +/** + * @internal + */ +const _injectLTSFileTools = (DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior) => { + /** + * Backwards compatibility. + * @internal + * @deprecated + */ + FileTools = { + DecodeBase64UrlToBinary, + DecodeBase64UrlToString, + DefaultRetryStrategy: FileToolsOptions.DefaultRetryStrategy, + BaseUrl: FileToolsOptions.BaseUrl, + CorsBehavior: FileToolsOptions.CorsBehavior, + PreprocessUrl: FileToolsOptions.PreprocessUrl, + IsBase64DataUrl, + IsFileURL, + LoadFile, + LoadImage, + ReadFile, + RequestFile, + SetCorsBehavior, + }; + Object.defineProperty(FileTools, "DefaultRetryStrategy", { + get: function () { + return FileToolsOptions.DefaultRetryStrategy; + }, + set: function (value) { + FileToolsOptions.DefaultRetryStrategy = value; + }, + }); + Object.defineProperty(FileTools, "BaseUrl", { + get: function () { + return FileToolsOptions.BaseUrl; + }, + set: function (value) { + FileToolsOptions.BaseUrl = value; + }, + }); + Object.defineProperty(FileTools, "PreprocessUrl", { + get: function () { + return FileToolsOptions.PreprocessUrl; + }, + set: function (value) { + FileToolsOptions.PreprocessUrl = value; + }, + }); + Object.defineProperty(FileTools, "CorsBehavior", { + get: function () { + return FileToolsOptions.CorsBehavior; + }, + set: function (value) { + FileToolsOptions.CorsBehavior = value; + }, + }); +}; +_injectLTSFileTools(DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior); + +/** + * Base class of all the textures in babylon. + * It groups all the common properties required to work with Thin Engine. + */ +class ThinTexture { + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + get wrapU() { + return this._wrapU; + } + set wrapU(value) { + this._wrapU = value; + } + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + get wrapV() { + return this._wrapV; + } + set wrapV(value) { + this._wrapV = value; + } + /** + * How a texture is mapped. + * Unused in thin texture mode. + */ + get coordinatesMode() { + return 0; + } + /** + * Define if the texture is a cube texture or if false a 2d texture. + */ + get isCube() { + if (!this._texture) { + return false; + } + return this._texture.isCube; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + set isCube(value) { + if (!this._texture) { + return; + } + this._texture.isCube = value; + } + /** + * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture. + */ + get is3D() { + if (!this._texture) { + return false; + } + return this._texture.is3D; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + set is3D(value) { + if (!this._texture) { + return; + } + this._texture.is3D = value; + } + /** + * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture. + */ + get is2DArray() { + if (!this._texture) { + return false; + } + return this._texture.is2DArray; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + set is2DArray(value) { + if (!this._texture) { + return; + } + this._texture.is2DArray = value; + } + /** + * Get the class name of the texture. + * @returns "ThinTexture" + */ + getClassName() { + return "ThinTexture"; + } + static _IsRenderTargetWrapper(texture) { + return texture?.shareDepth !== undefined; + } + /** + * Instantiates a new ThinTexture. + * Base class of all the textures in babylon. + * This can be used as an internal texture wrapper in AbstractEngine to benefit from the cache + * @param internalTexture Define the internalTexture to wrap. You can also pass a RenderTargetWrapper, in which case the texture will be the render target's texture + */ + constructor(internalTexture) { + this._wrapU = 1; + this._wrapV = 1; + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + this.wrapR = 1; + /** + * With compliant hardware and browser (supporting anisotropic filtering) + * this defines the level of anisotropic filtering in the texture. + * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff. + */ + this.anisotropicFilteringLevel = 4; + /** + * Define the current state of the loading sequence when in delayed load mode. + */ + this.delayLoadState = 0; + /** @internal */ + this._texture = null; + this._engine = null; + this._cachedSize = Size.Zero(); + this._cachedBaseSize = Size.Zero(); + /** @internal */ + this._initialSamplingMode = 2; + this._texture = ThinTexture._IsRenderTargetWrapper(internalTexture) ? internalTexture.texture : internalTexture; + if (this._texture) { + this._engine = this._texture.getEngine(); + } + } + /** + * Get if the texture is ready to be used (downloaded, converted, mip mapped...). + * @returns true if fully ready + */ + isReady() { + if (this.delayLoadState === 4) { + this.delayLoad(); + return false; + } + if (this._texture) { + return this._texture.isReady; + } + return false; + } + /** + * Triggers the load sequence in delayed load mode. + */ + delayLoad() { } + /** + * Get the underlying lower level texture from Babylon. + * @returns the internal texture + */ + getInternalTexture() { + return this._texture; + } + /** + * Get the size of the texture. + * @returns the texture size. + */ + getSize() { + if (this._texture) { + if (this._texture.width) { + this._cachedSize.width = this._texture.width; + this._cachedSize.height = this._texture.height; + return this._cachedSize; + } + if (this._texture._size) { + this._cachedSize.width = this._texture._size; + this._cachedSize.height = this._texture._size; + return this._cachedSize; + } + } + return this._cachedSize; + } + /** + * Get the base size of the texture. + * It can be different from the size if the texture has been resized for POT for instance + * @returns the base size + */ + getBaseSize() { + if (!this.isReady() || !this._texture) { + this._cachedBaseSize.width = 0; + this._cachedBaseSize.height = 0; + return this._cachedBaseSize; + } + if (this._texture._size) { + this._cachedBaseSize.width = this._texture._size; + this._cachedBaseSize.height = this._texture._size; + return this._cachedBaseSize; + } + this._cachedBaseSize.width = this._texture.baseWidth; + this._cachedBaseSize.height = this._texture.baseHeight; + return this._cachedBaseSize; + } + /** + * Get the current sampling mode associated with the texture. + */ + get samplingMode() { + if (!this._texture) { + return this._initialSamplingMode; + } + return this._texture.samplingMode; + } + /** + * Update the sampling mode of the texture. + * Default is Trilinear mode. + * + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear | + * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest | + * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear | + * | 4 | NEAREST_NEAREST_MIPNEAREST | | + * | 5 | NEAREST_LINEAR_MIPNEAREST | | + * | 6 | NEAREST_LINEAR_MIPLINEAR | | + * | 7 | NEAREST_LINEAR | | + * | 8 | NEAREST_NEAREST | | + * | 9 | LINEAR_NEAREST_MIPNEAREST | | + * | 10 | LINEAR_NEAREST_MIPLINEAR | | + * | 11 | LINEAR_LINEAR | | + * | 12 | LINEAR_NEAREST | | + * + * > _mag_: magnification filter (close to the viewer) + * > _min_: minification filter (far from the viewer) + * > _mip_: filter used between mip map levels + *@param samplingMode Define the new sampling mode of the texture + */ + updateSamplingMode(samplingMode) { + if (this._texture && this._engine) { + this._engine.updateTextureSamplingMode(samplingMode, this._texture); + } + } + /** + * Release and destroy the underlying lower level texture aka internalTexture. + */ + releaseInternalTexture() { + if (this._texture) { + this._texture.dispose(); + this._texture = null; + } + } + /** + * Dispose the texture and release its associated resources. + */ + dispose() { + if (this._texture) { + this.releaseInternalTexture(); + this._engine = null; + } + } +} + +/** + * Class used to evaluate queries containing `and` and `or` operators + */ +class AndOrNotEvaluator { + /** + * Evaluate a query + * @param query defines the query to evaluate + * @param evaluateCallback defines the callback used to filter result + * @returns true if the query matches + */ + static Eval(query, evaluateCallback) { + if (!query.match(/\([^()]*\)/g)) { + query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback); + } + else { + query = query.replace(/\([^()]*\)/g, (r) => { + // remove parenthesis + r = r.slice(1, r.length - 1); + return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback); + }); + } + if (query === "true") { + return true; + } + if (query === "false") { + return false; + } + return AndOrNotEvaluator.Eval(query, evaluateCallback); + } + static _HandleParenthesisContent(parenthesisContent, evaluateCallback) { + evaluateCallback = + evaluateCallback || + ((r) => { + return r === "true" ? true : false; + }); + let result; + const or = parenthesisContent.split("||"); + for (const i in or) { + if (Object.prototype.hasOwnProperty.call(or, i)) { + let ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim()); + const and = ori.split("&&"); + if (and.length > 1) { + for (let j = 0; j < and.length; ++j) { + const andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim()); + if (andj !== "true" && andj !== "false") { + if (andj[0] === "!") { + result = !evaluateCallback(andj.substring(1)); + } + else { + result = evaluateCallback(andj); + } + } + else { + result = andj === "true" ? true : false; + } + if (!result) { + // no need to continue since 'false && ... && ...' will always return false + ori = "false"; + break; + } + } + } + if (result || ori === "true") { + // no need to continue since 'true || ... || ...' will always return true + result = true; + break; + } + // result equals false (or undefined) + if (ori !== "true" && ori !== "false") { + if (ori[0] === "!") { + result = !evaluateCallback(ori.substring(1)); + } + else { + result = evaluateCallback(ori); + } + } + else { + result = ori === "true" ? true : false; + } + } + } + // the whole parenthesis scope is replaced by 'true' or 'false' + return result ? "true" : "false"; + } + static _SimplifyNegation(booleanString) { + booleanString = booleanString.replace(/^[\s!]+/, (r) => { + // remove whitespaces + r = r.replace(/[\s]/g, () => ""); + return r.length % 2 ? "!" : ""; + }); + booleanString = booleanString.trim(); + if (booleanString === "!true") { + booleanString = "false"; + } + else if (booleanString === "!false") { + booleanString = "true"; + } + return booleanString; + } +} + +/** + * Class used to store custom tags + */ +class Tags { + /** + * Adds support for tags on the given object + * @param obj defines the object to use + */ + static EnableFor(obj) { + obj._tags = obj._tags || {}; + obj.hasTags = () => { + return Tags.HasTags(obj); + }; + obj.addTags = (tagsString) => { + return Tags.AddTagsTo(obj, tagsString); + }; + obj.removeTags = (tagsString) => { + return Tags.RemoveTagsFrom(obj, tagsString); + }; + obj.matchesTagsQuery = (tagsQuery) => { + return Tags.MatchesQuery(obj, tagsQuery); + }; + } + /** + * Removes tags support + * @param obj defines the object to use + */ + static DisableFor(obj) { + delete obj._tags; + delete obj.hasTags; + delete obj.addTags; + delete obj.removeTags; + delete obj.matchesTagsQuery; + } + /** + * Gets a boolean indicating if the given object has tags + * @param obj defines the object to use + * @returns a boolean + */ + static HasTags(obj) { + if (!obj._tags) { + return false; + } + const tags = obj._tags; + for (const i in tags) { + if (Object.prototype.hasOwnProperty.call(tags, i)) { + return true; + } + } + return false; + } + /** + * Gets the tags available on a given object + * @param obj defines the object to use + * @param asString defines if the tags must be returned as a string instead of an array of strings + * @returns the tags + */ + static GetTags(obj, asString = true) { + if (!obj._tags) { + return null; + } + if (asString) { + const tagsArray = []; + for (const tag in obj._tags) { + if (Object.prototype.hasOwnProperty.call(obj._tags, tag) && obj._tags[tag] === true) { + tagsArray.push(tag); + } + } + return tagsArray.join(" "); + } + else { + return obj._tags; + } + } + /** + * Adds tags to an object + * @param obj defines the object to use + * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags. + * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces + */ + static AddTagsTo(obj, tagsString) { + if (!tagsString) { + return; + } + if (typeof tagsString !== "string") { + return; + } + const tags = tagsString.split(" "); + tags.forEach(function (tag) { + Tags._AddTagTo(obj, tag); + }); + } + /** + * @internal + */ + static _AddTagTo(obj, tag) { + tag = tag.trim(); + if (tag === "" || tag === "true" || tag === "false") { + return; + } + if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) { + return; + } + Tags.EnableFor(obj); + obj._tags[tag] = true; + } + /** + * Removes specific tags from a specific object + * @param obj defines the object to use + * @param tagsString defines the tags to remove + */ + static RemoveTagsFrom(obj, tagsString) { + if (!Tags.HasTags(obj)) { + return; + } + const tags = tagsString.split(" "); + for (const t in tags) { + Tags._RemoveTagFrom(obj, tags[t]); + } + } + /** + * @internal + */ + static _RemoveTagFrom(obj, tag) { + delete obj._tags[tag]; + } + /** + * Defines if tags hosted on an object match a given query + * @param obj defines the object to use + * @param tagsQuery defines the tag query + * @returns a boolean + */ + static MatchesQuery(obj, tagsQuery) { + if (tagsQuery === undefined) { + return true; + } + if (tagsQuery === "") { + return Tags.HasTags(obj); + } + return AndOrNotEvaluator.Eval(tagsQuery, (r) => Tags.HasTags(obj) && obj._tags[r]); + } +} + +const _copySource = function (creationFunction, source, instanciate, options = {}) { + const destination = creationFunction(); + // Tags + if (Tags && Tags.HasTags(source)) { + Tags.AddTagsTo(destination, Tags.GetTags(source, true)); + } + const classStore = GetMergedStore(destination); + // Map from source texture uniqueId to destination texture + const textureMap = {}; + // Properties + for (const property in classStore) { + const propertyDescriptor = classStore[property]; + const sourceProperty = source[property]; + const propertyType = propertyDescriptor.type; + if (sourceProperty !== undefined && sourceProperty !== null && (property !== "uniqueId" || SerializationHelper.AllowLoadingUniqueId)) { + switch (propertyType) { + case 0: // Value + case 6: // Mesh reference + case 9: // Image processing configuration reference + case 11: // Camera reference + destination[property] = sourceProperty; + break; + case 1: // Texture + if (options.cloneTexturesOnlyOnce && textureMap[sourceProperty.uniqueId]) { + destination[property] = textureMap[sourceProperty.uniqueId]; + } + else { + destination[property] = instanciate || sourceProperty.isRenderTarget ? sourceProperty : sourceProperty.clone(); + textureMap[sourceProperty.uniqueId] = destination[property]; + } + break; + case 2: // Color3 + case 3: // FresnelParameters + case 4: // Vector2 + case 5: // Vector3 + case 7: // Color Curves + case 8: // Color 4 + case 10: // Quaternion + case 12: // Matrix + destination[property] = instanciate ? sourceProperty : sourceProperty.clone(); + break; + } + } + } + return destination; +}; +/** + * Class used to help serialization objects + */ +class SerializationHelper { + /** + * Appends the serialized animations from the source animations + * @param source Source containing the animations + * @param destination Target to store the animations + */ + static AppendSerializedAnimations(source, destination) { + if (source.animations) { + destination.animations = []; + for (let animationIndex = 0; animationIndex < source.animations.length; animationIndex++) { + const animation = source.animations[animationIndex]; + destination.animations.push(animation.serialize()); + } + } + } + /** + * Static function used to serialized a specific entity + * @param entity defines the entity to serialize + * @param serializationObject defines the optional target object where serialization data will be stored + * @returns a JSON compatible object representing the serialization of the entity + */ + static Serialize(entity, serializationObject) { + if (!serializationObject) { + serializationObject = {}; + } + // Tags + if (Tags) { + serializationObject.tags = Tags.GetTags(entity); + } + const serializedProperties = GetMergedStore(entity); + // Properties + for (const property in serializedProperties) { + const propertyDescriptor = serializedProperties[property]; + const targetPropertyName = propertyDescriptor.sourceName || property; + const propertyType = propertyDescriptor.type; + const sourceProperty = entity[property]; + if (sourceProperty !== undefined && sourceProperty !== null && (property !== "uniqueId" || SerializationHelper.AllowLoadingUniqueId)) { + switch (propertyType) { + case 0: // Value + serializationObject[targetPropertyName] = sourceProperty; + break; + case 1: // Texture + serializationObject[targetPropertyName] = sourceProperty.serialize(); + break; + case 2: // Color3 + serializationObject[targetPropertyName] = sourceProperty.asArray(); + break; + case 3: // FresnelParameters + serializationObject[targetPropertyName] = sourceProperty.serialize(); + break; + case 4: // Vector2 + serializationObject[targetPropertyName] = sourceProperty.asArray(); + break; + case 5: // Vector3 + serializationObject[targetPropertyName] = sourceProperty.asArray(); + break; + case 6: // Mesh reference + serializationObject[targetPropertyName] = sourceProperty.id; + break; + case 7: // Color Curves + serializationObject[targetPropertyName] = sourceProperty.serialize(); + break; + case 8: // Color 4 + serializationObject[targetPropertyName] = sourceProperty.asArray(); + break; + case 9: // Image Processing + serializationObject[targetPropertyName] = sourceProperty.serialize(); + break; + case 10: // Quaternion + serializationObject[targetPropertyName] = sourceProperty.asArray(); + break; + case 11: // Camera reference + serializationObject[targetPropertyName] = sourceProperty.id; + break; + case 12: // Matrix + serializationObject[targetPropertyName] = sourceProperty.asArray(); + break; + } + } + } + return serializationObject; + } + /** + * Given a source json and a destination object in a scene, this function will parse the source and will try to apply its content to the destination object + * @param source the source json data + * @param destination the destination object + * @param scene the scene where the object is + * @param rootUrl root url to use to load assets + */ + static ParseProperties(source, destination, scene, rootUrl) { + if (!rootUrl) { + rootUrl = ""; + } + const classStore = GetMergedStore(destination); + // Properties + for (const property in classStore) { + const propertyDescriptor = classStore[property]; + const sourceProperty = source[propertyDescriptor.sourceName || property]; + const propertyType = propertyDescriptor.type; + if (sourceProperty !== undefined && sourceProperty !== null && (property !== "uniqueId" || SerializationHelper.AllowLoadingUniqueId)) { + const dest = destination; + switch (propertyType) { + case 0: // Value + dest[property] = sourceProperty; + break; + case 1: // Texture + if (scene) { + dest[property] = SerializationHelper._TextureParser(sourceProperty, scene, rootUrl); + } + break; + case 2: // Color3 + dest[property] = Color3.FromArray(sourceProperty); + break; + case 3: // FresnelParameters + dest[property] = SerializationHelper._FresnelParametersParser(sourceProperty); + break; + case 4: // Vector2 + dest[property] = Vector2.FromArray(sourceProperty); + break; + case 5: // Vector3 + dest[property] = Vector3.FromArray(sourceProperty); + break; + case 6: // Mesh reference + if (scene) { + dest[property] = scene.getLastMeshById(sourceProperty); + } + break; + case 7: // Color Curves + dest[property] = SerializationHelper._ColorCurvesParser(sourceProperty); + break; + case 8: // Color 4 + dest[property] = Color4.FromArray(sourceProperty); + break; + case 9: // Image Processing + dest[property] = SerializationHelper._ImageProcessingConfigurationParser(sourceProperty); + break; + case 10: // Quaternion + dest[property] = Quaternion.FromArray(sourceProperty); + break; + case 11: // Camera reference + if (scene) { + dest[property] = scene.getCameraById(sourceProperty); + } + break; + case 12: // Matrix + dest[property] = Matrix.FromArray(sourceProperty); + break; + } + } + } + } + /** + * Creates a new entity from a serialization data object + * @param creationFunction defines a function used to instanciated the new entity + * @param source defines the source serialization data + * @param scene defines the hosting scene + * @param rootUrl defines the root url for resources + * @returns a new entity + */ + static Parse(creationFunction, source, scene, rootUrl = null) { + const destination = creationFunction(); + // Tags + if (Tags) { + Tags.AddTagsTo(destination, source.tags); + } + SerializationHelper.ParseProperties(source, destination, scene, rootUrl); + return destination; + } + /** + * Clones an object + * @param creationFunction defines the function used to instanciate the new object + * @param source defines the source object + * @param options defines the options to use + * @returns the cloned object + */ + static Clone(creationFunction, source, options = {}) { + return _copySource(creationFunction, source, false, options); + } + /** + * Instanciates a new object based on a source one (some data will be shared between both object) + * @param creationFunction defines the function used to instanciate the new object + * @param source defines the source object + * @returns the new object + */ + static Instanciate(creationFunction, source) { + return _copySource(creationFunction, source, true); + } +} +/** + * Gets or sets a boolean to indicate if the UniqueId property should be serialized + */ +SerializationHelper.AllowLoadingUniqueId = false; +/** + * @internal + */ +SerializationHelper._ImageProcessingConfigurationParser = (sourceProperty) => { + throw _WarnImport("ImageProcessingConfiguration"); +}; +/** + * @internal + */ +SerializationHelper._FresnelParametersParser = (sourceProperty) => { + throw _WarnImport("FresnelParameters"); +}; +/** + * @internal + */ +SerializationHelper._ColorCurvesParser = (sourceProperty) => { + throw _WarnImport("ColorCurves"); +}; +/** + * @internal + */ +SerializationHelper._TextureParser = (sourceProperty, scene, rootUrl) => { + throw _WarnImport("Texture"); +}; + +/** + * Base class of all the textures in babylon. + * It groups all the common properties the materials, post process, lights... might need + * in order to make a correct use of the texture. + */ +class BaseTexture extends ThinTexture { + /** + * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance). + */ + set hasAlpha(value) { + if (this._hasAlpha === value) { + return; + } + this._hasAlpha = value; + if (this._scene) { + this._scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this); + }); + } + } + get hasAlpha() { + return this._hasAlpha; + } + /** + * Defines if the alpha value should be determined via the rgb values. + * If true the luminance of the pixel might be used to find the corresponding alpha value. + */ + set getAlphaFromRGB(value) { + if (this._getAlphaFromRGB === value) { + return; + } + this._getAlphaFromRGB = value; + if (this._scene) { + this._scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this); + }); + } + } + get getAlphaFromRGB() { + return this._getAlphaFromRGB; + } + /** + * Define the UV channel to use starting from 0 and defaulting to 0. + * This is part of the texture as textures usually maps to one uv set. + */ + set coordinatesIndex(value) { + if (this._coordinatesIndex === value) { + return; + } + this._coordinatesIndex = value; + if (this._scene) { + this._scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this); + }); + } + } + get coordinatesIndex() { + return this._coordinatesIndex; + } + /** + * How a texture is mapped. + * + * | Value | Type | Description | + * | ----- | ----------------------------------- | ----------- | + * | 0 | EXPLICIT_MODE | | + * | 1 | SPHERICAL_MODE | | + * | 2 | PLANAR_MODE | | + * | 3 | CUBIC_MODE | | + * | 4 | PROJECTION_MODE | | + * | 5 | SKYBOX_MODE | | + * | 6 | INVCUBIC_MODE | | + * | 7 | EQUIRECTANGULAR_MODE | | + * | 8 | FIXED_EQUIRECTANGULAR_MODE | | + * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | | + */ + set coordinatesMode(value) { + if (this._coordinatesMode === value) { + return; + } + this._coordinatesMode = value; + if (this._scene) { + this._scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this); + }); + } + } + get coordinatesMode() { + return this._coordinatesMode; + } + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + get wrapU() { + return this._wrapU; + } + set wrapU(value) { + this._wrapU = value; + } + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + get wrapV() { + return this._wrapV; + } + set wrapV(value) { + this._wrapV = value; + } + /** + * Define if the texture is a cube texture or if false a 2d texture. + */ + get isCube() { + if (!this._texture) { + return this._isCube; + } + return this._texture.isCube; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + set isCube(value) { + if (!this._texture) { + this._isCube = value; + } + else { + this._texture.isCube = value; + } + } + /** + * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture. + */ + get is3D() { + if (!this._texture) { + return false; + } + return this._texture.is3D; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + set is3D(value) { + if (!this._texture) { + return; + } + this._texture.is3D = value; + } + /** + * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture. + */ + get is2DArray() { + if (!this._texture) { + return false; + } + return this._texture.is2DArray; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + set is2DArray(value) { + if (!this._texture) { + return; + } + this._texture.is2DArray = value; + } + /** + * Define if the texture contains data in gamma space (most of the png/jpg aside bump). + * HDR texture are usually stored in linear space. + * This only impacts the PBR and Background materials + */ + get gammaSpace() { + if (!this._texture) { + return this._gammaSpace; + } + else { + if (this._texture._gammaSpace === null) { + this._texture._gammaSpace = this._gammaSpace; + } + } + return this._texture._gammaSpace && !this._texture._useSRGBBuffer; + } + set gammaSpace(gamma) { + if (!this._texture) { + if (this._gammaSpace === gamma) { + return; + } + this._gammaSpace = gamma; + } + else { + if (this._texture._gammaSpace === gamma) { + return; + } + this._texture._gammaSpace = gamma; + } + this.getScene()?.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this); + }); + } + /** + * Gets or sets whether or not the texture contains RGBD data. + */ + get isRGBD() { + return this._texture != null && this._texture._isRGBD; + } + set isRGBD(value) { + if (value === this.isRGBD) { + return; + } + if (this._texture) { + this._texture._isRGBD = value; + } + this.getScene()?.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this); + }); + } + /** + * Are mip maps generated for this texture or not. + */ + get noMipmap() { + return false; + } + /** + * With prefiltered texture, defined the offset used during the prefiltering steps. + */ + get lodGenerationOffset() { + if (this._texture) { + return this._texture._lodGenerationOffset; + } + return 0.0; + } + set lodGenerationOffset(value) { + if (this._texture) { + this._texture._lodGenerationOffset = value; + } + } + /** + * With prefiltered texture, defined the scale used during the prefiltering steps. + */ + get lodGenerationScale() { + if (this._texture) { + return this._texture._lodGenerationScale; + } + return 0.0; + } + set lodGenerationScale(value) { + if (this._texture) { + this._texture._lodGenerationScale = value; + } + } + /** + * With prefiltered texture, defined if the specular generation is based on a linear ramp. + * By default we are using a log2 of the linear roughness helping to keep a better resolution for + * average roughness values. + */ + get linearSpecularLOD() { + if (this._texture) { + return this._texture._linearSpecularLOD; + } + return false; + } + set linearSpecularLOD(value) { + if (this._texture) { + this._texture._linearSpecularLOD = value; + } + } + /** + * In case a better definition than spherical harmonics is required for the diffuse part of the environment. + * You can set the irradiance texture to rely on a texture instead of the spherical approach. + * This texture need to have the same characteristics than its parent (Cube vs 2d, coordinates mode, Gamma/Linear, RGBD). + */ + get irradianceTexture() { + if (this._texture) { + return this._texture._irradianceTexture; + } + return null; + } + set irradianceTexture(value) { + if (this._texture) { + this._texture._irradianceTexture = value; + } + } + /** + * Define the unique id of the texture in the scene. + */ + get uid() { + if (!this._uid) { + this._uid = RandomGUID(); + } + return this._uid; + } + /** + * Return a string representation of the texture. + * @returns the texture as a string + */ + toString() { + return this.name; + } + /** + * Get the class name of the texture. + * @returns "BaseTexture" + */ + getClassName() { + return "BaseTexture"; + } + /** + * Callback triggered when the texture has been disposed. + * Kept for back compatibility, you can use the onDisposeObservable instead. + */ + set onDispose(callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + } + /** + * Define if the texture is preventing a material to render or not. + * If not and the texture is not ready, the engine will use a default black texture instead. + */ + get isBlocking() { + return true; + } + /** + * Was there any loading error? + */ + get loadingError() { + return this._loadingError; + } + /** + * If a loading error occurred this object will be populated with information about the error. + */ + get errorObject() { + return this._errorObject; + } + /** + * Instantiates a new BaseTexture. + * Base class of all the textures in babylon. + * It groups all the common properties the materials, post process, lights... might need + * in order to make a correct use of the texture. + * @param sceneOrEngine Define the scene or engine the texture belongs to + * @param internalTexture Define the internal texture associated with the texture + */ + constructor(sceneOrEngine, internalTexture = null) { + super(null); + /** + * Gets or sets an object used to store user defined information. + */ + this.metadata = null; + /** + * For internal use only. Please do not use. + */ + this.reservedDataStore = null; + this._hasAlpha = false; + this._getAlphaFromRGB = false; + /** + * Intensity or strength of the texture. + * It is commonly used by materials to fine tune the intensity of the texture + */ + this.level = 1; + this._coordinatesIndex = 0; + /** + * Gets or sets a boolean indicating that the texture should try to reduce shader code if there is no UV manipulation. + * (ie. when texture.getTextureMatrix().isIdentityAs3x2() returns true) + */ + this.optimizeUVAllocation = true; + this._coordinatesMode = 0; + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + this.wrapR = 1; + /** + * With compliant hardware and browser (supporting anisotropic filtering) + * this defines the level of anisotropic filtering in the texture. + * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff. + */ + this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL; + /** @internal */ + this._isCube = false; + /** @internal */ + this._gammaSpace = true; + /** + * Is Z inverted in the texture (useful in a cube texture). + */ + this.invertZ = false; + /** + * @internal + */ + this.lodLevelInAlpha = false; + /** + * Define if the texture is a render target. + */ + this.isRenderTarget = false; + /** @internal */ + this._prefiltered = false; + /** @internal */ + this._forceSerialize = false; + /** + * Define the list of animation attached to the texture. + */ + this.animations = []; + /** + * An event triggered when the texture is disposed. + */ + this.onDisposeObservable = new Observable(); + this._onDisposeObserver = null; + this._scene = null; + /** @internal */ + this._uid = null; + /** @internal */ + this._parentContainer = null; + this._loadingError = false; + if (sceneOrEngine) { + if (BaseTexture._IsScene(sceneOrEngine)) { + this._scene = sceneOrEngine; + } + else { + this._engine = sceneOrEngine; + } + } + else { + this._scene = EngineStore.LastCreatedScene; + } + if (this._scene) { + this.uniqueId = this._scene.getUniqueId(); + this._scene.addTexture(this); + this._engine = this._scene.getEngine(); + } + this._texture = internalTexture; + this._uid = null; + } + /** + * Get the scene the texture belongs to. + * @returns the scene or null if undefined + */ + getScene() { + return this._scene; + } + /** @internal */ + _getEngine() { + return this._engine; + } + /** + * Get the texture transform matrix used to offset tile the texture for instance. + * @returns the transformation matrix + */ + getTextureMatrix() { + return Matrix.IdentityReadOnly; + } + /** + * Get the texture reflection matrix used to rotate/transform the reflection. + * @returns the reflection matrix + */ + getReflectionTextureMatrix() { + return Matrix.IdentityReadOnly; + } + /** + * Gets a suitable rotate/transform matrix when the texture is used for refraction. + * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode. + * @returns The refraction matrix + */ + getRefractionTextureMatrix() { + return this.getReflectionTextureMatrix(); + } + /** + * Get if the texture is ready to be consumed (either it is ready or it is not blocking) + * @returns true if ready, not blocking or if there was an error loading the texture + */ + isReadyOrNotBlocking() { + return !this.isBlocking || this.isReady() || this.loadingError; + } + /** + * Scales the texture if is `canRescale()` + * @param ratio the resize factor we want to use to rescale + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + scale(ratio) { } + /** + * Get if the texture can rescale. + */ + get canRescale() { + return false; + } + /** + * @internal + */ + _getFromCache(url, noMipmap, sampling, invertY, useSRGBBuffer, isCube) { + const engine = this._getEngine(); + if (!engine) { + return null; + } + const correctedUseSRGBBuffer = engine._getUseSRGBBuffer(!!useSRGBBuffer, noMipmap); + const texturesCache = engine.getLoadedTexturesCache(); + for (let index = 0; index < texturesCache.length; index++) { + const texturesCacheEntry = texturesCache[index]; + if (useSRGBBuffer === undefined || correctedUseSRGBBuffer === texturesCacheEntry._useSRGBBuffer) { + if (invertY === undefined || invertY === texturesCacheEntry.invertY) { + if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) { + if (!sampling || sampling === texturesCacheEntry.samplingMode) { + if (isCube === undefined || isCube === texturesCacheEntry.isCube) { + texturesCacheEntry.incrementReferences(); + return texturesCacheEntry; + } + } + } + } + } + } + return null; + } + /** @internal */ + _rebuild(_fromContextLost = false) { } + /** + * Clones the texture. + * @returns the cloned texture + */ + clone() { + return null; + } + /** + * Get the texture underlying type (INT, FLOAT...) + */ + get textureType() { + if (!this._texture) { + return 0; + } + return this._texture.type !== undefined ? this._texture.type : 0; + } + /** + * Get the texture underlying format (RGB, RGBA...) + */ + get textureFormat() { + if (!this._texture) { + return 5; + } + return this._texture.format !== undefined ? this._texture.format : 5; + } + /** + * Indicates that textures need to be re-calculated for all materials + */ + _markAllSubMeshesAsTexturesDirty() { + const scene = this.getScene(); + if (!scene) { + return; + } + scene.markAllMaterialsAsDirty(1); + } + /** + * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer. + * This will returns an RGBA array buffer containing either in values (0-255) or + * float values (0-1) depending of the underlying buffer type. + * @param faceIndex defines the face of the texture to read (in case of cube texture) + * @param level defines the LOD level of the texture to read (in case of Mip Maps) + * @param buffer defines a user defined buffer to fill with data (can be null) + * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels + * @param noDataConversion false to convert the data to Uint8Array (if texture type is UNSIGNED_BYTE) or to Float32Array (if texture type is anything but UNSIGNED_BYTE). If true, the type of the generated buffer (if buffer==null) will depend on the type of the texture + * @param x defines the region x coordinates to start reading from (default to 0) + * @param y defines the region y coordinates to start reading from (default to 0) + * @param width defines the region width to read from (default to the texture size at level) + * @param height defines the region width to read from (default to the texture size at level) + * @returns The Array buffer promise containing the pixels data. + */ + readPixels(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0, width = Number.MAX_VALUE, height = Number.MAX_VALUE) { + if (!this._texture) { + return null; + } + const engine = this._getEngine(); + if (!engine) { + return null; + } + const size = this.getSize(); + let maxWidth = size.width; + let maxHeight = size.height; + if (level !== 0) { + maxWidth = maxWidth / Math.pow(2, level); + maxHeight = maxHeight / Math.pow(2, level); + maxWidth = Math.round(maxWidth); + maxHeight = Math.round(maxHeight); + } + width = Math.min(maxWidth, width); + height = Math.min(maxHeight, height); + try { + if (this._texture.isCube) { + return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y); + } + return engine._readTexturePixels(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion, x, y); + } + catch (e) { + return null; + } + } + /** + * @internal + */ + _readPixelsSync(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false) { + if (!this._texture) { + return null; + } + const size = this.getSize(); + let width = size.width; + let height = size.height; + const engine = this._getEngine(); + if (!engine) { + return null; + } + if (level != 0) { + width = width / Math.pow(2, level); + height = height / Math.pow(2, level); + width = Math.round(width); + height = Math.round(height); + } + try { + if (this._texture.isCube) { + return engine._readTexturePixelsSync(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion); + } + return engine._readTexturePixelsSync(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion); + } + catch (e) { + return null; + } + } + /** @internal */ + get _lodTextureHigh() { + if (this._texture) { + return this._texture._lodTextureHigh; + } + return null; + } + /** @internal */ + get _lodTextureMid() { + if (this._texture) { + return this._texture._lodTextureMid; + } + return null; + } + /** @internal */ + get _lodTextureLow() { + if (this._texture) { + return this._texture._lodTextureLow; + } + return null; + } + /** + * Dispose the texture and release its associated resources. + */ + dispose() { + if (this._scene) { + // Animations + if (this._scene.stopAnimation) { + this._scene.stopAnimation(this); + } + // Remove from scene + this._scene.removePendingData(this); + const index = this._scene.textures.indexOf(this); + if (index >= 0) { + this._scene.textures.splice(index, 1); + } + this._scene.onTextureRemovedObservable.notifyObservers(this); + this._scene = null; + if (this._parentContainer) { + const index = this._parentContainer.textures.indexOf(this); + if (index > -1) { + this._parentContainer.textures.splice(index, 1); + } + this._parentContainer = null; + } + } + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + this.metadata = null; + super.dispose(); + } + /** + * Serialize the texture into a JSON representation that can be parsed later on. + * @param allowEmptyName True to force serialization even if name is empty. Default: false + * @returns the JSON representation of the texture + */ + serialize(allowEmptyName = false) { + if (!this.name && !allowEmptyName) { + return null; + } + const serializationObject = SerializationHelper.Serialize(this); + // Animations + SerializationHelper.AppendSerializedAnimations(this, serializationObject); + return serializationObject; + } + /** + * Helper function to be called back once a list of texture contains only ready textures. + * @param textures Define the list of textures to wait for + * @param callback Define the callback triggered once the entire list will be ready + */ + static WhenAllReady(textures, callback) { + let numRemaining = textures.length; + if (numRemaining === 0) { + callback(); + return; + } + for (let i = 0; i < textures.length; i++) { + const texture = textures[i]; + if (texture.isReady()) { + if (--numRemaining === 0) { + callback(); + } + } + else { + const onLoadObservable = texture.onLoadObservable; + if (onLoadObservable) { + onLoadObservable.addOnce(() => { + if (--numRemaining === 0) { + callback(); + } + }); + } + else { + if (--numRemaining === 0) { + callback(); + } + } + } + } + } + static _IsScene(sceneOrEngine) { + return sceneOrEngine.getClassName() === "Scene"; + } +} +/** + * Default anisotropic filtering level for the application. + * It is set to 4 as a good tradeoff between perf and quality. + */ +BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4; +__decorate([ + serialize() +], BaseTexture.prototype, "uniqueId", void 0); +__decorate([ + serialize() +], BaseTexture.prototype, "name", void 0); +__decorate([ + serialize() +], BaseTexture.prototype, "displayName", void 0); +__decorate([ + serialize() +], BaseTexture.prototype, "metadata", void 0); +__decorate([ + serialize("hasAlpha") +], BaseTexture.prototype, "_hasAlpha", void 0); +__decorate([ + serialize("getAlphaFromRGB") +], BaseTexture.prototype, "_getAlphaFromRGB", void 0); +__decorate([ + serialize() +], BaseTexture.prototype, "level", void 0); +__decorate([ + serialize("coordinatesIndex") +], BaseTexture.prototype, "_coordinatesIndex", void 0); +__decorate([ + serialize() +], BaseTexture.prototype, "optimizeUVAllocation", void 0); +__decorate([ + serialize("coordinatesMode") +], BaseTexture.prototype, "_coordinatesMode", void 0); +__decorate([ + serialize() +], BaseTexture.prototype, "wrapU", null); +__decorate([ + serialize() +], BaseTexture.prototype, "wrapV", null); +__decorate([ + serialize() +], BaseTexture.prototype, "wrapR", void 0); +__decorate([ + serialize() +], BaseTexture.prototype, "anisotropicFilteringLevel", void 0); +__decorate([ + serialize() +], BaseTexture.prototype, "isCube", null); +__decorate([ + serialize() +], BaseTexture.prototype, "is3D", null); +__decorate([ + serialize() +], BaseTexture.prototype, "is2DArray", null); +__decorate([ + serialize() +], BaseTexture.prototype, "gammaSpace", null); +__decorate([ + serialize() +], BaseTexture.prototype, "invertZ", void 0); +__decorate([ + serialize() +], BaseTexture.prototype, "lodLevelInAlpha", void 0); +__decorate([ + serialize() +], BaseTexture.prototype, "lodGenerationOffset", null); +__decorate([ + serialize() +], BaseTexture.prototype, "lodGenerationScale", null); +__decorate([ + serialize() +], BaseTexture.prototype, "linearSpecularLOD", null); +__decorate([ + serializeAsTexture() +], BaseTexture.prototype, "irradianceTexture", null); +__decorate([ + serialize() +], BaseTexture.prototype, "isRenderTarget", void 0); + +ThinEngine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = true) { + const callback = async (loadData) => { + if (!loadData) { + if (onLoad) { + onLoad(null); + } + return; + } + const texture = loadData.texture; + if (!createPolynomials) { + texture._sphericalPolynomial = new SphericalPolynomial(); + } + else if (loadData.info.sphericalPolynomial) { + texture._sphericalPolynomial = loadData.info.sphericalPolynomial; + } + texture._source = 9 /* InternalTextureSource.CubePrefiltered */; + if (this.getCaps().textureLOD) { + // Do not add extra process if texture lod is supported. + if (onLoad) { + onLoad(texture); + } + return; + } + const mipSlices = 3; + const gl = this._gl; + const width = loadData.width; + if (!width) { + return; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + const { DDSTools } = await Promise.resolve().then(() => dds); + const textures = []; + for (let i = 0; i < mipSlices; i++) { + //compute LOD from even spacing in smoothness (matching shader calculation) + const smoothness = i / (mipSlices - 1); + const roughness = 1 - smoothness; + const minLODIndex = lodOffset; // roughness = 0 + const maxLODIndex = Math.log2(width) * lodScale + lodOffset; // roughness = 1 + const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness; + const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex)); + const glTextureFromLod = new InternalTexture(this, 2 /* InternalTextureSource.Temp */); + glTextureFromLod.type = texture.type; + glTextureFromLod.format = texture.format; + glTextureFromLod.width = Math.pow(2, Math.max(Math.log2(width) - mipmapIndex, 0)); + glTextureFromLod.height = glTextureFromLod.width; + glTextureFromLod.isCube = true; + glTextureFromLod._cachedWrapU = 0; + glTextureFromLod._cachedWrapV = 0; + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true); + glTextureFromLod.samplingMode = 2; + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + if (loadData.isDDS) { + const info = loadData.info; + const data = loadData.data; + this._unpackFlipY(info.isCompressed); + DDSTools.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex); + } + else { + Logger.Warn("DDS is the only prefiltered cube map supported so far."); + } + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + // Wrap in a base texture for easy binding. + const lodTexture = new BaseTexture(scene); + lodTexture._isCube = true; + lodTexture._texture = glTextureFromLod; + glTextureFromLod.isReady = true; + textures.push(lodTexture); + } + texture._lodTextureHigh = textures[2]; + texture._lodTextureMid = textures[1]; + texture._lodTextureLow = textures[0]; + if (onLoad) { + onLoad(texture); + } + }; + return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset); +}; + +ThinEngine.prototype.createUniformBuffer = function (elements, _label) { + const ubo = this._gl.createBuffer(); + if (!ubo) { + throw new Error("Unable to create uniform buffer"); + } + const result = new WebGLDataBuffer(ubo); + this.bindUniformBuffer(result); + if (elements instanceof Float32Array) { + this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW); + } + else { + this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW); + } + this.bindUniformBuffer(null); + result.references = 1; + return result; +}; +ThinEngine.prototype.createDynamicUniformBuffer = function (elements, _label) { + const ubo = this._gl.createBuffer(); + if (!ubo) { + throw new Error("Unable to create dynamic uniform buffer"); + } + const result = new WebGLDataBuffer(ubo); + this.bindUniformBuffer(result); + if (elements instanceof Float32Array) { + this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW); + } + else { + this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW); + } + this.bindUniformBuffer(null); + result.references = 1; + return result; +}; +ThinEngine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) { + this.bindUniformBuffer(uniformBuffer); + if (offset === undefined) { + offset = 0; + } + if (count === undefined) { + if (elements instanceof Float32Array) { + this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements); + } + else { + this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements)); + } + } + else { + if (elements instanceof Float32Array) { + this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count)); + } + else { + this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count)); + } + } + this.bindUniformBuffer(null); +}; +ThinEngine.prototype.bindUniformBuffer = function (buffer) { + this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer ? buffer.underlyingResource : null); +}; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +ThinEngine.prototype.bindUniformBufferBase = function (buffer, location, name) { + this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer ? buffer.underlyingResource : null); +}; +ThinEngine.prototype.bindUniformBlock = function (pipelineContext, blockName, index) { + const program = pipelineContext.program; + const uniformLocation = this._gl.getUniformBlockIndex(program, blockName); + if (uniformLocation !== 0xffffffff) { + this._gl.uniformBlockBinding(program, uniformLocation, index); + } +}; + +AbstractEngine.prototype.displayLoadingUI = function () { + if (!IsWindowObjectExist()) { + return; + } + const loadingScreen = this.loadingScreen; + if (loadingScreen) { + loadingScreen.displayLoadingUI(); + } +}; +AbstractEngine.prototype.hideLoadingUI = function () { + if (!IsWindowObjectExist()) { + return; + } + const loadingScreen = this._loadingScreen; + if (loadingScreen) { + loadingScreen.hideLoadingUI(); + } +}; +Object.defineProperty(AbstractEngine.prototype, "loadingScreen", { + get: function () { + if (!this._loadingScreen && this._renderingCanvas) { + this._loadingScreen = AbstractEngine.DefaultLoadingScreenFactory(this._renderingCanvas); + } + return this._loadingScreen; + }, + set: function (value) { + this._loadingScreen = value; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(AbstractEngine.prototype, "loadingUIText", { + set: function (value) { + this.loadingScreen.loadingUIText = value; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(AbstractEngine.prototype, "loadingUIBackgroundColor", { + set: function (value) { + this.loadingScreen.loadingUIBackgroundColor = value; + }, + enumerable: true, + configurable: true, +}); + +AbstractEngine.prototype.getInputElement = function () { + return this._renderingCanvas; +}; +AbstractEngine.prototype.getRenderingCanvasClientRect = function () { + if (!this._renderingCanvas) { + return null; + } + return this._renderingCanvas.getBoundingClientRect(); +}; +AbstractEngine.prototype.getInputElementClientRect = function () { + if (!this._renderingCanvas) { + return null; + } + return this.getInputElement().getBoundingClientRect(); +}; +AbstractEngine.prototype.getAspectRatio = function (viewportOwner, useScreen = false) { + const viewport = viewportOwner.viewport; + return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height); +}; +AbstractEngine.prototype.getScreenAspectRatio = function () { + return this.getRenderWidth(true) / this.getRenderHeight(true); +}; +AbstractEngine.prototype._verifyPointerLock = function () { + this._onPointerLockChange?.(); +}; + +AbstractEngine.prototype.setAlphaEquation = function (equation) { + if (this._alphaEquation === equation) { + return; + } + switch (equation) { + case 0: + this._alphaState.setAlphaEquationParameters(32774, 32774); + break; + case 1: + this._alphaState.setAlphaEquationParameters(32778, 32778); + break; + case 2: + this._alphaState.setAlphaEquationParameters(32779, 32779); + break; + case 3: + this._alphaState.setAlphaEquationParameters(32776, 32776); + break; + case 4: + this._alphaState.setAlphaEquationParameters(32775, 32775); + break; + case 5: + this._alphaState.setAlphaEquationParameters(32775, 32774); + break; + } + this._alphaEquation = equation; +}; + +AbstractEngine.prototype.getInputElement = function () { + return this._renderingCanvas; +}; +AbstractEngine.prototype.getDepthFunction = function () { + return this._depthCullingState.depthFunc; +}; +AbstractEngine.prototype.setDepthFunction = function (depthFunc) { + this._depthCullingState.depthFunc = depthFunc; +}; +AbstractEngine.prototype.setDepthFunctionToGreater = function () { + this.setDepthFunction(516); +}; +AbstractEngine.prototype.setDepthFunctionToGreaterOrEqual = function () { + this.setDepthFunction(518); +}; +AbstractEngine.prototype.setDepthFunctionToLess = function () { + this.setDepthFunction(513); +}; +AbstractEngine.prototype.setDepthFunctionToLessOrEqual = function () { + this.setDepthFunction(515); +}; +AbstractEngine.prototype.getDepthWrite = function () { + return this._depthCullingState.depthMask; +}; +AbstractEngine.prototype.setDepthWrite = function (enable) { + this._depthCullingState.depthMask = enable; +}; +AbstractEngine.prototype.getStencilBuffer = function () { + return this._stencilState.stencilTest; +}; +AbstractEngine.prototype.setStencilBuffer = function (enable) { + this._stencilState.stencilTest = enable; +}; +AbstractEngine.prototype.getStencilMask = function () { + return this._stencilState.stencilMask; +}; +AbstractEngine.prototype.setStencilMask = function (mask) { + this._stencilState.stencilMask = mask; +}; +AbstractEngine.prototype.getStencilFunction = function () { + return this._stencilState.stencilFunc; +}; +AbstractEngine.prototype.getStencilFunctionReference = function () { + return this._stencilState.stencilFuncRef; +}; +AbstractEngine.prototype.getStencilFunctionMask = function () { + return this._stencilState.stencilFuncMask; +}; +AbstractEngine.prototype.setStencilFunction = function (stencilFunc) { + this._stencilState.stencilFunc = stencilFunc; +}; +AbstractEngine.prototype.setStencilFunctionReference = function (reference) { + this._stencilState.stencilFuncRef = reference; +}; +AbstractEngine.prototype.setStencilFunctionMask = function (mask) { + this._stencilState.stencilFuncMask = mask; +}; +AbstractEngine.prototype.getStencilOperationFail = function () { + return this._stencilState.stencilOpStencilFail; +}; +AbstractEngine.prototype.getStencilOperationDepthFail = function () { + return this._stencilState.stencilOpDepthFail; +}; +AbstractEngine.prototype.getStencilOperationPass = function () { + return this._stencilState.stencilOpStencilDepthPass; +}; +AbstractEngine.prototype.setStencilOperationFail = function (operation) { + this._stencilState.stencilOpStencilFail = operation; +}; +AbstractEngine.prototype.setStencilOperationDepthFail = function (operation) { + this._stencilState.stencilOpDepthFail = operation; +}; +AbstractEngine.prototype.setStencilOperationPass = function (operation) { + this._stencilState.stencilOpStencilDepthPass = operation; +}; +AbstractEngine.prototype.cacheStencilState = function () { + this._cachedStencilBuffer = this.getStencilBuffer(); + this._cachedStencilFunction = this.getStencilFunction(); + this._cachedStencilMask = this.getStencilMask(); + this._cachedStencilOperationPass = this.getStencilOperationPass(); + this._cachedStencilOperationFail = this.getStencilOperationFail(); + this._cachedStencilOperationDepthFail = this.getStencilOperationDepthFail(); + this._cachedStencilReference = this.getStencilFunctionReference(); +}; +AbstractEngine.prototype.restoreStencilState = function () { + this.setStencilFunction(this._cachedStencilFunction); + this.setStencilMask(this._cachedStencilMask); + this.setStencilBuffer(this._cachedStencilBuffer); + this.setStencilOperationPass(this._cachedStencilOperationPass); + this.setStencilOperationFail(this._cachedStencilOperationFail); + this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail); + this.setStencilFunctionReference(this._cachedStencilReference); +}; +AbstractEngine.prototype.setAlphaConstants = function (r, g, b, a) { + this._alphaState.setAlphaBlendConstants(r, g, b, a); +}; +AbstractEngine.prototype.getAlphaMode = function () { + return this._alphaMode; +}; +AbstractEngine.prototype.getAlphaEquation = function () { + return this._alphaEquation; +}; + +AbstractEngine.prototype.getRenderPassNames = function () { + return this._renderPassNames; +}; +AbstractEngine.prototype.getCurrentRenderPassName = function () { + return this._renderPassNames[this.currentRenderPassId]; +}; +AbstractEngine.prototype.createRenderPassId = function (name) { + // Note: render pass id == 0 is always for the main render pass + const id = ++AbstractEngine._RenderPassIdCounter; + this._renderPassNames[id] = name ?? "NONAME"; + return id; +}; +AbstractEngine.prototype.releaseRenderPassId = function (id) { + this._renderPassNames[id] = undefined; + for (let s = 0; s < this.scenes.length; ++s) { + const scene = this.scenes[s]; + for (let m = 0; m < scene.meshes.length; ++m) { + const mesh = scene.meshes[m]; + if (mesh.subMeshes) { + for (let b = 0; b < mesh.subMeshes.length; ++b) { + const subMesh = mesh.subMeshes[b]; + subMesh._removeDrawWrapper(id); + } + } + } + } +}; + +/** @internal */ +function _DisableTouchAction(canvas) { + if (!canvas || !canvas.setAttribute) { + return; + } + canvas.setAttribute("touch-action", "none"); + canvas.style.touchAction = "none"; + canvas.style.webkitTapHighlightColor = "transparent"; +} +/** @internal */ +function _CommonInit(commonEngine, canvas, creationOptions) { + commonEngine._onCanvasFocus = () => { + commonEngine.onCanvasFocusObservable.notifyObservers(commonEngine); + }; + commonEngine._onCanvasBlur = () => { + commonEngine.onCanvasBlurObservable.notifyObservers(commonEngine); + }; + commonEngine._onCanvasContextMenu = (evt) => { + if (commonEngine.disableContextMenu) { + evt.preventDefault(); + } + }; + canvas.addEventListener("focus", commonEngine._onCanvasFocus); + canvas.addEventListener("blur", commonEngine._onCanvasBlur); + canvas.addEventListener("contextmenu", commonEngine._onCanvasContextMenu); + commonEngine._onBlur = () => { + if (commonEngine.disablePerformanceMonitorInBackground) { + commonEngine.performanceMonitor.disable(); + } + commonEngine._windowIsBackground = true; + }; + commonEngine._onFocus = () => { + if (commonEngine.disablePerformanceMonitorInBackground) { + commonEngine.performanceMonitor.enable(); + } + commonEngine._windowIsBackground = false; + }; + commonEngine._onCanvasPointerOut = (ev) => { + // Check that the element at the point of the pointer out isn't the canvas and if it isn't, notify observers + // Note: This is a workaround for a bug with Safari + if (document.elementFromPoint(ev.clientX, ev.clientY) !== canvas) { + commonEngine.onCanvasPointerOutObservable.notifyObservers(ev); + } + }; + const hostWindow = commonEngine.getHostWindow(); // it calls IsWindowObjectExist() + if (hostWindow && typeof hostWindow.addEventListener === "function") { + hostWindow.addEventListener("blur", commonEngine._onBlur); + hostWindow.addEventListener("focus", commonEngine._onFocus); + } + canvas.addEventListener("pointerout", commonEngine._onCanvasPointerOut); + if (!creationOptions.doNotHandleTouchAction) { + _DisableTouchAction(canvas); + } + // Create Audio Engine if needed. + if (!AbstractEngine.audioEngine && creationOptions.audioEngine && AbstractEngine.AudioEngineFactory) { + AbstractEngine.audioEngine = AbstractEngine.AudioEngineFactory(commonEngine.getRenderingCanvas(), commonEngine.getAudioContext(), commonEngine.getAudioDestination()); + } + if (IsDocumentAvailable()) { + // Fullscreen + commonEngine._onFullscreenChange = () => { + commonEngine.isFullscreen = !!document.fullscreenElement; + // Pointer lock + if (commonEngine.isFullscreen && commonEngine._pointerLockRequested && canvas) { + RequestPointerlock(canvas); + } + }; + document.addEventListener("fullscreenchange", commonEngine._onFullscreenChange, false); + document.addEventListener("webkitfullscreenchange", commonEngine._onFullscreenChange, false); + // Pointer lock + commonEngine._onPointerLockChange = () => { + commonEngine.isPointerLock = document.pointerLockElement === canvas; + }; + document.addEventListener("pointerlockchange", commonEngine._onPointerLockChange, false); + document.addEventListener("webkitpointerlockchange", commonEngine._onPointerLockChange, false); + } + commonEngine.enableOfflineSupport = AbstractEngine.OfflineProviderFactory !== undefined; + commonEngine._deterministicLockstep = !!creationOptions.deterministicLockstep; + commonEngine._lockstepMaxSteps = creationOptions.lockstepMaxSteps || 0; + commonEngine._timeStep = creationOptions.timeStep || 1 / 60; +} +/** @internal */ +function _CommonDispose(commonEngine, canvas) { + // Release audio engine + if (EngineStore.Instances.length === 1 && AbstractEngine.audioEngine) { + AbstractEngine.audioEngine.dispose(); + AbstractEngine.audioEngine = null; + } + // Events + const hostWindow = commonEngine.getHostWindow(); // it calls IsWindowObjectExist() + if (hostWindow && typeof hostWindow.removeEventListener === "function") { + hostWindow.removeEventListener("blur", commonEngine._onBlur); + hostWindow.removeEventListener("focus", commonEngine._onFocus); + } + if (canvas) { + canvas.removeEventListener("focus", commonEngine._onCanvasFocus); + canvas.removeEventListener("blur", commonEngine._onCanvasBlur); + canvas.removeEventListener("pointerout", commonEngine._onCanvasPointerOut); + canvas.removeEventListener("contextmenu", commonEngine._onCanvasContextMenu); + } + if (IsDocumentAvailable()) { + document.removeEventListener("fullscreenchange", commonEngine._onFullscreenChange); + document.removeEventListener("mozfullscreenchange", commonEngine._onFullscreenChange); + document.removeEventListener("webkitfullscreenchange", commonEngine._onFullscreenChange); + document.removeEventListener("msfullscreenchange", commonEngine._onFullscreenChange); + document.removeEventListener("pointerlockchange", commonEngine._onPointerLockChange); + document.removeEventListener("mspointerlockchange", commonEngine._onPointerLockChange); + document.removeEventListener("mozpointerlockchange", commonEngine._onPointerLockChange); + document.removeEventListener("webkitpointerlockchange", commonEngine._onPointerLockChange); + } +} +/** + * Get Font size information + * @param font font name + * @returns an object containing ascent, height and descent + */ +function GetFontOffset(font) { + const text = document.createElement("span"); + text.textContent = "Hg"; + text.style.font = font; + const block = document.createElement("div"); + block.style.display = "inline-block"; + block.style.width = "1px"; + block.style.height = "0px"; + block.style.verticalAlign = "bottom"; + const div = document.createElement("div"); + div.style.whiteSpace = "nowrap"; + div.appendChild(text); + div.appendChild(block); + document.body.appendChild(div); + let fontAscent = 0; + let fontHeight = 0; + try { + fontHeight = block.getBoundingClientRect().top - text.getBoundingClientRect().top; + block.style.verticalAlign = "baseline"; + fontAscent = block.getBoundingClientRect().top - text.getBoundingClientRect().top; + } + finally { + document.body.removeChild(div); + } + return { ascent: fontAscent, height: fontHeight, descent: fontHeight - fontAscent }; +} +/** @internal */ +function CreateImageBitmapFromSource(engine, imageSource, options) { + const promise = new Promise((resolve, reject) => { + const image = new Image(); + image.onload = () => { + image.decode().then(() => { + engine.createImageBitmap(image, options).then((imageBitmap) => { + resolve(imageBitmap); + }); + }); + }; + image.onerror = () => { + reject(`Error loading image ${image.src}`); + }; + image.src = imageSource; + }); + return promise; +} +/** @internal */ +function ResizeImageBitmap(engine, image, bufferWidth, bufferHeight) { + const canvas = engine.createCanvas(bufferWidth, bufferHeight); + const context = canvas.getContext("2d"); + if (!context) { + throw new Error("Unable to get 2d context for resizeImageBitmap"); + } + context.drawImage(image, 0, 0); + // Create VertexData from map data + // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949 + const buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data; + return buffer; +} +/** + * Ask the browser to promote the current element to fullscreen rendering mode + * @param element defines the DOM element to promote + */ +function RequestFullscreen(element) { + const requestFunction = element.requestFullscreen || element.webkitRequestFullscreen; + if (!requestFunction) { + return; + } + requestFunction.call(element); +} +/** + * Asks the browser to exit fullscreen mode + */ +function ExitFullscreen() { + const anyDoc = document; + if (document.exitFullscreen) { + document.exitFullscreen(); + } + else if (anyDoc.webkitCancelFullScreen) { + anyDoc.webkitCancelFullScreen(); + } +} +/** + * Ask the browser to promote the current element to pointerlock mode + * @param element defines the DOM element to promote + */ +function RequestPointerlock(element) { + if (element.requestPointerLock) { + // In some browsers, requestPointerLock returns a promise. + // Handle possible rejections to avoid an unhandled top-level exception. + const promise = element.requestPointerLock(); + if (promise instanceof Promise) + promise + .then(() => { + element.focus(); + }) + .catch(() => { }); + else + element.focus(); + } +} +/** + * Asks the browser to exit pointerlock mode + */ +function ExitPointerlock() { + if (document.exitPointerLock) { + document.exitPointerLock(); + } +} + +/** + * This class is used to track a performance counter which is number based. + * The user has access to many properties which give statistics of different nature. + * + * The implementer can track two kinds of Performance Counter: time and count. + * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored. + * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor. + */ +class PerfCounter { + /** + * Returns the smallest value ever + */ + get min() { + return this._min; + } + /** + * Returns the biggest value ever + */ + get max() { + return this._max; + } + /** + * Returns the average value since the performance counter is running + */ + get average() { + return this._average; + } + /** + * Returns the average value of the last second the counter was monitored + */ + get lastSecAverage() { + return this._lastSecAverage; + } + /** + * Returns the current value + */ + get current() { + return this._current; + } + /** + * Gets the accumulated total + */ + get total() { + return this._totalAccumulated; + } + /** + * Gets the total value count + */ + get count() { + return this._totalValueCount; + } + /** + * Creates a new counter + */ + constructor() { + this._startMonitoringTime = 0; + this._min = 0; + this._max = 0; + this._average = 0; + this._lastSecAverage = 0; + this._current = 0; + this._totalValueCount = 0; + this._totalAccumulated = 0; + this._lastSecAccumulated = 0; + this._lastSecTime = 0; + this._lastSecValueCount = 0; + } + /** + * Call this method to start monitoring a new frame. + * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count. + */ + fetchNewFrame() { + this._totalValueCount++; + this._current = 0; + this._lastSecValueCount++; + } + /** + * Call this method to monitor a count of something (e.g. mesh drawn in viewport count) + * @param newCount the count value to add to the monitored count + * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics. + */ + addCount(newCount, fetchResult) { + if (!PerfCounter.Enabled) { + return; + } + this._current += newCount; + if (fetchResult) { + this._fetchResult(); + } + } + /** + * Start monitoring this performance counter + */ + beginMonitoring() { + if (!PerfCounter.Enabled) { + return; + } + this._startMonitoringTime = PrecisionDate.Now; + } + /** + * Compute the time lapsed since the previous beginMonitoring() call. + * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter + */ + endMonitoring(newFrame = true) { + if (!PerfCounter.Enabled) { + return; + } + if (newFrame) { + this.fetchNewFrame(); + } + const currentTime = PrecisionDate.Now; + this._current = currentTime - this._startMonitoringTime; + if (newFrame) { + this._fetchResult(); + } + } + /** + * Call this method to end the monitoring of a frame. + * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the end of the frame, after beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count. + */ + endFrame() { + this._fetchResult(); + } + /** @internal */ + _fetchResult() { + this._totalAccumulated += this._current; + this._lastSecAccumulated += this._current; + // Min/Max update + this._min = Math.min(this._min, this._current); + this._max = Math.max(this._max, this._current); + this._average = this._totalAccumulated / this._totalValueCount; + // Reset last sec? + const now = PrecisionDate.Now; + if (now - this._lastSecTime > 1000) { + this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount; + this._lastSecTime = now; + this._lastSecAccumulated = 0; + this._lastSecValueCount = 0; + } + } +} +/** + * Gets or sets a global boolean to turn on and off all the counters + */ +PerfCounter.Enabled = true; + +/** + * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio + */ +class Engine extends ThinEngine { + /** + * Returns the current npm package of the sdk + */ + // Not mixed with Version for tooling purpose. + static get NpmPackage() { + return AbstractEngine.NpmPackage; + } + /** + * Returns the current version of the framework + */ + static get Version() { + return AbstractEngine.Version; + } + /** Gets the list of created engines */ + static get Instances() { + return EngineStore.Instances; + } + /** + * Gets the latest created engine + */ + static get LastCreatedEngine() { + return EngineStore.LastCreatedEngine; + } + /** + * Gets the latest created scene + */ + static get LastCreatedScene() { + return EngineStore.LastCreatedScene; + } + /** @internal */ + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Method called to create the default loading screen. + * This can be overridden in your own app. + * @param canvas The rendering canvas element + * @returns The loading screen + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static DefaultLoadingScreenFactory(canvas) { + return AbstractEngine.DefaultLoadingScreenFactory(canvas); + } + get _supportsHardwareTextureRescaling() { + return !!Engine._RescalePostProcessFactory; + } + _measureFps() { + this._performanceMonitor.sampleFrame(); + this._fps = this._performanceMonitor.averageFPS; + this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0; + } + /** + * Gets the performance monitor attached to this engine + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation + */ + get performanceMonitor() { + return this._performanceMonitor; + } + // Events + /** + * Creates a new engine + * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which already used the WebGL context + * @param antialias defines enable antialiasing (default: false) + * @param options defines further options to be sent to the getContext() function + * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false) + */ + constructor(canvasOrContext, antialias, options, adaptToDeviceRatio = false) { + super(canvasOrContext, antialias, options, adaptToDeviceRatio); + // Members + /** + * If set, will be used to request the next animation frame for the render loop + */ + this.customAnimationFrameRequester = null; + this._performanceMonitor = new PerformanceMonitor(); + this._drawCalls = new PerfCounter(); + if (!canvasOrContext) { + return; + } + this._features.supportRenderPasses = true; + options = this._creationOptions; + } + _initGLContext() { + super._initGLContext(); + this._rescalePostProcess = null; + } + /** + * Shared initialization across engines types. + * @param canvas The canvas associated with this instance of the engine. + */ + _sharedInit(canvas) { + super._sharedInit(canvas); + _CommonInit(this, canvas, this._creationOptions); + } + /** + * Resize an image and returns the image data as an uint8array + * @param image image to resize + * @param bufferWidth destination buffer width + * @param bufferHeight destination buffer height + * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size + */ + resizeImageBitmap(image, bufferWidth, bufferHeight) { + return ResizeImageBitmap(this, image, bufferWidth, bufferHeight); + } + /** + * Engine abstraction for loading and creating an image bitmap from a given source string. + * @param imageSource source to load the image from. + * @param options An object that sets options for the image's extraction. + * @returns ImageBitmap + */ + _createImageBitmapFromSource(imageSource, options) { + return CreateImageBitmapFromSource(this, imageSource, options); + } + /** + * Toggle full screen mode + * @param requestPointerLock defines if a pointer lock should be requested from the user + */ + switchFullscreen(requestPointerLock) { + if (this.isFullscreen) { + this.exitFullscreen(); + } + else { + this.enterFullscreen(requestPointerLock); + } + } + /** + * Enters full screen mode + * @param requestPointerLock defines if a pointer lock should be requested from the user + */ + enterFullscreen(requestPointerLock) { + if (!this.isFullscreen) { + this._pointerLockRequested = requestPointerLock; + if (this._renderingCanvas) { + RequestFullscreen(this._renderingCanvas); + } + } + } + /** + * Exits full screen mode + */ + exitFullscreen() { + if (this.isFullscreen) { + ExitFullscreen(); + } + } + /** States */ + /** + * Sets a boolean indicating if the dithering state is enabled or disabled + * @param value defines the dithering state + */ + setDitheringState(value) { + if (value) { + this._gl.enable(this._gl.DITHER); + } + else { + this._gl.disable(this._gl.DITHER); + } + } + /** + * Sets a boolean indicating if the rasterizer state is enabled or disabled + * @param value defines the rasterizer state + */ + setRasterizerState(value) { + if (value) { + this._gl.disable(this._gl.RASTERIZER_DISCARD); + } + else { + this._gl.enable(this._gl.RASTERIZER_DISCARD); + } + } + /** + * Directly set the WebGL Viewport + * @param x defines the x coordinate of the viewport (in screen space) + * @param y defines the y coordinate of the viewport (in screen space) + * @param width defines the width of the viewport (in screen space) + * @param height defines the height of the viewport (in screen space) + * @returns the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state + */ + setDirectViewport(x, y, width, height) { + const currentViewport = this._cachedViewport; + this._cachedViewport = null; + this._viewport(x, y, width, height); + return currentViewport; + } + /** + * Executes a scissor clear (ie. a clear on a specific portion of the screen) + * @param x defines the x-coordinate of the bottom left corner of the clear rectangle + * @param y defines the y-coordinate of the corner of the clear rectangle + * @param width defines the width of the clear rectangle + * @param height defines the height of the clear rectangle + * @param clearColor defines the clear color + */ + scissorClear(x, y, width, height, clearColor) { + this.enableScissor(x, y, width, height); + this.clear(clearColor, true, true, true); + this.disableScissor(); + } + /** + * Enable scissor test on a specific rectangle (ie. render will only be executed on a specific portion of the screen) + * @param x defines the x-coordinate of the bottom left corner of the clear rectangle + * @param y defines the y-coordinate of the corner of the clear rectangle + * @param width defines the width of the clear rectangle + * @param height defines the height of the clear rectangle + */ + enableScissor(x, y, width, height) { + const gl = this._gl; + // Change state + gl.enable(gl.SCISSOR_TEST); + gl.scissor(x, y, width, height); + } + /** + * Disable previously set scissor test rectangle + */ + disableScissor() { + const gl = this._gl; + gl.disable(gl.SCISSOR_TEST); + } + /** + * @internal + */ + _loadFileAsync(url, offlineProvider, useArrayBuffer) { + return new Promise((resolve, reject) => { + this._loadFile(url, (data) => { + resolve(data); + }, undefined, offlineProvider, useArrayBuffer, (request, exception) => { + reject(exception); + }); + }); + } + /** + * Gets the source code of the vertex shader associated with a specific webGL program + * @param program defines the program to use + * @returns a string containing the source code of the vertex shader associated with the program + */ + getVertexShaderSource(program) { + const shaders = this._gl.getAttachedShaders(program); + if (!shaders) { + return null; + } + return this._gl.getShaderSource(shaders[0]); + } + /** + * Gets the source code of the fragment shader associated with a specific webGL program + * @param program defines the program to use + * @returns a string containing the source code of the fragment shader associated with the program + */ + getFragmentShaderSource(program) { + const shaders = this._gl.getAttachedShaders(program); + if (!shaders) { + return null; + } + return this._gl.getShaderSource(shaders[1]); + } + /** + * sets the object from which width and height will be taken from when getting render width and height + * Will fallback to the gl object + * @param dimensions the framebuffer width and height that will be used. + */ + set framebufferDimensionsObject(dimensions) { + this._framebufferDimensionsObject = dimensions; + if (this._framebufferDimensionsObject) { + this.onResizeObservable.notifyObservers(this); + } + } + _rebuildBuffers() { + // Index / Vertex + for (const scene of this.scenes) { + scene.resetCachedMaterial(); + scene._rebuildGeometries(); + } + for (const scene of this._virtualScenes) { + scene.resetCachedMaterial(); + scene._rebuildGeometries(); + } + super._rebuildBuffers(); + } + /** + * Get Font size information + * @param font font name + * @returns an object containing ascent, height and descent + */ + getFontOffset(font) { + return GetFontOffset(font); + } + _cancelFrame() { + if (this.customAnimationFrameRequester) { + if (this._frameHandler !== 0) { + this._frameHandler = 0; + const { cancelAnimationFrame } = this.customAnimationFrameRequester; + if (cancelAnimationFrame) { + cancelAnimationFrame(this.customAnimationFrameRequester.requestID); + } + } + } + else { + super._cancelFrame(); + } + } + _renderLoop(timestamp) { + this._processFrame(timestamp); + // The first condition prevents queuing another frame if we no longer have active render loops (e.g., if + // `stopRenderLoop` is called mid frame). The second condition prevents queuing another frame if one has + // already been queued (e.g., if `stopRenderLoop` and `runRenderLoop` is called mid frame). + if (this._activeRenderLoops.length > 0 && this._frameHandler === 0) { + if (this.customAnimationFrameRequester) { + this.customAnimationFrameRequester.requestID = this._queueNewFrame(this.customAnimationFrameRequester.renderFunction || this._boundRenderFunction, this.customAnimationFrameRequester); + this._frameHandler = this.customAnimationFrameRequester.requestID; + } + else { + this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()); + } + } + } + /** + * Enters Pointerlock mode + */ + enterPointerlock() { + if (this._renderingCanvas) { + RequestPointerlock(this._renderingCanvas); + } + } + /** + * Exits Pointerlock mode + */ + exitPointerlock() { + ExitPointerlock(); + } + /** + * Begin a new frame + */ + beginFrame() { + this._measureFps(); + super.beginFrame(); + } + _deletePipelineContext(pipelineContext) { + const webGLPipelineContext = pipelineContext; + if (webGLPipelineContext && webGLPipelineContext.program) { + if (webGLPipelineContext.transformFeedback) { + this.deleteTransformFeedback(webGLPipelineContext.transformFeedback); + webGLPipelineContext.transformFeedback = null; + } + } + super._deletePipelineContext(pipelineContext); + } + createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) { + context = context || this._gl; + this.onBeforeShaderCompilationObservable.notifyObservers(this); + const program = super.createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings); + this.onAfterShaderCompilationObservable.notifyObservers(this); + return program; + } + _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings = null) { + const shaderProgram = context.createProgram(); + pipelineContext.program = shaderProgram; + if (!shaderProgram) { + throw new Error("Unable to create program"); + } + context.attachShader(shaderProgram, vertexShader); + context.attachShader(shaderProgram, fragmentShader); + if (this.webGLVersion > 1 && transformFeedbackVaryings) { + const transformFeedback = this.createTransformFeedback(); + this.bindTransformFeedback(transformFeedback); + this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings); + pipelineContext.transformFeedback = transformFeedback; + } + context.linkProgram(shaderProgram); + if (this.webGLVersion > 1 && transformFeedbackVaryings) { + this.bindTransformFeedback(null); + } + pipelineContext.context = context; + pipelineContext.vertexShader = vertexShader; + pipelineContext.fragmentShader = fragmentShader; + if (!pipelineContext.isParallelCompiled) { + this._finalizePipelineContext(pipelineContext); + } + return shaderProgram; + } + /** + * @internal + */ + _releaseTexture(texture) { + super._releaseTexture(texture); + } + /** + * @internal + */ + _releaseRenderTargetWrapper(rtWrapper) { + super._releaseRenderTargetWrapper(rtWrapper); + // Set output texture of post process to null if the framebuffer has been released/disposed + this.scenes.forEach((scene) => { + scene.postProcesses.forEach((postProcess) => { + if (postProcess._outputTexture === rtWrapper) { + postProcess._outputTexture = null; + } + }); + scene.cameras.forEach((camera) => { + camera._postProcesses.forEach((postProcess) => { + if (postProcess) { + if (postProcess._outputTexture === rtWrapper) { + postProcess._outputTexture = null; + } + } + }); + }); + }); + } + /** + * @internal + * Rescales a texture + * @param source input texture + * @param destination destination texture + * @param scene scene to use to render the resize + * @param internalFormat format to use when resizing + * @param onComplete callback to be called when resize has completed + */ + _rescaleTexture(source, destination, scene, internalFormat, onComplete) { + this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR); + this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR); + this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE); + this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE); + const rtt = this.createRenderTargetTexture({ + width: destination.width, + height: destination.height, + }, { + generateMipMaps: false, + type: 0, + samplingMode: 2, + generateDepthBuffer: false, + generateStencilBuffer: false, + }); + if (!this._rescalePostProcess && Engine._RescalePostProcessFactory) { + this._rescalePostProcess = Engine._RescalePostProcessFactory(this); + } + if (this._rescalePostProcess) { + this._rescalePostProcess.externalTextureSamplerBinding = true; + const onCompiled = () => { + this._rescalePostProcess.onApply = function (effect) { + effect._bindTexture("textureSampler", source); + }; + let hostingScene = scene; + if (!hostingScene) { + hostingScene = this.scenes[this.scenes.length - 1]; + } + hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true); + this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true); + this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0); + this.unBindFramebuffer(rtt); + rtt.dispose(); + if (onComplete) { + onComplete(); + } + }; + const effect = this._rescalePostProcess.getEffect(); + if (effect) { + effect.executeWhenCompiled(onCompiled); + } + else { + this._rescalePostProcess.onEffectCreatedObservable.addOnce((effect) => { + effect.executeWhenCompiled(onCompiled); + }); + } + } + } + /** + * Wraps an external web gl texture in a Babylon texture. + * @param texture defines the external texture + * @param hasMipMaps defines whether the external texture has mip maps (default: false) + * @param samplingMode defines the sampling mode for the external texture (default: 3) + * @param width defines the width for the external texture (default: 0) + * @param height defines the height for the external texture (default: 0) + * @returns the babylon internal texture + */ + wrapWebGLTexture(texture, hasMipMaps = false, samplingMode = 3, width = 0, height = 0) { + const hardwareTexture = new WebGLHardwareTexture(texture, this._gl); + const internalTexture = new InternalTexture(this, 0 /* InternalTextureSource.Unknown */, true); + internalTexture._hardwareTexture = hardwareTexture; + internalTexture.baseWidth = width; + internalTexture.baseHeight = height; + internalTexture.width = width; + internalTexture.height = height; + internalTexture.isReady = true; + internalTexture.useMipMaps = hasMipMaps; + this.updateTextureSamplingMode(samplingMode, internalTexture); + return internalTexture; + } + /** + * @internal + */ + _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) { + const gl = this._gl; + const textureType = this._getWebGLTextureType(texture.type); + const format = this._getInternalFormat(texture.format); + const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format); + const bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; + this._bindTextureDirectly(bindTarget, texture, true); + this._unpackFlipY(texture.invertY); + let target = gl.TEXTURE_2D; + if (texture.isCube) { + target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; + } + gl.texImage2D(target, lod, internalFormat, format, textureType, image); + this._bindTextureDirectly(bindTarget, null, true); + } + /** + * Updates a depth texture Comparison Mode and Function. + * If the comparison Function is equal to 0, the mode will be set to none. + * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader. + * @param texture The texture to set the comparison function for + * @param comparisonFunction The comparison function to set, 0 if no comparison required + */ + updateTextureComparisonFunction(texture, comparisonFunction) { + if (this.webGLVersion === 1) { + Logger.Error("WebGL 1 does not support texture comparison."); + return; + } + const gl = this._gl; + if (texture.isCube) { + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true); + if (comparisonFunction === 0) { + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, 515); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE); + } + else { + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE); + } + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); + } + else { + this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); + if (comparisonFunction === 0) { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, 515); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE); + } + else { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE); + } + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + } + texture._comparisonFunction = comparisonFunction; + } + /** + * Creates a webGL buffer to use with instantiation + * @param capacity defines the size of the buffer + * @returns the webGL buffer + */ + createInstancesBuffer(capacity) { + const buffer = this._gl.createBuffer(); + if (!buffer) { + throw new Error("Unable to create instance buffer"); + } + const result = new WebGLDataBuffer(buffer); + result.capacity = capacity; + this.bindArrayBuffer(result); + this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW); + result.references = 1; + return result; + } + /** + * Delete a webGL buffer used with instantiation + * @param buffer defines the webGL buffer to delete + */ + deleteInstancesBuffer(buffer) { + this._gl.deleteBuffer(buffer); + } + _clientWaitAsync(sync, flags = 0, intervalms = 10) { + const gl = this._gl; + return new Promise((resolve, reject) => { + _retryWithInterval(() => { + const res = gl.clientWaitSync(sync, flags, 0); + if (res == gl.WAIT_FAILED) { + throw new Error("clientWaitSync failed"); + } + if (res == gl.TIMEOUT_EXPIRED) { + return false; + } + return true; + }, resolve, reject, intervalms); + }); + } + /** + * @internal + */ + _readPixelsAsync(x, y, w, h, format, type, outputBuffer) { + if (this._webGLVersion < 2) { + throw new Error("_readPixelsAsync only work on WebGL2+"); + } + const gl = this._gl; + const buf = gl.createBuffer(); + gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf); + gl.bufferData(gl.PIXEL_PACK_BUFFER, outputBuffer.byteLength, gl.STREAM_READ); + gl.readPixels(x, y, w, h, format, type, 0); + gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null); + const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0); + if (!sync) { + return null; + } + gl.flush(); + return this._clientWaitAsync(sync, 0, 10).then(() => { + gl.deleteSync(sync); + gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf); + gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, outputBuffer); + gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null); + gl.deleteBuffer(buf); + return outputBuffer; + }); + } + dispose() { + this.hideLoadingUI(); + // Rescale PP + if (this._rescalePostProcess) { + this._rescalePostProcess.dispose(); + } + _CommonDispose(this, this._renderingCanvas); + super.dispose(); + } +} +// Const statics +/** Defines that alpha blending is disabled */ +Engine.ALPHA_DISABLE = 0; +/** Defines that alpha blending to SRC ALPHA * SRC + DEST */ +Engine.ALPHA_ADD = 1; +/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */ +Engine.ALPHA_COMBINE = 2; +/** Defines that alpha blending to DEST - SRC * DEST */ +Engine.ALPHA_SUBTRACT = 3; +/** Defines that alpha blending to SRC * DEST */ +Engine.ALPHA_MULTIPLY = 4; +/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */ +Engine.ALPHA_MAXIMIZED = 5; +/** Defines that alpha blending to SRC + DEST */ +Engine.ALPHA_ONEONE = 6; +/** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */ +Engine.ALPHA_PREMULTIPLIED = 7; +/** + * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST + * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA + */ +Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8; +/** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */ +Engine.ALPHA_INTERPOLATE = 9; +/** + * Defines that alpha blending to SRC + (1 - SRC) * DEST + * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA + */ +Engine.ALPHA_SCREENMODE = 10; +/** Defines that the resource is not delayed*/ +Engine.DELAYLOADSTATE_NONE = 0; +/** Defines that the resource was successfully delay loaded */ +Engine.DELAYLOADSTATE_LOADED = 1; +/** Defines that the resource is currently delay loading */ +Engine.DELAYLOADSTATE_LOADING = 2; +/** Defines that the resource is delayed and has not started loading */ +Engine.DELAYLOADSTATE_NOTLOADED = 4; +// Depht or Stencil test Constants. +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */ +Engine.NEVER = 512; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */ +Engine.ALWAYS = 519; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */ +Engine.LESS = 513; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */ +Engine.EQUAL = 514; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */ +Engine.LEQUAL = 515; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */ +Engine.GREATER = 516; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */ +Engine.GEQUAL = 518; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */ +Engine.NOTEQUAL = 517; +// Stencil Actions Constants. +/** Passed to stencilOperation to specify that stencil value must be kept */ +Engine.KEEP = 7680; +/** Passed to stencilOperation to specify that stencil value must be replaced */ +Engine.REPLACE = 7681; +/** Passed to stencilOperation to specify that stencil value must be incremented */ +Engine.INCR = 7682; +/** Passed to stencilOperation to specify that stencil value must be decremented */ +Engine.DECR = 7683; +/** Passed to stencilOperation to specify that stencil value must be inverted */ +Engine.INVERT = 5386; +/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */ +Engine.INCR_WRAP = 34055; +/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */ +Engine.DECR_WRAP = 34056; +/** Texture is not repeating outside of 0..1 UVs */ +Engine.TEXTURE_CLAMP_ADDRESSMODE = 0; +/** Texture is repeating outside of 0..1 UVs */ +Engine.TEXTURE_WRAP_ADDRESSMODE = 1; +/** Texture is repeating and mirrored */ +Engine.TEXTURE_MIRROR_ADDRESSMODE = 2; +/** ALPHA */ +Engine.TEXTUREFORMAT_ALPHA = 0; +/** LUMINANCE */ +Engine.TEXTUREFORMAT_LUMINANCE = 1; +/** LUMINANCE_ALPHA */ +Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2; +/** RGB */ +Engine.TEXTUREFORMAT_RGB = 4; +/** RGBA */ +Engine.TEXTUREFORMAT_RGBA = 5; +/** RED */ +Engine.TEXTUREFORMAT_RED = 6; +/** RED (2nd reference) */ +Engine.TEXTUREFORMAT_R = 6; +/** RED unsigned short normed to [0, 1] **/ +Engine.TEXTUREFORMAT_R16_UNORM = 33322; +/** RG unsigned short normed to [0, 1] **/ +Engine.TEXTUREFORMAT_RG16_UNORM = 33324; +/** RGB unsigned short normed to [0, 1] **/ +Engine.TEXTUREFORMAT_RGB16_UNORM = 32852; +/** RGBA unsigned short normed to [0, 1] **/ +Engine.TEXTUREFORMAT_RGBA16_UNORM = 32859; +/** RED signed short normed to [-1, 1] **/ +Engine.TEXTUREFORMAT_R16_SNORM = 36760; +/** RG signed short normed to [-1, 1] **/ +Engine.TEXTUREFORMAT_RG16_SNORM = 36761; +/** RGB signed short normed to [-1, 1] **/ +Engine.TEXTUREFORMAT_RGB16_SNORM = 36762; +/** RGBA signed short normed to [-1, 1] **/ +Engine.TEXTUREFORMAT_RGBA16_SNORM = 36763; +/** RG */ +Engine.TEXTUREFORMAT_RG = 7; +/** RED_INTEGER */ +Engine.TEXTUREFORMAT_RED_INTEGER = 8; +/** RED_INTEGER (2nd reference) */ +Engine.TEXTUREFORMAT_R_INTEGER = 8; +/** RG_INTEGER */ +Engine.TEXTUREFORMAT_RG_INTEGER = 9; +/** RGB_INTEGER */ +Engine.TEXTUREFORMAT_RGB_INTEGER = 10; +/** RGBA_INTEGER */ +Engine.TEXTUREFORMAT_RGBA_INTEGER = 11; +/** UNSIGNED_BYTE */ +Engine.TEXTURETYPE_UNSIGNED_BYTE = 0; +/** @deprecated use more explicit TEXTURETYPE_UNSIGNED_BYTE instead. Use TEXTURETYPE_UNSIGNED_INTEGER for 32bits values.*/ +Engine.TEXTURETYPE_UNSIGNED_INT = 0; +/** FLOAT */ +Engine.TEXTURETYPE_FLOAT = 1; +/** HALF_FLOAT */ +Engine.TEXTURETYPE_HALF_FLOAT = 2; +/** BYTE */ +Engine.TEXTURETYPE_BYTE = 3; +/** SHORT */ +Engine.TEXTURETYPE_SHORT = 4; +/** UNSIGNED_SHORT */ +Engine.TEXTURETYPE_UNSIGNED_SHORT = 5; +/** INT */ +Engine.TEXTURETYPE_INT = 6; +/** UNSIGNED_INT */ +Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7; +/** UNSIGNED_SHORT_4_4_4_4 */ +Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8; +/** UNSIGNED_SHORT_5_5_5_1 */ +Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9; +/** UNSIGNED_SHORT_5_6_5 */ +Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10; +/** UNSIGNED_INT_2_10_10_10_REV */ +Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11; +/** UNSIGNED_INT_24_8 */ +Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12; +/** UNSIGNED_INT_10F_11F_11F_REV */ +Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13; +/** UNSIGNED_INT_5_9_9_9_REV */ +Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14; +/** FLOAT_32_UNSIGNED_INT_24_8_REV */ +Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15; +/** nearest is mag = nearest and min = nearest and mip = none */ +Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1; +/** Bilinear is mag = linear and min = linear and mip = nearest */ +Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2; +/** Trilinear is mag = linear and min = linear and mip = linear */ +Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3; +/** nearest is mag = nearest and min = nearest and mip = linear */ +Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8; +/** Bilinear is mag = linear and min = linear and mip = nearest */ +Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11; +/** Trilinear is mag = linear and min = linear and mip = linear */ +Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3; +/** mag = nearest and min = nearest and mip = nearest */ +Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4; +/** mag = nearest and min = linear and mip = nearest */ +Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5; +/** mag = nearest and min = linear and mip = linear */ +Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6; +/** mag = nearest and min = linear and mip = none */ +Engine.TEXTURE_NEAREST_LINEAR = 7; +/** mag = nearest and min = nearest and mip = none */ +Engine.TEXTURE_NEAREST_NEAREST = 1; +/** mag = linear and min = nearest and mip = nearest */ +Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9; +/** mag = linear and min = nearest and mip = linear */ +Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10; +/** mag = linear and min = linear and mip = none */ +Engine.TEXTURE_LINEAR_LINEAR = 2; +/** mag = linear and min = nearest and mip = none */ +Engine.TEXTURE_LINEAR_NEAREST = 12; +/** Explicit coordinates mode */ +Engine.TEXTURE_EXPLICIT_MODE = 0; +/** Spherical coordinates mode */ +Engine.TEXTURE_SPHERICAL_MODE = 1; +/** Planar coordinates mode */ +Engine.TEXTURE_PLANAR_MODE = 2; +/** Cubic coordinates mode */ +Engine.TEXTURE_CUBIC_MODE = 3; +/** Projection coordinates mode */ +Engine.TEXTURE_PROJECTION_MODE = 4; +/** Skybox coordinates mode */ +Engine.TEXTURE_SKYBOX_MODE = 5; +/** Inverse Cubic coordinates mode */ +Engine.TEXTURE_INVCUBIC_MODE = 6; +/** Equirectangular coordinates mode */ +Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7; +/** Equirectangular Fixed coordinates mode */ +Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8; +/** Equirectangular Fixed Mirrored coordinates mode */ +Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; +// Texture rescaling mode +/** Defines that texture rescaling will use a floor to find the closer power of 2 size */ +Engine.SCALEMODE_FLOOR = 1; +/** Defines that texture rescaling will look for the nearest power of 2 size */ +Engine.SCALEMODE_NEAREST = 2; +/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */ +Engine.SCALEMODE_CEILING = 3; + +class Monobehiver { + mainApp; + constructor(mainApp) { + this.mainApp = mainApp; + } + /** 醒来/初始化,子类可重写 */ + // eslint-disable-next-line @typescript-eslint/no-empty-function + Awake() { + } +} + +const AppConfig = { + container: document.querySelector("#renderDom"), + modelUrlList: [], + env: { + envPath: "/hdr/sanGiuseppeBridge.env", + intensity: 1.5, + rotationY: 0, + background: true + } +}; + +class AppEngin extends Monobehiver { + object; + canvas; + constructor(mainApp) { + super(mainApp); + this.object = null; + this.canvas = null; + } + Awake() { + this.canvas = AppConfig.container; + if (!this.canvas) { + throw new Error("Render canvas not found"); + } + this.object = new Engine(this.canvas, true, { + preserveDrawingBuffer: false, + // 不保留绘图缓冲区 + stencil: true, + // 启用模板缓冲 + alpha: true + // 启用透明背景 + }); + this.object.setSize(window.innerWidth, window.innerHeight); + this.object.setHardwareScalingLevel(1); + } + /** 处理窗口大小变化 */ + handleResize() { + if (this.object) { + this.object.setSize(window.innerWidth, window.innerHeight); + this.object.resize(); + } + } +} + +const CloneValue = (source, destinationObject, shallowCopyValues) => { + if (!source) { + return null; + } + if (source.getClassName && source.getClassName() === "Mesh") { + return null; + } + if (source.getClassName && (source.getClassName() === "SubMesh" || source.getClassName() === "PhysicsBody")) { + return source.clone(destinationObject); + } + else if (source.clone) { + return source.clone(); + } + else if (Array.isArray(source)) { + return source.slice(); + } + else if (shallowCopyValues && typeof source === "object") { + return { ...source }; + } + return null; +}; +function GetAllPropertyNames(obj) { + const props = []; + do { + Object.getOwnPropertyNames(obj).forEach(function (prop) { + if (props.indexOf(prop) === -1) { + props.push(prop); + } + }); + } while ((obj = Object.getPrototypeOf(obj))); + return props; +} +/** + * Class containing a set of static utilities functions for deep copy. + */ +class DeepCopier { + /** + * Tries to copy an object by duplicating every property + * @param source defines the source object + * @param destination defines the target object + * @param doNotCopyList defines a list of properties to avoid + * @param mustCopyList defines a list of properties to copy (even if they start with _) + * @param shallowCopyValues defines wether properties referencing objects (none cloneable) must be shallow copied (false by default) + * @remarks shallowCopyValues will not instantite the copied values which makes it only usable for "JSON objects" + */ + static DeepCopy(source, destination, doNotCopyList, mustCopyList, shallowCopyValues = false) { + const properties = GetAllPropertyNames(source); + for (const prop of properties) { + if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) { + continue; + } + if (prop.endsWith("Observable")) { + continue; + } + if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) { + continue; + } + const sourceValue = source[prop]; + const typeOfSourceValue = typeof sourceValue; + if (typeOfSourceValue === "function") { + continue; + } + try { + if (typeOfSourceValue === "object") { + if (sourceValue instanceof Uint8Array) { + destination[prop] = Uint8Array.from(sourceValue); + } + else if (sourceValue instanceof Array) { + destination[prop] = []; + if (sourceValue.length > 0) { + if (typeof sourceValue[0] == "object") { + for (let index = 0; index < sourceValue.length; index++) { + const clonedValue = CloneValue(sourceValue[index], destination, shallowCopyValues); + if (destination[prop].indexOf(clonedValue) === -1) { + // Test if auto inject was not done + destination[prop].push(clonedValue); + } + } + } + else { + destination[prop] = sourceValue.slice(0); + } + } + } + else { + destination[prop] = CloneValue(sourceValue, destination, shallowCopyValues); + } + } + else { + destination[prop] = sourceValue; + } + } + catch (e) { + // Log a warning (it could be because of a read-only property) + Logger.Warn(e.message); + } + } + } +} + +/** + * Class used to enable instantiation of objects by class name + */ +class InstantiationTools { + /** + * Tries to instantiate a new object from a given class name + * @param className defines the class name to instantiate + * @returns the new object or null if the system was not able to do the instantiation + */ + static Instantiate(className) { + if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[className]) { + return this.RegisteredExternalClasses[className]; + } + const internalClass = GetClass(className); + if (internalClass) { + return internalClass; + } + Logger.Warn(className + " not found, you may have missed an import."); + const arr = className.split("."); + let fn = window || this; + for (let i = 0, len = arr.length; i < len; i++) { + fn = fn[arr[i]]; + } + if (typeof fn !== "function") { + return null; + } + return fn; + } +} +/** + * Use this object to register external classes like custom textures or material + * to allow the loaders to instantiate them + */ +InstantiationTools.RegisteredExternalClasses = {}; + +/** + * Class containing a set of static utilities functions + */ +class Tools { + /** + * Gets or sets the base URL to use to load assets + */ + static get BaseUrl() { + return FileToolsOptions.BaseUrl; + } + static set BaseUrl(value) { + FileToolsOptions.BaseUrl = value; + } + /** + * Gets or sets the clean URL function to use to load assets + */ + static get CleanUrl() { + return FileToolsOptions.CleanUrl; + } + static set CleanUrl(value) { + FileToolsOptions.CleanUrl = value; + } + /** + * This function checks whether a URL is absolute or not. + * It will also detect data and blob URLs + * @param url the url to check + * @returns is the url absolute or relative + */ + static IsAbsoluteUrl(url) { + // See https://stackoverflow.com/a/38979205. + // URL is protocol-relative (= absolute) + if (url.indexOf("//") === 0) { + return true; + } + // URL has no protocol (= relative) + if (url.indexOf("://") === -1) { + return false; + } + // URL does not contain a dot, i.e. no TLD (= relative, possibly REST) + if (url.indexOf(".") === -1) { + return false; + } + // URL does not contain a single slash (= relative) + if (url.indexOf("/") === -1) { + return false; + } + // The first colon comes after the first slash (= relative) + if (url.indexOf(":") > url.indexOf("/")) { + return false; + } + // Protocol is defined before first dot (= absolute) + if (url.indexOf("://") < url.indexOf(".")) { + return true; + } + if (url.indexOf("data:") === 0 || url.indexOf("blob:") === 0) { + return true; + } + // Anything else must be relative + return false; + } + /** + * Sets the base URL to use to load scripts + */ + static set ScriptBaseUrl(value) { + FileToolsOptions.ScriptBaseUrl = value; + } + static get ScriptBaseUrl() { + return FileToolsOptions.ScriptBaseUrl; + } + /** + * Sets both the script base URL and the assets base URL to the same value. + * Setter only! + */ + static set CDNBaseUrl(value) { + Tools.ScriptBaseUrl = value; + Tools.AssetBaseUrl = value; + } + /** + * Sets a preprocessing function to run on a source URL before importing it + * Note that this function will execute AFTER the base URL is appended to the URL + */ + static set ScriptPreprocessUrl(func) { + FileToolsOptions.ScriptPreprocessUrl = func; + } + static get ScriptPreprocessUrl() { + return FileToolsOptions.ScriptPreprocessUrl; + } + /** + * Gets or sets the retry strategy to apply when an error happens while loading an asset + */ + static get DefaultRetryStrategy() { + return FileToolsOptions.DefaultRetryStrategy; + } + static set DefaultRetryStrategy(strategy) { + FileToolsOptions.DefaultRetryStrategy = strategy; + } + /** + * Default behavior for cors in the application. + * It can be a string if the expected behavior is identical in the entire app. + * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance) + */ + static get CorsBehavior() { + return FileToolsOptions.CorsBehavior; + } + static set CorsBehavior(value) { + FileToolsOptions.CorsBehavior = value; + } + /** + * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded + * @ignorenaming + */ + static get UseFallbackTexture() { + return EngineStore.UseFallbackTexture; + } + static set UseFallbackTexture(value) { + EngineStore.UseFallbackTexture = value; + } + /** + * Use this object to register external classes like custom textures or material + * to allow the loaders to instantiate them + */ + static get RegisteredExternalClasses() { + return InstantiationTools.RegisteredExternalClasses; + } + static set RegisteredExternalClasses(classes) { + InstantiationTools.RegisteredExternalClasses = classes; + } + /** + * Texture content used if a texture cannot loaded + * @ignorenaming + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + static get fallbackTexture() { + return EngineStore.FallbackTexture; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + static set fallbackTexture(value) { + EngineStore.FallbackTexture = value; + } + /** + * Read the content of a byte array at a specified coordinates (taking in account wrapping) + * @param u defines the coordinate on X axis + * @param v defines the coordinate on Y axis + * @param width defines the width of the source data + * @param height defines the height of the source data + * @param pixels defines the source byte array + * @param color defines the output color + */ + static FetchToRef(u, v, width, height, pixels, color) { + const wrappedU = (Math.abs(u) * width) % width | 0; + const wrappedV = (Math.abs(v) * height) % height | 0; + const position = (wrappedU + wrappedV * width) * 4; + color.r = pixels[position] / 255; + color.g = pixels[position + 1] / 255; + color.b = pixels[position + 2] / 255; + color.a = pixels[position + 3] / 255; + } + /** + * Interpolates between a and b via alpha + * @param a The lower value (returned when alpha = 0) + * @param b The upper value (returned when alpha = 1) + * @param alpha The interpolation-factor + * @returns The mixed value + */ + static Mix(a, b, alpha) { + return 0; + } + /** + * Tries to instantiate a new object from a given class name + * @param className defines the class name to instantiate + * @returns the new object or null if the system was not able to do the instantiation + */ + static Instantiate(className) { + return InstantiationTools.Instantiate(className); + } + /** + * Polyfill for setImmediate + * @param action defines the action to execute after the current execution block + */ + static SetImmediate(action) { + TimingTools.SetImmediate(action); + } + /** + * Function indicating if a number is an exponent of 2 + * @param value defines the value to test + * @returns true if the value is an exponent of 2 + */ + static IsExponentOfTwo(value) { + return true; + } + /** + * Returns the nearest 32-bit single precision float representation of a Number + * @param value A Number. If the parameter is of a different type, it will get converted + * to a number or to NaN if it cannot be converted + * @returns number + */ + static FloatRound(value) { + return Math.fround(value); + } + /** + * Extracts the filename from a path + * @param path defines the path to use + * @returns the filename + */ + static GetFilename(path) { + const index = path.lastIndexOf("/"); + if (index < 0) { + return path; + } + return path.substring(index + 1); + } + /** + * Extracts the "folder" part of a path (everything before the filename). + * @param uri The URI to extract the info from + * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present + * @returns The "folder" part of the path + */ + static GetFolderPath(uri, returnUnchangedIfNoSlash = false) { + const index = uri.lastIndexOf("/"); + if (index < 0) { + if (returnUnchangedIfNoSlash) { + return uri; + } + return ""; + } + return uri.substring(0, index + 1); + } + /** + * Convert an angle in radians to degrees + * @param angle defines the angle to convert + * @returns the angle in degrees + */ + static ToDegrees(angle) { + return (angle * 180) / Math.PI; + } + /** + * Convert an angle in degrees to radians + * @param angle defines the angle to convert + * @returns the angle in radians + */ + static ToRadians(angle) { + return (angle * Math.PI) / 180; + } + /** + * Smooth angle changes (kind of low-pass filter), in particular for device orientation "shaking" + * Use trigonometric functions to avoid discontinuity (0/360, -180/180) + * @param previousAngle defines last angle value, in degrees + * @param newAngle defines new angle value, in degrees + * @param smoothFactor defines smoothing sensitivity; min 0: no smoothing, max 1: new data ignored + * @returns the angle in degrees + */ + static SmoothAngleChange(previousAngle, newAngle, smoothFactor = 0.9) { + const previousAngleRad = this.ToRadians(previousAngle); + const newAngleRad = this.ToRadians(newAngle); + return this.ToDegrees(Math.atan2((1 - smoothFactor) * Math.sin(newAngleRad) + smoothFactor * Math.sin(previousAngleRad), (1 - smoothFactor) * Math.cos(newAngleRad) + smoothFactor * Math.cos(previousAngleRad))); + } + /** + * Returns an array if obj is not an array + * @param obj defines the object to evaluate as an array + * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined + * @returns either obj directly if obj is an array or a new array containing obj + */ + static MakeArray(obj, allowsNullUndefined) { + if (allowsNullUndefined !== true && (obj === undefined || obj == null)) { + return null; + } + return Array.isArray(obj) ? obj : [obj]; + } + /** + * Gets the pointer prefix to use + * @param engine defines the engine we are finding the prefix for + * @returns "pointer" if touch is enabled. Else returns "mouse" + */ + static GetPointerPrefix(engine) { + return IsWindowObjectExist() && !window.PointerEvent ? "mouse" : "pointer"; + } + /** + * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element. + * @param url define the url we are trying + * @param element define the dom element where to configure the cors policy + * @param element.crossOrigin + */ + static SetCorsBehavior(url, element) { + SetCorsBehavior(url, element); + } + /** + * Sets the referrerPolicy behavior on a dom element. + * @param referrerPolicy define the referrer policy to use + * @param element define the dom element where to configure the referrer policy + * @param element.referrerPolicy + */ + static SetReferrerPolicyBehavior(referrerPolicy, element) { + element.referrerPolicy = referrerPolicy; + } + // External files + /** + * Gets or sets a function used to pre-process url before using them to load assets + */ + static get PreprocessUrl() { + return FileToolsOptions.PreprocessUrl; + } + static set PreprocessUrl(processor) { + FileToolsOptions.PreprocessUrl = processor; + } + /** + * Loads an image as an HTMLImageElement. + * @param input url string, ArrayBuffer, or Blob to load + * @param onLoad callback called when the image successfully loads + * @param onError callback called when the image fails to load + * @param offlineProvider offline provider for caching + * @param mimeType optional mime type + * @param imageBitmapOptions optional the options to use when creating an ImageBitmap + * @returns the HTMLImageElement of the loaded image + */ + static LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions) { + return LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions); + } + /** + * Loads a file from a url + * @param url url string, ArrayBuffer, or Blob to load + * @param onSuccess callback called when the file successfully loads + * @param onProgress callback called while file is loading (if the server supports this mode) + * @param offlineProvider defines the offline provider for caching + * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer + * @param onError callback called when the file fails to load + * @returns a file request object + */ + static LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { + return LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); + } + /** + * Loads a file from a url + * @param url the file url to load + * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer + * @returns a promise containing an ArrayBuffer corresponding to the loaded file + */ + static LoadFileAsync(url, useArrayBuffer = true) { + return new Promise((resolve, reject) => { + LoadFile(url, (data) => { + resolve(data); + }, undefined, undefined, useArrayBuffer, (request, exception) => { + reject(exception); + }); + }); + } + /** + * This function will convert asset URLs if the AssetBaseUrl parameter is set. + * Any URL with `assets.babylonjs.com/core` will be replaced with the value of AssetBaseUrl. + * @param url the URL to convert + * @returns a new URL + */ + static GetAssetUrl(url) { + if (!url) { + return ""; + } + if (Tools.AssetBaseUrl && url.startsWith(Tools._DefaultAssetsUrl)) { + // normalize the baseUrl + const baseUrl = Tools.AssetBaseUrl[Tools.AssetBaseUrl.length - 1] === "/" ? Tools.AssetBaseUrl.substring(0, Tools.AssetBaseUrl.length - 1) : Tools.AssetBaseUrl; + return url.replace(Tools._DefaultAssetsUrl, baseUrl); + } + return url; + } + /** + * Get a script URL including preprocessing + * @param scriptUrl the script Url to process + * @param forceAbsoluteUrl force the script to be an absolute url (adding the current base url if necessary) + * @returns a modified URL to use + */ + static GetBabylonScriptURL(scriptUrl, forceAbsoluteUrl) { + if (!scriptUrl) { + return ""; + } + // if the base URL was set, and the script Url is an absolute path change the default path + if (Tools.ScriptBaseUrl && scriptUrl.startsWith(Tools._DefaultCdnUrl)) { + // change the default host, which is https://cdn.babylonjs.com with the one defined + // make sure no trailing slash is present + const baseUrl = Tools.ScriptBaseUrl[Tools.ScriptBaseUrl.length - 1] === "/" ? Tools.ScriptBaseUrl.substring(0, Tools.ScriptBaseUrl.length - 1) : Tools.ScriptBaseUrl; + scriptUrl = scriptUrl.replace(Tools._DefaultCdnUrl, baseUrl); + } + // run the preprocessor + scriptUrl = Tools.ScriptPreprocessUrl(scriptUrl); + if (forceAbsoluteUrl) { + scriptUrl = Tools.GetAbsoluteUrl(scriptUrl); + } + return scriptUrl; + } + /** + * This function is used internally by babylon components to load a script (identified by an url). When the url returns, the + * content of this file is added into a new script element, attached to the DOM (body element) + * @param scriptUrl defines the url of the script to load + * @param onSuccess defines the callback called when the script is loaded + * @param onError defines the callback to call if an error occurs + * @param scriptId defines the id of the script element + */ + static LoadBabylonScript(scriptUrl, onSuccess, onError, scriptId) { + scriptUrl = Tools.GetBabylonScriptURL(scriptUrl); + Tools.LoadScript(scriptUrl, onSuccess, onError); + } + /** + * Load an asynchronous script (identified by an url). When the url returns, the + * content of this file is added into a new script element, attached to the DOM (body element) + * @param scriptUrl defines the url of the script to laod + * @returns a promise request object + */ + static LoadBabylonScriptAsync(scriptUrl) { + scriptUrl = Tools.GetBabylonScriptURL(scriptUrl); + return Tools.LoadScriptAsync(scriptUrl); + } + /** + * This function is used internally by babylon components to load a script (identified by an url). When the url returns, the + * content of this file is added into a new script element, attached to the DOM (body element) + * @param scriptUrl defines the url of the script to load + * @param onSuccess defines the callback called when the script is loaded + * @param onError defines the callback to call if an error occurs + * @param scriptId defines the id of the script element + * @param useModule defines if we should use the module strategy to load the script + */ + static LoadScript(scriptUrl, onSuccess, onError, scriptId, useModule = false) { + if (typeof importScripts === "function") { + try { + importScripts(scriptUrl); + if (onSuccess) { + onSuccess(); + } + } + catch (e) { + onError?.(`Unable to load script '${scriptUrl}' in worker`, e); + } + return; + } + else if (!IsWindowObjectExist()) { + onError?.(`Cannot load script '${scriptUrl}' outside of a window or a worker`); + return; + } + const head = document.getElementsByTagName("head")[0]; + const script = document.createElement("script"); + if (useModule) { + script.setAttribute("type", "module"); + script.innerText = scriptUrl; + } + else { + script.setAttribute("type", "text/javascript"); + script.setAttribute("src", scriptUrl); + } + if (scriptId) { + script.id = scriptId; + } + script.onload = () => { + if (onSuccess) { + onSuccess(); + } + }; + script.onerror = (e) => { + if (onError) { + onError(`Unable to load script '${scriptUrl}'`, e); + } + }; + head.appendChild(script); + } + /** + * Load an asynchronous script (identified by an url). When the url returns, the + * content of this file is added into a new script element, attached to the DOM (body element) + * @param scriptUrl defines the url of the script to load + * @param scriptId defines the id of the script element + * @returns a promise request object + */ + static LoadScriptAsync(scriptUrl, scriptId) { + return new Promise((resolve, reject) => { + this.LoadScript(scriptUrl, () => { + resolve(); + }, (message, exception) => { + reject(exception || new Error(message)); + }, scriptId); + }); + } + /** + * Loads a file from a blob + * @param fileToLoad defines the blob to use + * @param callback defines the callback to call when data is loaded + * @param progressCallback defines the callback to call during loading process + * @returns a file request object + */ + static ReadFileAsDataURL(fileToLoad, callback, progressCallback) { + const reader = new FileReader(); + const request = { + onCompleteObservable: new Observable(), + abort: () => reader.abort(), + }; + reader.onloadend = () => { + request.onCompleteObservable.notifyObservers(request); + }; + reader.onload = (e) => { + //target doesn't have result from ts 1.3 + callback(e.target["result"]); + }; + reader.onprogress = progressCallback; + reader.readAsDataURL(fileToLoad); + return request; + } + /** + * Reads a file from a File object + * @param file defines the file to load + * @param onSuccess defines the callback to call when data is loaded + * @param onProgress defines the callback to call during loading process + * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer + * @param onError defines the callback to call when an error occurs + * @returns a file request object + */ + static ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError) { + return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError); + } + /** + * Creates a data url from a given string content + * @param content defines the content to convert + * @returns the new data url link + */ + static FileAsURL(content) { + const fileBlob = new Blob([content]); + const url = window.URL; + const link = url.createObjectURL(fileBlob); + return link; + } + /** + * Format the given number to a specific decimal format + * @param value defines the number to format + * @param decimals defines the number of decimals to use + * @returns the formatted string + */ + static Format(value, decimals = 2) { + return value.toFixed(decimals); + } + /** + * Tries to copy an object by duplicating every property + * @param source defines the source object + * @param destination defines the target object + * @param doNotCopyList defines a list of properties to avoid + * @param mustCopyList defines a list of properties to copy (even if they start with _) + */ + static DeepCopy(source, destination, doNotCopyList, mustCopyList) { + DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList); + } + /** + * Gets a boolean indicating if the given object has no own property + * @param obj defines the object to test + * @returns true if object has no own property + */ + static IsEmpty(obj) { + for (const i in obj) { + if (Object.prototype.hasOwnProperty.call(obj, i)) { + return false; + } + } + return true; + } + /** + * Function used to register events at window level + * @param windowElement defines the Window object to use + * @param events defines the events to register + */ + static RegisterTopRootEvents(windowElement, events) { + for (let index = 0; index < events.length; index++) { + const event = events[index]; + windowElement.addEventListener(event.name, event.handler, false); + try { + if (window.parent) { + window.parent.addEventListener(event.name, event.handler, false); + } + } + catch (e) { + // Silently fails... + } + } + } + /** + * Function used to unregister events from window level + * @param windowElement defines the Window object to use + * @param events defines the events to unregister + */ + static UnregisterTopRootEvents(windowElement, events) { + for (let index = 0; index < events.length; index++) { + const event = events[index]; + windowElement.removeEventListener(event.name, event.handler); + try { + if (windowElement.parent) { + windowElement.parent.removeEventListener(event.name, event.handler); + } + } + catch (e) { + // Silently fails... + } + } + } + /** + * Dumps the current bound framebuffer + * @param width defines the rendering width + * @param height defines the rendering height + * @param engine defines the hosting engine + * @param successCallback defines the callback triggered once the data are available + * @param mimeType defines the mime type of the result + * @param fileName defines the filename to download. If present, the result will automatically be downloaded + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @returns a void promise + */ + static async DumpFramebuffer(width, height, engine, successCallback, mimeType = "image/png", fileName, quality) { + throw _WarnImport("DumpTools"); + } + /** + * Dumps an array buffer + * @param width defines the rendering width + * @param height defines the rendering height + * @param data the data array + * @param successCallback defines the callback triggered once the data are available + * @param mimeType defines the mime type of the result + * @param fileName defines the filename to download. If present, the result will automatically be downloaded + * @param invertY true to invert the picture in the Y dimension + * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + */ + static DumpData(width, height, data, successCallback, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { + throw _WarnImport("DumpTools"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Dumps an array buffer + * @param width defines the rendering width + * @param height defines the rendering height + * @param data the data array + * @param mimeType defines the mime type of the result + * @param fileName defines the filename to download. If present, the result will automatically be downloaded + * @param invertY true to invert the picture in the Y dimension + * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @returns a promise that resolve to the final data + */ + static DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { + throw _WarnImport("DumpTools"); + } + static _IsOffScreenCanvas(canvas) { + return canvas.convertToBlob !== undefined; + } + /** + * Converts the canvas data to blob. + * This acts as a polyfill for browsers not supporting the to blob function. + * @param canvas Defines the canvas to extract the data from (can be an offscreen canvas) + * @param successCallback Defines the callback triggered once the data are available + * @param mimeType Defines the mime type of the result + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + */ + static ToBlob(canvas, successCallback, mimeType = "image/png", quality) { + // We need HTMLCanvasElement.toBlob for HD screenshots + if (!Tools._IsOffScreenCanvas(canvas) && !canvas.toBlob) { + // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob) + canvas.toBlob = function (callback, type, quality) { + setTimeout(() => { + const binStr = atob(this.toDataURL(type, quality).split(",")[1]), len = binStr.length, arr = new Uint8Array(len); + for (let i = 0; i < len; i++) { + arr[i] = binStr.charCodeAt(i); + } + callback(new Blob([arr])); + }); + }; + } + if (Tools._IsOffScreenCanvas(canvas)) { + canvas + .convertToBlob({ + type: mimeType, + quality, + }) + .then((blob) => successCallback(blob)); + } + else { + canvas.toBlob(function (blob) { + successCallback(blob); + }, mimeType, quality); + } + } + /** + * Download a Blob object + * @param blob the Blob object + * @param fileName the file name to download + */ + static DownloadBlob(blob, fileName) { + //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image. + if ("download" in document.createElement("a")) { + if (!fileName) { + const date = new Date(); + const stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ("0" + date.getMinutes()).slice(-2); + fileName = "screenshot_" + stringDate + ".png"; + } + Tools.Download(blob, fileName); + } + else { + if (blob && typeof URL !== "undefined") { + const url = URL.createObjectURL(blob); + const newWindow = window.open(""); + if (!newWindow) { + return; + } + const img = newWindow.document.createElement("img"); + img.onload = function () { + // no longer need to read the blob so it's revoked + URL.revokeObjectURL(url); + }; + img.src = url; + newWindow.document.body.appendChild(img); + } + } + } + /** + * Encodes the canvas data to base 64, or automatically downloads the result if `fileName` is defined. + * @param canvas The canvas to get the data from, which can be an offscreen canvas. + * @param successCallback The callback which is triggered once the data is available. If `fileName` is defined, the callback will be invoked after the download occurs, and the `data` argument will be an empty string. + * @param mimeType The mime type of the result. + * @param fileName The name of the file to download. If defined, the result will automatically be downloaded. If not defined, and `successCallback` is also not defined, the result will automatically be downloaded with an auto-generated file name. + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + */ + static EncodeScreenshotCanvasData(canvas, successCallback, mimeType = "image/png", fileName, quality) { + if (typeof fileName === "string" || !successCallback) { + this.ToBlob(canvas, function (blob) { + if (blob) { + Tools.DownloadBlob(blob, fileName); + } + if (successCallback) { + successCallback(""); + } + }, mimeType, quality); + } + else if (successCallback) { + if (Tools._IsOffScreenCanvas(canvas)) { + canvas + .convertToBlob({ + type: mimeType, + quality, + }) + .then((blob) => { + const reader = new FileReader(); + reader.readAsDataURL(blob); + reader.onloadend = () => { + const base64data = reader.result; + successCallback(base64data); + }; + }); + return; + } + const base64Image = canvas.toDataURL(mimeType, quality); + successCallback(base64Image); + } + } + /** + * Downloads a blob in the browser + * @param blob defines the blob to download + * @param fileName defines the name of the downloaded file + */ + static Download(blob, fileName) { + if (typeof URL === "undefined") { + return; + } + const url = window.URL.createObjectURL(blob); + const a = document.createElement("a"); + document.body.appendChild(a); + a.style.display = "none"; + a.href = url; + a.download = fileName; + a.addEventListener("click", () => { + if (a.parentElement) { + a.parentElement.removeChild(a); + } + }); + a.click(); + window.URL.revokeObjectURL(url); + } + /** + * Will return the right value of the noPreventDefault variable + * Needed to keep backwards compatibility to the old API. + * + * @param args arguments passed to the attachControl function + * @returns the correct value for noPreventDefault + */ + static BackCompatCameraNoPreventDefault(args) { + // is it used correctly? + if (typeof args[0] === "boolean") { + return args[0]; + } + else if (typeof args[1] === "boolean") { + return args[1]; + } + return false; + } + /** + * Captures a screenshot of the current rendering + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG + * @param engine defines the rendering engine + * @param camera defines the source camera + * @param size This parameter can be set to a single number or to an object with the + * following (optional) properties: precision, width, height. If a single number is passed, + * it will be used for both width and height. If an object is passed, the screenshot size + * will be derived from the parameters. The precision property is a multiplier allowing + * rendering at a higher or lower resolution + * @param successCallback defines the callback receives a single parameter which contains the + * screenshot as a string of base64-encoded characters. This string can be assigned to the + * src parameter of an to display it + * @param mimeType defines the MIME type of the screenshot image (default: image/png). + * Check your browser for supported MIME types + * @param forceDownload force the system to download the image even if a successCallback is provided + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static CreateScreenshot(engine, camera, size, successCallback, mimeType = "image/png", forceDownload = false, quality) { + throw _WarnImport("ScreenshotTools"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Captures a screenshot of the current rendering + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG + * @param engine defines the rendering engine + * @param camera defines the source camera + * @param size This parameter can be set to a single number or to an object with the + * following (optional) properties: precision, width, height. If a single number is passed, + * it will be used for both width and height. If an object is passed, the screenshot size + * will be derived from the parameters. The precision property is a multiplier allowing + * rendering at a higher or lower resolution + * @param mimeType defines the MIME type of the screenshot image (default: image/png). + * Check your browser for supported MIME types + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @returns screenshot as a string of base64-encoded characters. This string can be assigned + * to the src parameter of an to display it + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static CreateScreenshotAsync(engine, camera, size, mimeType = "image/png", quality) { + throw _WarnImport("ScreenshotTools"); + } + /** + * Generates an image screenshot from the specified camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG + * @param engine The engine to use for rendering + * @param camera The camera to use for rendering + * @param size This parameter can be set to a single number or to an object with the + * following (optional) properties: precision, width, height. If a single number is passed, + * it will be used for both width and height. If an object is passed, the screenshot size + * will be derived from the parameters. The precision property is a multiplier allowing + * rendering at a higher or lower resolution + * @param successCallback The callback receives a single parameter which contains the + * screenshot as a string of base64-encoded characters. This string can be assigned to the + * src parameter of an to display it + * @param mimeType The MIME type of the screenshot image (default: image/png). + * Check your browser for supported MIME types + * @param samples Texture samples (default: 1) + * @param antialiasing Whether antialiasing should be turned on or not (default: false) + * @param fileName A name for for the downloaded file. + * @param renderSprites Whether the sprites should be rendered or not (default: false) + * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) + * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true) + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @param customizeTexture An optional callback that can be used to modify the render target texture before taking the screenshot. This can be used, for instance, to enable camera post-processes before taking the screenshot. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static CreateScreenshotUsingRenderTarget(engine, camera, size, successCallback, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture) { + throw _WarnImport("ScreenshotTools"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Generates an image screenshot from the specified camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG + * @param engine The engine to use for rendering + * @param camera The camera to use for rendering + * @param size This parameter can be set to a single number or to an object with the + * following (optional) properties: precision, width, height. If a single number is passed, + * it will be used for both width and height. If an object is passed, the screenshot size + * will be derived from the parameters. The precision property is a multiplier allowing + * rendering at a higher or lower resolution + * @param mimeType The MIME type of the screenshot image (default: image/png). + * Check your browser for supported MIME types + * @param samples Texture samples (default: 1) + * @param antialiasing Whether antialiasing should be turned on or not (default: false) + * @param fileName A name for for the downloaded file. + * @param renderSprites Whether the sprites should be rendered or not (default: false) + * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) + * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true) + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @param customizeTexture An optional callback that can be used to modify the render target texture before taking the screenshot. This can be used, for instance, to enable camera post-processes before taking the screenshot. + * @returns screenshot as a string of base64-encoded characters. This string can be assigned + * to the src parameter of an to display it + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture) { + throw _WarnImport("ScreenshotTools"); + } + /** + * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 + * Be aware Math.random() could cause collisions, but: + * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" + * @returns a pseudo random id + */ + static RandomId() { + return RandomGUID(); + } + /** + * Test if the given uri is a base64 string + * @deprecated Please use FileTools.IsBase64DataUrl instead. + * @param uri The uri to test + * @returns True if the uri is a base64 string or false otherwise + */ + static IsBase64(uri) { + return IsBase64DataUrl(uri); + } + /** + * Decode the given base64 uri. + * @deprecated Please use FileTools.DecodeBase64UrlToBinary instead. + * @param uri The uri to decode + * @returns The decoded base64 data. + */ + static DecodeBase64(uri) { + return DecodeBase64UrlToBinary(uri); + } + /** + * Gets a value indicating the number of loading errors + * @ignorenaming + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + static get errorsCount() { + return Logger.errorsCount; + } + /** + * Log a message to the console + * @param message defines the message to log + */ + static Log(message) { + Logger.Log(message); + } + /** + * Write a warning message to the console + * @param message defines the message to log + */ + static Warn(message) { + Logger.Warn(message); + } + /** + * Write an error message to the console + * @param message defines the message to log + */ + static Error(message) { + Logger.Error(message); + } + /** + * Gets current log cache (list of logs) + */ + static get LogCache() { + return Logger.LogCache; + } + /** + * Clears the log cache + */ + static ClearLogCache() { + Logger.ClearLogCache(); + } + /** + * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel) + */ + static set LogLevels(level) { + Logger.LogLevels = level; + } + /** + * Sets the current performance log level + */ + static set PerformanceLogLevel(level) { + if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) { + Tools.StartPerformanceCounter = Tools._StartUserMark; + Tools.EndPerformanceCounter = Tools._EndUserMark; + return; + } + if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) { + Tools.StartPerformanceCounter = Tools._StartPerformanceConsole; + Tools.EndPerformanceCounter = Tools._EndPerformanceConsole; + return; + } + Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled; + Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static _StartPerformanceCounterDisabled(counterName, condition) { } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static _EndPerformanceCounterDisabled(counterName, condition) { } + static _StartUserMark(counterName, condition = true) { + if (!Tools._Performance) { + if (!IsWindowObjectExist()) { + return; + } + Tools._Performance = window.performance; + } + if (!condition || !Tools._Performance.mark) { + return; + } + Tools._Performance.mark(counterName + "-Begin"); + } + static _EndUserMark(counterName, condition = true) { + if (!condition || !Tools._Performance.mark) { + return; + } + Tools._Performance.mark(counterName + "-End"); + Tools._Performance.measure(counterName, counterName + "-Begin", counterName + "-End"); + } + static _StartPerformanceConsole(counterName, condition = true) { + if (!condition) { + return; + } + Tools._StartUserMark(counterName, condition); + if (console.time) { + console.time(counterName); + } + } + static _EndPerformanceConsole(counterName, condition = true) { + if (!condition) { + return; + } + Tools._EndUserMark(counterName, condition); + console.timeEnd(counterName); + } + /** + * Gets either window.performance.now() if supported or Date.now() else + */ + static get Now() { + return PrecisionDate.Now; + } + /** + * This method will return the name of the class used to create the instance of the given object. + * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator. + * @param object the object to get the class name from + * @param isType defines if the object is actually a type + * @returns the name of the class, will be "object" for a custom data type not using the @className decorator + */ + static GetClassName(object, isType = false) { + let name = null; + if (!isType && object.getClassName) { + name = object.getClassName(); + } + else { + if (object instanceof Object) { + const classObj = isType ? object : Object.getPrototypeOf(object); + name = classObj.constructor["__bjsclassName__"]; + } + if (!name) { + name = typeof object; + } + } + return name; + } + /** + * Gets the first element of an array satisfying a given predicate + * @param array defines the array to browse + * @param predicate defines the predicate to use + * @returns null if not found or the element + */ + static First(array, predicate) { + for (const el of array) { + if (predicate(el)) { + return el; + } + } + return null; + } + /** + * This method will return the name of the full name of the class, including its owning module (if any). + * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified). + * @param object the object to get the class name from + * @param isType defines if the object is actually a type + * @returns a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified. + * @ignorenaming + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + static getFullClassName(object, isType = false) { + let className = null; + let moduleName = null; + if (!isType && object.getClassName) { + className = object.getClassName(); + } + else { + if (object instanceof Object) { + const classObj = isType ? object : Object.getPrototypeOf(object); + className = classObj.constructor["__bjsclassName__"]; + moduleName = classObj.constructor["__bjsmoduleName__"]; + } + if (!className) { + className = typeof object; + } + } + if (!className) { + return null; + } + return (moduleName != null ? moduleName + "." : "") + className; + } + /** + * Returns a promise that resolves after the given amount of time. + * @param delay Number of milliseconds to delay + * @returns Promise that resolves after the given amount of time + */ + static DelayAsync(delay) { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, delay); + }); + } + /** + * Utility function to detect if the current user agent is Safari + * @returns whether or not the current user agent is safari + */ + static IsSafari() { + if (!IsNavigatorAvailable()) { + return false; + } + return /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + } +} +/** + * The base URL to use to load assets. If empty the default base url is used. + */ +Tools.AssetBaseUrl = ""; +/** + * Enable/Disable Custom HTTP Request Headers globally. + * default = false + * @see CustomRequestHeaders + */ +Tools.UseCustomRequestHeaders = false; +/** + * Custom HTTP Request Headers to be sent with XMLHttpRequests + * i.e. when loading files, where the server/service expects an Authorization header + */ +Tools.CustomRequestHeaders = WebRequest.CustomRequestHeaders; +/** + * Extracts text content from a DOM element hierarchy + * Back Compat only, please use GetDOMTextContent instead. + */ +Tools.GetDOMTextContent = GetDOMTextContent; +/** + * @internal + */ +Tools._DefaultCdnUrl = "https://cdn.babylonjs.com"; +/** + * @internal + */ +Tools._DefaultAssetsUrl = "https://assets.babylonjs.com/core"; +// eslint-disable-next-line jsdoc/require-returns-check, jsdoc/require-param +/** + * @returns the absolute URL of a given (relative) url + */ +Tools.GetAbsoluteUrl = typeof document === "object" + ? (url) => { + const a = document.createElement("a"); + a.href = url; + return a.href; + } + : typeof URL === "function" && typeof location === "object" + ? (url) => new URL(url, location.origin).href + : () => { + throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context."); + }; +// Logs +/** + * No log + */ +Tools.NoneLogLevel = Logger.NoneLogLevel; +/** + * Only message logs + */ +Tools.MessageLogLevel = Logger.MessageLogLevel; +/** + * Only warning logs + */ +Tools.WarningLogLevel = Logger.WarningLogLevel; +/** + * Only error logs + */ +Tools.ErrorLogLevel = Logger.ErrorLogLevel; +/** + * All logs + */ +Tools.AllLogLevel = Logger.AllLogLevel; +/** + * Checks if the window object exists + * Back Compat only, please use IsWindowObjectExist instead. + */ +Tools.IsWindowObjectExist = IsWindowObjectExist; +// Performances +/** + * No performance log + */ +Tools.PerformanceNoneLogLevel = 0; +/** + * Use user marks to log performance + */ +Tools.PerformanceUserMarkLogLevel = 1; +/** + * Log performance to the console + */ +Tools.PerformanceConsoleLogLevel = 2; +/** + * Starts a performance counter + */ +Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled; +/** + * Ends a specific performance counter + */ +Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled; +/** + * An implementation of a loop for asynchronous functions. + */ +class AsyncLoop { + /** + * Constructor. + * @param iterations the number of iterations. + * @param func the function to run each iteration + * @param successCallback the callback that will be called upon successful execution + * @param offset starting offset. + */ + constructor( + /** + * Defines the number of iterations for the loop + */ + iterations, func, successCallback, offset = 0) { + this.iterations = iterations; + this.index = offset - 1; + this._done = false; + this._fn = func; + this._successCallback = successCallback; + } + /** + * Execute the next iteration. Must be called after the last iteration was finished. + */ + executeNext() { + if (!this._done) { + if (this.index + 1 < this.iterations) { + ++this.index; + this._fn(this); + } + else { + this.breakLoop(); + } + } + } + /** + * Break the loop and run the success callback. + */ + breakLoop() { + this._done = true; + this._successCallback(); + } + /** + * Create and run an async loop. + * @param iterations the number of iterations. + * @param fn the function to run each iteration + * @param successCallback the callback that will be called upon successful execution + * @param offset starting offset. + * @returns the created async loop object + */ + static Run(iterations, fn, successCallback, offset = 0) { + const loop = new AsyncLoop(iterations, fn, successCallback, offset); + loop.executeNext(); + return loop; + } + /** + * A for-loop that will run a given number of iterations synchronous and the rest async. + * @param iterations total number of iterations + * @param syncedIterations number of synchronous iterations in each async iteration. + * @param fn the function to call each iteration. + * @param callback a success call back that will be called when iterating stops. + * @param breakFunction a break condition (optional) + * @param timeout timeout settings for the setTimeout function. default - 0. + * @returns the created async loop object + */ + static SyncAsyncForLoop(iterations, syncedIterations, fn, callback, breakFunction, timeout = 0) { + return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop) => { + if (breakFunction && breakFunction()) { + loop.breakLoop(); + } + else { + setTimeout(() => { + for (let i = 0; i < syncedIterations; ++i) { + const iteration = loop.index * syncedIterations + i; + if (iteration >= iterations) { + break; + } + fn(iteration); + if (breakFunction && breakFunction()) { + loop.breakLoop(); + break; + } + } + loop.executeNext(); + }, timeout); + } + }, callback); + } +} +Tools.Mix = Mix; +Tools.IsExponentOfTwo = IsExponentOfTwo; +// Will only be define if Tools is imported freeing up some space when only engine is required +EngineStore.FallbackTexture = + "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z"; + +/** + * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations. + */ +class SmartArray { + /** + * Instantiates a Smart Array. + * @param capacity defines the default capacity of the array. + */ + constructor(capacity) { + /** + * The active length of the array. + */ + this.length = 0; + this.data = new Array(capacity); + this._id = SmartArray._GlobalId++; + } + /** + * Pushes a value at the end of the active data. + * @param value defines the object to push in the array. + */ + push(value) { + this.data[this.length++] = value; + if (this.length > this.data.length) { + this.data.length *= 2; + } + } + /** + * Iterates over the active data and apply the lambda to them. + * @param func defines the action to apply on each value. + */ + forEach(func) { + for (let index = 0; index < this.length; index++) { + func(this.data[index]); + } + } + /** + * Sorts the full sets of data. + * @param compareFn defines the comparison function to apply. + */ + sort(compareFn) { + this.data.sort(compareFn); + } + /** + * Resets the active data to an empty array. + */ + reset() { + this.length = 0; + } + /** + * Releases all the data from the array as well as the array. + */ + dispose() { + this.reset(); + if (this.data) { + this.data.length = 0; + } + } + /** + * Concats the active data with a given array. + * @param array defines the data to concatenate with. + */ + concat(array) { + if (array.length === 0) { + return; + } + if (this.length + array.length > this.data.length) { + this.data.length = (this.length + array.length) * 2; + } + for (let index = 0; index < array.length; index++) { + this.data[this.length++] = (array.data || array)[index]; + } + } + /** + * Returns the position of a value in the active data. + * @param value defines the value to find the index for + * @returns the index if found in the active data otherwise -1 + */ + indexOf(value) { + const position = this.data.indexOf(value); + if (position >= this.length) { + return -1; + } + return position; + } + /** + * Returns whether an element is part of the active data. + * @param value defines the value to look for + * @returns true if found in the active data otherwise false + */ + contains(value) { + return this.indexOf(value) !== -1; + } +} +// Statics +SmartArray._GlobalId = 0; +/** + * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations. + * The data in this array can only be present once + */ +class SmartArrayNoDuplicate extends SmartArray { + constructor() { + super(...arguments); + this._duplicateId = 0; + } + /** + * Pushes a value at the end of the active data. + * THIS DOES NOT PREVENT DUPPLICATE DATA + * @param value defines the object to push in the array. + */ + push(value) { + super.push(value); + if (!value.__smartArrayFlags) { + value.__smartArrayFlags = {}; + } + value.__smartArrayFlags[this._id] = this._duplicateId; + } + /** + * Pushes a value at the end of the active data. + * If the data is already present, it won t be added again + * @param value defines the object to push in the array. + * @returns true if added false if it was already present + */ + pushNoDuplicate(value) { + if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) { + return false; + } + this.push(value); + return true; + } + /** + * Resets the active data to an empty array. + */ + reset() { + super.reset(); + this._duplicateId++; + } + /** + * Concats the active data with a given array. + * This ensures no duplicate will be present in the result. + * @param array defines the data to concatenate with. + */ + concatWithNoDuplicate(array) { + if (array.length === 0) { + return; + } + if (this.length + array.length > this.data.length) { + this.data.length = (this.length + array.length) * 2; + } + for (let index = 0; index < array.length; index++) { + const item = (array.data || array)[index]; + this.pushNoDuplicate(item); + } + } +} + +/** + * This class implement a typical dictionary using a string as key and the generic type T as value. + * The underlying implementation relies on an associative array to ensure the best performances. + * The value can be anything including 'null' but except 'undefined' + */ +class StringDictionary { + constructor() { + this._count = 0; + this._data = {}; + } + /** + * This will clear this dictionary and copy the content from the 'source' one. + * If the T value is a custom object, it won't be copied/cloned, the same object will be used + * @param source the dictionary to take the content from and copy to this dictionary + */ + copyFrom(source) { + this.clear(); + source.forEach((t, v) => this.add(t, v)); + } + /** + * Get a value based from its key + * @param key the given key to get the matching value from + * @returns the value if found, otherwise undefined is returned + */ + get(key) { + const val = this._data[key]; + if (val !== undefined) { + return val; + } + return undefined; + } + /** + * Get a value from its key or add it if it doesn't exist. + * This method will ensure you that a given key/data will be present in the dictionary. + * @param key the given key to get the matching value from + * @param factory the factory that will create the value if the key is not present in the dictionary. + * The factory will only be invoked if there's no data for the given key. + * @returns the value corresponding to the key. + */ + getOrAddWithFactory(key, factory) { + let val = this.get(key); + if (val !== undefined) { + return val; + } + val = factory(key); + if (val) { + this.add(key, val); + } + return val; + } + /** + * Get a value from its key if present in the dictionary otherwise add it + * @param key the key to get the value from + * @param val if there's no such key/value pair in the dictionary add it with this value + * @returns the value corresponding to the key + */ + getOrAdd(key, val) { + const curVal = this.get(key); + if (curVal !== undefined) { + return curVal; + } + this.add(key, val); + return val; + } + /** + * Check if there's a given key in the dictionary + * @param key the key to check for + * @returns true if the key is present, false otherwise + */ + contains(key) { + return this._data[key] !== undefined; + } + /** + * Add a new key and its corresponding value + * @param key the key to add + * @param value the value corresponding to the key + * @returns true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary + */ + add(key, value) { + if (this._data[key] !== undefined) { + return false; + } + this._data[key] = value; + ++this._count; + return true; + } + /** + * Update a specific value associated to a key + * @param key defines the key to use + * @param value defines the value to store + * @returns true if the value was updated (or false if the key was not found) + */ + set(key, value) { + if (this._data[key] === undefined) { + return false; + } + this._data[key] = value; + return true; + } + /** + * Get the element of the given key and remove it from the dictionary + * @param key defines the key to search + * @returns the value associated with the key or null if not found + */ + getAndRemove(key) { + const val = this.get(key); + if (val !== undefined) { + delete this._data[key]; + --this._count; + return val; + } + return null; + } + /** + * Remove a key/value from the dictionary. + * @param key the key to remove + * @returns true if the item was successfully deleted, false if no item with such key exist in the dictionary + */ + remove(key) { + if (this.contains(key)) { + delete this._data[key]; + --this._count; + return true; + } + return false; + } + /** + * Clear the whole content of the dictionary + */ + clear() { + this._data = {}; + this._count = 0; + } + /** + * Gets the current count + */ + get count() { + return this._count; + } + /** + * Execute a callback on each key/val of the dictionary. + * Note that you can remove any element in this dictionary in the callback implementation + * @param callback the callback to execute on a given key/value pair + */ + forEach(callback) { + for (const cur in this._data) { + const val = this._data[cur]; + callback(cur, val); + } + } + /** + * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object. + * If the callback returns null or undefined the method will iterate to the next key/value pair + * Note that you can remove any element in this dictionary in the callback implementation + * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned + * @returns the first item + */ + first(callback) { + for (const cur in this._data) { + const val = this._data[cur]; + const res = callback(cur, val); + if (res) { + return res; + } + } + return null; + } +} + +/** + * Prepare the list of uniforms associated with the ColorCurves effects. + * @param uniformsList The list of uniforms used in the effect + */ +function PrepareUniformsForColorCurves(uniformsList) { + uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative"); +} + +/** + * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ +class ColorCurves { + constructor() { + this._dirty = true; + this._tempColor = new Color4(0, 0, 0, 0); + this._globalCurve = new Color4(0, 0, 0, 0); + this._highlightsCurve = new Color4(0, 0, 0, 0); + this._midtonesCurve = new Color4(0, 0, 0, 0); + this._shadowsCurve = new Color4(0, 0, 0, 0); + this._positiveCurve = new Color4(0, 0, 0, 0); + this._negativeCurve = new Color4(0, 0, 0, 0); + this._globalHue = 30; + this._globalDensity = 0; + this._globalSaturation = 0; + this._globalExposure = 0; + this._highlightsHue = 30; + this._highlightsDensity = 0; + this._highlightsSaturation = 0; + this._highlightsExposure = 0; + this._midtonesHue = 30; + this._midtonesDensity = 0; + this._midtonesSaturation = 0; + this._midtonesExposure = 0; + this._shadowsHue = 30; + this._shadowsDensity = 0; + this._shadowsSaturation = 0; + this._shadowsExposure = 0; + } + /** + * Gets the global Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + get globalHue() { + return this._globalHue; + } + /** + * Sets the global Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + set globalHue(value) { + this._globalHue = value; + this._dirty = true; + } + /** + * Gets the global Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + get globalDensity() { + return this._globalDensity; + } + /** + * Sets the global Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + set globalDensity(value) { + this._globalDensity = value; + this._dirty = true; + } + /** + * Gets the global Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + get globalSaturation() { + return this._globalSaturation; + } + /** + * Sets the global Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + set globalSaturation(value) { + this._globalSaturation = value; + this._dirty = true; + } + /** + * Gets the global Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + get globalExposure() { + return this._globalExposure; + } + /** + * Sets the global Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + set globalExposure(value) { + this._globalExposure = value; + this._dirty = true; + } + /** + * Gets the highlights Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + get highlightsHue() { + return this._highlightsHue; + } + /** + * Sets the highlights Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + set highlightsHue(value) { + this._highlightsHue = value; + this._dirty = true; + } + /** + * Gets the highlights Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + get highlightsDensity() { + return this._highlightsDensity; + } + /** + * Sets the highlights Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + set highlightsDensity(value) { + this._highlightsDensity = value; + this._dirty = true; + } + /** + * Gets the highlights Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + get highlightsSaturation() { + return this._highlightsSaturation; + } + /** + * Sets the highlights Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + set highlightsSaturation(value) { + this._highlightsSaturation = value; + this._dirty = true; + } + /** + * Gets the highlights Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + get highlightsExposure() { + return this._highlightsExposure; + } + /** + * Sets the highlights Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + set highlightsExposure(value) { + this._highlightsExposure = value; + this._dirty = true; + } + /** + * Gets the midtones Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + get midtonesHue() { + return this._midtonesHue; + } + /** + * Sets the midtones Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + set midtonesHue(value) { + this._midtonesHue = value; + this._dirty = true; + } + /** + * Gets the midtones Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + get midtonesDensity() { + return this._midtonesDensity; + } + /** + * Sets the midtones Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + set midtonesDensity(value) { + this._midtonesDensity = value; + this._dirty = true; + } + /** + * Gets the midtones Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + get midtonesSaturation() { + return this._midtonesSaturation; + } + /** + * Sets the midtones Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + set midtonesSaturation(value) { + this._midtonesSaturation = value; + this._dirty = true; + } + /** + * Gets the midtones Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + get midtonesExposure() { + return this._midtonesExposure; + } + /** + * Sets the midtones Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + set midtonesExposure(value) { + this._midtonesExposure = value; + this._dirty = true; + } + /** + * Gets the shadows Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + get shadowsHue() { + return this._shadowsHue; + } + /** + * Sets the shadows Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + set shadowsHue(value) { + this._shadowsHue = value; + this._dirty = true; + } + /** + * Gets the shadows Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + get shadowsDensity() { + return this._shadowsDensity; + } + /** + * Sets the shadows Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + set shadowsDensity(value) { + this._shadowsDensity = value; + this._dirty = true; + } + /** + * Gets the shadows Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + get shadowsSaturation() { + return this._shadowsSaturation; + } + /** + * Sets the shadows Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + set shadowsSaturation(value) { + this._shadowsSaturation = value; + this._dirty = true; + } + /** + * Gets the shadows Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + get shadowsExposure() { + return this._shadowsExposure; + } + /** + * Sets the shadows Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + set shadowsExposure(value) { + this._shadowsExposure = value; + this._dirty = true; + } + /** + * Returns the class name + * @returns The class name + */ + getClassName() { + return "ColorCurves"; + } + /** + * Binds the color curves to the shader. + * @param colorCurves The color curve to bind + * @param effect The effect to bind to + * @param positiveUniform The positive uniform shader parameter + * @param neutralUniform The neutral uniform shader parameter + * @param negativeUniform The negative uniform shader parameter + */ + static Bind(colorCurves, effect, positiveUniform = "vCameraColorCurvePositive", neutralUniform = "vCameraColorCurveNeutral", negativeUniform = "vCameraColorCurveNegative") { + if (colorCurves._dirty) { + colorCurves._dirty = false; + // Fill in global info. + colorCurves._getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve); + // Compute highlights info. + colorCurves._getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor); + colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve); + // Compute midtones info. + colorCurves._getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor); + colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve); + // Compute shadows info. + colorCurves._getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor); + colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve); + // Compute deltas (neutral is midtones). + colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve); + colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve); + } + if (effect) { + effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a); + effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a); + effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a); + } + } + /** + * Returns color grading data based on a hue, density, saturation and exposure value. + * @param hue + * @param density + * @param saturation The saturation. + * @param exposure The exposure. + * @param result The result data container. + */ + _getColorGradingDataToRef(hue, density, saturation, exposure, result) { + if (hue == null) { + return; + } + hue = ColorCurves._Clamp(hue, 0, 360); + density = ColorCurves._Clamp(density, -100, 100); + saturation = ColorCurves._Clamp(saturation, -100, 100); + exposure = ColorCurves._Clamp(exposure, -100, 100); + // Remap the slider/config filter density with non-linear mapping and also scale by half + // so that the maximum filter density is only 50% control. This provides fine control + // for small values and reasonable range. + density = ColorCurves._ApplyColorGradingSliderNonlinear(density); + density *= 0.5; + exposure = ColorCurves._ApplyColorGradingSliderNonlinear(exposure); + if (density < 0) { + density *= -1; + hue = (hue + 180) % 360; + } + ColorCurves._FromHSBToRef(hue, density, 50 + 0.25 * exposure, result); + result.scaleToRef(2, result); + result.a = 1 + 0.01 * saturation; + } + /** + * Takes an input slider value and returns an adjusted value that provides extra control near the centre. + * @param value The input slider value in range [-100,100]. + * @returns Adjusted value. + */ + static _ApplyColorGradingSliderNonlinear(value) { + value /= 100; + let x = Math.abs(value); + x = Math.pow(x, 2); + if (value < 0) { + x *= -1; + } + x *= 100; + return x; + } + /** + * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV). + * @param hue The hue (H) input. + * @param saturation The saturation (S) input. + * @param brightness The brightness (B) input. + * @param result + * @result An RGBA color represented as Vector4. + */ + static _FromHSBToRef(hue, saturation, brightness, result) { + let h = ColorCurves._Clamp(hue, 0, 360); + const s = ColorCurves._Clamp(saturation / 100, 0, 1); + const v = ColorCurves._Clamp(brightness / 100, 0, 1); + if (s === 0) { + result.r = v; + result.g = v; + result.b = v; + } + else { + // sector 0 to 5 + h /= 60; + const i = Math.floor(h); + // fractional part of h + const f = h - i; + const p = v * (1 - s); + const q = v * (1 - s * f); + const t = v * (1 - s * (1 - f)); + switch (i) { + case 0: + result.r = v; + result.g = t; + result.b = p; + break; + case 1: + result.r = q; + result.g = v; + result.b = p; + break; + case 2: + result.r = p; + result.g = v; + result.b = t; + break; + case 3: + result.r = p; + result.g = q; + result.b = v; + break; + case 4: + result.r = t; + result.g = p; + result.b = v; + break; + default: + // case 5: + result.r = v; + result.g = p; + result.b = q; + break; + } + } + result.a = 1; + } + /** + * Returns a value clamped between min and max + * @param value The value to clamp + * @param min The minimum of value + * @param max The maximum of value + * @returns The clamped value. + */ + static _Clamp(value, min, max) { + return Math.min(Math.max(value, min), max); + } + /** + * Clones the current color curve instance. + * @returns The cloned curves + */ + clone() { + return SerializationHelper.Clone(() => new ColorCurves(), this); + } + /** + * Serializes the current color curve instance to a json representation. + * @returns a JSON representation + */ + serialize() { + return SerializationHelper.Serialize(this); + } + /** + * Parses the color curve from a json representation. + * @param source the JSON source to parse + * @returns The parsed curves + */ + static Parse(source) { + return SerializationHelper.Parse(() => new ColorCurves(), source, null, null); + } +} +/** + * Prepare the list of uniforms associated with the ColorCurves effects. + * @param uniformsList The list of uniforms used in the effect + */ +ColorCurves.PrepareUniforms = PrepareUniformsForColorCurves; +__decorate([ + serialize() +], ColorCurves.prototype, "_globalHue", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_globalDensity", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_globalSaturation", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_globalExposure", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_highlightsHue", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_highlightsDensity", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_highlightsSaturation", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_highlightsExposure", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_midtonesHue", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_midtonesDensity", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_midtonesSaturation", void 0); +__decorate([ + serialize() +], ColorCurves.prototype, "_midtonesExposure", void 0); +// References the dependencies. +SerializationHelper._ColorCurvesParser = ColorCurves.Parse; + +/** + * Prepare the list of uniforms associated with the Image Processing effects. + * @param uniforms The list of uniforms used in the effect + * @param defines the list of defines currently in use + */ +function PrepareUniformsForImageProcessing(uniforms, defines) { + if (defines.EXPOSURE) { + uniforms.push("exposureLinear"); + } + if (defines.CONTRAST) { + uniforms.push("contrast"); + } + if (defines.COLORGRADING) { + uniforms.push("colorTransformSettings"); + } + if (defines.VIGNETTE || defines.DITHER) { + uniforms.push("vInverseScreenSize"); + } + if (defines.VIGNETTE) { + uniforms.push("vignetteSettings1"); + uniforms.push("vignetteSettings2"); + } + if (defines.COLORCURVES) { + PrepareUniformsForColorCurves(uniforms); + } + if (defines.DITHER) { + uniforms.push("ditherIntensity"); + } +} +/** + * Prepare the list of samplers associated with the Image Processing effects. + * @param samplersList The list of uniforms used in the effect + * @param defines the list of defines currently in use + */ +function PrepareSamplersForImageProcessing(samplersList, defines) { + if (defines.COLORGRADING) { + samplersList.push("txColorTransform"); + } +} + +/** + * This groups together the common properties used for image processing either in direct forward pass + * or through post processing effect depending on the use of the image processing pipeline in your scene + * or not. + */ +class ImageProcessingConfiguration { + constructor() { + /** + * Color curves setup used in the effect if colorCurvesEnabled is set to true + */ + this.colorCurves = new ColorCurves(); + this._colorCurvesEnabled = false; + this._colorGradingEnabled = false; + this._colorGradingWithGreenDepth = true; + this._colorGradingBGR = true; + /** @internal */ + this._exposure = 1.0; + this._toneMappingEnabled = false; + this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD; + this._contrast = 1.0; + /** + * Vignette stretch size. + */ + this.vignetteStretch = 0; + /** + * Vignette center X Offset. + */ + this.vignetteCenterX = 0; + /** + * Vignette center Y Offset. + */ + this.vignetteCenterY = 0; + /** + * Vignette weight or intensity of the vignette effect. + */ + this.vignetteWeight = 1.5; + /** + * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) + * if vignetteEnabled is set to true. + */ + this.vignetteColor = new Color4(0, 0, 0, 0); + /** + * Camera field of view used by the Vignette effect. + */ + this.vignetteCameraFov = 0.5; + this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY; + this._vignetteEnabled = false; + this._ditheringEnabled = false; + this._ditheringIntensity = 1.0 / 255.0; + /** @internal */ + this._skipFinalColorClamp = false; + /** @internal */ + this._applyByPostProcess = false; + this._isEnabled = true; + /** + * An event triggered when the configuration changes and requires Shader to Update some parameters. + */ + this.onUpdateParameters = new Observable(); + } + /** + * Gets whether the color curves effect is enabled. + */ + get colorCurvesEnabled() { + return this._colorCurvesEnabled; + } + /** + * Sets whether the color curves effect is enabled. + */ + set colorCurvesEnabled(value) { + if (this._colorCurvesEnabled === value) { + return; + } + this._colorCurvesEnabled = value; + this._updateParameters(); + } + /** + * Color grading LUT texture used in the effect if colorGradingEnabled is set to true + */ + get colorGradingTexture() { + return this._colorGradingTexture; + } + /** + * Color grading LUT texture used in the effect if colorGradingEnabled is set to true + */ + set colorGradingTexture(value) { + if (this._colorGradingTexture === value) { + return; + } + this._colorGradingTexture = value; + this._updateParameters(); + } + /** + * Gets whether the color grading effect is enabled. + */ + get colorGradingEnabled() { + return this._colorGradingEnabled; + } + /** + * Sets whether the color grading effect is enabled. + */ + set colorGradingEnabled(value) { + if (this._colorGradingEnabled === value) { + return; + } + this._colorGradingEnabled = value; + this._updateParameters(); + } + /** + * Gets whether the color grading effect is using a green depth for the 3d Texture. + */ + get colorGradingWithGreenDepth() { + return this._colorGradingWithGreenDepth; + } + /** + * Sets whether the color grading effect is using a green depth for the 3d Texture. + */ + set colorGradingWithGreenDepth(value) { + if (this._colorGradingWithGreenDepth === value) { + return; + } + this._colorGradingWithGreenDepth = value; + this._updateParameters(); + } + /** + * Gets whether the color grading texture contains BGR values. + */ + get colorGradingBGR() { + return this._colorGradingBGR; + } + /** + * Sets whether the color grading texture contains BGR values. + */ + set colorGradingBGR(value) { + if (this._colorGradingBGR === value) { + return; + } + this._colorGradingBGR = value; + this._updateParameters(); + } + /** + * Gets the Exposure used in the effect. + */ + get exposure() { + return this._exposure; + } + /** + * Sets the Exposure used in the effect. + */ + set exposure(value) { + if (this._exposure === value) { + return; + } + this._exposure = value; + this._updateParameters(); + } + /** + * Gets whether the tone mapping effect is enabled. + */ + get toneMappingEnabled() { + return this._toneMappingEnabled; + } + /** + * Sets whether the tone mapping effect is enabled. + */ + set toneMappingEnabled(value) { + if (this._toneMappingEnabled === value) { + return; + } + this._toneMappingEnabled = value; + this._updateParameters(); + } + /** + * Gets the type of tone mapping effect. + */ + get toneMappingType() { + return this._toneMappingType; + } + /** + * Sets the type of tone mapping effect used in BabylonJS. + */ + set toneMappingType(value) { + if (this._toneMappingType === value) { + return; + } + this._toneMappingType = value; + this._updateParameters(); + } + /** + * Gets the contrast used in the effect. + */ + get contrast() { + return this._contrast; + } + /** + * Sets the contrast used in the effect. + */ + set contrast(value) { + if (this._contrast === value) { + return; + } + this._contrast = value; + this._updateParameters(); + } + /** + * Back Compat: Vignette center Y Offset. + * @deprecated use vignetteCenterY instead + */ + get vignetteCentreY() { + return this.vignetteCenterY; + } + set vignetteCentreY(value) { + this.vignetteCenterY = value; + } + /** + * Back Compat: Vignette center X Offset. + * @deprecated use vignetteCenterX instead + */ + get vignetteCentreX() { + return this.vignetteCenterX; + } + set vignetteCentreX(value) { + this.vignetteCenterX = value; + } + /** + * Gets the vignette blend mode allowing different kind of effect. + */ + get vignetteBlendMode() { + return this._vignetteBlendMode; + } + /** + * Sets the vignette blend mode allowing different kind of effect. + */ + set vignetteBlendMode(value) { + if (this._vignetteBlendMode === value) { + return; + } + this._vignetteBlendMode = value; + this._updateParameters(); + } + /** + * Gets whether the vignette effect is enabled. + */ + get vignetteEnabled() { + return this._vignetteEnabled; + } + /** + * Sets whether the vignette effect is enabled. + */ + set vignetteEnabled(value) { + if (this._vignetteEnabled === value) { + return; + } + this._vignetteEnabled = value; + this._updateParameters(); + } + /** + * Gets whether the dithering effect is enabled. + * The dithering effect can be used to reduce banding. + */ + get ditheringEnabled() { + return this._ditheringEnabled; + } + /** + * Sets whether the dithering effect is enabled. + * The dithering effect can be used to reduce banding. + */ + set ditheringEnabled(value) { + if (this._ditheringEnabled === value) { + return; + } + this._ditheringEnabled = value; + this._updateParameters(); + } + /** + * Gets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0. + */ + get ditheringIntensity() { + return this._ditheringIntensity; + } + /** + * Sets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0. + */ + set ditheringIntensity(value) { + if (this._ditheringIntensity === value) { + return; + } + this._ditheringIntensity = value; + this._updateParameters(); + } + /** + * If apply by post process is set to true, setting this to true will skip the final color clamp step in the fragment shader + * Applies to PBR materials. + */ + get skipFinalColorClamp() { + return this._skipFinalColorClamp; + } + /** + * If apply by post process is set to true, setting this to true will skip the final color clamp step in the fragment shader + * Applies to PBR materials. + */ + set skipFinalColorClamp(value) { + if (this._skipFinalColorClamp === value) { + return; + } + this._skipFinalColorClamp = value; + this._updateParameters(); + } + /** + * Gets whether the image processing is applied through a post process or not. + */ + get applyByPostProcess() { + return this._applyByPostProcess; + } + /** + * Sets whether the image processing is applied through a post process or not. + */ + set applyByPostProcess(value) { + if (this._applyByPostProcess === value) { + return; + } + this._applyByPostProcess = value; + this._updateParameters(); + } + /** + * Gets whether the image processing is enabled or not. + */ + get isEnabled() { + return this._isEnabled; + } + /** + * Sets whether the image processing is enabled or not. + */ + set isEnabled(value) { + if (this._isEnabled === value) { + return; + } + this._isEnabled = value; + this._updateParameters(); + } + /** + * Method called each time the image processing information changes requires to recompile the effect. + */ + _updateParameters() { + this.onUpdateParameters.notifyObservers(this); + } + /** + * Gets the current class name. + * @returns "ImageProcessingConfiguration" + */ + getClassName() { + return "ImageProcessingConfiguration"; + } + /** + * Prepare the list of defines associated to the shader. + * @param defines the list of defines to complete + * @param forPostProcess Define if we are currently in post process mode or not + */ + prepareDefines(defines, forPostProcess = false) { + if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) { + defines.VIGNETTE = false; + defines.TONEMAPPING = 0; + defines.CONTRAST = false; + defines.EXPOSURE = false; + defines.COLORCURVES = false; + defines.COLORGRADING = false; + defines.COLORGRADING3D = false; + defines.DITHER = false; + defines.IMAGEPROCESSING = false; + defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp; + defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled; + return; + } + defines.VIGNETTE = this.vignetteEnabled; + defines.VIGNETTEBLENDMODEMULTIPLY = this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY; + defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY; + if (!this._toneMappingEnabled) { + defines.TONEMAPPING = 0; + } + else { + switch (this._toneMappingType) { + case ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL: + defines.TONEMAPPING = 3; + break; + case ImageProcessingConfiguration.TONEMAPPING_ACES: + defines.TONEMAPPING = 2; + break; + default: + defines.TONEMAPPING = 1; + break; + } + } + defines.CONTRAST = this.contrast !== 1.0; + defines.EXPOSURE = this.exposure !== 1.0; + defines.COLORCURVES = this.colorCurvesEnabled && !!this.colorCurves; + defines.COLORGRADING = this.colorGradingEnabled && !!this.colorGradingTexture; + if (defines.COLORGRADING) { + defines.COLORGRADING3D = this.colorGradingTexture.is3D; + } + else { + defines.COLORGRADING3D = false; + } + defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth; + defines.SAMPLER3DBGRMAP = this.colorGradingBGR; + defines.DITHER = this._ditheringEnabled; + defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess; + defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp; + defines.IMAGEPROCESSING = + defines.VIGNETTE || !!defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.DITHER; + } + /** + * Returns true if all the image processing information are ready. + * @returns True if ready, otherwise, false + */ + isReady() { + // Color Grading texture can not be none blocking. + return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady(); + } + /** + * Binds the image processing to the shader. + * @param effect The effect to bind to + * @param overrideAspectRatio Override the aspect ratio of the effect + */ + bind(effect, overrideAspectRatio) { + // Color Curves + if (this._colorCurvesEnabled && this.colorCurves) { + ColorCurves.Bind(this.colorCurves, effect); + } + // Vignette and dither handled together due to common uniform. + if (this._vignetteEnabled || this._ditheringEnabled) { + const inverseWidth = 1 / effect.getEngine().getRenderWidth(); + const inverseHeight = 1 / effect.getEngine().getRenderHeight(); + effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight); + if (this._ditheringEnabled) { + effect.setFloat("ditherIntensity", 0.5 * this._ditheringIntensity); + } + if (this._vignetteEnabled) { + const aspectRatio = overrideAspectRatio != null ? overrideAspectRatio : inverseHeight / inverseWidth; + let vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5); + let vignetteScaleX = vignetteScaleY * aspectRatio; + const vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY); + vignetteScaleX = Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch); + vignetteScaleY = Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch); + effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCenterX, -vignetteScaleY * this.vignetteCenterY); + const vignettePower = -2 * this.vignetteWeight; + effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower); + } + } + // Exposure + effect.setFloat("exposureLinear", this.exposure); + // Contrast + effect.setFloat("contrast", this.contrast); + // Color transform settings + if (this.colorGradingTexture) { + effect.setTexture("txColorTransform", this.colorGradingTexture); + const textureSize = this.colorGradingTexture.getSize().height; + effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale + 0.5 / textureSize, // textureOffset + textureSize, // textureSize + this.colorGradingTexture.level // weight + ); + } + } + /** + * Clones the current image processing instance. + * @returns The cloned image processing + */ + clone() { + return SerializationHelper.Clone(() => new ImageProcessingConfiguration(), this); + } + /** + * Serializes the current image processing instance to a json representation. + * @returns a JSON representation + */ + serialize() { + return SerializationHelper.Serialize(this); + } + /** + * Parses the image processing from a json representation. + * @param source the JSON source to parse + * @returns The parsed image processing + */ + static Parse(source) { + const parsed = SerializationHelper.Parse(() => new ImageProcessingConfiguration(), source, null, null); + // Backward compatibility + if (source.vignetteCentreX !== undefined) { + parsed.vignetteCenterX = source.vignetteCentreX; + } + if (source.vignetteCentreY !== undefined) { + parsed.vignetteCenterY = source.vignetteCentreY; + } + return parsed; + } + /** + * Used to apply the vignette as a mix with the pixel color. + */ + static get VIGNETTEMODE_MULTIPLY() { + return this._VIGNETTEMODE_MULTIPLY; + } + /** + * Used to apply the vignette as a replacement of the pixel color. + */ + static get VIGNETTEMODE_OPAQUE() { + return this._VIGNETTEMODE_OPAQUE; + } +} +/** + * Default tone mapping applied in BabylonJS. + */ +ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0; +/** + * ACES Tone mapping (used by default in unreal and unity). This can help getting closer + * to other engines rendering to increase portability. + */ +ImageProcessingConfiguration.TONEMAPPING_ACES = 1; +/** + * Neutral Tone mapping developped by the Khronos group in order to constrain + * values between 0 and 1 without shifting Hue. + */ +ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL = 2; +/** + * Prepare the list of uniforms associated with the Image Processing effects. + * @param uniforms The list of uniforms used in the effect + * @param defines the list of defines currently in use + */ +ImageProcessingConfiguration.PrepareUniforms = PrepareUniformsForImageProcessing; +/** + * Prepare the list of samplers associated with the Image Processing effects. + * @param samplersList The list of uniforms used in the effect + * @param defines the list of defines currently in use + */ +ImageProcessingConfiguration.PrepareSamplers = PrepareSamplersForImageProcessing; +// Static constants associated to the image processing. +ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0; +ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1; +__decorate([ + serializeAsColorCurves() +], ImageProcessingConfiguration.prototype, "colorCurves", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0); +__decorate([ + serializeAsTexture("colorGradingTexture") +], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_exposure", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_contrast", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "vignetteCenterX", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "vignetteCenterY", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0); +__decorate([ + serializeAsColor4() +], ImageProcessingConfiguration.prototype, "vignetteColor", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_ditheringEnabled", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_ditheringIntensity", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_skipFinalColorClamp", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0); +__decorate([ + serialize() +], ImageProcessingConfiguration.prototype, "_isEnabled", void 0); +// References the dependencies. +SerializationHelper._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse; +// Register Class Name +RegisterClass("BABYLON.ImageProcessingConfiguration", ImageProcessingConfiguration); + +/** + * Uniform buffer objects. + * + * Handles blocks of uniform on the GPU. + * + * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls. + * + * For more information, please refer to : + * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object + */ +class UniformBuffer { + /** + * Instantiates a new Uniform buffer objects. + * + * Handles blocks of uniform on the GPU. + * + * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls. + * + * For more information, please refer to : + * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object + * @param engine Define the engine the buffer is associated with + * @param data Define the data contained in the buffer + * @param dynamic Define if the buffer is updatable + * @param name to assign to the buffer (debugging purpose) + * @param forceNoUniformBuffer define that this object must not rely on UBO objects + */ + constructor(engine, data, dynamic, name, forceNoUniformBuffer = false) { + // Matrix cache + this._valueCache = {}; + this._engine = engine; + this._noUBO = !engine.supportsUniformBuffers || forceNoUniformBuffer; + this._dynamic = dynamic; + this._name = name ?? "no-name"; + this._data = data || []; + this._uniformLocations = {}; + this._uniformSizes = {}; + this._uniformArraySizes = {}; + this._uniformLocationPointer = 0; + this._needSync = false; + if (this._engine._features.trackUbosInFrame) { + this._buffers = []; + this._bufferIndex = -1; + this._createBufferOnWrite = false; + this._currentFrameId = 0; + } + if (this._noUBO) { + this.updateMatrix3x3 = this._updateMatrix3x3ForEffect; + this.updateMatrix2x2 = this._updateMatrix2x2ForEffect; + this.updateFloat = this._updateFloatForEffect; + this.updateFloat2 = this._updateFloat2ForEffect; + this.updateFloat3 = this._updateFloat3ForEffect; + this.updateFloat4 = this._updateFloat4ForEffect; + this.updateFloatArray = this._updateFloatArrayForEffect; + this.updateArray = this._updateArrayForEffect; + this.updateIntArray = this._updateIntArrayForEffect; + this.updateUIntArray = this._updateUIntArrayForEffect; + this.updateMatrix = this._updateMatrixForEffect; + this.updateMatrices = this._updateMatricesForEffect; + this.updateVector3 = this._updateVector3ForEffect; + this.updateVector4 = this._updateVector4ForEffect; + this.updateColor3 = this._updateColor3ForEffect; + this.updateColor4 = this._updateColor4ForEffect; + this.updateDirectColor4 = this._updateDirectColor4ForEffect; + this.updateInt = this._updateIntForEffect; + this.updateInt2 = this._updateInt2ForEffect; + this.updateInt3 = this._updateInt3ForEffect; + this.updateInt4 = this._updateInt4ForEffect; + this.updateUInt = this._updateUIntForEffect; + this.updateUInt2 = this._updateUInt2ForEffect; + this.updateUInt3 = this._updateUInt3ForEffect; + this.updateUInt4 = this._updateUInt4ForEffect; + } + else { + this._engine._uniformBuffers.push(this); + this.updateMatrix3x3 = this._updateMatrix3x3ForUniform; + this.updateMatrix2x2 = this._updateMatrix2x2ForUniform; + this.updateFloat = this._updateFloatForUniform; + this.updateFloat2 = this._updateFloat2ForUniform; + this.updateFloat3 = this._updateFloat3ForUniform; + this.updateFloat4 = this._updateFloat4ForUniform; + this.updateFloatArray = this._updateFloatArrayForUniform; + this.updateArray = this._updateArrayForUniform; + this.updateIntArray = this._updateIntArrayForUniform; + this.updateUIntArray = this._updateUIntArrayForUniform; + this.updateMatrix = this._updateMatrixForUniform; + this.updateMatrices = this._updateMatricesForUniform; + this.updateVector3 = this._updateVector3ForUniform; + this.updateVector4 = this._updateVector4ForUniform; + this.updateColor3 = this._updateColor3ForUniform; + this.updateColor4 = this._updateColor4ForUniform; + this.updateDirectColor4 = this._updateDirectColor4ForUniform; + this.updateInt = this._updateIntForUniform; + this.updateInt2 = this._updateInt2ForUniform; + this.updateInt3 = this._updateInt3ForUniform; + this.updateInt4 = this._updateInt4ForUniform; + this.updateUInt = this._updateUIntForUniform; + this.updateUInt2 = this._updateUInt2ForUniform; + this.updateUInt3 = this._updateUInt3ForUniform; + this.updateUInt4 = this._updateUInt4ForUniform; + } + } + /** + * Indicates if the buffer is using the WebGL2 UBO implementation, + * or just falling back on setUniformXXX calls. + */ + get useUbo() { + return !this._noUBO; + } + /** + * Indicates if the WebGL underlying uniform buffer is in sync + * with the javascript cache data. + */ + get isSync() { + return !this._needSync; + } + /** + * Indicates if the WebGL underlying uniform buffer is dynamic. + * Also, a dynamic UniformBuffer will disable cache verification and always + * update the underlying WebGL uniform buffer to the GPU. + * @returns if Dynamic, otherwise false + */ + isDynamic() { + return this._dynamic !== undefined; + } + /** + * The data cache on JS side. + * @returns the underlying data as a float array + */ + getData() { + return this._bufferData; + } + /** + * The underlying WebGL Uniform buffer. + * @returns the webgl buffer + */ + getBuffer() { + return this._buffer; + } + /** + * std140 layout specifies how to align data within an UBO structure. + * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159 + * for specs. + * @param size + */ + _fillAlignment(size) { + // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components + // and 4x4 matrices + // TODO : change if other types are used + let alignment; + if (size <= 2) { + alignment = size; + } + else { + alignment = 4; + } + if (this._uniformLocationPointer % alignment !== 0) { + const oldPointer = this._uniformLocationPointer; + this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment); + const diff = this._uniformLocationPointer - oldPointer; + for (let i = 0; i < diff; i++) { + this._data.push(0); + } + } + } + /** + * Adds an uniform in the buffer. + * Warning : the subsequents calls of this function must be in the same order as declared in the shader + * for the layout to be correct ! The addUniform function only handles types like float, vec2, vec3, vec4, mat4, + * meaning size=1,2,3,4 or 16. It does not handle struct types. + * @param name Name of the uniform, as used in the uniform block in the shader. + * @param size Data size, or data directly. + * @param arraySize The number of elements in the array, 0 if not an array. + */ + addUniform(name, size, arraySize = 0) { + if (this._noUBO) { + return; + } + if (this._uniformLocations[name] !== undefined) { + // Already existing uniform + return; + } + // This function must be called in the order of the shader layout ! + // size can be the size of the uniform, or data directly + let data; + // std140 FTW... + if (arraySize > 0) { + if (size instanceof Array) { + // eslint-disable-next-line no-throw-literal + throw "addUniform should not be use with Array in UBO: " + name; + } + this._fillAlignment(4); + this._uniformArraySizes[name] = { strideSize: size, arraySize }; + if (size == 16) { + size = size * arraySize; + } + else { + const perElementPadding = 4 - size; + const totalPadding = perElementPadding * arraySize; + size = size * arraySize + totalPadding; + } + data = []; + // Fill with zeros + for (let i = 0; i < size; i++) { + data.push(0); + } + } + else { + if (size instanceof Array) { + data = size; + size = data.length; + } + else { + size = size; + data = []; + // Fill with zeros + for (let i = 0; i < size; i++) { + data.push(0); + } + } + this._fillAlignment(size); + } + this._uniformSizes[name] = size; + this._uniformLocations[name] = this._uniformLocationPointer; + this._uniformLocationPointer += size; + for (let i = 0; i < size; i++) { + this._data.push(data[i]); + } + this._needSync = true; + } + /** + * Adds a Matrix 4x4 to the uniform buffer. + * @param name Name of the uniform, as used in the uniform block in the shader. + * @param mat A 4x4 matrix. + */ + addMatrix(name, mat) { + this.addUniform(name, Array.prototype.slice.call(mat.asArray())); + } + /** + * Adds a vec2 to the uniform buffer. + * @param name Name of the uniform, as used in the uniform block in the shader. + * @param x Define the x component value of the vec2 + * @param y Define the y component value of the vec2 + */ + addFloat2(name, x, y) { + const temp = [x, y]; + this.addUniform(name, temp); + } + /** + * Adds a vec3 to the uniform buffer. + * @param name Name of the uniform, as used in the uniform block in the shader. + * @param x Define the x component value of the vec3 + * @param y Define the y component value of the vec3 + * @param z Define the z component value of the vec3 + */ + addFloat3(name, x, y, z) { + const temp = [x, y, z]; + this.addUniform(name, temp); + } + /** + * Adds a vec3 to the uniform buffer. + * @param name Name of the uniform, as used in the uniform block in the shader. + * @param color Define the vec3 from a Color + */ + addColor3(name, color) { + const temp = [color.r, color.g, color.b]; + this.addUniform(name, temp); + } + /** + * Adds a vec4 to the uniform buffer. + * @param name Name of the uniform, as used in the uniform block in the shader. + * @param color Define the rgb components from a Color + * @param alpha Define the a component of the vec4 + */ + addColor4(name, color, alpha) { + const temp = [color.r, color.g, color.b, alpha]; + this.addUniform(name, temp); + } + /** + * Adds a vec3 to the uniform buffer. + * @param name Name of the uniform, as used in the uniform block in the shader. + * @param vector Define the vec3 components from a Vector + */ + addVector3(name, vector) { + const temp = [vector.x, vector.y, vector.z]; + this.addUniform(name, temp); + } + /** + * Adds a Matrix 3x3 to the uniform buffer. + * @param name Name of the uniform, as used in the uniform block in the shader. + */ + addMatrix3x3(name) { + this.addUniform(name, 12); + } + /** + * Adds a Matrix 2x2 to the uniform buffer. + * @param name Name of the uniform, as used in the uniform block in the shader. + */ + addMatrix2x2(name) { + this.addUniform(name, 8); + } + /** + * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`. + */ + create() { + if (this._noUBO) { + return; + } + if (this._buffer) { + return; // nothing to do + } + // See spec, alignment must be filled as a vec4 + this._fillAlignment(4); + this._bufferData = new Float32Array(this._data); + this._rebuild(); + this._needSync = true; + } + // The result of this method is used for debugging purpose, as part of the buffer name + // It is meant to more easily know what this buffer is about when debugging + // Some buffers can have a lot of uniforms (several dozens), so the method only returns the first 10 of them + // (should be enough to understand what the buffer is for) + _getNames() { + const names = []; + let i = 0; + for (const name in this._uniformLocations) { + names.push(name); + if (++i === 10) { + break; + } + } + return names.join(","); + } + /** @internal */ + _rebuild() { + if (this._noUBO || !this._bufferData) { + return; + } + if (this._dynamic) { + this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData, this._name + "_UniformList:" + this._getNames()); + } + else { + this._buffer = this._engine.createUniformBuffer(this._bufferData, this._name + "_UniformList:" + this._getNames()); + } + if (this._engine._features.trackUbosInFrame) { + this._buffers.push([this._buffer, this._engine._features.checkUbosContentBeforeUpload ? this._bufferData.slice() : undefined]); + this._bufferIndex = this._buffers.length - 1; + this._createBufferOnWrite = false; + } + } + /** @internal */ + _rebuildAfterContextLost() { + if (this._engine._features.trackUbosInFrame) { + this._buffers = []; + this._currentFrameId = 0; + } + this._rebuild(); + } + /** @internal */ + get _numBuffers() { + return this._buffers.length; + } + /** @internal */ + get _indexBuffer() { + return this._bufferIndex; + } + /** Gets the name of this buffer */ + get name() { + return this._name; + } + /** Gets the current effect */ + get currentEffect() { + return this._currentEffect; + } + _buffersEqual(buf1, buf2) { + for (let i = 0; i < buf1.length; ++i) { + if (buf1[i] !== buf2[i]) { + return false; + } + } + return true; + } + _copyBuffer(src, dst) { + for (let i = 0; i < src.length; ++i) { + dst[i] = src[i]; + } + } + /** + * Updates the WebGL Uniform Buffer on the GPU. + * If the `dynamic` flag is set to true, no cache comparison is done. + * Otherwise, the buffer will be updated only if the cache differs. + */ + update() { + if (this._noUBO) { + return; + } + this.bindUniformBuffer(); + if (!this._buffer) { + this.create(); + return; + } + if (!this._dynamic && !this._needSync) { + this._createBufferOnWrite = this._engine._features.trackUbosInFrame; + return; + } + if (this._buffers && this._buffers.length > 1 && this._buffers[this._bufferIndex][1]) { + if (this._buffersEqual(this._bufferData, this._buffers[this._bufferIndex][1])) { + this._needSync = false; + this._createBufferOnWrite = this._engine._features.trackUbosInFrame; + return; + } + else { + this._copyBuffer(this._bufferData, this._buffers[this._bufferIndex][1]); + } + } + this._engine.updateUniformBuffer(this._buffer, this._bufferData); + if (this._engine._features._collectUbosUpdatedInFrame) { + if (!UniformBuffer._UpdatedUbosInFrame[this._name]) { + UniformBuffer._UpdatedUbosInFrame[this._name] = 0; + } + UniformBuffer._UpdatedUbosInFrame[this._name]++; + } + this._needSync = false; + this._createBufferOnWrite = this._engine._features.trackUbosInFrame; + } + _createNewBuffer() { + if (this._bufferIndex + 1 < this._buffers.length) { + this._bufferIndex++; + this._buffer = this._buffers[this._bufferIndex][0]; + this._createBufferOnWrite = false; + this._needSync = true; + } + else { + this._rebuild(); + } + } + _checkNewFrame() { + if (this._engine._features.trackUbosInFrame && this._currentFrameId !== this._engine.frameId) { + this._currentFrameId = this._engine.frameId; + this._createBufferOnWrite = false; + if (this._buffers && this._buffers.length > 0) { + this._needSync = this._bufferIndex !== 0; + this._bufferIndex = 0; + this._buffer = this._buffers[this._bufferIndex][0]; + } + else { + this._bufferIndex = -1; + } + } + } + /** + * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU. + * @param uniformName Define the name of the uniform, as used in the uniform block in the shader. + * @param data Define the flattened data + * @param size Define the size of the data. + */ + updateUniform(uniformName, data, size) { + this._checkNewFrame(); + let location = this._uniformLocations[uniformName]; + if (location === undefined) { + if (this._buffer) { + // Cannot add an uniform if the buffer is already created + Logger.Error("Cannot add an uniform after UBO has been created. uniformName=" + uniformName); + return; + } + this.addUniform(uniformName, size); + location = this._uniformLocations[uniformName]; + } + if (!this._buffer) { + this.create(); + } + if (!this._dynamic) { + // Cache for static uniform buffers + let changed = false; + for (let i = 0; i < size; i++) { + // We are checking the matrix cache before calling updateUniform so we do not need to check it here + // Hence the test for size === 16 to simply commit the matrix values + if ((size === 16 && !this._engine._features.uniformBufferHardCheckMatrix) || this._bufferData[location + i] !== Math.fround(data[i])) { + changed = true; + if (this._createBufferOnWrite) { + this._createNewBuffer(); + } + this._bufferData[location + i] = data[i]; + } + } + this._needSync = this._needSync || changed; + } + else { + // No cache for dynamic + for (let i = 0; i < size; i++) { + this._bufferData[location + i] = data[i]; + } + } + } + /** + * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU. + * @param uniformName Define the name of the uniform, as used in the uniform block in the shader. + * @param data Define the flattened data + * @param size Define the size of the data. + */ + updateUniformArray(uniformName, data, size) { + this._checkNewFrame(); + const location = this._uniformLocations[uniformName]; + if (location === undefined) { + Logger.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine."); + return; + } + if (!this._buffer) { + this.create(); + } + const arraySizes = this._uniformArraySizes[uniformName]; + if (!this._dynamic) { + // Cache for static uniform buffers + let changed = false; + let countToFour = 0; + let baseStride = 0; + for (let i = 0; i < size; i++) { + if (this._bufferData[location + baseStride * 4 + countToFour] !== Tools.FloatRound(data[i])) { + changed = true; + if (this._createBufferOnWrite) { + this._createNewBuffer(); + } + this._bufferData[location + baseStride * 4 + countToFour] = data[i]; + } + countToFour++; + if (countToFour === arraySizes.strideSize) { + for (; countToFour < 4; countToFour++) { + this._bufferData[location + baseStride * 4 + countToFour] = 0; + } + countToFour = 0; + baseStride++; + } + } + this._needSync = this._needSync || changed; + } + else { + // No cache for dynamic + for (let i = 0; i < size; i++) { + this._bufferData[location + i] = data[i]; + } + } + } + _cacheMatrix(name, matrix) { + this._checkNewFrame(); + const cache = this._valueCache[name]; + const flag = matrix.updateFlag; + if (cache !== undefined && cache === flag) { + return false; + } + this._valueCache[name] = flag; + return true; + } + // Update methods + _updateMatrix3x3ForUniform(name, matrix) { + // To match std140, matrix must be realigned + for (let i = 0; i < 3; i++) { + UniformBuffer._TempBuffer[i * 4] = matrix[i * 3]; + UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 3 + 1]; + UniformBuffer._TempBuffer[i * 4 + 2] = matrix[i * 3 + 2]; + UniformBuffer._TempBuffer[i * 4 + 3] = 0.0; + } + this.updateUniform(name, UniformBuffer._TempBuffer, 12); + } + _updateMatrix3x3ForEffect(name, matrix) { + this._currentEffect.setMatrix3x3(name, matrix); + } + _updateMatrix2x2ForEffect(name, matrix) { + this._currentEffect.setMatrix2x2(name, matrix); + } + _updateMatrix2x2ForUniform(name, matrix) { + // To match std140, matrix must be realigned + for (let i = 0; i < 2; i++) { + UniformBuffer._TempBuffer[i * 4] = matrix[i * 2]; + UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 2 + 1]; + UniformBuffer._TempBuffer[i * 4 + 2] = 0.0; + UniformBuffer._TempBuffer[i * 4 + 3] = 0.0; + } + this.updateUniform(name, UniformBuffer._TempBuffer, 8); + } + _updateFloatForEffect(name, x) { + this._currentEffect.setFloat(name, x); + } + _updateFloatForUniform(name, x) { + UniformBuffer._TempBuffer[0] = x; + this.updateUniform(name, UniformBuffer._TempBuffer, 1); + } + _updateFloat2ForEffect(name, x, y, suffix = "") { + this._currentEffect.setFloat2(name + suffix, x, y); + } + _updateFloat2ForUniform(name, x, y) { + UniformBuffer._TempBuffer[0] = x; + UniformBuffer._TempBuffer[1] = y; + this.updateUniform(name, UniformBuffer._TempBuffer, 2); + } + _updateFloat3ForEffect(name, x, y, z, suffix = "") { + this._currentEffect.setFloat3(name + suffix, x, y, z); + } + _updateFloat3ForUniform(name, x, y, z) { + UniformBuffer._TempBuffer[0] = x; + UniformBuffer._TempBuffer[1] = y; + UniformBuffer._TempBuffer[2] = z; + this.updateUniform(name, UniformBuffer._TempBuffer, 3); + } + _updateFloat4ForEffect(name, x, y, z, w, suffix = "") { + this._currentEffect.setFloat4(name + suffix, x, y, z, w); + } + _updateFloat4ForUniform(name, x, y, z, w) { + UniformBuffer._TempBuffer[0] = x; + UniformBuffer._TempBuffer[1] = y; + UniformBuffer._TempBuffer[2] = z; + UniformBuffer._TempBuffer[3] = w; + this.updateUniform(name, UniformBuffer._TempBuffer, 4); + } + _updateFloatArrayForEffect(name, array) { + this._currentEffect.setFloatArray(name, array); + } + _updateFloatArrayForUniform(name, array) { + this.updateUniformArray(name, array, array.length); + } + _updateArrayForEffect(name, array) { + this._currentEffect.setArray(name, array); + } + _updateArrayForUniform(name, array) { + this.updateUniformArray(name, array, array.length); + } + _updateIntArrayForEffect(name, array) { + this._currentEffect.setIntArray(name, array); + } + _updateIntArrayForUniform(name, array) { + UniformBuffer._TempBufferInt32View.set(array); + this.updateUniformArray(name, UniformBuffer._TempBuffer, array.length); + } + _updateUIntArrayForEffect(name, array) { + this._currentEffect.setUIntArray(name, array); + } + _updateUIntArrayForUniform(name, array) { + UniformBuffer._TempBufferUInt32View.set(array); + this.updateUniformArray(name, UniformBuffer._TempBuffer, array.length); + } + _updateMatrixForEffect(name, mat) { + this._currentEffect.setMatrix(name, mat); + } + _updateMatrixForUniform(name, mat) { + if (this._cacheMatrix(name, mat)) { + this.updateUniform(name, mat.asArray(), 16); + } + } + _updateMatricesForEffect(name, mat) { + this._currentEffect.setMatrices(name, mat); + } + _updateMatricesForUniform(name, mat) { + this.updateUniform(name, mat, mat.length); + } + _updateVector3ForEffect(name, vector) { + this._currentEffect.setVector3(name, vector); + } + _updateVector3ForUniform(name, vector) { + UniformBuffer._TempBuffer[0] = vector.x; + UniformBuffer._TempBuffer[1] = vector.y; + UniformBuffer._TempBuffer[2] = vector.z; + this.updateUniform(name, UniformBuffer._TempBuffer, 3); + } + _updateVector4ForEffect(name, vector) { + this._currentEffect.setVector4(name, vector); + } + _updateVector4ForUniform(name, vector) { + UniformBuffer._TempBuffer[0] = vector.x; + UniformBuffer._TempBuffer[1] = vector.y; + UniformBuffer._TempBuffer[2] = vector.z; + UniformBuffer._TempBuffer[3] = vector.w; + this.updateUniform(name, UniformBuffer._TempBuffer, 4); + } + _updateColor3ForEffect(name, color, suffix = "") { + this._currentEffect.setColor3(name + suffix, color); + } + _updateColor3ForUniform(name, color) { + UniformBuffer._TempBuffer[0] = color.r; + UniformBuffer._TempBuffer[1] = color.g; + UniformBuffer._TempBuffer[2] = color.b; + this.updateUniform(name, UniformBuffer._TempBuffer, 3); + } + _updateColor4ForEffect(name, color, alpha, suffix = "") { + this._currentEffect.setColor4(name + suffix, color, alpha); + } + _updateDirectColor4ForEffect(name, color, suffix = "") { + this._currentEffect.setDirectColor4(name + suffix, color); + } + _updateColor4ForUniform(name, color, alpha) { + UniformBuffer._TempBuffer[0] = color.r; + UniformBuffer._TempBuffer[1] = color.g; + UniformBuffer._TempBuffer[2] = color.b; + UniformBuffer._TempBuffer[3] = alpha; + this.updateUniform(name, UniformBuffer._TempBuffer, 4); + } + _updateDirectColor4ForUniform(name, color) { + UniformBuffer._TempBuffer[0] = color.r; + UniformBuffer._TempBuffer[1] = color.g; + UniformBuffer._TempBuffer[2] = color.b; + UniformBuffer._TempBuffer[3] = color.a; + this.updateUniform(name, UniformBuffer._TempBuffer, 4); + } + _updateIntForEffect(name, x, suffix = "") { + this._currentEffect.setInt(name + suffix, x); + } + _updateIntForUniform(name, x) { + UniformBuffer._TempBufferInt32View[0] = x; + this.updateUniform(name, UniformBuffer._TempBuffer, 1); + } + _updateInt2ForEffect(name, x, y, suffix = "") { + this._currentEffect.setInt2(name + suffix, x, y); + } + _updateInt2ForUniform(name, x, y) { + UniformBuffer._TempBufferInt32View[0] = x; + UniformBuffer._TempBufferInt32View[1] = y; + this.updateUniform(name, UniformBuffer._TempBuffer, 2); + } + _updateInt3ForEffect(name, x, y, z, suffix = "") { + this._currentEffect.setInt3(name + suffix, x, y, z); + } + _updateInt3ForUniform(name, x, y, z) { + UniformBuffer._TempBufferInt32View[0] = x; + UniformBuffer._TempBufferInt32View[1] = y; + UniformBuffer._TempBufferInt32View[2] = z; + this.updateUniform(name, UniformBuffer._TempBuffer, 3); + } + _updateInt4ForEffect(name, x, y, z, w, suffix = "") { + this._currentEffect.setInt4(name + suffix, x, y, z, w); + } + _updateInt4ForUniform(name, x, y, z, w) { + UniformBuffer._TempBufferInt32View[0] = x; + UniformBuffer._TempBufferInt32View[1] = y; + UniformBuffer._TempBufferInt32View[2] = z; + UniformBuffer._TempBufferInt32View[3] = w; + this.updateUniform(name, UniformBuffer._TempBuffer, 4); + } + _updateUIntForEffect(name, x, suffix = "") { + this._currentEffect.setUInt(name + suffix, x); + } + _updateUIntForUniform(name, x) { + UniformBuffer._TempBufferUInt32View[0] = x; + this.updateUniform(name, UniformBuffer._TempBuffer, 1); + } + _updateUInt2ForEffect(name, x, y, suffix = "") { + this._currentEffect.setUInt2(name + suffix, x, y); + } + _updateUInt2ForUniform(name, x, y) { + UniformBuffer._TempBufferUInt32View[0] = x; + UniformBuffer._TempBufferUInt32View[1] = y; + this.updateUniform(name, UniformBuffer._TempBuffer, 2); + } + _updateUInt3ForEffect(name, x, y, z, suffix = "") { + this._currentEffect.setUInt3(name + suffix, x, y, z); + } + _updateUInt3ForUniform(name, x, y, z) { + UniformBuffer._TempBufferUInt32View[0] = x; + UniformBuffer._TempBufferUInt32View[1] = y; + UniformBuffer._TempBufferUInt32View[2] = z; + this.updateUniform(name, UniformBuffer._TempBuffer, 3); + } + _updateUInt4ForEffect(name, x, y, z, w, suffix = "") { + this._currentEffect.setUInt4(name + suffix, x, y, z, w); + } + _updateUInt4ForUniform(name, x, y, z, w) { + UniformBuffer._TempBufferUInt32View[0] = x; + UniformBuffer._TempBufferUInt32View[1] = y; + UniformBuffer._TempBufferUInt32View[2] = z; + UniformBuffer._TempBufferUInt32View[3] = w; + this.updateUniform(name, UniformBuffer._TempBuffer, 4); + } + /** + * Sets a sampler uniform on the effect. + * @param name Define the name of the sampler. + * @param texture Define the texture to set in the sampler + */ + setTexture(name, texture) { + this._currentEffect.setTexture(name, texture); + } + /** + * Sets an array of sampler uniforms on the effect. + * @param name Define the name of uniform. + * @param textures Define the textures to set in the array of samplers + */ + setTextureArray(name, textures) { + this._currentEffect.setTextureArray(name, textures); + } + /** + * Sets a sampler uniform on the effect. + * @param name Define the name of the sampler. + * @param texture Define the (internal) texture to set in the sampler + */ + bindTexture(name, texture) { + this._currentEffect._bindTexture(name, texture); + } + /** + * Directly updates the value of the uniform in the cache AND on the GPU. + * @param uniformName Define the name of the uniform, as used in the uniform block in the shader. + * @param data Define the flattened data + */ + updateUniformDirectly(uniformName, data) { + this.updateUniform(uniformName, data, data.length); + this.update(); + } + /** + * Associates an effect to this uniform buffer + * @param effect Define the effect to associate the buffer to + * @param name Name of the uniform block in the shader. + */ + bindToEffect(effect, name) { + this._currentEffect = effect; + this._currentEffectName = name; + } + /** + * Binds the current (GPU) buffer to the effect + */ + bindUniformBuffer() { + if (!this._noUBO && this._buffer && this._currentEffect) { + this._currentEffect.bindUniformBuffer(this._buffer, this._currentEffectName); + } + } + /** + * Dissociates the current effect from this uniform buffer + */ + unbindEffect() { + this._currentEffect = undefined; + this._currentEffectName = undefined; + } + /** + * Sets the current state of the class (_bufferIndex, _buffer) to point to the data buffer passed in parameter if this buffer is one of the buffers handled by the class (meaning if it can be found in the _buffers array) + * This method is meant to be able to update a buffer at any time: just call setDataBuffer to set the class in the right state, call some updateXXX methods and then call udpate() => that will update the GPU buffer on the graphic card + * @param dataBuffer buffer to look for + * @returns true if the buffer has been found and the class internal state points to it, else false + */ + setDataBuffer(dataBuffer) { + if (!this._buffers) { + return this._buffer === dataBuffer; + } + for (let b = 0; b < this._buffers.length; ++b) { + const buffer = this._buffers[b]; + if (buffer[0] === dataBuffer) { + this._bufferIndex = b; + this._buffer = dataBuffer; + this._createBufferOnWrite = false; + this._currentEffect = undefined; + return true; + } + } + return false; + } + /** + * Disposes the uniform buffer. + */ + dispose() { + if (this._noUBO) { + return; + } + const uniformBuffers = this._engine._uniformBuffers; + const index = uniformBuffers.indexOf(this); + if (index !== -1) { + uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1]; + uniformBuffers.pop(); + } + if (this._engine._features.trackUbosInFrame && this._buffers) { + for (let i = 0; i < this._buffers.length; ++i) { + const buffer = this._buffers[i][0]; + this._engine._releaseBuffer(buffer); + } + } + else if (this._buffer && this._engine._releaseBuffer(this._buffer)) { + this._buffer = null; + } + } +} +/** @internal */ +UniformBuffer._UpdatedUbosInFrame = {}; +// Pool for avoiding memory leaks +UniformBuffer._MAX_UNIFORM_SIZE = 256; +UniformBuffer._TempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE); +UniformBuffer._TempBufferInt32View = new Int32Array(UniformBuffer._TempBuffer.buffer); +UniformBuffer._TempBufferUInt32View = new Uint32Array(UniformBuffer._TempBuffer.buffer); + +function GetFloatValue(dataView, type, byteOffset, normalized) { + switch (type) { + case 5120: { + let value = dataView.getInt8(byteOffset); + if (normalized) { + value = Math.max(value / 127, -1); + } + return value; + } + case 5121: { + let value = dataView.getUint8(byteOffset); + if (normalized) { + value = value / 255; + } + return value; + } + case 5122: { + let value = dataView.getInt16(byteOffset, true); + if (normalized) { + value = Math.max(value / 32767, -1); + } + return value; + } + case 5123: { + let value = dataView.getUint16(byteOffset, true); + if (normalized) { + value = value / 65535; + } + return value; + } + case 5124: { + return dataView.getInt32(byteOffset, true); + } + case 5125: { + return dataView.getUint32(byteOffset, true); + } + case 5126: { + return dataView.getFloat32(byteOffset, true); + } + default: { + throw new Error(`Invalid component type ${type}`); + } + } +} +function SetFloatValue(dataView, type, byteOffset, normalized, value) { + switch (type) { + case 5120: { + if (normalized) { + value = Math.round(value * 127.0); + } + dataView.setInt8(byteOffset, value); + break; + } + case 5121: { + if (normalized) { + value = Math.round(value * 255); + } + dataView.setUint8(byteOffset, value); + break; + } + case 5122: { + if (normalized) { + value = Math.round(value * 32767); + } + dataView.setInt16(byteOffset, value, true); + break; + } + case 5123: { + if (normalized) { + value = Math.round(value * 65535); + } + dataView.setUint16(byteOffset, value, true); + break; + } + case 5124: { + dataView.setInt32(byteOffset, value, true); + break; + } + case 5125: { + dataView.setUint32(byteOffset, value, true); + break; + } + case 5126: { + dataView.setFloat32(byteOffset, value, true); + break; + } + default: { + throw new Error(`Invalid component type ${type}`); + } + } +} +/** + * Gets the byte length of the given type. + * @param type the type + * @returns the number of bytes + */ +function GetTypeByteLength(type) { + switch (type) { + case 5120: + case 5121: + return 1; + case 5122: + case 5123: + return 2; + case 5124: + case 5125: + case 5126: + return 4; + default: + throw new Error(`Invalid type '${type}'`); + } +} +/** + * Gets the appropriate TypedArray constructor for the given component type. + * @param componentType the component type + * @returns the constructor object + */ +function GetTypedArrayConstructor(componentType) { + switch (componentType) { + case 5120: + return Int8Array; + case 5121: + return Uint8Array; + case 5122: + return Int16Array; + case 5123: + return Uint16Array; + case 5124: + return Int32Array; + case 5125: + return Uint32Array; + case 5126: + return Float32Array; + default: + throw new Error(`Invalid component type '${componentType}'`); + } +} +/** + * Enumerates each value of the data array and calls the given callback. + * @param data the data to enumerate + * @param byteOffset the byte offset of the data + * @param byteStride the byte stride of the data + * @param componentCount the number of components per element + * @param componentType the type of the component + * @param count the number of values to enumerate + * @param normalized whether the data is normalized + * @param callback the callback function called for each group of component values + */ +function EnumerateFloatValues(data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) { + const oldValues = new Array(componentCount); + const newValues = new Array(componentCount); + if (data instanceof Array) { + let offset = byteOffset / 4; + const stride = byteStride / 4; + for (let index = 0; index < count; index += componentCount) { + for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) { + oldValues[componentIndex] = newValues[componentIndex] = data[offset + componentIndex]; + } + callback(newValues, index); + for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) { + if (oldValues[componentIndex] !== newValues[componentIndex]) { + data[offset + componentIndex] = newValues[componentIndex]; + } + } + offset += stride; + } + } + else { + const dataView = !ArrayBuffer.isView(data) ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength); + const componentByteLength = GetTypeByteLength(componentType); + for (let index = 0; index < count; index += componentCount) { + for (let componentIndex = 0, componentByteOffset = byteOffset; componentIndex < componentCount; componentIndex++, componentByteOffset += componentByteLength) { + oldValues[componentIndex] = newValues[componentIndex] = GetFloatValue(dataView, componentType, componentByteOffset, normalized); + } + callback(newValues, index); + for (let componentIndex = 0, componentByteOffset = byteOffset; componentIndex < componentCount; componentIndex++, componentByteOffset += componentByteLength) { + if (oldValues[componentIndex] !== newValues[componentIndex]) { + SetFloatValue(dataView, componentType, componentByteOffset, normalized, newValues[componentIndex]); + } + } + byteOffset += byteStride; + } + } +} +/** + * Gets the given data array as a float array. Float data is constructed if the data array cannot be returned directly. + * @param data the input data array + * @param size the number of components + * @param type the component type + * @param byteOffset the byte offset of the data + * @param byteStride the byte stride of the data + * @param normalized whether the data is normalized + * @param totalVertices number of vertices in the buffer to take into account + * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it + * @returns a float array containing vertex data + */ +function GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy) { + const tightlyPackedByteStride = size * GetTypeByteLength(type); + const count = totalVertices * size; + if (type !== 5126 || byteStride !== tightlyPackedByteStride) { + const copy = new Float32Array(count); + EnumerateFloatValues(data, byteOffset, byteStride, size, type, count, normalized, (values, index) => { + for (let i = 0; i < size; i++) { + copy[index + i] = values[i]; + } + }); + return copy; + } + if (!(data instanceof Array || data instanceof Float32Array) || byteOffset !== 0 || data.length !== count) { + if (data instanceof Array) { + const offset = byteOffset / 4; + return data.slice(offset, offset + count); + } + else if (data instanceof ArrayBuffer) { + return new Float32Array(data, byteOffset, count); + } + else { + const offset = data.byteOffset + byteOffset; + if ((offset & 3) !== 0) { + Logger.Warn("Float array must be aligned to 4-bytes border"); + forceCopy = true; + } + if (forceCopy) { + return new Float32Array(data.buffer.slice(offset, offset + count * Float32Array.BYTES_PER_ELEMENT)); + } + else { + return new Float32Array(data.buffer, offset, count); + } + } + } + if (forceCopy) { + return data.slice(); + } + return data; +} +/** + * Gets the given data array as a typed array that matches the component type. If the data cannot be used directly, a copy is made to support the new typed array. + * If the data is number[], byteOffset and byteStride must be a multiple of 4, as data will be treated like a list of floats. + * @param data the input data array + * @param size the number of components + * @param type the component type + * @param byteOffset the byte offset of the data + * @param byteStride the byte stride of the data + * @param normalized whether the data is normalized + * @param totalVertices number of vertices in the buffer to take into account + * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it + * @returns a typed array containing vertex data + */ +function GetTypedArrayData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy) { + const typeByteLength = GetTypeByteLength(type); + const constructor = GetTypedArrayConstructor(type); + const count = totalVertices * size; + // Handle number[] + if (Array.isArray(data)) { + if ((byteOffset & 3) !== 0 || (byteStride & 3) !== 0) { + throw new Error("byteOffset and byteStride must be a multiple of 4 for number[] data."); + } + const offset = byteOffset / 4; + const stride = byteStride / 4; + const lastIndex = offset + (totalVertices - 1) * stride + size; + if (lastIndex > data.length) { + throw new Error("Last accessed index is out of bounds."); + } + if (stride < size) { + throw new Error("Data stride cannot be smaller than the component size."); + } + if (stride !== size) { + const copy = new constructor(count); + EnumerateFloatValues(data, byteOffset, byteStride, size, type, count, normalized, (values, index) => { + for (let i = 0; i < size; i++) { + copy[index + i] = values[i]; + } + }); + return copy; + } + return new constructor(data.slice(offset, offset + count)); + } + // Handle ArrayBuffer and ArrayBufferView + let buffer; + let adjustedByteOffset = byteOffset; + if (data instanceof ArrayBuffer) { + buffer = data; + } + else { + buffer = data.buffer; + adjustedByteOffset += data.byteOffset; + } + const lastByteOffset = adjustedByteOffset + (totalVertices - 1) * byteStride + size * typeByteLength; + if (lastByteOffset > buffer.byteLength) { + throw new Error("Last accessed byte is out of bounds."); + } + const tightlyPackedByteStride = size * typeByteLength; + if (byteStride < tightlyPackedByteStride) { + throw new Error("Byte stride cannot be smaller than the component's byte size."); + } + if (byteStride !== tightlyPackedByteStride) { + const copy = new constructor(count); + EnumerateFloatValues(buffer, adjustedByteOffset, byteStride, size, type, count, normalized, (values, index) => { + for (let i = 0; i < size; i++) { + copy[index + i] = values[i]; + } + }); + return copy; + } + if (typeByteLength !== 1 && (adjustedByteOffset & (typeByteLength - 1)) !== 0) { + Logger.Warn("Array must be aligned to border of element size. Data will be copied."); + forceCopy = true; + } + if (forceCopy) { + return new constructor(buffer.slice(adjustedByteOffset, adjustedByteOffset + count * typeByteLength)); + } + return new constructor(buffer, adjustedByteOffset, count); +} +/** + * Copies the given data array to the given float array. + * @param input the input data array + * @param size the number of components + * @param type the component type + * @param byteOffset the byte offset of the data + * @param byteStride the byte stride of the data + * @param normalized whether the data is normalized + * @param totalVertices number of vertices in the buffer to take into account + * @param output the output float array + */ +function CopyFloatData(input, size, type, byteOffset, byteStride, normalized, totalVertices, output) { + const tightlyPackedByteStride = size * GetTypeByteLength(type); + const count = totalVertices * size; + if (output.length !== count) { + throw new Error("Output length is not valid"); + } + if (type !== 5126 || byteStride !== tightlyPackedByteStride) { + EnumerateFloatValues(input, byteOffset, byteStride, size, type, count, normalized, (values, index) => { + for (let i = 0; i < size; i++) { + output[index + i] = values[i]; + } + }); + return; + } + if (input instanceof Array) { + const offset = byteOffset / 4; + output.set(input, offset); + } + else if (input instanceof ArrayBuffer) { + const floatData = new Float32Array(input, byteOffset, count); + output.set(floatData); + } + else { + const offset = input.byteOffset + byteOffset; + if ((offset & 3) !== 0) { + Logger.Warn("Float array must be aligned to 4-bytes border"); + output.set(new Float32Array(input.buffer.slice(offset, offset + count * Float32Array.BYTES_PER_ELEMENT))); + return; + } + const floatData = new Float32Array(input.buffer, offset, count); + output.set(floatData); + } +} +/** + * Utility function to determine if an IndicesArray is an Uint32Array. If indices is an Array, determines whether at least one index is 32 bits. + * @param indices The IndicesArray to check. + * @param count The number of indices. Only used if indices is an Array. + * @param start The offset to start at (default: 0). Only used if indices is an Array. + * @param offset The offset to substract from the indices before testing (default: 0). Only used if indices is an Array. + * @returns True if the indices use 32 bits + */ +function AreIndices32Bits(indices, count, start = 0, offset = 0) { + if (Array.isArray(indices)) { + for (let index = 0; index < count; index++) { + if (indices[start + index] - offset > 65535) { + return true; + } + } + return false; + } + return indices.BYTES_PER_ELEMENT === 4; +} + +/** + * Class used to store data that will be store in GPU memory + */ +class Buffer { + /** + * Gets a boolean indicating if the Buffer is disposed + */ + get isDisposed() { + return this._isDisposed; + } + /** + * Constructor + * @param engine the engine + * @param data the data to use for this buffer + * @param updatable whether the data is updatable + * @param stride the stride (optional) + * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) + * @param instanced whether the buffer is instanced (optional) + * @param useBytes set to true if the stride in in bytes (optional) + * @param divisor sets an optional divisor for instances (1 by default) + * @param label defines the label of the buffer (for debug purpose) + */ + constructor(engine, data, updatable, stride = 0, postponeInternalCreation = false, instanced = false, useBytes = false, divisor, label) { + this._isAlreadyOwned = false; + this._isDisposed = false; + if (engine && engine.getScene) { + // old versions of VertexBuffer accepted 'mesh' instead of 'engine' + this._engine = engine.getScene().getEngine(); + } + else { + this._engine = engine; + } + this._updatable = updatable; + this._instanced = instanced; + this._divisor = divisor || 1; + this._label = label; + if (data instanceof DataBuffer) { + this._data = null; + this._buffer = data; + } + else { + this._data = data; + this._buffer = null; + } + this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT; + if (!postponeInternalCreation) { + // by default + this.create(); + } + } + /** + * Create a new VertexBuffer based on the current buffer + * @param kind defines the vertex buffer kind (position, normal, etc.) + * @param offset defines offset in the buffer (0 by default) + * @param size defines the size in floats of attributes (position is 3 for instance) + * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved) + * @param instanced defines if the vertex buffer contains indexed data + * @param useBytes defines if the offset and stride are in bytes * + * @param divisor sets an optional divisor for instances (1 by default) + * @returns the new vertex buffer + */ + createVertexBuffer(kind, offset, size, stride, instanced, useBytes = false, divisor) { + const byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT; + const byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride; + // a lot of these parameters are ignored as they are overridden by the buffer + return new VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true, this._divisor || divisor); + } + // Properties + /** + * Gets a boolean indicating if the Buffer is updatable? + * @returns true if the buffer is updatable + */ + isUpdatable() { + return this._updatable; + } + /** + * Gets current buffer's data + * @returns a DataArray or null + */ + getData() { + return this._data; + } + /** + * Gets underlying native buffer + * @returns underlying native buffer + */ + getBuffer() { + return this._buffer; + } + /** + * Gets the stride in float32 units (i.e. byte stride / 4). + * May not be an integer if the byte stride is not divisible by 4. + * @returns the stride in float32 units + * @deprecated Please use byteStride instead. + */ + getStrideSize() { + return this.byteStride / Float32Array.BYTES_PER_ELEMENT; + } + // Methods + /** + * Store data into the buffer. Creates the buffer if not used already. + * If the buffer was already used, it will be updated only if it is updatable, otherwise it will do nothing. + * @param data defines the data to store + */ + create(data = null) { + if (!data && this._buffer) { + return; // nothing to do + } + data = data || this._data; + if (!data) { + return; + } + if (!this._buffer) { + // create buffer + if (this._updatable) { + this._buffer = this._engine.createDynamicVertexBuffer(data, this._label); + this._data = data; + } + else { + this._buffer = this._engine.createVertexBuffer(data, undefined, this._label); + } + } + else if (this._updatable) { + // update buffer + this._engine.updateDynamicVertexBuffer(this._buffer, data); + this._data = data; + } + } + /** @internal */ + _rebuild() { + if (!this._data) { + if (!this._buffer) { + // Buffer was not yet created, nothing to do + return; + } + if (this._buffer.capacity > 0) { + // We can at least recreate the buffer with the right size, even if we don't have the data + if (this._updatable) { + this._buffer = this._engine.createDynamicVertexBuffer(this._buffer.capacity, this._label); + } + else { + this._buffer = this._engine.createVertexBuffer(this._buffer.capacity, undefined, this._label); + } + return; + } + Logger.Warn(`Missing data for buffer "${this._label}" ${this._buffer ? "(uniqueId: " + this._buffer.uniqueId + ")" : ""}. Buffer reconstruction failed.`); + this._buffer = null; + } + else { + this._buffer = null; + this.create(this._data); + } + } + /** + * Update current buffer data + * @param data defines the data to store + */ + update(data) { + this.create(data); + } + /** + * Updates the data directly. + * @param data the new data + * @param offset the new offset + * @param vertexCount the vertex count (optional) + * @param useBytes set to true if the offset is in bytes + */ + updateDirectly(data, offset, vertexCount, useBytes = false) { + if (!this._buffer) { + return; + } + if (this._updatable) { + // update buffer + this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, vertexCount ? vertexCount * this.byteStride : undefined); + if (offset === 0 && vertexCount === undefined) { + // Keep the data if we easily can + this._data = data; + } + else { + this._data = null; + } + } + } + /** @internal */ + _increaseReferences() { + if (!this._buffer) { + return; + } + if (!this._isAlreadyOwned) { + this._isAlreadyOwned = true; + return; + } + this._buffer.references++; + } + /** + * Release all resources + */ + dispose() { + if (!this._buffer) { + return; + } + // The data buffer has an internal counter as this buffer can be used by several VertexBuffer objects + // This means that we only flag it as disposed when all references are released (when _releaseBuffer will return true) + if (this._engine._releaseBuffer(this._buffer)) { + this._isDisposed = true; + this._data = null; + this._buffer = null; + } + } +} +/** + * Specialized buffer used to store vertex data + */ +class VertexBuffer { + /** + * Gets a boolean indicating if the Buffer is disposed + */ + get isDisposed() { + return this._isDisposed; + } + /** + * Gets or sets the instance divisor when in instanced mode + */ + get instanceDivisor() { + return this._instanceDivisor; + } + set instanceDivisor(value) { + const isInstanced = value != 0; + this._instanceDivisor = value; + if (isInstanced !== this._instanced) { + this._instanced = isInstanced; + this._computeHashCode(); + } + } + /** + * Gets the max possible amount of vertices stored within the current vertex buffer. + * We do not have the end offset or count so this will be too big for concatenated vertex buffers. + * @internal + */ + get _maxVerticesCount() { + const data = this.getData(); + if (!data) { + return 0; + } + if (Array.isArray(data)) { + // data is a regular number[] with float values + return data.length / (this.byteStride / 4) - this.byteOffset / 4; + } + return (data.byteLength - this.byteOffset) / this.byteStride; + } + /** @internal */ + constructor(engine, data, kind, updatableOrOptions, postponeInternalCreation, stride, instanced, offset, size, type, normalized = false, useBytes = false, divisor = 1, takeBufferOwnership = false) { + /** @internal */ + this._isDisposed = false; + let updatable = false; + this.engine = engine; + if (typeof updatableOrOptions === "object" && updatableOrOptions !== null) { + updatable = updatableOrOptions.updatable ?? false; + postponeInternalCreation = updatableOrOptions.postponeInternalCreation; + stride = updatableOrOptions.stride; + instanced = updatableOrOptions.instanced; + offset = updatableOrOptions.offset; + size = updatableOrOptions.size; + type = updatableOrOptions.type; + normalized = updatableOrOptions.normalized ?? false; + useBytes = updatableOrOptions.useBytes ?? false; + divisor = updatableOrOptions.divisor ?? 1; + takeBufferOwnership = updatableOrOptions.takeBufferOwnership ?? false; + this._label = updatableOrOptions.label; + } + else { + updatable = !!updatableOrOptions; + } + if (data instanceof Buffer) { + this._buffer = data; + this._ownsBuffer = takeBufferOwnership; + } + else { + this._buffer = new Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes, divisor, this._label); + this._ownsBuffer = true; + } + this.uniqueId = VertexBuffer._Counter++; + this._kind = kind; + if (type === undefined) { + const vertexData = this.getData(); + this.type = vertexData ? VertexBuffer.GetDataType(vertexData) : VertexBuffer.FLOAT; + } + else { + this.type = type; + } + const typeByteLength = GetTypeByteLength(this.type); + if (useBytes) { + this._size = size || (stride ? stride / typeByteLength : VertexBuffer.DeduceStride(kind)); + this.byteStride = stride || this._buffer.byteStride || this._size * typeByteLength; + this.byteOffset = offset || 0; + } + else { + this._size = size || stride || VertexBuffer.DeduceStride(kind); + this.byteStride = stride ? stride * typeByteLength : this._buffer.byteStride || this._size * typeByteLength; + this.byteOffset = (offset || 0) * typeByteLength; + } + this.normalized = normalized; + this._instanced = instanced !== undefined ? instanced : false; + this._instanceDivisor = instanced ? divisor : 0; + this._alignBuffer(); + this._computeHashCode(); + } + _computeHashCode() { + // note: cast to any because the property is declared readonly + this.hashCode = + ((this.type - 5120) << 0) + + ((this.normalized ? 1 : 0) << 3) + + (this._size << 4) + + ((this._instanced ? 1 : 0) << 6) + + /* keep 5 bits free */ + (this.byteStride << 12); + } + /** @internal */ + _rebuild() { + this._buffer?._rebuild(); + } + /** + * Returns the kind of the VertexBuffer (string) + * @returns a string + */ + getKind() { + return this._kind; + } + // Properties + /** + * Gets a boolean indicating if the VertexBuffer is updatable? + * @returns true if the buffer is updatable + */ + isUpdatable() { + return this._buffer.isUpdatable(); + } + /** + * Gets current buffer's data + * @returns a DataArray or null + */ + getData() { + return this._buffer.getData(); + } + /** + * Gets current buffer's data as a float array. Float data is constructed if the vertex buffer data cannot be returned directly. + * @param totalVertices number of vertices in the buffer to take into account + * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it + * @returns a float array containing vertex data + */ + getFloatData(totalVertices, forceCopy) { + const data = this.getData(); + if (!data) { + return null; + } + return GetFloatData(data, this._size, this.type, this.byteOffset, this.byteStride, this.normalized, totalVertices, forceCopy); + } + /** + * Gets underlying native buffer + * @returns underlying native buffer + */ + getBuffer() { + return this._buffer.getBuffer(); + } + /** + * Gets the Buffer instance that wraps the native GPU buffer + * @returns the wrapper buffer + */ + getWrapperBuffer() { + return this._buffer; + } + /** + * Gets the stride in float32 units (i.e. byte stride / 4). + * May not be an integer if the byte stride is not divisible by 4. + * @returns the stride in float32 units + * @deprecated Please use byteStride instead. + */ + getStrideSize() { + return this.byteStride / GetTypeByteLength(this.type); + } + /** + * Returns the offset as a multiple of the type byte length. + * @returns the offset in bytes + * @deprecated Please use byteOffset instead. + */ + getOffset() { + return this.byteOffset / GetTypeByteLength(this.type); + } + /** + * Returns the number of components or the byte size per vertex attribute + * @param sizeInBytes If true, returns the size in bytes or else the size in number of components of the vertex attribute (default: false) + * @returns the number of components + */ + getSize(sizeInBytes = false) { + return sizeInBytes ? this._size * GetTypeByteLength(this.type) : this._size; + } + /** + * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced + * @returns true if this buffer is instanced + */ + getIsInstanced() { + return this._instanced; + } + /** + * Returns the instancing divisor, zero for non-instanced (integer). + * @returns a number + */ + getInstanceDivisor() { + return this._instanceDivisor; + } + // Methods + /** + * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property + * @param data defines the data to store + */ + create(data) { + this._buffer.create(data); + this._alignBuffer(); + } + /** + * Updates the underlying buffer according to the passed numeric array or Float32Array. + * This function will create a new buffer if the current one is not updatable + * @param data defines the data to store + */ + update(data) { + this._buffer.update(data); + this._alignBuffer(); + } + /** + * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array. + * Returns the directly updated WebGLBuffer. + * @param data the new data + * @param offset the new offset + * @param useBytes set to true if the offset is in bytes + */ + updateDirectly(data, offset, useBytes = false) { + this._buffer.updateDirectly(data, offset, undefined, useBytes); + this._alignBuffer(); + } + /** + * Disposes the VertexBuffer and the underlying WebGLBuffer. + */ + dispose() { + if (this._ownsBuffer) { + this._buffer.dispose(); + } + this._isDisposed = true; + } + /** + * Enumerates each value of this vertex buffer as numbers. + * @param count the number of values to enumerate + * @param callback the callback function called for each value + */ + forEach(count, callback) { + EnumerateFloatValues(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, (values, index) => { + for (let i = 0; i < this._size; i++) { + callback(values[i], index + i); + } + }); + } + /** @internal */ + _alignBuffer() { } + /** + * Deduces the stride given a kind. + * @param kind The kind string to deduce + * @returns The deduced stride + */ + static DeduceStride(kind) { + switch (kind) { + case VertexBuffer.UVKind: + case VertexBuffer.UV2Kind: + case VertexBuffer.UV3Kind: + case VertexBuffer.UV4Kind: + case VertexBuffer.UV5Kind: + case VertexBuffer.UV6Kind: + return 2; + case VertexBuffer.NormalKind: + case VertexBuffer.PositionKind: + return 3; + case VertexBuffer.ColorKind: + case VertexBuffer.ColorInstanceKind: + case VertexBuffer.MatricesIndicesKind: + case VertexBuffer.MatricesIndicesExtraKind: + case VertexBuffer.MatricesWeightsKind: + case VertexBuffer.MatricesWeightsExtraKind: + case VertexBuffer.TangentKind: + return 4; + default: + throw new Error("Invalid kind '" + kind + "'"); + } + } + /** + * Gets the vertex buffer type of the given data array. + * @param data the data array + * @returns the vertex buffer type + */ + static GetDataType(data) { + if (data instanceof Int8Array) { + return VertexBuffer.BYTE; + } + else if (data instanceof Uint8Array) { + return VertexBuffer.UNSIGNED_BYTE; + } + else if (data instanceof Int16Array) { + return VertexBuffer.SHORT; + } + else if (data instanceof Uint16Array) { + return VertexBuffer.UNSIGNED_SHORT; + } + else if (data instanceof Int32Array) { + return VertexBuffer.INT; + } + else if (data instanceof Uint32Array) { + return VertexBuffer.UNSIGNED_INT; + } + else { + return VertexBuffer.FLOAT; + } + } + /** + * Gets the byte length of the given type. + * @param type the type + * @returns the number of bytes + * @deprecated Use `getTypeByteLength` from `bufferUtils` instead + */ + static GetTypeByteLength(type) { + return GetTypeByteLength(type); + } + /** + * Enumerates each value of the given parameters as numbers. + * @param data the data to enumerate + * @param byteOffset the byte offset of the data + * @param byteStride the byte stride of the data + * @param componentCount the number of components per element + * @param componentType the type of the component + * @param count the number of values to enumerate + * @param normalized whether the data is normalized + * @param callback the callback function called for each value + * @deprecated Use `EnumerateFloatValues` from `bufferUtils` instead + */ + static ForEach(data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) { + EnumerateFloatValues(data, byteOffset, byteStride, componentCount, componentType, count, normalized, (values, index) => { + for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) { + callback(values[componentIndex], index + componentIndex); + } + }); + } + /** + * Gets the given data array as a float array. Float data is constructed if the data array cannot be returned directly. + * @param data the input data array + * @param size the number of components + * @param type the component type + * @param byteOffset the byte offset of the data + * @param byteStride the byte stride of the data + * @param normalized whether the data is normalized + * @param totalVertices number of vertices in the buffer to take into account + * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it + * @returns a float array containing vertex data + * @deprecated Use `GetFloatData` from `bufferUtils` instead + */ + static GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy) { + return GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy); + } +} +VertexBuffer._Counter = 0; +/** + * The byte type. + */ +VertexBuffer.BYTE = 5120; +/** + * The unsigned byte type. + */ +VertexBuffer.UNSIGNED_BYTE = 5121; +/** + * The short type. + */ +VertexBuffer.SHORT = 5122; +/** + * The unsigned short type. + */ +VertexBuffer.UNSIGNED_SHORT = 5123; +/** + * The integer type. + */ +VertexBuffer.INT = 5124; +/** + * The unsigned integer type. + */ +VertexBuffer.UNSIGNED_INT = 5125; +/** + * The float type. + */ +VertexBuffer.FLOAT = 5126; +// Enums +/** + * Positions + */ +VertexBuffer.PositionKind = `position`; +/** + * Normals + */ +VertexBuffer.NormalKind = `normal`; +/** + * Tangents + */ +VertexBuffer.TangentKind = `tangent`; +/** + * Texture coordinates + */ +VertexBuffer.UVKind = `uv`; +/** + * Texture coordinates 2 + */ +VertexBuffer.UV2Kind = `uv2`; +/** + * Texture coordinates 3 + */ +VertexBuffer.UV3Kind = `uv3`; +/** + * Texture coordinates 4 + */ +VertexBuffer.UV4Kind = `uv4`; +/** + * Texture coordinates 5 + */ +VertexBuffer.UV5Kind = `uv5`; +/** + * Texture coordinates 6 + */ +VertexBuffer.UV6Kind = `uv6`; +/** + * Colors + */ +VertexBuffer.ColorKind = `color`; +/** + * Instance Colors + */ +VertexBuffer.ColorInstanceKind = `instanceColor`; +/** + * Matrix indices (for bones) + */ +VertexBuffer.MatricesIndicesKind = `matricesIndices`; +/** + * Matrix weights (for bones) + */ +VertexBuffer.MatricesWeightsKind = `matricesWeights`; +/** + * Additional matrix indices (for bones) + */ +VertexBuffer.MatricesIndicesExtraKind = `matricesIndicesExtra`; +/** + * Additional matrix weights (for bones) + */ +VertexBuffer.MatricesWeightsExtraKind = `matricesWeightsExtra`; + +/** + * Information about the result of picking within a scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions + */ +class PickingInfo { + constructor() { + /** + * If the pick collided with an object + */ + this.hit = false; + /** + * Distance away where the pick collided + */ + this.distance = 0; + /** + * The location of pick collision + */ + this.pickedPoint = null; + /** + * The mesh corresponding the pick collision + */ + this.pickedMesh = null; + /** (See getTextureCoordinates) The barycentric U coordinate that is used when calculating the texture coordinates of the collision.*/ + this.bu = 0; + /** (See getTextureCoordinates) The barycentric V coordinate that is used when calculating the texture coordinates of the collision.*/ + this.bv = 0; + /** The index of the face on the mesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */ + this.faceId = -1; + /** The index of the face on the subMesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */ + this.subMeshFaceId = -1; + /** Id of the submesh that was picked */ + this.subMeshId = 0; + /** If a sprite was picked, this will be the sprite the pick collided with */ + this.pickedSprite = null; + /** If we are picking a mesh with thin instance, this will give you the picked thin instance */ + this.thinInstanceIndex = -1; + /** + * The ray that was used to perform the picking. + */ + this.ray = null; + /** + * If a mesh was used to do the picking (eg. 6dof controller) as a "near interaction", this will be populated. + */ + this.originMesh = null; + /** + * The aim-space transform of the input used for picking, if it is an XR input source. + */ + this.aimTransform = null; + /** + * The grip-space transform of the input used for picking, if it is an XR input source. + * Some XR sources, such as input coming from head mounted displays, do not have this. + */ + this.gripTransform = null; + } + /** + * Gets the normal corresponding to the face the pick collided with + * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false) + * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map (default: true) + * @returns The normal corresponding to the face the pick collided with + * @remarks Note that the returned normal will always point towards the picking ray. + */ + getNormal(useWorldCoordinates = false, useVerticesNormals = true) { + if (!this.pickedMesh || (useVerticesNormals && !this.pickedMesh.isVerticesDataPresent(VertexBuffer.NormalKind))) { + return null; + } + let indices = this.pickedMesh.getIndices(); + if (indices?.length === 0) { + indices = null; + } + let result; + const tmp0 = TmpVectors.Vector3[0]; + const tmp1 = TmpVectors.Vector3[1]; + const tmp2 = TmpVectors.Vector3[2]; + if (useVerticesNormals) { + const normals = this.pickedMesh.getVerticesData(VertexBuffer.NormalKind); + let normal0 = indices + ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3] * 3, tmp0) + : tmp0.copyFromFloats(normals[this.faceId * 3 * 3], normals[this.faceId * 3 * 3 + 1], normals[this.faceId * 3 * 3 + 2]); + let normal1 = indices + ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 1] * 3, tmp1) + : tmp1.copyFromFloats(normals[(this.faceId * 3 + 1) * 3], normals[(this.faceId * 3 + 1) * 3 + 1], normals[(this.faceId * 3 + 1) * 3 + 2]); + let normal2 = indices + ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 2] * 3, tmp2) + : tmp2.copyFromFloats(normals[(this.faceId * 3 + 2) * 3], normals[(this.faceId * 3 + 2) * 3 + 1], normals[(this.faceId * 3 + 2) * 3 + 2]); + normal0 = normal0.scale(this.bu); + normal1 = normal1.scale(this.bv); + normal2 = normal2.scale(1.0 - this.bu - this.bv); + result = new Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z); + } + else { + const positions = this.pickedMesh.getVerticesData(VertexBuffer.PositionKind); + const vertex1 = indices + ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3] * 3, tmp0) + : tmp0.copyFromFloats(positions[this.faceId * 3 * 3], positions[this.faceId * 3 * 3 + 1], positions[this.faceId * 3 * 3 + 2]); + const vertex2 = indices + ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 1] * 3, tmp1) + : tmp1.copyFromFloats(positions[(this.faceId * 3 + 1) * 3], positions[(this.faceId * 3 + 1) * 3 + 1], positions[(this.faceId * 3 + 1) * 3 + 2]); + const vertex3 = indices + ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 2] * 3, tmp2) + : tmp2.copyFromFloats(positions[(this.faceId * 3 + 2) * 3], positions[(this.faceId * 3 + 2) * 3 + 1], positions[(this.faceId * 3 + 2) * 3 + 2]); + const p1p2 = vertex1.subtract(vertex2); + const p3p2 = vertex3.subtract(vertex2); + result = Vector3.Cross(p1p2, p3p2); + } + const transformNormalToWorld = (pickedMesh, n) => { + if (this.thinInstanceIndex !== -1) { + const tm = pickedMesh.thinInstanceGetWorldMatrices()[this.thinInstanceIndex]; + if (tm) { + Vector3.TransformNormalToRef(n, tm, n); + } + } + let wm = pickedMesh.getWorldMatrix(); + if (pickedMesh.nonUniformScaling) { + TmpVectors.Matrix[0].copyFrom(wm); + wm = TmpVectors.Matrix[0]; + wm.setTranslationFromFloats(0, 0, 0); + wm.invert(); + wm.transposeToRef(TmpVectors.Matrix[1]); + wm = TmpVectors.Matrix[1]; + } + Vector3.TransformNormalToRef(n, wm, n); + }; + if (useWorldCoordinates) { + transformNormalToWorld(this.pickedMesh, result); + } + if (this.ray) { + const normalForDirectionChecking = TmpVectors.Vector3[0].copyFrom(result); + if (!useWorldCoordinates) { + // the normal has not been transformed to world space as part as the normal processing, so we must do it now + transformNormalToWorld(this.pickedMesh, normalForDirectionChecking); + } + // Flip the normal if the picking ray is in the same direction. + if (Vector3.Dot(normalForDirectionChecking, this.ray.direction) > 0) { + result.negateInPlace(); + } + } + result.normalize(); + return result; + } + /** + * Gets the texture coordinates of where the pick occurred + * @param uvSet The UV set to use to calculate the texture coordinates (default: VertexBuffer.UVKind) + * @returns The vector containing the coordinates of the texture + */ + getTextureCoordinates(uvSet = VertexBuffer.UVKind) { + if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(uvSet)) { + return null; + } + const indices = this.pickedMesh.getIndices(); + if (!indices) { + return null; + } + const uvs = this.pickedMesh.getVerticesData(uvSet); + if (!uvs) { + return null; + } + let uv0 = Vector2.FromArray(uvs, indices[this.faceId * 3] * 2); + let uv1 = Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2); + let uv2 = Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2); + uv0 = uv0.scale(this.bu); + uv1 = uv1.scale(this.bv); + uv2 = uv2.scale(1.0 - this.bu - this.bv); + return new Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y); + } +} + +/** + * ActionEvent is the event being sent when an action is triggered. + */ +class ActionEvent { + /** + * Creates a new ActionEvent + * @param source The mesh or sprite that triggered the action + * @param pointerX The X mouse cursor position at the time of the event + * @param pointerY The Y mouse cursor position at the time of the event + * @param meshUnderPointer The mesh that is currently pointed at (can be null) + * @param sourceEvent the original (browser) event that triggered the ActionEvent + * @param additionalData additional data for the event + */ + constructor( + /** The mesh or sprite that triggered the action */ + source, + /** The X mouse cursor position at the time of the event */ + pointerX, + /** The Y mouse cursor position at the time of the event */ + pointerY, + /** The mesh that is currently pointed at (can be null) */ + meshUnderPointer, + /** the original (browser) event that triggered the ActionEvent */ + sourceEvent, + /** additional data for the event */ + additionalData) { + this.source = source; + this.pointerX = pointerX; + this.pointerY = pointerY; + this.meshUnderPointer = meshUnderPointer; + this.sourceEvent = sourceEvent; + this.additionalData = additionalData; + } + /** + * Helper function to auto-create an ActionEvent from a source mesh. + * @param source The source mesh that triggered the event + * @param evt The original (browser) event + * @param additionalData additional data for the event + * @returns the new ActionEvent + */ + static CreateNew(source, evt, additionalData) { + const scene = source.getScene(); + return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer || source, evt, additionalData); + } + /** + * Helper function to auto-create an ActionEvent from a source sprite + * @param source The source sprite that triggered the event + * @param scene Scene associated with the sprite + * @param evt The original (browser) event + * @param additionalData additional data for the event + * @returns the new ActionEvent + */ + static CreateNewFromSprite(source, scene, evt, additionalData) { + return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData); + } + /** + * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew + * @param scene the scene where the event occurred + * @param evt The original (browser) event + * @returns the new ActionEvent + */ + static CreateNewFromScene(scene, evt) { + return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt); + } + /** + * Helper function to auto-create an ActionEvent from a primitive + * @param prim defines the target primitive + * @param pointerPos defines the pointer position + * @param evt The original (browser) event + * @param additionalData additional data for the event + * @returns the new ActionEvent + */ + static CreateNewFromPrimitive(prim, pointerPos, evt, additionalData) { + return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData); + } +} + +/** + * PostProcessManager is used to manage one or more post processes or post process pipelines + * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses + */ +class PostProcessManager { + /** + * Creates a new instance PostProcess + * @param scene The scene that the post process is associated with. + */ + constructor(scene) { + this._vertexBuffers = {}; + this.onBeforeRenderObservable = new Observable(); + this._scene = scene; + } + _prepareBuffers() { + if (this._vertexBuffers[VertexBuffer.PositionKind]) { + return; + } + // VBO + const vertices = []; + vertices.push(1, 1); + vertices.push(-1, 1); + vertices.push(-1, -1); + vertices.push(1, -1); + this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(this._scene.getEngine(), vertices, VertexBuffer.PositionKind, false, false, 2); + this._buildIndexBuffer(); + } + _buildIndexBuffer() { + // Indices + const indices = []; + indices.push(0); + indices.push(1); + indices.push(2); + indices.push(0); + indices.push(2); + indices.push(3); + this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices); + } + /** + * Rebuilds the vertex buffers of the manager. + * @internal + */ + _rebuild() { + const vb = this._vertexBuffers[VertexBuffer.PositionKind]; + if (!vb) { + return; + } + vb._rebuild(); + this._buildIndexBuffer(); + } + // Methods + /** + * Prepares a frame to be run through a post process. + * @param sourceTexture The input texture to the post processes. (default: null) + * @param postProcesses An array of post processes to be run. (default: null) + * @returns True if the post processes were able to be run. + * @internal + */ + _prepareFrame(sourceTexture = null, postProcesses = null) { + const camera = this._scene.activeCamera; + if (!camera) { + return false; + } + postProcesses = postProcesses || camera._postProcesses.filter((pp) => { + return pp != null; + }); + if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) { + return false; + } + postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined); + return true; + } + /** + * Manually render a set of post processes to a texture. + * Please note, the frame buffer won't be unbound after the call in case you have more render to do. + * @param postProcesses An array of post processes to be run. + * @param targetTexture The render target wrapper to render to. + * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight + * @param faceIndex defines the face to render to if a cubemap is defined as the target + * @param lodLevel defines which lod of the texture to render to + * @param doNotBindFrambuffer If set to true, assumes that the framebuffer has been bound previously + */ + directRender(postProcesses, targetTexture = null, forceFullscreenViewport = false, faceIndex = 0, lodLevel = 0, doNotBindFrambuffer = false) { + const engine = this._scene.getEngine(); + for (let index = 0; index < postProcesses.length; index++) { + if (index < postProcesses.length - 1) { + postProcesses[index + 1].activate(this._scene.activeCamera || this._scene, targetTexture?.texture); + } + else { + if (targetTexture) { + engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, lodLevel); + } + else if (!doNotBindFrambuffer) { + engine.restoreDefaultFramebuffer(); + } + engine._debugInsertMarker?.(`post process ${postProcesses[index].name} output`); + } + const pp = postProcesses[index]; + const effect = pp.apply(); + if (effect) { + pp.onBeforeRenderObservable.notifyObservers(effect); + // VBOs + this._prepareBuffers(); + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); + // Draw order + engine.drawElementsType(0, 0, 6); + pp.onAfterRenderObservable.notifyObservers(effect); + } + } + // Restore depth buffer + engine.setDepthBuffer(true); + engine.setDepthWrite(true); + } + /** + * Finalize the result of the output of the postprocesses. + * @param doNotPresent If true the result will not be displayed to the screen. + * @param targetTexture The render target wrapper to render to. + * @param faceIndex The index of the face to bind the target texture to. + * @param postProcesses The array of post processes to render. + * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false) + * @internal + */ + _finalizeFrame(doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport = false) { + const camera = this._scene.activeCamera; + if (!camera) { + return; + } + this.onBeforeRenderObservable.notifyObservers(this); + postProcesses = postProcesses || camera._postProcesses.filter((pp) => { + return pp != null; + }); + if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) { + return; + } + const engine = this._scene.getEngine(); + for (let index = 0, len = postProcesses.length; index < len; index++) { + const pp = postProcesses[index]; + if (index < len - 1) { + pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture?.texture); + } + else { + if (targetTexture) { + engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport); + pp._outputTexture = targetTexture; + } + else { + engine.restoreDefaultFramebuffer(); + pp._outputTexture = null; + } + engine._debugInsertMarker?.(`post process ${postProcesses[index].name} output`); + } + if (doNotPresent) { + break; + } + const effect = pp.apply(); + if (effect) { + pp.onBeforeRenderObservable.notifyObservers(effect); + // VBOs + this._prepareBuffers(); + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); + // Draw order + engine.drawElementsType(0, 0, 6); + pp.onAfterRenderObservable.notifyObservers(effect); + } + } + // Restore states + engine.setDepthBuffer(true); + engine.setDepthWrite(true); + engine.setAlphaMode(0); + } + /** + * Disposes of the post process manager. + */ + dispose() { + const buffer = this._vertexBuffers[VertexBuffer.PositionKind]; + if (buffer) { + buffer.dispose(); + this._vertexBuffers[VertexBuffer.PositionKind] = null; + } + if (this._indexBuffer) { + this._scene.getEngine()._releaseBuffer(this._indexBuffer); + this._indexBuffer = null; + } + } +} + +/** + * This represents the object necessary to create a rendering group. + * This is exclusively used and created by the rendering manager. + * To modify the behavior, you use the available helpers in your scene or meshes. + * @internal + */ +class RenderingGroup { + /** + * Set the opaque sort comparison function. + * If null the sub meshes will be render in the order they were created + */ + set opaqueSortCompareFn(value) { + if (value) { + this._opaqueSortCompareFn = value; + } + else { + this._opaqueSortCompareFn = RenderingGroup.PainterSortCompare; + } + this._renderOpaque = this._renderOpaqueSorted; + } + /** + * Set the alpha test sort comparison function. + * If null the sub meshes will be render in the order they were created + */ + set alphaTestSortCompareFn(value) { + if (value) { + this._alphaTestSortCompareFn = value; + } + else { + this._alphaTestSortCompareFn = RenderingGroup.PainterSortCompare; + } + this._renderAlphaTest = this._renderAlphaTestSorted; + } + /** + * Set the transparent sort comparison function. + * If null the sub meshes will be render in the order they were created + */ + set transparentSortCompareFn(value) { + if (value) { + this._transparentSortCompareFn = value; + } + else { + this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare; + } + this._renderTransparent = this._renderTransparentSorted; + } + /** + * Creates a new rendering group. + * @param index The rendering group index + * @param scene + * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied + * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied + * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied + */ + constructor(index, scene, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { + this.index = index; + this._opaqueSubMeshes = new SmartArray(256); + this._transparentSubMeshes = new SmartArray(256); + this._alphaTestSubMeshes = new SmartArray(256); + this._depthOnlySubMeshes = new SmartArray(256); + this._particleSystems = new SmartArray(256); + this._spriteManagers = new SmartArray(256); + /** @internal */ + this._empty = true; + /** @internal */ + this._edgesRenderers = new SmartArrayNoDuplicate(16); + this._scene = scene; + this.opaqueSortCompareFn = opaqueSortCompareFn; + this.alphaTestSortCompareFn = alphaTestSortCompareFn; + this.transparentSortCompareFn = transparentSortCompareFn; + } + /** + * Render all the sub meshes contained in the group. + * @param customRenderFunction Used to override the default render behaviour of the group. + * @param renderSprites + * @param renderParticles + * @param activeMeshes + */ + render(customRenderFunction, renderSprites, renderParticles, activeMeshes) { + if (customRenderFunction) { + customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes); + return; + } + const engine = this._scene.getEngine(); + // Depth only + if (this._depthOnlySubMeshes.length !== 0) { + engine.setColorWrite(false); + this._renderAlphaTest(this._depthOnlySubMeshes); + engine.setColorWrite(true); + } + // Opaque + if (this._opaqueSubMeshes.length !== 0) { + this._renderOpaque(this._opaqueSubMeshes); + } + // Alpha test + if (this._alphaTestSubMeshes.length !== 0) { + this._renderAlphaTest(this._alphaTestSubMeshes); + } + const stencilState = engine.getStencilBuffer(); + engine.setStencilBuffer(false); + // Sprites + if (renderSprites) { + this._renderSprites(); + } + // Particles + if (renderParticles) { + this._renderParticles(activeMeshes); + } + if (this.onBeforeTransparentRendering) { + this.onBeforeTransparentRendering(); + } + // Transparent + if (this._transparentSubMeshes.length !== 0 || this._scene.useOrderIndependentTransparency) { + engine.setStencilBuffer(stencilState); + if (this._scene.useOrderIndependentTransparency) { + const excludedMeshes = this._scene.depthPeelingRenderer.render(this._transparentSubMeshes); + if (excludedMeshes.length) { + // Render leftover meshes that could not be processed by depth peeling + this._renderTransparent(excludedMeshes); + } + } + else { + this._renderTransparent(this._transparentSubMeshes); + } + engine.setAlphaMode(0); + } + // Set back stencil to false in case it changes before the edge renderer. + engine.setStencilBuffer(false); + // Edges + if (this._edgesRenderers.length) { + for (let edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) { + this._edgesRenderers.data[edgesRendererIndex].render(); + } + engine.setAlphaMode(0); + } + // Restore Stencil state. + engine.setStencilBuffer(stencilState); + } + /** + * Renders the opaque submeshes in the order from the opaqueSortCompareFn. + * @param subMeshes The submeshes to render + */ + _renderOpaqueSorted(subMeshes) { + RenderingGroup._RenderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false); + } + /** + * Renders the opaque submeshes in the order from the alphatestSortCompareFn. + * @param subMeshes The submeshes to render + */ + _renderAlphaTestSorted(subMeshes) { + RenderingGroup._RenderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false); + } + /** + * Renders the opaque submeshes in the order from the transparentSortCompareFn. + * @param subMeshes The submeshes to render + */ + _renderTransparentSorted(subMeshes) { + RenderingGroup._RenderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true); + } + /** + * Renders the submeshes in a specified order. + * @param subMeshes The submeshes to sort before render + * @param sortCompareFn The comparison function use to sort + * @param camera The camera position use to preprocess the submeshes to help sorting + * @param transparent Specifies to activate blending if true + */ + static _RenderSorted(subMeshes, sortCompareFn, camera, transparent) { + let subIndex = 0; + let subMesh; + const cameraPosition = camera ? camera.globalPosition : RenderingGroup._ZeroVector; + if (transparent) { + for (; subIndex < subMeshes.length; subIndex++) { + subMesh = subMeshes.data[subIndex]; + subMesh._alphaIndex = subMesh.getMesh().alphaIndex; + subMesh._distanceToCamera = Vector3.Distance(subMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition); + } + } + const sortedArray = subMeshes.length === subMeshes.data.length ? subMeshes.data : subMeshes.data.slice(0, subMeshes.length); + if (sortCompareFn) { + sortedArray.sort(sortCompareFn); + } + const scene = sortedArray[0].getMesh().getScene(); + for (subIndex = 0; subIndex < sortedArray.length; subIndex++) { + subMesh = sortedArray[subIndex]; + if (scene._activeMeshesFrozenButKeepClipping && !subMesh.isInFrustum(scene._frustumPlanes)) { + continue; + } + if (transparent) { + const material = subMesh.getMaterial(); + if (material && material.needDepthPrePass) { + const engine = material.getScene().getEngine(); + engine.setColorWrite(false); + engine.setAlphaMode(0); + subMesh.render(false); + engine.setColorWrite(true); + } + } + subMesh.render(transparent); + } + } + /** + * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) + * are rendered back to front if in the same alpha index. + * + * @param a The first submesh + * @param b The second submesh + * @returns The result of the comparison + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + static defaultTransparentSortCompare(a, b) { + // Alpha index first + if (a._alphaIndex > b._alphaIndex) { + return 1; + } + if (a._alphaIndex < b._alphaIndex) { + return -1; + } + // Then distance to camera + return RenderingGroup.backToFrontSortCompare(a, b); + } + /** + * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) + * are rendered back to front. + * + * @param a The first submesh + * @param b The second submesh + * @returns The result of the comparison + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + static backToFrontSortCompare(a, b) { + // Then distance to camera + if (a._distanceToCamera < b._distanceToCamera) { + return 1; + } + if (a._distanceToCamera > b._distanceToCamera) { + return -1; + } + return 0; + } + /** + * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) + * are rendered front to back (prevent overdraw). + * + * @param a The first submesh + * @param b The second submesh + * @returns The result of the comparison + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + static frontToBackSortCompare(a, b) { + // Then distance to camera + if (a._distanceToCamera < b._distanceToCamera) { + return -1; + } + if (a._distanceToCamera > b._distanceToCamera) { + return 1; + } + return 0; + } + /** + * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) + * are grouped by material then geometry. + * + * @param a The first submesh + * @param b The second submesh + * @returns The result of the comparison + */ + static PainterSortCompare(a, b) { + const meshA = a.getMesh(); + const meshB = b.getMesh(); + if (meshA.material && meshB.material) { + return meshA.material.uniqueId - meshB.material.uniqueId; + } + return meshA.uniqueId - meshB.uniqueId; + } + /** + * Resets the different lists of submeshes to prepare a new frame. + */ + prepare() { + this._opaqueSubMeshes.reset(); + this._transparentSubMeshes.reset(); + this._alphaTestSubMeshes.reset(); + this._depthOnlySubMeshes.reset(); + this._particleSystems.reset(); + this.prepareSprites(); + this._edgesRenderers.reset(); + this._empty = true; + } + /** + * Resets the different lists of sprites to prepare a new frame. + */ + prepareSprites() { + this._spriteManagers.reset(); + } + dispose() { + this._opaqueSubMeshes.dispose(); + this._transparentSubMeshes.dispose(); + this._alphaTestSubMeshes.dispose(); + this._depthOnlySubMeshes.dispose(); + this._particleSystems.dispose(); + this._spriteManagers.dispose(); + this._edgesRenderers.dispose(); + } + /** + * Inserts the submesh in its correct queue depending on its material. + * @param subMesh The submesh to dispatch + * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. + * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. + */ + dispatch(subMesh, mesh, material) { + // Get mesh and materials if not provided + if (mesh === undefined) { + mesh = subMesh.getMesh(); + } + if (material === undefined) { + material = subMesh.getMaterial(); + } + if (material === null || material === undefined) { + return; + } + if (material.needAlphaBlendingForMesh(mesh)) { + // Transparent + this._transparentSubMeshes.push(subMesh); + } + else if (material.needAlphaTestingForMesh(mesh)) { + // Alpha test + if (material.needDepthPrePass) { + this._depthOnlySubMeshes.push(subMesh); + } + this._alphaTestSubMeshes.push(subMesh); + } + else { + if (material.needDepthPrePass) { + this._depthOnlySubMeshes.push(subMesh); + } + this._opaqueSubMeshes.push(subMesh); // Opaque + } + mesh._renderingGroup = this; + if (mesh._edgesRenderer && mesh.isEnabled() && mesh.isVisible && mesh._edgesRenderer.isEnabled) { + this._edgesRenderers.pushNoDuplicate(mesh._edgesRenderer); + } + this._empty = false; + } + dispatchSprites(spriteManager) { + this._spriteManagers.push(spriteManager); + this._empty = false; + } + dispatchParticles(particleSystem) { + this._particleSystems.push(particleSystem); + this._empty = false; + } + _renderParticles(activeMeshes) { + if (this._particleSystems.length === 0) { + return; + } + // Particles + const activeCamera = this._scene.activeCamera; + this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene); + for (let particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) { + const particleSystem = this._particleSystems.data[particleIndex]; + if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) { + continue; + } + const emitter = particleSystem.emitter; + if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) { + this._scene._activeParticles.addCount(particleSystem.render(), false); + } + } + this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene); + } + _renderSprites() { + if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) { + return; + } + // Sprites + const activeCamera = this._scene.activeCamera; + this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene); + for (let id = 0; id < this._spriteManagers.length; id++) { + const spriteManager = this._spriteManagers.data[id]; + if ((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0) { + spriteManager.render(); + } + } + this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene); + } +} +RenderingGroup._ZeroVector = Vector3.Zero(); + +/** + * This class is used by the onRenderingGroupObservable + */ +class RenderingGroupInfo { +} +/** + * This is the manager responsible of all the rendering for meshes sprites and particles. + * It is enable to manage the different groups as well as the different necessary sort functions. + * This should not be used directly aside of the few static configurations + */ +class RenderingManager { + /** + * Gets or sets a boolean indicating that the manager will not reset between frames. + * This means that if a mesh becomes invisible or transparent it will not be visible until this boolean is set to false again. + * By default, the rendering manager will dispatch all active meshes per frame (moving them to the transparent, opaque or alpha testing lists). + * By turning this property on, you will accelerate the rendering by keeping all these lists unchanged between frames. + */ + get maintainStateBetweenFrames() { + return this._maintainStateBetweenFrames; + } + set maintainStateBetweenFrames(value) { + if (value === this._maintainStateBetweenFrames) { + return; + } + this._maintainStateBetweenFrames = value; + if (!this._maintainStateBetweenFrames) { + this.restoreDispachedFlags(); + } + } + /** + * Restore wasDispatched flags on the lists of elements to render. + */ + restoreDispachedFlags() { + for (const mesh of this._scene.meshes) { + if (mesh.subMeshes) { + for (const subMesh of mesh.subMeshes) { + subMesh._wasDispatched = false; + } + } + } + if (this._scene.spriteManagers) { + for (const spriteManager of this._scene.spriteManagers) { + spriteManager._wasDispatched = false; + } + } + for (const particleSystem of this._scene.particleSystems) { + particleSystem._wasDispatched = false; + } + } + /** + * Instantiates a new rendering group for a particular scene + * @param scene Defines the scene the groups belongs to + */ + constructor(scene) { + /** + * @internal + */ + this._useSceneAutoClearSetup = false; + this._renderingGroups = new Array(); + this._autoClearDepthStencil = {}; + this._customOpaqueSortCompareFn = {}; + this._customAlphaTestSortCompareFn = {}; + this._customTransparentSortCompareFn = {}; + this._renderingGroupInfo = new RenderingGroupInfo(); + this._maintainStateBetweenFrames = false; + this._scene = scene; + for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) { + this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true }; + } + } + /** + * @returns the rendering group with the specified id. + * @param id the id of the rendering group (0 by default) + */ + getRenderingGroup(id) { + const renderingGroupId = id || 0; + this._prepareRenderingGroup(renderingGroupId); + return this._renderingGroups[renderingGroupId]; + } + _clearDepthStencilBuffer(depth = true, stencil = true) { + if (this._depthStencilBufferAlreadyCleaned) { + return; + } + this._scene.getEngine().clear(null, false, depth, stencil); + this._depthStencilBufferAlreadyCleaned = true; + } + /** + * Renders the entire managed groups. This is used by the scene or the different render targets. + * @internal + */ + render(customRenderFunction, activeMeshes, renderParticles, renderSprites) { + // Update the observable context (not null as it only goes away on dispose) + const info = this._renderingGroupInfo; + info.scene = this._scene; + info.camera = this._scene.activeCamera; + info.renderingManager = this; + // Dispatch sprites + if (this._scene.spriteManagers && renderSprites) { + for (let index = 0; index < this._scene.spriteManagers.length; index++) { + const manager = this._scene.spriteManagers[index]; + this.dispatchSprites(manager); + } + } + // Render + for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { + this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS; + const renderingGroup = this._renderingGroups[index]; + if (!renderingGroup || renderingGroup._empty) { + continue; + } + const renderingGroupMask = 1 << index; + info.renderingGroupId = index; + // Before Observable + this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask); + // Clear depth/stencil if needed + if (RenderingManager.AUTOCLEAR) { + const autoClear = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(index) : this._autoClearDepthStencil[index]; + if (autoClear && autoClear.autoClear) { + this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil); + } + } + // Render + for (const step of this._scene._beforeRenderingGroupDrawStage) { + step.action(index); + } + renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes); + for (const step of this._scene._afterRenderingGroupDrawStage) { + step.action(index); + } + // After Observable + this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask); + } + } + /** + * Resets the different information of the group to prepare a new frame + * @internal + */ + reset() { + if (this.maintainStateBetweenFrames) { + return; + } + for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { + const renderingGroup = this._renderingGroups[index]; + if (renderingGroup) { + renderingGroup.prepare(); + } + } + } + /** + * Resets the sprites information of the group to prepare a new frame + * @internal + */ + resetSprites() { + if (this.maintainStateBetweenFrames) { + return; + } + for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { + const renderingGroup = this._renderingGroups[index]; + if (renderingGroup) { + renderingGroup.prepareSprites(); + } + } + } + /** + * Dispose and release the group and its associated resources. + * @internal + */ + dispose() { + this.freeRenderingGroups(); + this._renderingGroups.length = 0; + this._renderingGroupInfo = null; + } + /** + * Clear the info related to rendering groups preventing retention points during dispose. + */ + freeRenderingGroups() { + for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { + const renderingGroup = this._renderingGroups[index]; + if (renderingGroup) { + renderingGroup.dispose(); + } + } + } + _prepareRenderingGroup(renderingGroupId) { + if (this._renderingGroups[renderingGroupId] === undefined) { + this._renderingGroups[renderingGroupId] = new RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]); + } + } + /** + * Add a sprite manager to the rendering manager in order to render it this frame. + * @param spriteManager Define the sprite manager to render + */ + dispatchSprites(spriteManager) { + if (this.maintainStateBetweenFrames && spriteManager._wasDispatched) { + return; + } + spriteManager._wasDispatched = true; + this.getRenderingGroup(spriteManager.renderingGroupId).dispatchSprites(spriteManager); + } + /** + * Add a particle system to the rendering manager in order to render it this frame. + * @param particleSystem Define the particle system to render + */ + dispatchParticles(particleSystem) { + if (this.maintainStateBetweenFrames && particleSystem._wasDispatched) { + return; + } + particleSystem._wasDispatched = true; + this.getRenderingGroup(particleSystem.renderingGroupId).dispatchParticles(particleSystem); + } + /** + * Add a submesh to the manager in order to render it this frame + * @param subMesh The submesh to dispatch + * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. + * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. + */ + dispatch(subMesh, mesh, material) { + if (mesh === undefined) { + mesh = subMesh.getMesh(); + } + if (this.maintainStateBetweenFrames && subMesh._wasDispatched) { + return; + } + subMesh._wasDispatched = true; + this.getRenderingGroup(mesh.renderingGroupId).dispatch(subMesh, mesh, material); + } + /** + * Overrides the default sort function applied in the rendering group to prepare the meshes. + * This allowed control for front to back rendering or reversely depending of the special needs. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param opaqueSortCompareFn The opaque queue comparison function use to sort. + * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. + * @param transparentSortCompareFn The transparent queue comparison function use to sort. + */ + setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { + this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn; + this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn; + this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn; + if (this._renderingGroups[renderingGroupId]) { + const group = this._renderingGroups[renderingGroupId]; + group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId]; + group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId]; + group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId]; + } + } + /** + * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. + * @param depth Automatically clears depth between groups if true and autoClear is true. + * @param stencil Automatically clears stencil between groups if true and autoClear is true. + */ + setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) { + this._autoClearDepthStencil[renderingGroupId] = { + autoClear: autoClearDepthStencil, + depth: depth, + stencil: stencil, + }; + } + /** + * Gets the current auto clear configuration for one rendering group of the rendering + * manager. + * @param index the rendering group index to get the information for + * @returns The auto clear setup for the requested rendering group + */ + getAutoClearDepthStencilSetup(index) { + return this._autoClearDepthStencil[index]; + } +} +/** + * The max id used for rendering groups (not included) + */ +RenderingManager.MAX_RENDERINGGROUPS = 4; +/** + * The min id used for rendering groups (included) + */ +RenderingManager.MIN_RENDERINGGROUPS = 0; +/** + * Used to globally prevent autoclearing scenes. + */ +RenderingManager.AUTOCLEAR = true; + +/** + * Groups all the scene component constants in one place to ease maintenance. + * @internal + */ +class SceneComponentConstants { +} +SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer"; +SceneComponentConstants.NAME_LAYER = "Layer"; +SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem"; +SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer"; +SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem"; +SceneComponentConstants.NAME_GAMEPAD = "Gamepad"; +SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue"; +SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer"; +SceneComponentConstants.NAME_PREPASSRENDERER = "PrePassRenderer"; +SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer"; +SceneComponentConstants.NAME_DEPTHPEELINGRENDERER = "DepthPeelingRenderer"; +SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager"; +SceneComponentConstants.NAME_SPRITE = "Sprite"; +SceneComponentConstants.NAME_SUBSURFACE = "SubSurface"; +SceneComponentConstants.NAME_OUTLINERENDERER = "Outline"; +SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture"; +SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator"; +SceneComponentConstants.NAME_OCTREE = "Octree"; +SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine"; +SceneComponentConstants.NAME_AUDIO = "Audio"; +SceneComponentConstants.NAME_FLUIDRENDERER = "FluidRenderer"; +SceneComponentConstants.NAME_IBLCDFGENERATOR = "iblCDFGenerator"; +SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0; +SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0; +SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0; +SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER = 0; +SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1; +SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS = 0; +SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 1; +SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 2; +SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS = 0; +SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER = 1; +SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS = 0; +SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 1; +SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS = 0; +SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 1; +SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0; +SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1; +SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0; +SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0; +SceneComponentConstants.STEP_BEFORECLEAR_PREPASS = 1; +SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS = 0; +SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_PREPASS = 0; +SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER = 1; +SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS = 0; +SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 1; +SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 2; +SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3; +SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4; +SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER = 5; +SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER = 0; +SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER = 0; +SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0; +SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 0; +SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1; +SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 2; +SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3; +SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0; +SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER = 1; +SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0; +SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0; +SceneComponentConstants.STEP_POINTERUP_SPRITE = 0; +/** + * Representation of a stage in the scene (Basically a list of ordered steps) + * @internal + */ +class Stage extends Array { + /** + * Hide ctor from the rest of the world. + * @param items The items to add. + */ + constructor(items) { + super(...items); + } + /** + * Creates a new Stage. + * @returns A new instance of a Stage + */ + static Create() { + return Object.create(Stage.prototype); + } + /** + * Registers a step in an ordered way in the targeted stage. + * @param index Defines the position to register the step in + * @param component Defines the component attached to the step + * @param action Defines the action to launch during the step + */ + registerStep(index, component, action) { + let i = 0; + let maxIndex = Number.MAX_VALUE; + for (; i < this.length; i++) { + const step = this[i]; + maxIndex = step.index; + if (index < maxIndex) { + break; + } + } + this.splice(i, 0, { index, component, action: action.bind(component) }); + } + /** + * Clears all the steps from the stage. + */ + clear() { + this.length = 0; + } +} + +/** + * Gather the list of pointer event types as constants. + */ +class PointerEventTypes { +} +/** + * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer. + */ +PointerEventTypes.POINTERDOWN = 0x01; +/** + * The pointerup event is fired when a pointer is no longer active. + */ +PointerEventTypes.POINTERUP = 0x02; +/** + * The pointermove event is fired when a pointer changes coordinates. + */ +PointerEventTypes.POINTERMOVE = 0x04; +/** + * The pointerwheel event is fired when a mouse wheel has been rotated. + */ +PointerEventTypes.POINTERWHEEL = 0x08; +/** + * The pointerpick event is fired when a mesh or sprite has been picked by the pointer. + */ +PointerEventTypes.POINTERPICK = 0x10; +/** + * The pointertap event is fired when a the object has been touched and released without drag. + */ +PointerEventTypes.POINTERTAP = 0x20; +/** + * The pointerdoubletap event is fired when a the object has been touched and released twice without drag. + */ +PointerEventTypes.POINTERDOUBLETAP = 0x40; +/** + * Base class of pointer info types. + */ +class PointerInfoBase { + /** + * Instantiates the base class of pointers info. + * @param type Defines the type of event (PointerEventTypes) + * @param event Defines the related dom event + */ + constructor( + /** + * Defines the type of event (PointerEventTypes) + */ + type, + /** + * Defines the related dom event + */ + event) { + this.type = type; + this.event = event; + } +} +/** + * This class is used to store pointer related info for the onPrePointerObservable event. + * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable + */ +class PointerInfoPre extends PointerInfoBase { + /** + * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event. + * @param type Defines the type of event (PointerEventTypes) + * @param event Defines the related dom event + * @param localX Defines the local x coordinates of the pointer when the event occured + * @param localY Defines the local y coordinates of the pointer when the event occured + */ + constructor(type, event, localX, localY) { + super(type, event); + /** + * Ray from a pointer if available (eg. 6dof controller) + */ + this.ray = null; + /** + * The original picking info that was used to trigger the pointer event + */ + this.originalPickingInfo = null; + this.skipOnPointerObservable = false; + this.localPosition = new Vector2(localX, localY); + } +} +/** + * This type contains all the data related to a pointer event in Babylon.js. + * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class. + */ +class PointerInfo extends PointerInfoBase { + /** + * Defines the picking info associated with this PointerInfo object (if applicable) + */ + get pickInfo() { + if (!this._pickInfo) { + this._generatePickInfo(); + } + return this._pickInfo; + } + /** + * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event. + * @param type Defines the type of event (PointerEventTypes) + * @param event Defines the related dom event + * @param pickInfo Defines the picking info associated to the info (if any) + * @param inputManager Defines the InputManager to use if there is no pickInfo + */ + constructor(type, event, pickInfo, inputManager = null) { + super(type, event); + this._pickInfo = pickInfo; + this._inputManager = inputManager; + } + /** + * Generates the picking info if needed + */ + /** @internal */ + _generatePickInfo() { + if (this._inputManager) { + this._pickInfo = this._inputManager._pickMove(this.event); + this._inputManager._setRayOnPointerInfo(this._pickInfo, this.event); + this._inputManager = null; + } + } +} + +/** + * Abstract class used to decouple action Manager from scene and meshes. + * Do not instantiate. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class AbstractActionManager { + constructor() { + /** Gets the cursor to use when hovering items */ + this.hoverCursor = ""; + /** Gets the list of actions */ + this.actions = []; + /** + * Gets or sets a boolean indicating that the manager is recursive meaning that it can trigger action from children + */ + this.isRecursive = false; + /** + * Gets or sets a boolean indicating if this ActionManager should be disposed once the last Mesh using it is disposed + */ + this.disposeWhenUnowned = true; + } + /** + * Does exist one action manager with at least one trigger + **/ + static get HasTriggers() { + for (const t in AbstractActionManager.Triggers) { + if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) { + return true; + } + } + return false; + } + /** + * Does exist one action manager with at least one pick trigger + **/ + static get HasPickTriggers() { + for (const t in AbstractActionManager.Triggers) { + if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) { + const tAsInt = parseInt(t); + if (tAsInt >= 1 && tAsInt <= 7) { + return true; + } + } + } + return false; + } + /** + * Does exist one action manager that handles actions of a given trigger + * @param trigger defines the trigger to be tested + * @returns a boolean indicating whether the trigger is handled by at least one action manager + **/ + static HasSpecificTrigger(trigger) { + for (const t in AbstractActionManager.Triggers) { + if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) { + const tAsInt = parseInt(t); + if (tAsInt === trigger) { + return true; + } + } + } + return false; + } +} +/** Gets the list of active triggers */ +AbstractActionManager.Triggers = {}; + +/** + * Gather the list of keyboard event types as constants. + */ +class KeyboardEventTypes { +} +/** + * The keydown event is fired when a key becomes active (pressed). + */ +KeyboardEventTypes.KEYDOWN = 0x01; +/** + * The keyup event is fired when a key has been released. + */ +KeyboardEventTypes.KEYUP = 0x02; +/** + * This class is used to store keyboard related info for the onKeyboardObservable event. + */ +class KeyboardInfo { + /** + * Instantiates a new keyboard info. + * This class is used to store keyboard related info for the onKeyboardObservable event. + * @param type Defines the type of event (KeyboardEventTypes) + * @param event Defines the related dom event + */ + constructor( + /** + * Defines the type of event (KeyboardEventTypes) + */ + type, + /** + * Defines the related dom event + */ + event) { + this.type = type; + this.event = event; + } +} +/** + * This class is used to store keyboard related info for the onPreKeyboardObservable event. + * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable + */ +class KeyboardInfoPre extends KeyboardInfo { + /** + * Defines whether the engine should skip the next onKeyboardObservable associated to this pre. + * @deprecated use skipOnKeyboardObservable property instead + */ + get skipOnPointerObservable() { + return this.skipOnKeyboardObservable; + } + set skipOnPointerObservable(value) { + this.skipOnKeyboardObservable = value; + } + /** + * Instantiates a new keyboard pre info. + * This class is used to store keyboard related info for the onPreKeyboardObservable event. + * @param type Defines the type of event (KeyboardEventTypes) + * @param event Defines the related dom event + */ + constructor( + /** + * Defines the type of event (KeyboardEventTypes) + */ + type, + /** + * Defines the related dom event + */ + event) { + super(type, event); + this.type = type; + this.event = event; + this.skipOnKeyboardObservable = false; + } +} + +/** + * Enum for Device Types + */ +var DeviceType; +(function (DeviceType) { + /** Generic */ + DeviceType[DeviceType["Generic"] = 0] = "Generic"; + /** Keyboard */ + DeviceType[DeviceType["Keyboard"] = 1] = "Keyboard"; + /** Mouse */ + DeviceType[DeviceType["Mouse"] = 2] = "Mouse"; + /** Touch Pointers */ + DeviceType[DeviceType["Touch"] = 3] = "Touch"; + /** PS4 Dual Shock */ + DeviceType[DeviceType["DualShock"] = 4] = "DualShock"; + /** Xbox */ + DeviceType[DeviceType["Xbox"] = 5] = "Xbox"; + /** Switch Controller */ + DeviceType[DeviceType["Switch"] = 6] = "Switch"; + /** PS5 DualSense */ + DeviceType[DeviceType["DualSense"] = 7] = "DualSense"; +})(DeviceType || (DeviceType = {})); +// Device Enums +/** + * Enum for All Pointers (Touch/Mouse) + */ +var PointerInput; +(function (PointerInput) { + /** Horizontal Axis (Not used in events/observables; only in polling) */ + PointerInput[PointerInput["Horizontal"] = 0] = "Horizontal"; + /** Vertical Axis (Not used in events/observables; only in polling) */ + PointerInput[PointerInput["Vertical"] = 1] = "Vertical"; + /** Left Click or Touch */ + PointerInput[PointerInput["LeftClick"] = 2] = "LeftClick"; + /** Middle Click */ + PointerInput[PointerInput["MiddleClick"] = 3] = "MiddleClick"; + /** Right Click */ + PointerInput[PointerInput["RightClick"] = 4] = "RightClick"; + /** Browser Back */ + PointerInput[PointerInput["BrowserBack"] = 5] = "BrowserBack"; + /** Browser Forward */ + PointerInput[PointerInput["BrowserForward"] = 6] = "BrowserForward"; + /** Mouse Wheel X */ + PointerInput[PointerInput["MouseWheelX"] = 7] = "MouseWheelX"; + /** Mouse Wheel Y */ + PointerInput[PointerInput["MouseWheelY"] = 8] = "MouseWheelY"; + /** Mouse Wheel Z */ + PointerInput[PointerInput["MouseWheelZ"] = 9] = "MouseWheelZ"; + /** Used in events/observables to identify if x/y changes occurred */ + PointerInput[PointerInput["Move"] = 12] = "Move"; +})(PointerInput || (PointerInput = {})); +/** @internal */ +var NativePointerInput; +(function (NativePointerInput) { + /** Horizontal Axis */ + NativePointerInput[NativePointerInput["Horizontal"] = 0] = "Horizontal"; + /** Vertical Axis */ + NativePointerInput[NativePointerInput["Vertical"] = 1] = "Vertical"; + /** Left Click or Touch */ + NativePointerInput[NativePointerInput["LeftClick"] = 2] = "LeftClick"; + /** Middle Click */ + NativePointerInput[NativePointerInput["MiddleClick"] = 3] = "MiddleClick"; + /** Right Click */ + NativePointerInput[NativePointerInput["RightClick"] = 4] = "RightClick"; + /** Browser Back */ + NativePointerInput[NativePointerInput["BrowserBack"] = 5] = "BrowserBack"; + /** Browser Forward */ + NativePointerInput[NativePointerInput["BrowserForward"] = 6] = "BrowserForward"; + /** Mouse Wheel X */ + NativePointerInput[NativePointerInput["MouseWheelX"] = 7] = "MouseWheelX"; + /** Mouse Wheel Y */ + NativePointerInput[NativePointerInput["MouseWheelY"] = 8] = "MouseWheelY"; + /** Mouse Wheel Z */ + NativePointerInput[NativePointerInput["MouseWheelZ"] = 9] = "MouseWheelZ"; + /** Delta X */ + NativePointerInput[NativePointerInput["DeltaHorizontal"] = 10] = "DeltaHorizontal"; + /** Delta Y */ + NativePointerInput[NativePointerInput["DeltaVertical"] = 11] = "DeltaVertical"; +})(NativePointerInput || (NativePointerInput = {})); +/** + * Enum for Dual Shock Gamepad + */ +var DualShockInput; +(function (DualShockInput) { + /** Cross */ + DualShockInput[DualShockInput["Cross"] = 0] = "Cross"; + /** Circle */ + DualShockInput[DualShockInput["Circle"] = 1] = "Circle"; + /** Square */ + DualShockInput[DualShockInput["Square"] = 2] = "Square"; + /** Triangle */ + DualShockInput[DualShockInput["Triangle"] = 3] = "Triangle"; + /** L1 */ + DualShockInput[DualShockInput["L1"] = 4] = "L1"; + /** R1 */ + DualShockInput[DualShockInput["R1"] = 5] = "R1"; + /** L2 */ + DualShockInput[DualShockInput["L2"] = 6] = "L2"; + /** R2 */ + DualShockInput[DualShockInput["R2"] = 7] = "R2"; + /** Share */ + DualShockInput[DualShockInput["Share"] = 8] = "Share"; + /** Options */ + DualShockInput[DualShockInput["Options"] = 9] = "Options"; + /** L3 */ + DualShockInput[DualShockInput["L3"] = 10] = "L3"; + /** R3 */ + DualShockInput[DualShockInput["R3"] = 11] = "R3"; + /** DPadUp */ + DualShockInput[DualShockInput["DPadUp"] = 12] = "DPadUp"; + /** DPadDown */ + DualShockInput[DualShockInput["DPadDown"] = 13] = "DPadDown"; + /** DPadLeft */ + DualShockInput[DualShockInput["DPadLeft"] = 14] = "DPadLeft"; + /** DRight */ + DualShockInput[DualShockInput["DPadRight"] = 15] = "DPadRight"; + /** Home */ + DualShockInput[DualShockInput["Home"] = 16] = "Home"; + /** TouchPad */ + DualShockInput[DualShockInput["TouchPad"] = 17] = "TouchPad"; + /** LStickXAxis */ + DualShockInput[DualShockInput["LStickXAxis"] = 18] = "LStickXAxis"; + /** LStickYAxis */ + DualShockInput[DualShockInput["LStickYAxis"] = 19] = "LStickYAxis"; + /** RStickXAxis */ + DualShockInput[DualShockInput["RStickXAxis"] = 20] = "RStickXAxis"; + /** RStickYAxis */ + DualShockInput[DualShockInput["RStickYAxis"] = 21] = "RStickYAxis"; +})(DualShockInput || (DualShockInput = {})); +/** + * Enum for Dual Sense Gamepad + */ +var DualSenseInput; +(function (DualSenseInput) { + /** Cross */ + DualSenseInput[DualSenseInput["Cross"] = 0] = "Cross"; + /** Circle */ + DualSenseInput[DualSenseInput["Circle"] = 1] = "Circle"; + /** Square */ + DualSenseInput[DualSenseInput["Square"] = 2] = "Square"; + /** Triangle */ + DualSenseInput[DualSenseInput["Triangle"] = 3] = "Triangle"; + /** L1 */ + DualSenseInput[DualSenseInput["L1"] = 4] = "L1"; + /** R1 */ + DualSenseInput[DualSenseInput["R1"] = 5] = "R1"; + /** L2 */ + DualSenseInput[DualSenseInput["L2"] = 6] = "L2"; + /** R2 */ + DualSenseInput[DualSenseInput["R2"] = 7] = "R2"; + /** Create */ + DualSenseInput[DualSenseInput["Create"] = 8] = "Create"; + /** Options */ + DualSenseInput[DualSenseInput["Options"] = 9] = "Options"; + /** L3 */ + DualSenseInput[DualSenseInput["L3"] = 10] = "L3"; + /** R3 */ + DualSenseInput[DualSenseInput["R3"] = 11] = "R3"; + /** DPadUp */ + DualSenseInput[DualSenseInput["DPadUp"] = 12] = "DPadUp"; + /** DPadDown */ + DualSenseInput[DualSenseInput["DPadDown"] = 13] = "DPadDown"; + /** DPadLeft */ + DualSenseInput[DualSenseInput["DPadLeft"] = 14] = "DPadLeft"; + /** DRight */ + DualSenseInput[DualSenseInput["DPadRight"] = 15] = "DPadRight"; + /** Home */ + DualSenseInput[DualSenseInput["Home"] = 16] = "Home"; + /** TouchPad */ + DualSenseInput[DualSenseInput["TouchPad"] = 17] = "TouchPad"; + /** LStickXAxis */ + DualSenseInput[DualSenseInput["LStickXAxis"] = 18] = "LStickXAxis"; + /** LStickYAxis */ + DualSenseInput[DualSenseInput["LStickYAxis"] = 19] = "LStickYAxis"; + /** RStickXAxis */ + DualSenseInput[DualSenseInput["RStickXAxis"] = 20] = "RStickXAxis"; + /** RStickYAxis */ + DualSenseInput[DualSenseInput["RStickYAxis"] = 21] = "RStickYAxis"; +})(DualSenseInput || (DualSenseInput = {})); +/** + * Enum for Xbox Gamepad + */ +var XboxInput; +(function (XboxInput) { + /** A */ + XboxInput[XboxInput["A"] = 0] = "A"; + /** B */ + XboxInput[XboxInput["B"] = 1] = "B"; + /** X */ + XboxInput[XboxInput["X"] = 2] = "X"; + /** Y */ + XboxInput[XboxInput["Y"] = 3] = "Y"; + /** LB */ + XboxInput[XboxInput["LB"] = 4] = "LB"; + /** RB */ + XboxInput[XboxInput["RB"] = 5] = "RB"; + /** LT */ + XboxInput[XboxInput["LT"] = 6] = "LT"; + /** RT */ + XboxInput[XboxInput["RT"] = 7] = "RT"; + /** Back */ + XboxInput[XboxInput["Back"] = 8] = "Back"; + /** Start */ + XboxInput[XboxInput["Start"] = 9] = "Start"; + /** LS */ + XboxInput[XboxInput["LS"] = 10] = "LS"; + /** RS */ + XboxInput[XboxInput["RS"] = 11] = "RS"; + /** DPadUp */ + XboxInput[XboxInput["DPadUp"] = 12] = "DPadUp"; + /** DPadDown */ + XboxInput[XboxInput["DPadDown"] = 13] = "DPadDown"; + /** DPadLeft */ + XboxInput[XboxInput["DPadLeft"] = 14] = "DPadLeft"; + /** DRight */ + XboxInput[XboxInput["DPadRight"] = 15] = "DPadRight"; + /** Home */ + XboxInput[XboxInput["Home"] = 16] = "Home"; + /** LStickXAxis */ + XboxInput[XboxInput["LStickXAxis"] = 17] = "LStickXAxis"; + /** LStickYAxis */ + XboxInput[XboxInput["LStickYAxis"] = 18] = "LStickYAxis"; + /** RStickXAxis */ + XboxInput[XboxInput["RStickXAxis"] = 19] = "RStickXAxis"; + /** RStickYAxis */ + XboxInput[XboxInput["RStickYAxis"] = 20] = "RStickYAxis"; +})(XboxInput || (XboxInput = {})); +/** + * Enum for Switch (Pro/JoyCon L+R) Gamepad + */ +var SwitchInput; +(function (SwitchInput) { + /** B */ + SwitchInput[SwitchInput["B"] = 0] = "B"; + /** A */ + SwitchInput[SwitchInput["A"] = 1] = "A"; + /** Y */ + SwitchInput[SwitchInput["Y"] = 2] = "Y"; + /** X */ + SwitchInput[SwitchInput["X"] = 3] = "X"; + /** L */ + SwitchInput[SwitchInput["L"] = 4] = "L"; + /** R */ + SwitchInput[SwitchInput["R"] = 5] = "R"; + /** ZL */ + SwitchInput[SwitchInput["ZL"] = 6] = "ZL"; + /** ZR */ + SwitchInput[SwitchInput["ZR"] = 7] = "ZR"; + /** Minus */ + SwitchInput[SwitchInput["Minus"] = 8] = "Minus"; + /** Plus */ + SwitchInput[SwitchInput["Plus"] = 9] = "Plus"; + /** LS */ + SwitchInput[SwitchInput["LS"] = 10] = "LS"; + /** RS */ + SwitchInput[SwitchInput["RS"] = 11] = "RS"; + /** DPadUp */ + SwitchInput[SwitchInput["DPadUp"] = 12] = "DPadUp"; + /** DPadDown */ + SwitchInput[SwitchInput["DPadDown"] = 13] = "DPadDown"; + /** DPadLeft */ + SwitchInput[SwitchInput["DPadLeft"] = 14] = "DPadLeft"; + /** DRight */ + SwitchInput[SwitchInput["DPadRight"] = 15] = "DPadRight"; + /** Home */ + SwitchInput[SwitchInput["Home"] = 16] = "Home"; + /** Capture */ + SwitchInput[SwitchInput["Capture"] = 17] = "Capture"; + /** LStickXAxis */ + SwitchInput[SwitchInput["LStickXAxis"] = 18] = "LStickXAxis"; + /** LStickYAxis */ + SwitchInput[SwitchInput["LStickYAxis"] = 19] = "LStickYAxis"; + /** RStickXAxis */ + SwitchInput[SwitchInput["RStickXAxis"] = 20] = "RStickXAxis"; + /** RStickYAxis */ + SwitchInput[SwitchInput["RStickYAxis"] = 21] = "RStickYAxis"; +})(SwitchInput || (SwitchInput = {})); + +/** + * Event Types + */ +var DeviceInputEventType; +(function (DeviceInputEventType) { + // Pointers + /** PointerMove */ + DeviceInputEventType[DeviceInputEventType["PointerMove"] = 0] = "PointerMove"; + /** PointerDown */ + DeviceInputEventType[DeviceInputEventType["PointerDown"] = 1] = "PointerDown"; + /** PointerUp */ + DeviceInputEventType[DeviceInputEventType["PointerUp"] = 2] = "PointerUp"; +})(DeviceInputEventType || (DeviceInputEventType = {})); +/** + * Constants used for Events + */ +class EventConstants { +} +/** + * Pixel delta for Wheel Events (Default) + */ +EventConstants.DOM_DELTA_PIXEL = 0x00; +/** + * Line delta for Wheel Events + */ +EventConstants.DOM_DELTA_LINE = 0x01; +/** + * Page delta for Wheel Events + */ +EventConstants.DOM_DELTA_PAGE = 0x02; + +/** + * Class to wrap DeviceInputSystem data into an event object + */ +class DeviceEventFactory { + /** + * Create device input events based on provided type and slot + * + * @param deviceType Type of device + * @param deviceSlot "Slot" or index that device is referenced in + * @param inputIndex Id of input to be checked + * @param currentState Current value for given input + * @param deviceInputSystem Reference to DeviceInputSystem + * @param elementToAttachTo HTMLElement to reference as target for inputs + * @param pointerId PointerId to use for pointer events + * @returns IUIEvent object + */ + static CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) { + switch (deviceType) { + case DeviceType.Keyboard: + return this._CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo); + case DeviceType.Mouse: + if (inputIndex === PointerInput.MouseWheelX || inputIndex === PointerInput.MouseWheelY || inputIndex === PointerInput.MouseWheelZ) { + return this._CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo); + } + // eslint-disable-next-line no-fallthrough + case DeviceType.Touch: + return this._CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId); + default: + // eslint-disable-next-line no-throw-literal + throw `Unable to generate event for device ${DeviceType[deviceType]}`; + } + } + /** + * Creates pointer event + * + * @param deviceType Type of device + * @param deviceSlot "Slot" or index that device is referenced in + * @param inputIndex Id of input to be checked + * @param currentState Current value for given input + * @param deviceInputSystem Reference to DeviceInputSystem + * @param elementToAttachTo HTMLElement to reference as target for inputs + * @param pointerId PointerId to use for pointer events + * @returns IUIEvent object (Pointer) + */ + static _CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) { + const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo); + if (deviceType === DeviceType.Mouse) { + evt.deviceType = DeviceType.Mouse; + evt.pointerId = 1; + evt.pointerType = "mouse"; + } + else { + evt.deviceType = DeviceType.Touch; + evt.pointerId = pointerId ?? deviceSlot; + evt.pointerType = "touch"; + } + let buttons = 0; + // Populate buttons property with current state of all mouse buttons + // Uses values found on: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons + buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.LeftClick); + buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.RightClick) * 2; + buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.MiddleClick) * 4; + evt.buttons = buttons; + if (inputIndex === PointerInput.Move) { + evt.type = "pointermove"; + } + else if (inputIndex >= PointerInput.LeftClick && inputIndex <= PointerInput.RightClick) { + evt.type = currentState === 1 ? "pointerdown" : "pointerup"; + evt.button = inputIndex - 2; + } + return evt; + } + /** + * Create Mouse Wheel Event + * @param deviceType Type of device + * @param deviceSlot "Slot" or index that device is referenced in + * @param inputIndex Id of input to be checked + * @param currentState Current value for given input + * @param deviceInputSystem Reference to DeviceInputSystem + * @param elementToAttachTo HTMLElement to reference as target for inputs + * @returns IUIEvent object (Wheel) + */ + static _CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) { + const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo); + // While WheelEvents don't generally have a pointerId, we used to add one in the InputManager + // This line has been added to make the InputManager more platform-agnostic + // Similar code exists in the WebDeviceInputSystem to handle browser created events + evt.pointerId = 1; + evt.type = "wheel"; + evt.deltaMode = EventConstants.DOM_DELTA_PIXEL; + evt.deltaX = 0; + evt.deltaY = 0; + evt.deltaZ = 0; + switch (inputIndex) { + case PointerInput.MouseWheelX: + evt.deltaX = currentState; + break; + case PointerInput.MouseWheelY: + evt.deltaY = currentState; + break; + case PointerInput.MouseWheelZ: + evt.deltaZ = currentState; + break; + } + return evt; + } + /** + * Create Mouse Event + * @param deviceType Type of device + * @param deviceSlot "Slot" or index that device is referenced in + * @param inputIndex Id of input to be checked + * @param currentState Current value for given input + * @param deviceInputSystem Reference to DeviceInputSystem + * @param elementToAttachTo HTMLElement to reference as target for inputs + * @returns IUIEvent object (Mouse) + */ + static _CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) { + const evt = this._CreateEvent(elementToAttachTo); + const pointerX = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Horizontal); + const pointerY = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Vertical); + // Handle offsets/deltas based on existence of HTMLElement + if (elementToAttachTo) { + evt.movementX = 0; + evt.movementY = 0; + evt.offsetX = evt.movementX - elementToAttachTo.getBoundingClientRect().x; + evt.offsetY = evt.movementY - elementToAttachTo.getBoundingClientRect().y; + } + else { + evt.movementX = deviceInputSystem.pollInput(deviceType, deviceSlot, 10 /* NativePointerInput.DeltaHorizontal */); // DeltaHorizontal + evt.movementY = deviceInputSystem.pollInput(deviceType, deviceSlot, 11 /* NativePointerInput.DeltaVertical */); // DeltaVertical + evt.offsetX = 0; + evt.offsetY = 0; + } + this._CheckNonCharacterKeys(evt, deviceInputSystem); + evt.clientX = pointerX; + evt.clientY = pointerY; + evt.x = pointerX; + evt.y = pointerY; + evt.deviceType = deviceType; + evt.deviceSlot = deviceSlot; + evt.inputIndex = inputIndex; + return evt; + } + /** + * Create Keyboard Event + * @param inputIndex Id of input to be checked + * @param currentState Current value for given input + * @param deviceInputSystem Reference to DeviceInputSystem + * @param elementToAttachTo HTMLElement to reference as target for inputs + * @returns IEvent object (Keyboard) + */ + static _CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo) { + const evt = this._CreateEvent(elementToAttachTo); + this._CheckNonCharacterKeys(evt, deviceInputSystem); + evt.deviceType = DeviceType.Keyboard; + evt.deviceSlot = 0; + evt.inputIndex = inputIndex; + evt.type = currentState === 1 ? "keydown" : "keyup"; + evt.key = String.fromCharCode(inputIndex); + evt.keyCode = inputIndex; + return evt; + } + /** + * Add parameters for non-character keys (Ctrl, Alt, Meta, Shift) + * @param evt Event object to add parameters to + * @param deviceInputSystem DeviceInputSystem to pull values from + */ + static _CheckNonCharacterKeys(evt, deviceInputSystem) { + const isKeyboardActive = deviceInputSystem.isDeviceAvailable(DeviceType.Keyboard); + const altKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 18) === 1; + const ctrlKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 17) === 1; + const metaKey = isKeyboardActive && + (deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 91) === 1 || + deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 92) === 1 || + deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 93) === 1); + const shiftKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 16) === 1; + evt.altKey = altKey; + evt.ctrlKey = ctrlKey; + evt.metaKey = metaKey; + evt.shiftKey = shiftKey; + } + /** + * Create base event object + * @param elementToAttachTo Value to use as event target + * @returns + */ + static _CreateEvent(elementToAttachTo) { + const evt = {}; + evt.preventDefault = () => { }; + evt.target = elementToAttachTo; + return evt; + } +} + +/** @internal */ +class NativeDeviceInputSystem { + constructor(onDeviceConnected, onDeviceDisconnected, onInputChanged) { + this._nativeInput = _native.DeviceInputSystem + ? new _native.DeviceInputSystem(onDeviceConnected, onDeviceDisconnected, (deviceType, deviceSlot, inputIndex, currentState) => { + const evt = DeviceEventFactory.CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, this); + onInputChanged(deviceType, deviceSlot, evt); + }) + : this._createDummyNativeInput(); + } + // Public functions + /** + * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized. + * @param deviceType Enum specifying device type + * @param deviceSlot "Slot" or index that device is referenced in + * @param inputIndex Id of input to be checked + * @returns Current value of input + */ + pollInput(deviceType, deviceSlot, inputIndex) { + return this._nativeInput.pollInput(deviceType, deviceSlot, inputIndex); + } + /** + * Check for a specific device in the DeviceInputSystem + * @param deviceType Type of device to check for + * @returns bool with status of device's existence + */ + isDeviceAvailable(deviceType) { + //TODO: FIx native side first + return deviceType === DeviceType.Mouse || deviceType === DeviceType.Touch; + } + /** + * Dispose of all the observables + */ + dispose() { + this._nativeInput.dispose(); + } + /** + * For versions of BabylonNative that don't have the NativeInput plugin initialized, create a dummy version + * @returns Object with dummy functions + */ + _createDummyNativeInput() { + const nativeInput = { + pollInput: () => { + return 0; + }, + isDeviceAvailable: () => { + return false; + }, + dispose: () => { }, + }; + return nativeInput; + } +} + +// eslint-disable-next-line @typescript-eslint/naming-convention +const MAX_KEYCODES = 255; +// eslint-disable-next-line @typescript-eslint/naming-convention +const MAX_POINTER_INPUTS = Object.keys(PointerInput).length / 2; +/** @internal */ +class WebDeviceInputSystem { + /** + * Constructor for the WebDeviceInputSystem + * @param engine Engine to reference + * @param onDeviceConnected Callback to execute when device is connected + * @param onDeviceDisconnected Callback to execute when device is disconnected + * @param onInputChanged Callback to execute when input changes on device + */ + constructor(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged) { + // Private Members + this._inputs = []; + this._keyboardActive = false; + this._pointerActive = false; + this._usingSafari = Tools.IsSafari(); + // Found solution for determining if MacOS is being used here: + // https://stackoverflow.com/questions/10527983/best-way-to-detect-mac-os-x-or-windows-computers-with-javascript-or-jquery + this._usingMacOS = IsNavigatorAvailable() && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._keyboardDownEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._keyboardUpEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._keyboardBlurEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._pointerMoveEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._pointerDownEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._pointerUpEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._pointerCancelEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._pointerCancelTouch = (pointerId) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._pointerLeaveEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._pointerWheelEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._pointerBlurEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._pointerMacOSChromeOutEvent = (evt) => { }; + this._eventsAttached = false; + this._mouseId = -1; + this._isUsingFirefox = IsNavigatorAvailable() && navigator.userAgent && navigator.userAgent.indexOf("Firefox") !== -1; + this._isUsingChromium = IsNavigatorAvailable() && navigator.userAgent && navigator.userAgent.indexOf("Chrome") !== -1; + this._maxTouchPoints = 0; + this._pointerInputClearObserver = null; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._gamepadConnectedEvent = (evt) => { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._gamepadDisconnectedEvent = (evt) => { }; + this._eventPrefix = Tools.GetPointerPrefix(engine); + this._engine = engine; + this._onDeviceConnected = onDeviceConnected; + this._onDeviceDisconnected = onDeviceDisconnected; + this._onInputChanged = onInputChanged; + // If we need a pointerId, set one for future use + this._mouseId = this._isUsingFirefox ? 0 : 1; + this._enableEvents(); + if (this._usingMacOS) { + this._metaKeys = []; + } + // Set callback to enable event handler switching when inputElement changes + if (!this._engine._onEngineViewChanged) { + this._engine._onEngineViewChanged = () => { + this._enableEvents(); + }; + } + } + // Public functions + /** + * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized. + * @param deviceType Enum specifying device type + * @param deviceSlot "Slot" or index that device is referenced in + * @param inputIndex Id of input to be checked + * @returns Current value of input + */ + pollInput(deviceType, deviceSlot, inputIndex) { + const device = this._inputs[deviceType][deviceSlot]; + if (!device) { + // eslint-disable-next-line no-throw-literal + throw `Unable to find device ${DeviceType[deviceType]}`; + } + if (deviceType >= DeviceType.DualShock && deviceType <= DeviceType.DualSense) { + this._updateDevice(deviceType, deviceSlot, inputIndex); + } + const currentValue = device[inputIndex]; + if (currentValue === undefined) { + // eslint-disable-next-line no-throw-literal + throw `Unable to find input ${inputIndex} for device ${DeviceType[deviceType]} in slot ${deviceSlot}`; + } + if (inputIndex === PointerInput.Move) { + Tools.Warn(`Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data.`); + } + return currentValue; + } + /** + * Check for a specific device in the DeviceInputSystem + * @param deviceType Type of device to check for + * @returns bool with status of device's existence + */ + isDeviceAvailable(deviceType) { + return this._inputs[deviceType] !== undefined; + } + /** + * Dispose of all the eventlisteners + */ + dispose() { + // Callbacks + this._onDeviceConnected = () => { }; + this._onDeviceDisconnected = () => { }; + this._onInputChanged = () => { }; + delete this._engine._onEngineViewChanged; + if (this._elementToAttachTo) { + this._disableEvents(); + } + } + /** + * Enable listening for user input events + */ + _enableEvents() { + const inputElement = this?._engine.getInputElement(); + if (inputElement && (!this._eventsAttached || this._elementToAttachTo !== inputElement)) { + // Remove events before adding to avoid double events or simultaneous events on multiple canvases + this._disableEvents(); + // If the inputs array has already been created, zero it out to before setting up events + if (this._inputs) { + for (const inputs of this._inputs) { + if (inputs) { + for (const deviceSlotKey in inputs) { + const deviceSlot = +deviceSlotKey; + const device = inputs[deviceSlot]; + if (device) { + for (let inputIndex = 0; inputIndex < device.length; inputIndex++) { + device[inputIndex] = 0; + } + } + } + } + } + } + this._elementToAttachTo = inputElement; + // Set tab index for the inputElement to the engine's canvasTabIndex, if and only if the element's tab index is -1 + this._elementToAttachTo.tabIndex = this._elementToAttachTo.tabIndex !== -1 ? this._elementToAttachTo.tabIndex : this._engine.canvasTabIndex; + this._handleKeyActions(); + this._handlePointerActions(); + this._handleGamepadActions(); + this._eventsAttached = true; + // Check for devices that are already connected but aren't registered. Currently, only checks for gamepads and mouse + this._checkForConnectedDevices(); + } + } + /** + * Disable listening for user input events + */ + _disableEvents() { + if (this._elementToAttachTo) { + // Blur Events + this._elementToAttachTo.removeEventListener("blur", this._keyboardBlurEvent); + this._elementToAttachTo.removeEventListener("blur", this._pointerBlurEvent); + // Keyboard Events + this._elementToAttachTo.removeEventListener("keydown", this._keyboardDownEvent); + this._elementToAttachTo.removeEventListener("keyup", this._keyboardUpEvent); + // Pointer Events + this._elementToAttachTo.removeEventListener(this._eventPrefix + "move", this._pointerMoveEvent); + this._elementToAttachTo.removeEventListener(this._eventPrefix + "down", this._pointerDownEvent); + this._elementToAttachTo.removeEventListener(this._eventPrefix + "up", this._pointerUpEvent); + this._elementToAttachTo.removeEventListener(this._eventPrefix + "cancel", this._pointerCancelEvent); + this._elementToAttachTo.removeEventListener(this._eventPrefix + "leave", this._pointerLeaveEvent); + this._elementToAttachTo.removeEventListener(this._wheelEventName, this._pointerWheelEvent); + if (this._usingMacOS && this._isUsingChromium) { + this._elementToAttachTo.removeEventListener("lostpointercapture", this._pointerMacOSChromeOutEvent); + } + // Gamepad Events + window.removeEventListener("gamepadconnected", this._gamepadConnectedEvent); + window.removeEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent); + } + if (this._pointerInputClearObserver) { + this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver); + } + this._eventsAttached = false; + } + /** + * Checks for existing connections to devices and register them, if necessary + * Currently handles gamepads and mouse + */ + _checkForConnectedDevices() { + if (navigator.getGamepads) { + const gamepads = navigator.getGamepads(); + for (const gamepad of gamepads) { + if (gamepad) { + this._addGamePad(gamepad); + } + } + } + // If the device in use has mouse capabilities, pre-register mouse + if (typeof matchMedia === "function" && matchMedia("(pointer:fine)").matches) { + // This will provide a dummy value for the cursor position and is expected to be overridden when the first mouse event happens. + // There isn't any good way to get the current position outside of a pointer event so that's why this was done. + this._addPointerDevice(DeviceType.Mouse, 0, 0, 0); + } + } + // Private functions + /** + * Add a gamepad to the DeviceInputSystem + * @param gamepad A single DOM Gamepad object + */ + _addGamePad(gamepad) { + const deviceType = this._getGamepadDeviceType(gamepad.id); + const deviceSlot = gamepad.index; + this._gamepads = this._gamepads || new Array(gamepad.index + 1); + this._registerDevice(deviceType, deviceSlot, gamepad.buttons.length + gamepad.axes.length); + this._gamepads[deviceSlot] = deviceType; + } + /** + * Add pointer device to DeviceInputSystem + * @param deviceType Type of Pointer to add + * @param deviceSlot Pointer ID (0 for mouse, pointerId for Touch) + * @param currentX Current X at point of adding + * @param currentY Current Y at point of adding + */ + _addPointerDevice(deviceType, deviceSlot, currentX, currentY) { + if (!this._pointerActive) { + this._pointerActive = true; + } + this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS); + const pointer = this._inputs[deviceType][deviceSlot]; /* initialize our pointer position immediately after registration */ + pointer[0] = currentX; + pointer[1] = currentY; + } + /** + * Add device and inputs to device array + * @param deviceType Enum specifying device type + * @param deviceSlot "Slot" or index that device is referenced in + * @param numberOfInputs Number of input entries to create for given device + */ + _registerDevice(deviceType, deviceSlot, numberOfInputs) { + if (deviceSlot === undefined) { + // eslint-disable-next-line no-throw-literal + throw `Unable to register device ${DeviceType[deviceType]} to undefined slot.`; + } + if (!this._inputs[deviceType]) { + this._inputs[deviceType] = {}; + } + if (!this._inputs[deviceType][deviceSlot]) { + const device = new Array(numberOfInputs); + device.fill(0); + this._inputs[deviceType][deviceSlot] = device; + this._onDeviceConnected(deviceType, deviceSlot); + } + } + /** + * Given a specific device name, remove that device from the device map + * @param deviceType Enum specifying device type + * @param deviceSlot "Slot" or index that device is referenced in + */ + _unregisterDevice(deviceType, deviceSlot) { + if (this._inputs[deviceType][deviceSlot]) { + delete this._inputs[deviceType][deviceSlot]; + this._onDeviceDisconnected(deviceType, deviceSlot); + } + } + /** + * Handle all actions that come from keyboard interaction + */ + _handleKeyActions() { + this._keyboardDownEvent = (evt) => { + if (!this._keyboardActive) { + this._keyboardActive = true; + this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES); + } + const kbKey = this._inputs[DeviceType.Keyboard][0]; + if (kbKey) { + kbKey[evt.keyCode] = 1; + const deviceEvent = evt; + deviceEvent.inputIndex = evt.keyCode; + if (this._usingMacOS && evt.metaKey && evt.key !== "Meta") { + if (!this._metaKeys.includes(evt.keyCode)) { + this._metaKeys.push(evt.keyCode); + } + } + this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); + } + }; + this._keyboardUpEvent = (evt) => { + if (!this._keyboardActive) { + this._keyboardActive = true; + this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES); + } + const kbKey = this._inputs[DeviceType.Keyboard][0]; + if (kbKey) { + kbKey[evt.keyCode] = 0; + const deviceEvent = evt; + deviceEvent.inputIndex = evt.keyCode; + if (this._usingMacOS && evt.key === "Meta" && this._metaKeys.length > 0) { + for (const keyCode of this._metaKeys) { + const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, keyCode, 0, this, this._elementToAttachTo); + kbKey[keyCode] = 0; + this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); + } + this._metaKeys.splice(0, this._metaKeys.length); + } + this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); + } + }; + this._keyboardBlurEvent = () => { + if (this._keyboardActive) { + const kbKey = this._inputs[DeviceType.Keyboard][0]; + for (let i = 0; i < kbKey.length; i++) { + if (kbKey[i] !== 0) { + kbKey[i] = 0; + const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, i, 0, this, this._elementToAttachTo); + this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); + } + } + if (this._usingMacOS) { + this._metaKeys.splice(0, this._metaKeys.length); + } + } + }; + this._elementToAttachTo.addEventListener("keydown", this._keyboardDownEvent); + this._elementToAttachTo.addEventListener("keyup", this._keyboardUpEvent); + this._elementToAttachTo.addEventListener("blur", this._keyboardBlurEvent); + } + /** + * Handle all actions that come from pointer interaction + */ + _handlePointerActions() { + // If maxTouchPoints is defined, use that value. Otherwise, allow for a minimum for supported gestures like pinch + this._maxTouchPoints = (IsNavigatorAvailable() && navigator.maxTouchPoints) || 2; + if (!this._activeTouchIds) { + this._activeTouchIds = new Array(this._maxTouchPoints); + } + for (let i = 0; i < this._maxTouchPoints; i++) { + this._activeTouchIds[i] = -1; + } + this._pointerMoveEvent = (evt) => { + const deviceType = this._getPointerType(evt); + let deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId); + // In the event that we're getting pointermove events from touch inputs that we aren't tracking, + // look for an available slot and retroactively connect it. + if (deviceType === DeviceType.Touch && deviceSlot === -1) { + const idx = this._activeTouchIds.indexOf(-1); + if (idx >= 0) { + deviceSlot = idx; + this._activeTouchIds[idx] = evt.pointerId; + // Because this is a "new" input, inform the connected callback + this._onDeviceConnected(deviceType, deviceSlot); + } + else { + // We can't find an open slot to store new pointer so just return (can only support max number of touches) + Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`); + return; + } + } + if (!this._inputs[deviceType]) { + this._inputs[deviceType] = {}; + } + if (!this._inputs[deviceType][deviceSlot]) { + this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY); + } + const pointer = this._inputs[deviceType][deviceSlot]; + if (pointer) { + const deviceEvent = evt; + deviceEvent.inputIndex = PointerInput.Move; + pointer[PointerInput.Horizontal] = evt.clientX; + pointer[PointerInput.Vertical] = evt.clientY; + // For touches that aren't started with a down, we need to set the button state to 1 + if (deviceType === DeviceType.Touch && pointer[PointerInput.LeftClick] === 0) { + pointer[PointerInput.LeftClick] = 1; + } + if (evt.pointerId === undefined) { + evt.pointerId = this._mouseId; + } + this._onInputChanged(deviceType, deviceSlot, deviceEvent); + // Lets Propagate the event for move with same position. + if (!this._usingSafari && evt.button !== -1) { + deviceEvent.inputIndex = evt.button + 2; + pointer[evt.button + 2] = pointer[evt.button + 2] ? 0 : 1; // Reverse state of button if evt.button has value + this._onInputChanged(deviceType, deviceSlot, deviceEvent); + } + } + }; + this._pointerDownEvent = (evt) => { + const deviceType = this._getPointerType(evt); + let deviceSlot = deviceType === DeviceType.Mouse ? 0 : evt.pointerId; + if (deviceType === DeviceType.Touch) { + // See if this pointerId is already using an existing slot + // (possible on some devices which raise the pointerMove event before the pointerDown event, e.g. when using a pen) + let idx = this._activeTouchIds.indexOf(evt.pointerId); + if (idx === -1) { + // If the pointerId wasn't already using a slot, find an open one + idx = this._activeTouchIds.indexOf(-1); + } + if (idx >= 0) { + deviceSlot = idx; + this._activeTouchIds[idx] = evt.pointerId; + } + else { + // We can't find an open slot to store new pointer so just return (can only support max number of touches) + Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`); + return; + } + } + if (!this._inputs[deviceType]) { + this._inputs[deviceType] = {}; + } + if (!this._inputs[deviceType][deviceSlot]) { + this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY); + } + else if (deviceType === DeviceType.Touch) { + this._onDeviceConnected(deviceType, deviceSlot); + } + const pointer = this._inputs[deviceType][deviceSlot]; + if (pointer) { + const previousHorizontal = pointer[PointerInput.Horizontal]; + const previousVertical = pointer[PointerInput.Vertical]; + if (deviceType === DeviceType.Mouse) { + // Mouse; Set pointerId if undefined + if (evt.pointerId === undefined) { + evt.pointerId = this._mouseId; + } + if (!document.pointerLockElement) { + try { + this._elementToAttachTo.setPointerCapture(this._mouseId); + } + catch (e) { + // DO NOTHING + } + } + } + else { + // Touch; Since touches are dynamically assigned, only set capture if we have an id + if (evt.pointerId && !document.pointerLockElement) { + try { + this._elementToAttachTo.setPointerCapture(evt.pointerId); + } + catch (e) { + // DO NOTHING + } + } + } + pointer[PointerInput.Horizontal] = evt.clientX; + pointer[PointerInput.Vertical] = evt.clientY; + pointer[evt.button + 2] = 1; + const deviceEvent = evt; + // NOTE: The +2 used here to is because PointerInput has the same value progression for its mouse buttons as PointerEvent.button + // However, we have our X and Y values front-loaded to group together the touch inputs but not break this progression + // EG. ([X, Y, Left-click], Middle-click, etc...) + deviceEvent.inputIndex = evt.button + 2; + this._onInputChanged(deviceType, deviceSlot, deviceEvent); + if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) { + deviceEvent.inputIndex = PointerInput.Move; + this._onInputChanged(deviceType, deviceSlot, deviceEvent); + } + } + }; + this._pointerUpEvent = (evt) => { + const deviceType = this._getPointerType(evt); + const deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId); + if (deviceType === DeviceType.Touch) { + // If we're getting a pointerup event for a touch that isn't active, just return. + if (deviceSlot === -1) { + return; + } + else { + this._activeTouchIds[deviceSlot] = -1; + } + } + const pointer = this._inputs[deviceType]?.[deviceSlot]; + let button = evt.button; + let shouldProcessPointerUp = pointer && pointer[button + 2] !== 0; + // Workaround for an issue in Firefox on MacOS only where the browser allows the user to change left button + // actions into right button actions by holding down control. If the user starts a drag with the control button + // down, then lifts control, then releases the mouse, we'll get mismatched up and down events (the down will be + // the right button, and the up will be the left button). In that specific case, where we get an up from a button + // which didn't have a corresponding down, and we are in Firefox on MacOS, we should process the up event as if it + // was from the other button. + // Ideally this would be fixed in Firefox so that if you start a drag with the control button down, then the button + // passed along to both pointer down and up would be the right button regardless of the order in which control and the + // mouse button were released. + // If Firefox makes a fix to ensure this is the case, this workaround can be removed. + // Relevant forum thread: https://forum.babylonjs.com/t/camera-pan-getting-stuck-in-firefox/57158 + if (!shouldProcessPointerUp && this._isUsingFirefox && this._usingMacOS && pointer) { + // Try the other button (left or right button) + button = button === 2 ? 0 : 2; + shouldProcessPointerUp = pointer[button + 2] !== 0; + } + if (shouldProcessPointerUp) { + const previousHorizontal = pointer[PointerInput.Horizontal]; + const previousVertical = pointer[PointerInput.Vertical]; + pointer[PointerInput.Horizontal] = evt.clientX; + pointer[PointerInput.Vertical] = evt.clientY; + pointer[button + 2] = 0; + const deviceEvent = evt; + if (evt.pointerId === undefined) { + evt.pointerId = this._mouseId; + } + if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) { + deviceEvent.inputIndex = PointerInput.Move; + this._onInputChanged(deviceType, deviceSlot, deviceEvent); + } + // NOTE: The +2 used here to is because PointerInput has the same value progression for its mouse buttons as PointerEvent.button + // However, we have our X and Y values front-loaded to group together the touch inputs but not break this progression + // EG. ([X, Y, Left-click], Middle-click, etc...) + deviceEvent.inputIndex = button + 2; + if (deviceType === DeviceType.Mouse && this._mouseId >= 0 && this._elementToAttachTo.hasPointerCapture?.(this._mouseId)) { + this._elementToAttachTo.releasePointerCapture(this._mouseId); + } + else if (evt.pointerId && this._elementToAttachTo.hasPointerCapture?.(evt.pointerId)) { + this._elementToAttachTo.releasePointerCapture(evt.pointerId); + } + this._onInputChanged(deviceType, deviceSlot, deviceEvent); + if (deviceType === DeviceType.Touch) { + this._onDeviceDisconnected(deviceType, deviceSlot); + } + } + }; + this._pointerCancelTouch = (pointerId) => { + const deviceSlot = this._activeTouchIds.indexOf(pointerId); + // If we're getting a pointercancel event for a touch that isn't active, just return + if (deviceSlot === -1) { + return; + } + if (this._elementToAttachTo.hasPointerCapture?.(pointerId)) { + this._elementToAttachTo.releasePointerCapture(pointerId); + } + this._inputs[DeviceType.Touch][deviceSlot][PointerInput.LeftClick] = 0; + const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, pointerId); + this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent); + this._activeTouchIds[deviceSlot] = -1; + this._onDeviceDisconnected(DeviceType.Touch, deviceSlot); + }; + this._pointerCancelEvent = (evt) => { + if (evt.pointerType === "mouse") { + const pointer = this._inputs[DeviceType.Mouse][0]; + if (this._mouseId >= 0 && this._elementToAttachTo.hasPointerCapture?.(this._mouseId)) { + this._elementToAttachTo.releasePointerCapture(this._mouseId); + } + for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) { + if (pointer[inputIndex] === 1) { + pointer[inputIndex] = 0; + const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo); + this._onInputChanged(DeviceType.Mouse, 0, deviceEvent); + } + } + } + else { + this._pointerCancelTouch(evt.pointerId); + } + }; + this._pointerLeaveEvent = (evt) => { + if (evt.pointerType === "pen") { + // If a pen leaves the hover range detectible by the hardware this event is raised and we need to cancel the operation + // Note that pen operations are treated as touch operations + this._pointerCancelTouch(evt.pointerId); + } + }; + // Set Wheel Event Name, code originally from scene.inputManager + this._wheelEventName = + "onwheel" in document.createElement("div") + ? "wheel" // Modern browsers support "wheel" + : document.onmousewheel !== undefined + ? "mousewheel" // Webkit and IE support at least "mousewheel" + : "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox + // Code originally in scene.inputManager.ts + // Chrome reports warning in console if wheel listener doesn't set an explicit passive option. + // IE11 only supports captureEvent:boolean, not options:object, and it defaults to false. + // Feature detection technique copied from: https://github.com/github/eventlistener-polyfill (MIT license) + let passiveSupported = false; + const noop = function () { }; + try { + const options = Object.defineProperty({}, "passive", { + get: function () { + passiveSupported = true; + }, + }); + this._elementToAttachTo.addEventListener("test", noop, options); + this._elementToAttachTo.removeEventListener("test", noop, options); + } + catch (e) { + /* */ + } + this._pointerBlurEvent = () => { + // Handle mouse buttons + if (this.isDeviceAvailable(DeviceType.Mouse)) { + const pointer = this._inputs[DeviceType.Mouse][0]; + if (this._mouseId >= 0 && this._elementToAttachTo.hasPointerCapture?.(this._mouseId)) { + this._elementToAttachTo.releasePointerCapture(this._mouseId); + } + for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) { + if (pointer[inputIndex] === 1) { + pointer[inputIndex] = 0; + const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo); + this._onInputChanged(DeviceType.Mouse, 0, deviceEvent); + } + } + } + // Handle Active Touches + if (this.isDeviceAvailable(DeviceType.Touch)) { + const pointer = this._inputs[DeviceType.Touch]; + for (let deviceSlot = 0; deviceSlot < this._activeTouchIds.length; deviceSlot++) { + const pointerId = this._activeTouchIds[deviceSlot]; + if (this._elementToAttachTo.hasPointerCapture?.(pointerId)) { + this._elementToAttachTo.releasePointerCapture(pointerId); + } + if (pointerId !== -1 && pointer[deviceSlot]?.[PointerInput.LeftClick] === 1) { + pointer[deviceSlot][PointerInput.LeftClick] = 0; + const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, pointerId); + this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent); + this._activeTouchIds[deviceSlot] = -1; + this._onDeviceDisconnected(DeviceType.Touch, deviceSlot); + } + } + } + }; + this._pointerWheelEvent = (evt) => { + const deviceType = DeviceType.Mouse; + const deviceSlot = 0; + if (!this._inputs[deviceType]) { + this._inputs[deviceType] = []; + } + if (!this._inputs[deviceType][deviceSlot]) { + this._pointerActive = true; + this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS); + } + const pointer = this._inputs[deviceType][deviceSlot]; + if (pointer) { + pointer[PointerInput.MouseWheelX] = evt.deltaX || 0; + pointer[PointerInput.MouseWheelY] = evt.deltaY || evt.wheelDelta || 0; + pointer[PointerInput.MouseWheelZ] = evt.deltaZ || 0; + const deviceEvent = evt; + // By default, there is no pointerId for mouse wheel events so we'll add one here + // This logic was originally in the InputManager but was added here to make the + // InputManager more platform-agnostic + if (evt.pointerId === undefined) { + evt.pointerId = this._mouseId; + } + if (pointer[PointerInput.MouseWheelX] !== 0) { + deviceEvent.inputIndex = PointerInput.MouseWheelX; + this._onInputChanged(deviceType, deviceSlot, deviceEvent); + } + if (pointer[PointerInput.MouseWheelY] !== 0) { + deviceEvent.inputIndex = PointerInput.MouseWheelY; + this._onInputChanged(deviceType, deviceSlot, deviceEvent); + } + if (pointer[PointerInput.MouseWheelZ] !== 0) { + deviceEvent.inputIndex = PointerInput.MouseWheelZ; + this._onInputChanged(deviceType, deviceSlot, deviceEvent); + } + } + }; + // Workaround for MacOS Chromium Browsers for lost pointer capture bug + if (this._usingMacOS && this._isUsingChromium) { + this._pointerMacOSChromeOutEvent = (evt) => { + if (evt.buttons > 1) { + this._pointerCancelEvent(evt); + } + }; + this._elementToAttachTo.addEventListener("lostpointercapture", this._pointerMacOSChromeOutEvent); + } + this._elementToAttachTo.addEventListener(this._eventPrefix + "move", this._pointerMoveEvent); + this._elementToAttachTo.addEventListener(this._eventPrefix + "down", this._pointerDownEvent); + this._elementToAttachTo.addEventListener(this._eventPrefix + "up", this._pointerUpEvent); + this._elementToAttachTo.addEventListener(this._eventPrefix + "cancel", this._pointerCancelEvent); + this._elementToAttachTo.addEventListener(this._eventPrefix + "leave", this._pointerLeaveEvent); + this._elementToAttachTo.addEventListener("blur", this._pointerBlurEvent); + this._elementToAttachTo.addEventListener(this._wheelEventName, this._pointerWheelEvent, passiveSupported ? { passive: false } : false); + // Since there's no up or down event for mouse wheel or delta x/y, clear mouse values at end of frame + this._pointerInputClearObserver = this._engine.onEndFrameObservable.add(() => { + if (this.isDeviceAvailable(DeviceType.Mouse)) { + const pointer = this._inputs[DeviceType.Mouse][0]; + pointer[PointerInput.MouseWheelX] = 0; + pointer[PointerInput.MouseWheelY] = 0; + pointer[PointerInput.MouseWheelZ] = 0; + } + }); + } + /** + * Handle all actions that come from gamepad interaction + */ + _handleGamepadActions() { + this._gamepadConnectedEvent = (evt) => { + this._addGamePad(evt.gamepad); + }; + this._gamepadDisconnectedEvent = (evt) => { + if (this._gamepads) { + const deviceType = this._getGamepadDeviceType(evt.gamepad.id); + const deviceSlot = evt.gamepad.index; + this._unregisterDevice(deviceType, deviceSlot); + delete this._gamepads[deviceSlot]; + } + }; + window.addEventListener("gamepadconnected", this._gamepadConnectedEvent); + window.addEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent); + } + /** + * Update all non-event based devices with each frame + * @param deviceType Enum specifying device type + * @param deviceSlot "Slot" or index that device is referenced in + * @param inputIndex Id of input to be checked + */ + _updateDevice(deviceType, deviceSlot, inputIndex) { + // Gamepads + const gp = navigator.getGamepads()[deviceSlot]; + if (gp && deviceType === this._gamepads[deviceSlot]) { + const device = this._inputs[deviceType][deviceSlot]; + if (inputIndex >= gp.buttons.length) { + device[inputIndex] = gp.axes[inputIndex - gp.buttons.length].valueOf(); + } + else { + device[inputIndex] = gp.buttons[inputIndex].value; + } + } + } + /** + * Gets DeviceType from the device name + * @param deviceName Name of Device from DeviceInputSystem + * @returns DeviceType enum value + */ + _getGamepadDeviceType(deviceName) { + if (deviceName.indexOf("054c") !== -1) { + // DualShock 4 Gamepad + return deviceName.indexOf("0ce6") !== -1 ? DeviceType.DualSense : DeviceType.DualShock; + } + else if (deviceName.indexOf("Xbox One") !== -1 || deviceName.search("Xbox 360") !== -1 || deviceName.search("xinput") !== -1) { + // Xbox Gamepad + return DeviceType.Xbox; + } + else if (deviceName.indexOf("057e") !== -1) { + // Switch Gamepad + return DeviceType.Switch; + } + return DeviceType.Generic; + } + /** + * Get DeviceType from a given pointer/mouse/touch event. + * @param evt PointerEvent to evaluate + * @returns DeviceType interpreted from event + */ + _getPointerType(evt) { + let deviceType = DeviceType.Mouse; + if (evt.pointerType === "touch" || evt.pointerType === "pen" || evt.touches) { + deviceType = DeviceType.Touch; + } + return deviceType; + } +} + +/** + * Class that handles all input for a specific device + */ +class DeviceSource { + /** + * Default Constructor + * @param deviceInputSystem - Reference to DeviceInputSystem + * @param deviceType - Type of device + * @param deviceSlot - "Slot" or index that device is referenced in + */ + constructor(deviceInputSystem, + /** Type of device */ + deviceType, + /** [0] "Slot" or index that device is referenced in */ + deviceSlot = 0) { + this.deviceType = deviceType; + this.deviceSlot = deviceSlot; + // Public Members + /** + * Observable to handle device input changes per device + */ + this.onInputChangedObservable = new Observable(); + this._deviceInputSystem = deviceInputSystem; + } + /** + * Get input for specific input + * @param inputIndex - index of specific input on device + * @returns Input value from DeviceInputSystem + */ + getInput(inputIndex) { + return this._deviceInputSystem.pollInput(this.deviceType, this.deviceSlot, inputIndex); + } +} + +/** @internal */ +class InternalDeviceSourceManager { + constructor(engine) { + this._registeredManagers = new Array(); + this._refCount = 0; + // Public Functions + this.registerManager = (manager) => { + for (let deviceType = 0; deviceType < this._devices.length; deviceType++) { + const device = this._devices[deviceType]; + for (const deviceSlotKey in device) { + const deviceSlot = +deviceSlotKey; + manager._addDevice(new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot)); + } + } + this._registeredManagers.push(manager); + }; + this.unregisterManager = (manager) => { + const idx = this._registeredManagers.indexOf(manager); + if (idx > -1) { + this._registeredManagers.splice(idx, 1); + } + }; + const numberOfDeviceTypes = Object.keys(DeviceType).length / 2; + this._devices = new Array(numberOfDeviceTypes); + const onDeviceConnected = (deviceType, deviceSlot) => { + if (!this._devices[deviceType]) { + this._devices[deviceType] = new Array(); + } + if (!this._devices[deviceType][deviceSlot]) { + this._devices[deviceType][deviceSlot] = deviceSlot; + } + for (const manager of this._registeredManagers) { + const deviceSource = new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot); + manager._addDevice(deviceSource); + } + }; + const onDeviceDisconnected = (deviceType, deviceSlot) => { + if (this._devices[deviceType]?.[deviceSlot]) { + delete this._devices[deviceType][deviceSlot]; + } + for (const manager of this._registeredManagers) { + manager._removeDevice(deviceType, deviceSlot); + } + }; + const onInputChanged = (deviceType, deviceSlot, eventData) => { + if (eventData) { + for (const manager of this._registeredManagers) { + manager._onInputChanged(deviceType, deviceSlot, eventData); + } + } + }; + if (typeof _native !== "undefined") { + this._deviceInputSystem = new NativeDeviceInputSystem(onDeviceConnected, onDeviceDisconnected, onInputChanged); + } + else { + this._deviceInputSystem = new WebDeviceInputSystem(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged); + } + } + dispose() { + this._deviceInputSystem.dispose(); + } +} + +/** + * Class to keep track of devices + */ +class DeviceSourceManager { + // Public Functions + /** + * Gets a DeviceSource, given a type and slot + * @param deviceType - Type of Device + * @param deviceSlot - Slot or ID of device + * @returns DeviceSource + */ + getDeviceSource(deviceType, deviceSlot) { + if (deviceSlot === undefined) { + if (this._firstDevice[deviceType] === undefined) { + return null; + } + deviceSlot = this._firstDevice[deviceType]; + } + if (!this._devices[deviceType] || this._devices[deviceType][deviceSlot] === undefined) { + return null; + } + return this._devices[deviceType][deviceSlot]; + } + /** + * Gets an array of DeviceSource objects for a given device type + * @param deviceType - Type of Device + * @returns All available DeviceSources of a given type + */ + getDeviceSources(deviceType) { + // If device type hasn't had any devices connected yet, return empty array. + if (!this._devices[deviceType]) { + return []; + } + return this._devices[deviceType].filter((source) => { + return !!source; + }); + } + /** + * Default constructor + * @param engine - Used to get canvas (if applicable) + */ + constructor(engine) { + const numberOfDeviceTypes = Object.keys(DeviceType).length / 2; + this._devices = new Array(numberOfDeviceTypes); + this._firstDevice = new Array(numberOfDeviceTypes); + this._engine = engine; + if (!this._engine._deviceSourceManager) { + this._engine._deviceSourceManager = new InternalDeviceSourceManager(engine); + } + this._engine._deviceSourceManager._refCount++; + // Observables + this.onDeviceConnectedObservable = new Observable((observer) => { + for (const devices of this._devices) { + if (devices) { + for (const device of devices) { + if (device) { + this.onDeviceConnectedObservable.notifyObserver(observer, device); + } + } + } + } + }); + this.onDeviceDisconnectedObservable = new Observable(); + this._engine._deviceSourceManager.registerManager(this); + this._onDisposeObserver = engine.onDisposeObservable.add(() => { + this.dispose(); + }); + } + /** + * Dispose of DeviceSourceManager + */ + dispose() { + // Null out observable refs + this.onDeviceConnectedObservable.clear(); + this.onDeviceDisconnectedObservable.clear(); + if (this._engine._deviceSourceManager) { + this._engine._deviceSourceManager.unregisterManager(this); + if (--this._engine._deviceSourceManager._refCount < 1) { + this._engine._deviceSourceManager.dispose(); + delete this._engine._deviceSourceManager; + } + } + this._engine.onDisposeObservable.remove(this._onDisposeObserver); + } + // Hidden Functions + /** + * @param deviceSource - Source to add + * @internal + */ + _addDevice(deviceSource) { + if (!this._devices[deviceSource.deviceType]) { + this._devices[deviceSource.deviceType] = new Array(); + } + if (!this._devices[deviceSource.deviceType][deviceSource.deviceSlot]) { + this._devices[deviceSource.deviceType][deviceSource.deviceSlot] = deviceSource; + this._updateFirstDevices(deviceSource.deviceType); + } + this.onDeviceConnectedObservable.notifyObservers(deviceSource); + } + /** + * @param deviceType - DeviceType + * @param deviceSlot - DeviceSlot + * @internal + */ + _removeDevice(deviceType, deviceSlot) { + const deviceSource = this._devices[deviceType]?.[deviceSlot]; // Grab local reference to use before removing from devices + this.onDeviceDisconnectedObservable.notifyObservers(deviceSource); + if (this._devices[deviceType]?.[deviceSlot]) { + delete this._devices[deviceType][deviceSlot]; + } + // Even if we don't delete a device, we should still check for the first device as things may have gotten out of sync. + this._updateFirstDevices(deviceType); + } + /** + * @param deviceType - DeviceType + * @param deviceSlot - DeviceSlot + * @param eventData - Event + * @internal + */ + _onInputChanged(deviceType, deviceSlot, eventData) { + this._devices[deviceType]?.[deviceSlot]?.onInputChangedObservable.notifyObservers(eventData); + } + // Private Functions + _updateFirstDevices(type) { + switch (type) { + case DeviceType.Keyboard: + case DeviceType.Mouse: + this._firstDevice[type] = 0; + break; + case DeviceType.Touch: + case DeviceType.DualSense: + case DeviceType.DualShock: + case DeviceType.Xbox: + case DeviceType.Switch: + case DeviceType.Generic: { + delete this._firstDevice[type]; + // eslint-disable-next-line no-case-declarations + const devices = this._devices[type]; + if (devices) { + for (let i = 0; i < devices.length; i++) { + if (devices[i]) { + this._firstDevice[type] = i; + break; + } + } + } + break; + } + } + } +} + +/** @internal */ +class _ImportHelper { +} +/** @internal */ +_ImportHelper._IsPickingAvailable = false; + +/** @internal */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _ClickInfo { + constructor() { + this._singleClick = false; + this._doubleClick = false; + this._hasSwiped = false; + this._ignore = false; + } + get singleClick() { + return this._singleClick; + } + get doubleClick() { + return this._doubleClick; + } + get hasSwiped() { + return this._hasSwiped; + } + get ignore() { + return this._ignore; + } + set singleClick(b) { + this._singleClick = b; + } + set doubleClick(b) { + this._doubleClick = b; + } + set hasSwiped(b) { + this._hasSwiped = b; + } + set ignore(b) { + this._ignore = b; + } +} +/** + * Class used to manage all inputs for the scene. + */ +class InputManager { + /** + * Creates a new InputManager + * @param scene - defines the hosting scene + */ + constructor(scene) { + /** This is a defensive check to not allow control attachment prior to an already active one. If already attached, previous control is unattached before attaching the new one. */ + this._alreadyAttached = false; + this._meshPickProceed = false; + this._currentPickResult = null; + this._previousPickResult = null; + this._activePointerIds = new Array(); + /** Tracks the count of used slots in _activePointerIds for perf */ + this._activePointerIdsCount = 0; + this._doubleClickOccured = false; + this._isSwiping = false; + this._swipeButtonPressed = -1; + this._skipPointerTap = false; + this._isMultiTouchGesture = false; + this._pointerX = 0; + this._pointerY = 0; + this._startingPointerPosition = new Vector2(0, 0); + this._previousStartingPointerPosition = new Vector2(0, 0); + this._startingPointerTime = 0; + this._previousStartingPointerTime = 0; + this._pointerCaptures = {}; + this._meshUnderPointerId = {}; + this._movePointerInfo = null; + this._cameraObserverCount = 0; + this._delayedClicks = [null, null, null, null, null]; + this._deviceSourceManager = null; + this._scene = scene || EngineStore.LastCreatedScene; + if (!this._scene) { + return; + } + } + /** + * Gets the mesh that is currently under the pointer + * @returns Mesh that the pointer is pointer is hovering over + */ + get meshUnderPointer() { + if (this._movePointerInfo) { + // Because _pointerOverMesh is populated as part of _pickMove, we need to force a pick to update it. + // Calling _pickMove calls _setCursorAndPointerOverMesh which calls setPointerOverMesh + this._movePointerInfo._generatePickInfo(); + // Once we have what we need, we can clear _movePointerInfo because we don't need it anymore + this._movePointerInfo = null; + } + return this._pointerOverMesh; + } + /** + * When using more than one pointer (for example in XR) you can get the mesh under the specific pointer + * @param pointerId - the pointer id to use + * @returns The mesh under this pointer id or null if not found + */ + getMeshUnderPointerByPointerId(pointerId) { + return this._meshUnderPointerId[pointerId] || null; + } + /** + * Gets the pointer coordinates in 2D without any translation (ie. straight out of the pointer event) + * @returns Vector with X/Y values directly from pointer event + */ + get unTranslatedPointer() { + return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY); + } + /** + * Gets or sets the current on-screen X position of the pointer + * @returns Translated X with respect to screen + */ + get pointerX() { + return this._pointerX; + } + set pointerX(value) { + this._pointerX = value; + } + /** + * Gets or sets the current on-screen Y position of the pointer + * @returns Translated Y with respect to screen + */ + get pointerY() { + return this._pointerY; + } + set pointerY(value) { + this._pointerY = value; + } + _updatePointerPosition(evt) { + const canvasRect = this._scene.getEngine().getInputElementClientRect(); + if (!canvasRect) { + return; + } + this._pointerX = evt.clientX - canvasRect.left; + this._pointerY = evt.clientY - canvasRect.top; + this._unTranslatedPointerX = this._pointerX; + this._unTranslatedPointerY = this._pointerY; + } + _processPointerMove(pickResult, evt) { + const scene = this._scene; + const engine = scene.getEngine(); + const canvas = engine.getInputElement(); + if (canvas) { + canvas.tabIndex = engine.canvasTabIndex; + // Restore pointer + if (!scene.doNotHandleCursors) { + canvas.style.cursor = scene.defaultCursor; + } + } + this._setCursorAndPointerOverMesh(pickResult, evt, scene); + for (const step of scene._pointerMoveStage) { + // If _pointerMoveState is defined, we have an active spriteManager and can't use Lazy Picking + // Therefore, we need to force a pick to update the pickResult + pickResult = pickResult || this._pickMove(evt); + const isMeshPicked = pickResult?.pickedMesh ? true : false; + pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas); + } + const type = evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE; + if (scene.onPointerMove) { + // Because of lazy picking, we need to force a pick to update the pickResult + pickResult = pickResult || this._pickMove(evt); + scene.onPointerMove(evt, pickResult, type); + } + let pointerInfo; + if (pickResult) { + pointerInfo = new PointerInfo(type, evt, pickResult); + this._setRayOnPointerInfo(pickResult, evt); + } + else { + pointerInfo = new PointerInfo(type, evt, null, this); + this._movePointerInfo = pointerInfo; + } + if (scene.onPointerObservable.hasObservers()) { + scene.onPointerObservable.notifyObservers(pointerInfo, type); + } + } + // Pointers handling + /** @internal */ + _setRayOnPointerInfo(pickInfo, event) { + const scene = this._scene; + if (pickInfo && _ImportHelper._IsPickingAvailable) { + if (!pickInfo.ray) { + pickInfo.ray = scene.createPickingRay(event.offsetX, event.offsetY, Matrix.Identity(), scene.activeCamera); + } + } + } + /** @internal */ + _addCameraPointerObserver(observer, mask) { + this._cameraObserverCount++; + return this._scene.onPointerObservable.add(observer, mask); + } + /** @internal */ + _removeCameraPointerObserver(observer) { + this._cameraObserverCount--; + return this._scene.onPointerObservable.remove(observer); + } + _checkForPicking() { + return !!(this._scene.onPointerObservable.observers.length > this._cameraObserverCount || this._scene.onPointerPick); + } + _checkPrePointerObservable(pickResult, evt, type) { + const scene = this._scene; + const pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY); + if (pickResult) { + pi.originalPickingInfo = pickResult; + pi.ray = pickResult.ray; + if (evt.pointerType === "xr-near" && pickResult.originMesh) { + pi.nearInteractionPickingInfo = pickResult; + } + } + scene.onPrePointerObservable.notifyObservers(pi, type); + if (pi.skipOnPointerObservable) { + return true; + } + else { + return false; + } + } + /** @internal */ + _pickMove(evt) { + const scene = this._scene; + const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerMovePredicate, scene.pointerMoveFastCheck, scene.cameraToUseForPointers, scene.pointerMoveTrianglePredicate); + this._setCursorAndPointerOverMesh(pickResult, evt, scene); + return pickResult; + } + _setCursorAndPointerOverMesh(pickResult, evt, scene) { + const engine = scene.getEngine(); + const canvas = engine.getInputElement(); + if (pickResult?.pickedMesh) { + this.setPointerOverMesh(pickResult.pickedMesh, evt.pointerId, pickResult, evt); + if (!scene.doNotHandleCursors && canvas && this._pointerOverMesh) { + const actionManager = this._pointerOverMesh._getActionManagerForTrigger(); + if (actionManager && actionManager.hasPointerTriggers) { + canvas.style.cursor = actionManager.hoverCursor || scene.hoverCursor; + } + } + } + else { + this.setPointerOverMesh(null, evt.pointerId, pickResult, evt); + } + } + /** + * Use this method to simulate a pointer move on a mesh + * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay + * @param pickResult - pickingInfo of the object wished to simulate pointer event on + * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) + */ + simulatePointerMove(pickResult, pointerEventInit) { + const evt = new PointerEvent("pointermove", pointerEventInit); + evt.inputIndex = PointerInput.Move; + if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERMOVE)) { + return; + } + this._processPointerMove(pickResult, evt); + } + /** + * Use this method to simulate a pointer down on a mesh + * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay + * @param pickResult - pickingInfo of the object wished to simulate pointer event on + * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) + */ + simulatePointerDown(pickResult, pointerEventInit) { + const evt = new PointerEvent("pointerdown", pointerEventInit); + evt.inputIndex = evt.button + 2; + if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERDOWN)) { + return; + } + this._processPointerDown(pickResult, evt); + } + _processPointerDown(pickResult, evt) { + const scene = this._scene; + if (pickResult?.pickedMesh) { + this._pickedDownMesh = pickResult.pickedMesh; + const actionManager = pickResult.pickedMesh._getActionManagerForTrigger(); + if (actionManager) { + if (actionManager.hasPickTriggers) { + actionManager.processTrigger(5, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult)); + switch (evt.button) { + case 0: + actionManager.processTrigger(2, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult)); + break; + case 1: + actionManager.processTrigger(4, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult)); + break; + case 2: + actionManager.processTrigger(3, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult)); + break; + } + } + if (actionManager.hasSpecificTrigger(8)) { + window.setTimeout(() => { + const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, (mesh) => ((mesh.isPickable && + mesh.isVisible && + mesh.isReady() && + mesh.actionManager && + mesh.actionManager.hasSpecificTrigger(8) && + mesh === this._pickedDownMesh)), false, scene.cameraToUseForPointers); + if (pickResult?.pickedMesh && actionManager) { + if (this._activePointerIdsCount !== 0 && Date.now() - this._startingPointerTime > InputManager.LongPressDelay && !this._isPointerSwiping()) { + this._startingPointerTime = 0; + actionManager.processTrigger(8, ActionEvent.CreateNew(pickResult.pickedMesh, evt)); + } + } + }, InputManager.LongPressDelay); + } + } + } + else { + for (const step of scene._pointerDownStage) { + pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, false); + } + } + let pointerInfo; + const type = PointerEventTypes.POINTERDOWN; + if (pickResult) { + if (scene.onPointerDown) { + scene.onPointerDown(evt, pickResult, type); + } + pointerInfo = new PointerInfo(type, evt, pickResult); + this._setRayOnPointerInfo(pickResult, evt); + } + else { + pointerInfo = new PointerInfo(type, evt, null, this); + } + if (scene.onPointerObservable.hasObservers()) { + scene.onPointerObservable.notifyObservers(pointerInfo, type); + } + } + /** + * @internal + * @internals Boolean if delta for pointer exceeds drag movement threshold + */ + _isPointerSwiping() { + return this._isSwiping; + } + /** + * Use this method to simulate a pointer up on a mesh + * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay + * @param pickResult - pickingInfo of the object wished to simulate pointer event on + * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) + * @param doubleTap - indicates that the pointer up event should be considered as part of a double click (false by default) + */ + simulatePointerUp(pickResult, pointerEventInit, doubleTap) { + const evt = new PointerEvent("pointerup", pointerEventInit); + evt.inputIndex = PointerInput.Move; + const clickInfo = new _ClickInfo(); + if (doubleTap) { + clickInfo.doubleClick = true; + } + else { + clickInfo.singleClick = true; + } + if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERUP)) { + return; + } + this._processPointerUp(pickResult, evt, clickInfo); + } + _processPointerUp(pickResult, evt, clickInfo) { + const scene = this._scene; + if (pickResult?.pickedMesh) { + this._pickedUpMesh = pickResult.pickedMesh; + if (this._pickedDownMesh === this._pickedUpMesh) { + if (scene.onPointerPick) { + scene.onPointerPick(evt, pickResult); + } + if (clickInfo.singleClick && !clickInfo.ignore && scene.onPointerObservable.observers.length > this._cameraObserverCount) { + const type = PointerEventTypes.POINTERPICK; + const pi = new PointerInfo(type, evt, pickResult); + this._setRayOnPointerInfo(pickResult, evt); + scene.onPointerObservable.notifyObservers(pi, type); + } + } + const actionManager = pickResult.pickedMesh._getActionManagerForTrigger(); + if (actionManager && !clickInfo.ignore) { + actionManager.processTrigger(7, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); + if (!clickInfo.hasSwiped && clickInfo.singleClick) { + actionManager.processTrigger(1, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); + } + const doubleClickActionManager = pickResult.pickedMesh._getActionManagerForTrigger(6); + if (clickInfo.doubleClick && doubleClickActionManager) { + doubleClickActionManager.processTrigger(6, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); + } + } + } + else { + if (!clickInfo.ignore) { + for (const step of scene._pointerUpStage) { + pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, clickInfo.doubleClick); + } + } + } + if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) { + const pickedDownActionManager = this._pickedDownMesh._getActionManagerForTrigger(16); + if (pickedDownActionManager) { + pickedDownActionManager.processTrigger(16, ActionEvent.CreateNew(this._pickedDownMesh, evt)); + } + } + if (!clickInfo.ignore) { + const pi = new PointerInfo(PointerEventTypes.POINTERUP, evt, pickResult); + // Set ray on picking info. Note that this info will also be reused for the tap notification. + this._setRayOnPointerInfo(pickResult, evt); + scene.onPointerObservable.notifyObservers(pi, PointerEventTypes.POINTERUP); + if (scene.onPointerUp) { + scene.onPointerUp(evt, pickResult, PointerEventTypes.POINTERUP); + } + if (!clickInfo.hasSwiped && !this._skipPointerTap && !this._isMultiTouchGesture) { + let type = 0; + if (clickInfo.singleClick) { + type = PointerEventTypes.POINTERTAP; + } + else if (clickInfo.doubleClick) { + type = PointerEventTypes.POINTERDOUBLETAP; + } + if (type) { + const pi = new PointerInfo(type, evt, pickResult); + if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) { + scene.onPointerObservable.notifyObservers(pi, type); + } + } + } + } + } + /** + * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down) + * @param pointerId - defines the pointer id to use in a multi-touch scenario (0 by default) + * @returns true if the pointer was captured + */ + isPointerCaptured(pointerId = 0) { + return this._pointerCaptures[pointerId]; + } + /** + * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp + * @param attachUp - defines if you want to attach events to pointerup + * @param attachDown - defines if you want to attach events to pointerdown + * @param attachMove - defines if you want to attach events to pointermove + * @param elementToAttachTo - defines the target DOM element to attach to (will use the canvas by default) + */ + attachControl(attachUp = true, attachDown = true, attachMove = true, elementToAttachTo = null) { + const scene = this._scene; + const engine = scene.getEngine(); + if (!elementToAttachTo) { + elementToAttachTo = engine.getInputElement(); + } + if (this._alreadyAttached) { + this.detachControl(); + } + if (elementToAttachTo) { + this._alreadyAttachedTo = elementToAttachTo; + } + this._deviceSourceManager = new DeviceSourceManager(engine); + // Because this is only called from _initClickEvent, which is called in _onPointerUp, we'll use the pointerUpPredicate for the pick call + this._initActionManager = (act) => { + if (!this._meshPickProceed) { + const pickResult = scene.skipPointerUpPicking || (scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerUp) + ? null + : scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerUpPredicate, scene.pointerUpFastCheck, scene.cameraToUseForPointers, scene.pointerUpTrianglePredicate); + this._currentPickResult = pickResult; + if (pickResult) { + act = pickResult.hit && pickResult.pickedMesh ? pickResult.pickedMesh._getActionManagerForTrigger() : null; + } + this._meshPickProceed = true; + } + return act; + }; + this._delayedSimpleClick = (btn, clickInfo, cb) => { + // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different + if ((Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay && !this._doubleClickOccured) || btn !== this._previousButtonPressed) { + this._doubleClickOccured = false; + clickInfo.singleClick = true; + clickInfo.ignore = false; + // If we have a delayed click, we need to resolve the TAP event + if (this._delayedClicks[btn]) { + const evt = this._delayedClicks[btn].evt; + const type = PointerEventTypes.POINTERTAP; + const pi = new PointerInfo(type, evt, this._currentPickResult); + if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) { + scene.onPointerObservable.notifyObservers(pi, type); + } + // Clear the delayed click + this._delayedClicks[btn] = null; + } + } + }; + this._initClickEvent = (obs1, obs2, evt, cb) => { + const clickInfo = new _ClickInfo(); + this._currentPickResult = null; + let act = null; + let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || + obs2.hasSpecificMask(PointerEventTypes.POINTERPICK) || + obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || + obs2.hasSpecificMask(PointerEventTypes.POINTERTAP) || + obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || + obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP); + if (!checkPicking && AbstractActionManager) { + act = this._initActionManager(act, clickInfo); + if (act) { + checkPicking = act.hasPickTriggers; + } + } + let needToIgnoreNext = false; + // Never pick if this is a multi-touch gesture (e.g. pinch) + checkPicking = checkPicking && !this._isMultiTouchGesture; + if (checkPicking) { + const btn = evt.button; + clickInfo.hasSwiped = this._isPointerSwiping(); + if (!clickInfo.hasSwiped) { + let checkSingleClickImmediately = !InputManager.ExclusiveDoubleClickMode; + if (!checkSingleClickImmediately) { + checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP); + if (checkSingleClickImmediately && !AbstractActionManager.HasSpecificTrigger(6)) { + act = this._initActionManager(act, clickInfo); + if (act) { + checkSingleClickImmediately = !act.hasSpecificTrigger(6); + } + } + } + if (checkSingleClickImmediately) { + // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required + if (Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay || btn !== this._previousButtonPressed) { + clickInfo.singleClick = true; + cb(clickInfo, this._currentPickResult); + needToIgnoreNext = true; + } + } + // at least one double click is required to be check and exclusive double click is enabled + else { + // Queue up a delayed click, just in case this isn't a double click + // It should be noted that while this delayed event happens + // because of user input, it shouldn't be considered as a direct, + // timing-dependent result of that input. It's meant to just fire the TAP event + const delayedClick = { + evt: evt, + clickInfo: clickInfo, + timeoutId: window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), InputManager.DoubleClickDelay), + }; + this._delayedClicks[btn] = delayedClick; + } + let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP); + if (!checkDoubleClick && AbstractActionManager.HasSpecificTrigger(6)) { + act = this._initActionManager(act, clickInfo); + if (act) { + checkDoubleClick = act.hasSpecificTrigger(6); + } + } + if (checkDoubleClick) { + // two successive keys pressed are equal, double click delay is not over and double click has not just occurred + if (btn === this._previousButtonPressed && Date.now() - this._previousStartingPointerTime < InputManager.DoubleClickDelay && !this._doubleClickOccured) { + // pointer has not moved for 2 clicks, it's a double click + if (!clickInfo.hasSwiped && !this._isPointerSwiping()) { + this._previousStartingPointerTime = 0; + this._doubleClickOccured = true; + clickInfo.doubleClick = true; + clickInfo.ignore = false; + // If we have a pending click, we need to cancel it + if (InputManager.ExclusiveDoubleClickMode && this._delayedClicks[btn]) { + clearTimeout(this._delayedClicks[btn]?.timeoutId); + this._delayedClicks[btn] = null; + } + cb(clickInfo, this._currentPickResult); + } + // if the two successive clicks are too far, it's just two simple clicks + else { + this._doubleClickOccured = false; + this._previousStartingPointerTime = this._startingPointerTime; + this._previousStartingPointerPosition.x = this._startingPointerPosition.x; + this._previousStartingPointerPosition.y = this._startingPointerPosition.y; + this._previousButtonPressed = btn; + if (InputManager.ExclusiveDoubleClickMode) { + // If we have a delayed click, we need to cancel it + if (this._delayedClicks[btn]) { + clearTimeout(this._delayedClicks[btn]?.timeoutId); + this._delayedClicks[btn] = null; + } + cb(clickInfo, this._previousPickResult); + } + else { + cb(clickInfo, this._currentPickResult); + } + } + needToIgnoreNext = true; + } + // just the first click of the double has been raised + else { + this._doubleClickOccured = false; + this._previousStartingPointerTime = this._startingPointerTime; + this._previousStartingPointerPosition.x = this._startingPointerPosition.x; + this._previousStartingPointerPosition.y = this._startingPointerPosition.y; + this._previousButtonPressed = btn; + } + } + } + } + // Even if ExclusiveDoubleClickMode is true, we need to always handle + // up events at time of execution, unless we're explicitly ignoring them. + if (!needToIgnoreNext) { + cb(clickInfo, this._currentPickResult); + } + }; + this._onPointerMove = (evt) => { + this._updatePointerPosition(evt); + // Check if pointer leaves DragMovementThreshold range to determine if swipe is occurring + if (!this._isSwiping && this._swipeButtonPressed !== -1) { + this._isSwiping = + Math.abs(this._startingPointerPosition.x - this._pointerX) > InputManager.DragMovementThreshold || + Math.abs(this._startingPointerPosition.y - this._pointerY) > InputManager.DragMovementThreshold; + } + // Because there's a race condition between pointermove and pointerlockchange events, we need to + // verify that the pointer is still locked after each pointermove event. + if (engine.isPointerLock) { + engine._verifyPointerLock(); + } + // PreObservable support + if (this._checkPrePointerObservable(null, evt, evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE)) { + return; + } + if (!scene.cameraToUseForPointers && !scene.activeCamera) { + return; + } + if (scene.skipPointerMovePicking) { + this._processPointerMove(new PickingInfo(), evt); + return; + } + if (!scene.pointerMovePredicate) { + scene.pointerMovePredicate = (mesh) => mesh.isPickable && + mesh.isVisible && + mesh.isReady() && + mesh.isEnabled() && + (mesh.enablePointerMoveEvents || scene.constantlyUpdateMeshUnderPointer || mesh._getActionManagerForTrigger() !== null) && + (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0); + } + const pickResult = scene._registeredActions > 0 || scene.constantlyUpdateMeshUnderPointer ? this._pickMove(evt) : null; + this._processPointerMove(pickResult, evt); + }; + this._onPointerDown = (evt) => { + const freeIndex = this._activePointerIds.indexOf(-1); + if (freeIndex === -1) { + this._activePointerIds.push(evt.pointerId); + } + else { + this._activePointerIds[freeIndex] = evt.pointerId; + } + this._activePointerIdsCount++; + this._pickedDownMesh = null; + this._meshPickProceed = false; + // If ExclusiveDoubleClickMode is true, we need to resolve any pending delayed clicks + if (InputManager.ExclusiveDoubleClickMode) { + for (let i = 0; i < this._delayedClicks.length; i++) { + if (this._delayedClicks[i]) { + // If the button that was pressed is the same as the one that was released, + // just clear the timer. This will be resolved in the up event. + if (evt.button === i) { + clearTimeout(this._delayedClicks[i]?.timeoutId); + } + else { + // Otherwise, we need to resolve the click + const clickInfo = this._delayedClicks[i].clickInfo; + this._doubleClickOccured = false; + clickInfo.singleClick = true; + clickInfo.ignore = false; + const prevEvt = this._delayedClicks[i].evt; + const type = PointerEventTypes.POINTERTAP; + const pi = new PointerInfo(type, prevEvt, this._currentPickResult); + if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) { + scene.onPointerObservable.notifyObservers(pi, type); + } + // Clear the delayed click + this._delayedClicks[i] = null; + } + } + } + } + this._updatePointerPosition(evt); + if (this._swipeButtonPressed === -1) { + this._swipeButtonPressed = evt.button; + } + if (scene.preventDefaultOnPointerDown && elementToAttachTo) { + evt.preventDefault(); + elementToAttachTo.focus(); + } + this._startingPointerPosition.x = this._pointerX; + this._startingPointerPosition.y = this._pointerY; + this._startingPointerTime = Date.now(); + // PreObservable support + if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOWN)) { + return; + } + if (!scene.cameraToUseForPointers && !scene.activeCamera) { + return; + } + this._pointerCaptures[evt.pointerId] = true; + if (!scene.pointerDownPredicate) { + scene.pointerDownPredicate = (mesh) => { + return (mesh.isPickable && + mesh.isVisible && + mesh.isReady() && + mesh.isEnabled() && + (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0)); + }; + } + // Meshes + this._pickedDownMesh = null; + let pickResult; + if (scene.skipPointerDownPicking || (scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerDown)) { + pickResult = new PickingInfo(); + } + else { + pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerDownPredicate, scene.pointerDownFastCheck, scene.cameraToUseForPointers, scene.pointerDownTrianglePredicate); + } + this._processPointerDown(pickResult, evt); + }; + this._onPointerUp = (evt) => { + const pointerIdIndex = this._activePointerIds.indexOf(evt.pointerId); + if (pointerIdIndex === -1) { + // We are attaching the pointer up to windows because of a bug in FF + // If this pointerId is not paired with an _onPointerDown call, ignore it + return; + } + this._activePointerIds[pointerIdIndex] = -1; + this._activePointerIdsCount--; + this._pickedUpMesh = null; + this._meshPickProceed = false; + this._updatePointerPosition(evt); + if (scene.preventDefaultOnPointerUp && elementToAttachTo) { + evt.preventDefault(); + elementToAttachTo.focus(); + } + this._initClickEvent(scene.onPrePointerObservable, scene.onPointerObservable, evt, (clickInfo, pickResult) => { + // PreObservable support + if (scene.onPrePointerObservable.hasObservers()) { + this._skipPointerTap = false; + if (!clickInfo.ignore) { + if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)) { + // If we're skipping the next observable, we need to reset the swipe state before returning + if (this._swipeButtonPressed === evt.button) { + this._isSwiping = false; + this._swipeButtonPressed = -1; + } + // If we're going to skip the POINTERUP, we need to reset the pointer capture + if (evt.buttons === 0) { + this._pointerCaptures[evt.pointerId] = false; + } + return; + } + if (!clickInfo.hasSwiped) { + if (clickInfo.singleClick && scene.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) { + if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERTAP)) { + this._skipPointerTap = true; + } + } + if (clickInfo.doubleClick && scene.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) { + if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOUBLETAP)) { + this._skipPointerTap = true; + } + } + } + } + } + // There should be a pointer captured at this point so if there isn't we should reset and return + if (!this._pointerCaptures[evt.pointerId]) { + if (this._swipeButtonPressed === evt.button) { + this._isSwiping = false; + this._swipeButtonPressed = -1; + } + return; + } + // Only release capture if all buttons are released + if (evt.buttons === 0) { + this._pointerCaptures[evt.pointerId] = false; + } + if (!scene.cameraToUseForPointers && !scene.activeCamera) { + return; + } + if (!scene.pointerUpPredicate) { + scene.pointerUpPredicate = (mesh) => { + return (mesh.isPickable && + mesh.isVisible && + mesh.isReady() && + mesh.isEnabled() && + (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0)); + }; + } + // Meshes + if (!this._meshPickProceed && ((AbstractActionManager && AbstractActionManager.HasTriggers) || this._checkForPicking() || scene.onPointerUp)) { + this._initActionManager(null, clickInfo); + } + if (!pickResult) { + pickResult = this._currentPickResult; + } + this._processPointerUp(pickResult, evt, clickInfo); + this._previousPickResult = this._currentPickResult; + if (this._swipeButtonPressed === evt.button) { + this._isSwiping = false; + this._swipeButtonPressed = -1; + } + }); + }; + this._onKeyDown = (evt) => { + const type = KeyboardEventTypes.KEYDOWN; + if (scene.onPreKeyboardObservable.hasObservers()) { + const pi = new KeyboardInfoPre(type, evt); + scene.onPreKeyboardObservable.notifyObservers(pi, type); + if (pi.skipOnKeyboardObservable) { + return; + } + } + if (scene.onKeyboardObservable.hasObservers()) { + const pi = new KeyboardInfo(type, evt); + scene.onKeyboardObservable.notifyObservers(pi, type); + } + if (scene.actionManager) { + scene.actionManager.processTrigger(14, ActionEvent.CreateNewFromScene(scene, evt)); + } + }; + this._onKeyUp = (evt) => { + const type = KeyboardEventTypes.KEYUP; + if (scene.onPreKeyboardObservable.hasObservers()) { + const pi = new KeyboardInfoPre(type, evt); + scene.onPreKeyboardObservable.notifyObservers(pi, type); + if (pi.skipOnKeyboardObservable) { + return; + } + } + if (scene.onKeyboardObservable.hasObservers()) { + const pi = new KeyboardInfo(type, evt); + scene.onKeyboardObservable.notifyObservers(pi, type); + } + if (scene.actionManager) { + scene.actionManager.processTrigger(15, ActionEvent.CreateNewFromScene(scene, evt)); + } + }; + // If a device connects that we can handle, wire up the observable + this._deviceSourceManager.onDeviceConnectedObservable.add((deviceSource) => { + if (deviceSource.deviceType === DeviceType.Mouse) { + deviceSource.onInputChangedObservable.add((eventData) => { + this._originMouseEvent = eventData; + if (eventData.inputIndex === PointerInput.LeftClick || + eventData.inputIndex === PointerInput.MiddleClick || + eventData.inputIndex === PointerInput.RightClick || + eventData.inputIndex === PointerInput.BrowserBack || + eventData.inputIndex === PointerInput.BrowserForward) { + if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) { + this._onPointerDown(eventData); + } + else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) { + this._onPointerUp(eventData); + } + } + else if (attachMove) { + if (eventData.inputIndex === PointerInput.Move) { + this._onPointerMove(eventData); + } + else if (eventData.inputIndex === PointerInput.MouseWheelX || + eventData.inputIndex === PointerInput.MouseWheelY || + eventData.inputIndex === PointerInput.MouseWheelZ) { + this._onPointerMove(eventData); + } + } + }); + } + else if (deviceSource.deviceType === DeviceType.Touch) { + deviceSource.onInputChangedObservable.add((eventData) => { + if (eventData.inputIndex === PointerInput.LeftClick) { + if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) { + this._onPointerDown(eventData); + if (this._activePointerIdsCount > 1) { + this._isMultiTouchGesture = true; + } + } + else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) { + this._onPointerUp(eventData); + if (this._activePointerIdsCount === 0) { + this._isMultiTouchGesture = false; + } + } + } + if (attachMove && eventData.inputIndex === PointerInput.Move) { + this._onPointerMove(eventData); + } + }); + } + else if (deviceSource.deviceType === DeviceType.Keyboard) { + deviceSource.onInputChangedObservable.add((eventData) => { + if (eventData.type === "keydown") { + this._onKeyDown(eventData); + } + else if (eventData.type === "keyup") { + this._onKeyUp(eventData); + } + }); + } + }); + this._alreadyAttached = true; + } + /** + * Detaches all event handlers + */ + detachControl() { + if (this._alreadyAttached) { + this._deviceSourceManager.dispose(); + this._deviceSourceManager = null; + // Cursor + if (this._alreadyAttachedTo && !this._scene.doNotHandleCursors) { + this._alreadyAttachedTo.style.cursor = this._scene.defaultCursor; + } + this._alreadyAttached = false; + this._alreadyAttachedTo = null; + } + } + /** + * Set the value of meshUnderPointer for a given pointerId + * @param mesh - defines the mesh to use + * @param pointerId - optional pointer id when using more than one pointer. Defaults to 0 + * @param pickResult - optional pickingInfo data used to find mesh + * @param evt - optional pointer event + */ + setPointerOverMesh(mesh, pointerId = 0, pickResult, evt) { + if (this._meshUnderPointerId[pointerId] === mesh && (!mesh || !mesh._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting)) { + return; + } + const underPointerMesh = this._meshUnderPointerId[pointerId]; + let actionManager; + if (underPointerMesh) { + actionManager = underPointerMesh._getActionManagerForTrigger(10); + if (actionManager) { + actionManager.processTrigger(10, new ActionEvent(underPointerMesh, this._pointerX, this._pointerY, mesh, evt, { pointerId })); + } + } + if (mesh) { + this._meshUnderPointerId[pointerId] = mesh; + this._pointerOverMesh = mesh; + actionManager = mesh._getActionManagerForTrigger(9); + if (actionManager) { + actionManager.processTrigger(9, new ActionEvent(mesh, this._pointerX, this._pointerY, mesh, evt, { pointerId, pickResult })); + } + } + else { + delete this._meshUnderPointerId[pointerId]; + this._pointerOverMesh = null; + } + // if we reached this point, meshUnderPointerId has been updated. We need to notify observers that are registered. + if (this._scene.onMeshUnderPointerUpdatedObservable.hasObservers()) { + this._scene.onMeshUnderPointerUpdatedObservable.notifyObservers({ + mesh, + pointerId, + }); + } + } + /** + * Gets the mesh under the pointer + * @returns a Mesh or null if no mesh is under the pointer + */ + getPointerOverMesh() { + return this.meshUnderPointer; + } + /** + * @param mesh - Mesh to invalidate + * @internal + */ + _invalidateMesh(mesh) { + if (this._pointerOverMesh === mesh) { + this._pointerOverMesh = null; + } + if (this._pickedDownMesh === mesh) { + this._pickedDownMesh = null; + } + if (this._pickedUpMesh === mesh) { + this._pickedUpMesh = null; + } + for (const pointerId in this._meshUnderPointerId) { + if (this._meshUnderPointerId[pointerId] === mesh) { + delete this._meshUnderPointerId[pointerId]; + } + } + } +} +/** The distance in pixel that you have to move to prevent some events */ +InputManager.DragMovementThreshold = 10; // in pixels +/** Time in milliseconds to wait to raise long press events if button is still pressed */ +InputManager.LongPressDelay = 500; // in milliseconds +/** Time in milliseconds with two consecutive clicks will be considered as a double click */ +InputManager.DoubleClickDelay = 300; // in milliseconds +/** + * This flag will modify the behavior so that, when true, a click will happen if and only if + * another click DOES NOT happen within the DoubleClickDelay time frame. If another click does + * happen within that time frame, the first click will not fire an event and and a double click will occur. + */ +InputManager.ExclusiveDoubleClickMode = false; + +/** + * Helper class used to generate session unique ID + */ +class UniqueIdGenerator { + /** + * Gets an unique (relatively to the current scene) Id + */ + static get UniqueId() { + const result = this._UniqueIdCounter; + this._UniqueIdCounter++; + return result; + } +} +// Statics +UniqueIdGenerator._UniqueIdCounter = 1; + +/** Defines the cross module constantsused by lights to avoid circular dependencies */ +class LightConstants { + /** + * Sort function to order lights for rendering. + * @param a First Light object to compare to second. + * @param b Second Light object to compare first. + * @returns -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b. + */ + static CompareLightsPriority(a, b) { + //shadow-casting lights have priority over non-shadow-casting lights + //the renderPriority is a secondary sort criterion + if (a.shadowEnabled !== b.shadowEnabled) { + return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0); + } + return b.renderPriority - a.renderPriority; + } +} +/** + * Falloff Default: light is falling off following the material specification: + * standard material is using standard falloff whereas pbr material can request special falloff per materials. + */ +LightConstants.FALLOFF_DEFAULT = 0; +/** + * Falloff Physical: light is falling off following the inverse squared distance law. + */ +LightConstants.FALLOFF_PHYSICAL = 1; +/** + * Falloff gltf: light is falling off as described in the gltf moving to PBR document + * to enhance interoperability with other engines. + */ +LightConstants.FALLOFF_GLTF = 2; +/** + * Falloff Standard: light is falling off like in the standard material + * to enhance interoperability with other materials. + */ +LightConstants.FALLOFF_STANDARD = 3; +//lightmapMode Consts +/** + * If every light affecting the material is in this lightmapMode, + * material.lightmapTexture adds or multiplies + * (depends on material.useLightmapAsShadowmap) + * after every other light calculations. + */ +LightConstants.LIGHTMAP_DEFAULT = 0; +/** + * material.lightmapTexture as only diffuse lighting from this light + * adds only specular lighting from this light + * adds dynamic shadows + */ +LightConstants.LIGHTMAP_SPECULAR = 1; +/** + * material.lightmapTexture as only lighting + * no light calculation from this light + * only adds dynamic shadows from this light + */ +LightConstants.LIGHTMAP_SHADOWSONLY = 2; +// Intensity Mode Consts +/** + * Each light type uses the default quantity according to its type: + * point/spot lights use luminous intensity + * directional lights use illuminance + */ +LightConstants.INTENSITYMODE_AUTOMATIC = 0; +/** + * lumen (lm) + */ +LightConstants.INTENSITYMODE_LUMINOUSPOWER = 1; +/** + * candela (lm/sr) + */ +LightConstants.INTENSITYMODE_LUMINOUSINTENSITY = 2; +/** + * lux (lm/m^2) + */ +LightConstants.INTENSITYMODE_ILLUMINANCE = 3; +/** + * nit (cd/m^2) + */ +LightConstants.INTENSITYMODE_LUMINANCE = 4; +// Light types ids const. +/** + * Light type const id of the point light. + */ +LightConstants.LIGHTTYPEID_POINTLIGHT = 0; +/** + * Light type const id of the directional light. + */ +LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT = 1; +/** + * Light type const id of the spot light. + */ +LightConstants.LIGHTTYPEID_SPOTLIGHT = 2; +/** + * Light type const id of the hemispheric light. + */ +LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT = 3; +/** + * Light type const id of the area light. + */ +LightConstants.LIGHTTYPEID_RECT_AREALIGHT = 4; + +/** + * Class used to store configuration data associated with pointer picking + */ +class PointerPickingConfiguration { + constructor() { + /** + * Gets or sets a predicate used to select candidate meshes for a pointer down event + */ + this.pointerDownFastCheck = false; + /** + * Gets or sets a predicate used to select candidate meshes for a pointer up event + */ + this.pointerUpFastCheck = false; + /** + * Gets or sets a predicate used to select candidate meshes for a pointer move event + */ + this.pointerMoveFastCheck = false; + /** + * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer move event occurs. + */ + this.skipPointerMovePicking = false; + /** + * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer down event occurs. + */ + this.skipPointerDownPicking = false; + /** + * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer up event occurs. Off by default. + */ + this.skipPointerUpPicking = false; + } +} + +/** + * Define how the scene should favor performance over ease of use + */ +var ScenePerformancePriority; +(function (ScenePerformancePriority) { + /** Default mode. No change. Performance will be treated as less important than backward compatibility */ + ScenePerformancePriority[ScenePerformancePriority["BackwardCompatible"] = 0] = "BackwardCompatible"; + /** Some performance options will be turned on trying to strike a balance between perf and ease of use */ + ScenePerformancePriority[ScenePerformancePriority["Intermediate"] = 1] = "Intermediate"; + /** Performance will be top priority */ + ScenePerformancePriority[ScenePerformancePriority["Aggressive"] = 2] = "Aggressive"; +})(ScenePerformancePriority || (ScenePerformancePriority = {})); +/** + * Represents a scene to be rendered by the engine. + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene + */ +class Scene { + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Factory used to create the default material. + * @param scene The scene to create the material for + * @returns The default material + */ + static DefaultMaterialFactory(scene) { + throw _WarnImport("StandardMaterial"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Factory used to create the a collision coordinator. + * @returns The collision coordinator + */ + static CollisionCoordinatorFactory() { + throw _WarnImport("DefaultCollisionCoordinator"); + } + /** + * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0)) + */ + get clearColor() { + return this._clearColor; + } + set clearColor(value) { + if (value !== this._clearColor) { + this._clearColor = value; + this.onClearColorChangedObservable.notifyObservers(this._clearColor); + } + } + /** + * Default image processing configuration used either in the rendering + * Forward main pass or through the imageProcessingPostProcess if present. + * As in the majority of the scene they are the same (exception for multi camera), + * this is easier to reference from here than from all the materials and post process. + * + * No setter as we it is a shared configuration, you can set the values instead. + */ + get imageProcessingConfiguration() { + return this._imageProcessingConfiguration; + } + /** + * Gets or sets a value indicating how to treat performance relatively to ease of use and backward compatibility + */ + get performancePriority() { + return this._performancePriority; + } + set performancePriority(value) { + if (value === this._performancePriority) { + return; + } + this._performancePriority = value; + switch (value) { + case 0 /* ScenePerformancePriority.BackwardCompatible */: + this.skipFrustumClipping = false; + this._renderingManager.maintainStateBetweenFrames = false; + this.skipPointerMovePicking = false; + this.autoClear = true; + break; + case 1 /* ScenePerformancePriority.Intermediate */: + this.skipFrustumClipping = false; + this._renderingManager.maintainStateBetweenFrames = false; + this.skipPointerMovePicking = true; + this.autoClear = false; + break; + case 2 /* ScenePerformancePriority.Aggressive */: + this.skipFrustumClipping = true; + this._renderingManager.maintainStateBetweenFrames = true; + this.skipPointerMovePicking = true; + this.autoClear = false; + break; + } + this.onScenePerformancePriorityChangedObservable.notifyObservers(value); + } + /** + * Gets or sets a boolean indicating if all rendering must be done in wireframe + */ + set forceWireframe(value) { + if (this._forceWireframe === value) { + return; + } + this._forceWireframe = value; + this.markAllMaterialsAsDirty(16); + } + get forceWireframe() { + return this._forceWireframe; + } + /** + * Gets or sets a boolean indicating if we should skip the frustum clipping part of the active meshes selection + */ + set skipFrustumClipping(value) { + if (this._skipFrustumClipping === value) { + return; + } + this._skipFrustumClipping = value; + } + get skipFrustumClipping() { + return this._skipFrustumClipping; + } + /** + * Gets or sets a boolean indicating if all rendering must be done in point cloud + */ + set forcePointsCloud(value) { + if (this._forcePointsCloud === value) { + return; + } + this._forcePointsCloud = value; + this.markAllMaterialsAsDirty(16); + } + get forcePointsCloud() { + return this._forcePointsCloud; + } + /** + * Texture used in all pbr material as the reflection texture. + * As in the majority of the scene they are the same (exception for multi room and so on), + * this is easier to reference from here than from all the materials. + */ + get environmentTexture() { + return this._environmentTexture; + } + /** + * Texture used in all pbr material as the reflection texture. + * As in the majority of the scene they are the same (exception for multi room and so on), + * this is easier to set here than in all the materials. + */ + set environmentTexture(value) { + if (this._environmentTexture === value) { + return; + } + this._environmentTexture = value; + this.onEnvironmentTextureChangedObservable.notifyObservers(value); + this.markAllMaterialsAsDirty(1); + } + /** + * @returns all meshes, lights, cameras, transformNodes and bones + */ + getNodes() { + let nodes = []; + nodes = nodes.concat(this.meshes); + nodes = nodes.concat(this.lights); + nodes = nodes.concat(this.cameras); + nodes = nodes.concat(this.transformNodes); // dummies + this.skeletons.forEach((skeleton) => (nodes = nodes.concat(skeleton.bones))); + return nodes; + } + /** + * Gets or sets the animation properties override + */ + get animationPropertiesOverride() { + return this._animationPropertiesOverride; + } + set animationPropertiesOverride(value) { + this._animationPropertiesOverride = value; + } + /** Sets a function to be executed when this scene is disposed. */ + set onDispose(callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + } + /** Sets a function to be executed before rendering this scene */ + set beforeRender(callback) { + if (this._onBeforeRenderObserver) { + this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); + } + if (callback) { + this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); + } + } + /** Sets a function to be executed after rendering this scene */ + set afterRender(callback) { + if (this._onAfterRenderObserver) { + this.onAfterRenderObservable.remove(this._onAfterRenderObserver); + } + if (callback) { + this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); + } + } + /** Sets a function to be executed before rendering a camera*/ + set beforeCameraRender(callback) { + if (this._onBeforeCameraRenderObserver) { + this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); + } + this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback); + } + /** Sets a function to be executed after rendering a camera*/ + set afterCameraRender(callback) { + if (this._onAfterCameraRenderObserver) { + this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver); + } + this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback); + } + /** + * Gets or sets a predicate used to select candidate meshes for a pointer down event + */ + get pointerDownPredicate() { + return this._pointerPickingConfiguration.pointerDownPredicate; + } + set pointerDownPredicate(value) { + this._pointerPickingConfiguration.pointerDownPredicate = value; + } + /** + * Gets or sets a predicate used to select candidate meshes for a pointer up event + */ + get pointerUpPredicate() { + return this._pointerPickingConfiguration.pointerUpPredicate; + } + set pointerUpPredicate(value) { + this._pointerPickingConfiguration.pointerUpPredicate = value; + } + /** + * Gets or sets a predicate used to select candidate meshes for a pointer move event + */ + get pointerMovePredicate() { + return this._pointerPickingConfiguration.pointerMovePredicate; + } + set pointerMovePredicate(value) { + this._pointerPickingConfiguration.pointerMovePredicate = value; + } + /** + * Gets or sets a predicate used to select candidate meshes for a pointer down event + */ + get pointerDownFastCheck() { + return this._pointerPickingConfiguration.pointerDownFastCheck; + } + set pointerDownFastCheck(value) { + this._pointerPickingConfiguration.pointerDownFastCheck = value; + } + /** + * Gets or sets a predicate used to select candidate meshes for a pointer up event + */ + get pointerUpFastCheck() { + return this._pointerPickingConfiguration.pointerUpFastCheck; + } + set pointerUpFastCheck(value) { + this._pointerPickingConfiguration.pointerUpFastCheck = value; + } + /** + * Gets or sets a predicate used to select candidate meshes for a pointer move event + */ + get pointerMoveFastCheck() { + return this._pointerPickingConfiguration.pointerMoveFastCheck; + } + set pointerMoveFastCheck(value) { + this._pointerPickingConfiguration.pointerMoveFastCheck = value; + } + /** + * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer move event occurs. + */ + get skipPointerMovePicking() { + return this._pointerPickingConfiguration.skipPointerMovePicking; + } + set skipPointerMovePicking(value) { + this._pointerPickingConfiguration.skipPointerMovePicking = value; + } + /** + * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer down event occurs. + */ + get skipPointerDownPicking() { + return this._pointerPickingConfiguration.skipPointerDownPicking; + } + set skipPointerDownPicking(value) { + this._pointerPickingConfiguration.skipPointerDownPicking = value; + } + /** + * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer up event occurs. Off by default. + */ + get skipPointerUpPicking() { + return this._pointerPickingConfiguration.skipPointerUpPicking; + } + set skipPointerUpPicking(value) { + this._pointerPickingConfiguration.skipPointerUpPicking = value; + } + /** + * Gets the pointer coordinates without any translation (ie. straight out of the pointer event) + */ + get unTranslatedPointer() { + return this._inputManager.unTranslatedPointer; + } + /** + * Gets or sets the distance in pixel that you have to move to prevent some events. Default is 10 pixels + */ + static get DragMovementThreshold() { + return InputManager.DragMovementThreshold; + } + static set DragMovementThreshold(value) { + InputManager.DragMovementThreshold = value; + } + /** + * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 500 ms + */ + static get LongPressDelay() { + return InputManager.LongPressDelay; + } + static set LongPressDelay(value) { + InputManager.LongPressDelay = value; + } + /** + * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 300 ms + */ + static get DoubleClickDelay() { + return InputManager.DoubleClickDelay; + } + static set DoubleClickDelay(value) { + InputManager.DoubleClickDelay = value; + } + /** If you need to check double click without raising a single click at first click, enable this flag */ + static get ExclusiveDoubleClickMode() { + return InputManager.ExclusiveDoubleClickMode; + } + static set ExclusiveDoubleClickMode(value) { + InputManager.ExclusiveDoubleClickMode = value; + } + /** + * Bind the current view position to an effect. + * @param effect The effect to be bound + * @param variableName name of the shader variable that will hold the eye position + * @param isVector3 true to indicates that variableName is a Vector3 and not a Vector4 + * @returns the computed eye position + */ + bindEyePosition(effect, variableName = "vEyePosition", isVector3 = false) { + const eyePosition = this._forcedViewPosition + ? this._forcedViewPosition + : this._mirroredCameraPosition + ? this._mirroredCameraPosition + : (this.activeCamera?.globalPosition ?? Vector3.ZeroReadOnly); + const invertNormal = this.useRightHandedSystem === (this._mirroredCameraPosition != null); + TmpVectors.Vector4[0].set(eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1); + if (effect) { + if (isVector3) { + effect.setFloat3(variableName, TmpVectors.Vector4[0].x, TmpVectors.Vector4[0].y, TmpVectors.Vector4[0].z); + } + else { + effect.setVector4(variableName, TmpVectors.Vector4[0]); + } + } + return TmpVectors.Vector4[0]; + } + /** + * Update the scene ubo before it can be used in rendering processing + * @returns the scene UniformBuffer + */ + finalizeSceneUbo() { + const ubo = this.getSceneUniformBuffer(); + const eyePosition = this.bindEyePosition(null); + ubo.updateFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, eyePosition.w); + ubo.update(); + return ubo; + } + /** + * Gets or sets a boolean indicating if the scene must use right-handed coordinates system + */ + set useRightHandedSystem(value) { + if (this._useRightHandedSystem === value) { + return; + } + this._useRightHandedSystem = value; + this.markAllMaterialsAsDirty(16); + } + get useRightHandedSystem() { + return this._useRightHandedSystem; + } + /** + * Sets the step Id used by deterministic lock step + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep + * @param newStepId defines the step Id + */ + setStepId(newStepId) { + this._currentStepId = newStepId; + } + /** + * Gets the step Id used by deterministic lock step + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep + * @returns the step Id + */ + getStepId() { + return this._currentStepId; + } + /** + * Gets the internal step used by deterministic lock step + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep + * @returns the internal step + */ + getInternalStep() { + return this._currentInternalStep; + } + /** + * Gets or sets a boolean indicating if fog is enabled on this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog + * (Default is true) + */ + set fogEnabled(value) { + if (this._fogEnabled === value) { + return; + } + this._fogEnabled = value; + this.markAllMaterialsAsDirty(16); + } + get fogEnabled() { + return this._fogEnabled; + } + /** + * Gets or sets the fog mode to use + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog + * | mode | value | + * | --- | --- | + * | FOGMODE_NONE | 0 | + * | FOGMODE_EXP | 1 | + * | FOGMODE_EXP2 | 2 | + * | FOGMODE_LINEAR | 3 | + */ + set fogMode(value) { + if (this._fogMode === value) { + return; + } + this._fogMode = value; + this.markAllMaterialsAsDirty(16); + } + get fogMode() { + return this._fogMode; + } + /** + * Flag indicating that the frame buffer binding is handled by another component + */ + get prePass() { + return !!this.prePassRenderer && this.prePassRenderer.defaultRT.enabled; + } + /** + * Gets or sets a boolean indicating if shadows are enabled on this scene + */ + set shadowsEnabled(value) { + if (this._shadowsEnabled === value) { + return; + } + this._shadowsEnabled = value; + this.markAllMaterialsAsDirty(2); + } + get shadowsEnabled() { + return this._shadowsEnabled; + } + /** + * Gets or sets a boolean indicating if lights are enabled on this scene + */ + set lightsEnabled(value) { + if (this._lightsEnabled === value) { + return; + } + this._lightsEnabled = value; + this.markAllMaterialsAsDirty(2); + } + get lightsEnabled() { + return this._lightsEnabled; + } + /** All of the active cameras added to this scene. */ + get activeCameras() { + return this._activeCameras; + } + set activeCameras(cameras) { + if (this._unObserveActiveCameras) { + this._unObserveActiveCameras(); + this._unObserveActiveCameras = null; + } + if (cameras) { + this._unObserveActiveCameras = _ObserveArray(cameras, () => { + this.onActiveCamerasChanged.notifyObservers(this); + }); + } + this._activeCameras = cameras; + } + /** Gets or sets the current active camera */ + get activeCamera() { + return this._activeCamera; + } + set activeCamera(value) { + if (value === this._activeCamera) { + return; + } + this._activeCamera = value; + this.onActiveCameraChanged.notifyObservers(this); + } + /** @internal */ + get _hasDefaultMaterial() { + return Scene.DefaultMaterialFactory !== Scene._OriginalDefaultMaterialFactory; + } + /** The default material used on meshes when no material is affected */ + get defaultMaterial() { + if (!this._defaultMaterial) { + this._defaultMaterial = Scene.DefaultMaterialFactory(this); + } + return this._defaultMaterial; + } + /** The default material used on meshes when no material is affected */ + set defaultMaterial(value) { + this._defaultMaterial = value; + } + /** + * Gets or sets a boolean indicating if textures are enabled on this scene + */ + set texturesEnabled(value) { + if (this._texturesEnabled === value) { + return; + } + this._texturesEnabled = value; + this.markAllMaterialsAsDirty(1); + } + get texturesEnabled() { + return this._texturesEnabled; + } + /** + * Gets or sets the frame graph used to render the scene. If set, the scene will use the frame graph to render the scene instead of the default render loop. + */ + get frameGraph() { + return this._frameGraph; + } + set frameGraph(value) { + if (this._frameGraph) { + this._frameGraph = value; + if (!value) { + this.customRenderFunction = this._currentCustomRenderFunction; + } + return; + } + this._frameGraph = value; + if (value) { + this._currentCustomRenderFunction = this.customRenderFunction; + this.customRenderFunction = this._renderWithFrameGraph; + } + } + /** + * Gets or sets a boolean indicating if skeletons are enabled on this scene + */ + set skeletonsEnabled(value) { + if (this._skeletonsEnabled === value) { + return; + } + this._skeletonsEnabled = value; + this.markAllMaterialsAsDirty(8); + } + get skeletonsEnabled() { + return this._skeletonsEnabled; + } + /** @internal */ + get collisionCoordinator() { + if (!this._collisionCoordinator) { + this._collisionCoordinator = Scene.CollisionCoordinatorFactory(); + this._collisionCoordinator.init(this); + } + return this._collisionCoordinator; + } + /** + * Gets the scene's rendering manager + */ + get renderingManager() { + return this._renderingManager; + } + /** + * Gets the list of frustum planes (built from the active camera) + */ + get frustumPlanes() { + return this._frustumPlanes; + } + /** + * Registers the transient components if needed. + */ + _registerTransientComponents() { + // Register components that have been associated lately to the scene. + if (this._transientComponents.length > 0) { + for (const component of this._transientComponents) { + component.register(); + } + this._transientComponents.length = 0; + } + } + /** + * @internal + * Add a component to the scene. + * Note that the ccomponent could be registered on th next frame if this is called after + * the register component stage. + * @param component Defines the component to add to the scene + */ + _addComponent(component) { + this._components.push(component); + this._transientComponents.push(component); + const serializableComponent = component; + if (serializableComponent.addFromContainer && serializableComponent.serialize) { + this._serializableComponents.push(serializableComponent); + } + } + /** + * @internal + * Gets a component from the scene. + * @param name defines the name of the component to retrieve + * @returns the component or null if not present + */ + _getComponent(name) { + for (const component of this._components) { + if (component.name === name) { + return component; + } + } + return null; + } + /** + * Creates a new Scene + * @param engine defines the engine to use to render this scene + * @param options defines the scene options + */ + constructor(engine, options) { + /** @internal */ + this._inputManager = new InputManager(this); + /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */ + this.cameraToUseForPointers = null; + /** @internal */ + this._isScene = true; + /** @internal */ + this._blockEntityCollection = false; + /** + * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame + */ + this.autoClear = true; + /** + * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame + */ + this.autoClearDepthAndStencil = true; + this._clearColor = new Color4(0.2, 0.2, 0.3, 1.0); + /** + * Observable triggered when the performance priority is changed + */ + this.onClearColorChangedObservable = new Observable(); + /** + * Defines the color used to simulate the ambient color (Default is (0, 0, 0)) + */ + this.ambientColor = new Color3(0, 0, 0); + /** + * Intensity of the environment (i.e. all indirect lighting) in all pbr material. + * This dims or reinforces the indirect lighting overall (reflection and diffuse). + * As in the majority of the scene they are the same (exception for multi room and so on), + * this is easier to reference from here than from all the materials. + * Note that this is more of a debugging parameter and is not physically accurate. + * If you want to modify the intensity of the IBL texture, you should update iblIntensity instead. + */ + this.environmentIntensity = 1; + /** + * Overall intensity of the IBL texture. + * This value is multiplied with the reflectionTexture.level value to calculate the final IBL intensity. + */ + this.iblIntensity = 1; + this._performancePriority = 0 /* ScenePerformancePriority.BackwardCompatible */; + /** + * Observable triggered when the performance priority is changed + */ + this.onScenePerformancePriorityChangedObservable = new Observable(); + this._forceWireframe = false; + this._skipFrustumClipping = false; + this._forcePointsCloud = false; + /** + * Gets the list of root nodes (ie. nodes with no parent) + */ + this.rootNodes = []; + /** All of the cameras added to this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras + */ + this.cameras = []; + /** + * All of the lights added to this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + */ + this.lights = []; + /** + * All of the (abstract) meshes added to this scene + */ + this.meshes = []; + /** + * The list of skeletons added to the scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons + */ + this.skeletons = []; + /** + * All of the particle systems added to this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro + */ + this.particleSystems = []; + /** + * Gets a list of Animations associated with the scene + */ + this.animations = []; + /** + * All of the animation groups added to this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations + */ + this.animationGroups = []; + /** + * All of the multi-materials added to this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials + */ + this.multiMaterials = []; + /** + * All of the materials added to this scene + * In the context of a Scene, it is not supposed to be modified manually. + * Any addition or removal should be done using the addMaterial and removeMaterial Scene methods. + * Note also that the order of the Material within the array is not significant and might change. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction + */ + this.materials = []; + /** + * The list of morph target managers added to the scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph + */ + this.morphTargetManagers = []; + /** + * The list of geometries used in the scene. + */ + this.geometries = []; + /** + * All of the transform nodes added to this scene + * In the context of a Scene, it is not supposed to be modified manually. + * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods. + * Note also that the order of the TransformNode within the array is not significant and might change. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node + */ + this.transformNodes = []; + /** + * ActionManagers available on the scene. + * @deprecated + */ + this.actionManagers = []; + /** + * Textures to keep. + */ + this.textures = []; + /** @internal */ + this._environmentTexture = null; + /** + * The list of postprocesses added to the scene + */ + this.postProcesses = []; + /** + * The list of effect layers (highlights/glow) added to the scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/highlightLayer + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/glowLayer + */ + this.effectLayers = []; + /** + * The list of sounds used in the scene. + */ + this.sounds = null; + /** + * The list of layers (background and foreground) of the scene + */ + this.layers = []; + /** + * The list of lens flare system added to the scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare + */ + this.lensFlareSystems = []; + /** + * The list of procedural textures added to the scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures + */ + this.proceduralTextures = []; + /** + * Gets or sets a boolean indicating if animations are enabled + */ + this.animationsEnabled = true; + this._animationPropertiesOverride = null; + /** + * Gets or sets a boolean indicating if a constant deltatime has to be used + * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate + */ + this.useConstantAnimationDeltaTime = false; + /** + * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated + * Please note that it requires to run a ray cast through the scene on every frame + */ + this.constantlyUpdateMeshUnderPointer = false; + /** + * Defines the HTML cursor to use when hovering over interactive elements + */ + this.hoverCursor = "pointer"; + /** + * Defines the HTML default cursor to use (empty by default) + */ + this.defaultCursor = ""; + /** + * Defines whether cursors are handled by the scene. + */ + this.doNotHandleCursors = false; + /** + * This is used to call preventDefault() on pointer down + * in order to block unwanted artifacts like system double clicks + */ + this.preventDefaultOnPointerDown = true; + /** + * This is used to call preventDefault() on pointer up + * in order to block unwanted artifacts like system double clicks + */ + this.preventDefaultOnPointerUp = true; + // Metadata + /** + * Gets or sets user defined metadata + */ + this.metadata = null; + /** + * For internal use only. Please do not use. + */ + this.reservedDataStore = null; + /** + * Use this array to add regular expressions used to disable offline support for specific urls + */ + this.disableOfflineSupportExceptionRules = []; + /** + * An event triggered when the scene is disposed. + */ + this.onDisposeObservable = new Observable(); + this._onDisposeObserver = null; + /** + * An event triggered before rendering the scene (right after animations and physics) + */ + this.onBeforeRenderObservable = new Observable(); + this._onBeforeRenderObserver = null; + /** + * An event triggered after rendering the scene + */ + this.onAfterRenderObservable = new Observable(); + /** + * An event triggered after rendering the scene for an active camera (When scene.render is called this will be called after each camera) + * This is triggered for each "sub" camera in a Camera Rig unlike onAfterCameraRenderObservable + */ + this.onAfterRenderCameraObservable = new Observable(); + this._onAfterRenderObserver = null; + /** + * An event triggered before animating the scene + */ + this.onBeforeAnimationsObservable = new Observable(); + /** + * An event triggered after animations processing + */ + this.onAfterAnimationsObservable = new Observable(); + /** + * An event triggered before draw calls are ready to be sent + */ + this.onBeforeDrawPhaseObservable = new Observable(); + /** + * An event triggered after draw calls have been sent + */ + this.onAfterDrawPhaseObservable = new Observable(); + /** + * An event triggered when the scene is ready + */ + this.onReadyObservable = new Observable(); + /** + * An event triggered before rendering a camera + */ + this.onBeforeCameraRenderObservable = new Observable(); + this._onBeforeCameraRenderObserver = null; + /** + * An event triggered after rendering a camera + * This is triggered for the full rig Camera only unlike onAfterRenderCameraObservable + */ + this.onAfterCameraRenderObservable = new Observable(); + this._onAfterCameraRenderObserver = null; + /** + * An event triggered when active meshes evaluation is about to start + */ + this.onBeforeActiveMeshesEvaluationObservable = new Observable(); + /** + * An event triggered when active meshes evaluation is done + */ + this.onAfterActiveMeshesEvaluationObservable = new Observable(); + /** + * An event triggered when particles rendering is about to start + * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well) + */ + this.onBeforeParticlesRenderingObservable = new Observable(); + /** + * An event triggered when particles rendering is done + * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well) + */ + this.onAfterParticlesRenderingObservable = new Observable(); + /** + * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed + */ + this.onDataLoadedObservable = new Observable(); + /** + * An event triggered when a camera is created + */ + this.onNewCameraAddedObservable = new Observable(); + /** + * An event triggered when a camera is removed + */ + this.onCameraRemovedObservable = new Observable(); + /** + * An event triggered when a light is created + */ + this.onNewLightAddedObservable = new Observable(); + /** + * An event triggered when a light is removed + */ + this.onLightRemovedObservable = new Observable(); + /** + * An event triggered when a geometry is created + */ + this.onNewGeometryAddedObservable = new Observable(); + /** + * An event triggered when a geometry is removed + */ + this.onGeometryRemovedObservable = new Observable(); + /** + * An event triggered when a transform node is created + */ + this.onNewTransformNodeAddedObservable = new Observable(); + /** + * An event triggered when a transform node is removed + */ + this.onTransformNodeRemovedObservable = new Observable(); + /** + * An event triggered when a mesh is created + */ + this.onNewMeshAddedObservable = new Observable(); + /** + * An event triggered when a mesh is removed + */ + this.onMeshRemovedObservable = new Observable(); + /** + * An event triggered when a skeleton is created + */ + this.onNewSkeletonAddedObservable = new Observable(); + /** + * An event triggered when a skeleton is removed + */ + this.onSkeletonRemovedObservable = new Observable(); + /** + * An event triggered when a material is created + */ + this.onNewMaterialAddedObservable = new Observable(); + /** + * An event triggered when a multi material is created + */ + this.onNewMultiMaterialAddedObservable = new Observable(); + /** + * An event triggered when a material is removed + */ + this.onMaterialRemovedObservable = new Observable(); + /** + * An event triggered when a multi material is removed + */ + this.onMultiMaterialRemovedObservable = new Observable(); + /** + * An event triggered when a texture is created + */ + this.onNewTextureAddedObservable = new Observable(); + /** + * An event triggered when a texture is removed + */ + this.onTextureRemovedObservable = new Observable(); + /** + * An event triggered when render targets are about to be rendered + * Can happen multiple times per frame. + */ + this.onBeforeRenderTargetsRenderObservable = new Observable(); + /** + * An event triggered when render targets were rendered. + * Can happen multiple times per frame. + */ + this.onAfterRenderTargetsRenderObservable = new Observable(); + /** + * An event triggered before calculating deterministic simulation step + */ + this.onBeforeStepObservable = new Observable(); + /** + * An event triggered after calculating deterministic simulation step + */ + this.onAfterStepObservable = new Observable(); + /** + * An event triggered when the activeCamera property is updated + */ + this.onActiveCameraChanged = new Observable(); + /** + * An event triggered when the activeCameras property is updated + */ + this.onActiveCamerasChanged = new Observable(); + /** + * This Observable will be triggered before rendering each renderingGroup of each rendered camera. + * The RenderingGroupInfo class contains all the information about the context in which the observable is called + * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3) + */ + this.onBeforeRenderingGroupObservable = new Observable(); + /** + * This Observable will be triggered after rendering each renderingGroup of each rendered camera. + * The RenderingGroupInfo class contains all the information about the context in which the observable is called + * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3) + */ + this.onAfterRenderingGroupObservable = new Observable(); + /** + * This Observable will when a mesh has been imported into the scene. + */ + this.onMeshImportedObservable = new Observable(); + /** + * This Observable will when an animation file has been imported into the scene. + */ + this.onAnimationFileImportedObservable = new Observable(); + /** + * An event triggered when the environmentTexture is changed. + */ + this.onEnvironmentTextureChangedObservable = new Observable(); + /** + * An event triggered when the state of mesh under pointer, for a specific pointerId, changes. + */ + this.onMeshUnderPointerUpdatedObservable = new Observable(); + // Animations + /** @internal */ + this._registeredForLateAnimationBindings = new SmartArrayNoDuplicate(256); + // Pointers + this._pointerPickingConfiguration = new PointerPickingConfiguration(); + /** + * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance). + * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true + */ + this.onPrePointerObservable = new Observable(); + /** + * Observable event triggered each time an input event is received from the rendering canvas + */ + this.onPointerObservable = new Observable(); + // Keyboard + /** + * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl() + * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true + */ + this.onPreKeyboardObservable = new Observable(); + /** + * Observable event triggered each time an keyboard event is received from the hosting window + */ + this.onKeyboardObservable = new Observable(); + // Coordinates system + this._useRightHandedSystem = false; + // Deterministic lockstep + this._timeAccumulator = 0; + this._currentStepId = 0; + this._currentInternalStep = 0; + // Fog + this._fogEnabled = true; + this._fogMode = Scene.FOGMODE_NONE; + /** + * Gets or sets the fog color to use + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog + * (Default is Color3(0.2, 0.2, 0.3)) + */ + this.fogColor = new Color3(0.2, 0.2, 0.3); + /** + * Gets or sets the fog density to use + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog + * (Default is 0.1) + */ + this.fogDensity = 0.1; + /** + * Gets or sets the fog start distance to use + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog + * (Default is 0) + */ + this.fogStart = 0; + /** + * Gets or sets the fog end distance to use + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog + * (Default is 1000) + */ + this.fogEnd = 1000.0; + /** + * Flag indicating if we need to store previous matrices when rendering + */ + this.needsPreviousWorldMatrices = false; + // Lights + this._shadowsEnabled = true; + this._lightsEnabled = true; + this._unObserveActiveCameras = null; + // Textures + this._texturesEnabled = true; + this._frameGraph = null; + /** + * List of frame graphs associated with the scene + */ + this.frameGraphs = []; + // Physics + /** + * Gets or sets a boolean indicating if physic engines are enabled on this scene + */ + this.physicsEnabled = true; + // Particles + /** + * Gets or sets a boolean indicating if particles are enabled on this scene + */ + this.particlesEnabled = true; + // Sprites + /** + * Gets or sets a boolean indicating if sprites are enabled on this scene + */ + this.spritesEnabled = true; + // Skeletons + this._skeletonsEnabled = true; + // Lens flares + /** + * Gets or sets a boolean indicating if lens flares are enabled on this scene + */ + this.lensFlaresEnabled = true; + // Collisions + /** + * Gets or sets a boolean indicating if collisions are enabled on this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions + */ + this.collisionsEnabled = true; + /** + * Defines the gravity applied to this scene (used only for collisions) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions + */ + this.gravity = new Vector3(0, -9.807, 0); + // Postprocesses + /** + * Gets or sets a boolean indicating if postprocesses are enabled on this scene + */ + this.postProcessesEnabled = true; + // Customs render targets + /** + * Gets or sets a boolean indicating if render targets are enabled on this scene + */ + this.renderTargetsEnabled = true; + /** + * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes + * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com + */ + this.dumpNextRenderTargets = false; + /** + * The list of user defined render targets added to the scene + */ + this.customRenderTargets = []; + /** + * Gets the list of meshes imported to the scene through SceneLoader + */ + this.importedMeshesFiles = []; + // Probes + /** + * Gets or sets a boolean indicating if probes are enabled on this scene + */ + this.probesEnabled = true; + this._meshesForIntersections = new SmartArrayNoDuplicate(256); + // Procedural textures + /** + * Gets or sets a boolean indicating if procedural textures are enabled on this scene + */ + this.proceduralTexturesEnabled = true; + // Performance counters + this._totalVertices = new PerfCounter(); + /** @internal */ + this._activeIndices = new PerfCounter(); + /** @internal */ + this._activeParticles = new PerfCounter(); + /** @internal */ + this._activeBones = new PerfCounter(); + /** @internal */ + this._animationTime = 0; + /** + * Gets or sets a general scale for animation speed + * @see https://www.babylonjs-playground.com/#IBU2W7#3 + */ + this.animationTimeScale = 1; + this._renderId = 0; + this._frameId = 0; + this._executeWhenReadyTimeoutId = null; + this._intermediateRendering = false; + this._defaultFrameBufferCleared = false; + this._viewUpdateFlag = -1; + this._projectionUpdateFlag = -1; + /** @internal */ + this._toBeDisposed = new Array(256); + this._activeRequests = new Array(); + /** @internal */ + this._pendingData = new Array(); + this._isDisposed = false; + /** + * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered + * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound) + */ + this.dispatchAllSubMeshesOfActiveMeshes = false; + this._activeMeshes = new SmartArray(256); + this._processedMaterials = new SmartArray(256); + this._renderTargets = new SmartArrayNoDuplicate(256); + this._materialsRenderTargets = new SmartArrayNoDuplicate(256); + /** @internal */ + this._activeParticleSystems = new SmartArray(256); + this._activeSkeletons = new SmartArrayNoDuplicate(32); + this._softwareSkinnedMeshes = new SmartArrayNoDuplicate(32); + /** @internal */ + this._activeAnimatables = new Array(); + this._transformMatrix = Matrix.Zero(); + /** + * Gets or sets a boolean indicating if lights must be sorted by priority (off by default) + * This is useful if there are more lights that the maximum simulteanous authorized + */ + this.requireLightSorting = false; + /** + * @internal + * Backing store of defined scene components. + */ + this._components = []; + /** + * @internal + * Backing store of defined scene components. + */ + this._serializableComponents = []; + /** + * List of components to register on the next registration step. + */ + this._transientComponents = []; + /** + * @internal + * Defines the actions happening before camera updates. + */ + this._beforeCameraUpdateStage = Stage.Create(); + /** + * @internal + * Defines the actions happening before clear the canvas. + */ + this._beforeClearStage = Stage.Create(); + /** + * @internal + * Defines the actions happening before clear the canvas. + */ + this._beforeRenderTargetClearStage = Stage.Create(); + /** + * @internal + * Defines the actions when collecting render targets for the frame. + */ + this._gatherRenderTargetsStage = Stage.Create(); + /** + * @internal + * Defines the actions happening for one camera in the frame. + */ + this._gatherActiveCameraRenderTargetsStage = Stage.Create(); + /** + * @internal + * Defines the actions happening during the per mesh ready checks. + */ + this._isReadyForMeshStage = Stage.Create(); + /** + * @internal + * Defines the actions happening before evaluate active mesh checks. + */ + this._beforeEvaluateActiveMeshStage = Stage.Create(); + /** + * @internal + * Defines the actions happening during the evaluate sub mesh checks. + */ + this._evaluateSubMeshStage = Stage.Create(); + /** + * @internal + * Defines the actions happening during the active mesh stage. + */ + this._preActiveMeshStage = Stage.Create(); + /** + * @internal + * Defines the actions happening during the per camera render target step. + */ + this._cameraDrawRenderTargetStage = Stage.Create(); + /** + * @internal + * Defines the actions happening just before the active camera is drawing. + */ + this._beforeCameraDrawStage = Stage.Create(); + /** + * @internal + * Defines the actions happening just before a render target is drawing. + */ + this._beforeRenderTargetDrawStage = Stage.Create(); + /** + * @internal + * Defines the actions happening just before a rendering group is drawing. + */ + this._beforeRenderingGroupDrawStage = Stage.Create(); + /** + * @internal + * Defines the actions happening just before a mesh is drawing. + */ + this._beforeRenderingMeshStage = Stage.Create(); + /** + * @internal + * Defines the actions happening just after a mesh has been drawn. + */ + this._afterRenderingMeshStage = Stage.Create(); + /** + * @internal + * Defines the actions happening just after a rendering group has been drawn. + */ + this._afterRenderingGroupDrawStage = Stage.Create(); + /** + * @internal + * Defines the actions happening just after the active camera has been drawn. + */ + this._afterCameraDrawStage = Stage.Create(); + /** + * @internal + * Defines the actions happening just after the post processing + */ + this._afterCameraPostProcessStage = Stage.Create(); + /** + * @internal + * Defines the actions happening just after a render target has been drawn. + */ + this._afterRenderTargetDrawStage = Stage.Create(); + /** + * Defines the actions happening just after the post processing on a render target + */ + this._afterRenderTargetPostProcessStage = Stage.Create(); + /** + * @internal + * Defines the actions happening just after rendering all cameras and computing intersections. + */ + this._afterRenderStage = Stage.Create(); + /** + * @internal + * Defines the actions happening when a pointer move event happens. + */ + this._pointerMoveStage = Stage.Create(); + /** + * @internal + * Defines the actions happening when a pointer down event happens. + */ + this._pointerDownStage = Stage.Create(); + /** + * @internal + * Defines the actions happening when a pointer up event happens. + */ + this._pointerUpStage = Stage.Create(); + /** + * an optional map from Geometry Id to Geometry index in the 'geometries' array + */ + this._geometriesByUniqueId = null; + this._defaultMeshCandidates = { + data: [], + length: 0, + }; + this._defaultSubMeshCandidates = { + data: [], + length: 0, + }; + this._preventFreeActiveMeshesAndRenderingGroups = false; + /** @internal */ + this._activeMeshesFrozen = false; + /** @internal */ + this._activeMeshesFrozenButKeepClipping = false; + this._skipEvaluateActiveMeshesCompletely = false; + /** @internal */ + this._useCurrentFrameBuffer = false; + /** @internal */ + this._allowPostProcessClearColor = true; + /** + * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode + * @returns the frame time + */ + this.getDeterministicFrameTime = () => { + return this._engine.getTimeStep(); + }; + /** @internal */ + this._registeredActions = 0; + this._blockMaterialDirtyMechanism = false; + /** + * Internal perfCollector instance used for sharing between inspector and playground. + * Marked as protected to allow sharing between prototype extensions, but disallow access at toplevel. + */ + this._perfCollector = null; + this.activeCameras = []; + const fullOptions = { + useGeometryUniqueIdsMap: true, + useMaterialMeshMap: true, + useClonedMeshMap: true, + virtual: false, + ...options, + }; + engine = this._engine = engine || EngineStore.LastCreatedEngine; + if (fullOptions.virtual) { + engine._virtualScenes.push(this); + } + else { + EngineStore._LastCreatedScene = this; + engine.scenes.push(this); + } + this._uid = null; + this._renderingManager = new RenderingManager(this); + if (PostProcessManager) { + this.postProcessManager = new PostProcessManager(this); + } + if (IsWindowObjectExist()) { + this.attachControl(); + } + // Uniform Buffer + this._createUbo(); + // Default Image processing definition + if (ImageProcessingConfiguration) { + this._imageProcessingConfiguration = new ImageProcessingConfiguration(); + } + this.setDefaultCandidateProviders(); + if (fullOptions.useGeometryUniqueIdsMap) { + this._geometriesByUniqueId = {}; + } + this.useMaterialMeshMap = fullOptions.useMaterialMeshMap; + this.useClonedMeshMap = fullOptions.useClonedMeshMap; + if (!options || !options.virtual) { + engine.onNewSceneAddedObservable.notifyObservers(this); + } + } + /** + * Gets a string identifying the name of the class + * @returns "Scene" string + */ + getClassName() { + return "Scene"; + } + /** + * @internal + */ + _getDefaultMeshCandidates() { + this._defaultMeshCandidates.data = this.meshes; + this._defaultMeshCandidates.length = this.meshes.length; + return this._defaultMeshCandidates; + } + /** + * @internal + */ + _getDefaultSubMeshCandidates(mesh) { + this._defaultSubMeshCandidates.data = mesh.subMeshes; + this._defaultSubMeshCandidates.length = mesh.subMeshes.length; + return this._defaultSubMeshCandidates; + } + /** + * Sets the default candidate providers for the scene. + * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates + * and getCollidingSubMeshCandidates to their default function + */ + setDefaultCandidateProviders() { + this.getActiveMeshCandidates = () => this._getDefaultMeshCandidates(); + this.getActiveSubMeshCandidates = (mesh) => this._getDefaultSubMeshCandidates(mesh); + this.getIntersectingSubMeshCandidates = (mesh, localRay) => this._getDefaultSubMeshCandidates(mesh); + this.getCollidingSubMeshCandidates = (mesh, collider) => this._getDefaultSubMeshCandidates(mesh); + } + /** + * Gets the mesh that is currently under the pointer + */ + get meshUnderPointer() { + return this._inputManager.meshUnderPointer; + } + /** + * Gets or sets the current on-screen X position of the pointer + */ + get pointerX() { + return this._inputManager.pointerX; + } + set pointerX(value) { + this._inputManager.pointerX = value; + } + /** + * Gets or sets the current on-screen Y position of the pointer + */ + get pointerY() { + return this._inputManager.pointerY; + } + set pointerY(value) { + this._inputManager.pointerY = value; + } + /** + * Gets the cached material (ie. the latest rendered one) + * @returns the cached material + */ + getCachedMaterial() { + return this._cachedMaterial; + } + /** + * Gets the cached effect (ie. the latest rendered one) + * @returns the cached effect + */ + getCachedEffect() { + return this._cachedEffect; + } + /** + * Gets the cached visibility state (ie. the latest rendered one) + * @returns the cached visibility state + */ + getCachedVisibility() { + return this._cachedVisibility; + } + /** + * Gets a boolean indicating if the current material / effect / visibility must be bind again + * @param material defines the current material + * @param effect defines the current effect + * @param visibility defines the current visibility state + * @returns true if one parameter is not cached + */ + isCachedMaterialInvalid(material, effect, visibility = 1) { + return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility; + } + /** + * Gets the engine associated with the scene + * @returns an Engine + */ + getEngine() { + return this._engine; + } + /** + * Gets the total number of vertices rendered per frame + * @returns the total number of vertices rendered per frame + */ + getTotalVertices() { + return this._totalVertices.current; + } + /** + * Gets the performance counter for total vertices + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation + */ + get totalVerticesPerfCounter() { + return this._totalVertices; + } + /** + * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3) + * @returns the total number of active indices rendered per frame + */ + getActiveIndices() { + return this._activeIndices.current; + } + /** + * Gets the performance counter for active indices + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation + */ + get totalActiveIndicesPerfCounter() { + return this._activeIndices; + } + /** + * Gets the total number of active particles rendered per frame + * @returns the total number of active particles rendered per frame + */ + getActiveParticles() { + return this._activeParticles.current; + } + /** + * Gets the performance counter for active particles + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation + */ + get activeParticlesPerfCounter() { + return this._activeParticles; + } + /** + * Gets the total number of active bones rendered per frame + * @returns the total number of active bones rendered per frame + */ + getActiveBones() { + return this._activeBones.current; + } + /** + * Gets the performance counter for active bones + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation + */ + get activeBonesPerfCounter() { + return this._activeBones; + } + /** + * Gets the array of active meshes + * @returns an array of AbstractMesh + */ + getActiveMeshes() { + return this._activeMeshes; + } + /** + * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.) + * @returns a number + */ + getAnimationRatio() { + return this._animationRatio !== undefined ? this._animationRatio : 1; + } + /** + * Gets an unique Id for the current render phase + * @returns a number + */ + getRenderId() { + return this._renderId; + } + /** + * Gets an unique Id for the current frame + * @returns a number + */ + getFrameId() { + return this._frameId; + } + /** Call this function if you want to manually increment the render Id*/ + incrementRenderId() { + this._renderId++; + } + _createUbo() { + this.setSceneUniformBuffer(this.createSceneUniformBuffer()); + } + /** + * Use this method to simulate a pointer move on a mesh + * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay + * @param pickResult pickingInfo of the object wished to simulate pointer event on + * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) + * @returns the current scene + */ + simulatePointerMove(pickResult, pointerEventInit) { + this._inputManager.simulatePointerMove(pickResult, pointerEventInit); + return this; + } + /** + * Use this method to simulate a pointer down on a mesh + * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay + * @param pickResult pickingInfo of the object wished to simulate pointer event on + * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) + * @returns the current scene + */ + simulatePointerDown(pickResult, pointerEventInit) { + this._inputManager.simulatePointerDown(pickResult, pointerEventInit); + return this; + } + /** + * Use this method to simulate a pointer up on a mesh + * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay + * @param pickResult pickingInfo of the object wished to simulate pointer event on + * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) + * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default) + * @returns the current scene + */ + simulatePointerUp(pickResult, pointerEventInit, doubleTap) { + this._inputManager.simulatePointerUp(pickResult, pointerEventInit, doubleTap); + return this; + } + /** + * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down) + * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default) + * @returns true if the pointer was captured + */ + isPointerCaptured(pointerId = 0) { + return this._inputManager.isPointerCaptured(pointerId); + } + /** + * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp + * @param attachUp defines if you want to attach events to pointerup + * @param attachDown defines if you want to attach events to pointerdown + * @param attachMove defines if you want to attach events to pointermove + */ + attachControl(attachUp = true, attachDown = true, attachMove = true) { + this._inputManager.attachControl(attachUp, attachDown, attachMove); + } + /** Detaches all event handlers*/ + detachControl() { + this._inputManager.detachControl(); + } + /** + * This function will check if the scene can be rendered (textures are loaded, shaders are compiled) + * Delay loaded resources are not taking in account + * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: true) + * @returns true if all required resources are ready + */ + isReady(checkRenderTargets = true) { + if (this._isDisposed) { + return false; + } + let index; + const engine = this.getEngine(); + const currentRenderPassId = engine.currentRenderPassId; + engine.currentRenderPassId = this.activeCamera?.renderPassId ?? currentRenderPassId; + let isReady = true; + // Pending data + if (this._pendingData.length > 0) { + isReady = false; + } + // Ensures that the pre-pass renderer is enabled if it is to be enabled. + this.prePassRenderer?.update(); + // OIT + if (this.useOrderIndependentTransparency && this.depthPeelingRenderer) { + isReady && (isReady = this.depthPeelingRenderer.isReady()); + } + // Meshes + if (checkRenderTargets) { + this._processedMaterials.reset(); + this._materialsRenderTargets.reset(); + } + for (index = 0; index < this.meshes.length; index++) { + const mesh = this.meshes[index]; + if (!mesh.subMeshes || mesh.subMeshes.length === 0) { + continue; + } + // Do not stop at the first encountered "unready" object as we want to ensure + // all materials are starting off their compilation in parallel. + if (!mesh.isReady(true)) { + isReady = false; + continue; + } + const hardwareInstancedRendering = mesh.hasThinInstances || + mesh.getClassName() === "InstancedMesh" || + mesh.getClassName() === "InstancedLinesMesh" || + (engine.getCaps().instancedArrays && mesh.instances.length > 0); + // Is Ready For Mesh + for (const step of this._isReadyForMeshStage) { + if (!step.action(mesh, hardwareInstancedRendering)) { + isReady = false; + } + } + if (!checkRenderTargets) { + continue; + } + const mat = mesh.material || this.defaultMaterial; + if (mat) { + if (mat._storeEffectOnSubMeshes) { + for (const subMesh of mesh.subMeshes) { + const material = subMesh.getMaterial(); + if (material && material.hasRenderTargetTextures && material.getRenderTargetTextures != null) { + if (this._processedMaterials.indexOf(material) === -1) { + this._processedMaterials.push(material); + this._materialsRenderTargets.concatWithNoDuplicate(material.getRenderTargetTextures()); + } + } + } + } + else { + if (mat.hasRenderTargetTextures && mat.getRenderTargetTextures != null) { + if (this._processedMaterials.indexOf(mat) === -1) { + this._processedMaterials.push(mat); + this._materialsRenderTargets.concatWithNoDuplicate(mat.getRenderTargetTextures()); + } + } + } + } + } + // Render targets + if (checkRenderTargets) { + for (index = 0; index < this._materialsRenderTargets.length; ++index) { + const rtt = this._materialsRenderTargets.data[index]; + if (!rtt.isReadyForRendering()) { + isReady = false; + } + } + } + // Geometries + for (index = 0; index < this.geometries.length; index++) { + const geometry = this.geometries[index]; + if (geometry.delayLoadState === 2) { + isReady = false; + } + } + // Post-processes + if (this.activeCameras && this.activeCameras.length > 0) { + for (const camera of this.activeCameras) { + if (!camera.isReady(true)) { + isReady = false; + } + } + } + else if (this.activeCamera) { + if (!this.activeCamera.isReady(true)) { + isReady = false; + } + } + // Particles + for (const particleSystem of this.particleSystems) { + if (!particleSystem.isReady()) { + isReady = false; + } + } + // Layers + if (this.layers) { + for (const layer of this.layers) { + if (!layer.isReady()) { + isReady = false; + } + } + } + // Effect layers + if (this.effectLayers) { + for (const effectLayer of this.effectLayers) { + if (!effectLayer.isLayerReady()) { + isReady = false; + } + } + } + // Effects + if (!engine.areAllEffectsReady()) { + isReady = false; + } + engine.currentRenderPassId = currentRenderPassId; + return isReady; + } + /** Resets all cached information relative to material (including effect and visibility) */ + resetCachedMaterial() { + this._cachedMaterial = null; + this._cachedEffect = null; + this._cachedVisibility = null; + } + /** + * Registers a function to be called before every frame render + * @param func defines the function to register + */ + registerBeforeRender(func) { + this.onBeforeRenderObservable.add(func); + } + /** + * Unregisters a function called before every frame render + * @param func defines the function to unregister + */ + unregisterBeforeRender(func) { + this.onBeforeRenderObservable.removeCallback(func); + } + /** + * Registers a function to be called after every frame render + * @param func defines the function to register + */ + registerAfterRender(func) { + this.onAfterRenderObservable.add(func); + } + /** + * Unregisters a function called after every frame render + * @param func defines the function to unregister + */ + unregisterAfterRender(func) { + this.onAfterRenderObservable.removeCallback(func); + } + _executeOnceBeforeRender(func) { + const execFunc = () => { + func(); + setTimeout(() => { + this.unregisterBeforeRender(execFunc); + }); + }; + this.registerBeforeRender(execFunc); + } + /** + * The provided function will run before render once and will be disposed afterwards. + * A timeout delay can be provided so that the function will be executed in N ms. + * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed. + * @param func The function to be executed. + * @param timeout optional delay in ms + */ + executeOnceBeforeRender(func, timeout) { + if (timeout !== undefined) { + setTimeout(() => { + this._executeOnceBeforeRender(func); + }, timeout); + } + else { + this._executeOnceBeforeRender(func); + } + } + /** + * This function can help adding any object to the list of data awaited to be ready in order to check for a complete scene loading. + * @param data defines the object to wait for + */ + addPendingData(data) { + this._pendingData.push(data); + } + /** + * Remove a pending data from the loading list which has previously been added with addPendingData. + * @param data defines the object to remove from the pending list + */ + removePendingData(data) { + const wasLoading = this.isLoading; + const index = this._pendingData.indexOf(data); + if (index !== -1) { + this._pendingData.splice(index, 1); + } + if (wasLoading && !this.isLoading) { + this.onDataLoadedObservable.notifyObservers(this); + } + } + /** + * Returns the number of items waiting to be loaded + * @returns the number of items waiting to be loaded + */ + getWaitingItemsCount() { + return this._pendingData.length; + } + /** + * Returns a boolean indicating if the scene is still loading data + */ + get isLoading() { + return this._pendingData.length > 0; + } + /** + * Registers a function to be executed when the scene is ready + * @param func - the function to be executed + * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: false) + */ + executeWhenReady(func, checkRenderTargets = false) { + this.onReadyObservable.addOnce(func); + if (this._executeWhenReadyTimeoutId !== null) { + return; + } + this._checkIsReady(checkRenderTargets); + } + /** + * Returns a promise that resolves when the scene is ready + * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: false) + * @returns A promise that resolves when the scene is ready + */ + whenReadyAsync(checkRenderTargets = false) { + return new Promise((resolve) => { + this.executeWhenReady(() => { + resolve(); + }, checkRenderTargets); + }); + } + /** + * @internal + */ + _checkIsReady(checkRenderTargets = false) { + this._registerTransientComponents(); + if (this.isReady(checkRenderTargets)) { + this.onReadyObservable.notifyObservers(this); + this.onReadyObservable.clear(); + this._executeWhenReadyTimeoutId = null; + return; + } + if (this._isDisposed) { + this.onReadyObservable.clear(); + this._executeWhenReadyTimeoutId = null; + return; + } + this._executeWhenReadyTimeoutId = setTimeout(() => { + // Ensure materials effects are checked outside render loops + this.incrementRenderId(); + this._checkIsReady(checkRenderTargets); + }, 100); + } + /** + * Gets all animatable attached to the scene + */ + get animatables() { + return this._activeAnimatables; + } + /** + * Resets the last animation time frame. + * Useful to override when animations start running when loading a scene for the first time. + */ + resetLastAnimationTimeFrame() { + this._animationTimeLast = PrecisionDate.Now; + } + // Matrix + /** + * Gets the current view matrix + * @returns a Matrix + */ + getViewMatrix() { + return this._viewMatrix; + } + /** + * Gets the current projection matrix + * @returns a Matrix + */ + getProjectionMatrix() { + return this._projectionMatrix; + } + /** + * Gets the current transform matrix + * @returns a Matrix made of View * Projection + */ + getTransformMatrix() { + return this._transformMatrix; + } + /** + * Sets the current transform matrix + * @param viewL defines the View matrix to use + * @param projectionL defines the Projection matrix to use + * @param viewR defines the right View matrix to use (if provided) + * @param projectionR defines the right Projection matrix to use (if provided) + */ + setTransformMatrix(viewL, projectionL, viewR, projectionR) { + // clear the multiviewSceneUbo if no viewR and projectionR are defined + if (!viewR && !projectionR && this._multiviewSceneUbo) { + this._multiviewSceneUbo.dispose(); + this._multiviewSceneUbo = null; + } + if (this._viewUpdateFlag === viewL.updateFlag && this._projectionUpdateFlag === projectionL.updateFlag) { + return; + } + this._viewUpdateFlag = viewL.updateFlag; + this._projectionUpdateFlag = projectionL.updateFlag; + this._viewMatrix = viewL; + this._projectionMatrix = projectionL; + this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); + // Update frustum + if (!this._frustumPlanes) { + this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix); + } + else { + Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes); + } + if (this._multiviewSceneUbo && this._multiviewSceneUbo.useUbo) { + this._updateMultiviewUbo(viewR, projectionR); + } + else if (this._sceneUbo.useUbo) { + this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix); + this._sceneUbo.updateMatrix("view", this._viewMatrix); + this._sceneUbo.updateMatrix("projection", this._projectionMatrix); + } + } + /** + * Gets the uniform buffer used to store scene data + * @returns a UniformBuffer + */ + getSceneUniformBuffer() { + return this._multiviewSceneUbo ? this._multiviewSceneUbo : this._sceneUbo; + } + /** + * Creates a scene UBO + * @param name name of the uniform buffer (optional, for debugging purpose only) + * @returns a new ubo + */ + createSceneUniformBuffer(name) { + const sceneUbo = new UniformBuffer(this._engine, undefined, false, name ?? "scene"); + sceneUbo.addUniform("viewProjection", 16); + sceneUbo.addUniform("view", 16); + sceneUbo.addUniform("projection", 16); + sceneUbo.addUniform("vEyePosition", 4); + return sceneUbo; + } + /** + * Sets the scene ubo + * @param ubo the ubo to set for the scene + */ + setSceneUniformBuffer(ubo) { + this._sceneUbo = ubo; + this._viewUpdateFlag = -1; + this._projectionUpdateFlag = -1; + } + /** + * Gets an unique (relatively to the current scene) Id + * @returns an unique number for the scene + */ + getUniqueId() { + return UniqueIdGenerator.UniqueId; + } + /** + * Add a mesh to the list of scene's meshes + * @param newMesh defines the mesh to add + * @param recursive if all child meshes should also be added to the scene + */ + addMesh(newMesh, recursive = false) { + if (this._blockEntityCollection) { + return; + } + this.meshes.push(newMesh); + newMesh._resyncLightSources(); + if (!newMesh.parent) { + newMesh._addToSceneRootNodes(); + } + Tools.SetImmediate(() => { + this.onNewMeshAddedObservable.notifyObservers(newMesh); + }); + if (recursive) { + newMesh.getChildMeshes().forEach((m) => { + this.addMesh(m); + }); + } + } + /** + * Remove a mesh for the list of scene's meshes + * @param toRemove defines the mesh to remove + * @param recursive if all child meshes should also be removed from the scene + * @returns the index where the mesh was in the mesh list + */ + removeMesh(toRemove, recursive = false) { + const index = this.meshes.indexOf(toRemove); + if (index !== -1) { + // Remove from the scene if the mesh found + this.meshes.splice(index, 1); + if (!toRemove.parent) { + toRemove._removeFromSceneRootNodes(); + } + } + this._inputManager._invalidateMesh(toRemove); + this.onMeshRemovedObservable.notifyObservers(toRemove); + if (recursive) { + toRemove.getChildMeshes().forEach((m) => { + this.removeMesh(m); + }); + } + return index; + } + /** + * Add a transform node to the list of scene's transform nodes + * @param newTransformNode defines the transform node to add + */ + addTransformNode(newTransformNode) { + if (this._blockEntityCollection) { + return; + } + if (newTransformNode.getScene() === this && newTransformNode._indexInSceneTransformNodesArray !== -1) { + // Already there? + return; + } + newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length; + this.transformNodes.push(newTransformNode); + if (!newTransformNode.parent) { + newTransformNode._addToSceneRootNodes(); + } + this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode); + } + /** + * Remove a transform node for the list of scene's transform nodes + * @param toRemove defines the transform node to remove + * @returns the index where the transform node was in the transform node list + */ + removeTransformNode(toRemove) { + const index = toRemove._indexInSceneTransformNodesArray; + if (index !== -1) { + if (index !== this.transformNodes.length - 1) { + const lastNode = this.transformNodes[this.transformNodes.length - 1]; + this.transformNodes[index] = lastNode; + lastNode._indexInSceneTransformNodesArray = index; + } + toRemove._indexInSceneTransformNodesArray = -1; + this.transformNodes.pop(); + if (!toRemove.parent) { + toRemove._removeFromSceneRootNodes(); + } + } + this.onTransformNodeRemovedObservable.notifyObservers(toRemove); + return index; + } + /** + * Remove a skeleton for the list of scene's skeletons + * @param toRemove defines the skeleton to remove + * @returns the index where the skeleton was in the skeleton list + */ + removeSkeleton(toRemove) { + const index = this.skeletons.indexOf(toRemove); + if (index !== -1) { + // Remove from the scene if found + this.skeletons.splice(index, 1); + this.onSkeletonRemovedObservable.notifyObservers(toRemove); + // Clean active container + this._executeActiveContainerCleanup(this._activeSkeletons); + } + return index; + } + /** + * Remove a morph target for the list of scene's morph targets + * @param toRemove defines the morph target to remove + * @returns the index where the morph target was in the morph target list + */ + removeMorphTargetManager(toRemove) { + const index = this.morphTargetManagers.indexOf(toRemove); + if (index !== -1) { + // Remove from the scene if found + this.morphTargetManagers.splice(index, 1); + } + return index; + } + /** + * Remove a light for the list of scene's lights + * @param toRemove defines the light to remove + * @returns the index where the light was in the light list + */ + removeLight(toRemove) { + const index = this.lights.indexOf(toRemove); + if (index !== -1) { + // Remove from meshes + for (const mesh of this.meshes) { + mesh._removeLightSource(toRemove, false); + } + // Remove from the scene if mesh found + this.lights.splice(index, 1); + this.sortLightsByPriority(); + if (!toRemove.parent) { + toRemove._removeFromSceneRootNodes(); + } + } + this.onLightRemovedObservable.notifyObservers(toRemove); + return index; + } + /** + * Remove a camera for the list of scene's cameras + * @param toRemove defines the camera to remove + * @returns the index where the camera was in the camera list + */ + removeCamera(toRemove) { + const index = this.cameras.indexOf(toRemove); + if (index !== -1) { + // Remove from the scene if mesh found + this.cameras.splice(index, 1); + if (!toRemove.parent) { + toRemove._removeFromSceneRootNodes(); + } + } + // Remove from activeCameras + if (this.activeCameras) { + const index2 = this.activeCameras.indexOf(toRemove); + if (index2 !== -1) { + // Remove from the scene if mesh found + this.activeCameras.splice(index2, 1); + } + } + // Reset the activeCamera + if (this.activeCamera === toRemove) { + if (this.cameras.length > 0) { + this.activeCamera = this.cameras[0]; + } + else { + this.activeCamera = null; + } + } + this.onCameraRemovedObservable.notifyObservers(toRemove); + return index; + } + /** + * Remove a particle system for the list of scene's particle systems + * @param toRemove defines the particle system to remove + * @returns the index where the particle system was in the particle system list + */ + removeParticleSystem(toRemove) { + const index = this.particleSystems.indexOf(toRemove); + if (index !== -1) { + this.particleSystems.splice(index, 1); + // Clean active container + this._executeActiveContainerCleanup(this._activeParticleSystems); + } + return index; + } + /** + * Remove a animation for the list of scene's animations + * @param toRemove defines the animation to remove + * @returns the index where the animation was in the animation list + */ + removeAnimation(toRemove) { + const index = this.animations.indexOf(toRemove); + if (index !== -1) { + this.animations.splice(index, 1); + } + return index; + } + /** + * Will stop the animation of the given target + * @param target - the target + * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty) + * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty) + */ + stopAnimation(target, animationName, targetMask) { + // Do nothing as code will be provided by animation component + } + /** + * Removes the given animation group from this scene. + * @param toRemove The animation group to remove + * @returns The index of the removed animation group + */ + removeAnimationGroup(toRemove) { + const index = this.animationGroups.indexOf(toRemove); + if (index !== -1) { + this.animationGroups.splice(index, 1); + } + return index; + } + /** + * Removes the given multi-material from this scene. + * @param toRemove The multi-material to remove + * @returns The index of the removed multi-material + */ + removeMultiMaterial(toRemove) { + const index = this.multiMaterials.indexOf(toRemove); + if (index !== -1) { + this.multiMaterials.splice(index, 1); + } + this.onMultiMaterialRemovedObservable.notifyObservers(toRemove); + return index; + } + /** + * Removes the given material from this scene. + * @param toRemove The material to remove + * @returns The index of the removed material + */ + removeMaterial(toRemove) { + const index = toRemove._indexInSceneMaterialArray; + if (index !== -1 && index < this.materials.length) { + if (index !== this.materials.length - 1) { + const lastMaterial = this.materials[this.materials.length - 1]; + this.materials[index] = lastMaterial; + lastMaterial._indexInSceneMaterialArray = index; + } + toRemove._indexInSceneMaterialArray = -1; + this.materials.pop(); + } + this.onMaterialRemovedObservable.notifyObservers(toRemove); + return index; + } + /** + * Removes the given action manager from this scene. + * @deprecated + * @param toRemove The action manager to remove + * @returns The index of the removed action manager + */ + removeActionManager(toRemove) { + const index = this.actionManagers.indexOf(toRemove); + if (index !== -1) { + this.actionManagers.splice(index, 1); + } + return index; + } + /** + * Removes the given texture from this scene. + * @param toRemove The texture to remove + * @returns The index of the removed texture + */ + removeTexture(toRemove) { + const index = this.textures.indexOf(toRemove); + if (index !== -1) { + this.textures.splice(index, 1); + } + this.onTextureRemovedObservable.notifyObservers(toRemove); + return index; + } + /** + * Adds the given light to this scene + * @param newLight The light to add + */ + addLight(newLight) { + if (this._blockEntityCollection) { + return; + } + this.lights.push(newLight); + this.sortLightsByPriority(); + if (!newLight.parent) { + newLight._addToSceneRootNodes(); + } + // Add light to all meshes (To support if the light is removed and then re-added) + for (const mesh of this.meshes) { + if (mesh.lightSources.indexOf(newLight) === -1) { + mesh.lightSources.push(newLight); + mesh._resyncLightSources(); + } + } + Tools.SetImmediate(() => { + this.onNewLightAddedObservable.notifyObservers(newLight); + }); + } + /** + * Sorts the list list based on light priorities + */ + sortLightsByPriority() { + if (this.requireLightSorting) { + this.lights.sort(LightConstants.CompareLightsPriority); + } + } + /** + * Adds the given camera to this scene + * @param newCamera The camera to add + */ + addCamera(newCamera) { + if (this._blockEntityCollection) { + return; + } + this.cameras.push(newCamera); + Tools.SetImmediate(() => { + this.onNewCameraAddedObservable.notifyObservers(newCamera); + }); + if (!newCamera.parent) { + newCamera._addToSceneRootNodes(); + } + } + /** + * Adds the given skeleton to this scene + * @param newSkeleton The skeleton to add + */ + addSkeleton(newSkeleton) { + if (this._blockEntityCollection) { + return; + } + this.skeletons.push(newSkeleton); + Tools.SetImmediate(() => { + this.onNewSkeletonAddedObservable.notifyObservers(newSkeleton); + }); + } + /** + * Adds the given particle system to this scene + * @param newParticleSystem The particle system to add + */ + addParticleSystem(newParticleSystem) { + if (this._blockEntityCollection) { + return; + } + this.particleSystems.push(newParticleSystem); + } + /** + * Adds the given animation to this scene + * @param newAnimation The animation to add + */ + addAnimation(newAnimation) { + if (this._blockEntityCollection) { + return; + } + this.animations.push(newAnimation); + } + /** + * Adds the given animation group to this scene. + * @param newAnimationGroup The animation group to add + */ + addAnimationGroup(newAnimationGroup) { + if (this._blockEntityCollection) { + return; + } + this.animationGroups.push(newAnimationGroup); + } + /** + * Adds the given multi-material to this scene + * @param newMultiMaterial The multi-material to add + */ + addMultiMaterial(newMultiMaterial) { + if (this._blockEntityCollection) { + return; + } + this.multiMaterials.push(newMultiMaterial); + Tools.SetImmediate(() => { + this.onNewMultiMaterialAddedObservable.notifyObservers(newMultiMaterial); + }); + } + /** + * Adds the given material to this scene + * @param newMaterial The material to add + */ + addMaterial(newMaterial) { + if (this._blockEntityCollection) { + return; + } + if (newMaterial.getScene() === this && newMaterial._indexInSceneMaterialArray !== -1) { + // Already there?? + return; + } + newMaterial._indexInSceneMaterialArray = this.materials.length; + this.materials.push(newMaterial); + Tools.SetImmediate(() => { + this.onNewMaterialAddedObservable.notifyObservers(newMaterial); + }); + } + /** + * Adds the given morph target to this scene + * @param newMorphTargetManager The morph target to add + */ + addMorphTargetManager(newMorphTargetManager) { + if (this._blockEntityCollection) { + return; + } + this.morphTargetManagers.push(newMorphTargetManager); + } + /** + * Adds the given geometry to this scene + * @param newGeometry The geometry to add + */ + addGeometry(newGeometry) { + if (this._blockEntityCollection) { + return; + } + if (this._geometriesByUniqueId) { + this._geometriesByUniqueId[newGeometry.uniqueId] = this.geometries.length; + } + this.geometries.push(newGeometry); + } + /** + * Adds the given action manager to this scene + * @deprecated + * @param newActionManager The action manager to add + */ + addActionManager(newActionManager) { + this.actionManagers.push(newActionManager); + } + /** + * Adds the given texture to this scene. + * @param newTexture The texture to add + */ + addTexture(newTexture) { + if (this._blockEntityCollection) { + return; + } + this.textures.push(newTexture); + this.onNewTextureAddedObservable.notifyObservers(newTexture); + } + /** + * Switch active camera + * @param newCamera defines the new active camera + * @param attachControl defines if attachControl must be called for the new active camera (default: true) + */ + switchActiveCamera(newCamera, attachControl = true) { + const canvas = this._engine.getInputElement(); + if (!canvas) { + return; + } + if (this.activeCamera) { + this.activeCamera.detachControl(); + } + this.activeCamera = newCamera; + if (attachControl) { + newCamera.attachControl(); + } + } + /** + * sets the active camera of the scene using its Id + * @param id defines the camera's Id + * @returns the new active camera or null if none found. + */ + setActiveCameraById(id) { + const camera = this.getCameraById(id); + if (camera) { + this.activeCamera = camera; + return camera; + } + return null; + } + /** + * sets the active camera of the scene using its name + * @param name defines the camera's name + * @returns the new active camera or null if none found. + */ + setActiveCameraByName(name) { + const camera = this.getCameraByName(name); + if (camera) { + this.activeCamera = camera; + return camera; + } + return null; + } + /** + * get an animation group using its name + * @param name defines the material's name + * @returns the animation group or null if none found. + */ + getAnimationGroupByName(name) { + for (let index = 0; index < this.animationGroups.length; index++) { + if (this.animationGroups[index].name === name) { + return this.animationGroups[index]; + } + } + return null; + } + _getMaterial(allowMultiMaterials, predicate) { + for (let index = 0; index < this.materials.length; index++) { + const material = this.materials[index]; + if (predicate(material)) { + return material; + } + } + if (allowMultiMaterials) { + for (let index = 0; index < this.multiMaterials.length; index++) { + const material = this.multiMaterials[index]; + if (predicate(material)) { + return material; + } + } + } + return null; + } + /** + * Get a material using its unique id + * @param uniqueId defines the material's unique id + * @param allowMultiMaterials determines whether multimaterials should be considered + * @returns the material or null if none found. + */ + getMaterialByUniqueID(uniqueId, allowMultiMaterials = false) { + return this._getMaterial(allowMultiMaterials, (m) => m.uniqueId === uniqueId); + } + /** + * get a material using its id + * @param id defines the material's Id + * @param allowMultiMaterials determines whether multimaterials should be considered + * @returns the material or null if none found. + */ + getMaterialById(id, allowMultiMaterials = false) { + return this._getMaterial(allowMultiMaterials, (m) => m.id === id); + } + /** + * Gets a material using its name + * @param name defines the material's name + * @param allowMultiMaterials determines whether multimaterials should be considered + * @returns the material or null if none found. + */ + getMaterialByName(name, allowMultiMaterials = false) { + return this._getMaterial(allowMultiMaterials, (m) => m.name === name); + } + /** + * Gets a last added material using a given id + * @param id defines the material's id + * @param allowMultiMaterials determines whether multimaterials should be considered + * @returns the last material with the given id or null if none found. + */ + getLastMaterialById(id, allowMultiMaterials = false) { + for (let index = this.materials.length - 1; index >= 0; index--) { + if (this.materials[index].id === id) { + return this.materials[index]; + } + } + if (allowMultiMaterials) { + for (let index = this.multiMaterials.length - 1; index >= 0; index--) { + if (this.multiMaterials[index].id === id) { + return this.multiMaterials[index]; + } + } + } + return null; + } + /** + * Get a texture using its unique id + * @param uniqueId defines the texture's unique id + * @returns the texture or null if none found. + */ + getTextureByUniqueId(uniqueId) { + for (let index = 0; index < this.textures.length; index++) { + if (this.textures[index].uniqueId === uniqueId) { + return this.textures[index]; + } + } + return null; + } + /** + * Gets a texture using its name + * @param name defines the texture's name + * @returns the texture or null if none found. + */ + getTextureByName(name) { + for (let index = 0; index < this.textures.length; index++) { + if (this.textures[index].name === name) { + return this.textures[index]; + } + } + return null; + } + /** + * Gets a camera using its Id + * @param id defines the Id to look for + * @returns the camera or null if not found + */ + getCameraById(id) { + for (let index = 0; index < this.cameras.length; index++) { + if (this.cameras[index].id === id) { + return this.cameras[index]; + } + } + return null; + } + /** + * Gets a camera using its unique Id + * @param uniqueId defines the unique Id to look for + * @returns the camera or null if not found + */ + getCameraByUniqueId(uniqueId) { + for (let index = 0; index < this.cameras.length; index++) { + if (this.cameras[index].uniqueId === uniqueId) { + return this.cameras[index]; + } + } + return null; + } + /** + * Gets a camera using its name + * @param name defines the camera's name + * @returns the camera or null if none found. + */ + getCameraByName(name) { + for (let index = 0; index < this.cameras.length; index++) { + if (this.cameras[index].name === name) { + return this.cameras[index]; + } + } + return null; + } + /** + * Gets a bone using its Id + * @param id defines the bone's Id + * @returns the bone or null if not found + */ + getBoneById(id) { + for (let skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) { + const skeleton = this.skeletons[skeletonIndex]; + for (let boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) { + if (skeleton.bones[boneIndex].id === id) { + return skeleton.bones[boneIndex]; + } + } + } + return null; + } + /** + * Gets a bone using its id + * @param name defines the bone's name + * @returns the bone or null if not found + */ + getBoneByName(name) { + for (let skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) { + const skeleton = this.skeletons[skeletonIndex]; + for (let boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) { + if (skeleton.bones[boneIndex].name === name) { + return skeleton.bones[boneIndex]; + } + } + } + return null; + } + /** + * Gets a light node using its name + * @param name defines the light's name + * @returns the light or null if none found. + */ + getLightByName(name) { + for (let index = 0; index < this.lights.length; index++) { + if (this.lights[index].name === name) { + return this.lights[index]; + } + } + return null; + } + /** + * Gets a light node using its Id + * @param id defines the light's Id + * @returns the light or null if none found. + */ + getLightById(id) { + for (let index = 0; index < this.lights.length; index++) { + if (this.lights[index].id === id) { + return this.lights[index]; + } + } + return null; + } + /** + * Gets a light node using its scene-generated unique Id + * @param uniqueId defines the light's unique Id + * @returns the light or null if none found. + */ + getLightByUniqueId(uniqueId) { + for (let index = 0; index < this.lights.length; index++) { + if (this.lights[index].uniqueId === uniqueId) { + return this.lights[index]; + } + } + return null; + } + /** + * Gets a particle system by Id + * @param id defines the particle system Id + * @returns the corresponding system or null if none found + */ + getParticleSystemById(id) { + for (let index = 0; index < this.particleSystems.length; index++) { + if (this.particleSystems[index].id === id) { + return this.particleSystems[index]; + } + } + return null; + } + /** + * Gets a geometry using its Id + * @param id defines the geometry's Id + * @returns the geometry or null if none found. + */ + getGeometryById(id) { + for (let index = 0; index < this.geometries.length; index++) { + if (this.geometries[index].id === id) { + return this.geometries[index]; + } + } + return null; + } + _getGeometryByUniqueId(uniqueId) { + if (this._geometriesByUniqueId) { + const index = this._geometriesByUniqueId[uniqueId]; + if (index !== undefined) { + return this.geometries[index]; + } + } + else { + for (let index = 0; index < this.geometries.length; index++) { + if (this.geometries[index].uniqueId === uniqueId) { + return this.geometries[index]; + } + } + } + return null; + } + /** + * Gets a frame graph using its name + * @param name defines the frame graph's name + * @returns the frame graph or null if none found. + */ + getFrameGraphByName(name) { + for (let index = 0; index < this.frameGraphs.length; index++) { + if (this.frameGraphs[index].name === name) { + return this.frameGraphs[index]; + } + } + return null; + } + /** + * Add a new geometry to this scene + * @param geometry defines the geometry to be added to the scene. + * @param force defines if the geometry must be pushed even if a geometry with this id already exists + * @returns a boolean defining if the geometry was added or not + */ + pushGeometry(geometry, force) { + if (!force && this._getGeometryByUniqueId(geometry.uniqueId)) { + return false; + } + this.addGeometry(geometry); + Tools.SetImmediate(() => { + this.onNewGeometryAddedObservable.notifyObservers(geometry); + }); + return true; + } + /** + * Removes an existing geometry + * @param geometry defines the geometry to be removed from the scene + * @returns a boolean defining if the geometry was removed or not + */ + removeGeometry(geometry) { + let index; + if (this._geometriesByUniqueId) { + index = this._geometriesByUniqueId[geometry.uniqueId]; + if (index === undefined) { + return false; + } + } + else { + index = this.geometries.indexOf(geometry); + if (index < 0) { + return false; + } + } + if (index !== this.geometries.length - 1) { + const lastGeometry = this.geometries[this.geometries.length - 1]; + if (lastGeometry) { + this.geometries[index] = lastGeometry; + if (this._geometriesByUniqueId) { + this._geometriesByUniqueId[lastGeometry.uniqueId] = index; + } + } + } + if (this._geometriesByUniqueId) { + this._geometriesByUniqueId[geometry.uniqueId] = undefined; + } + this.geometries.pop(); + this.onGeometryRemovedObservable.notifyObservers(geometry); + return true; + } + /** + * Gets the list of geometries attached to the scene + * @returns an array of Geometry + */ + getGeometries() { + return this.geometries; + } + /** + * Gets the first added mesh found of a given Id + * @param id defines the Id to search for + * @returns the mesh found or null if not found at all + */ + getMeshById(id) { + for (let index = 0; index < this.meshes.length; index++) { + if (this.meshes[index].id === id) { + return this.meshes[index]; + } + } + return null; + } + /** + * Gets a list of meshes using their Id + * @param id defines the Id to search for + * @returns a list of meshes + */ + getMeshesById(id) { + return this.meshes.filter(function (m) { + return m.id === id; + }); + } + /** + * Gets the first added transform node found of a given Id + * @param id defines the Id to search for + * @returns the found transform node or null if not found at all. + */ + getTransformNodeById(id) { + for (let index = 0; index < this.transformNodes.length; index++) { + if (this.transformNodes[index].id === id) { + return this.transformNodes[index]; + } + } + return null; + } + /** + * Gets a transform node with its auto-generated unique Id + * @param uniqueId defines the unique Id to search for + * @returns the found transform node or null if not found at all. + */ + getTransformNodeByUniqueId(uniqueId) { + for (let index = 0; index < this.transformNodes.length; index++) { + if (this.transformNodes[index].uniqueId === uniqueId) { + return this.transformNodes[index]; + } + } + return null; + } + /** + * Gets a list of transform nodes using their Id + * @param id defines the Id to search for + * @returns a list of transform nodes + */ + getTransformNodesById(id) { + return this.transformNodes.filter(function (m) { + return m.id === id; + }); + } + /** + * Gets a mesh with its auto-generated unique Id + * @param uniqueId defines the unique Id to search for + * @returns the found mesh or null if not found at all. + */ + getMeshByUniqueId(uniqueId) { + for (let index = 0; index < this.meshes.length; index++) { + if (this.meshes[index].uniqueId === uniqueId) { + return this.meshes[index]; + } + } + return null; + } + /** + * Gets a the last added mesh using a given Id + * @param id defines the Id to search for + * @returns the found mesh or null if not found at all. + */ + getLastMeshById(id) { + for (let index = this.meshes.length - 1; index >= 0; index--) { + if (this.meshes[index].id === id) { + return this.meshes[index]; + } + } + return null; + } + /** + * Gets a the last transform node using a given Id + * @param id defines the Id to search for + * @returns the found mesh or null if not found at all. + */ + getLastTransformNodeById(id) { + for (let index = this.transformNodes.length - 1; index >= 0; index--) { + if (this.transformNodes[index].id === id) { + return this.transformNodes[index]; + } + } + return null; + } + /** + * Gets a the last added node (Mesh, Camera, Light) using a given Id + * @param id defines the Id to search for + * @returns the found node or null if not found at all + */ + getLastEntryById(id) { + let index; + for (index = this.meshes.length - 1; index >= 0; index--) { + if (this.meshes[index].id === id) { + return this.meshes[index]; + } + } + for (index = this.transformNodes.length - 1; index >= 0; index--) { + if (this.transformNodes[index].id === id) { + return this.transformNodes[index]; + } + } + for (index = this.cameras.length - 1; index >= 0; index--) { + if (this.cameras[index].id === id) { + return this.cameras[index]; + } + } + for (index = this.lights.length - 1; index >= 0; index--) { + if (this.lights[index].id === id) { + return this.lights[index]; + } + } + return null; + } + /** + * Gets a node (Mesh, Camera, Light) using a given Id + * @param id defines the Id to search for + * @returns the found node or null if not found at all + */ + getNodeById(id) { + const mesh = this.getMeshById(id); + if (mesh) { + return mesh; + } + const transformNode = this.getTransformNodeById(id); + if (transformNode) { + return transformNode; + } + const light = this.getLightById(id); + if (light) { + return light; + } + const camera = this.getCameraById(id); + if (camera) { + return camera; + } + const bone = this.getBoneById(id); + if (bone) { + return bone; + } + return null; + } + /** + * Gets a node (Mesh, Camera, Light) using a given name + * @param name defines the name to search for + * @returns the found node or null if not found at all. + */ + getNodeByName(name) { + const mesh = this.getMeshByName(name); + if (mesh) { + return mesh; + } + const transformNode = this.getTransformNodeByName(name); + if (transformNode) { + return transformNode; + } + const light = this.getLightByName(name); + if (light) { + return light; + } + const camera = this.getCameraByName(name); + if (camera) { + return camera; + } + const bone = this.getBoneByName(name); + if (bone) { + return bone; + } + return null; + } + /** + * Gets a mesh using a given name + * @param name defines the name to search for + * @returns the found mesh or null if not found at all. + */ + getMeshByName(name) { + for (let index = 0; index < this.meshes.length; index++) { + if (this.meshes[index].name === name) { + return this.meshes[index]; + } + } + return null; + } + /** + * Gets a transform node using a given name + * @param name defines the name to search for + * @returns the found transform node or null if not found at all. + */ + getTransformNodeByName(name) { + for (let index = 0; index < this.transformNodes.length; index++) { + if (this.transformNodes[index].name === name) { + return this.transformNodes[index]; + } + } + return null; + } + /** + * Gets a skeleton using a given Id (if many are found, this function will pick the last one) + * @param id defines the Id to search for + * @returns the found skeleton or null if not found at all. + */ + getLastSkeletonById(id) { + for (let index = this.skeletons.length - 1; index >= 0; index--) { + if (this.skeletons[index].id === id) { + return this.skeletons[index]; + } + } + return null; + } + /** + * Gets a skeleton using a given auto generated unique id + * @param uniqueId defines the unique id to search for + * @returns the found skeleton or null if not found at all. + */ + getSkeletonByUniqueId(uniqueId) { + for (let index = 0; index < this.skeletons.length; index++) { + if (this.skeletons[index].uniqueId === uniqueId) { + return this.skeletons[index]; + } + } + return null; + } + /** + * Gets a skeleton using a given id (if many are found, this function will pick the first one) + * @param id defines the id to search for + * @returns the found skeleton or null if not found at all. + */ + getSkeletonById(id) { + for (let index = 0; index < this.skeletons.length; index++) { + if (this.skeletons[index].id === id) { + return this.skeletons[index]; + } + } + return null; + } + /** + * Gets a skeleton using a given name + * @param name defines the name to search for + * @returns the found skeleton or null if not found at all. + */ + getSkeletonByName(name) { + for (let index = 0; index < this.skeletons.length; index++) { + if (this.skeletons[index].name === name) { + return this.skeletons[index]; + } + } + return null; + } + /** + * Gets a morph target manager using a given id (if many are found, this function will pick the last one) + * @param id defines the id to search for + * @returns the found morph target manager or null if not found at all. + */ + getMorphTargetManagerById(id) { + for (let index = 0; index < this.morphTargetManagers.length; index++) { + if (this.morphTargetManagers[index].uniqueId === id) { + return this.morphTargetManagers[index]; + } + } + return null; + } + /** + * Gets a morph target using a given id (if many are found, this function will pick the first one) + * @param id defines the id to search for + * @returns the found morph target or null if not found at all. + */ + getMorphTargetById(id) { + for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) { + const morphTargetManager = this.morphTargetManagers[managerIndex]; + for (let index = 0; index < morphTargetManager.numTargets; ++index) { + const target = morphTargetManager.getTarget(index); + if (target.id === id) { + return target; + } + } + } + return null; + } + /** + * Gets a morph target using a given name (if many are found, this function will pick the first one) + * @param name defines the name to search for + * @returns the found morph target or null if not found at all. + */ + getMorphTargetByName(name) { + for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) { + const morphTargetManager = this.morphTargetManagers[managerIndex]; + for (let index = 0; index < morphTargetManager.numTargets; ++index) { + const target = morphTargetManager.getTarget(index); + if (target.name === name) { + return target; + } + } + } + return null; + } + /** + * Gets a post process using a given name (if many are found, this function will pick the first one) + * @param name defines the name to search for + * @returns the found post process or null if not found at all. + */ + getPostProcessByName(name) { + for (let postProcessIndex = 0; postProcessIndex < this.postProcesses.length; ++postProcessIndex) { + const postProcess = this.postProcesses[postProcessIndex]; + if (postProcess.name === name) { + return postProcess; + } + } + return null; + } + /** + * Gets a boolean indicating if the given mesh is active + * @param mesh defines the mesh to look for + * @returns true if the mesh is in the active list + */ + isActiveMesh(mesh) { + return this._activeMeshes.indexOf(mesh) !== -1; + } + /** + * Return a unique id as a string which can serve as an identifier for the scene + */ + get uid() { + if (!this._uid) { + this._uid = Tools.RandomId(); + } + return this._uid; + } + /** + * Add an externally attached data from its key. + * This method call will fail and return false, if such key already exists. + * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method. + * @param key the unique key that identifies the data + * @param data the data object to associate to the key for this Engine instance + * @returns true if no such key were already present and the data was added successfully, false otherwise + */ + addExternalData(key, data) { + if (!this._externalData) { + this._externalData = new StringDictionary(); + } + return this._externalData.add(key, data); + } + /** + * Get an externally attached data from its key + * @param key the unique key that identifies the data + * @returns the associated data, if present (can be null), or undefined if not present + */ + getExternalData(key) { + if (!this._externalData) { + return null; + } + return this._externalData.get(key); + } + /** + * Get an externally attached data from its key, create it using a factory if it's not already present + * @param key the unique key that identifies the data + * @param factory the factory that will be called to create the instance if and only if it doesn't exists + * @returns the associated data, can be null if the factory returned null. + */ + getOrAddExternalDataWithFactory(key, factory) { + if (!this._externalData) { + this._externalData = new StringDictionary(); + } + return this._externalData.getOrAddWithFactory(key, factory); + } + /** + * Remove an externally attached data from the Engine instance + * @param key the unique key that identifies the data + * @returns true if the data was successfully removed, false if it doesn't exist + */ + removeExternalData(key) { + return this._externalData.remove(key); + } + _evaluateSubMesh(subMesh, mesh, initialMesh, forcePush) { + if (forcePush || subMesh.isInFrustum(this._frustumPlanes)) { + for (const step of this._evaluateSubMeshStage) { + step.action(mesh, subMesh); + } + const material = subMesh.getMaterial(); + if (material !== null && material !== undefined) { + // Render targets + if (material.hasRenderTargetTextures && material.getRenderTargetTextures != null) { + if (this._processedMaterials.indexOf(material) === -1) { + this._processedMaterials.push(material); + this._materialsRenderTargets.concatWithNoDuplicate(material.getRenderTargetTextures()); + } + } + // Dispatch + this._renderingManager.dispatch(subMesh, mesh, material); + } + } + } + /** + * Clear the processed materials smart array preventing retention point in material dispose. + */ + freeProcessedMaterials() { + this._processedMaterials.dispose(); + } + /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups + * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance + * when disposing several meshes in a row or a hierarchy of meshes. + * When used, it is the responsibility of the user to blockfreeActiveMeshesAndRenderingGroups back to false. + */ + get blockfreeActiveMeshesAndRenderingGroups() { + return this._preventFreeActiveMeshesAndRenderingGroups; + } + set blockfreeActiveMeshesAndRenderingGroups(value) { + if (this._preventFreeActiveMeshesAndRenderingGroups === value) { + return; + } + if (value) { + this.freeActiveMeshes(); + this.freeRenderingGroups(); + } + this._preventFreeActiveMeshesAndRenderingGroups = value; + } + /** + * Clear the active meshes smart array preventing retention point in mesh dispose. + */ + freeActiveMeshes() { + if (this.blockfreeActiveMeshesAndRenderingGroups) { + return; + } + this._activeMeshes.dispose(); + if (this.activeCamera && this.activeCamera._activeMeshes) { + this.activeCamera._activeMeshes.dispose(); + } + if (this.activeCameras) { + for (let i = 0; i < this.activeCameras.length; i++) { + const activeCamera = this.activeCameras[i]; + if (activeCamera && activeCamera._activeMeshes) { + activeCamera._activeMeshes.dispose(); + } + } + } + } + /** + * Clear the info related to rendering groups preventing retention points during dispose. + */ + freeRenderingGroups() { + if (this.blockfreeActiveMeshesAndRenderingGroups) { + return; + } + if (this._renderingManager) { + this._renderingManager.freeRenderingGroups(); + } + if (this.textures) { + for (let i = 0; i < this.textures.length; i++) { + const texture = this.textures[i]; + if (texture && texture.renderList) { + texture.freeRenderingGroups(); + } + } + } + } + /** @internal */ + _isInIntermediateRendering() { + return this._intermediateRendering; + } + /** + * Use this function to stop evaluating active meshes. The current list will be keep alive between frames + * @param skipEvaluateActiveMeshes defines an optional boolean indicating that the evaluate active meshes step must be completely skipped + * @param onSuccess optional success callback + * @param onError optional error callback + * @param freezeMeshes defines if meshes should be frozen (true by default) + * @param keepFrustumCulling defines if you want to keep running the frustum clipping (false by default) + * @returns the current scene + */ + freezeActiveMeshes(skipEvaluateActiveMeshes = false, onSuccess, onError, freezeMeshes = true, keepFrustumCulling = false) { + this.executeWhenReady(() => { + if (!this.activeCamera) { + onError && onError("No active camera found"); + return; + } + if (!this._frustumPlanes) { + this.updateTransformMatrix(); + } + this._evaluateActiveMeshes(); + this._activeMeshesFrozen = true; + this._activeMeshesFrozenButKeepClipping = keepFrustumCulling; + this._skipEvaluateActiveMeshesCompletely = skipEvaluateActiveMeshes; + if (freezeMeshes) { + for (let index = 0; index < this._activeMeshes.length; index++) { + this._activeMeshes.data[index]._freeze(); + } + } + onSuccess && onSuccess(); + }); + return this; + } + /** + * Use this function to restart evaluating active meshes on every frame + * @returns the current scene + */ + unfreezeActiveMeshes() { + for (let index = 0; index < this.meshes.length; index++) { + const mesh = this.meshes[index]; + if (mesh._internalAbstractMeshDataInfo) { + mesh._internalAbstractMeshDataInfo._isActive = false; + } + } + for (let index = 0; index < this._activeMeshes.length; index++) { + this._activeMeshes.data[index]._unFreeze(); + } + this._activeMeshesFrozen = false; + return this; + } + _executeActiveContainerCleanup(container) { + const isInFastMode = this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1; + if (!isInFastMode && this._activeMeshesFrozen && this._activeMeshes.length) { + return; // Do not execute in frozen mode + } + // We need to ensure we are not in the rendering loop + this.onBeforeRenderObservable.addOnce(() => container.dispose()); + } + _evaluateActiveMeshes() { + if (this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1) { + if (this._activeMeshes.length > 0) { + this.activeCamera?._activeMeshes.reset(); + this._activeMeshes.reset(); + this._renderingManager.reset(); + this._processedMaterials.reset(); + this._activeParticleSystems.reset(); + this._activeSkeletons.reset(); + this._softwareSkinnedMeshes.reset(); + } + return; + } + if (this._activeMeshesFrozen && this._activeMeshes.length) { + if (!this._skipEvaluateActiveMeshesCompletely) { + const len = this._activeMeshes.length; + for (let i = 0; i < len; i++) { + const mesh = this._activeMeshes.data[i]; + mesh.computeWorldMatrix(); + } + } + if (this._activeParticleSystems) { + const psLength = this._activeParticleSystems.length; + for (let i = 0; i < psLength; i++) { + this._activeParticleSystems.data[i].animate(); + } + } + this._renderingManager.resetSprites(); + return; + } + if (!this.activeCamera) { + return; + } + this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this); + this.activeCamera._activeMeshes.reset(); + this._activeMeshes.reset(); + this._renderingManager.reset(); + this._processedMaterials.reset(); + this._activeParticleSystems.reset(); + this._activeSkeletons.reset(); + this._softwareSkinnedMeshes.reset(); + this._materialsRenderTargets.reset(); + for (const step of this._beforeEvaluateActiveMeshStage) { + step.action(); + } + // Determine mesh candidates + const meshes = this.getActiveMeshCandidates(); + // Check each mesh + const len = meshes.length; + for (let i = 0; i < len; i++) { + const mesh = meshes.data[i]; + let currentLOD = mesh._internalAbstractMeshDataInfo._currentLOD.get(this.activeCamera); + if (currentLOD) { + currentLOD[1] = -1; + } + else { + currentLOD = [mesh, -1]; + mesh._internalAbstractMeshDataInfo._currentLOD.set(this.activeCamera, currentLOD); + } + if (mesh.isBlocked) { + continue; + } + this._totalVertices.addCount(mesh.getTotalVertices(), false); + if (!mesh.isReady() || !mesh.isEnabled() || mesh.scaling.hasAZeroComponent) { + continue; + } + mesh.computeWorldMatrix(); + // Intersections + if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(12, 13)) { + this._meshesForIntersections.pushNoDuplicate(mesh); + } + // Switch to current LOD + let meshToRender = this.customLODSelector ? this.customLODSelector(mesh, this.activeCamera) : mesh.getLOD(this.activeCamera); + currentLOD[0] = meshToRender; + currentLOD[1] = this._frameId; + if (meshToRender === undefined || meshToRender === null) { + continue; + } + // Compute world matrix if LOD is billboard + if (meshToRender !== mesh && meshToRender.billboardMode !== 0) { + meshToRender.computeWorldMatrix(); + } + mesh._preActivate(); + if (mesh.isVisible && + mesh.visibility > 0 && + (mesh.layerMask & this.activeCamera.layerMask) !== 0 && + (this._skipFrustumClipping || mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) { + this._activeMeshes.push(mesh); + this.activeCamera._activeMeshes.push(mesh); + if (meshToRender !== mesh) { + meshToRender._activate(this._renderId, false); + } + for (const step of this._preActiveMeshStage) { + step.action(mesh); + } + if (mesh._activate(this._renderId, false)) { + if (!mesh.isAnInstance) { + meshToRender._internalAbstractMeshDataInfo._onlyForInstances = false; + } + else { + if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) { + meshToRender = mesh; + } + } + meshToRender._internalAbstractMeshDataInfo._isActive = true; + this._activeMesh(mesh, meshToRender); + } + mesh._postActivate(); + } + } + this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this); + // Particle systems + if (this.particlesEnabled) { + this.onBeforeParticlesRenderingObservable.notifyObservers(this); + for (let particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) { + const particleSystem = this.particleSystems[particleIndex]; + if (!particleSystem.isStarted() || !particleSystem.emitter) { + continue; + } + const emitter = particleSystem.emitter; + if (!emitter.position || emitter.isEnabled()) { + this._activeParticleSystems.push(particleSystem); + particleSystem.animate(); + this._renderingManager.dispatchParticles(particleSystem); + } + } + this.onAfterParticlesRenderingObservable.notifyObservers(this); + } + } + /** @internal */ + _prepareSkeleton(mesh) { + if (!this._skeletonsEnabled || !mesh.skeleton) { + return; + } + if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) { + mesh.skeleton.prepare(); + this._activeBones.addCount(mesh.skeleton.bones.length, false); + } + if (!mesh.computeBonesUsingShaders) { + if (this._softwareSkinnedMeshes.pushNoDuplicate(mesh) && this.frameGraph) { + mesh.applySkeleton(mesh.skeleton); + } + } + } + _activeMesh(sourceMesh, mesh) { + this._prepareSkeleton(mesh); + let forcePush = sourceMesh.hasInstances || sourceMesh.isAnInstance || this.dispatchAllSubMeshesOfActiveMeshes || this._skipFrustumClipping || mesh.alwaysSelectAsActiveMesh; + if (mesh && mesh.subMeshes && mesh.subMeshes.length > 0) { + const subMeshes = this.getActiveSubMeshCandidates(mesh); + const len = subMeshes.length; + forcePush = forcePush || len === 1; + for (let i = 0; i < len; i++) { + const subMesh = subMeshes.data[i]; + this._evaluateSubMesh(subMesh, mesh, sourceMesh, forcePush); + } + } + } + /** + * Update the transform matrix to update from the current active camera + * @param force defines a boolean used to force the update even if cache is up to date + */ + updateTransformMatrix(force) { + const activeCamera = this.activeCamera; + if (!activeCamera) { + return; + } + if (activeCamera._renderingMultiview) { + const leftCamera = activeCamera._rigCameras[0]; + const rightCamera = activeCamera._rigCameras[1]; + this.setTransformMatrix(leftCamera.getViewMatrix(), leftCamera.getProjectionMatrix(force), rightCamera.getViewMatrix(), rightCamera.getProjectionMatrix(force)); + } + else { + this.setTransformMatrix(activeCamera.getViewMatrix(), activeCamera.getProjectionMatrix(force)); + } + } + _bindFrameBuffer(camera, clear = true) { + if (!this._useCurrentFrameBuffer) { + if (camera && camera._multiviewTexture) { + camera._multiviewTexture._bindFrameBuffer(); + } + else if (camera && camera.outputRenderTarget) { + camera.outputRenderTarget._bindFrameBuffer(); + } + else { + if (!this._engine._currentFrameBufferIsDefaultFrameBuffer()) { + this._engine.restoreDefaultFramebuffer(); + } + } + } + if (clear) { + this._clearFrameBuffer(camera); + } + } + _clearFrameBuffer(camera) { + // we assume the framebuffer currently bound is the right one + if (camera && camera._multiviewTexture) ; + else if (camera && camera.outputRenderTarget && !camera._renderingMultiview) { + const rtt = camera.outputRenderTarget; + if (rtt.onClearObservable.hasObservers()) { + rtt.onClearObservable.notifyObservers(this._engine); + } + else if (!rtt.skipInitialClear && !camera.isRightCamera) { + if (this.autoClear) { + this._engine.clear(rtt.clearColor || this._clearColor, !rtt._cleared, true, true); + } + rtt._cleared = true; + } + } + else { + if (!this._defaultFrameBufferCleared) { + this._defaultFrameBufferCleared = true; + this._clear(); + } + else { + this._engine.clear(null, false, true, true); + } + } + } + /** + * @internal + */ + _renderForCamera(camera, rigParent, bindFrameBuffer = true) { + if (camera && camera._skipRendering) { + return; + } + const engine = this._engine; + // Use _activeCamera instead of activeCamera to avoid onActiveCameraChanged + this._activeCamera = camera; + if (!this.activeCamera) { + throw new Error("Active camera not set"); + } + // Viewport + engine.setViewport(this.activeCamera.viewport); + // Camera + this.resetCachedMaterial(); + this._renderId++; + if (!this.prePass && bindFrameBuffer) { + let skipInitialClear = true; + if (camera._renderingMultiview && camera.outputRenderTarget) { + skipInitialClear = camera.outputRenderTarget.skipInitialClear; + if (this.autoClear) { + this._defaultFrameBufferCleared = false; + camera.outputRenderTarget.skipInitialClear = false; + } + } + this._bindFrameBuffer(this._activeCamera); + if (camera._renderingMultiview && camera.outputRenderTarget) { + camera.outputRenderTarget.skipInitialClear = skipInitialClear; + } + } + this.updateTransformMatrix(); + this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera); + // Meshes + this._evaluateActiveMeshes(); + // Software skinning + for (let softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) { + const mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex]; + mesh.applySkeleton(mesh.skeleton); + } + // Render targets + this.onBeforeRenderTargetsRenderObservable.notifyObservers(this); + this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets); + if (camera.customRenderTargets && camera.customRenderTargets.length > 0) { + this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets); + } + if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) { + this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets); + } + if (this.environmentTexture && this.environmentTexture.isRenderTarget) { + this._renderTargets.pushNoDuplicate(this.environmentTexture); + } + // Collects render targets from external components. + for (const step of this._gatherActiveCameraRenderTargetsStage) { + step.action(this._renderTargets); + } + let needRebind = false; + if (this.renderTargetsEnabled) { + this._intermediateRendering = true; + if (this._renderTargets.length > 0) { + Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0); + for (let renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) { + const renderTarget = this._renderTargets.data[renderIndex]; + if (renderTarget._shouldRender()) { + this._renderId++; + const hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera; + renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets); + needRebind = true; + } + } + Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0); + this._renderId++; + } + for (const step of this._cameraDrawRenderTargetStage) { + needRebind = step.action(this.activeCamera) || needRebind; + } + this._intermediateRendering = false; + } + this._engine.currentRenderPassId = camera.outputRenderTarget?.renderPassId ?? camera.renderPassId ?? 0; + // Restore framebuffer after rendering to targets + if (needRebind && !this.prePass) { + this._bindFrameBuffer(this._activeCamera, false); + this.updateTransformMatrix(); + } + this.onAfterRenderTargetsRenderObservable.notifyObservers(this); + // Prepare Frame + if (this.postProcessManager && !camera._multiviewTexture && !this.prePass) { + this.postProcessManager._prepareFrame(); + } + // Before Camera Draw + for (const step of this._beforeCameraDrawStage) { + step.action(this.activeCamera); + } + // Render + this.onBeforeDrawPhaseObservable.notifyObservers(this); + if (engine.snapshotRendering && engine.snapshotRenderingMode === 1) { + this.finalizeSceneUbo(); + } + this._renderingManager.render(null, null, true, true); + this.onAfterDrawPhaseObservable.notifyObservers(this); + // After Camera Draw + for (const step of this._afterCameraDrawStage) { + step.action(this.activeCamera); + } + // Finalize frame + if (this.postProcessManager && !camera._multiviewTexture) { + // if the camera has an output render target, render the post process to the render target + const texture = camera.outputRenderTarget ? camera.outputRenderTarget.renderTarget : undefined; + this.postProcessManager._finalizeFrame(camera.isIntermediate, texture); + } + // After post process + for (const step of this._afterCameraPostProcessStage) { + step.action(this.activeCamera); + } + // Reset some special arrays + this._renderTargets.reset(); + this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera); + } + _processSubCameras(camera, bindFrameBuffer = true) { + if (camera.cameraRigMode === 0 || camera._renderingMultiview) { + if (camera._renderingMultiview && !this._multiviewSceneUbo) { + this._createMultiviewUbo(); + } + this._renderForCamera(camera, undefined, bindFrameBuffer); + this.onAfterRenderCameraObservable.notifyObservers(camera); + return; + } + if (camera._useMultiviewToSingleView) { + this._renderMultiviewToSingleView(camera); + } + else { + // rig cameras + this.onBeforeCameraRenderObservable.notifyObservers(camera); + for (let index = 0; index < camera._rigCameras.length; index++) { + this._renderForCamera(camera._rigCameras[index], camera); + } + } + // Use _activeCamera instead of activeCamera to avoid onActiveCameraChanged + this._activeCamera = camera; + this.updateTransformMatrix(); + this.onAfterRenderCameraObservable.notifyObservers(camera); + } + _checkIntersections() { + for (let index = 0; index < this._meshesForIntersections.length; index++) { + const sourceMesh = this._meshesForIntersections.data[index]; + if (!sourceMesh.actionManager) { + continue; + } + for (let actionIndex = 0; sourceMesh.actionManager && actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) { + const action = sourceMesh.actionManager.actions[actionIndex]; + if (action.trigger === 12 || action.trigger === 13) { + const parameters = action.getTriggerParameter(); + const otherMesh = parameters.mesh ? parameters.mesh : parameters; + const areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection); + const currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh); + if (areIntersecting && currentIntersectionInProgress === -1) { + if (action.trigger === 12) { + action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh)); + sourceMesh._intersectionsInProgress.push(otherMesh); + } + else if (action.trigger === 13) { + sourceMesh._intersectionsInProgress.push(otherMesh); + } + } + else if (!areIntersecting && currentIntersectionInProgress > -1) { + //They intersected, and now they don't. + //is this trigger an exit trigger? execute an event. + if (action.trigger === 13) { + action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh)); + } + //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array. + if (!sourceMesh.actionManager.hasSpecificTrigger(13, (parameter) => { + const parameterMesh = parameter.mesh ? parameter.mesh : parameter; + return otherMesh === parameterMesh; + }) || + action.trigger === 13) { + sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1); + } + } + } + } + } + } + /** + * @internal + */ + _advancePhysicsEngineStep(step) { + // Do nothing. Code will be replaced if physics engine component is referenced + } + /** @internal */ + _animate(customDeltaTime) { + // Nothing to do as long as Animatable have not been imported. + } + /** Execute all animations (for a frame) */ + animate() { + if (this._engine.isDeterministicLockStep()) { + let deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator; + const defaultFrameTime = this._engine.getTimeStep(); + const defaultFPS = 1000.0 / defaultFrameTime / 1000.0; + let stepsTaken = 0; + const maxSubSteps = this._engine.getLockstepMaxSteps(); + let internalSteps = Math.floor(deltaTime / defaultFrameTime); + internalSteps = Math.min(internalSteps, maxSubSteps); + while (deltaTime > 0 && stepsTaken < internalSteps) { + this.onBeforeStepObservable.notifyObservers(this); + // Animations + this._animationRatio = defaultFrameTime * defaultFPS; + this._animate(defaultFrameTime); + this.onAfterAnimationsObservable.notifyObservers(this); + // Physics + if (this.physicsEnabled) { + this._advancePhysicsEngineStep(defaultFrameTime); + } + this.onAfterStepObservable.notifyObservers(this); + this._currentStepId++; + stepsTaken++; + deltaTime -= defaultFrameTime; + } + this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime; + } + else { + // Animations + const deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)); + this._animationRatio = deltaTime * (60.0 / 1000.0); + this._animate(); + this.onAfterAnimationsObservable.notifyObservers(this); + // Physics + if (this.physicsEnabled) { + this._advancePhysicsEngineStep(deltaTime); + } + } + } + _clear() { + if (this.autoClearDepthAndStencil || this.autoClear) { + this._engine.clear(this._clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil); + } + } + _checkCameraRenderTarget(camera) { + if (camera?.outputRenderTarget && !camera?.isRigCamera) { + camera.outputRenderTarget._cleared = false; + } + if (camera?.rigCameras?.length) { + for (let i = 0; i < camera.rigCameras.length; ++i) { + const rtt = camera.rigCameras[i].outputRenderTarget; + if (rtt) { + rtt._cleared = false; + } + } + } + } + /** + * Resets the draw wrappers cache of all meshes + * @param passId If provided, releases only the draw wrapper corresponding to this render pass id + */ + resetDrawCache(passId) { + if (!this.meshes) { + return; + } + for (const mesh of this.meshes) { + mesh.resetDrawCache(passId); + } + } + _renderWithFrameGraph(updateCameras = true, ignoreAnimations = false) { + this.activeCamera = null; + this._activeParticleSystems.reset(); + this._activeSkeletons.reset(); + // Update Cameras + if (updateCameras) { + for (const camera of this.cameras) { + camera.update(); + if (camera.cameraRigMode !== 0) { + // rig cameras + for (let index = 0; index < camera._rigCameras.length; index++) { + camera._rigCameras[index].update(); + } + } + } + } + // We must keep these steps because the procedural texture component relies on them. + // TODO: move the procedural texture component to the frame graph. + for (const step of this._beforeClearStage) { + step.action(); + } + // Process meshes + const meshes = this.getActiveMeshCandidates(); + const len = meshes.length; + for (let i = 0; i < len; i++) { + const mesh = meshes.data[i]; + if (mesh.isBlocked) { + continue; + } + this._totalVertices.addCount(mesh.getTotalVertices(), false); + if (!mesh.isReady() || !mesh.isEnabled() || mesh.scaling.hasAZeroComponent) { + continue; + } + mesh.computeWorldMatrix(); + if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(12, 13)) { + this._meshesForIntersections.pushNoDuplicate(mesh); + } + } + // Animate Particle systems + if (this.particlesEnabled) { + for (let particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) { + const particleSystem = this.particleSystems[particleIndex]; + if (!particleSystem.isStarted() || !particleSystem.emitter) { + continue; + } + const emitter = particleSystem.emitter; + if (!emitter.position || emitter.isEnabled()) { + this._activeParticleSystems.push(particleSystem); + particleSystem.animate(); + } + } + } + // Render the graph + this.frameGraph?.execute(); + } + /** + * Render the scene + * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default) + * @param ignoreAnimations defines a boolean indicating if animations should not be executed (false by default) + */ + render(updateCameras = true, ignoreAnimations = false) { + if (this.isDisposed) { + return; + } + if (this.onReadyObservable.hasObservers() && this._executeWhenReadyTimeoutId === null) { + this._checkIsReady(); + } + this._frameId++; + this._defaultFrameBufferCleared = false; + this._checkCameraRenderTarget(this.activeCamera); + if (this.activeCameras?.length) { + this.activeCameras.forEach(this._checkCameraRenderTarget); + } + // Register components that have been associated lately to the scene. + this._registerTransientComponents(); + this._activeParticles.fetchNewFrame(); + this._totalVertices.fetchNewFrame(); + this._activeIndices.fetchNewFrame(); + this._activeBones.fetchNewFrame(); + this._meshesForIntersections.reset(); + this.resetCachedMaterial(); + this.onBeforeAnimationsObservable.notifyObservers(this); + // Actions + if (this.actionManager) { + this.actionManager.processTrigger(11); + } + // Animations + if (!ignoreAnimations) { + this.animate(); + } + // Before camera update steps + for (const step of this._beforeCameraUpdateStage) { + step.action(); + } + // Update Cameras + if (updateCameras) { + if (this.activeCameras && this.activeCameras.length > 0) { + for (let cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) { + const camera = this.activeCameras[cameraIndex]; + camera.update(); + if (camera.cameraRigMode !== 0) { + // rig cameras + for (let index = 0; index < camera._rigCameras.length; index++) { + camera._rigCameras[index].update(); + } + } + } + } + else if (this.activeCamera) { + this.activeCamera.update(); + if (this.activeCamera.cameraRigMode !== 0) { + // rig cameras + for (let index = 0; index < this.activeCamera._rigCameras.length; index++) { + this.activeCamera._rigCameras[index].update(); + } + } + } + } + // Before render + this.onBeforeRenderObservable.notifyObservers(this); + // Custom render function? + if (this.customRenderFunction) { + this._renderId++; + this._engine.currentRenderPassId = 0; + this.customRenderFunction(updateCameras, ignoreAnimations); + } + else { + const engine = this.getEngine(); + // Customs render targets + this.onBeforeRenderTargetsRenderObservable.notifyObservers(this); + const currentActiveCamera = this.activeCameras?.length ? this.activeCameras[0] : this.activeCamera; + if (this.renderTargetsEnabled) { + Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0); + this._intermediateRendering = true; + for (let customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) { + const renderTarget = this.customRenderTargets[customIndex]; + if (renderTarget._shouldRender()) { + this._renderId++; + this.activeCamera = renderTarget.activeCamera || this.activeCamera; + if (!this.activeCamera) { + throw new Error("Active camera not set"); + } + // Viewport + engine.setViewport(this.activeCamera.viewport); + // Camera + this.updateTransformMatrix(); + renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets); + } + } + Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0); + this._intermediateRendering = false; + this._renderId++; + } + this._engine.currentRenderPassId = currentActiveCamera?.renderPassId ?? 0; + // Restore back buffer + this.activeCamera = currentActiveCamera; + if (this._activeCamera && this._activeCamera.cameraRigMode !== 22 && !this.prePass) { + this._bindFrameBuffer(this._activeCamera, false); + } + this.onAfterRenderTargetsRenderObservable.notifyObservers(this); + for (const step of this._beforeClearStage) { + step.action(); + } + // Clear + this._clearFrameBuffer(this.activeCamera); + // Collects render targets from external components. + for (const step of this._gatherRenderTargetsStage) { + step.action(this._renderTargets); + } + // Multi-cameras? + if (this.activeCameras && this.activeCameras.length > 0) { + for (let cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) { + this._processSubCameras(this.activeCameras[cameraIndex], cameraIndex > 0); + } + } + else { + if (!this.activeCamera) { + throw new Error("No camera defined"); + } + this._processSubCameras(this.activeCamera, !!this.activeCamera.outputRenderTarget); + } + } + // Intersection checks + this._checkIntersections(); + // Executes the after render stage actions. + for (const step of this._afterRenderStage) { + step.action(); + } + // After render + if (this.afterRender) { + this.afterRender(); + } + this.onAfterRenderObservable.notifyObservers(this); + // Cleaning + if (this._toBeDisposed.length) { + for (let index = 0; index < this._toBeDisposed.length; index++) { + const data = this._toBeDisposed[index]; + if (data) { + data.dispose(); + } + } + this._toBeDisposed.length = 0; + } + if (this.dumpNextRenderTargets) { + this.dumpNextRenderTargets = false; + } + this._activeBones.addCount(0, true); + this._activeIndices.addCount(0, true); + this._activeParticles.addCount(0, true); + this._engine.restoreDefaultFramebuffer(); + } + /** + * Freeze all materials + * A frozen material will not be updatable but should be faster to render + * Note: multimaterials will not be frozen, but their submaterials will + */ + freezeMaterials() { + for (let i = 0; i < this.materials.length; i++) { + this.materials[i].freeze(); + } + } + /** + * Unfreeze all materials + * A frozen material will not be updatable but should be faster to render + */ + unfreezeMaterials() { + for (let i = 0; i < this.materials.length; i++) { + this.materials[i].unfreeze(); + } + } + /** + * Releases all held resources + */ + dispose() { + if (this.isDisposed) { + return; + } + this.beforeRender = null; + this.afterRender = null; + this.metadata = null; + this.skeletons.length = 0; + this.morphTargetManagers.length = 0; + this._transientComponents.length = 0; + this._isReadyForMeshStage.clear(); + this._beforeEvaluateActiveMeshStage.clear(); + this._evaluateSubMeshStage.clear(); + this._preActiveMeshStage.clear(); + this._cameraDrawRenderTargetStage.clear(); + this._beforeCameraDrawStage.clear(); + this._beforeRenderTargetDrawStage.clear(); + this._beforeRenderingGroupDrawStage.clear(); + this._beforeRenderingMeshStage.clear(); + this._afterRenderingMeshStage.clear(); + this._afterRenderingGroupDrawStage.clear(); + this._afterCameraDrawStage.clear(); + this._afterRenderTargetDrawStage.clear(); + this._afterRenderStage.clear(); + this._beforeCameraUpdateStage.clear(); + this._beforeClearStage.clear(); + this._gatherRenderTargetsStage.clear(); + this._gatherActiveCameraRenderTargetsStage.clear(); + this._pointerMoveStage.clear(); + this._pointerDownStage.clear(); + this._pointerUpStage.clear(); + this.importedMeshesFiles = []; + if (this._activeAnimatables && this.stopAllAnimations) { + // Ensures that no animatable notifies a callback that could start a new animation group, constantly adding new animatables to the active list... + this._activeAnimatables.forEach((animatable) => { + animatable.onAnimationEndObservable.clear(); + animatable.onAnimationEnd = null; + }); + this.stopAllAnimations(); + } + this.resetCachedMaterial(); + // Smart arrays + if (this.activeCamera) { + this.activeCamera._activeMeshes.dispose(); + this.activeCamera = null; + } + this.activeCameras = null; + this._activeMeshes.dispose(); + this._renderingManager.dispose(); + this._processedMaterials.dispose(); + this._activeParticleSystems.dispose(); + this._activeSkeletons.dispose(); + this._softwareSkinnedMeshes.dispose(); + this._renderTargets.dispose(); + this._materialsRenderTargets.dispose(); + this._registeredForLateAnimationBindings.dispose(); + this._meshesForIntersections.dispose(); + this._toBeDisposed.length = 0; + // Abort active requests + const activeRequests = this._activeRequests.slice(); + for (const request of activeRequests) { + request.abort(); + } + this._activeRequests.length = 0; + // Events + try { + this.onDisposeObservable.notifyObservers(this); + } + catch (e) { + Logger.Error("An error occurred while calling onDisposeObservable!", e); + } + this.detachControl(); + // Detach cameras + const canvas = this._engine.getInputElement(); + if (canvas) { + for (let index = 0; index < this.cameras.length; index++) { + this.cameras[index].detachControl(); + } + } + // Release animation groups + this._disposeList(this.animationGroups); + // Release lights + this._disposeList(this.lights); + // Release materials + if (this._defaultMaterial) { + this._defaultMaterial.dispose(); + } + this._disposeList(this.multiMaterials); + this._disposeList(this.materials); + // Release meshes + this._disposeList(this.meshes, (item) => item.dispose(true)); + this._disposeList(this.transformNodes, (item) => item.dispose(true)); + // Release cameras + const cameras = this.cameras; + this._disposeList(cameras); + // Release particles + this._disposeList(this.particleSystems); + // Release postProcesses + this._disposeList(this.postProcesses); + // Release textures + this._disposeList(this.textures); + // Release morph targets + this._disposeList(this.morphTargetManagers); + // Release UBO + this._sceneUbo.dispose(); + if (this._multiviewSceneUbo) { + this._multiviewSceneUbo.dispose(); + } + // Post-processes + this.postProcessManager.dispose(); + // Components + this._disposeList(this._components); + // Remove from engine + let index = this._engine.scenes.indexOf(this); + if (index > -1) { + this._engine.scenes.splice(index, 1); + } + if (EngineStore._LastCreatedScene === this) { + EngineStore._LastCreatedScene = null; + let engineIndex = EngineStore.Instances.length - 1; + while (engineIndex >= 0) { + const engine = EngineStore.Instances[engineIndex]; + if (engine.scenes.length > 0) { + EngineStore._LastCreatedScene = engine.scenes[this._engine.scenes.length - 1]; + break; + } + engineIndex--; + } + } + index = this._engine._virtualScenes.indexOf(this); + if (index > -1) { + this._engine._virtualScenes.splice(index, 1); + } + this._engine.wipeCaches(true); + this.onDisposeObservable.clear(); + this.onBeforeRenderObservable.clear(); + this.onAfterRenderObservable.clear(); + this.onBeforeRenderTargetsRenderObservable.clear(); + this.onAfterRenderTargetsRenderObservable.clear(); + this.onAfterStepObservable.clear(); + this.onBeforeStepObservable.clear(); + this.onBeforeActiveMeshesEvaluationObservable.clear(); + this.onAfterActiveMeshesEvaluationObservable.clear(); + this.onBeforeParticlesRenderingObservable.clear(); + this.onAfterParticlesRenderingObservable.clear(); + this.onBeforeDrawPhaseObservable.clear(); + this.onAfterDrawPhaseObservable.clear(); + this.onBeforeAnimationsObservable.clear(); + this.onAfterAnimationsObservable.clear(); + this.onDataLoadedObservable.clear(); + this.onBeforeRenderingGroupObservable.clear(); + this.onAfterRenderingGroupObservable.clear(); + this.onMeshImportedObservable.clear(); + this.onBeforeCameraRenderObservable.clear(); + this.onAfterCameraRenderObservable.clear(); + this.onAfterRenderCameraObservable.clear(); + this.onReadyObservable.clear(); + this.onNewCameraAddedObservable.clear(); + this.onCameraRemovedObservable.clear(); + this.onNewLightAddedObservable.clear(); + this.onLightRemovedObservable.clear(); + this.onNewGeometryAddedObservable.clear(); + this.onGeometryRemovedObservable.clear(); + this.onNewTransformNodeAddedObservable.clear(); + this.onTransformNodeRemovedObservable.clear(); + this.onNewMeshAddedObservable.clear(); + this.onMeshRemovedObservable.clear(); + this.onNewSkeletonAddedObservable.clear(); + this.onSkeletonRemovedObservable.clear(); + this.onNewMaterialAddedObservable.clear(); + this.onNewMultiMaterialAddedObservable.clear(); + this.onMaterialRemovedObservable.clear(); + this.onMultiMaterialRemovedObservable.clear(); + this.onNewTextureAddedObservable.clear(); + this.onTextureRemovedObservable.clear(); + this.onPrePointerObservable.clear(); + this.onPointerObservable.clear(); + this.onPreKeyboardObservable.clear(); + this.onKeyboardObservable.clear(); + this.onActiveCameraChanged.clear(); + this.onScenePerformancePriorityChangedObservable.clear(); + this.onClearColorChangedObservable.clear(); + this.onEnvironmentTextureChangedObservable.clear(); + this.onMeshUnderPointerUpdatedObservable.clear(); + this._isDisposed = true; + } + _disposeList(items, callback) { + const itemsCopy = items.slice(0); + callback = callback ?? ((item) => item.dispose()); + for (const item of itemsCopy) { + callback(item); + } + items.length = 0; + } + /** + * Gets if the scene is already disposed + */ + get isDisposed() { + return this._isDisposed; + } + /** + * Call this function to reduce memory footprint of the scene. + * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly) + */ + clearCachedVertexData() { + for (let meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) { + const mesh = this.meshes[meshIndex]; + const geometry = mesh.geometry; + if (geometry) { + geometry.clearCachedData(); + } + } + } + /** + * This function will remove the local cached buffer data from texture. + * It will save memory but will prevent the texture from being rebuilt + */ + cleanCachedTextureBuffer() { + for (const baseTexture of this.textures) { + const buffer = baseTexture._buffer; + if (buffer) { + baseTexture._buffer = null; + } + } + } + /** + * Get the world extend vectors with an optional filter + * + * @param filterPredicate the predicate - which meshes should be included when calculating the world size + * @returns {{ min: Vector3; max: Vector3 }} min and max vectors + */ + getWorldExtends(filterPredicate) { + const min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + const max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + filterPredicate = filterPredicate || (() => true); + this.meshes.filter(filterPredicate).forEach((mesh) => { + mesh.computeWorldMatrix(true); + if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) { + return; + } + const boundingInfo = mesh.getBoundingInfo(); + const minBox = boundingInfo.boundingBox.minimumWorld; + const maxBox = boundingInfo.boundingBox.maximumWorld; + Vector3.CheckExtends(minBox, min, max); + Vector3.CheckExtends(maxBox, min, max); + }); + return { + min: min, + max: max, + }; + } + // Picking + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Creates a ray that can be used to pick in the scene + * @param x defines the x coordinate of the origin (on-screen) + * @param y defines the y coordinate of the origin (on-screen) + * @param world defines the world matrix to use if you want to pick in object space (instead of world space) + * @param camera defines the camera to use for the picking + * @param cameraViewSpace defines if picking will be done in view space (false by default) + * @returns a Ray + */ + createPickingRay(x, y, world, camera, cameraViewSpace = false) { + throw _WarnImport("Ray"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Creates a ray that can be used to pick in the scene + * @param x defines the x coordinate of the origin (on-screen) + * @param y defines the y coordinate of the origin (on-screen) + * @param world defines the world matrix to use if you want to pick in object space (instead of world space) + * @param result defines the ray where to store the picking ray + * @param camera defines the camera to use for the picking + * @param cameraViewSpace defines if picking will be done in view space (false by default) + * @param enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default) + * @returns the current scene + */ + createPickingRayToRef(x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) { + throw _WarnImport("Ray"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Creates a ray that can be used to pick in the scene + * @param x defines the x coordinate of the origin (on-screen) + * @param y defines the y coordinate of the origin (on-screen) + * @param camera defines the camera to use for the picking + * @returns a Ray + */ + createPickingRayInCameraSpace(x, y, camera) { + throw _WarnImport("Ray"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Creates a ray that can be used to pick in the scene + * @param x defines the x coordinate of the origin (on-screen) + * @param y defines the y coordinate of the origin (on-screen) + * @param result defines the ray where to store the picking ray + * @param camera defines the camera to use for the picking + * @returns the current scene + */ + createPickingRayInCameraSpaceToRef(x, y, result, camera) { + throw _WarnImport("Ray"); + } + /** Launch a ray to try to pick a mesh in the scene + * @param x position on screen + * @param y position on screen + * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced + * @param fastCheck defines if the first intersection will be used (and not the closest) + * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @returns a PickingInfo + */ + pick(x, y, predicate, fastCheck, camera, trianglePredicate) { + const warn = _WarnImport("Ray", true); + if (warn) { + Logger.Warn(warn); + } + // Dummy info if picking as not been imported + return new PickingInfo(); + } + /** Launch a ray to try to pick a mesh in the scene using only bounding information of the main mesh (not using submeshes) + * @param x position on screen + * @param y position on screen + * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced + * @param fastCheck defines if the first intersection will be used (and not the closest) + * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used + * @returns a PickingInfo (Please note that some info will not be set like distance, bv, bu and everything that cannot be capture by only using bounding infos) + */ + pickWithBoundingInfo(x, y, predicate, fastCheck, camera) { + const warn = _WarnImport("Ray", true); + if (warn) { + Logger.Warn(warn); + } + // Dummy info if picking as not been imported + return new PickingInfo(); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Use the given ray to pick a mesh in the scene. A mesh triangle can be picked both from its front and back sides, + * irrespective of orientation. + * @param ray The ray to use to pick meshes + * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced + * @param fastCheck defines if the first intersection will be used (and not the closest) + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @returns a PickingInfo + */ + pickWithRay(ray, predicate, fastCheck, trianglePredicate) { + throw _WarnImport("Ray"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Launch a ray to try to pick a mesh in the scene. A mesh triangle can be picked both from its front and back sides, + * irrespective of orientation. + * @param x X position on screen + * @param y Y position on screen + * @param predicate Predicate function used to determine eligible meshes and instances. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced + * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @returns an array of PickingInfo + */ + multiPick(x, y, predicate, camera, trianglePredicate) { + throw _WarnImport("Ray"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Launch a ray to try to pick a mesh in the scene + * @param ray Ray to use + * @param predicate Predicate function used to determine eligible meshes and instances. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @returns an array of PickingInfo + */ + multiPickWithRay(ray, predicate, trianglePredicate) { + throw _WarnImport("Ray"); + } + /** + * Force the value of meshUnderPointer + * @param mesh defines the mesh to use + * @param pointerId optional pointer id when using more than one pointer + * @param pickResult optional pickingInfo data used to find mesh + */ + setPointerOverMesh(mesh, pointerId, pickResult) { + this._inputManager.setPointerOverMesh(mesh, pointerId, pickResult); + } + /** + * Gets the mesh under the pointer + * @returns a Mesh or null if no mesh is under the pointer + */ + getPointerOverMesh() { + return this._inputManager.getPointerOverMesh(); + } + // Misc. + /** @internal */ + _rebuildGeometries() { + for (const geometry of this.geometries) { + geometry._rebuild(); + } + for (const mesh of this.meshes) { + mesh._rebuild(); + } + if (this.postProcessManager) { + this.postProcessManager._rebuild(); + } + for (const component of this._components) { + component.rebuild(); + } + for (const system of this.particleSystems) { + system.rebuild(); + } + if (this.spriteManagers) { + for (const spriteMgr of this.spriteManagers) { + spriteMgr.rebuild(); + } + } + } + /** @internal */ + _rebuildTextures() { + for (const texture of this.textures) { + texture._rebuild(true); + } + this.markAllMaterialsAsDirty(1); + } + /** + * Get from a list of objects by tags + * @param list the list of objects to use + * @param tagsQuery the query to use + * @param filter a predicate to filter for tags + * @returns + */ + _getByTags(list, tagsQuery, filter) { + if (tagsQuery === undefined) { + // returns the complete list (could be done with Tags.MatchesQuery but no need to have a for-loop here) + return list; + } + const listByTags = []; + for (const i in list) { + const item = list[i]; + if (Tags && Tags.MatchesQuery(item, tagsQuery) && (!filter || filter(item))) { + listByTags.push(item); + } + } + return listByTags; + } + /** + * Get a list of meshes by tags + * @param tagsQuery defines the tags query to use + * @param filter defines a predicate used to filter results + * @returns an array of Mesh + */ + getMeshesByTags(tagsQuery, filter) { + return this._getByTags(this.meshes, tagsQuery, filter); + } + /** + * Get a list of cameras by tags + * @param tagsQuery defines the tags query to use + * @param filter defines a predicate used to filter results + * @returns an array of Camera + */ + getCamerasByTags(tagsQuery, filter) { + return this._getByTags(this.cameras, tagsQuery, filter); + } + /** + * Get a list of lights by tags + * @param tagsQuery defines the tags query to use + * @param filter defines a predicate used to filter results + * @returns an array of Light + */ + getLightsByTags(tagsQuery, filter) { + return this._getByTags(this.lights, tagsQuery, filter); + } + /** + * Get a list of materials by tags + * @param tagsQuery defines the tags query to use + * @param filter defines a predicate used to filter results + * @returns an array of Material + */ + getMaterialByTags(tagsQuery, filter) { + return this._getByTags(this.materials, tagsQuery, filter).concat(this._getByTags(this.multiMaterials, tagsQuery, filter)); + } + /** + * Get a list of transform nodes by tags + * @param tagsQuery defines the tags query to use + * @param filter defines a predicate used to filter results + * @returns an array of TransformNode + */ + getTransformNodesByTags(tagsQuery, filter) { + return this._getByTags(this.transformNodes, tagsQuery, filter); + } + /** + * Overrides the default sort function applied in the rendering group to prepare the meshes. + * This allowed control for front to back rendering or reversly depending of the special needs. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param opaqueSortCompareFn The opaque queue comparison function use to sort. + * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. + * @param transparentSortCompareFn The transparent queue comparison function use to sort. + */ + setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { + this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn); + } + /** + * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. + * @param depth Automatically clears depth between groups if true and autoClear is true. + * @param stencil Automatically clears stencil between groups if true and autoClear is true. + */ + setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) { + this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil); + } + /** + * Gets the current auto clear configuration for one rendering group of the rendering + * manager. + * @param index the rendering group index to get the information for + * @returns The auto clear setup for the requested rendering group + */ + getAutoClearDepthStencilSetup(index) { + return this._renderingManager.getAutoClearDepthStencilSetup(index); + } + /** @internal */ + _forceBlockMaterialDirtyMechanism(value) { + this._blockMaterialDirtyMechanism = value; + } + /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */ + get blockMaterialDirtyMechanism() { + return this._blockMaterialDirtyMechanism; + } + set blockMaterialDirtyMechanism(value) { + if (this._blockMaterialDirtyMechanism === value) { + return; + } + this._blockMaterialDirtyMechanism = value; + if (!value) { + // Do a complete update + this.markAllMaterialsAsDirty(127); + } + } + /** + * Will flag all materials as dirty to trigger new shader compilation + * @param flag defines the flag used to specify which material part must be marked as dirty + * @param predicate If not null, it will be used to specify if a material has to be marked as dirty + */ + markAllMaterialsAsDirty(flag, predicate) { + if (this._blockMaterialDirtyMechanism) { + return; + } + for (const material of this.materials) { + if (predicate && !predicate(material)) { + continue; + } + material.markAsDirty(flag); + } + } + /** + * @internal + */ + _loadFile(fileOrUrl, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError, onOpened) { + const request = LoadFile(fileOrUrl, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError, onOpened); + this._activeRequests.push(request); + request.onCompleteObservable.add((request) => { + this._activeRequests.splice(this._activeRequests.indexOf(request), 1); + }); + return request; + } + /** + * @internal + */ + _loadFileAsync(fileOrUrl, onProgress, useOfflineSupport, useArrayBuffer, onOpened) { + return new Promise((resolve, reject) => { + this._loadFile(fileOrUrl, (data) => { + resolve(data); + }, onProgress, useOfflineSupport, useArrayBuffer, (request, exception) => { + reject(exception); + }, onOpened); + }); + } + /** + * @internal + */ + _requestFile(url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError, onOpened) { + const request = RequestFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError, onOpened); + this._activeRequests.push(request); + request.onCompleteObservable.add((request) => { + this._activeRequests.splice(this._activeRequests.indexOf(request), 1); + }); + return request; + } + /** + * @internal + */ + _requestFileAsync(url, onProgress, useOfflineSupport, useArrayBuffer, onOpened) { + return new Promise((resolve, reject) => { + this._requestFile(url, (data) => { + resolve(data); + }, onProgress, useOfflineSupport, useArrayBuffer, (error) => { + reject(error); + }, onOpened); + }); + } + /** + * @internal + */ + _readFile(file, onSuccess, onProgress, useArrayBuffer, onError) { + const request = ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError); + this._activeRequests.push(request); + request.onCompleteObservable.add((request) => { + this._activeRequests.splice(this._activeRequests.indexOf(request), 1); + }); + return request; + } + /** + * @internal + */ + _readFileAsync(file, onProgress, useArrayBuffer) { + return new Promise((resolve, reject) => { + this._readFile(file, (data) => { + resolve(data); + }, onProgress, useArrayBuffer, (error) => { + reject(error); + }); + }); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * This method gets the performance collector belonging to the scene, which is generally shared with the inspector. + * @returns the perf collector belonging to the scene. + */ + getPerfCollector() { + throw _WarnImport("performanceViewerSceneExtension"); + } + // deprecated + /** + * Sets the active camera of the scene using its Id + * @param id defines the camera's Id + * @returns the new active camera or null if none found. + * @deprecated Please use setActiveCameraById instead + */ + setActiveCameraByID(id) { + return this.setActiveCameraById(id); + } + /** + * Get a material using its id + * @param id defines the material's Id + * @returns the material or null if none found. + * @deprecated Please use getMaterialById instead + */ + getMaterialByID(id) { + return this.getMaterialById(id); + } + /** + * Gets a the last added material using a given id + * @param id defines the material's Id + * @returns the last material with the given id or null if none found. + * @deprecated Please use getLastMaterialById instead + */ + getLastMaterialByID(id) { + return this.getLastMaterialById(id); + } + /** + * Get a texture using its unique id + * @param uniqueId defines the texture's unique id + * @returns the texture or null if none found. + * @deprecated Please use getTextureByUniqueId instead + */ + getTextureByUniqueID(uniqueId) { + return this.getTextureByUniqueId(uniqueId); + } + /** + * Gets a camera using its Id + * @param id defines the Id to look for + * @returns the camera or null if not found + * @deprecated Please use getCameraById instead + */ + getCameraByID(id) { + return this.getCameraById(id); + } + /** + * Gets a camera using its unique Id + * @param uniqueId defines the unique Id to look for + * @returns the camera or null if not found + * @deprecated Please use getCameraByUniqueId instead + */ + getCameraByUniqueID(uniqueId) { + return this.getCameraByUniqueId(uniqueId); + } + /** + * Gets a bone using its Id + * @param id defines the bone's Id + * @returns the bone or null if not found + * @deprecated Please use getBoneById instead + */ + getBoneByID(id) { + return this.getBoneById(id); + } + /** + * Gets a light node using its Id + * @param id defines the light's Id + * @returns the light or null if none found. + * @deprecated Please use getLightById instead + */ + getLightByID(id) { + return this.getLightById(id); + } + /** + * Gets a light node using its scene-generated unique Id + * @param uniqueId defines the light's unique Id + * @returns the light or null if none found. + * @deprecated Please use getLightByUniqueId instead + */ + getLightByUniqueID(uniqueId) { + return this.getLightByUniqueId(uniqueId); + } + /** + * Gets a particle system by Id + * @param id defines the particle system Id + * @returns the corresponding system or null if none found + * @deprecated Please use getParticleSystemById instead + */ + getParticleSystemByID(id) { + return this.getParticleSystemById(id); + } + /** + * Gets a geometry using its Id + * @param id defines the geometry's Id + * @returns the geometry or null if none found. + * @deprecated Please use getGeometryById instead + */ + getGeometryByID(id) { + return this.getGeometryById(id); + } + /** + * Gets the first added mesh found of a given Id + * @param id defines the Id to search for + * @returns the mesh found or null if not found at all + * @deprecated Please use getMeshById instead + */ + getMeshByID(id) { + return this.getMeshById(id); + } + /** + * Gets a mesh with its auto-generated unique Id + * @param uniqueId defines the unique Id to search for + * @returns the found mesh or null if not found at all. + * @deprecated Please use getMeshByUniqueId instead + */ + getMeshByUniqueID(uniqueId) { + return this.getMeshByUniqueId(uniqueId); + } + /** + * Gets a the last added mesh using a given Id + * @param id defines the Id to search for + * @returns the found mesh or null if not found at all. + * @deprecated Please use getLastMeshById instead + */ + getLastMeshByID(id) { + return this.getLastMeshById(id); + } + /** + * Gets a list of meshes using their Id + * @param id defines the Id to search for + * @returns a list of meshes + * @deprecated Please use getMeshesById instead + */ + getMeshesByID(id) { + return this.getMeshesById(id); + } + /** + * Gets the first added transform node found of a given Id + * @param id defines the Id to search for + * @returns the found transform node or null if not found at all. + * @deprecated Please use getTransformNodeById instead + */ + getTransformNodeByID(id) { + return this.getTransformNodeById(id); + } + /** + * Gets a transform node with its auto-generated unique Id + * @param uniqueId defines the unique Id to search for + * @returns the found transform node or null if not found at all. + * @deprecated Please use getTransformNodeByUniqueId instead + */ + getTransformNodeByUniqueID(uniqueId) { + return this.getTransformNodeByUniqueId(uniqueId); + } + /** + * Gets a list of transform nodes using their Id + * @param id defines the Id to search for + * @returns a list of transform nodes + * @deprecated Please use getTransformNodesById instead + */ + getTransformNodesByID(id) { + return this.getTransformNodesById(id); + } + /** + * Gets a node (Mesh, Camera, Light) using a given Id + * @param id defines the Id to search for + * @returns the found node or null if not found at all + * @deprecated Please use getNodeById instead + */ + getNodeByID(id) { + return this.getNodeById(id); + } + /** + * Gets a the last added node (Mesh, Camera, Light) using a given Id + * @param id defines the Id to search for + * @returns the found node or null if not found at all + * @deprecated Please use getLastEntryById instead + */ + getLastEntryByID(id) { + return this.getLastEntryById(id); + } + /** + * Gets a skeleton using a given Id (if many are found, this function will pick the last one) + * @param id defines the Id to search for + * @returns the found skeleton or null if not found at all. + * @deprecated Please use getLastSkeletonById instead + */ + getLastSkeletonByID(id) { + return this.getLastSkeletonById(id); + } +} +/** The fog is deactivated */ +Scene.FOGMODE_NONE = 0; +/** The fog density is following an exponential function */ +Scene.FOGMODE_EXP = 1; +/** The fog density is following an exponential function faster than FOGMODE_EXP */ +Scene.FOGMODE_EXP2 = 2; +/** The fog density is following a linear function. */ +Scene.FOGMODE_LINEAR = 3; +/** + * Gets or sets the minimum deltatime when deterministic lock step is enabled + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep + */ +Scene.MinDeltaTime = 1.0; +/** + * Gets or sets the maximum deltatime when deterministic lock step is enabled + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep + */ +Scene.MaxDeltaTime = 1000.0; +Scene._OriginalDefaultMaterialFactory = Scene.DefaultMaterialFactory; +// Register Class Name +RegisterClass("BABYLON.Scene", Scene); + +class AppScene extends Monobehiver { + object; + constructor(mainApp) { + super(mainApp); + this.object = null; + } + /** 初始化场景 */ + Awake() { + this.object = new Scene(this.mainApp.appEngin.object); + this.object.clearColor = new Color4(0, 0, 0, 0); + this.object.skipFrustumClipping = true; + } +} + +/** @internal */ +class _InternalNodeDataInfo { + constructor() { + this._doNotSerialize = false; + this._isDisposed = false; + this._sceneRootNodesIndex = -1; + this._isEnabled = true; + this._isParentEnabled = true; + this._isReady = true; + this._onEnabledStateChangedObservable = new Observable(); + this._onClonedObservable = new Observable(); + } +} +/** + * Node is the basic class for all scene objects (Mesh, Light, Camera.) + */ +let Node$2 = class Node { + /** + * Add a new node constructor + * @param type defines the type name of the node to construct + * @param constructorFunc defines the constructor function + */ + static AddNodeConstructor(type, constructorFunc) { + this._NodeConstructors[type] = constructorFunc; + } + /** + * Returns a node constructor based on type name + * @param type defines the type name + * @param name defines the new node name + * @param scene defines the hosting scene + * @param options defines optional options to transmit to constructors + * @returns the new constructor or null + */ + static Construct(type, name, scene, options) { + const constructorFunc = this._NodeConstructors[type]; + if (!constructorFunc) { + return null; + } + return constructorFunc(name, scene, options); + } + /** + * Gets or sets the accessibility tag to describe the node for accessibility purpose. + */ + set accessibilityTag(value) { + this._accessibilityTag = value; + this.onAccessibilityTagChangedObservable.notifyObservers(value); + } + get accessibilityTag() { + return this._accessibilityTag; + } + /** + * Gets or sets a boolean used to define if the node must be serialized + */ + get doNotSerialize() { + if (this._nodeDataStorage._doNotSerialize) { + return true; + } + if (this._parentNode) { + return this._parentNode.doNotSerialize; + } + return false; + } + set doNotSerialize(value) { + this._nodeDataStorage._doNotSerialize = value; + } + /** + * Gets a boolean indicating if the node has been disposed + * @returns true if the node was disposed + */ + isDisposed() { + return this._nodeDataStorage._isDisposed; + } + /** + * Gets or sets the parent of the node (without keeping the current position in the scene) + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent + */ + set parent(parent) { + if (this._parentNode === parent) { + return; + } + const previousParentNode = this._parentNode; + // Remove self from list of children of parent + if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) { + const index = this._parentNode._children.indexOf(this); + if (index !== -1) { + this._parentNode._children.splice(index, 1); + } + if (!parent && !this._nodeDataStorage._isDisposed) { + this._addToSceneRootNodes(); + } + } + // Store new parent + this._parentNode = parent; + this._isDirty = true; + // Add as child to new parent + if (this._parentNode) { + if (this._parentNode._children === undefined || this._parentNode._children === null) { + this._parentNode._children = new Array(); + } + this._parentNode._children.push(this); + if (!previousParentNode) { + this._removeFromSceneRootNodes(); + } + } + // Enabled state + this._syncParentEnabledState(); + } + get parent() { + return this._parentNode; + } + /** + * @internal + */ + _serializeAsParent(serializationObject) { + serializationObject.parentId = this.uniqueId; + } + /** @internal */ + _addToSceneRootNodes() { + if (this._nodeDataStorage._sceneRootNodesIndex === -1) { + this._nodeDataStorage._sceneRootNodesIndex = this._scene.rootNodes.length; + this._scene.rootNodes.push(this); + } + } + /** @internal */ + _removeFromSceneRootNodes() { + if (this._nodeDataStorage._sceneRootNodesIndex !== -1) { + const rootNodes = this._scene.rootNodes; + const lastIdx = rootNodes.length - 1; + rootNodes[this._nodeDataStorage._sceneRootNodesIndex] = rootNodes[lastIdx]; + rootNodes[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex = this._nodeDataStorage._sceneRootNodesIndex; + this._scene.rootNodes.pop(); + this._nodeDataStorage._sceneRootNodesIndex = -1; + } + } + /** + * Gets or sets the animation properties override + */ + get animationPropertiesOverride() { + if (!this._animationPropertiesOverride) { + return this._scene.animationPropertiesOverride; + } + return this._animationPropertiesOverride; + } + set animationPropertiesOverride(value) { + this._animationPropertiesOverride = value; + } + /** + * Gets a string identifying the name of the class + * @returns "Node" string + */ + getClassName() { + return "Node"; + } + /** + * Sets a callback that will be raised when the node will be disposed + */ + set onDispose(callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + } + /** + * An event triggered when the enabled state of the node changes + */ + get onEnabledStateChangedObservable() { + return this._nodeDataStorage._onEnabledStateChangedObservable; + } + /** + * An event triggered when the node is cloned + */ + get onClonedObservable() { + return this._nodeDataStorage._onClonedObservable; + } + /** + * Creates a new Node + * @param name the name and id to be given to this node + * @param scene the scene this node will be added to + * @param isPure indicates this Node is just a Node, and not a derived class like Mesh or Camera + */ + constructor(name, scene = null, isPure = true) { + this._isDirty = false; + this._nodeDataStorage = new _InternalNodeDataInfo(); + /** + * Gets or sets a string used to store user defined state for the node + */ + this.state = ""; + /** + * Gets or sets an object used to store user defined information for the node + */ + this.metadata = null; + /** + * For internal use only. Please do not use. + */ + this.reservedDataStore = null; + this._accessibilityTag = null; + /** + * Observable fired when an accessibility tag is changed + */ + this.onAccessibilityTagChangedObservable = new Observable(); + /** @internal */ + this._parentContainer = null; + /** + * Gets a list of Animations associated with the node + */ + this.animations = []; + this._ranges = {}; + /** + * Callback raised when the node is ready to be used + */ + this.onReady = null; + /** @internal */ + this._currentRenderId = -1; + this._parentUpdateId = -1; + /** @internal */ + this._childUpdateId = -1; + /** @internal */ + this._waitingParentId = null; + /** @internal */ + this._waitingParentInstanceIndex = null; + /** @internal */ + this._waitingParsedUniqueId = null; + /** @internal */ + this._cache = {}; + this._parentNode = null; + /** @internal */ + this._children = null; + /** @internal */ + this._worldMatrix = Matrix.Identity(); + /** @internal */ + this._worldMatrixDeterminant = 0; + /** @internal */ + this._worldMatrixDeterminantIsDirty = true; + this._animationPropertiesOverride = null; + /** @internal */ + this._isNode = true; + /** + * An event triggered when the mesh is disposed + */ + this.onDisposeObservable = new Observable(); + this._onDisposeObserver = null; + // Behaviors + this._behaviors = new Array(); + this.name = name; + this.id = name; + this._scene = (scene || EngineStore.LastCreatedScene); + this.uniqueId = this._scene.getUniqueId(); + this._initCache(); + if (isPure) { + this._addToSceneRootNodes(); + } + } + /** + * Gets the scene of the node + * @returns a scene + */ + getScene() { + return this._scene; + } + /** + * Gets the engine of the node + * @returns a Engine + */ + getEngine() { + return this._scene.getEngine(); + } + /** + * Attach a behavior to the node + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors + * @param behavior defines the behavior to attach + * @param attachImmediately defines that the behavior must be attached even if the scene is still loading + * @returns the current Node + */ + addBehavior(behavior, attachImmediately = false) { + const index = this._behaviors.indexOf(behavior); + if (index !== -1) { + return this; + } + behavior.init(); + if (this._scene.isLoading && !attachImmediately) { + // We defer the attach when the scene will be loaded + this._scene.onDataLoadedObservable.addOnce(() => { + behavior.attach(this); + }); + } + else { + behavior.attach(this); + } + this._behaviors.push(behavior); + return this; + } + /** + * Remove an attached behavior + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors + * @param behavior defines the behavior to attach + * @returns the current Node + */ + removeBehavior(behavior) { + const index = this._behaviors.indexOf(behavior); + if (index === -1) { + return this; + } + this._behaviors[index].detach(); + this._behaviors.splice(index, 1); + return this; + } + /** + * Gets the list of attached behaviors + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors + */ + get behaviors() { + return this._behaviors; + } + /** + * Gets an attached behavior by name + * @param name defines the name of the behavior to look for + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors + * @returns null if behavior was not found else the requested behavior + */ + getBehaviorByName(name) { + for (const behavior of this._behaviors) { + if (behavior.name === name) { + return behavior; + } + } + return null; + } + /** + * Returns the latest update of the World matrix + * @returns a Matrix + */ + getWorldMatrix() { + if (this._currentRenderId !== this._scene.getRenderId()) { + this.computeWorldMatrix(); + } + return this._worldMatrix; + } + /** @internal */ + _getWorldMatrixDeterminant() { + if (this._worldMatrixDeterminantIsDirty) { + this._worldMatrixDeterminantIsDirty = false; + this._worldMatrixDeterminant = this._worldMatrix.determinant(); + } + return this._worldMatrixDeterminant; + } + /** + * Returns directly the latest state of the mesh World matrix. + * A Matrix is returned. + */ + get worldMatrixFromCache() { + return this._worldMatrix; + } + // override it in derived class if you add new variables to the cache + // and call the parent class method + /** @internal */ + _initCache() { + this._cache = {}; + } + /** + * @internal + */ + updateCache(force) { + if (!force && this.isSynchronized()) { + return; + } + this._updateCache(); + } + /** + * @internal + */ + _getActionManagerForTrigger(trigger, _initialCall = true) { + if (!this.parent) { + return null; + } + return this.parent._getActionManagerForTrigger(trigger, false); + } + // override it in derived class if you add new variables to the cache + // and call the parent class method if !ignoreParentClass + /** + * @internal + */ + _updateCache(_ignoreParentClass) { } + // override it in derived class if you add new variables to the cache + /** @internal */ + _isSynchronized() { + return true; + } + /** @internal */ + _markSyncedWithParent() { + if (this._parentNode) { + this._parentUpdateId = this._parentNode._childUpdateId; + } + } + /** @internal */ + isSynchronizedWithParent() { + if (!this._parentNode) { + return true; + } + if (this._parentNode._isDirty || this._parentUpdateId !== this._parentNode._childUpdateId) { + return false; + } + return this._parentNode.isSynchronized(); + } + /** @internal */ + isSynchronized() { + if (this._parentNode && !this.isSynchronizedWithParent()) { + return false; + } + return this._isSynchronized(); + } + /** + * Is this node ready to be used/rendered + * @param _completeCheck defines if a complete check (including materials and lights) has to be done (false by default) + * @returns true if the node is ready + */ + isReady(_completeCheck = false) { + return this._nodeDataStorage._isReady; + } + /** + * Flag the node as dirty (Forcing it to update everything) + * @param _property helps children apply precise "dirtyfication" + * @returns this node + */ + markAsDirty(_property) { + this._currentRenderId = Number.MAX_VALUE; + this._isDirty = true; + return this; + } + /** + * Is this node enabled? + * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true + * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors + * @returns whether this node (and its parent) is enabled + */ + isEnabled(checkAncestors = true) { + if (checkAncestors === false) { + return this._nodeDataStorage._isEnabled; + } + if (!this._nodeDataStorage._isEnabled) { + return false; + } + return this._nodeDataStorage._isParentEnabled; + } + /** @internal */ + _syncParentEnabledState() { + this._nodeDataStorage._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true; + if (this._children) { + this._children.forEach((c) => { + c._syncParentEnabledState(); // Force children to update accordingly + }); + } + } + /** + * Set the enabled state of this node + * @param value defines the new enabled state + */ + setEnabled(value) { + if (this._nodeDataStorage._isEnabled === value) { + return; + } + this._nodeDataStorage._isEnabled = value; + this._syncParentEnabledState(); + this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(value); + } + /** + * Is this node a descendant of the given node? + * The function will iterate up the hierarchy until the ancestor was found or no more parents defined + * @param ancestor defines the parent node to inspect + * @returns a boolean indicating if this node is a descendant of the given node + */ + isDescendantOf(ancestor) { + if (this.parent) { + if (this.parent === ancestor) { + return true; + } + return this.parent.isDescendantOf(ancestor); + } + return false; + } + /** + * @internal + */ + _getDescendants(results, directDescendantsOnly = false, predicate) { + if (!this._children) { + return; + } + for (let index = 0; index < this._children.length; index++) { + const item = this._children[index]; + if (!predicate || predicate(item)) { + results.push(item); + } + if (!directDescendantsOnly) { + item._getDescendants(results, false, predicate); + } + } + } + /** + * Will return all nodes that have this node as ascendant + * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered + * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored + * @returns all children nodes of all types + */ + getDescendants(directDescendantsOnly, predicate) { + const results = []; + this._getDescendants(results, directDescendantsOnly, predicate); + return results; + } + /** + * Get all child-meshes of this node + * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered (Default: false) + * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored + * @returns an array of AbstractMesh + */ + getChildMeshes(directDescendantsOnly, predicate) { + const results = []; + this._getDescendants(results, directDescendantsOnly, (node) => { + return (!predicate || predicate(node)) && node.cullingStrategy !== undefined; + }); + return results; + } + /** + * Get all direct children of this node + * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored + * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered (Default: true) + * @returns an array of Node + */ + getChildren(predicate, directDescendantsOnly = true) { + return this.getDescendants(directDescendantsOnly, predicate); + } + /** + * @internal + */ + _setReady(state) { + if (state === this._nodeDataStorage._isReady) { + return; + } + if (!state) { + this._nodeDataStorage._isReady = false; + return; + } + if (this.onReady) { + this.onReady(this); + } + this._nodeDataStorage._isReady = true; + } + /** + * Get an animation by name + * @param name defines the name of the animation to look for + * @returns null if not found else the requested animation + */ + getAnimationByName(name) { + for (let i = 0; i < this.animations.length; i++) { + const animation = this.animations[i]; + if (animation.name === name) { + return animation; + } + } + return null; + } + /** + * Creates an animation range for this node + * @param name defines the name of the range + * @param from defines the starting key + * @param to defines the end key + */ + createAnimationRange(name, from, to) { + // check name not already in use + if (!this._ranges[name]) { + this._ranges[name] = Node._AnimationRangeFactory(name, from, to); + for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) { + if (this.animations[i]) { + this.animations[i].createRange(name, from, to); + } + } + } + } + /** + * Delete a specific animation range + * @param name defines the name of the range to delete + * @param deleteFrames defines if animation frames from the range must be deleted as well + */ + deleteAnimationRange(name, deleteFrames = true) { + for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) { + if (this.animations[i]) { + this.animations[i].deleteRange(name, deleteFrames); + } + } + this._ranges[name] = null; // said much faster than 'delete this._range[name]' + } + /** + * Get an animation range by name + * @param name defines the name of the animation range to look for + * @returns null if not found else the requested animation range + */ + getAnimationRange(name) { + return this._ranges[name] || null; + } + /** + * Clone the current node + * @param name Name of the new clone + * @param newParent New parent for the clone + * @param doNotCloneChildren Do not clone children hierarchy + * @returns the new transform node + */ + clone(name, newParent, doNotCloneChildren) { + const result = SerializationHelper.Clone(() => new Node(name, this.getScene()), this); + if (newParent) { + result.parent = newParent; + } + if (!doNotCloneChildren) { + // Children + const directDescendants = this.getDescendants(true); + for (let index = 0; index < directDescendants.length; index++) { + const child = directDescendants[index]; + child.clone(name + "." + child.name, result); + } + } + return result; + } + /** + * Gets the list of all animation ranges defined on this node + * @returns an array + */ + getAnimationRanges() { + const animationRanges = []; + let name; + for (name in this._ranges) { + animationRanges.push(this._ranges[name]); + } + return animationRanges; + } + /** + * Will start the animation sequence + * @param name defines the range frames for animation sequence + * @param loop defines if the animation should loop (false by default) + * @param speedRatio defines the speed factor in which to run the animation (1 by default) + * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default) + * @returns the object created for this animation. If range does not exist, it will return null + */ + beginAnimation(name, loop, speedRatio, onAnimationEnd) { + const range = this.getAnimationRange(name); + if (!range) { + return null; + } + return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd); + } + /** + * Serialize animation ranges into a JSON compatible object + * @returns serialization object + */ + serializeAnimationRanges() { + const serializationRanges = []; + for (const name in this._ranges) { + const localRange = this._ranges[name]; + if (!localRange) { + continue; + } + const range = {}; + range.name = name; + range.from = localRange.from; + range.to = localRange.to; + serializationRanges.push(range); + } + return serializationRanges; + } + /** + * Computes the world matrix of the node + * @param _force defines if the cache version should be invalidated forcing the world matrix to be created from scratch + * @returns the world matrix + */ + computeWorldMatrix(_force) { + if (!this._worldMatrix) { + this._worldMatrix = Matrix.Identity(); + } + return this._worldMatrix; + } + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse, disposeMaterialAndTextures = false) { + this._nodeDataStorage._isDisposed = true; + if (!doNotRecurse) { + const nodes = this.getDescendants(true); + for (const node of nodes) { + node.dispose(doNotRecurse, disposeMaterialAndTextures); + } + } + if (!this.parent) { + this._removeFromSceneRootNodes(); + } + else { + this.parent = null; + } + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + this.onEnabledStateChangedObservable.clear(); + this.onClonedObservable.clear(); + // Behaviors + for (const behavior of this._behaviors) { + behavior.detach(); + } + this._behaviors.length = 0; + this.metadata = null; + } + /** + * Parse animation range data from a serialization object and store them into a given node + * @param node defines where to store the animation ranges + * @param parsedNode defines the serialization object to read data from + * @param _scene defines the hosting scene + */ + static ParseAnimationRanges(node, parsedNode, _scene) { + if (parsedNode.ranges) { + for (let index = 0; index < parsedNode.ranges.length; index++) { + const data = parsedNode.ranges[index]; + node.createAnimationRange(data.name, data.from, data.to); + } + } + } + /** + * Return the minimum and maximum world vectors of the entire hierarchy under current node + * @param includeDescendants Include bounding info from descendants as well (true by default) + * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors + * @returns the new bounding vectors + */ + getHierarchyBoundingVectors(includeDescendants = true, predicate = null) { + // Ensures that all world matrix will be recomputed. + this.getScene().incrementRenderId(); + this.computeWorldMatrix(true); + let min; + let max; + const thisAbstractMesh = this; + if (thisAbstractMesh.getBoundingInfo && thisAbstractMesh.subMeshes) { + // If this is an abstract mesh get its bounding info + const boundingInfo = thisAbstractMesh.getBoundingInfo(); + min = boundingInfo.boundingBox.minimumWorld.clone(); + max = boundingInfo.boundingBox.maximumWorld.clone(); + } + else { + min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + } + if (includeDescendants) { + const descendants = this.getDescendants(false); + for (const descendant of descendants) { + const childMesh = descendant; + childMesh.computeWorldMatrix(true); + // Filters meshes based on custom predicate function. + if (predicate && !predicate(childMesh)) { + continue; + } + //make sure we have the needed params to get mix and max + if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) { + continue; + } + const childBoundingInfo = childMesh.getBoundingInfo(); + const boundingBox = childBoundingInfo.boundingBox; + const minBox = boundingBox.minimumWorld; + const maxBox = boundingBox.maximumWorld; + Vector3.CheckExtends(minBox, min, max); + Vector3.CheckExtends(maxBox, min, max); + } + } + return { + min: min, + max: max, + }; + } +}; +/** + * @internal + */ +Node$2._AnimationRangeFactory = (_name, _from, _to) => { + throw _WarnImport("AnimationRange"); +}; +Node$2._NodeConstructors = {}; +__decorate([ + serialize() +], Node$2.prototype, "name", void 0); +__decorate([ + serialize() +], Node$2.prototype, "id", void 0); +__decorate([ + serialize() +], Node$2.prototype, "uniqueId", void 0); +__decorate([ + serialize() +], Node$2.prototype, "state", void 0); +__decorate([ + serialize() +], Node$2.prototype, "metadata", void 0); + +/* eslint-disable @typescript-eslint/naming-convention */ +// "Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed." +// https://en.wikipedia.org/wiki/Coroutine +// The inline scheduler simply steps the coroutine synchronously. This is useful for running a coroutine synchronously, and also as a helper function for other schedulers. +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function inlineScheduler(coroutine, onStep, onError) { + try { + const step = coroutine.next(); + if (step.done) { + onStep(step); + } + else if (!step.value) { + // NOTE: The properties of step have been narrowed, but the type of step itself is not narrowed, so the cast below is the most type safe way to deal with this without instantiating a new object to hold the values. + onStep(step); + } + else { + step.value.then(() => { + step.value = undefined; + onStep(step); + }, onError); + } + } + catch (error) { + onError(error); + } +} +// The yielding scheduler steps the coroutine synchronously until the specified time interval has elapsed, then yields control so other operations can be performed. +// A single instance of a yielding scheduler could be shared across multiple coroutines to yield when their collective work exceeds the threshold. +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function createYieldingScheduler(yieldAfterMS = 25) { + let startTime; + return (coroutine, onStep, onError) => { + const currentTime = performance.now(); + if (startTime === undefined || currentTime - startTime > yieldAfterMS) { + // If this is the first coroutine step, or if the time interval has elapsed, record a new start time, and schedule the coroutine step to happen later, effectively yielding control of the execution context. + startTime = currentTime; + setTimeout(() => { + inlineScheduler(coroutine, onStep, onError); + }, 0); + } + else { + // Otherwise it is not time to yield yet, so step the coroutine synchronously. + inlineScheduler(coroutine, onStep, onError); + } + }; +} +// Runs the specified coroutine with the specified scheduler. The success or error callback will be invoked when the coroutine finishes. +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function runCoroutine(coroutine, scheduler, onSuccess, onError, abortSignal) { + const resume = () => { + let reschedule; + const onStep = (stepResult) => { + if (stepResult.done) { + // If the coroutine is done, report success. + onSuccess(stepResult.value); + } + else { + // If the coroutine is not done, resume the coroutine (via the scheduler). + if (reschedule === undefined) { + // If reschedule is undefined at this point, then the coroutine must have stepped synchronously, so just flag another loop iteration. + reschedule = true; + } + else { + // If reschedule is defined at this point, then the coroutine must have stepped asynchronously, so call resume to restart the step loop. + resume(); + } + } + }; + do { + reschedule = undefined; + { + scheduler(coroutine, onStep, onError); + } + if (reschedule === undefined) { + // If reschedule is undefined at this point, then the coroutine must have stepped asynchronously, so stop looping and let the coroutine be resumed later. + reschedule = false; + } + } while (reschedule); + }; + resume(); +} +// Runs the specified coroutine synchronously. +/** + * @internal + */ +function runCoroutineSync(coroutine, abortSignal) { + // Run the coroutine with the inline scheduler, storing the returned value, or re-throwing the error (since the error callback will be called synchronously by the inline scheduler). + let result; + runCoroutine(coroutine, inlineScheduler, (r) => (result = r), (e) => { + throw e; + }); + // Synchronously return the result of the coroutine. + return result; +} +// Runs the specified coroutine asynchronously with the specified scheduler. +/** + * @internal + */ +function runCoroutineAsync(coroutine, scheduler, abortSignal) { + // Run the coroutine with a yielding scheduler, resolving or rejecting the result promise when the coroutine finishes. + return new Promise((resolve, reject) => { + runCoroutine(coroutine, scheduler, resolve, reject); + }); +} +/** + * Given a function that returns a Coroutine, produce a function with the same parameters that returns a T. + * The returned function runs the coroutine synchronously. + * @param coroutineFactory A function that returns a Coroutine. + * @param abortSignal + * @returns A function that runs the coroutine synchronously. + * @internal + */ +function makeSyncFunction(coroutineFactory, abortSignal) { + return (...params) => { + // Run the coroutine synchronously. + return runCoroutineSync(coroutineFactory(...params)); + }; +} + +/** + * This is the base class of all the camera used in the application. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras + */ +class Camera extends Node$2 { + /** + * Define the current local position of the camera in the scene + */ + get position() { + return this._position; + } + set position(newPosition) { + this._position = newPosition; + } + /** + * The vector the camera should consider as up. + * (default is Vector3(0, 1, 0) aka Vector3.Up()) + */ + set upVector(vec) { + this._upVector = vec; + } + get upVector() { + return this._upVector; + } + /** + * The screen area in scene units squared + */ + get screenArea() { + let x = 0; + let y = 0; + if (this.mode === Camera.PERSPECTIVE_CAMERA) { + if (this.fovMode === Camera.FOVMODE_VERTICAL_FIXED) { + y = this.minZ * 2 * Math.tan(this.fov / 2); + x = this.getEngine().getAspectRatio(this) * y; + } + else { + x = this.minZ * 2 * Math.tan(this.fov / 2); + y = x / this.getEngine().getAspectRatio(this); + } + } + else { + const halfWidth = this.getEngine().getRenderWidth() / 2.0; + const halfHeight = this.getEngine().getRenderHeight() / 2.0; + x = (this.orthoRight ?? halfWidth) - (this.orthoLeft ?? -halfWidth); + y = (this.orthoTop ?? halfHeight) - (this.orthoBottom ?? -halfHeight); + } + return x * y; + } + /** + * Define the current limit on the left side for an orthographic camera + * In scene unit + */ + set orthoLeft(value) { + this._orthoLeft = value; + for (const rigCamera of this._rigCameras) { + rigCamera.orthoLeft = value; + } + } + get orthoLeft() { + return this._orthoLeft; + } + /** + * Define the current limit on the right side for an orthographic camera + * In scene unit + */ + set orthoRight(value) { + this._orthoRight = value; + for (const rigCamera of this._rigCameras) { + rigCamera.orthoRight = value; + } + } + get orthoRight() { + return this._orthoRight; + } + /** + * Define the current limit on the bottom side for an orthographic camera + * In scene unit + */ + set orthoBottom(value) { + this._orthoBottom = value; + for (const rigCamera of this._rigCameras) { + rigCamera.orthoBottom = value; + } + } + get orthoBottom() { + return this._orthoBottom; + } + /** + * Define the current limit on the top side for an orthographic camera + * In scene unit + */ + set orthoTop(value) { + this._orthoTop = value; + for (const rigCamera of this._rigCameras) { + rigCamera.orthoTop = value; + } + } + get orthoTop() { + return this._orthoTop; + } + /** + * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.ORTHOGRAPHIC_CAMERA) + */ + set mode(mode) { + this._mode = mode; + // Pass the mode down to the rig cameras + for (const rigCamera of this._rigCameras) { + rigCamera.mode = mode; + } + } + get mode() { + return this._mode; + } + /** + * Gets a flag indicating that the camera has moved in some way since the last call to Camera.update() + */ + get hasMoved() { + return this._hasMoved; + } + /** + * Instantiates a new camera object. + * This should not be used directly but through the inherited cameras: ArcRotate, Free... + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras + * @param name Defines the name of the camera in the scene + * @param position Defines the position of the camera + * @param scene Defines the scene the camera belongs too + * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene + */ + constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) { + super(name, scene, false); + /** @internal */ + this._position = Vector3.Zero(); + this._upVector = Vector3.Up(); + /** + * Object containing oblique projection values (only used with ORTHOGRAPHIC_CAMERA) + */ + this.oblique = null; + this._orthoLeft = null; + this._orthoRight = null; + this._orthoBottom = null; + this._orthoTop = null; + /** + * Field Of View is set in Radians. (default is 0.8) + */ + this.fov = 0.8; + /** + * Projection plane tilt around the X axis (horizontal), set in Radians. (default is 0) + * Can be used to make vertical lines in world space actually vertical on the screen. + * See https://forum.babylonjs.com/t/add-vertical-shift-to-3ds-max-exporter-babylon-cameras/17480 + */ + this.projectionPlaneTilt = 0; + /** + * Define the minimum distance the camera can see from. + * This is important to note that the depth buffer are not infinite and the closer it starts + * the more your scene might encounter depth fighting issue. + */ + this.minZ = 1; + /** + * Define the maximum distance the camera can see to. (default is 10000) + * This is important to note that the depth buffer are not infinite and the further it end + * the more your scene might encounter depth fighting issue. + */ + this.maxZ = 10000.0; + /** + * Define the default inertia of the camera. + * This helps giving a smooth feeling to the camera movement. + */ + this.inertia = 0.9; + this._mode = Camera.PERSPECTIVE_CAMERA; + /** + * Define whether the camera is intermediate. + * This is useful to not present the output directly to the screen in case of rig without post process for instance + */ + this.isIntermediate = false; + /** + * Define the viewport of the camera. + * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit. + */ + this.viewport = new Viewport(0, 0, 1.0, 1.0); + /** + * Restricts the camera to viewing objects with the same layerMask. + * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0 + */ + this.layerMask = 0x0fffffff; + /** + * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED) + */ + this.fovMode = Camera.FOVMODE_VERTICAL_FIXED; + /** + * Rig mode of the camera. + * This is useful to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes. + * This is normally controlled byt the camera themselves as internal use. + */ + this.cameraRigMode = Camera.RIG_MODE_NONE; + /** + * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene + * This is pretty helpful if you wish to make a camera render to a texture you could reuse somewhere + * else in the scene. (Eg. security camera) + * + * To change the final output target of the camera, camera.outputRenderTarget should be used instead (eg. webXR renders to a render target corresponding to an HMD) + */ + this.customRenderTargets = []; + /** + * When set, the camera will render to this render target instead of the default canvas + * + * If the desire is to use the output of a camera as a texture in the scene consider using camera.customRenderTargets instead + */ + this.outputRenderTarget = null; + /** + * Observable triggered when the camera view matrix has changed. + * Beware of reentrance! Some methods like Camera.getViewMatrix and Camera.getWorldMatrix can trigger the onViewMatrixChangedObservable + * observable, so using them inside an observer will require additional logic to avoid a stack overflow error. + */ + this.onViewMatrixChangedObservable = new Observable(); + /** + * Observable triggered when the camera Projection matrix has changed. + */ + this.onProjectionMatrixChangedObservable = new Observable(); + /** + * Observable triggered when the inputs have been processed. + */ + this.onAfterCheckInputsObservable = new Observable(); + /** + * Observable triggered when reset has been called and applied to the camera. + */ + this.onRestoreStateObservable = new Observable(); + /** + * Is this camera a part of a rig system? + */ + this.isRigCamera = false; + this._hasMoved = false; + /** @internal */ + this._rigCameras = new Array(); + /** @internal */ + this._skipRendering = false; + /** @internal */ + this._projectionMatrix = new Matrix(); + /** @internal */ + this._postProcesses = new Array(); + /** @internal */ + this._activeMeshes = new SmartArray(256); + this._globalPosition = Vector3.Zero(); + /** @internal */ + this._computedViewMatrix = Matrix.Identity(); + this._doNotComputeProjectionMatrix = false; + this._transformMatrix = Matrix.Zero(); + this._refreshFrustumPlanes = true; + this._absoluteRotation = Quaternion.Identity(); + /** @internal */ + this._isCamera = true; + /** @internal */ + this._isLeftCamera = false; + /** @internal */ + this._isRightCamera = false; + this.getScene().addCamera(this); + if (setActiveOnSceneIfNoneActive && !this.getScene().activeCamera) { + this.getScene().activeCamera = this; + } + this.position = position; + this.renderPassId = this.getScene().getEngine().createRenderPassId(`Camera ${name}`); + } + /** + * Store current camera state (fov, position, etc..) + * @returns the camera + */ + storeState() { + this._stateStored = true; + this._storedFov = this.fov; + return this; + } + /** + * Returns true if a state has been stored by calling storeState method. + * @returns true if state has been stored. + */ + hasStateStored() { + return !!this._stateStored; + } + /** + * Restores the camera state values if it has been stored. You must call storeState() first + * @returns true if restored and false otherwise + */ + _restoreStateValues() { + if (!this._stateStored) { + return false; + } + this.fov = this._storedFov; + return true; + } + /** + * Restored camera state. You must call storeState() first. + * @returns true if restored and false otherwise + */ + restoreState() { + if (this._restoreStateValues()) { + this.onRestoreStateObservable.notifyObservers(this); + return true; + } + return false; + } + /** + * Gets the class name of the camera. + * @returns the class name + */ + getClassName() { + return "Camera"; + } + /** + * Gets a string representation of the camera useful for debug purpose. + * @param fullDetails Defines that a more verbose level of logging is required + * @returns the string representation + */ + toString(fullDetails) { + let ret = "Name: " + this.name; + ret += ", type: " + this.getClassName(); + if (this.animations) { + for (let i = 0; i < this.animations.length; i++) { + ret += ", animation[0]: " + this.animations[i].toString(fullDetails); + } + } + return ret; + } + /** + * Automatically tilts the projection plane, using `projectionPlaneTilt`, to correct the perspective effect on vertical lines. + */ + applyVerticalCorrection() { + const rot = this.absoluteRotation.toEulerAngles(); + this.projectionPlaneTilt = this._scene.useRightHandedSystem ? -rot.x : rot.x; + } + /** + * Gets the current world space position of the camera. + */ + get globalPosition() { + return this._globalPosition; + } + /** + * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame) + * @returns the active meshe list + */ + getActiveMeshes() { + return this._activeMeshes; + } + /** + * Check whether a mesh is part of the current active mesh list of the camera + * @param mesh Defines the mesh to check + * @returns true if active, false otherwise + */ + isActiveMesh(mesh) { + return this._activeMeshes.indexOf(mesh) !== -1; + } + /** + * Is this camera ready to be used/rendered + * @param completeCheck defines if a complete check (including post processes) has to be done (false by default) + * @returns true if the camera is ready + */ + isReady(completeCheck = false) { + if (completeCheck) { + for (const pp of this._postProcesses) { + if (pp && !pp.isReady()) { + return false; + } + } + } + return super.isReady(completeCheck); + } + /** @internal */ + _initCache() { + super._initCache(); + this._cache.position = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cache.upVector = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cache.mode = undefined; + this._cache.minZ = undefined; + this._cache.maxZ = undefined; + this._cache.fov = undefined; + this._cache.fovMode = undefined; + this._cache.aspectRatio = undefined; + this._cache.orthoLeft = undefined; + this._cache.orthoRight = undefined; + this._cache.orthoBottom = undefined; + this._cache.orthoTop = undefined; + this._cache.obliqueAngle = undefined; + this._cache.obliqueLength = undefined; + this._cache.obliqueOffset = undefined; + this._cache.renderWidth = undefined; + this._cache.renderHeight = undefined; + } + /** + * @internal + */ + _updateCache(ignoreParentClass) { + if (!ignoreParentClass) { + super._updateCache(); + } + this._cache.position.copyFrom(this.position); + this._cache.upVector.copyFrom(this.upVector); + } + /** @internal */ + _isSynchronized() { + return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix(); + } + /** @internal */ + _isSynchronizedViewMatrix() { + if (!super._isSynchronized()) { + return false; + } + return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent(); + } + /** @internal */ + _isSynchronizedProjectionMatrix() { + let isSynchronized = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ; + if (!isSynchronized) { + return false; + } + const engine = this.getEngine(); + if (this.mode === Camera.PERSPECTIVE_CAMERA) { + isSynchronized = + this._cache.fov === this.fov && + this._cache.fovMode === this.fovMode && + this._cache.aspectRatio === engine.getAspectRatio(this) && + this._cache.projectionPlaneTilt === this.projectionPlaneTilt; + } + else { + isSynchronized = + this._cache.orthoLeft === this.orthoLeft && + this._cache.orthoRight === this.orthoRight && + this._cache.orthoBottom === this.orthoBottom && + this._cache.orthoTop === this.orthoTop && + this._cache.renderWidth === engine.getRenderWidth() && + this._cache.renderHeight === engine.getRenderHeight(); + if (this.oblique) { + isSynchronized = + isSynchronized && + this._cache.obliqueAngle === this.oblique.angle && + this._cache.obliqueLength === this.oblique.length && + this._cache.obliqueOffset === this.oblique.offset; + } + } + return isSynchronized; + } + /** + * Attach the input controls to a specific dom element to get the input from. + * This function is here because typescript removes the typing of the last function. + * @param _ignored defines an ignored parameter kept for backward compatibility. + * @param _noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(_ignored, _noPreventDefault) { } + /** + * Detach the current controls from the specified dom element. + * This function is here because typescript removes the typing of the last function. + * @param _ignored defines an ignored parameter kept for backward compatibility. + */ + detachControl(_ignored) { } + /** + * Update the camera state according to the different inputs gathered during the frame. + */ + update() { + this._hasMoved = false; + this._checkInputs(); + if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { + this._updateRigCameras(); + } + // Attempt to update the camera's view and projection matrices. + // This call is being made because these matrices are no longer being updated + // as a part of the picking ray process (in addition to scene.render). + this.getViewMatrix(); + this.getProjectionMatrix(); + } + /** @internal */ + _checkInputs() { + this.onAfterCheckInputsObservable.notifyObservers(this); + } + /** @internal */ + get rigCameras() { + return this._rigCameras; + } + /** + * Gets the post process used by the rig cameras + */ + get rigPostProcess() { + return this._rigPostProcess; + } + /** + * Internal, gets the first post process. + * @returns the first post process to be run on this camera. + */ + _getFirstPostProcess() { + for (let ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) { + if (this._postProcesses[ppIndex] !== null) { + return this._postProcesses[ppIndex]; + } + } + return null; + } + _cascadePostProcessesToRigCams() { + // invalidate framebuffer + const firstPostProcess = this._getFirstPostProcess(); + if (firstPostProcess) { + firstPostProcess.markTextureDirty(); + } + // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera + for (let i = 0, len = this._rigCameras.length; i < len; i++) { + const cam = this._rigCameras[i]; + const rigPostProcess = cam._rigPostProcess; + // for VR rig, there does not have to be a post process + if (rigPostProcess) { + const isPass = rigPostProcess.getEffectName() === "pass"; + if (isPass) { + // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses + cam.isIntermediate = this._postProcesses.length === 0; + } + cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess); + rigPostProcess.markTextureDirty(); + } + else { + cam._postProcesses = this._postProcesses.slice(0); + } + } + } + /** + * Attach a post process to the camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess + * @param postProcess The post process to attach to the camera + * @param insertAt The position of the post process in case several of them are in use in the scene + * @returns the position the post process has been inserted at + */ + attachPostProcess(postProcess, insertAt = null) { + if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) { + Logger.Error("You're trying to reuse a post process not defined as reusable."); + return 0; + } + if (insertAt == null || insertAt < 0) { + this._postProcesses.push(postProcess); + } + else if (this._postProcesses[insertAt] === null) { + this._postProcesses[insertAt] = postProcess; + } + else { + this._postProcesses.splice(insertAt, 0, postProcess); + } + this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated + // Update prePass + if (this._scene.prePassRenderer) { + this._scene.prePassRenderer.markAsDirty(); + } + return this._postProcesses.indexOf(postProcess); + } + /** + * Detach a post process to the camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess + * @param postProcess The post process to detach from the camera + */ + detachPostProcess(postProcess) { + const idx = this._postProcesses.indexOf(postProcess); + if (idx !== -1) { + this._postProcesses[idx] = null; + } + // Update prePass + if (this._scene.prePassRenderer) { + this._scene.prePassRenderer.markAsDirty(); + } + this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated + } + /** + * Gets the current world matrix of the camera + * @returns the world matrix + */ + getWorldMatrix() { + if (this._isSynchronizedViewMatrix()) { + return this._worldMatrix; + } + // Getting the view matrix will also compute the world matrix. + this.getViewMatrix(); + return this._worldMatrix; + } + /** @internal */ + _getViewMatrix() { + return Matrix.Identity(); + } + /** + * Gets the current view matrix of the camera. + * @param force forces the camera to recompute the matrix without looking at the cached state + * @returns the view matrix + */ + getViewMatrix(force) { + if (!force && this._isSynchronizedViewMatrix()) { + return this._computedViewMatrix; + } + this._hasMoved = true; + this.updateCache(); + this._computedViewMatrix = this._getViewMatrix(); + this._currentRenderId = this.getScene().getRenderId(); + this._childUpdateId++; + this._refreshFrustumPlanes = true; + if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) { + this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix); + } + // Notify parent camera if rig camera is changed + if (this.parent && this.parent.onViewMatrixChangedObservable) { + this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent); + } + this.onViewMatrixChangedObservable.notifyObservers(this); + this._computedViewMatrix.invertToRef(this._worldMatrix); + return this._computedViewMatrix; + } + /** + * Freeze the projection matrix. + * It will prevent the cache check of the camera projection compute and can speed up perf + * if no parameter of the camera are meant to change + * @param projection Defines manually a projection if necessary + */ + freezeProjectionMatrix(projection) { + this._doNotComputeProjectionMatrix = true; + if (projection !== undefined) { + this._projectionMatrix = projection; + } + } + /** + * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix. + */ + unfreezeProjectionMatrix() { + this._doNotComputeProjectionMatrix = false; + } + /** + * Gets the current projection matrix of the camera. + * @param force forces the camera to recompute the matrix without looking at the cached state + * @returns the projection matrix + */ + getProjectionMatrix(force) { + if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) { + return this._projectionMatrix; + } + // Cache + this._cache.mode = this.mode; + this._cache.minZ = this.minZ; + this._cache.maxZ = this.maxZ; + // Matrix + this._refreshFrustumPlanes = true; + const engine = this.getEngine(); + const scene = this.getScene(); + const reverseDepth = engine.useReverseDepthBuffer; + if (this.mode === Camera.PERSPECTIVE_CAMERA) { + this._cache.fov = this.fov; + this._cache.fovMode = this.fovMode; + this._cache.aspectRatio = engine.getAspectRatio(this); + this._cache.projectionPlaneTilt = this.projectionPlaneTilt; + if (this.minZ <= 0) { + this.minZ = 0.1; + } + let getProjectionMatrix; + if (scene.useRightHandedSystem) { + getProjectionMatrix = Matrix.PerspectiveFovRHToRef; + } + else { + getProjectionMatrix = Matrix.PerspectiveFovLHToRef; + } + getProjectionMatrix(this.fov, engine.getAspectRatio(this), reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED, engine.isNDCHalfZRange, this.projectionPlaneTilt, reverseDepth); + } + else { + const halfWidth = engine.getRenderWidth() / 2.0; + const halfHeight = engine.getRenderHeight() / 2.0; + if (scene.useRightHandedSystem) { + if (this.oblique) { + Matrix.ObliqueOffCenterRHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this.oblique.length, this.oblique.angle, this._computeObliqueDistance(this.oblique.offset), this._projectionMatrix, engine.isNDCHalfZRange); + } + else { + Matrix.OrthoOffCenterRHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange); + } + } + else { + if (this.oblique) { + Matrix.ObliqueOffCenterLHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this.oblique.length, this.oblique.angle, this._computeObliqueDistance(this.oblique.offset), this._projectionMatrix, engine.isNDCHalfZRange); + } + else { + Matrix.OrthoOffCenterLHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange); + } + } + this._cache.orthoLeft = this.orthoLeft; + this._cache.orthoRight = this.orthoRight; + this._cache.orthoBottom = this.orthoBottom; + this._cache.orthoTop = this.orthoTop; + this._cache.obliqueAngle = this.oblique?.angle; + this._cache.obliqueLength = this.oblique?.length; + this._cache.obliqueOffset = this.oblique?.offset; + this._cache.renderWidth = engine.getRenderWidth(); + this._cache.renderHeight = engine.getRenderHeight(); + } + this.onProjectionMatrixChangedObservable.notifyObservers(this); + return this._projectionMatrix; + } + /** + * Gets the transformation matrix (ie. the multiplication of view by projection matrices) + * @returns a Matrix + */ + getTransformationMatrix() { + this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); + return this._transformMatrix; + } + _computeObliqueDistance(offset) { + const arcRotateCamera = this; + const targetCamera = this; + return (arcRotateCamera.radius || (targetCamera.target ? Vector3.Distance(this.position, targetCamera.target) : this.position.length())) + offset; + } + /** @internal */ + _updateFrustumPlanes() { + if (!this._refreshFrustumPlanes) { + return; + } + this.getTransformationMatrix(); + if (!this._frustumPlanes) { + this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix); + } + else { + Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes); + } + this._refreshFrustumPlanes = false; + } + /** + * Checks if a cullable object (mesh...) is in the camera frustum + * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check + * @param target The object to check + * @param checkRigCameras If the rig cameras should be checked (eg. with VR camera both eyes should be checked) (Default: false) + * @returns true if the object is in frustum otherwise false + */ + isInFrustum(target, checkRigCameras = false) { + this._updateFrustumPlanes(); + if (checkRigCameras && this.rigCameras.length > 0) { + let result = false; + this.rigCameras.forEach((cam) => { + cam._updateFrustumPlanes(); + result = result || target.isInFrustum(cam._frustumPlanes); + }); + return result; + } + else { + return target.isInFrustum(this._frustumPlanes); + } + } + /** + * Checks if a cullable object (mesh...) is in the camera frustum + * Unlike isInFrustum this checks the full bounding box + * @param target The object to check + * @returns true if the object is in frustum otherwise false + */ + isCompletelyInFrustum(target) { + this._updateFrustumPlanes(); + return target.isCompletelyInFrustum(this._frustumPlanes); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Gets a ray in the forward direction from the camera. + * @param length Defines the length of the ray to create + * @param transform Defines the transform to apply to the ray, by default the world matrix is used to create a workd space ray + * @param origin Defines the start point of the ray which defaults to the camera position + * @returns the forward ray + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getForwardRay(length = 100, transform, origin) { + throw _WarnImport("Ray"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Gets a ray in the forward direction from the camera. + * @param refRay the ray to (re)use when setting the values + * @param length Defines the length of the ray to create + * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray + * @param origin Defines the start point of the ray which defaults to the camera position + * @returns the forward ray + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getForwardRayToRef(refRay, length = 100, transform, origin) { + throw _WarnImport("Ray"); + } + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse, disposeMaterialAndTextures = false) { + // Observables + this.onViewMatrixChangedObservable.clear(); + this.onProjectionMatrixChangedObservable.clear(); + this.onAfterCheckInputsObservable.clear(); + this.onRestoreStateObservable.clear(); + // Inputs + if (this.inputs) { + this.inputs.clear(); + } + // Animations + this.getScene().stopAnimation(this); + // Remove from scene + this.getScene().removeCamera(this); + while (this._rigCameras.length > 0) { + const camera = this._rigCameras.pop(); + if (camera) { + camera.dispose(); + } + } + if (this._parentContainer) { + const index = this._parentContainer.cameras.indexOf(this); + if (index > -1) { + this._parentContainer.cameras.splice(index, 1); + } + this._parentContainer = null; + } + // Postprocesses + if (this._rigPostProcess) { + this._rigPostProcess.dispose(this); + this._rigPostProcess = null; + this._postProcesses.length = 0; + } + else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { + this._rigPostProcess = null; + this._postProcesses.length = 0; + } + else { + let i = this._postProcesses.length; + while (--i >= 0) { + const postProcess = this._postProcesses[i]; + if (postProcess) { + postProcess.dispose(this); + } + } + } + // Render targets + let i = this.customRenderTargets.length; + while (--i >= 0) { + this.customRenderTargets[i].dispose(); + } + this.customRenderTargets.length = 0; + // Active Meshes + this._activeMeshes.dispose(); + this.getScene().getEngine().releaseRenderPassId(this.renderPassId); + super.dispose(doNotRecurse, disposeMaterialAndTextures); + } + /** + * Gets the left camera of a rig setup in case of Rigged Camera + */ + get isLeftCamera() { + return this._isLeftCamera; + } + /** + * Gets the right camera of a rig setup in case of Rigged Camera + */ + get isRightCamera() { + return this._isRightCamera; + } + /** + * Gets the left camera of a rig setup in case of Rigged Camera + */ + get leftCamera() { + if (this._rigCameras.length < 1) { + return null; + } + return this._rigCameras[0]; + } + /** + * Gets the right camera of a rig setup in case of Rigged Camera + */ + get rightCamera() { + if (this._rigCameras.length < 2) { + return null; + } + return this._rigCameras[1]; + } + /** + * Gets the left camera target of a rig setup in case of Rigged Camera + * @returns the target position + */ + getLeftTarget() { + if (this._rigCameras.length < 1) { + return null; + } + return this._rigCameras[0].getTarget(); + } + /** + * Gets the right camera target of a rig setup in case of Rigged Camera + * @returns the target position + */ + getRightTarget() { + if (this._rigCameras.length < 2) { + return null; + } + return this._rigCameras[1].getTarget(); + } + /** + * @internal + */ + setCameraRigMode(mode, rigParams) { + if (this.cameraRigMode === mode) { + return; + } + while (this._rigCameras.length > 0) { + const camera = this._rigCameras.pop(); + if (camera) { + camera.dispose(); + } + } + this.cameraRigMode = mode; + this._cameraRigParams = {}; + //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target, + //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced + this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637; + this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637); + // create the rig cameras, unless none + if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { + const leftCamera = this.createRigCamera(this.name + "_L", 0); + if (leftCamera) { + leftCamera._isLeftCamera = true; + } + const rightCamera = this.createRigCamera(this.name + "_R", 1); + if (rightCamera) { + rightCamera._isRightCamera = true; + } + if (leftCamera && rightCamera) { + this._rigCameras.push(leftCamera); + this._rigCameras.push(rightCamera); + } + } + this._setRigMode(rigParams); + this._cascadePostProcessesToRigCams(); + this.update(); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _setRigMode(rigParams) { + // no-op + } + /** @internal */ + _getVRProjectionMatrix() { + Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix, true, this.getEngine().isNDCHalfZRange); + this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix); + return this._projectionMatrix; + } + /** + * @internal + */ + setCameraRigParameter(name, value) { + if (!this._cameraRigParams) { + this._cameraRigParams = {}; + } + this._cameraRigParams[name] = value; + //provisionnally: + if (name === "interaxialDistance") { + this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(value / 0.0637); + } + } + /** + * needs to be overridden by children so sub has required properties to be copied + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + createRigCamera(name, cameraIndex) { + return null; + } + /** + * May need to be overridden by children + * @internal + */ + _updateRigCameras() { + for (let i = 0; i < this._rigCameras.length; i++) { + this._rigCameras[i].minZ = this.minZ; + this._rigCameras[i].maxZ = this.maxZ; + this._rigCameras[i].fov = this.fov; + this._rigCameras[i].upVector.copyFrom(this.upVector); + } + // only update viewport when ANAGLYPH + if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) { + this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport; + } + } + /** @internal */ + _setupInputs() { } + /** + * Serialiaze the camera setup to a json representation + * @returns the JSON representation + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.uniqueId = this.uniqueId; + // Type + serializationObject.type = this.getClassName(); + // Parent + if (this.parent) { + this.parent._serializeAsParent(serializationObject); + } + if (this.inputs) { + this.inputs.serialize(serializationObject); + } + // Animations + SerializationHelper.AppendSerializedAnimations(this, serializationObject); + serializationObject.ranges = this.serializeAnimationRanges(); + serializationObject.isEnabled = this.isEnabled(); + return serializationObject; + } + /** + * Clones the current camera. + * @param name The cloned camera name + * @param newParent The cloned camera's new parent (none by default) + * @returns the cloned camera + */ + clone(name, newParent = null) { + const camera = SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this); + camera.name = name; + camera.parent = newParent; + this.onClonedObservable.notifyObservers(camera); + return camera; + } + /** + * Gets the direction of the camera relative to a given local axis. + * @param localAxis Defines the reference axis to provide a relative direction. + * @returns the direction + */ + getDirection(localAxis) { + const result = Vector3.Zero(); + this.getDirectionToRef(localAxis, result); + return result; + } + /** + * Returns the current camera absolute rotation + */ + get absoluteRotation() { + this.getWorldMatrix().decompose(undefined, this._absoluteRotation); + return this._absoluteRotation; + } + /** + * Gets the direction of the camera relative to a given local axis into a passed vector. + * @param localAxis Defines the reference axis to provide a relative direction. + * @param result Defines the vector to store the result in + */ + getDirectionToRef(localAxis, result) { + Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result); + } + /** + * Gets a camera constructor for a given camera type + * @param type The type of the camera to construct (should be equal to one of the camera class name) + * @param name The name of the camera the result will be able to instantiate + * @param scene The scene the result will construct the camera in + * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes + * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side + * @returns a factory method to construct the camera + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + static GetConstructorFromName(type, name, scene, interaxial_distance = 0, isStereoscopicSideBySide = true) { + const constructorFunc = Node$2.Construct(type, name, scene, { + // eslint-disable-next-line @typescript-eslint/naming-convention + interaxial_distance: interaxial_distance, + isStereoscopicSideBySide: isStereoscopicSideBySide, + }); + if (constructorFunc) { + return constructorFunc; + } + // Default to universal camera + return () => Camera._CreateDefaultParsedCamera(name, scene); + } + /** + * Compute the world matrix of the camera. + * @returns the camera world matrix + */ + computeWorldMatrix() { + return this.getWorldMatrix(); + } + /** + * Parse a JSON and creates the camera from the parsed information + * @param parsedCamera The JSON to parse + * @param scene The scene to instantiate the camera in + * @returns the newly constructed camera + */ + static Parse(parsedCamera, scene) { + const type = parsedCamera.type; + const construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide); + const camera = SerializationHelper.Parse(construct, parsedCamera, scene); + // Parent + if (parsedCamera.parentId !== undefined) { + camera._waitingParentId = parsedCamera.parentId; + } + // Parent instance index + if (parsedCamera.parentInstanceIndex !== undefined) { + camera._waitingParentInstanceIndex = parsedCamera.parentInstanceIndex; + } + //If camera has an input manager, let it parse inputs settings + if (camera.inputs) { + camera.inputs.parse(parsedCamera); + camera._setupInputs(); + } + if (parsedCamera.upVector) { + camera.upVector = Vector3.FromArray(parsedCamera.upVector); // need to force the upVector + } + if (camera.setPosition) { + // need to force position + camera.position.copyFromFloats(0, 0, 0); + camera.setPosition(Vector3.FromArray(parsedCamera.position)); + } + // Target + if (parsedCamera.target) { + if (camera.setTarget) { + camera.setTarget(Vector3.FromArray(parsedCamera.target)); + } + } + // Apply 3d rig, when found + if (parsedCamera.cameraRigMode) { + const rigParams = parsedCamera.interaxial_distance ? { interaxialDistance: parsedCamera.interaxial_distance } : {}; + camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams); + } + // Animations + if (parsedCamera.animations) { + for (let animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) { + const parsedAnimation = parsedCamera.animations[animationIndex]; + const internalClass = GetClass("BABYLON.Animation"); + if (internalClass) { + camera.animations.push(internalClass.Parse(parsedAnimation)); + } + } + Node$2.ParseAnimationRanges(camera, parsedCamera, scene); + } + if (parsedCamera.autoAnimate) { + scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0); + } + // Check if isEnabled is defined to be back compatible with prior serialized versions. + if (parsedCamera.isEnabled !== undefined) { + camera.setEnabled(parsedCamera.isEnabled); + } + return camera; + } + /** @internal */ + _calculateHandednessMultiplier() { + let handednessMultiplier = this.getScene().useRightHandedSystem ? -1 : 1; + if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) { + handednessMultiplier *= -1; + } + return handednessMultiplier; + } +} +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Camera._CreateDefaultParsedCamera = (name, scene) => { + throw _WarnImport("UniversalCamera"); +}; +/** + * This is the default projection mode used by the cameras. + * It helps recreating a feeling of perspective and better appreciate depth. + * This is the best way to simulate real life cameras. + */ +Camera.PERSPECTIVE_CAMERA = 0; +/** + * This helps creating camera with an orthographic mode. + * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object. + */ +Camera.ORTHOGRAPHIC_CAMERA = 1; +/** + * This is the default FOV mode for perspective cameras. + * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum. + */ +Camera.FOVMODE_VERTICAL_FIXED = 0; +/** + * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum. + */ +Camera.FOVMODE_HORIZONTAL_FIXED = 1; +/** + * This specifies there is no need for a camera rig. + * Basically only one eye is rendered corresponding to the camera. + */ +Camera.RIG_MODE_NONE = 0; +/** + * Simulates a camera Rig with one blue eye and one red eye. + * This can be use with 3d blue and red glasses. + */ +Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10; +/** + * Defines that both eyes of the camera will be rendered side by side with a parallel target. + */ +Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11; +/** + * Defines that both eyes of the camera will be rendered side by side with a none parallel target. + */ +Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12; +/** + * Defines that both eyes of the camera will be rendered over under each other. + */ +Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13; +/** + * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors. + */ +Camera.RIG_MODE_STEREOSCOPIC_INTERLACED = 14; +/** + * Defines that both eyes of the camera should be renderered in a VR mode (carbox). + */ +Camera.RIG_MODE_VR = 20; +/** + * Custom rig mode allowing rig cameras to be populated manually with any number of cameras + */ +Camera.RIG_MODE_CUSTOM = 22; +/** + * Defines if by default attaching controls should prevent the default javascript event to continue. + */ +Camera.ForceAttachControlToAlwaysPreventDefault = false; +__decorate([ + serializeAsVector3("position") +], Camera.prototype, "_position", void 0); +__decorate([ + serializeAsVector3("upVector") +], Camera.prototype, "_upVector", void 0); +__decorate([ + serialize() +], Camera.prototype, "orthoLeft", null); +__decorate([ + serialize() +], Camera.prototype, "orthoRight", null); +__decorate([ + serialize() +], Camera.prototype, "orthoBottom", null); +__decorate([ + serialize() +], Camera.prototype, "orthoTop", null); +__decorate([ + serialize() +], Camera.prototype, "fov", void 0); +__decorate([ + serialize() +], Camera.prototype, "projectionPlaneTilt", void 0); +__decorate([ + serialize() +], Camera.prototype, "minZ", void 0); +__decorate([ + serialize() +], Camera.prototype, "maxZ", void 0); +__decorate([ + serialize() +], Camera.prototype, "inertia", void 0); +__decorate([ + serialize() +], Camera.prototype, "mode", null); +__decorate([ + serialize() +], Camera.prototype, "layerMask", void 0); +__decorate([ + serialize() +], Camera.prototype, "fovMode", void 0); +__decorate([ + serialize() +], Camera.prototype, "cameraRigMode", void 0); +__decorate([ + serialize() +], Camera.prototype, "interaxialDistance", void 0); +__decorate([ + serialize() +], Camera.prototype, "isStereoscopicSideBySide", void 0); + +/** + * @internal + */ +class IntersectionInfo { + constructor(bu, bv, distance) { + this.bu = bu; + this.bv = bv; + this.distance = distance; + this.faceId = 0; + this.subMeshId = 0; + } +} + +/** + * Class used to store bounding box information + */ +class BoundingBox { + /** + * Creates a new bounding box + * @param min defines the minimum vector (in local space) + * @param max defines the maximum vector (in local space) + * @param worldMatrix defines the new world matrix + */ + constructor(min, max, worldMatrix) { + /** + * Gets the 8 vectors representing the bounding box in local space + */ + this.vectors = BuildArray(8, Vector3.Zero); + /** + * Gets the center of the bounding box in local space + */ + this.center = Vector3.Zero(); + /** + * Gets the center of the bounding box in world space + */ + this.centerWorld = Vector3.Zero(); + /** + * Gets half the size of the extent in local space. Multiply by 2 to obtain the full size of the box! + */ + this.extendSize = Vector3.Zero(); + /** + * Gets half the size of the extent in world space. Multiply by 2 to obtain the full size of the box! + */ + this.extendSizeWorld = Vector3.Zero(); + /** + * Gets the OBB (object bounding box) directions + */ + this.directions = BuildArray(3, Vector3.Zero); + /** + * Gets the 8 vectors representing the bounding box in world space + */ + this.vectorsWorld = BuildArray(8, Vector3.Zero); + /** + * Gets the minimum vector in world space + */ + this.minimumWorld = Vector3.Zero(); + /** + * Gets the maximum vector in world space + */ + this.maximumWorld = Vector3.Zero(); + /** + * Gets the minimum vector in local space + */ + this.minimum = Vector3.Zero(); + /** + * Gets the maximum vector in local space + */ + this.maximum = Vector3.Zero(); + /** @internal */ + this._drawWrapperFront = null; + /** @internal */ + this._drawWrapperBack = null; + this.reConstruct(min, max, worldMatrix); + } + // Methods + /** + * Recreates the entire bounding box from scratch as if we call the constructor in place + * @param min defines the new minimum vector (in local space) + * @param max defines the new maximum vector (in local space) + * @param worldMatrix defines the new world matrix + */ + reConstruct(min, max, worldMatrix) { + const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; + const vectors = this.vectors; + this.minimum.copyFromFloats(minX, minY, minZ); + this.maximum.copyFromFloats(maxX, maxY, maxZ); + vectors[0].copyFromFloats(minX, minY, minZ); + vectors[1].copyFromFloats(maxX, maxY, maxZ); + vectors[2].copyFromFloats(maxX, minY, minZ); + vectors[3].copyFromFloats(minX, maxY, minZ); + vectors[4].copyFromFloats(minX, minY, maxZ); + vectors[5].copyFromFloats(maxX, maxY, minZ); + vectors[6].copyFromFloats(minX, maxY, maxZ); + vectors[7].copyFromFloats(maxX, minY, maxZ); + // OBB + max.addToRef(min, this.center).scaleInPlace(0.5); + max.subtractToRef(min, this.extendSize).scaleInPlace(0.5); + this._worldMatrix = worldMatrix || Matrix.IdentityReadOnly; + this._update(this._worldMatrix); + } + /** + * Scale the current bounding box by applying a scale factor + * @param factor defines the scale factor to apply + * @returns the current bounding box + */ + scale(factor) { + const tmpVectors = BoundingBox._TmpVector3; + const diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]); + const len = diff.length(); + diff.normalizeFromLength(len); + const distance = len * factor; + const newRadius = diff.scaleInPlace(distance * 0.5); + const min = this.center.subtractToRef(newRadius, tmpVectors[1]); + const max = this.center.addToRef(newRadius, tmpVectors[2]); + this.reConstruct(min, max, this._worldMatrix); + return this; + } + /** + * Gets the world matrix of the bounding box + * @returns a matrix + */ + getWorldMatrix() { + return this._worldMatrix; + } + /** + * @internal + */ + _update(world) { + const minWorld = this.minimumWorld; + const maxWorld = this.maximumWorld; + const directions = this.directions; + const vectorsWorld = this.vectorsWorld; + const vectors = this.vectors; + if (!world.isIdentity()) { + minWorld.setAll(Number.MAX_VALUE); + maxWorld.setAll(-Number.MAX_VALUE); + for (let index = 0; index < 8; ++index) { + const v = vectorsWorld[index]; + Vector3.TransformCoordinatesToRef(vectors[index], world, v); + minWorld.minimizeInPlace(v); + maxWorld.maximizeInPlace(v); + } + // Extend + maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5); + maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5); + } + else { + minWorld.copyFrom(this.minimum); + maxWorld.copyFrom(this.maximum); + for (let index = 0; index < 8; ++index) { + vectorsWorld[index].copyFrom(vectors[index]); + } + // Extend + this.extendSizeWorld.copyFrom(this.extendSize); + this.centerWorld.copyFrom(this.center); + } + Vector3.FromArrayToRef(world.m, 0, directions[0]); + Vector3.FromArrayToRef(world.m, 4, directions[1]); + Vector3.FromArrayToRef(world.m, 8, directions[2]); + this._worldMatrix = world; + } + /** + * Tests if the bounding box is intersecting the frustum planes + * @param frustumPlanes defines the frustum planes to test + * @returns true if there is an intersection + */ + isInFrustum(frustumPlanes) { + return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes); + } + /** + * Tests if the bounding box is entirely inside the frustum planes + * @param frustumPlanes defines the frustum planes to test + * @returns true if there is an inclusion + */ + isCompletelyInFrustum(frustumPlanes) { + return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes); + } + /** + * Tests if a point is inside the bounding box + * @param point defines the point to test + * @returns true if the point is inside the bounding box + */ + intersectsPoint(point) { + const min = this.minimumWorld; + const max = this.maximumWorld; + const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; + const pointX = point.x, pointY = point.y, pointZ = point.z; + const delta = -Epsilon; + if (maxX - pointX < delta || delta > pointX - minX) { + return false; + } + if (maxY - pointY < delta || delta > pointY - minY) { + return false; + } + if (maxZ - pointZ < delta || delta > pointZ - minZ) { + return false; + } + return true; + } + /** + * Tests if the bounding box intersects with a bounding sphere + * @param sphere defines the sphere to test + * @returns true if there is an intersection + */ + intersectsSphere(sphere) { + return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld); + } + /** + * Tests if the bounding box intersects with a box defined by a min and max vectors + * @param min defines the min vector to use + * @param max defines the max vector to use + * @returns true if there is an intersection + */ + intersectsMinMax(min, max) { + const myMin = this.minimumWorld; + const myMax = this.maximumWorld; + const myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z; + const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; + if (myMaxX < minX || myMinX > maxX) { + return false; + } + if (myMaxY < minY || myMinY > maxY) { + return false; + } + if (myMaxZ < minZ || myMinZ > maxZ) { + return false; + } + return true; + } + /** + * Disposes the resources of the class + */ + dispose() { + this._drawWrapperFront?.dispose(); + this._drawWrapperBack?.dispose(); + } + // Statics + /** + * Tests if two bounding boxes are intersections + * @param box0 defines the first box to test + * @param box1 defines the second box to test + * @returns true if there is an intersection + */ + static Intersects(box0, box1) { + return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld); + } + /** + * Tests if a bounding box defines by a min/max vectors intersects a sphere + * @param minPoint defines the minimum vector of the bounding box + * @param maxPoint defines the maximum vector of the bounding box + * @param sphereCenter defines the sphere center + * @param sphereRadius defines the sphere radius + * @returns true if there is an intersection + */ + static IntersectsSphere(minPoint, maxPoint, sphereCenter, sphereRadius) { + const vector = BoundingBox._TmpVector3[0]; + Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector); + const num = Vector3.DistanceSquared(sphereCenter, vector); + return num <= sphereRadius * sphereRadius; + } + /** + * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes + * @param boundingVectors defines an array of 8 vectors representing a bounding box + * @param frustumPlanes defines the frustum planes to test + * @returns true if there is an inclusion + */ + static IsCompletelyInFrustum(boundingVectors, frustumPlanes) { + for (let p = 0; p < 6; ++p) { + const frustumPlane = frustumPlanes[p]; + for (let i = 0; i < 8; ++i) { + if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) { + return false; + } + } + } + return true; + } + /** + * Tests if a bounding box defined with 8 vectors intersects frustum planes + * @param boundingVectors defines an array of 8 vectors representing a bounding box + * @param frustumPlanes defines the frustum planes to test + * @returns true if there is an intersection + */ + static IsInFrustum(boundingVectors, frustumPlanes) { + for (let p = 0; p < 6; ++p) { + let canReturnFalse = true; + const frustumPlane = frustumPlanes[p]; + for (let i = 0; i < 8; ++i) { + if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) { + canReturnFalse = false; + break; + } + } + if (canReturnFalse) { + return false; + } + } + return true; + } +} +BoundingBox._TmpVector3 = BuildArray(3, Vector3.Zero); + +/** + * Class used to store bounding sphere information + */ +class BoundingSphere { + /** + * Creates a new bounding sphere + * @param min defines the minimum vector (in local space) + * @param max defines the maximum vector (in local space) + * @param worldMatrix defines the new world matrix + */ + constructor(min, max, worldMatrix) { + /** + * Gets the center of the bounding sphere in local space + */ + this.center = Vector3.Zero(); + /** + * Gets the center of the bounding sphere in world space + */ + this.centerWorld = Vector3.Zero(); + /** + * Gets the minimum vector in local space + */ + this.minimum = Vector3.Zero(); + /** + * Gets the maximum vector in local space + */ + this.maximum = Vector3.Zero(); + this.reConstruct(min, max, worldMatrix); + } + /** + * Recreates the entire bounding sphere from scratch as if we call the constructor in place + * @param min defines the new minimum vector (in local space) + * @param max defines the new maximum vector (in local space) + * @param worldMatrix defines the new world matrix + */ + reConstruct(min, max, worldMatrix) { + this.minimum.copyFrom(min); + this.maximum.copyFrom(max); + const distance = Vector3.Distance(min, max); + max.addToRef(min, this.center).scaleInPlace(0.5); + this.radius = distance * 0.5; + this._update(worldMatrix || Matrix.IdentityReadOnly); + } + /** + * Scale the current bounding sphere by applying a scale factor + * @param factor defines the scale factor to apply + * @returns the current bounding box + */ + scale(factor) { + const newRadius = this.radius * factor; + const tmpVectors = BoundingSphere._TmpVector3; + const tempRadiusVector = tmpVectors[0].setAll(newRadius); + const min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]); + const max = this.center.addToRef(tempRadiusVector, tmpVectors[2]); + this.reConstruct(min, max, this._worldMatrix); + return this; + } + /** + * Gets the world matrix of the bounding box + * @returns a matrix + */ + getWorldMatrix() { + return this._worldMatrix; + } + // Methods + /** + * @internal + */ + _update(worldMatrix) { + if (!worldMatrix.isIdentity()) { + Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld); + const tempVector = BoundingSphere._TmpVector3[0]; + Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector); + this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius; + } + else { + this.centerWorld.copyFrom(this.center); + this.radiusWorld = this.radius; + } + } + /** + * Tests if the bounding sphere is intersecting the frustum planes + * @param frustumPlanes defines the frustum planes to test + * @returns true if there is an intersection + */ + isInFrustum(frustumPlanes) { + const center = this.centerWorld; + const radius = this.radiusWorld; + for (let i = 0; i < 6; i++) { + if (frustumPlanes[i].dotCoordinate(center) <= -radius) { + return false; + } + } + return true; + } + /** + * Tests if the bounding sphere center is in between the frustum planes. + * Used for optimistic fast inclusion. + * @param frustumPlanes defines the frustum planes to test + * @returns true if the sphere center is in between the frustum planes + */ + isCenterInFrustum(frustumPlanes) { + const center = this.centerWorld; + for (let i = 0; i < 6; i++) { + if (frustumPlanes[i].dotCoordinate(center) < 0) { + return false; + } + } + return true; + } + /** + * Tests if a point is inside the bounding sphere + * @param point defines the point to test + * @returns true if the point is inside the bounding sphere + */ + intersectsPoint(point) { + const squareDistance = Vector3.DistanceSquared(this.centerWorld, point); + if (this.radiusWorld * this.radiusWorld < squareDistance) { + return false; + } + return true; + } + // Statics + /** + * Checks if two sphere intersect + * @param sphere0 sphere 0 + * @param sphere1 sphere 1 + * @returns true if the spheres intersect + */ + static Intersects(sphere0, sphere1) { + const squareDistance = Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld); + const radiusSum = sphere0.radiusWorld + sphere1.radiusWorld; + if (radiusSum * radiusSum < squareDistance) { + return false; + } + return true; + } + /** + * Creates a sphere from a center and a radius + * @param center The center + * @param radius radius + * @param matrix Optional worldMatrix + * @returns The sphere + */ + static CreateFromCenterAndRadius(center, radius, matrix) { + this._TmpVector3[0].copyFrom(center); + this._TmpVector3[1].copyFromFloats(0, 0, radius); + this._TmpVector3[2].copyFrom(center); + this._TmpVector3[0].addInPlace(this._TmpVector3[1]); + this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]); + const sphere = new BoundingSphere(this._TmpVector3[0], this._TmpVector3[2]); + if (matrix) { + sphere._worldMatrix = matrix; + } + else { + sphere._worldMatrix = Matrix.Identity(); + } + return sphere; + } +} +BoundingSphere._TmpVector3 = BuildArray(3, Vector3.Zero); + +const _result0 = { min: 0, max: 0 }; +const _result1 = { min: 0, max: 0 }; +const computeBoxExtents = (axis, box, result) => { + const p = Vector3.Dot(box.centerWorld, axis); + const r0 = Math.abs(Vector3.Dot(box.directions[0], axis)) * box.extendSize.x; + const r1 = Math.abs(Vector3.Dot(box.directions[1], axis)) * box.extendSize.y; + const r2 = Math.abs(Vector3.Dot(box.directions[2], axis)) * box.extendSize.z; + const r = r0 + r1 + r2; + result.min = p - r; + result.max = p + r; +}; +const axisOverlap = (axis, box0, box1) => { + computeBoxExtents(axis, box0, _result0); + computeBoxExtents(axis, box1, _result1); + return !(_result0.min > _result1.max || _result1.min > _result0.max); +}; +/** + * Info for a bounding data of a mesh + */ +class BoundingInfo { + /** + * Constructs bounding info + * @param minimum min vector of the bounding box/sphere + * @param maximum max vector of the bounding box/sphere + * @param worldMatrix defines the new world matrix + */ + constructor(minimum, maximum, worldMatrix) { + this._isLocked = false; + this.boundingBox = new BoundingBox(minimum, maximum, worldMatrix); + this.boundingSphere = new BoundingSphere(minimum, maximum, worldMatrix); + } + /** + * Recreates the entire bounding info from scratch as if we call the constructor in place + * @param min defines the new minimum vector (in local space) + * @param max defines the new maximum vector (in local space) + * @param worldMatrix defines the new world matrix + */ + reConstruct(min, max, worldMatrix) { + this.boundingBox.reConstruct(min, max, worldMatrix); + this.boundingSphere.reConstruct(min, max, worldMatrix); + } + /** + * min vector of the bounding box/sphere + */ + get minimum() { + return this.boundingBox.minimum; + } + /** + * max vector of the bounding box/sphere + */ + get maximum() { + return this.boundingBox.maximum; + } + /** + * If the info is locked and won't be updated to avoid perf overhead + */ + get isLocked() { + return this._isLocked; + } + set isLocked(value) { + this._isLocked = value; + } + // Methods + /** + * Updates the bounding sphere and box + * @param world world matrix to be used to update + */ + update(world) { + if (this._isLocked) { + return; + } + this.boundingBox._update(world); + this.boundingSphere._update(world); + } + /** + * Recreate the bounding info to be centered around a specific point given a specific extend. + * @param center New center of the bounding info + * @param extend New extend of the bounding info + * @returns the current bounding info + */ + centerOn(center, extend) { + const minimum = BoundingInfo._TmpVector3[0].copyFrom(center).subtractInPlace(extend); + const maximum = BoundingInfo._TmpVector3[1].copyFrom(center).addInPlace(extend); + this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix()); + this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix()); + return this; + } + /** + * Grows the bounding info to include the given point. + * @param point The point that will be included in the current bounding info (in local space) + * @returns the current bounding info + */ + encapsulate(point) { + const minimum = Vector3.Minimize(this.minimum, point); + const maximum = Vector3.Maximize(this.maximum, point); + this.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix()); + return this; + } + /** + * Grows the bounding info to encapsulate the given bounding info. + * @param toEncapsulate The bounding info that will be encapsulated in the current bounding info + * @returns the current bounding info + */ + encapsulateBoundingInfo(toEncapsulate) { + const invw = TmpVectors.Matrix[0]; + this.boundingBox.getWorldMatrix().invertToRef(invw); + const v = TmpVectors.Vector3[0]; + Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.minimumWorld, invw, v); + this.encapsulate(v); + Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.maximumWorld, invw, v); + this.encapsulate(v); + return this; + } + /** + * Scale the current bounding info by applying a scale factor + * @param factor defines the scale factor to apply + * @returns the current bounding info + */ + scale(factor) { + this.boundingBox.scale(factor); + this.boundingSphere.scale(factor); + return this; + } + /** + * Returns `true` if the bounding info is within the frustum defined by the passed array of planes. + * @param frustumPlanes defines the frustum to test + * @param strategy defines the strategy to use for the culling (default is BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD) + * The different strategies available are: + * * BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD most accurate but slower @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_STANDARD + * * BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY faster but less accurate @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY + * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION + * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY + * @returns true if the bounding info is in the frustum planes + */ + isInFrustum(frustumPlanes, strategy = 0) { + const inclusionTest = strategy === 2 || strategy === 3; + if (inclusionTest) { + if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) { + return true; + } + } + if (!this.boundingSphere.isInFrustum(frustumPlanes)) { + return false; + } + const bSphereOnlyTest = strategy === 1 || strategy === 3; + if (bSphereOnlyTest) { + return true; + } + return this.boundingBox.isInFrustum(frustumPlanes); + } + /** + * Gets the world distance between the min and max points of the bounding box + */ + get diagonalLength() { + const boundingBox = this.boundingBox; + const diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo._TmpVector3[0]); + return diag.length(); + } + /** + * Checks if a cullable object (mesh...) is in the camera frustum + * Unlike isInFrustum this checks the full bounding box + * @param frustumPlanes Camera near/planes + * @returns true if the object is in frustum otherwise false + */ + isCompletelyInFrustum(frustumPlanes) { + return this.boundingBox.isCompletelyInFrustum(frustumPlanes); + } + /** + * @internal + */ + _checkCollision(collider) { + return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld); + } + /** + * Checks if a point is inside the bounding box and bounding sphere or the mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect + * @param point the point to check intersection with + * @returns if the point intersects + */ + intersectsPoint(point) { + if (!this.boundingSphere.centerWorld) { + return false; + } + if (!this.boundingSphere.intersectsPoint(point)) { + return false; + } + if (!this.boundingBox.intersectsPoint(point)) { + return false; + } + return true; + } + /** + * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect + * @param boundingInfo the bounding info to check intersection with + * @param precise if the intersection should be done using OBB + * @returns if the bounding info intersects + */ + intersects(boundingInfo, precise) { + if (!BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) { + return false; + } + if (!BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) { + return false; + } + if (!precise) { + return true; + } + const box0 = this.boundingBox; + const box1 = boundingInfo.boundingBox; + if (!axisOverlap(box0.directions[0], box0, box1)) { + return false; + } + if (!axisOverlap(box0.directions[1], box0, box1)) { + return false; + } + if (!axisOverlap(box0.directions[2], box0, box1)) { + return false; + } + if (!axisOverlap(box1.directions[0], box0, box1)) { + return false; + } + if (!axisOverlap(box1.directions[1], box0, box1)) { + return false; + } + if (!axisOverlap(box1.directions[2], box0, box1)) { + return false; + } + if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) { + return false; + } + if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) { + return false; + } + if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) { + return false; + } + if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) { + return false; + } + if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) { + return false; + } + if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) { + return false; + } + if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) { + return false; + } + if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) { + return false; + } + if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) { + return false; + } + return true; + } +} +BoundingInfo._TmpVector3 = BuildArray(2, Vector3.Zero); + +// This helper class is only here so we can apply the nativeOverride decorator to functions. +class MathHelpers { + static extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum) { + for (let index = indexStart; index < indexStart + indexCount; index++) { + const offset = indices[index] * 3; + const x = positions[offset]; + const y = positions[offset + 1]; + const z = positions[offset + 2]; + minimum.minimizeInPlaceFromFloats(x, y, z); + maximum.maximizeInPlaceFromFloats(x, y, z); + } + } + static extractMinAndMax(positions, start, count, stride, minimum, maximum) { + for (let index = start, offset = start * stride; index < start + count; index++, offset += stride) { + const x = positions[offset]; + const y = positions[offset + 1]; + const z = positions[offset + 2]; + minimum.minimizeInPlaceFromFloats(x, y, z); + maximum.maximizeInPlaceFromFloats(x, y, z); + } + } +} +__decorate([ + nativeOverride.filter((...[positions, indices]) => !Array.isArray(positions) && !Array.isArray(indices)) + // eslint-disable-next-line @typescript-eslint/naming-convention +], MathHelpers, "extractMinAndMaxIndexed", null); +__decorate([ + nativeOverride.filter((...[positions]) => !Array.isArray(positions)) + // eslint-disable-next-line @typescript-eslint/naming-convention +], MathHelpers, "extractMinAndMax", null); +/** + * Extracts minimum and maximum values from a list of indexed positions + * @param positions defines the positions to use + * @param indices defines the indices to the positions + * @param indexStart defines the start index + * @param indexCount defines the end index + * @param bias defines bias value to add to the result + * @returns minimum and maximum values + */ +function extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, bias = null) { + const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + MathHelpers.extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum); + if (bias) { + minimum.x -= minimum.x * bias.x + bias.y; + minimum.y -= minimum.y * bias.x + bias.y; + minimum.z -= minimum.z * bias.x + bias.y; + maximum.x += maximum.x * bias.x + bias.y; + maximum.y += maximum.y * bias.x + bias.y; + maximum.z += maximum.z * bias.x + bias.y; + } + return { + minimum: minimum, + maximum: maximum, + }; +} +/** + * Extracts minimum and maximum values from a list of positions + * @param positions defines the positions to use + * @param start defines the start index in the positions array + * @param count defines the number of positions to handle + * @param bias defines bias value to add to the result + * @param stride defines the stride size to use (distance between two positions in the positions array) + * @returns minimum and maximum values + */ +function extractMinAndMax(positions, start, count, bias = null, stride) { + const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + if (!stride) { + stride = 3; + } + MathHelpers.extractMinAndMax(positions, start, count, stride, minimum, maximum); + if (bias) { + minimum.x -= minimum.x * bias.x + bias.y; + minimum.y -= minimum.y * bias.x + bias.y; + minimum.z -= minimum.z * bias.x + bias.y; + maximum.x += maximum.x * bias.x + bias.y; + maximum.y += maximum.y * bias.x + bias.y; + maximum.z += maximum.z * bias.x + bias.y; + } + return { + minimum: minimum, + maximum: maximum, + }; +} +/** + * Flip flipped faces + * @param positions defines the positions to use + * @param indices defines the indices to use and update + */ +function FixFlippedFaces(positions, indices) { + const boundingInfo = extractMinAndMax(positions, 0, positions.length / 3); + const inside = boundingInfo.maximum.subtract(boundingInfo.minimum).scale(0.5).add(boundingInfo.minimum); + const tmpVectorA = new Vector3(); + const tmpVectorB = new Vector3(); + const tmpVectorC = new Vector3(); + const tmpVectorAB = new Vector3(); + const tmpVectorAC = new Vector3(); + const tmpVectorNormal = new Vector3(); + const tmpVectorAvgNormal = new Vector3(); + // Clean indices + for (let index = 0; index < indices.length; index += 3) { + const a = indices[index]; + const b = indices[index + 1]; + const c = indices[index + 2]; + // Evaluate face normal + tmpVectorA.fromArray(positions, a * 3); + tmpVectorB.fromArray(positions, b * 3); + tmpVectorC.fromArray(positions, c * 3); + tmpVectorB.subtractToRef(tmpVectorA, tmpVectorAB); + tmpVectorC.subtractToRef(tmpVectorA, tmpVectorAC); + Vector3.CrossToRef(tmpVectorAB, tmpVectorAC, tmpVectorNormal); + tmpVectorNormal.normalize(); + // Calculate normal from face center to the inside of the geometry + const avgX = tmpVectorA.x + tmpVectorB.x + tmpVectorC.x; + const avgY = tmpVectorA.y + tmpVectorB.y + tmpVectorC.y; + const avgZ = tmpVectorA.z + tmpVectorB.z + tmpVectorC.z; + tmpVectorAvgNormal.set(avgX / 3, avgY / 3, avgZ / 3); + tmpVectorAvgNormal.subtractInPlace(inside); + tmpVectorAvgNormal.normalize(); + if (Vector3.Dot(tmpVectorNormal, tmpVectorAvgNormal) >= 0) { + // Flip! + indices[index] = c; + indices[index + 2] = a; + } + } +} + +/** @internal */ +class DrawWrapper { + static GetEffect(effect) { + return effect.getPipelineContext === undefined ? effect.effect : effect; + } + constructor(engine, createMaterialContext = true) { + /** + * @internal + * Specifies if the effect was previously ready + */ + this._wasPreviouslyReady = false; + /** + * @internal + * Forces the code from bindForSubMesh to be fully run the next time it is called + */ + this._forceRebindOnNextCall = true; + /** + * @internal + * Specifies if the effect was previously using instances + */ + this._wasPreviouslyUsingInstances = null; + this.effect = null; + this.defines = null; + this.drawContext = engine.createDrawContext(); + if (createMaterialContext) { + this.materialContext = engine.createMaterialContext(); + } + } + setEffect(effect, defines, resetContext = true) { + this.effect = effect; + if (defines !== undefined) { + this.defines = defines; + } + if (resetContext) { + this.drawContext?.reset(); + } + } + /** + * Dispose the effect wrapper and its resources + * @param immediate if the effect should be disposed immediately or on the next frame. + * If dispose() is not called during a scene or engine dispose, we want to delay the dispose of the underlying effect. Mostly to give a chance to user code to reuse the effect in some way. + */ + dispose(immediate = false) { + if (this.effect) { + const effect = this.effect; + if (immediate) { + effect.dispose(); + } + else { + TimingTools.SetImmediate(() => { + effect.getEngine().onEndFrameObservable.addOnce(() => { + effect.dispose(); + }); + }); + } + this.effect = null; + } + this.drawContext?.dispose(); + } +} + +/** + * Defines a subdivision inside a mesh + */ +class SubMesh { + /** + * Gets material defines used by the effect associated to the sub mesh + */ + get materialDefines() { + return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.defines : this._getDrawWrapper()?.defines; + } + /** + * Sets material defines used by the effect associated to the sub mesh + */ + set materialDefines(defines) { + const drawWrapper = this._mainDrawWrapperOverride ?? this._getDrawWrapper(undefined, true); + drawWrapper.defines = defines; + } + /** + * @internal + */ + _getDrawWrapper(passId, createIfNotExisting = false) { + passId = passId ?? this._engine.currentRenderPassId; + let drawWrapper = this._drawWrappers[passId]; + if (!drawWrapper && createIfNotExisting) { + this._drawWrappers[passId] = drawWrapper = new DrawWrapper(this._mesh.getScene().getEngine()); + } + return drawWrapper; + } + /** + * @internal + */ + _removeDrawWrapper(passId, disposeWrapper = true, immediate = false) { + if (disposeWrapper) { + this._drawWrappers[passId]?.dispose(immediate); + } + this._drawWrappers[passId] = undefined; + } + /** + * Gets associated (main) effect (possibly the effect override if defined) + */ + get effect() { + return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.effect : (this._getDrawWrapper()?.effect ?? null); + } + /** @internal */ + get _drawWrapper() { + return this._mainDrawWrapperOverride ?? this._getDrawWrapper(undefined, true); + } + /** @internal */ + get _drawWrapperOverride() { + return this._mainDrawWrapperOverride; + } + /** + * @internal + */ + _setMainDrawWrapperOverride(wrapper) { + this._mainDrawWrapperOverride = wrapper; + } + /** + * Sets associated effect (effect used to render this submesh) + * @param effect defines the effect to associate with + * @param defines defines the set of defines used to compile this effect + * @param materialContext material context associated to the effect + * @param resetContext true to reset the draw context + */ + setEffect(effect, defines = null, materialContext, resetContext = true) { + const drawWrapper = this._drawWrapper; + drawWrapper.setEffect(effect, defines, resetContext); + if (materialContext !== undefined) { + drawWrapper.materialContext = materialContext; + } + if (!effect) { + drawWrapper.defines = null; + drawWrapper.materialContext = undefined; + } + } + /** + * Resets the draw wrappers cache + * @param passId If provided, releases only the draw wrapper corresponding to this render pass id + * @param immediate If true, the draw wrapper will dispose the effect immediately (false by default) + */ + resetDrawCache(passId, immediate = false) { + if (this._drawWrappers) { + if (passId !== undefined) { + this._removeDrawWrapper(passId, true, immediate); + return; + } + else { + for (const drawWrapper of this._drawWrappers) { + drawWrapper?.dispose(immediate); + } + } + } + this._drawWrappers = []; + } + /** + * Add a new submesh to a mesh + * @param materialIndex defines the material index to use + * @param verticesStart defines vertex index start + * @param verticesCount defines vertices count + * @param indexStart defines index start + * @param indexCount defines indices count + * @param mesh defines the parent mesh + * @param renderingMesh defines an optional rendering mesh + * @param createBoundingBox defines if bounding box should be created for this submesh + * @returns the new submesh + */ + static AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox = true) { + return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox); + } + /** + * Creates a new submesh + * @param materialIndex defines the material index to use + * @param verticesStart defines vertex index start + * @param verticesCount defines vertices count + * @param indexStart defines index start + * @param indexCount defines indices count + * @param mesh defines the parent mesh + * @param renderingMesh defines an optional rendering mesh + * @param createBoundingBox defines if bounding box should be created for this submesh + * @param addToMesh defines a boolean indicating that the submesh must be added to the mesh.subMeshes array (true by default) + */ + constructor( + /** the material index to use */ + materialIndex, + /** vertex index start */ + verticesStart, + /** vertices count */ + verticesCount, + /** index start */ + indexStart, + /** indices count */ + indexCount, mesh, renderingMesh, createBoundingBox = true, addToMesh = true) { + this.materialIndex = materialIndex; + this.verticesStart = verticesStart; + this.verticesCount = verticesCount; + this.indexStart = indexStart; + this.indexCount = indexCount; + this._mainDrawWrapperOverride = null; + /** @internal */ + this._linesIndexCount = 0; + this._linesIndexBuffer = null; + /** @internal */ + this._lastColliderWorldVertices = null; + /** @internal */ + this._lastColliderTransformMatrix = null; + /** @internal */ + this._wasDispatched = false; + /** @internal */ + this._renderId = 0; + /** @internal */ + this._alphaIndex = 0; + /** @internal */ + this._distanceToCamera = 0; + this._currentMaterial = null; + this._mesh = mesh; + this._renderingMesh = renderingMesh || mesh; + if (addToMesh) { + mesh.subMeshes.push(this); + } + this._engine = this._mesh.getScene().getEngine(); + this.resetDrawCache(); + this._trianglePlanes = []; + this._id = mesh.subMeshes.length - 1; + if (createBoundingBox) { + this.refreshBoundingInfo(); + mesh.computeWorldMatrix(true); + } + } + /** + * Returns true if this submesh covers the entire parent mesh + * @ignorenaming + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + get IsGlobal() { + return this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices() && this.indexStart === 0 && this.indexCount === this._mesh.getTotalIndices(); + } + /** + * Returns the submesh BoundingInfo object + * @returns current bounding info (or mesh's one if the submesh is global) + */ + getBoundingInfo() { + if (this.IsGlobal || this._mesh.hasThinInstances) { + return this._mesh.getBoundingInfo(); + } + return this._boundingInfo; + } + /** + * Sets the submesh BoundingInfo + * @param boundingInfo defines the new bounding info to use + * @returns the SubMesh + */ + setBoundingInfo(boundingInfo) { + this._boundingInfo = boundingInfo; + return this; + } + /** + * Returns the mesh of the current submesh + * @returns the parent mesh + */ + getMesh() { + return this._mesh; + } + /** + * Returns the rendering mesh of the submesh + * @returns the rendering mesh (could be different from parent mesh) + */ + getRenderingMesh() { + return this._renderingMesh; + } + /** + * Returns the replacement mesh of the submesh + * @returns the replacement mesh (could be different from parent mesh) + */ + getReplacementMesh() { + return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null; + } + /** + * Returns the effective mesh of the submesh + * @returns the effective mesh (could be different from parent mesh) + */ + getEffectiveMesh() { + const replacementMesh = this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null; + return replacementMesh ? replacementMesh : this._renderingMesh; + } + /** + * Returns the submesh material + * @param getDefaultMaterial Defines whether or not to get the default material if nothing has been defined. + * @returns null or the current material + */ + getMaterial(getDefaultMaterial = true) { + const rootMaterial = this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId) ?? this._renderingMesh.material; + if (!rootMaterial) { + return getDefaultMaterial && this._mesh.getScene()._hasDefaultMaterial ? this._mesh.getScene().defaultMaterial : null; + } + else if (this._isMultiMaterial(rootMaterial)) { + const effectiveMaterial = rootMaterial.getSubMaterial(this.materialIndex); + if (this._currentMaterial !== effectiveMaterial) { + this._currentMaterial = effectiveMaterial; + this.resetDrawCache(); + } + return effectiveMaterial; + } + return rootMaterial; + } + _isMultiMaterial(material) { + return material.getSubMaterial !== undefined; + } + // Methods + /** + * Sets a new updated BoundingInfo object to the submesh + * @param data defines an optional position array to use to determine the bounding info + * @returns the SubMesh + */ + refreshBoundingInfo(data = null) { + this._lastColliderWorldVertices = null; + if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) { + return this; + } + if (!data) { + data = this._renderingMesh.getVerticesData(VertexBuffer.PositionKind); + } + if (!data) { + this._boundingInfo = this._mesh.getBoundingInfo(); + return this; + } + const indices = this._renderingMesh.getIndices(); + let extend; + //is this the only submesh? + if (this.indexStart === 0 && this.indexCount === indices.length) { + const boundingInfo = this._renderingMesh.getBoundingInfo(); + //the rendering mesh's bounding info can be used, it is the standard submesh for all indices. + extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() }; + } + else { + extend = extractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias); + } + if (this._boundingInfo) { + this._boundingInfo.reConstruct(extend.minimum, extend.maximum); + } + else { + this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum); + } + return this; + } + /** + * @internal + */ + _checkCollision(collider) { + const boundingInfo = this.getBoundingInfo(); + return boundingInfo._checkCollision(collider); + } + /** + * Updates the submesh BoundingInfo + * @param world defines the world matrix to use to update the bounding info + * @returns the submesh + */ + updateBoundingInfo(world) { + let boundingInfo = this.getBoundingInfo(); + if (!boundingInfo) { + this.refreshBoundingInfo(); + boundingInfo = this.getBoundingInfo(); + } + if (boundingInfo) { + boundingInfo.update(world); + } + return this; + } + /** + * True is the submesh bounding box intersects the frustum defined by the passed array of planes. + * @param frustumPlanes defines the frustum planes + * @returns true if the submesh is intersecting with the frustum + */ + isInFrustum(frustumPlanes) { + const boundingInfo = this.getBoundingInfo(); + if (!boundingInfo) { + return false; + } + return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy); + } + /** + * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes + * @param frustumPlanes defines the frustum planes + * @returns true if the submesh is inside the frustum + */ + isCompletelyInFrustum(frustumPlanes) { + const boundingInfo = this.getBoundingInfo(); + if (!boundingInfo) { + return false; + } + return boundingInfo.isCompletelyInFrustum(frustumPlanes); + } + /** + * Renders the submesh + * @param enableAlphaMode defines if alpha needs to be used + * @returns the submesh + */ + render(enableAlphaMode) { + this._renderingMesh.render(this, enableAlphaMode, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : undefined); + return this; + } + /** + * @internal + */ + _getLinesIndexBuffer(indices, engine) { + if (!this._linesIndexBuffer) { + const adjustedIndexCount = Math.floor(this.indexCount / 3) * 6; + const shouldUseUint32 = this.verticesStart + this.verticesCount > 65535; + const linesIndices = shouldUseUint32 ? new Uint32Array(adjustedIndexCount) : new Uint16Array(adjustedIndexCount); + let offset = 0; + if (indices.length === 0) { + // Unindexed mesh + for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) { + linesIndices[offset++] = index; + linesIndices[offset++] = index + 1; + linesIndices[offset++] = index + 1; + linesIndices[offset++] = index + 2; + linesIndices[offset++] = index + 2; + linesIndices[offset++] = index; + } + } + else { + for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) { + linesIndices[offset++] = indices[index]; + linesIndices[offset++] = indices[index + 1]; + linesIndices[offset++] = indices[index + 1]; + linesIndices[offset++] = indices[index + 2]; + linesIndices[offset++] = indices[index + 2]; + linesIndices[offset++] = indices[index]; + } + } + this._linesIndexBuffer = engine.createIndexBuffer(linesIndices); + this._linesIndexCount = linesIndices.length; + } + return this._linesIndexBuffer; + } + /** + * Checks if the submesh intersects with a ray + * @param ray defines the ray to test + * @returns true is the passed ray intersects the submesh bounding box + */ + canIntersects(ray) { + const boundingInfo = this.getBoundingInfo(); + if (!boundingInfo) { + return false; + } + return ray.intersectsBox(boundingInfo.boundingBox); + } + /** + * Intersects current submesh with a ray + * @param ray defines the ray to test + * @param positions defines mesh's positions array + * @param indices defines mesh's indices array + * @param fastCheck defines if the first intersection will be used (and not the closest) + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @returns intersection info or null if no intersection + */ + intersects(ray, positions, indices, fastCheck, trianglePredicate) { + const material = this.getMaterial(); + if (!material) { + return null; + } + let step = 3; + let checkStopper = false; + switch (material.fillMode) { + case 3: + case 5: + case 6: + case 8: + return null; + case 7: + step = 1; + checkStopper = true; + break; + } + // LineMesh first as it's also a Mesh... + if (material.fillMode === 4) { + // Check if mesh is unindexed + if (!indices.length) { + return this._intersectUnIndexedLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck); + } + return this._intersectLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck); + } + else { + // Check if mesh is unindexed + if (!indices.length && this._mesh._unIndexed) { + return this._intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate); + } + return this._intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate); + } + } + /** + * @internal + */ + _intersectLines(ray, positions, indices, intersectionThreshold, fastCheck) { + let intersectInfo = null; + // Line test + for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) { + const p0 = positions[indices[index]]; + const p1 = positions[indices[index + 1]]; + const length = ray.intersectionSegment(p0, p1, intersectionThreshold); + if (length < 0) { + continue; + } + if (fastCheck || !intersectInfo || length < intersectInfo.distance) { + intersectInfo = new IntersectionInfo(null, null, length); + intersectInfo.faceId = index / 2; + if (fastCheck) { + break; + } + } + } + return intersectInfo; + } + /** + * @internal + */ + _intersectUnIndexedLines(ray, positions, indices, intersectionThreshold, fastCheck) { + let intersectInfo = null; + // Line test + for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 2) { + const p0 = positions[index]; + const p1 = positions[index + 1]; + const length = ray.intersectionSegment(p0, p1, intersectionThreshold); + if (length < 0) { + continue; + } + if (fastCheck || !intersectInfo || length < intersectInfo.distance) { + intersectInfo = new IntersectionInfo(null, null, length); + intersectInfo.faceId = index / 2; + if (fastCheck) { + break; + } + } + } + return intersectInfo; + } + /** + * @internal + */ + _intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate) { + let intersectInfo = null; + // Triangles test + let faceId = -1; + for (let index = this.indexStart; index < this.indexStart + this.indexCount - (3 - step); index += step) { + faceId++; + const indexA = indices[index]; + const indexB = indices[index + 1]; + const indexC = indices[index + 2]; + if (checkStopper && indexC === 0xffffffff) { + index += 2; + continue; + } + const p0 = positions[indexA]; + const p1 = positions[indexB]; + const p2 = positions[indexC]; + // stay defensive and don't check against undefined positions. + if (!p0 || !p1 || !p2) { + continue; + } + if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, indexA, indexB, indexC)) { + continue; + } + const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2); + if (currentIntersectInfo) { + if (currentIntersectInfo.distance < 0) { + continue; + } + if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { + intersectInfo = currentIntersectInfo; + intersectInfo.faceId = faceId; + if (fastCheck) { + break; + } + } + } + } + return intersectInfo; + } + /** + * @internal + */ + _intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate) { + let intersectInfo = null; + // Triangles test + for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) { + const p0 = positions[index]; + const p1 = positions[index + 1]; + const p2 = positions[index + 2]; + if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, -1, -1, -1)) { + continue; + } + const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2); + if (currentIntersectInfo) { + if (currentIntersectInfo.distance < 0) { + continue; + } + if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { + intersectInfo = currentIntersectInfo; + intersectInfo.faceId = index / 3; + if (fastCheck) { + break; + } + } + } + } + return intersectInfo; + } + /** @internal */ + _rebuild() { + if (this._linesIndexBuffer) { + this._linesIndexBuffer = null; + } + } + // Clone + /** + * Creates a new submesh from the passed mesh + * @param newMesh defines the new hosting mesh + * @param newRenderingMesh defines an optional rendering mesh + * @returns the new submesh + */ + clone(newMesh, newRenderingMesh) { + const result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false); + if (!this.IsGlobal) { + const boundingInfo = this.getBoundingInfo(); + if (!boundingInfo) { + return result; + } + result._boundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum); + } + return result; + } + // Dispose + /** + * Release associated resources + * @param immediate If true, the effect will be disposed immediately (false by default) + */ + dispose(immediate = false) { + if (this._linesIndexBuffer) { + this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer); + this._linesIndexBuffer = null; + } + // Remove from mesh + const index = this._mesh.subMeshes.indexOf(this); + this._mesh.subMeshes.splice(index, 1); + this.resetDrawCache(undefined, immediate); + } + /** + * Gets the class name + * @returns the string "SubMesh". + */ + getClassName() { + return "SubMesh"; + } + // Statics + /** + * Creates a new submesh from indices data + * @param materialIndex the index of the main mesh material + * @param startIndex the index where to start the copy in the mesh indices array + * @param indexCount the number of indices to copy then from the startIndex + * @param mesh the main mesh to create the submesh from + * @param renderingMesh the optional rendering mesh + * @param createBoundingBox defines if bounding box should be created for this submesh + * @returns a new submesh + */ + static CreateFromIndices(materialIndex, startIndex, indexCount, mesh, renderingMesh, createBoundingBox = true) { + let minVertexIndex = Number.MAX_VALUE; + let maxVertexIndex = -Number.MAX_VALUE; + const whatWillRender = renderingMesh || mesh; + const indices = whatWillRender.getIndices(); + for (let index = startIndex; index < startIndex + indexCount; index++) { + const vertexIndex = indices[index]; + if (vertexIndex < minVertexIndex) { + minVertexIndex = vertexIndex; + } + if (vertexIndex > maxVertexIndex) { + maxVertexIndex = vertexIndex; + } + } + return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh, createBoundingBox); + } +} + +/** Class used to attach material info to sub section of a vertex data class */ +class VertexDataMaterialInfo { +} +/** + * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance + */ +class VertexData { + /** + * Creates a new VertexData + */ + constructor() { + /** + * Gets the unique ID of this vertex Data + */ + this.uniqueId = 0; + /** + * Metadata used to store contextual values + */ + this.metadata = {}; + this._applyTo = makeSyncFunction(this._applyToCoroutine.bind(this)); + this.uniqueId = VertexData._UniqueIDGenerator; + VertexData._UniqueIDGenerator++; + } + /** + * Uses the passed data array to set the set the values for the specified kind of data + * @param data a linear array of floating numbers + * @param kind the type of data that is being set, eg positions, colors etc + */ + set(data, kind) { + if (!data.length) { + Logger.Warn(`Setting vertex data kind '${kind}' with an empty array`); + } + switch (kind) { + case VertexBuffer.PositionKind: + this.positions = data; + break; + case VertexBuffer.NormalKind: + this.normals = data; + break; + case VertexBuffer.TangentKind: + this.tangents = data; + break; + case VertexBuffer.UVKind: + this.uvs = data; + break; + case VertexBuffer.UV2Kind: + this.uvs2 = data; + break; + case VertexBuffer.UV3Kind: + this.uvs3 = data; + break; + case VertexBuffer.UV4Kind: + this.uvs4 = data; + break; + case VertexBuffer.UV5Kind: + this.uvs5 = data; + break; + case VertexBuffer.UV6Kind: + this.uvs6 = data; + break; + case VertexBuffer.ColorKind: + this.colors = data; + break; + case VertexBuffer.MatricesIndicesKind: + this.matricesIndices = data; + break; + case VertexBuffer.MatricesWeightsKind: + this.matricesWeights = data; + break; + case VertexBuffer.MatricesIndicesExtraKind: + this.matricesIndicesExtra = data; + break; + case VertexBuffer.MatricesWeightsExtraKind: + this.matricesWeightsExtra = data; + break; + } + } + /** + * Associates the vertexData to the passed Mesh. + * Sets it as updatable or not (default `false`) + * @param mesh the mesh the vertexData is applied to + * @param updatable when used and having the value true allows new data to update the vertexData + * @returns the VertexData + */ + applyToMesh(mesh, updatable) { + this._applyTo(mesh, updatable, false); + return this; + } + /** + * Associates the vertexData to the passed Geometry. + * Sets it as updatable or not (default `false`) + * @param geometry the geometry the vertexData is applied to + * @param updatable when used and having the value true allows new data to update the vertexData + * @returns VertexData + */ + applyToGeometry(geometry, updatable) { + this._applyTo(geometry, updatable, false); + return this; + } + /** + * Updates the associated mesh + * @param mesh the mesh to be updated + * @returns VertexData + */ + updateMesh(mesh) { + this._update(mesh); + return this; + } + /** + * Updates the associated geometry + * @param geometry the geometry to be updated + * @returns VertexData. + */ + updateGeometry(geometry) { + this._update(geometry); + return this; + } + /** + * @internal + */ + *_applyToCoroutine(meshOrGeometry, updatable = false, isAsync) { + if (this.positions) { + meshOrGeometry.setVerticesData(VertexBuffer.PositionKind, this.positions, updatable); + if (isAsync) { + yield; + } + } + if (this.normals) { + meshOrGeometry.setVerticesData(VertexBuffer.NormalKind, this.normals, updatable); + if (isAsync) { + yield; + } + } + if (this.tangents) { + meshOrGeometry.setVerticesData(VertexBuffer.TangentKind, this.tangents, updatable); + if (isAsync) { + yield; + } + } + if (this.uvs) { + meshOrGeometry.setVerticesData(VertexBuffer.UVKind, this.uvs, updatable); + if (isAsync) { + yield; + } + } + if (this.uvs2) { + meshOrGeometry.setVerticesData(VertexBuffer.UV2Kind, this.uvs2, updatable); + if (isAsync) { + yield; + } + } + if (this.uvs3) { + meshOrGeometry.setVerticesData(VertexBuffer.UV3Kind, this.uvs3, updatable); + if (isAsync) { + yield; + } + } + if (this.uvs4) { + meshOrGeometry.setVerticesData(VertexBuffer.UV4Kind, this.uvs4, updatable); + if (isAsync) { + yield; + } + } + if (this.uvs5) { + meshOrGeometry.setVerticesData(VertexBuffer.UV5Kind, this.uvs5, updatable); + if (isAsync) { + yield; + } + } + if (this.uvs6) { + meshOrGeometry.setVerticesData(VertexBuffer.UV6Kind, this.uvs6, updatable); + if (isAsync) { + yield; + } + } + if (this.colors) { + const stride = this.positions && this.colors.length === this.positions.length ? 3 : 4; + meshOrGeometry.setVerticesData(VertexBuffer.ColorKind, this.colors, updatable, stride); + if (this.hasVertexAlpha && meshOrGeometry.hasVertexAlpha !== undefined) { + meshOrGeometry.hasVertexAlpha = true; + } + if (isAsync) { + yield; + } + } + if (this.matricesIndices) { + meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable); + if (isAsync) { + yield; + } + } + if (this.matricesWeights) { + meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable); + if (isAsync) { + yield; + } + } + if (this.matricesIndicesExtra) { + meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable); + if (isAsync) { + yield; + } + } + if (this.matricesWeightsExtra) { + meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable); + if (isAsync) { + yield; + } + } + if (this.indices) { + meshOrGeometry.setIndices(this.indices, null, updatable); + if (isAsync) { + yield; + } + } + else { + meshOrGeometry.setIndices([], null); + } + if (meshOrGeometry.subMeshes && this.materialInfos && this.materialInfos.length > 1) { + const mesh = meshOrGeometry; + mesh.subMeshes = []; + for (const matInfo of this.materialInfos) { + new SubMesh(matInfo.materialIndex, matInfo.verticesStart, matInfo.verticesCount, matInfo.indexStart, matInfo.indexCount, mesh); + } + } + return this; + } + _update(meshOrGeometry, updateExtends, makeItUnique) { + if (this.positions) { + meshOrGeometry.updateVerticesData(VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique); + } + if (this.normals) { + meshOrGeometry.updateVerticesData(VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique); + } + if (this.tangents) { + meshOrGeometry.updateVerticesData(VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique); + } + if (this.uvs) { + meshOrGeometry.updateVerticesData(VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique); + } + if (this.uvs2) { + meshOrGeometry.updateVerticesData(VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique); + } + if (this.uvs3) { + meshOrGeometry.updateVerticesData(VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique); + } + if (this.uvs4) { + meshOrGeometry.updateVerticesData(VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique); + } + if (this.uvs5) { + meshOrGeometry.updateVerticesData(VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique); + } + if (this.uvs6) { + meshOrGeometry.updateVerticesData(VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique); + } + if (this.colors) { + meshOrGeometry.updateVerticesData(VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique); + } + if (this.matricesIndices) { + meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique); + } + if (this.matricesWeights) { + meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique); + } + if (this.matricesIndicesExtra) { + meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique); + } + if (this.matricesWeightsExtra) { + meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique); + } + if (this.indices) { + meshOrGeometry.setIndices(this.indices, null); + } + return this; + } + static _TransformVector3Coordinates(coordinates, transformation, offset = 0, length = coordinates.length) { + const coordinate = TmpVectors.Vector3[0]; + const transformedCoordinate = TmpVectors.Vector3[1]; + for (let index = offset; index < offset + length; index += 3) { + Vector3.FromArrayToRef(coordinates, index, coordinate); + Vector3.TransformCoordinatesToRef(coordinate, transformation, transformedCoordinate); + coordinates[index] = transformedCoordinate.x; + coordinates[index + 1] = transformedCoordinate.y; + coordinates[index + 2] = transformedCoordinate.z; + } + } + static _TransformVector3Normals(normals, transformation, offset = 0, length = normals.length) { + const normal = TmpVectors.Vector3[0]; + const transformedNormal = TmpVectors.Vector3[1]; + for (let index = offset; index < offset + length; index += 3) { + Vector3.FromArrayToRef(normals, index, normal); + Vector3.TransformNormalToRef(normal, transformation, transformedNormal); + normals[index] = transformedNormal.x; + normals[index + 1] = transformedNormal.y; + normals[index + 2] = transformedNormal.z; + } + } + static _TransformVector4Normals(normals, transformation, offset = 0, length = normals.length) { + const normal = TmpVectors.Vector4[0]; + const transformedNormal = TmpVectors.Vector4[1]; + for (let index = offset; index < offset + length; index += 4) { + Vector4.FromArrayToRef(normals, index, normal); + Vector4.TransformNormalToRef(normal, transformation, transformedNormal); + normals[index] = transformedNormal.x; + normals[index + 1] = transformedNormal.y; + normals[index + 2] = transformedNormal.z; + normals[index + 3] = transformedNormal.w; + } + } + static _FlipFaces(indices, offset = 0, length = indices.length) { + for (let index = offset; index < offset + length; index += 3) { + const tmp = indices[index + 1]; + indices[index + 1] = indices[index + 2]; + indices[index + 2] = tmp; + } + } + /** + * Transforms each position and each normal of the vertexData according to the passed Matrix + * @param matrix the transforming matrix + * @returns the VertexData + */ + transform(matrix) { + const flip = matrix.determinant() < 0; + if (this.positions) { + VertexData._TransformVector3Coordinates(this.positions, matrix); + } + if (this.normals) { + VertexData._TransformVector3Normals(this.normals, matrix); + } + if (this.tangents) { + VertexData._TransformVector4Normals(this.tangents, matrix); + } + if (flip && this.indices) { + VertexData._FlipFaces(this.indices); + } + return this; + } + /** + * Generates an array of vertex data where each vertex data only has one material info + * @returns An array of VertexData + */ + splitBasedOnMaterialID() { + if (!this.materialInfos || this.materialInfos.length < 2) { + return [this]; + } + const result = []; + for (const materialInfo of this.materialInfos) { + const vertexData = new VertexData(); + if (this.positions) { + vertexData.positions = this.positions.slice(materialInfo.verticesStart * 3, (materialInfo.verticesCount + materialInfo.verticesStart) * 3); + } + if (this.normals) { + vertexData.normals = this.normals.slice(materialInfo.verticesStart * 3, (materialInfo.verticesCount + materialInfo.verticesStart) * 3); + } + if (this.tangents) { + vertexData.tangents = this.tangents.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); + } + if (this.colors) { + vertexData.colors = this.colors.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); + } + if (this.uvs) { + vertexData.uvs = this.uvs.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); + } + if (this.uvs2) { + vertexData.uvs2 = this.uvs2.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); + } + if (this.uvs3) { + vertexData.uvs3 = this.uvs3.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); + } + if (this.uvs4) { + vertexData.uvs4 = this.uvs4.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); + } + if (this.uvs5) { + vertexData.uvs5 = this.uvs5.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); + } + if (this.uvs6) { + vertexData.uvs6 = this.uvs6.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); + } + if (this.matricesIndices) { + vertexData.matricesIndices = this.matricesIndices.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); + } + if (this.matricesIndicesExtra) { + vertexData.matricesIndicesExtra = this.matricesIndicesExtra.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); + } + if (this.matricesWeights) { + vertexData.matricesWeights = this.matricesWeights.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); + } + if (this.matricesWeightsExtra) { + vertexData.matricesWeightsExtra = this.matricesWeightsExtra.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); + } + if (this.indices) { + vertexData.indices = []; + for (let index = materialInfo.indexStart; index < materialInfo.indexStart + materialInfo.indexCount; index++) { + vertexData.indices.push(this.indices[index] - materialInfo.verticesStart); + } + } + const newMaterialInfo = new VertexDataMaterialInfo(); + newMaterialInfo.indexStart = 0; + newMaterialInfo.indexCount = vertexData.indices ? vertexData.indices.length : 0; + newMaterialInfo.materialIndex = materialInfo.materialIndex; + newMaterialInfo.verticesStart = 0; + newMaterialInfo.verticesCount = (vertexData.positions ? vertexData.positions.length : 0) / 3; + vertexData.materialInfos = [newMaterialInfo]; + result.push(vertexData); + } + return result; + } + /** + * Merges the passed VertexData into the current one + * @param others the VertexData to be merged into the current one + * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array + * @param forceCloneIndices defines a boolean indicating if indices are forced to be cloned + * @param mergeMaterialIds defines a boolean indicating if we need to merge the material infos + * @param enableCompletion defines a boolean indicating if the vertex data should be completed to be compatible + * @returns the modified VertexData + */ + merge(others, use32BitsIndices = false, forceCloneIndices = false, mergeMaterialIds = false, enableCompletion = false) { + const vertexDatas = Array.isArray(others) + ? others.map((other) => { + return { vertexData: other }; + }) + : [{ vertexData: others }]; + return runCoroutineSync(this._mergeCoroutine(undefined, vertexDatas, use32BitsIndices, false, forceCloneIndices, mergeMaterialIds, enableCompletion)); + } + /** + * @internal + */ + *_mergeCoroutine(transform, vertexDatas, use32BitsIndices = false, isAsync, forceCloneIndices, mergeMaterialIds = false, enableCompletion = false) { + this._validate(); + let others = vertexDatas.map((vertexData) => vertexData.vertexData); + // eslint-disable-next-line @typescript-eslint/no-this-alias + let root = this; + if (enableCompletion) { + // First let's make sure we have the max set of attributes on the main vertex data + for (const other of others) { + if (!other) { + continue; + } + other._validate(); + if (!this.normals && other.normals) { + this.normals = new Float32Array(this.positions.length); + } + if (!this.tangents && other.tangents) { + this.tangents = new Float32Array((this.positions.length / 3) * 4); + } + if (!this.uvs && other.uvs) { + this.uvs = new Float32Array((this.positions.length / 3) * 2); + } + if (!this.uvs2 && other.uvs2) { + this.uvs2 = new Float32Array((this.positions.length / 3) * 2); + } + if (!this.uvs3 && other.uvs3) { + this.uvs3 = new Float32Array((this.positions.length / 3) * 2); + } + if (!this.uvs4 && other.uvs4) { + this.uvs4 = new Float32Array((this.positions.length / 3) * 2); + } + if (!this.uvs5 && other.uvs5) { + this.uvs5 = new Float32Array((this.positions.length / 3) * 2); + } + if (!this.uvs6 && other.uvs6) { + this.uvs6 = new Float32Array((this.positions.length / 3) * 2); + } + if (!this.colors && other.colors) { + this.colors = new Float32Array((this.positions.length / 3) * 4); + this.colors.fill(1); // Set to white by default + } + if (!this.matricesIndices && other.matricesIndices) { + this.matricesIndices = new Float32Array((this.positions.length / 3) * 4); + } + if (!this.matricesWeights && other.matricesWeights) { + this.matricesWeights = new Float32Array((this.positions.length / 3) * 4); + } + if (!this.matricesIndicesExtra && other.matricesIndicesExtra) { + this.matricesIndicesExtra = new Float32Array((this.positions.length / 3) * 4); + } + if (!this.matricesWeightsExtra && other.matricesWeightsExtra) { + this.matricesWeightsExtra = new Float32Array((this.positions.length / 3) * 4); + } + } + } + for (const other of others) { + if (!other) { + continue; + } + if (!enableCompletion) { + other._validate(); + if (!this.normals !== !other.normals || + !this.tangents !== !other.tangents || + !this.uvs !== !other.uvs || + !this.uvs2 !== !other.uvs2 || + !this.uvs3 !== !other.uvs3 || + !this.uvs4 !== !other.uvs4 || + !this.uvs5 !== !other.uvs5 || + !this.uvs6 !== !other.uvs6 || + !this.colors !== !other.colors || + !this.matricesIndices !== !other.matricesIndices || + !this.matricesWeights !== !other.matricesWeights || + !this.matricesIndicesExtra !== !other.matricesIndicesExtra || + !this.matricesWeightsExtra !== !other.matricesWeightsExtra) { + throw new Error("Cannot merge vertex data that do not have the same set of attributes"); + } + } + else { + // Align the others with main set of attributes + if (this.normals && !other.normals) { + other.normals = new Float32Array(other.positions.length); + } + if (this.tangents && !other.tangents) { + other.tangents = new Float32Array((other.positions.length / 3) * 4); + } + if (this.uvs && !other.uvs) { + other.uvs = new Float32Array((other.positions.length / 3) * 2); + } + if (this.uvs2 && !other.uvs2) { + other.uvs2 = new Float32Array((other.positions.length / 3) * 2); + } + if (this.uvs3 && !other.uvs3) { + other.uvs3 = new Float32Array((other.positions.length / 3) * 2); + } + if (this.uvs4 && !other.uvs4) { + other.uvs4 = new Float32Array((other.positions.length / 3) * 2); + } + if (this.uvs5 && !other.uvs5) { + other.uvs5 = new Float32Array((other.positions.length / 3) * 2); + } + if (this.uvs6 && !other.uvs6) { + other.uvs6 = new Float32Array((other.positions.length / 3) * 2); + } + if (this.colors && !other.colors) { + other.colors = new Float32Array((other.positions.length / 3) * 4); + other.colors.fill(1); // Set to white by default + } + if (this.matricesIndices && !other.matricesIndices) { + other.matricesIndices = new Float32Array((other.positions.length / 3) * 4); + } + if (this.matricesWeights && !other.matricesWeights) { + other.matricesWeights = new Float32Array((other.positions.length / 3) * 4); + } + if (this.matricesIndicesExtra && !other.matricesIndicesExtra) { + other.matricesIndicesExtra = new Float32Array((other.positions.length / 3) * 4); + } + if (this.matricesWeightsExtra && !other.matricesWeightsExtra) { + other.matricesWeightsExtra = new Float32Array((other.positions.length / 3) * 4); + } + } + } + if (mergeMaterialIds) { + // Merge material infos + let materialIndex = 0; + let indexOffset = 0; + let vertexOffset = 0; + const materialInfos = []; + let currentMaterialInfo = null; + const vertexDataList = []; + // We need to split vertexData with more than one materialInfo + for (const split of this.splitBasedOnMaterialID()) { + vertexDataList.push({ vertexData: split, transform: transform }); + } + for (const data of vertexDatas) { + if (!data.vertexData) { + continue; + } + for (const split of data.vertexData.splitBasedOnMaterialID()) { + vertexDataList.push({ vertexData: split, transform: data.transform }); + } + } + // Sort by material IDs + vertexDataList.sort((a, b) => { + const matInfoA = a.vertexData.materialInfos ? a.vertexData.materialInfos[0].materialIndex : 0; + const matInfoB = b.vertexData.materialInfos ? b.vertexData.materialInfos[0].materialIndex : 0; + if (matInfoA > matInfoB) { + return 1; + } + if (matInfoA === matInfoB) { + return 0; + } + return -1; + }); + // Build the new material info + for (const vertexDataSource of vertexDataList) { + const vertexData = vertexDataSource.vertexData; + if (vertexData.materialInfos) { + materialIndex = vertexData.materialInfos[0].materialIndex; + } + else { + materialIndex = 0; + } + if (currentMaterialInfo && currentMaterialInfo.materialIndex === materialIndex) { + currentMaterialInfo.indexCount += vertexData.indices.length; + currentMaterialInfo.verticesCount += vertexData.positions.length / 3; + } + else { + const materialInfo = new VertexDataMaterialInfo(); + materialInfo.materialIndex = materialIndex; + materialInfo.indexStart = indexOffset; + materialInfo.indexCount = vertexData.indices.length; + materialInfo.verticesStart = vertexOffset; + materialInfo.verticesCount = vertexData.positions.length / 3; + materialInfos.push(materialInfo); + currentMaterialInfo = materialInfo; + } + indexOffset += vertexData.indices.length; + vertexOffset += vertexData.positions.length / 3; + } + // Extract sorted values + const first = vertexDataList.splice(0, 1)[0]; + root = first.vertexData; + transform = first.transform; + others = vertexDataList.map((v) => v.vertexData); + vertexDatas = vertexDataList; + this.materialInfos = materialInfos; + } + // Merge geometries + const totalIndices = others.reduce((indexSum, vertexData) => indexSum + (vertexData.indices?.length ?? 0), root.indices?.length ?? 0); + const sliceIndices = forceCloneIndices || others.some((vertexData) => vertexData.indices === root.indices); + let indices = sliceIndices ? root.indices?.slice() : root.indices; + if (totalIndices > 0) { + let indicesOffset = indices?.length ?? 0; + if (!indices) { + indices = new Array(totalIndices); + } + if (indices.length !== totalIndices) { + if (Array.isArray(indices)) { + indices.length = totalIndices; + } + else { + const temp = use32BitsIndices || indices instanceof Uint32Array ? new Uint32Array(totalIndices) : new Uint16Array(totalIndices); + temp.set(indices); + indices = temp; + } + if (transform && transform.determinant() < 0) { + VertexData._FlipFaces(indices, 0, indicesOffset); + } + } + let positionsOffset = root.positions ? root.positions.length / 3 : 0; + for (const { vertexData: other, transform } of vertexDatas) { + if (other.indices) { + for (let index = 0; index < other.indices.length; index++) { + indices[indicesOffset + index] = other.indices[index] + positionsOffset; + } + if (transform && transform.determinant() < 0) { + VertexData._FlipFaces(indices, indicesOffset, other.indices.length); + } + // The call to _validate already checked for positions + positionsOffset += other.positions.length / 3; + indicesOffset += other.indices.length; + if (isAsync) { + yield; + } + } + } + } + this.indices = indices; + this.positions = VertexData._MergeElement(VertexBuffer.PositionKind, root.positions, transform, vertexDatas.map((other) => [other.vertexData.positions, other.transform])); + if (isAsync) { + yield; + } + if (root.normals) { + this.normals = VertexData._MergeElement(VertexBuffer.NormalKind, root.normals, transform, vertexDatas.map((other) => [other.vertexData.normals, other.transform])); + if (isAsync) { + yield; + } + } + if (root.tangents) { + this.tangents = VertexData._MergeElement(VertexBuffer.TangentKind, root.tangents, transform, vertexDatas.map((other) => [other.vertexData.tangents, other.transform])); + if (isAsync) { + yield; + } + } + if (root.uvs) { + this.uvs = VertexData._MergeElement(VertexBuffer.UVKind, root.uvs, transform, vertexDatas.map((other) => [other.vertexData.uvs, other.transform])); + if (isAsync) { + yield; + } + } + if (root.uvs2) { + this.uvs2 = VertexData._MergeElement(VertexBuffer.UV2Kind, root.uvs2, transform, vertexDatas.map((other) => [other.vertexData.uvs2, other.transform])); + if (isAsync) { + yield; + } + } + if (root.uvs3) { + this.uvs3 = VertexData._MergeElement(VertexBuffer.UV3Kind, root.uvs3, transform, vertexDatas.map((other) => [other.vertexData.uvs3, other.transform])); + if (isAsync) { + yield; + } + } + if (root.uvs4) { + this.uvs4 = VertexData._MergeElement(VertexBuffer.UV4Kind, root.uvs4, transform, vertexDatas.map((other) => [other.vertexData.uvs4, other.transform])); + if (isAsync) { + yield; + } + } + if (root.uvs5) { + this.uvs5 = VertexData._MergeElement(VertexBuffer.UV5Kind, root.uvs5, transform, vertexDatas.map((other) => [other.vertexData.uvs5, other.transform])); + if (isAsync) { + yield; + } + } + if (root.uvs6) { + this.uvs6 = VertexData._MergeElement(VertexBuffer.UV6Kind, root.uvs6, transform, vertexDatas.map((other) => [other.vertexData.uvs6, other.transform])); + if (isAsync) { + yield; + } + } + if (root.colors) { + this.colors = VertexData._MergeElement(VertexBuffer.ColorKind, root.colors, transform, vertexDatas.map((other) => [other.vertexData.colors, other.transform])); + if (root.hasVertexAlpha !== undefined || vertexDatas.some((other) => other.vertexData.hasVertexAlpha !== undefined)) { + this.hasVertexAlpha = root.hasVertexAlpha || vertexDatas.some((other) => other.vertexData.hasVertexAlpha); + } + if (isAsync) { + yield; + } + } + if (root.matricesIndices) { + this.matricesIndices = VertexData._MergeElement(VertexBuffer.MatricesIndicesKind, root.matricesIndices, transform, vertexDatas.map((other) => [other.vertexData.matricesIndices, other.transform])); + if (isAsync) { + yield; + } + } + if (root.matricesWeights) { + this.matricesWeights = VertexData._MergeElement(VertexBuffer.MatricesWeightsKind, root.matricesWeights, transform, vertexDatas.map((other) => [other.vertexData.matricesWeights, other.transform])); + if (isAsync) { + yield; + } + } + if (root.matricesIndicesExtra) { + this.matricesIndicesExtra = VertexData._MergeElement(VertexBuffer.MatricesIndicesExtraKind, root.matricesIndicesExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesIndicesExtra, other.transform])); + if (isAsync) { + yield; + } + } + if (root.matricesWeightsExtra) { + this.matricesWeightsExtra = VertexData._MergeElement(VertexBuffer.MatricesWeightsExtraKind, root.matricesWeightsExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesWeightsExtra, other.transform])); + } + return this; + } + static _MergeElement(kind, source, transform, others) { + const nonNullOthers = others.filter((other) => other[0] !== null && other[0] !== undefined); + // If there is no source to copy and no other non-null sources then skip this element. + if (!source && nonNullOthers.length == 0) { + return source; + } + if (!source) { + return this._MergeElement(kind, nonNullOthers[0][0], nonNullOthers[0][1], nonNullOthers.slice(1)); + } + const len = nonNullOthers.reduce((sumLen, elements) => sumLen + elements[0].length, source.length); + const transformRange = kind === VertexBuffer.PositionKind + ? VertexData._TransformVector3Coordinates + : kind === VertexBuffer.NormalKind + ? VertexData._TransformVector3Normals + : kind === VertexBuffer.TangentKind + ? VertexData._TransformVector4Normals + : () => { }; + if (source instanceof Float32Array) { + // use non-loop method when the source is Float32Array + const ret32 = new Float32Array(len); + ret32.set(source); + transform && transformRange(ret32, transform, 0, source.length); + let offset = source.length; + for (const [vertexData, transform] of nonNullOthers) { + ret32.set(vertexData, offset); + transform && transformRange(ret32, transform, offset, vertexData.length); + offset += vertexData.length; + } + return ret32; + } + else { + // don't use concat as it is super slow, just loop for other cases + const ret = new Array(len); + for (let i = 0; i < source.length; i++) { + ret[i] = source[i]; + } + transform && transformRange(ret, transform, 0, source.length); + let offset = source.length; + for (const [vertexData, transform] of nonNullOthers) { + for (let i = 0; i < vertexData.length; i++) { + ret[offset + i] = vertexData[i]; + } + transform && transformRange(ret, transform, offset, vertexData.length); + offset += vertexData.length; + } + return ret; + } + } + _validate() { + if (!this.positions) { + throw new RuntimeError("Positions are required", ErrorCodes.MeshInvalidPositionsError); + } + const getElementCount = (kind, values) => { + const stride = VertexBuffer.DeduceStride(kind); + if (values.length % stride !== 0) { + throw new Error("The " + kind + "s array count must be a multiple of " + stride); + } + return values.length / stride; + }; + const positionsElementCount = getElementCount(VertexBuffer.PositionKind, this.positions); + const validateElementCount = (kind, values) => { + const elementCount = getElementCount(kind, values); + if (elementCount !== positionsElementCount) { + throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")"); + } + }; + if (this.normals) { + validateElementCount(VertexBuffer.NormalKind, this.normals); + } + if (this.tangents) { + validateElementCount(VertexBuffer.TangentKind, this.tangents); + } + if (this.uvs) { + validateElementCount(VertexBuffer.UVKind, this.uvs); + } + if (this.uvs2) { + validateElementCount(VertexBuffer.UV2Kind, this.uvs2); + } + if (this.uvs3) { + validateElementCount(VertexBuffer.UV3Kind, this.uvs3); + } + if (this.uvs4) { + validateElementCount(VertexBuffer.UV4Kind, this.uvs4); + } + if (this.uvs5) { + validateElementCount(VertexBuffer.UV5Kind, this.uvs5); + } + if (this.uvs6) { + validateElementCount(VertexBuffer.UV6Kind, this.uvs6); + } + if (this.colors) { + validateElementCount(VertexBuffer.ColorKind, this.colors); + } + if (this.matricesIndices) { + validateElementCount(VertexBuffer.MatricesIndicesKind, this.matricesIndices); + } + if (this.matricesWeights) { + validateElementCount(VertexBuffer.MatricesWeightsKind, this.matricesWeights); + } + if (this.matricesIndicesExtra) { + validateElementCount(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra); + } + if (this.matricesWeightsExtra) { + validateElementCount(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra); + } + } + /** + * Clone the current vertex data + * @returns a copy of the current data + */ + clone() { + const serializationObject = this.serialize(); + return VertexData.Parse(serializationObject); + } + /** + * Serializes the VertexData + * @returns a serialized object + */ + serialize() { + const serializationObject = {}; + if (this.positions) { + serializationObject.positions = Array.from(this.positions); + } + if (this.normals) { + serializationObject.normals = Array.from(this.normals); + } + if (this.tangents) { + serializationObject.tangents = Array.from(this.tangents); + } + if (this.uvs) { + serializationObject.uvs = Array.from(this.uvs); + } + if (this.uvs2) { + serializationObject.uvs2 = Array.from(this.uvs2); + } + if (this.uvs3) { + serializationObject.uvs3 = Array.from(this.uvs3); + } + if (this.uvs4) { + serializationObject.uvs4 = Array.from(this.uvs4); + } + if (this.uvs5) { + serializationObject.uvs5 = Array.from(this.uvs5); + } + if (this.uvs6) { + serializationObject.uvs6 = Array.from(this.uvs6); + } + if (this.colors) { + serializationObject.colors = Array.from(this.colors); + serializationObject.hasVertexAlpha = this.hasVertexAlpha; + } + if (this.matricesIndices) { + serializationObject.matricesIndices = Array.from(this.matricesIndices); + serializationObject.matricesIndices._isExpanded = true; + } + if (this.matricesWeights) { + serializationObject.matricesWeights = Array.from(this.matricesWeights); + } + if (this.matricesIndicesExtra) { + serializationObject.matricesIndicesExtra = Array.from(this.matricesIndicesExtra); + serializationObject.matricesIndicesExtra._isExpanded = true; + } + if (this.matricesWeightsExtra) { + serializationObject.matricesWeightsExtra = Array.from(this.matricesWeightsExtra); + } + serializationObject.indices = this.indices ? Array.from(this.indices) : []; + if (this.materialInfos) { + serializationObject.materialInfos = []; + for (const materialInfo of this.materialInfos) { + const materialInfoSerializationObject = { + indexStart: materialInfo.indexStart, + indexCount: materialInfo.indexCount, + materialIndex: materialInfo.materialIndex, + verticesStart: materialInfo.verticesStart, + verticesCount: materialInfo.verticesCount, + }; + serializationObject.materialInfos.push(materialInfoSerializationObject); + } + } + return serializationObject; + } + // Statics + /** + * Extracts the vertexData from a mesh + * @param mesh the mesh from which to extract the VertexData + * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false + * @param forceCopy indicating that the VertexData must be cloned, optional, default false + * @returns the object VertexData associated to the passed mesh + */ + static ExtractFromMesh(mesh, copyWhenShared, forceCopy) { + return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy); + } + /** + * Extracts the vertexData from the geometry + * @param geometry the geometry from which to extract the VertexData + * @param copyWhenShared defines if the VertexData must be cloned when the geometry is shared between multiple meshes, optional, default false + * @param forceCopy indicating that the VertexData must be cloned, optional, default false + * @returns the object VertexData associated to the passed mesh + */ + static ExtractFromGeometry(geometry, copyWhenShared, forceCopy) { + return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy); + } + static _ExtractFrom(meshOrGeometry, copyWhenShared, forceCopy) { + const result = new VertexData(); + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.PositionKind)) { + result.positions = meshOrGeometry.getVerticesData(VertexBuffer.PositionKind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.NormalKind)) { + result.normals = meshOrGeometry.getVerticesData(VertexBuffer.NormalKind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.TangentKind)) { + result.tangents = meshOrGeometry.getVerticesData(VertexBuffer.TangentKind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UVKind)) { + result.uvs = meshOrGeometry.getVerticesData(VertexBuffer.UVKind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV2Kind)) { + result.uvs2 = meshOrGeometry.getVerticesData(VertexBuffer.UV2Kind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV3Kind)) { + result.uvs3 = meshOrGeometry.getVerticesData(VertexBuffer.UV3Kind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV4Kind)) { + result.uvs4 = meshOrGeometry.getVerticesData(VertexBuffer.UV4Kind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV5Kind)) { + result.uvs5 = meshOrGeometry.getVerticesData(VertexBuffer.UV5Kind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV6Kind)) { + result.uvs6 = meshOrGeometry.getVerticesData(VertexBuffer.UV6Kind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.ColorKind)) { + const geometry = meshOrGeometry.geometry || meshOrGeometry; + const vertexBuffer = geometry.getVertexBuffer(VertexBuffer.ColorKind); + const colors = geometry.getVerticesData(VertexBuffer.ColorKind, copyWhenShared, forceCopy); + if (vertexBuffer.getSize() === 3) { + const newColors = new Float32Array((colors.length * 4) / 3); + for (let i = 0, j = 0; i < colors.length; i += 3, j += 4) { + newColors[j] = colors[i]; + newColors[j + 1] = colors[i + 1]; + newColors[j + 2] = colors[i + 2]; + newColors[j + 3] = 1; + } + result.colors = newColors; + } + else if (vertexBuffer.getSize() === 4) { + result.colors = colors; + } + else { + throw new Error(`Unexpected number of color components: ${vertexBuffer.getSize()}`); + } + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) { + result.matricesIndices = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) { + result.matricesWeights = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesExtraKind)) { + result.matricesIndicesExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy); + } + if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) { + result.matricesWeightsExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy); + } + result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy); + return result; + } + /** + * Creates the VertexData for a Ribbon + * @param options an object used to set the following optional parameters for the ribbon, required but can be empty + * * pathArray array of paths, each of which an array of successive Vector3 + * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false + * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false + * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false + * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional + * * colors a linear array, of length 4 * number of vertices, of custom color values, optional + * @returns the VertexData of the ribbon + * @deprecated use CreateRibbonVertexData instead + */ + static CreateRibbon(options) { + throw _WarnImport("ribbonBuilder"); + } + /** + * Creates the VertexData for a box + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * size sets the width, height and depth of the box to the value of size, optional default 1 + * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size + * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size + * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size + * * faceUV an array of 6 Vector4 elements used to set different images to each box side + * * faceColors an array of 6 Color3 elements used to set different colors to each box side + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box + * @deprecated Please use CreateBoxVertexData from the BoxBuilder file instead + */ + static CreateBox(options) { + throw _WarnImport("boxBuilder"); + } + /** + * Creates the VertexData for a tiled box + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * faceTiles sets the pattern, tile size and number of tiles for a face + * * faceUV an array of 6 Vector4 elements used to set different images to each box side + * * faceColors an array of 6 Color3 elements used to set different colors to each box side + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * @param options.pattern + * @param options.width + * @param options.height + * @param options.depth + * @param options.tileSize + * @param options.tileWidth + * @param options.tileHeight + * @param options.alignHorizontal + * @param options.alignVertical + * @param options.faceUV + * @param options.faceColors + * @param options.sideOrientation + * @returns the VertexData of the box + * @deprecated Please use CreateTiledBoxVertexData instead + */ + static CreateTiledBox(options) { + throw _WarnImport("tiledBoxBuilder"); + } + /** + * Creates the VertexData for a tiled plane + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * pattern a limited pattern arrangement depending on the number + * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1 + * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size + * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the tiled plane + * @deprecated use CreateTiledPlaneVertexData instead + */ + static CreateTiledPlane(options) { + throw _WarnImport("tiledPlaneBuilder"); + } + /** + * Creates the VertexData for an ellipsoid, defaults to a sphere + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * segments sets the number of horizontal strips optional, default 32 + * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1 + * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter + * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter + * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter + * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1 + * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the ellipsoid + * @deprecated use CreateSphereVertexData instead + */ + static CreateSphere(options) { + throw _WarnImport("sphereBuilder"); + } + /** + * Creates the VertexData for a cylinder, cone or prism + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * height sets the height (y direction) of the cylinder, optional, default 2 + * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter + * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter + * * diameter sets the diameter of the top and bottom of the cone, optional default 1 + * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 + * * subdivisions` the number of rings along the cylinder height, optional, default 1 + * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1 + * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * * hasRings when true makes each subdivision independently treated as a face for faceUV and faceColors, optional, default false + * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the cylinder, cone or prism + * @deprecated please use CreateCylinderVertexData instead + */ + static CreateCylinder(options) { + throw _WarnImport("cylinderBuilder"); + } + /** + * Creates the VertexData for a torus + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * diameter the diameter of the torus, optional default 1 + * * thickness the diameter of the tube forming the torus, optional default 0.5 + * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the torus + * @deprecated use CreateTorusVertexData instead + */ + static CreateTorus(options) { + throw _WarnImport("torusBuilder"); + } + /** + * Creates the VertexData of the LineSystem + * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty + * - lines an array of lines, each line being an array of successive Vector3 + * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point + * @returns the VertexData of the LineSystem + * @deprecated use CreateLineSystemVertexData instead + */ + static CreateLineSystem(options) { + throw _WarnImport("linesBuilder"); + } + /** + * Create the VertexData for a DashedLines + * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty + * - points an array successive Vector3 + * - dashSize the size of the dashes relative to the dash number, optional, default 3 + * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1 + * - dashNb the intended total number of dashes, optional, default 200 + * @returns the VertexData for the DashedLines + * @deprecated use CreateDashedLinesVertexData instead + */ + static CreateDashedLines(options) { + throw _WarnImport("linesBuilder"); + } + /** + * Creates the VertexData for a Ground + * @param options an object used to set the following optional parameters for the Ground, required but can be empty + * - width the width (x direction) of the ground, optional, default 1 + * - height the height (z direction) of the ground, optional, default 1 + * - subdivisions the number of subdivisions per side, optional, default 1 + * @returns the VertexData of the Ground + * @deprecated Please use CreateGroundVertexData instead + */ + static CreateGround(options) { + throw _WarnImport("groundBuilder"); + } + /** + * Creates the VertexData for a TiledGround by subdividing the ground into tiles + * @param options an object used to set the following optional parameters for the Ground, required but can be empty + * * xmin the ground minimum X coordinate, optional, default -1 + * * zmin the ground minimum Z coordinate, optional, default -1 + * * xmax the ground maximum X coordinate, optional, default 1 + * * zmax the ground maximum Z coordinate, optional, default 1 + * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6} + * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2} + * @returns the VertexData of the TiledGround + * @deprecated use CreateTiledGroundVertexData instead + */ + static CreateTiledGround(options) { + throw _WarnImport("groundBuilder"); + } + /** + * Creates the VertexData of the Ground designed from a heightmap + * @param options an object used to set the following parameters for the Ground, required and provided by CreateGroundFromHeightMap + * * width the width (x direction) of the ground + * * height the height (z direction) of the ground + * * subdivisions the number of subdivisions per side + * * minHeight the minimum altitude on the ground, optional, default 0 + * * maxHeight the maximum altitude on the ground, optional default 1 + * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11) + * * buffer the array holding the image color data + * * bufferWidth the width of image + * * bufferHeight the height of image + * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible) + * @returns the VertexData of the Ground designed from a heightmap + * @deprecated use CreateGroundFromHeightMapVertexData instead + */ + static CreateGroundFromHeightMap(options) { + throw _WarnImport("groundBuilder"); + } + /** + * Creates the VertexData for a Plane + * @param options an object used to set the following optional parameters for the plane, required but can be empty + * * size sets the width and height of the plane to the value of size, optional default 1 + * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size + * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box + * @deprecated use CreatePlaneVertexData instead + */ + static CreatePlane(options) { + throw _WarnImport("planeBuilder"); + } + /** + * Creates the VertexData of the Disc or regular Polygon + * @param options an object used to set the following optional parameters for the disc, required but can be empty + * * radius the radius of the disc, optional default 0.5 + * * tessellation the number of polygon sides, optional, default 64 + * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box + * @deprecated use CreateDiscVertexData instead + */ + static CreateDisc(options) { + throw _WarnImport("discBuilder"); + } + /** + * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build() + * All parameters are provided by CreatePolygon as needed + * @param polygon a mesh built from polygonTriangulation.build() + * @param sideOrientation takes the values Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @param wrap a boolean, default false, when true and fUVs used texture is wrapped around all sides, when false texture is applied side + * @returns the VertexData of the Polygon + * @deprecated use CreatePolygonVertexData instead + */ + static CreatePolygon(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrap) { + throw _WarnImport("polygonBuilder"); + } + /** + * Creates the VertexData of the IcoSphere + * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty + * * radius the radius of the IcoSphere, optional default 1 + * * radiusX allows stretching in the x direction, optional, default radius + * * radiusY allows stretching in the y direction, optional, default radius + * * radiusZ allows stretching in the z direction, optional, default radius + * * flat when true creates a flat shaded mesh, optional, default true + * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the IcoSphere + * @deprecated use CreateIcoSphereVertexData instead + */ + static CreateIcoSphere(options) { + throw _WarnImport("icoSphereBuilder"); + } + // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html + /** + * Creates the VertexData for a Polyhedron + * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty + * * type provided types are: + * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) + * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20) + * * size the size of the IcoSphere, optional default 1 + * * sizeX allows stretching in the x direction, optional, default size + * * sizeY allows stretching in the y direction, optional, default size + * * sizeZ allows stretching in the z direction, optional, default size + * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor + * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * * flat when true creates a flat shaded mesh, optional, default true + * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the Polyhedron + * @deprecated use CreatePolyhedronVertexData instead + */ + static CreatePolyhedron(options) { + throw _WarnImport("polyhedronBuilder"); + } + /** + * Creates the VertexData for a Capsule, inspired from https://github.com/maximeq/three-js-capsule-geometry/blob/master/src/CapsuleBufferGeometry.js + * @param options an object used to set the following optional parameters for the capsule, required but can be empty + * @returns the VertexData of the Capsule + * @deprecated Please use CreateCapsuleVertexData from the capsuleBuilder file instead + */ + static CreateCapsule(options = { + orientation: Vector3.Up(), + subdivisions: 2, + tessellation: 16, + height: 1, + radius: 0.25, + capSubdivisions: 6, + }) { + throw _WarnImport("capsuleBuilder"); + } + // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473 + /** + * Creates the VertexData for a TorusKnot + * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty + * * radius the radius of the torus knot, optional, default 2 + * * tube the thickness of the tube, optional, default 0.5 + * * radialSegments the number of sides on each tube segments, optional, default 32 + * * tubularSegments the number of tubes to decompose the knot into, optional, default 32 + * * p the number of windings around the z axis, optional, default 2 + * * q the number of windings around the x axis, optional, default 3 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the Torus Knot + * @deprecated use CreateTorusKnotVertexData instead + */ + static CreateTorusKnot(options) { + throw _WarnImport("torusKnotBuilder"); + } + // Tools + /** + * Compute normals for given positions and indices + * @param positions an array of vertex positions, [...., x, y, z, ......] + * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......] + * @param normals an array of vertex normals, [...., x, y, z, ......] + * @param options an object used to set the following optional parameters for the TorusKnot, optional + * * facetNormals : optional array of facet normals (vector3) + * * facetPositions : optional array of facet positions (vector3) + * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation + * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation + * * bInfo : optional bounding info, required for facetPartitioning computation + * * bbSize : optional bounding box size data, required for facetPartitioning computation + * * subDiv : optional partitioning data about subdivisions on each axis (int), required for facetPartitioning computation + * * useRightHandedSystem: optional boolean to for right handed system computation + * * depthSort : optional boolean to enable the facet depth sort computation + * * distanceTo : optional Vector3 to compute the facet depth from this location + * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location + */ + static ComputeNormals(positions, indices, normals, options) { + // temporary scalar variables + let index = 0; // facet index + let p1p2x = 0.0; // p1p2 vector x coordinate + let p1p2y = 0.0; // p1p2 vector y coordinate + let p1p2z = 0.0; // p1p2 vector z coordinate + let p3p2x = 0.0; // p3p2 vector x coordinate + let p3p2y = 0.0; // p3p2 vector y coordinate + let p3p2z = 0.0; // p3p2 vector z coordinate + let faceNormalx = 0.0; // facet normal x coordinate + let faceNormaly = 0.0; // facet normal y coordinate + let faceNormalz = 0.0; // facet normal z coordinate + let length = 0.0; // facet normal length before normalization + let v1x = 0; // vector1 x index in the positions array + let v1y = 0; // vector1 y index in the positions array + let v1z = 0; // vector1 z index in the positions array + let v2x = 0; // vector2 x index in the positions array + let v2y = 0; // vector2 y index in the positions array + let v2z = 0; // vector2 z index in the positions array + let v3x = 0; // vector3 x index in the positions array + let v3y = 0; // vector3 y index in the positions array + let v3z = 0; // vector3 z index in the positions array + let computeFacetNormals = false; + let computeFacetPositions = false; + let computeFacetPartitioning = false; + let computeDepthSort = false; + let faceNormalSign = 1; + let ratio = 0; + let distanceTo = null; + if (options) { + computeFacetNormals = options.facetNormals ? true : false; + computeFacetPositions = options.facetPositions ? true : false; + computeFacetPartitioning = options.facetPartitioning ? true : false; + faceNormalSign = options.useRightHandedSystem === true ? -1 : 1; + ratio = options.ratio || 0; + computeDepthSort = options.depthSort ? true : false; + distanceTo = options.distanceTo; + if (computeDepthSort) { + if (distanceTo === undefined) { + distanceTo = Vector3.Zero(); + } + } + } + // facetPartitioning reinit if needed + let xSubRatio = 0; + let ySubRatio = 0; + let zSubRatio = 0; + let subSq = 0; + if (computeFacetPartitioning && options && options.bbSize) { + //let bbSizeMax = options.bbSize.x > options.bbSize.y ? options.bbSize.x : options.bbSize.y; + //bbSizeMax = bbSizeMax > options.bbSize.z ? bbSizeMax : options.bbSize.z; + xSubRatio = (options.subDiv.X * ratio) / options.bbSize.x; + ySubRatio = (options.subDiv.Y * ratio) / options.bbSize.y; + zSubRatio = (options.subDiv.Z * ratio) / options.bbSize.z; + subSq = options.subDiv.max * options.subDiv.max; + options.facetPartitioning.length = 0; + } + // reset the normals + for (index = 0; index < positions.length; index++) { + normals[index] = 0.0; + } + // Loop : 1 indice triplet = 1 facet + const nbFaces = (indices.length / 3) | 0; + for (index = 0; index < nbFaces; index++) { + // get the indexes of the coordinates of each vertex of the facet + v1x = indices[index * 3] * 3; + v1y = v1x + 1; + v1z = v1x + 2; + v2x = indices[index * 3 + 1] * 3; + v2y = v2x + 1; + v2z = v2x + 2; + v3x = indices[index * 3 + 2] * 3; + v3y = v3x + 1; + v3z = v3x + 2; + p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2 + p1p2y = positions[v1y] - positions[v2y]; + p1p2z = positions[v1z] - positions[v2z]; + p3p2x = positions[v3x] - positions[v2x]; + p3p2y = positions[v3y] - positions[v2y]; + p3p2z = positions[v3z] - positions[v2z]; + // compute the face normal with the cross product + faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y); + faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z); + faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x); + // normalize this normal and store it in the array facetData + length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz); + length = length === 0 ? 1.0 : length; + faceNormalx /= length; + faceNormaly /= length; + faceNormalz /= length; + if (computeFacetNormals && options) { + options.facetNormals[index].x = faceNormalx; + options.facetNormals[index].y = faceNormaly; + options.facetNormals[index].z = faceNormalz; + } + if (computeFacetPositions && options) { + // compute and the facet barycenter coordinates in the array facetPositions + options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0; + options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0; + options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0; + } + if (computeFacetPartitioning && options) { + // store the facet indexes in arrays in the main facetPartitioning array : + // compute each facet vertex (+ facet barycenter) index in the partiniong array + const ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio); + const oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio); + const oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio); + const b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio); + const b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio); + const b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio); + const b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio); + const b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio); + const b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio); + const b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio); + const b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio); + const b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio); + const block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z; + const block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z; + const block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z; + const block_idx_o = ox + options.subDiv.max * oy + subSq * oz; + options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array(); + options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array(); + options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array(); + options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array(); + // push each facet index in each block containing the vertex + options.facetPartitioning[block_idx_v1].push(index); + if (block_idx_v2 != block_idx_v1) { + options.facetPartitioning[block_idx_v2].push(index); + } + if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) { + options.facetPartitioning[block_idx_v3].push(index); + } + if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) { + options.facetPartitioning[block_idx_o].push(index); + } + } + if (computeDepthSort && options && options.facetPositions) { + const dsf = options.depthSortedFacets[index]; + dsf.ind = index * 3; + dsf.sqDistance = Vector3.DistanceSquared(options.facetPositions[index], distanceTo); + } + // compute the normals anyway + normals[v1x] += faceNormalx; // accumulate all the normals per face + normals[v1y] += faceNormaly; + normals[v1z] += faceNormalz; + normals[v2x] += faceNormalx; + normals[v2y] += faceNormaly; + normals[v2z] += faceNormalz; + normals[v3x] += faceNormalx; + normals[v3y] += faceNormaly; + normals[v3z] += faceNormalz; + } + // last normalization of each normal + for (index = 0; index < normals.length / 3; index++) { + faceNormalx = normals[index * 3]; + faceNormaly = normals[index * 3 + 1]; + faceNormalz = normals[index * 3 + 2]; + length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz); + length = length === 0 ? 1.0 : length; + faceNormalx /= length; + faceNormaly /= length; + faceNormalz /= length; + normals[index * 3] = faceNormalx; + normals[index * 3 + 1] = faceNormaly; + normals[index * 3 + 2] = faceNormalz; + } + } + /** + * @internal + */ + static _ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) { + const li = indices.length; + const ln = normals.length; + let i; + let n; + sideOrientation = sideOrientation || VertexData.DEFAULTSIDE; + switch (sideOrientation) { + case VertexData.FRONTSIDE: + // nothing changed + break; + case VertexData.BACKSIDE: + // indices + for (i = 0; i < li; i += 3) { + const tmp = indices[i]; + indices[i] = indices[i + 2]; + indices[i + 2] = tmp; + } + // normals + for (n = 0; n < ln; n++) { + normals[n] = -normals[n]; + } + break; + case VertexData.DOUBLESIDE: { + // positions + const lp = positions.length; + const l = lp / 3; + for (let p = 0; p < lp; p++) { + positions[lp + p] = positions[p]; + } + // indices + for (i = 0; i < li; i += 3) { + indices[i + li] = indices[i + 2] + l; + indices[i + 1 + li] = indices[i + 1] + l; + indices[i + 2 + li] = indices[i] + l; + } + // normals + for (n = 0; n < ln; n++) { + normals[ln + n] = -normals[n]; + } + // uvs + const lu = uvs.length; + let u = 0; + for (u = 0; u < lu; u++) { + uvs[u + lu] = uvs[u]; + } + frontUVs = frontUVs ? frontUVs : new Vector4(0.0, 0.0, 1.0, 1.0); + backUVs = backUVs ? backUVs : new Vector4(0.0, 0.0, 1.0, 1.0); + u = 0; + for (i = 0; i < lu / 2; i++) { + uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u]; + uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1]; + uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu]; + uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1]; + u += 2; + } + break; + } + } + } + /** + * Creates a VertexData from serialized data + * @param parsedVertexData the parsed data from an imported file + * @returns a VertexData + */ + static Parse(parsedVertexData) { + const vertexData = new VertexData(); + // positions + const positions = parsedVertexData.positions; + if (positions) { + vertexData.set(positions, VertexBuffer.PositionKind); + } + // normals + const normals = parsedVertexData.normals; + if (normals) { + vertexData.set(normals, VertexBuffer.NormalKind); + } + // tangents + const tangents = parsedVertexData.tangents; + if (tangents) { + vertexData.set(tangents, VertexBuffer.TangentKind); + } + // uvs + const uvs = parsedVertexData.uvs; + if (uvs) { + vertexData.set(uvs, VertexBuffer.UVKind); + } + // uv2s + const uvs2 = parsedVertexData.uvs2; + if (uvs2) { + vertexData.set(uvs2, VertexBuffer.UV2Kind); + } + // uv3s + const uvs3 = parsedVertexData.uvs3; + if (uvs3) { + vertexData.set(uvs3, VertexBuffer.UV3Kind); + } + // uv4s + const uvs4 = parsedVertexData.uvs4; + if (uvs4) { + vertexData.set(uvs4, VertexBuffer.UV4Kind); + } + // uv5s + const uvs5 = parsedVertexData.uvs5; + if (uvs5) { + vertexData.set(uvs5, VertexBuffer.UV5Kind); + } + // uv6s + const uvs6 = parsedVertexData.uvs6; + if (uvs6) { + vertexData.set(uvs6, VertexBuffer.UV6Kind); + } + // colors + const colors = parsedVertexData.colors; + if (colors) { + vertexData.set(Color4.CheckColors4(colors, positions.length / 3), VertexBuffer.ColorKind); + if (parsedVertexData.hasVertexAlpha !== undefined) { + vertexData.hasVertexAlpha = parsedVertexData.hasVertexAlpha; + } + } + // matricesIndices + const matricesIndices = parsedVertexData.matricesIndices; + if (matricesIndices) { + vertexData.set(matricesIndices, VertexBuffer.MatricesIndicesKind); + } + // matricesWeights + const matricesWeights = parsedVertexData.matricesWeights; + if (matricesWeights) { + vertexData.set(matricesWeights, VertexBuffer.MatricesWeightsKind); + } + // indices + const indices = parsedVertexData.indices; + if (indices) { + vertexData.indices = indices; + } + // MaterialInfos + const materialInfos = parsedVertexData.materialInfos; + if (materialInfos) { + vertexData.materialInfos = []; + for (const materialInfoFromJSON of materialInfos) { + const materialInfo = new VertexDataMaterialInfo(); + materialInfo.indexCount = materialInfoFromJSON.indexCount; + materialInfo.indexStart = materialInfoFromJSON.indexStart; + materialInfo.verticesCount = materialInfoFromJSON.verticesCount; + materialInfo.verticesStart = materialInfoFromJSON.verticesStart; + materialInfo.materialIndex = materialInfoFromJSON.materialIndex; + vertexData.materialInfos.push(materialInfo); + } + } + return vertexData; + } + /** + * Applies VertexData created from the imported parameters to the geometry + * @param parsedVertexData the parsed data from an imported file + * @param geometry the geometry to apply the VertexData to + */ + static ImportVertexData(parsedVertexData, geometry) { + const vertexData = VertexData.Parse(parsedVertexData); + geometry.setAllVerticesData(vertexData, parsedVertexData.updatable); + } +} +/** + * Mesh side orientation : usually the external or front surface + */ +VertexData.FRONTSIDE = 0; +/** + * Mesh side orientation : usually the internal or back surface + */ +VertexData.BACKSIDE = 1; +/** + * Mesh side orientation : both internal and external or front and back surfaces + */ +VertexData.DOUBLESIDE = 2; +/** + * Mesh side orientation : by default, `FRONTSIDE` + */ +VertexData.DEFAULTSIDE = 0; +VertexData._UniqueIDGenerator = 0; +__decorate([ + nativeOverride.filter((...[coordinates]) => !Array.isArray(coordinates)) +], VertexData, "_TransformVector3Coordinates", null); +__decorate([ + nativeOverride.filter((...[normals]) => !Array.isArray(normals)) +], VertexData, "_TransformVector3Normals", null); +__decorate([ + nativeOverride.filter((...[normals]) => !Array.isArray(normals)) +], VertexData, "_TransformVector4Normals", null); +__decorate([ + nativeOverride.filter((...[indices]) => !Array.isArray(indices)) +], VertexData, "_FlipFaces", null); + +/** + * Class used to represent data loading progression + */ +class SceneLoaderFlags { + /** + * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data + */ + static get ForceFullSceneLoadingForIncremental() { + return SceneLoaderFlags._ForceFullSceneLoadingForIncremental; + } + static set ForceFullSceneLoadingForIncremental(value) { + SceneLoaderFlags._ForceFullSceneLoadingForIncremental = value; + } + /** + * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene + */ + static get ShowLoadingScreen() { + return SceneLoaderFlags._ShowLoadingScreen; + } + static set ShowLoadingScreen(value) { + SceneLoaderFlags._ShowLoadingScreen = value; + } + /** + * Defines the current logging level (while loading the scene) + * @ignorenaming + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + static get loggingLevel() { + return SceneLoaderFlags._LoggingLevel; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + static set loggingLevel(value) { + SceneLoaderFlags._LoggingLevel = value; + } + /** + * Gets or set a boolean indicating if matrix weights must be cleaned upon loading + */ + static get CleanBoneMatrixWeights() { + return SceneLoaderFlags._CleanBoneMatrixWeights; + } + static set CleanBoneMatrixWeights(value) { + SceneLoaderFlags._CleanBoneMatrixWeights = value; + } +} +// Flags +SceneLoaderFlags._ForceFullSceneLoadingForIncremental = false; +SceneLoaderFlags._ShowLoadingScreen = true; +SceneLoaderFlags._CleanBoneMatrixWeights = false; +SceneLoaderFlags._LoggingLevel = 0; + +/** + * Class used to store geometry data (vertex buffers + index buffer) + */ +class Geometry { + /** + * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y + */ + get boundingBias() { + return this._boundingBias; + } + /** + * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y + */ + set boundingBias(value) { + if (this._boundingBias) { + this._boundingBias.copyFrom(value); + } + else { + this._boundingBias = value.clone(); + } + this._updateBoundingInfo(true, null); + } + /** + * Static function used to attach a new empty geometry to a mesh + * @param mesh defines the mesh to attach the geometry to + * @returns the new Geometry + */ + static CreateGeometryForMesh(mesh) { + const geometry = new Geometry(Geometry.RandomId(), mesh.getScene()); + geometry.applyToMesh(mesh); + return geometry; + } + /** Get the list of meshes using this geometry */ + get meshes() { + return this._meshes; + } + /** + * Creates a new geometry + * @param id defines the unique ID + * @param scene defines the hosting scene + * @param vertexData defines the VertexData used to get geometry data + * @param updatable defines if geometry must be updatable (false by default) + * @param mesh defines the mesh that will be associated with the geometry + */ + constructor(id, scene, vertexData, updatable = false, mesh = null) { + /** + * Gets the delay loading state of the geometry (none by default which means not delayed) + */ + this.delayLoadState = 0; + this._totalVertices = 0; + this._isDisposed = false; + this._extend = { + minimum: new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE), + maximum: new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE), + }; + this._indexBufferIsUpdatable = false; + this._positionsCache = []; + /** @internal */ + this._parentContainer = null; + /** + * If set to true (false by default), the bounding info applied to the meshes sharing this geometry will be the bounding info defined at the class level + * and won't be computed based on the vertex positions (which is what we get when useBoundingInfoFromGeometry = false) + */ + this.useBoundingInfoFromGeometry = false; + this._scene = scene || EngineStore.LastCreatedScene; + if (!this._scene) { + return; + } + this.id = id; + this.uniqueId = this._scene.getUniqueId(); + this._engine = this._scene.getEngine(); + this._meshes = []; + //Init vertex buffer cache + this._vertexBuffers = {}; + this._indices = []; + this._updatable = updatable; + // vertexData + if (vertexData) { + this.setAllVerticesData(vertexData, updatable); + } + else { + this._totalVertices = 0; + } + if (this._engine.getCaps().vertexArrayObject) { + this._vertexArrayObjects = {}; + } + // applyToMesh + if (mesh) { + this.applyToMesh(mesh); + mesh.computeWorldMatrix(true); + } + } + /** + * Gets the current extend of the geometry + */ + get extend() { + return this._extend; + } + /** + * Gets the hosting scene + * @returns the hosting Scene + */ + getScene() { + return this._scene; + } + /** + * Gets the hosting engine + * @returns the hosting Engine + */ + getEngine() { + return this._engine; + } + /** + * Defines if the geometry is ready to use + * @returns true if the geometry is ready to be used + */ + isReady() { + return this.delayLoadState === 1 || this.delayLoadState === 0; + } + /** + * Gets a value indicating that the geometry should not be serialized + */ + get doNotSerialize() { + for (let index = 0; index < this._meshes.length; index++) { + if (!this._meshes[index].doNotSerialize) { + return false; + } + } + return true; + } + /** @internal */ + _rebuild() { + if (this._vertexArrayObjects) { + this._vertexArrayObjects = {}; + } + // Index buffer + if (this._meshes.length !== 0 && this._indices) { + this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable, "Geometry_" + this.id + "_IndexBuffer"); + } + // Vertex buffers + const buffers = new Set(); + for (const key in this._vertexBuffers) { + buffers.add(this._vertexBuffers[key].getWrapperBuffer()); + } + buffers.forEach((buffer) => { + buffer._rebuild(); + }); + } + /** + * Affects all geometry data in one call + * @param vertexData defines the geometry data + * @param updatable defines if the geometry must be flagged as updatable (false as default) + */ + setAllVerticesData(vertexData, updatable) { + vertexData.applyToGeometry(this, updatable); + this._notifyUpdate(); + } + /** + * Set specific vertex data + * @param kind defines the data kind (Position, normal, etc...) + * @param data defines the vertex data to use + * @param updatable defines if the vertex must be flagged as updatable (false as default) + * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified + */ + setVerticesData(kind, data, updatable = false, stride) { + if (updatable && Array.isArray(data)) { + // to avoid converting to Float32Array at each draw call in engine.updateDynamicVertexBuffer, we make the conversion a single time here + data = new Float32Array(data); + } + const buffer = new VertexBuffer(this._engine, data, kind, { + updatable, + postponeInternalCreation: this._meshes.length === 0, + stride, + label: "Geometry_" + this.id + "_" + kind, + }); + this.setVerticesBuffer(buffer); + } + /** + * Removes a specific vertex data + * @param kind defines the data kind (Position, normal, etc...) + */ + removeVerticesData(kind) { + if (this._vertexBuffers[kind]) { + this._vertexBuffers[kind].dispose(); + delete this._vertexBuffers[kind]; + } + if (this._vertexArrayObjects) { + this._disposeVertexArrayObjects(); + } + } + /** + * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data + * @param buffer defines the vertex buffer to use + * @param totalVertices defines the total number of vertices for position kind (could be null) + * @param disposeExistingBuffer disposes the existing buffer, if any (default: true) + */ + setVerticesBuffer(buffer, totalVertices = null, disposeExistingBuffer = true) { + const kind = buffer.getKind(); + if (this._vertexBuffers[kind] && disposeExistingBuffer) { + this._vertexBuffers[kind].dispose(); + } + if (buffer._buffer) { + buffer._buffer._increaseReferences(); + } + this._vertexBuffers[kind] = buffer; + const meshes = this._meshes; + const numOfMeshes = meshes.length; + if (kind === VertexBuffer.PositionKind) { + this._totalVertices = totalVertices ?? buffer._maxVerticesCount; + this._updateExtend(buffer.getFloatData(this._totalVertices)); + this._resetPointsArrayCache(); + // this._extend can be empty if buffer.getFloatData(this._totalVertices) returned null + const minimum = (this._extend && this._extend.minimum) || new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + const maximum = (this._extend && this._extend.maximum) || new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + for (let index = 0; index < numOfMeshes; index++) { + const mesh = meshes[index]; + mesh.buildBoundingInfo(minimum, maximum); + mesh._createGlobalSubMesh(mesh.isUnIndexed); + mesh.computeWorldMatrix(true); + mesh.synchronizeInstances(); + } + } + this._notifyUpdate(kind); + } + /** + * Update a specific vertex buffer + * This function will directly update the underlying DataBuffer according to the passed numeric array or Float32Array + * It will do nothing if the buffer is not updatable + * @param kind defines the data kind (Position, normal, etc...) + * @param data defines the data to use + * @param offset defines the offset in the target buffer where to store the data + * @param useBytes set to true if the offset is in bytes + */ + updateVerticesDataDirectly(kind, data, offset, useBytes = false) { + const vertexBuffer = this.getVertexBuffer(kind); + if (!vertexBuffer) { + return; + } + vertexBuffer.updateDirectly(data, offset, useBytes); + this._notifyUpdate(kind); + } + /** + * Update a specific vertex buffer + * This function will create a new buffer if the current one is not updatable + * @param kind defines the data kind (Position, normal, etc...) + * @param data defines the data to use + * @param updateExtends defines if the geometry extends must be recomputed (false by default) + */ + updateVerticesData(kind, data, updateExtends = false) { + const vertexBuffer = this.getVertexBuffer(kind); + if (!vertexBuffer) { + return; + } + vertexBuffer.update(data); + if (kind === VertexBuffer.PositionKind) { + this._updateBoundingInfo(updateExtends, data); + } + this._notifyUpdate(kind); + } + _updateBoundingInfo(updateExtends, data) { + if (updateExtends) { + this._updateExtend(data); + } + this._resetPointsArrayCache(); + if (updateExtends) { + const meshes = this._meshes; + for (const mesh of meshes) { + if (mesh.hasBoundingInfo) { + mesh.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum); + } + else { + mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum); + } + const subMeshes = mesh.subMeshes; + for (const subMesh of subMeshes) { + subMesh.refreshBoundingInfo(); + } + } + } + } + /** + * @internal + */ + _bind(effect, indexToBind, overrideVertexBuffers, overrideVertexArrayObjects) { + if (!effect) { + return; + } + if (indexToBind === undefined) { + indexToBind = this._indexBuffer; + } + const vbs = this.getVertexBuffers(); + if (!vbs) { + return; + } + if (indexToBind != this._indexBuffer || (!this._vertexArrayObjects && !overrideVertexArrayObjects)) { + this._engine.bindBuffers(vbs, indexToBind, effect, overrideVertexBuffers); + return; + } + const vaos = overrideVertexArrayObjects ? overrideVertexArrayObjects : this._vertexArrayObjects; + const engine = this._engine; + // Using VAO + if (!vaos[effect.key]) { + vaos[effect.key] = engine.recordVertexArrayObject(vbs, indexToBind, effect, overrideVertexBuffers); + } + engine.bindVertexArrayObject(vaos[effect.key], indexToBind); + } + /** + * Gets total number of vertices + * @returns the total number of vertices + */ + getTotalVertices() { + if (!this.isReady()) { + return 0; + } + return this._totalVertices; + } + /** + * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly. + * @param kind defines the data kind (Position, normal, etc...) + * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes + * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it + * @returns a float array containing vertex data + */ + getVerticesData(kind, copyWhenShared, forceCopy) { + const vertexBuffer = this.getVertexBuffer(kind); + if (!vertexBuffer) { + return null; + } + return vertexBuffer.getFloatData(this._totalVertices, forceCopy || (copyWhenShared && this._meshes.length !== 1)); + } + /** + * Copies the requested vertex data kind into the given vertex data map. Float data is constructed if the map doesn't have the data. + * @param kind defines the data kind (Position, normal, etc...) + * @param vertexData defines the map that stores the resulting data + */ + copyVerticesData(kind, vertexData) { + const vertexBuffer = this.getVertexBuffer(kind); + if (!vertexBuffer) { + return; + } + vertexData[kind] || (vertexData[kind] = new Float32Array(this._totalVertices * vertexBuffer.getSize())); + const data = vertexBuffer.getData(); + if (data) { + CopyFloatData(data, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.normalized, this._totalVertices, vertexData[kind]); + } + } + /** + * Returns a boolean defining if the vertex data for the requested `kind` is updatable + * @param kind defines the data kind (Position, normal, etc...) + * @returns true if the vertex buffer with the specified kind is updatable + */ + isVertexBufferUpdatable(kind) { + const vb = this._vertexBuffers[kind]; + if (!vb) { + return false; + } + return vb.isUpdatable(); + } + /** + * Gets a specific vertex buffer + * @param kind defines the data kind (Position, normal, etc...) + * @returns a VertexBuffer + */ + getVertexBuffer(kind) { + if (!this.isReady()) { + return null; + } + return this._vertexBuffers[kind]; + } + /** + * Returns all vertex buffers + * @returns an object holding all vertex buffers indexed by kind + */ + getVertexBuffers() { + if (!this.isReady()) { + return null; + } + return this._vertexBuffers; + } + /** + * Gets a boolean indicating if specific vertex buffer is present + * @param kind defines the data kind (Position, normal, etc...) + * @returns true if data is present + */ + isVerticesDataPresent(kind) { + if (!this._vertexBuffers) { + if (this._delayInfo) { + return this._delayInfo.indexOf(kind) !== -1; + } + return false; + } + return this._vertexBuffers[kind] !== undefined; + } + /** + * Gets a list of all attached data kinds (Position, normal, etc...) + * @returns a list of string containing all kinds + */ + getVerticesDataKinds() { + const result = []; + let kind; + if (!this._vertexBuffers && this._delayInfo) { + for (kind in this._delayInfo) { + result.push(kind); + } + } + else { + for (kind in this._vertexBuffers) { + result.push(kind); + } + } + return result; + } + /** + * Update index buffer + * @param indices defines the indices to store in the index buffer + * @param offset defines the offset in the target buffer where to store the data + * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default) + */ + updateIndices(indices, offset, gpuMemoryOnly = false) { + if (!this._indexBuffer) { + return; + } + if (!this._indexBufferIsUpdatable) { + this.setIndices(indices, null, true); + } + else { + const needToUpdateSubMeshes = indices.length !== this._indices.length; + if (!gpuMemoryOnly) { + this._indices = indices.slice(); + } + this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset); + if (needToUpdateSubMeshes) { + for (const mesh of this._meshes) { + mesh._createGlobalSubMesh(true); + } + } + } + } + /** + * Sets the index buffer for this geometry. + * @param indexBuffer Defines the index buffer to use for this geometry + * @param totalVertices Defines the total number of vertices used by the buffer + * @param totalIndices Defines the total number of indices in the index buffer + * @param is32Bits Defines if the indices are 32 bits. If null (default), the value is guessed from the number of vertices + */ + setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits = null) { + this._indices = []; + this._indexBufferIsUpdatable = false; + this._indexBuffer = indexBuffer; + this._totalVertices = totalVertices; + this._totalIndices = totalIndices; + if (is32Bits === null) { + indexBuffer.is32Bits = totalVertices > 65535; + } + else { + indexBuffer.is32Bits = is32Bits; + } + for (const mesh of this._meshes) { + mesh._createGlobalSubMesh(true); + mesh.synchronizeInstances(); + } + this._notifyUpdate(); + } + /** + * Creates a new index buffer + * @param indices defines the indices to store in the index buffer + * @param totalVertices defines the total number of vertices (could be null) + * @param updatable defines if the index buffer must be flagged as updatable (false by default) + * @param dontForceSubMeshRecreation defines a boolean indicating that we don't want to force the recreation of sub-meshes if we don't have to (false by default) + */ + setIndices(indices, totalVertices = null, updatable = false, dontForceSubMeshRecreation = false) { + if (this._indexBuffer) { + this._engine._releaseBuffer(this._indexBuffer); + } + this._indices = indices; + this._indexBufferIsUpdatable = updatable; + if (this._meshes.length !== 0 && this._indices) { + this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable, "Geometry_" + this.id + "_IndexBuffer"); + } + if (totalVertices != undefined) { + // including null and undefined + this._totalVertices = totalVertices; + } + for (const mesh of this._meshes) { + mesh._createGlobalSubMesh(!dontForceSubMeshRecreation); + mesh.synchronizeInstances(); + } + this._notifyUpdate(); + } + /** + * Return the total number of indices + * @returns the total number of indices + */ + getTotalIndices() { + if (!this.isReady()) { + return 0; + } + return this._totalIndices !== undefined ? this._totalIndices : this._indices.length; + } + /** + * Gets the index buffer array + * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes + * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it + * @returns the index buffer array + */ + getIndices(copyWhenShared, forceCopy) { + if (!this.isReady()) { + return null; + } + const orig = this._indices; + if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) { + return orig; + } + else { + return orig.slice(); + } + } + /** + * Gets the index buffer + * @returns the index buffer + */ + getIndexBuffer() { + if (!this.isReady()) { + return null; + } + return this._indexBuffer; + } + /** + * @internal + */ + _releaseVertexArrayObject(effect = null) { + if (!effect || !this._vertexArrayObjects) { + return; + } + if (this._vertexArrayObjects[effect.key]) { + this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]); + delete this._vertexArrayObjects[effect.key]; + } + } + /** + * Release the associated resources for a specific mesh + * @param mesh defines the source mesh + * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it + */ + releaseForMesh(mesh, shouldDispose) { + const meshes = this._meshes; + const index = meshes.indexOf(mesh); + if (index === -1) { + return; + } + meshes.splice(index, 1); + if (this._vertexArrayObjects) { + mesh._invalidateInstanceVertexArrayObject(); + } + mesh._geometry = null; + if (meshes.length === 0 && shouldDispose) { + this.dispose(); + } + } + /** + * Apply current geometry to a given mesh + * @param mesh defines the mesh to apply geometry to + */ + applyToMesh(mesh) { + if (mesh._geometry === this) { + return; + } + const previousGeometry = mesh._geometry; + if (previousGeometry) { + previousGeometry.releaseForMesh(mesh); + } + if (this._vertexArrayObjects) { + mesh._invalidateInstanceVertexArrayObject(); + } + const meshes = this._meshes; + // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh() + mesh._geometry = this; + mesh._internalAbstractMeshDataInfo._positions = null; + this._scene.pushGeometry(this); + meshes.push(mesh); + if (this.isReady()) { + this._applyToMesh(mesh); + } + else if (this._boundingInfo) { + mesh.setBoundingInfo(this._boundingInfo); + } + } + _updateExtend(data = null) { + if (this.useBoundingInfoFromGeometry && this._boundingInfo) { + this._extend = { + minimum: this._boundingInfo.minimum.clone(), + maximum: this._boundingInfo.maximum.clone(), + }; + } + else { + if (!data) { + data = this.getVerticesData(VertexBuffer.PositionKind); + // This can happen if the buffer comes from a Hardware Buffer where + // The data have not been uploaded by Babylon. (ex: Compute Shaders and Storage Buffers) + if (!data) { + return; + } + } + this._extend = extractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3); + } + } + _applyToMesh(mesh) { + const numOfMeshes = this._meshes.length; + // vertexBuffers + for (const kind in this._vertexBuffers) { + if (numOfMeshes === 1) { + this._vertexBuffers[kind].create(); + } + if (kind === VertexBuffer.PositionKind) { + if (!this._extend) { + this._updateExtend(); + } + mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum); + mesh._createGlobalSubMesh(mesh.isUnIndexed); + //bounding info was just created again, world matrix should be applied again. + mesh._updateBoundingInfo(); + } + } + // indexBuffer + if (numOfMeshes === 1 && this._indices && this._indices.length > 0) { + this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable, "Geometry_" + this.id + "_IndexBuffer"); + } + // morphTargets + mesh._syncGeometryWithMorphTargetManager(); + // instances + mesh.synchronizeInstances(); + } + _notifyUpdate(kind) { + if (this.onGeometryUpdated) { + this.onGeometryUpdated(this, kind); + } + if (this._vertexArrayObjects) { + this._disposeVertexArrayObjects(); + } + for (const mesh of this._meshes) { + mesh._markSubMeshesAsAttributesDirty(); + } + } + /** + * Load the geometry if it was flagged as delay loaded + * @param scene defines the hosting scene + * @param onLoaded defines a callback called when the geometry is loaded + */ + load(scene, onLoaded) { + if (this.delayLoadState === 2) { + return; + } + if (this.isReady()) { + if (onLoaded) { + onLoaded(); + } + return; + } + this.delayLoadState = 2; + this._queueLoad(scene, onLoaded); + } + _queueLoad(scene, onLoaded) { + if (!this.delayLoadingFile) { + return; + } + scene.addPendingData(this); + scene._loadFile(this.delayLoadingFile, (data) => { + if (!this._delayLoadingFunction) { + return; + } + this._delayLoadingFunction(JSON.parse(data), this); + this.delayLoadState = 1; + this._delayInfo = []; + scene.removePendingData(this); + const meshes = this._meshes; + const numOfMeshes = meshes.length; + for (let index = 0; index < numOfMeshes; index++) { + this._applyToMesh(meshes[index]); + } + if (onLoaded) { + onLoaded(); + } + }, undefined, true); + } + /** + * Invert the geometry to move from a right handed system to a left handed one. + */ + toLeftHanded() { + // Flip faces + const tIndices = this.getIndices(false); + if (tIndices != null && tIndices.length > 0) { + for (let i = 0; i < tIndices.length; i += 3) { + const tTemp = tIndices[i + 0]; + tIndices[i + 0] = tIndices[i + 2]; + tIndices[i + 2] = tTemp; + } + this.setIndices(tIndices); + } + // Negate position.z + const tPositions = this.getVerticesData(VertexBuffer.PositionKind, false); + if (tPositions != null && tPositions.length > 0) { + for (let i = 0; i < tPositions.length; i += 3) { + tPositions[i + 2] = -tPositions[i + 2]; + } + this.setVerticesData(VertexBuffer.PositionKind, tPositions, false); + } + // Negate normal.z + const tNormals = this.getVerticesData(VertexBuffer.NormalKind, false); + if (tNormals != null && tNormals.length > 0) { + for (let i = 0; i < tNormals.length; i += 3) { + tNormals[i + 2] = -tNormals[i + 2]; + } + this.setVerticesData(VertexBuffer.NormalKind, tNormals, false); + } + } + // Cache + /** @internal */ + _resetPointsArrayCache() { + this._positions = null; + } + /** @internal */ + _generatePointsArray() { + if (this._positions) { + return true; + } + const data = this.getVerticesData(VertexBuffer.PositionKind); + if (!data || data.length === 0) { + return false; + } + for (let index = this._positionsCache.length * 3, arrayIdx = this._positionsCache.length; index < data.length; index += 3, ++arrayIdx) { + this._positionsCache[arrayIdx] = Vector3.FromArray(data, index); + } + for (let index = 0, arrayIdx = 0; index < data.length; index += 3, ++arrayIdx) { + this._positionsCache[arrayIdx].set(data[0 + index], data[1 + index], data[2 + index]); + } + // just in case the number of positions was reduced, splice the array + this._positionsCache.length = data.length / 3; + this._positions = this._positionsCache; + return true; + } + /** + * Gets a value indicating if the geometry is disposed + * @returns true if the geometry was disposed + */ + isDisposed() { + return this._isDisposed; + } + _disposeVertexArrayObjects() { + if (this._vertexArrayObjects) { + for (const kind in this._vertexArrayObjects) { + this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]); + } + this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported + const meshes = this._meshes; + const numOfMeshes = meshes.length; + for (let index = 0; index < numOfMeshes; index++) { + meshes[index]._invalidateInstanceVertexArrayObject(); + } + } + } + /** + * Free all associated resources + */ + dispose() { + const meshes = this._meshes; + const numOfMeshes = meshes.length; + let index; + for (index = 0; index < numOfMeshes; index++) { + this.releaseForMesh(meshes[index]); + } + this._meshes.length = 0; + this._disposeVertexArrayObjects(); + for (const kind in this._vertexBuffers) { + this._vertexBuffers[kind].dispose(); + } + this._vertexBuffers = {}; + this._totalVertices = 0; + if (this._indexBuffer) { + this._engine._releaseBuffer(this._indexBuffer); + } + this._indexBuffer = null; + this._indices = []; + this.delayLoadState = 0; + this.delayLoadingFile = null; + this._delayLoadingFunction = null; + this._delayInfo = []; + this._boundingInfo = null; + this._scene.removeGeometry(this); + if (this._parentContainer) { + const index = this._parentContainer.geometries.indexOf(this); + if (index > -1) { + this._parentContainer.geometries.splice(index, 1); + } + this._parentContainer = null; + } + this._isDisposed = true; + } + /** + * Clone the current geometry into a new geometry + * @param id defines the unique ID of the new geometry + * @returns a new geometry object + */ + copy(id) { + const vertexData = new VertexData(); + vertexData.indices = []; + const indices = this.getIndices(); + if (indices) { + for (let index = 0; index < indices.length; index++) { + vertexData.indices.push(indices[index]); + } + } + let updatable = false; + let stopChecking = false; + let kind; + for (kind in this._vertexBuffers) { + const data = this.getVerticesData(kind); + if (data) { + if (data instanceof Float32Array) { + vertexData.set(new Float32Array(data), kind); + } + else { + vertexData.set(data.slice(0), kind); + } + if (!stopChecking) { + const vb = this.getVertexBuffer(kind); + if (vb) { + updatable = vb.isUpdatable(); + stopChecking = !updatable; + } + } + } + } + const geometry = new Geometry(id, this._scene, vertexData, updatable); + geometry.delayLoadState = this.delayLoadState; + geometry.delayLoadingFile = this.delayLoadingFile; + geometry._delayLoadingFunction = this._delayLoadingFunction; + for (kind in this._delayInfo) { + geometry._delayInfo = geometry._delayInfo || []; + geometry._delayInfo.push(kind); + } + // Bounding info + geometry._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum); + return geometry; + } + /** + * Serialize the current geometry info (and not the vertices data) into a JSON object + * @returns a JSON representation of the current geometry data (without the vertices data) + */ + serialize() { + const serializationObject = {}; + serializationObject.id = this.id; + serializationObject.uniqueId = this.uniqueId; + serializationObject.updatable = this._updatable; + if (Tags && Tags.HasTags(this)) { + serializationObject.tags = Tags.GetTags(this); + } + return serializationObject; + } + _toNumberArray(origin) { + if (Array.isArray(origin)) { + return origin; + } + else { + return Array.prototype.slice.call(origin); + } + } + /** + * Release any memory retained by the cached data on the Geometry. + * + * Call this function to reduce memory footprint of the mesh. + * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly) + */ + clearCachedData() { + this._indices = []; + this._resetPointsArrayCache(); + for (const vbName in this._vertexBuffers) { + if (!Object.prototype.hasOwnProperty.call(this._vertexBuffers, vbName)) { + continue; + } + this._vertexBuffers[vbName]._buffer._data = null; + } + } + /** + * Serialize all vertices data into a JSON object + * @returns a JSON representation of the current geometry data + */ + serializeVerticeData() { + const serializationObject = this.serialize(); + if (this.isVerticesDataPresent(VertexBuffer.PositionKind)) { + serializationObject.positions = this._toNumberArray(this.getVerticesData(VertexBuffer.PositionKind)); + if (this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) { + serializationObject.positions._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) { + serializationObject.normals = this._toNumberArray(this.getVerticesData(VertexBuffer.NormalKind)); + if (this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) { + serializationObject.normals._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) { + serializationObject.tangents = this._toNumberArray(this.getVerticesData(VertexBuffer.TangentKind)); + if (this.isVertexBufferUpdatable(VertexBuffer.TangentKind)) { + serializationObject.tangents._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.UVKind)) { + serializationObject.uvs = this._toNumberArray(this.getVerticesData(VertexBuffer.UVKind)); + if (this.isVertexBufferUpdatable(VertexBuffer.UVKind)) { + serializationObject.uvs._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.UV2Kind)) { + serializationObject.uvs2 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind)); + if (this.isVertexBufferUpdatable(VertexBuffer.UV2Kind)) { + serializationObject.uvs2._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.UV3Kind)) { + serializationObject.uvs3 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind)); + if (this.isVertexBufferUpdatable(VertexBuffer.UV3Kind)) { + serializationObject.uvs3._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.UV4Kind)) { + serializationObject.uvs4 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind)); + if (this.isVertexBufferUpdatable(VertexBuffer.UV4Kind)) { + serializationObject.uvs4._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.UV5Kind)) { + serializationObject.uvs5 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind)); + if (this.isVertexBufferUpdatable(VertexBuffer.UV5Kind)) { + serializationObject.uvs5._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.UV6Kind)) { + serializationObject.uvs6 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind)); + if (this.isVertexBufferUpdatable(VertexBuffer.UV6Kind)) { + serializationObject.uvs6._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.ColorKind)) { + serializationObject.colors = this._toNumberArray(this.getVerticesData(VertexBuffer.ColorKind)); + if (this.isVertexBufferUpdatable(VertexBuffer.ColorKind)) { + serializationObject.colors._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) { + serializationObject.matricesIndices = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind)); + serializationObject.matricesIndices._isExpanded = true; + if (this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind)) { + serializationObject.matricesIndices._updatable = true; + } + } + if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) { + serializationObject.matricesWeights = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind)); + if (this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind)) { + serializationObject.matricesWeights._updatable = true; + } + } + serializationObject.indices = this._toNumberArray(this.getIndices()); + return serializationObject; + } + // Statics + /** + * Extracts a clone of a mesh geometry + * @param mesh defines the source mesh + * @param id defines the unique ID of the new geometry object + * @returns the new geometry object + */ + static ExtractFromMesh(mesh, id) { + const geometry = mesh._geometry; + if (!geometry) { + return null; + } + return geometry.copy(id); + } + /** + * You should now use Tools.RandomId(), this method is still here for legacy reasons. + * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 + * Be aware Math.random() could cause collisions, but: + * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" + * @returns a string containing a new GUID + */ + static RandomId() { + return Tools.RandomId(); + } + static _GetGeometryByLoadedUniqueId(uniqueId, scene) { + for (let index = 0; index < scene.geometries.length; index++) { + if (scene.geometries[index]._loadedUniqueId === uniqueId) { + return scene.geometries[index]; + } + } + return null; + } + /** + * @internal + */ + static _ImportGeometry(parsedGeometry, mesh) { + const scene = mesh.getScene(); + // Geometry + const geometryUniqueId = parsedGeometry.geometryUniqueId; + const geometryId = parsedGeometry.geometryId; + if (geometryUniqueId || geometryId) { + const geometry = geometryUniqueId ? this._GetGeometryByLoadedUniqueId(geometryUniqueId, scene) : scene.getGeometryById(geometryId); + if (geometry) { + geometry.applyToMesh(mesh); + } + } + else if (parsedGeometry instanceof ArrayBuffer) { + const binaryInfo = mesh._binaryInfo; + if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) { + const positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count); + mesh.setVerticesData(VertexBuffer.PositionKind, positionsData, false); + } + if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) { + const normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count); + mesh.setVerticesData(VertexBuffer.NormalKind, normalsData, false); + } + if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) { + const tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count); + mesh.setVerticesData(VertexBuffer.TangentKind, tangentsData, false); + } + if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) { + const uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count); + mesh.setVerticesData(VertexBuffer.UVKind, uvsData, false); + } + if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) { + const uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count); + mesh.setVerticesData(VertexBuffer.UV2Kind, uvs2Data, false); + } + if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) { + const uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count); + mesh.setVerticesData(VertexBuffer.UV3Kind, uvs3Data, false); + } + if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) { + const uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count); + mesh.setVerticesData(VertexBuffer.UV4Kind, uvs4Data, false); + } + if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) { + const uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count); + mesh.setVerticesData(VertexBuffer.UV5Kind, uvs5Data, false); + } + if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) { + const uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count); + mesh.setVerticesData(VertexBuffer.UV6Kind, uvs6Data, false); + } + if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) { + const colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count); + mesh.setVerticesData(VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride); + } + if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) { + const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count); + const floatIndices = []; + for (let i = 0; i < matricesIndicesData.length; i++) { + const index = matricesIndicesData[i]; + floatIndices.push(index & 0x000000ff); + floatIndices.push((index & 0x0000ff00) >> 8); + floatIndices.push((index & 0x00ff0000) >> 16); + floatIndices.push((index >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0 + } + mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, false); + } + if (binaryInfo.matricesIndicesExtraAttrDesc && binaryInfo.matricesIndicesExtraAttrDesc.count > 0) { + const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesExtraAttrDesc.offset, binaryInfo.matricesIndicesExtraAttrDesc.count); + const floatIndices = []; + for (let i = 0; i < matricesIndicesData.length; i++) { + const index = matricesIndicesData[i]; + floatIndices.push(index & 0x000000ff); + floatIndices.push((index & 0x0000ff00) >> 8); + floatIndices.push((index & 0x00ff0000) >> 16); + floatIndices.push((index >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0 + } + mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, false); + } + if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) { + const matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count); + mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsData, false); + } + if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) { + const indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count); + mesh.setIndices(indicesData, null); + } + if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) { + const subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5); + mesh.subMeshes = []; + for (let i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) { + const materialIndex = subMeshesData[i * 5 + 0]; + const verticesStart = subMeshesData[i * 5 + 1]; + const verticesCount = subMeshesData[i * 5 + 2]; + const indexStart = subMeshesData[i * 5 + 3]; + const indexCount = subMeshesData[i * 5 + 4]; + SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh); + } + } + } + else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) { + mesh.setVerticesData(VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable); + mesh.setVerticesData(VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable); + if (parsedGeometry.tangents) { + mesh.setVerticesData(VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable); + } + if (parsedGeometry.uvs) { + mesh.setVerticesData(VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable); + } + if (parsedGeometry.uvs2) { + mesh.setVerticesData(VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable); + } + if (parsedGeometry.uvs3) { + mesh.setVerticesData(VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable); + } + if (parsedGeometry.uvs4) { + mesh.setVerticesData(VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable); + } + if (parsedGeometry.uvs5) { + mesh.setVerticesData(VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable); + } + if (parsedGeometry.uvs6) { + mesh.setVerticesData(VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable); + } + if (parsedGeometry.colors) { + mesh.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable); + } + if (parsedGeometry.matricesIndices) { + if (!parsedGeometry.matricesIndices._isExpanded) { + const floatIndices = []; + for (let i = 0; i < parsedGeometry.matricesIndices.length; i++) { + const matricesIndex = parsedGeometry.matricesIndices[i]; + floatIndices.push(matricesIndex & 0x000000ff); + floatIndices.push((matricesIndex & 0x0000ff00) >> 8); + floatIndices.push((matricesIndex & 0x00ff0000) >> 16); + floatIndices.push((matricesIndex >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0 + } + mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable); + } + else { + delete parsedGeometry.matricesIndices._isExpanded; + mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable); + } + } + if (parsedGeometry.matricesIndicesExtra) { + if (!parsedGeometry.matricesIndicesExtra._isExpanded) { + const floatIndices = []; + for (let i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) { + const matricesIndex = parsedGeometry.matricesIndicesExtra[i]; + floatIndices.push(matricesIndex & 0x000000ff); + floatIndices.push((matricesIndex & 0x0000ff00) >> 8); + floatIndices.push((matricesIndex & 0x00ff0000) >> 16); + floatIndices.push((matricesIndex >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0 + } + mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable); + } + else { + delete parsedGeometry.matricesIndices._isExpanded; + mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable); + } + } + if (parsedGeometry.matricesWeights) { + Geometry._CleanMatricesWeights(parsedGeometry, mesh); + mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable); + } + if (parsedGeometry.matricesWeightsExtra) { + mesh.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable); + } + mesh.setIndices(parsedGeometry.indices, null); + } + // SubMeshes + if (parsedGeometry.subMeshes) { + mesh.subMeshes = []; + for (let subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) { + const parsedSubMesh = parsedGeometry.subMeshes[subIndex]; + SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh); + } + } + // Flat shading + if (mesh._shouldGenerateFlatShading) { + mesh.convertToFlatShadedMesh(); + mesh._shouldGenerateFlatShading = false; + } + // Update + mesh.computeWorldMatrix(true); + scene.onMeshImportedObservable.notifyObservers(mesh); + } + static _CleanMatricesWeights(parsedGeometry, mesh) { + const epsilon = 1e-3; + if (!SceneLoaderFlags.CleanBoneMatrixWeights) { + return; + } + let noInfluenceBoneIndex = 0.0; + if (parsedGeometry.skeletonId > -1) { + const skeleton = mesh.getScene().getLastSkeletonById(parsedGeometry.skeletonId); + if (!skeleton) { + return; + } + noInfluenceBoneIndex = skeleton.bones.length; + } + else { + return; + } + const matricesIndices = mesh.getVerticesData(VertexBuffer.MatricesIndicesKind); + const matricesIndicesExtra = mesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind); + const matricesWeights = parsedGeometry.matricesWeights; + const matricesWeightsExtra = parsedGeometry.matricesWeightsExtra; + const influencers = parsedGeometry.numBoneInfluencer; + const size = matricesWeights.length; + for (let i = 0; i < size; i += 4) { + let weight = 0.0; + let firstZeroWeight = -1; + for (let j = 0; j < 4; j++) { + const w = matricesWeights[i + j]; + weight += w; + if (w < epsilon && firstZeroWeight < 0) { + firstZeroWeight = j; + } + } + if (matricesWeightsExtra) { + for (let j = 0; j < 4; j++) { + const w = matricesWeightsExtra[i + j]; + weight += w; + if (w < epsilon && firstZeroWeight < 0) { + firstZeroWeight = j + 4; + } + } + } + if (firstZeroWeight < 0 || firstZeroWeight > influencers - 1) { + firstZeroWeight = influencers - 1; + } + if (weight > epsilon) { + const mweight = 1.0 / weight; + for (let j = 0; j < 4; j++) { + matricesWeights[i + j] *= mweight; + } + if (matricesWeightsExtra) { + for (let j = 0; j < 4; j++) { + matricesWeightsExtra[i + j] *= mweight; + } + } + } + else { + if (firstZeroWeight >= 4) { + matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight; + matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex; + } + else { + matricesWeights[i + firstZeroWeight] = 1.0 - weight; + matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex; + } + } + } + mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, matricesIndices); + if (parsedGeometry.matricesWeightsExtra) { + mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra); + } + } + /** + * Create a new geometry from persisted data (Using .babylon file format) + * @param parsedVertexData defines the persisted data + * @param scene defines the hosting scene + * @param rootUrl defines the root url to use to load assets (like delayed data) + * @returns the new geometry object + */ + static Parse(parsedVertexData, scene, rootUrl) { + const geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable); + geometry._loadedUniqueId = parsedVertexData.uniqueId; + if (Tags) { + Tags.AddTagsTo(geometry, parsedVertexData.tags); + } + if (parsedVertexData.delayLoadingFile) { + geometry.delayLoadState = 4; + geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile; + geometry._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedVertexData.boundingBoxMinimum), Vector3.FromArray(parsedVertexData.boundingBoxMaximum)); + geometry._delayInfo = []; + if (parsedVertexData.hasUVs) { + geometry._delayInfo.push(VertexBuffer.UVKind); + } + if (parsedVertexData.hasUVs2) { + geometry._delayInfo.push(VertexBuffer.UV2Kind); + } + if (parsedVertexData.hasUVs3) { + geometry._delayInfo.push(VertexBuffer.UV3Kind); + } + if (parsedVertexData.hasUVs4) { + geometry._delayInfo.push(VertexBuffer.UV4Kind); + } + if (parsedVertexData.hasUVs5) { + geometry._delayInfo.push(VertexBuffer.UV5Kind); + } + if (parsedVertexData.hasUVs6) { + geometry._delayInfo.push(VertexBuffer.UV6Kind); + } + if (parsedVertexData.hasColors) { + geometry._delayInfo.push(VertexBuffer.ColorKind); + } + if (parsedVertexData.hasMatricesIndices) { + geometry._delayInfo.push(VertexBuffer.MatricesIndicesKind); + } + if (parsedVertexData.hasMatricesWeights) { + geometry._delayInfo.push(VertexBuffer.MatricesWeightsKind); + } + geometry._delayLoadingFunction = VertexData.ImportVertexData; + } + else { + VertexData.ImportVertexData(parsedVertexData, geometry); + } + scene.pushGeometry(geometry, true); + return geometry; + } +} + +const convertRHSToLHS = Matrix.Compose(Vector3.One(), Quaternion.FromEulerAngles(0, Math.PI, 0), Vector3.Zero()); +/** + * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node + */ +class TransformNode extends Node$2 { + /** + * Gets or sets the billboard mode. Default is 0. + * + * | Value | Type | Description | + * | --- | --- | --- | + * | 0 | BILLBOARDMODE_NONE | | + * | 1 | BILLBOARDMODE_X | | + * | 2 | BILLBOARDMODE_Y | | + * | 4 | BILLBOARDMODE_Z | | + * | 7 | BILLBOARDMODE_ALL | | + * + */ + get billboardMode() { + return this._billboardMode; + } + set billboardMode(value) { + if (this._billboardMode === value) { + return; + } + this._billboardMode = value; + this._cache.useBillboardPosition = (this._billboardMode & TransformNode.BILLBOARDMODE_USE_POSITION) !== 0; + this._computeUseBillboardPath(); + } + /** + * Gets or sets a boolean indicating that parent rotation should be preserved when using billboards. + * This could be useful for glTF objects where parent rotation helps converting from right handed to left handed + */ + get preserveParentRotationForBillboard() { + return this._preserveParentRotationForBillboard; + } + set preserveParentRotationForBillboard(value) { + if (value === this._preserveParentRotationForBillboard) { + return; + } + this._preserveParentRotationForBillboard = value; + this._computeUseBillboardPath(); + } + _computeUseBillboardPath() { + this._cache.useBillboardPath = this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard; + } + /** + * Gets or sets the distance of the object to max, often used by skybox + */ + get infiniteDistance() { + return this._infiniteDistance; + } + set infiniteDistance(value) { + if (this._infiniteDistance === value) { + return; + } + this._infiniteDistance = value; + } + constructor(name, scene = null, isPure = true) { + super(name, scene, false); + this._forward = new Vector3(0, 0, 1); + this._up = new Vector3(0, 1, 0); + this._right = new Vector3(1, 0, 0); + // Properties + this._position = Vector3.Zero(); + this._rotation = Vector3.Zero(); + this._rotationQuaternion = null; + this._scaling = Vector3.One(); + this._transformToBoneReferal = null; + this._isAbsoluteSynced = false; + this._billboardMode = TransformNode.BILLBOARDMODE_NONE; + this._preserveParentRotationForBillboard = false; + /** + * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube + */ + this.scalingDeterminant = 1; + this._infiniteDistance = false; + /** + * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored. + * By default the system will update normals to compensate + */ + this.ignoreNonUniformScaling = false; + /** + * Gets or sets a boolean indicating that even if rotationQuaternion is defined, you can keep updating rotation property and Babylon.js will just mix both + */ + this.reIntegrateRotationIntoRotationQuaternion = false; + // Cache + /** @internal */ + this._poseMatrix = null; + /** @internal */ + this._localMatrix = Matrix.Zero(); + this._usePivotMatrix = false; + this._absolutePosition = Vector3.Zero(); + this._absoluteScaling = Vector3.Zero(); + this._absoluteRotationQuaternion = Quaternion.Identity(); + this._pivotMatrix = Matrix.Identity(); + /** @internal */ + this._postMultiplyPivotMatrix = false; + this._isWorldMatrixFrozen = false; + /** @internal */ + this._indexInSceneTransformNodesArray = -1; + /** + * An event triggered after the world matrix is updated + */ + this.onAfterWorldMatrixUpdateObservable = new Observable(); + this._nonUniformScaling = false; + if (isPure) { + this.getScene().addTransformNode(this); + } + } + /** + * Gets a string identifying the name of the class + * @returns "TransformNode" string + */ + getClassName() { + return "TransformNode"; + } + /** + * Gets or set the node position (default is (0.0, 0.0, 0.0)) + */ + get position() { + return this._position; + } + set position(newPosition) { + this._position = newPosition; + this._markAsDirtyInternal(); + } + /** + * return true if a pivot has been set + * @returns true if a pivot matrix is used + */ + isUsingPivotMatrix() { + return this._usePivotMatrix; + } + /** + * @returns true if pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect. + */ + isUsingPostMultiplyPivotMatrix() { + return this._postMultiplyPivotMatrix; + } + /** + * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)). + * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion + */ + get rotation() { + return this._rotation; + } + set rotation(newRotation) { + this._rotation = newRotation; + this._rotationQuaternion = null; + this._markAsDirtyInternal(); + } + /** + * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (1.0, 1.0, 1.0)). + */ + get scaling() { + return this._scaling; + } + set scaling(newScaling) { + this._scaling = newScaling; + this._markAsDirtyInternal(); + } + /** + * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (undefined by default, but can be null). + * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored) + */ + get rotationQuaternion() { + return this._rotationQuaternion; + } + set rotationQuaternion(quaternion) { + this._rotationQuaternion = quaternion; + //reset the rotation vector. + if (quaternion) { + this._rotation.setAll(0.0); + } + this._markAsDirtyInternal(); + } + _markAsDirtyInternal() { + if (this._isDirty) { + return; + } + this._isDirty = true; + if (this.customMarkAsDirty) { + this.customMarkAsDirty(); + } + } + /** + * The forward direction of that transform in world space. + */ + get forward() { + Vector3.TransformNormalFromFloatsToRef(0, 0, this.getScene().useRightHandedSystem ? -1 : 1.0, this.getWorldMatrix(), this._forward); + return this._forward.normalize(); + } + /** + * The up direction of that transform in world space. + */ + get up() { + Vector3.TransformNormalFromFloatsToRef(0, 1, 0, this.getWorldMatrix(), this._up); + return this._up.normalize(); + } + /** + * The right direction of that transform in world space. + */ + get right() { + Vector3.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem ? -1 : 1.0, 0, 0, this.getWorldMatrix(), this._right); + return this._right.normalize(); + } + /** + * Copies the parameter passed Matrix into the mesh Pose matrix. + * @param matrix the matrix to copy the pose from + * @returns this TransformNode. + */ + updatePoseMatrix(matrix) { + if (!this._poseMatrix) { + this._poseMatrix = matrix.clone(); + return this; + } + this._poseMatrix.copyFrom(matrix); + return this; + } + /** + * Returns the mesh Pose matrix. + * @returns the pose matrix + */ + getPoseMatrix() { + if (!this._poseMatrix) { + this._poseMatrix = Matrix.Identity(); + } + return this._poseMatrix; + } + /** @internal */ + _isSynchronized() { + const cache = this._cache; + if (this._billboardMode !== cache.billboardMode || this._billboardMode !== TransformNode.BILLBOARDMODE_NONE) { + return false; + } + if (cache.pivotMatrixUpdated) { + return false; + } + if (this._infiniteDistance) { + return false; + } + if (this._position._isDirty) { + return false; + } + if (this._scaling._isDirty) { + return false; + } + if ((this._rotationQuaternion && this._rotationQuaternion._isDirty) || this._rotation._isDirty) { + return false; + } + return true; + } + /** @internal */ + _initCache() { + super._initCache(); + const cache = this._cache; + cache.localMatrixUpdated = false; + cache.billboardMode = -1; + cache.infiniteDistance = false; + cache.useBillboardPosition = false; + cache.useBillboardPath = false; + } + /** + * Returns the current mesh absolute position. + * Returns a Vector3. + */ + get absolutePosition() { + return this.getAbsolutePosition(); + } + /** + * Returns the current mesh absolute scaling. + * Returns a Vector3. + */ + get absoluteScaling() { + this._syncAbsoluteScalingAndRotation(); + return this._absoluteScaling; + } + /** + * Returns the current mesh absolute rotation. + * Returns a Quaternion. + */ + get absoluteRotationQuaternion() { + this._syncAbsoluteScalingAndRotation(); + return this._absoluteRotationQuaternion; + } + /** + * Sets a new matrix to apply before all other transformation + * @param matrix defines the transform matrix + * @returns the current TransformNode + */ + setPreTransformMatrix(matrix) { + return this.setPivotMatrix(matrix, false); + } + /** + * Sets a new pivot matrix to the current node + * @param matrix defines the new pivot matrix to use + * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect + * @returns the current TransformNode + */ + setPivotMatrix(matrix, postMultiplyPivotMatrix = true) { + this._pivotMatrix.copyFrom(matrix); + this._usePivotMatrix = !this._pivotMatrix.isIdentity(); + this._cache.pivotMatrixUpdated = true; + this._postMultiplyPivotMatrix = postMultiplyPivotMatrix; + if (this._postMultiplyPivotMatrix) { + if (!this._pivotMatrixInverse) { + this._pivotMatrixInverse = Matrix.Invert(this._pivotMatrix); + } + else { + this._pivotMatrix.invertToRef(this._pivotMatrixInverse); + } + } + return this; + } + /** + * Returns the mesh pivot matrix. + * Default : Identity. + * @returns the matrix + */ + getPivotMatrix() { + return this._pivotMatrix; + } + /** + * Instantiate (when possible) or clone that node with its hierarchy + * @param newParent defines the new parent to use for the instance (or clone) + * @param options defines options to configure how copy is done + * @param options.doNotInstantiate defines if the model must be instantiated or just cloned + * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created + * @returns an instance (or a clone) of the current node with its hierarchy + */ + instantiateHierarchy(newParent = null, options, onNewNodeCreated) { + const clone = this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true); + if (clone) { + if (onNewNodeCreated) { + onNewNodeCreated(this, clone); + } + } + for (const child of this.getChildTransformNodes(true)) { + child.instantiateHierarchy(clone, options, onNewNodeCreated); + } + return clone; + } + /** + * Prevents the World matrix to be computed any longer + * @param newWorldMatrix defines an optional matrix to use as world matrix + * @param decompose defines whether to decompose the given newWorldMatrix or directly assign + * @returns the TransformNode. + */ + freezeWorldMatrix(newWorldMatrix = null, decompose = false) { + if (newWorldMatrix) { + if (decompose) { + this._rotation.setAll(0); + this._rotationQuaternion = this._rotationQuaternion || Quaternion.Identity(); + newWorldMatrix.decompose(this._scaling, this._rotationQuaternion, this._position); + this.computeWorldMatrix(true); + } + else { + this._worldMatrix = newWorldMatrix; + this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]); + this._afterComputeWorldMatrix(); + } + } + else { + this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily + this.computeWorldMatrix(true); + } + this._isDirty = false; + this._isWorldMatrixFrozen = true; + return this; + } + /** + * Allows back the World matrix computation. + * @returns the TransformNode. + */ + unfreezeWorldMatrix() { + this._isWorldMatrixFrozen = false; + this.computeWorldMatrix(true); + return this; + } + /** + * True if the World matrix has been frozen. + */ + get isWorldMatrixFrozen() { + return this._isWorldMatrixFrozen; + } + /** + * Returns the mesh absolute position in the World. + * @returns a Vector3. + */ + getAbsolutePosition() { + this.computeWorldMatrix(); + return this._absolutePosition; + } + /** + * Sets the mesh absolute position in the World from a Vector3 or an Array(3). + * @param absolutePosition the absolute position to set + * @returns the TransformNode. + */ + setAbsolutePosition(absolutePosition) { + if (!absolutePosition) { + return this; + } + let absolutePositionX; + let absolutePositionY; + let absolutePositionZ; + if (absolutePosition.x === undefined) { + if (arguments.length < 3) { + return this; + } + absolutePositionX = arguments[0]; + absolutePositionY = arguments[1]; + absolutePositionZ = arguments[2]; + } + else { + absolutePositionX = absolutePosition.x; + absolutePositionY = absolutePosition.y; + absolutePositionZ = absolutePosition.z; + } + if (this.parent) { + const invertParentWorldMatrix = TmpVectors.Matrix[0]; + this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix); + Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position); + } + else { + this.position.x = absolutePositionX; + this.position.y = absolutePositionY; + this.position.z = absolutePositionZ; + } + this._absolutePosition.copyFrom(absolutePosition); + return this; + } + /** + * Sets the mesh position in its local space. + * @param vector3 the position to set in localspace + * @returns the TransformNode. + */ + setPositionWithLocalVector(vector3) { + this.computeWorldMatrix(); + this.position = Vector3.TransformNormal(vector3, this._localMatrix); + return this; + } + /** + * Returns the mesh position in the local space from the current World matrix values. + * @returns a new Vector3. + */ + getPositionExpressedInLocalSpace() { + this.computeWorldMatrix(); + const invLocalWorldMatrix = TmpVectors.Matrix[0]; + this._localMatrix.invertToRef(invLocalWorldMatrix); + return Vector3.TransformNormal(this.position, invLocalWorldMatrix); + } + /** + * Translates the mesh along the passed Vector3 in its local space. + * @param vector3 the distance to translate in localspace + * @returns the TransformNode. + */ + locallyTranslate(vector3) { + this.computeWorldMatrix(true); + this.position = Vector3.TransformCoordinates(vector3, this._localMatrix); + return this; + } + /** + * Orients a mesh towards a target point. Mesh must be drawn facing user. + * @param targetPoint the position (must be in same space as current mesh) to look at + * @param yawCor optional yaw (y-axis) correction in radians + * @param pitchCor optional pitch (x-axis) correction in radians + * @param rollCor optional roll (z-axis) correction in radians + * @param space the chosen space of the target + * @returns the TransformNode. + */ + lookAt(targetPoint, yawCor = 0, pitchCor = 0, rollCor = 0, space = 0 /* Space.LOCAL */) { + const dv = TransformNode._LookAtVectorCache; + const pos = space === 0 /* Space.LOCAL */ ? this.position : this.getAbsolutePosition(); + targetPoint.subtractToRef(pos, dv); + this.setDirection(dv, yawCor, pitchCor, rollCor); + // Correct for parent's rotation offset + if (space === 1 /* Space.WORLD */ && this.parent) { + if (this.rotationQuaternion) { + // Get local rotation matrix of the looking object + const rotationMatrix = TmpVectors.Matrix[0]; + this.rotationQuaternion.toRotationMatrix(rotationMatrix); + // Offset rotation by parent's inverted rotation matrix to correct in world space + const parentRotationMatrix = TmpVectors.Matrix[1]; + this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix); + parentRotationMatrix.invert(); + rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix); + this.rotationQuaternion.fromRotationMatrix(rotationMatrix); + } + else { + // Get local rotation matrix of the looking object + const quaternionRotation = TmpVectors.Quaternion[0]; + Quaternion.FromEulerVectorToRef(this.rotation, quaternionRotation); + const rotationMatrix = TmpVectors.Matrix[0]; + quaternionRotation.toRotationMatrix(rotationMatrix); + // Offset rotation by parent's inverted rotation matrix to correct in world space + const parentRotationMatrix = TmpVectors.Matrix[1]; + this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix); + parentRotationMatrix.invert(); + rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix); + quaternionRotation.fromRotationMatrix(rotationMatrix); + quaternionRotation.toEulerAnglesToRef(this.rotation); + } + } + return this; + } + /** + * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh. + * This Vector3 is expressed in the World space. + * @param localAxis axis to rotate + * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh. + */ + getDirection(localAxis) { + const result = Vector3.Zero(); + this.getDirectionToRef(localAxis, result); + return result; + } + /** + * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh. + * localAxis is expressed in the mesh local space. + * result is computed in the World space from the mesh World matrix. + * @param localAxis axis to rotate + * @param result the resulting transformnode + * @returns this TransformNode. + */ + getDirectionToRef(localAxis, result) { + Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result); + return this; + } + /** + * Sets this transform node rotation to the given local axis. + * @param localAxis the axis in local space + * @param yawCor optional yaw (y-axis) correction in radians + * @param pitchCor optional pitch (x-axis) correction in radians + * @param rollCor optional roll (z-axis) correction in radians + * @returns this TransformNode + */ + setDirection(localAxis, yawCor = 0, pitchCor = 0, rollCor = 0) { + const yaw = -Math.atan2(localAxis.z, localAxis.x) + Math.PI / 2; + const len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z); + const pitch = -Math.atan2(localAxis.y, len); + if (this.rotationQuaternion) { + Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion); + } + else { + this.rotation.x = pitch + pitchCor; + this.rotation.y = yaw + yawCor; + this.rotation.z = rollCor; + } + return this; + } + /** + * Sets a new pivot point to the current node + * @param point defines the new pivot point to use + * @param space defines if the point is in world or local space (local by default) + * @returns the current TransformNode + */ + setPivotPoint(point, space = 0 /* Space.LOCAL */) { + if (this.getScene().getRenderId() == 0) { + this.computeWorldMatrix(true); + } + const wm = this.getWorldMatrix(); + if (space == 1 /* Space.WORLD */) { + const tmat = TmpVectors.Matrix[0]; + wm.invertToRef(tmat); + point = Vector3.TransformCoordinates(point, tmat); + } + return this.setPivotMatrix(Matrix.Translation(-point.x, -point.y, -point.z), true); + } + /** + * Returns a new Vector3 set with the mesh pivot point coordinates in the local space. + * @returns the pivot point + */ + getPivotPoint() { + const point = Vector3.Zero(); + this.getPivotPointToRef(point); + return point; + } + /** + * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space. + * @param result the vector3 to store the result + * @returns this TransformNode. + */ + getPivotPointToRef(result) { + result.x = -this._pivotMatrix.m[12]; + result.y = -this._pivotMatrix.m[13]; + result.z = -this._pivotMatrix.m[14]; + return this; + } + /** + * Returns a new Vector3 set with the mesh pivot point World coordinates. + * @returns a new Vector3 set with the mesh pivot point World coordinates. + */ + getAbsolutePivotPoint() { + const point = Vector3.Zero(); + this.getAbsolutePivotPointToRef(point); + return point; + } + /** + * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates. + * @param result vector3 to store the result + * @returns this TransformNode. + */ + getAbsolutePivotPointToRef(result) { + this.getPivotPointToRef(result); + Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result); + return this; + } + /** + * Flag the transform node as dirty (Forcing it to update everything) + * @param property if set to "rotation" the objects rotationQuaternion will be set to null + * @returns this node + */ + markAsDirty(property) { + if (this._isDirty) { + return this; + } + // We need to explicitly update the children + // as the scene.evaluateActiveMeshes will not poll the transform nodes + if (this._children) { + for (const child of this._children) { + child.markAsDirty(property); + } + } + return super.markAsDirty(property); + } + /** + * Defines the passed node as the parent of the current node. + * The node will remain exactly where it is and its position / rotation will be updated accordingly. + * If you don't want to preserve the current rotation / position, assign the parent through parent accessor. + * Note that if the mesh has a pivot matrix / point defined it will be applied after the parent was updated. + * In that case the node will not remain in the same space as it is, as the pivot will be applied. + * To avoid this, you can set updatePivot to true and the pivot will be updated to identity + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent + * @param node the node ot set as the parent + * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change. + * @param updatePivot if true, update the pivot matrix to keep the node in the same space as before + * @returns this TransformNode. + */ + setParent(node, preserveScalingSign = false, updatePivot = false) { + if (!node && !this.parent) { + return this; + } + const quatRotation = TmpVectors.Quaternion[0]; + const position = TmpVectors.Vector3[0]; + const scale = TmpVectors.Vector3[1]; + const invParentMatrix = TmpVectors.Matrix[1]; + Matrix.IdentityToRef(invParentMatrix); + const composedMatrix = TmpVectors.Matrix[0]; + this.computeWorldMatrix(true); + let currentRotation = this.rotationQuaternion; + if (!currentRotation) { + currentRotation = TransformNode._TmpRotation; + Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, currentRotation); + } + // current global transformation without pivot + Matrix.ComposeToRef(this.scaling, currentRotation, this.position, composedMatrix); + if (this.parent) { + composedMatrix.multiplyToRef(this.parent.computeWorldMatrix(true), composedMatrix); + } + // is a node was set, calculate the difference between this and the node + if (node) { + node.computeWorldMatrix(true).invertToRef(invParentMatrix); + composedMatrix.multiplyToRef(invParentMatrix, composedMatrix); + } + composedMatrix.decompose(scale, quatRotation, position, preserveScalingSign ? this : undefined); + if (this.rotationQuaternion) { + this.rotationQuaternion.copyFrom(quatRotation); + } + else { + quatRotation.toEulerAnglesToRef(this.rotation); + } + this.scaling.copyFrom(scale); + this.position.copyFrom(position); + this.parent = node; + if (updatePivot) { + this.setPivotMatrix(Matrix.Identity()); + } + return this; + } + /** + * Adds the passed mesh as a child to the current mesh. + * The node will remain exactly where it is and its position / rotation will be updated accordingly. + * This method is equivalent to calling setParent(). + * @param mesh defines the child mesh + * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change. + * @returns the current mesh + */ + addChild(mesh, preserveScalingSign = false) { + mesh.setParent(this, preserveScalingSign); + return this; + } + /** + * Removes the passed mesh from the current mesh children list + * @param mesh defines the child mesh + * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change. + * @returns the current mesh + */ + removeChild(mesh, preserveScalingSign = false) { + if (mesh.parent !== this) + return this; + mesh.setParent(null, preserveScalingSign); + return this; + } + /** + * True if the scaling property of this object is non uniform eg. (1,2,1) + */ + get nonUniformScaling() { + return this._nonUniformScaling; + } + /** + * @internal + */ + _updateNonUniformScalingState(value) { + if (this._nonUniformScaling === value) { + return false; + } + this._nonUniformScaling = value; + return true; + } + /** + * Attach the current TransformNode to another TransformNode associated with a bone + * @param bone Bone affecting the TransformNode + * @param affectedTransformNode TransformNode associated with the bone + * @returns this object + */ + attachToBone(bone, affectedTransformNode) { + this._currentParentWhenAttachingToBone = this.parent; + this._transformToBoneReferal = affectedTransformNode; + this.parent = bone; + bone.getSkeleton().prepare(true); // make sure bone.getFinalMatrix() is up to date + if (bone.getFinalMatrix().determinant() < 0) { + this.scalingDeterminant *= -1; + } + return this; + } + /** + * Detach the transform node if its associated with a bone + * @param resetToPreviousParent Indicates if the parent that was in effect when attachToBone was called should be set back or if we should set parent to null instead (defaults to the latter) + * @returns this object + */ + detachFromBone(resetToPreviousParent = false) { + if (!this.parent) { + if (resetToPreviousParent) { + this.parent = this._currentParentWhenAttachingToBone; + } + return this; + } + if (this.parent.getWorldMatrix().determinant() < 0) { + this.scalingDeterminant *= -1; + } + this._transformToBoneReferal = null; + if (resetToPreviousParent) { + this.parent = this._currentParentWhenAttachingToBone; + } + else { + this.parent = null; + } + return this; + } + /** + * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space. + * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD. + * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. + * The passed axis is also normalized. + * @param axis the axis to rotate around + * @param amount the amount to rotate in radians + * @param space Space to rotate in (Default: local) + * @returns the TransformNode. + */ + rotate(axis, amount, space) { + axis.normalize(); + if (!this.rotationQuaternion) { + this.rotationQuaternion = this.rotation.toQuaternion(); + this.rotation.setAll(0); + } + let rotationQuaternion; + if (!space || space === 0 /* Space.LOCAL */) { + rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._RotationAxisCache); + this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion); + } + else { + if (this.parent) { + const parentWorldMatrix = this.parent.getWorldMatrix(); + const invertParentWorldMatrix = TmpVectors.Matrix[0]; + parentWorldMatrix.invertToRef(invertParentWorldMatrix); + axis = Vector3.TransformNormal(axis, invertParentWorldMatrix); + if (parentWorldMatrix.determinant() < 0) { + amount *= -1; + } + } + rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._RotationAxisCache); + rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); + } + return this; + } + /** + * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space. + * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. + * The passed axis is also normalized. . + * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm + * @param point the point to rotate around + * @param axis the axis to rotate around + * @param amount the amount to rotate in radians + * @returns the TransformNode + */ + rotateAround(point, axis, amount) { + axis.normalize(); + if (!this.rotationQuaternion) { + this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z); + this.rotation.setAll(0); + } + const tmpVector = TmpVectors.Vector3[0]; + const finalScale = TmpVectors.Vector3[1]; + const finalTranslation = TmpVectors.Vector3[2]; + const finalRotation = TmpVectors.Quaternion[0]; + const translationMatrix = TmpVectors.Matrix[0]; // T + const translationMatrixInv = TmpVectors.Matrix[1]; // T' + const rotationMatrix = TmpVectors.Matrix[2]; // R + const finalMatrix = TmpVectors.Matrix[3]; // T' x R x T + point.subtractToRef(this.position, tmpVector); + Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T + Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T' + Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R + translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R + finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T + finalMatrix.decompose(finalScale, finalRotation, finalTranslation); + this.position.addInPlace(finalTranslation); + finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); + return this; + } + /** + * Translates the mesh along the axis vector for the passed distance in the given space. + * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD. + * @param axis the axis to translate in + * @param distance the distance to translate + * @param space Space to rotate in (Default: local) + * @returns the TransformNode. + */ + translate(axis, distance, space) { + const displacementVector = axis.scale(distance); + if (!space || space === 0 /* Space.LOCAL */) { + const tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector); + this.setPositionWithLocalVector(tempV3); + } + else { + this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector)); + } + return this; + } + /** + * Adds a rotation step to the mesh current rotation. + * x, y, z are Euler angles expressed in radians. + * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set. + * This means this rotation is made in the mesh local space only. + * It's useful to set a custom rotation order different from the BJS standard one YXZ. + * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis. + * ```javascript + * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3); + * ``` + * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values. + * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles. + * @param x Rotation to add + * @param y Rotation to add + * @param z Rotation to add + * @returns the TransformNode. + */ + addRotation(x, y, z) { + let rotationQuaternion; + if (this.rotationQuaternion) { + rotationQuaternion = this.rotationQuaternion; + } + else { + rotationQuaternion = TmpVectors.Quaternion[1]; + Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion); + } + const accumulation = TmpVectors.Quaternion[0]; + Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation); + rotationQuaternion.multiplyInPlace(accumulation); + if (!this.rotationQuaternion) { + rotationQuaternion.toEulerAnglesToRef(this.rotation); + } + return this; + } + /** + * @internal + */ + _getEffectiveParent() { + return this.parent; + } + /** + * Returns whether the transform node world matrix computation needs the camera information to be computed. + * This is the case when the node is a billboard or has an infinite distance for instance. + * @returns true if the world matrix computation needs the camera information to be computed + */ + isWorldMatrixCameraDependent() { + return (this._infiniteDistance && !this.parent) || (this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard); + } + /** + * Computes the world matrix of the node + * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch + * @param camera defines the camera used if different from the scene active camera (This is used with modes like Billboard or infinite distance) + * @returns the world matrix + */ + computeWorldMatrix(force = false, camera = null) { + if (this._isWorldMatrixFrozen && !this._isDirty) { + return this._worldMatrix; + } + const currentRenderId = this.getScene().getRenderId(); + if (!this._isDirty && !force && (this._currentRenderId === currentRenderId || this.isSynchronized())) { + this._currentRenderId = currentRenderId; + return this._worldMatrix; + } + camera = camera || this.getScene().activeCamera; + this._updateCache(); + const cache = this._cache; + cache.pivotMatrixUpdated = false; + cache.billboardMode = this.billboardMode; + cache.infiniteDistance = this.infiniteDistance; + cache.parent = this._parentNode; + this._currentRenderId = currentRenderId; + this._childUpdateId += 1; + this._isDirty = false; + this._position._isDirty = false; + this._rotation._isDirty = false; + this._scaling._isDirty = false; + const parent = this._getEffectiveParent(); + // Scaling + const scaling = TransformNode._TmpScaling; + let translation = this._position; + // Translation + if (this._infiniteDistance) { + if (!this.parent && camera) { + const cameraWorldMatrix = camera.getWorldMatrix(); + const cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]); + translation = TransformNode._TmpTranslation; + translation.copyFromFloats(this._position.x + cameraGlobalPosition.x, this._position.y + cameraGlobalPosition.y, this._position.z + cameraGlobalPosition.z); + } + } + // Scaling + scaling.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant); + // Rotation + let rotation; + if (this._rotationQuaternion) { + this._rotationQuaternion._isDirty = false; + rotation = this._rotationQuaternion; + if (this.reIntegrateRotationIntoRotationQuaternion) { + const len = this.rotation.lengthSquared(); + if (len) { + this._rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z)); + this._rotation.copyFromFloats(0, 0, 0); + } + } + } + else { + rotation = TransformNode._TmpRotation; + Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, rotation); + } + // Compose + if (this._usePivotMatrix) { + const scaleMatrix = TmpVectors.Matrix[1]; + Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, scaleMatrix); + // Rotation + const rotationMatrix = TmpVectors.Matrix[0]; + rotation.toRotationMatrix(rotationMatrix); + // Composing transformations + this._pivotMatrix.multiplyToRef(scaleMatrix, TmpVectors.Matrix[4]); + TmpVectors.Matrix[4].multiplyToRef(rotationMatrix, this._localMatrix); + // Post multiply inverse of pivotMatrix + if (this._postMultiplyPivotMatrix) { + this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix); + } + this._localMatrix.addTranslationFromFloats(translation.x, translation.y, translation.z); + } + else { + Matrix.ComposeToRef(scaling, rotation, translation, this._localMatrix); + } + // Parent + if (parent && parent.getWorldMatrix) { + if (force) { + parent.computeWorldMatrix(force); + } + if (cache.useBillboardPath) { + if (this._transformToBoneReferal) { + const bone = this.parent; + bone.getSkeleton().prepare(); + bone.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), TmpVectors.Matrix[7]); + } + else { + TmpVectors.Matrix[7].copyFrom(parent.getWorldMatrix()); + } + // Extract scaling and translation from parent + const translation = TmpVectors.Vector3[5]; + const scale = TmpVectors.Vector3[6]; + const orientation = TmpVectors.Quaternion[0]; + TmpVectors.Matrix[7].decompose(scale, orientation, translation); + Matrix.ScalingToRef(scale.x, scale.y, scale.z, TmpVectors.Matrix[7]); + TmpVectors.Matrix[7].setTranslation(translation); + if (TransformNode.BillboardUseParentOrientation) { + // set localMatrix translation to be transformed against parent's orientation. + this._position.applyRotationQuaternionToRef(orientation, translation); + this._localMatrix.setTranslation(translation); + } + this._localMatrix.multiplyToRef(TmpVectors.Matrix[7], this._worldMatrix); + } + else { + if (this._transformToBoneReferal) { + const bone = this.parent; + bone.getSkeleton().prepare(); + this._localMatrix.multiplyToRef(bone.getFinalMatrix(), TmpVectors.Matrix[6]); + TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix); + } + else { + this._localMatrix.multiplyToRef(parent.getWorldMatrix(), this._worldMatrix); + } + } + this._markSyncedWithParent(); + } + else { + this._worldMatrix.copyFrom(this._localMatrix); + } + // Billboarding based on camera orientation (testing PG:http://www.babylonjs-playground.com/#UJEIL#13) + if (cache.useBillboardPath && camera && this.billboardMode && !cache.useBillboardPosition) { + const storedTranslation = TmpVectors.Vector3[0]; + this._worldMatrix.getTranslationToRef(storedTranslation); // Save translation + // Cancel camera rotation + TmpVectors.Matrix[1].copyFrom(camera.getViewMatrix()); + if (this._scene.useRightHandedSystem) { + TmpVectors.Matrix[1].multiplyToRef(convertRHSToLHS, TmpVectors.Matrix[1]); + } + TmpVectors.Matrix[1].setTranslationFromFloats(0, 0, 0); + TmpVectors.Matrix[1].invertToRef(TmpVectors.Matrix[0]); + if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) { + TmpVectors.Matrix[0].decompose(undefined, TmpVectors.Quaternion[0], undefined); + const eulerAngles = TmpVectors.Vector3[1]; + TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles); + if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) { + eulerAngles.x = 0; + } + if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) { + eulerAngles.y = 0; + } + if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) { + eulerAngles.z = 0; + } + Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]); + } + this._worldMatrix.setTranslationFromFloats(0, 0, 0); + this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix); + // Restore translation + this._worldMatrix.setTranslation(TmpVectors.Vector3[0]); + } + // Billboarding based on camera position + else if (cache.useBillboardPath && camera && cache.useBillboardPosition) { + const storedTranslation = TmpVectors.Vector3[0]; + // Save translation + this._worldMatrix.getTranslationToRef(storedTranslation); + // Compute camera position in local space + const cameraPosition = camera.globalPosition; + this._worldMatrix.invertToRef(TmpVectors.Matrix[1]); + const camInObjSpace = TmpVectors.Vector3[1]; + Vector3.TransformCoordinatesToRef(cameraPosition, TmpVectors.Matrix[1], camInObjSpace); + camInObjSpace.normalize(); + // Find the lookAt info in local space + const yaw = -Math.atan2(camInObjSpace.z, camInObjSpace.x) + Math.PI / 2; + const len = Math.sqrt(camInObjSpace.x * camInObjSpace.x + camInObjSpace.z * camInObjSpace.z); + const pitch = -Math.atan2(camInObjSpace.y, len); + Quaternion.RotationYawPitchRollToRef(yaw, pitch, 0, TmpVectors.Quaternion[0]); + if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) { + const eulerAngles = TmpVectors.Vector3[1]; + TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles); + if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) { + eulerAngles.x = 0; + } + if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) { + eulerAngles.y = 0; + } + if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) { + eulerAngles.z = 0; + } + Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]); + } + else { + Matrix.FromQuaternionToRef(TmpVectors.Quaternion[0], TmpVectors.Matrix[0]); + } + // Cancel translation + this._worldMatrix.setTranslationFromFloats(0, 0, 0); + // Rotate according to lookat (diff from local to lookat) + this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix); + // Restore translation + this._worldMatrix.setTranslation(TmpVectors.Vector3[0]); + } + // Normal matrix + if (!this.ignoreNonUniformScaling) { + if (this._scaling.isNonUniformWithinEpsilon(0.000001)) { + this._updateNonUniformScalingState(true); + } + else if (parent && parent._nonUniformScaling) { + this._updateNonUniformScalingState(parent._nonUniformScaling); + } + else { + this._updateNonUniformScalingState(false); + } + } + else { + this._updateNonUniformScalingState(false); + } + this._afterComputeWorldMatrix(); + // Absolute position + this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]); + this._isAbsoluteSynced = false; + // Callbacks + this.onAfterWorldMatrixUpdateObservable.notifyObservers(this); + if (!this._poseMatrix) { + this._poseMatrix = Matrix.Invert(this._worldMatrix); + } + // Cache the determinant + this._worldMatrixDeterminantIsDirty = true; + return this._worldMatrix; + } + /** + * Resets this nodeTransform's local matrix to Matrix.Identity(). + * @param independentOfChildren indicates if all child nodeTransform's world-space transform should be preserved. + */ + resetLocalMatrix(independentOfChildren = true) { + this.computeWorldMatrix(); + if (independentOfChildren) { + const children = this.getChildren(); + for (let i = 0; i < children.length; ++i) { + const child = children[i]; + if (child) { + child.computeWorldMatrix(); + const bakedMatrix = TmpVectors.Matrix[0]; + child._localMatrix.multiplyToRef(this._localMatrix, bakedMatrix); + const tmpRotationQuaternion = TmpVectors.Quaternion[0]; + bakedMatrix.decompose(child.scaling, tmpRotationQuaternion, child.position); + if (child.rotationQuaternion) { + child.rotationQuaternion.copyFrom(tmpRotationQuaternion); + } + else { + tmpRotationQuaternion.toEulerAnglesToRef(child.rotation); + } + } + } + } + this.scaling.copyFromFloats(1, 1, 1); + this.position.copyFromFloats(0, 0, 0); + this.rotation.copyFromFloats(0, 0, 0); + //only if quaternion is already set + if (this.rotationQuaternion) { + this.rotationQuaternion = Quaternion.Identity(); + } + this._worldMatrix = Matrix.Identity(); + } + _afterComputeWorldMatrix() { } + /** + * If you'd like to be called back after the mesh position, rotation or scaling has been updated. + * @param func callback function to add + * + * @returns the TransformNode. + */ + registerAfterWorldMatrixUpdate(func) { + this.onAfterWorldMatrixUpdateObservable.add(func); + return this; + } + /** + * Removes a registered callback function. + * @param func callback function to remove + * @returns the TransformNode. + */ + unregisterAfterWorldMatrixUpdate(func) { + this.onAfterWorldMatrixUpdateObservable.removeCallback(func); + return this; + } + /** + * Gets the position of the current mesh in camera space + * @param camera defines the camera to use + * @returns a position + */ + getPositionInCameraSpace(camera = null) { + if (!camera) { + camera = this.getScene().activeCamera; + } + return Vector3.TransformCoordinates(this.getAbsolutePosition(), camera.getViewMatrix()); + } + /** + * Returns the distance from the mesh to the active camera + * @param camera defines the camera to use + * @returns the distance + */ + getDistanceToCamera(camera = null) { + if (!camera) { + camera = this.getScene().activeCamera; + } + return this.getAbsolutePosition().subtract(camera.globalPosition).length(); + } + /** + * Clone the current transform node + * @param name Name of the new clone + * @param newParent New parent for the clone + * @param doNotCloneChildren Do not clone children hierarchy + * @returns the new transform node + */ + clone(name, newParent, doNotCloneChildren) { + const result = SerializationHelper.Clone(() => new TransformNode(name, this.getScene()), this); + result.name = name; + result.id = name; + if (newParent) { + result.parent = newParent; + } + if (!doNotCloneChildren) { + // Children + const directDescendants = this.getDescendants(true); + for (let index = 0; index < directDescendants.length; index++) { + const child = directDescendants[index]; + if (child.clone) { + child.clone(name + "." + child.name, result); + } + } + } + return result; + } + /** + * Serializes the objects information. + * @param currentSerializationObject defines the object to serialize in + * @returns the serialized object + */ + serialize(currentSerializationObject) { + const serializationObject = SerializationHelper.Serialize(this, currentSerializationObject); + serializationObject.type = this.getClassName(); + serializationObject.uniqueId = this.uniqueId; + // Parent + if (this.parent) { + this.parent._serializeAsParent(serializationObject); + } + serializationObject.localMatrix = this.getPivotMatrix().asArray(); + serializationObject.isEnabled = this.isEnabled(); + // Animations + SerializationHelper.AppendSerializedAnimations(this, serializationObject); + serializationObject.ranges = this.serializeAnimationRanges(); + return serializationObject; + } + // Statics + /** + * Returns a new TransformNode object parsed from the source provided. + * @param parsedTransformNode is the source. + * @param scene the scene the object belongs to + * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with + * @returns a new TransformNode object parsed from the source provided. + */ + static Parse(parsedTransformNode, scene, rootUrl) { + const transformNode = SerializationHelper.Parse(() => new TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl); + if (parsedTransformNode.localMatrix) { + transformNode.setPreTransformMatrix(Matrix.FromArray(parsedTransformNode.localMatrix)); + } + else if (parsedTransformNode.pivotMatrix) { + transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.pivotMatrix)); + } + transformNode.setEnabled(parsedTransformNode.isEnabled); + transformNode._waitingParsedUniqueId = parsedTransformNode.uniqueId; + // Parent + if (parsedTransformNode.parentId !== undefined) { + transformNode._waitingParentId = parsedTransformNode.parentId; + } + if (parsedTransformNode.parentInstanceIndex !== undefined) { + transformNode._waitingParentInstanceIndex = parsedTransformNode.parentInstanceIndex; + } + // Animations + if (parsedTransformNode.animations) { + for (let animationIndex = 0; animationIndex < parsedTransformNode.animations.length; animationIndex++) { + const parsedAnimation = parsedTransformNode.animations[animationIndex]; + const internalClass = GetClass("BABYLON.Animation"); + if (internalClass) { + transformNode.animations.push(internalClass.Parse(parsedAnimation)); + } + } + Node$2.ParseAnimationRanges(transformNode, parsedTransformNode, scene); + } + if (parsedTransformNode.autoAnimate) { + scene.beginAnimation(transformNode, parsedTransformNode.autoAnimateFrom, parsedTransformNode.autoAnimateTo, parsedTransformNode.autoAnimateLoop, parsedTransformNode.autoAnimateSpeed || 1.0); + } + return transformNode; + } + /** + * Get all child-transformNodes of this node + * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered + * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored + * @returns an array of TransformNode + */ + getChildTransformNodes(directDescendantsOnly, predicate) { + const results = []; + this._getDescendants(results, directDescendantsOnly, (node) => { + return (!predicate || predicate(node)) && node instanceof TransformNode; + }); + return results; + } + /** + * Releases resources associated with this transform node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse, disposeMaterialAndTextures = false) { + // Animations + this.getScene().stopAnimation(this); + // Remove from scene + this.getScene().removeTransformNode(this); + if (this._parentContainer) { + const index = this._parentContainer.transformNodes.indexOf(this); + if (index > -1) { + this._parentContainer.transformNodes.splice(index, 1); + } + this._parentContainer = null; + } + this.onAfterWorldMatrixUpdateObservable.clear(); + if (doNotRecurse) { + const transformNodes = this.getChildTransformNodes(true); + for (const transformNode of transformNodes) { + transformNode.parent = null; + transformNode.computeWorldMatrix(true); + } + } + super.dispose(doNotRecurse, disposeMaterialAndTextures); + } + /** + * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) + * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false + * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false + * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling + * @returns the current mesh + */ + normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) { + let storedRotation = null; + let storedRotationQuaternion = null; + if (ignoreRotation) { + if (this.rotationQuaternion) { + storedRotationQuaternion = this.rotationQuaternion.clone(); + this.rotationQuaternion.copyFromFloats(0, 0, 0, 1); + } + else if (this.rotation) { + storedRotation = this.rotation.clone(); + this.rotation.copyFromFloats(0, 0, 0); + } + } + const boundingVectors = this.getHierarchyBoundingVectors(includeDescendants, predicate); + const sizeVec = boundingVectors.max.subtract(boundingVectors.min); + const maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z); + if (maxDimension === 0) { + return this; + } + const scale = 1 / maxDimension; + this.scaling.scaleInPlace(scale); + if (ignoreRotation) { + if (this.rotationQuaternion && storedRotationQuaternion) { + this.rotationQuaternion.copyFrom(storedRotationQuaternion); + } + else if (this.rotation && storedRotation) { + this.rotation.copyFrom(storedRotation); + } + } + return this; + } + _syncAbsoluteScalingAndRotation() { + if (!this._isAbsoluteSynced) { + this._worldMatrix.decompose(this._absoluteScaling, this._absoluteRotationQuaternion); + this._isAbsoluteSynced = true; + } + } +} +// Statics +/** + * Object will not rotate to face the camera + */ +TransformNode.BILLBOARDMODE_NONE = 0; +/** + * Object will rotate to face the camera but only on the x axis + */ +TransformNode.BILLBOARDMODE_X = 1; +/** + * Object will rotate to face the camera but only on the y axis + */ +TransformNode.BILLBOARDMODE_Y = 2; +/** + * Object will rotate to face the camera but only on the z axis + */ +TransformNode.BILLBOARDMODE_Z = 4; +/** + * Object will rotate to face the camera + */ +TransformNode.BILLBOARDMODE_ALL = 7; +/** + * Object will rotate to face the camera's position instead of orientation + */ +TransformNode.BILLBOARDMODE_USE_POSITION = 128; +/** + * Child transform with Billboard flags should or should not apply parent rotation (default if off) + */ +TransformNode.BillboardUseParentOrientation = false; +TransformNode._TmpRotation = Quaternion.Zero(); +TransformNode._TmpScaling = Vector3.Zero(); +TransformNode._TmpTranslation = Vector3.Zero(); +TransformNode._LookAtVectorCache = new Vector3(0, 0, 0); +TransformNode._RotationAxisCache = new Quaternion(); +__decorate([ + serializeAsVector3("position") +], TransformNode.prototype, "_position", void 0); +__decorate([ + serializeAsVector3("rotation") +], TransformNode.prototype, "_rotation", void 0); +__decorate([ + serializeAsQuaternion("rotationQuaternion") +], TransformNode.prototype, "_rotationQuaternion", void 0); +__decorate([ + serializeAsVector3("scaling") +], TransformNode.prototype, "_scaling", void 0); +__decorate([ + serialize("billboardMode") +], TransformNode.prototype, "_billboardMode", void 0); +__decorate([ + serialize() +], TransformNode.prototype, "scalingDeterminant", void 0); +__decorate([ + serialize("infiniteDistance") +], TransformNode.prototype, "_infiniteDistance", void 0); +__decorate([ + serialize() +], TransformNode.prototype, "ignoreNonUniformScaling", void 0); +__decorate([ + serialize() +], TransformNode.prototype, "reIntegrateRotationIntoRotationQuaternion", void 0); + +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _MeshCollisionData { + constructor() { + this._checkCollisions = false; + this._collisionMask = -1; + this._collisionGroup = -1; + this._surroundingMeshes = null; + this._collider = null; + this._oldPositionForCollisions = new Vector3(0, 0, 0); + this._diffPositionForCollisions = new Vector3(0, 0, 0); + this._collisionResponse = true; + } +} + +function applyMorph(data, kind, morphTargetManager) { + let getTargetData = null; + switch (kind) { + case VertexBuffer.PositionKind: + getTargetData = (target) => target.getPositions(); + break; + case VertexBuffer.NormalKind: + getTargetData = (target) => target.getNormals(); + break; + case VertexBuffer.TangentKind: + getTargetData = (target) => target.getTangents(); + break; + case VertexBuffer.UVKind: + getTargetData = (target) => target.getUVs(); + break; + case VertexBuffer.UV2Kind: + getTargetData = (target) => target.getUV2s(); + break; + case VertexBuffer.ColorKind: + getTargetData = (target) => target.getColors(); + break; + default: + return; + } + for (let index = 0; index < data.length; index++) { + let value = data[index]; + for (let targetCount = 0; targetCount < morphTargetManager.numTargets; targetCount++) { + const target = morphTargetManager.getTarget(targetCount); + const influence = target.influence; + if (influence !== 0) { + const targetData = getTargetData(target); + if (targetData) { + value += (targetData[index] - data[index]) * influence; + } + } + } + data[index] = value; + } +} +function applySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData) { + const tempVector = TmpVectors.Vector3[0]; + const finalMatrix = TmpVectors.Matrix[0]; + const tempMatrix = TmpVectors.Matrix[1]; + const transformFromFloatsToRef = kind === VertexBuffer.NormalKind ? Vector3.TransformNormalFromFloatsToRef : Vector3.TransformCoordinatesFromFloatsToRef; + for (let index = 0, matWeightIdx = 0; index < data.length; index += 3, matWeightIdx += 4) { + finalMatrix.reset(); + let inf; + let weight; + for (inf = 0; inf < 4; inf++) { + weight = matricesWeightsData[matWeightIdx + inf]; + if (weight > 0) { + Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix); + finalMatrix.addToSelf(tempMatrix); + } + } + if (matricesIndicesExtraData && matricesWeightsExtraData) { + for (inf = 0; inf < 4; inf++) { + weight = matricesWeightsExtraData[matWeightIdx + inf]; + if (weight > 0) { + Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix); + finalMatrix.addToSelf(tempMatrix); + } + } + } + transformFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector); + tempVector.toArray(data, index); + } +} +/** @internal */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _FacetDataStorage { + constructor() { + this.facetNb = 0; // facet number + this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partitioning space + this.partitioningBBoxRatio = 1.01; // the partitioning array space is by default 1% bigger than the bounding box + this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ? + this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation + this.bbSize = Vector3.Zero(); // bbox size approximated for facet data + this.subDiv = { + // actual number of subdivisions per axis for ComputeNormals() + max: 1, + // eslint-disable-next-line @typescript-eslint/naming-convention + X: 1, + // eslint-disable-next-line @typescript-eslint/naming-convention + Y: 1, + // eslint-disable-next-line @typescript-eslint/naming-convention + Z: 1, + }; + this.facetDepthSort = false; // is the facet depth sort to be computed + this.facetDepthSortEnabled = false; // is the facet depth sort initialized + } +} +/** + * @internal + **/ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _InternalAbstractMeshDataInfo { + constructor() { + this._hasVertexAlpha = false; + this._useVertexColors = true; + this._numBoneInfluencers = 4; + this._applyFog = true; + this._receiveShadows = false; + this._facetData = new _FacetDataStorage(); + this._visibility = 1.0; + this._skeleton = null; + this._layerMask = 0x0fffffff; + this._computeBonesUsingShaders = true; + this._isActive = false; + this._onlyForInstances = false; + this._isActiveIntermediate = false; + this._onlyForInstancesIntermediate = false; + this._actAsRegularMesh = false; + this._currentLOD = new Map(); + this._collisionRetryCount = 3; + this._morphTargetManager = null; + this._renderingGroupId = 0; + this._bakedVertexAnimationManager = null; + this._material = null; + this._positions = null; + this._pointerOverDisableMeshTesting = false; + // Collisions + this._meshCollisionData = new _MeshCollisionData(); + this._enableDistantPicking = false; + /** @internal + * Bounding info that is unnafected by the addition of thin instances + */ + this._rawBoundingInfo = null; + /** @internal + * This value will indicate us that at some point, the mesh was specifically used with the opposite winding order + * We use that as a clue to force the material to sideOrientation = null + */ + this._sideOrientationHint = false; + /** + * @internal + * if this is set to true, the mesh will be visible only if its parent(s) are also visible + */ + this._inheritVisibility = false; + } +} +/** + * Class used to store all common mesh properties + */ +class AbstractMesh extends TransformNode { + /** + * No billboard + */ + static get BILLBOARDMODE_NONE() { + return TransformNode.BILLBOARDMODE_NONE; + } + /** Billboard on X axis */ + static get BILLBOARDMODE_X() { + return TransformNode.BILLBOARDMODE_X; + } + /** Billboard on Y axis */ + static get BILLBOARDMODE_Y() { + return TransformNode.BILLBOARDMODE_Y; + } + /** Billboard on Z axis */ + static get BILLBOARDMODE_Z() { + return TransformNode.BILLBOARDMODE_Z; + } + /** Billboard on all axes */ + static get BILLBOARDMODE_ALL() { + return TransformNode.BILLBOARDMODE_ALL; + } + /** Billboard on using position instead of orientation */ + static get BILLBOARDMODE_USE_POSITION() { + return TransformNode.BILLBOARDMODE_USE_POSITION; + } + /** + * Gets the number of facets in the mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet + */ + get facetNb() { + return this._internalAbstractMeshDataInfo._facetData.facetNb; + } + /** + * Gets or set the number (integer) of subdivisions per axis in the partitioning space + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning + */ + get partitioningSubdivisions() { + return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions; + } + set partitioningSubdivisions(nb) { + this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions = nb; + } + /** + * The ratio (float) to apply to the bounding box size to set to the partitioning space. + * Ex : 1.01 (default) the partitioning space is 1% bigger than the bounding box + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning + */ + get partitioningBBoxRatio() { + return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio; + } + set partitioningBBoxRatio(ratio) { + this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio = ratio; + } + /** + * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`. + * Works only for updatable meshes. + * Doesn't work with multi-materials + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort + */ + get mustDepthSortFacets() { + return this._internalAbstractMeshDataInfo._facetData.facetDepthSort; + } + set mustDepthSortFacets(sort) { + this._internalAbstractMeshDataInfo._facetData.facetDepthSort = sort; + } + /** + * The location (Vector3) where the facet depth sort must be computed from. + * By default, the active camera position. + * Used only when facet depth sort is enabled + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort + */ + get facetDepthSortFrom() { + return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom; + } + set facetDepthSortFrom(location) { + this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom = location; + } + /** number of collision detection tries. Change this value if not all collisions are detected and handled properly */ + get collisionRetryCount() { + return this._internalAbstractMeshDataInfo._collisionRetryCount; + } + set collisionRetryCount(retryCount) { + this._internalAbstractMeshDataInfo._collisionRetryCount = retryCount; + } + /** + * gets a boolean indicating if facetData is enabled + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet + */ + get isFacetDataEnabled() { + return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled; + } + /** + * Gets or sets the morph target manager + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets + */ + get morphTargetManager() { + return this._internalAbstractMeshDataInfo._morphTargetManager; + } + set morphTargetManager(value) { + if (this._internalAbstractMeshDataInfo._morphTargetManager === value) { + return; + } + this._internalAbstractMeshDataInfo._morphTargetManager = value; + this._syncGeometryWithMorphTargetManager(); + } + /** + * Gets or sets the baked vertex animation manager + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/baked_texture_animations + */ + get bakedVertexAnimationManager() { + return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager; + } + set bakedVertexAnimationManager(value) { + if (this._internalAbstractMeshDataInfo._bakedVertexAnimationManager === value) { + return; + } + this._internalAbstractMeshDataInfo._bakedVertexAnimationManager = value; + this._markSubMeshesAsAttributesDirty(); + } + /** @internal */ + _syncGeometryWithMorphTargetManager() { } + /** + * @internal + */ + _updateNonUniformScalingState(value) { + if (!super._updateNonUniformScalingState(value)) { + return false; + } + this._markSubMeshesAsMiscDirty(); + return true; + } + /** @internal */ + get rawBoundingInfo() { + return this._internalAbstractMeshDataInfo._rawBoundingInfo; + } + set rawBoundingInfo(boundingInfo) { + this._internalAbstractMeshDataInfo._rawBoundingInfo = boundingInfo; + } + /** Set a function to call when this mesh collides with another one */ + set onCollide(callback) { + if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver) { + this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver); + } + this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver = this.onCollideObservable.add(callback); + } + /** Set a function to call when the collision's position changes */ + set onCollisionPositionChange(callback) { + if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver) { + this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver); + } + this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback); + } + /** + * Gets or sets mesh visibility between 0 and 1 (default is 1) + */ + get visibility() { + return this._internalAbstractMeshDataInfo._visibility; + } + /** + * Gets or sets mesh visibility between 0 and 1 (default is 1) + */ + set visibility(value) { + if (this._internalAbstractMeshDataInfo._visibility === value) { + return; + } + const oldValue = this._internalAbstractMeshDataInfo._visibility; + this._internalAbstractMeshDataInfo._visibility = value; + if ((oldValue === 1 && value !== 1) || (oldValue !== 1 && value === 1)) { + this._markSubMeshesAsDirty((defines) => { + defines.markAsMiscDirty(); + defines.markAsPrePassDirty(); + }); + } + } + /** + * If set to true, a mesh will only be visible only if its parent(s) are also visible (default is false) + */ + get inheritVisibility() { + return this._internalAbstractMeshDataInfo._inheritVisibility; + } + set inheritVisibility(value) { + this._internalAbstractMeshDataInfo._inheritVisibility = value; + } + /** + * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true + */ + get isVisible() { + if (!this._isVisible || !this.inheritVisibility || !this._parentNode) { + return this._isVisible; + } + if (this._isVisible) { + let parent = this._parentNode; + while (parent) { + const parentVisible = parent.isVisible; + if (typeof parentVisible !== "undefined") { + return parentVisible; + } + parent = parent.parent; + } + } + return this._isVisible; + } + set isVisible(value) { + this._isVisible = value; + } + /** + * Gets or sets the property which disables the test that is checking that the mesh under the pointer is the same than the previous time we tested for it (default: false). + * Set this property to true if you want thin instances picking to be reported accurately when moving over the mesh. + * Note that setting this property to true will incur some performance penalties when dealing with pointer events for this mesh so use it sparingly. + */ + get pointerOverDisableMeshTesting() { + return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting; + } + set pointerOverDisableMeshTesting(disable) { + this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting = disable; + } + /** + * Specifies the rendering group id for this mesh (0 by default) + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#rendering-groups + */ + get renderingGroupId() { + return this._internalAbstractMeshDataInfo._renderingGroupId; + } + set renderingGroupId(value) { + this._internalAbstractMeshDataInfo._renderingGroupId = value; + } + /** Gets or sets current material */ + get material() { + return this._internalAbstractMeshDataInfo._material; + } + set material(value) { + this._setMaterial(value); + } + /** @internal */ + _setMaterial(value) { + if (this._internalAbstractMeshDataInfo._material === value) { + return; + } + // remove from material mesh map id needed + if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) { + this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined; + } + this._internalAbstractMeshDataInfo._material = value; + if (value && value.meshMap) { + value.meshMap[this.uniqueId] = this; + } + if (this.onMaterialChangedObservable.hasObservers()) { + this.onMaterialChangedObservable.notifyObservers(this); + } + if (!this.subMeshes) { + return; + } + this.resetDrawCache(undefined, value == null); + this._unBindEffect(); + } + /** + * Gets the material used to render the mesh in a specific render pass + * @param renderPassId render pass id + * @returns material used for the render pass. If no specific material is used for this render pass, undefined is returned (meaning mesh.material is used for this pass) + */ + getMaterialForRenderPass(renderPassId) { + return this._internalAbstractMeshDataInfo._materialForRenderPass?.[renderPassId]; + } + /** + * Sets the material to be used to render the mesh in a specific render pass + * @param renderPassId render pass id + * @param material material to use for this render pass. If undefined is passed, no specific material will be used for this render pass but the regular material will be used instead (mesh.material) + */ + setMaterialForRenderPass(renderPassId, material) { + this.resetDrawCache(renderPassId); + if (!this._internalAbstractMeshDataInfo._materialForRenderPass) { + this._internalAbstractMeshDataInfo._materialForRenderPass = []; + } + const currentMaterial = this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId]; + if (currentMaterial?.meshMap?.[this.uniqueId]) { + currentMaterial.meshMap[this.uniqueId] = undefined; + } + this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId] = material; + if (material && material.meshMap) { + material.meshMap[this.uniqueId] = this; + } + } + /** + * Gets or sets a boolean indicating that this mesh can receive realtime shadows + * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows + */ + get receiveShadows() { + return this._internalAbstractMeshDataInfo._receiveShadows; + } + set receiveShadows(value) { + if (this._internalAbstractMeshDataInfo._receiveShadows === value) { + return; + } + this._internalAbstractMeshDataInfo._receiveShadows = value; + this._markSubMeshesAsLightDirty(); + } + /** + * Gets or sets a boolean indicating that this mesh needs to use vertex alpha data to render. + * This property is misnamed and should be `useVertexAlpha`. Note that the mesh will be rendered + * with alpha blending when this flag is set even if vertex alpha data is missing from the geometry. + */ + get hasVertexAlpha() { + return this._internalAbstractMeshDataInfo._hasVertexAlpha; + } + set hasVertexAlpha(value) { + if (this._internalAbstractMeshDataInfo._hasVertexAlpha === value) { + return; + } + this._internalAbstractMeshDataInfo._hasVertexAlpha = value; + this._markSubMeshesAsAttributesDirty(); + this._markSubMeshesAsMiscDirty(); + } + /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */ + get useVertexColors() { + return this._internalAbstractMeshDataInfo._useVertexColors; + } + set useVertexColors(value) { + if (this._internalAbstractMeshDataInfo._useVertexColors === value) { + return; + } + this._internalAbstractMeshDataInfo._useVertexColors = value; + this._markSubMeshesAsAttributesDirty(); + } + /** + * Gets or sets a boolean indicating that bone animations must be computed by the GPU (true by default) + */ + get computeBonesUsingShaders() { + return this._internalAbstractMeshDataInfo._computeBonesUsingShaders; + } + set computeBonesUsingShaders(value) { + if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) { + return; + } + this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value; + this._markSubMeshesAsAttributesDirty(); + } + /** Gets or sets the number of allowed bone influences per vertex (4 by default) */ + get numBoneInfluencers() { + return this._internalAbstractMeshDataInfo._numBoneInfluencers; + } + set numBoneInfluencers(value) { + if (this._internalAbstractMeshDataInfo._numBoneInfluencers === value) { + return; + } + this._internalAbstractMeshDataInfo._numBoneInfluencers = value; + this._markSubMeshesAsAttributesDirty(); + } + /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */ + get applyFog() { + return this._internalAbstractMeshDataInfo._applyFog; + } + set applyFog(value) { + if (this._internalAbstractMeshDataInfo._applyFog === value) { + return; + } + this._internalAbstractMeshDataInfo._applyFog = value; + this._markSubMeshesAsMiscDirty(); + } + /** When enabled, decompose picking matrices for better precision with large values for mesh position and scling */ + get enableDistantPicking() { + return this._internalAbstractMeshDataInfo._enableDistantPicking; + } + set enableDistantPicking(value) { + this._internalAbstractMeshDataInfo._enableDistantPicking = value; + } + /** + * Gets or sets the current layer mask (default is 0x0FFFFFFF) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/layerMasksAndMultiCam + */ + get layerMask() { + return this._internalAbstractMeshDataInfo._layerMask; + } + set layerMask(value) { + if (value === this._internalAbstractMeshDataInfo._layerMask) { + return; + } + this._internalAbstractMeshDataInfo._layerMask = value; + this._resyncLightSources(); + } + /** + * Gets or sets a collision mask used to mask collisions (default is -1). + * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 + */ + get collisionMask() { + return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask; + } + set collisionMask(mask) { + this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask = !isNaN(mask) ? mask : -1; + } + /** + * Gets or sets a collision response flag (default is true). + * when collisionResponse is false, events are still triggered but colliding entity has no response + * This helps creating trigger volume when user wants collision feedback events but not position/velocity + * to respond to the collision. + */ + get collisionResponse() { + return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse; + } + set collisionResponse(response) { + this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse = response; + } + /** + * Gets or sets the current collision group mask (-1 by default). + * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 + */ + get collisionGroup() { + return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup; + } + set collisionGroup(mask) { + this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup = !isNaN(mask) ? mask : -1; + } + /** + * Gets or sets current surrounding meshes (null by default). + * + * By default collision detection is tested against every mesh in the scene. + * It is possible to set surroundingMeshes to a defined list of meshes and then only these specified + * meshes will be tested for the collision. + * + * Note: if set to an empty array no collision will happen when this mesh is moved. + */ + get surroundingMeshes() { + return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes; + } + set surroundingMeshes(meshes) { + this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes = meshes; + } + /** Gets the list of lights affecting that mesh */ + get lightSources() { + return this._lightSources; + } + /** + * Gets or sets a skeleton to apply skinning transformations + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons + */ + set skeleton(value) { + const skeleton = this._internalAbstractMeshDataInfo._skeleton; + if (skeleton && skeleton.needInitialSkinMatrix) { + skeleton._unregisterMeshWithPoseMatrix(this); + } + if (value && value.needInitialSkinMatrix) { + value._registerMeshWithPoseMatrix(this); + } + this._internalAbstractMeshDataInfo._skeleton = value; + if (!this._internalAbstractMeshDataInfo._skeleton) { + this._bonesTransformMatrices = null; + } + this._markSubMeshesAsAttributesDirty(); + } + get skeleton() { + return this._internalAbstractMeshDataInfo._skeleton; + } + // Constructor + /** + * Creates a new AbstractMesh + * @param name defines the name of the mesh + * @param scene defines the hosting scene + */ + constructor(name, scene = null) { + super(name, scene, false); + // Internal data + /** @internal */ + this._internalAbstractMeshDataInfo = new _InternalAbstractMeshDataInfo(); + /** @internal */ + this._waitingMaterialId = null; + /** @internal */ + this._waitingMorphTargetManagerId = null; + /** + * The culling strategy to use to check whether the mesh must be rendered or not. + * This value can be changed at any time and will be used on the next render mesh selection. + * The possible values are : + * - AbstractMesh.CULLINGSTRATEGY_STANDARD + * - AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY + * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION + * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY + * Please read each static variable documentation to get details about the culling process. + * */ + this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY; + // Events + /** + * An event triggered when this mesh collides with another one + */ + this.onCollideObservable = new Observable(); + /** + * An event triggered when the collision's position changes + */ + this.onCollisionPositionChangeObservable = new Observable(); + /** + * An event triggered when material is changed + */ + this.onMaterialChangedObservable = new Observable(); + // Properties + /** + * Gets or sets the orientation for POV movement & rotation + */ + this.definedFacingForward = true; + /** @internal */ + this._occlusionQuery = null; + /** @internal */ + this._renderingGroup = null; + /** Gets or sets the alpha index used to sort transparent meshes + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#alpha-index + */ + this.alphaIndex = Number.MAX_VALUE; + this._isVisible = true; + /** + * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true + */ + this.isPickable = true; + /** + * Gets or sets a boolean indicating if the mesh can be near picked (touched by the XR controller or hands). Default is false + */ + this.isNearPickable = false; + /** + * Gets or sets a boolean indicating if the mesh can be grabbed. Default is false. + * Setting this to true, while using the XR near interaction feature, will trigger a pointer event when the mesh is grabbed. + * Grabbing means that the controller is using the squeeze or main trigger button to grab the mesh. + * This is different from nearPickable which only triggers the event when the mesh is touched by the controller + */ + this.isNearGrabbable = false; + /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */ + this.showSubMeshesBoundingBox = false; + /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default) + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare + */ + this.isBlocker = false; + /** + * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default) + */ + this.enablePointerMoveEvents = false; + /** Defines color to use when rendering outline */ + this.outlineColor = Color3.Red(); + /** Define width to use when rendering outline */ + this.outlineWidth = 0.02; + /** Defines color to use when rendering overlay */ + this.overlayColor = Color3.Red(); + /** Defines alpha to use when rendering overlay */ + this.overlayAlpha = 0.5; + /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */ + this.useOctreeForRenderingSelection = true; + /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */ + this.useOctreeForPicking = true; + /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */ + this.useOctreeForCollisions = true; + /** + * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase) + */ + this.alwaysSelectAsActiveMesh = false; + /** + * Gets or sets a boolean indicating that the bounding info does not need to be kept in sync (for performance reason) + */ + this.doNotSyncBoundingInfo = false; + /** + * Gets or sets the current action manager + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ + this.actionManager = null; + /** + * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5)) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions + */ + this.ellipsoid = new Vector3(0.5, 1, 0.5); + /** + * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0)) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions + */ + this.ellipsoidOffset = new Vector3(0, 0, 0); + // Edges + /** + * Defines edge width used when edgesRenderer is enabled + * @see https://www.babylonjs-playground.com/#10OJSG#13 + */ + this.edgesWidth = 1; + /** + * Defines edge color used when edgesRenderer is enabled + * @see https://www.babylonjs-playground.com/#10OJSG#13 + */ + this.edgesColor = new Color4(1, 0, 0, 1); + /** @internal */ + this._edgesRenderer = null; + /** @internal */ + this._masterMesh = null; + this._boundingInfo = null; + this._boundingInfoIsDirty = true; + /** @internal */ + this._renderId = 0; + /** @internal */ + this._intersectionsInProgress = new Array(); + /** @internal */ + this._unIndexed = false; + /** @internal */ + this._lightSources = new Array(); + // Loading properties + /** @internal */ + this._waitingData = { + lods: null, + actions: null, + freezeWorldMatrix: null, + }; + /** @internal */ + this._bonesTransformMatrices = null; + /** @internal */ + this._transformMatrixTexture = null; + /** + * An event triggered when the mesh is rebuilt. + */ + this.onRebuildObservable = new Observable(); + this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => { + newPosition.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions); + if (this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length() > AbstractEngine.CollisionsEpsilon) { + this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions); + } + if (collidedMesh) { + this.onCollideObservable.notifyObservers(collidedMesh); + } + this.onCollisionPositionChangeObservable.notifyObservers(this.position); + }; + scene = this.getScene(); + scene.addMesh(this); + this._resyncLightSources(); + // Mesh Uniform Buffer. + this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name, !this.getScene().getEngine().isWebGPU); + this._buildUniformLayout(); + switch (scene.performancePriority) { + case 2 /* ScenePerformancePriority.Aggressive */: + this.doNotSyncBoundingInfo = true; + // eslint-disable-next-line no-fallthrough + case 1 /* ScenePerformancePriority.Intermediate */: + this.alwaysSelectAsActiveMesh = true; + this.isPickable = false; + break; + } + } + _buildUniformLayout() { + this._uniformBuffer.addUniform("world", 16); + this._uniformBuffer.addUniform("visibility", 1); + this._uniformBuffer.create(); + } + /** + * Transfer the mesh values to its UBO. + * @param world The world matrix associated with the mesh + */ + transferToEffect(world) { + const ubo = this._uniformBuffer; + ubo.updateMatrix("world", world); + ubo.updateFloat("visibility", this._internalAbstractMeshDataInfo._visibility); + ubo.update(); + } + /** + * Gets the mesh uniform buffer. + * @returns the uniform buffer of the mesh. + */ + getMeshUniformBuffer() { + return this._uniformBuffer; + } + /** + * Returns the string "AbstractMesh" + * @returns "AbstractMesh" + */ + getClassName() { + return "AbstractMesh"; + } + /** + * Gets a string representation of the current mesh + * @param fullDetails defines a boolean indicating if full details must be included + * @returns a string representation of the current mesh + */ + toString(fullDetails) { + let ret = "Name: " + this.name + ", isInstance: " + (this.getClassName() !== "InstancedMesh" ? "YES" : "NO"); + ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0); + const skeleton = this._internalAbstractMeshDataInfo._skeleton; + if (skeleton) { + ret += ", skeleton: " + skeleton.name; + } + if (fullDetails) { + ret += ", billboard mode: " + ["NONE", "X", "Y", null, "Z", null, null, "ALL"][this.billboardMode]; + ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingData.freezeWorldMatrix ? "YES" : "NO"); + } + return ret; + } + /** + * @internal + */ + _getEffectiveParent() { + if (this._masterMesh && this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) { + return this._masterMesh; + } + return super._getEffectiveParent(); + } + /** + * @internal + */ + _getActionManagerForTrigger(trigger, initialCall = true) { + if (this.actionManager && (initialCall || this.actionManager.isRecursive)) { + if (trigger) { + if (this.actionManager.hasSpecificTrigger(trigger)) { + return this.actionManager; + } + } + else { + return this.actionManager; + } + } + if (!this.parent) { + return null; + } + return this.parent._getActionManagerForTrigger(trigger, false); + } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _rebuild(dispose = false) { + this.onRebuildObservable.notifyObservers(this); + if (this._occlusionQuery !== null) { + this._occlusionQuery = null; + } + if (!this.subMeshes) { + return; + } + for (const subMesh of this.subMeshes) { + subMesh._rebuild(); + } + this.resetDrawCache(); + } + /** @internal */ + _resyncLightSources() { + this._lightSources.length = 0; + for (const light of this.getScene().lights) { + if (!light.isEnabled()) { + continue; + } + if (light.canAffectMesh(this)) { + this._lightSources.push(light); + } + } + this._markSubMeshesAsLightDirty(); + } + /** + * @internal + */ + _resyncLightSource(light) { + const isIn = light.isEnabled() && light.canAffectMesh(this); + const index = this._lightSources.indexOf(light); + let removed = false; + if (index === -1) { + if (!isIn) { + return; + } + this._lightSources.push(light); + } + else { + if (isIn) { + return; + } + removed = true; + this._lightSources.splice(index, 1); + } + this._markSubMeshesAsLightDirty(removed); + } + /** @internal */ + _unBindEffect() { + for (const subMesh of this.subMeshes) { + subMesh.setEffect(null); + } + } + /** + * @internal + */ + _removeLightSource(light, dispose) { + const index = this._lightSources.indexOf(light); + if (index === -1) { + return; + } + this._lightSources.splice(index, 1); + this._markSubMeshesAsLightDirty(dispose); + } + _markSubMeshesAsDirty(func) { + if (!this.subMeshes) { + return; + } + for (const subMesh of this.subMeshes) { + for (let i = 0; i < subMesh._drawWrappers.length; ++i) { + const drawWrapper = subMesh._drawWrappers[i]; + if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) { + continue; + } + func(drawWrapper.defines); + } + } + } + /** + * @internal + */ + _markSubMeshesAsLightDirty(dispose = false) { + this._markSubMeshesAsDirty((defines) => defines.markAsLightDirty(dispose)); + } + /** @internal */ + _markSubMeshesAsAttributesDirty() { + this._markSubMeshesAsDirty((defines) => defines.markAsAttributesDirty()); + } + /** @internal */ + _markSubMeshesAsMiscDirty() { + this._markSubMeshesAsDirty((defines) => defines.markAsMiscDirty()); + } + /** + * Flag the AbstractMesh as dirty (Forcing it to update everything) + * @param property if set to "rotation" the objects rotationQuaternion will be set to null + * @returns this AbstractMesh + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + markAsDirty(property) { + this._currentRenderId = Number.MAX_VALUE; + super.markAsDirty(property); + this._isDirty = true; + return this; + } + /** + * Resets the draw wrappers cache for all submeshes of this abstract mesh + * @param passId If provided, releases only the draw wrapper corresponding to this render pass id + * @param immediate If true, the effect will be released immediately, otherwise it will be released at the next frame + */ + resetDrawCache(passId, immediate = false) { + if (!this.subMeshes) { + return; + } + for (const subMesh of this.subMeshes) { + subMesh.resetDrawCache(passId, immediate); + } + } + // Methods + /** + * Returns true if the mesh is blocked. Implemented by child classes + */ + get isBlocked() { + return false; + } + /** + * Returns the mesh itself by default. Implemented by child classes + * @param camera defines the camera to use to pick the right LOD level + * @returns the currentAbstractMesh + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getLOD(camera) { + return this; + } + /** + * Returns 0 by default. Implemented by child classes + * @returns an integer + */ + getTotalVertices() { + return 0; + } + /** + * Returns a positive integer : the total number of indices in this mesh geometry. + * @returns the number of indices or zero if the mesh has no geometry. + */ + getTotalIndices() { + return 0; + } + /** + * Returns null by default. Implemented by child classes + * @returns null + */ + getIndices() { + return null; + } + /** + * Returns the array of the requested vertex data kind. Implemented by child classes + * @param kind defines the vertex data kind to use + * @returns null + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getVerticesData(kind) { + return null; + } + /** + * Sets the vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. + * Note that a new underlying VertexBuffer object is created each call. + * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. + * @param kind defines vertex data kind: + * * VertexBuffer.PositionKind + * * VertexBuffer.UVKind + * * VertexBuffer.UV2Kind + * * VertexBuffer.UV3Kind + * * VertexBuffer.UV4Kind + * * VertexBuffer.UV5Kind + * * VertexBuffer.UV6Kind + * * VertexBuffer.ColorKind + * * VertexBuffer.MatricesIndicesKind + * * VertexBuffer.MatricesIndicesExtraKind + * * VertexBuffer.MatricesWeightsKind + * * VertexBuffer.MatricesWeightsExtraKind + * @param data defines the data source + * @param updatable defines if the data must be flagged as updatable (or static) + * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind + * @returns the current mesh + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + setVerticesData(kind, data, updatable, stride) { + return this; + } + /** + * Updates the existing vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, it is simply returned as it is. + * @param kind defines vertex data kind: + * * VertexBuffer.PositionKind + * * VertexBuffer.UVKind + * * VertexBuffer.UV2Kind + * * VertexBuffer.UV3Kind + * * VertexBuffer.UV4Kind + * * VertexBuffer.UV5Kind + * * VertexBuffer.UV6Kind + * * VertexBuffer.ColorKind + * * VertexBuffer.MatricesIndicesKind + * * VertexBuffer.MatricesIndicesExtraKind + * * VertexBuffer.MatricesWeightsKind + * * VertexBuffer.MatricesWeightsExtraKind + * @param data defines the data source + * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed + * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh + * @returns the current mesh + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + updateVerticesData(kind, data, updateExtends, makeItUnique) { + return this; + } + /** + * Sets the mesh indices, + * If the mesh has no geometry, a new Geometry object is created and set to the mesh. + * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) + * @param totalVertices Defines the total number of vertices + * @returns the current mesh + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + setIndices(indices, totalVertices) { + return this; + } + /** + * Gets a boolean indicating if specific vertex data is present + * @param kind defines the vertex data kind to use + * @returns true is data kind is present + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + isVerticesDataPresent(kind) { + return false; + } + /** + * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined. + * Note that it returns a shallow bounding of the mesh (i.e. it does not include children). + * However, if the mesh contains thin instances, it will be expanded to include them. If you want the "raw" bounding data instead, then use `getRawBoundingInfo()`. + * To get the full bounding of all children, call `getHierarchyBoundingVectors` instead. + * @returns a BoundingInfo + */ + getBoundingInfo() { + if (this._masterMesh) { + return this._masterMesh.getBoundingInfo(); + } + if (this._boundingInfoIsDirty) { + this._boundingInfoIsDirty = false; + // this._boundingInfo is being created if undefined + this._updateBoundingInfo(); + } + // cannot be null. + return this._boundingInfo; + } + /** + * Returns the bounding info unnafected by instance data. + * @returns the bounding info of the mesh unaffected by instance data. + */ + getRawBoundingInfo() { + return this.rawBoundingInfo ?? this.getBoundingInfo(); + } + /** + * Overwrite the current bounding info + * @param boundingInfo defines the new bounding info + * @returns the current mesh + */ + setBoundingInfo(boundingInfo) { + this._boundingInfo = boundingInfo; + return this; + } + /** + * Returns true if there is already a bounding info + */ + get hasBoundingInfo() { + return this._boundingInfo !== null; + } + /** + * Creates a new bounding info for the mesh + * @param minimum min vector of the bounding box/sphere + * @param maximum max vector of the bounding box/sphere + * @param worldMatrix defines the new world matrix + * @returns the new bounding info + */ + buildBoundingInfo(minimum, maximum, worldMatrix) { + this._boundingInfo = new BoundingInfo(minimum, maximum, worldMatrix); + return this._boundingInfo; + } + /** + * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) + * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false + * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false + * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling + * @returns the current mesh + */ + normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) { + return super.normalizeToUnitCube(includeDescendants, ignoreRotation, predicate); + } + /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */ + get useBones() { + return ((this.skeleton && + this.getScene().skeletonsEnabled && + this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && + this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind))); + } + /** @internal */ + _preActivate() { } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _preActivateForIntermediateRendering(renderId) { } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _activate(renderId, intermediateRendering) { + this._renderId = renderId; + return true; + } + /** @internal */ + _postActivate() { + // Do nothing + } + /** @internal */ + _freeze() { + // Do nothing + } + /** @internal */ + _unFreeze() { + // Do nothing + } + /** + * Gets the current world matrix + * @returns a Matrix + */ + getWorldMatrix() { + if (this._masterMesh && this.billboardMode === TransformNode.BILLBOARDMODE_NONE) { + return this._masterMesh.getWorldMatrix(); + } + return super.getWorldMatrix(); + } + /** @internal */ + _getWorldMatrixDeterminant() { + if (this._masterMesh) { + return this._masterMesh._getWorldMatrixDeterminant(); + } + return super._getWorldMatrixDeterminant(); + } + /** + * Gets a boolean indicating if this mesh is an instance or a regular mesh + */ + get isAnInstance() { + return false; + } + /** + * Gets a boolean indicating if this mesh has instances + */ + get hasInstances() { + return false; + } + /** + * Gets a boolean indicating if this mesh has thin instances + */ + get hasThinInstances() { + return false; + } + // ================================== Point of View Movement ================================= + /** + * Perform relative position change from the point of view of behind the front of the mesh. + * This is performed taking into account the meshes current rotation, so you do not have to care. + * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. + * @param amountRight defines the distance on the right axis + * @param amountUp defines the distance on the up axis + * @param amountForward defines the distance on the forward axis + * @returns the current mesh + */ + movePOV(amountRight, amountUp, amountForward) { + this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward)); + return this; + } + /** + * Calculate relative position change from the point of view of behind the front of the mesh. + * This is performed taking into account the meshes current rotation, so you do not have to care. + * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. + * @param amountRight defines the distance on the right axis + * @param amountUp defines the distance on the up axis + * @param amountForward defines the distance on the forward axis + * @returns the new displacement vector + */ + calcMovePOV(amountRight, amountUp, amountForward) { + const rotMatrix = new Matrix(); + const rotQuaternion = this.rotationQuaternion ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z); + rotQuaternion.toRotationMatrix(rotMatrix); + const translationDelta = Vector3.Zero(); + const defForwardMult = this.definedFacingForward ? -1 : 1; + Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta); + return translationDelta; + } + // ================================== Point of View Rotation ================================= + /** + * Perform relative rotation change from the point of view of behind the front of the mesh. + * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. + * @param flipBack defines the flip + * @param twirlClockwise defines the twirl + * @param tiltRight defines the tilt + * @returns the current mesh + */ + rotatePOV(flipBack, twirlClockwise, tiltRight) { + this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight)); + return this; + } + /** + * Calculate relative rotation change from the point of view of behind the front of the mesh. + * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. + * @param flipBack defines the flip + * @param twirlClockwise defines the twirl + * @param tiltRight defines the tilt + * @returns the new rotation vector + */ + calcRotatePOV(flipBack, twirlClockwise, tiltRight) { + const defForwardMult = this.definedFacingForward ? 1 : -1; + return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult); + } + /** + * @internal + */ + _refreshBoundingInfo(data, bias) { + if (data) { + const extend = extractMinAndMax(data, 0, this.getTotalVertices(), bias); + if (this._boundingInfo) { + this._boundingInfo.reConstruct(extend.minimum, extend.maximum); + } + else { + this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum); + } + } + if (this.subMeshes) { + for (let index = 0; index < this.subMeshes.length; index++) { + this.subMeshes[index].refreshBoundingInfo(data); + } + } + this._updateBoundingInfo(); + } + /** + * @internal + */ + _refreshBoundingInfoDirect(extend) { + if (this._boundingInfo) { + this._boundingInfo.reConstruct(extend.minimum, extend.maximum); + } + else { + this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum); + } + if (this.subMeshes) { + for (let index = 0; index < this.subMeshes.length; index++) { + this.subMeshes[index].refreshBoundingInfo(null); + } + } + this._updateBoundingInfo(); + } + // This function is only here so we can apply the nativeOverride decorator. + static _ApplySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData) { + applySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData); + } + /** @internal */ + _getData(options, data, kind = VertexBuffer.PositionKind) { + const cache = options.cache; + const getVertexData = (kind) => { + if (cache) { + const vertexData = (cache._vertexData || (cache._vertexData = {})); + if (!vertexData[kind]) { + this.copyVerticesData(kind, vertexData); + } + return vertexData[kind]; + } + return this.getVerticesData(kind); + }; + data || (data = getVertexData(kind)); + if (!data) { + return null; + } + if (cache) { + if (cache._outputData) { + cache._outputData.set(data); + } + else { + cache._outputData = new Float32Array(data); + } + data = cache._outputData; + } + else if ((options.applyMorph && this.morphTargetManager) || (options.applySkeleton && this.skeleton)) { + data = data.slice(); + } + if (options.applyMorph && this.morphTargetManager) { + applyMorph(data, kind, this.morphTargetManager); + } + if (options.applySkeleton && this.skeleton) { + const matricesIndicesData = getVertexData(VertexBuffer.MatricesIndicesKind); + const matricesWeightsData = getVertexData(VertexBuffer.MatricesWeightsKind); + if (matricesWeightsData && matricesIndicesData) { + const needExtras = this.numBoneInfluencers > 4; + const matricesIndicesExtraData = needExtras ? getVertexData(VertexBuffer.MatricesIndicesExtraKind) : null; + const matricesWeightsExtraData = needExtras ? getVertexData(VertexBuffer.MatricesWeightsExtraKind) : null; + const skeletonMatrices = this.skeleton.getTransformMatrices(this); + AbstractMesh._ApplySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData); + } + } + if (options.updatePositionsArray !== false && kind === VertexBuffer.PositionKind) { + const positions = this._internalAbstractMeshDataInfo._positions || []; + const previousLength = positions.length; + positions.length = data.length / 3; + if (previousLength < positions.length) { + for (let positionIndex = previousLength; positionIndex < positions.length; positionIndex++) { + positions[positionIndex] = new Vector3(); + } + } + for (let positionIndex = 0, dataIndex = 0; positionIndex < positions.length; positionIndex++, dataIndex += 3) { + positions[positionIndex].copyFromFloats(data[dataIndex], data[dataIndex + 1], data[dataIndex + 2]); + } + this._internalAbstractMeshDataInfo._positions = positions; + } + return data; + } + /** + * Get the normals vertex data and optionally apply skeleton and morphing. + * @param applySkeleton defines whether to apply the skeleton + * @param applyMorph defines whether to apply the morph target + * @returns the normals data + */ + getNormalsData(applySkeleton = false, applyMorph = false) { + return this._getData({ applySkeleton, applyMorph, updatePositionsArray: false }, null, VertexBuffer.NormalKind); + } + /** + * Get the position vertex data and optionally apply skeleton and morphing. + * @param applySkeleton defines whether to apply the skeleton + * @param applyMorph defines whether to apply the morph target + * @param data defines the position data to apply the skeleton and morph to + * @returns the position data + */ + getPositionData(applySkeleton = false, applyMorph = false, data = null) { + return this._getData({ applySkeleton, applyMorph, updatePositionsArray: false }, data, VertexBuffer.PositionKind); + } + /** @internal */ + _updateBoundingInfo() { + if (this._boundingInfo) { + this._boundingInfo.update(this.worldMatrixFromCache); + } + else { + this._boundingInfo = new BoundingInfo(Vector3.Zero(), Vector3.Zero(), this.worldMatrixFromCache); + } + this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache); + return this; + } + /** + * @internal + */ + _updateSubMeshesBoundingInfo(matrix) { + if (!this.subMeshes) { + return this; + } + const count = this.subMeshes.length; + for (let subIndex = 0; subIndex < count; subIndex++) { + const subMesh = this.subMeshes[subIndex]; + if (count > 1 || !subMesh.IsGlobal) { + subMesh.updateBoundingInfo(matrix); + } + } + return this; + } + /** @internal */ + _afterComputeWorldMatrix() { + if (this.doNotSyncBoundingInfo) { + return; + } + // Bounding info + this._boundingInfoIsDirty = true; + } + /** + * Returns `true` if the mesh is within the frustum defined by the passed array of planes. + * A mesh is in the frustum if its bounding box intersects the frustum + * @param frustumPlanes defines the frustum to test + * @returns true if the mesh is in the frustum planes + */ + isInFrustum(frustumPlanes) { + return this.getBoundingInfo().isInFrustum(frustumPlanes, this.cullingStrategy); + } + /** + * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes. + * A mesh is completely in the frustum if its bounding box it completely inside the frustum. + * @param frustumPlanes defines the frustum to test + * @returns true if the mesh is completely in the frustum planes + */ + isCompletelyInFrustum(frustumPlanes) { + return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes); + } + /** + * True if the mesh intersects another mesh or a SolidParticle object + * @param mesh defines a target mesh or SolidParticle to test + * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes) + * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes + * @returns true if there is an intersection + */ + intersectsMesh(mesh, precise = false, includeDescendants) { + const boundingInfo = this.getBoundingInfo(); + const otherBoundingInfo = mesh.getBoundingInfo(); + if (boundingInfo.intersects(otherBoundingInfo, precise)) { + return true; + } + if (includeDescendants) { + for (const child of this.getChildMeshes()) { + if (child.intersectsMesh(mesh, precise, true)) { + return true; + } + } + } + return false; + } + /** + * Returns true if the passed point (Vector3) is inside the mesh bounding box + * @param point defines the point to test + * @returns true if there is an intersection + */ + intersectsPoint(point) { + return this.getBoundingInfo().intersectsPoint(point); + } + // Collisions + /** + * Gets or sets a boolean indicating that this mesh can be used in the collision engine + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions + */ + get checkCollisions() { + return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions; + } + set checkCollisions(collisionEnabled) { + this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions = collisionEnabled; + } + /** + * Gets Collider object used to compute collisions (not physics) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions + */ + get collider() { + return this._internalAbstractMeshDataInfo._meshCollisionData._collider; + } + /** + * Move the mesh using collision engine + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions + * @param displacement defines the requested displacement vector + * @returns the current mesh + */ + moveWithCollisions(displacement) { + const globalPosition = this.getAbsolutePosition(); + globalPosition.addToRef(this.ellipsoidOffset, this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions); + const coordinator = this.getScene().collisionCoordinator; + if (!this._internalAbstractMeshDataInfo._meshCollisionData._collider) { + this._internalAbstractMeshDataInfo._meshCollisionData._collider = coordinator.createCollider(); + } + this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius = this.ellipsoid; + coordinator.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, displacement, this._internalAbstractMeshDataInfo._meshCollisionData._collider, this.collisionRetryCount, this, this._onCollisionPositionChange, this.uniqueId); + return this; + } + // Collisions + /** + * @internal + */ + _collideForSubMesh(subMesh, transformMatrix, collider) { + this._generatePointsArray(); + if (!this._positions) { + return this; + } + // Transformation + if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) { + subMesh._lastColliderTransformMatrix = transformMatrix.clone(); + subMesh._lastColliderWorldVertices = []; + subMesh._trianglePlanes = []; + const start = subMesh.verticesStart; + const end = subMesh.verticesStart + subMesh.verticesCount; + for (let i = start; i < end; i++) { + subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix)); + } + } + // Collide + collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial(), this, this._shouldConvertRHS(), subMesh.getMaterial()?.fillMode === 7); + return this; + } + /** + * @internal + */ + _processCollisionsForSubMeshes(collider, transformMatrix) { + const subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider); + const len = subMeshes.length; + for (let index = 0; index < len; index++) { + const subMesh = subMeshes.data[index]; + // Bounding test + if (len > 1 && !subMesh._checkCollision(collider)) { + continue; + } + this._collideForSubMesh(subMesh, transformMatrix, collider); + } + return this; + } + /** @internal */ + _shouldConvertRHS() { + return false; + } + /** + * @internal + */ + _checkCollision(collider) { + // Bounding box test + if (!this.getBoundingInfo()._checkCollision(collider)) { + return this; + } + // Transformation matrix + const collisionsScalingMatrix = TmpVectors.Matrix[0]; + const collisionsTransformMatrix = TmpVectors.Matrix[1]; + Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix); + this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix); + this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix); + return this; + } + // Picking + /** @internal */ + _generatePointsArray() { + return false; + } + /** + * Checks if the passed Ray intersects with the mesh. A mesh triangle can be picked both from its front and back sides, + * irrespective of orientation. + * @param ray defines the ray to use. It should be in the mesh's LOCAL coordinate space. + * @param fastCheck defines if fast mode (but less precise) must be used (false by default) + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default) + * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point + * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check + * @returns the picking info + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect + */ + intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) { + const pickingInfo = new PickingInfo(); + const className = this.getClassName(); + const intersectionThreshold = className === "InstancedLinesMesh" || className === "LinesMesh" || className === "GreasedLineMesh" ? this.intersectionThreshold : 0; + const boundingInfo = this.getBoundingInfo(); + if (!this.subMeshes) { + return pickingInfo; + } + if (!skipBoundingInfo && + (!ray.intersectsSphere(boundingInfo.boundingSphere, intersectionThreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionThreshold))) { + return pickingInfo; + } + if (onlyBoundingInfo) { + pickingInfo.hit = skipBoundingInfo ? false : true; + pickingInfo.pickedMesh = skipBoundingInfo ? null : this; + pickingInfo.distance = skipBoundingInfo ? 0 : Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center); + pickingInfo.subMeshId = 0; + return pickingInfo; + } + if (!this._generatePointsArray()) { + return pickingInfo; + } + let intersectInfo = null; + const subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray); + const len = subMeshes.length; + // Check if all submeshes are using a material that don't allow picking (point/lines rendering) + // if no submesh can be picked that way, then fallback to BBox picking + let anySubmeshSupportIntersect = false; + for (let index = 0; index < len; index++) { + const subMesh = subMeshes.data[index]; + const material = subMesh.getMaterial(); + if (!material) { + continue; + } + if (material.fillMode == 7 || + material.fillMode == 0 || + material.fillMode == 1 || + material.fillMode == 2 || + material.fillMode == 4) { + anySubmeshSupportIntersect = true; + break; + } + } + // no sub mesh support intersection, fallback to BBox that has already be done + if (!anySubmeshSupportIntersect) { + pickingInfo.hit = true; + pickingInfo.pickedMesh = this; + pickingInfo.distance = Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center); + pickingInfo.subMeshId = -1; + return pickingInfo; + } + // at least 1 submesh supports intersection, keep going + for (let index = 0; index < len; index++) { + const subMesh = subMeshes.data[index]; + // Bounding test + if (len > 1 && !skipBoundingInfo && !subMesh.canIntersects(ray)) { + continue; + } + const currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck, trianglePredicate); + if (currentIntersectInfo) { + if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { + intersectInfo = currentIntersectInfo; + intersectInfo.subMeshId = index; + if (fastCheck) { + break; + } + } + } + } + if (intersectInfo) { + // Get picked point + const world = worldToUse ?? this.getWorldMatrix(); + const worldOrigin = TmpVectors.Vector3[0]; + const direction = TmpVectors.Vector3[1]; + Vector3.TransformCoordinatesToRef(ray.origin, world, worldOrigin); + ray.direction.scaleToRef(intersectInfo.distance, direction); + const worldDirection = Vector3.TransformNormal(direction, world); + const pickedPoint = worldDirection.addInPlace(worldOrigin); + // Return result + pickingInfo.hit = true; + pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint); + pickingInfo.pickedPoint = pickedPoint; + pickingInfo.pickedMesh = this; + pickingInfo.bu = intersectInfo.bu || 0; + pickingInfo.bv = intersectInfo.bv || 0; + pickingInfo.subMeshFaceId = intersectInfo.faceId; + pickingInfo.faceId = intersectInfo.faceId + subMeshes.data[intersectInfo.subMeshId].indexStart / (this.getClassName().indexOf("LinesMesh") !== -1 ? 2 : 3); + pickingInfo.subMeshId = intersectInfo.subMeshId; + return pickingInfo; + } + return pickingInfo; + } + /** + * Clones the current mesh + * @param name defines the mesh name + * @param newParent defines the new mesh parent + * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default) + * @returns the new mesh + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + clone(name, newParent, doNotCloneChildren) { + return null; + } + /** + * Disposes all the submeshes of the current mesh + * @param immediate should dispose the effects immediately or not + * @returns the current mesh + */ + releaseSubMeshes(immediate = false) { + if (this.subMeshes) { + while (this.subMeshes.length) { + this.subMeshes[0].dispose(immediate); + } + } + else { + this.subMeshes = []; + } + return this; + } + /** + * Releases resources associated with this abstract mesh. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse, disposeMaterialAndTextures = false) { + let index; + const scene = this.getScene(); + // mesh map release. + if (this._scene.useMaterialMeshMap) { + // remove from material mesh map id needed + if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) { + this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined; + } + } + // Smart Array Retainers. + scene.freeActiveMeshes(); + scene.freeRenderingGroups(); + if (scene.renderingManager.maintainStateBetweenFrames) { + scene.renderingManager.restoreDispachedFlags(); + } + // Action manager + if (this.actionManager !== undefined && this.actionManager !== null) { + // If we are the only mesh using the action manager, dispose of the action manager too unless it has opted out from that behavior + if (this.actionManager.disposeWhenUnowned && !this._scene.meshes.some((m) => m !== this && m.actionManager === this.actionManager)) { + this.actionManager.dispose(); + } + this.actionManager = null; + } + // Skeleton + this._internalAbstractMeshDataInfo._skeleton = null; + if (this._transformMatrixTexture) { + this._transformMatrixTexture.dispose(); + this._transformMatrixTexture = null; + } + // Intersections in progress + for (index = 0; index < this._intersectionsInProgress.length; index++) { + const other = this._intersectionsInProgress[index]; + const pos = other._intersectionsInProgress.indexOf(this); + other._intersectionsInProgress.splice(pos, 1); + } + this._intersectionsInProgress.length = 0; + // Lights + const lights = scene.lights; + lights.forEach((light) => { + let meshIndex = light.includedOnlyMeshes.indexOf(this); + if (meshIndex !== -1) { + light.includedOnlyMeshes.splice(meshIndex, 1); + } + meshIndex = light.excludedMeshes.indexOf(this); + if (meshIndex !== -1) { + light.excludedMeshes.splice(meshIndex, 1); + } + // Shadow generators + const generators = light.getShadowGenerators(); + if (generators) { + const iterator = generators.values(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const generator = key.value; + const shadowMap = generator.getShadowMap(); + if (shadowMap && shadowMap.renderList) { + meshIndex = shadowMap.renderList.indexOf(this); + if (meshIndex !== -1) { + shadowMap.renderList.splice(meshIndex, 1); + } + } + } + } + }); + // SubMeshes + if (this.getClassName() !== "InstancedMesh" || this.getClassName() !== "InstancedLinesMesh") { + this.releaseSubMeshes(true); + } + // Query + const engine = scene.getEngine(); + if (this._occlusionQuery !== null) { + this.isOcclusionQueryInProgress = false; + engine.deleteQuery(this._occlusionQuery); + this._occlusionQuery = null; + } + // Engine + engine.wipeCaches(); + // Remove from scene + scene.removeMesh(this); + if (this._parentContainer) { + const index = this._parentContainer.meshes.indexOf(this); + if (index > -1) { + this._parentContainer.meshes.splice(index, 1); + } + this._parentContainer = null; + } + if (disposeMaterialAndTextures) { + if (this.material) { + if (this.material.getClassName() === "MultiMaterial") { + this.material.dispose(false, true, true); + } + else { + this.material.dispose(false, true); + } + } + } + if (!doNotRecurse) { + // Particles + for (index = 0; index < scene.particleSystems.length; index++) { + if (scene.particleSystems[index].emitter === this) { + scene.particleSystems[index].dispose(); + index--; + } + } + } + // facet data + if (this._internalAbstractMeshDataInfo._facetData.facetDataEnabled) { + this.disableFacetData(); + } + this._uniformBuffer.dispose(); + this.onAfterWorldMatrixUpdateObservable.clear(); + this.onCollideObservable.clear(); + this.onCollisionPositionChangeObservable.clear(); + this.onRebuildObservable.clear(); + super.dispose(doNotRecurse, disposeMaterialAndTextures); + } + // Facet data + /** @internal */ + _initFacetData() { + const data = this._internalAbstractMeshDataInfo._facetData; + if (!data.facetNormals) { + data.facetNormals = []; + } + if (!data.facetPositions) { + data.facetPositions = []; + } + if (!data.facetPartitioning) { + data.facetPartitioning = new Array(); + } + data.facetNb = (this.getIndices().length / 3) | 0; + data.partitioningSubdivisions = data.partitioningSubdivisions ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10 + data.partitioningBBoxRatio = data.partitioningBBoxRatio ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box + for (let f = 0; f < data.facetNb; f++) { + data.facetNormals[f] = Vector3.Zero(); + data.facetPositions[f] = Vector3.Zero(); + } + data.facetDataEnabled = true; + return this; + } + /** + * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated. + * This method can be called within the render loop. + * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation + * @returns the current mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + updateFacetData() { + const data = this._internalAbstractMeshDataInfo._facetData; + if (!data.facetDataEnabled) { + this._initFacetData(); + } + const positions = this.getVerticesData(VertexBuffer.PositionKind); + const indices = this.getIndices(); + const normals = this.getVerticesData(VertexBuffer.NormalKind); + const bInfo = this.getBoundingInfo(); + if (data.facetDepthSort && !data.facetDepthSortEnabled) { + // init arrays, matrix and sort function on first call + data.facetDepthSortEnabled = true; + if (indices instanceof Uint16Array) { + data.depthSortedIndices = new Uint16Array(indices); + } + else if (indices instanceof Uint32Array) { + data.depthSortedIndices = new Uint32Array(indices); + } + else { + let needs32bits = false; + for (let i = 0; i < indices.length; i++) { + if (indices[i] > 65535) { + needs32bits = true; + break; + } + } + if (needs32bits) { + data.depthSortedIndices = new Uint32Array(indices); + } + else { + data.depthSortedIndices = new Uint16Array(indices); + } + } + data.facetDepthSortFunction = function (f1, f2) { + return f2.sqDistance - f1.sqDistance; + }; + if (!data.facetDepthSortFrom) { + const camera = this.getScene().activeCamera; + data.facetDepthSortFrom = camera ? camera.position : Vector3.Zero(); + } + data.depthSortedFacets = []; + for (let f = 0; f < data.facetNb; f++) { + const depthSortedFacet = { ind: f * 3, sqDistance: 0.0 }; + data.depthSortedFacets.push(depthSortedFacet); + } + data.invertedMatrix = Matrix.Identity(); + data.facetDepthSortOrigin = Vector3.Zero(); + } + data.bbSize.x = bInfo.maximum.x - bInfo.minimum.x > Epsilon ? bInfo.maximum.x - bInfo.minimum.x : Epsilon; + data.bbSize.y = bInfo.maximum.y - bInfo.minimum.y > Epsilon ? bInfo.maximum.y - bInfo.minimum.y : Epsilon; + data.bbSize.z = bInfo.maximum.z - bInfo.minimum.z > Epsilon ? bInfo.maximum.z - bInfo.minimum.z : Epsilon; + let bbSizeMax = data.bbSize.x > data.bbSize.y ? data.bbSize.x : data.bbSize.y; + bbSizeMax = bbSizeMax > data.bbSize.z ? bbSizeMax : data.bbSize.z; + data.subDiv.max = data.partitioningSubdivisions; + data.subDiv.X = Math.floor((data.subDiv.max * data.bbSize.x) / bbSizeMax); // adjust the number of subdivisions per axis + data.subDiv.Y = Math.floor((data.subDiv.max * data.bbSize.y) / bbSizeMax); // according to each bbox size per axis + data.subDiv.Z = Math.floor((data.subDiv.max * data.bbSize.z) / bbSizeMax); + data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision + data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y; + data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z; + // set the parameters for ComputeNormals() + data.facetParameters.facetNormals = this.getFacetLocalNormals(); + data.facetParameters.facetPositions = this.getFacetLocalPositions(); + data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning(); + data.facetParameters.bInfo = bInfo; + data.facetParameters.bbSize = data.bbSize; + data.facetParameters.subDiv = data.subDiv; + data.facetParameters.ratio = this.partitioningBBoxRatio; + data.facetParameters.depthSort = data.facetDepthSort; + if (data.facetDepthSort && data.facetDepthSortEnabled) { + this.computeWorldMatrix(true); + this._worldMatrix.invertToRef(data.invertedMatrix); + Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin); + data.facetParameters.distanceTo = data.facetDepthSortOrigin; + } + data.facetParameters.depthSortedFacets = data.depthSortedFacets; + if (normals) { + VertexData.ComputeNormals(positions, indices, normals, data.facetParameters); + } + if (data.facetDepthSort && data.facetDepthSortEnabled) { + data.depthSortedFacets.sort(data.facetDepthSortFunction); + const l = (data.depthSortedIndices.length / 3) | 0; + for (let f = 0; f < l; f++) { + const sind = data.depthSortedFacets[f].ind; + data.depthSortedIndices[f * 3] = indices[sind]; + data.depthSortedIndices[f * 3 + 1] = indices[sind + 1]; + data.depthSortedIndices[f * 3 + 2] = indices[sind + 2]; + } + this.updateIndices(data.depthSortedIndices, undefined, true); + } + return this; + } + /** + * Returns the facetLocalNormals array. + * The normals are expressed in the mesh local spac + * @returns an array of Vector3 + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getFacetLocalNormals() { + const facetData = this._internalAbstractMeshDataInfo._facetData; + if (!facetData.facetNormals) { + this.updateFacetData(); + } + return facetData.facetNormals; + } + /** + * Returns the facetLocalPositions array. + * The facet positions are expressed in the mesh local space + * @returns an array of Vector3 + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getFacetLocalPositions() { + const facetData = this._internalAbstractMeshDataInfo._facetData; + if (!facetData.facetPositions) { + this.updateFacetData(); + } + return facetData.facetPositions; + } + /** + * Returns the facetLocalPartitioning array + * @returns an array of array of numbers + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getFacetLocalPartitioning() { + const facetData = this._internalAbstractMeshDataInfo._facetData; + if (!facetData.facetPartitioning) { + this.updateFacetData(); + } + return facetData.facetPartitioning; + } + /** + * Returns the i-th facet position in the world system. + * This method allocates a new Vector3 per call + * @param i defines the facet index + * @returns a new Vector3 + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getFacetPosition(i) { + const pos = Vector3.Zero(); + this.getFacetPositionToRef(i, pos); + return pos; + } + /** + * Sets the reference Vector3 with the i-th facet position in the world system + * @param i defines the facet index + * @param ref defines the target vector + * @returns the current mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getFacetPositionToRef(i, ref) { + const localPos = this.getFacetLocalPositions()[i]; + const world = this.getWorldMatrix(); + Vector3.TransformCoordinatesToRef(localPos, world, ref); + return this; + } + /** + * Returns the i-th facet normal in the world system. + * This method allocates a new Vector3 per call + * @param i defines the facet index + * @returns a new Vector3 + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getFacetNormal(i) { + const norm = Vector3.Zero(); + this.getFacetNormalToRef(i, norm); + return norm; + } + /** + * Sets the reference Vector3 with the i-th facet normal in the world system + * @param i defines the facet index + * @param ref defines the target vector + * @returns the current mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getFacetNormalToRef(i, ref) { + const localNorm = this.getFacetLocalNormals()[i]; + Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref); + return this; + } + /** + * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system) + * @param x defines x coordinate + * @param y defines y coordinate + * @param z defines z coordinate + * @returns the array of facet indexes + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getFacetsAtLocalCoordinates(x, y, z) { + const bInfo = this.getBoundingInfo(); + const data = this._internalAbstractMeshDataInfo._facetData; + const ox = Math.floor(((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio) / data.bbSize.x); + const oy = Math.floor(((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio) / data.bbSize.y); + const oz = Math.floor(((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio) / data.bbSize.z); + if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) { + return null; + } + return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz]; + } + /** + * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found + * @param x defines x coordinate + * @param y defines y coordinate + * @param z defines z coordinate + * @param projected sets as the (x,y,z) world projection on the facet + * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned + * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position + * @returns the face index if found (or null instead) + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getClosestFacetAtCoordinates(x, y, z, projected, checkFace = false, facing = true) { + const world = this.getWorldMatrix(); + const invMat = TmpVectors.Matrix[5]; + world.invertToRef(invMat); + const invVect = TmpVectors.Vector3[8]; + Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space + const closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing); + if (projected) { + // transform the local computed projected vector to world coordinates + Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected); + } + return closest; + } + /** + * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found + * @param x defines x coordinate + * @param y defines y coordinate + * @param z defines z coordinate + * @param projected sets as the (x,y,z) local projection on the facet + * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned + * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position + * @returns the face index if found (or null instead) + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getClosestFacetAtLocalCoordinates(x, y, z, projected, checkFace = false, facing = true) { + let closest = null; + let tmpx = 0.0; + let tmpy = 0.0; + let tmpz = 0.0; + let d = 0.0; // tmp dot facet normal * facet position + let t0 = 0.0; + let projx = 0.0; + let projy = 0.0; + let projz = 0.0; + // Get all the facets in the same partitioning block than (x, y, z) + const facetPositions = this.getFacetLocalPositions(); + const facetNormals = this.getFacetLocalNormals(); + const facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z); + if (!facetsInBlock) { + return null; + } + // Get the closest facet to (x, y, z) + let shortest = Number.MAX_VALUE; // init distance vars + let tmpDistance = shortest; + let fib; // current facet in the block + let norm; // current facet normal + let p0; // current facet barycenter position + // loop on all the facets in the current partitioning block + for (let idx = 0; idx < facetsInBlock.length; idx++) { + fib = facetsInBlock[idx]; + norm = facetNormals[fib]; + p0 = facetPositions[fib]; + d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z; + if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) { + // compute (x,y,z) projection on the facet = (projx, projy, projz) + d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z; + t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z); + projx = x + norm.x * t0; + projy = y + norm.y * t0; + projz = z + norm.z * t0; + tmpx = projx - x; + tmpy = projy - y; + tmpz = projz - z; + tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet + if (tmpDistance < shortest) { + // just keep the closest facet to (x, y, z) + shortest = tmpDistance; + closest = fib; + if (projected) { + projected.x = projx; + projected.y = projy; + projected.z = projz; + } + } + } + } + return closest; + } + /** + * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals() + * @returns the parameters + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + getFacetDataParameters() { + return this._internalAbstractMeshDataInfo._facetData.facetParameters; + } + /** + * Disables the feature FacetData and frees the related memory + * @returns the current mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData + */ + disableFacetData() { + const facetData = this._internalAbstractMeshDataInfo._facetData; + if (facetData.facetDataEnabled) { + facetData.facetDataEnabled = false; + facetData.facetPositions = []; + facetData.facetNormals = []; + facetData.facetPartitioning = new Array(); + facetData.facetParameters = {}; + facetData.depthSortedIndices = new Uint32Array(0); + } + return this; + } + /** + * Updates the AbstractMesh indices array + * @param indices defines the data source + * @param offset defines the offset in the index buffer where to store the new data (can be null) + * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default) + * @returns the current mesh + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + updateIndices(indices, offset, gpuMemoryOnly = false) { + return this; + } + /** + * Creates new normals data for the mesh + * @param updatable defines if the normal vertex buffer must be flagged as updatable + * @returns the current mesh + */ + createNormals(updatable) { + const positions = this.getVerticesData(VertexBuffer.PositionKind); + const indices = this.getIndices(); + let normals; + if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) { + normals = this.getVerticesData(VertexBuffer.NormalKind); + } + else { + normals = []; + } + VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem }); + this.setVerticesData(VertexBuffer.NormalKind, normals, updatable); + return this; + } + /** + * Optimize the indices order so that we keep the faces with similar indices together + * @returns the current mesh + */ + async optimizeIndicesAsync() { + const indices = this.getIndices(); + if (!indices) { + return this; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + const { OptimizeIndices } = await Promise.resolve().then(() => mesh_vertexData_functions); + OptimizeIndices(indices); + this.setIndices(indices, this.getTotalVertices()); + return this; + } + /** + * Align the mesh with a normal + * @param normal defines the normal to use + * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default) + * @returns the current mesh + */ + alignWithNormal(normal, upDirection) { + if (!upDirection) { + upDirection = Axis.Y; + } + const axisX = TmpVectors.Vector3[0]; + const axisZ = TmpVectors.Vector3[1]; + Vector3.CrossToRef(upDirection, normal, axisZ); + Vector3.CrossToRef(normal, axisZ, axisX); + if (this.rotationQuaternion) { + Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion); + } + else { + Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation); + } + return this; + } + /** @internal */ + _checkOcclusionQuery() { + // Will be replaced by correct code if Occlusion queries are referenced + return false; + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Disables the mesh edge rendering mode + * @returns the currentAbstractMesh + */ + disableEdgesRendering() { + throw _WarnImport("EdgesRenderer"); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Enables the edge rendering mode on the mesh. + * This mode makes the mesh edges visible + * @param epsilon defines the maximal distance between two angles to detect a face + * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces + * @param options options to the edge renderer + * @returns the currentAbstractMesh + * @see https://www.babylonjs-playground.com/#19O9TU#0 + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + enableEdgesRendering(epsilon, checkVerticesInsteadOfIndices, options) { + throw _WarnImport("EdgesRenderer"); + } + /** + * This function returns all of the particle systems in the scene that use the mesh as an emitter. + * @returns an array of particle systems in the scene that use the mesh as an emitter + */ + getConnectedParticleSystems() { + return this._scene.particleSystems.filter((particleSystem) => particleSystem.emitter === this); + } +} +/** No occlusion */ +AbstractMesh.OCCLUSION_TYPE_NONE = 0; +/** Occlusion set to optimistic */ +AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1; +/** Occlusion set to strict */ +AbstractMesh.OCCLUSION_TYPE_STRICT = 2; +/** Use an accurate occlusion algorithm */ +AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0; +/** Use a conservative occlusion algorithm */ +AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1; +/** Default culling strategy : this is an exclusion test and it's the more accurate. + * Test order : + * Is the bounding sphere outside the frustum ? + * If not, are the bounding box vertices outside the frustum ? + * It not, then the cullable object is in the frustum. + */ +AbstractMesh.CULLINGSTRATEGY_STANDARD = 0; +/** Culling strategy : Bounding Sphere Only. + * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested. + * It's also less accurate than the standard because some not visible objects can still be selected. + * Test : is the bounding sphere outside the frustum ? + * If not, then the cullable object is in the frustum. + */ +AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1; +/** Culling strategy : Optimistic Inclusion. + * This in an inclusion test first, then the standard exclusion test. + * This can be faster when a cullable object is expected to be almost always in the camera frustum. + * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside. + * Anyway, it's as accurate as the standard strategy. + * Test : + * Is the cullable object bounding sphere center in the frustum ? + * If not, apply the default culling strategy. + */ +AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2; +/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only. + * This in an inclusion test first, then the bounding sphere only exclusion test. + * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum. + * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it. + * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy. + * Test : + * Is the cullable object bounding sphere center in the frustum ? + * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here. + */ +AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3; +__decorate([ + nativeOverride.filter((...[data, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData]) => !Array.isArray(data) && + !Array.isArray(matricesIndicesData) && + !Array.isArray(matricesWeightsData) && + !Array.isArray(matricesIndicesExtraData) && + !Array.isArray(matricesWeightsExtraData)) +], AbstractMesh, "_ApplySkeleton", null); +RegisterClass("BABYLON.AbstractMesh", AbstractMesh); + +/** + * Class that holds the different stencil states of a material + * Usage example: https://playground.babylonjs.com/#CW5PRI#10 + */ +class MaterialStencilState { + /** + * Creates a material stencil state instance + */ + constructor() { + this.reset(); + } + /** + * Resets all the stencil states to default values + */ + reset() { + this.enabled = false; + this.mask = 0xff; + this.func = 519; + this.funcRef = 1; + this.funcMask = 0xff; + this.opStencilFail = 7680; + this.opDepthFail = 7680; + this.opStencilDepthPass = 7681; + } + /** + * Gets or sets the stencil function + */ + get func() { + return this._func; + } + set func(value) { + this._func = value; + } + /** + * Gets or sets the stencil function reference + */ + get funcRef() { + return this._funcRef; + } + set funcRef(value) { + this._funcRef = value; + } + /** + * Gets or sets the stencil function mask + */ + get funcMask() { + return this._funcMask; + } + set funcMask(value) { + this._funcMask = value; + } + /** + * Gets or sets the operation when the stencil test fails + */ + get opStencilFail() { + return this._opStencilFail; + } + set opStencilFail(value) { + this._opStencilFail = value; + } + /** + * Gets or sets the operation when the depth test fails + */ + get opDepthFail() { + return this._opDepthFail; + } + set opDepthFail(value) { + this._opDepthFail = value; + } + /** + * Gets or sets the operation when the stencil+depth test succeeds + */ + get opStencilDepthPass() { + return this._opStencilDepthPass; + } + set opStencilDepthPass(value) { + this._opStencilDepthPass = value; + } + /** + * Gets or sets the stencil mask + */ + get mask() { + return this._mask; + } + set mask(value) { + this._mask = value; + } + /** + * Enables or disables the stencil test + */ + get enabled() { + return this._enabled; + } + set enabled(value) { + this._enabled = value; + } + /** + * Get the current class name, useful for serialization or dynamic coding. + * @returns "MaterialStencilState" + */ + getClassName() { + return "MaterialStencilState"; + } + /** + * Makes a duplicate of the current configuration into another one. + * @param stencilState defines stencil state where to copy the info + */ + copyTo(stencilState) { + SerializationHelper.Clone(() => stencilState, this); + } + /** + * Serializes this stencil configuration. + * @returns - An object with the serialized config. + */ + serialize() { + return SerializationHelper.Serialize(this); + } + /** + * Parses a stencil state configuration from a serialized object. + * @param source - Serialized object. + * @param scene Defines the scene we are parsing for + * @param rootUrl Defines the rootUrl to load from + */ + parse(source, scene, rootUrl) { + SerializationHelper.Parse(() => this, source, scene, rootUrl); + } +} +__decorate([ + serialize() +], MaterialStencilState.prototype, "func", null); +__decorate([ + serialize() +], MaterialStencilState.prototype, "funcRef", null); +__decorate([ + serialize() +], MaterialStencilState.prototype, "funcMask", null); +__decorate([ + serialize() +], MaterialStencilState.prototype, "opStencilFail", null); +__decorate([ + serialize() +], MaterialStencilState.prototype, "opDepthFail", null); +__decorate([ + serialize() +], MaterialStencilState.prototype, "opStencilDepthPass", null); +__decorate([ + serialize() +], MaterialStencilState.prototype, "mask", null); +__decorate([ + serialize() +], MaterialStencilState.prototype, "enabled", null); + +/** @internal */ +function addClipPlaneUniforms(uniforms) { + if (uniforms.indexOf("vClipPlane") === -1) { + uniforms.push("vClipPlane"); + } + if (uniforms.indexOf("vClipPlane2") === -1) { + uniforms.push("vClipPlane2"); + } + if (uniforms.indexOf("vClipPlane3") === -1) { + uniforms.push("vClipPlane3"); + } + if (uniforms.indexOf("vClipPlane4") === -1) { + uniforms.push("vClipPlane4"); + } + if (uniforms.indexOf("vClipPlane5") === -1) { + uniforms.push("vClipPlane5"); + } + if (uniforms.indexOf("vClipPlane6") === -1) { + uniforms.push("vClipPlane6"); + } +} +/** @internal */ +function prepareStringDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) { + const clipPlane = !!(primaryHolder.clipPlane ?? secondaryHolder.clipPlane); + const clipPlane2 = !!(primaryHolder.clipPlane2 ?? secondaryHolder.clipPlane2); + const clipPlane3 = !!(primaryHolder.clipPlane3 ?? secondaryHolder.clipPlane3); + const clipPlane4 = !!(primaryHolder.clipPlane4 ?? secondaryHolder.clipPlane4); + const clipPlane5 = !!(primaryHolder.clipPlane5 ?? secondaryHolder.clipPlane5); + const clipPlane6 = !!(primaryHolder.clipPlane6 ?? secondaryHolder.clipPlane6); + if (clipPlane) + defines.push("#define CLIPPLANE"); + if (clipPlane2) + defines.push("#define CLIPPLANE2"); + if (clipPlane3) + defines.push("#define CLIPPLANE3"); + if (clipPlane4) + defines.push("#define CLIPPLANE4"); + if (clipPlane5) + defines.push("#define CLIPPLANE5"); + if (clipPlane6) + defines.push("#define CLIPPLANE6"); +} +/** @internal */ +function prepareDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) { + let changed = false; + const clipPlane = !!(primaryHolder.clipPlane ?? secondaryHolder.clipPlane); + const clipPlane2 = !!(primaryHolder.clipPlane2 ?? secondaryHolder.clipPlane2); + const clipPlane3 = !!(primaryHolder.clipPlane3 ?? secondaryHolder.clipPlane3); + const clipPlane4 = !!(primaryHolder.clipPlane4 ?? secondaryHolder.clipPlane4); + const clipPlane5 = !!(primaryHolder.clipPlane5 ?? secondaryHolder.clipPlane5); + const clipPlane6 = !!(primaryHolder.clipPlane6 ?? secondaryHolder.clipPlane6); + // Do not factorize this code, it breaks browsers optimizations. + if (defines["CLIPPLANE"] !== clipPlane) { + defines["CLIPPLANE"] = clipPlane; + changed = true; + } + if (defines["CLIPPLANE2"] !== clipPlane2) { + defines["CLIPPLANE2"] = clipPlane2; + changed = true; + } + if (defines["CLIPPLANE3"] !== clipPlane3) { + defines["CLIPPLANE3"] = clipPlane3; + changed = true; + } + if (defines["CLIPPLANE4"] !== clipPlane4) { + defines["CLIPPLANE4"] = clipPlane4; + changed = true; + } + if (defines["CLIPPLANE5"] !== clipPlane5) { + defines["CLIPPLANE5"] = clipPlane5; + changed = true; + } + if (defines["CLIPPLANE6"] !== clipPlane6) { + defines["CLIPPLANE6"] = clipPlane6; + changed = true; + } + return changed; +} +/** @internal */ +function bindClipPlane(effect, primaryHolder, secondaryHolder) { + let clipPlane = primaryHolder.clipPlane ?? secondaryHolder.clipPlane; + setClipPlane(effect, "vClipPlane", clipPlane); + clipPlane = primaryHolder.clipPlane2 ?? secondaryHolder.clipPlane2; + setClipPlane(effect, "vClipPlane2", clipPlane); + clipPlane = primaryHolder.clipPlane3 ?? secondaryHolder.clipPlane3; + setClipPlane(effect, "vClipPlane3", clipPlane); + clipPlane = primaryHolder.clipPlane4 ?? secondaryHolder.clipPlane4; + setClipPlane(effect, "vClipPlane4", clipPlane); + clipPlane = primaryHolder.clipPlane5 ?? secondaryHolder.clipPlane5; + setClipPlane(effect, "vClipPlane5", clipPlane); + clipPlane = primaryHolder.clipPlane6 ?? secondaryHolder.clipPlane6; + setClipPlane(effect, "vClipPlane6", clipPlane); +} +function setClipPlane(effect, uniformName, clipPlane) { + if (clipPlane) { + effect.setFloat4(uniformName, clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); + } +} + +// Temps +const _TempFogColor = Color3.Black(); +const _TmpMorphInfluencers = { + NUM_MORPH_INFLUENCERS: 0, + NORMAL: false, + TANGENT: false, + UV: false, + UV2: false, + COLOR: false, +}; +/** + * Binds the logarithmic depth information from the scene to the effect for the given defines. + * @param defines The generated defines used in the effect + * @param effect The effect we are binding the data to + * @param scene The scene we are willing to render with logarithmic scale for + */ +function BindLogDepth(defines, effect, scene) { + if (!defines || defines["LOGARITHMICDEPTH"] || (defines.indexOf && defines.indexOf("LOGARITHMICDEPTH") >= 0)) { + const camera = scene.activeCamera; + if (camera.mode === 1) { + Logger.Error("Logarithmic depth is not compatible with orthographic cameras!", 20); + } + effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(camera.maxZ + 1.0) / Math.LN2)); + } +} +/** + * Binds the fog information from the scene to the effect for the given mesh. + * @param scene The scene the lights belongs to + * @param mesh The mesh we are binding the information to render + * @param effect The effect we are binding the data to + * @param linearSpace Defines if the fog effect is applied in linear space + */ +function BindFogParameters(scene, mesh, effect, linearSpace = false) { + if (effect && scene.fogEnabled && (!mesh || mesh.applyFog) && scene.fogMode !== 0) { + effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); + // Convert fog color to linear space if used in a linear space computed shader. + if (linearSpace) { + scene.fogColor.toLinearSpaceToRef(_TempFogColor, scene.getEngine().useExactSrgbConversions); + effect.setColor3("vFogColor", _TempFogColor); + } + else { + effect.setColor3("vFogColor", scene.fogColor); + } + } +} +/** + * Prepares the list of attributes and defines required for morph targets. + * @param morphTargetManager The manager for the morph targets + * @param defines The current list of defines + * @param attribs The current list of attributes + * @param mesh The mesh to prepare the defines and attributes for + * @param usePositionMorph Whether the position morph target is used + * @param useNormalMorph Whether the normal morph target is used + * @param useTangentMorph Whether the tangent morph target is used + * @param useUVMorph Whether the UV morph target is used + * @param useUV2Morph Whether the UV2 morph target is used + * @param useColorMorph Whether the color morph target is used + * @returns The maxSimultaneousMorphTargets for the effect + */ +function PrepareDefinesAndAttributesForMorphTargets(morphTargetManager, defines, attribs, mesh, usePositionMorph, useNormalMorph, useTangentMorph, useUVMorph, useUV2Morph, useColorMorph) { + const numMorphInfluencers = morphTargetManager.numMaxInfluencers || morphTargetManager.numInfluencers; + if (numMorphInfluencers <= 0) { + return 0; + } + defines.push("#define MORPHTARGETS"); + if (morphTargetManager.hasPositions) + defines.push("#define MORPHTARGETTEXTURE_HASPOSITIONS"); + if (morphTargetManager.hasNormals) + defines.push("#define MORPHTARGETTEXTURE_HASNORMALS"); + if (morphTargetManager.hasTangents) + defines.push("#define MORPHTARGETTEXTURE_HASTANGENTS"); + if (morphTargetManager.hasUVs) + defines.push("#define MORPHTARGETTEXTURE_HASUVS"); + if (morphTargetManager.hasUV2s) + defines.push("#define MORPHTARGETTEXTURE_HASUV2S"); + if (morphTargetManager.hasColors) + defines.push("#define MORPHTARGETTEXTURE_HASCOLORS"); + if (morphTargetManager.supportsPositions && usePositionMorph) + defines.push("#define MORPHTARGETS_POSITION"); + if (morphTargetManager.supportsNormals && useNormalMorph) + defines.push("#define MORPHTARGETS_NORMAL"); + if (morphTargetManager.supportsTangents && useTangentMorph) + defines.push("#define MORPHTARGETS_TANGENT"); + if (morphTargetManager.supportsUVs && useUVMorph) + defines.push("#define MORPHTARGETS_UV"); + if (morphTargetManager.supportsUV2s && useUV2Morph) + defines.push("#define MORPHTARGETS_UV2"); + if (morphTargetManager.supportsColors && useColorMorph) + defines.push("#define MORPHTARGETS_COLOR"); + defines.push("#define NUM_MORPH_INFLUENCERS " + numMorphInfluencers); + if (morphTargetManager.isUsingTextureForTargets) { + defines.push("#define MORPHTARGETS_TEXTURE"); + } + _TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = numMorphInfluencers; + _TmpMorphInfluencers.NORMAL = useNormalMorph; + _TmpMorphInfluencers.TANGENT = useTangentMorph; + _TmpMorphInfluencers.UV = useUVMorph; + _TmpMorphInfluencers.UV2 = useUV2Morph; + _TmpMorphInfluencers.COLOR = useColorMorph; + PrepareAttributesForMorphTargets(attribs, mesh, _TmpMorphInfluencers, usePositionMorph); + return numMorphInfluencers; +} +/** + * Prepares the list of attributes required for morph targets according to the effect defines. + * @param attribs The current list of supported attribs + * @param mesh The mesh to prepare the morph targets attributes for + * @param defines The current Defines of the effect + * @param usePositionMorph Whether the position morph target is used + */ +function PrepareAttributesForMorphTargets(attribs, mesh, defines, usePositionMorph = true) { + const influencers = defines["NUM_MORPH_INFLUENCERS"]; + if (influencers > 0 && EngineStore.LastCreatedEngine) { + const maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs; + const manager = mesh.morphTargetManager; + if (manager?.isUsingTextureForTargets) { + return; + } + const position = manager && manager.supportsPositions && usePositionMorph; + const normal = manager && manager.supportsNormals && defines["NORMAL"]; + const tangent = manager && manager.supportsTangents && defines["TANGENT"]; + const uv = manager && manager.supportsUVs && defines["UV1"]; + const uv2 = manager && manager.supportsUV2s && defines["UV2"]; + const color = manager && manager.supportsColors && defines["COLOR"]; + for (let index = 0; index < influencers; index++) { + if (position) { + attribs.push(`position` + index); + } + if (normal) { + attribs.push(`normal` + index); + } + if (tangent) { + attribs.push(`tangent` + index); + } + if (uv) { + attribs.push(`uv` + "_" + index); + } + if (uv2) { + attribs.push(`uv2` + "_" + index); + } + if (color) { + attribs.push(`color` + index); + } + if (attribs.length > maxAttributesCount) { + Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name); + } + } + } +} +/** + * Add the list of attributes required for instances to the attribs array. + * @param attribs The current list of supported attribs + * @param needsPreviousMatrices If the shader needs previous matrices + */ +function PushAttributesForInstances(attribs, needsPreviousMatrices = false) { + attribs.push("world0"); + attribs.push("world1"); + attribs.push("world2"); + attribs.push("world3"); + if (needsPreviousMatrices) { + attribs.push("previousWorld0"); + attribs.push("previousWorld1"); + attribs.push("previousWorld2"); + attribs.push("previousWorld3"); + } +} +/** + * Binds the morph targets information from the mesh to the effect. + * @param abstractMesh The mesh we are binding the information to render + * @param effect The effect we are binding the data to + */ +function BindMorphTargetParameters(abstractMesh, effect) { + const manager = abstractMesh.morphTargetManager; + if (!abstractMesh || !manager) { + return; + } + effect.setFloatArray("morphTargetInfluences", manager.influences); +} +/** + * Binds the scene's uniform buffer to the effect. + * @param effect defines the effect to bind to the scene uniform buffer + * @param sceneUbo defines the uniform buffer storing scene data + */ +function BindSceneUniformBuffer(effect, sceneUbo) { + sceneUbo.bindToEffect(effect, "Scene"); +} +/** + * Helps preparing the defines values about the UVs in used in the effect. + * UVs are shared as much as we can across channels in the shaders. + * @param texture The texture we are preparing the UVs for + * @param defines The defines to update + * @param key The channel key "diffuse", "specular"... used in the shader + */ +function PrepareDefinesForMergedUV(texture, defines, key) { + defines._needUVs = true; + defines[key] = true; + if (texture.optimizeUVAllocation && texture.getTextureMatrix().isIdentityAs3x2()) { + defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1; + defines["MAINUV" + (texture.coordinatesIndex + 1)] = true; + } + else { + defines[key + "DIRECTUV"] = 0; + } +} +/** + * Binds a texture matrix value to its corresponding uniform + * @param texture The texture to bind the matrix for + * @param uniformBuffer The uniform buffer receiving the data + * @param key The channel key "diffuse", "specular"... used in the shader + */ +function BindTextureMatrix(texture, uniformBuffer, key) { + const matrix = texture.getTextureMatrix(); + uniformBuffer.updateMatrix(key + "Matrix", matrix); +} +/** + * Prepares the list of attributes required for baked vertex animations according to the effect defines. + * @param attribs The current list of supported attribs + * @param mesh The mesh to prepare for baked vertex animations + * @param defines The current Defines of the effect + */ +function PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines) { + const enabled = defines["BAKED_VERTEX_ANIMATION_TEXTURE"] && defines["INSTANCES"]; + if (enabled) { + attribs.push("bakedVertexAnimationSettingsInstanced"); + } +} +// Copies the bones transformation matrices into the target array and returns the target's reference +function _CopyBonesTransformationMatrices(source, target) { + target.set(source); + return target; +} +/** + * Binds the bones information from the mesh to the effect. + * @param mesh The mesh we are binding the information to render + * @param effect The effect we are binding the data to + * @param prePassConfiguration Configuration for the prepass, in case prepass is activated + */ +function BindBonesParameters(mesh, effect, prePassConfiguration) { + if (!effect || !mesh) { + return; + } + if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) { + mesh.computeBonesUsingShaders = false; + } + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + const skeleton = mesh.skeleton; + if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) { + const boneTexture = skeleton.getTransformMatrixTexture(mesh); + effect.setTexture("boneSampler", boneTexture); + effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); + } + else { + const matrices = skeleton.getTransformMatrices(mesh); + if (matrices) { + effect.setMatrices("mBones", matrices); + if (prePassConfiguration && mesh.getScene().prePassRenderer && mesh.getScene().prePassRenderer.getIndex(2)) { + if (!prePassConfiguration.previousBones[mesh.uniqueId]) { + prePassConfiguration.previousBones[mesh.uniqueId] = matrices.slice(); + } + effect.setMatrices("mPreviousBones", prePassConfiguration.previousBones[mesh.uniqueId]); + _CopyBonesTransformationMatrices(matrices, prePassConfiguration.previousBones[mesh.uniqueId]); + } + } + } + } +} +/** + * Binds the lights information from the scene to the effect for the given mesh. + * @param light Light to bind + * @param lightIndex Light index + * @param scene The scene where the light belongs to + * @param effect The effect we are binding the data to + * @param useSpecular Defines if specular is supported + * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows + */ +function BindLight(light, lightIndex, scene, effect, useSpecular, receiveShadows = true) { + light._bindLight(lightIndex, scene, effect, useSpecular, receiveShadows); +} +/** + * Binds the lights information from the scene to the effect for the given mesh. + * @param scene The scene the lights belongs to + * @param mesh The mesh we are binding the information to render + * @param effect The effect we are binding the data to + * @param defines The generated defines for the effect + * @param maxSimultaneousLights The maximum number of light that can be bound to the effect + */ +function BindLights(scene, mesh, effect, defines, maxSimultaneousLights = 4) { + const len = Math.min(mesh.lightSources.length, maxSimultaneousLights); + for (let i = 0; i < len; i++) { + const light = mesh.lightSources[i]; + BindLight(light, i, scene, effect, typeof defines === "boolean" ? defines : defines["SPECULARTERM"], mesh.receiveShadows); + } +} +/** + * Prepares the list of attributes required for bones according to the effect defines. + * @param attribs The current list of supported attribs + * @param mesh The mesh to prepare the bones attributes for + * @param defines The current Defines of the effect + * @param fallbacks The current effect fallback strategy + */ +function PrepareAttributesForBones(attribs, mesh, defines, fallbacks) { + if (defines["NUM_BONE_INFLUENCERS"] > 0) { + fallbacks.addCPUSkinningFallback(0, mesh); + attribs.push(`matricesIndices`); + attribs.push(`matricesWeights`); + if (defines["NUM_BONE_INFLUENCERS"] > 4) { + attribs.push(`matricesIndicesExtra`); + attribs.push(`matricesWeightsExtra`); + } + } +} +/** + * Check and prepare the list of attributes required for instances according to the effect defines. + * @param attribs The current list of supported attribs + * @param defines The current MaterialDefines of the effect + */ +function PrepareAttributesForInstances(attribs, defines) { + if (defines["INSTANCES"] || defines["THIN_INSTANCES"]) { + PushAttributesForInstances(attribs, !!defines["PREPASS_VELOCITY"]); + } + if (defines.INSTANCESCOLOR) { + attribs.push(`instanceColor`); + } +} +/** + * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality) + * @param defines The defines to update while falling back + * @param fallbacks The authorized effect fallbacks + * @param maxSimultaneousLights The maximum number of lights allowed + * @param rank the current rank of the Effect + * @returns The newly affected rank + */ +function HandleFallbacksForShadows(defines, fallbacks, maxSimultaneousLights = 4, rank = 0) { + let lightFallbackRank = 0; + for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) { + if (!defines["LIGHT" + lightIndex]) { + break; + } + if (lightIndex > 0) { + lightFallbackRank = rank + lightIndex; + fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex); + } + if (!defines["SHADOWS"]) { + if (defines["SHADOW" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOW" + lightIndex); + } + if (defines["SHADOWPCF" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex); + } + if (defines["SHADOWPCSS" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex); + } + if (defines["SHADOWPOISSON" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex); + } + if (defines["SHADOWESM" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOWESM" + lightIndex); + } + if (defines["SHADOWCLOSEESM" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOWCLOSEESM" + lightIndex); + } + } + } + return lightFallbackRank++; +} +/** + * Gets the current status of the fog (should it be enabled?) + * @param mesh defines the mesh to evaluate for fog support + * @param scene defines the hosting scene + * @returns true if fog must be enabled + */ +function GetFogState(mesh, scene) { + return scene.fogEnabled && mesh.applyFog && scene.fogMode !== 0; +} +/** + * Helper used to prepare the list of defines associated with misc. values for shader compilation + * @param mesh defines the current mesh + * @param scene defines the current scene + * @param useLogarithmicDepth defines if logarithmic depth has to be turned on + * @param pointsCloud defines if point cloud rendering has to be turned on + * @param fogEnabled defines if fog has to be turned on + * @param alphaTest defines if alpha testing has to be turned on + * @param defines defines the current list of defines + * @param applyDecalAfterDetail Defines if the decal is applied after or before the detail + */ +function PrepareDefinesForMisc(mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines, applyDecalAfterDetail = false) { + if (defines._areMiscDirty) { + defines["LOGARITHMICDEPTH"] = useLogarithmicDepth; + defines["POINTSIZE"] = pointsCloud; + defines["FOG"] = fogEnabled && GetFogState(mesh, scene); + defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling; + defines["ALPHATEST"] = alphaTest; + defines["DECAL_AFTER_DETAIL"] = applyDecalAfterDetail; + } +} +/** + * Prepares the defines related to the light information passed in parameter + * @param scene The scene we are intending to draw + * @param mesh The mesh the effect is compiling for + * @param defines The defines to update + * @param specularSupported Specifies whether specular is supported or not (override lights data) + * @param maxSimultaneousLights Specifies how manuy lights can be added to the effect at max + * @param disableLighting Specifies whether the lighting is disabled (override scene and light) + * @returns true if normals will be required for the rest of the effect + */ +function PrepareDefinesForLights(scene, mesh, defines, specularSupported, maxSimultaneousLights = 4, disableLighting = false) { + if (!defines._areLightsDirty) { + return defines._needNormals; + } + let lightIndex = 0; + const state = { + needNormals: defines._needNormals, // prevents overriding previous reflection or other needs for normals + needRebuild: false, + lightmapMode: false, + shadowEnabled: false, + specularEnabled: false, + }; + if (scene.lightsEnabled && !disableLighting) { + for (const light of mesh.lightSources) { + PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state); + lightIndex++; + if (lightIndex === maxSimultaneousLights) { + break; + } + } + } + defines["SPECULARTERM"] = state.specularEnabled; + defines["SHADOWS"] = state.shadowEnabled; + // Resetting all other lights if any + for (let index = lightIndex; index < maxSimultaneousLights; index++) { + if (defines["LIGHT" + index] !== undefined) { + defines["LIGHT" + index] = false; + defines["HEMILIGHT" + index] = false; + defines["POINTLIGHT" + index] = false; + defines["DIRLIGHT" + index] = false; + defines["SPOTLIGHT" + index] = false; + defines["AREALIGHT" + index] = false; + defines["SHADOW" + index] = false; + defines["SHADOWCSM" + index] = false; + defines["SHADOWCSMDEBUG" + index] = false; + defines["SHADOWCSMNUM_CASCADES" + index] = false; + defines["SHADOWCSMUSESHADOWMAXZ" + index] = false; + defines["SHADOWCSMNOBLEND" + index] = false; + defines["SHADOWCSM_RIGHTHANDED" + index] = false; + defines["SHADOWPCF" + index] = false; + defines["SHADOWPCSS" + index] = false; + defines["SHADOWPOISSON" + index] = false; + defines["SHADOWESM" + index] = false; + defines["SHADOWCLOSEESM" + index] = false; + defines["SHADOWCUBE" + index] = false; + defines["SHADOWLOWQUALITY" + index] = false; + defines["SHADOWMEDIUMQUALITY" + index] = false; + } + } + const caps = scene.getEngine().getCaps(); + if (defines["SHADOWFLOAT"] === undefined) { + state.needRebuild = true; + } + defines["SHADOWFLOAT"] = + state.shadowEnabled && ((caps.textureFloatRender && caps.textureFloatLinearFiltering) || (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering)); + defines["LIGHTMAPEXCLUDED"] = state.lightmapMode; + if (state.needRebuild) { + defines.rebuild(); + } + return state.needNormals; +} +/** + * Prepares the defines related to the light information passed in parameter + * @param scene The scene we are intending to draw + * @param mesh The mesh the effect is compiling for + * @param light The light the effect is compiling for + * @param lightIndex The index of the light + * @param defines The defines to update + * @param specularSupported Specifies whether specular is supported or not (override lights data) + * @param state Defines the current state regarding what is needed (normals, etc...) + * @param state.needNormals + * @param state.needRebuild + * @param state.shadowEnabled + * @param state.specularEnabled + * @param state.lightmapMode + */ +function PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state) { + state.needNormals = true; + if (defines["LIGHT" + lightIndex] === undefined) { + state.needRebuild = true; + } + defines["LIGHT" + lightIndex] = true; + defines["SPOTLIGHT" + lightIndex] = false; + defines["HEMILIGHT" + lightIndex] = false; + defines["POINTLIGHT" + lightIndex] = false; + defines["DIRLIGHT" + lightIndex] = false; + defines["AREALIGHT" + lightIndex] = false; + light.prepareLightSpecificDefines(defines, lightIndex); + // FallOff. + defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false; + defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false; + defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false; + switch (light.falloffType) { + case LightConstants.FALLOFF_GLTF: + defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true; + break; + case LightConstants.FALLOFF_PHYSICAL: + defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true; + break; + case LightConstants.FALLOFF_STANDARD: + defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true; + break; + } + // Specular + if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) { + state.specularEnabled = true; + } + // Shadows + defines["SHADOW" + lightIndex] = false; + defines["SHADOWCSM" + lightIndex] = false; + defines["SHADOWCSMDEBUG" + lightIndex] = false; + defines["SHADOWCSMNUM_CASCADES" + lightIndex] = false; + defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = false; + defines["SHADOWCSMNOBLEND" + lightIndex] = false; + defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = false; + defines["SHADOWPCF" + lightIndex] = false; + defines["SHADOWPCSS" + lightIndex] = false; + defines["SHADOWPOISSON" + lightIndex] = false; + defines["SHADOWESM" + lightIndex] = false; + defines["SHADOWCLOSEESM" + lightIndex] = false; + defines["SHADOWCUBE" + lightIndex] = false; + defines["SHADOWLOWQUALITY" + lightIndex] = false; + defines["SHADOWMEDIUMQUALITY" + lightIndex] = false; + if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) { + const shadowGenerator = light.getShadowGenerator(scene.activeCamera) ?? light.getShadowGenerator(); + if (shadowGenerator) { + const shadowMap = shadowGenerator.getShadowMap(); + if (shadowMap) { + if (shadowMap.renderList && shadowMap.renderList.length > 0) { + state.shadowEnabled = true; + shadowGenerator.prepareDefines(defines, lightIndex); + } + } + } + } + if (light.lightmapMode != LightConstants.LIGHTMAP_DEFAULT) { + state.lightmapMode = true; + defines["LIGHTMAPEXCLUDED" + lightIndex] = true; + defines["LIGHTMAPNOSPECULAR" + lightIndex] = light.lightmapMode == LightConstants.LIGHTMAP_SHADOWSONLY; + } + else { + defines["LIGHTMAPEXCLUDED" + lightIndex] = false; + defines["LIGHTMAPNOSPECULAR" + lightIndex] = false; + } +} +/** + * Helper used to prepare the list of defines associated with frame values for shader compilation + * @param scene defines the current scene + * @param engine defines the current engine + * @param material defines the material we are compiling the shader for + * @param defines specifies the list of active defines + * @param useInstances defines if instances have to be turned on + * @param useClipPlane defines if clip plane have to be turned on + * @param useThinInstances defines if thin instances have to be turned on + */ +function PrepareDefinesForFrameBoundValues(scene, engine, material, defines, useInstances, useClipPlane = null, useThinInstances = false) { + let changed = PrepareDefinesForCamera(scene, defines); + if (useClipPlane !== false) { + changed = prepareDefinesForClipPlanes(material, scene, defines); + } + if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) { + defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"]; + changed = true; + } + if (defines["INSTANCES"] !== useInstances) { + defines["INSTANCES"] = useInstances; + changed = true; + } + if (defines["THIN_INSTANCES"] !== useThinInstances) { + defines["THIN_INSTANCES"] = useThinInstances; + changed = true; + } + if (changed) { + defines.markAsUnprocessed(); + } +} +/** + * Prepares the defines for bones + * @param mesh The mesh containing the geometry data we will draw + * @param defines The defines to update + */ +function PrepareDefinesForBones(mesh, defines) { + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers; + const materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined; + if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) { + defines["BONETEXTURE"] = true; + } + else { + defines["BonesPerMesh"] = mesh.skeleton.bones.length + 1; + defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined; + const prePassRenderer = mesh.getScene().prePassRenderer; + if (prePassRenderer && prePassRenderer.enabled) { + const nonExcluded = prePassRenderer.excludedSkinnedMesh.indexOf(mesh) === -1; + defines["BONES_VELOCITY_ENABLED"] = nonExcluded; + } + } + } + else { + defines["NUM_BONE_INFLUENCERS"] = 0; + defines["BonesPerMesh"] = 0; + if (defines["BONETEXTURE"] !== undefined) { + defines["BONETEXTURE"] = false; + } + } +} +/** + * Prepares the defines for morph targets + * @param mesh The mesh containing the geometry data we will draw + * @param defines The defines to update + */ +function PrepareDefinesForMorphTargets(mesh, defines) { + const manager = mesh.morphTargetManager; + if (manager) { + defines["MORPHTARGETS_UV"] = manager.supportsUVs && defines["UV1"]; + defines["MORPHTARGETS_UV2"] = manager.supportsUV2s && defines["UV2"]; + defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"]; + defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"]; + defines["MORPHTARGETS_POSITION"] = manager.supportsPositions; + defines["MORPHTARGETS_COLOR"] = manager.supportsColors; + defines["MORPHTARGETTEXTURE_HASUVS"] = manager.hasUVs; + defines["MORPHTARGETTEXTURE_HASUV2S"] = manager.hasUV2s; + defines["MORPHTARGETTEXTURE_HASTANGENTS"] = manager.hasTangents; + defines["MORPHTARGETTEXTURE_HASNORMALS"] = manager.hasNormals; + defines["MORPHTARGETTEXTURE_HASPOSITIONS"] = manager.hasPositions; + defines["MORPHTARGETTEXTURE_HASCOLORS"] = manager.hasColors; + defines["NUM_MORPH_INFLUENCERS"] = manager.numMaxInfluencers || manager.numInfluencers; + defines["MORPHTARGETS"] = defines["NUM_MORPH_INFLUENCERS"] > 0; + defines["MORPHTARGETS_TEXTURE"] = manager.isUsingTextureForTargets; + } + else { + defines["MORPHTARGETS_UV"] = false; + defines["MORPHTARGETS_UV2"] = false; + defines["MORPHTARGETS_TANGENT"] = false; + defines["MORPHTARGETS_NORMAL"] = false; + defines["MORPHTARGETS_POSITION"] = false; + defines["MORPHTARGETS_COLOR"] = false; + defines["MORPHTARGETTEXTURE_HASUVS"] = false; + defines["MORPHTARGETTEXTURE_HASUV2S"] = false; + defines["MORPHTARGETTEXTURE_HASTANGENTS"] = false; + defines["MORPHTARGETTEXTURE_HASNORMALS"] = false; + defines["MORPHTARGETTEXTURE_HASPOSITIONS"] = false; + defines["MORPHTARGETTEXTURE_HAS_COLORS"] = false; + defines["MORPHTARGETS"] = false; + defines["NUM_MORPH_INFLUENCERS"] = 0; + } +} +/** + * Prepares the defines for baked vertex animation + * @param mesh The mesh containing the geometry data we will draw + * @param defines The defines to update + */ +function PrepareDefinesForBakedVertexAnimation(mesh, defines) { + const manager = mesh.bakedVertexAnimationManager; + defines["BAKED_VERTEX_ANIMATION_TEXTURE"] = manager && manager.isEnabled ? true : false; +} +/** + * Prepares the defines used in the shader depending on the attributes data available in the mesh + * @param mesh The mesh containing the geometry data we will draw + * @param defines The defines to update + * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info) + * @param useBones Precise whether bones should be used or not (override mesh info) + * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info) + * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info) + * @param useBakedVertexAnimation Precise whether baked vertex animation should be used or not (override mesh info) + * @returns false if defines are considered not dirty and have not been checked + */ +function PrepareDefinesForAttributes(mesh, defines, useVertexColor, useBones, useMorphTargets = false, useVertexAlpha = true, useBakedVertexAnimation = true) { + if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) { + return false; + } + defines._normals = defines._needNormals; + defines._uvs = defines._needUVs; + defines["NORMAL"] = defines._needNormals && mesh.isVerticesDataPresent(`normal`); + if (defines._needNormals && mesh.isVerticesDataPresent(`tangent`)) { + defines["TANGENT"] = true; + } + for (let i = 1; i <= 6; ++i) { + defines["UV" + i] = defines._needUVs ? mesh.isVerticesDataPresent(`uv${i === 1 ? "" : i}`) : false; + } + if (useVertexColor) { + const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(`color`); + defines["VERTEXCOLOR"] = hasVertexColors; + defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha; + } + if (mesh.isVerticesDataPresent(`instanceColor`) && (mesh.hasInstances || mesh.hasThinInstances)) { + defines["INSTANCESCOLOR"] = true; + } + if (useBones) { + PrepareDefinesForBones(mesh, defines); + } + if (useMorphTargets) { + PrepareDefinesForMorphTargets(mesh, defines); + } + if (useBakedVertexAnimation) { + PrepareDefinesForBakedVertexAnimation(mesh, defines); + } + return true; +} +/** + * Prepares the defines related to multiview + * @param scene The scene we are intending to draw + * @param defines The defines to update + */ +function PrepareDefinesForMultiview(scene, defines) { + if (scene.activeCamera) { + const previousMultiview = defines.MULTIVIEW; + defines.MULTIVIEW = scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1; + if (defines.MULTIVIEW != previousMultiview) { + defines.markAsUnprocessed(); + } + } +} +/** + * Prepares the defines related to order independant transparency + * @param scene The scene we are intending to draw + * @param defines The defines to update + * @param needAlphaBlending Determines if the material needs alpha blending + */ +function PrepareDefinesForOIT(scene, defines, needAlphaBlending) { + const previousDefine = defines.ORDER_INDEPENDENT_TRANSPARENCY; + const previousDefine16Bits = defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS; + defines.ORDER_INDEPENDENT_TRANSPARENCY = scene.useOrderIndependentTransparency && needAlphaBlending; + defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !scene.getEngine().getCaps().textureFloatLinearFiltering; + if (previousDefine !== defines.ORDER_INDEPENDENT_TRANSPARENCY || previousDefine16Bits !== defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS) { + defines.markAsUnprocessed(); + } +} +/** + * Prepares the defines related to the prepass + * @param scene The scene we are intending to draw + * @param defines The defines to update + * @param canRenderToMRT Indicates if this material renders to several textures in the prepass + */ +function PrepareDefinesForPrePass(scene, defines, canRenderToMRT) { + const previousPrePass = defines.PREPASS; + if (!defines._arePrePassDirty) { + return; + } + const texturesList = [ + { + type: 1, + define: "PREPASS_POSITION", + index: "PREPASS_POSITION_INDEX", + }, + { + type: 9, + define: "PREPASS_LOCAL_POSITION", + index: "PREPASS_LOCAL_POSITION_INDEX", + }, + { + type: 2, + define: "PREPASS_VELOCITY", + index: "PREPASS_VELOCITY_INDEX", + }, + { + type: 11, + define: "PREPASS_VELOCITY_LINEAR", + index: "PREPASS_VELOCITY_LINEAR_INDEX", + }, + { + type: 3, + define: "PREPASS_REFLECTIVITY", + index: "PREPASS_REFLECTIVITY_INDEX", + }, + { + type: 0, + define: "PREPASS_IRRADIANCE", + index: "PREPASS_IRRADIANCE_INDEX", + }, + { + type: 7, + define: "PREPASS_ALBEDO_SQRT", + index: "PREPASS_ALBEDO_SQRT_INDEX", + }, + { + type: 5, + define: "PREPASS_DEPTH", + index: "PREPASS_DEPTH_INDEX", + }, + { + type: 10, + define: "PREPASS_SCREENSPACE_DEPTH", + index: "PREPASS_SCREENSPACE_DEPTH_INDEX", + }, + { + type: 6, + define: "PREPASS_NORMAL", + index: "PREPASS_NORMAL_INDEX", + }, + { + type: 8, + define: "PREPASS_WORLD_NORMAL", + index: "PREPASS_WORLD_NORMAL_INDEX", + }, + ]; + if (scene.prePassRenderer && scene.prePassRenderer.enabled && canRenderToMRT) { + defines.PREPASS = true; + defines.SCENE_MRT_COUNT = scene.prePassRenderer.mrtCount; + defines.PREPASS_NORMAL_WORLDSPACE = scene.prePassRenderer.generateNormalsInWorldSpace; + defines.PREPASS_COLOR = true; + defines.PREPASS_COLOR_INDEX = 0; + for (let i = 0; i < texturesList.length; i++) { + const index = scene.prePassRenderer.getIndex(texturesList[i].type); + if (index !== -1) { + defines[texturesList[i].define] = true; + defines[texturesList[i].index] = index; + } + else { + defines[texturesList[i].define] = false; + } + } + } + else { + defines.PREPASS = false; + for (let i = 0; i < texturesList.length; i++) { + defines[texturesList[i].define] = false; + } + } + if (defines.PREPASS != previousPrePass) { + defines.markAsUnprocessed(); + defines.markAsImageProcessingDirty(); + } +} +/** + * Helper used to prepare the defines relative to the active camera + * @param scene defines the current scene + * @param defines specifies the list of active defines + * @returns true if the defines have been updated, else false + */ +function PrepareDefinesForCamera(scene, defines) { + let changed = false; + if (scene.activeCamera) { + const wasOrtho = defines["CAMERA_ORTHOGRAPHIC"] ? 1 : 0; + const wasPersp = defines["CAMERA_PERSPECTIVE"] ? 1 : 0; + const isOrtho = scene.activeCamera.mode === 1 ? 1 : 0; + const isPersp = scene.activeCamera.mode === 0 ? 1 : 0; + if (wasOrtho ^ isOrtho || wasPersp ^ isPersp) { + defines["CAMERA_ORTHOGRAPHIC"] = isOrtho === 1; + defines["CAMERA_PERSPECTIVE"] = isPersp === 1; + changed = true; + } + } + return changed; +} +/** + * Prepares the uniforms and samplers list to be used in the effect (for a specific light) + * @param lightIndex defines the light index + * @param uniformsList The uniform list + * @param samplersList The sampler list + * @param projectedLightTexture defines if projected texture must be used + * @param uniformBuffersList defines an optional list of uniform buffers + * @param updateOnlyBuffersList True to only update the uniformBuffersList array + * @param iesLightTexture defines if IES texture must be used + */ +function PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, projectedLightTexture, uniformBuffersList = null, updateOnlyBuffersList = false, iesLightTexture = false) { + if (uniformBuffersList) { + uniformBuffersList.push("Light" + lightIndex); + } + if (updateOnlyBuffersList) { + return; + } + uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightWidth" + lightIndex, "vLightHeight" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex); + samplersList.push("shadowTexture" + lightIndex); + samplersList.push("depthTexture" + lightIndex); + uniformsList.push("viewFrustumZ" + lightIndex, "cascadeBlendFactor" + lightIndex, "lightSizeUVCorrection" + lightIndex, "depthCorrection" + lightIndex, "penumbraDarkness" + lightIndex, "frustumLengths" + lightIndex); + if (projectedLightTexture) { + samplersList.push("projectionLightTexture" + lightIndex); + uniformsList.push("textureProjectionMatrix" + lightIndex); + } + if (iesLightTexture) { + samplersList.push("iesLightTexture" + lightIndex); + } +} +/** + * Prepares the uniforms and samplers list to be used in the effect + * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the list and extra information + * @param samplersList The sampler list + * @param defines The defines helping in the list generation + * @param maxSimultaneousLights The maximum number of simultaneous light allowed in the effect + */ +function PrepareUniformsAndSamplersList(uniformsListOrOptions, samplersList, defines, maxSimultaneousLights = 4) { + let uniformsList; + let uniformBuffersList; + if (uniformsListOrOptions.uniformsNames) { + const options = uniformsListOrOptions; + uniformsList = options.uniformsNames; + uniformBuffersList = options.uniformBuffersNames; + samplersList = options.samplers; + defines = options.defines; + maxSimultaneousLights = options.maxSimultaneousLights || 0; + } + else { + uniformsList = uniformsListOrOptions; + if (!samplersList) { + samplersList = []; + } + } + for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) { + if (!defines["LIGHT" + lightIndex]) { + break; + } + PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffersList, false, defines["IESLIGHTTEXTURE" + lightIndex]); + } + if (defines["NUM_MORPH_INFLUENCERS"]) { + uniformsList.push("morphTargetInfluences"); + uniformsList.push("morphTargetCount"); + } + if (defines["BAKED_VERTEX_ANIMATION_TEXTURE"]) { + uniformsList.push("bakedVertexAnimationSettings"); + uniformsList.push("bakedVertexAnimationTextureSizeInverted"); + uniformsList.push("bakedVertexAnimationTime"); + samplersList.push("bakedVertexAnimationTexture"); + } +} + +/** + * Base class for the main features of a material in Babylon.js + */ +class Material { + /** @internal */ + get _supportGlowLayer() { + return false; + } + /** @internal */ + set _glowModeEnabled(value) { + // Do nothing here + } + /** + * Gets the shader language used in this material. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * If the material can be rendered to several textures with MRT extension + */ + get canRenderToMRT() { + // By default, shaders are not compatible with MRTs + // Base classes should override that if their shader supports MRT + return false; + } + /** + * Sets the alpha value of the material + */ + set alpha(value) { + if (this._alpha === value) { + return; + } + const oldValue = this._alpha; + this._alpha = value; + // Only call dirty when there is a state change (no alpha / alpha) + if (oldValue === 1 || value === 1) { + this.markAsDirty(Material.MiscDirtyFlag + Material.PrePassDirtyFlag); + } + } + /** + * Gets the alpha value of the material + */ + get alpha() { + return this._alpha; + } + /** + * Sets the culling state (true to enable culling, false to disable) + */ + set backFaceCulling(value) { + if (this._backFaceCulling === value) { + return; + } + this._backFaceCulling = value; + this.markAsDirty(Material.TextureDirtyFlag); + } + /** + * Gets the culling state + */ + get backFaceCulling() { + return this._backFaceCulling; + } + /** + * Sets the type of faces that should be culled (true for back faces, false for front faces) + */ + set cullBackFaces(value) { + if (this._cullBackFaces === value) { + return; + } + this._cullBackFaces = value; + this.markAsDirty(Material.TextureDirtyFlag); + } + /** + * Gets the type of faces that should be culled + */ + get cullBackFaces() { + return this._cullBackFaces; + } + /** + * Block the dirty-mechanism for this specific material + * When set to false after being true the material will be marked as dirty. + */ + get blockDirtyMechanism() { + return this._blockDirtyMechanism; + } + set blockDirtyMechanism(value) { + if (this._blockDirtyMechanism === value) { + return; + } + this._blockDirtyMechanism = value; + if (!value) { + this.markDirty(); + } + } + /** + * This allows you to modify the material without marking it as dirty after every change. + * This function should be used if you need to make more than one dirty-enabling change to the material - adding a texture, setting a new fill mode and so on. + * The callback will pass the material as an argument, so you can make your changes to it. + * @param callback the callback to be executed that will update the material + */ + atomicMaterialsUpdate(callback) { + this.blockDirtyMechanism = true; + try { + callback(this); + } + finally { + this.blockDirtyMechanism = false; + } + } + /** + * Gets a boolean indicating that current material needs to register RTT + */ + get hasRenderTargetTextures() { + this._eventInfo.hasRenderTargetTextures = false; + this._callbackPluginEventHasRenderTargetTextures(this._eventInfo); + return this._eventInfo.hasRenderTargetTextures; + } + /** + * Called during a dispose event + */ + set onDispose(callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + } + /** + * An event triggered when the material is bound + */ + get onBindObservable() { + if (!this._onBindObservable) { + this._onBindObservable = new Observable(); + } + return this._onBindObservable; + } + /** + * Called during a bind event + */ + set onBind(callback) { + if (this._onBindObserver) { + this.onBindObservable.remove(this._onBindObserver); + } + this._onBindObserver = this.onBindObservable.add(callback); + } + /** + * An event triggered when the material is unbound + */ + get onUnBindObservable() { + if (!this._onUnBindObservable) { + this._onUnBindObservable = new Observable(); + } + return this._onUnBindObservable; + } + /** + * An event triggered when the effect is (re)created + */ + get onEffectCreatedObservable() { + if (!this._onEffectCreatedObservable) { + this._onEffectCreatedObservable = new Observable(); + } + return this._onEffectCreatedObservable; + } + /** + * Sets the value of the alpha mode. + * + * | Value | Type | Description | + * | --- | --- | --- | + * | 0 | ALPHA_DISABLE | | + * | 1 | ALPHA_ADD | | + * | 2 | ALPHA_COMBINE | | + * | 3 | ALPHA_SUBTRACT | | + * | 4 | ALPHA_MULTIPLY | | + * | 5 | ALPHA_MAXIMIZED | | + * | 6 | ALPHA_ONEONE | | + * | 7 | ALPHA_PREMULTIPLIED | | + * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | | + * | 9 | ALPHA_INTERPOLATE | | + * | 10 | ALPHA_SCREENMODE | | + * + */ + set alphaMode(value) { + if (this._alphaMode === value) { + return; + } + this._alphaMode = value; + this.markAsDirty(Material.TextureDirtyFlag); + } + /** + * Gets the value of the alpha mode + */ + get alphaMode() { + return this._alphaMode; + } + /** + * Sets the need depth pre-pass value + */ + set needDepthPrePass(value) { + if (this._needDepthPrePass === value) { + return; + } + this._needDepthPrePass = value; + if (this._needDepthPrePass) { + this.checkReadyOnEveryCall = true; + } + } + /** + * Gets the depth pre-pass value + */ + get needDepthPrePass() { + return this._needDepthPrePass; + } + /** + * Can this material render to prepass + */ + get isPrePassCapable() { + return false; + } + /** + * Sets the state for enabling fog + */ + set fogEnabled(value) { + if (this._fogEnabled === value) { + return; + } + this._fogEnabled = value; + this.markAsDirty(Material.MiscDirtyFlag); + } + /** + * Gets the value of the fog enabled state + */ + get fogEnabled() { + return this._fogEnabled; + } + get wireframe() { + switch (this._fillMode) { + case Material.WireFrameFillMode: + case Material.LineListDrawMode: + case Material.LineLoopDrawMode: + case Material.LineStripDrawMode: + return true; + } + return this._scene.forceWireframe; + } + /** + * Sets the state of wireframe mode + */ + set wireframe(value) { + this.fillMode = value ? Material.WireFrameFillMode : Material.TriangleFillMode; + } + /** + * Gets the value specifying if point clouds are enabled + */ + get pointsCloud() { + switch (this._fillMode) { + case Material.PointFillMode: + case Material.PointListDrawMode: + return true; + } + return this._scene.forcePointsCloud; + } + /** + * Sets the state of point cloud mode + */ + set pointsCloud(value) { + this.fillMode = value ? Material.PointFillMode : Material.TriangleFillMode; + } + /** + * Gets the material fill mode + */ + get fillMode() { + return this._fillMode; + } + /** + * Sets the material fill mode + */ + set fillMode(value) { + if (this._fillMode === value) { + return; + } + this._fillMode = value; + this.markAsDirty(Material.MiscDirtyFlag); + } + /** + * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes) + * You can try switching to logarithmic depth. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/logarithmicDepthBuffer + */ + get useLogarithmicDepth() { + return this._useLogarithmicDepth; + } + set useLogarithmicDepth(value) { + const fragmentDepthSupported = this.getScene().getEngine().getCaps().fragmentDepthSupported; + if (value && !fragmentDepthSupported) { + Logger.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."); + } + this._useLogarithmicDepth = value && fragmentDepthSupported; + this._markAllSubMeshesAsMiscDirty(); + } + /** @internal */ + _getDrawWrapper() { + return this._drawWrapper; + } + /** + * @internal + */ + _setDrawWrapper(drawWrapper) { + this._drawWrapper = drawWrapper; + } + /** + * Creates a material instance + * @param name defines the name of the material + * @param scene defines the scene to reference + * @param doNotAdd specifies if the material should be added to the scene + * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false + */ + constructor(name, scene, doNotAdd, forceGLSL = false) { + /** + * Custom shadow depth material to use for shadow rendering instead of the in-built one + */ + this.shadowDepthWrapper = null; + /** + * Gets or sets a boolean indicating that the material is allowed (if supported) to do shader hot swapping. + * This means that the material can keep using a previous shader while a new one is being compiled. + * This is mostly used when shader parallel compilation is supported (true by default) + */ + this.allowShaderHotSwapping = true; + /** Shader language used by the material */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._forceGLSL = false; + /** + * Gets or sets user defined metadata + */ + this.metadata = null; + /** + * For internal use only. Please do not use. + */ + this.reservedDataStore = null; + /** + * Specifies if the ready state should be checked on each call + */ + this.checkReadyOnEveryCall = false; + /** + * Specifies if the ready state should be checked once + */ + this.checkReadyOnlyOnce = false; + /** + * The state of the material + */ + this.state = ""; + /** + * The alpha value of the material + */ + this._alpha = 1.0; + /** + * Specifies if back face culling is enabled + */ + this._backFaceCulling = true; + /** + * Specifies if back or front faces should be culled (when culling is enabled) + */ + this._cullBackFaces = true; + this._blockDirtyMechanism = false; + /** + * Stores the value for side orientation + */ + this.sideOrientation = null; + /** + * Callback triggered when the material is compiled + */ + this.onCompiled = null; + /** + * Callback triggered when an error occurs + */ + this.onError = null; + /** + * Callback triggered to get the render target textures + */ + this.getRenderTargetTextures = null; + /** + * Specifies if the material should be serialized + */ + this.doNotSerialize = false; + /** + * @internal + */ + this._storeEffectOnSubMeshes = false; + /** + * Stores the animations for the material + */ + this.animations = null; + /** + * An event triggered when the material is disposed + */ + this.onDisposeObservable = new Observable(); + /** + * An observer which watches for dispose events + */ + this._onDisposeObserver = null; + this._onUnBindObservable = null; + /** + * An observer which watches for bind events + */ + this._onBindObserver = null; + /** + * Stores the value of the alpha mode + */ + this._alphaMode = 2; + /** + * Stores the state of the need depth pre-pass value + */ + this._needDepthPrePass = false; + /** + * Specifies if depth writing should be disabled + */ + this.disableDepthWrite = false; + /** + * Specifies if color writing should be disabled + */ + this.disableColorWrite = false; + /** + * Specifies if depth writing should be forced + */ + this.forceDepthWrite = false; + /** + * Specifies the depth function that should be used. 0 means the default engine function + */ + this.depthFunction = 0; + /** + * Specifies if there should be a separate pass for culling + */ + this.separateCullingPass = false; + /** + * Stores the state specifying if fog should be enabled + */ + this._fogEnabled = true; + /** + * Stores the size of points + */ + this.pointSize = 1.0; + /** + * Stores the z offset Factor value + */ + this.zOffset = 0; + /** + * Stores the z offset Units value + */ + this.zOffsetUnits = 0; + /** + * Gives access to the stencil properties of the material + */ + this.stencil = new MaterialStencilState(); + /** + * Specifies if uniform buffers should be used + */ + this._useUBO = false; + /** + * Stores the fill mode state + */ + this._fillMode = Material.TriangleFillMode; + /** + * Specifies if the depth write state should be cached + */ + this._cachedDepthWriteState = false; + /** + * Specifies if the color write state should be cached + */ + this._cachedColorWriteState = false; + /** + * Specifies if the depth function state should be cached + */ + this._cachedDepthFunctionState = 0; + /** @internal */ + this._indexInSceneMaterialArray = -1; + /** @internal */ + this.meshMap = null; + /** @internal */ + this._parentContainer = null; + /** @internal */ + this._uniformBufferLayoutBuilt = false; + this._eventInfo = {}; // will be initialized before each event notification + /** @internal */ + this._callbackPluginEventGeneric = () => void 0; + /** @internal */ + this._callbackPluginEventIsReadyForSubMesh = () => void 0; + /** @internal */ + this._callbackPluginEventPrepareDefines = () => void 0; + /** @internal */ + this._callbackPluginEventPrepareDefinesBeforeAttributes = () => void 0; + /** @internal */ + this._callbackPluginEventHardBindForSubMesh = () => void 0; + /** @internal */ + this._callbackPluginEventBindForSubMesh = () => void 0; + /** @internal */ + this._callbackPluginEventHasRenderTargetTextures = () => void 0; + /** @internal */ + this._callbackPluginEventFillRenderTargetTextures = () => void 0; + /** + * The transparency mode of the material. + */ + this._transparencyMode = null; + this.name = name; + const setScene = scene || EngineStore.LastCreatedScene; + if (!setScene) { + return; + } + this._scene = setScene; + this._dirtyCallbacks = {}; + this._forceGLSL = forceGLSL; + this._dirtyCallbacks[1] = this._markAllSubMeshesAsTexturesDirty.bind(this); + this._dirtyCallbacks[2] = this._markAllSubMeshesAsLightsDirty.bind(this); + this._dirtyCallbacks[4] = this._markAllSubMeshesAsFresnelDirty.bind(this); + this._dirtyCallbacks[8] = this._markAllSubMeshesAsAttributesDirty.bind(this); + this._dirtyCallbacks[16] = this._markAllSubMeshesAsMiscDirty.bind(this); + this._dirtyCallbacks[32] = this._markAllSubMeshesAsPrePassDirty.bind(this); + this._dirtyCallbacks[127] = this._markAllSubMeshesAsAllDirty.bind(this); + this.id = name || Tools.RandomId(); + this.uniqueId = this._scene.getUniqueId(); + this._materialContext = this._scene.getEngine().createMaterialContext(); + this._drawWrapper = new DrawWrapper(this._scene.getEngine(), false); + this._drawWrapper.materialContext = this._materialContext; + this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), undefined, undefined, name); + this._useUBO = this.getScene().getEngine().supportsUniformBuffers; + this._createUniformBuffer(); + if (!doNotAdd) { + this._scene.addMaterial(this); + } + if (this._scene.useMaterialMeshMap) { + this.meshMap = {}; + } + Material.OnEventObservable.notifyObservers(this, 1 /* MaterialPluginEvent.Created */); + } + /** @internal */ + _createUniformBuffer() { + const engine = this.getScene().getEngine(); + this._uniformBuffer?.dispose(); + if (engine.isWebGPU && !this._forceGLSL) { + // Switch main UBO to non UBO to connect to leftovers UBO in webgpu + this._uniformBuffer = new UniformBuffer(engine, undefined, undefined, this.name, true); + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + } + else { + this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), undefined, undefined, this.name); + } + this._uniformBufferLayoutBuilt = false; + } + /** + * Returns a string representation of the current material + * @param fullDetails defines a boolean indicating which levels of logging is desired + * @returns a string with material information + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + toString(fullDetails) { + const ret = "Name: " + this.name; + return ret; + } + /** + * Gets the class name of the material + * @returns a string with the class name of the material + */ + getClassName() { + return "Material"; + } + /** @internal */ + get _isMaterial() { + return true; + } + /** + * Specifies if updates for the material been locked + */ + get isFrozen() { + return this.checkReadyOnlyOnce; + } + /** + * Locks updates for the material + */ + freeze() { + this.markDirty(); + this.checkReadyOnlyOnce = true; + } + /** + * Unlocks updates for the material + */ + unfreeze() { + this.markDirty(); + this.checkReadyOnlyOnce = false; + } + /** + * Specifies if the material is ready to be used + * @param mesh defines the mesh to check + * @param useInstances specifies if instances should be used + * @returns a boolean indicating if the material is ready to be used + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + isReady(mesh, useInstances) { + return true; + } + /** + * Specifies that the submesh is ready to be used + * @param mesh defines the mesh to check + * @param subMesh defines which submesh to check + * @param useInstances specifies that instances should be used + * @returns a boolean indicating that the submesh is ready or not + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + isReadyForSubMesh(mesh, subMesh, useInstances) { + const defines = subMesh.materialDefines; + if (!defines) { + return false; + } + this._eventInfo.isReadyForSubMesh = true; + this._eventInfo.defines = defines; + this._callbackPluginEventIsReadyForSubMesh(this._eventInfo); + return this._eventInfo.isReadyForSubMesh; + } + /** + * Returns the material effect + * @returns the effect associated with the material + */ + getEffect() { + return this._drawWrapper.effect; + } + /** + * Returns the current scene + * @returns a Scene + */ + getScene() { + return this._scene; + } + /** @internal */ + _getEffectiveOrientation(mesh) { + return this.sideOrientation !== null ? this.sideOrientation : mesh.sideOrientation; + } + /** + * Gets the current transparency mode. + */ + get transparencyMode() { + return this._transparencyMode; + } + /** + * Sets the transparency mode of the material. + * + * | Value | Type | Description | + * | ----- | ----------------------------------- | ----------- | + * | 0 | OPAQUE | | + * | 1 | ALPHATEST | | + * | 2 | ALPHABLEND | | + * | 3 | ALPHATESTANDBLEND | | + * + */ + set transparencyMode(value) { + if (this._transparencyMode === value) { + return; + } + this._transparencyMode = value; + this._markAllSubMeshesAsTexturesAndMiscDirty(); + } + get _hasTransparencyMode() { + return this._transparencyMode != null; + } + get _transparencyModeIsBlend() { + return this._transparencyMode === Material.MATERIAL_ALPHABLEND || this._transparencyMode === Material.MATERIAL_ALPHATESTANDBLEND; + } + get _transparencyModeIsTest() { + return this._transparencyMode === Material.MATERIAL_ALPHATEST || this._transparencyMode === Material.MATERIAL_ALPHATESTANDBLEND; + } + /** + * Returns true if alpha blending should be disabled. + */ + get _disableAlphaBlending() { + return this._transparencyMode === Material.MATERIAL_OPAQUE || this._transparencyMode === Material.MATERIAL_ALPHATEST; + } + /** + * Specifies whether or not this material should be rendered in alpha blend mode. + * @returns a boolean specifying if alpha blending is needed + * @deprecated Please use needAlphaBlendingForMesh instead + */ + needAlphaBlending() { + if (this._hasTransparencyMode) { + return this._transparencyModeIsBlend; + } + if (this._disableAlphaBlending) { + return false; + } + return this.alpha < 1.0; + } + /** + * Specifies if the mesh will require alpha blending + * @param mesh defines the mesh to check + * @returns a boolean specifying if alpha blending is needed for the mesh + */ + needAlphaBlendingForMesh(mesh) { + if (this._hasTransparencyMode) { + return this._transparencyModeIsBlend; + } + if (mesh.visibility < 1.0) { + return true; + } + if (this._disableAlphaBlending) { + return false; + } + return mesh.hasVertexAlpha || this.needAlphaBlending(); + } + /** + * Specifies whether or not this material should be rendered in alpha test mode. + * @returns a boolean specifying if an alpha test is needed. + * @deprecated Please use needAlphaTestingForMesh instead + */ + needAlphaTesting() { + if (this._hasTransparencyMode) { + return this._transparencyModeIsTest; + } + return false; + } + /** + * Specifies if material alpha testing should be turned on for the mesh + * @param mesh defines the mesh to check + * @returns a boolean specifying if alpha testing should be turned on for the mesh + */ + needAlphaTestingForMesh(mesh) { + if (this._hasTransparencyMode) { + return this._transparencyModeIsTest; + } + return !this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting(); + } + /** + * Gets the texture used for the alpha test + * @returns the texture to use for alpha testing + */ + getAlphaTestTexture() { + return null; + } + /** + * Marks the material to indicate that it needs to be re-calculated + * @param forceMaterialDirty - Forces the material to be marked as dirty for all components (same as this.markAsDirty(Material.AllDirtyFlag)). You should use this flag if the material is frozen and you want to force a recompilation. + */ + markDirty(forceMaterialDirty = false) { + const meshes = this.getScene().meshes; + for (const mesh of meshes) { + if (!mesh.subMeshes) { + continue; + } + for (const subMesh of mesh.subMeshes) { + if (subMesh.getMaterial() !== this) { + continue; + } + for (const drawWrapper of subMesh._drawWrappers) { + if (!drawWrapper) { + continue; + } + if (this._materialContext === drawWrapper.materialContext) { + drawWrapper._wasPreviouslyReady = false; + drawWrapper._wasPreviouslyUsingInstances = null; + drawWrapper._forceRebindOnNextCall = forceMaterialDirty; + } + } + } + } + if (forceMaterialDirty) { + this.markAsDirty(Material.AllDirtyFlag); + } + } + /** + * @internal + */ + _preBind(effect, overrideOrientation = null) { + const engine = this._scene.getEngine(); + const orientation = overrideOrientation == null ? this.sideOrientation : overrideOrientation; + const reverse = orientation === Material.ClockWiseSideOrientation; + engine.enableEffect(effect ? effect : this._getDrawWrapper()); + engine.setState(this.backFaceCulling, this.zOffset, false, reverse, this._scene._mirroredCameraPosition ? !this.cullBackFaces : this.cullBackFaces, this.stencil, this.zOffsetUnits); + return reverse; + } + /** + * Binds the material to the mesh + * @param world defines the world transformation matrix + * @param mesh defines the mesh to bind the material to + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + bind(world, mesh) { } + /** + * Initializes the uniform buffer layout for the shader. + */ + buildUniformLayout() { + const ubo = this._uniformBuffer; + this._eventInfo.ubo = ubo; + this._callbackPluginEventGeneric(8 /* MaterialPluginEvent.PrepareUniformBuffer */, this._eventInfo); + ubo.create(); + this._uniformBufferLayoutBuilt = true; + } + /** + * Binds the submesh to the material + * @param world defines the world transformation matrix + * @param mesh defines the mesh containing the submesh + * @param subMesh defines the submesh to bind the material to + */ + bindForSubMesh(world, mesh, subMesh) { + const drawWrapper = subMesh._drawWrapper; + this._eventInfo.subMesh = subMesh; + this._callbackPluginEventBindForSubMesh(this._eventInfo); + drawWrapper._forceRebindOnNextCall = false; + } + /** + * Binds the world matrix to the material + * @param world defines the world transformation matrix + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + bindOnlyWorldMatrix(world) { } + /** + * Binds the view matrix to the effect + * @param effect defines the effect to bind the view matrix to + */ + bindView(effect) { + if (!this._useUBO) { + effect.setMatrix("view", this.getScene().getViewMatrix()); + } + else { + this._needToBindSceneUbo = true; + } + } + /** + * Binds the view projection and projection matrices to the effect + * @param effect defines the effect to bind the view projection and projection matrices to + */ + bindViewProjection(effect) { + if (!this._useUBO) { + effect.setMatrix("viewProjection", this.getScene().getTransformMatrix()); + effect.setMatrix("projection", this.getScene().getProjectionMatrix()); + } + else { + this._needToBindSceneUbo = true; + } + } + /** + * Binds the view matrix to the effect + * @param effect defines the effect to bind the view matrix to + * @param variableName name of the shader variable that will hold the eye position + */ + bindEyePosition(effect, variableName) { + if (!this._useUBO) { + this._scene.bindEyePosition(effect, variableName); + } + else { + this._needToBindSceneUbo = true; + } + } + /** + * Processes to execute after binding the material to a mesh + * @param mesh defines the rendered mesh + * @param effect defines the effect used to bind the material + * @param _subMesh defines the subMesh that the material has been bound for + */ + _afterBind(mesh, effect = null, _subMesh) { + this._scene._cachedMaterial = this; + if (this._needToBindSceneUbo) { + if (effect) { + this._needToBindSceneUbo = false; + BindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer()); + this._scene.finalizeSceneUbo(); + } + } + if (mesh) { + this._scene._cachedVisibility = mesh.visibility; + } + else { + this._scene._cachedVisibility = 1; + } + if (this._onBindObservable && mesh) { + this._onBindObservable.notifyObservers(mesh); + } + if (this.disableDepthWrite) { + const engine = this._scene.getEngine(); + this._cachedDepthWriteState = engine.getDepthWrite(); + engine.setDepthWrite(false); + } + if (this.disableColorWrite) { + const engine = this._scene.getEngine(); + this._cachedColorWriteState = engine.getColorWrite(); + engine.setColorWrite(false); + } + if (this.depthFunction !== 0) { + const engine = this._scene.getEngine(); + this._cachedDepthFunctionState = engine.getDepthFunction() || 0; + engine.setDepthFunction(this.depthFunction); + } + } + /** + * Unbinds the material from the mesh + */ + unbind() { + this._scene.getSceneUniformBuffer().unbindEffect(); + if (this._onUnBindObservable) { + this._onUnBindObservable.notifyObservers(this); + } + if (this.depthFunction !== 0) { + const engine = this._scene.getEngine(); + engine.setDepthFunction(this._cachedDepthFunctionState); + } + if (this.disableDepthWrite) { + const engine = this._scene.getEngine(); + engine.setDepthWrite(this._cachedDepthWriteState); + } + if (this.disableColorWrite) { + const engine = this._scene.getEngine(); + engine.setColorWrite(this._cachedColorWriteState); + } + } + /** + * Returns the animatable textures. + * @returns - Array of animatable textures. + */ + getAnimatables() { + this._eventInfo.animatables = []; + this._callbackPluginEventGeneric(256 /* MaterialPluginEvent.GetAnimatables */, this._eventInfo); + return this._eventInfo.animatables; + } + /** + * Gets the active textures from the material + * @returns an array of textures + */ + getActiveTextures() { + this._eventInfo.activeTextures = []; + this._callbackPluginEventGeneric(512 /* MaterialPluginEvent.GetActiveTextures */, this._eventInfo); + return this._eventInfo.activeTextures; + } + /** + * Specifies if the material uses a texture + * @param texture defines the texture to check against the material + * @returns a boolean specifying if the material uses the texture + */ + hasTexture(texture) { + this._eventInfo.hasTexture = false; + this._eventInfo.texture = texture; + this._callbackPluginEventGeneric(1024 /* MaterialPluginEvent.HasTexture */, this._eventInfo); + return this._eventInfo.hasTexture; + } + /** + * Makes a duplicate of the material, and gives it a new name + * @param name defines the new name for the duplicated material + * @returns the cloned material + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + clone(name) { + return null; + } + _clonePlugins(targetMaterial, rootUrl) { + const serializationObject = {}; + // Create plugins in targetMaterial in case they don't exist + this._serializePlugins(serializationObject); + Material._ParsePlugins(serializationObject, targetMaterial, this._scene, rootUrl); + // Copy the properties of the current plugins to the cloned material's plugins + if (this.pluginManager) { + for (const plugin of this.pluginManager._plugins) { + const targetPlugin = targetMaterial.pluginManager.getPlugin(plugin.name); + if (targetPlugin) { + plugin.copyTo(targetPlugin); + } + } + } + } + /** + * Gets the meshes bound to the material + * @returns an array of meshes bound to the material + */ + getBindedMeshes() { + if (this.meshMap) { + const result = []; + for (const meshId in this.meshMap) { + const mesh = this.meshMap[meshId]; + if (mesh) { + result.push(mesh); + } + } + return result; + } + else { + const meshes = this._scene.meshes; + return meshes.filter((mesh) => mesh.material === this); + } + } + /** + * Force shader compilation + * @param mesh defines the mesh associated with this material + * @param onCompiled defines a function to execute once the material is compiled + * @param options defines the options to configure the compilation + * @param onError defines a function to execute if the material fails compiling + */ + forceCompilation(mesh, onCompiled, options, onError) { + const localOptions = { + clipPlane: false, + useInstances: false, + ...options, + }; + const scene = this.getScene(); + const currentHotSwapingState = this.allowShaderHotSwapping; + this.allowShaderHotSwapping = false; // Turned off to let us evaluate the real compilation state + const checkReady = () => { + if (!this._scene || !this._scene.getEngine()) { + return; + } + const clipPlaneState = scene.clipPlane; + if (localOptions.clipPlane) { + scene.clipPlane = new Plane(0, 0, 0, 1); + } + if (this._storeEffectOnSubMeshes) { + let allDone = true, lastError = null; + if (mesh.subMeshes) { + const tempSubMesh = new SubMesh(0, 0, 0, 0, 0, mesh, undefined, false, false); + if (tempSubMesh.materialDefines) { + tempSubMesh.materialDefines._renderId = -1; + } + if (!this.isReadyForSubMesh(mesh, tempSubMesh, localOptions.useInstances)) { + if (tempSubMesh.effect && tempSubMesh.effect.getCompilationError() && tempSubMesh.effect.allFallbacksProcessed()) { + lastError = tempSubMesh.effect.getCompilationError(); + } + else { + allDone = false; + setTimeout(checkReady, 16); + } + } + } + if (allDone) { + this.allowShaderHotSwapping = currentHotSwapingState; + if (lastError) { + if (onError) { + onError(lastError); + } + } + if (onCompiled) { + onCompiled(this); + } + } + } + else { + if (this.isReady()) { + this.allowShaderHotSwapping = currentHotSwapingState; + if (onCompiled) { + onCompiled(this); + } + } + else { + setTimeout(checkReady, 16); + } + } + if (localOptions.clipPlane) { + scene.clipPlane = clipPlaneState; + } + }; + checkReady(); + } + /** + * Force shader compilation + * @param mesh defines the mesh that will use this material + * @param options defines additional options for compiling the shaders + * @returns a promise that resolves when the compilation completes + */ + forceCompilationAsync(mesh, options) { + return new Promise((resolve, reject) => { + this.forceCompilation(mesh, () => { + resolve(); + }, options, (reason) => { + reject(reason); + }); + }); + } + /** + * Marks a define in the material to indicate that it needs to be re-computed + * @param flag defines a flag used to determine which parts of the material have to be marked as dirty + */ + markAsDirty(flag) { + if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) { + return; + } + Material._DirtyCallbackArray.length = 0; + if (flag & Material.ImageProcessingDirtyFlag) { + Material._DirtyCallbackArray.push(Material._ImageProcessingDirtyCallBack); + } + if (flag & Material.TextureDirtyFlag) { + Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack); + } + if (flag & Material.LightDirtyFlag) { + Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack); + } + if (flag & Material.FresnelDirtyFlag) { + Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack); + } + if (flag & Material.AttributesDirtyFlag) { + Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack); + } + if (flag & Material.MiscDirtyFlag) { + Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack); + } + if (flag & Material.PrePassDirtyFlag) { + Material._DirtyCallbackArray.push(Material._PrePassDirtyCallBack); + } + if (Material._DirtyCallbackArray.length) { + this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks); + } + this.getScene().resetCachedMaterial(); + } + /** + * Resets the draw wrappers cache for all submeshes that are using this material + */ + resetDrawCache() { + const meshes = this.getScene().meshes; + for (const mesh of meshes) { + if (!mesh.subMeshes) { + continue; + } + for (const subMesh of mesh.subMeshes) { + if (subMesh.getMaterial() !== this) { + continue; + } + subMesh.resetDrawCache(); + } + } + } + /** + * Marks all submeshes of a material to indicate that their material defines need to be re-calculated + * @param func defines a function which checks material defines against the submeshes + */ + _markAllSubMeshesAsDirty(func) { + const scene = this.getScene(); + if (scene.blockMaterialDirtyMechanism || this._blockDirtyMechanism) { + return; + } + const meshes = scene.meshes; + for (const mesh of meshes) { + if (!mesh.subMeshes) { + continue; + } + for (const subMesh of mesh.subMeshes) { + // We want to skip the submeshes which are not using this material or which have not yet rendered at least once + const material = subMesh.getMaterial() || (scene._hasDefaultMaterial ? scene.defaultMaterial : null); + if (material !== this) { + continue; + } + for (const drawWrapper of subMesh._drawWrappers) { + if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) { + continue; + } + if (this._materialContext === drawWrapper.materialContext) { + func(drawWrapper.defines); + } + } + } + } + } + /** + * Indicates that the scene should check if the rendering now needs a prepass + */ + _markScenePrePassDirty() { + if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) { + return; + } + const prePassRenderer = this.getScene().enablePrePassRenderer(); + if (prePassRenderer) { + prePassRenderer.markAsDirty(); + } + } + /** + * Indicates that we need to re-calculated for all submeshes + */ + _markAllSubMeshesAsAllDirty() { + this._markAllSubMeshesAsDirty(Material._AllDirtyCallBack); + } + /** + * Indicates that image processing needs to be re-calculated for all submeshes + */ + _markAllSubMeshesAsImageProcessingDirty() { + this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack); + } + /** + * Indicates that textures need to be re-calculated for all submeshes + */ + _markAllSubMeshesAsTexturesDirty() { + this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack); + } + /** + * Indicates that fresnel needs to be re-calculated for all submeshes + */ + _markAllSubMeshesAsFresnelDirty() { + this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack); + } + /** + * Indicates that fresnel and misc need to be re-calculated for all submeshes + */ + _markAllSubMeshesAsFresnelAndMiscDirty() { + this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack); + } + /** + * Indicates that lights need to be re-calculated for all submeshes + */ + _markAllSubMeshesAsLightsDirty() { + this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack); + } + /** + * Indicates that attributes need to be re-calculated for all submeshes + */ + _markAllSubMeshesAsAttributesDirty() { + this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack); + } + /** + * Indicates that misc needs to be re-calculated for all submeshes + */ + _markAllSubMeshesAsMiscDirty() { + this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack); + } + /** + * Indicates that prepass needs to be re-calculated for all submeshes + */ + _markAllSubMeshesAsPrePassDirty() { + this._markAllSubMeshesAsDirty(Material._PrePassDirtyCallBack); + } + /** + * Indicates that textures and misc need to be re-calculated for all submeshes + */ + _markAllSubMeshesAsTexturesAndMiscDirty() { + this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack); + } + _checkScenePerformancePriority() { + if (this._scene.performancePriority !== 0 /* ScenePerformancePriority.BackwardCompatible */) { + this.checkReadyOnlyOnce = true; + // re-set the flag when the perf priority changes + const observer = this._scene.onScenePerformancePriorityChangedObservable.addOnce(() => { + this.checkReadyOnlyOnce = false; + }); + // if this material is disposed before the scene is disposed, cleanup the observer + this.onDisposeObservable.add(() => { + this._scene.onScenePerformancePriorityChangedObservable.remove(observer); + }); + } + } + /** + * Sets the required values to the prepass renderer. + * @param prePassRenderer defines the prepass renderer to setup. + * @returns true if the pre pass is needed. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + setPrePassRenderer(prePassRenderer) { + // Do Nothing by default + return false; + } + /** + * Disposes the material + * @param _forceDisposeEffect kept for backward compat. We reference count the effect now. + * @param forceDisposeTextures specifies if textures should be forcefully disposed + * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh + */ + dispose(_forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { + const scene = this.getScene(); + // Animations + scene.stopAnimation(this); + scene.freeProcessedMaterials(); + // Remove from scene + scene.removeMaterial(this); + this._eventInfo.forceDisposeTextures = forceDisposeTextures; + this._callbackPluginEventGeneric(2 /* MaterialPluginEvent.Disposed */, this._eventInfo); + if (this._parentContainer) { + const index = this._parentContainer.materials.indexOf(this); + if (index > -1) { + this._parentContainer.materials.splice(index, 1); + } + this._parentContainer = null; + } + if (notBoundToMesh !== true) { + // Remove from meshes + if (this.meshMap) { + for (const meshId in this.meshMap) { + const mesh = this.meshMap[meshId]; + this._disposeMeshResources(mesh); + } + } + else { + const meshes = scene.meshes; + for (const mesh of meshes) { + this._disposeMeshResources(mesh); + } + } + } + this._uniformBuffer.dispose(); + // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect + if (this._drawWrapper.effect) { + if (!this._storeEffectOnSubMeshes) { + this._drawWrapper.effect.dispose(); + } + this._drawWrapper.effect = null; + } + this.metadata = null; + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + if (this._onBindObservable) { + this._onBindObservable.clear(); + } + if (this._onUnBindObservable) { + this._onUnBindObservable.clear(); + } + if (this._onEffectCreatedObservable) { + this._onEffectCreatedObservable.clear(); + } + if (this._eventInfo) { + this._eventInfo = {}; + } + } + _disposeMeshResources(mesh) { + if (!mesh) { + return; + } + const geometry = mesh.geometry; + const materialForRenderPass = mesh._internalAbstractMeshDataInfo._materialForRenderPass; + if (this._storeEffectOnSubMeshes) { + if (mesh.subMeshes && materialForRenderPass) { + for (const subMesh of mesh.subMeshes) { + const drawWrappers = subMesh._drawWrappers; + for (let renderPassIndex = 0; renderPassIndex < drawWrappers.length; renderPassIndex++) { + const effect = drawWrappers[renderPassIndex]?.effect; + if (!effect) { + continue; + } + const material = materialForRenderPass[renderPassIndex]; + if (material === this) { + geometry?._releaseVertexArrayObject(effect); + subMesh._removeDrawWrapper(renderPassIndex, true, true); + } + } + } + } + } + else { + geometry?._releaseVertexArrayObject(this._drawWrapper.effect); + } + if (mesh.material === this && !mesh.sourceMesh) { + mesh.material = null; + } + } + /** + * Serializes this material + * @returns the serialized material object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.stencil = this.stencil.serialize(); + serializationObject.uniqueId = this.uniqueId; + this._serializePlugins(serializationObject); + return serializationObject; + } + _serializePlugins(serializationObject) { + serializationObject.plugins = {}; + if (this.pluginManager) { + for (const plugin of this.pluginManager._plugins) { + if (!plugin.doNotSerialize) { + serializationObject.plugins[plugin.getClassName()] = plugin.serialize(); + } + } + } + } + /** + * Creates a material from parsed material data + * @param parsedMaterial defines parsed material data + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures + * @returns a new material + */ + static Parse(parsedMaterial, scene, rootUrl) { + if (!parsedMaterial.customType) { + parsedMaterial.customType = "BABYLON.StandardMaterial"; + } + else if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) { + parsedMaterial.customType = "BABYLON.LegacyPBRMaterial"; + if (!BABYLON.LegacyPBRMaterial) { + Logger.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."); + return null; + } + } + const materialType = Tools.Instantiate(parsedMaterial.customType); + const material = materialType.Parse(parsedMaterial, scene, rootUrl); + material._loadedUniqueId = parsedMaterial.uniqueId; + return material; + } + static _ParsePlugins(serializationObject, material, scene, rootUrl) { + if (!serializationObject.plugins) { + return; + } + for (const pluginClassName in serializationObject.plugins) { + const pluginData = serializationObject.plugins[pluginClassName]; + let plugin = material.pluginManager?.getPlugin(pluginData.name); + if (!plugin) { + const pluginClassType = Tools.Instantiate("BABYLON." + pluginClassName); + if (pluginClassType) { + plugin = new pluginClassType(material); + } + } + plugin?.parse(pluginData, scene, rootUrl); + } + } +} +/** + * Returns the triangle fill mode + */ +Material.TriangleFillMode = 0; +/** + * Returns the wireframe mode + */ +Material.WireFrameFillMode = 1; +/** + * Returns the point fill mode + */ +Material.PointFillMode = 2; +/** + * Returns the point list draw mode + */ +Material.PointListDrawMode = 3; +/** + * Returns the line list draw mode + */ +Material.LineListDrawMode = 4; +/** + * Returns the line loop draw mode + */ +Material.LineLoopDrawMode = 5; +/** + * Returns the line strip draw mode + */ +Material.LineStripDrawMode = 6; +/** + * Returns the triangle strip draw mode + */ +Material.TriangleStripDrawMode = 7; +/** + * Returns the triangle fan draw mode + */ +Material.TriangleFanDrawMode = 8; +/** + * Stores the clock-wise side orientation + */ +Material.ClockWiseSideOrientation = 0; +/** + * Stores the counter clock-wise side orientation + */ +Material.CounterClockWiseSideOrientation = 1; +/** + * The dirty image processing flag value + */ +Material.ImageProcessingDirtyFlag = 64; +/** + * The dirty texture flag value + */ +Material.TextureDirtyFlag = 1; +/** + * The dirty light flag value + */ +Material.LightDirtyFlag = 2; +/** + * The dirty fresnel flag value + */ +Material.FresnelDirtyFlag = 4; +/** + * The dirty attribute flag value + */ +Material.AttributesDirtyFlag = 8; +/** + * The dirty misc flag value + */ +Material.MiscDirtyFlag = 16; +/** + * The dirty prepass flag value + */ +Material.PrePassDirtyFlag = 32; +/** + * The all dirty flag value + */ +Material.AllDirtyFlag = 127; +/** + * MaterialTransparencyMode: No transparency mode, Alpha channel is not use. + */ +Material.MATERIAL_OPAQUE = 0; +/** + * MaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value. + */ +Material.MATERIAL_ALPHATEST = 1; +/** + * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. + */ +Material.MATERIAL_ALPHABLEND = 2; +/** + * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. + * They are also discarded below the alpha cutoff threshold to improve performances. + */ +Material.MATERIAL_ALPHATESTANDBLEND = 3; +/** + * The Whiteout method is used to blend normals. + * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/ + */ +Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0; +/** + * The Reoriented Normal Mapping method is used to blend normals. + * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/ + */ +Material.MATERIAL_NORMALBLENDMETHOD_RNM = 1; +/** + * Event observable which raises global events common to all materials (like MaterialPluginEvent.Created) + */ +Material.OnEventObservable = new Observable(); +Material._AllDirtyCallBack = (defines) => defines.markAllAsDirty(); +Material._ImageProcessingDirtyCallBack = (defines) => defines.markAsImageProcessingDirty(); +Material._TextureDirtyCallBack = (defines) => defines.markAsTexturesDirty(); +Material._FresnelDirtyCallBack = (defines) => defines.markAsFresnelDirty(); +Material._MiscDirtyCallBack = (defines) => defines.markAsMiscDirty(); +Material._PrePassDirtyCallBack = (defines) => defines.markAsPrePassDirty(); +Material._LightsDirtyCallBack = (defines) => defines.markAsLightDirty(); +Material._AttributeDirtyCallBack = (defines) => defines.markAsAttributesDirty(); +Material._FresnelAndMiscDirtyCallBack = (defines) => { + Material._FresnelDirtyCallBack(defines); + Material._MiscDirtyCallBack(defines); +}; +Material._TextureAndMiscDirtyCallBack = (defines) => { + Material._TextureDirtyCallBack(defines); + Material._MiscDirtyCallBack(defines); +}; +Material._DirtyCallbackArray = []; +Material._RunDirtyCallBacks = (defines) => { + for (const cb of Material._DirtyCallbackArray) { + cb(defines); + } +}; +__decorate([ + serialize() +], Material.prototype, "id", void 0); +__decorate([ + serialize() +], Material.prototype, "uniqueId", void 0); +__decorate([ + serialize() +], Material.prototype, "name", void 0); +__decorate([ + serialize() +], Material.prototype, "metadata", void 0); +__decorate([ + serialize() +], Material.prototype, "checkReadyOnEveryCall", void 0); +__decorate([ + serialize() +], Material.prototype, "checkReadyOnlyOnce", void 0); +__decorate([ + serialize() +], Material.prototype, "state", void 0); +__decorate([ + serialize("alpha") +], Material.prototype, "_alpha", void 0); +__decorate([ + serialize("backFaceCulling") +], Material.prototype, "_backFaceCulling", void 0); +__decorate([ + serialize("cullBackFaces") +], Material.prototype, "_cullBackFaces", void 0); +__decorate([ + serialize() +], Material.prototype, "sideOrientation", void 0); +__decorate([ + serialize("alphaMode") +], Material.prototype, "_alphaMode", void 0); +__decorate([ + serialize() +], Material.prototype, "_needDepthPrePass", void 0); +__decorate([ + serialize() +], Material.prototype, "disableDepthWrite", void 0); +__decorate([ + serialize() +], Material.prototype, "disableColorWrite", void 0); +__decorate([ + serialize() +], Material.prototype, "forceDepthWrite", void 0); +__decorate([ + serialize() +], Material.prototype, "depthFunction", void 0); +__decorate([ + serialize() +], Material.prototype, "separateCullingPass", void 0); +__decorate([ + serialize("fogEnabled") +], Material.prototype, "_fogEnabled", void 0); +__decorate([ + serialize() +], Material.prototype, "pointSize", void 0); +__decorate([ + serialize() +], Material.prototype, "zOffset", void 0); +__decorate([ + serialize() +], Material.prototype, "zOffsetUnits", void 0); +__decorate([ + serialize() +], Material.prototype, "pointsCloud", null); +__decorate([ + serialize() +], Material.prototype, "fillMode", null); +__decorate([ + serialize() +], Material.prototype, "useLogarithmicDepth", null); +__decorate([ + serialize() +], Material.prototype, "transparencyMode", null); + +/** + * A multi-material is used to apply different materials to different parts of the same object without the need of + * separate meshes. This can be use to improve performances. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials + */ +class MultiMaterial extends Material { + /** + * Gets or Sets the list of Materials used within the multi material. + * They need to be ordered according to the submeshes order in the associated mesh + */ + get subMaterials() { + return this._subMaterials; + } + set subMaterials(value) { + this._subMaterials = value; + this._hookArray(value); + } + /** + * Function used to align with Node.getChildren() + * @returns the list of Materials used within the multi material + */ + getChildren() { + return this.subMaterials; + } + /** + * Instantiates a new Multi Material + * A multi-material is used to apply different materials to different parts of the same object without the need of + * separate meshes. This can be use to improve performances. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials + * @param name Define the name in the scene + * @param scene Define the scene the material belongs to + */ + constructor(name, scene) { + super(name, scene, true); + /** @internal */ + this._waitingSubMaterialsUniqueIds = []; + this.getScene().addMultiMaterial(this); + this.subMaterials = []; + this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material + } + _hookArray(array) { + const oldPush = array.push; + array.push = (...items) => { + const result = oldPush.apply(array, items); + this._markAllSubMeshesAsTexturesDirty(); + return result; + }; + const oldSplice = array.splice; + array.splice = (index, deleteCount) => { + const deleted = oldSplice.apply(array, [index, deleteCount]); + this._markAllSubMeshesAsTexturesDirty(); + return deleted; + }; + } + /** + * Get one of the submaterial by its index in the submaterials array + * @param index The index to look the sub material at + * @returns The Material if the index has been defined + */ + getSubMaterial(index) { + if (index < 0 || index >= this.subMaterials.length) { + return this.getScene().defaultMaterial; + } + return this.subMaterials[index]; + } + /** + * Get the list of active textures for the whole sub materials list. + * @returns All the textures that will be used during the rendering + */ + getActiveTextures() { + return super.getActiveTextures().concat(...this.subMaterials.map((subMaterial) => { + if (subMaterial) { + return subMaterial.getActiveTextures(); + } + else { + return []; + } + })); + } + /** + * Specifies if any sub-materials of this multi-material use a given texture. + * @param texture Defines the texture to check against this multi-material's sub-materials. + * @returns A boolean specifying if any sub-material of this multi-material uses the texture. + */ + hasTexture(texture) { + if (super.hasTexture(texture)) { + return true; + } + for (let i = 0; i < this.subMaterials.length; i++) { + if (this.subMaterials[i]?.hasTexture(texture)) { + return true; + } + } + return false; + } + /** + * Gets the current class name of the material e.g. "MultiMaterial" + * Mainly use in serialization. + * @returns the class name + */ + getClassName() { + return "MultiMaterial"; + } + /** + * Checks if the material is ready to render the requested sub mesh + * @param mesh Define the mesh the submesh belongs to + * @param subMesh Define the sub mesh to look readiness for + * @param useInstances Define whether or not the material is used with instances + * @returns true if ready, otherwise false + */ + isReadyForSubMesh(mesh, subMesh, useInstances) { + for (let index = 0; index < this.subMaterials.length; index++) { + const subMaterial = this.subMaterials[index]; + if (subMaterial) { + if (subMaterial._storeEffectOnSubMeshes) { + if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) { + return false; + } + continue; + } + if (!subMaterial.isReady(mesh)) { + return false; + } + } + } + return true; + } + /** + * Clones the current material and its related sub materials + * @param name Define the name of the newly cloned material + * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance + * @returns the cloned material + */ + clone(name, cloneChildren) { + const newMultiMaterial = new MultiMaterial(name, this.getScene()); + for (let index = 0; index < this.subMaterials.length; index++) { + let subMaterial = null; + const current = this.subMaterials[index]; + if (cloneChildren && current) { + subMaterial = current.clone(name + "-" + current.name); + } + else { + subMaterial = this.subMaterials[index]; + } + newMultiMaterial.subMaterials.push(subMaterial); + } + return newMultiMaterial; + } + /** + * Serializes the materials into a JSON representation. + * @returns the JSON representation + */ + serialize() { + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.id = this.id; + serializationObject.uniqueId = this.uniqueId; + if (Tags) { + serializationObject.tags = Tags.GetTags(this); + } + serializationObject.materialsUniqueIds = []; + serializationObject.materials = []; + for (let matIndex = 0; matIndex < this.subMaterials.length; matIndex++) { + const subMat = this.subMaterials[matIndex]; + if (subMat) { + serializationObject.materialsUniqueIds.push(subMat.uniqueId); + serializationObject.materials.push(subMat.id); + } + else { + serializationObject.materialsUniqueIds.push(null); + serializationObject.materials.push(null); + } + } + return serializationObject; + } + /** + * Dispose the material and release its associated resources + * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on) + * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app) + * @param forceDisposeChildren Define if we want to force disposing the associated submaterials (if false, they will not be disposed and can still be use elsewhere in the app) + */ + dispose(forceDisposeEffect, forceDisposeTextures, forceDisposeChildren) { + const scene = this.getScene(); + if (!scene) { + return; + } + if (forceDisposeChildren) { + for (let index = 0; index < this.subMaterials.length; index++) { + const subMaterial = this.subMaterials[index]; + if (subMaterial) { + subMaterial.dispose(forceDisposeEffect, forceDisposeTextures); + } + } + } + const index = scene.multiMaterials.indexOf(this); + if (index >= 0) { + scene.multiMaterials.splice(index, 1); + } + super.dispose(forceDisposeEffect, forceDisposeTextures); + } + /** + * Creates a MultiMaterial from parsed MultiMaterial data. + * @param parsedMultiMaterial defines parsed MultiMaterial data. + * @param scene defines the hosting scene + * @returns a new MultiMaterial + */ + static ParseMultiMaterial(parsedMultiMaterial, scene) { + const multiMaterial = new MultiMaterial(parsedMultiMaterial.name, scene); + multiMaterial.id = parsedMultiMaterial.id; + multiMaterial._loadedUniqueId = parsedMultiMaterial.uniqueId; + if (Tags) { + Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags); + } + if (parsedMultiMaterial.materialsUniqueIds) { + multiMaterial._waitingSubMaterialsUniqueIds = parsedMultiMaterial.materialsUniqueIds; + } + else { + parsedMultiMaterial.materials.forEach((subMatId) => multiMaterial.subMaterials.push(scene.getLastMaterialById(subMatId))); + } + return multiMaterial; + } +} +RegisterClass("BABYLON.MultiMaterial", MultiMaterial); + +/** + * Class used to represent a specific level of detail of a mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD + */ +class MeshLODLevel { + /** + * Creates a new LOD level + * @param distanceOrScreenCoverage defines either the distance or the screen coverage where this level should start being displayed + * @param mesh defines the mesh to use to render this level + */ + constructor( + /** Either distance from the center of the object to show this level or the screen coverage if `useLODScreenCoverage` is set to `true` on the mesh*/ + distanceOrScreenCoverage, + /** Defines the mesh to use to render this level */ + mesh) { + this.distanceOrScreenCoverage = distanceOrScreenCoverage; + this.mesh = mesh; + } +} + +/** + * @internal + **/ +class _CreationDataStorage { +} +/** + * @internal + **/ +class _InstanceDataStorage { + constructor() { + this.visibleInstances = {}; + this.batchCache = new _InstancesBatch(); + this.batchCacheReplacementModeInFrozenMode = new _InstancesBatch(); + this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances + } +} +/** + * @internal + **/ +class _InstancesBatch { + constructor() { + /** + * + */ + this.mustReturn = false; + /** + * + */ + this.visibleInstances = new Array(); + /** + * + */ + this.renderSelf = []; + /** + * + */ + this.hardwareInstancedRendering = []; + } +} +/** + * @internal + **/ +class _ThinInstanceDataStorage { + constructor() { + this.instancesCount = 0; + this.matrixBuffer = null; + this.previousMatrixBuffer = null; + this.matrixBufferSize = 32 * 16; // let's start with a maximum of 32 thin instances + this.matrixData = null; + this.boundingVectors = []; + this.worldMatrices = null; + } +} +/** + * @internal + **/ +class _InternalMeshDataInfo { + constructor() { + this._areNormalsFrozen = false; // Will be used by ribbons mainly + // Will be used to save a source mesh reference, If any + this._source = null; + // Will be used to for fast cloned mesh lookup + this.meshMap = null; + this._preActivateId = -1; + // eslint-disable-next-line @typescript-eslint/naming-convention + this._LODLevels = new Array(); + /** Alternative definition of LOD level, using screen coverage instead of distance */ + this._useLODScreenCoverage = false; + this._effectiveMaterial = null; + this._forcedInstanceCount = 0; + this._overrideRenderingFillMode = null; + } +} +const meshCreationOptions = { + source: null, + parent: null, + doNotCloneChildren: false, + clonePhysicsImpostor: true, + cloneThinInstances: false, +}; +/** + * Class used to represent renderable models + */ +class Mesh extends AbstractMesh { + /** + * Gets the default side orientation. + * @param orientation the orientation to value to attempt to get + * @returns the default orientation + * @internal + */ + static _GetDefaultSideOrientation(orientation) { + return orientation || Mesh.FRONTSIDE; // works as Mesh.FRONTSIDE is 0 + } + /** + * Determines if the LOD levels are intended to be calculated using screen coverage (surface area ratio) instead of distance. + */ + get useLODScreenCoverage() { + return this._internalMeshDataInfo._useLODScreenCoverage; + } + set useLODScreenCoverage(value) { + this._internalMeshDataInfo._useLODScreenCoverage = value; + this._sortLODLevels(); + } + get computeBonesUsingShaders() { + return this._internalAbstractMeshDataInfo._computeBonesUsingShaders; + } + set computeBonesUsingShaders(value) { + if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) { + return; + } + if (value && this._internalMeshDataInfo._sourcePositions) { + // switch from software to GPU computation: we need to reset the vertex and normal buffers that have been updated by the software process + this.setVerticesData(VertexBuffer.PositionKind, this._internalMeshDataInfo._sourcePositions, true); + if (this._internalMeshDataInfo._sourceNormals) { + this.setVerticesData(VertexBuffer.NormalKind, this._internalMeshDataInfo._sourceNormals, true); + } + this._internalMeshDataInfo._sourcePositions = null; + this._internalMeshDataInfo._sourceNormals = null; + } + this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value; + this._markSubMeshesAsAttributesDirty(); + } + /** + * An event triggered before rendering the mesh + */ + get onBeforeRenderObservable() { + if (!this._internalMeshDataInfo._onBeforeRenderObservable) { + this._internalMeshDataInfo._onBeforeRenderObservable = new Observable(); + } + return this._internalMeshDataInfo._onBeforeRenderObservable; + } + /** + * An event triggered before binding the mesh + */ + get onBeforeBindObservable() { + if (!this._internalMeshDataInfo._onBeforeBindObservable) { + this._internalMeshDataInfo._onBeforeBindObservable = new Observable(); + } + return this._internalMeshDataInfo._onBeforeBindObservable; + } + /** + * An event triggered after rendering the mesh + */ + get onAfterRenderObservable() { + if (!this._internalMeshDataInfo._onAfterRenderObservable) { + this._internalMeshDataInfo._onAfterRenderObservable = new Observable(); + } + return this._internalMeshDataInfo._onAfterRenderObservable; + } + /** + * An event triggeredbetween rendering pass when using separateCullingPass = true + */ + get onBetweenPassObservable() { + if (!this._internalMeshDataInfo._onBetweenPassObservable) { + this._internalMeshDataInfo._onBetweenPassObservable = new Observable(); + } + return this._internalMeshDataInfo._onBetweenPassObservable; + } + /** + * An event triggered before drawing the mesh + */ + get onBeforeDrawObservable() { + if (!this._internalMeshDataInfo._onBeforeDrawObservable) { + this._internalMeshDataInfo._onBeforeDrawObservable = new Observable(); + } + return this._internalMeshDataInfo._onBeforeDrawObservable; + } + /** + * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead + */ + set onBeforeDraw(callback) { + if (this._onBeforeDrawObserver) { + this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver); + } + this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback); + } + get hasInstances() { + return this.instances.length > 0; + } + get hasThinInstances() { + return (this.forcedInstanceCount || this._thinInstanceDataStorage.instancesCount || 0) > 0; + } + /** + * Gets or sets the forced number of instances to display. + * If 0 (default value), the number of instances is not forced and depends on the draw type + * (regular / instance / thin instances mesh) + */ + get forcedInstanceCount() { + return this._internalMeshDataInfo._forcedInstanceCount; + } + set forcedInstanceCount(count) { + this._internalMeshDataInfo._forcedInstanceCount = count; + } + /** + * Use this property to change the original side orientation defined at construction time + * Material.sideOrientation will override this value if set + * User will still be able to change the material sideOrientation afterwards if they really need it + */ + get sideOrientation() { + return this._internalMeshDataInfo._sideOrientation; + } + set sideOrientation(value) { + this._internalMeshDataInfo._sideOrientation = value; + this._internalAbstractMeshDataInfo._sideOrientationHint = + (this._scene.useRightHandedSystem && value === 1) || + (!this._scene.useRightHandedSystem && value === 0); + } + /** + * @deprecated Please use sideOrientation instead. + * @see https://doc.babylonjs.com/breaking-changes#7110 + */ + get overrideMaterialSideOrientation() { + return this.sideOrientation; + } + set overrideMaterialSideOrientation(value) { + this.sideOrientation = value; + if (this.material) { + this.material.sideOrientation = null; + } + } + /** + * Use this property to override the Material's fillMode value + */ + get overrideRenderingFillMode() { + return this._internalMeshDataInfo._overrideRenderingFillMode; + } + set overrideRenderingFillMode(fillMode) { + this._internalMeshDataInfo._overrideRenderingFillMode = fillMode; + } + get material() { + return this._internalAbstractMeshDataInfo._material; + } + set material(value) { + if (value && ((this.material && this.material.sideOrientation === null) || this._internalAbstractMeshDataInfo._sideOrientationHint)) { + value.sideOrientation = null; + } + this._setMaterial(value); + } + /** + * Gets the source mesh (the one used to clone this one from) + */ + get source() { + return this._internalMeshDataInfo._source; + } + /** + * Gets the list of clones of this mesh + * The scene must have been constructed with useClonedMeshMap=true for this to work! + * Note that useClonedMeshMap=true is the default setting + */ + get cloneMeshMap() { + return this._internalMeshDataInfo.meshMap; + } + /** + * Gets or sets a boolean indicating that this mesh does not use index buffer + */ + get isUnIndexed() { + return this._unIndexed; + } + set isUnIndexed(value) { + if (this._unIndexed !== value) { + this._unIndexed = value; + this._markSubMeshesAsAttributesDirty(); + } + } + /** Gets the array buffer used to store the instanced buffer used for instances' world matrices */ + get worldMatrixInstancedBuffer() { + return this._instanceDataStorage.instancesData; + } + /** Gets the array buffer used to store the instanced buffer used for instances' previous world matrices */ + get previousWorldMatrixInstancedBuffer() { + return this._instanceDataStorage.instancesPreviousData; + } + /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */ + get manualUpdateOfWorldMatrixInstancedBuffer() { + return this._instanceDataStorage.manualUpdate; + } + set manualUpdateOfWorldMatrixInstancedBuffer(value) { + this._instanceDataStorage.manualUpdate = value; + } + /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */ + get manualUpdateOfPreviousWorldMatrixInstancedBuffer() { + return this._instanceDataStorage.previousManualUpdate; + } + set manualUpdateOfPreviousWorldMatrixInstancedBuffer(value) { + this._instanceDataStorage.previousManualUpdate = value; + } + /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices must be performed in all cases (and notably even in frozen mode) */ + get forceWorldMatrixInstancedBufferUpdate() { + return this._instanceDataStorage.forceMatrixUpdates; + } + set forceWorldMatrixInstancedBufferUpdate(value) { + this._instanceDataStorage.forceMatrixUpdates = value; + } + _copySource(source, doNotCloneChildren, clonePhysicsImpostor = true, cloneThinInstances = false) { + const scene = this.getScene(); + // Geometry + if (source._geometry) { + source._geometry.applyToMesh(this); + } + // Deep copy + DeepCopier.DeepCopy(source, this, [ + "name", + "material", + "skeleton", + "instances", + "parent", + "uniqueId", + "source", + "metadata", + "morphTargetManager", + "hasInstances", + "worldMatrixInstancedBuffer", + "previousWorldMatrixInstancedBuffer", + "hasLODLevels", + "geometry", + "isBlocked", + "areNormalsFrozen", + "facetNb", + "isFacetDataEnabled", + "lightSources", + "useBones", + "isAnInstance", + "collider", + "edgesRenderer", + "forward", + "up", + "right", + "absolutePosition", + "absoluteScaling", + "absoluteRotationQuaternion", + "isWorldMatrixFrozen", + "nonUniformScaling", + "behaviors", + "worldMatrixFromCache", + "hasThinInstances", + "cloneMeshMap", + "hasBoundingInfo", + "physicsBody", + "physicsImpostor", + ], ["_poseMatrix"]); + // Source mesh + this._internalMeshDataInfo._source = source; + if (scene.useClonedMeshMap) { + if (!source._internalMeshDataInfo.meshMap) { + source._internalMeshDataInfo.meshMap = {}; + } + source._internalMeshDataInfo.meshMap[this.uniqueId] = this; + } + // Construction Params + // Clone parameters allowing mesh to be updated in case of parametric shapes. + this._originalBuilderSideOrientation = source._originalBuilderSideOrientation; + this._creationDataStorage = source._creationDataStorage; + // Animation ranges + if (source._ranges) { + const ranges = source._ranges; + for (const name in ranges) { + if (!Object.prototype.hasOwnProperty.call(ranges, name)) { + continue; + } + if (!ranges[name]) { + continue; + } + this.createAnimationRange(name, ranges[name].from, ranges[name].to); + } + } + // Metadata + if (source.metadata && source.metadata.clone) { + this.metadata = source.metadata.clone(); + } + else { + this.metadata = source.metadata; + } + this._internalMetadata = source._internalMetadata; + // Tags + if (Tags && Tags.HasTags(source)) { + Tags.AddTagsTo(this, Tags.GetTags(source, true)); + } + // Enabled. We shouldn't need to check the source's ancestors, as this mesh + // will have the same ones. + this.setEnabled(source.isEnabled(false)); + // Parent + this.parent = source.parent; + // Pivot + this.setPivotMatrix(source.getPivotMatrix(), this._postMultiplyPivotMatrix); + this.id = this.name + "." + source.id; + // Material + this.material = source.material; + if (!doNotCloneChildren) { + // Children + const directDescendants = source.getDescendants(true); + for (let index = 0; index < directDescendants.length; index++) { + const child = directDescendants[index]; + if (child._isMesh) { + meshCreationOptions.parent = this; + meshCreationOptions.doNotCloneChildren = doNotCloneChildren; + meshCreationOptions.clonePhysicsImpostor = clonePhysicsImpostor; + meshCreationOptions.cloneThinInstances = cloneThinInstances; + child.clone(this.name + "." + child.name, meshCreationOptions); + } + else if (child.clone) { + child.clone(this.name + "." + child.name, this); + } + } + } + // Morphs + if (source.morphTargetManager) { + this.morphTargetManager = source.morphTargetManager; + } + // Physics clone + if (scene.getPhysicsEngine) { + const physicsEngine = scene.getPhysicsEngine(); + if (clonePhysicsImpostor && physicsEngine) { + if (physicsEngine.getPluginVersion() === 1) { + const impostor = physicsEngine.getImpostorForPhysicsObject(source); + if (impostor) { + this.physicsImpostor = impostor.clone(this); + } + } + else if (physicsEngine.getPluginVersion() === 2) { + if (source.physicsBody) { + source.physicsBody.clone(this); + } + } + } + } + // Particles + for (let index = 0; index < scene.particleSystems.length; index++) { + const system = scene.particleSystems[index]; + if (system.emitter === source) { + system.clone(system.name, this); + } + } + // Skeleton + this.skeleton = source.skeleton; + // Thin instances + if (cloneThinInstances) { + if (source._thinInstanceDataStorage.matrixData) { + this.thinInstanceSetBuffer("matrix", new Float32Array(source._thinInstanceDataStorage.matrixData), 16, !source._thinInstanceDataStorage.matrixBuffer.isUpdatable()); + this._thinInstanceDataStorage.matrixBufferSize = source._thinInstanceDataStorage.matrixBufferSize; + this._thinInstanceDataStorage.instancesCount = source._thinInstanceDataStorage.instancesCount; + } + else { + this._thinInstanceDataStorage.matrixBufferSize = source._thinInstanceDataStorage.matrixBufferSize; + } + if (source._userThinInstanceBuffersStorage) { + const userThinInstance = source._userThinInstanceBuffersStorage; + for (const kind in userThinInstance.data) { + this.thinInstanceSetBuffer(kind, new Float32Array(userThinInstance.data[kind]), userThinInstance.strides[kind], !userThinInstance.vertexBuffers?.[kind]?.isUpdatable()); + this._userThinInstanceBuffersStorage.sizes[kind] = userThinInstance.sizes[kind]; + } + } + } + this.refreshBoundingInfo(true, true); + this.computeWorldMatrix(true); + } + /** @internal */ + constructor(name, scene = null, parentOrOptions = null, source = null, doNotCloneChildren, clonePhysicsImpostor = true) { + super(name, scene); + // Internal data + this._internalMeshDataInfo = new _InternalMeshDataInfo(); + // Members + /** + * Gets the delay loading state of the mesh (when delay loading is turned on) + * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/incrementalLoading + */ + this.delayLoadState = 0; + /** + * Gets the list of instances created from this mesh + * it is not supposed to be modified manually. + * Note also that the order of the InstancedMesh wihin the array is not significant and might change. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances + */ + this.instances = []; + // Private + /** @internal */ + this._creationDataStorage = null; + /** @internal */ + this._geometry = null; + /** @internal */ + this._instanceDataStorage = new _InstanceDataStorage(); + /** @internal */ + this._thinInstanceDataStorage = new _ThinInstanceDataStorage(); + /** @internal */ + this._shouldGenerateFlatShading = false; + // Use by builder only to know what orientation were the mesh build in. + /** @internal */ + this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE; + /** + * Gets or sets a boolean indicating whether to render ignoring the active camera's max z setting. (false by default) + * You should not mix meshes that have this property set to true with meshes that have it set to false if they all write + * to the depth buffer, because the z-values are not comparable in the two cases and you will get rendering artifacts if you do. + * You can set the property to true for meshes that do not write to the depth buffer, or set the same value (either false or true) otherwise. + * Note this will reduce performance when set to true. + */ + this.ignoreCameraMaxZ = false; + scene = this.getScene(); + if (this._scene.useRightHandedSystem) { + this.sideOrientation = 0; + } + else { + this.sideOrientation = 1; + } + this._onBeforeDraw = (isInstance, world, effectiveMaterial) => { + if (isInstance && effectiveMaterial) { + if (this._uniformBuffer) { + this.transferToEffect(world); + } + else { + effectiveMaterial.bindOnlyWorldMatrix(world); + } + } + }; + let parent = null; + let cloneThinInstances = false; + if (parentOrOptions && parentOrOptions._addToSceneRootNodes === undefined) { + const options = parentOrOptions; + parent = options.parent ?? null; + source = options.source ?? null; + doNotCloneChildren = options.doNotCloneChildren ?? false; + clonePhysicsImpostor = options.clonePhysicsImpostor ?? true; + cloneThinInstances = options.cloneThinInstances ?? false; + } + else { + parent = parentOrOptions; + } + if (source) { + this._copySource(source, doNotCloneChildren, clonePhysicsImpostor, cloneThinInstances); + } + // Parent + if (parent !== null) { + this.parent = parent; + } + this._instanceDataStorage.hardwareInstancedRendering = this.getEngine().getCaps().instancedArrays; + this._internalMeshDataInfo._onMeshReadyObserverAdded = (observer) => { + // only notify once! then unregister the observer + observer.unregisterOnNextCall = true; + if (this.isReady(true)) { + this.onMeshReadyObservable.notifyObservers(this); + } + else { + if (!this._internalMeshDataInfo._checkReadinessObserver) { + this._internalMeshDataInfo._checkReadinessObserver = this._scene.onBeforeRenderObservable.add(() => { + // check for complete readiness + if (this.isReady(true)) { + this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver); + this._internalMeshDataInfo._checkReadinessObserver = null; + this.onMeshReadyObservable.notifyObservers(this); + } + }); + } + } + }; + this.onMeshReadyObservable = new Observable(this._internalMeshDataInfo._onMeshReadyObserverAdded); + if (source) { + source.onClonedObservable.notifyObservers(this); + } + } + instantiateHierarchy(newParent = null, options, onNewNodeCreated) { + const instance = this.getTotalVertices() === 0 || (options && options.doNotInstantiate && (options.doNotInstantiate === true || options.doNotInstantiate(this))) + ? this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true) + : this.createInstance("instance of " + (this.name || this.id)); + instance.parent = newParent || this.parent; + instance.position = this.position.clone(); + instance.scaling = this.scaling.clone(); + if (this.rotationQuaternion) { + instance.rotationQuaternion = this.rotationQuaternion.clone(); + } + else { + instance.rotation = this.rotation.clone(); + } + if (onNewNodeCreated) { + onNewNodeCreated(this, instance); + } + for (const child of this.getChildTransformNodes(true)) { + // instancedMesh should have a different sourced mesh + if (child.getClassName() === "InstancedMesh" && instance.getClassName() === "Mesh" && child.sourceMesh === this) { + child.instantiateHierarchy(instance, { + doNotInstantiate: (options && options.doNotInstantiate) || false, + newSourcedMesh: instance, + }, onNewNodeCreated); + } + else { + child.instantiateHierarchy(instance, options, onNewNodeCreated); + } + } + return instance; + } + /** + * Gets the class name + * @returns the string "Mesh". + */ + getClassName() { + return "Mesh"; + } + /** @internal */ + get _isMesh() { + return true; + } + /** + * Returns a description of this mesh + * @param fullDetails define if full details about this mesh must be used + * @returns a descriptive string representing this mesh + */ + toString(fullDetails) { + let ret = super.toString(fullDetails); + ret += ", n vertices: " + this.getTotalVertices(); + ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : this.parent ? this.parent.name : "NONE"); + if (this.animations) { + for (let i = 0; i < this.animations.length; i++) { + ret += ", animation[0]: " + this.animations[i].toString(fullDetails); + } + } + if (fullDetails) { + if (this._geometry) { + const ib = this.getIndices(); + const vb = this.getVerticesData(VertexBuffer.PositionKind); + if (vb && ib) { + ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO"); + } + } + else { + ret += ", flat shading: UNKNOWN"; + } + } + return ret; + } + /** @internal */ + _unBindEffect() { + super._unBindEffect(); + for (const instance of this.instances) { + instance._unBindEffect(); + } + } + /** + * Gets a boolean indicating if this mesh has LOD + */ + get hasLODLevels() { + return this._internalMeshDataInfo._LODLevels.length > 0; + } + /** + * Gets the list of MeshLODLevel associated with the current mesh + * @returns an array of MeshLODLevel + */ + getLODLevels() { + return this._internalMeshDataInfo._LODLevels; + } + _sortLODLevels() { + const sortingOrderFactor = this._internalMeshDataInfo._useLODScreenCoverage ? -1 : 1; + this._internalMeshDataInfo._LODLevels.sort((a, b) => { + if (a.distanceOrScreenCoverage < b.distanceOrScreenCoverage) { + return sortingOrderFactor; + } + if (a.distanceOrScreenCoverage > b.distanceOrScreenCoverage) { + return -sortingOrderFactor; + } + return 0; + }); + } + /** + * Add a mesh as LOD level triggered at the given distance. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD + * @param distanceOrScreenCoverage Either distance from the center of the object to show this level or the screen coverage if `useScreenCoverage` is set to `true`. + * If screen coverage, value is a fraction of the screen's total surface, between 0 and 1. + * Example Playground for distance https://playground.babylonjs.com/#QE7KM#197 + * Example Playground for screen coverage https://playground.babylonjs.com/#QE7KM#196 + * @param mesh The mesh to be added as LOD level (can be null) + * @returns This mesh (for chaining) + */ + addLODLevel(distanceOrScreenCoverage, mesh) { + if (mesh && mesh._masterMesh) { + Logger.Warn("You cannot use a mesh as LOD level twice"); + return this; + } + const level = new MeshLODLevel(distanceOrScreenCoverage, mesh); + this._internalMeshDataInfo._LODLevels.push(level); + if (mesh) { + mesh._masterMesh = this; + } + this._sortLODLevels(); + return this; + } + /** + * Returns the LOD level mesh at the passed distance or null if not found. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD + * @param distance The distance from the center of the object to show this level + * @returns a Mesh or `null` + */ + getLODLevelAtDistance(distance) { + const internalDataInfo = this._internalMeshDataInfo; + for (let index = 0; index < internalDataInfo._LODLevels.length; index++) { + const level = internalDataInfo._LODLevels[index]; + if (level.distanceOrScreenCoverage === distance) { + return level.mesh; + } + } + return null; + } + /** + * Remove a mesh from the LOD array + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD + * @param mesh defines the mesh to be removed + * @returns This mesh (for chaining) + */ + removeLODLevel(mesh) { + const internalDataInfo = this._internalMeshDataInfo; + for (let index = 0; index < internalDataInfo._LODLevels.length; index++) { + if (internalDataInfo._LODLevels[index].mesh === mesh) { + internalDataInfo._LODLevels.splice(index, 1); + if (mesh) { + mesh._masterMesh = null; + } + } + } + this._sortLODLevels(); + return this; + } + /** + * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD + * @param camera defines the camera to use to compute distance + * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh + * @returns This mesh (for chaining) + */ + getLOD(camera, boundingSphere) { + const internalDataInfo = this._internalMeshDataInfo; + if (!internalDataInfo._LODLevels || internalDataInfo._LODLevels.length === 0) { + return this; + } + const bSphere = boundingSphere || this.getBoundingInfo().boundingSphere; + const distanceToCamera = camera.mode === Camera.ORTHOGRAPHIC_CAMERA ? camera.minZ : bSphere.centerWorld.subtract(camera.globalPosition).length(); + let compareValue = distanceToCamera; + let compareSign = 1; + if (internalDataInfo._useLODScreenCoverage) { + const screenArea = camera.screenArea; + let meshArea = (bSphere.radiusWorld * camera.minZ) / distanceToCamera; + meshArea = meshArea * meshArea * Math.PI; + compareValue = meshArea / screenArea; + compareSign = -1; + } + if (compareSign * internalDataInfo._LODLevels[internalDataInfo._LODLevels.length - 1].distanceOrScreenCoverage > compareSign * compareValue) { + if (this.onLODLevelSelection) { + this.onLODLevelSelection(compareValue, this, this); + } + return this; + } + for (let index = 0; index < internalDataInfo._LODLevels.length; index++) { + const level = internalDataInfo._LODLevels[index]; + if (compareSign * level.distanceOrScreenCoverage < compareSign * compareValue) { + if (level.mesh) { + if (level.mesh.delayLoadState === 4) { + level.mesh._checkDelayState(); + return this; + } + if (level.mesh.delayLoadState === 2) { + return this; + } + level.mesh._preActivate(); + level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache); + } + if (this.onLODLevelSelection) { + this.onLODLevelSelection(compareValue, this, level.mesh); + } + return level.mesh; + } + } + if (this.onLODLevelSelection) { + this.onLODLevelSelection(compareValue, this, this); + } + return this; + } + /** + * Gets the mesh internal Geometry object + */ + get geometry() { + return this._geometry; + } + /** + * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry. + * @returns the total number of vertices + */ + getTotalVertices() { + if (this._geometry === null || this._geometry === undefined) { + return 0; + } + return this._geometry.getTotalVertices(); + } + /** + * Returns the content of an associated vertex buffer + * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one + * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is + * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false + * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind. + */ + getVerticesData(kind, copyWhenShared, forceCopy, bypassInstanceData) { + if (!this._geometry) { + return null; + } + let data = bypassInstanceData + ? undefined + : this._userInstancedBuffersStorage?.vertexBuffers[kind]?.getFloatData(this.instances.length + 1, // +1 because the master mesh is not included in the instances array + forceCopy || (copyWhenShared && this._geometry.meshes.length !== 1)); + if (!data) { + data = this._geometry.getVerticesData(kind, copyWhenShared, forceCopy); + } + return data; + } + copyVerticesData(kind, vertexData) { + if (this._geometry) { + this._geometry.copyVerticesData(kind, vertexData); + } + } + /** + * Returns the mesh VertexBuffer object from the requested `kind` + * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.NormalKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false + * @returns a FloatArray or null if the mesh has no vertex buffer for this kind. + */ + getVertexBuffer(kind, bypassInstanceData) { + if (!this._geometry) { + return null; + } + return (bypassInstanceData ? undefined : this._userInstancedBuffersStorage?.vertexBuffers[kind]) ?? this._geometry.getVertexBuffer(kind); + } + /** + * Tests if a specific vertex buffer is associated with this mesh + * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.NormalKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false + * @returns a boolean + */ + isVerticesDataPresent(kind, bypassInstanceData) { + if (!this._geometry) { + if (this._delayInfo) { + return this._delayInfo.indexOf(kind) !== -1; + } + return false; + } + return (!bypassInstanceData && this._userInstancedBuffersStorage?.vertexBuffers[kind] !== undefined) || this._geometry.isVerticesDataPresent(kind); + } + /** + * Returns a boolean defining if the vertex data for the requested `kind` is updatable. + * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false + * @returns a boolean + */ + isVertexBufferUpdatable(kind, bypassInstanceData) { + if (!this._geometry) { + if (this._delayInfo) { + return this._delayInfo.indexOf(kind) !== -1; + } + return false; + } + if (!bypassInstanceData) { + const buffer = this._userInstancedBuffersStorage?.vertexBuffers[kind]; + if (buffer) { + return buffer.isUpdatable(); + } + } + return this._geometry.isVertexBufferUpdatable(kind); + } + /** + * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh. + * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false + * @returns an array of strings + */ + getVerticesDataKinds(bypassInstanceData) { + if (!this._geometry) { + const result = []; + if (this._delayInfo) { + this._delayInfo.forEach(function (kind) { + result.push(kind); + }); + } + return result; + } + const kinds = this._geometry.getVerticesDataKinds(); + if (!bypassInstanceData && this._userInstancedBuffersStorage) { + for (const kind in this._userInstancedBuffersStorage.vertexBuffers) { + if (kinds.indexOf(kind) === -1) { + kinds.push(kind); + } + } + } + return kinds; + } + /** + * Returns a positive integer : the total number of indices in this mesh geometry. + * @returns the numner of indices or zero if the mesh has no geometry. + */ + getTotalIndices() { + if (!this._geometry) { + return 0; + } + return this._geometry.getTotalIndices(); + } + /** + * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices. + * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. + * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it + * @returns the indices array or an empty array if the mesh has no geometry + */ + getIndices(copyWhenShared, forceCopy) { + if (!this._geometry) { + return []; + } + return this._geometry.getIndices(copyWhenShared, forceCopy); + } + get isBlocked() { + return this._masterMesh !== null && this._masterMesh !== undefined; + } + /** + * Determine if the current mesh is ready to be rendered + * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) + * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default) + * @returns true if all associated assets are ready (material, textures, shaders) + */ + isReady(completeCheck = false, forceInstanceSupport = false) { + if (this.delayLoadState === 2) { + return false; + } + if (!super.isReady(completeCheck)) { + return false; + } + if (!this.subMeshes || this.subMeshes.length === 0) { + return true; + } + if (!completeCheck) { + return true; + } + const engine = this.getEngine(); + const scene = this.getScene(); + const hardwareInstancedRendering = forceInstanceSupport || (engine.getCaps().instancedArrays && (this.instances.length > 0 || this.hasThinInstances)); + this.computeWorldMatrix(); + const mat = this.material || scene.defaultMaterial; + if (mat) { + if (mat._storeEffectOnSubMeshes) { + for (const subMesh of this.subMeshes) { + const effectiveMaterial = subMesh.getMaterial(); + if (effectiveMaterial) { + if (effectiveMaterial._storeEffectOnSubMeshes) { + if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) { + return false; + } + } + else { + if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) { + return false; + } + } + } + } + } + else { + if (!mat.isReady(this, hardwareInstancedRendering)) { + return false; + } + } + } + // Shadows + const currentRenderPassId = engine.currentRenderPassId; + for (const light of this.lightSources) { + const generators = light.getShadowGenerators(); + if (!generators) { + continue; + } + const iterator = generators.values(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const generator = key.value; + if (generator && (!generator.getShadowMap()?.renderList || (generator.getShadowMap()?.renderList && generator.getShadowMap()?.renderList?.indexOf(this) !== -1))) { + const shadowMap = generator.getShadowMap(); + const renderPassIds = shadowMap.renderPassIds ?? [engine.currentRenderPassId]; + for (let p = 0; p < renderPassIds.length; ++p) { + engine.currentRenderPassId = renderPassIds[p]; + for (const subMesh of this.subMeshes) { + if (!generator.isReady(subMesh, hardwareInstancedRendering, subMesh.getMaterial()?.needAlphaBlendingForMesh(this) ?? false)) { + engine.currentRenderPassId = currentRenderPassId; + return false; + } + } + } + engine.currentRenderPassId = currentRenderPassId; + } + } + } + // LOD + for (const lod of this._internalMeshDataInfo._LODLevels) { + if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) { + return false; + } + } + return true; + } + /** + * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes. + */ + get areNormalsFrozen() { + return this._internalMeshDataInfo._areNormalsFrozen; + } + /** + * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update. + * @returns the current mesh + */ + freezeNormals() { + this._internalMeshDataInfo._areNormalsFrozen = true; + return this; + } + /** + * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen + * @returns the current mesh + */ + unfreezeNormals() { + this._internalMeshDataInfo._areNormalsFrozen = false; + return this; + } + /** + * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs + */ + set overridenInstanceCount(count) { + this._instanceDataStorage.overridenInstanceCount = count; + } + // Methods + /** @internal */ + _preActivate() { + const internalDataInfo = this._internalMeshDataInfo; + const sceneRenderId = this.getScene().getRenderId(); + if (internalDataInfo._preActivateId === sceneRenderId) { + return this; + } + internalDataInfo._preActivateId = sceneRenderId; + this._instanceDataStorage.visibleInstances = null; + return this; + } + /** + * @internal + */ + _preActivateForIntermediateRendering(renderId) { + if (this._instanceDataStorage.visibleInstances) { + this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId; + } + return this; + } + /** + * @internal + */ + _registerInstanceForRenderId(instance, renderId) { + if (!this._instanceDataStorage.visibleInstances) { + this._instanceDataStorage.visibleInstances = { + defaultRenderId: renderId, + selfDefaultRenderId: this._renderId, + }; + } + if (!this._instanceDataStorage.visibleInstances[renderId]) { + if (this._instanceDataStorage.previousRenderId !== undefined && this._instanceDataStorage.isFrozen) { + this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId] = null; + } + this._instanceDataStorage.previousRenderId = renderId; + this._instanceDataStorage.visibleInstances[renderId] = new Array(); + } + this._instanceDataStorage.visibleInstances[renderId].push(instance); + return this; + } + _afterComputeWorldMatrix() { + super._afterComputeWorldMatrix(); + if (!this.hasThinInstances) { + return; + } + if (!this.doNotSyncBoundingInfo) { + this.thinInstanceRefreshBoundingInfo(false); + } + } + /** @internal */ + _postActivate() { + if (this.edgesShareWithInstances && this.edgesRenderer && this.edgesRenderer.isEnabled && this._renderingGroup) { + this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer); + this.edgesRenderer.customInstances.push(this.getWorldMatrix()); + } + } + /** + * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked. + * This means the mesh underlying bounding box and sphere are recomputed. + * @param applySkeletonOrOptions defines whether to apply the skeleton before computing the bounding info or a set of options + * @param applyMorph defines whether to apply the morph target before computing the bounding info + * @returns the current mesh + */ + refreshBoundingInfo(applySkeletonOrOptions = false, applyMorph = false) { + if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) { + return this; + } + let options; + if (typeof applySkeletonOrOptions === "object") { + options = applySkeletonOrOptions; + } + else { + options = { + applySkeleton: applySkeletonOrOptions, + applyMorph: applyMorph, + }; + } + const bias = this.geometry ? this.geometry.boundingBias : null; + this._refreshBoundingInfo(this._getData(options, null, VertexBuffer.PositionKind), bias); + return this; + } + /** + * @internal + */ + _createGlobalSubMesh(force) { + const totalVertices = this.getTotalVertices(); + if (!totalVertices || !this.getIndices()) { + return null; + } + // Check if we need to recreate the submeshes + if (this.subMeshes && this.subMeshes.length > 0) { + const ib = this.getIndices(); + if (!ib) { + return null; + } + const totalIndices = ib.length; + let needToRecreate = false; + if (force) { + needToRecreate = true; + } + else { + for (const submesh of this.subMeshes) { + if (submesh.indexStart + submesh.indexCount > totalIndices) { + needToRecreate = true; + break; + } + if (submesh.verticesStart + submesh.verticesCount > totalVertices) { + needToRecreate = true; + break; + } + } + } + if (!needToRecreate) { + return this.subMeshes[0]; + } + } + this.releaseSubMeshes(); + return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices() || totalVertices, this); // getTotalIndices() can be zero if the mesh is unindexed + } + /** + * This function will subdivide the mesh into multiple submeshes + * @param count defines the expected number of submeshes + */ + subdivide(count) { + if (count < 1) { + return; + } + const totalIndices = this.getTotalIndices(); + let subdivisionSize = (totalIndices / count) | 0; + let offset = 0; + // Ensure that subdivisionSize is a multiple of 3 + while (subdivisionSize % 3 !== 0) { + subdivisionSize++; + } + this.releaseSubMeshes(); + for (let index = 0; index < count; index++) { + if (offset >= totalIndices) { + break; + } + SubMesh.CreateFromIndices(0, offset, index === count - 1 ? totalIndices - offset : subdivisionSize, this, undefined, false); + offset += subdivisionSize; + } + this.refreshBoundingInfo(); + this.synchronizeInstances(); + } + /** + * Copy a FloatArray into a specific associated vertex buffer + * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + * @param data defines the data source + * @param updatable defines if the updated vertex buffer must be flagged as updatable + * @param stride defines the data stride size (can be null) + * @returns the current mesh + */ + setVerticesData(kind, data, updatable = false, stride) { + if (!this._geometry) { + const vertexData = new VertexData(); + vertexData.set(data, kind); + const scene = this.getScene(); + new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this); + } + else { + this._geometry.setVerticesData(kind, data, updatable, stride); + } + return this; + } + /** + * Delete a vertex buffer associated with this mesh + * @param kind defines which buffer to delete (positions, indices, normals, etc). Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + */ + removeVerticesData(kind) { + if (!this._geometry) { + return; + } + this._geometry.removeVerticesData(kind); + } + /** + * Flags an associated vertex buffer as updatable + * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + * @param updatable defines if the updated vertex buffer must be flagged as updatable + */ + markVerticesDataAsUpdatable(kind, updatable = true) { + const vb = this.getVertexBuffer(kind); + if (!vb || vb.isUpdatable() === updatable) { + return; + } + this.setVerticesData(kind, this.getVerticesData(kind), updatable); + } + /** + * Sets the mesh global Vertex Buffer + * @param buffer defines the buffer to use + * @param disposeExistingBuffer disposes the existing buffer, if any (default: true) + * @returns the current mesh + */ + setVerticesBuffer(buffer, disposeExistingBuffer = true) { + if (!this._geometry) { + this._geometry = Geometry.CreateGeometryForMesh(this); + } + this._geometry.setVerticesBuffer(buffer, null, disposeExistingBuffer); + return this; + } + /** + * Update a specific associated vertex buffer + * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + * @param data defines the data source + * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind + * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry) + * @returns the current mesh + */ + updateVerticesData(kind, data, updateExtends, makeItUnique) { + if (!this._geometry) { + return this; + } + if (!makeItUnique) { + this._geometry.updateVerticesData(kind, data, updateExtends); + } + else { + this.makeGeometryUnique(); + this.updateVerticesData(kind, data, updateExtends, false); + } + return this; + } + /** + * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#other-shapes-updatemeshpositions + * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything + * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update + * @returns the current mesh + */ + updateMeshPositions(positionFunction, computeNormals = true) { + const positions = this.getVerticesData(VertexBuffer.PositionKind); + if (!positions) { + return this; + } + positionFunction(positions); + this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false); + if (computeNormals) { + const indices = this.getIndices(); + const normals = this.getVerticesData(VertexBuffer.NormalKind); + if (!normals) { + return this; + } + VertexData.ComputeNormals(positions, indices, normals); + this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false); + } + return this; + } + /** + * Creates a un-shared specific occurence of the geometry for the mesh. + * @returns the current mesh + */ + makeGeometryUnique() { + if (!this._geometry) { + return this; + } + if (this._geometry.meshes.length === 1) { + return this; + } + const oldGeometry = this._geometry; + const geometry = this._geometry.copy(Geometry.RandomId()); + oldGeometry.releaseForMesh(this, true); + geometry.applyToMesh(this); + return this; + } + /** + * Sets the index buffer of this mesh. + * @param indexBuffer Defines the index buffer to use for this mesh + * @param totalVertices Defines the total number of vertices used by the buffer + * @param totalIndices Defines the total number of indices in the index buffer + * @param is32Bits Defines if the indices are 32 bits. If null (default), the value is guessed from the number of vertices + */ + setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits = null) { + let geometry = this._geometry; + if (!geometry) { + geometry = new Geometry(Geometry.RandomId(), this.getScene(), undefined, undefined, this); + } + geometry.setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits); + } + /** + * Set the index buffer of this mesh + * @param indices defines the source data + * @param totalVertices defines the total number of vertices referenced by this index data (can be null) + * @param updatable defines if the updated index buffer must be flagged as updatable (default is false) + * @param dontForceSubMeshRecreation defines a boolean indicating that we don't want to force the recreation of sub-meshes if we don't have to (false by default) + * @returns the current mesh + */ + setIndices(indices, totalVertices = null, updatable = false, dontForceSubMeshRecreation = false) { + if (!this._geometry) { + const vertexData = new VertexData(); + vertexData.indices = indices; + const scene = this.getScene(); + new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this); + } + else { + this._geometry.setIndices(indices, totalVertices, updatable, dontForceSubMeshRecreation); + } + return this; + } + /** + * Update the current index buffer + * @param indices defines the source data + * @param offset defines the offset in the index buffer where to store the new data (can be null) + * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default) + * @returns the current mesh + */ + updateIndices(indices, offset, gpuMemoryOnly = false) { + if (!this._geometry) { + return this; + } + this._geometry.updateIndices(indices, offset, gpuMemoryOnly); + return this; + } + /** + * Invert the geometry to move from a right handed system to a left handed one. + * @returns the current mesh + */ + toLeftHanded() { + if (!this._geometry) { + return this; + } + this._geometry.toLeftHanded(); + return this; + } + /** + * @internal + */ + _bind(subMesh, effect, fillMode, allowInstancedRendering = true) { + if (!this._geometry) { + return this; + } + const engine = this.getScene().getEngine(); + // Wireframe + let indexToBind; + if (this._unIndexed) { + switch (this._getRenderingFillMode(fillMode)) { + case Material.WireFrameFillMode: + indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine); + break; + default: + indexToBind = null; + break; + } + } + else { + switch (this._getRenderingFillMode(fillMode)) { + case Material.PointFillMode: + indexToBind = null; + break; + case Material.WireFrameFillMode: + indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine); + break; + default: + case Material.TriangleFillMode: + indexToBind = this._geometry.getIndexBuffer(); + break; + } + } + return this._bindDirect(effect, indexToBind, allowInstancedRendering); + } + /** + * @internal + */ + _bindDirect(effect, indexToBind, allowInstancedRendering = true) { + if (!this._geometry) { + return this; + } + // Morph targets + if (this.morphTargetManager && this.morphTargetManager.isUsingTextureForTargets) { + this.morphTargetManager._bind(effect); + } + // VBOs + if (!allowInstancedRendering || !this._userInstancedBuffersStorage || this.hasThinInstances) { + this._geometry._bind(effect, indexToBind); + } + else { + this._geometry._bind(effect, indexToBind, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects); + } + return this; + } + /** + * @internal + */ + _draw(subMesh, fillMode, instancesCount) { + if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { + return this; + } + if (this._internalMeshDataInfo._onBeforeDrawObservable) { + this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this); + } + const scene = this.getScene(); + const engine = scene.getEngine(); + if ((this._unIndexed && fillMode !== Material.WireFrameFillMode) || fillMode == Material.PointFillMode) { + // or triangles as points + engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, this.forcedInstanceCount || instancesCount); + } + else if (fillMode == Material.WireFrameFillMode) { + // Triangles as wireframe + engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, this.forcedInstanceCount || instancesCount); + } + else { + engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, this.forcedInstanceCount || instancesCount); + } + return this; + } + /** + * Registers for this mesh a javascript function called just before the rendering process + * @param func defines the function to call before rendering this mesh + * @returns the current mesh + */ + registerBeforeRender(func) { + this.onBeforeRenderObservable.add(func); + return this; + } + /** + * Disposes a previously registered javascript function called before the rendering + * @param func defines the function to remove + * @returns the current mesh + */ + unregisterBeforeRender(func) { + this.onBeforeRenderObservable.removeCallback(func); + return this; + } + /** + * Registers for this mesh a javascript function called just after the rendering is complete + * @param func defines the function to call after rendering this mesh + * @returns the current mesh + */ + registerAfterRender(func) { + this.onAfterRenderObservable.add(func); + return this; + } + /** + * Disposes a previously registered javascript function called after the rendering. + * @param func defines the function to remove + * @returns the current mesh + */ + unregisterAfterRender(func) { + this.onAfterRenderObservable.removeCallback(func); + return this; + } + /** + * @internal + */ + _getInstancesRenderList(subMeshId, isReplacementMode = false) { + if (this._instanceDataStorage.isFrozen) { + if (isReplacementMode) { + this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[subMeshId] = false; + this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[subMeshId] = true; + return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode; + } + if (this._instanceDataStorage.previousBatch) { + return this._instanceDataStorage.previousBatch; + } + } + const scene = this.getScene(); + const isInIntermediateRendering = scene._isInIntermediateRendering(); + const onlyForInstances = isInIntermediateRendering + ? this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate + : this._internalAbstractMeshDataInfo._onlyForInstances; + const batchCache = this._instanceDataStorage.batchCache; + batchCache.mustReturn = false; + batchCache.renderSelf[subMeshId] = isReplacementMode || (!onlyForInstances && this.isEnabled() && this.isVisible); + batchCache.visibleInstances[subMeshId] = null; + if (this._instanceDataStorage.visibleInstances && !isReplacementMode) { + const visibleInstances = this._instanceDataStorage.visibleInstances; + const currentRenderId = scene.getRenderId(); + const defaultRenderId = isInIntermediateRendering ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId; + batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId]; + if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) { + batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId]; + } + } + batchCache.hardwareInstancedRendering[subMeshId] = + !isReplacementMode && + this._instanceDataStorage.hardwareInstancedRendering && + batchCache.visibleInstances[subMeshId] !== null && + batchCache.visibleInstances[subMeshId] !== undefined; + this._instanceDataStorage.previousBatch = batchCache; + return batchCache; + } + /** + * This method will also draw the instances if fillMode and effect are passed + * @internal + */ + _updateInstancedBuffers(subMesh, batch, currentInstancesBufferSize, engine, fillMode, effect) { + const visibleInstances = batch.visibleInstances[subMesh._id]; + const visibleInstanceCount = visibleInstances ? visibleInstances.length : 0; + const instanceStorage = this._instanceDataStorage; + let instancesBuffer = instanceStorage.instancesBuffer; + let instancesPreviousBuffer = instanceStorage.instancesPreviousBuffer; + let offset = 0; + let instancesCount = 0; + const renderSelf = batch.renderSelf[subMesh._id]; + const needUpdateBuffer = !instancesBuffer || + currentInstancesBufferSize !== instanceStorage.instancesBufferSize || + (this._scene.needsPreviousWorldMatrices && !instanceStorage.instancesPreviousBuffer); + if (!this._instanceDataStorage.manualUpdate && (!instanceStorage.isFrozen || needUpdateBuffer)) { + const world = this.getWorldMatrix(); + if (renderSelf) { + if (this._scene.needsPreviousWorldMatrices) { + if (!instanceStorage.masterMeshPreviousWorldMatrix) { + instanceStorage.masterMeshPreviousWorldMatrix = world.clone(); + instanceStorage.masterMeshPreviousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); + } + else { + instanceStorage.masterMeshPreviousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); + instanceStorage.masterMeshPreviousWorldMatrix.copyFrom(world); + } + } + world.copyToArray(instanceStorage.instancesData, offset); + offset += 16; + instancesCount++; + } + if (visibleInstances) { + if (Mesh.INSTANCEDMESH_SORT_TRANSPARENT && this._scene.activeCamera && subMesh.getMaterial()?.needAlphaBlendingForMesh(subMesh.getRenderingMesh())) { + const cameraPosition = this._scene.activeCamera.globalPosition; + for (let instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) { + const instanceMesh = visibleInstances[instanceIndex]; + instanceMesh._distanceToCamera = Vector3.Distance(instanceMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition); + } + visibleInstances.sort((m1, m2) => { + return m1._distanceToCamera > m2._distanceToCamera ? -1 : m1._distanceToCamera < m2._distanceToCamera ? 1 : 0; + }); + } + for (let instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) { + const instance = visibleInstances[instanceIndex]; + const matrix = instance.getWorldMatrix(); + matrix.copyToArray(instanceStorage.instancesData, offset); + if (this._scene.needsPreviousWorldMatrices) { + if (!instance._previousWorldMatrix) { + instance._previousWorldMatrix = matrix.clone(); + instance._previousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); + } + else { + instance._previousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); + instance._previousWorldMatrix.copyFrom(matrix); + } + } + offset += 16; + instancesCount++; + } + } + } + else { + instancesCount = (renderSelf ? 1 : 0) + visibleInstanceCount; + } + if (needUpdateBuffer) { + if (instancesBuffer) { + instancesBuffer.dispose(); + } + if (instancesPreviousBuffer) { + instancesPreviousBuffer.dispose(); + } + instancesBuffer = new Buffer(engine, instanceStorage.instancesData, true, 16, false, true); + instanceStorage.instancesBuffer = instancesBuffer; + if (!this._userInstancedBuffersStorage) { + this._userInstancedBuffersStorage = { + data: {}, + vertexBuffers: {}, + strides: {}, + sizes: {}, + vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : undefined, + }; + } + this._userInstancedBuffersStorage.vertexBuffers["world0"] = instancesBuffer.createVertexBuffer("world0", 0, 4); + this._userInstancedBuffersStorage.vertexBuffers["world1"] = instancesBuffer.createVertexBuffer("world1", 4, 4); + this._userInstancedBuffersStorage.vertexBuffers["world2"] = instancesBuffer.createVertexBuffer("world2", 8, 4); + this._userInstancedBuffersStorage.vertexBuffers["world3"] = instancesBuffer.createVertexBuffer("world3", 12, 4); + if (this._scene.needsPreviousWorldMatrices) { + instancesPreviousBuffer = new Buffer(engine, instanceStorage.instancesPreviousData, true, 16, false, true); + instanceStorage.instancesPreviousBuffer = instancesPreviousBuffer; + this._userInstancedBuffersStorage.vertexBuffers["previousWorld0"] = instancesPreviousBuffer.createVertexBuffer("previousWorld0", 0, 4); + this._userInstancedBuffersStorage.vertexBuffers["previousWorld1"] = instancesPreviousBuffer.createVertexBuffer("previousWorld1", 4, 4); + this._userInstancedBuffersStorage.vertexBuffers["previousWorld2"] = instancesPreviousBuffer.createVertexBuffer("previousWorld2", 8, 4); + this._userInstancedBuffersStorage.vertexBuffers["previousWorld3"] = instancesPreviousBuffer.createVertexBuffer("previousWorld3", 12, 4); + } + this._invalidateInstanceVertexArrayObject(); + } + else { + if (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) { + instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount); + if (this._scene.needsPreviousWorldMatrices && (!this._instanceDataStorage.manualUpdate || this._instanceDataStorage.previousManualUpdate)) { + instancesPreviousBuffer.updateDirectly(instanceStorage.instancesPreviousData, 0, instancesCount); + } + } + } + this._processInstancedBuffers(visibleInstances, renderSelf); + if (effect && fillMode !== undefined) { + // Stats + this.getScene()._activeIndices.addCount(subMesh.indexCount * instancesCount, false); + // Draw + if (engine._currentDrawContext) { + engine._currentDrawContext.useInstancing = true; + } + this._bind(subMesh, effect, fillMode); + this._draw(subMesh, fillMode, instancesCount); + } + // Write current matrices as previous matrices in case of manual update + // Default behaviour when previous matrices are not specified explicitly + // Will break if instances number/order changes + if (this._scene.needsPreviousWorldMatrices && + !needUpdateBuffer && + this._instanceDataStorage.manualUpdate && + (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) && + !this._instanceDataStorage.previousManualUpdate) { + instancesPreviousBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount); + } + } + /** + * @internal + */ + _renderWithInstances(subMesh, fillMode, batch, effect, engine) { + const visibleInstances = batch.visibleInstances[subMesh._id]; + const visibleInstanceCount = visibleInstances ? visibleInstances.length : 0; + const instanceStorage = this._instanceDataStorage; + const currentInstancesBufferSize = instanceStorage.instancesBufferSize; + const matricesCount = visibleInstanceCount + 1; + const bufferSize = matricesCount * 16 * 4; + while (instanceStorage.instancesBufferSize < bufferSize) { + instanceStorage.instancesBufferSize *= 2; + } + if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) { + instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4); + } + if ((this._scene.needsPreviousWorldMatrices && !instanceStorage.instancesPreviousData) || currentInstancesBufferSize != instanceStorage.instancesBufferSize) { + instanceStorage.instancesPreviousData = new Float32Array(instanceStorage.instancesBufferSize / 4); + } + this._updateInstancedBuffers(subMesh, batch, currentInstancesBufferSize, engine, fillMode, effect); + engine.unbindInstanceAttributes(); + return this; + } + /** + * @internal + */ + _renderWithThinInstances(subMesh, fillMode, effect, engine) { + // Stats + const instancesCount = this._thinInstanceDataStorage?.instancesCount ?? 0; + this.getScene()._activeIndices.addCount(subMesh.indexCount * instancesCount, false); + // Draw + if (engine._currentDrawContext) { + engine._currentDrawContext.useInstancing = true; + } + this._bind(subMesh, effect, fillMode); + this._draw(subMesh, fillMode, instancesCount); + // Write current matrices as previous matrices + // Default behaviour when previous matrices are not specified explicitly + // Will break if instances number/order changes + if (this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData && this._thinInstanceDataStorage.matrixData) { + if (!this._thinInstanceDataStorage.previousMatrixBuffer) { + this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", this._thinInstanceDataStorage.matrixData, false); + } + else { + this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, instancesCount); + } + } + engine.unbindInstanceAttributes(); + } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _processInstancedBuffers(visibleInstances, renderSelf) { + // Do nothing + } + /** + * @internal + */ + _processRendering(renderingMesh, subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) { + const scene = this.getScene(); + const engine = scene.getEngine(); + fillMode = this._getRenderingFillMode(fillMode); + if (hardwareInstancedRendering && subMesh.getRenderingMesh().hasThinInstances) { + this._renderWithThinInstances(subMesh, fillMode, effect, engine); + return this; + } + if (hardwareInstancedRendering) { + this._renderWithInstances(subMesh, fillMode, batch, effect, engine); + } + else { + if (engine._currentDrawContext) { + engine._currentDrawContext.useInstancing = false; + } + let instanceCount = 0; + if (batch.renderSelf[subMesh._id]) { + // Draw + if (onBeforeDraw) { + onBeforeDraw(false, renderingMesh.getWorldMatrix(), effectiveMaterial); + } + instanceCount++; + this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount); + } + const visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id]; + if (visibleInstancesForSubMesh) { + const visibleInstanceCount = visibleInstancesForSubMesh.length; + instanceCount += visibleInstanceCount; + // Stats + for (let instanceIndex = 0; instanceIndex < visibleInstanceCount; instanceIndex++) { + const instance = visibleInstancesForSubMesh[instanceIndex]; + // World + const world = instance.getWorldMatrix(); + if (onBeforeDraw) { + onBeforeDraw(true, world, effectiveMaterial); + } + // Draw + this._draw(subMesh, fillMode); + } + } + // Stats + scene._activeIndices.addCount(subMesh.indexCount * instanceCount, false); + } + return this; + } + /** + * @internal + */ + _rebuild(dispose = false) { + if (this._instanceDataStorage.instancesBuffer) { + // Dispose instance buffer to be recreated in _renderWithInstances when rendered + if (dispose) { + this._instanceDataStorage.instancesBuffer.dispose(); + } + this._instanceDataStorage.instancesBuffer = null; + } + if (this._userInstancedBuffersStorage) { + for (const kind in this._userInstancedBuffersStorage.vertexBuffers) { + const buffer = this._userInstancedBuffersStorage.vertexBuffers[kind]; + if (buffer) { + // Dispose instance buffer to be recreated in _renderWithInstances when rendered + if (dispose) { + buffer.dispose(); + } + this._userInstancedBuffersStorage.vertexBuffers[kind] = null; + } + } + if (this._userInstancedBuffersStorage.vertexArrayObjects) { + this._userInstancedBuffersStorage.vertexArrayObjects = {}; + } + } + this._internalMeshDataInfo._effectiveMaterial = null; + super._rebuild(dispose); + } + /** @internal */ + _freeze() { + if (!this.subMeshes) { + return; + } + // Prepare batches + for (let index = 0; index < this.subMeshes.length; index++) { + this._getInstancesRenderList(index); + } + this._internalMeshDataInfo._effectiveMaterial = null; + this._instanceDataStorage.isFrozen = true; + } + /** @internal */ + _unFreeze() { + this._instanceDataStorage.isFrozen = false; + this._instanceDataStorage.previousBatch = null; + } + /** + * Triggers the draw call for the mesh (or a submesh), for a specific render pass id + * @param renderPassId defines the render pass id to use to draw the mesh / submesh. If not provided, use the current renderPassId of the engine. + * @param enableAlphaMode defines if alpha mode can be changed (default: false) + * @param effectiveMeshReplacement defines an optional mesh used to provide info for the rendering (default: undefined) + * @param subMesh defines the subMesh to render. If not provided, draw all mesh submeshes (default: undefined) + * @param checkFrustumCulling defines if frustum culling must be checked (default: true). If you know the mesh is in the frustum (or if you don't care!), you can pass false to optimize. + * @returns the current mesh + */ + renderWithRenderPassId(renderPassId, enableAlphaMode, effectiveMeshReplacement, subMesh, checkFrustumCulling = true) { + const engine = this._scene.getEngine(); + const currentRenderPassId = engine.currentRenderPassId; + if (renderPassId !== undefined) { + engine.currentRenderPassId = renderPassId; + } + if (subMesh) { + if (!checkFrustumCulling || (checkFrustumCulling && subMesh.isInFrustum(this._scene._frustumPlanes))) { + this.render(subMesh, !!enableAlphaMode, effectiveMeshReplacement); + } + } + else { + for (let s = 0; s < this.subMeshes.length; s++) { + const subMesh = this.subMeshes[s]; + if (!checkFrustumCulling || (checkFrustumCulling && subMesh.isInFrustum(this._scene._frustumPlanes))) { + this.render(subMesh, !!enableAlphaMode, effectiveMeshReplacement); + } + } + } + if (renderPassId !== undefined) { + engine.currentRenderPassId = currentRenderPassId; + } + return this; + } + /** + * Render a complete mesh by going through all submeshes + * @returns the current mesh + * @see [simple test](https://playground.babylonjs.com/#5SPY1V#2) + * @see [perf test](https://playground.babylonjs.com/#5SPY1V#5) + */ + directRender() { + if (!this.subMeshes) { + return this; + } + for (const submesh of this.subMeshes) { + this.render(submesh, false); + } + return this; + } + /** + * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager + * @param subMesh defines the subMesh to render + * @param enableAlphaMode defines if alpha mode can be changed + * @param effectiveMeshReplacement defines an optional mesh used to provide info for the rendering + * @returns the current mesh + */ + render(subMesh, enableAlphaMode, effectiveMeshReplacement) { + const scene = this.getScene(); + if (this._internalAbstractMeshDataInfo._isActiveIntermediate) { + this._internalAbstractMeshDataInfo._isActiveIntermediate = false; + } + else { + this._internalAbstractMeshDataInfo._isActive = false; + } + const numActiveCameras = scene.activeCameras?.length ?? 0; + const canCheckOcclusionQuery = (numActiveCameras > 1 && scene.activeCamera === scene.activeCameras[0]) || numActiveCameras <= 1; + if (canCheckOcclusionQuery && this._checkOcclusionQuery() && !this._occlusionDataStorage.forceRenderingWhenOccluded) { + return this; + } + // Managing instances + const batch = this._getInstancesRenderList(subMesh._id, !!effectiveMeshReplacement); + if (batch.mustReturn) { + return this; + } + // Checking geometry state + if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { + return this; + } + const engine = scene.getEngine(); + let oldCameraMaxZ = 0; + let oldCamera = null; + if (this.ignoreCameraMaxZ && scene.activeCamera && !scene._isInIntermediateRendering()) { + oldCameraMaxZ = scene.activeCamera.maxZ; + oldCamera = scene.activeCamera; + scene.activeCamera.maxZ = 0; + scene.updateTransformMatrix(true); + } + if (this._internalMeshDataInfo._onBeforeRenderObservable) { + this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this); + } + const renderingMesh = subMesh.getRenderingMesh(); + const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || + renderingMesh.hasThinInstances || + (!!this._userInstancedBuffersStorage && !subMesh.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh); + const instanceDataStorage = this._instanceDataStorage; + const material = subMesh.getMaterial(); + if (!material) { + if (oldCamera) { + oldCamera.maxZ = oldCameraMaxZ; + scene.updateTransformMatrix(true); + } + return this; + } + // Material + if (!instanceDataStorage.isFrozen || !this._internalMeshDataInfo._effectiveMaterial || this._internalMeshDataInfo._effectiveMaterial !== material) { + if (material._storeEffectOnSubMeshes) { + if (!material.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) { + if (oldCamera) { + oldCamera.maxZ = oldCameraMaxZ; + scene.updateTransformMatrix(true); + } + return this; + } + } + else if (!material.isReady(this, hardwareInstancedRendering)) { + if (oldCamera) { + oldCamera.maxZ = oldCameraMaxZ; + scene.updateTransformMatrix(true); + } + return this; + } + this._internalMeshDataInfo._effectiveMaterial = material; + } + else if ((material._storeEffectOnSubMeshes && !subMesh._drawWrapper?._wasPreviouslyReady) || + (!material._storeEffectOnSubMeshes && !material._getDrawWrapper()._wasPreviouslyReady)) { + if (oldCamera) { + oldCamera.maxZ = oldCameraMaxZ; + scene.updateTransformMatrix(true); + } + return this; + } + // Alpha mode + if (enableAlphaMode) { + engine.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode); + } + let drawWrapper; + if (this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes) { + drawWrapper = subMesh._drawWrapper; + } + else { + drawWrapper = this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper(); + } + const effect = drawWrapper?.effect ?? null; + for (const step of scene._beforeRenderingMeshStage) { + step.action(this, subMesh, batch, effect); + } + if (!drawWrapper || !effect) { + if (oldCamera) { + oldCamera.maxZ = oldCameraMaxZ; + scene.updateTransformMatrix(true); + } + return this; + } + const effectiveMesh = effectiveMeshReplacement || this; + let sideOrientation; + if (!instanceDataStorage.isFrozen && + (this._internalMeshDataInfo._effectiveMaterial.backFaceCulling || + this._internalMeshDataInfo._effectiveMaterial.sideOrientation !== null || + this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)) { + // Note: if two sided lighting is enabled, we need to ensure that the normal will point in the right direction even if the determinant of the world matrix is negative + const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant(); + sideOrientation = this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this); + if (mainDeterminant < 0) { + sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation; + } + instanceDataStorage.sideOrientation = sideOrientation; + } + else { + sideOrientation = instanceDataStorage.sideOrientation; + } + const reverse = this._internalMeshDataInfo._effectiveMaterial._preBind(drawWrapper, sideOrientation); + if (this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite) { + engine.setDepthWrite(true); + } + // Bind + const effectiveMaterial = this._internalMeshDataInfo._effectiveMaterial; + const fillMode = effectiveMaterial.fillMode; + if (this._internalMeshDataInfo._onBeforeBindObservable) { + this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this); + } + if (!hardwareInstancedRendering) { + // Binding will be done later because we need to add more info to the VB + this._bind(subMesh, effect, fillMode, false); + } + const world = effectiveMesh.getWorldMatrix(); + if (effectiveMaterial._storeEffectOnSubMeshes) { + effectiveMaterial.bindForSubMesh(world, this, subMesh); + } + else { + effectiveMaterial.bind(world, this); + } + if (!effectiveMaterial.backFaceCulling && effectiveMaterial.separateCullingPass) { + engine.setState(true, effectiveMaterial.zOffset, false, !reverse, effectiveMaterial.cullBackFaces, effectiveMaterial.stencil, effectiveMaterial.zOffsetUnits); + this._processRendering(this, subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial); + engine.setState(true, effectiveMaterial.zOffset, false, reverse, effectiveMaterial.cullBackFaces, effectiveMaterial.stencil, effectiveMaterial.zOffsetUnits); + if (this._internalMeshDataInfo._onBetweenPassObservable) { + this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(subMesh); + } + } + // Draw + this._processRendering(this, subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial); + // Unbind + this._internalMeshDataInfo._effectiveMaterial.unbind(); + for (const step of scene._afterRenderingMeshStage) { + step.action(this, subMesh, batch, effect); + } + if (this._internalMeshDataInfo._onAfterRenderObservable) { + this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this); + } + if (oldCamera) { + oldCamera.maxZ = oldCameraMaxZ; + scene.updateTransformMatrix(true); + } + if (scene.performancePriority === 2 /* ScenePerformancePriority.Aggressive */ && !instanceDataStorage.isFrozen) { + this._freeze(); + } + return this; + } + /** + * Renormalize the mesh and patch it up if there are no weights + * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1. + * However in the case of zero weights then we set just a single influence to 1. + * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version. + */ + cleanMatrixWeights() { + if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) { + if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) { + this._normalizeSkinWeightsAndExtra(); + } + else { + this._normalizeSkinFourWeights(); + } + } + } + // faster 4 weight version. + _normalizeSkinFourWeights() { + const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind); + const numWeights = matricesWeights.length; + for (let a = 0; a < numWeights; a += 4) { + // accumulate weights + const t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3]; + // check for invalid weight and just set it to 1. + if (t === 0) { + matricesWeights[a] = 1; + } + else { + // renormalize so everything adds to 1 use reciprocal + const recip = 1 / t; + matricesWeights[a] *= recip; + matricesWeights[a + 1] *= recip; + matricesWeights[a + 2] *= recip; + matricesWeights[a + 3] *= recip; + } + } + this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights); + } + // handle special case of extra verts. (in theory gltf can handle 12 influences) + _normalizeSkinWeightsAndExtra() { + const matricesWeightsExtra = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind); + const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind); + const numWeights = matricesWeights.length; + for (let a = 0; a < numWeights; a += 4) { + // accumulate weights + let t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3]; + t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3]; + // check for invalid weight and just set it to 1. + if (t === 0) { + matricesWeights[a] = 1; + } + else { + // renormalize so everything adds to 1 use reciprocal + const recip = 1 / t; + matricesWeights[a] *= recip; + matricesWeights[a + 1] *= recip; + matricesWeights[a + 2] *= recip; + matricesWeights[a + 3] *= recip; + // same goes for extras + matricesWeightsExtra[a] *= recip; + matricesWeightsExtra[a + 1] *= recip; + matricesWeightsExtra[a + 2] *= recip; + matricesWeightsExtra[a + 3] *= recip; + } + } + this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights); + this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsExtra); + } + /** + * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights, + * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let + * the user know there was an issue with importing the mesh + * @returns a validation object with skinned, valid and report string + */ + validateSkinning() { + const matricesWeightsExtra = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind); + const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind); + if (matricesWeights === null || this.skeleton == null) { + return { skinned: false, valid: true, report: "not skinned" }; + } + const numWeights = matricesWeights.length; + let numberNotSorted = 0; + let missingWeights = 0; + let maxUsedWeights = 0; + let numberNotNormalized = 0; + const numInfluences = matricesWeightsExtra === null ? 4 : 8; + const usedWeightCounts = []; + for (let a = 0; a <= numInfluences; a++) { + usedWeightCounts[a] = 0; + } + const toleranceEpsilon = 0.001; + for (let a = 0; a < numWeights; a += 4) { + let lastWeight = matricesWeights[a]; + let t = lastWeight; + let usedWeights = t === 0 ? 0 : 1; + for (let b = 1; b < numInfluences; b++) { + const d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4]; + if (d > lastWeight) { + numberNotSorted++; + } + if (d !== 0) { + usedWeights++; + } + t += d; + lastWeight = d; + } + // count the buffer weights usage + usedWeightCounts[usedWeights]++; + // max influences + if (usedWeights > maxUsedWeights) { + maxUsedWeights = usedWeights; + } + // check for invalid weight and just set it to 1. + if (t === 0) { + missingWeights++; + } + else { + // renormalize so everything adds to 1 use reciprocal + const recip = 1 / t; + let tolerance = 0; + for (let b = 0; b < numInfluences; b++) { + if (b < 4) { + tolerance += Math.abs(matricesWeights[a + b] - matricesWeights[a + b] * recip); + } + else { + tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - matricesWeightsExtra[a + b - 4] * recip); + } + } + // arbitrary epsilon value for dictating not normalized + if (tolerance > toleranceEpsilon) { + numberNotNormalized++; + } + } + } + // validate bone indices are in range of the skeleton + const numBones = this.skeleton.bones.length; + const matricesIndices = this.getVerticesData(VertexBuffer.MatricesIndicesKind); + const matricesIndicesExtra = this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind); + let numBadBoneIndices = 0; + for (let a = 0; a < numWeights; a += 4) { + for (let b = 0; b < numInfluences; b++) { + const index = b < 4 ? matricesIndices[a + b] : matricesIndicesExtra[a + b - 4]; + if (index >= numBones || index < 0) { + numBadBoneIndices++; + } + } + } + // log mesh stats + const output = "Number of Weights = " + + numWeights / 4 + + "\nMaximum influences = " + + maxUsedWeights + + "\nMissing Weights = " + + missingWeights + + "\nNot Sorted = " + + numberNotSorted + + "\nNot Normalized = " + + numberNotNormalized + + "\nWeightCounts = [" + + usedWeightCounts + + "]" + + "\nNumber of bones = " + + numBones + + "\nBad Bone Indices = " + + numBadBoneIndices; + return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output }; + } + /** @internal */ + _checkDelayState() { + const scene = this.getScene(); + if (this._geometry) { + this._geometry.load(scene); + } + else if (this.delayLoadState === 4) { + this.delayLoadState = 2; + this._queueLoad(scene); + } + return this; + } + _queueLoad(scene) { + scene.addPendingData(this); + const getBinaryData = this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1; + Tools.LoadFile(this.delayLoadingFile, (data) => { + if (data instanceof ArrayBuffer) { + this._delayLoadingFunction(data, this); + } + else { + this._delayLoadingFunction(JSON.parse(data), this); + } + this.instances.forEach((instance) => { + instance.refreshBoundingInfo(); + instance._syncSubMeshes(); + }); + this.delayLoadState = 1; + scene.removePendingData(this); + }, () => { }, scene.offlineProvider, getBinaryData); + return this; + } + /** + * Returns `true` if the mesh is within the frustum defined by the passed array of planes. + * A mesh is in the frustum if its bounding box intersects the frustum + * @param frustumPlanes defines the frustum to test + * @returns true if the mesh is in the frustum planes + */ + isInFrustum(frustumPlanes) { + if (this.delayLoadState === 2) { + return false; + } + if (!super.isInFrustum(frustumPlanes)) { + return false; + } + this._checkDelayState(); + return true; + } + /** + * Sets the mesh material by the material or multiMaterial `id` property + * @param id is a string identifying the material or the multiMaterial + * @returns the current mesh + */ + setMaterialById(id) { + const materials = this.getScene().materials; + let index; + for (index = materials.length - 1; index > -1; index--) { + if (materials[index].id === id) { + this.material = materials[index]; + return this; + } + } + // Multi + const multiMaterials = this.getScene().multiMaterials; + for (index = multiMaterials.length - 1; index > -1; index--) { + if (multiMaterials[index].id === id) { + this.material = multiMaterials[index]; + return this; + } + } + return this; + } + /** + * Returns as a new array populated with the mesh material and/or skeleton, if any. + * @returns an array of IAnimatable + */ + getAnimatables() { + const results = []; + if (this.material) { + results.push(this.material); + } + if (this.skeleton) { + results.push(this.skeleton); + } + return results; + } + /** + * Modifies the mesh geometry according to the passed transformation matrix. + * This method returns nothing, but it really modifies the mesh even if it's originally not set as updatable. + * The mesh normals are modified using the same transformation. + * Note that, under the hood, this method sets a new VertexBuffer each call. + * @param transform defines the transform matrix to use + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms + * @returns the current mesh + */ + bakeTransformIntoVertices(transform) { + // Position + if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) { + return this; + } + const submeshes = this.subMeshes.splice(0); + this._resetPointsArrayCache(); + let data = this.getVerticesData(VertexBuffer.PositionKind); + const temp = Vector3.Zero(); + let index; + for (index = 0; index < data.length; index += 3) { + Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp).toArray(data, index); + } + this.setVerticesData(VertexBuffer.PositionKind, data, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()); + // Normals + if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) { + data = this.getVerticesData(VertexBuffer.NormalKind); + for (index = 0; index < data.length; index += 3) { + Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp) + .normalize() + .toArray(data, index); + } + this.setVerticesData(VertexBuffer.NormalKind, data, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable()); + } + // Tangents + if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) { + data = this.getVerticesData(VertexBuffer.TangentKind); + for (index = 0; index < data.length; index += 4) { + Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp) + .normalize() + .toArray(data, index); + } + this.setVerticesData(VertexBuffer.TangentKind, data, this.getVertexBuffer(VertexBuffer.TangentKind).isUpdatable()); + } + // flip faces? + if (transform.determinant() < 0) { + this.flipFaces(); + } + // Restore submeshes + this.releaseSubMeshes(); + this.subMeshes = submeshes; + return this; + } + /** + * Modifies the mesh geometry according to its own current World Matrix. + * The mesh World Matrix is then reset. + * This method returns nothing but really modifies the mesh even if it's originally not set as updatable. + * Note that, under the hood, this method sets a new VertexBuffer each call. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms + * @param bakeIndependentlyOfChildren indicates whether to preserve all child nodes' World Matrix during baking + * @param forceUnique indicates whether to force the mesh geometry to be unique + * @returns the current mesh + */ + bakeCurrentTransformIntoVertices(bakeIndependentlyOfChildren = true, forceUnique = false) { + if (forceUnique) { + this.makeGeometryUnique(); + } + this.bakeTransformIntoVertices(this.computeWorldMatrix(true)); + this.resetLocalMatrix(bakeIndependentlyOfChildren); + return this; + } + // Cache + /** @internal */ + get _positions() { + return this._internalAbstractMeshDataInfo._positions || (this._geometry && this._geometry._positions) || null; + } + /** @internal */ + _resetPointsArrayCache() { + if (this._geometry) { + this._geometry._resetPointsArrayCache(); + } + return this; + } + /** @internal */ + _generatePointsArray() { + if (this._geometry) { + return this._geometry._generatePointsArray(); + } + return false; + } + /** + * Returns a new Mesh object generated from the current mesh properties. + * This method must not get confused with createInstance() + * @param name is a string, the name given to the new mesh + * @param newParent can be any Node object (default `null`) or an instance of MeshCloneOptions. If the latter, doNotCloneChildren and clonePhysicsImpostor are unused. + * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`) + * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`) + * @returns a new mesh + */ + clone(name = "", newParent = null, doNotCloneChildren, clonePhysicsImpostor = true) { + if (newParent && newParent._addToSceneRootNodes === undefined) { + const cloneOptions = newParent; + meshCreationOptions.source = this; + meshCreationOptions.doNotCloneChildren = cloneOptions.doNotCloneChildren; + meshCreationOptions.clonePhysicsImpostor = cloneOptions.clonePhysicsImpostor; + meshCreationOptions.cloneThinInstances = cloneOptions.cloneThinInstances; + return new Mesh(name, this.getScene(), meshCreationOptions); + } + return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor); + } + /** + * Releases resources associated with this mesh. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse, disposeMaterialAndTextures = false) { + this.morphTargetManager = null; + if (this._geometry) { + this._geometry.releaseForMesh(this, true); + } + const internalDataInfo = this._internalMeshDataInfo; + if (internalDataInfo._onBeforeDrawObservable) { + internalDataInfo._onBeforeDrawObservable.clear(); + } + if (internalDataInfo._onBeforeBindObservable) { + internalDataInfo._onBeforeBindObservable.clear(); + } + if (internalDataInfo._onBeforeRenderObservable) { + internalDataInfo._onBeforeRenderObservable.clear(); + } + if (internalDataInfo._onAfterRenderObservable) { + internalDataInfo._onAfterRenderObservable.clear(); + } + if (internalDataInfo._onBetweenPassObservable) { + internalDataInfo._onBetweenPassObservable.clear(); + } + // Sources + if (this._scene.useClonedMeshMap) { + if (internalDataInfo.meshMap) { + for (const uniqueId in internalDataInfo.meshMap) { + const mesh = internalDataInfo.meshMap[uniqueId]; + if (mesh) { + mesh._internalMeshDataInfo._source = null; + internalDataInfo.meshMap[uniqueId] = undefined; + } + } + } + if (internalDataInfo._source && internalDataInfo._source._internalMeshDataInfo.meshMap) { + internalDataInfo._source._internalMeshDataInfo.meshMap[this.uniqueId] = undefined; + } + } + else { + const meshes = this.getScene().meshes; + for (const abstractMesh of meshes) { + const mesh = abstractMesh; + if (mesh._internalMeshDataInfo && mesh._internalMeshDataInfo._source && mesh._internalMeshDataInfo._source === this) { + mesh._internalMeshDataInfo._source = null; + } + } + } + internalDataInfo._source = null; + this._instanceDataStorage.visibleInstances = {}; + // Instances + this._disposeInstanceSpecificData(); + // Thin instances + this._disposeThinInstanceSpecificData(); + if (this._internalMeshDataInfo._checkReadinessObserver) { + this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver); + } + super.dispose(doNotRecurse, disposeMaterialAndTextures); + } + /** @internal */ + _disposeInstanceSpecificData() { + // Do nothing + } + /** @internal */ + _disposeThinInstanceSpecificData() { + // Do nothing + } + /** @internal */ + _invalidateInstanceVertexArrayObject() { + // Do nothing + } + /** + * Modifies the mesh geometry according to a displacement map. + * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. + * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. + * @param url is a string, the URL from the image file is to be downloaded. + * @param minHeight is the lower limit of the displacement. + * @param maxHeight is the upper limit of the displacement. + * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing. + * @param uvOffset is an optional vector2 used to offset UV. + * @param uvScale is an optional vector2 used to scale UV. + * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance. + * @param onError defines a callback called when an error occurs during the processing of the request. + * @returns the Mesh. + */ + applyDisplacementMap(url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate = false, onError) { + const scene = this.getScene(); + const onload = (img) => { + // Getting height map data + const heightMapWidth = img.width; + const heightMapHeight = img.height; + const canvas = this.getEngine().createCanvas(heightMapWidth, heightMapHeight); + const context = canvas.getContext("2d"); + context.drawImage(img, 0, 0); + // Create VertexData from map data + //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949 + const buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data; + this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate); + //execute success callback, if set + if (onSuccess) { + onSuccess(this); + } + }; + Tools.LoadImage(url, onload, onError ? onError : () => { }, scene.offlineProvider); + return this; + } + /** + * Modifies the mesh geometry according to a displacementMap buffer. + * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. + * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. + * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel. + * @param heightMapWidth is the width of the buffer image. + * @param heightMapHeight is the height of the buffer image. + * @param minHeight is the lower limit of the displacement. + * @param maxHeight is the upper limit of the displacement. + * @param uvOffset is an optional vector2 used to offset UV. + * @param uvScale is an optional vector2 used to scale UV. + * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance. + * @returns the Mesh. + */ + applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate = false) { + if (!this.isVerticesDataPresent(VertexBuffer.PositionKind) || !this.isVerticesDataPresent(VertexBuffer.NormalKind) || !this.isVerticesDataPresent(VertexBuffer.UVKind)) { + Logger.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"); + return this; + } + const positions = this.getVerticesData(VertexBuffer.PositionKind, true, true); + const normals = this.getVerticesData(VertexBuffer.NormalKind); + const uvs = this.getVerticesData(VertexBuffer.UVKind); + let position = Vector3.Zero(); + const normal = Vector3.Zero(); + const uv = Vector2.Zero(); + uvOffset = uvOffset || Vector2.Zero(); + uvScale = uvScale || new Vector2(1, 1); + for (let index = 0; index < positions.length; index += 3) { + Vector3.FromArrayToRef(positions, index, position); + Vector3.FromArrayToRef(normals, index, normal); + Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv); + // Compute height + const u = (Math.abs(uv.x * uvScale.x + (uvOffset.x % 1)) * (heightMapWidth - 1)) % heightMapWidth | 0; + const v = (Math.abs(uv.y * uvScale.y + (uvOffset.y % 1)) * (heightMapHeight - 1)) % heightMapHeight | 0; + const pos = (u + v * heightMapWidth) * 4; + const r = buffer[pos] / 255.0; + const g = buffer[pos + 1] / 255.0; + const b = buffer[pos + 2] / 255.0; + const gradient = r * 0.3 + g * 0.59 + b * 0.11; + normal.normalize(); + normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient); + position = position.add(normal); + position.toArray(positions, index); + } + VertexData.ComputeNormals(positions, this.getIndices(), normals); + if (forceUpdate) { + this.setVerticesData(VertexBuffer.PositionKind, positions); + this.setVerticesData(VertexBuffer.NormalKind, normals); + this.setVerticesData(VertexBuffer.UVKind, uvs); + } + else { + this.updateVerticesData(VertexBuffer.PositionKind, positions); + this.updateVerticesData(VertexBuffer.NormalKind, normals); + } + return this; + } + _getFlattenedNormals(indices, positions) { + const normals = new Float32Array(indices.length * 3); + let normalsCount = 0; + // Decide if normals should be flipped + const flipNormalGeneration = this.sideOrientation === (this._scene.useRightHandedSystem ? 1 : 0); + // Generate new normals + for (let index = 0; index < indices.length; index += 3) { + const p1 = Vector3.FromArray(positions, indices[index] * 3); + const p2 = Vector3.FromArray(positions, indices[index + 1] * 3); + const p3 = Vector3.FromArray(positions, indices[index + 2] * 3); + const p1p2 = p1.subtract(p2); + const p3p2 = p3.subtract(p2); + const normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2)); + if (flipNormalGeneration) { + normal.scaleInPlace(-1); + } + // Store same normals for every vertex + for (let localIndex = 0; localIndex < 3; localIndex++) { + normals[normalsCount++] = normal.x; + normals[normalsCount++] = normal.y; + normals[normalsCount++] = normal.z; + } + } + return normals; + } + _convertToUnIndexedMesh(flattenNormals = false) { + const kinds = this.getVerticesDataKinds().filter((kind) => !this.getVertexBuffer(kind)?.getIsInstanced()); + const indices = this.getIndices(); + const data = {}; + const separateVertices = (data, size) => { + const newData = new Float32Array(indices.length * size); + let count = 0; + for (let index = 0; index < indices.length; index++) { + for (let offset = 0; offset < size; offset++) { + newData[count++] = data[indices[index] * size + offset]; + } + } + return newData; + }; + // Save mesh bounding info + const meshBoundingInfo = this.getBoundingInfo(); + // Save previous submeshes + const previousSubmeshes = this.geometry ? this.subMeshes.slice(0) : []; + // Cache vertex data + for (const kind of kinds) { + data[kind] = this.getVerticesData(kind); + } + // Update vertex data + for (const kind of kinds) { + const vertexBuffer = this.getVertexBuffer(kind); + const size = vertexBuffer.getSize(); + if (flattenNormals && kind === VertexBuffer.NormalKind) { + const normals = this._getFlattenedNormals(indices, data[VertexBuffer.PositionKind]); + this.setVerticesData(VertexBuffer.NormalKind, normals, vertexBuffer.isUpdatable(), size); + } + else { + this.setVerticesData(kind, separateVertices(data[kind], size), vertexBuffer.isUpdatable(), size); + } + } + // Update morph targets + if (this.morphTargetManager) { + for (let targetIndex = 0; targetIndex < this.morphTargetManager.numTargets; targetIndex++) { + const target = this.morphTargetManager.getTarget(targetIndex); + const positions = target.getPositions(); + target.setPositions(separateVertices(positions, 3)); + const normals = target.getNormals(); + if (normals) { + target.setNormals(flattenNormals ? this._getFlattenedNormals(indices, positions) : separateVertices(normals, 3)); + } + const tangents = target.getTangents(); + if (tangents) { + target.setTangents(separateVertices(tangents, 3)); + } + const uvs = target.getUVs(); + if (uvs) { + target.setUVs(separateVertices(uvs, 2)); + } + const colors = target.getColors(); + if (colors) { + target.setColors(separateVertices(colors, 4)); + } + } + this.morphTargetManager.synchronize(); + } + // Update indices + for (let index = 0; index < indices.length; index++) { + indices[index] = index; + } + this.setIndices(indices); + this._unIndexed = true; + // Update submeshes + this.releaseSubMeshes(); + for (const previousOne of previousSubmeshes) { + const boundingInfo = previousOne.getBoundingInfo(); + const subMesh = SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this); + subMesh.setBoundingInfo(boundingInfo); + } + this.setBoundingInfo(meshBoundingInfo); + this.synchronizeInstances(); + return this; + } + /** + * Modify the mesh to get a flat shading rendering. + * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result. + * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated. + * @returns current mesh + */ + convertToFlatShadedMesh() { + return this._convertToUnIndexedMesh(true); + } + /** + * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers. + * In other words, more vertices, no more indices and a single bigger VBO. + * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated. + * @returns current mesh + */ + convertToUnIndexedMesh() { + return this._convertToUnIndexedMesh(); + } + /** + * Inverses facet orientations. + * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. + * @param flipNormals will also inverts the normals + * @returns current mesh + */ + flipFaces(flipNormals = false) { + const vertex_data = VertexData.ExtractFromMesh(this); + let i; + if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind) && vertex_data.normals) { + for (i = 0; i < vertex_data.normals.length; i++) { + vertex_data.normals[i] *= -1; + } + this.setVerticesData(VertexBuffer.NormalKind, vertex_data.normals, this.isVertexBufferUpdatable(VertexBuffer.NormalKind)); + } + if (vertex_data.indices) { + let temp; + for (i = 0; i < vertex_data.indices.length; i += 3) { + // reassign indices + temp = vertex_data.indices[i + 1]; + vertex_data.indices[i + 1] = vertex_data.indices[i + 2]; + vertex_data.indices[i + 2] = temp; + } + this.setIndices(vertex_data.indices, null, this.isVertexBufferUpdatable(VertexBuffer.PositionKind), true); + } + return this; + } + /** + * Increase the number of facets and hence vertices in a mesh + * Vertex normals are interpolated from existing vertex normals + * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. + * @param numberPerEdge the number of new vertices to add to each edge of a facet, optional default 1 + */ + increaseVertices(numberPerEdge = 1) { + const vertex_data = VertexData.ExtractFromMesh(this); + const currentIndices = vertex_data.indices && !Array.isArray(vertex_data.indices) && Array.from ? Array.from(vertex_data.indices) : vertex_data.indices; + const positions = vertex_data.positions && !Array.isArray(vertex_data.positions) && Array.from ? Array.from(vertex_data.positions) : vertex_data.positions; + const uvs = vertex_data.uvs && !Array.isArray(vertex_data.uvs) && Array.from ? Array.from(vertex_data.uvs) : vertex_data.uvs; + const normals = vertex_data.normals && !Array.isArray(vertex_data.normals) && Array.from ? Array.from(vertex_data.normals) : vertex_data.normals; + if (!currentIndices || !positions) { + Logger.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions"); + } + else { + vertex_data.indices = currentIndices; + vertex_data.positions = positions; + if (uvs) { + vertex_data.uvs = uvs; + } + if (normals) { + vertex_data.normals = normals; + } + const segments = numberPerEdge + 1; //segments per current facet edge, become sides of new facets + const tempIndices = new Array(); + for (let i = 0; i < segments + 1; i++) { + tempIndices[i] = new Array(); + } + let a; //vertex index of one end of a side + let b; //vertex index of other end of the side + const deltaPosition = new Vector3(0, 0, 0); + const deltaNormal = new Vector3(0, 0, 0); + const deltaUV = new Vector2(0, 0); + const indices = new Array(); + const vertexIndex = new Array(); + const side = new Array(); + let len; + let positionPtr = positions.length; + let uvPtr; + if (uvs) { + uvPtr = uvs.length; + } + let normalsPtr; + if (normals) { + normalsPtr = normals.length; + } + for (let i = 0; i < currentIndices.length; i += 3) { + vertexIndex[0] = currentIndices[i]; + vertexIndex[1] = currentIndices[i + 1]; + vertexIndex[2] = currentIndices[i + 2]; + for (let j = 0; j < 3; j++) { + a = vertexIndex[j]; + b = vertexIndex[(j + 1) % 3]; + if (side[a] === undefined && side[b] === undefined) { + side[a] = new Array(); + side[b] = new Array(); + } + else { + if (side[a] === undefined) { + side[a] = new Array(); + } + if (side[b] === undefined) { + side[b] = new Array(); + } + } + if (side[a][b] === undefined && side[b][a] === undefined) { + side[a][b] = []; + deltaPosition.x = (positions[3 * b] - positions[3 * a]) / segments; + deltaPosition.y = (positions[3 * b + 1] - positions[3 * a + 1]) / segments; + deltaPosition.z = (positions[3 * b + 2] - positions[3 * a + 2]) / segments; + if (normals) { + deltaNormal.x = (normals[3 * b] - normals[3 * a]) / segments; + deltaNormal.y = (normals[3 * b + 1] - normals[3 * a + 1]) / segments; + deltaNormal.z = (normals[3 * b + 2] - normals[3 * a + 2]) / segments; + } + if (uvs) { + deltaUV.x = (uvs[2 * b] - uvs[2 * a]) / segments; + deltaUV.y = (uvs[2 * b + 1] - uvs[2 * a + 1]) / segments; + } + side[a][b].push(a); + for (let k = 1; k < segments; k++) { + side[a][b].push(positions.length / 3); + positions[positionPtr++] = positions[3 * a] + k * deltaPosition.x; + positions[positionPtr++] = positions[3 * a + 1] + k * deltaPosition.y; + positions[positionPtr++] = positions[3 * a + 2] + k * deltaPosition.z; + if (normals) { + normals[normalsPtr++] = normals[3 * a] + k * deltaNormal.x; + normals[normalsPtr++] = normals[3 * a + 1] + k * deltaNormal.y; + normals[normalsPtr++] = normals[3 * a + 2] + k * deltaNormal.z; + } + if (uvs) { + uvs[uvPtr++] = uvs[2 * a] + k * deltaUV.x; + uvs[uvPtr++] = uvs[2 * a + 1] + k * deltaUV.y; + } + } + side[a][b].push(b); + side[b][a] = new Array(); + len = side[a][b].length; + for (let idx = 0; idx < len; idx++) { + side[b][a][idx] = side[a][b][len - 1 - idx]; + } + } + } + //Calculate positions, normals and uvs of new internal vertices + tempIndices[0][0] = currentIndices[i]; + tempIndices[1][0] = side[currentIndices[i]][currentIndices[i + 1]][1]; + tempIndices[1][1] = side[currentIndices[i]][currentIndices[i + 2]][1]; + for (let k = 2; k < segments; k++) { + tempIndices[k][0] = side[currentIndices[i]][currentIndices[i + 1]][k]; + tempIndices[k][k] = side[currentIndices[i]][currentIndices[i + 2]][k]; + deltaPosition.x = (positions[3 * tempIndices[k][k]] - positions[3 * tempIndices[k][0]]) / k; + deltaPosition.y = (positions[3 * tempIndices[k][k] + 1] - positions[3 * tempIndices[k][0] + 1]) / k; + deltaPosition.z = (positions[3 * tempIndices[k][k] + 2] - positions[3 * tempIndices[k][0] + 2]) / k; + if (normals) { + deltaNormal.x = (normals[3 * tempIndices[k][k]] - normals[3 * tempIndices[k][0]]) / k; + deltaNormal.y = (normals[3 * tempIndices[k][k] + 1] - normals[3 * tempIndices[k][0] + 1]) / k; + deltaNormal.z = (normals[3 * tempIndices[k][k] + 2] - normals[3 * tempIndices[k][0] + 2]) / k; + } + if (uvs) { + deltaUV.x = (uvs[2 * tempIndices[k][k]] - uvs[2 * tempIndices[k][0]]) / k; + deltaUV.y = (uvs[2 * tempIndices[k][k] + 1] - uvs[2 * tempIndices[k][0] + 1]) / k; + } + for (let j = 1; j < k; j++) { + tempIndices[k][j] = positions.length / 3; + positions[positionPtr++] = positions[3 * tempIndices[k][0]] + j * deltaPosition.x; + positions[positionPtr++] = positions[3 * tempIndices[k][0] + 1] + j * deltaPosition.y; + positions[positionPtr++] = positions[3 * tempIndices[k][0] + 2] + j * deltaPosition.z; + if (normals) { + normals[normalsPtr++] = normals[3 * tempIndices[k][0]] + j * deltaNormal.x; + normals[normalsPtr++] = normals[3 * tempIndices[k][0] + 1] + j * deltaNormal.y; + normals[normalsPtr++] = normals[3 * tempIndices[k][0] + 2] + j * deltaNormal.z; + } + if (uvs) { + uvs[uvPtr++] = uvs[2 * tempIndices[k][0]] + j * deltaUV.x; + uvs[uvPtr++] = uvs[2 * tempIndices[k][0] + 1] + j * deltaUV.y; + } + } + } + tempIndices[segments] = side[currentIndices[i + 1]][currentIndices[i + 2]]; + // reform indices + indices.push(tempIndices[0][0], tempIndices[1][0], tempIndices[1][1]); + for (let k = 1; k < segments; k++) { + let j; + for (j = 0; j < k; j++) { + indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]); + indices.push(tempIndices[k][j], tempIndices[k + 1][j + 1], tempIndices[k][j + 1]); + } + indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]); + } + } + vertex_data.indices = indices; + vertex_data.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind)); + } + } + /** + * Force adjacent facets to share vertices and remove any facets that have all vertices in a line + * This will undo any application of covertToFlatShadedMesh + * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. + */ + forceSharedVertices() { + const vertex_data = VertexData.ExtractFromMesh(this); + const currentUVs = vertex_data.uvs; + const currentIndices = vertex_data.indices; + const currentPositions = vertex_data.positions; + const currentColors = vertex_data.colors; + const currentMatrixIndices = vertex_data.matricesIndices; + const currentMatrixWeights = vertex_data.matricesWeights; + const currentMatrixIndicesExtra = vertex_data.matricesIndicesExtra; + const currentMatrixWeightsExtra = vertex_data.matricesWeightsExtra; + if (currentIndices === void 0 || currentPositions === void 0 || currentIndices === null || currentPositions === null) { + Logger.Warn("VertexData contains empty entries"); + } + else { + const positions = new Array(); + const indices = new Array(); + const uvs = new Array(); + const colors = new Array(); + const matrixIndices = new Array(); + const matrixWeights = new Array(); + const matrixIndicesExtra = new Array(); + const matrixWeightsExtra = new Array(); + let pstring = new Array(); //lists facet vertex positions (a,b,c) as string "a|b|c" + let indexPtr = 0; // pointer to next available index value + const uniquePositions = {}; // unique vertex positions + let ptr; // pointer to element in uniquePositions + let facet; + for (let i = 0; i < currentIndices.length; i += 3) { + facet = [currentIndices[i], currentIndices[i + 1], currentIndices[i + 2]]; //facet vertex indices + pstring = []; + for (let j = 0; j < 3; j++) { + pstring[j] = ""; + for (let k = 0; k < 3; k++) { + //small values make 0 + if (Math.abs(currentPositions[3 * facet[j] + k]) < 0.00000001) { + currentPositions[3 * facet[j] + k] = 0; + } + pstring[j] += currentPositions[3 * facet[j] + k] + "|"; + } + } + //check facet vertices to see that none are repeated + // do not process any facet that has a repeated vertex, ie is a line + if (!(pstring[0] == pstring[1] || pstring[0] == pstring[2] || pstring[1] == pstring[2])) { + //for each facet position check if already listed in uniquePositions + // if not listed add to uniquePositions and set index pointer + // if listed use its index in uniquePositions and new index pointer + for (let j = 0; j < 3; j++) { + ptr = uniquePositions[pstring[j]]; + if (ptr === undefined) { + uniquePositions[pstring[j]] = indexPtr; + ptr = indexPtr++; + //not listed so add individual x, y, z coordinates to positions + for (let k = 0; k < 3; k++) { + positions.push(currentPositions[3 * facet[j] + k]); + } + if (currentColors !== null && currentColors !== void 0) { + for (let k = 0; k < 4; k++) { + colors.push(currentColors[4 * facet[j] + k]); + } + } + if (currentUVs !== null && currentUVs !== void 0) { + for (let k = 0; k < 2; k++) { + uvs.push(currentUVs[2 * facet[j] + k]); + } + } + if (currentMatrixIndices !== null && currentMatrixIndices !== void 0) { + for (let k = 0; k < 4; k++) { + matrixIndices.push(currentMatrixIndices[4 * facet[j] + k]); + } + } + if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) { + for (let k = 0; k < 4; k++) { + matrixWeights.push(currentMatrixWeights[4 * facet[j] + k]); + } + } + if (currentMatrixIndicesExtra !== null && currentMatrixIndicesExtra !== void 0) { + for (let k = 0; k < 4; k++) { + matrixIndicesExtra.push(currentMatrixIndicesExtra[4 * facet[j] + k]); + } + } + if (currentMatrixWeightsExtra !== null && currentMatrixWeightsExtra !== void 0) { + for (let k = 0; k < 4; k++) { + matrixWeightsExtra.push(currentMatrixWeightsExtra[4 * facet[j] + k]); + } + } + } + // add new index pointer to indices array + indices.push(ptr); + } + } + } + const normals = new Array(); + VertexData.ComputeNormals(positions, indices, normals); + //create new vertex data object and update + vertex_data.positions = positions; + vertex_data.indices = indices; + vertex_data.normals = normals; + if (currentUVs !== null && currentUVs !== void 0) { + vertex_data.uvs = uvs; + } + if (currentColors !== null && currentColors !== void 0) { + vertex_data.colors = colors; + } + if (currentMatrixIndices !== null && currentMatrixIndices !== void 0) { + vertex_data.matricesIndices = matrixIndices; + } + if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) { + vertex_data.matricesWeights = matrixWeights; + } + if (currentMatrixIndicesExtra !== null && currentMatrixIndicesExtra !== void 0) { + vertex_data.matricesIndicesExtra = matrixIndicesExtra; + } + if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) { + vertex_data.matricesWeightsExtra = matrixWeightsExtra; + } + vertex_data.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind)); + } + } + // Instances + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/naming-convention + static _instancedMeshFactory(name, mesh) { + throw _WarnImport("InstancedMesh"); + } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static _PhysicsImpostorParser(scene, physicObject, jsonObject) { + throw _WarnImport("PhysicsImpostor"); + } + /** + * Creates a new InstancedMesh object from the mesh model. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances + * @param name defines the name of the new instance + * @returns a new InstancedMesh + */ + createInstance(name) { + const instance = Mesh._instancedMeshFactory(name, this); + instance.parent = this.parent; + return instance; + } + /** + * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any. + * After this call, all the mesh instances have the same submeshes than the current mesh. + * @returns the current mesh + */ + synchronizeInstances() { + for (let instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) { + const instance = this.instances[instanceIndex]; + instance._syncSubMeshes(); + } + return this; + } + /** + * Optimization of the mesh's indices, in case a mesh has duplicated vertices. + * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. + * This should be used together with the simplification to avoid disappearing triangles. + * @param successCallback an optional success callback to be called after the optimization finished. + * @returns the current mesh + */ + optimizeIndices(successCallback) { + const indices = this.getIndices(); + const positions = this.getVerticesData(VertexBuffer.PositionKind); + if (!positions || !indices) { + return this; + } + const vectorPositions = []; + for (let pos = 0; pos < positions.length; pos = pos + 3) { + vectorPositions.push(Vector3.FromArray(positions, pos)); + } + const dupes = []; + AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => { + const realPos = vectorPositions.length - 1 - iteration; + const testedPosition = vectorPositions[realPos]; + for (let j = 0; j < realPos; ++j) { + const againstPosition = vectorPositions[j]; + if (testedPosition.equals(againstPosition)) { + dupes[realPos] = j; + break; + } + } + }, () => { + for (let i = 0; i < indices.length; ++i) { + indices[i] = dupes[indices[i]] || indices[i]; + } + //indices are now reordered + const originalSubMeshes = this.subMeshes.slice(0); + this.setIndices(indices); + this.subMeshes = originalSubMeshes; + if (successCallback) { + successCallback(this); + } + }); + return this; + } + /** + * Serialize current mesh + * @param serializationObject defines the object which will receive the serialization data + * @returns the serialized object + */ + serialize(serializationObject = {}) { + serializationObject.name = this.name; + serializationObject.id = this.id; + serializationObject.uniqueId = this.uniqueId; + serializationObject.type = this.getClassName(); + if (Tags && Tags.HasTags(this)) { + serializationObject.tags = Tags.GetTags(this); + } + serializationObject.position = this.position.asArray(); + if (this.rotationQuaternion) { + serializationObject.rotationQuaternion = this.rotationQuaternion.asArray(); + } + else if (this.rotation) { + serializationObject.rotation = this.rotation.asArray(); + } + serializationObject.scaling = this.scaling.asArray(); + if (this._postMultiplyPivotMatrix) { + serializationObject.pivotMatrix = this.getPivotMatrix().asArray(); + } + else { + serializationObject.localMatrix = this.getPivotMatrix().asArray(); + } + serializationObject.isEnabled = this.isEnabled(false); + serializationObject.isVisible = this.isVisible; + serializationObject.infiniteDistance = this.infiniteDistance; + serializationObject.pickable = this.isPickable; + serializationObject.receiveShadows = this.receiveShadows; + serializationObject.billboardMode = this.billboardMode; + serializationObject.visibility = this.visibility; + serializationObject.alwaysSelectAsActiveMesh = this.alwaysSelectAsActiveMesh; + serializationObject.checkCollisions = this.checkCollisions; + serializationObject.ellipsoid = this.ellipsoid.asArray(); + serializationObject.ellipsoidOffset = this.ellipsoidOffset.asArray(); + serializationObject.doNotSyncBoundingInfo = this.doNotSyncBoundingInfo; + serializationObject.isBlocker = this.isBlocker; + serializationObject.sideOrientation = this.sideOrientation; + // Parent + if (this.parent) { + this.parent._serializeAsParent(serializationObject); + } + // Geometry + serializationObject.isUnIndexed = this.isUnIndexed; + const geometry = this._geometry; + if (geometry && this.subMeshes) { + serializationObject.geometryUniqueId = geometry.uniqueId; + serializationObject.geometryId = geometry.id; + // SubMeshes + serializationObject.subMeshes = []; + for (let subIndex = 0; subIndex < this.subMeshes.length; subIndex++) { + const subMesh = this.subMeshes[subIndex]; + serializationObject.subMeshes.push({ + materialIndex: subMesh.materialIndex, + verticesStart: subMesh.verticesStart, + verticesCount: subMesh.verticesCount, + indexStart: subMesh.indexStart, + indexCount: subMesh.indexCount, + }); + } + } + // Material + if (this.material) { + if (!this.material.doNotSerialize) { + serializationObject.materialUniqueId = this.material.uniqueId; + serializationObject.materialId = this.material.id; // back compat + } + } + else { + this.material = null; + serializationObject.materialUniqueId = this._scene.defaultMaterial.uniqueId; + serializationObject.materialId = this._scene.defaultMaterial.id; // back compat + } + // Morph targets + if (this.morphTargetManager) { + serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId; + } + // Skeleton + if (this.skeleton) { + serializationObject.skeletonId = this.skeleton.id; + serializationObject.numBoneInfluencers = this.numBoneInfluencers; + } + // Physics + //TODO implement correct serialization for physics impostors. + if (this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) { + const impostor = this.getPhysicsImpostor(); + if (impostor) { + serializationObject.physicsMass = impostor.getParam("mass"); + serializationObject.physicsFriction = impostor.getParam("friction"); + serializationObject.physicsRestitution = impostor.getParam("mass"); + serializationObject.physicsImpostor = impostor.type; + } + } + // Metadata + if (this.metadata) { + serializationObject.metadata = this.metadata; + } + // Instances + serializationObject.instances = []; + for (let index = 0; index < this.instances.length; index++) { + const instance = this.instances[index]; + if (instance.doNotSerialize) { + continue; + } + const serializationInstance = { + name: instance.name, + id: instance.id, + isEnabled: instance.isEnabled(false), + isVisible: instance.isVisible, + isPickable: instance.isPickable, + checkCollisions: instance.checkCollisions, + position: instance.position.asArray(), + scaling: instance.scaling.asArray(), + }; + if (instance.parent) { + instance.parent._serializeAsParent(serializationInstance); + } + if (instance.rotationQuaternion) { + serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray(); + } + else if (instance.rotation) { + serializationInstance.rotation = instance.rotation.asArray(); + } + // Physics + //TODO implement correct serialization for physics impostors. + if (this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) { + const impostor = instance.getPhysicsImpostor(); + if (impostor) { + serializationInstance.physicsMass = impostor.getParam("mass"); + serializationInstance.physicsFriction = impostor.getParam("friction"); + serializationInstance.physicsRestitution = impostor.getParam("mass"); + serializationInstance.physicsImpostor = impostor.type; + } + } + // Metadata + if (instance.metadata) { + serializationInstance.metadata = instance.metadata; + } + // Action Manager + if (instance.actionManager) { + serializationInstance.actions = instance.actionManager.serialize(instance.name); + } + serializationObject.instances.push(serializationInstance); + // Animations + SerializationHelper.AppendSerializedAnimations(instance, serializationInstance); + serializationInstance.ranges = instance.serializeAnimationRanges(); + } + // Thin instances + if (this._thinInstanceDataStorage.instancesCount && this._thinInstanceDataStorage.matrixData) { + serializationObject.thinInstances = { + instancesCount: this._thinInstanceDataStorage.instancesCount, + matrixData: Array.from(this._thinInstanceDataStorage.matrixData), + matrixBufferSize: this._thinInstanceDataStorage.matrixBufferSize, + enablePicking: this.thinInstanceEnablePicking, + }; + if (this._userThinInstanceBuffersStorage) { + const userThinInstance = { + data: {}, + sizes: {}, + strides: {}, + }; + for (const kind in this._userThinInstanceBuffersStorage.data) { + userThinInstance.data[kind] = Array.from(this._userThinInstanceBuffersStorage.data[kind]); + userThinInstance.sizes[kind] = this._userThinInstanceBuffersStorage.sizes[kind]; + userThinInstance.strides[kind] = this._userThinInstanceBuffersStorage.strides[kind]; + } + serializationObject.thinInstances.userThinInstance = userThinInstance; + } + } + // Animations + SerializationHelper.AppendSerializedAnimations(this, serializationObject); + serializationObject.ranges = this.serializeAnimationRanges(); + // Layer mask + serializationObject.layerMask = this.layerMask; + // Alpha + serializationObject.alphaIndex = this.alphaIndex; + serializationObject.hasVertexAlpha = this.hasVertexAlpha; + // Overlay + serializationObject.overlayAlpha = this.overlayAlpha; + serializationObject.overlayColor = this.overlayColor.asArray(); + serializationObject.renderOverlay = this.renderOverlay; + // Fog + serializationObject.applyFog = this.applyFog; + // Action Manager + if (this.actionManager) { + serializationObject.actions = this.actionManager.serialize(this.name); + } + return serializationObject; + } + /** @internal */ + _syncGeometryWithMorphTargetManager() { + if (!this.geometry) { + return; + } + this._markSubMeshesAsAttributesDirty(); + const morphTargetManager = this._internalAbstractMeshDataInfo._morphTargetManager; + if (morphTargetManager && morphTargetManager.vertexCount) { + if (morphTargetManager.vertexCount !== this.getTotalVertices()) { + Logger.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."); + this.morphTargetManager = null; + return; + } + if (morphTargetManager.isUsingTextureForTargets) { + return; + } + for (let index = 0; index < morphTargetManager.numInfluencers; index++) { + const morphTarget = morphTargetManager.getActiveTarget(index); + const positions = morphTarget.getPositions(); + if (!positions) { + Logger.Error("Invalid morph target. Target must have positions."); + return; + } + this.geometry.setVerticesData(VertexBuffer.PositionKind + index, positions, false, 3); + const normals = morphTarget.getNormals(); + if (normals) { + this.geometry.setVerticesData(VertexBuffer.NormalKind + index, normals, false, 3); + } + const tangents = morphTarget.getTangents(); + if (tangents) { + this.geometry.setVerticesData(VertexBuffer.TangentKind + index, tangents, false, 3); + } + const uvs = morphTarget.getUVs(); + if (uvs) { + this.geometry.setVerticesData(VertexBuffer.UVKind + "_" + index, uvs, false, 2); + } + const uv2s = morphTarget.getUV2s(); + if (uv2s) { + this.geometry.setVerticesData(VertexBuffer.UV2Kind + "_" + index, uv2s, false, 2); + } + const colors = morphTarget.getColors(); + if (colors) { + this.geometry.setVerticesData(VertexBuffer.ColorKind + index, colors, false, 4); + } + } + } + else { + let index = 0; + // Positions + while (this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind + index)) { + this.geometry.removeVerticesData(VertexBuffer.PositionKind + index); + if (this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind + index)) { + this.geometry.removeVerticesData(VertexBuffer.NormalKind + index); + } + if (this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind + index)) { + this.geometry.removeVerticesData(VertexBuffer.TangentKind + index); + } + if (this.geometry.isVerticesDataPresent(VertexBuffer.UVKind + index)) { + this.geometry.removeVerticesData(VertexBuffer.UVKind + "_" + index); + } + if (this.geometry.isVerticesDataPresent(VertexBuffer.UV2Kind + index)) { + this.geometry.removeVerticesData(VertexBuffer.UV2Kind + "_" + index); + } + if (this.geometry.isVerticesDataPresent(VertexBuffer.ColorKind + index)) { + this.geometry.removeVerticesData(VertexBuffer.ColorKind + index); + } + index++; + } + } + } + /** + * Returns a new Mesh object parsed from the source provided. + * @param parsedMesh is the source + * @param scene defines the hosting scene + * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with + * @returns a new Mesh + */ + static Parse(parsedMesh, scene, rootUrl) { + let mesh; + if (parsedMesh.type && parsedMesh.type === "LinesMesh") { + mesh = Mesh._LinesMeshParser(parsedMesh, scene); + } + else if (parsedMesh.type && parsedMesh.type === "GroundMesh") { + mesh = Mesh._GroundMeshParser(parsedMesh, scene); + } + else if (parsedMesh.type && parsedMesh.type === "GoldbergMesh") { + mesh = Mesh._GoldbergMeshParser(parsedMesh, scene); + } + else if (parsedMesh.type && parsedMesh.type === "GreasedLineMesh") { + mesh = Mesh._GreasedLineMeshParser(parsedMesh, scene); + } + else if (parsedMesh.type && parsedMesh.type === "TrailMesh") { + mesh = Mesh._TrailMeshParser(parsedMesh, scene); + } + else { + mesh = new Mesh(parsedMesh.name, scene); + } + mesh.id = parsedMesh.id; + mesh._waitingParsedUniqueId = parsedMesh.uniqueId; + if (Tags) { + Tags.AddTagsTo(mesh, parsedMesh.tags); + } + mesh.position = Vector3.FromArray(parsedMesh.position); + if (parsedMesh.metadata !== undefined) { + mesh.metadata = parsedMesh.metadata; + } + if (parsedMesh.rotationQuaternion) { + mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion); + } + else if (parsedMesh.rotation) { + mesh.rotation = Vector3.FromArray(parsedMesh.rotation); + } + mesh.scaling = Vector3.FromArray(parsedMesh.scaling); + if (parsedMesh.localMatrix) { + mesh.setPreTransformMatrix(Matrix.FromArray(parsedMesh.localMatrix)); + } + else if (parsedMesh.pivotMatrix) { + mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix)); + } + mesh.setEnabled(parsedMesh.isEnabled); + mesh.isVisible = parsedMesh.isVisible; + mesh.infiniteDistance = parsedMesh.infiniteDistance; + mesh.alwaysSelectAsActiveMesh = !!parsedMesh.alwaysSelectAsActiveMesh; + mesh.showBoundingBox = parsedMesh.showBoundingBox; + mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox; + if (parsedMesh.applyFog !== undefined) { + mesh.applyFog = parsedMesh.applyFog; + } + if (parsedMesh.pickable !== undefined) { + mesh.isPickable = parsedMesh.pickable; + } + if (parsedMesh.alphaIndex !== undefined) { + mesh.alphaIndex = parsedMesh.alphaIndex; + } + mesh.receiveShadows = parsedMesh.receiveShadows; + if (parsedMesh.billboardMode !== undefined) { + mesh.billboardMode = parsedMesh.billboardMode; + } + if (parsedMesh.visibility !== undefined) { + mesh.visibility = parsedMesh.visibility; + } + mesh.checkCollisions = parsedMesh.checkCollisions; + mesh.doNotSyncBoundingInfo = !!parsedMesh.doNotSyncBoundingInfo; + if (parsedMesh.ellipsoid) { + mesh.ellipsoid = Vector3.FromArray(parsedMesh.ellipsoid); + } + if (parsedMesh.ellipsoidOffset) { + mesh.ellipsoidOffset = Vector3.FromArray(parsedMesh.ellipsoidOffset); + } + // For Backward compatibility ("!=" to exclude null and undefined) + if (parsedMesh.overrideMaterialSideOrientation != null) { + mesh.sideOrientation = parsedMesh.overrideMaterialSideOrientation; + } + if (parsedMesh.sideOrientation !== undefined) { + mesh.sideOrientation = parsedMesh.sideOrientation; + } + if (parsedMesh.isBlocker !== undefined) { + mesh.isBlocker = parsedMesh.isBlocker; + } + mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading; + // freezeWorldMatrix + if (parsedMesh.freezeWorldMatrix) { + mesh._waitingData.freezeWorldMatrix = parsedMesh.freezeWorldMatrix; + } + // Parent + if (parsedMesh.parentId !== undefined) { + mesh._waitingParentId = parsedMesh.parentId; + } + if (parsedMesh.parentInstanceIndex !== undefined) { + mesh._waitingParentInstanceIndex = parsedMesh.parentInstanceIndex; + } + // Actions + if (parsedMesh.actions !== undefined) { + mesh._waitingData.actions = parsedMesh.actions; + } + // Overlay + if (parsedMesh.overlayAlpha !== undefined) { + mesh.overlayAlpha = parsedMesh.overlayAlpha; + } + if (parsedMesh.overlayColor !== undefined) { + mesh.overlayColor = Color3.FromArray(parsedMesh.overlayColor); + } + if (parsedMesh.renderOverlay !== undefined) { + mesh.renderOverlay = parsedMesh.renderOverlay; + } + // Geometry + mesh.isUnIndexed = !!parsedMesh.isUnIndexed; + mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha; + if (parsedMesh.delayLoadingFile) { + mesh.delayLoadState = 4; + mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile; + mesh.buildBoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum)); + if (parsedMesh._binaryInfo) { + mesh._binaryInfo = parsedMesh._binaryInfo; + } + mesh._delayInfo = []; + if (parsedMesh.hasUVs) { + mesh._delayInfo.push(VertexBuffer.UVKind); + } + if (parsedMesh.hasUVs2) { + mesh._delayInfo.push(VertexBuffer.UV2Kind); + } + if (parsedMesh.hasUVs3) { + mesh._delayInfo.push(VertexBuffer.UV3Kind); + } + if (parsedMesh.hasUVs4) { + mesh._delayInfo.push(VertexBuffer.UV4Kind); + } + if (parsedMesh.hasUVs5) { + mesh._delayInfo.push(VertexBuffer.UV5Kind); + } + if (parsedMesh.hasUVs6) { + mesh._delayInfo.push(VertexBuffer.UV6Kind); + } + if (parsedMesh.hasColors) { + mesh._delayInfo.push(VertexBuffer.ColorKind); + } + if (parsedMesh.hasMatricesIndices) { + mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind); + } + if (parsedMesh.hasMatricesWeights) { + mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind); + } + mesh._delayLoadingFunction = Geometry._ImportGeometry; + if (SceneLoaderFlags.ForceFullSceneLoadingForIncremental) { + mesh._checkDelayState(); + } + } + else { + Geometry._ImportGeometry(parsedMesh, mesh); + } + // Material + if (parsedMesh.materialUniqueId) { + mesh._waitingMaterialId = parsedMesh.materialUniqueId; + } + else if (parsedMesh.materialId) { + mesh._waitingMaterialId = parsedMesh.materialId; + } + // Morph targets + if (parsedMesh.morphTargetManagerId > -1) { + mesh._waitingMorphTargetManagerId = parsedMesh.morphTargetManagerId; + } + // Skeleton + if (parsedMesh.skeletonId !== undefined && parsedMesh.skeletonId !== null) { + mesh.skeleton = scene.getLastSkeletonById(parsedMesh.skeletonId); + if (parsedMesh.numBoneInfluencers) { + mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers; + } + } + // Animations + if (parsedMesh.animations) { + for (let animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) { + const parsedAnimation = parsedMesh.animations[animationIndex]; + const internalClass = GetClass("BABYLON.Animation"); + if (internalClass) { + mesh.animations.push(internalClass.Parse(parsedAnimation)); + } + } + Node$2.ParseAnimationRanges(mesh, parsedMesh, scene); + } + if (parsedMesh.autoAnimate) { + scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0); + } + // Layer Mask + if (parsedMesh.layerMask && !isNaN(parsedMesh.layerMask)) { + mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask)); + } + else { + mesh.layerMask = 0x0fffffff; + } + // Physics + if (parsedMesh.physicsImpostor) { + mesh.physicsImpostor = Mesh._PhysicsImpostorParser(scene, mesh, parsedMesh); + } + // Levels + if (parsedMesh.lodMeshIds) { + mesh._waitingData.lods = { + ids: parsedMesh.lodMeshIds, + distances: parsedMesh.lodDistances ? parsedMesh.lodDistances : null, + coverages: parsedMesh.lodCoverages ? parsedMesh.lodCoverages : null, + }; + } + // Instances + if (parsedMesh.instances) { + for (let index = 0; index < parsedMesh.instances.length; index++) { + const parsedInstance = parsedMesh.instances[index]; + const instance = mesh.createInstance(parsedInstance.name); + if (parsedInstance.id) { + instance.id = parsedInstance.id; + } + if (Tags) { + if (parsedInstance.tags) { + Tags.AddTagsTo(instance, parsedInstance.tags); + } + else { + Tags.AddTagsTo(instance, parsedMesh.tags); + } + } + instance.position = Vector3.FromArray(parsedInstance.position); + if (parsedInstance.metadata !== undefined) { + instance.metadata = parsedInstance.metadata; + } + if (parsedInstance.parentId !== undefined) { + instance._waitingParentId = parsedInstance.parentId; + } + if (parsedInstance.parentInstanceIndex !== undefined) { + instance._waitingParentInstanceIndex = parsedInstance.parentInstanceIndex; + } + if (parsedInstance.isEnabled !== undefined && parsedInstance.isEnabled !== null) { + instance.setEnabled(parsedInstance.isEnabled); + } + if (parsedInstance.isVisible !== undefined && parsedInstance.isVisible !== null) { + instance.isVisible = parsedInstance.isVisible; + } + if (parsedInstance.isPickable !== undefined && parsedInstance.isPickable !== null) { + instance.isPickable = parsedInstance.isPickable; + } + if (parsedInstance.rotationQuaternion) { + instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion); + } + else if (parsedInstance.rotation) { + instance.rotation = Vector3.FromArray(parsedInstance.rotation); + } + instance.scaling = Vector3.FromArray(parsedInstance.scaling); + if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) { + instance.checkCollisions = parsedInstance.checkCollisions; + } + if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) { + instance.isPickable = parsedInstance.pickable; + } + if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) { + instance.showBoundingBox = parsedInstance.showBoundingBox; + } + if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) { + instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox; + } + if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) { + instance.alphaIndex = parsedInstance.alphaIndex; + } + // Physics + if (parsedInstance.physicsImpostor) { + instance.physicsImpostor = Mesh._PhysicsImpostorParser(scene, instance, parsedInstance); + } + // Actions + if (parsedInstance.actions !== undefined) { + instance._waitingData.actions = parsedInstance.actions; + } + // Animation + if (parsedInstance.animations) { + for (let animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) { + const parsedAnimation = parsedInstance.animations[animationIndex]; + const internalClass = GetClass("BABYLON.Animation"); + if (internalClass) { + instance.animations.push(internalClass.Parse(parsedAnimation)); + } + } + Node$2.ParseAnimationRanges(instance, parsedInstance, scene); + if (parsedInstance.autoAnimate) { + scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0); + } + } + } + } + // Thin instances + if (parsedMesh.thinInstances) { + const thinInstances = parsedMesh.thinInstances; + mesh.thinInstanceEnablePicking = !!thinInstances.enablePicking; + if (thinInstances.matrixData) { + mesh.thinInstanceSetBuffer("matrix", new Float32Array(thinInstances.matrixData), 16, false); + mesh._thinInstanceDataStorage.matrixBufferSize = thinInstances.matrixBufferSize; + mesh._thinInstanceDataStorage.instancesCount = thinInstances.instancesCount; + } + else { + mesh._thinInstanceDataStorage.matrixBufferSize = thinInstances.matrixBufferSize; + } + if (parsedMesh.thinInstances.userThinInstance) { + const userThinInstance = parsedMesh.thinInstances.userThinInstance; + for (const kind in userThinInstance.data) { + mesh.thinInstanceSetBuffer(kind, new Float32Array(userThinInstance.data[kind]), userThinInstance.strides[kind], false); + mesh._userThinInstanceBuffersStorage.sizes[kind] = userThinInstance.sizes[kind]; + } + } + } + return mesh; + } + // Skeletons + /** + * Prepare internal position array for software CPU skinning + * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh + */ + setPositionsForCPUSkinning() { + const internalDataInfo = this._internalMeshDataInfo; + if (!internalDataInfo._sourcePositions) { + const source = this.getVerticesData(VertexBuffer.PositionKind); + if (!source) { + return internalDataInfo._sourcePositions; + } + internalDataInfo._sourcePositions = new Float32Array(source); + if (!this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) { + this.setVerticesData(VertexBuffer.PositionKind, source, true); + } + } + return internalDataInfo._sourcePositions; + } + /** + * Prepare internal normal array for software CPU skinning + * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. + */ + setNormalsForCPUSkinning() { + const internalDataInfo = this._internalMeshDataInfo; + if (!internalDataInfo._sourceNormals) { + const source = this.getVerticesData(VertexBuffer.NormalKind); + if (!source) { + return internalDataInfo._sourceNormals; + } + internalDataInfo._sourceNormals = new Float32Array(source); + if (!this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) { + this.setVerticesData(VertexBuffer.NormalKind, source, true); + } + } + return internalDataInfo._sourceNormals; + } + /** + * Updates the vertex buffer by applying transformation from the bones + * @param skeleton defines the skeleton to apply to current mesh + * @returns the current mesh + */ + applySkeleton(skeleton) { + if (!this.geometry) { + return this; + } + if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) { + return this; + } + this.geometry._softwareSkinningFrameId = this.getScene().getFrameId(); + if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) { + return this; + } + if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) { + return this; + } + if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) { + return this; + } + const hasNormals = this.isVerticesDataPresent(VertexBuffer.NormalKind); + const internalDataInfo = this._internalMeshDataInfo; + if (!internalDataInfo._sourcePositions) { + const submeshes = this.subMeshes.slice(); + this.setPositionsForCPUSkinning(); + this.subMeshes = submeshes; + } + if (hasNormals && !internalDataInfo._sourceNormals) { + this.setNormalsForCPUSkinning(); + } + // positionsData checks for not being Float32Array will only pass at most once + let positionsData = this.getVerticesData(VertexBuffer.PositionKind); + if (!positionsData) { + return this; + } + if (!(positionsData instanceof Float32Array)) { + positionsData = new Float32Array(positionsData); + } + // normalsData checks for not being Float32Array will only pass at most once + let normalsData = this.getVerticesData(VertexBuffer.NormalKind); + if (hasNormals) { + if (!normalsData) { + return this; + } + if (!(normalsData instanceof Float32Array)) { + normalsData = new Float32Array(normalsData); + } + } + const matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind); + const matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind); + if (!matricesWeightsData || !matricesIndicesData) { + return this; + } + const needExtras = this.numBoneInfluencers > 4; + const matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null; + const matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null; + const skeletonMatrices = skeleton.getTransformMatrices(this); + const tempVector3 = Vector3.Zero(); + const finalMatrix = new Matrix(); + const tempMatrix = new Matrix(); + let matWeightIdx = 0; + let inf; + for (let index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) { + let weight; + for (inf = 0; inf < 4; inf++) { + weight = matricesWeightsData[matWeightIdx + inf]; + if (weight > 0) { + Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix); + finalMatrix.addToSelf(tempMatrix); + } + } + if (needExtras) { + for (inf = 0; inf < 4; inf++) { + weight = matricesWeightsExtraData[matWeightIdx + inf]; + if (weight > 0) { + Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix); + finalMatrix.addToSelf(tempMatrix); + } + } + } + Vector3.TransformCoordinatesFromFloatsToRef(internalDataInfo._sourcePositions[index], internalDataInfo._sourcePositions[index + 1], internalDataInfo._sourcePositions[index + 2], finalMatrix, tempVector3); + tempVector3.toArray(positionsData, index); + if (hasNormals) { + Vector3.TransformNormalFromFloatsToRef(internalDataInfo._sourceNormals[index], internalDataInfo._sourceNormals[index + 1], internalDataInfo._sourceNormals[index + 2], finalMatrix, tempVector3); + tempVector3.toArray(normalsData, index); + } + finalMatrix.reset(); + } + this.updateVerticesData(VertexBuffer.PositionKind, positionsData); + if (hasNormals) { + this.updateVerticesData(VertexBuffer.NormalKind, normalsData); + } + return this; + } + // Tools + /** + * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates + * @param meshes defines the list of meshes to scan + * @returns an object `{min:` Vector3`, max:` Vector3`}` + */ + static MinMax(meshes) { + let minVector = null; + let maxVector = null; + meshes.forEach(function (mesh) { + const boundingInfo = mesh.getBoundingInfo(); + const boundingBox = boundingInfo.boundingBox; + if (!minVector || !maxVector) { + minVector = boundingBox.minimumWorld; + maxVector = boundingBox.maximumWorld; + } + else { + minVector.minimizeInPlace(boundingBox.minimumWorld); + maxVector.maximizeInPlace(boundingBox.maximumWorld); + } + }); + if (!minVector || !maxVector) { + return { + min: Vector3.Zero(), + max: Vector3.Zero(), + }; + } + return { + min: minVector, + max: maxVector, + }; + } + /** + * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array + * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object + * @returns a vector3 + */ + static Center(meshesOrMinMaxVector) { + const minMaxVector = meshesOrMinMaxVector instanceof Array ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector; + return Vector3.Center(minMaxVector.min, minMaxVector.max); + } + /** + * Merge the array of meshes into a single mesh for performance reasons. + * @param meshes array of meshes with the vertices to merge. Entries cannot be empty meshes. + * @param disposeSource when true (default), dispose of the vertices from the source meshes. + * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true. + * @param meshSubclass (optional) can be set to a Mesh where the merged vertices will be inserted. + * @param subdivideWithSubMeshes when true (false default), subdivide mesh into subMeshes. + * @param multiMultiMaterials when true (false default), subdivide mesh into subMeshes with multiple materials, ignores subdivideWithSubMeshes. + * @returns a new mesh + */ + static MergeMeshes(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) { + return runCoroutineSync(Mesh._MergeMeshesCoroutine(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, false)); + } + /** + * Merge the array of meshes into a single mesh for performance reasons. + * @param meshes array of meshes with the vertices to merge. Entries cannot be empty meshes. + * @param disposeSource when true (default), dispose of the vertices from the source meshes. + * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true. + * @param meshSubclass (optional) can be set to a Mesh where the merged vertices will be inserted. + * @param subdivideWithSubMeshes when true (false default), subdivide mesh into subMeshes. + * @param multiMultiMaterials when true (false default), subdivide mesh into subMeshes with multiple materials, ignores subdivideWithSubMeshes. + * @returns a new mesh + */ + static MergeMeshesAsync(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) { + return runCoroutineAsync(Mesh._MergeMeshesCoroutine(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, true), createYieldingScheduler()); + } + static *_MergeMeshesCoroutine(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, isAsync) { + // Remove any null/undefined entries from the mesh array + meshes = meshes.filter(Boolean); + if (meshes.length === 0) { + return null; + } + let index; + if (!allow32BitsIndices) { + let totalVertices = 0; + // Counting vertices + for (index = 0; index < meshes.length; index++) { + totalVertices += meshes[index].getTotalVertices(); + if (totalVertices >= 65536) { + Logger.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"); + return null; + } + } + } + if (multiMultiMaterials) { + subdivideWithSubMeshes = false; + } + const materialArray = new Array(); + const materialIndexArray = new Array(); + // Merge + const indiceArray = new Array(); + const currentsideOrientation = meshes[0].sideOrientation; + for (index = 0; index < meshes.length; index++) { + const mesh = meshes[index]; + if (mesh.isAnInstance) { + Logger.Warn("Cannot merge instance meshes."); + return null; + } + if (currentsideOrientation !== mesh.sideOrientation) { + Logger.Warn("Cannot merge meshes with different sideOrientation values."); + return null; + } + if (subdivideWithSubMeshes) { + indiceArray.push(mesh.getTotalIndices()); + } + if (multiMultiMaterials) { + if (mesh.material) { + const material = mesh.material; + if (material instanceof MultiMaterial) { + for (let matIndex = 0; matIndex < material.subMaterials.length; matIndex++) { + if (materialArray.indexOf(material.subMaterials[matIndex]) < 0) { + materialArray.push(material.subMaterials[matIndex]); + } + } + for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { + materialIndexArray.push(materialArray.indexOf(material.subMaterials[mesh.subMeshes[subIndex].materialIndex])); + indiceArray.push(mesh.subMeshes[subIndex].indexCount); + } + } + else { + if (materialArray.indexOf(material) < 0) { + materialArray.push(material); + } + for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { + materialIndexArray.push(materialArray.indexOf(material)); + indiceArray.push(mesh.subMeshes[subIndex].indexCount); + } + } + } + else { + for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { + materialIndexArray.push(0); + indiceArray.push(mesh.subMeshes[subIndex].indexCount); + } + } + } + } + const source = meshes[0]; + const getVertexDataFromMesh = (mesh) => { + const wm = mesh.computeWorldMatrix(true); + const vertexData = VertexData.ExtractFromMesh(mesh, false, false); + return { vertexData, transform: wm }; + }; + const { vertexData: sourceVertexData, transform: sourceTransform } = getVertexDataFromMesh(source); + if (isAsync) { + yield; + } + const meshVertexDatas = new Array(meshes.length - 1); + for (let i = 1; i < meshes.length; i++) { + meshVertexDatas[i - 1] = getVertexDataFromMesh(meshes[i]); + if (isAsync) { + yield; + } + } + const mergeCoroutine = sourceVertexData._mergeCoroutine(sourceTransform, meshVertexDatas, allow32BitsIndices, isAsync, !disposeSource); + let mergeCoroutineStep = mergeCoroutine.next(); + while (!mergeCoroutineStep.done) { + if (isAsync) { + yield; + } + mergeCoroutineStep = mergeCoroutine.next(); + } + const vertexData = mergeCoroutineStep.value; + if (!meshSubclass) { + meshSubclass = new Mesh(source.name + "_merged", source.getScene()); + } + const applyToCoroutine = vertexData._applyToCoroutine(meshSubclass, undefined, isAsync); + let applyToCoroutineStep = applyToCoroutine.next(); + while (!applyToCoroutineStep.done) { + if (isAsync) { + yield; + } + applyToCoroutineStep = applyToCoroutine.next(); + } + // Setting properties + meshSubclass.checkCollisions = source.checkCollisions; + meshSubclass.sideOrientation = source.sideOrientation; + // Cleaning + if (disposeSource) { + for (index = 0; index < meshes.length; index++) { + meshes[index].dispose(); + } + } + // Subdivide + if (subdivideWithSubMeshes || multiMultiMaterials) { + //-- removal of global submesh + meshSubclass.releaseSubMeshes(); + index = 0; + let offset = 0; + //-- apply subdivision according to index table + while (index < indiceArray.length) { + SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass, undefined, false); + offset += indiceArray[index]; + index++; + } + for (const subMesh of meshSubclass.subMeshes) { + subMesh.refreshBoundingInfo(); + } + meshSubclass.computeWorldMatrix(true); + } + if (multiMultiMaterials) { + const newMultiMaterial = new MultiMaterial(source.name + "_merged", source.getScene()); + newMultiMaterial.subMaterials = materialArray; + for (let subIndex = 0; subIndex < meshSubclass.subMeshes.length; subIndex++) { + meshSubclass.subMeshes[subIndex].materialIndex = materialIndexArray[subIndex]; + } + meshSubclass.material = newMultiMaterial; + } + else { + meshSubclass.material = source.material; + } + return meshSubclass; + } + /** + * @internal + */ + addInstance(instance) { + instance._indexInSourceMeshInstanceArray = this.instances.length; + this.instances.push(instance); + } + /** + * @internal + */ + removeInstance(instance) { + // Remove from mesh + const index = instance._indexInSourceMeshInstanceArray; + if (index != -1) { + if (index !== this.instances.length - 1) { + const last = this.instances[this.instances.length - 1]; + this.instances[index] = last; + last._indexInSourceMeshInstanceArray = index; + } + instance._indexInSourceMeshInstanceArray = -1; + this.instances.pop(); + } + } + /** @internal */ + _shouldConvertRHS() { + return this._scene.useRightHandedSystem && this.sideOrientation === Material.CounterClockWiseSideOrientation; + } + /** @internal */ + _getRenderingFillMode(fillMode) { + const scene = this.getScene(); + if (scene.forcePointsCloud) + return Material.PointFillMode; + if (scene.forceWireframe) + return Material.WireFrameFillMode; + return this.overrideRenderingFillMode ?? fillMode; + } + // deprecated methods + /** + * Sets the mesh material by the material or multiMaterial `id` property + * @param id is a string identifying the material or the multiMaterial + * @returns the current mesh + * @deprecated Please use MeshBuilder instead Please use setMaterialById instead + */ + setMaterialByID(id) { + return this.setMaterialById(id); + } + /** + * Creates a ribbon mesh. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param + * @param name defines the name of the mesh to create + * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry. + * @param closeArray creates a seam between the first and the last paths of the path array (default is false) + * @param closePath creates a seam between the first and the last points of each path of the path array + * @param offset is taken in account only if the `pathArray` is containing a single path + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateRibbon(name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a plane polygonal mesh. By default, this is a disc. + * @param name defines the name of the mesh to create + * @param radius sets the radius size (float) of the polygon (default 0.5) + * @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateDisc(name, radius, tessellation, scene, updatable, sideOrientation) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a box mesh. + * @param name defines the name of the mesh to create + * @param size sets the size (float) of each box side (default 1) + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateBox(name, size, scene, updatable, sideOrientation) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a sphere mesh. + * @param name defines the name of the mesh to create + * @param segments sets the sphere number of horizontal stripes (positive integer, default 32) + * @param diameter sets the diameter size (float) of the sphere (default 1) + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateSphere(name, segments, diameter, scene, updatable, sideOrientation) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a hemisphere mesh. + * @param name defines the name of the mesh to create + * @param segments sets the sphere number of horizontal stripes (positive integer, default 32) + * @param diameter sets the diameter size (float) of the sphere (default 1) + * @param scene defines the hosting scene + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateHemisphere(name, segments, diameter, scene) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a cylinder or a cone mesh. + * @param name defines the name of the mesh to create + * @param height sets the height size (float) of the cylinder/cone (float, default 2) + * @param diameterTop set the top cap diameter (floats, default 1) + * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero + * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance + * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1) + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateCylinder(name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) { + throw new Error("Import MeshBuilder to populate this function"); + } + // Torus (Code from SharpDX.org) + /** + * Creates a torus mesh. + * @param name defines the name of the mesh to create + * @param diameter sets the diameter size (float) of the torus (default 1) + * @param thickness sets the diameter size of the tube of the torus (float, default 0.5) + * @param tessellation sets the number of torus sides (positive integer, default 16) + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateTorus(name, diameter, thickness, tessellation, scene, updatable, sideOrientation) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a torus knot mesh. + * @param name defines the name of the mesh to create + * @param radius sets the global radius size (float) of the torus knot (default 2) + * @param tube sets the diameter size of the tube of the torus (float, default 0.5) + * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32) + * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32) + * @param p the number of windings on X axis (positive integers, default 2) + * @param q the number of windings on Y axis (positive integers, default 3) + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateTorusKnot(name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a line mesh.. + * @param name defines the name of the mesh to create + * @param points is an array successive Vector3 + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines). + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateLines(name, points, scene, updatable, instance) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a dashed line mesh. + * @param name defines the name of the mesh to create + * @param points is an array successive Vector3 + * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3) + * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1) + * @param dashNb is the intended total number of dashes (positive integer, default 200) + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateDashedLines(name, points, dashSize, gapSize, dashNb, scene, updatable, instance) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead + * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh. + * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors. + * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * Remember you can only change the shape positions, not their number when updating a polygon. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#non-regular-polygon + * @param name defines the name of the mesh to create + * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors + * @param scene defines the hosting scene + * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @param earcutInjection can be used to inject your own earcut reference + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreatePolygon(name, shape, scene, holes, updatable, sideOrientation, earcutInjection) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates an extruded polygon mesh, with depth in the Y direction.. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-non-regular-polygon + * @param name defines the name of the mesh to create + * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors + * @param depth defines the height of extrusion + * @param scene defines the hosting scene + * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @param earcutInjection can be used to inject your own earcut reference + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static ExtrudePolygon(name, shape, depth, scene, holes, updatable, sideOrientation, earcutInjection) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates an extruded shape mesh. + * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes + * @param name defines the name of the mesh to create + * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis + * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along + * @param scale is the value to scale the shape + * @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve + * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static ExtrudeShape(name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates an custom extruded shape mesh. + * The custom extrusion is a parametric shape. + * It has no predefined shape. Its final shape will depend on the input parameters. + * + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes + * @param name defines the name of the mesh to create + * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis + * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along + * @param scaleFunction is a custom Javascript function called on each path point + * @param rotationFunction is a custom Javascript function called on each path point + * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray` + * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray` + * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#extruded-shape) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static ExtrudeShapeCustom(name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates lathe mesh. + * The lathe is a shape with a symmetry axis : a 2D model shape is rotated around this axis to design the lathe. + * @param name defines the name of the mesh to create + * @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero + * @param radius is the radius value of the lathe + * @param tessellation is the side number of the lathe. + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateLathe(name, shape, radius, tessellation, scene, updatable, sideOrientation) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a plane mesh. + * @param name defines the name of the mesh to create + * @param size sets the size (float) of both sides of the plane at once (default 1) + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreatePlane(name, size, scene, updatable, sideOrientation) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a ground mesh. + * @param name defines the name of the mesh to create + * @param width set the width of the ground + * @param height set the height of the ground + * @param subdivisions sets the number of subdivisions per side + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateGround(name, width, height, subdivisions, scene, updatable) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a tiled ground mesh. + * @param name defines the name of the mesh to create + * @param xmin set the ground minimum X coordinate + * @param zmin set the ground minimum Y coordinate + * @param xmax set the ground maximum X coordinate + * @param zmax set the ground maximum Z coordinate + * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile + * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateTiledGround(name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a ground mesh from a height map. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/height_map + * @param name defines the name of the mesh to create + * @param url sets the URL of the height map image resource + * @param width set the ground width size + * @param height set the ground height size + * @param subdivisions sets the number of subdivision per side + * @param minHeight is the minimum altitude on the ground + * @param maxHeight is the maximum altitude on the ground + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time) + * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateGroundFromHeightMap(name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a tube mesh. + * The tube is a parametric shape. + * It has no predefined shape. Its final shape will depend on the input parameters. + * + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param + * @param name defines the name of the mesh to create + * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube + * @param radius sets the tube radius size + * @param tessellation is the number of sides on the tubular surface + * @param radiusFunction is a custom function. If it is not null, it overrides the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path + * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL + * @param scene defines the hosting scene + * @param updatable defines if the mesh must be flagged as updatable + * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) + * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube) + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateTube(name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a polyhedron mesh. + *. + * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embedded types. Please refer to the type sheet in the tutorial to choose the wanted type + * * The parameter `size` (positive float, default 1) sets the polygon size + * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value) + * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type` + * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron + * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`) + * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace + * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored + * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh to create + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreatePolyhedron(name, options, scene) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided + * * The parameter `radius` sets the radius size (float) of the icosphere (default 1) + * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`) + * * The parameter `subdivisions` sets the number of subdivisions (positive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size + * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface + * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra#icosphere + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateIcoSphere(name, options, scene) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Creates a decal mesh. + *. + * A decal is a mesh usually applied as a model onto the surface of another mesh + * @param name defines the name of the mesh + * @param sourceMesh defines the mesh receiving the decal + * @param position sets the position of the decal in world coordinates + * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates + * @param size sets the decal scaling + * @param angle sets the angle to rotate the decal + * @returns a new Mesh + * @deprecated Please use MeshBuilder instead + */ + static CreateDecal(name, sourceMesh, position, normal, size, angle) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** Creates a Capsule Mesh + * @param name defines the name of the mesh. + * @param options the constructors options used to shape the mesh. + * @param scene defines the scene the mesh is scoped to. + * @returns the capsule mesh + * @see https://doc.babylonjs.com/how_to/capsule_shape + * @deprecated Please use MeshBuilder instead + */ + static CreateCapsule(name, options, scene) { + throw new Error("Import MeshBuilder to populate this function"); + } + /** + * Extends a mesh to a Goldberg mesh + * Warning the mesh to convert MUST be an import of a perviously exported Goldberg mesh + * @param mesh the mesh to convert + * @returns the extended mesh + * @deprecated Please use ExtendMeshToGoldberg instead + */ + static ExtendToGoldberg(mesh) { + throw new Error("Import MeshBuilder to populate this function"); + } +} +// Consts +/** + * Mesh side orientation : usually the external or front surface + */ +Mesh.FRONTSIDE = VertexData.FRONTSIDE; +/** + * Mesh side orientation : usually the internal or back surface + */ +Mesh.BACKSIDE = VertexData.BACKSIDE; +/** + * Mesh side orientation : both internal and external or front and back surfaces + */ +Mesh.DOUBLESIDE = VertexData.DOUBLESIDE; +/** + * Mesh side orientation : by default, `FRONTSIDE` + */ +Mesh.DEFAULTSIDE = VertexData.DEFAULTSIDE; +/** + * Mesh cap setting : no cap + */ +Mesh.NO_CAP = 0; +/** + * Mesh cap setting : one cap at the beginning of the mesh + */ +Mesh.CAP_START = 1; +/** + * Mesh cap setting : one cap at the end of the mesh + */ +Mesh.CAP_END = 2; +/** + * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh + */ +Mesh.CAP_ALL = 3; +/** + * Mesh pattern setting : no flip or rotate + */ +Mesh.NO_FLIP = 0; +/** + * Mesh pattern setting : flip (reflect in y axis) alternate tiles on each row or column + */ +Mesh.FLIP_TILE = 1; +/** + * Mesh pattern setting : rotate (180degs) alternate tiles on each row or column + */ +Mesh.ROTATE_TILE = 2; +/** + * Mesh pattern setting : flip (reflect in y axis) all tiles on alternate rows + */ +Mesh.FLIP_ROW = 3; +/** + * Mesh pattern setting : rotate (180degs) all tiles on alternate rows + */ +Mesh.ROTATE_ROW = 4; +/** + * Mesh pattern setting : flip and rotate alternate tiles on each row or column + */ +Mesh.FLIP_N_ROTATE_TILE = 5; +/** + * Mesh pattern setting : rotate pattern and rotate + */ +Mesh.FLIP_N_ROTATE_ROW = 6; +/** + * Mesh tile positioning : part tiles same on left/right or top/bottom + */ +Mesh.CENTER = 0; +/** + * Mesh tile positioning : part tiles on left + */ +Mesh.LEFT = 1; +/** + * Mesh tile positioning : part tiles on right + */ +Mesh.RIGHT = 2; +/** + * Mesh tile positioning : part tiles on top + */ +Mesh.TOP = 3; +/** + * Mesh tile positioning : part tiles on bottom + */ +Mesh.BOTTOM = 4; +/** + * Indicates that the instanced meshes should be sorted from back to front before rendering if their material is transparent + */ +Mesh.INSTANCEDMESH_SORT_TRANSPARENT = false; +// Statics +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Mesh._GroundMeshParser = (parsedMesh, scene) => { + throw _WarnImport("GroundMesh"); +}; +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Mesh._GoldbergMeshParser = (parsedMesh, scene) => { + throw _WarnImport("GoldbergMesh"); +}; +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Mesh._LinesMeshParser = (parsedMesh, scene) => { + throw _WarnImport("LinesMesh"); +}; +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Mesh._GreasedLineMeshParser = (parsedMesh, scene) => { + throw _WarnImport("GreasedLineMesh"); +}; +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Mesh._GreasedLineRibbonMeshParser = (parsedMesh, scene) => { + throw _WarnImport("GreasedLineRibbonMesh"); +}; +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Mesh._TrailMeshParser = (parsedMesh, scene) => { + throw _WarnImport("TrailMesh"); +}; +RegisterClass("BABYLON.Mesh", Mesh); + +/** + * The autoRotation behavior (AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction. + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior + */ +class AutoRotationBehavior { + constructor() { + this._zoomStopsAnimation = false; + this._idleRotationSpeed = 0.05; + this._idleRotationWaitTime = 2000; + this._idleRotationSpinupTime = 2000; + /** + * Target alpha + */ + this.targetAlpha = null; + this._isPointerDown = false; + this._lastFrameTime = null; + this._lastInteractionTime = -Infinity; + this._cameraRotationSpeed = 0; + this._lastFrameRadius = 0; + } + /** + * Gets the name of the behavior. + */ + get name() { + return "AutoRotation"; + } + /** + * Sets the flag that indicates if user zooming should stop animation. + */ + set zoomStopsAnimation(flag) { + this._zoomStopsAnimation = flag; + } + /** + * Gets the flag that indicates if user zooming should stop animation. + */ + get zoomStopsAnimation() { + return this._zoomStopsAnimation; + } + /** + * Sets the default speed at which the camera rotates around the model. + */ + set idleRotationSpeed(speed) { + this._idleRotationSpeed = speed; + } + /** + * Gets the default speed at which the camera rotates around the model. + */ + get idleRotationSpeed() { + return this._idleRotationSpeed; + } + /** + * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating. + */ + set idleRotationWaitTime(time) { + this._idleRotationWaitTime = time; + } + /** + * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating. + */ + get idleRotationWaitTime() { + return this._idleRotationWaitTime; + } + /** + * Sets the time (milliseconds) to take to spin up to the full idle rotation speed. + */ + set idleRotationSpinupTime(time) { + this._idleRotationSpinupTime = time; + } + /** + * Gets the time (milliseconds) to take to spin up to the full idle rotation speed. + */ + get idleRotationSpinupTime() { + return this._idleRotationSpinupTime; + } + /** + * Gets a value indicating if the camera is currently rotating because of this behavior + */ + get rotationInProgress() { + return Math.abs(this._cameraRotationSpeed) > 0; + } + /** + * Initializes the behavior. + */ + init() { + // Do nothing + } + /** + * Attaches the behavior to its arc rotate camera. + * @param camera Defines the camera to attach the behavior to + */ + attach(camera) { + this._attachedCamera = camera; + const scene = this._attachedCamera.getScene(); + this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => { + if (pointerInfoPre.type === PointerEventTypes.POINTERDOWN) { + this._isPointerDown = true; + return; + } + if (pointerInfoPre.type === PointerEventTypes.POINTERUP) { + this._isPointerDown = false; + } + }); + this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => { + if (this._reachTargetAlpha()) { + return; + } + const now = PrecisionDate.Now; + let dt = 0; + if (this._lastFrameTime != null) { + dt = now - this._lastFrameTime; + } + this._lastFrameTime = now; + // Stop the animation if there is user interaction and the animation should stop for this interaction + this._applyUserInteraction(); + const timeToRotation = now - this._lastInteractionTime - this._idleRotationWaitTime; + const scale = Math.max(Math.min(timeToRotation / this._idleRotationSpinupTime, 1), 0); + this._cameraRotationSpeed = this._idleRotationSpeed * scale; + // Step camera rotation by rotation speed + if (this._attachedCamera) { + this._attachedCamera.alpha -= this._cameraRotationSpeed * (dt / 1000); + } + }); + } + /** + * Detaches the behavior from its current arc rotate camera. + */ + detach() { + if (!this._attachedCamera) { + return; + } + const scene = this._attachedCamera.getScene(); + if (this._onPrePointerObservableObserver) { + scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); + } + this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); + this._attachedCamera = null; + this._lastFrameTime = null; + } + /** + * Force-reset the last interaction time + * @param customTime an optional time that will be used instead of the current last interaction time. For example `Date.now()` + */ + resetLastInteractionTime(customTime) { + this._lastInteractionTime = customTime ?? PrecisionDate.Now; + } + /** + * Returns true if camera alpha reaches the target alpha + * @returns true if camera alpha reaches the target alpha + */ + _reachTargetAlpha() { + if (this._attachedCamera && this.targetAlpha) { + return Math.abs(this._attachedCamera.alpha - this.targetAlpha) < Epsilon; + } + return false; + } + /** + * Returns true if user is scrolling. + * @returns true if user is scrolling. + */ + _userIsZooming() { + if (!this._attachedCamera) { + return false; + } + return this._attachedCamera.inertialRadiusOffset !== 0; + } + _shouldAnimationStopForInteraction() { + if (!this._attachedCamera) { + return false; + } + let zoomHasHitLimit = false; + if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) { + zoomHasHitLimit = true; + } + // Update the record of previous radius - works as an approx. indicator of hitting radius limits + this._lastFrameRadius = this._attachedCamera.radius; + return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming(); + } + /** + * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. + */ + _applyUserInteraction() { + if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) { + this._lastInteractionTime = PrecisionDate.Now; + } + } + // Tools + _userIsMoving() { + if (!this._attachedCamera) { + return false; + } + return (this._attachedCamera.inertialAlphaOffset !== 0 || + this._attachedCamera.inertialBetaOffset !== 0 || + this._attachedCamera.inertialRadiusOffset !== 0 || + this._attachedCamera.inertialPanningX !== 0 || + this._attachedCamera.inertialPanningY !== 0 || + this._isPointerDown); + } +} + +/** + * Base class used for every default easing function. + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class EasingFunction { + constructor() { + this._easingMode = EasingFunction.EASINGMODE_EASEIN; + } + /** + * Sets the easing mode of the current function. + * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT) + */ + setEasingMode(easingMode) { + const n = Math.min(Math.max(easingMode, 0), 2); + this._easingMode = n; + } + /** + * Gets the current easing mode. + * @returns the easing mode + */ + getEasingMode() { + return this._easingMode; + } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + easeInCore(gradient) { + throw new Error("You must implement this method"); + } + /** + * Given an input gradient between 0 and 1, this returns the corresponding value + * of the easing function. + * @param gradient Defines the value between 0 and 1 we want the easing value for + * @returns the corresponding value on the curve defined by the easing function + */ + ease(gradient) { + switch (this._easingMode) { + case EasingFunction.EASINGMODE_EASEIN: + return this.easeInCore(gradient); + case EasingFunction.EASINGMODE_EASEOUT: + return 1 - this.easeInCore(1 - gradient); + } + if (gradient >= 0.5) { + return (1 - this.easeInCore((1 - gradient) * 2)) * 0.5 + 0.5; + } + return this.easeInCore(gradient * 2) * 0.5; + } +} +/** + * Interpolation follows the mathematical formula associated with the easing function. + */ +EasingFunction.EASINGMODE_EASEIN = 0; +/** + * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function. + */ +EasingFunction.EASINGMODE_EASEOUT = 1; +/** + * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half. + */ +EasingFunction.EASINGMODE_EASEINOUT = 2; +/** + * Easing function with a circle shape (see link below). + * @see https://easings.net/#easeInCirc + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class CircleEase extends EasingFunction { + /** + * @internal + */ + easeInCore(gradient) { + gradient = Math.max(0, Math.min(1, gradient)); + return 1.0 - Math.sqrt(1.0 - gradient * gradient); + } +} +/** + * Easing function with a ease back shape (see link below). + * @see https://easings.net/#easeInBack + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class BackEase extends EasingFunction { + /** + * Instantiates a back ease easing + * @see https://easings.net/#easeInBack + * @param amplitude Defines the amplitude of the function + */ + constructor( + /** [1] Defines the amplitude of the function */ + amplitude = 1) { + super(); + this.amplitude = amplitude; + } + /** + * @internal + */ + easeInCore(gradient) { + const num = Math.max(0, this.amplitude); + return Math.pow(gradient, 3.0) - gradient * num * Math.sin(3.1415926535897931 * gradient); + } +} +/** + * Easing function with a bouncing shape (see link below). + * @see https://easings.net/#easeInBounce + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class BounceEase extends EasingFunction { + /** + * Instantiates a bounce easing + * @see https://easings.net/#easeInBounce + * @param bounces Defines the number of bounces + * @param bounciness Defines the amplitude of the bounce + */ + constructor( + /** [3] Defines the number of bounces */ + bounces = 3, + /** [2] Defines the amplitude of the bounce */ + bounciness = 2) { + super(); + this.bounces = bounces; + this.bounciness = bounciness; + } + /** + * @internal + */ + easeInCore(gradient) { + const y = Math.max(0.0, this.bounces); + let bounciness = this.bounciness; + if (bounciness <= 1.0) { + bounciness = 1.001; + } + const num9 = Math.pow(bounciness, y); + const num5 = 1.0 - bounciness; + const num4 = (1.0 - num9) / num5 + num9 * 0.5; + const num15 = gradient * num4; + const num65 = Math.log(-num15 * (1.0 - bounciness) + 1.0) / Math.log(bounciness); + const num3 = Math.floor(num65); + const num13 = num3 + 1.0; + const num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4); + const num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4); + const num7 = (num8 + num12) * 0.5; + const num6 = gradient - num7; + const num2 = num7 - num8; + return (-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2) * (num6 + num2); + } +} +/** + * Easing function with a power of 3 shape (see link below). + * @see https://easings.net/#easeInCubic + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class CubicEase extends EasingFunction { + /** + * @internal + */ + easeInCore(gradient) { + return gradient * gradient * gradient; + } +} +/** + * Easing function with an elastic shape (see link below). + * @see https://easings.net/#easeInElastic + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class ElasticEase extends EasingFunction { + /** + * Instantiates an elastic easing function + * @see https://easings.net/#easeInElastic + * @param oscillations Defines the number of oscillations + * @param springiness Defines the amplitude of the oscillations + */ + constructor( + /** [3] Defines the number of oscillations*/ + oscillations = 3, + /** [3] Defines the amplitude of the oscillations*/ + springiness = 3) { + super(); + this.oscillations = oscillations; + this.springiness = springiness; + } + /** + * @internal + */ + easeInCore(gradient) { + let num2; + const num3 = Math.max(0.0, this.oscillations); + const num = Math.max(0.0, this.springiness); + if (num == 0) { + num2 = gradient; + } + else { + num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0); + } + return num2 * Math.sin((6.2831853071795862 * num3 + 1.5707963267948966) * gradient); + } +} +/** + * Easing function with an exponential shape (see link below). + * @see https://easings.net/#easeInExpo + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class ExponentialEase extends EasingFunction { + /** + * Instantiates an exponential easing function + * @see https://easings.net/#easeInExpo + * @param exponent Defines the exponent of the function + */ + constructor( + /** [3] Defines the exponent of the function */ + exponent = 2) { + super(); + this.exponent = exponent; + } + /** + * @internal + */ + easeInCore(gradient) { + if (this.exponent <= 0) { + return gradient; + } + return (Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0); + } +} +/** + * Easing function with a power of 2 shape (see link below). + * @see https://easings.net/#easeInQuad + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class QuadraticEase extends EasingFunction { + /** + * @internal + */ + easeInCore(gradient) { + return gradient * gradient; + } +} +/** + * Easing function with a power of 4 shape (see link below). + * @see https://easings.net/#easeInQuart + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class QuarticEase extends EasingFunction { + /** + * @internal + */ + easeInCore(gradient) { + return gradient * gradient * gradient * gradient; + } +} +/** + * Easing function with a power of 5 shape (see link below). + * @see https://easings.net/#easeInQuint + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class QuinticEase extends EasingFunction { + /** + * @internal + */ + easeInCore(gradient) { + return gradient * gradient * gradient * gradient * gradient; + } +} +/** + * Easing function with a sin shape (see link below). + * @see https://easings.net/#easeInSine + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class SineEase extends EasingFunction { + /** + * @internal + */ + easeInCore(gradient) { + return 1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)); + } +} +/** + * Easing function with a bezier shape (see link below). + * @see http://cubic-bezier.com/#.17,.67,.83,.67 + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions + */ +class BezierCurveEase extends EasingFunction { + /** + * Instantiates a bezier function + * @see http://cubic-bezier.com/#.17,.67,.83,.67 + * @param x1 Defines the x component of the start tangent in the bezier curve + * @param y1 Defines the y component of the start tangent in the bezier curve + * @param x2 Defines the x component of the end tangent in the bezier curve + * @param y2 Defines the y component of the end tangent in the bezier curve + */ + constructor( + /** [0] Defines the x component of the start tangent in the bezier curve */ + x1 = 0, + /** [0] Defines the y component of the start tangent in the bezier curve */ + y1 = 0, + /** [1] Defines the x component of the end tangent in the bezier curve */ + x2 = 1, + /** [1] Defines the y component of the end tangent in the bezier curve */ + y2 = 1) { + super(); + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } + /** + * @internal + */ + easeInCore(gradient) { + return BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2); + } +} + +/** + * Represents the range of an animation + */ +class AnimationRange { + /** + * Initializes the range of an animation + * @param name The name of the animation range + * @param from The starting frame of the animation + * @param to The ending frame of the animation + */ + constructor( + /**The name of the animation range**/ + name, + /**The starting frame of the animation */ + from, + /**The ending frame of the animation*/ + to) { + this.name = name; + this.from = from; + this.to = to; + } + /** + * Makes a copy of the animation range + * @returns A copy of the animation range + */ + clone() { + return new AnimationRange(this.name, this.from, this.to); + } +} + +// Static values to help the garbage collector +// Quaternion +const _staticOffsetValueQuaternion = Object.freeze(new Quaternion(0, 0, 0, 0)); +// Vector3 +const _staticOffsetValueVector3 = Object.freeze(Vector3.Zero()); +// Vector2 +const _staticOffsetValueVector2 = Object.freeze(Vector2.Zero()); +// Size +const _staticOffsetValueSize = Object.freeze(Size.Zero()); +// Color3 +const _staticOffsetValueColor3 = Object.freeze(Color3.Black()); +// Color4 +const _staticOffsetValueColor4 = Object.freeze(new Color4(0, 0, 0, 0)); +const evaluateAnimationState = { + key: 0, + repeatCount: 0, + loopMode: 2 /*Animation.ANIMATIONLOOPMODE_CONSTANT*/, +}; +/** + * Class used to store any kind of animation + */ +class Animation { + /** + * @internal Internal use + */ + static _PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) { + let dataType = undefined; + if (!isNaN(parseFloat(from)) && isFinite(from)) { + dataType = Animation.ANIMATIONTYPE_FLOAT; + } + else if (from instanceof Quaternion) { + dataType = Animation.ANIMATIONTYPE_QUATERNION; + } + else if (from instanceof Vector3) { + dataType = Animation.ANIMATIONTYPE_VECTOR3; + } + else if (from instanceof Vector2) { + dataType = Animation.ANIMATIONTYPE_VECTOR2; + } + else if (from instanceof Color3) { + dataType = Animation.ANIMATIONTYPE_COLOR3; + } + else if (from instanceof Color4) { + dataType = Animation.ANIMATIONTYPE_COLOR4; + } + else if (from instanceof Size) { + dataType = Animation.ANIMATIONTYPE_SIZE; + } + if (dataType == undefined) { + return null; + } + const animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode); + const keys = [ + { frame: 0, value: from }, + { frame: totalFrame, value: to }, + ]; + animation.setKeys(keys); + if (easingFunction !== undefined) { + animation.setEasingFunction(easingFunction); + } + return animation; + } + /** + * Sets up an animation + * @param property The property to animate + * @param animationType The animation type to apply + * @param framePerSecond The frames per second of the animation + * @param easingFunction The easing function used in the animation + * @returns The created animation + */ + static CreateAnimation(property, animationType, framePerSecond, easingFunction) { + const animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT); + animation.setEasingFunction(easingFunction); + return animation; + } + /** + * Create and start an animation on a node + * @param name defines the name of the global animation that will be run on all nodes + * @param target defines the target where the animation will take place + * @param targetProperty defines property to animate + * @param framePerSecond defines the number of frame per second yo use + * @param totalFrame defines the number of frames in total + * @param from defines the initial value + * @param to defines the final value + * @param loopMode defines which loop mode you want to use (off by default) + * @param easingFunction defines the easing function to use (linear by default) + * @param onAnimationEnd defines the callback to call when animation end + * @param scene defines the hosting scene + * @returns the animatable created for this animation + */ + static CreateAndStartAnimation(name, target, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd, scene) { + const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); + if (!animation) { + return null; + } + if (target.getScene) { + scene = target.getScene(); + } + if (!scene) { + return null; + } + return scene.beginDirectAnimation(target, [animation], 0, totalFrame, animation.loopMode !== Animation.ANIMATIONLOOPMODE_CONSTANT, 1.0, onAnimationEnd); + } + /** + * Create and start an animation on a node and its descendants + * @param name defines the name of the global animation that will be run on all nodes + * @param node defines the root node where the animation will take place + * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used + * @param targetProperty defines property to animate + * @param framePerSecond defines the number of frame per second to use + * @param totalFrame defines the number of frames in total + * @param from defines the initial value + * @param to defines the final value + * @param loopMode defines which loop mode you want to use (off by default) + * @param easingFunction defines the easing function to use (linear by default) + * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node) + * @returns the list of animatables created for all nodes + * @example https://www.babylonjs-playground.com/#MH0VLI + */ + static CreateAndStartHierarchyAnimation(name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { + const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); + if (!animation) { + return null; + } + const scene = node.getScene(); + return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd); + } + /** + * Creates a new animation, merges it with the existing animations and starts it + * @param name Name of the animation + * @param node Node which contains the scene that begins the animations + * @param targetProperty Specifies which property to animate + * @param framePerSecond The frames per second of the animation + * @param totalFrame The total number of frames + * @param from The frame at the beginning of the animation + * @param to The frame at the end of the animation + * @param loopMode Specifies the loop mode of the animation + * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations + * @param onAnimationEnd Callback to run once the animation is complete + * @returns Nullable animation + */ + static CreateMergeAndStartAnimation(name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { + const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); + if (!animation) { + return null; + } + node.animations.push(animation); + return node.getScene().beginAnimation(node, 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd); + } + /** @internal */ + static MakeAnimationAdditive(sourceAnimation, referenceFrameOrOptions, range, cloneOriginal = false, clonedName) { + let options; + if (typeof referenceFrameOrOptions === "object") { + options = referenceFrameOrOptions; + } + else { + options = { + referenceFrame: referenceFrameOrOptions ?? 0, + range: range, + cloneOriginalAnimation: cloneOriginal, + clonedAnimationName: clonedName, + }; + } + let animation = sourceAnimation; + if (options.cloneOriginalAnimation) { + animation = sourceAnimation.clone(); + animation.name = options.clonedAnimationName || animation.name; + } + if (!animation._keys.length) { + return animation; + } + const referenceFrame = options.referenceFrame && options.referenceFrame >= 0 ? options.referenceFrame : 0; + let startIndex = 0; + const firstKey = animation._keys[0]; + let endIndex = animation._keys.length - 1; + const lastKey = animation._keys[endIndex]; + const valueStore = { + referenceValue: firstKey.value, + referencePosition: TmpVectors.Vector3[0], + referenceQuaternion: TmpVectors.Quaternion[0], + referenceScaling: TmpVectors.Vector3[1], + keyPosition: TmpVectors.Vector3[2], + keyQuaternion: TmpVectors.Quaternion[1], + keyScaling: TmpVectors.Vector3[3], + }; + let from = firstKey.frame; + let to = lastKey.frame; + if (options.range) { + const rangeValue = animation.getRange(options.range); + if (rangeValue) { + from = rangeValue.from; + to = rangeValue.to; + } + } + else { + from = options.fromFrame ?? from; + to = options.toFrame ?? to; + } + if (from !== firstKey.frame) { + startIndex = animation.createKeyForFrame(from); + } + if (to !== lastKey.frame) { + endIndex = animation.createKeyForFrame(to); + } + // There's only one key, so use it + if (animation._keys.length === 1) { + const value = animation._getKeyValue(animation._keys[0]); + valueStore.referenceValue = value.clone ? value.clone() : value; + } + // Reference frame is before the first frame, so just use the first frame + else if (referenceFrame <= firstKey.frame) { + const value = animation._getKeyValue(firstKey.value); + valueStore.referenceValue = value.clone ? value.clone() : value; + } + // Reference frame is after the last frame, so just use the last frame + else if (referenceFrame >= lastKey.frame) { + const value = animation._getKeyValue(lastKey.value); + valueStore.referenceValue = value.clone ? value.clone() : value; + } + // Interpolate the reference value from the animation + else { + evaluateAnimationState.key = 0; + const value = animation._interpolate(referenceFrame, evaluateAnimationState); + valueStore.referenceValue = value.clone ? value.clone() : value; + } + // Conjugate the quaternion + if (animation.dataType === Animation.ANIMATIONTYPE_QUATERNION) { + valueStore.referenceValue.normalize().conjugateInPlace(); + } + // Decompose matrix and conjugate the quaternion + else if (animation.dataType === Animation.ANIMATIONTYPE_MATRIX) { + valueStore.referenceValue.decompose(valueStore.referenceScaling, valueStore.referenceQuaternion, valueStore.referencePosition); + valueStore.referenceQuaternion.normalize().conjugateInPlace(); + } + let startFrame = Number.MAX_VALUE; + const clippedKeys = options.clipKeys ? [] : null; + // Subtract the reference value from all of the key values + for (let index = startIndex; index <= endIndex; index++) { + let key = animation._keys[index]; + if (clippedKeys || options.cloneOriginalAnimation) { + key = { + frame: key.frame, + value: key.value.clone ? key.value.clone() : key.value, + inTangent: key.inTangent, + outTangent: key.outTangent, + interpolation: key.interpolation, + lockedTangent: key.lockedTangent, + }; + if (clippedKeys) { + if (startFrame === Number.MAX_VALUE) { + startFrame = key.frame; + } + key.frame -= startFrame; + clippedKeys.push(key); + } + } + // If this key was duplicated to create a frame 0 key, skip it because its value has already been updated + if (index && animation.dataType !== Animation.ANIMATIONTYPE_FLOAT && key.value === firstKey.value) { + continue; + } + switch (animation.dataType) { + case Animation.ANIMATIONTYPE_MATRIX: + key.value.decompose(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition); + valueStore.keyPosition.subtractInPlace(valueStore.referencePosition); + valueStore.keyScaling.divideInPlace(valueStore.referenceScaling); + valueStore.referenceQuaternion.multiplyToRef(valueStore.keyQuaternion, valueStore.keyQuaternion); + Matrix.ComposeToRef(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition, key.value); + break; + case Animation.ANIMATIONTYPE_QUATERNION: + valueStore.referenceValue.multiplyToRef(key.value, key.value); + break; + case Animation.ANIMATIONTYPE_VECTOR2: + case Animation.ANIMATIONTYPE_VECTOR3: + case Animation.ANIMATIONTYPE_COLOR3: + case Animation.ANIMATIONTYPE_COLOR4: + key.value.subtractToRef(valueStore.referenceValue, key.value); + break; + case Animation.ANIMATIONTYPE_SIZE: + key.value.width -= valueStore.referenceValue.width; + key.value.height -= valueStore.referenceValue.height; + break; + default: + key.value -= valueStore.referenceValue; + } + } + if (clippedKeys) { + animation.setKeys(clippedKeys, true); + } + return animation; + } + /** + * Transition property of an host to the target Value + * @param property The property to transition + * @param targetValue The target Value of the property + * @param host The object where the property to animate belongs + * @param scene Scene used to run the animation + * @param frameRate Framerate (in frame/s) to use + * @param transition The transition type we want to use + * @param duration The duration of the animation, in milliseconds + * @param onAnimationEnd Callback trigger at the end of the animation + * @returns Nullable animation + */ + static TransitionTo(property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd = null) { + if (duration <= 0) { + host[property] = targetValue; + if (onAnimationEnd) { + onAnimationEnd(); + } + return null; + } + const endFrame = frameRate * (duration / 1000); + transition.setKeys([ + { + frame: 0, + value: host[property].clone ? host[property].clone() : host[property], + }, + { + frame: endFrame, + value: targetValue, + }, + ]); + if (!host.animations) { + host.animations = []; + } + host.animations.push(transition); + const animation = scene.beginAnimation(host, 0, endFrame, false); + animation.onAnimationEnd = onAnimationEnd; + return animation; + } + /** + * Return the array of runtime animations currently using this animation + */ + get runtimeAnimations() { + return this._runtimeAnimations; + } + /** + * Specifies if any of the runtime animations are currently running + */ + get hasRunningRuntimeAnimations() { + for (const runtimeAnimation of this._runtimeAnimations) { + if (!runtimeAnimation.isStopped()) { + return true; + } + } + return false; + } + /** + * Initializes the animation + * @param name Name of the animation + * @param targetProperty Property to animate + * @param framePerSecond The frames per second of the animation + * @param dataType The data type of the animation + * @param loopMode The loop mode of the animation + * @param enableBlending Specifies if blending should be enabled + */ + constructor( + /**Name of the animation */ + name, + /**Property to animate */ + targetProperty, + /**The frames per second of the animation */ + framePerSecond, + /**The data type of the animation */ + dataType, + /**The loop mode of the animation */ + loopMode, + /**Specifies if blending should be enabled */ + enableBlending) { + this.name = name; + this.targetProperty = targetProperty; + this.framePerSecond = framePerSecond; + this.dataType = dataType; + this.loopMode = loopMode; + this.enableBlending = enableBlending; + /** + * Stores the easing function of the animation + */ + this._easingFunction = null; + /** + * @internal Internal use only + */ + this._runtimeAnimations = new Array(); + /** + * The set of event that will be linked to this animation + */ + this._events = new Array(); + /** + * Stores the blending speed of the animation + */ + this.blendingSpeed = 0.01; + /** + * Stores the animation ranges for the animation + */ + this._ranges = {}; + this.targetPropertyPath = targetProperty.split("."); + this.dataType = dataType; + this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode; + this.uniqueId = Animation._UniqueIdGenerator++; + } + // Methods + /** + * Converts the animation to a string + * @param fullDetails support for multiple levels of logging within scene loading + * @returns String form of the animation + */ + toString(fullDetails) { + let ret = "Name: " + this.name + ", property: " + this.targetProperty; + ret += ", datatype: " + ["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"][this.dataType]; + ret += ", nKeys: " + (this._keys ? this._keys.length : "none"); + ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"); + if (fullDetails) { + ret += ", Ranges: {"; + let first = true; + for (const name in this._ranges) { + if (first) { + ret += ", "; + first = false; + } + ret += name; + } + ret += "}"; + } + return ret; + } + /** + * Add an event to this animation + * @param event Event to add + */ + addEvent(event) { + this._events.push(event); + this._events.sort((a, b) => a.frame - b.frame); + } + /** + * Remove all events found at the given frame + * @param frame The frame to remove events from + */ + removeEvents(frame) { + for (let index = 0; index < this._events.length; index++) { + if (this._events[index].frame === frame) { + this._events.splice(index, 1); + index--; + } + } + } + /** + * Retrieves all the events from the animation + * @returns Events from the animation + */ + getEvents() { + return this._events; + } + /** + * Creates an animation range + * @param name Name of the animation range + * @param from Starting frame of the animation range + * @param to Ending frame of the animation + */ + createRange(name, from, to) { + // check name not already in use; could happen for bones after serialized + if (!this._ranges[name]) { + this._ranges[name] = new AnimationRange(name, from, to); + } + } + /** + * Deletes an animation range by name + * @param name Name of the animation range to delete + * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false) + */ + deleteRange(name, deleteFrames = true) { + const range = this._ranges[name]; + if (!range) { + return; + } + if (deleteFrames) { + const from = range.from; + const to = range.to; + // this loop MUST go high to low for multiple splices to work + for (let key = this._keys.length - 1; key >= 0; key--) { + if (this._keys[key].frame >= from && this._keys[key].frame <= to) { + this._keys.splice(key, 1); + } + } + } + this._ranges[name] = null; // said much faster than 'delete this._range[name]' + } + /** + * Gets the animation range by name, or null if not defined + * @param name Name of the animation range + * @returns Nullable animation range + */ + getRange(name) { + return this._ranges[name]; + } + /** + * Gets the key frames from the animation + * @returns The key frames of the animation + */ + getKeys() { + return this._keys; + } + /** + * Gets the highest frame of the animation + * @returns Highest frame of the animation + */ + getHighestFrame() { + let ret = 0; + for (let key = 0, nKeys = this._keys.length; key < nKeys; key++) { + if (ret < this._keys[key].frame) { + ret = this._keys[key].frame; + } + } + return ret; + } + /** + * Gets the easing function of the animation + * @returns Easing function of the animation + */ + getEasingFunction() { + return this._easingFunction; + } + /** + * Sets the easing function of the animation + * @param easingFunction A custom mathematical formula for animation + */ + setEasingFunction(easingFunction) { + this._easingFunction = easingFunction; + } + /** + * Interpolates a scalar linearly + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated scalar value + */ + floatInterpolateFunction(startValue, endValue, gradient) { + return Lerp(startValue, endValue, gradient); + } + /** + * Interpolates a scalar cubically + * @param startValue Start value of the animation curve + * @param outTangent End tangent of the animation + * @param endValue End value of the animation curve + * @param inTangent Start tangent of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated scalar value + */ + floatInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { + return Hermite(startValue, outTangent, endValue, inTangent, gradient); + } + /** + * Interpolates a quaternion using a spherical linear interpolation + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated quaternion value + */ + quaternionInterpolateFunction(startValue, endValue, gradient) { + return Quaternion.Slerp(startValue, endValue, gradient); + } + /** + * Interpolates a quaternion cubically + * @param startValue Start value of the animation curve + * @param outTangent End tangent of the animation curve + * @param endValue End value of the animation curve + * @param inTangent Start tangent of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated quaternion value + */ + quaternionInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { + return Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize(); + } + /** + * Interpolates a Vector3 linearly + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate (value between 0 and 1) + * @returns Interpolated scalar value + */ + vector3InterpolateFunction(startValue, endValue, gradient) { + return Vector3.Lerp(startValue, endValue, gradient); + } + /** + * Interpolates a Vector3 cubically + * @param startValue Start value of the animation curve + * @param outTangent End tangent of the animation + * @param endValue End value of the animation curve + * @param inTangent Start tangent of the animation curve + * @param gradient Scalar amount to interpolate (value between 0 and 1) + * @returns InterpolatedVector3 value + */ + vector3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { + return Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient); + } + /** + * Interpolates a Vector2 linearly + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate (value between 0 and 1) + * @returns Interpolated Vector2 value + */ + vector2InterpolateFunction(startValue, endValue, gradient) { + return Vector2.Lerp(startValue, endValue, gradient); + } + /** + * Interpolates a Vector2 cubically + * @param startValue Start value of the animation curve + * @param outTangent End tangent of the animation + * @param endValue End value of the animation curve + * @param inTangent Start tangent of the animation curve + * @param gradient Scalar amount to interpolate (value between 0 and 1) + * @returns Interpolated Vector2 value + */ + vector2InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { + return Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient); + } + /** + * Interpolates a size linearly + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated Size value + */ + sizeInterpolateFunction(startValue, endValue, gradient) { + return Size.Lerp(startValue, endValue, gradient); + } + /** + * Interpolates a Color3 linearly + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated Color3 value + */ + color3InterpolateFunction(startValue, endValue, gradient) { + return Color3.Lerp(startValue, endValue, gradient); + } + /** + * Interpolates a Color3 cubically + * @param startValue Start value of the animation curve + * @param outTangent End tangent of the animation + * @param endValue End value of the animation curve + * @param inTangent Start tangent of the animation curve + * @param gradient Scalar amount to interpolate + * @returns interpolated value + */ + color3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { + return Color3.Hermite(startValue, outTangent, endValue, inTangent, gradient); + } + /** + * Interpolates a Color4 linearly + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated Color3 value + */ + color4InterpolateFunction(startValue, endValue, gradient) { + return Color4.Lerp(startValue, endValue, gradient); + } + /** + * Interpolates a Color4 cubically + * @param startValue Start value of the animation curve + * @param outTangent End tangent of the animation + * @param endValue End value of the animation curve + * @param inTangent Start tangent of the animation curve + * @param gradient Scalar amount to interpolate + * @returns interpolated value + */ + color4InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { + return Color4.Hermite(startValue, outTangent, endValue, inTangent, gradient); + } + /** + * @internal Internal use only + */ + _getKeyValue(value) { + if (typeof value === "function") { + return value(); + } + return value; + } + /** + * Evaluate the animation value at a given frame + * @param currentFrame defines the frame where we want to evaluate the animation + * @returns the animation value + */ + evaluate(currentFrame) { + evaluateAnimationState.key = 0; + return this._interpolate(currentFrame, evaluateAnimationState); + } + /** + * @internal Internal use only + */ + _interpolate(currentFrame, state, searchClosestKeyOnly = false) { + if (state.loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && state.repeatCount > 0) { + return state.highLimitValue.clone ? state.highLimitValue.clone() : state.highLimitValue; + } + const keys = this._keys; + const keysLength = keys.length; + let key = state.key; + while (key >= 0 && currentFrame < keys[key].frame) { + --key; + } + while (key + 1 <= keysLength - 1 && currentFrame >= keys[key + 1].frame) { + ++key; + } + state.key = key; + if (key < 0) { + return searchClosestKeyOnly ? undefined : this._getKeyValue(keys[0].value); + } + else if (key + 1 > keysLength - 1) { + return searchClosestKeyOnly ? undefined : this._getKeyValue(keys[keysLength - 1].value); + } + const startKey = keys[key]; + const endKey = keys[key + 1]; + if (searchClosestKeyOnly && (currentFrame === startKey.frame || currentFrame === endKey.frame)) { + return undefined; + } + const startValue = this._getKeyValue(startKey.value); + const endValue = this._getKeyValue(endKey.value); + if (startKey.interpolation === 1 /* AnimationKeyInterpolation.STEP */) { + if (endKey.frame > currentFrame) { + return startValue; + } + else { + return endValue; + } + } + const useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined; + const frameDelta = endKey.frame - startKey.frame; + // gradient : percent of currentFrame between the frame inf and the frame sup + let gradient = (currentFrame - startKey.frame) / frameDelta; + // check for easingFunction and correction of gradient + const easingFunction = startKey.easingFunction || this.getEasingFunction(); + // can also be undefined, if not provided + if (easingFunction) { + gradient = easingFunction.ease(gradient); + } + switch (this.dataType) { + // Float + case Animation.ANIMATIONTYPE_FLOAT: { + const floatValue = useTangent + ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) + : this.floatInterpolateFunction(startValue, endValue, gradient); + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + case Animation.ANIMATIONLOOPMODE_YOYO: + return floatValue; + case Animation.ANIMATIONLOOPMODE_RELATIVE: + case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: + return (state.offsetValue ?? 0) * state.repeatCount + floatValue; + } + break; + } + // Quaternion + case Animation.ANIMATIONTYPE_QUATERNION: { + const quatValue = useTangent + ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) + : this.quaternionInterpolateFunction(startValue, endValue, gradient); + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + case Animation.ANIMATIONLOOPMODE_YOYO: + return quatValue; + case Animation.ANIMATIONLOOPMODE_RELATIVE: + case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: + return quatValue.addInPlace((state.offsetValue || _staticOffsetValueQuaternion).scale(state.repeatCount)); + } + return quatValue; + } + // Vector3 + case Animation.ANIMATIONTYPE_VECTOR3: { + const vec3Value = useTangent + ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) + : this.vector3InterpolateFunction(startValue, endValue, gradient); + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + case Animation.ANIMATIONLOOPMODE_YOYO: + return vec3Value; + case Animation.ANIMATIONLOOPMODE_RELATIVE: + case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: + return vec3Value.add((state.offsetValue || _staticOffsetValueVector3).scale(state.repeatCount)); + } + break; + } + // Vector2 + case Animation.ANIMATIONTYPE_VECTOR2: { + const vec2Value = useTangent + ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) + : this.vector2InterpolateFunction(startValue, endValue, gradient); + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + case Animation.ANIMATIONLOOPMODE_YOYO: + return vec2Value; + case Animation.ANIMATIONLOOPMODE_RELATIVE: + case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: + return vec2Value.add((state.offsetValue || _staticOffsetValueVector2).scale(state.repeatCount)); + } + break; + } + // Size + case Animation.ANIMATIONTYPE_SIZE: { + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + case Animation.ANIMATIONLOOPMODE_YOYO: + return this.sizeInterpolateFunction(startValue, endValue, gradient); + case Animation.ANIMATIONLOOPMODE_RELATIVE: + case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: + return this.sizeInterpolateFunction(startValue, endValue, gradient).add((state.offsetValue || _staticOffsetValueSize).scale(state.repeatCount)); + } + break; + } + // Color3 + case Animation.ANIMATIONTYPE_COLOR3: { + const color3Value = useTangent + ? this.color3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) + : this.color3InterpolateFunction(startValue, endValue, gradient); + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + case Animation.ANIMATIONLOOPMODE_YOYO: + return color3Value; + case Animation.ANIMATIONLOOPMODE_RELATIVE: + case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: + return color3Value.add((state.offsetValue || _staticOffsetValueColor3).scale(state.repeatCount)); + } + break; + } + // Color4 + case Animation.ANIMATIONTYPE_COLOR4: { + const color4Value = useTangent + ? this.color4InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) + : this.color4InterpolateFunction(startValue, endValue, gradient); + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + case Animation.ANIMATIONLOOPMODE_YOYO: + return color4Value; + case Animation.ANIMATIONLOOPMODE_RELATIVE: + case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: + return color4Value.add((state.offsetValue || _staticOffsetValueColor4).scale(state.repeatCount)); + } + break; + } + // Matrix + case Animation.ANIMATIONTYPE_MATRIX: { + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + case Animation.ANIMATIONLOOPMODE_YOYO: { + if (Animation.AllowMatricesInterpolation) { + return this.matrixInterpolateFunction(startValue, endValue, gradient, state.workValue); + } + return startValue; + } + case Animation.ANIMATIONLOOPMODE_RELATIVE: + case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: { + return startValue; + } + } + break; + } + } + return 0; + } + /** + * Defines the function to use to interpolate matrices + * @param startValue defines the start matrix + * @param endValue defines the end matrix + * @param gradient defines the gradient between both matrices + * @param result defines an optional target matrix where to store the interpolation + * @returns the interpolated matrix + */ + matrixInterpolateFunction(startValue, endValue, gradient, result) { + if (Animation.AllowMatrixDecomposeForInterpolation) { + if (result) { + Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result); + return result; + } + return Matrix.DecomposeLerp(startValue, endValue, gradient); + } + if (result) { + Matrix.LerpToRef(startValue, endValue, gradient, result); + return result; + } + return Matrix.Lerp(startValue, endValue, gradient); + } + /** + * Makes a copy of the animation + * @returns Cloned animation + */ + clone() { + const clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode); + clone.enableBlending = this.enableBlending; + clone.blendingSpeed = this.blendingSpeed; + if (this._keys) { + clone.setKeys(this._keys); + } + if (this._ranges) { + clone._ranges = {}; + for (const name in this._ranges) { + const range = this._ranges[name]; + if (!range) { + continue; + } + clone._ranges[name] = range.clone(); + } + } + return clone; + } + /** + * Sets the key frames of the animation + * @param values The animation key frames to set + * @param dontClone Whether to clone the keys or not (default is false, so the array of keys is cloned) + */ + setKeys(values, dontClone = false) { + this._keys = !dontClone ? values.slice(0) : values; + } + /** + * Creates a key for the frame passed as a parameter and adds it to the animation IF a key doesn't already exist for that frame + * @param frame Frame number + * @returns The key index if the key was added or the index of the pre existing key if the frame passed as parameter already has a corresponding key + */ + createKeyForFrame(frame) { + // Find the key corresponding to frame + evaluateAnimationState.key = 0; + const value = this._interpolate(frame, evaluateAnimationState, true); + if (!value) { + // A key corresponding to this frame already exists + return this._keys[evaluateAnimationState.key].frame === frame ? evaluateAnimationState.key : evaluateAnimationState.key + 1; + } + // The frame is between two keys, so create a new key + const newKey = { + frame, + value: value.clone ? value.clone() : value, + }; + this._keys.splice(evaluateAnimationState.key + 1, 0, newKey); + return evaluateAnimationState.key + 1; + } + /** + * Serializes the animation to an object + * @returns Serialized object + */ + serialize() { + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.property = this.targetProperty; + serializationObject.framePerSecond = this.framePerSecond; + serializationObject.dataType = this.dataType; + serializationObject.loopBehavior = this.loopMode; + serializationObject.enableBlending = this.enableBlending; + serializationObject.blendingSpeed = this.blendingSpeed; + const dataType = this.dataType; + serializationObject.keys = []; + const keys = this.getKeys(); + for (let index = 0; index < keys.length; index++) { + const animationKey = keys[index]; + const key = {}; + key.frame = animationKey.frame; + switch (dataType) { + case Animation.ANIMATIONTYPE_FLOAT: + key.values = [animationKey.value]; + if (animationKey.inTangent !== undefined) { + key.values.push(animationKey.inTangent); + } + if (animationKey.outTangent !== undefined) { + if (animationKey.inTangent === undefined) { + key.values.push(undefined); + } + key.values.push(animationKey.outTangent); + } + if (animationKey.interpolation !== undefined) { + if (animationKey.inTangent === undefined) { + key.values.push(undefined); + } + if (animationKey.outTangent === undefined) { + key.values.push(undefined); + } + key.values.push(animationKey.interpolation); + } + break; + case Animation.ANIMATIONTYPE_QUATERNION: + case Animation.ANIMATIONTYPE_MATRIX: + case Animation.ANIMATIONTYPE_VECTOR3: + case Animation.ANIMATIONTYPE_COLOR3: + case Animation.ANIMATIONTYPE_COLOR4: + key.values = animationKey.value.asArray(); + if (animationKey.inTangent != undefined) { + key.values.push(animationKey.inTangent.asArray()); + } + if (animationKey.outTangent != undefined) { + if (animationKey.inTangent === undefined) { + key.values.push(undefined); + } + key.values.push(animationKey.outTangent.asArray()); + } + if (animationKey.interpolation !== undefined) { + if (animationKey.inTangent === undefined) { + key.values.push(undefined); + } + if (animationKey.outTangent === undefined) { + key.values.push(undefined); + } + key.values.push(animationKey.interpolation); + } + break; + } + serializationObject.keys.push(key); + } + serializationObject.ranges = []; + for (const name in this._ranges) { + const source = this._ranges[name]; + if (!source) { + continue; + } + const range = {}; + range.name = name; + range.from = source.from; + range.to = source.to; + serializationObject.ranges.push(range); + } + return serializationObject; + } + /** + * @internal + */ + static _UniversalLerp(left, right, amount) { + const constructor = left.constructor; + if (constructor.Lerp) { + // Lerp supported + return constructor.Lerp(left, right, amount); + } + else if (constructor.Slerp) { + // Slerp supported + return constructor.Slerp(left, right, amount); + } + else if (left.toFixed) { + // Number + return left * (1.0 - amount) + amount * right; + } + else { + // Blending not supported + return right; + } + } + /** + * Parses an animation object and creates an animation + * @param parsedAnimation Parsed animation object + * @returns Animation object + */ + static Parse(parsedAnimation) { + const animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior); + const dataType = parsedAnimation.dataType; + const keys = []; + let data; + let index; + if (parsedAnimation.enableBlending) { + animation.enableBlending = parsedAnimation.enableBlending; + } + if (parsedAnimation.blendingSpeed) { + animation.blendingSpeed = parsedAnimation.blendingSpeed; + } + for (index = 0; index < parsedAnimation.keys.length; index++) { + const key = parsedAnimation.keys[index]; + let inTangent = undefined; + let outTangent = undefined; + let interpolation = undefined; + switch (dataType) { + case Animation.ANIMATIONTYPE_FLOAT: + data = key.values[0]; + if (key.values.length >= 2) { + inTangent = key.values[1]; + } + if (key.values.length >= 3) { + outTangent = key.values[2]; + } + if (key.values.length >= 4) { + interpolation = key.values[3]; + } + break; + case Animation.ANIMATIONTYPE_QUATERNION: + data = Quaternion.FromArray(key.values); + if (key.values.length >= 8) { + const _inTangent = Quaternion.FromArray(key.values.slice(4, 8)); + if (!_inTangent.equals(Quaternion.Zero())) { + inTangent = _inTangent; + } + } + if (key.values.length >= 12) { + const _outTangent = Quaternion.FromArray(key.values.slice(8, 12)); + if (!_outTangent.equals(Quaternion.Zero())) { + outTangent = _outTangent; + } + } + if (key.values.length >= 13) { + interpolation = key.values[12]; + } + break; + case Animation.ANIMATIONTYPE_MATRIX: + data = Matrix.FromArray(key.values); + if (key.values.length >= 17) { + interpolation = key.values[16]; + } + break; + case Animation.ANIMATIONTYPE_COLOR3: + data = Color3.FromArray(key.values); + if (key.values[3]) { + inTangent = Color3.FromArray(key.values[3]); + } + if (key.values[4]) { + outTangent = Color3.FromArray(key.values[4]); + } + if (key.values[5]) { + interpolation = key.values[5]; + } + break; + case Animation.ANIMATIONTYPE_COLOR4: + data = Color4.FromArray(key.values); + if (key.values[4]) { + inTangent = Color4.FromArray(key.values[4]); + } + if (key.values[5]) { + outTangent = Color4.FromArray(key.values[5]); + } + if (key.values[6]) { + interpolation = Color4.FromArray(key.values[6]); + } + break; + case Animation.ANIMATIONTYPE_VECTOR3: + default: + data = Vector3.FromArray(key.values); + if (key.values[3]) { + inTangent = Vector3.FromArray(key.values[3]); + } + if (key.values[4]) { + outTangent = Vector3.FromArray(key.values[4]); + } + if (key.values[5]) { + interpolation = key.values[5]; + } + break; + } + const keyData = {}; + keyData.frame = key.frame; + keyData.value = data; + if (inTangent != undefined) { + keyData.inTangent = inTangent; + } + if (outTangent != undefined) { + keyData.outTangent = outTangent; + } + if (interpolation != undefined) { + keyData.interpolation = interpolation; + } + keys.push(keyData); + } + animation.setKeys(keys); + if (parsedAnimation.ranges) { + for (index = 0; index < parsedAnimation.ranges.length; index++) { + data = parsedAnimation.ranges[index]; + animation.createRange(data.name, data.from, data.to); + } + } + return animation; + } + /** + * Appends the serialized animations from the source animations + * @param source Source containing the animations + * @param destination Target to store the animations + */ + static AppendSerializedAnimations(source, destination) { + SerializationHelper.AppendSerializedAnimations(source, destination); + } + /** + * Creates a new animation or an array of animations from a snippet saved in a remote file + * @param name defines the name of the animation to create (can be null or empty to use the one from the json data) + * @param url defines the url to load from + * @returns a promise that will resolve to the new animation or an array of animations + */ + static ParseFromFileAsync(name, url) { + return new Promise((resolve, reject) => { + const request = new WebRequest(); + request.addEventListener("readystatechange", () => { + if (request.readyState == 4) { + if (request.status == 200) { + let serializationObject = JSON.parse(request.responseText); + if (serializationObject.animations) { + serializationObject = serializationObject.animations; + } + if (serializationObject.length) { + const output = []; + for (const serializedAnimation of serializationObject) { + output.push(this.Parse(serializedAnimation)); + } + resolve(output); + } + else { + const output = this.Parse(serializationObject); + if (name) { + output.name = name; + } + resolve(output); + } + } + else { + reject("Unable to load the animation"); + } + } + }); + request.open("GET", url); + request.send(); + }); + } + /** + * Creates an animation or an array of animations from a snippet saved by the Inspector + * @param snippetId defines the snippet to load + * @returns a promise that will resolve to the new animation or a new array of animations + */ + static ParseFromSnippetAsync(snippetId) { + return new Promise((resolve, reject) => { + const request = new WebRequest(); + request.addEventListener("readystatechange", () => { + if (request.readyState == 4) { + if (request.status == 200) { + const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); + if (snippet.animations) { + const serializationObject = JSON.parse(snippet.animations); + const outputs = []; + for (const serializedAnimation of serializationObject.animations) { + const output = this.Parse(serializedAnimation); + output.snippetId = snippetId; + outputs.push(output); + } + resolve(outputs); + } + else { + const serializationObject = JSON.parse(snippet.animation); + const output = this.Parse(serializationObject); + output.snippetId = snippetId; + resolve(output); + } + } + else { + reject("Unable to load the snippet " + snippetId); + } + } + }); + request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); + request.send(); + }); + } +} +Animation._UniqueIdGenerator = 0; +/** + * Use matrix interpolation instead of using direct key value when animating matrices + */ +Animation.AllowMatricesInterpolation = false; +/** + * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower + */ +Animation.AllowMatrixDecomposeForInterpolation = true; +/** Define the Url to load snippets */ +Animation.SnippetUrl = `https://snippet.babylonjs.com`; +// Statics +/** + * Float animation type + */ +Animation.ANIMATIONTYPE_FLOAT = 0; +/** + * Vector3 animation type + */ +Animation.ANIMATIONTYPE_VECTOR3 = 1; +/** + * Quaternion animation type + */ +Animation.ANIMATIONTYPE_QUATERNION = 2; +/** + * Matrix animation type + */ +Animation.ANIMATIONTYPE_MATRIX = 3; +/** + * Color3 animation type + */ +Animation.ANIMATIONTYPE_COLOR3 = 4; +/** + * Color3 animation type + */ +Animation.ANIMATIONTYPE_COLOR4 = 7; +/** + * Vector2 animation type + */ +Animation.ANIMATIONTYPE_VECTOR2 = 5; +/** + * Size animation type + */ +Animation.ANIMATIONTYPE_SIZE = 6; +/** + * Relative Loop Mode + */ +Animation.ANIMATIONLOOPMODE_RELATIVE = 0; +/** + * Cycle Loop Mode + */ +Animation.ANIMATIONLOOPMODE_CYCLE = 1; +/** + * Constant Loop Mode + */ +Animation.ANIMATIONLOOPMODE_CONSTANT = 2; +/** + * Yoyo Loop Mode + */ +Animation.ANIMATIONLOOPMODE_YOYO = 4; +/** + * Relative Loop Mode (add to current value of animated object, unlike ANIMATIONLOOPMODE_RELATIVE) + */ +Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT = 5; +/** + * Creates an animation or an array of animations from a snippet saved by the Inspector + * @deprecated Please use ParseFromSnippetAsync instead + * @param snippetId defines the snippet to load + * @returns a promise that will resolve to the new animation or a new array of animations + */ +Animation.CreateFromSnippetAsync = Animation.ParseFromSnippetAsync; +RegisterClass("BABYLON.Animation", Animation); +Node$2._AnimationRangeFactory = (name, from, to) => new AnimationRange(name, from, to); + +/** + * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior + */ +class BouncingBehavior { + constructor() { + /** + * The duration of the animation, in milliseconds + */ + this.transitionDuration = 450; + /** + * Length of the distance animated by the transition when lower radius is reached + */ + this.lowerRadiusTransitionRange = 2; + /** + * Length of the distance animated by the transition when upper radius is reached + */ + this.upperRadiusTransitionRange = -2; + this._autoTransitionRange = false; + // Animations + this._radiusIsAnimating = false; + this._radiusBounceTransition = null; + this._animatables = new Array(); + } + /** + * Gets the name of the behavior. + */ + get name() { + return "Bouncing"; + } + /** + * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically + */ + get autoTransitionRange() { + return this._autoTransitionRange; + } + /** + * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically + * Transition ranges will be set to 5% of the bounding box diagonal in world space + */ + set autoTransitionRange(value) { + if (this._autoTransitionRange === value) { + return; + } + this._autoTransitionRange = value; + const camera = this._attachedCamera; + if (!camera) { + return; + } + if (value) { + this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((transformNode) => { + if (!transformNode) { + return; + } + transformNode.computeWorldMatrix(true); + if (transformNode.getBoundingInfo) { + const diagonal = transformNode.getBoundingInfo().diagonalLength; + this.lowerRadiusTransitionRange = diagonal * 0.05; + this.upperRadiusTransitionRange = diagonal * 0.05; + } + }); + } + else if (this._onMeshTargetChangedObserver) { + camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); + } + } + /** + * Initializes the behavior. + */ + init() { + // Do nothing + } + /** + * Attaches the behavior to its arc rotate camera. + * @param camera Defines the camera to attach the behavior to + */ + attach(camera) { + this._attachedCamera = camera; + this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => { + if (!this._attachedCamera) { + return; + } + // Add the bounce animation to the lower radius limit + if (this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)) { + this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange); + } + // Add the bounce animation to the upper radius limit + if (this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)) { + this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange); + } + }); + } + /** + * Detaches the behavior from its current arc rotate camera. + */ + detach() { + if (!this._attachedCamera) { + return; + } + if (this._onAfterCheckInputsObserver) { + this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); + } + if (this._onMeshTargetChangedObserver) { + this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); + } + this._attachedCamera = null; + } + /** + * Checks if the camera radius is at the specified limit. Takes into account animation locks. + * @param radiusLimit The limit to check against. + * @returns Bool to indicate if at limit. + */ + _isRadiusAtLimit(radiusLimit) { + if (!this._attachedCamera) { + return false; + } + if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) { + return true; + } + return false; + } + /** + * Applies an animation to the radius of the camera, extending by the radiusDelta. + * @param radiusDelta The delta by which to animate to. Can be negative. + */ + _applyBoundRadiusAnimation(radiusDelta) { + if (!this._attachedCamera) { + return; + } + if (!this._radiusBounceTransition) { + BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode); + this._radiusBounceTransition = Animation.CreateAnimation("radius", Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction); + } + // Prevent zoom until bounce has completed + this._cachedWheelPrecision = this._attachedCamera.wheelPrecision; + this._attachedCamera.wheelPrecision = Infinity; + this._attachedCamera.inertialRadiusOffset = 0; + // Animate to the radius limit + this.stopAllAnimations(); + this._radiusIsAnimating = true; + const animatable = Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, () => this._clearAnimationLocks()); + if (animatable) { + this._animatables.push(animatable); + } + } + /** + * Removes all animation locks. Allows new animations to be added to any of the camera properties. + */ + _clearAnimationLocks() { + this._radiusIsAnimating = false; + if (this._attachedCamera) { + this._attachedCamera.wheelPrecision = this._cachedWheelPrecision; + } + } + /** + * Stops and removes all animations that have been applied to the camera + */ + stopAllAnimations() { + if (this._attachedCamera) { + this._attachedCamera.animations = []; + } + while (this._animatables.length) { + this._animatables[0].onAnimationEnd = null; + this._animatables[0].stop(); + this._animatables.shift(); + } + } +} +/** + * The easing function used by animations + */ +BouncingBehavior.EasingFunction = new BackEase(0.3); +/** + * The easing mode used by animations + */ +BouncingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEOUT; + +/** + * The framing behavior (FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane. + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior + */ +class FramingBehavior { + constructor() { + /** + * An event triggered when the animation to zoom on target mesh has ended + */ + this.onTargetFramingAnimationEndObservable = new Observable(); + this._mode = FramingBehavior.FitFrustumSidesMode; + this._radiusScale = 1.0; + this._positionScale = 0.5; + this._defaultElevation = 0.3; + this._elevationReturnTime = 1500; + this._elevationReturnWaitTime = 1000; + this._zoomStopsAnimation = false; + this._framingTime = 1500; + /** + * Define if the behavior should automatically change the configured + * camera limits and sensibilities. + */ + this.autoCorrectCameraLimitsAndSensibility = true; + this._isPointerDown = false; + this._lastInteractionTime = -Infinity; + // Framing control + this._animatables = new Array(); + this._betaIsAnimating = false; + } + /** + * Gets the name of the behavior. + */ + get name() { + return "Framing"; + } + /** + * Sets the current mode used by the behavior + */ + set mode(mode) { + this._mode = mode; + } + /** + * Gets current mode used by the behavior. + */ + get mode() { + return this._mode; + } + /** + * Sets the scale applied to the radius (1 by default) + */ + set radiusScale(radius) { + this._radiusScale = radius; + } + /** + * Gets the scale applied to the radius + */ + get radiusScale() { + return this._radiusScale; + } + /** + * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. + */ + set positionScale(scale) { + this._positionScale = scale; + } + /** + * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. + */ + get positionScale() { + return this._positionScale; + } + /** + * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle + * behaviour is triggered, in radians. + */ + set defaultElevation(elevation) { + this._defaultElevation = elevation; + } + /** + * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle + * behaviour is triggered, in radians. + */ + get defaultElevation() { + return this._defaultElevation; + } + /** + * Sets the time (in milliseconds) taken to return to the default beta position. + * Negative value indicates camera should not return to default. + */ + set elevationReturnTime(speed) { + this._elevationReturnTime = speed; + } + /** + * Gets the time (in milliseconds) taken to return to the default beta position. + * Negative value indicates camera should not return to default. + */ + get elevationReturnTime() { + return this._elevationReturnTime; + } + /** + * Sets the delay (in milliseconds) taken before the camera returns to the default beta position. + */ + set elevationReturnWaitTime(time) { + this._elevationReturnWaitTime = time; + } + /** + * Gets the delay (in milliseconds) taken before the camera returns to the default beta position. + */ + get elevationReturnWaitTime() { + return this._elevationReturnWaitTime; + } + /** + * Sets the flag that indicates if user zooming should stop animation. + */ + set zoomStopsAnimation(flag) { + this._zoomStopsAnimation = flag; + } + /** + * Gets the flag that indicates if user zooming should stop animation. + */ + get zoomStopsAnimation() { + return this._zoomStopsAnimation; + } + /** + * Sets the transition time when framing the mesh, in milliseconds + */ + set framingTime(time) { + this._framingTime = time; + } + /** + * Gets the transition time when framing the mesh, in milliseconds + */ + get framingTime() { + return this._framingTime; + } + /** + * Initializes the behavior. + */ + init() { + // Do nothing + } + /** + * Attaches the behavior to its arc rotate camera. + * @param camera Defines the camera to attach the behavior to + */ + attach(camera) { + this._attachedCamera = camera; + const scene = this._attachedCamera.getScene(); + FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode); + this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => { + if (pointerInfoPre.type === PointerEventTypes.POINTERDOWN) { + this._isPointerDown = true; + return; + } + if (pointerInfoPre.type === PointerEventTypes.POINTERUP) { + this._isPointerDown = false; + } + }); + this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((transformNode) => { + if (transformNode && transformNode.getBoundingInfo) { + this.zoomOnMesh(transformNode, undefined, () => { + this.onTargetFramingAnimationEndObservable.notifyObservers(); + }); + } + }); + this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => { + // Stop the animation if there is user interaction and the animation should stop for this interaction + this._applyUserInteraction(); + // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it + // back to the default position after a given timeout + this._maintainCameraAboveGround(); + }); + } + /** + * Detaches the behavior from its current arc rotate camera. + */ + detach() { + if (!this._attachedCamera) { + return; + } + const scene = this._attachedCamera.getScene(); + if (this._onPrePointerObservableObserver) { + scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); + } + if (this._onAfterCheckInputsObserver) { + this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); + } + if (this._onMeshTargetChangedObserver) { + this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); + } + this._attachedCamera = null; + } + /** + * Targets the given mesh and updates zoom level accordingly. + * @param mesh The mesh to target. + * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh + * @param onAnimationEnd Callback triggered at the end of the framing animation + */ + zoomOnMesh(mesh, focusOnOriginXZ = false, onAnimationEnd = null) { + mesh.computeWorldMatrix(true); + const boundingBox = mesh.getBoundingInfo().boundingBox; + this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd); + } + /** + * Targets the given mesh with its children and updates zoom level accordingly. + * @param mesh The mesh to target. + * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh + * @param onAnimationEnd Callback triggered at the end of the framing animation + */ + zoomOnMeshHierarchy(mesh, focusOnOriginXZ = false, onAnimationEnd = null) { + mesh.computeWorldMatrix(true); + const boundingBox = mesh.getHierarchyBoundingVectors(true); + this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd); + } + /** + * Targets the given meshes with their children and updates zoom level accordingly. + * @param meshes The mesh to target. + * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh + * @param onAnimationEnd Callback triggered at the end of the framing animation + */ + zoomOnMeshesHierarchy(meshes, focusOnOriginXZ = false, onAnimationEnd = null) { + const min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + const max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + for (let i = 0; i < meshes.length; i++) { + const boundingInfo = meshes[i].getHierarchyBoundingVectors(true); + Vector3.CheckExtends(boundingInfo.min, min, max); + Vector3.CheckExtends(boundingInfo.max, min, max); + } + this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd); + } + /** + * Targets the bounding box info defined by its extends and updates zoom level accordingly. + * @param minimumWorld Determines the smaller position of the bounding box extend + * @param maximumWorld Determines the bigger position of the bounding box extend + * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh + * @param onAnimationEnd Callback triggered at the end of the framing animation + * @returns true if the zoom was done + */ + zoomOnBoundingInfo(minimumWorld, maximumWorld, focusOnOriginXZ = false, onAnimationEnd = null) { + let zoomTarget; + if (!this._attachedCamera) { + return false; + } + // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY + const bottom = minimumWorld.y; + const top = maximumWorld.y; + const zoomTargetY = bottom + (top - bottom) * this._positionScale; + const radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5); + if (!isFinite(zoomTargetY)) { + return false; // Abort mission as there is no target + } + if (focusOnOriginXZ) { + zoomTarget = new Vector3(0, zoomTargetY, 0); + } + else { + const centerWorld = minimumWorld.add(radiusWorld); + zoomTarget = new Vector3(centerWorld.x, zoomTargetY, centerWorld.z); + } + if (!this._vectorTransition) { + this._vectorTransition = Animation.CreateAnimation("target", Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction); + } + this._betaIsAnimating = true; + let animatable = Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime); + if (animatable) { + this._animatables.push(animatable); + } + // sets the radius and lower radius bounds + // Small delta ensures camera is not always at lower zoom limit. + let radius = 0; + if (this._mode === FramingBehavior.FitFrustumSidesMode) { + const position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); + if (this.autoCorrectCameraLimitsAndSensibility) { + this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ; + } + radius = position; + } + else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) { + radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); + if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) { + this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ; + } + } + // Set sensibilities + if (this.autoCorrectCameraLimitsAndSensibility) { + const extend = maximumWorld.subtract(minimumWorld).length(); + this._attachedCamera.panningSensibility = 5000 / extend; + this._attachedCamera.wheelPrecision = 100 / radius; + } + // transition to new radius + if (!this._radiusTransition) { + this._radiusTransition = Animation.CreateAnimation("radius", Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); + } + animatable = Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, () => { + this.stopAllAnimations(); + if (onAnimationEnd) { + onAnimationEnd(); + } + if (this._attachedCamera && this._attachedCamera.useInputToRestoreState) { + this._attachedCamera.storeState(); + } + }); + if (animatable) { + this._animatables.push(animatable); + } + return true; + } + /** + * Calculates the lowest radius for the camera based on the bounding box of the mesh. + * @param minimumWorld + * @param maximumWorld + * @returns The minimum distance from the primary mesh's center point at which the camera must be kept in order + * to fully enclose the mesh in the viewing frustum. + */ + _calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld) { + const camera = this._attachedCamera; + if (!camera) { + return 0; + } + let distance = camera._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld, this._radiusScale); + if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) { + // Don't exceed the requested limit + distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance; + } + // Don't exceed the upper radius limit + if (camera.upperRadiusLimit) { + distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance; + } + return distance; + } + /** + * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera + * is automatically returned to its default position (expected to be above ground plane). + */ + _maintainCameraAboveGround() { + if (this._elevationReturnTime < 0) { + return; + } + const timeSinceInteraction = PrecisionDate.Now - this._lastInteractionTime; + const defaultBeta = Math.PI * 0.5 - this._defaultElevation; + const limitBeta = Math.PI * 0.5; + // Bring the camera back up if below the ground plane + if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) { + this._betaIsAnimating = true; + //Transition to new position + this.stopAllAnimations(); + if (!this._betaTransition) { + this._betaTransition = Animation.CreateAnimation("beta", Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); + } + const animatabe = Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, () => { + this._clearAnimationLocks(); + this.stopAllAnimations(); + }); + if (animatabe) { + this._animatables.push(animatabe); + } + } + } + /** + * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties. + */ + _clearAnimationLocks() { + this._betaIsAnimating = false; + } + /** + * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. + */ + _applyUserInteraction() { + if (this.isUserIsMoving) { + this._lastInteractionTime = PrecisionDate.Now; + this.stopAllAnimations(); + this._clearAnimationLocks(); + } + } + /** + * Stops and removes all animations that have been applied to the camera + */ + stopAllAnimations() { + if (this._attachedCamera) { + this._attachedCamera.animations = []; + } + while (this._animatables.length) { + if (this._animatables[0]) { + this._animatables[0].onAnimationEnd = null; + this._animatables[0].stop(); + } + this._animatables.shift(); + } + } + /** + * Gets a value indicating if the user is moving the camera + */ + get isUserIsMoving() { + if (!this._attachedCamera) { + return false; + } + return (this._attachedCamera.inertialAlphaOffset !== 0 || + this._attachedCamera.inertialBetaOffset !== 0 || + this._attachedCamera.inertialRadiusOffset !== 0 || + this._attachedCamera.inertialPanningX !== 0 || + this._attachedCamera.inertialPanningY !== 0 || + this._isPointerDown); + } +} +/** + * The easing function used by animations + */ +FramingBehavior.EasingFunction = new ExponentialEase(); +/** + * The easing mode used by animations + */ +FramingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEINOUT; +// Statics +/** + * The camera can move all the way towards the mesh. + */ +FramingBehavior.IgnoreBoundsSizeMode = 0; +/** + * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides + */ +FramingBehavior.FitFrustumSidesMode = 1; + +Node$2.AddNodeConstructor("TargetCamera", (name, scene) => { + return () => new TargetCamera(name, Vector3.Zero(), scene); +}); +/** + * A target camera takes a mesh or position as a target and continues to look at it while it moves. + * This is the base of the follow, arc rotate cameras and Free camera + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras + */ +class TargetCamera extends Camera { + /** + * Instantiates a target camera that takes a mesh or position as a target and continues to look at it while it moves. + * This is the base of the follow, arc rotate cameras and Free camera + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras + * @param name Defines the name of the camera in the scene + * @param position Defines the start position of the camera in the scene + * @param scene Defines the scene the camera belongs to + * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined + */ + constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) { + super(name, position, scene, setActiveOnSceneIfNoneActive); + this._tmpUpVector = Vector3.Zero(); + this._tmpTargetVector = Vector3.Zero(); + /** + * Define the current direction the camera is moving to + */ + this.cameraDirection = new Vector3(0, 0, 0); + /** + * Define the current rotation the camera is rotating to + */ + this.cameraRotation = new Vector2(0, 0); + /** Gets or sets a boolean indicating that the scaling of the parent hierarchy will not be taken in account by the camera */ + this.ignoreParentScaling = false; + /** + * When set, the up vector of the camera will be updated by the rotation of the camera + */ + this.updateUpVectorFromRotation = false; + this._tmpQuaternion = new Quaternion(); + /** + * Define the current rotation of the camera + */ + this.rotation = new Vector3(0, 0, 0); + /** + * Define the current speed of the camera + */ + this.speed = 2.0; + /** + * Add constraint to the camera to prevent it to move freely in all directions and + * around all axis. + */ + this.noRotationConstraint = false; + /** + * Reverses mouselook direction to 'natural' panning as opposed to traditional direct + * panning + */ + this.invertRotation = false; + /** + * Speed multiplier for inverse camera panning + */ + this.inverseRotationSpeed = 0.2; + /** + * Define the current target of the camera as an object or a position. + * Please note that locking a target will disable panning. + */ + this.lockedTarget = null; + /** @internal */ + this._currentTarget = Vector3.Zero(); + /** @internal */ + this._initialFocalDistance = 1; + /** @internal */ + this._viewMatrix = Matrix.Zero(); + /** @internal */ + this._camMatrix = Matrix.Zero(); + /** @internal */ + this._cameraTransformMatrix = Matrix.Zero(); + /** @internal */ + this._cameraRotationMatrix = Matrix.Zero(); + /** @internal */ + this._referencePoint = new Vector3(0, 0, 1); + /** @internal */ + this._transformedReferencePoint = Vector3.Zero(); + this._deferredPositionUpdate = new Vector3(); + this._deferredRotationQuaternionUpdate = new Quaternion(); + this._deferredRotationUpdate = new Vector3(); + this._deferredUpdated = false; + this._deferOnly = false; + this._defaultUp = Vector3.Up(); + this._cachedRotationZ = 0; + this._cachedQuaternionRotationZ = 0; + } + /** + * Gets the position in front of the camera at a given distance. + * @param distance The distance from the camera we want the position to be + * @returns the position + */ + getFrontPosition(distance) { + this.getWorldMatrix(); + const worldForward = TmpVectors.Vector3[0]; + const localForward = TmpVectors.Vector3[1]; + localForward.set(0, 0, this._scene.useRightHandedSystem ? -1 : 1.0); + this.getDirectionToRef(localForward, worldForward); + worldForward.scaleInPlace(distance); + return this.globalPosition.add(worldForward); + } + /** @internal */ + _getLockedTargetPosition() { + if (!this.lockedTarget) { + return null; + } + if (this.lockedTarget.absolutePosition) { + const lockedTarget = this.lockedTarget; + const m = lockedTarget.computeWorldMatrix(); + // in some cases the absolute position resets externally, but doesn't update since the matrix is cached. + m.getTranslationToRef(lockedTarget.absolutePosition); + } + return this.lockedTarget.absolutePosition || this.lockedTarget; + } + /** + * Store current camera state of the camera (fov, position, rotation, etc..) + * @returns the camera + */ + storeState() { + this._storedPosition = this.position.clone(); + this._storedRotation = this.rotation.clone(); + if (this.rotationQuaternion) { + this._storedRotationQuaternion = this.rotationQuaternion.clone(); + } + return super.storeState(); + } + /** + * Restored camera state. You must call storeState() first + * @returns whether it was successful or not + * @internal + */ + _restoreStateValues() { + if (!super._restoreStateValues()) { + return false; + } + this.position = this._storedPosition.clone(); + this.rotation = this._storedRotation.clone(); + if (this.rotationQuaternion) { + this.rotationQuaternion = this._storedRotationQuaternion.clone(); + } + this.cameraDirection.copyFromFloats(0, 0, 0); + this.cameraRotation.copyFromFloats(0, 0); + return true; + } + /** @internal */ + _initCache() { + super._initCache(); + this._cache.lockedTarget = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cache.rotation = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cache.rotationQuaternion = new Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + } + /** + * @internal + */ + _updateCache(ignoreParentClass) { + if (!ignoreParentClass) { + super._updateCache(); + } + const lockedTargetPosition = this._getLockedTargetPosition(); + if (!lockedTargetPosition) { + this._cache.lockedTarget = null; + } + else { + if (!this._cache.lockedTarget) { + this._cache.lockedTarget = lockedTargetPosition.clone(); + } + else { + this._cache.lockedTarget.copyFrom(lockedTargetPosition); + } + } + this._cache.rotation.copyFrom(this.rotation); + if (this.rotationQuaternion) { + this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion); + } + } + // Synchronized + /** @internal */ + _isSynchronizedViewMatrix() { + if (!super._isSynchronizedViewMatrix()) { + return false; + } + const lockedTargetPosition = this._getLockedTargetPosition(); + return ((this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && + (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation))); + } + // Methods + /** @internal */ + _computeLocalCameraSpeed() { + const engine = this.getEngine(); + return this.speed * Math.sqrt(engine.getDeltaTime() / (engine.getFps() * 100.0)); + } + // Target + /** + * Defines the target the camera should look at. + * @param target Defines the new target as a Vector + */ + setTarget(target) { + this.upVector.normalize(); + this._initialFocalDistance = target.subtract(this.position).length(); + if (this.position.z === target.z) { + this.position.z += Epsilon; + } + this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance); + Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix); + this._camMatrix.invert(); + this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]); + const vDir = target.subtract(this.position); + if (vDir.x >= 0.0) { + this.rotation.y = -Math.atan(vDir.z / vDir.x) + Math.PI / 2.0; + } + else { + this.rotation.y = -Math.atan(vDir.z / vDir.x) - Math.PI / 2.0; + } + this.rotation.z = 0; + if (isNaN(this.rotation.x)) { + this.rotation.x = 0; + } + if (isNaN(this.rotation.y)) { + this.rotation.y = 0; + } + if (isNaN(this.rotation.z)) { + this.rotation.z = 0; + } + if (this.rotationQuaternion) { + Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion); + } + } + /** + * Defines the target point of the camera. + * The camera looks towards it form the radius distance. + */ + get target() { + return this.getTarget(); + } + set target(value) { + this.setTarget(value); + } + /** + * Return the current target position of the camera. This value is expressed in local space. + * @returns the target position + */ + getTarget() { + return this._currentTarget; + } + /** @internal */ + _decideIfNeedsToMove() { + return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; + } + /** @internal */ + _updatePosition() { + if (this.parent) { + this.parent.getWorldMatrix().invertToRef(TmpVectors.Matrix[0]); + Vector3.TransformNormalToRef(this.cameraDirection, TmpVectors.Matrix[0], TmpVectors.Vector3[0]); + this._deferredPositionUpdate.addInPlace(TmpVectors.Vector3[0]); + if (!this._deferOnly) { + this.position.copyFrom(this._deferredPositionUpdate); + } + else { + this._deferredUpdated = true; + } + return; + } + this._deferredPositionUpdate.addInPlace(this.cameraDirection); + if (!this._deferOnly) { + this.position.copyFrom(this._deferredPositionUpdate); + } + else { + this._deferredUpdated = true; + } + } + /** @internal */ + _checkInputs() { + const directionMultiplier = this.invertRotation ? -this.inverseRotationSpeed : 1.0; + const needToMove = this._decideIfNeedsToMove(); + const needToRotate = this.cameraRotation.x || this.cameraRotation.y; + this._deferredUpdated = false; + this._deferredRotationUpdate.copyFrom(this.rotation); + this._deferredPositionUpdate.copyFrom(this.position); + if (this.rotationQuaternion) { + this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion); + } + // Move + if (needToMove) { + this._updatePosition(); + } + // Rotate + if (needToRotate) { + //rotate, if quaternion is set and rotation was used + if (this.rotationQuaternion) { + this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate); + } + this._deferredRotationUpdate.x += this.cameraRotation.x * directionMultiplier; + this._deferredRotationUpdate.y += this.cameraRotation.y * directionMultiplier; + // Apply constraints + if (!this.noRotationConstraint) { + const limit = 1.570796; + if (this._deferredRotationUpdate.x > limit) { + this._deferredRotationUpdate.x = limit; + } + if (this._deferredRotationUpdate.x < -limit) { + this._deferredRotationUpdate.x = -limit; + } + } + if (!this._deferOnly) { + this.rotation.copyFrom(this._deferredRotationUpdate); + } + else { + this._deferredUpdated = true; + } + //rotate, if quaternion is set and rotation was used + if (this.rotationQuaternion) { + const len = this._deferredRotationUpdate.lengthSquared(); + if (len) { + Quaternion.RotationYawPitchRollToRef(this._deferredRotationUpdate.y, this._deferredRotationUpdate.x, this._deferredRotationUpdate.z, this._deferredRotationQuaternionUpdate); + if (!this._deferOnly) { + this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate); + } + else { + this._deferredUpdated = true; + } + } + } + } + // Inertia + if (needToMove) { + if (Math.abs(this.cameraDirection.x) < this.speed * Epsilon) { + this.cameraDirection.x = 0; + } + if (Math.abs(this.cameraDirection.y) < this.speed * Epsilon) { + this.cameraDirection.y = 0; + } + if (Math.abs(this.cameraDirection.z) < this.speed * Epsilon) { + this.cameraDirection.z = 0; + } + this.cameraDirection.scaleInPlace(this.inertia); + } + if (needToRotate) { + if (Math.abs(this.cameraRotation.x) < this.speed * Epsilon) { + this.cameraRotation.x = 0; + } + if (Math.abs(this.cameraRotation.y) < this.speed * Epsilon) { + this.cameraRotation.y = 0; + } + this.cameraRotation.scaleInPlace(this.inertia); + } + super._checkInputs(); + } + _updateCameraRotationMatrix() { + if (this.rotationQuaternion) { + this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix); + } + else { + Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix); + } + } + /** + * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well) + * @returns the current camera + */ + _rotateUpVectorWithCameraRotationMatrix() { + Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector); + return this; + } + /** @internal */ + _getViewMatrix() { + if (this.lockedTarget) { + this.setTarget(this._getLockedTargetPosition()); + } + // Compute + this._updateCameraRotationMatrix(); + // Apply the changed rotation to the upVector + if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) { + this._rotateUpVectorWithCameraRotationMatrix(); + this._cachedQuaternionRotationZ = this.rotationQuaternion.z; + } + else if (this._cachedRotationZ !== this.rotation.z) { + this._rotateUpVectorWithCameraRotationMatrix(); + this._cachedRotationZ = this.rotation.z; + } + Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint); + // Computing target and final matrix + this.position.addToRef(this._transformedReferencePoint, this._currentTarget); + if (this.updateUpVectorFromRotation) { + if (this.rotationQuaternion) { + Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector); + } + else { + Quaternion.FromEulerVectorToRef(this.rotation, this._tmpQuaternion); + Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector); + } + } + this._computeViewMatrix(this.position, this._currentTarget, this.upVector); + return this._viewMatrix; + } + _computeViewMatrix(position, target, up) { + if (this.ignoreParentScaling) { + if (this.parent) { + const parentWorldMatrix = this.parent.getWorldMatrix(); + Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition); + Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._tmpTargetVector); + Vector3.TransformNormalToRef(up, parentWorldMatrix, this._tmpUpVector); + this._markSyncedWithParent(); + } + else { + this._globalPosition.copyFrom(position); + this._tmpTargetVector.copyFrom(target); + this._tmpUpVector.copyFrom(up); + } + if (this.getScene().useRightHandedSystem) { + Matrix.LookAtRHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix); + } + else { + Matrix.LookAtLHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix); + } + return; + } + if (this.getScene().useRightHandedSystem) { + Matrix.LookAtRHToRef(position, target, up, this._viewMatrix); + } + else { + Matrix.LookAtLHToRef(position, target, up, this._viewMatrix); + } + if (this.parent) { + const parentWorldMatrix = this.parent.getWorldMatrix(); + this._viewMatrix.invert(); + this._viewMatrix.multiplyToRef(parentWorldMatrix, this._viewMatrix); + this._viewMatrix.getTranslationToRef(this._globalPosition); + this._viewMatrix.invert(); + this._markSyncedWithParent(); + } + else { + this._globalPosition.copyFrom(position); + } + } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + createRigCamera(name, cameraIndex) { + if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { + const rigCamera = new TargetCamera(name, this.position.clone(), this.getScene()); + rigCamera.isRigCamera = true; + rigCamera.rigParent = this; + if (this.cameraRigMode === Camera.RIG_MODE_VR) { + if (!this.rotationQuaternion) { + this.rotationQuaternion = new Quaternion(); + } + rigCamera._cameraRigParams = {}; + rigCamera.rotationQuaternion = new Quaternion(); + } + rigCamera.mode = this.mode; + rigCamera.orthoLeft = this.orthoLeft; + rigCamera.orthoRight = this.orthoRight; + rigCamera.orthoTop = this.orthoTop; + rigCamera.orthoBottom = this.orthoBottom; + return rigCamera; + } + return null; + } + /** + * @internal + */ + _updateRigCameras() { + const camLeft = this._rigCameras[0]; + const camRight = this._rigCameras[1]; + this.computeWorldMatrix(); + switch (this.cameraRigMode) { + case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH: + case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: + case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: + case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER: + case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED: { + //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance: + const leftSign = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? 1 : -1; + const rightSign = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? -1 : 1; + this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft); + this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * rightSign, camRight); + break; + } + case Camera.RIG_MODE_VR: + if (camLeft.rotationQuaternion) { + camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion); + camRight.rotationQuaternion.copyFrom(this.rotationQuaternion); + } + else { + camLeft.rotation.copyFrom(this.rotation); + camRight.rotation.copyFrom(this.rotation); + } + camLeft.position.copyFrom(this.position); + camRight.position.copyFrom(this.position); + break; + } + super._updateRigCameras(); + } + _getRigCamPositionAndTarget(halfSpace, rigCamera) { + const target = this.getTarget(); + target.subtractToRef(this.position, TargetCamera._TargetFocalPoint); + TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance); + const newFocalTarget = TargetCamera._TargetFocalPoint.addInPlace(this.position); + Matrix.TranslationToRef(-newFocalTarget.x, -newFocalTarget.y, -newFocalTarget.z, TargetCamera._TargetTransformMatrix); + TargetCamera._TargetTransformMatrix.multiplyToRef(Matrix.RotationAxis(rigCamera.upVector, halfSpace), TargetCamera._RigCamTransformMatrix); + Matrix.TranslationToRef(newFocalTarget.x, newFocalTarget.y, newFocalTarget.z, TargetCamera._TargetTransformMatrix); + TargetCamera._RigCamTransformMatrix.multiplyToRef(TargetCamera._TargetTransformMatrix, TargetCamera._RigCamTransformMatrix); + Vector3.TransformCoordinatesToRef(this.position, TargetCamera._RigCamTransformMatrix, rigCamera.position); + rigCamera.setTarget(newFocalTarget); + } + /** + * Gets the current object class name. + * @returns the class name + */ + getClassName() { + return "TargetCamera"; + } +} +TargetCamera._RigCamTransformMatrix = new Matrix(); +TargetCamera._TargetTransformMatrix = new Matrix(); +TargetCamera._TargetFocalPoint = new Vector3(); +__decorate([ + serialize() +], TargetCamera.prototype, "ignoreParentScaling", void 0); +__decorate([ + serialize() +], TargetCamera.prototype, "updateUpVectorFromRotation", void 0); +__decorate([ + serializeAsVector3() +], TargetCamera.prototype, "rotation", void 0); +__decorate([ + serialize() +], TargetCamera.prototype, "speed", void 0); +__decorate([ + serializeAsMeshReference("lockedTargetId") +], TargetCamera.prototype, "lockedTarget", void 0); + +/** + * @ignore + * This is a list of all the different input types that are available in the application. + * Fo instance: ArcRotateCameraGamepadInput... + */ +// eslint-disable-next-line no-var, @typescript-eslint/naming-convention +var CameraInputTypes = {}; +/** + * This represents the input manager used within a camera. + * It helps dealing with all the different kind of input attached to a camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class CameraInputsManager { + /** + * Instantiate a new Camera Input Manager. + * @param camera Defines the camera the input manager belongs to + */ + constructor(camera) { + /** + * Defines the dom element the camera is collecting inputs from. + * This is null if the controls have not been attached. + */ + this.attachedToElement = false; + this.attached = {}; + this.camera = camera; + this.checkInputs = () => { }; + } + /** + * Add an input method to a camera + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + * @param input Camera input method + */ + add(input) { + const type = input.getSimpleName(); + if (this.attached[type]) { + Logger.Warn("camera input of type " + type + " already exists on camera"); + return; + } + this.attached[type] = input; + input.camera = this.camera; + // for checkInputs, we are dynamically creating a function + // the goal is to avoid the performance penalty of looping for inputs in the render loop + if (input.checkInputs) { + this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input)); + } + if (this.attachedToElement) { + input.attachControl(this.noPreventDefault); + } + } + /** + * Remove a specific input method from a camera + * example: camera.inputs.remove(camera.inputs.attached.mouse); + * @param inputToRemove camera input method + */ + remove(inputToRemove) { + for (const cam in this.attached) { + const input = this.attached[cam]; + if (input === inputToRemove) { + input.detachControl(); + input.camera = null; + delete this.attached[cam]; + this.rebuildInputCheck(); + return; + } + } + } + /** + * Remove a specific input type from a camera + * example: camera.inputs.remove("ArcRotateCameraGamepadInput"); + * @param inputType the type of the input to remove + */ + removeByType(inputType) { + for (const cam in this.attached) { + const input = this.attached[cam]; + if (input.getClassName() === inputType) { + input.detachControl(); + input.camera = null; + delete this.attached[cam]; + this.rebuildInputCheck(); + } + } + } + _addCheckInputs(fn) { + const current = this.checkInputs; + return () => { + current(); + fn(); + }; + } + /** + * Attach the input controls to the currently attached dom element to listen the events from. + * @param input Defines the input to attach + */ + attachInput(input) { + if (this.attachedToElement) { + input.attachControl(this.noPreventDefault); + } + } + /** + * Attach the current manager inputs controls to a specific dom element to listen the events from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachElement(noPreventDefault = false) { + if (this.attachedToElement) { + return; + } + noPreventDefault = Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault; + this.attachedToElement = true; + this.noPreventDefault = noPreventDefault; + for (const cam in this.attached) { + this.attached[cam].attachControl(noPreventDefault); + } + } + /** + * Detach the current manager inputs controls from a specific dom element. + * @param disconnect Defines whether the input should be removed from the current list of attached inputs + */ + detachElement(disconnect = false) { + for (const cam in this.attached) { + this.attached[cam].detachControl(); + if (disconnect) { + this.attached[cam].camera = null; + } + } + this.attachedToElement = false; + } + /** + * Rebuild the dynamic inputCheck function from the current list of + * defined inputs in the manager. + */ + rebuildInputCheck() { + this.checkInputs = () => { }; + for (const cam in this.attached) { + const input = this.attached[cam]; + if (input.checkInputs) { + this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input)); + } + } + } + /** + * Remove all attached input methods from a camera + */ + clear() { + if (this.attachedToElement) { + this.detachElement(true); + } + this.attached = {}; + this.attachedToElement = false; + this.checkInputs = () => { }; + } + /** + * Serialize the current input manager attached to a camera. + * This ensures than once parsed, + * the input associated to the camera will be identical to the current ones + * @param serializedCamera Defines the camera serialization JSON the input serialization should write to + */ + serialize(serializedCamera) { + const inputs = {}; + for (const cam in this.attached) { + const input = this.attached[cam]; + const res = SerializationHelper.Serialize(input); + inputs[input.getClassName()] = res; + } + serializedCamera.inputsmgr = inputs; + } + /** + * Parses an input manager serialized JSON to restore the previous list of inputs + * and states associated to a camera. + * @param parsedCamera Defines the JSON to parse + */ + parse(parsedCamera) { + const parsedInputs = parsedCamera.inputsmgr; + if (parsedInputs) { + this.clear(); + for (const n in parsedInputs) { + const construct = CameraInputTypes[n]; + if (construct) { + const parsedinput = parsedInputs[n]; + const input = SerializationHelper.Parse(() => { + return new construct(); + }, parsedinput, null); + this.add(input); + } + } + } + else { + //2016-03-08 this part is for managing backward compatibility + for (const n in this.attached) { + const construct = CameraInputTypes[this.attached[n].getClassName()]; + if (construct) { + const input = SerializationHelper.Parse(() => { + return new construct(); + }, parsedCamera, null); + this.remove(this.attached[n]); + this.add(input); + } + } + } + } +} + +/** + * Base class for Camera Pointer Inputs. + * See FollowCameraPointersInput in src/Cameras/Inputs/followCameraPointersInput.ts + * for example usage. + */ +class BaseCameraPointersInput { + constructor() { + /** + * Which pointer ID is currently down (only for mouse events, not used for touch events) + */ + this._currentMousePointerIdDown = -1; + /** + * Defines the buttons associated with the input to handle camera move. + */ + this.buttons = [0, 1, 2]; + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + const engine = this.camera.getEngine(); + const element = engine.getInputElement(); + let previousPinchSquaredDistance = 0; + let previousMultiTouchPanPosition = null; + this._pointA = null; + this._pointB = null; + this._altKey = false; + this._ctrlKey = false; + this._metaKey = false; + this._shiftKey = false; + this._buttonsPressed = 0; + this._pointerInput = (p) => { + const evt = p.event; + const isTouch = evt.pointerType === "touch"; + if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) { + return; + } + const srcElement = evt.target; + this._altKey = evt.altKey; + this._ctrlKey = evt.ctrlKey; + this._metaKey = evt.metaKey; + this._shiftKey = evt.shiftKey; + this._buttonsPressed = evt.buttons; + if (engine.isPointerLock) { + const offsetX = evt.movementX; + const offsetY = evt.movementY; + this.onTouch(null, offsetX, offsetY); + this._pointA = null; + this._pointB = null; + } + else if (p.type !== PointerEventTypes.POINTERDOWN && + p.type !== PointerEventTypes.POINTERDOUBLETAP && + isTouch && + this._pointA?.pointerId !== evt.pointerId && + this._pointB?.pointerId !== evt.pointerId) { + return; // If we get a non-down event for a touch that we're not tracking, ignore it + } + else if (p.type === PointerEventTypes.POINTERDOWN && (this._currentMousePointerIdDown === -1 || isTouch)) { + try { + srcElement?.setPointerCapture(evt.pointerId); + } + catch (e) { + //Nothing to do with the error. Execution will continue. + } + if (this._pointA === null) { + this._pointA = { + x: evt.clientX, + y: evt.clientY, + pointerId: evt.pointerId, + type: evt.pointerType, + }; + } + else if (this._pointB === null) { + this._pointB = { + x: evt.clientX, + y: evt.clientY, + pointerId: evt.pointerId, + type: evt.pointerType, + }; + } + else { + return; // We are already tracking two pointers so ignore this one + } + if (this._currentMousePointerIdDown === -1 && !isTouch) { + this._currentMousePointerIdDown = evt.pointerId; + } + this.onButtonDown(evt); + if (!noPreventDefault) { + evt.preventDefault(); + element && element.focus(); + } + } + else if (p.type === PointerEventTypes.POINTERDOUBLETAP) { + this.onDoubleTap(evt.pointerType); + } + else if (p.type === PointerEventTypes.POINTERUP && (this._currentMousePointerIdDown === evt.pointerId || isTouch)) { + try { + srcElement?.releasePointerCapture(evt.pointerId); + } + catch (e) { + //Nothing to do with the error. + } + if (!isTouch) { + this._pointB = null; // Mouse and pen are mono pointer + } + //would be better to use pointers.remove(evt.pointerId) for multitouch gestures, + //but emptying completely pointers collection is required to fix a bug on iPhone : + //when changing orientation while pinching camera, + //one pointer stay pressed forever if we don't release all pointers + //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected + if (engine._badOS) { + this._pointA = this._pointB = null; + } + else { + //only remove the impacted pointer in case of multitouch allowing on most + //platforms switching from rotate to zoom and pan seamlessly. + if (this._pointB && this._pointA && this._pointA.pointerId == evt.pointerId) { + this._pointA = this._pointB; + this._pointB = null; + } + else if (this._pointA && this._pointB && this._pointB.pointerId == evt.pointerId) { + this._pointB = null; + } + else { + this._pointA = this._pointB = null; + } + } + if (previousPinchSquaredDistance !== 0 || previousMultiTouchPanPosition) { + // Previous pinch data is populated but a button has been lifted + // so pinch has ended. + this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, 0, // pinchSquaredDistance + previousMultiTouchPanPosition, null // multiTouchPanPosition + ); + previousPinchSquaredDistance = 0; + previousMultiTouchPanPosition = null; + } + this._currentMousePointerIdDown = -1; + this.onButtonUp(evt); + if (!noPreventDefault) { + evt.preventDefault(); + } + } + else if (p.type === PointerEventTypes.POINTERMOVE) { + if (!noPreventDefault) { + evt.preventDefault(); + } + // One button down + if (this._pointA && this._pointB === null) { + const offsetX = evt.clientX - this._pointA.x; + const offsetY = evt.clientY - this._pointA.y; + this._pointA.x = evt.clientX; + this._pointA.y = evt.clientY; + this.onTouch(this._pointA, offsetX, offsetY); + } + // Two buttons down: pinch + else if (this._pointA && this._pointB) { + const ed = this._pointA.pointerId === evt.pointerId ? this._pointA : this._pointB; + ed.x = evt.clientX; + ed.y = evt.clientY; + const distX = this._pointA.x - this._pointB.x; + const distY = this._pointA.y - this._pointB.y; + const pinchSquaredDistance = distX * distX + distY * distY; + const multiTouchPanPosition = { + x: (this._pointA.x + this._pointB.x) / 2, + y: (this._pointA.y + this._pointB.y) / 2, + pointerId: evt.pointerId, + type: p.type, + }; + this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition); + previousMultiTouchPanPosition = multiTouchPanPosition; + previousPinchSquaredDistance = pinchSquaredDistance; + } + } + }; + this._observer = this.camera + .getScene() + ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE | PointerEventTypes.POINTERDOUBLETAP); + this._onLostFocus = () => { + this._pointA = this._pointB = null; + previousPinchSquaredDistance = 0; + previousMultiTouchPanPosition = null; + this.onLostFocus(); + }; + this._contextMenuBind = (evt) => this.onContextMenu(evt); + element && element.addEventListener("contextmenu", this._contextMenuBind, false); + const hostWindow = this.camera.getScene().getEngine().getHostWindow(); + if (hostWindow) { + Tools.RegisterTopRootEvents(hostWindow, [{ name: "blur", handler: this._onLostFocus }]); + } + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._onLostFocus) { + const hostWindow = this.camera.getScene().getEngine().getHostWindow(); + if (hostWindow) { + Tools.UnregisterTopRootEvents(hostWindow, [{ name: "blur", handler: this._onLostFocus }]); + } + } + if (this._observer) { + this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); + this._observer = null; + if (this._contextMenuBind) { + const inputElement = this.camera.getScene().getEngine().getInputElement(); + inputElement && inputElement.removeEventListener("contextmenu", this._contextMenuBind); + } + this._onLostFocus = null; + } + this._altKey = false; + this._ctrlKey = false; + this._metaKey = false; + this._shiftKey = false; + this._buttonsPressed = 0; + this._currentMousePointerIdDown = -1; + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "BaseCameraPointersInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "pointers"; + } + /** + * Called on pointer POINTERDOUBLETAP event. + * Override this method to provide functionality on POINTERDOUBLETAP event. + * @param type type of event + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onDoubleTap(type) { } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + /** + * Called on pointer POINTERMOVE event if only a single touch is active. + * Override this method to provide functionality. + * @param point The current position of the pointer + * @param offsetX The offsetX of the pointer when the event occurred + * @param offsetY The offsetY of the pointer when the event occurred + */ + onTouch(point, offsetX, offsetY) { } + /** + * Called on pointer POINTERMOVE event if multiple touches are active. + * Override this method to provide functionality. + * @param _pointA First point in the pair + * @param _pointB Second point in the pair + * @param previousPinchSquaredDistance Sqr Distance between the points the last time this event was fired (by this input) + * @param pinchSquaredDistance Sqr Distance between the points this time + * @param previousMultiTouchPanPosition Previous center point between the points + * @param multiTouchPanPosition Current center point between the points + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onMultiTouch(_pointA, _pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { } + /** + * Called on JS contextmenu event. + * Override this method to provide functionality. + * @param evt the event to be handled + */ + onContextMenu(evt) { + evt.preventDefault(); + } + /** + * Called each time a new POINTERDOWN event occurs. Ie, for each button + * press. + * Override this method to provide functionality. + * @param _evt Defines the event to track + */ + onButtonDown(_evt) { } + /** + * Called each time a new POINTERUP event occurs. Ie, for each button + * release. + * Override this method to provide functionality. + * @param _evt Defines the event to track + */ + onButtonUp(_evt) { } + /** + * Called when window becomes inactive. + * Override this method to provide functionality. + */ + onLostFocus() { } +} +__decorate([ + serialize() +], BaseCameraPointersInput.prototype, "buttons", void 0); + +/** + * Manage the pointers inputs to control an arc rotate camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class ArcRotateCameraPointersInput extends BaseCameraPointersInput { + constructor() { + super(...arguments); + /** + * Defines the buttons associated with the input to handle camera move. + */ + this.buttons = [0, 1, 2]; + /** + * Defines the pointer angular sensibility along the X axis or how fast is + * the camera rotating. + */ + this.angularSensibilityX = 1000.0; + /** + * Defines the pointer angular sensibility along the Y axis or how fast is + * the camera rotating. + */ + this.angularSensibilityY = 1000.0; + /** + * Defines the pointer pinch precision or how fast is the camera zooming. + */ + this.pinchPrecision = 12.0; + /** + * pinchDeltaPercentage will be used instead of pinchPrecision if different + * from 0. + * It defines the percentage of current camera.radius to use as delta when + * pinch zoom is used. + */ + this.pinchDeltaPercentage = 0; + /** + * When useNaturalPinchZoom is true, multi touch zoom will zoom in such + * that any object in the plane at the camera's target point will scale + * perfectly with finger motion. + * Overrides pinchDeltaPercentage and pinchPrecision. + */ + this.useNaturalPinchZoom = false; + /** + * Defines whether zoom (2 fingers pinch) is enabled through multitouch + */ + this.pinchZoom = true; + /** + * Defines the pointer panning sensibility or how fast is the camera moving. + */ + this.panningSensibility = 1000.0; + /** + * Defines whether panning (2 fingers swipe) is enabled through multitouch. + */ + this.multiTouchPanning = true; + /** + * Defines whether panning is enabled for both pan (2 fingers swipe) and + * zoom (pinch) through multitouch. + */ + this.multiTouchPanAndZoom = true; + /** + * Revers pinch action direction. + */ + this.pinchInwards = true; + this._isPanClick = false; + this._twoFingerActivityCount = 0; + this._isPinching = false; + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "ArcRotateCameraPointersInput"; + } + /** + * Move camera from multi touch panning positions. + * @param previousMultiTouchPanPosition + * @param multiTouchPanPosition + */ + _computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition) { + if (this.panningSensibility !== 0 && previousMultiTouchPanPosition && multiTouchPanPosition) { + const moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x; + const moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y; + this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility; + this.camera.inertialPanningY += moveDeltaY / this.panningSensibility; + } + } + /** + * Move camera from pinch zoom distances. + * @param previousPinchSquaredDistance + * @param pinchSquaredDistance + */ + _computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance) { + const radius = this.camera.radius || ArcRotateCameraPointersInput.MinimumRadiusForPinch; + if (this.useNaturalPinchZoom) { + this.camera.radius = (radius * Math.sqrt(previousPinchSquaredDistance)) / Math.sqrt(pinchSquaredDistance); + } + else if (this.pinchDeltaPercentage) { + this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * radius * this.pinchDeltaPercentage; + } + else { + this.camera.inertialRadiusOffset += + (pinchSquaredDistance - previousPinchSquaredDistance) / + ((this.pinchPrecision * (this.pinchInwards ? 1 : -1) * (this.angularSensibilityX + this.angularSensibilityY)) / 2); + } + } + /** + * Called on pointer POINTERMOVE event if only a single touch is active. + * @param point current touch point + * @param offsetX offset on X + * @param offsetY offset on Y + */ + onTouch(point, offsetX, offsetY) { + if (this.panningSensibility !== 0 && ((this._ctrlKey && this.camera._useCtrlForPanning) || this._isPanClick)) { + this.camera.inertialPanningX += -offsetX / this.panningSensibility; + this.camera.inertialPanningY += offsetY / this.panningSensibility; + } + else { + this.camera.inertialAlphaOffset -= offsetX / this.angularSensibilityX; + this.camera.inertialBetaOffset -= offsetY / this.angularSensibilityY; + } + } + /** + * Called on pointer POINTERDOUBLETAP event. + */ + onDoubleTap() { + if (this.camera.useInputToRestoreState) { + this.camera.restoreState(); + } + } + /** + * Called on pointer POINTERMOVE event if multiple touches are active. + * @param pointA point A + * @param pointB point B + * @param previousPinchSquaredDistance distance between points in previous pinch + * @param pinchSquaredDistance distance between points in current pinch + * @param previousMultiTouchPanPosition multi-touch position in previous step + * @param multiTouchPanPosition multi-touch position in current step + */ + onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { + if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) { + // First time this method is called for new pinch. + // Next time this is called there will be a + // previousPinchSquaredDistance and pinchSquaredDistance to compare. + return; + } + if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) { + // Last time this method is called at the end of a pinch. + return; + } + // Zoom and panning enabled together + if (this.multiTouchPanAndZoom) { + this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance); + this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition); + // Zoom and panning enabled but only one at a time + } + else if (this.multiTouchPanning && this.pinchZoom) { + this._twoFingerActivityCount++; + if (this._isPinching || + (this._twoFingerActivityCount < 20 && Math.abs(Math.sqrt(pinchSquaredDistance) - Math.sqrt(previousPinchSquaredDistance)) > this.camera.pinchToPanMaxDistance)) { + // Since pinch has not been active long, assume we intend to zoom. + this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance); + // Since we are pinching, remain pinching on next iteration. + this._isPinching = true; + } + else { + // Pause between pinch starting and moving implies not a zoom event. Pan instead. + this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition); + } + // Panning enabled, zoom disabled + } + else if (this.multiTouchPanning) { + this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition); + // Zoom enabled, panning disabled + } + else if (this.pinchZoom) { + this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance); + } + } + /** + * Called each time a new POINTERDOWN event occurs. Ie, for each button + * press. + * @param evt Defines the event to track + */ + onButtonDown(evt) { + this._isPanClick = evt.button === this.camera._panningMouseButton; + } + /** + * Called each time a new POINTERUP event occurs. Ie, for each button + * release. + * @param _evt Defines the event to track + */ + onButtonUp(_evt) { + this._twoFingerActivityCount = 0; + this._isPinching = false; + } + /** + * Called when window becomes inactive. + */ + onLostFocus() { + this._isPanClick = false; + this._twoFingerActivityCount = 0; + this._isPinching = false; + } +} +/** + * The minimum radius used for pinch, to avoid radius lock at 0 + */ +ArcRotateCameraPointersInput.MinimumRadiusForPinch = 0.001; +__decorate([ + serialize() +], ArcRotateCameraPointersInput.prototype, "buttons", void 0); +__decorate([ + serialize() +], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0); +__decorate([ + serialize() +], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0); +__decorate([ + serialize() +], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0); +__decorate([ + serialize() +], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0); +__decorate([ + serialize() +], ArcRotateCameraPointersInput.prototype, "useNaturalPinchZoom", void 0); +__decorate([ + serialize() +], ArcRotateCameraPointersInput.prototype, "pinchZoom", void 0); +__decorate([ + serialize() +], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0); +__decorate([ + serialize() +], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0); +__decorate([ + serialize() +], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0); +CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput; + +/** + * Manage the keyboard inputs to control the movement of an arc rotate camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class ArcRotateCameraKeyboardMoveInput { + constructor() { + /** + * Defines the list of key codes associated with the up action (increase alpha) + */ + this.keysUp = [38]; + /** + * Defines the list of key codes associated with the down action (decrease alpha) + */ + this.keysDown = [40]; + /** + * Defines the list of key codes associated with the left action (increase beta) + */ + this.keysLeft = [37]; + /** + * Defines the list of key codes associated with the right action (decrease beta) + */ + this.keysRight = [39]; + /** + * Defines the list of key codes associated with the reset action. + * Those keys reset the camera to its last stored state (with the method camera.storeState()) + */ + this.keysReset = [220]; + /** + * Defines the panning sensibility of the inputs. + * (How fast is the camera panning) + */ + this.panningSensibility = 50.0; + /** + * Defines the zooming sensibility of the inputs. + * (How fast is the camera zooming) + */ + this.zoomingSensibility = 25.0; + /** + * Defines whether maintaining the alt key down switch the movement mode from + * orientation to zoom. + */ + this.useAltToZoom = true; + /** + * Rotation speed of the camera + */ + this.angularSpeed = 0.01; + this._keys = new Array(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + // was there a second variable defined? + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + if (this._onCanvasBlurObserver) { + return; + } + this._scene = this.camera.getScene(); + this._engine = this._scene.getEngine(); + this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => { + this._keys.length = 0; + }); + this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => { + const evt = info.event; + if (!evt.metaKey) { + if (info.type === KeyboardEventTypes.KEYDOWN) { + this._ctrlPressed = evt.ctrlKey; + this._altPressed = evt.altKey; + if (this.keysUp.indexOf(evt.keyCode) !== -1 || + this.keysDown.indexOf(evt.keyCode) !== -1 || + this.keysLeft.indexOf(evt.keyCode) !== -1 || + this.keysRight.indexOf(evt.keyCode) !== -1 || + this.keysReset.indexOf(evt.keyCode) !== -1) { + const index = this._keys.indexOf(evt.keyCode); + if (index === -1) { + this._keys.push(evt.keyCode); + } + if (evt.preventDefault) { + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + } + else { + if (this.keysUp.indexOf(evt.keyCode) !== -1 || + this.keysDown.indexOf(evt.keyCode) !== -1 || + this.keysLeft.indexOf(evt.keyCode) !== -1 || + this.keysRight.indexOf(evt.keyCode) !== -1 || + this.keysReset.indexOf(evt.keyCode) !== -1) { + const index = this._keys.indexOf(evt.keyCode); + if (index >= 0) { + this._keys.splice(index, 1); + } + if (evt.preventDefault) { + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + } + } + }); + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._scene) { + if (this._onKeyboardObserver) { + this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); + } + if (this._onCanvasBlurObserver) { + this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); + } + this._onKeyboardObserver = null; + this._onCanvasBlurObserver = null; + } + this._keys.length = 0; + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + if (this._onKeyboardObserver) { + const camera = this.camera; + for (let index = 0; index < this._keys.length; index++) { + const keyCode = this._keys[index]; + if (this.keysLeft.indexOf(keyCode) !== -1) { + if (this._ctrlPressed && this.camera._useCtrlForPanning) { + camera.inertialPanningX -= 1 / this.panningSensibility; + } + else { + camera.inertialAlphaOffset -= this.angularSpeed; + } + } + else if (this.keysUp.indexOf(keyCode) !== -1) { + if (this._ctrlPressed && this.camera._useCtrlForPanning) { + camera.inertialPanningY += 1 / this.panningSensibility; + } + else if (this._altPressed && this.useAltToZoom) { + camera.inertialRadiusOffset += 1 / this.zoomingSensibility; + } + else { + camera.inertialBetaOffset -= this.angularSpeed; + } + } + else if (this.keysRight.indexOf(keyCode) !== -1) { + if (this._ctrlPressed && this.camera._useCtrlForPanning) { + camera.inertialPanningX += 1 / this.panningSensibility; + } + else { + camera.inertialAlphaOffset += this.angularSpeed; + } + } + else if (this.keysDown.indexOf(keyCode) !== -1) { + if (this._ctrlPressed && this.camera._useCtrlForPanning) { + camera.inertialPanningY -= 1 / this.panningSensibility; + } + else if (this._altPressed && this.useAltToZoom) { + camera.inertialRadiusOffset -= 1 / this.zoomingSensibility; + } + else { + camera.inertialBetaOffset += this.angularSpeed; + } + } + else if (this.keysReset.indexOf(keyCode) !== -1) { + if (camera.useInputToRestoreState) { + camera.restoreState(); + } + } + } + } + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "ArcRotateCameraKeyboardMoveInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "keyboard"; + } +} +__decorate([ + serialize() +], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0); +__decorate([ + serialize() +], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0); +__decorate([ + serialize() +], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0); +__decorate([ + serialize() +], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0); +__decorate([ + serialize() +], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0); +__decorate([ + serialize() +], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0); +__decorate([ + serialize() +], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0); +__decorate([ + serialize() +], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0); +__decorate([ + serialize() +], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0); +CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput; + +/** + * Firefox uses a different scheme to report scroll distances to other + * browsers. Rather than use complicated methods to calculate the exact + * multiple we need to apply, let's just cheat and use a constant. + * https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode + * https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line + */ +const ffMultiplier = 40; +/** + * Manage the mouse wheel inputs to control an arc rotate camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class ArcRotateCameraMouseWheelInput { + constructor() { + /** + * Gets or Set the mouse wheel precision or how fast is the camera zooming. + */ + this.wheelPrecision = 3.0; + /** + * Gets or Set the boolean value that controls whether or not the mouse wheel + * zooms to the location of the mouse pointer or not. The default is false. + */ + this.zoomToMouseLocation = false; + /** + * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0. + * It defines the percentage of current camera.radius to use as delta when wheel is used. + */ + this.wheelDeltaPercentage = 0; + /** + * If set, this function will be used to set the radius delta that will be added to the current camera radius + */ + this.customComputeDeltaFromMouseWheel = null; + this._viewOffset = new Vector3(0, 0, 0); + this._globalOffset = new Vector3(0, 0, 0); + this._inertialPanning = Vector3.Zero(); + } + _computeDeltaFromMouseWheelLegacyEvent(mouseWheelDelta, radius) { + let delta = 0; + const wheelDelta = mouseWheelDelta * 0.01 * this.wheelDeltaPercentage * radius; + if (mouseWheelDelta > 0) { + delta = wheelDelta / (1.0 + this.wheelDeltaPercentage); + } + else { + delta = wheelDelta * (1.0 + this.wheelDeltaPercentage); + } + return delta; + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + this._wheel = (p) => { + //sanity check - this should be a PointerWheel event. + if (p.type !== PointerEventTypes.POINTERWHEEL) { + return; + } + const event = p.event; + let delta = 0; + const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? ffMultiplier : 1; // If this happens to be set to DOM_DELTA_LINE, adjust accordingly + const wheelDelta = -(event.deltaY * platformScale); + if (this.customComputeDeltaFromMouseWheel) { + delta = this.customComputeDeltaFromMouseWheel(wheelDelta, this, event); + } + else { + if (this.wheelDeltaPercentage) { + delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, this.camera.radius); + // If zooming in, estimate the target radius and use that to compute the delta for inertia + // this will stop multiple scroll events zooming in from adding too much inertia + if (delta > 0) { + let estimatedTargetRadius = this.camera.radius; + let targetInertia = this.camera.inertialRadiusOffset + delta; + for (let i = 0; i < 20 && Math.abs(targetInertia) > 0.001; i++) { + estimatedTargetRadius -= targetInertia; + targetInertia *= this.camera.inertia; + } + estimatedTargetRadius = Clamp(estimatedTargetRadius, 0, Number.MAX_VALUE); + delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, estimatedTargetRadius); + } + } + else { + delta = wheelDelta / (this.wheelPrecision * 40); + } + } + if (delta) { + if (this.zoomToMouseLocation) { + // If we are zooming to the mouse location, then we need to get the hit plane at the start of the zoom gesture if it doesn't exist + // The hit plane is normally calculated after the first motion and each time there's motion so if we don't do this first, + // the first zoom will be to the center of the screen + if (!this._hitPlane) { + this._updateHitPlane(); + } + this._zoomToMouse(delta); + } + else { + this.camera.inertialRadiusOffset += delta; + } + } + if (event.preventDefault) { + if (!noPreventDefault) { + event.preventDefault(); + } + } + }; + this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL); + if (this.zoomToMouseLocation) { + this._inertialPanning.setAll(0); + } + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._observer) { + this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); + this._observer = null; + this._wheel = null; + } + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + if (!this.zoomToMouseLocation) { + return; + } + const camera = this.camera; + const motion = 0.0 + camera.inertialAlphaOffset + camera.inertialBetaOffset + camera.inertialRadiusOffset; + if (motion) { + // if zooming is still happening as a result of inertia, then we also need to update + // the hit plane. + this._updateHitPlane(); + // Note we cannot use arcRotateCamera.inertialPlanning here because arcRotateCamera panning + // uses a different panningInertia which could cause this panning to get out of sync with + // the zooming, and for this to work they must be exactly in sync. + camera.target.addInPlace(this._inertialPanning); + this._inertialPanning.scaleInPlace(camera.inertia); + this._zeroIfClose(this._inertialPanning); + } + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "ArcRotateCameraMouseWheelInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "mousewheel"; + } + _updateHitPlane() { + const camera = this.camera; + const direction = camera.target.subtract(camera.position); + this._hitPlane = Plane.FromPositionAndNormal(camera.target, direction); + } + // Get position on the hit plane + _getPosition() { + const camera = this.camera; + const scene = camera.getScene(); + // since the _hitPlane is always updated to be orthogonal to the camera position vector + // we don't have to worry about this ray shooting off to infinity. This ray creates + // a vector defining where we want to zoom to. + const ray = scene.createPickingRay(scene.pointerX, scene.pointerY, Matrix.Identity(), camera, false); + // Since the camera is the origin of the picking ray, we need to offset it by the camera's offset manually + // Because the offset is in view space, we need to convert it to world space first + if (camera.targetScreenOffset.x !== 0 || camera.targetScreenOffset.y !== 0) { + this._viewOffset.set(camera.targetScreenOffset.x, camera.targetScreenOffset.y, 0); + camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); + this._globalOffset = Vector3.TransformNormal(this._viewOffset, camera._cameraTransformMatrix); + ray.origin.addInPlace(this._globalOffset); + } + let distance = 0; + if (this._hitPlane) { + distance = ray.intersectsPlane(this._hitPlane) ?? 0; + } + // not using this ray again, so modifying its vectors here is fine + return ray.origin.addInPlace(ray.direction.scaleInPlace(distance)); + } + _zoomToMouse(delta) { + const camera = this.camera; + const inertiaComp = 1 - camera.inertia; + if (camera.lowerRadiusLimit) { + const lowerLimit = camera.lowerRadiusLimit ?? 0; + if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp < lowerLimit) { + delta = (camera.radius - lowerLimit) * inertiaComp - camera.inertialRadiusOffset; + } + } + if (camera.upperRadiusLimit) { + const upperLimit = camera.upperRadiusLimit ?? 0; + if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp > upperLimit) { + delta = (camera.radius - upperLimit) * inertiaComp - camera.inertialRadiusOffset; + } + } + const zoomDistance = delta / inertiaComp; + const ratio = zoomDistance / camera.radius; + const vec = this._getPosition(); + // Now this vector tells us how much we also need to pan the camera + // so the targeted mouse location becomes the center of zooming. + const directionToZoomLocation = TmpVectors.Vector3[6]; + vec.subtractToRef(camera.target, directionToZoomLocation); + directionToZoomLocation.scaleInPlace(ratio); + directionToZoomLocation.scaleInPlace(inertiaComp); + this._inertialPanning.addInPlace(directionToZoomLocation); + camera.inertialRadiusOffset += delta; + } + // Sets x y or z of passed in vector to zero if less than Epsilon. + _zeroIfClose(vec) { + if (Math.abs(vec.x) < Epsilon) { + vec.x = 0; + } + if (Math.abs(vec.y) < Epsilon) { + vec.y = 0; + } + if (Math.abs(vec.z) < Epsilon) { + vec.z = 0; + } + } +} +__decorate([ + serialize() +], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0); +__decorate([ + serialize() +], ArcRotateCameraMouseWheelInput.prototype, "zoomToMouseLocation", void 0); +__decorate([ + serialize() +], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0); +CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput; + +/** + * Default Inputs manager for the ArcRotateCamera. + * It groups all the default supported inputs for ease of use. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class ArcRotateCameraInputsManager extends CameraInputsManager { + /** + * Instantiates a new ArcRotateCameraInputsManager. + * @param camera Defines the camera the inputs belong to + */ + constructor(camera) { + super(camera); + } + /** + * Add mouse wheel input support to the input manager. + * @returns the current input manager + */ + addMouseWheel() { + this.add(new ArcRotateCameraMouseWheelInput()); + return this; + } + /** + * Add pointers input support to the input manager. + * @returns the current input manager + */ + addPointers() { + this.add(new ArcRotateCameraPointersInput()); + return this; + } + /** + * Add keyboard input support to the input manager. + * @returns the current input manager + */ + addKeyboard() { + this.add(new ArcRotateCameraKeyboardMoveInput()); + return this; + } +} + +Node$2.AddNodeConstructor("ArcRotateCamera", (name, scene) => { + return () => new ArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), scene); +}); +/** + * Computes the alpha angle based on the source position and the target position. + * @param offset The directional offset between the source position and the target position + * @returns The alpha angle in radians + */ +function ComputeAlpha(offset) { + // Default alpha to π/2 to handle the edge case where x and z are both zero (when looking along up axis) + let alpha = Math.PI / 2; + if (!(offset.x === 0 && offset.z === 0)) { + alpha = Math.acos(offset.x / Math.sqrt(Math.pow(offset.x, 2) + Math.pow(offset.z, 2))); + } + if (offset.z < 0) { + alpha = 2 * Math.PI - alpha; + } + return alpha; +} +/** + * Computes the beta angle based on the source position and the target position. + * @param verticalOffset The y value of the directional offset between the source position and the target position + * @param radius The distance between the source position and the target position + * @returns The beta angle in radians + */ +function ComputeBeta(verticalOffset, radius) { + return Math.acos(verticalOffset / radius); +} +/** + * This represents an orbital type of camera. + * + * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events. + * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#arc-rotate-camera + */ +class ArcRotateCamera extends TargetCamera { + /** + * Defines the target point of the camera. + * The camera looks towards it from the radius distance. + */ + get target() { + return this._target; + } + set target(value) { + this.setTarget(value); + } + /** + * Defines the target transform node of the camera. + * The camera looks towards it from the radius distance. + * Please note that setting a target host will disable panning. + */ + get targetHost() { + return this._targetHost; + } + set targetHost(value) { + if (value) { + this.setTarget(value); + } + } + /** + * Return the current target position of the camera. This value is expressed in local space. + * @returns the target position + */ + getTarget() { + return this.target; + } + /** + * Define the current local position of the camera in the scene + */ + get position() { + return this._position; + } + set position(newPosition) { + this.setPosition(newPosition); + } + /** + * The vector the camera should consider as up. (default is Vector3(0, 1, 0) as returned by Vector3.Up()) + * Setting this will copy the given vector to the camera's upVector, and set rotation matrices to and from Y up. + * DO NOT set the up vector using copyFrom or copyFromFloats, as this bypasses setting the above matrices. + */ + set upVector(vec) { + if (!this._upToYMatrix) { + this._yToUpMatrix = new Matrix(); + this._upToYMatrix = new Matrix(); + this._upVector = Vector3.Zero(); + } + vec.normalize(); + this._upVector.copyFrom(vec); + this.setMatUp(); + } + get upVector() { + return this._upVector; + } + /** + * Sets the Y-up to camera up-vector rotation matrix, and the up-vector to Y-up rotation matrix. + */ + setMatUp() { + // from y-up to custom-up (used in _getViewMatrix) + Matrix.RotationAlignToRef(Vector3.UpReadOnly, this._upVector, this._yToUpMatrix); + // from custom-up to y-up (used in rebuildAnglesAndRadius) + Matrix.RotationAlignToRef(this._upVector, Vector3.UpReadOnly, this._upToYMatrix); + } + //-- begin properties for backward compatibility for inputs + /** + * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating. + */ + get angularSensibilityX() { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.angularSensibilityX; + } + return 0; + } + set angularSensibilityX(value) { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.angularSensibilityX = value; + } + } + /** + * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating. + */ + get angularSensibilityY() { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.angularSensibilityY; + } + return 0; + } + set angularSensibilityY(value) { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.angularSensibilityY = value; + } + } + /** + * Gets or Set the pointer pinch precision or how fast is the camera zooming. + */ + get pinchPrecision() { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.pinchPrecision; + } + return 0; + } + set pinchPrecision(value) { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.pinchPrecision = value; + } + } + /** + * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming. + * It will be used instead of pinchPrecision if different from 0. + * It defines the percentage of current camera.radius to use as delta when pinch zoom is used. + */ + get pinchDeltaPercentage() { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.pinchDeltaPercentage; + } + return 0; + } + set pinchDeltaPercentage(value) { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.pinchDeltaPercentage = value; + } + } + /** + * Gets or Set the pointer use natural pinch zoom to override the pinch precision + * and pinch delta percentage. + * When useNaturalPinchZoom is true, multi touch zoom will zoom in such + * that any object in the plane at the camera's target point will scale + * perfectly with finger motion. + */ + get useNaturalPinchZoom() { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.useNaturalPinchZoom; + } + return false; + } + set useNaturalPinchZoom(value) { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.useNaturalPinchZoom = value; + } + } + /** + * Gets or Set the pointer panning sensibility or how fast is the camera moving. + */ + get panningSensibility() { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.panningSensibility; + } + return 0; + } + set panningSensibility(value) { + const pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.panningSensibility = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control beta angle in a positive direction. + */ + get keysUp() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysUp; + } + return []; + } + set keysUp(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysUp = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control beta angle in a negative direction. + */ + get keysDown() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysDown; + } + return []; + } + set keysDown(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysDown = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction. + */ + get keysLeft() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysLeft; + } + return []; + } + set keysLeft(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysLeft = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction. + */ + get keysRight() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysRight; + } + return []; + } + set keysRight(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysRight = value; + } + } + /** + * Gets or Set the mouse wheel precision or how fast is the camera zooming. + */ + get wheelPrecision() { + const mousewheel = this.inputs.attached["mousewheel"]; + if (mousewheel) { + return mousewheel.wheelPrecision; + } + return 0; + } + set wheelPrecision(value) { + const mousewheel = this.inputs.attached["mousewheel"]; + if (mousewheel) { + mousewheel.wheelPrecision = value; + } + } + /** + * Gets or Set the boolean value that controls whether or not the mouse wheel + * zooms to the location of the mouse pointer or not. The default is false. + */ + get zoomToMouseLocation() { + const mousewheel = this.inputs.attached["mousewheel"]; + if (mousewheel) { + return mousewheel.zoomToMouseLocation; + } + return false; + } + set zoomToMouseLocation(value) { + const mousewheel = this.inputs.attached["mousewheel"]; + if (mousewheel) { + mousewheel.zoomToMouseLocation = value; + } + } + /** + * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming. + * It will be used instead of wheelPrecision if different from 0. + * It defines the percentage of current camera.radius to use as delta when wheel zoom is used. + */ + get wheelDeltaPercentage() { + const mousewheel = this.inputs.attached["mousewheel"]; + if (mousewheel) { + return mousewheel.wheelDeltaPercentage; + } + return 0; + } + set wheelDeltaPercentage(value) { + const mousewheel = this.inputs.attached["mousewheel"]; + if (mousewheel) { + mousewheel.wheelDeltaPercentage = value; + } + } + /** + * Gets the bouncing behavior of the camera if it has been enabled. + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior + */ + get bouncingBehavior() { + return this._bouncingBehavior; + } + /** + * Defines if the bouncing behavior of the camera is enabled on the camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior + */ + get useBouncingBehavior() { + return this._bouncingBehavior != null; + } + set useBouncingBehavior(value) { + if (value === this.useBouncingBehavior) { + return; + } + if (value) { + this._bouncingBehavior = new BouncingBehavior(); + this.addBehavior(this._bouncingBehavior); + } + else if (this._bouncingBehavior) { + this.removeBehavior(this._bouncingBehavior); + this._bouncingBehavior = null; + } + } + /** + * Gets the framing behavior of the camera if it has been enabled. + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior + */ + get framingBehavior() { + return this._framingBehavior; + } + /** + * Defines if the framing behavior of the camera is enabled on the camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior + */ + get useFramingBehavior() { + return this._framingBehavior != null; + } + set useFramingBehavior(value) { + if (value === this.useFramingBehavior) { + return; + } + if (value) { + this._framingBehavior = new FramingBehavior(); + this.addBehavior(this._framingBehavior); + } + else if (this._framingBehavior) { + this.removeBehavior(this._framingBehavior); + this._framingBehavior = null; + } + } + /** + * Gets the auto rotation behavior of the camera if it has been enabled. + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior + */ + get autoRotationBehavior() { + return this._autoRotationBehavior; + } + /** + * Defines if the auto rotation behavior of the camera is enabled on the camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior + */ + get useAutoRotationBehavior() { + return this._autoRotationBehavior != null; + } + set useAutoRotationBehavior(value) { + if (value === this.useAutoRotationBehavior) { + return; + } + if (value) { + this._autoRotationBehavior = new AutoRotationBehavior(); + this.addBehavior(this._autoRotationBehavior); + } + else if (this._autoRotationBehavior) { + this.removeBehavior(this._autoRotationBehavior); + this._autoRotationBehavior = null; + } + } + /** + * Instantiates a new ArcRotateCamera in a given scene + * @param name Defines the name of the camera + * @param alpha Defines the camera rotation along the longitudinal axis + * @param beta Defines the camera rotation along the latitudinal axis + * @param radius Defines the camera distance from its target + * @param target Defines the camera target + * @param scene Defines the scene the camera belongs to + * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined + */ + constructor(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive = true) { + super(name, Vector3.Zero(), scene, setActiveOnSceneIfNoneActive); + /** + * Current inertia value on the longitudinal axis. + * The bigger this number the longer it will take for the camera to stop. + */ + this.inertialAlphaOffset = 0; + /** + * Current inertia value on the latitudinal axis. + * The bigger this number the longer it will take for the camera to stop. + */ + this.inertialBetaOffset = 0; + /** + * Current inertia value on the radius axis. + * The bigger this number the longer it will take for the camera to stop. + */ + this.inertialRadiusOffset = 0; + /** + * Minimum allowed angle on the longitudinal axis. + * This can help limiting how the Camera is able to move in the scene. + */ + this.lowerAlphaLimit = null; + /** + * Maximum allowed angle on the longitudinal axis. + * This can help limiting how the Camera is able to move in the scene. + */ + this.upperAlphaLimit = null; + /** + * Minimum allowed angle on the latitudinal axis. + * This can help limiting how the Camera is able to move in the scene. + */ + this.lowerBetaLimit = 0.01; + /** + * Maximum allowed angle on the latitudinal axis. + * This can help limiting how the Camera is able to move in the scene. + */ + this.upperBetaLimit = Math.PI - 0.01; + /** + * Minimum allowed distance of the camera to the target (The camera can not get closer). + * This can help limiting how the Camera is able to move in the scene. + */ + this.lowerRadiusLimit = null; + /** + * Maximum allowed distance of the camera to the target (The camera can not get further). + * This can help limiting how the Camera is able to move in the scene. + */ + this.upperRadiusLimit = null; + /** + * Minimum allowed vertical target position of the camera. + * Use this setting in combination with `upperRadiusLimit` to set a global limit for the Cameras vertical position. + */ + this.lowerTargetYLimit = -Infinity; + /** + * Defines the current inertia value used during panning of the camera along the X axis. + */ + this.inertialPanningX = 0; + /** + * Defines the current inertia value used during panning of the camera along the Y axis. + */ + this.inertialPanningY = 0; + /** + * Defines the distance used to consider the camera in pan mode vs pinch/zoom. + * Basically if your fingers moves away from more than this distance you will be considered + * in pinch mode. + */ + this.pinchToPanMaxDistance = 20; + /** + * Defines the maximum distance the camera can pan. + * This could help keeping the camera always in your scene. + */ + this.panningDistanceLimit = null; + /** + * Defines the target of the camera before panning. + */ + this.panningOriginTarget = Vector3.Zero(); + /** + * Defines the value of the inertia used during panning. + * 0 would mean stop inertia and one would mean no deceleration at all. + */ + this.panningInertia = 0.9; + //-- end properties for backward compatibility for inputs + /** + * Defines how much the radius should be scaled while zooming on a particular mesh (through the zoomOn function) + */ + this.zoomOnFactor = 1; + /** + * Defines a screen offset for the camera position. + */ + this.targetScreenOffset = Vector2.Zero(); + /** + * Allows the camera to be completely reversed. + * If false the camera can not arrive upside down. + */ + this.allowUpsideDown = true; + /** + * Define if double tap/click is used to restore the previously saved state of the camera. + */ + this.useInputToRestoreState = true; + /** + * Factor for restoring information interpolation. default is 0 = off. Any value \< 0 or \> 1 will disable interpolation. + */ + this.restoreStateInterpolationFactor = 0; + this._currentInterpolationFactor = 0; + /** @internal */ + this._viewMatrix = new Matrix(); + /** + * Defines the allowed panning axis. + */ + this.panningAxis = new Vector3(1, 1, 0); + this._transformedDirection = new Vector3(); + /** + * Defines if camera will eliminate transform on y axis. + */ + this.mapPanning = false; + // restoring state progressively + this._progressiveRestore = false; + /** + * Observable triggered when the transform node target has been changed on the camera. + */ + this.onMeshTargetChangedObservable = new Observable(); + /** + * Defines whether the camera should check collision with the objects oh the scene. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#how-can-i-do-this- + */ + this.checkCollisions = false; + /** + * Defines the collision radius of the camera. + * This simulates a sphere around the camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera + */ + this.collisionRadius = new Vector3(0.5, 0.5, 0.5); + this._previousPosition = Vector3.Zero(); + this._collisionVelocity = Vector3.Zero(); + this._newPosition = Vector3.Zero(); + this._computationVector = Vector3.Zero(); + this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => { + if (!collidedMesh) { + this._previousPosition.copyFrom(this._position); + } + else { + this.setPosition(newPosition); + if (this.onCollide) { + this.onCollide(collidedMesh); + } + } + // Recompute because of constraints + const cosa = Math.cos(this.alpha); + const sina = Math.sin(this.alpha); + const cosb = Math.cos(this.beta); + let sinb = Math.sin(this.beta); + if (sinb === 0) { + sinb = 0.0001; + } + const target = this._getTargetPosition(); + this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb); + target.addToRef(this._computationVector, this._newPosition); + this._position.copyFrom(this._newPosition); + let up = this.upVector; + if (this.allowUpsideDown && this.beta < 0) { + up = up.clone(); + up = up.negate(); + } + this._computeViewMatrix(this._position, target, up); + this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x); + this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y); + this._collisionTriggered = false; + }; + this._target = Vector3.Zero(); + if (target) { + this.setTarget(target); + } + this.alpha = alpha; + this.beta = beta; + this.radius = radius; + this.getViewMatrix(); + this.inputs = new ArcRotateCameraInputsManager(this); + this.inputs.addKeyboard().addMouseWheel().addPointers(); + } + // Cache + /** @internal */ + _initCache() { + super._initCache(); + this._cache._target = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cache.alpha = undefined; + this._cache.beta = undefined; + this._cache.radius = undefined; + this._cache.targetScreenOffset = Vector2.Zero(); + } + /** + * @internal + */ + _updateCache(ignoreParentClass) { + if (!ignoreParentClass) { + super._updateCache(); + } + this._cache._target.copyFrom(this._getTargetPosition()); + this._cache.alpha = this.alpha; + this._cache.beta = this.beta; + this._cache.radius = this.radius; + this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset); + } + _getTargetPosition() { + if (this._targetHost && this._targetHost.getAbsolutePosition) { + const pos = this._targetHost.getAbsolutePosition(); + if (this._targetBoundingCenter) { + pos.addToRef(this._targetBoundingCenter, this._target); + } + else { + this._target.copyFrom(pos); + } + } + const lockedTargetPosition = this._getLockedTargetPosition(); + if (lockedTargetPosition) { + return lockedTargetPosition; + } + return this._target; + } + /** + * Stores the current state of the camera (alpha, beta, radius and target) + * @returns the camera itself + */ + storeState() { + this._storedAlpha = this._goalAlpha = this.alpha; + this._storedBeta = this._goalBeta = this.beta; + this._storedRadius = this._goalRadius = this.radius; + this._storedTarget = this._goalTarget = this._getTargetPosition().clone(); + this._storedTargetScreenOffset = this._goalTargetScreenOffset = this.targetScreenOffset.clone(); + return super.storeState(); + } + /** + * @internal + * Restored camera state. You must call storeState() first + */ + _restoreStateValues() { + if (this.hasStateStored() && this.restoreStateInterpolationFactor > Epsilon && this.restoreStateInterpolationFactor < 1) { + this.interpolateTo(this._storedAlpha, this._storedBeta, this._storedRadius, this._storedTarget, this._storedTargetScreenOffset, this.restoreStateInterpolationFactor); + return true; + } + if (!super._restoreStateValues()) { + return false; + } + this.setTarget(this._storedTarget.clone()); + this.alpha = this._storedAlpha; + this.beta = this._storedBeta; + this.radius = this._storedRadius; + this.targetScreenOffset = this._storedTargetScreenOffset.clone(); + this.inertialAlphaOffset = 0; + this.inertialBetaOffset = 0; + this.inertialRadiusOffset = 0; + this.inertialPanningX = 0; + this.inertialPanningY = 0; + return true; + } + /** + * Interpolates the camera to a goal state. + * @param alpha Defines the goal alpha. + * @param beta Defines the goal beta. + * @param radius Defines the goal radius. + * @param target Defines the goal target. + * @param targetScreenOffset Defines the goal target screen offset. + * @param interpolationFactor A value between 0 and 1 that determines the speed of the interpolation. + */ + interpolateTo(alpha = this.alpha, beta = this.beta, radius = this.radius, target = this.target, targetScreenOffset = this.targetScreenOffset, interpolationFactor) { + this._progressiveRestore = true; + this.inertialAlphaOffset = 0; + this.inertialBetaOffset = 0; + this.inertialRadiusOffset = 0; + this.inertialPanningX = 0; + this.inertialPanningY = 0; + if (interpolationFactor != null) { + this._currentInterpolationFactor = interpolationFactor; + } + else if (this.restoreStateInterpolationFactor !== 0) { + this._currentInterpolationFactor = this.restoreStateInterpolationFactor; + } + else { + this._currentInterpolationFactor = 0.1; + } + alpha = Clamp(alpha, this.lowerAlphaLimit ?? -Infinity, this.upperAlphaLimit ?? Infinity); + beta = Clamp(beta, this.lowerBetaLimit ?? -Infinity, this.upperBetaLimit ?? Infinity); + radius = Clamp(radius, this.lowerRadiusLimit ?? -Infinity, this.upperRadiusLimit ?? Infinity); + target.y = Clamp(target.y, this.lowerTargetYLimit ?? -Infinity, Infinity); + this._goalAlpha = alpha; + this._goalBeta = beta; + this._goalRadius = radius; + this._goalTarget = target; + this._goalTargetScreenOffset = targetScreenOffset; + } + // Synchronized + /** @internal */ + _isSynchronizedViewMatrix() { + if (!super._isSynchronizedViewMatrix()) { + return false; + } + return (this._cache._target.equals(this._getTargetPosition()) && + this._cache.alpha === this.alpha && + this._cache.beta === this.beta && + this._cache.radius === this.radius && + this._cache.targetScreenOffset.equals(this.targetScreenOffset)); + } + /** + * Attached controls to the current camera. + * @param ignored defines an ignored parameter kept for backward compatibility. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + * @param useCtrlForPanning Defines whether ctrl is used for panning within the controls + * @param panningMouseButton Defines whether panning is allowed through mouse click button + */ + attachControl(ignored, noPreventDefault, useCtrlForPanning = true, panningMouseButton = 2) { + // eslint-disable-next-line prefer-rest-params + const args = arguments; + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(args); + this._useCtrlForPanning = useCtrlForPanning; + this._panningMouseButton = panningMouseButton; + // backwards compatibility + if (typeof args[0] === "boolean") { + if (args.length > 1) { + this._useCtrlForPanning = args[1]; + } + if (args.length > 2) { + this._panningMouseButton = args[2]; + } + } + this.inputs.attachElement(noPreventDefault); + this._reset = () => { + this.inertialAlphaOffset = 0; + this.inertialBetaOffset = 0; + this.inertialRadiusOffset = 0; + this.inertialPanningX = 0; + this.inertialPanningY = 0; + }; + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + this.inputs.detachElement(); + if (this._reset) { + this._reset(); + } + } + /** @internal */ + _checkInputs() { + //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called. + if (this._collisionTriggered) { + return; + } + this.inputs.checkInputs(); + // progressive restore + if (this._progressiveRestore) { + const dt = this._scene.getEngine().getDeltaTime() / 1000; + const t = 1 - Math.pow(2, -dt / this._currentInterpolationFactor); + // can't use tmp vector here because of assignment + this.setTarget(Vector3.Lerp(this.getTarget(), this._goalTarget, t)); + // Using quaternion for smoother interpolation (and no Euler angles modulo) + Quaternion.RotationAlphaBetaGammaToRef(this._goalAlpha, this._goalBeta, 0, TmpVectors.Quaternion[0]); + Quaternion.RotationAlphaBetaGammaToRef(this.alpha, this.beta, 0, TmpVectors.Quaternion[1]); + Quaternion.SlerpToRef(TmpVectors.Quaternion[1], TmpVectors.Quaternion[0], t, TmpVectors.Quaternion[2]); + TmpVectors.Quaternion[2].normalize(); + TmpVectors.Quaternion[2].toAlphaBetaGammaToRef(TmpVectors.Vector3[0]); + this.alpha = TmpVectors.Vector3[0].x; + this.beta = TmpVectors.Vector3[0].y; + this.radius += (this._goalRadius - this.radius) * t; + Vector2.LerpToRef(this.targetScreenOffset, this._goalTargetScreenOffset, t, this.targetScreenOffset); + // stop restoring when within close range or when user starts interacting + if ((Vector3.DistanceSquared(this.getTarget(), this._goalTarget) < Epsilon && + TmpVectors.Quaternion[2].isApprox(TmpVectors.Quaternion[0]) && + Math.pow(this._goalRadius - this.radius, 2) < Epsilon && + Vector2.Distance(this.targetScreenOffset, this._goalTargetScreenOffset) < Epsilon) || + this.inertialAlphaOffset !== 0 || + this.inertialBetaOffset !== 0 || + this.inertialRadiusOffset !== 0 || + this.inertialPanningX !== 0 || + this.inertialPanningY !== 0) { + this._progressiveRestore = false; + } + } + // Inertia + if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) { + const directionModifier = this.invertRotation ? -1 : 1; + const handednessMultiplier = this._calculateHandednessMultiplier(); + let inertialAlphaOffset = this.inertialAlphaOffset * handednessMultiplier; + if (this.beta < 0) { + inertialAlphaOffset *= -1; + } + this.alpha += inertialAlphaOffset * directionModifier; + this.beta += this.inertialBetaOffset * directionModifier; + this.radius -= this.inertialRadiusOffset; + this.inertialAlphaOffset *= this.inertia; + this.inertialBetaOffset *= this.inertia; + this.inertialRadiusOffset *= this.inertia; + if (Math.abs(this.inertialAlphaOffset) < Epsilon) { + this.inertialAlphaOffset = 0; + } + if (Math.abs(this.inertialBetaOffset) < Epsilon) { + this.inertialBetaOffset = 0; + } + if (Math.abs(this.inertialRadiusOffset) < this.speed * Epsilon) { + this.inertialRadiusOffset = 0; + } + } + // Panning inertia + if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) { + const localDirection = new Vector3(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY); + this._viewMatrix.invertToRef(this._cameraTransformMatrix); + localDirection.multiplyInPlace(this.panningAxis); + Vector3.TransformNormalToRef(localDirection, this._cameraTransformMatrix, this._transformedDirection); + // If mapPanning is enabled, we need to take the upVector into account and + // make sure we're not panning in the y direction + if (this.mapPanning) { + const up = this.upVector; + const right = Vector3.CrossToRef(this._transformedDirection, up, this._transformedDirection); + Vector3.CrossToRef(up, right, this._transformedDirection); + } + else if (!this.panningAxis.y) { + this._transformedDirection.y = 0; + } + if (!this._targetHost) { + if (this.panningDistanceLimit) { + this._transformedDirection.addInPlace(this._target); + const distanceSquared = Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget); + if (distanceSquared <= this.panningDistanceLimit * this.panningDistanceLimit) { + this._target.copyFrom(this._transformedDirection); + } + } + else { + if (this.parent) { + const m = TmpVectors.Matrix[0]; + this.parent.getWorldMatrix().getRotationMatrixToRef(m); + m.transposeToRef(m); + Vector3.TransformCoordinatesToRef(this._transformedDirection, m, this._transformedDirection); + } + this._target.addInPlace(this._transformedDirection); + } + } + this.inertialPanningX *= this.panningInertia; + this.inertialPanningY *= this.panningInertia; + if (Math.abs(this.inertialPanningX) < this.speed * Epsilon) { + this.inertialPanningX = 0; + } + if (Math.abs(this.inertialPanningY) < this.speed * Epsilon) { + this.inertialPanningY = 0; + } + } + // Limits + this._checkLimits(); + super._checkInputs(); + } + _checkLimits() { + if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) { + if (this.allowUpsideDown && this.beta > Math.PI) { + this.beta = this.beta - 2 * Math.PI; + } + } + else { + if (this.beta < this.lowerBetaLimit) { + this.beta = this.lowerBetaLimit; + } + } + if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) { + if (this.allowUpsideDown && this.beta < -Math.PI) { + this.beta = this.beta + 2 * Math.PI; + } + } + else { + if (this.beta > this.upperBetaLimit) { + this.beta = this.upperBetaLimit; + } + } + if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) { + this.alpha = this.lowerAlphaLimit; + } + if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) { + this.alpha = this.upperAlphaLimit; + } + if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) { + this.radius = this.lowerRadiusLimit; + this.inertialRadiusOffset = 0; + } + if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) { + this.radius = this.upperRadiusLimit; + this.inertialRadiusOffset = 0; + } + this.target.y = Math.max(this.target.y, this.lowerTargetYLimit); + } + /** + * Rebuilds angles (alpha, beta) and radius from the give position and target + */ + rebuildAnglesAndRadius() { + this._position.subtractToRef(this._getTargetPosition(), this._computationVector); + // need to rotate to Y up equivalent if up vector not Axis.Y + if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) { + Vector3.TransformCoordinatesToRef(this._computationVector, this._upToYMatrix, this._computationVector); + } + this.radius = this._computationVector.length(); + if (this.radius === 0) { + this.radius = 0.0001; // Just to avoid division by zero + } + // Alpha and Beta + const previousAlpha = this.alpha; + this.alpha = ComputeAlpha(this._computationVector); + this.beta = ComputeBeta(this._computationVector.y, this.radius); + // Calculate the number of revolutions between the new and old alpha values. + const alphaCorrectionTurns = Math.round((previousAlpha - this.alpha) / (2.0 * Math.PI)); + // Adjust alpha so that its numerical representation is the closest one to the old value. + this.alpha += alphaCorrectionTurns * 2.0 * Math.PI; + this._checkLimits(); + } + /** + * Use a position to define the current camera related information like alpha, beta and radius + * @param position Defines the position to set the camera at + */ + setPosition(position) { + if (this._position.equals(position)) { + return; + } + this._position.copyFrom(position); + this.rebuildAnglesAndRadius(); + } + /** + * Defines the target the camera should look at. + * This will automatically adapt alpha beta and radius to fit within the new target. + * Please note that setting a target as a mesh will disable panning. + * @param target Defines the new target as a Vector or a transform node + * @param toBoundingCenter In case of a mesh target, defines whether to target the mesh position or its bounding information center + * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim) + * @param cloneAlphaBetaRadius If true, replicate the current setup (alpha, beta, radius) on the new target + */ + setTarget(target, toBoundingCenter = false, allowSamePosition = false, cloneAlphaBetaRadius = false) { + cloneAlphaBetaRadius = this.overrideCloneAlphaBetaRadius ?? cloneAlphaBetaRadius; + if (target.computeWorldMatrix) { + if (toBoundingCenter && target.getBoundingInfo) { + this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone(); + } + else { + this._targetBoundingCenter = null; + } + target.computeWorldMatrix(); + this._targetHost = target; + this._target = this._getTargetPosition(); + this.onMeshTargetChangedObservable.notifyObservers(this._targetHost); + } + else { + const newTarget = target; + const currentTarget = this._getTargetPosition(); + if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) { + return; + } + this._targetHost = null; + this._target = newTarget; + this._targetBoundingCenter = null; + this.onMeshTargetChangedObservable.notifyObservers(null); + } + if (!cloneAlphaBetaRadius) { + this.rebuildAnglesAndRadius(); + } + } + /** @internal */ + _getViewMatrix() { + // Compute + const cosa = Math.cos(this.alpha); + const sina = Math.sin(this.alpha); + const cosb = Math.cos(this.beta); + let sinb = Math.sin(this.beta); + if (sinb === 0) { + sinb = 0.0001; + } + if (this.radius === 0) { + this.radius = 0.0001; // Just to avoid division by zero + } + const target = this._getTargetPosition(); + this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb); + // Rotate according to up vector + if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) { + Vector3.TransformCoordinatesToRef(this._computationVector, this._yToUpMatrix, this._computationVector); + } + target.addToRef(this._computationVector, this._newPosition); + if (this.getScene().collisionsEnabled && this.checkCollisions) { + const coordinator = this.getScene().collisionCoordinator; + if (!this._collider) { + this._collider = coordinator.createCollider(); + } + this._collider._radius = this.collisionRadius; + this._newPosition.subtractToRef(this._position, this._collisionVelocity); + this._collisionTriggered = true; + coordinator.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); + } + else { + this._position.copyFrom(this._newPosition); + let up = this.upVector; + if (this.allowUpsideDown && sinb < 0) { + up = up.negate(); + } + this._computeViewMatrix(this._position, target, up); + this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x); + this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y); + } + this._currentTarget = target; + return this._viewMatrix; + } + /** + * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport. + * @param meshes Defines the mesh to zoom on + * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance) + */ + zoomOn(meshes, doNotUpdateMaxZ = false) { + meshes = meshes || this.getScene().meshes; + const minMaxVector = Mesh.MinMax(meshes); + let distance = this._calculateLowerRadiusFromModelBoundingSphere(minMaxVector.min, minMaxVector.max); + // If there are defined limits, we need to take them into account + distance = Math.max(Math.min(distance, this.upperRadiusLimit || Number.MAX_VALUE), this.lowerRadiusLimit || 0); + this.radius = distance * this.zoomOnFactor; + this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ); + } + /** + * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius. + * The target will be changed but the radius + * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on + * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance) + */ + focusOn(meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ = false) { + let meshesOrMinMaxVector; + let distance; + if (meshesOrMinMaxVectorAndDistance.min === undefined) { + // meshes + const meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes; + meshesOrMinMaxVector = Mesh.MinMax(meshes); + distance = Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max); + } + else { + //minMaxVector and distance + const minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance; + meshesOrMinMaxVector = minMaxVectorAndDistance; + distance = minMaxVectorAndDistance.distance; + } + this._target = Mesh.Center(meshesOrMinMaxVector); + if (!doNotUpdateMaxZ) { + this.maxZ = distance * 2; + } + } + /** + * @override + * Override Camera.createRigCamera + * @param name the name of the camera + * @param cameraIndex the index of the camera in the rig cameras array + */ + createRigCamera(name, cameraIndex) { + let alphaShift = 0; + switch (this.cameraRigMode) { + case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH: + case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: + case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER: + case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED: + case Camera.RIG_MODE_VR: + alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1); + break; + case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: + alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1); + break; + } + const rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene()); + rigCam._cameraRigParams = {}; + rigCam.isRigCamera = true; + rigCam.rigParent = this; + rigCam.upVector = this.upVector; + rigCam.mode = this.mode; + rigCam.orthoLeft = this.orthoLeft; + rigCam.orthoRight = this.orthoRight; + rigCam.orthoBottom = this.orthoBottom; + rigCam.orthoTop = this.orthoTop; + return rigCam; + } + /** + * @internal + * @override + * Override Camera._updateRigCameras + */ + _updateRigCameras() { + const camLeft = this._rigCameras[0]; + const camRight = this._rigCameras[1]; + camLeft.beta = camRight.beta = this.beta; + switch (this.cameraRigMode) { + case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH: + case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: + case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER: + case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED: + case Camera.RIG_MODE_VR: + camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle; + camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle; + break; + case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: + camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle; + camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle; + break; + } + super._updateRigCameras(); + } + /** + * @internal + */ + _calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld, radiusScale = 1) { + const boxVectorGlobalDiagonal = Vector3.Distance(minimumWorld, maximumWorld); + // Get aspect ratio in order to calculate frustum slope + const engine = this.getScene().getEngine(); + const aspectRatio = engine.getAspectRatio(this); + const frustumSlopeY = Math.tan(this.fov / 2); + const frustumSlopeX = frustumSlopeY * aspectRatio; + // Formula for setting distance + // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene) + const radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5; + // Horizon distance + const radius = radiusWithoutFraming * radiusScale; + const distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlopeX * frustumSlopeX)); + const distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlopeY * frustumSlopeY)); + return Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum); + } + /** + * Destroy the camera and release the current resources hold by it. + */ + dispose() { + this.inputs.clear(); + super.dispose(); + } + /** + * Gets the current object class name. + * @returns the class name + */ + getClassName() { + return "ArcRotateCamera"; + } +} +__decorate([ + serialize() +], ArcRotateCamera.prototype, "alpha", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "beta", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "radius", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "overrideCloneAlphaBetaRadius", void 0); +__decorate([ + serializeAsVector3("target") +], ArcRotateCamera.prototype, "_target", void 0); +__decorate([ + serializeAsMeshReference("targetHost") +], ArcRotateCamera.prototype, "_targetHost", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "inertialBetaOffset", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "upperAlphaLimit", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "lowerBetaLimit", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "upperBetaLimit", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "upperRadiusLimit", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "lowerTargetYLimit", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "inertialPanningX", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "inertialPanningY", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "panningDistanceLimit", void 0); +__decorate([ + serializeAsVector3() +], ArcRotateCamera.prototype, "panningOriginTarget", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "panningInertia", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "zoomToMouseLocation", null); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "zoomOnFactor", void 0); +__decorate([ + serializeAsVector2() +], ArcRotateCamera.prototype, "targetScreenOffset", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "allowUpsideDown", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "useInputToRestoreState", void 0); +__decorate([ + serialize() +], ArcRotateCamera.prototype, "restoreStateInterpolationFactor", void 0); +// Register Class Name +RegisterClass("BABYLON.ArcRotateCamera", ArcRotateCamera); + +class AppCamera extends Monobehiver { + object; + constructor(mainApp) { + super(mainApp); + this.object = null; + } + /** 初始化相机 */ + Awake() { + const scene = this.mainApp.appScene.object; + const canvas = AppConfig.container; + if (!scene || !canvas) return; + this.object = new ArcRotateCamera("Camera", Tools.ToRadians(70), Tools.ToRadians(85), 5, new Vector3(0, 2, 0), scene); + this.object.attachControl(canvas, true); + this.object.minZ = 0.01; + this.object.panningSensibility = 0; + this.object.position = new Vector3(-0, 100, 0); + this.setTarget(0, 2, 0); + } + /** 设置相机目标点 */ + setTarget(x, y, z) { + if (this.object) { + this.object.target = new Vector3(x, y, z); + } + } + /** 重置相机到默认位置 */ + reset() { + if (!this.object) return; + this.object.radius = 5; + this.object.alpha = Tools.ToRadians(60); + this.object.beta = Tools.ToRadians(60); + this.setTarget(0, 2, 0); + this.object.position = new Vector3(-0, 100, 0); + } + update() { + } +} + +/** + * Base class of all the lights in Babylon. It groups all the generic information about lights. + * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour. + * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased. + */ +class Light extends Node$2 { + /** + * Defines how far from the source the light is impacting in scene units. + * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff. + */ + get range() { + return this._range; + } + /** + * Defines how far from the source the light is impacting in scene units. + * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff. + */ + set range(value) { + this._range = value; + this._inverseSquaredRange = 1.0 / (this.range * this.range); + } + /** + * Gets the photometric scale used to interpret the intensity. + * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. + */ + get intensityMode() { + return this._intensityMode; + } + /** + * Sets the photometric scale used to interpret the intensity. + * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. + */ + set intensityMode(value) { + this._intensityMode = value; + this._computePhotometricScale(); + } + /** + * Gets the light radius used by PBR Materials to simulate soft area lights. + */ + get radius() { + return this._radius; + } + /** + * sets the light radius used by PBR Materials to simulate soft area lights. + */ + set radius(value) { + this._radius = value; + this._computePhotometricScale(); + } + /** + * Gets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching + * the current shadow generator. + */ + get shadowEnabled() { + return this._shadowEnabled; + } + /** + * Sets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching + * the current shadow generator. + */ + set shadowEnabled(value) { + if (this._shadowEnabled === value) { + return; + } + this._shadowEnabled = value; + this._markMeshesAsLightDirty(); + } + /** + * Gets the only meshes impacted by this light. + */ + get includedOnlyMeshes() { + return this._includedOnlyMeshes; + } + /** + * Sets the only meshes impacted by this light. + */ + set includedOnlyMeshes(value) { + this._includedOnlyMeshes = value; + this._hookArrayForIncludedOnly(value); + } + /** + * Gets the meshes not impacted by this light. + */ + get excludedMeshes() { + return this._excludedMeshes; + } + /** + * Sets the meshes not impacted by this light. + */ + set excludedMeshes(value) { + this._excludedMeshes = value; + this._hookArrayForExcluded(value); + } + /** + * Gets the layer id use to find what meshes are not impacted by the light. + * Inactive if 0 + */ + get excludeWithLayerMask() { + return this._excludeWithLayerMask; + } + /** + * Sets the layer id use to find what meshes are not impacted by the light. + * Inactive if 0 + */ + set excludeWithLayerMask(value) { + this._excludeWithLayerMask = value; + this._resyncMeshes(); + } + /** + * Gets the layer id use to find what meshes are impacted by the light. + * Inactive if 0 + */ + get includeOnlyWithLayerMask() { + return this._includeOnlyWithLayerMask; + } + /** + * Sets the layer id use to find what meshes are impacted by the light. + * Inactive if 0 + */ + set includeOnlyWithLayerMask(value) { + this._includeOnlyWithLayerMask = value; + this._resyncMeshes(); + } + /** + * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) + */ + get lightmapMode() { + return this._lightmapMode; + } + /** + * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) + */ + set lightmapMode(value) { + if (this._lightmapMode === value) { + return; + } + this._lightmapMode = value; + this._markMeshesAsLightDirty(); + } + /** + * Returns the view matrix. + * @param _faceIndex The index of the face for which we want to extract the view matrix. Only used for point light types. + * @returns The view matrix. Can be null, if a view matrix cannot be defined for the type of light considered (as for a hemispherical light, for example). + */ + getViewMatrix(_faceIndex) { + return null; + } + /** + * Returns the projection matrix. + * Note that viewMatrix and renderList are optional and are only used by lights that calculate the projection matrix from a list of meshes (e.g. directional lights with automatic extents calculation). + * @param _viewMatrix The view transform matrix of the light (optional). + * @param _renderList The list of meshes to take into account when calculating the projection matrix (optional). + * @returns The projection matrix. Can be null, if a projection matrix cannot be defined for the type of light considered (as for a hemispherical light, for example). + */ + getProjectionMatrix(_viewMatrix, _renderList) { + return null; + } + /** + * Creates a Light object in the scene. + * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + * @param name The friendly name of the light + * @param scene The scene the light belongs too + */ + constructor(name, scene) { + super(name, scene, false); + /** + * Diffuse gives the basic color to an object. + */ + this.diffuse = new Color3(1.0, 1.0, 1.0); + /** + * Specular produces a highlight color on an object. + * Note: This is not affecting PBR materials. + */ + this.specular = new Color3(1.0, 1.0, 1.0); + /** + * Defines the falloff type for this light. This lets overriding how punctual light are + * falling off base on range or angle. + * This can be set to any values in Light.FALLOFF_x. + * + * Note: This is only useful for PBR Materials at the moment. This could be extended if required to + * other types of materials. + */ + this.falloffType = Light.FALLOFF_DEFAULT; + /** + * Strength of the light. + * Note: By default it is define in the framework own unit. + * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in. + */ + this.intensity = 1.0; + this._range = Number.MAX_VALUE; + this._inverseSquaredRange = 0; + /** + * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type + * of light. + */ + this._photometricScale = 1.0; + this._intensityMode = Light.INTENSITYMODE_AUTOMATIC; + this._radius = 0.00001; + /** + * Defines the rendering priority of the lights. It can help in case of fallback or number of lights + * exceeding the number allowed of the materials. + */ + this.renderPriority = 0; + this._shadowEnabled = true; + this._excludeWithLayerMask = 0; + this._includeOnlyWithLayerMask = 0; + this._lightmapMode = 0; + /** + * Shadow generators associated to the light. + * @internal Internal use only. + */ + this._shadowGenerators = null; + /** + * @internal Internal use only. + */ + this._excludedMeshesIds = new Array(); + /** + * @internal Internal use only. + */ + this._includedOnlyMeshesIds = new Array(); + /** @internal */ + this._isLight = true; + this.getScene().addLight(this); + this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name); + this._buildUniformLayout(); + this.includedOnlyMeshes = []; + this.excludedMeshes = []; + this._resyncMeshes(); + } + /** + * Sets the passed Effect "effect" with the Light textures. + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The light + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + transferTexturesToEffect(effect, lightIndex) { + // Do nothing by default. + return this; + } + /** + * Binds the lights information from the scene to the effect for the given mesh. + * @param lightIndex Light index + * @param scene The scene where the light belongs to + * @param effect The effect we are binding the data to + * @param useSpecular Defines if specular is supported + * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows + */ + _bindLight(lightIndex, scene, effect, useSpecular, receiveShadows = true) { + const iAsString = lightIndex.toString(); + let needUpdate = false; + this._uniformBuffer.bindToEffect(effect, "Light" + iAsString); + if (this._renderId !== scene.getRenderId() || this._lastUseSpecular !== useSpecular || !this._uniformBuffer.useUbo) { + this._renderId = scene.getRenderId(); + this._lastUseSpecular = useSpecular; + const scaledIntensity = this.getScaledIntensity(); + this.transferToEffect(effect, iAsString); + this.diffuse.scaleToRef(scaledIntensity, TmpColors.Color3[0]); + this._uniformBuffer.updateColor4("vLightDiffuse", TmpColors.Color3[0], this.range, iAsString); + if (useSpecular) { + this.specular.scaleToRef(scaledIntensity, TmpColors.Color3[1]); + this._uniformBuffer.updateColor4("vLightSpecular", TmpColors.Color3[1], this.radius, iAsString); + } + needUpdate = true; + } + // Textures might still need to be rebound. + this.transferTexturesToEffect(effect, iAsString); + // Shadows + if (scene.shadowsEnabled && this.shadowEnabled && receiveShadows) { + const shadowGenerator = this.getShadowGenerator(scene.activeCamera) ?? this.getShadowGenerator(); + if (shadowGenerator) { + shadowGenerator.bindShadowLight(iAsString, effect); + needUpdate = true; + } + } + if (needUpdate) { + this._uniformBuffer.update(); + } + else { + this._uniformBuffer.bindUniformBuffer(); + } + } + /** + * Returns the string "Light". + * @returns the class name + */ + getClassName() { + return "Light"; + } + /** + * Converts the light information to a readable string for debug purpose. + * @param fullDetails Supports for multiple levels of logging within scene loading + * @returns the human readable light info + */ + toString(fullDetails) { + let ret = "Name: " + this.name; + ret += ", type: " + ["Point", "Directional", "Spot", "Hemispheric"][this.getTypeID()]; + if (this.animations) { + for (let i = 0; i < this.animations.length; i++) { + ret += ", animation[0]: " + this.animations[i].toString(fullDetails); + } + } + return ret; + } + /** @internal */ + _syncParentEnabledState() { + super._syncParentEnabledState(); + if (!this.isDisposed()) { + this._resyncMeshes(); + } + } + /** + * Set the enabled state of this node. + * @param value - the new enabled state + */ + setEnabled(value) { + super.setEnabled(value); + this._resyncMeshes(); + } + /** + * Returns the Light associated shadow generator if any. + * @param camera Camera for which the shadow generator should be retrieved (default: null). If null, retrieves the default shadow generator + * @returns the associated shadow generator. + */ + getShadowGenerator(camera = null) { + if (this._shadowGenerators === null) { + return null; + } + return this._shadowGenerators.get(camera) ?? null; + } + /** + * Returns all the shadow generators associated to this light + * @returns + */ + getShadowGenerators() { + return this._shadowGenerators; + } + /** + * Returns a Vector3, the absolute light position in the World. + * @returns the world space position of the light + */ + getAbsolutePosition() { + return Vector3.Zero(); + } + /** + * Specifies if the light will affect the passed mesh. + * @param mesh The mesh to test against the light + * @returns true the mesh is affected otherwise, false. + */ + canAffectMesh(mesh) { + if (!mesh) { + return true; + } + if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) { + return false; + } + if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) { + return false; + } + if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) { + return false; + } + if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) { + return false; + } + return true; + } + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse, disposeMaterialAndTextures = false) { + if (this._shadowGenerators) { + const iterator = this._shadowGenerators.values(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const shadowGenerator = key.value; + shadowGenerator.dispose(); + } + this._shadowGenerators = null; + } + // Animations + this.getScene().stopAnimation(this); + if (this._parentContainer) { + const index = this._parentContainer.lights.indexOf(this); + if (index > -1) { + this._parentContainer.lights.splice(index, 1); + } + this._parentContainer = null; + } + // Remove from meshes + for (const mesh of this.getScene().meshes) { + mesh._removeLightSource(this, true); + } + this._uniformBuffer.dispose(); + // Remove from scene + this.getScene().removeLight(this); + super.dispose(doNotRecurse, disposeMaterialAndTextures); + } + /** + * Returns the light type ID (integer). + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + getTypeID() { + return 0; + } + /** + * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode. + * @returns the scaled intensity in intensity mode unit + */ + getScaledIntensity() { + return this._photometricScale * this.intensity; + } + /** + * Returns a new Light object, named "name", from the current one. + * @param name The name of the cloned light + * @param newParent The parent of this light, if it has one + * @returns the new created light + */ + clone(name, newParent = null) { + const constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()); + if (!constructor) { + return null; + } + const clonedLight = SerializationHelper.Clone(constructor, this); + if (name) { + clonedLight.name = name; + } + if (newParent) { + clonedLight.parent = newParent; + } + clonedLight.setEnabled(this.isEnabled()); + this.onClonedObservable.notifyObservers(clonedLight); + return clonedLight; + } + /** + * Serializes the current light into a Serialization object. + * @returns the serialized object. + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.uniqueId = this.uniqueId; + // Type + serializationObject.type = this.getTypeID(); + // Parent + if (this.parent) { + this.parent._serializeAsParent(serializationObject); + } + // Inclusion / exclusions + if (this.excludedMeshes.length > 0) { + serializationObject.excludedMeshesIds = []; + this.excludedMeshes.forEach((mesh) => { + serializationObject.excludedMeshesIds.push(mesh.id); + }); + } + if (this.includedOnlyMeshes.length > 0) { + serializationObject.includedOnlyMeshesIds = []; + this.includedOnlyMeshes.forEach((mesh) => { + serializationObject.includedOnlyMeshesIds.push(mesh.id); + }); + } + // Animations + SerializationHelper.AppendSerializedAnimations(this, serializationObject); + serializationObject.ranges = this.serializeAnimationRanges(); + serializationObject.isEnabled = this.isEnabled(); + return serializationObject; + } + /** + * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3. + * This new light is named "name" and added to the passed scene. + * @param type Type according to the types available in Light.LIGHTTYPEID_x + * @param name The friendly name of the light + * @param scene The scene the new light will belong to + * @returns the constructor function + */ + static GetConstructorFromName(type, name, scene) { + const constructorFunc = Node$2.Construct("Light_Type_" + type, name, scene); + if (constructorFunc) { + return constructorFunc; + } + // Default to no light for none present once. + return null; + } + /** + * Parses the passed "parsedLight" and returns a new instanced Light from this parsing. + * @param parsedLight The JSON representation of the light + * @param scene The scene to create the parsed light in + * @returns the created light after parsing + */ + static Parse(parsedLight, scene) { + const constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene); + if (!constructor) { + return null; + } + const light = SerializationHelper.Parse(constructor, parsedLight, scene); + // Inclusion / exclusions + if (parsedLight.excludedMeshesIds) { + light._excludedMeshesIds = parsedLight.excludedMeshesIds; + } + if (parsedLight.includedOnlyMeshesIds) { + light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds; + } + // Parent + if (parsedLight.parentId !== undefined) { + light._waitingParentId = parsedLight.parentId; + } + if (parsedLight.parentInstanceIndex !== undefined) { + light._waitingParentInstanceIndex = parsedLight.parentInstanceIndex; + } + // Falloff + if (parsedLight.falloffType !== undefined) { + light.falloffType = parsedLight.falloffType; + } + // Lightmaps + if (parsedLight.lightmapMode !== undefined) { + light.lightmapMode = parsedLight.lightmapMode; + } + // Animations + if (parsedLight.animations) { + for (let animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) { + const parsedAnimation = parsedLight.animations[animationIndex]; + const internalClass = GetClass("BABYLON.Animation"); + if (internalClass) { + light.animations.push(internalClass.Parse(parsedAnimation)); + } + } + Node$2.ParseAnimationRanges(light, parsedLight, scene); + } + if (parsedLight.autoAnimate) { + scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0); + } + // Check if isEnabled is defined to be back compatible with prior serialized versions. + if (parsedLight.isEnabled !== undefined) { + light.setEnabled(parsedLight.isEnabled); + } + return light; + } + _hookArrayForExcluded(array) { + const oldPush = array.push; + array.push = (...items) => { + const result = oldPush.apply(array, items); + for (const item of items) { + item._resyncLightSource(this); + } + return result; + }; + const oldSplice = array.splice; + array.splice = (index, deleteCount) => { + const deleted = oldSplice.apply(array, [index, deleteCount]); + for (const item of deleted) { + item._resyncLightSource(this); + } + return deleted; + }; + for (const item of array) { + item._resyncLightSource(this); + } + } + _hookArrayForIncludedOnly(array) { + const oldPush = array.push; + array.push = (...items) => { + const result = oldPush.apply(array, items); + this._resyncMeshes(); + return result; + }; + const oldSplice = array.splice; + array.splice = (index, deleteCount) => { + const deleted = oldSplice.apply(array, [index, deleteCount]); + this._resyncMeshes(); + return deleted; + }; + this._resyncMeshes(); + } + _resyncMeshes() { + for (const mesh of this.getScene().meshes) { + mesh._resyncLightSource(this); + } + } + /** + * Forces the meshes to update their light related information in their rendering used effects + * @internal Internal Use Only + */ + _markMeshesAsLightDirty() { + for (const mesh of this.getScene().meshes) { + if (mesh.lightSources.indexOf(this) !== -1) { + mesh._markSubMeshesAsLightDirty(); + } + } + } + /** + * Recomputes the cached photometric scale if needed. + */ + _computePhotometricScale() { + this._photometricScale = this._getPhotometricScale(); + this.getScene().resetCachedMaterial(); + } + /** + * @returns the Photometric Scale according to the light type and intensity mode. + */ + _getPhotometricScale() { + let photometricScale = 0.0; + const lightTypeID = this.getTypeID(); + //get photometric mode + let photometricMode = this.intensityMode; + if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) { + if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) { + photometricMode = Light.INTENSITYMODE_ILLUMINANCE; + } + else { + photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY; + } + } + //compute photometric scale + switch (lightTypeID) { + case Light.LIGHTTYPEID_POINTLIGHT: + case Light.LIGHTTYPEID_SPOTLIGHT: + switch (photometricMode) { + case Light.INTENSITYMODE_LUMINOUSPOWER: + photometricScale = 1.0 / (4.0 * Math.PI); + break; + case Light.INTENSITYMODE_LUMINOUSINTENSITY: + photometricScale = 1.0; + break; + case Light.INTENSITYMODE_LUMINANCE: + photometricScale = this.radius * this.radius; + break; + } + break; + case Light.LIGHTTYPEID_DIRECTIONALLIGHT: + switch (photometricMode) { + case Light.INTENSITYMODE_ILLUMINANCE: + photometricScale = 1.0; + break; + case Light.INTENSITYMODE_LUMINANCE: { + // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance. + // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres). + let apexAngleRadians = this.radius; + // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function). + apexAngleRadians = Math.max(apexAngleRadians, 0.001); + const solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians)); + photometricScale = solidAngle; + break; + } + } + break; + case Light.LIGHTTYPEID_HEMISPHERICLIGHT: + // No fall off in hemispheric light. + photometricScale = 1.0; + break; + } + return photometricScale; + } + /** + * Reorder the light in the scene according to their defined priority. + * @internal Internal Use Only + */ + _reorderLightsInScene() { + const scene = this.getScene(); + if (this._renderPriority != 0) { + scene.requireLightSorting = true; + } + this.getScene().sortLightsByPriority(); + } + /** + * @internal + */ + _isReady() { + return true; + } +} +/** + * Falloff Default: light is falling off following the material specification: + * standard material is using standard falloff whereas pbr material can request special falloff per materials. + */ +Light.FALLOFF_DEFAULT = LightConstants.FALLOFF_DEFAULT; +/** + * Falloff Physical: light is falling off following the inverse squared distance law. + */ +Light.FALLOFF_PHYSICAL = LightConstants.FALLOFF_PHYSICAL; +/** + * Falloff gltf: light is falling off as described in the gltf moving to PBR document + * to enhance interoperability with other engines. + */ +Light.FALLOFF_GLTF = LightConstants.FALLOFF_GLTF; +/** + * Falloff Standard: light is falling off like in the standard material + * to enhance interoperability with other materials. + */ +Light.FALLOFF_STANDARD = LightConstants.FALLOFF_STANDARD; +//lightmapMode Consts +/** + * If every light affecting the material is in this lightmapMode, + * material.lightmapTexture adds or multiplies + * (depends on material.useLightmapAsShadowmap) + * after every other light calculations. + */ +Light.LIGHTMAP_DEFAULT = LightConstants.LIGHTMAP_DEFAULT; +/** + * material.lightmapTexture as only diffuse lighting from this light + * adds only specular lighting from this light + * adds dynamic shadows + */ +Light.LIGHTMAP_SPECULAR = LightConstants.LIGHTMAP_SPECULAR; +/** + * material.lightmapTexture as only lighting + * no light calculation from this light + * only adds dynamic shadows from this light + */ +Light.LIGHTMAP_SHADOWSONLY = LightConstants.LIGHTMAP_SHADOWSONLY; +// Intensity Mode Consts +/** + * Each light type uses the default quantity according to its type: + * point/spot lights use luminous intensity + * directional lights use illuminance + */ +Light.INTENSITYMODE_AUTOMATIC = LightConstants.INTENSITYMODE_AUTOMATIC; +/** + * lumen (lm) + */ +Light.INTENSITYMODE_LUMINOUSPOWER = LightConstants.INTENSITYMODE_LUMINOUSPOWER; +/** + * candela (lm/sr) + */ +Light.INTENSITYMODE_LUMINOUSINTENSITY = LightConstants.INTENSITYMODE_LUMINOUSINTENSITY; +/** + * lux (lm/m^2) + */ +Light.INTENSITYMODE_ILLUMINANCE = LightConstants.INTENSITYMODE_ILLUMINANCE; +/** + * nit (cd/m^2) + */ +Light.INTENSITYMODE_LUMINANCE = LightConstants.INTENSITYMODE_LUMINANCE; +// Light types ids const. +/** + * Light type const id of the point light. + */ +Light.LIGHTTYPEID_POINTLIGHT = LightConstants.LIGHTTYPEID_POINTLIGHT; +/** + * Light type const id of the directional light. + */ +Light.LIGHTTYPEID_DIRECTIONALLIGHT = LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT; +/** + * Light type const id of the spot light. + */ +Light.LIGHTTYPEID_SPOTLIGHT = LightConstants.LIGHTTYPEID_SPOTLIGHT; +/** + * Light type const id of the hemispheric light. + */ +Light.LIGHTTYPEID_HEMISPHERICLIGHT = LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT; +/** + * Light type const id of the area light. + */ +Light.LIGHTTYPEID_RECT_AREALIGHT = LightConstants.LIGHTTYPEID_RECT_AREALIGHT; +__decorate([ + serializeAsColor3() +], Light.prototype, "diffuse", void 0); +__decorate([ + serializeAsColor3() +], Light.prototype, "specular", void 0); +__decorate([ + serialize() +], Light.prototype, "falloffType", void 0); +__decorate([ + serialize() +], Light.prototype, "intensity", void 0); +__decorate([ + serialize() +], Light.prototype, "range", null); +__decorate([ + serialize() +], Light.prototype, "intensityMode", null); +__decorate([ + serialize() +], Light.prototype, "radius", null); +__decorate([ + serialize() +], Light.prototype, "_renderPriority", void 0); +__decorate([ + expandToProperty("_reorderLightsInScene") +], Light.prototype, "renderPriority", void 0); +__decorate([ + serialize("shadowEnabled") +], Light.prototype, "_shadowEnabled", void 0); +__decorate([ + serialize("excludeWithLayerMask") +], Light.prototype, "_excludeWithLayerMask", void 0); +__decorate([ + serialize("includeOnlyWithLayerMask") +], Light.prototype, "_includeOnlyWithLayerMask", void 0); +__decorate([ + serialize("lightmapMode") +], Light.prototype, "_lightmapMode", void 0); + +/** + * Base implementation IShadowLight + * It groups all the common behaviour in order to reduce duplication and better follow the DRY pattern. + */ +class ShadowLight extends Light { + constructor() { + super(...arguments); + this._needProjectionMatrixCompute = true; + this._viewMatrix = Matrix.Identity(); + this._projectionMatrix = Matrix.Identity(); + } + _setPosition(value) { + this._position = value; + } + /** + * Sets the position the shadow will be casted from. Also use as the light position for both + * point and spot lights. + */ + get position() { + return this._position; + } + /** + * Sets the position the shadow will be casted from. Also use as the light position for both + * point and spot lights. + */ + set position(value) { + this._setPosition(value); + } + _setDirection(value) { + this._direction = value; + } + /** + * In 2d mode (needCube being false), gets the direction used to cast the shadow. + * Also use as the light direction on spot and directional lights. + */ + get direction() { + return this._direction; + } + /** + * In 2d mode (needCube being false), sets the direction used to cast the shadow. + * Also use as the light direction on spot and directional lights. + */ + set direction(value) { + this._setDirection(value); + } + /** + * Gets the shadow projection clipping minimum z value. + */ + get shadowMinZ() { + return this._shadowMinZ; + } + /** + * Sets the shadow projection clipping minimum z value. + */ + set shadowMinZ(value) { + this._shadowMinZ = value; + this.forceProjectionMatrixCompute(); + } + /** + * Sets the shadow projection clipping maximum z value. + */ + get shadowMaxZ() { + return this._shadowMaxZ; + } + /** + * Gets the shadow projection clipping maximum z value. + */ + set shadowMaxZ(value) { + this._shadowMaxZ = value; + this.forceProjectionMatrixCompute(); + } + /** + * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light + * @returns true if the information has been computed, false if it does not need to (no parenting) + */ + computeTransformedInformation() { + if (this.parent && this.parent.getWorldMatrix) { + if (!this.transformedPosition) { + this.transformedPosition = Vector3.Zero(); + } + Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition); + // In case the direction is present. + if (this.direction) { + if (!this.transformedDirection) { + this.transformedDirection = Vector3.Zero(); + } + Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection); + } + return true; + } + return false; + } + /** + * Return the depth scale used for the shadow map. + * @returns the depth scale. + */ + getDepthScale() { + return 50.0; + } + /** + * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed. + * @param faceIndex The index of the face we are computed the direction to generate shadow + * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getShadowDirection(faceIndex) { + return this.transformedDirection ? this.transformedDirection : this.direction; + } + /** + * If computeTransformedInformation has been called, returns the ShadowLight absolute position in the world. Otherwise, returns the local position. + * @returns the position vector in world space + */ + getAbsolutePosition() { + return this.transformedPosition ? this.transformedPosition : this.position; + } + /** + * Sets the ShadowLight direction toward the passed target. + * @param target The point to target in local space + * @returns the updated ShadowLight direction + */ + setDirectionToTarget(target) { + this.direction = Vector3.Normalize(target.subtract(this.position)); + return this.direction; + } + /** + * Returns the light rotation in euler definition. + * @returns the x y z rotation in local space. + */ + getRotation() { + this.direction.normalize(); + const xaxis = Vector3.Cross(this.direction, Axis.Y); + const yaxis = Vector3.Cross(xaxis, this.direction); + return Vector3.RotationFromAxis(xaxis, yaxis, this.direction); + } + /** + * Returns whether or not the shadow generation require a cube texture or a 2d texture. + * @returns true if a cube texture needs to be use + */ + needCube() { + return false; + } + /** + * Detects if the projection matrix requires to be recomputed this frame. + * @returns true if it requires to be recomputed otherwise, false. + */ + needProjectionMatrixCompute() { + return this._needProjectionMatrixCompute; + } + /** + * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed. + */ + forceProjectionMatrixCompute() { + this._needProjectionMatrixCompute = true; + } + /** @internal */ + _initCache() { + super._initCache(); + this._cache.position = Vector3.Zero(); + } + /** @internal */ + _isSynchronized() { + if (!this._cache.position.equals(this.position)) { + return false; + } + return true; + } + /** + * Computes the world matrix of the node + * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch + * @returns the world matrix + */ + computeWorldMatrix(force) { + if (!force && this.isSynchronized()) { + this._currentRenderId = this.getScene().getRenderId(); + return this._worldMatrix; + } + this._updateCache(); + this._cache.position.copyFrom(this.position); + if (!this._worldMatrix) { + this._worldMatrix = Matrix.Identity(); + } + Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix); + if (this.parent && this.parent.getWorldMatrix) { + this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix); + this._markSyncedWithParent(); + } + // Cache the determinant + this._worldMatrixDeterminantIsDirty = true; + return this._worldMatrix; + } + /** + * Gets the minZ used for shadow according to both the scene and the light. + * @param activeCamera The camera we are returning the min for + * @returns the depth min z + */ + getDepthMinZ(activeCamera) { + return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera?.minZ || 0; + } + /** + * Gets the maxZ used for shadow according to both the scene and the light. + * @param activeCamera The camera we are returning the max for + * @returns the depth max z + */ + getDepthMaxZ(activeCamera) { + return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera?.maxZ || 10000; + } + /** + * Sets the shadow projection matrix in parameter to the generated projection matrix. + * @param matrix The matrix to updated with the projection information + * @param viewMatrix The transform matrix of the light + * @param renderList The list of mesh to render in the map + * @returns The current light + */ + setShadowProjectionMatrix(matrix, viewMatrix, renderList) { + if (this.customProjectionMatrixBuilder) { + this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix); + } + else { + this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList); + } + return this; + } + /** @internal */ + _syncParentEnabledState() { + super._syncParentEnabledState(); + if (!this.parent || !this.parent.getWorldMatrix) { + this.transformedPosition = null; + this.transformedDirection = null; + } + } + /** + * Returns the view matrix. + * @param faceIndex The index of the face for which we want to extract the view matrix. Only used for point light types. + * @returns The view matrix. Can be null, if a view matrix cannot be defined for the type of light considered (as for a hemispherical light, for example). + */ + getViewMatrix(faceIndex) { + const lightDirection = TmpVectors.Vector3[0]; + let lightPosition = this.position; + if (this.computeTransformedInformation()) { + lightPosition = this.transformedPosition; + } + Vector3.NormalizeToRef(this.getShadowDirection(faceIndex), lightDirection); + if (Math.abs(Vector3.Dot(lightDirection, Vector3.Up())) === 1.0) { + lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light + } + const lightTarget = TmpVectors.Vector3[1]; + lightPosition.addToRef(lightDirection, lightTarget); + Matrix.LookAtLHToRef(lightPosition, lightTarget, Vector3.Up(), this._viewMatrix); + return this._viewMatrix; + } + /** + * Returns the projection matrix. + * Note that viewMatrix and renderList are optional and are only used by lights that calculate the projection matrix from a list of meshes (e.g. directional lights with automatic extents calculation). + * @param viewMatrix The view transform matrix of the light (optional). + * @param renderList The list of meshes to take into account when calculating the projection matrix (optional). + * @returns The projection matrix. Can be null, if a projection matrix cannot be defined for the type of light considered (as for a hemispherical light, for example). + */ + getProjectionMatrix(viewMatrix, renderList) { + this.setShadowProjectionMatrix(this._projectionMatrix, viewMatrix ?? this._viewMatrix, renderList ?? []); + return this._projectionMatrix; + } +} +__decorate([ + serializeAsVector3() +], ShadowLight.prototype, "position", null); +__decorate([ + serializeAsVector3() +], ShadowLight.prototype, "direction", null); +__decorate([ + serialize() +], ShadowLight.prototype, "shadowMinZ", null); +__decorate([ + serialize() +], ShadowLight.prototype, "shadowMaxZ", null); + +Node$2.AddNodeConstructor("Light_Type_1", (name, scene) => { + return () => new DirectionalLight(name, Vector3.Zero(), scene); +}); +/** + * A directional light is defined by a direction (what a surprise!). + * The light is emitted from everywhere in the specified direction, and has an infinite range. + * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object. + * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + */ +class DirectionalLight extends ShadowLight { + /** + * Fix frustum size for the shadow generation. This is disabled if the value is 0. + */ + get shadowFrustumSize() { + return this._shadowFrustumSize; + } + /** + * Specifies a fix frustum size for the shadow generation. + */ + set shadowFrustumSize(value) { + this._shadowFrustumSize = value; + this.forceProjectionMatrixCompute(); + } + /** + * Gets the shadow projection scale against the optimal computed one. + * 0.1 by default which means that the projection window is increase by 10% from the optimal size. + * This does not impact in fixed frustum size (shadowFrustumSize being set) + */ + get shadowOrthoScale() { + return this._shadowOrthoScale; + } + /** + * Sets the shadow projection scale against the optimal computed one. + * 0.1 by default which means that the projection window is increase by 10% from the optimal size. + * This does not impact in fixed frustum size (shadowFrustumSize being set) + */ + set shadowOrthoScale(value) { + this._shadowOrthoScale = value; + this.forceProjectionMatrixCompute(); + } + /** + * Gets or sets the orthoLeft property used to build the light frustum + */ + get orthoLeft() { + return this._orthoLeft; + } + set orthoLeft(left) { + this._orthoLeft = left; + } + /** + * Gets or sets the orthoRight property used to build the light frustum + */ + get orthoRight() { + return this._orthoRight; + } + set orthoRight(right) { + this._orthoRight = right; + } + /** + * Gets or sets the orthoTop property used to build the light frustum + */ + get orthoTop() { + return this._orthoTop; + } + set orthoTop(top) { + this._orthoTop = top; + } + /** + * Gets or sets the orthoBottom property used to build the light frustum + */ + get orthoBottom() { + return this._orthoBottom; + } + set orthoBottom(bottom) { + this._orthoBottom = bottom; + } + /** + * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3). + * The directional light is emitted from everywhere in the given direction. + * It can cast shadows. + * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + * @param name The friendly name of the light + * @param direction The direction of the light + * @param scene The scene the light belongs to + */ + constructor(name, direction, scene) { + super(name, scene); + this._shadowFrustumSize = 0; + this._shadowOrthoScale = 0.1; + /** + * Automatically compute the projection matrix to best fit (including all the casters) + * on each frame. + */ + this.autoUpdateExtends = true; + /** + * Automatically compute the shadowMinZ and shadowMaxZ for the projection matrix to best fit (including all the casters) + * on each frame. autoUpdateExtends must be set to true for this to work + */ + this.autoCalcShadowZBounds = false; + // Cache + this._orthoLeft = Number.MAX_VALUE; + this._orthoRight = Number.MIN_VALUE; + this._orthoTop = Number.MIN_VALUE; + this._orthoBottom = Number.MAX_VALUE; + this.position = direction.scale(-1); + this.direction = direction; + } + /** + * Returns the string "DirectionalLight". + * @returns The class name + */ + getClassName() { + return "DirectionalLight"; + } + /** + * Returns the integer 1. + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + getTypeID() { + return Light.LIGHTTYPEID_DIRECTIONALLIGHT; + } + /** + * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix. + * Returns the DirectionalLight Shadow projection matrix. + * @param matrix + * @param viewMatrix + * @param renderList + */ + _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) { + if (this.shadowFrustumSize > 0) { + this._setDefaultFixedFrustumShadowProjectionMatrix(matrix); + } + else { + this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList); + } + } + /** + * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix. + * Returns the DirectionalLight Shadow projection matrix. + * @param matrix + */ + _setDefaultFixedFrustumShadowProjectionMatrix(matrix) { + const activeCamera = this.getScene().activeCamera; + if (!activeCamera) { + return; + } + Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix, this.getScene().getEngine().isNDCHalfZRange); + } + /** + * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix. + * Returns the DirectionalLight Shadow projection matrix. + * @param matrix + * @param viewMatrix + * @param renderList + */ + _setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList) { + const activeCamera = this.getScene().activeCamera; + // Check extends + if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) { + const tempVector3 = Vector3.Zero(); + this._orthoLeft = Number.MAX_VALUE; + this._orthoRight = -Number.MAX_VALUE; + this._orthoTop = -Number.MAX_VALUE; + this._orthoBottom = Number.MAX_VALUE; + let shadowMinZ = Number.MAX_VALUE; + let shadowMaxZ = -Number.MAX_VALUE; + for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) { + const mesh = renderList[meshIndex]; + if (!mesh) { + continue; + } + const boundingInfo = mesh.getBoundingInfo(); + const boundingBox = boundingInfo.boundingBox; + for (let index = 0; index < boundingBox.vectorsWorld.length; index++) { + Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3); + if (tempVector3.x < this._orthoLeft) { + this._orthoLeft = tempVector3.x; + } + if (tempVector3.y < this._orthoBottom) { + this._orthoBottom = tempVector3.y; + } + if (tempVector3.x > this._orthoRight) { + this._orthoRight = tempVector3.x; + } + if (tempVector3.y > this._orthoTop) { + this._orthoTop = tempVector3.y; + } + if (this.autoCalcShadowZBounds) { + if (tempVector3.z < shadowMinZ) { + shadowMinZ = tempVector3.z; + } + if (tempVector3.z > shadowMaxZ) { + shadowMaxZ = tempVector3.z; + } + } + } + } + if (this.autoCalcShadowZBounds) { + this._shadowMinZ = shadowMinZ; + this._shadowMaxZ = shadowMaxZ; + } + } + const xOffset = this._orthoRight - this._orthoLeft; + const yOffset = this._orthoTop - this._orthoBottom; + const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera?.minZ || 0; + const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera?.maxZ || 10000; + const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer; + Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, this.getScene().getEngine().isNDCHalfZRange); + } + _buildUniformLayout() { + this._uniformBuffer.addUniform("vLightData", 4); + this._uniformBuffer.addUniform("vLightDiffuse", 4); + this._uniformBuffer.addUniform("vLightSpecular", 4); + this._uniformBuffer.addUniform("shadowsInfo", 3); + this._uniformBuffer.addUniform("depthValues", 2); + this._uniformBuffer.create(); + } + /** + * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name. + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The directional light + */ + transferToEffect(effect, lightIndex) { + if (this.computeTransformedInformation()) { + this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex); + return this; + } + this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex); + return this; + } + transferToNodeMaterialEffect(effect, lightDataUniformName) { + if (this.computeTransformedInformation()) { + effect.setFloat3(lightDataUniformName, this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z); + return this; + } + effect.setFloat3(lightDataUniformName, this.direction.x, this.direction.y, this.direction.z); + return this; + } + /** + * Gets the minZ used for shadow according to both the scene and the light. + * + * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being + * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5. + * (when not using reverse depth buffer / NDC half Z range) + * @param _activeCamera The camera we are returning the min for (not used) + * @returns the depth min z + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getDepthMinZ(_activeCamera) { + const engine = this._scene.getEngine(); + return !engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1; + } + /** + * Gets the maxZ used for shadow according to both the scene and the light. + * + * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being + * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5. + * (when not using reverse depth buffer / NDC half Z range) + * @param _activeCamera The camera we are returning the max for + * @returns the depth max z + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getDepthMaxZ(_activeCamera) { + const engine = this._scene.getEngine(); + return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1; + } + /** + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect + */ + prepareLightSpecificDefines(defines, lightIndex) { + defines["DIRLIGHT" + lightIndex] = true; + } +} +__decorate([ + serialize() +], DirectionalLight.prototype, "shadowFrustumSize", null); +__decorate([ + serialize() +], DirectionalLight.prototype, "shadowOrthoScale", null); +__decorate([ + serialize() +], DirectionalLight.prototype, "autoUpdateExtends", void 0); +__decorate([ + serialize() +], DirectionalLight.prototype, "autoCalcShadowZBounds", void 0); +__decorate([ + serialize("orthoLeft") +], DirectionalLight.prototype, "_orthoLeft", void 0); +__decorate([ + serialize("orthoRight") +], DirectionalLight.prototype, "_orthoRight", void 0); +__decorate([ + serialize("orthoTop") +], DirectionalLight.prototype, "_orthoTop", void 0); +__decorate([ + serialize("orthoBottom") +], DirectionalLight.prototype, "_orthoBottom", void 0); +// Register Class Name +RegisterClass("BABYLON.DirectionalLight", DirectionalLight); + +/** + * Transform some pixel data to a base64 string + * @param pixels defines the pixel data to transform to base64 + * @param size defines the width and height of the (texture) data + * @param invertY true if the data must be inverted for the Y coordinate during the conversion + * @returns The base64 encoded string or null + */ +function GenerateBase64StringFromPixelData(pixels, size, invertY = false) { + const width = size.width; + const height = size.height; + if (pixels instanceof Float32Array) { + let len = pixels.byteLength / pixels.BYTES_PER_ELEMENT; + const npixels = new Uint8Array(len); + while (--len >= 0) { + let val = pixels[len]; + if (val < 0) { + val = 0; + } + else if (val > 1) { + val = 1; + } + npixels[len] = val * 255; + } + pixels = npixels; + } + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + const ctx = canvas.getContext("2d"); + if (!ctx) { + return null; + } + const imageData = ctx.createImageData(width, height); + const castData = imageData.data; + castData.set(pixels); + ctx.putImageData(imageData, 0, 0); + if (invertY) { + const canvas2 = document.createElement("canvas"); + canvas2.width = width; + canvas2.height = height; + const ctx2 = canvas2.getContext("2d"); + if (!ctx2) { + return null; + } + ctx2.translate(0, height); + ctx2.scale(1, -1); + ctx2.drawImage(canvas, 0, 0); + return canvas2.toDataURL("image/png"); + } + return canvas.toDataURL("image/png"); +} +/** + * Reads the pixels stored in the webgl texture and returns them as a base64 string + * @param texture defines the texture to read pixels from + * @param faceIndex defines the face of the texture to read (in case of cube texture) + * @param level defines the LOD level of the texture to read (in case of Mip Maps) + * @returns The base64 encoded string or null + */ +function GenerateBase64StringFromTexture(texture, faceIndex = 0, level = 0) { + const internalTexture = texture.getInternalTexture(); + if (!internalTexture) { + return null; + } + const pixels = texture._readPixelsSync(faceIndex, level); + if (!pixels) { + return null; + } + return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY); +} +/** + * Reads the pixels stored in the webgl texture and returns them as a base64 string + * @param texture defines the texture to read pixels from + * @param faceIndex defines the face of the texture to read (in case of cube texture) + * @param level defines the LOD level of the texture to read (in case of Mip Maps) + * @returns The base64 encoded string or null wrapped in a promise + */ +async function GenerateBase64StringFromTextureAsync(texture, faceIndex = 0, level = 0) { + const internalTexture = texture.getInternalTexture(); + if (!internalTexture) { + return null; + } + const pixels = await texture.readPixels(faceIndex, level); + if (!pixels) { + return null; + } + return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY); +} + +/** + * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture + */ +class Texture extends BaseTexture { + /** + * @internal + */ + static _CreateVideoTexture(name, src, scene, generateMipMaps = false, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) { + throw _WarnImport("VideoTexture"); + } + /** + * Are mip maps generated for this texture or not. + */ + get noMipmap() { + return this._noMipmap; + } + /** Returns the texture mime type if it was defined by a loader (undefined else) */ + get mimeType() { + return this._mimeType; + } + /** + * Is the texture preventing material to render while loading. + * If false, a default texture will be used instead of the loading one during the preparation step. + */ + set isBlocking(value) { + this._isBlocking = value; + } + get isBlocking() { + return this._isBlocking; + } + /** + * Gets a boolean indicating if the texture needs to be inverted on the y axis during loading + */ + get invertY() { + return this._invertY; + } + /** + * Instantiates a new texture. + * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture + * @param url defines the url of the picture to load as a texture + * @param sceneOrEngine defines the scene or engine the texture will belong to + * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture + * @param invertY defines if the texture needs to be inverted on the y axis during loading + * @param samplingMode defines the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...) + * @param onLoad defines a callback triggered when the texture has been loaded + * @param onError defines a callback triggered when an error occurred during the loading session + * @param buffer defines the buffer to load the texture from in case the texture is loaded from a buffer representation + * @param deleteBuffer defines if the buffer we are loading the texture from should be deleted after load + * @param format defines the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) + * @param mimeType defines an optional mime type information + * @param loaderOptions options to be passed to the loader + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @param forcedExtension defines the extension to use to pick the right loader + */ + constructor(url, sceneOrEngine, noMipmapOrOptions, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, buffer = null, deleteBuffer = false, format, mimeType, loaderOptions, creationFlags, forcedExtension) { + super(sceneOrEngine); + /** + * Define the url of the texture. + */ + this.url = null; + /** + * Define an offset on the texture to offset the u coordinates of the UVs + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#offsetting + */ + this.uOffset = 0; + /** + * Define an offset on the texture to offset the v coordinates of the UVs + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#offsetting + */ + this.vOffset = 0; + /** + * Define an offset on the texture to scale the u coordinates of the UVs + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#tiling + */ + this.uScale = 1.0; + /** + * Define an offset on the texture to scale the v coordinates of the UVs + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#tiling + */ + this.vScale = 1.0; + /** + * Define an offset on the texture to rotate around the u coordinates of the UVs + * The angle is defined in radians. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials + */ + this.uAng = 0; + /** + * Define an offset on the texture to rotate around the v coordinates of the UVs + * The angle is defined in radians. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials + */ + this.vAng = 0; + /** + * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture) + * The angle is defined in radians. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials + */ + this.wAng = 0; + /** + * Defines the center of rotation (U) + */ + this.uRotationCenter = 0.5; + /** + * Defines the center of rotation (V) + */ + this.vRotationCenter = 0.5; + /** + * Defines the center of rotation (W) + */ + this.wRotationCenter = 0.5; + /** + * Sets this property to true to avoid deformations when rotating the texture with non-uniform scaling + */ + this.homogeneousRotationInUVTransform = false; + /** + * List of inspectable custom properties (used by the Inspector) + * @see https://doc.babylonjs.com/toolsAndResources/inspector#extensibility + */ + this.inspectableCustomProperties = null; + /** @internal */ + this._noMipmap = false; + /** @internal */ + this._invertY = false; + this._rowGenerationMatrix = null; + this._cachedTextureMatrix = null; + this._projectionModeMatrix = null; + this._t0 = null; + this._t1 = null; + this._t2 = null; + this._cachedUOffset = -1; + this._cachedVOffset = -1; + this._cachedUScale = 0; + this._cachedVScale = 0; + this._cachedUAng = -1; + this._cachedVAng = -1; + this._cachedWAng = -1; + this._cachedReflectionProjectionMatrixId = -1; + this._cachedURotationCenter = -1; + this._cachedVRotationCenter = -1; + this._cachedWRotationCenter = -1; + this._cachedHomogeneousRotationInUVTransform = false; + this._cachedIdentity3x2 = true; + this._cachedReflectionTextureMatrix = null; + this._cachedReflectionUOffset = -1; + this._cachedReflectionVOffset = -1; + this._cachedReflectionUScale = 0; + this._cachedReflectionVScale = 0; + this._cachedReflectionCoordinatesMode = -1; + /** @internal */ + this._buffer = null; + this._deleteBuffer = false; + this._format = null; + this._delayedOnLoad = null; + this._delayedOnError = null; + /** + * Observable triggered once the texture has been loaded. + */ + this.onLoadObservable = new Observable(); + this._isBlocking = true; + this.name = url || ""; + this.url = url; + let noMipmap; + let useSRGBBuffer = false; + let internalTexture = null; + let gammaSpace = true; + if (typeof noMipmapOrOptions === "object" && noMipmapOrOptions !== null) { + noMipmap = noMipmapOrOptions.noMipmap ?? false; + invertY = noMipmapOrOptions.invertY ?? true; + samplingMode = noMipmapOrOptions.samplingMode ?? Texture.TRILINEAR_SAMPLINGMODE; + onLoad = noMipmapOrOptions.onLoad ?? null; + onError = noMipmapOrOptions.onError ?? null; + buffer = noMipmapOrOptions.buffer ?? null; + deleteBuffer = noMipmapOrOptions.deleteBuffer ?? false; + format = noMipmapOrOptions.format; + mimeType = noMipmapOrOptions.mimeType; + loaderOptions = noMipmapOrOptions.loaderOptions; + creationFlags = noMipmapOrOptions.creationFlags; + useSRGBBuffer = noMipmapOrOptions.useSRGBBuffer ?? false; + internalTexture = noMipmapOrOptions.internalTexture ?? null; + gammaSpace = noMipmapOrOptions.gammaSpace ?? gammaSpace; + forcedExtension = noMipmapOrOptions.forcedExtension ?? forcedExtension; + } + else { + noMipmap = !!noMipmapOrOptions; + } + this._gammaSpace = gammaSpace; + this._noMipmap = noMipmap; + this._invertY = invertY === undefined ? true : invertY; + this._initialSamplingMode = samplingMode; + this._buffer = buffer; + this._deleteBuffer = deleteBuffer; + this._mimeType = mimeType; + this._loaderOptions = loaderOptions; + this._creationFlags = creationFlags; + this._useSRGBBuffer = useSRGBBuffer; + this._forcedExtension = forcedExtension; + if (format) { + this._format = format; + } + const scene = this.getScene(); + const engine = this._getEngine(); + if (!engine) { + return; + } + engine.onBeforeTextureInitObservable.notifyObservers(this); + const load = () => { + if (this._texture) { + if (this._texture._invertVScale) { + this.vScale *= -1; + this.vOffset += 1; + } + // Update texture to match internal texture's wrapping + if (this._texture._cachedWrapU !== null) { + this.wrapU = this._texture._cachedWrapU; + this._texture._cachedWrapU = null; + } + if (this._texture._cachedWrapV !== null) { + this.wrapV = this._texture._cachedWrapV; + this._texture._cachedWrapV = null; + } + if (this._texture._cachedWrapR !== null) { + this.wrapR = this._texture._cachedWrapR; + this._texture._cachedWrapR = null; + } + } + if (this.onLoadObservable.hasObservers()) { + this.onLoadObservable.notifyObservers(this); + } + if (onLoad) { + onLoad(); + } + if (!this.isBlocking && scene) { + scene.resetCachedMaterial(); + } + }; + const errorHandler = (message, exception) => { + this._loadingError = true; + this._errorObject = { message, exception }; + if (onError) { + onError(message, exception); + } + Texture.OnTextureLoadErrorObservable.notifyObservers(this); + }; + if (!this.url && !internalTexture) { + this._delayedOnLoad = load; + this._delayedOnError = errorHandler; + return; + } + this._texture = internalTexture ?? this._getFromCache(this.url, noMipmap, samplingMode, this._invertY, useSRGBBuffer, this.isCube); + if (!this._texture) { + if (!scene || !scene.useDelayedTextureLoading) { + try { + this._texture = engine.createTexture(this.url, noMipmap, this._invertY, scene, samplingMode, load, errorHandler, this._buffer, undefined, this._format, this._forcedExtension, mimeType, loaderOptions, creationFlags, useSRGBBuffer); + } + catch (e) { + errorHandler("error loading", e); + throw e; + } + if (deleteBuffer) { + this._buffer = null; + } + } + else { + this.delayLoadState = 4; + this._delayedOnLoad = load; + this._delayedOnError = errorHandler; + } + } + else { + if (this._texture.isReady) { + TimingTools.SetImmediate(() => load()); + } + else { + const loadObserver = this._texture.onLoadedObservable.add(load); + this._texture.onErrorObservable.add((e) => { + errorHandler(e.message, e.exception); + this._texture?.onLoadedObservable.remove(loadObserver); + }); + } + } + } + /** + * Update the url (and optional buffer) of this texture if url was null during construction. + * @param url the url of the texture + * @param buffer the buffer of the texture (defaults to null) + * @param onLoad callback called when the texture is loaded (defaults to null) + * @param forcedExtension defines the extension to use to pick the right loader + */ + updateURL(url, buffer = null, onLoad, forcedExtension) { + if (this.url) { + this.releaseInternalTexture(); + this.getScene().markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this); + }); + } + if (!this.name || this.name.startsWith("data:")) { + this.name = url; + } + this.url = url; + this._buffer = buffer; + this._forcedExtension = forcedExtension; + this.delayLoadState = 4; + if (onLoad) { + this._delayedOnLoad = onLoad; + } + this.delayLoad(); + } + /** + * Finish the loading sequence of a texture flagged as delayed load. + * @internal + */ + delayLoad() { + if (this.delayLoadState !== 4) { + return; + } + const scene = this.getScene(); + if (!scene) { + return; + } + this.delayLoadState = 1; + this._texture = this._getFromCache(this.url, this._noMipmap, this.samplingMode, this._invertY, this._useSRGBBuffer, this.isCube); + if (!this._texture) { + this._texture = scene + .getEngine() + .createTexture(this.url, this._noMipmap, this._invertY, scene, this.samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format, this._forcedExtension, this._mimeType, this._loaderOptions, this._creationFlags, this._useSRGBBuffer); + if (this._deleteBuffer) { + this._buffer = null; + } + } + else { + if (this._delayedOnLoad) { + if (this._texture.isReady) { + TimingTools.SetImmediate(this._delayedOnLoad); + } + else { + this._texture.onLoadedObservable.add(this._delayedOnLoad); + } + } + } + this._delayedOnLoad = null; + this._delayedOnError = null; + } + _prepareRowForTextureGeneration(x, y, z, t) { + x *= this._cachedUScale; + y *= this._cachedVScale; + x -= this.uRotationCenter * this._cachedUScale; + y -= this.vRotationCenter * this._cachedVScale; + z -= this.wRotationCenter; + Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t); + t.x += this.uRotationCenter * this._cachedUScale + this._cachedUOffset; + t.y += this.vRotationCenter * this._cachedVScale + this._cachedVOffset; + t.z += this.wRotationCenter; + } + /** + * Get the current texture matrix which includes the requested offsetting, tiling and rotation components. + * @param uBase The horizontal base offset multiplier (1 by default) + * @returns the transform matrix of the texture. + */ + getTextureMatrix(uBase = 1) { + if (this.uOffset === this._cachedUOffset && + this.vOffset === this._cachedVOffset && + this.uScale * uBase === this._cachedUScale && + this.vScale === this._cachedVScale && + this.uAng === this._cachedUAng && + this.vAng === this._cachedVAng && + this.wAng === this._cachedWAng && + this.uRotationCenter === this._cachedURotationCenter && + this.vRotationCenter === this._cachedVRotationCenter && + this.wRotationCenter === this._cachedWRotationCenter && + this.homogeneousRotationInUVTransform === this._cachedHomogeneousRotationInUVTransform) { + return this._cachedTextureMatrix; + } + this._cachedUOffset = this.uOffset; + this._cachedVOffset = this.vOffset; + this._cachedUScale = this.uScale * uBase; + this._cachedVScale = this.vScale; + this._cachedUAng = this.uAng; + this._cachedVAng = this.vAng; + this._cachedWAng = this.wAng; + this._cachedURotationCenter = this.uRotationCenter; + this._cachedVRotationCenter = this.vRotationCenter; + this._cachedWRotationCenter = this.wRotationCenter; + this._cachedHomogeneousRotationInUVTransform = this.homogeneousRotationInUVTransform; + if (!this._cachedTextureMatrix || !this._rowGenerationMatrix) { + this._cachedTextureMatrix = Matrix.Zero(); + this._rowGenerationMatrix = new Matrix(); + this._t0 = Vector3.Zero(); + this._t1 = Vector3.Zero(); + this._t2 = Vector3.Zero(); + } + Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix); + if (this.homogeneousRotationInUVTransform) { + Matrix.TranslationToRef(-this._cachedURotationCenter, -this._cachedVRotationCenter, -this._cachedWRotationCenter, TmpVectors.Matrix[0]); + Matrix.TranslationToRef(this._cachedURotationCenter, this._cachedVRotationCenter, this._cachedWRotationCenter, TmpVectors.Matrix[1]); + Matrix.ScalingToRef(this._cachedUScale, this._cachedVScale, 0, TmpVectors.Matrix[2]); + Matrix.TranslationToRef(this._cachedUOffset, this._cachedVOffset, 0, TmpVectors.Matrix[3]); + TmpVectors.Matrix[0].multiplyToRef(this._rowGenerationMatrix, this._cachedTextureMatrix); + this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[1], this._cachedTextureMatrix); + this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[2], this._cachedTextureMatrix); + this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[3], this._cachedTextureMatrix); + // copy the translation row to the 3rd row of the matrix so that we don't need to update the shaders (which expects the translation to be on the 3rd row) + this._cachedTextureMatrix.setRowFromFloats(2, this._cachedTextureMatrix.m[12], this._cachedTextureMatrix.m[13], this._cachedTextureMatrix.m[14], 1); + } + else { + this._prepareRowForTextureGeneration(0, 0, 0, this._t0); + this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1); + this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2); + this._t1.subtractInPlace(this._t0); + this._t2.subtractInPlace(this._t0); + Matrix.FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0.0, this._t2.x, this._t2.y, this._t2.z, 0.0, this._t0.x, this._t0.y, this._t0.z, 0.0, 0.0, 0.0, 0.0, 1.0, this._cachedTextureMatrix); + } + const scene = this.getScene(); + if (!scene) { + return this._cachedTextureMatrix; + } + const previousIdentity3x2 = this._cachedIdentity3x2; + this._cachedIdentity3x2 = this._cachedTextureMatrix.isIdentityAs3x2(); + if (this.optimizeUVAllocation && previousIdentity3x2 !== this._cachedIdentity3x2) { + // We flag the materials that are using this texture as "texture dirty" because depending on the fact that the matrix is the identity or not, some defines + // will get different values (see PrepareDefinesForMergedUV), meaning we should regenerate the effect accordingly + scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this); + }); + } + return this._cachedTextureMatrix; + } + /** + * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance. + * @returns The reflection texture transform + */ + getReflectionTextureMatrix() { + const scene = this.getScene(); + if (!scene) { + return this._cachedReflectionTextureMatrix; + } + if (this.uOffset === this._cachedReflectionUOffset && + this.vOffset === this._cachedReflectionVOffset && + this.uScale === this._cachedReflectionUScale && + this.vScale === this._cachedReflectionVScale && + this.coordinatesMode === this._cachedReflectionCoordinatesMode) { + if (this.coordinatesMode === Texture.PROJECTION_MODE) { + if (this._cachedReflectionProjectionMatrixId === scene.getProjectionMatrix().updateFlag) { + return this._cachedReflectionTextureMatrix; + } + } + else { + return this._cachedReflectionTextureMatrix; + } + } + if (!this._cachedReflectionTextureMatrix) { + this._cachedReflectionTextureMatrix = Matrix.Zero(); + } + if (!this._projectionModeMatrix) { + this._projectionModeMatrix = Matrix.Zero(); + } + const flagMaterialsAsTextureDirty = this._cachedReflectionCoordinatesMode !== this.coordinatesMode; + this._cachedReflectionUOffset = this.uOffset; + this._cachedReflectionVOffset = this.vOffset; + this._cachedReflectionUScale = this.uScale; + this._cachedReflectionVScale = this.vScale; + this._cachedReflectionCoordinatesMode = this.coordinatesMode; + switch (this.coordinatesMode) { + case Texture.PLANAR_MODE: { + Matrix.IdentityToRef(this._cachedReflectionTextureMatrix); + this._cachedReflectionTextureMatrix[0] = this.uScale; + this._cachedReflectionTextureMatrix[5] = this.vScale; + this._cachedReflectionTextureMatrix[12] = this.uOffset; + this._cachedReflectionTextureMatrix[13] = this.vOffset; + break; + } + case Texture.PROJECTION_MODE: { + Matrix.FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, this._projectionModeMatrix); + const projectionMatrix = scene.getProjectionMatrix(); + this._cachedReflectionProjectionMatrixId = projectionMatrix.updateFlag; + projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedReflectionTextureMatrix); + break; + } + default: + Matrix.IdentityToRef(this._cachedReflectionTextureMatrix); + break; + } + if (flagMaterialsAsTextureDirty) { + // We flag the materials that are using this texture as "texture dirty" if the coordinatesMode has changed. + // Indeed, this property is used to set the value of some defines used to generate the effect (in material.isReadyForSubMesh), so we must make sure this code will be re-executed and the effect recreated if necessary + scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this); + }); + } + return this._cachedReflectionTextureMatrix; + } + /** + * Clones the texture. + * @returns the cloned texture + */ + clone() { + const options = { + noMipmap: this._noMipmap, + invertY: this._invertY, + samplingMode: this.samplingMode, + onLoad: undefined, + onError: undefined, + buffer: this._texture ? this._texture._buffer : undefined, + deleteBuffer: this._deleteBuffer, + format: this.textureFormat, + mimeType: this.mimeType, + loaderOptions: this._loaderOptions, + creationFlags: this._creationFlags, + useSRGBBuffer: this._useSRGBBuffer, + }; + return SerializationHelper.Clone(() => { + return new Texture(this._texture ? this._texture.url : null, this.getScene(), options); + }, this); + } + /** + * Serialize the texture to a JSON representation we can easily use in the respective Parse function. + * @returns The JSON representation of the texture + */ + serialize() { + const savedName = this.name; + if (!Texture.SerializeBuffers) { + if (this.name.startsWith("data:")) { + this.name = ""; + } + } + if (this.name.startsWith("data:") && this.url === this.name) { + this.url = ""; + } + const serializationObject = super.serialize(Texture._SerializeInternalTextureUniqueId); + if (!serializationObject) { + return null; + } + if (Texture.SerializeBuffers || Texture.ForceSerializeBuffers) { + if (typeof this._buffer === "string" && this._buffer.substring(0, 5) === "data:") { + serializationObject.base64String = this._buffer; + serializationObject.name = serializationObject.name.replace("data:", ""); + } + else if (this.url && this.url.startsWith("data:") && this._buffer instanceof Uint8Array) { + serializationObject.base64String = "data:image/png;base64," + EncodeArrayBufferToBase64(this._buffer); + } + else if (Texture.ForceSerializeBuffers || (this.url && this.url.startsWith("blob:")) || this._forceSerialize) { + serializationObject.base64String = + !this._engine || this._engine._features.supportSyncTextureRead ? GenerateBase64StringFromTexture(this) : GenerateBase64StringFromTextureAsync(this); + } + } + serializationObject.invertY = this._invertY; + serializationObject.samplingMode = this.samplingMode; + serializationObject._creationFlags = this._creationFlags; + serializationObject._useSRGBBuffer = this._useSRGBBuffer; + if (Texture._SerializeInternalTextureUniqueId) { + serializationObject.internalTextureUniqueId = this._texture?.uniqueId; + } + serializationObject.internalTextureLabel = this._texture?.label; + serializationObject.noMipmap = this._noMipmap; + this.name = savedName; + return serializationObject; + } + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "Texture" + */ + getClassName() { + return "Texture"; + } + /** + * Dispose the texture and release its associated resources. + */ + dispose() { + super.dispose(); + this.onLoadObservable.clear(); + this._delayedOnLoad = null; + this._delayedOnError = null; + this._buffer = null; + } + /** + * Parse the JSON representation of a texture in order to recreate the texture in the given scene. + * @param parsedTexture Define the JSON representation of the texture + * @param scene Define the scene the parsed texture should be instantiated in + * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies + * @returns The parsed texture if successful + */ + static Parse(parsedTexture, scene, rootUrl) { + if (parsedTexture.customType) { + const customTexture = InstantiationTools.Instantiate(parsedTexture.customType); + // Update Sampling Mode + const parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl); + if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) { + if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) { + parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode); + } + } + return parsedCustomTexture; + } + if (parsedTexture.isCube && !parsedTexture.isRenderTarget) { + return Texture._CubeTextureParser(parsedTexture, scene, rootUrl); + } + const hasInternalTextureUniqueId = parsedTexture.internalTextureUniqueId !== undefined; + if (!parsedTexture.name && !parsedTexture.isRenderTarget && !hasInternalTextureUniqueId) { + return null; + } + let internalTexture; + if (hasInternalTextureUniqueId) { + const cache = scene.getEngine().getLoadedTexturesCache(); + for (const texture of cache) { + if (texture.uniqueId === parsedTexture.internalTextureUniqueId) { + internalTexture = texture; + break; + } + } + } + const onLoaded = (texture) => { + // Clear cache + if (texture && texture._texture) { + texture._texture._cachedWrapU = null; + texture._texture._cachedWrapV = null; + texture._texture._cachedWrapR = null; + } + // Update Sampling Mode + if (parsedTexture.samplingMode) { + const sampling = parsedTexture.samplingMode; + if (texture && texture.samplingMode !== sampling) { + texture.updateSamplingMode(sampling); + } + } + // Animations + if (texture && parsedTexture.animations) { + for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) { + const parsedAnimation = parsedTexture.animations[animationIndex]; + const internalClass = GetClass("BABYLON.Animation"); + if (internalClass) { + texture.animations.push(internalClass.Parse(parsedAnimation)); + } + } + } + if (texture && texture._texture) { + if (hasInternalTextureUniqueId && !internalTexture) { + texture._texture._setUniqueId(parsedTexture.internalTextureUniqueId); + } + texture._texture.label = parsedTexture.internalTextureLabel; + } + }; + const texture = SerializationHelper.Parse(() => { + let generateMipMaps = true; + if (parsedTexture.noMipmap) { + generateMipMaps = false; + } + if (parsedTexture.mirrorPlane) { + const mirrorTexture = Texture._CreateMirror(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps); + mirrorTexture._waitingRenderList = parsedTexture.renderList; + mirrorTexture.mirrorPlane = Plane.FromArray(parsedTexture.mirrorPlane); + onLoaded(mirrorTexture); + return mirrorTexture; + } + else if (parsedTexture.isRenderTarget) { + let renderTargetTexture = null; + if (parsedTexture.isCube) { + // Search for an existing reflection probe (which contains a cube render target texture) + if (scene.reflectionProbes) { + for (let index = 0; index < scene.reflectionProbes.length; index++) { + const probe = scene.reflectionProbes[index]; + if (probe.name === parsedTexture.name) { + return probe.cubeTexture; + } + } + } + } + else { + renderTargetTexture = Texture._CreateRenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps, parsedTexture._creationFlags ?? 0); + renderTargetTexture._waitingRenderList = parsedTexture.renderList; + } + onLoaded(renderTargetTexture); + return renderTargetTexture; + } + else if (parsedTexture.isVideo) { + const texture = Texture._CreateVideoTexture(rootUrl + (parsedTexture.url || parsedTexture.name), rootUrl + (parsedTexture.src || parsedTexture.url), scene, generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, parsedTexture.settings || {}); + onLoaded(texture); + return texture; + } + else { + let texture; + if (parsedTexture.base64String && !internalTexture) { + // name and url are the same to ensure caching happens from the actual base64 string + texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.base64String, scene, !generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, () => { + onLoaded(texture); + }, parsedTexture._creationFlags ?? 0, parsedTexture._useSRGBBuffer ?? false); + // prettier name to fit with the loaded data + texture.name = parsedTexture.name; + } + else { + let url; + if (parsedTexture.name && (parsedTexture.name.indexOf("://") > 0 || parsedTexture.name.startsWith("data:"))) { + url = parsedTexture.name; + } + else { + url = rootUrl + parsedTexture.name; + } + if (parsedTexture.url && (parsedTexture.url.startsWith("data:") || Texture.UseSerializedUrlIfAny)) { + url = parsedTexture.url; + } + const options = { + noMipmap: !generateMipMaps, + invertY: parsedTexture.invertY, + samplingMode: parsedTexture.samplingMode, + onLoad: () => { + onLoaded(texture); + }, + internalTexture, + }; + texture = new Texture(url, scene, options); + } + return texture; + } + }, parsedTexture, scene); + return texture; + } + /** + * Creates a texture from its base 64 representation. + * @param data Define the base64 payload without the data: prefix + * @param name Define the name of the texture in the scene useful fo caching purpose for instance + * @param scene Define the scene the texture should belong to + * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture + * @param invertY define if the texture needs to be inverted on the y axis during loading + * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...) + * @param onLoad define a callback triggered when the texture has been loaded + * @param onError define a callback triggered when an error occurred during the loading session + * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @param forcedExtension defines the extension to use to pick the right loader + * @returns the created texture + */ + static CreateFromBase64String(data, name, scene, noMipmapOrOptions, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags, forcedExtension) { + return new Texture("data:" + name, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, data, false, format, undefined, undefined, creationFlags, forcedExtension); + } + /** + * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in) + * @param name Define the name of the texture in the scene useful fo caching purpose for instance + * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation + * @param scene Define the scene the texture should belong to + * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load + * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture + * @param invertY define if the texture needs to be inverted on the y axis during loading + * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...) + * @param onLoad define a callback triggered when the texture has been loaded + * @param onError define a callback triggered when an error occurred during the loading session + * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @param forcedExtension defines the extension to use to pick the right loader + * @returns the created texture + */ + static LoadFromDataString(name, buffer, scene, deleteBuffer = false, noMipmapOrOptions, invertY = true, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags, forcedExtension) { + if (name.substring(0, 5) !== "data:") { + name = "data:" + name; + } + return new Texture(name, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format, undefined, undefined, creationFlags, forcedExtension); + } +} +/** + * Gets or sets a general boolean used to indicate that textures containing direct data (buffers) must be saved as part of the serialization process + */ +Texture.SerializeBuffers = true; +/** + * Gets or sets a general boolean used to indicate that texture buffers must be saved as part of the serialization process. + * If no buffer exists, one will be created as base64 string from the internal webgl data. + */ +Texture.ForceSerializeBuffers = false; +/** + * This observable will notify when any texture had a loading error + */ +Texture.OnTextureLoadErrorObservable = new Observable(); +/** @internal */ +Texture._SerializeInternalTextureUniqueId = false; +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Texture._CubeTextureParser = (jsonTexture, scene, rootUrl) => { + throw _WarnImport("CubeTexture"); +}; +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Texture._CreateMirror = (name, renderTargetSize, scene, generateMipMaps) => { + throw _WarnImport("MirrorTexture"); +}; +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Texture._CreateRenderTargetTexture = (name, renderTargetSize, scene, generateMipMaps, creationFlags) => { + throw _WarnImport("RenderTargetTexture"); +}; +/** nearest is mag = nearest and min = nearest and no mip */ +Texture.NEAREST_SAMPLINGMODE = 1; +/** nearest is mag = nearest and min = nearest and mip = linear */ +Texture.NEAREST_NEAREST_MIPLINEAR = 8; // nearest is mag = nearest and min = nearest and mip = linear +/** Bilinear is mag = linear and min = linear and no mip */ +Texture.BILINEAR_SAMPLINGMODE = 2; +/** Bilinear is mag = linear and min = linear and mip = nearest */ +Texture.LINEAR_LINEAR_MIPNEAREST = 11; // Bilinear is mag = linear and min = linear and mip = nearest +/** Trilinear is mag = linear and min = linear and mip = linear */ +Texture.TRILINEAR_SAMPLINGMODE = 3; +/** Trilinear is mag = linear and min = linear and mip = linear */ +Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear +/** mag = nearest and min = nearest and mip = nearest */ +Texture.NEAREST_NEAREST_MIPNEAREST = 4; +/** mag = nearest and min = linear and mip = nearest */ +Texture.NEAREST_LINEAR_MIPNEAREST = 5; +/** mag = nearest and min = linear and mip = linear */ +Texture.NEAREST_LINEAR_MIPLINEAR = 6; +/** mag = nearest and min = linear and mip = none */ +Texture.NEAREST_LINEAR = 7; +/** mag = nearest and min = nearest and mip = none */ +Texture.NEAREST_NEAREST = 1; +/** mag = linear and min = nearest and mip = nearest */ +Texture.LINEAR_NEAREST_MIPNEAREST = 9; +/** mag = linear and min = nearest and mip = linear */ +Texture.LINEAR_NEAREST_MIPLINEAR = 10; +/** mag = linear and min = linear and mip = none */ +Texture.LINEAR_LINEAR = 2; +/** mag = linear and min = nearest and mip = none */ +Texture.LINEAR_NEAREST = 12; +/** Explicit coordinates mode */ +Texture.EXPLICIT_MODE = 0; +/** Spherical coordinates mode */ +Texture.SPHERICAL_MODE = 1; +/** Planar coordinates mode */ +Texture.PLANAR_MODE = 2; +/** Cubic coordinates mode */ +Texture.CUBIC_MODE = 3; +/** Projection coordinates mode */ +Texture.PROJECTION_MODE = 4; +/** Inverse Cubic coordinates mode */ +Texture.SKYBOX_MODE = 5; +/** Inverse Cubic coordinates mode */ +Texture.INVCUBIC_MODE = 6; +/** Equirectangular coordinates mode */ +Texture.EQUIRECTANGULAR_MODE = 7; +/** Equirectangular Fixed coordinates mode */ +Texture.FIXED_EQUIRECTANGULAR_MODE = 8; +/** Equirectangular Fixed Mirrored coordinates mode */ +Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; +/** Texture is not repeating outside of 0..1 UVs */ +Texture.CLAMP_ADDRESSMODE = 0; +/** Texture is repeating outside of 0..1 UVs */ +Texture.WRAP_ADDRESSMODE = 1; +/** Texture is repeating and mirrored */ +Texture.MIRROR_ADDRESSMODE = 2; +/** + * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file + */ +Texture.UseSerializedUrlIfAny = false; +__decorate([ + serialize() +], Texture.prototype, "url", void 0); +__decorate([ + serialize() +], Texture.prototype, "uOffset", void 0); +__decorate([ + serialize() +], Texture.prototype, "vOffset", void 0); +__decorate([ + serialize() +], Texture.prototype, "uScale", void 0); +__decorate([ + serialize() +], Texture.prototype, "vScale", void 0); +__decorate([ + serialize() +], Texture.prototype, "uAng", void 0); +__decorate([ + serialize() +], Texture.prototype, "vAng", void 0); +__decorate([ + serialize() +], Texture.prototype, "wAng", void 0); +__decorate([ + serialize() +], Texture.prototype, "uRotationCenter", void 0); +__decorate([ + serialize() +], Texture.prototype, "vRotationCenter", void 0); +__decorate([ + serialize() +], Texture.prototype, "wRotationCenter", void 0); +__decorate([ + serialize() +], Texture.prototype, "homogeneousRotationInUVTransform", void 0); +__decorate([ + serialize() +], Texture.prototype, "isBlocking", null); +// References the dependencies. +RegisterClass("BABYLON.Texture", Texture); +SerializationHelper._TextureParser = Texture.Parse; + +/** + * A class that renders objects to the currently bound render target. + * This class only renders objects, and is not concerned with the output texture or post-processing. + */ +class ObjectRenderer { + /** + * Use this list to define the list of mesh you want to render. + */ + get renderList() { + return this._renderList; + } + set renderList(value) { + if (this._renderList === value) { + return; + } + if (this._unObserveRenderList) { + this._unObserveRenderList(); + this._unObserveRenderList = null; + } + if (value) { + this._unObserveRenderList = _ObserveArray(value, this._renderListHasChanged); + } + this._renderList = value; + } + /** + * If true, the object renderer will render all objects in linear space (default: false) + */ + get renderInLinearSpace() { + return this._renderInLinearSpace; + } + set renderInLinearSpace(value) { + if (value === this._renderInLinearSpace) { + return; + } + this._renderInLinearSpace = value; + this._scene.markAllMaterialsAsDirty(64); + } + /** + * Friendly name of the object renderer + */ + get name() { + return this._name; + } + set name(value) { + if (this._name === value) { + return; + } + this._name = value; + if (!this._scene) { + return; + } + const engine = this._scene.getEngine(); + for (let i = 0; i < this._renderPassIds.length; ++i) { + const renderPassId = this._renderPassIds[i]; + engine._renderPassNames[renderPassId] = `${this._name}#${i}`; + } + } + /** + * Gets the render pass ids used by the object renderer. + */ + get renderPassIds() { + return this._renderPassIds; + } + /** + * Gets the current value of the refreshId counter + */ + get currentRefreshId() { + return this._currentRefreshId; + } + /** + * Sets a specific material to be used to render a mesh/a list of meshes with this object renderer + * @param mesh mesh or array of meshes + * @param material material or array of materials to use for this render pass. If undefined is passed, no specific material will be used but the regular material instead (mesh.material). It's possible to provide an array of materials to use a different material for each rendering pass. + */ + setMaterialForRendering(mesh, material) { + let meshes; + if (!Array.isArray(mesh)) { + meshes = [mesh]; + } + else { + meshes = mesh; + } + for (let j = 0; j < meshes.length; ++j) { + for (let i = 0; i < this.options.numPasses; ++i) { + meshes[j].setMaterialForRenderPass(this._renderPassIds[i], material !== undefined ? (Array.isArray(material) ? material[i] : material) : undefined); + } + } + } + /** + * Instantiates an object renderer. + * @param name The friendly name of the object renderer + * @param scene The scene the renderer belongs to + * @param options The options used to create the renderer (optional) + */ + constructor(name, scene, options) { + this._unObserveRenderList = null; + this._renderListHasChanged = (_functionName, previousLength) => { + const newLength = this._renderList ? this._renderList.length : 0; + if ((previousLength === 0 && newLength > 0) || newLength === 0) { + this._scene.meshes.forEach((mesh) => { + mesh._markSubMeshesAsLightDirty(); + }); + } + }; + /** + * Define the list of particle systems to render. If not provided, will render all the particle systems of the scene. + * Note that the particle systems are rendered only if renderParticles is set to true. + */ + this.particleSystemList = null; + /** + * Use this function to overload the renderList array at rendering time. + * Return null to render with the current renderList, else return the list of meshes to use for rendering. + * For 2DArray, layerOrFace is the index of the layer that is going to be rendered, else it is the faceIndex of + * the cube (if the RTT is a cube, else layerOrFace=0). + * The renderList passed to the function is the current render list (the one that will be used if the function returns null). + * The length of this list is passed through renderListLength: don't use renderList.length directly because the array can + * hold dummy elements! + */ + this.getCustomRenderList = null; + /** + * Define if particles should be rendered. + */ + this.renderParticles = true; + /** + * Define if sprites should be rendered. + */ + this.renderSprites = false; + /** + * Force checking the layerMask property even if a custom list of meshes is provided (ie. if renderList is not undefined) + */ + this.forceLayerMaskCheck = false; + this._renderInLinearSpace = false; + /** + * An event triggered before rendering the objects + */ + this.onBeforeRenderObservable = new Observable(); + /** + * An event triggered after rendering the objects + */ + this.onAfterRenderObservable = new Observable(); + /** + * An event triggered before the rendering group is processed + */ + this.onBeforeRenderingManagerRenderObservable = new Observable(); + /** + * An event triggered after the rendering group is processed + */ + this.onAfterRenderingManagerRenderObservable = new Observable(); + /** + * An event triggered when fast path rendering is used + */ + this.onFastPathRenderObservable = new Observable(); + this._currentRefreshId = -1; + this._refreshRate = 1; + this._currentApplyByPostProcessSetting = false; + this._currentSceneCamera = null; + this.name = name; + this._scene = scene; + this.renderList = []; + this._renderPassIds = []; + this.options = { + numPasses: 1, + doNotChangeAspectRatio: true, + ...options, + }; + this._createRenderPassId(); + this.renderPassId = this._renderPassIds[0]; + // Rendering groups + this._renderingManager = new RenderingManager(scene); + this._renderingManager._useSceneAutoClearSetup = true; + } + _releaseRenderPassId() { + const engine = this._scene.getEngine(); + for (let i = 0; i < this.options.numPasses; ++i) { + engine.releaseRenderPassId(this._renderPassIds[i]); + } + this._renderPassIds.length = 0; + } + _createRenderPassId() { + this._releaseRenderPassId(); + const engine = this._scene.getEngine(); + for (let i = 0; i < this.options.numPasses; ++i) { + this._renderPassIds[i] = engine.createRenderPassId(`${this.name}#${i}`); + } + } + /** + * Resets the refresh counter of the renderer and start back from scratch. + * Could be useful to re-render if it is setup to render only once. + */ + resetRefreshCounter() { + this._currentRefreshId = -1; + } + /** + * Defines the refresh rate of the rendering or the rendering frequency. + * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... + */ + get refreshRate() { + return this._refreshRate; + } + set refreshRate(value) { + this._refreshRate = value; + this.resetRefreshCounter(); + } + /** + * Indicates if the renderer should render the current frame. + * The output is based on the specified refresh rate. + * @returns true if the renderer should render the current frame + */ + shouldRender() { + if (this._currentRefreshId === -1) { + // At least render once + this._currentRefreshId = 1; + return true; + } + if (this.refreshRate === this._currentRefreshId) { + this._currentRefreshId = 1; + return true; + } + this._currentRefreshId++; + return false; + } + /** + * This function will check if the renderer is ready to render (textures are loaded, shaders are compiled) + * @param viewportWidth defines the width of the viewport + * @param viewportHeight defines the height of the viewport + * @returns true if all required resources are ready + */ + isReadyForRendering(viewportWidth, viewportHeight) { + this.prepareRenderList(); + this.initRender(viewportWidth, viewportHeight); + const isReady = this._checkReadiness(); + this.finishRender(); + return isReady; + } + /** + * Makes sure the list of meshes is ready to be rendered + * You should call this function before "initRender", but if you know the render list is ok, you may call "initRender" directly + */ + prepareRenderList() { + const scene = this._scene; + if (this._waitingRenderList) { + if (!this.renderListPredicate) { + this.renderList = []; + for (let index = 0; index < this._waitingRenderList.length; index++) { + const id = this._waitingRenderList[index]; + const mesh = scene.getMeshById(id); + if (mesh) { + this.renderList.push(mesh); + } + } + } + this._waitingRenderList = undefined; + } + // Is predicate defined? + if (this.renderListPredicate) { + if (this.renderList) { + this.renderList.length = 0; // Clear previous renderList + } + else { + this.renderList = []; + } + const sceneMeshes = this._scene.meshes; + for (let index = 0; index < sceneMeshes.length; index++) { + const mesh = sceneMeshes[index]; + if (this.renderListPredicate(mesh)) { + this.renderList.push(mesh); + } + } + } + this._currentApplyByPostProcessSetting = this._scene.imageProcessingConfiguration.applyByPostProcess; + // we do not use the applyByPostProcess setter to avoid flagging all the materials as "image processing dirty"! + this._scene.imageProcessingConfiguration._applyByPostProcess = !!this._renderInLinearSpace; + } + /** + * This method makes sure everything is setup before "render" can be called + * @param viewportWidth Width of the viewport to render to + * @param viewportHeight Height of the viewport to render to + */ + initRender(viewportWidth, viewportHeight) { + const engine = this._scene.getEngine(); + const camera = this.activeCamera ?? this._scene.activeCamera; + this._currentSceneCamera = this._scene.activeCamera; + if (camera) { + if (camera !== this._scene.activeCamera) { + this._scene.setTransformMatrix(camera.getViewMatrix(), camera.getProjectionMatrix(true)); + this._scene.activeCamera = camera; + } + engine.setViewport(camera.rigParent ? camera.rigParent.viewport : camera.viewport, viewportWidth, viewportHeight); + } + this._defaultRenderListPrepared = false; + } + /** + * This method must be called after the "render" call(s), to complete the rendering process. + */ + finishRender() { + const scene = this._scene; + scene.imageProcessingConfiguration._applyByPostProcess = this._currentApplyByPostProcessSetting; + scene.activeCamera = this._currentSceneCamera; + if (this._currentSceneCamera) { + if (this.activeCamera && this.activeCamera !== scene.activeCamera) { + scene.setTransformMatrix(this._currentSceneCamera.getViewMatrix(), this._currentSceneCamera.getProjectionMatrix(true)); + } + scene.getEngine().setViewport(this._currentSceneCamera.viewport); + } + scene.resetCachedMaterial(); + } + /** + * Renders all the objects (meshes, particles systems, sprites) to the currently bound render target texture. + * @param passIndex defines the pass index to use (default: 0) + * @param skipOnAfterRenderObservable defines a flag to skip raising the onAfterRenderObservable + */ + render(passIndex = 0, skipOnAfterRenderObservable = false) { + const scene = this._scene; + const engine = scene.getEngine(); + const currentRenderPassId = engine.currentRenderPassId; + engine.currentRenderPassId = this._renderPassIds[passIndex]; + this.onBeforeRenderObservable.notifyObservers(passIndex); + const fastPath = engine.snapshotRendering && engine.snapshotRenderingMode === 1; + if (!fastPath) { + // Get the list of meshes to render + let currentRenderList = null; + const defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data; + const defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length; + if (this.getCustomRenderList) { + currentRenderList = this.getCustomRenderList(passIndex, defaultRenderList, defaultRenderListLength); + } + if (!currentRenderList) { + // No custom render list provided, we prepare the rendering for the default list, but check + // first if we did not already performed the preparation before so as to avoid re-doing it several times + if (!this._defaultRenderListPrepared) { + this._prepareRenderingManager(defaultRenderList, defaultRenderListLength, !this.renderList || this.forceLayerMaskCheck); + this._defaultRenderListPrepared = true; + } + currentRenderList = defaultRenderList; + } + else { + // Prepare the rendering for the custom render list provided + this._prepareRenderingManager(currentRenderList, currentRenderList.length, this.forceLayerMaskCheck); + } + this.onBeforeRenderingManagerRenderObservable.notifyObservers(passIndex); + this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites); + this.onAfterRenderingManagerRenderObservable.notifyObservers(passIndex); + } + else { + this.onFastPathRenderObservable.notifyObservers(passIndex); + } + if (!skipOnAfterRenderObservable) { + this.onAfterRenderObservable.notifyObservers(passIndex); + } + engine.currentRenderPassId = currentRenderPassId; + } + /** @internal */ + _checkReadiness() { + const scene = this._scene; + const engine = scene.getEngine(); + const currentRenderPassId = engine.currentRenderPassId; + let returnValue = true; + if (!scene.getViewMatrix()) { + // We probably didn't execute scene.render() yet, so make sure we have a view/projection matrix setup for the scene + scene.updateTransformMatrix(); + } + const numPasses = this.options.numPasses; + for (let passIndex = 0; passIndex < numPasses && returnValue; passIndex++) { + let currentRenderList = null; + const defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data; + const defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length; + engine.currentRenderPassId = this._renderPassIds[passIndex]; + this.onBeforeRenderObservable.notifyObservers(passIndex); + if (this.getCustomRenderList) { + currentRenderList = this.getCustomRenderList(passIndex, defaultRenderList, defaultRenderListLength); + } + if (!currentRenderList) { + currentRenderList = defaultRenderList; + } + if (!this.options.doNotChangeAspectRatio) { + scene.updateTransformMatrix(true); + } + for (let i = 0; i < currentRenderList.length && returnValue; ++i) { + const mesh = currentRenderList[i]; + if (!mesh.isEnabled() || mesh.isBlocked || !mesh.isVisible || !mesh.subMeshes) { + continue; + } + if (this.customIsReadyFunction) { + if (!this.customIsReadyFunction(mesh, this.refreshRate, true)) { + returnValue = false; + continue; + } + } + else if (!mesh.isReady(true)) { + returnValue = false; + continue; + } + } + this.onAfterRenderObservable.notifyObservers(passIndex); + if (numPasses > 1) { + scene.incrementRenderId(); + scene.resetCachedMaterial(); + } + } + const particleSystems = this.particleSystemList || scene.particleSystems; + for (const particleSystem of particleSystems) { + if (!particleSystem.isReady()) { + returnValue = false; + } + } + engine.currentRenderPassId = currentRenderPassId; + return returnValue; + } + _prepareRenderingManager(currentRenderList, currentRenderListLength, checkLayerMask) { + const scene = this._scene; + const camera = scene.activeCamera; // note that at this point, scene.activeCamera == this.activeCamera if defined, because initRender() has been called before + const cameraForLOD = this.cameraForLOD ?? camera; + this._renderingManager.reset(); + const sceneRenderId = scene.getRenderId(); + const currentFrameId = scene.getFrameId(); + for (let meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) { + const mesh = currentRenderList[meshIndex]; + if (mesh && !mesh.isBlocked) { + if (this.customIsReadyFunction) { + if (!this.customIsReadyFunction(mesh, this.refreshRate, false)) { + this.resetRefreshCounter(); + continue; + } + } + else if (!mesh.isReady(this.refreshRate === 0)) { + this.resetRefreshCounter(); + continue; + } + let meshToRender = null; + if (cameraForLOD) { + const meshToRenderAndFrameId = mesh._internalAbstractMeshDataInfo._currentLOD.get(cameraForLOD); + if (!meshToRenderAndFrameId || meshToRenderAndFrameId[1] !== currentFrameId) { + meshToRender = scene.customLODSelector ? scene.customLODSelector(mesh, cameraForLOD) : mesh.getLOD(cameraForLOD); + if (!meshToRenderAndFrameId) { + mesh._internalAbstractMeshDataInfo._currentLOD.set(cameraForLOD, [meshToRender, currentFrameId]); + } + else { + meshToRenderAndFrameId[0] = meshToRender; + meshToRenderAndFrameId[1] = currentFrameId; + } + } + else { + meshToRender = meshToRenderAndFrameId[0]; + } + } + else { + meshToRender = mesh; + } + if (!meshToRender) { + continue; + } + if (meshToRender !== mesh && meshToRender.billboardMode !== 0) { + meshToRender.computeWorldMatrix(); // Compute world matrix if LOD is billboard + } + meshToRender._preActivateForIntermediateRendering(sceneRenderId); + let isMasked; + if (checkLayerMask && camera) { + isMasked = (mesh.layerMask & camera.layerMask) === 0; + } + else { + isMasked = false; + } + if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) { + if (meshToRender !== mesh) { + meshToRender._activate(sceneRenderId, true); + } + if (mesh._activate(sceneRenderId, true) && mesh.subMeshes.length) { + if (!mesh.isAnInstance) { + meshToRender._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = false; + } + else { + if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) { + meshToRender = mesh; + } + } + meshToRender._internalAbstractMeshDataInfo._isActiveIntermediate = true; + scene._prepareSkeleton(meshToRender); + for (let subIndex = 0; subIndex < meshToRender.subMeshes.length; subIndex++) { + const subMesh = meshToRender.subMeshes[subIndex]; + this._renderingManager.dispatch(subMesh, meshToRender); + } + } + mesh._postActivate(); + } + } + } + const particleSystems = this.particleSystemList || scene.particleSystems; + for (let particleIndex = 0; particleIndex < particleSystems.length; particleIndex++) { + const particleSystem = particleSystems[particleIndex]; + const emitter = particleSystem.emitter; + if (!particleSystem.isStarted() || !emitter || (emitter.position && !emitter.isEnabled())) { + continue; + } + this._renderingManager.dispatchParticles(particleSystem); + } + } + /** + * Overrides the default sort function applied in the rendering group to prepare the meshes. + * This allowed control for front to back rendering or reversely depending of the special needs. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param opaqueSortCompareFn The opaque queue comparison function use to sort. + * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. + * @param transparentSortCompareFn The transparent queue comparison function use to sort. + */ + setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { + this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn); + } + /** + * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. + * @param depth Automatically clears depth between groups if true and autoClear is true. + * @param stencil Automatically clears stencil between groups if true and autoClear is true. + */ + setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) { + this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil); + this._renderingManager._useSceneAutoClearSetup = false; + } + /** + * Clones the renderer. + * @returns the cloned renderer + */ + clone() { + const newRenderer = new ObjectRenderer(this.name, this._scene, this.options); + if (this.renderList) { + newRenderer.renderList = this.renderList.slice(0); + } + return newRenderer; + } + /** + * Dispose the renderer and release its associated resources. + */ + dispose() { + const renderList = this.renderList ? this.renderList : this._scene.getActiveMeshes().data; + const renderListLength = this.renderList ? this.renderList.length : this._scene.getActiveMeshes().length; + for (let i = 0; i < renderListLength; i++) { + const mesh = renderList[i]; + if (mesh.getMaterialForRenderPass(this.renderPassId) !== undefined) { + mesh.setMaterialForRenderPass(this.renderPassId, undefined); + } + } + this.onBeforeRenderObservable.clear(); + this.onAfterRenderObservable.clear(); + this.onBeforeRenderingManagerRenderObservable.clear(); + this.onAfterRenderingManagerRenderObservable.clear(); + this.onFastPathRenderObservable.clear(); + this._releaseRenderPassId(); + this.renderList = null; + } + /** @internal */ + _rebuild() { + if (this.refreshRate === ObjectRenderer.REFRESHRATE_RENDER_ONCE) { + this.refreshRate = ObjectRenderer.REFRESHRATE_RENDER_ONCE; + } + } + /** + * Clear the info related to rendering groups preventing retention point in material dispose. + */ + freeRenderingGroups() { + if (this._renderingManager) { + this._renderingManager.freeRenderingGroups(); + } + } +} +/** + * Objects will only be rendered once which can be useful to improve performance if everything in your render is static for instance. + */ +ObjectRenderer.REFRESHRATE_RENDER_ONCE = 0; +/** + * Objects will be rendered every frame and is recommended for dynamic contents. + */ +ObjectRenderer.REFRESHRATE_RENDER_ONEVERYFRAME = 1; +/** + * Objects will be rendered every 2 frames which could be enough if your dynamic objects are not + * the central point of your effect and can save a lot of performances. + */ +ObjectRenderer.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2; + +/** + * Sets a depth stencil texture from a render target on the engine to be used in the shader. + * @param channel Name of the sampler variable. + * @param texture Texture to set. + */ +Effect.prototype.setDepthStencilTexture = function (channel, texture) { + this._engine.setDepthStencilTexture(this._samplers[channel], this._uniforms[channel], texture, channel); +}; +/** + * This Helps creating a texture that will be created from a camera in your scene. + * It is basically a dynamic texture that could be used to create special effects for instance. + * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines... + */ +class RenderTargetTexture extends Texture { + /** + * Use this predicate to dynamically define the list of mesh you want to render. + * If set, the renderList property will be overwritten. + */ + get renderListPredicate() { + return this._objectRenderer.renderListPredicate; + } + set renderListPredicate(value) { + this._objectRenderer.renderListPredicate = value; + } + /** + * Use this list to define the list of mesh you want to render. + */ + get renderList() { + return this._objectRenderer.renderList; + } + set renderList(value) { + this._objectRenderer.renderList = value; + } + /** + * Define the list of particle systems to render in the texture. If not provided, will render all the particle systems of the scene. + * Note that the particle systems are rendered only if renderParticles is set to true. + */ + get particleSystemList() { + return this._objectRenderer.particleSystemList; + } + set particleSystemList(value) { + this._objectRenderer.particleSystemList = value; + } + /** + * Use this function to overload the renderList array at rendering time. + * Return null to render with the current renderList, else return the list of meshes to use for rendering. + * For 2DArray RTT, layerOrFace is the index of the layer that is going to be rendered, else it is the faceIndex of + * the cube (if the RTT is a cube, else layerOrFace=0). + * The renderList passed to the function is the current render list (the one that will be used if the function returns null). + * The length of this list is passed through renderListLength: don't use renderList.length directly because the array can + * hold dummy elements! + */ + get getCustomRenderList() { + return this._objectRenderer.getCustomRenderList; + } + set getCustomRenderList(value) { + this._objectRenderer.getCustomRenderList = value; + } + /** + * Define if particles should be rendered in your texture (default: true). + */ + get renderParticles() { + return this._objectRenderer.renderParticles; + } + set renderParticles(value) { + this._objectRenderer.renderParticles = value; + } + /** + * Define if sprites should be rendered in your texture (default: false). + */ + get renderSprites() { + return this._objectRenderer.renderSprites; + } + set renderSprites(value) { + this._objectRenderer.renderSprites = value; + } + /** + * Force checking the layerMask property even if a custom list of meshes is provided (ie. if renderList is not undefined) (default: false). + */ + get forceLayerMaskCheck() { + return this._objectRenderer.forceLayerMaskCheck; + } + set forceLayerMaskCheck(value) { + this._objectRenderer.forceLayerMaskCheck = value; + } + /** + * Define the camera used to render the texture. + */ + get activeCamera() { + return this._objectRenderer.activeCamera; + } + set activeCamera(value) { + this._objectRenderer.activeCamera = value; + } + /** + * Define the camera used to calculate the LOD of the objects. + * If not defined, activeCamera will be used. If not defined nor activeCamera, scene's active camera will be used. + */ + get cameraForLOD() { + return this._objectRenderer.cameraForLOD; + } + set cameraForLOD(value) { + this._objectRenderer.cameraForLOD = value; + } + /** + * If true, all objects will be rendered in linear space (default: false) + */ + get renderInLinearSpace() { + return this._objectRenderer.renderInLinearSpace; + } + set renderInLinearSpace(value) { + this._objectRenderer.renderInLinearSpace = value; + } + /** + * Override the mesh isReady function with your own one. + */ + get customIsReadyFunction() { + return this._objectRenderer.customIsReadyFunction; + } + set customIsReadyFunction(value) { + this._objectRenderer.customIsReadyFunction = value; + } + /** + * Override the render function of the texture with your own one. + */ + get customRenderFunction() { + return this._objectRenderer.customRenderFunction; + } + set customRenderFunction(value) { + this._objectRenderer.customRenderFunction = value; + } + /** + * Post-processes for this render target + */ + get postProcesses() { + return this._postProcesses; + } + get _prePassEnabled() { + return !!this._prePassRenderTarget && this._prePassRenderTarget.enabled; + } + /** + * Set a after unbind callback in the texture. + * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended. + */ + set onAfterUnbind(callback) { + if (this._onAfterUnbindObserver) { + this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver); + } + this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback); + } + /** + * An event triggered before rendering the texture + */ + get onBeforeRenderObservable() { + return this._objectRenderer.onBeforeRenderObservable; + } + /** + * Set a before render callback in the texture. + * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended. + */ + set onBeforeRender(callback) { + if (this._onBeforeRenderObserver) { + this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); + } + this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); + } + /** + * An event triggered after rendering the texture + */ + get onAfterRenderObservable() { + return this._objectRenderer.onAfterRenderObservable; + } + /** + * Set a after render callback in the texture. + * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended. + */ + set onAfterRender(callback) { + if (this._onAfterRenderObserver) { + this.onAfterRenderObservable.remove(this._onAfterRenderObserver); + } + this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); + } + /** + * Set a clear callback in the texture. + * This has been kept for backward compatibility and use of onClearObservable is recommended. + */ + set onClear(callback) { + if (this._onClearObserver) { + this.onClearObservable.remove(this._onClearObserver); + } + this._onClearObserver = this.onClearObservable.add(callback); + } + /** @internal */ + get _waitingRenderList() { + return this._objectRenderer._waitingRenderList; + } + /** @internal */ + set _waitingRenderList(value) { + this._objectRenderer._waitingRenderList = value; + } + /** + * Current render pass id of the render target texture. Note it can change over the rendering as there's a separate id for each face of a cube / each layer of an array layer! + */ + get renderPassId() { + return this._objectRenderer.renderPassId; + } + /** + * Gets the render pass ids used by the render target texture. For a single render target the array length will be 1, for a cube texture it will be 6 and for + * a 2D texture array it will return an array of ids the size of the 2D texture array + */ + get renderPassIds() { + return this._objectRenderer.renderPassIds; + } + /** + * Gets the current value of the refreshId counter + */ + get currentRefreshId() { + return this._objectRenderer.currentRefreshId; + } + /** + * Sets a specific material to be used to render a mesh/a list of meshes in this render target texture + * @param mesh mesh or array of meshes + * @param material material or array of materials to use for this render pass. If undefined is passed, no specific material will be used but the regular material instead (mesh.material). It's possible to provide an array of materials to use a different material for each rendering in the case of a cube texture (6 rendering) and a 2D texture array (as many rendering as the length of the array) + */ + setMaterialForRendering(mesh, material) { + this._objectRenderer.setMaterialForRendering(mesh, material); + } + /** + * Define if the texture has multiple draw buffers or if false a single draw buffer. + */ + get isMulti() { + return this._renderTarget?.isMulti ?? false; + } + /** + * Gets render target creation options that were used. + */ + get renderTargetOptions() { + return this._renderTargetOptions; + } + /** + * Gets the render target wrapper associated with this render target + */ + get renderTarget() { + return this._renderTarget; + } + _onRatioRescale() { + if (this._sizeRatio) { + this.resize(this._initialSizeParameter); + } + } + /** + * Gets or sets the size of the bounding box associated with the texture (when in cube mode) + * When defined, the cubemap will switch to local mode + * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity + * @example https://www.babylonjs-playground.com/#RNASML + */ + set boundingBoxSize(value) { + if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { + return; + } + this._boundingBoxSize = value; + const scene = this.getScene(); + if (scene) { + scene.markAllMaterialsAsDirty(1); + } + } + get boundingBoxSize() { + return this._boundingBoxSize; + } + /** + * In case the RTT has been created with a depth texture, get the associated + * depth texture. + * Otherwise, return null. + */ + get depthStencilTexture() { + return this._renderTarget?._depthStencilTexture ?? null; + } + /** @internal */ + constructor(name, size, scene, generateMipMaps = false, doNotChangeAspectRatio = true, type = 0, isCube = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false, format = 5, delayAllocation = false, samples, creationFlags, noColorAttachment = false, useSRGBBuffer = false) { + let colorAttachment = undefined; + let gammaSpace = true; + let existingObjectRenderer = undefined; + if (typeof generateMipMaps === "object") { + const options = generateMipMaps; + generateMipMaps = !!options.generateMipMaps; + doNotChangeAspectRatio = options.doNotChangeAspectRatio ?? true; + type = options.type ?? 0; + isCube = !!options.isCube; + samplingMode = options.samplingMode ?? Texture.TRILINEAR_SAMPLINGMODE; + generateDepthBuffer = options.generateDepthBuffer ?? true; + generateStencilBuffer = !!options.generateStencilBuffer; + isMulti = !!options.isMulti; + format = options.format ?? 5; + delayAllocation = !!options.delayAllocation; + samples = options.samples; + creationFlags = options.creationFlags; + noColorAttachment = !!options.noColorAttachment; + useSRGBBuffer = !!options.useSRGBBuffer; + colorAttachment = options.colorAttachment; + gammaSpace = options.gammaSpace ?? gammaSpace; + existingObjectRenderer = options.existingObjectRenderer; + } + super(null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format); + /** + * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture. + */ + this.ignoreCameraViewport = false; + /** + * An event triggered when the texture is unbind. + */ + this.onBeforeBindObservable = new Observable(); + /** + * An event triggered when the texture is unbind. + */ + this.onAfterUnbindObservable = new Observable(); + /** + * An event triggered after the texture clear + */ + this.onClearObservable = new Observable(); + /** + * An event triggered when the texture is resized. + */ + this.onResizeObservable = new Observable(); + /** @internal */ + this._cleared = false; + /** + * Skip the initial clear of the rtt at the beginning of the frame render loop + */ + this.skipInitialClear = false; + this._samples = 1; + this._canRescale = true; + this._renderTarget = null; + this._dontDisposeObjectRenderer = false; + /** + * Gets or sets the center of the bounding box associated with the texture (when in cube mode) + * It must define where the camera used to render the texture is set + */ + this.boundingBoxPosition = Vector3.Zero(); + /** @internal */ + this._disableEngineStages = false; // TODO: remove this when the shadow generator task (frame graph) is reworked (see https://github.com/BabylonJS/Babylon.js/pull/15962#discussion_r1874417607) + this._dumpToolsLoading = false; + scene = this.getScene(); + if (!scene) { + return; + } + const engine = this.getScene().getEngine(); + this._gammaSpace = gammaSpace; + this._coordinatesMode = Texture.PROJECTION_MODE; + this.name = name; + this.isRenderTarget = true; + this._initialSizeParameter = size; + this._dontDisposeObjectRenderer = !!existingObjectRenderer; + this._processSizeParameter(size); + this._objectRenderer = + existingObjectRenderer ?? + new ObjectRenderer(name, scene, { + numPasses: isCube ? 6 : this.getRenderLayers() || 1, + doNotChangeAspectRatio, + }); + this._onBeforeRenderingManagerRenderObserver = this._objectRenderer.onBeforeRenderingManagerRenderObservable.add(() => { + // Before clear + if (!this._disableEngineStages) { + for (const step of this._scene._beforeRenderTargetClearStage) { + step.action(this, this._currentFaceIndex, this._currentLayer); + } + } + // Clear + if (this.onClearObservable.hasObservers()) { + this.onClearObservable.notifyObservers(engine); + } + else if (!this.skipInitialClear) { + engine.clear(this.clearColor || this._scene.clearColor, true, true, true); + } + if (!this._doNotChangeAspectRatio) { + this._scene.updateTransformMatrix(true); + } + // Before Camera Draw + if (!this._disableEngineStages) { + for (const step of this._scene._beforeRenderTargetDrawStage) { + step.action(this, this._currentFaceIndex, this._currentLayer); + } + } + }); + this._onAfterRenderingManagerRenderObserver = this._objectRenderer.onAfterRenderingManagerRenderObservable.add(() => { + // After Camera Draw + if (!this._disableEngineStages) { + for (const step of this._scene._afterRenderTargetDrawStage) { + step.action(this, this._currentFaceIndex, this._currentLayer); + } + } + const saveGenerateMipMaps = this._texture?.generateMipMaps ?? false; + if (this._texture) { + this._texture.generateMipMaps = false; // if left true, the mipmaps will be generated (if this._texture.generateMipMaps = true) when the first post process binds its own RTT: by doing so it will unbind the current RTT, + // which will trigger a mipmap generation. We don't want this because it's a wasted work, we will do an unbind of the current RTT at the end of the process (see unbindFrameBuffer) which will + // trigger the generation of the final mipmaps + } + if (this._postProcessManager) { + this._postProcessManager._finalizeFrame(false, this._renderTarget ?? undefined, this._currentFaceIndex, this._postProcesses, this.ignoreCameraViewport); + } + else if (this._currentUseCameraPostProcess) { + this._scene.postProcessManager._finalizeFrame(false, this._renderTarget ?? undefined, this._currentFaceIndex); + } + if (!this._disableEngineStages) { + for (const step of this._scene._afterRenderTargetPostProcessStage) { + step.action(this, this._currentFaceIndex, this._currentLayer); + } + } + if (this._texture) { + this._texture.generateMipMaps = saveGenerateMipMaps; + } + if (!this._doNotChangeAspectRatio) { + this._scene.updateTransformMatrix(true); + } + // Dump ? + if (this._currentDumpForDebug) { + if (!this._dumpTools) { + Logger.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project"); + } + else { + this._dumpTools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine); + } + } + }); + this._onFastPathRenderObserver = this._objectRenderer.onFastPathRenderObservable.add(() => { + if (this.onClearObservable.hasObservers()) { + this.onClearObservable.notifyObservers(engine); + } + else { + if (!this.skipInitialClear) { + engine.clear(this.clearColor || this._scene.clearColor, true, true, true); + } + } + }); + this._resizeObserver = engine.onResizeObservable.add(() => { }); + this._generateMipMaps = generateMipMaps ? true : false; + this._doNotChangeAspectRatio = doNotChangeAspectRatio; + if (isMulti) { + return; + } + this._renderTargetOptions = { + generateMipMaps: generateMipMaps, + type: type, + format: this._format ?? undefined, + samplingMode: this.samplingMode, + generateDepthBuffer: generateDepthBuffer, + generateStencilBuffer: generateStencilBuffer, + samples, + creationFlags, + noColorAttachment: noColorAttachment, + useSRGBBuffer, + colorAttachment: colorAttachment, + label: this.name, + }; + if (this.samplingMode === Texture.NEAREST_SAMPLINGMODE) { + this.wrapU = Texture.CLAMP_ADDRESSMODE; + this.wrapV = Texture.CLAMP_ADDRESSMODE; + } + if (!delayAllocation) { + if (isCube) { + this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions); + this.coordinatesMode = Texture.INVCUBIC_MODE; + this._textureMatrix = Matrix.Identity(); + } + else { + this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions); + } + this._texture = this._renderTarget.texture; + if (samples !== undefined) { + this.samples = samples; + } + } + } + /** + * Creates a depth stencil texture. + * This is only available in WebGL 2 or with the depth texture extension available. + * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode (default: 0) + * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture (default: true) + * @param generateStencil Specifies whether or not a stencil should be allocated in the texture (default: false) + * @param samples sample count of the depth/stencil texture (default: 1) + * @param format format of the depth texture (default: 14) + * @param label defines the label of the texture (for debugging purpose) + */ + createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) { + this._renderTarget?.createDepthStencilTexture(comparisonFunction, bilinearFiltering, generateStencil, samples, format, label); + } + _processSizeParameter(size) { + if (size.ratio) { + this._sizeRatio = size.ratio; + const engine = this._getEngine(); + this._size = { + width: this._bestReflectionRenderTargetDimension(engine.getRenderWidth(), this._sizeRatio), + height: this._bestReflectionRenderTargetDimension(engine.getRenderHeight(), this._sizeRatio), + }; + } + else { + this._size = size; + } + } + /** + * Define the number of samples to use in case of MSAA. + * It defaults to one meaning no MSAA has been enabled. + */ + get samples() { + return this._renderTarget?.samples ?? this._samples; + } + set samples(value) { + if (this._renderTarget) { + this._samples = this._renderTarget.setSamples(value); + } + } + /** + * Adds a post process to the render target rendering passes. + * @param postProcess define the post process to add + */ + addPostProcess(postProcess) { + if (!this._postProcessManager) { + const scene = this.getScene(); + if (!scene) { + return; + } + this._postProcessManager = new PostProcessManager(scene); + this._postProcesses = new Array(); + } + this._postProcesses.push(postProcess); + this._postProcesses[0].autoClear = false; + } + /** + * Clear all the post processes attached to the render target + * @param dispose define if the cleared post processes should also be disposed (false by default) + */ + clearPostProcesses(dispose = false) { + if (!this._postProcesses) { + return; + } + if (dispose) { + for (const postProcess of this._postProcesses) { + postProcess.dispose(); + } + } + this._postProcesses = []; + } + /** + * Remove one of the post process from the list of attached post processes to the texture + * @param postProcess define the post process to remove from the list + */ + removePostProcess(postProcess) { + if (!this._postProcesses) { + return; + } + const index = this._postProcesses.indexOf(postProcess); + if (index === -1) { + return; + } + this._postProcesses.splice(index, 1); + if (this._postProcesses.length > 0) { + this._postProcesses[0].autoClear = false; + } + } + /** + * Resets the refresh counter of the texture and start bak from scratch. + * Could be useful to regenerate the texture if it is setup to render only once. + */ + resetRefreshCounter() { + this._objectRenderer.resetRefreshCounter(); + } + /** + * Define the refresh rate of the texture or the rendering frequency. + * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... + */ + get refreshRate() { + return this._objectRenderer.refreshRate; + } + set refreshRate(value) { + this._objectRenderer.refreshRate = value; + } + /** @internal */ + _shouldRender() { + return this._objectRenderer.shouldRender(); + } + /** + * Gets the actual render size of the texture. + * @returns the width of the render size + */ + getRenderSize() { + return this.getRenderWidth(); + } + /** + * Gets the actual render width of the texture. + * @returns the width of the render size + */ + getRenderWidth() { + if (this._size.width) { + return this._size.width; + } + return this._size; + } + /** + * Gets the actual render height of the texture. + * @returns the height of the render size + */ + getRenderHeight() { + if (this._size.width) { + return this._size.height; + } + return this._size; + } + /** + * Gets the actual number of layers of the texture or, in the case of a 3D texture, return the depth. + * @returns the number of layers + */ + getRenderLayers() { + const layers = this._size.layers; + if (layers) { + return layers; + } + const depth = this._size.depth; + if (depth) { + return depth; + } + return 0; + } + /** + * Don't allow this render target texture to rescale. Mainly used to prevent rescaling by the scene optimizer. + */ + disableRescaling() { + this._canRescale = false; + } + /** + * Get if the texture can be rescaled or not. + */ + get canRescale() { + return this._canRescale; + } + /** + * Resize the texture using a ratio. + * @param ratio the ratio to apply to the texture size in order to compute the new target size + */ + scale(ratio) { + const newSize = Math.max(1, this.getRenderSize() * ratio); + this.resize(newSize); + } + /** + * Get the texture reflection matrix used to rotate/transform the reflection. + * @returns the reflection matrix + */ + getReflectionTextureMatrix() { + if (this.isCube) { + return this._textureMatrix; + } + return super.getReflectionTextureMatrix(); + } + /** + * Resize the texture to a new desired size. + * Be careful as it will recreate all the data in the new texture. + * @param size Define the new size. It can be: + * - a number for squared texture, + * - an object containing { width: number, height: number } + * - or an object containing a ratio { ratio: number } + */ + resize(size) { + const wasCube = this.isCube; + this._renderTarget?.dispose(); + this._renderTarget = null; + const scene = this.getScene(); + if (!scene) { + return; + } + this._processSizeParameter(size); + if (wasCube) { + this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions); + } + else { + this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions); + } + this._texture = this._renderTarget.texture; + if (this._renderTargetOptions.samples !== undefined) { + this.samples = this._renderTargetOptions.samples; + } + if (this.onResizeObservable.hasObservers()) { + this.onResizeObservable.notifyObservers(this); + } + } + /** + * Renders all the objects from the render list into the texture. + * @param useCameraPostProcess Define if camera post processes should be used during the rendering + * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose + */ + render(useCameraPostProcess = false, dumpForDebug = false) { + this._render(useCameraPostProcess, dumpForDebug); + } + /** + * This function will check if the render target texture can be rendered (textures are loaded, shaders are compiled) + * @returns true if all required resources are ready + */ + isReadyForRendering() { + if (!this._dumpToolsLoading) { + this._dumpToolsLoading = true; + // avoid a static import to allow ignoring the import in some cases + Promise.resolve().then(() => dumpTools).then((module) => (this._dumpTools = module)); + } + this._objectRenderer.prepareRenderList(); + this.onBeforeBindObservable.notifyObservers(this); + this._objectRenderer.initRender(this.getRenderWidth(), this.getRenderHeight()); + const isReady = this._objectRenderer._checkReadiness(); + this.onAfterUnbindObservable.notifyObservers(this); + this._objectRenderer.finishRender(); + return isReady; + } + _render(useCameraPostProcess = false, dumpForDebug = false) { + const scene = this.getScene(); + if (!scene) { + return; + } + if (this.useCameraPostProcesses !== undefined) { + useCameraPostProcess = this.useCameraPostProcesses; + } + this._objectRenderer.prepareRenderList(); + this.onBeforeBindObservable.notifyObservers(this); + this._objectRenderer.initRender(this.getRenderWidth(), this.getRenderHeight()); + if ((this.is2DArray || this.is3D) && !this.isMulti) { + for (let layer = 0; layer < this.getRenderLayers(); layer++) { + this._renderToTarget(0, useCameraPostProcess, dumpForDebug, layer); + scene.incrementRenderId(); + scene.resetCachedMaterial(); + } + } + else if (this.isCube && !this.isMulti) { + for (let face = 0; face < 6; face++) { + this._renderToTarget(face, useCameraPostProcess, dumpForDebug); + scene.incrementRenderId(); + scene.resetCachedMaterial(); + } + } + else { + this._renderToTarget(0, useCameraPostProcess, dumpForDebug); + } + this.onAfterUnbindObservable.notifyObservers(this); + this._objectRenderer.finishRender(); + } + _bestReflectionRenderTargetDimension(renderDimension, scale) { + const minimum = 128; + const x = renderDimension * scale; + const curved = NearestPOT(x + (minimum * minimum) / (minimum + x)); + // Ensure we don't exceed the render dimension (while staying POT) + return Math.min(FloorPOT(renderDimension), curved); + } + /** + * @internal + * @param faceIndex face index to bind to if this is a cubetexture + * @param layer defines the index of the texture to bind in the array + */ + _bindFrameBuffer(faceIndex = 0, layer = 0) { + const scene = this.getScene(); + if (!scene) { + return; + } + const engine = scene.getEngine(); + if (this._renderTarget) { + engine.bindFramebuffer(this._renderTarget, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, 0, layer); + } + } + _unbindFrameBuffer(engine, faceIndex) { + if (!this._renderTarget) { + return; + } + engine.unBindFramebuffer(this._renderTarget, this.isCube, () => { + this.onAfterRenderObservable.notifyObservers(faceIndex); + }); + } + /** + * @internal + */ + _prepareFrame(scene, faceIndex, layer, useCameraPostProcess) { + if (this._postProcessManager) { + if (!this._prePassEnabled) { + this._postProcessManager._prepareFrame(this._texture, this._postProcesses); + } + } + else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) { + this._bindFrameBuffer(faceIndex, layer); + } + } + _renderToTarget(faceIndex, useCameraPostProcess, dumpForDebug, layer = 0) { + const scene = this.getScene(); + if (!scene) { + return; + } + const engine = scene.getEngine(); + this._currentFaceIndex = faceIndex; + this._currentLayer = layer; + this._currentUseCameraPostProcess = useCameraPostProcess; + this._currentDumpForDebug = dumpForDebug; + this._prepareFrame(scene, faceIndex, layer, useCameraPostProcess); + engine._debugPushGroup?.(`render to face #${faceIndex} layer #${layer}`, 2); + this._objectRenderer.render(faceIndex + layer, true); // only faceIndex or layer (if any) will be different from 0 (we don't support array of cubes), so it's safe to add them to get the pass index + engine._debugPopGroup?.(2); + this._unbindFrameBuffer(engine, faceIndex); + if (this._texture && this.isCube && faceIndex === 5) { + engine.generateMipMapsForCubemap(this._texture, true); + } + } + /** + * Overrides the default sort function applied in the rendering group to prepare the meshes. + * This allowed control for front to back rendering or reversely depending of the special needs. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param opaqueSortCompareFn The opaque queue comparison function use to sort. + * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. + * @param transparentSortCompareFn The transparent queue comparison function use to sort. + */ + setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { + this._objectRenderer.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn); + } + /** + * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. + */ + setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) { + this._objectRenderer.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); + } + /** + * Clones the texture. + * @returns the cloned texture + */ + clone() { + const textureSize = this.getSize(); + const newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer, undefined, this._renderTargetOptions.format, undefined, this._renderTargetOptions.samples); + // Base texture + newTexture.hasAlpha = this.hasAlpha; + newTexture.level = this.level; + // RenderTarget Texture + newTexture.coordinatesMode = this.coordinatesMode; + if (this.renderList) { + newTexture.renderList = this.renderList.slice(0); + } + return newTexture; + } + /** + * Serialize the texture to a JSON representation we can easily use in the respective Parse function. + * @returns The JSON representation of the texture + */ + serialize() { + if (!this.name) { + return null; + } + const serializationObject = super.serialize(); + serializationObject.renderTargetSize = this.getRenderSize(); + serializationObject.renderList = []; + if (this.renderList) { + for (let index = 0; index < this.renderList.length; index++) { + serializationObject.renderList.push(this.renderList[index].id); + } + } + return serializationObject; + } + /** + * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore + */ + disposeFramebufferObjects() { + this._renderTarget?.dispose(true); + } + /** + * Release and destroy the underlying lower level texture aka internalTexture. + */ + releaseInternalTexture() { + this._renderTarget?.releaseTextures(); + this._texture = null; + } + /** + * Dispose the texture and release its associated resources. + */ + dispose() { + this.onResizeObservable.clear(); + this.onClearObservable.clear(); + this.onAfterUnbindObservable.clear(); + this.onBeforeBindObservable.clear(); + if (this._postProcessManager) { + this._postProcessManager.dispose(); + this._postProcessManager = null; + } + if (this._prePassRenderTarget) { + this._prePassRenderTarget.dispose(); + } + this._objectRenderer.onBeforeRenderingManagerRenderObservable.remove(this._onBeforeRenderingManagerRenderObserver); + this._objectRenderer.onAfterRenderingManagerRenderObservable.remove(this._onAfterRenderingManagerRenderObserver); + this._objectRenderer.onFastPathRenderObservable.remove(this._onFastPathRenderObserver); + if (!this._dontDisposeObjectRenderer) { + this._objectRenderer.dispose(); + } + this.clearPostProcesses(true); + if (this._resizeObserver) { + this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver); + this._resizeObserver = null; + } + // Remove from custom render targets + const scene = this.getScene(); + if (!scene) { + return; + } + let index = scene.customRenderTargets.indexOf(this); + if (index >= 0) { + scene.customRenderTargets.splice(index, 1); + } + for (const camera of scene.cameras) { + index = camera.customRenderTargets.indexOf(this); + if (index >= 0) { + camera.customRenderTargets.splice(index, 1); + } + } + this._renderTarget?.dispose(); + this._renderTarget = null; + this._texture = null; + super.dispose(); + } + /** @internal */ + _rebuild() { + this._objectRenderer._rebuild(); + if (this._postProcessManager) { + this._postProcessManager._rebuild(); + } + } + /** + * Clear the info related to rendering groups preventing retention point in material dispose. + */ + freeRenderingGroups() { + this._objectRenderer.freeRenderingGroups(); + } + /** + * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1) + * @returns the view count + */ + getViewCount() { + return 1; + } +} +/** + * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance. + */ +RenderTargetTexture.REFRESHRATE_RENDER_ONCE = ObjectRenderer.REFRESHRATE_RENDER_ONCE; +/** + * The texture will be rendered every frame and is recommended for dynamic contents. + */ +RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = ObjectRenderer.REFRESHRATE_RENDER_ONEVERYFRAME; +/** + * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not + * the central point of your effect and can save a lot of performances. + */ +RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = ObjectRenderer.REFRESHRATE_RENDER_ONEVERYTWOFRAMES; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +Texture._CreateRenderTargetTexture = (name, renderTargetSize, scene, generateMipMaps, creationFlags) => { + return new RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps); +}; + +// Do not edit. +const name$8h = "postprocessVertexShader"; +const shader$8g = `attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$8h]) { + ShaderStore.ShadersStore[name$8h] = shader$8g; +} +/** @internal */ +const postprocessVertexShader = { name: name$8h, shader: shader$8g }; + +const postprocess_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + postprocessVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Fullscreen quad buffers by default. +const defaultOptions = { + positions: [1, 1, -1, 1, -1, -1, 1, -1], + indices: [0, 1, 2, 0, 2, 3], +}; +/** + * Helper class to render one or more effects. + * You can access the previous rendering in your shader by declaring a sampler named textureSampler + */ +class EffectRenderer { + /** + * Creates an effect renderer + * @param engine the engine to use for rendering + * @param options defines the options of the effect renderer + */ + constructor(engine, options = defaultOptions) { + this._fullscreenViewport = new Viewport(0, 0, 1, 1); + const positions = options.positions ?? defaultOptions.positions; + const indices = options.indices ?? defaultOptions.indices; + this.engine = engine; + this._vertexBuffers = { + [VertexBuffer.PositionKind]: new VertexBuffer(engine, positions, VertexBuffer.PositionKind, false, false, 2), + }; + this._indexBuffer = engine.createIndexBuffer(indices); + this._onContextRestoredObserver = engine.onContextRestoredObservable.add(() => { + this._indexBuffer = engine.createIndexBuffer(indices); + for (const key in this._vertexBuffers) { + const vertexBuffer = this._vertexBuffers[key]; + vertexBuffer._rebuild(); + } + }); + } + /** + * Sets the current viewport in normalized coordinates 0-1 + * @param viewport Defines the viewport to set (defaults to 0 0 1 1) + */ + setViewport(viewport = this._fullscreenViewport) { + this.engine.setViewport(viewport); + } + /** + * Binds the embedded attributes buffer to the effect. + * @param effect Defines the effect to bind the attributes for + */ + bindBuffers(effect) { + this.engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); + } + /** + * Sets the current effect wrapper to use during draw. + * The effect needs to be ready before calling this api. + * This also sets the default full screen position attribute. + * @param effectWrapper Defines the effect to draw with + */ + applyEffectWrapper(effectWrapper) { + this.engine.setState(true); + this.engine.depthCullingState.depthTest = false; + this.engine.stencilState.stencilTest = false; + this.engine.enableEffect(effectWrapper.drawWrapper); + this.bindBuffers(effectWrapper.effect); + effectWrapper.onApplyObservable.notifyObservers({}); + } + /** + * Saves engine states + */ + saveStates() { + this._savedStateDepthTest = this.engine.depthCullingState.depthTest; + this._savedStateStencilTest = this.engine.stencilState.stencilTest; + } + /** + * Restores engine states + */ + restoreStates() { + this.engine.depthCullingState.depthTest = this._savedStateDepthTest; + this.engine.stencilState.stencilTest = this._savedStateStencilTest; + } + /** + * Draws a full screen quad. + */ + draw() { + this.engine.drawElementsType(0, 0, 6); + } + _isRenderTargetTexture(texture) { + return texture.renderTarget !== undefined; + } + /** + * renders one or more effects to a specified texture + * @param effectWrapper the effect to renderer + * @param outputTexture texture to draw to, if null it will render to the currently bound frame buffer + */ + render(effectWrapper, outputTexture = null) { + // Ensure effect is ready + if (!effectWrapper.effect.isReady()) { + return; + } + this.saveStates(); + // Reset state + this.setViewport(); + const out = outputTexture === null ? null : this._isRenderTargetTexture(outputTexture) ? outputTexture.renderTarget : outputTexture; + if (out) { + this.engine.bindFramebuffer(out); + } + this.applyEffectWrapper(effectWrapper); + this.draw(); + if (out) { + this.engine.unBindFramebuffer(out); + } + this.restoreStates(); + } + /** + * Disposes of the effect renderer + */ + dispose() { + const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind]; + if (vertexBuffer) { + vertexBuffer.dispose(); + delete this._vertexBuffers[VertexBuffer.PositionKind]; + } + if (this._indexBuffer) { + this.engine._releaseBuffer(this._indexBuffer); + } + if (this._onContextRestoredObserver) { + this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver); + this._onContextRestoredObserver = null; + } + } +} +/** + * Wraps an effect to be used for rendering + */ +class EffectWrapper { + /** + * Registers a shader code processing with an effect wrapper name. + * @param effectWrapperName name of the effect wrapper. Use null for the fallback shader code processing. This is the shader code processing that will be used in case no specific shader code processing has been associated to an effect wrapper name + * @param customShaderCodeProcessing shader code processing to associate to the effect wrapper name + */ + static RegisterShaderCodeProcessing(effectWrapperName, customShaderCodeProcessing) { + if (!customShaderCodeProcessing) { + delete EffectWrapper._CustomShaderCodeProcessing[effectWrapperName ?? ""]; + return; + } + EffectWrapper._CustomShaderCodeProcessing[effectWrapperName ?? ""] = customShaderCodeProcessing; + } + static _GetShaderCodeProcessing(effectWrapperName) { + return EffectWrapper._CustomShaderCodeProcessing[effectWrapperName] ?? EffectWrapper._CustomShaderCodeProcessing[""]; + } + /** + * Gets or sets the name of the effect wrapper + */ + get name() { + return this.options.name; + } + set name(value) { + this.options.name = value; + } + /** + * Get a value indicating if the effect is ready to be used + * @returns true if the post-process is ready (shader is compiled) + */ + isReady() { + return this._drawWrapper.effect?.isReady() ?? false; + } + /** + * Get the draw wrapper associated with the effect wrapper + * @returns the draw wrapper associated with the effect wrapper + */ + get drawWrapper() { + return this._drawWrapper; + } + /** + * The underlying effect + */ + get effect() { + return this._drawWrapper.effect; + } + set effect(effect) { + this._drawWrapper.effect = effect; + } + /** + * Creates an effect to be rendered + * @param creationOptions options to create the effect + */ + constructor(creationOptions) { + /** + * Type of alpha mode to use when applying the effect (default: Engine.ALPHA_DISABLE). Used only if useAsPostProcess is true. + */ + this.alphaMode = 0; + /** + * Executed when the effect is created + * @returns effect that was created for this effect wrapper + */ + this.onEffectCreatedObservable = new Observable(undefined, true); + /** + * Event that is fired (only when the EffectWrapper is used with an EffectRenderer) right before the effect is drawn (should be used to update uniforms) + */ + this.onApplyObservable = new Observable(); + this._shadersLoaded = false; + /** @internal */ + this._webGPUReady = false; + this._importPromises = []; + this.options = { + ...creationOptions, + name: creationOptions.name || "effectWrapper", + engine: creationOptions.engine, + uniforms: creationOptions.uniforms || creationOptions.uniformNames || [], + uniformNames: undefined, + samplers: creationOptions.samplers || creationOptions.samplerNames || [], + samplerNames: undefined, + attributeNames: creationOptions.attributeNames || ["position"], + uniformBuffers: creationOptions.uniformBuffers || [], + defines: creationOptions.defines || "", + useShaderStore: creationOptions.useShaderStore || false, + vertexUrl: creationOptions.vertexUrl || creationOptions.vertexShader || "postprocess", + vertexShader: undefined, + fragmentShader: creationOptions.fragmentShader || "pass", + indexParameters: creationOptions.indexParameters, + blockCompilation: creationOptions.blockCompilation || false, + shaderLanguage: creationOptions.shaderLanguage || 0 /* ShaderLanguage.GLSL */, + onCompiled: creationOptions.onCompiled || undefined, + extraInitializations: creationOptions.extraInitializations || undefined, + extraInitializationsAsync: creationOptions.extraInitializationsAsync || undefined, + useAsPostProcess: creationOptions.useAsPostProcess ?? false, + }; + this.options.uniformNames = this.options.uniforms; + this.options.samplerNames = this.options.samplers; + this.options.vertexShader = this.options.vertexUrl; + if (this.options.useAsPostProcess) { + if (this.options.samplers.indexOf("textureSampler") === -1) { + this.options.samplers.push("textureSampler"); + } + if (this.options.uniforms.indexOf("scale") === -1) { + this.options.uniforms.push("scale"); + } + } + if (creationOptions.vertexUrl || creationOptions.vertexShader) { + this._shaderPath = { + vertexSource: this.options.vertexShader, + }; + } + else { + if (!this.options.useAsPostProcess) { + this.options.uniforms.push("scale"); + this.onApplyObservable.add(() => { + this.effect.setFloat2("scale", 1, 1); + }); + } + this._shaderPath = { + vertex: this.options.vertexShader, + }; + } + this._shaderPath.fragmentSource = this.options.fragmentShader; + this._shaderPath.spectorName = this.options.name; + if (this.options.useShaderStore) { + this._shaderPath.fragment = this._shaderPath.fragmentSource; + if (!this._shaderPath.vertex) { + this._shaderPath.vertex = this._shaderPath.vertexSource; + } + delete this._shaderPath.fragmentSource; + delete this._shaderPath.vertexSource; + } + this.onApplyObservable.add(() => { + this.bind(); + }); + if (!this.options.useShaderStore) { + this._onContextRestoredObserver = this.options.engine.onContextRestoredObservable.add(() => { + this.effect._pipelineContext = null; // because _prepareEffect will try to dispose this pipeline before recreating it and that would lead to webgl errors + this.effect._prepareEffect(); + }); + } + this._drawWrapper = new DrawWrapper(this.options.engine); + this._webGPUReady = this.options.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + const defines = Array.isArray(this.options.defines) ? this.options.defines.join("\n") : this.options.defines; + this._postConstructor(this.options.blockCompilation, defines, this.options.extraInitializations); + } + _gatherImports(useWebGPU = false, list) { + if (!this.options.useAsPostProcess) { + return; + } + // this._webGPUReady is used to detect when an effect wrapper is intended to be used with WebGPU + if (useWebGPU && this._webGPUReady) { + list.push(Promise.all([Promise.resolve().then(() => postprocess_vertex)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => postprocess_vertex$1)])); + } + } + /** @internal */ + _postConstructor(blockCompilation, defines = null, extraInitializations, importPromises) { + this._importPromises.length = 0; + if (importPromises) { + this._importPromises.push(...importPromises); + } + const useWebGPU = this.options.engine.isWebGPU && !EffectWrapper.ForceGLSL; + this._gatherImports(useWebGPU, this._importPromises); + if (extraInitializations !== undefined) { + extraInitializations(useWebGPU, this._importPromises); + } + if (useWebGPU && this._webGPUReady) { + this.options.shaderLanguage = 1 /* ShaderLanguage.WGSL */; + } + if (!blockCompilation) { + this.updateEffect(defines); + } + } + /** + * Updates the effect with the current effect wrapper compile time values and recompiles the shader. + * @param defines Define statements that should be added at the beginning of the shader. (default: null) + * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) + * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) + * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx + * @param onCompiled Called when the shader has been compiled. + * @param onError Called if there is an error when compiling a shader. + * @param vertexUrl The url of the vertex shader to be used (default: the one given at construction time) + * @param fragmentUrl The url of the fragment shader to be used (default: the one given at construction time) + */ + updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl) { + const customShaderCodeProcessing = EffectWrapper._GetShaderCodeProcessing(this.name); + if (customShaderCodeProcessing?.defineCustomBindings) { + const newUniforms = uniforms?.slice() ?? []; + newUniforms.push(...this.options.uniforms); + const newSamplers = samplers?.slice() ?? []; + newSamplers.push(...this.options.samplers); + defines = customShaderCodeProcessing.defineCustomBindings(this.name, defines, newUniforms, newSamplers); + uniforms = newUniforms; + samplers = newSamplers; + } + this.options.defines = defines || ""; + const waitImportsLoaded = this._shadersLoaded || this._importPromises.length === 0 + ? undefined + : async () => { + await Promise.all(this._importPromises); + this._shadersLoaded = true; + }; + let extraInitializationsAsync; + if (this.options.extraInitializationsAsync) { + extraInitializationsAsync = async () => { + waitImportsLoaded?.(); + await this.options.extraInitializationsAsync(); + }; + } + else { + extraInitializationsAsync = waitImportsLoaded; + } + if (this.options.useShaderStore) { + this._drawWrapper.effect = this.options.engine.createEffect({ vertex: vertexUrl ?? this._shaderPath.vertex, fragment: fragmentUrl ?? this._shaderPath.fragment }, { + attributes: this.options.attributeNames, + uniformsNames: uniforms || this.options.uniforms, + uniformBuffersNames: this.options.uniformBuffers, + samplers: samplers || this.options.samplers, + defines: defines !== null ? defines : "", + fallbacks: null, + onCompiled: onCompiled ?? this.options.onCompiled, + onError: onError ?? null, + indexParameters: indexParameters || this.options.indexParameters, + processCodeAfterIncludes: customShaderCodeProcessing?.processCodeAfterIncludes + ? (shaderType, code) => customShaderCodeProcessing.processCodeAfterIncludes(this.name, shaderType, code) + : null, + processFinalCode: customShaderCodeProcessing?.processFinalCode + ? (shaderType, code) => customShaderCodeProcessing.processFinalCode(this.name, shaderType, code) + : null, + shaderLanguage: this.options.shaderLanguage, + extraInitializationsAsync, + }, this.options.engine); + } + else { + this._drawWrapper.effect = new Effect(this._shaderPath, this.options.attributeNames, uniforms || this.options.uniforms, samplers || this.options.samplerNames, this.options.engine, defines, undefined, onCompiled || this.options.onCompiled, undefined, undefined, undefined, this.options.shaderLanguage, extraInitializationsAsync); + } + this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect); + } + /** + * Binds the data to the effect. + */ + bind() { + if (this.options.useAsPostProcess) { + this.options.engine.setAlphaMode(this.alphaMode); + this.drawWrapper.effect.setFloat2("scale", 1, 1); + } + EffectWrapper._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name, this._drawWrapper.effect); + } + /** + * Disposes of the effect wrapper + * @param _ignored kept for backward compatibility + */ + dispose(_ignored = false) { + if (this._onContextRestoredObserver) { + this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver); + this._onContextRestoredObserver = null; + } + this.onEffectCreatedObservable.clear(); + this._drawWrapper.dispose(true); + } +} +/** + * Force code to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +EffectWrapper.ForceGLSL = false; +EffectWrapper._CustomShaderCodeProcessing = {}; + +AbstractEngine.prototype.setTextureFromPostProcess = function (channel, postProcess, name) { + let postProcessInput = null; + if (postProcess) { + if (postProcess._forcedOutputTexture) { + postProcessInput = postProcess._forcedOutputTexture; + } + else if (postProcess._textures.data[postProcess._currentRenderTextureInd]) { + postProcessInput = postProcess._textures.data[postProcess._currentRenderTextureInd]; + } + } + this._bindTexture(channel, postProcessInput?.texture ?? null, name); +}; +AbstractEngine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess, name) { + this._bindTexture(channel, postProcess?._outputTexture?.texture ?? null, name); +}; +/** + * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline) + * @param channel Name of the sampler variable. + * @param postProcess Post process to get the input texture from. + */ +Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) { + this._engine.setTextureFromPostProcess(this._samplers[channel], postProcess, channel); +}; +/** + * (Warning! setTextureFromPostProcessOutput may be desired instead) + * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput) + * @param channel Name of the sampler variable. + * @param postProcess Post process to get the output texture from. + */ +Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) { + this._engine.setTextureFromPostProcessOutput(this._samplers[channel], postProcess, channel); +}; +/** + * PostProcess can be used to apply a shader to a texture after it has been rendered + * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses + */ +class PostProcess { + /** + * Force all the postprocesses to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ + static get ForceGLSL() { + return EffectWrapper.ForceGLSL; + } + static set ForceGLSL(force) { + EffectWrapper.ForceGLSL = force; + } + /** + * Registers a shader code processing with a post process name. + * @param postProcessName name of the post process. Use null for the fallback shader code processing. This is the shader code processing that will be used in case no specific shader code processing has been associated to a post process name + * @param customShaderCodeProcessing shader code processing to associate to the post process name + */ + static RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing) { + EffectWrapper.RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing); + } + /** Name of the PostProcess. */ + get name() { + return this._effectWrapper.name; + } + set name(value) { + this._effectWrapper.name = value; + } + /** + * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE) + */ + get alphaMode() { + return this._effectWrapper.alphaMode; + } + set alphaMode(value) { + this._effectWrapper.alphaMode = value; + } + /** + * Number of sample textures (default: 1) + */ + get samples() { + return this._samples; + } + set samples(n) { + this._samples = Math.min(n, this._engine.getCaps().maxMSAASamples); + this._textures.forEach((texture) => { + texture.setSamples(this._samples); + }); + } + /** + * Gets the shader language type used to generate vertex and fragment source code. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Returns the fragment url or shader name used in the post process. + * @returns the fragment url or name in the shader store. + */ + getEffectName() { + return this._fragmentUrl; + } + /** + * A function that is added to the onActivateObservable + */ + set onActivate(callback) { + if (this._onActivateObserver) { + this.onActivateObservable.remove(this._onActivateObserver); + } + if (callback) { + this._onActivateObserver = this.onActivateObservable.add(callback); + } + } + /** + * A function that is added to the onSizeChangedObservable + */ + set onSizeChanged(callback) { + if (this._onSizeChangedObserver) { + this.onSizeChangedObservable.remove(this._onSizeChangedObserver); + } + this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback); + } + /** + * A function that is added to the onApplyObservable + */ + set onApply(callback) { + if (this._onApplyObserver) { + this.onApplyObservable.remove(this._onApplyObserver); + } + this._onApplyObserver = this.onApplyObservable.add(callback); + } + /** + * A function that is added to the onBeforeRenderObservable + */ + set onBeforeRender(callback) { + if (this._onBeforeRenderObserver) { + this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); + } + this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); + } + /** + * A function that is added to the onAfterRenderObservable + */ + set onAfterRender(callback) { + if (this._onAfterRenderObserver) { + this.onAfterRenderObservable.remove(this._onAfterRenderObserver); + } + this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); + } + /** + * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will + * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process. + */ + get inputTexture() { + return this._textures.data[this._currentRenderTextureInd]; + } + set inputTexture(value) { + this._forcedOutputTexture = value; + } + /** + * Since inputTexture should always be defined, if we previously manually set `inputTexture`, + * the only way to unset it is to use this function to restore its internal state + */ + restoreDefaultInputTexture() { + if (this._forcedOutputTexture) { + this._forcedOutputTexture = null; + this.markTextureDirty(); + } + } + /** + * Gets the camera which post process is applied to. + * @returns The camera the post process is applied to. + */ + getCamera() { + return this._camera; + } + /** + * Gets the texel size of the postprocess. + * See https://en.wikipedia.org/wiki/Texel_(graphics) + */ + get texelSize() { + if (this._shareOutputWithPostProcess) { + return this._shareOutputWithPostProcess.texelSize; + } + if (this._forcedOutputTexture) { + this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height); + } + return this._texelSize; + } + /** @internal */ + constructor(name, fragmentUrl, parameters, samplers, _size, camera, samplingMode = 1, engine, reusable, defines = null, textureType = 0, vertexUrl = "postprocess", indexParameters, blockCompilation = false, textureFormat = 5, shaderLanguage, extraInitializations) { + /** @internal */ + this._parentContainer = null; + /** + * Width of the texture to apply the post process on + */ + this.width = -1; + /** + * Height of the texture to apply the post process on + */ + this.height = -1; + /** + * Gets the node material used to create this postprocess (null if the postprocess was manually created) + */ + this.nodeMaterialSource = null; + /** + * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain) + * @internal + */ + this._outputTexture = null; + /** + * If the buffer needs to be cleared before applying the post process. (default: true) + * Should be set to false if shader will overwrite all previous pixels. + */ + this.autoClear = true; + /** + * If clearing the buffer should be forced in autoClear mode, even when alpha mode is enabled (default: false). + * By default, the buffer will only be cleared if alpha mode is disabled (and autoClear is true). + */ + this.forceAutoClearInAlphaMode = false; + /** + * Animations to be used for the post processing + */ + this.animations = []; + /** + * Enable Pixel Perfect mode where texture is not scaled to be power of 2. + * Can only be used on a single postprocess or on the last one of a chain. (default: false) + */ + this.enablePixelPerfectMode = false; + /** + * Force the postprocess to be applied without taking in account viewport + */ + this.forceFullscreenViewport = true; + /** + * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR) + * + * | Value | Type | Description | + * | ----- | ----------------------------------- | ----------- | + * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) | + * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) | + * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) | + * + */ + this.scaleMode = 1; + /** + * Force textures to be a power of two (default: false) + */ + this.alwaysForcePOT = false; + this._samples = 1; + /** + * Modify the scale of the post process to be the same as the viewport (default: false) + */ + this.adaptScaleToCurrentViewport = false; + this._webGPUReady = false; + this._reusable = false; + this._renderId = 0; + /** + * if externalTextureSamplerBinding is true, the "apply" method won't bind the textureSampler texture, it is expected to be done by the "outside" (by the onApplyObservable observer most probably). + * counter-productive in some cases because if the texture bound by "apply" is different from the currently texture bound, (the one set by the onApplyObservable observer, for eg) some + * internal structures (materialContext) will be dirtified, which may impact performances + */ + this.externalTextureSamplerBinding = false; + /** + * Smart array of input and output textures for the post process. + * @internal + */ + this._textures = new SmartArray(2); + /** + * Smart array of input and output textures for the post process. + * @internal + */ + this._textureCache = []; + /** + * The index in _textures that corresponds to the output texture. + * @internal + */ + this._currentRenderTextureInd = 0; + this._scaleRatio = new Vector2(1, 1); + this._texelSize = Vector2.Zero(); + // Events + /** + * An event triggered when the postprocess is activated. + */ + this.onActivateObservable = new Observable(); + /** + * An event triggered when the postprocess changes its size. + */ + this.onSizeChangedObservable = new Observable(); + /** + * An event triggered when the postprocess applies its effect. + */ + this.onApplyObservable = new Observable(); + /** + * An event triggered before rendering the postprocess + */ + this.onBeforeRenderObservable = new Observable(); + /** + * An event triggered after rendering the postprocess + */ + this.onAfterRenderObservable = new Observable(); + /** + * An event triggered when the post-process is disposed + */ + this.onDisposeObservable = new Observable(); + let size = 1; + let uniformBuffers = null; + let effectWrapper; + if (parameters && !Array.isArray(parameters)) { + const options = parameters; + parameters = options.uniforms ?? null; + samplers = options.samplers ?? null; + size = options.size ?? 1; + camera = options.camera ?? null; + samplingMode = options.samplingMode ?? 1; + engine = options.engine; + reusable = options.reusable; + defines = Array.isArray(options.defines) ? options.defines.join("\n") : (options.defines ?? null); + textureType = options.textureType ?? 0; + vertexUrl = options.vertexUrl ?? "postprocess"; + indexParameters = options.indexParameters; + blockCompilation = options.blockCompilation ?? false; + textureFormat = options.textureFormat ?? 5; + shaderLanguage = options.shaderLanguage ?? 0 /* ShaderLanguage.GLSL */; + uniformBuffers = options.uniformBuffers ?? null; + extraInitializations = options.extraInitializations; + effectWrapper = options.effectWrapper; + } + else if (_size) { + if (typeof _size === "number") { + size = _size; + } + else { + size = { width: _size.width, height: _size.height }; + } + } + this._useExistingThinPostProcess = !!effectWrapper; + this._effectWrapper = + effectWrapper ?? + new EffectWrapper({ + name, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: fragmentUrl, + engine: engine || camera?.getScene().getEngine(), + uniforms: parameters, + samplers, + uniformBuffers, + defines, + vertexUrl, + indexParameters, + blockCompilation: true, + shaderLanguage, + extraInitializations: undefined, + }); + this.name = name; + this.onEffectCreatedObservable = this._effectWrapper.onEffectCreatedObservable; + if (camera != null) { + this._camera = camera; + this._scene = camera.getScene(); + camera.attachPostProcess(this); + this._engine = this._scene.getEngine(); + this._scene.postProcesses.push(this); + this.uniqueId = this._scene.getUniqueId(); + } + else if (engine) { + this._engine = engine; + this._engine.postProcesses.push(this); + } + this._options = size; + this.renderTargetSamplingMode = samplingMode ? samplingMode : 1; + this._reusable = reusable || false; + this._textureType = textureType; + this._textureFormat = textureFormat; + this._shaderLanguage = shaderLanguage || 0 /* ShaderLanguage.GLSL */; + this._samplers = samplers || []; + if (this._samplers.indexOf("textureSampler") === -1) { + this._samplers.push("textureSampler"); + } + this._fragmentUrl = fragmentUrl; + this._vertexUrl = vertexUrl; + this._parameters = parameters || []; + if (this._parameters.indexOf("scale") === -1) { + this._parameters.push("scale"); + } + this._uniformBuffers = uniformBuffers || []; + this._indexParameters = indexParameters; + if (!this._useExistingThinPostProcess) { + this._webGPUReady = this._shaderLanguage === 1 /* ShaderLanguage.WGSL */; + const importPromises = []; + this._gatherImports(this._engine.isWebGPU && !PostProcess.ForceGLSL, importPromises); + this._effectWrapper._webGPUReady = this._webGPUReady; + this._effectWrapper._postConstructor(blockCompilation, defines, extraInitializations, importPromises); + } + } + _gatherImports(useWebGPU = false, list) { + // this._webGPUReady is used to detect when a postprocess is intended to be used with WebGPU + if (useWebGPU && this._webGPUReady) { + list.push(Promise.all([Promise.resolve().then(() => postprocess_vertex)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => postprocess_vertex$1)])); + } + } + /** + * Gets a string identifying the name of the class + * @returns "PostProcess" string + */ + getClassName() { + return "PostProcess"; + } + /** + * Gets the engine which this post process belongs to. + * @returns The engine the post process was enabled with. + */ + getEngine() { + return this._engine; + } + /** + * The effect that is created when initializing the post process. + * @returns The created effect corresponding to the postprocess. + */ + getEffect() { + return this._effectWrapper.drawWrapper.effect; + } + /** + * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another. + * @param postProcess The post process to share the output with. + * @returns This post process. + */ + shareOutputWith(postProcess) { + this._disposeTextures(); + this._shareOutputWithPostProcess = postProcess; + return this; + } + /** + * Reverses the effect of calling shareOutputWith and returns the post process back to its original state. + * This should be called if the post process that shares output with this post process is disabled/disposed. + */ + useOwnOutput() { + if (this._textures.length == 0) { + this._textures = new SmartArray(2); + } + this._shareOutputWithPostProcess = null; + } + /** + * Updates the effect with the current post process compile time values and recompiles the shader. + * @param defines Define statements that should be added at the beginning of the shader. (default: null) + * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) + * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) + * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx + * @param onCompiled Called when the shader has been compiled. + * @param onError Called if there is an error when compiling a shader. + * @param vertexUrl The url of the vertex shader to be used (default: the one given at construction time) + * @param fragmentUrl The url of the fragment shader to be used (default: the one given at construction time) + */ + updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl) { + this._effectWrapper.updateEffect(defines, uniforms, samplers, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl); + this._postProcessDefines = Array.isArray(this._effectWrapper.options.defines) ? this._effectWrapper.options.defines.join("\n") : this._effectWrapper.options.defines; + } + /** + * The post process is reusable if it can be used multiple times within one frame. + * @returns If the post process is reusable + */ + isReusable() { + return this._reusable; + } + /** invalidate frameBuffer to hint the postprocess to create a depth buffer */ + markTextureDirty() { + this.width = -1; + } + _createRenderTargetTexture(textureSize, textureOptions, channel = 0) { + for (let i = 0; i < this._textureCache.length; i++) { + if (this._textureCache[i].texture.width === textureSize.width && + this._textureCache[i].texture.height === textureSize.height && + this._textureCache[i].postProcessChannel === channel && + this._textureCache[i].texture._generateDepthBuffer === textureOptions.generateDepthBuffer && + this._textureCache[i].texture.samples === textureOptions.samples) { + return this._textureCache[i].texture; + } + } + const tex = this._engine.createRenderTargetTexture(textureSize, textureOptions); + this._textureCache.push({ texture: tex, postProcessChannel: channel, lastUsedRenderId: -1 }); + return tex; + } + _flushTextureCache() { + const currentRenderId = this._renderId; + for (let i = this._textureCache.length - 1; i >= 0; i--) { + if (currentRenderId - this._textureCache[i].lastUsedRenderId > 100) { + let currentlyUsed = false; + for (let j = 0; j < this._textures.length; j++) { + if (this._textures.data[j] === this._textureCache[i].texture) { + currentlyUsed = true; + break; + } + } + if (!currentlyUsed) { + this._textureCache[i].texture.dispose(); + this._textureCache.splice(i, 1); + } + } + } + } + /** + * Resizes the post-process texture + * @param width Width of the texture + * @param height Height of the texture + * @param camera The camera this post-process is applied to. Pass null if the post-process is used outside the context of a camera post-process chain (default: null) + * @param needMipMaps True if mip maps need to be generated after render (default: false) + * @param forceDepthStencil True to force post-process texture creation with stencil depth and buffer (default: false) + */ + resize(width, height, camera = null, needMipMaps = false, forceDepthStencil = false) { + if (this._textures.length > 0) { + this._textures.reset(); + } + this.width = width; + this.height = height; + let firstPP = null; + if (camera) { + for (let i = 0; i < camera._postProcesses.length; i++) { + if (camera._postProcesses[i] !== null) { + firstPP = camera._postProcesses[i]; + break; + } + } + } + const textureSize = { width: this.width, height: this.height }; + const textureOptions = { + generateMipMaps: needMipMaps, + generateDepthBuffer: forceDepthStencil || firstPP === this, + generateStencilBuffer: (forceDepthStencil || firstPP === this) && this._engine.isStencilEnable, + samplingMode: this.renderTargetSamplingMode, + type: this._textureType, + format: this._textureFormat, + samples: this._samples, + label: "PostProcessRTT-" + this.name, + }; + this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 0)); + if (this._reusable) { + this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 1)); + } + this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height); + this.onSizeChangedObservable.notifyObservers(this); + } + _getTarget() { + let target; + if (this._shareOutputWithPostProcess) { + target = this._shareOutputWithPostProcess.inputTexture; + } + else if (this._forcedOutputTexture) { + target = this._forcedOutputTexture; + this.width = this._forcedOutputTexture.width; + this.height = this._forcedOutputTexture.height; + } + else { + target = this.inputTexture; + let cache; + for (let i = 0; i < this._textureCache.length; i++) { + if (this._textureCache[i].texture === target) { + cache = this._textureCache[i]; + break; + } + } + if (cache) { + cache.lastUsedRenderId = this._renderId; + } + } + return target; + } + /** + * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable. + * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous. + * @param cameraOrScene The camera that will be used in the post process. This camera will be used when calling onActivateObservable. You can also pass the scene if no camera is available. + * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null) + * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false) + * @returns The render target wrapper that was bound to be written to. + */ + activate(cameraOrScene, sourceTexture = null, forceDepthStencil) { + const camera = cameraOrScene === null || cameraOrScene.cameraRigMode !== undefined ? cameraOrScene || this._camera : null; + const scene = camera?.getScene() ?? cameraOrScene; + const engine = scene.getEngine(); + const maxSize = engine.getCaps().maxTextureSize; + const requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0; + const requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0; + let desiredWidth = this._options.width || requiredWidth; + let desiredHeight = this._options.height || requiredHeight; + const needMipMaps = this.renderTargetSamplingMode !== 7 && + this.renderTargetSamplingMode !== 1 && + this.renderTargetSamplingMode !== 2; + let target = null; + if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) { + if (this.adaptScaleToCurrentViewport) { + const currentViewport = engine.currentViewport; + if (currentViewport) { + desiredWidth *= currentViewport.width; + desiredHeight *= currentViewport.height; + } + } + if (needMipMaps || this.alwaysForcePOT) { + if (!this._options.width) { + desiredWidth = engine.needPOTTextures ? GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth; + } + if (!this._options.height) { + desiredHeight = engine.needPOTTextures ? GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight; + } + } + if (this.width !== desiredWidth || this.height !== desiredHeight || !(target = this._getTarget())) { + this.resize(desiredWidth, desiredHeight, camera, needMipMaps, forceDepthStencil); + } + this._textures.forEach((texture) => { + if (texture.samples !== this.samples) { + this._engine.updateRenderTargetTextureSampleCount(texture, this.samples); + } + }); + this._flushTextureCache(); + this._renderId++; + } + if (!target) { + target = this._getTarget(); + } + // Bind the input of this post process to be used as the output of the previous post process. + if (this.enablePixelPerfectMode) { + this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight); + this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport); + } + else { + this._scaleRatio.copyFromFloats(1, 1); + this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport); + } + this._engine._debugInsertMarker?.(`post process ${this.name} input`); + this.onActivateObservable.notifyObservers(camera); + // Clear + if (this.autoClear && (this.alphaMode === 0 || this.forceAutoClearInAlphaMode)) { + this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true); + } + if (this._reusable) { + this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2; + } + return target; + } + /** + * If the post process is supported. + */ + get isSupported() { + return this._effectWrapper.drawWrapper.effect.isSupported; + } + /** + * The aspect ratio of the output texture. + */ + get aspectRatio() { + if (this._shareOutputWithPostProcess) { + return this._shareOutputWithPostProcess.aspectRatio; + } + if (this._forcedOutputTexture) { + return this._forcedOutputTexture.width / this._forcedOutputTexture.height; + } + return this.width / this.height; + } + /** + * Get a value indicating if the post-process is ready to be used + * @returns true if the post-process is ready (shader is compiled) + */ + isReady() { + return this._effectWrapper.isReady(); + } + /** + * Binds all textures and uniforms to the shader, this will be run on every pass. + * @returns the effect corresponding to this post process. Null if not compiled or not ready. + */ + apply() { + // Check + if (!this._effectWrapper.isReady()) { + return null; + } + // States + this._engine.enableEffect(this._effectWrapper.drawWrapper); + this._engine.setState(false); + this._engine.setDepthBuffer(false); + this._engine.setDepthWrite(false); + // Alpha + if (this.alphaConstants) { + this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a); + } + // Bind the output texture of the preivous post process as the input to this post process. + let source; + if (this._shareOutputWithPostProcess) { + source = this._shareOutputWithPostProcess.inputTexture; + } + else if (this._forcedOutputTexture) { + source = this._forcedOutputTexture; + } + else { + source = this.inputTexture; + } + if (!this.externalTextureSamplerBinding) { + this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler", source?.texture); + } + // Parameters + this._effectWrapper.drawWrapper.effect.setVector2("scale", this._scaleRatio); + this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect); + this._effectWrapper.bind(); + return this._effectWrapper.drawWrapper.effect; + } + _disposeTextures() { + if (this._shareOutputWithPostProcess || this._forcedOutputTexture) { + this._disposeTextureCache(); + return; + } + this._disposeTextureCache(); + this._textures.dispose(); + } + _disposeTextureCache() { + for (let i = this._textureCache.length - 1; i >= 0; i--) { + this._textureCache[i].texture.dispose(); + } + this._textureCache.length = 0; + } + /** + * Sets the required values to the prepass renderer. + * @param prePassRenderer defines the prepass renderer to setup. + * @returns true if the pre pass is needed. + */ + setPrePassRenderer(prePassRenderer) { + if (this._prePassEffectConfiguration) { + this._prePassEffectConfiguration = prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration); + this._prePassEffectConfiguration.enabled = true; + return true; + } + return false; + } + /** + * Disposes the post process. + * @param camera The camera to dispose the post process on. + */ + dispose(camera) { + camera = camera || this._camera; + if (!this._useExistingThinPostProcess) { + this._effectWrapper.dispose(); + } + this._disposeTextures(); + let index; + if (this._scene) { + index = this._scene.postProcesses.indexOf(this); + if (index !== -1) { + this._scene.postProcesses.splice(index, 1); + } + } + if (this._parentContainer) { + const index = this._parentContainer.postProcesses.indexOf(this); + if (index > -1) { + this._parentContainer.postProcesses.splice(index, 1); + } + this._parentContainer = null; + } + index = this._engine.postProcesses.indexOf(this); + if (index !== -1) { + this._engine.postProcesses.splice(index, 1); + } + this.onDisposeObservable.notifyObservers(); + if (!camera) { + return; + } + camera.detachPostProcess(this); + index = camera._postProcesses.indexOf(this); + if (index === 0 && camera._postProcesses.length > 0) { + const firstPostProcess = this._camera._getFirstPostProcess(); + if (firstPostProcess) { + firstPostProcess.markTextureDirty(); + } + } + this.onActivateObservable.clear(); + this.onAfterRenderObservable.clear(); + this.onApplyObservable.clear(); + this.onBeforeRenderObservable.clear(); + this.onSizeChangedObservable.clear(); + this.onEffectCreatedObservable.clear(); + } + /** + * Serializes the post process to a JSON object + * @returns the JSON object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + const camera = this.getCamera() || (this._scene && this._scene.activeCamera); + serializationObject.customType = "BABYLON." + this.getClassName(); + serializationObject.cameraId = camera ? camera.id : null; + serializationObject.reusable = this._reusable; + serializationObject.textureType = this._textureType; + serializationObject.fragmentUrl = this._fragmentUrl; + serializationObject.parameters = this._parameters; + serializationObject.samplers = this._samplers; + serializationObject.uniformBuffers = this._uniformBuffers; + serializationObject.options = this._options; + serializationObject.defines = this._postProcessDefines; + serializationObject.textureFormat = this._textureFormat; + serializationObject.vertexUrl = this._vertexUrl; + serializationObject.indexParameters = this._indexParameters; + return serializationObject; + } + /** + * Clones this post process + * @returns a new post process similar to this one + */ + clone() { + const serializationObject = this.serialize(); + serializationObject._engine = this._engine; + serializationObject.cameraId = null; + const result = PostProcess.Parse(serializationObject, this._scene, ""); + if (!result) { + return null; + } + result.onActivateObservable = this.onActivateObservable.clone(); + result.onSizeChangedObservable = this.onSizeChangedObservable.clone(); + result.onApplyObservable = this.onApplyObservable.clone(); + result.onBeforeRenderObservable = this.onBeforeRenderObservable.clone(); + result.onAfterRenderObservable = this.onAfterRenderObservable.clone(); + result._prePassEffectConfiguration = this._prePassEffectConfiguration; + return result; + } + /** + * Creates a material from parsed material data + * @param parsedPostProcess defines parsed post process data + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures + * @returns a new post process + */ + static Parse(parsedPostProcess, scene, rootUrl) { + const postProcessType = GetClass(parsedPostProcess.customType); + if (!postProcessType || !postProcessType._Parse) { + return null; + } + const camera = scene ? scene.getCameraById(parsedPostProcess.cameraId) : null; + return postProcessType._Parse(parsedPostProcess, camera, scene, rootUrl); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new PostProcess(parsedPostProcess.name, parsedPostProcess.fragmentUrl, parsedPostProcess.parameters, parsedPostProcess.samplers, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable, parsedPostProcess.defines, parsedPostProcess.textureType, parsedPostProcess.vertexUrl, parsedPostProcess.indexParameters, false, parsedPostProcess.textureFormat); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], PostProcess.prototype, "uniqueId", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "name", null); +__decorate([ + serialize() +], PostProcess.prototype, "width", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "height", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "renderTargetSamplingMode", void 0); +__decorate([ + serializeAsColor4() +], PostProcess.prototype, "clearColor", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "autoClear", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "forceAutoClearInAlphaMode", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "alphaMode", null); +__decorate([ + serialize() +], PostProcess.prototype, "alphaConstants", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "enablePixelPerfectMode", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "forceFullscreenViewport", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "scaleMode", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "alwaysForcePOT", void 0); +__decorate([ + serialize("samples") +], PostProcess.prototype, "_samples", void 0); +__decorate([ + serialize() +], PostProcess.prototype, "adaptScaleToCurrentViewport", void 0); +RegisterClass("BABYLON.PostProcess", PostProcess); + +/** + * Post process used to apply a blur effect + */ +class ThinBlurPostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => kernelBlur_fragment), Promise.resolve().then(() => kernelBlur_vertex)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => kernelBlur_fragment$1), Promise.resolve().then(() => kernelBlur_vertex$1)])); + } + } + /** + * Constructs a new blur post process + * @param name Name of the effect + * @param engine Engine to use to render the effect. If not provided, the last created engine will be used + * @param direction Direction in which to apply the blur + * @param kernel Kernel size of the blur + * @param options Options to configure the effect + */ + constructor(name, engine = null, direction, kernel, options) { + const blockCompilationFinal = !!options?.blockCompilation; + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinBlurPostProcess.FragmentUrl, + uniforms: ThinBlurPostProcess.Uniforms, + samplers: ThinBlurPostProcess.Samplers, + vertexUrl: ThinBlurPostProcess.VertexUrl, + blockCompilation: true, + }); + this._packedFloat = false; + this._staticDefines = ""; + /** + * Width of the texture to apply the blur on + */ + this.textureWidth = 0; + /** + * Height of the texture to apply the blur on + */ + this.textureHeight = 0; + this.options.blockCompilation = blockCompilationFinal; + if (direction !== undefined) { + this.direction = direction; + } + if (kernel !== undefined) { + this.kernel = kernel; + } + } + /** + * Sets the length in pixels of the blur sample region + */ + set kernel(v) { + if (this._idealKernel === v) { + return; + } + v = Math.max(v, 1); + this._idealKernel = v; + this._kernel = this._nearestBestKernel(v); + if (!this.options.blockCompilation) { + this._updateParameters(); + } + } + /** + * Gets the length in pixels of the blur sample region + */ + get kernel() { + return this._idealKernel; + } + /** + * Sets whether or not the blur needs to unpack/repack floats + */ + set packedFloat(v) { + if (this._packedFloat === v) { + return; + } + this._packedFloat = v; + if (!this.options.blockCompilation) { + this._updateParameters(); + } + } + /** + * Gets whether or not the blur is unpacking/repacking floats + */ + get packedFloat() { + return this._packedFloat; + } + bind() { + super.bind(); + this._drawWrapper.effect.setFloat2("delta", (1 / this.textureWidth) * this.direction.x, (1 / this.textureHeight) * this.direction.y); + } + /** @internal */ + _updateParameters(onCompiled, onError) { + // Generate sampling offsets and weights + const N = this._kernel; + const centerIndex = (N - 1) / 2; + // Generate Gaussian sampling weights over kernel + let offsets = []; + let weights = []; + let totalWeight = 0; + for (let i = 0; i < N; i++) { + const u = i / (N - 1); + const w = this._gaussianWeight(u * 2.0 - 1); + offsets[i] = i - centerIndex; + weights[i] = w; + totalWeight += w; + } + // Normalize weights + for (let i = 0; i < weights.length; i++) { + weights[i] /= totalWeight; + } + // Optimize: combine samples to take advantage of hardware linear sampling + // Walk from left to center, combining pairs (symmetrically) + const linearSamplingWeights = []; + const linearSamplingOffsets = []; + const linearSamplingMap = []; + for (let i = 0; i <= centerIndex; i += 2) { + const j = Math.min(i + 1, Math.floor(centerIndex)); + const singleCenterSample = i === j; + if (singleCenterSample) { + linearSamplingMap.push({ o: offsets[i], w: weights[i] }); + } + else { + const sharedCell = j === centerIndex; + const weightLinear = weights[i] + weights[j] * (sharedCell ? 0.5 : 1); + const offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]); + if (offsetLinear === 0) { + linearSamplingMap.push({ o: offsets[i], w: weights[i] }); + linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] }); + } + else { + linearSamplingMap.push({ o: offsetLinear, w: weightLinear }); + linearSamplingMap.push({ o: -offsetLinear, w: weightLinear }); + } + } + } + for (let i = 0; i < linearSamplingMap.length; i++) { + linearSamplingOffsets[i] = linearSamplingMap[i].o; + linearSamplingWeights[i] = linearSamplingMap[i].w; + } + // Replace with optimized + offsets = linearSamplingOffsets; + weights = linearSamplingWeights; + // Generate shaders + const maxVaryingRows = this.options.engine.getCaps().maxVaryingVectors - (this.options.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? 1 : 0); // Because of the additional builtins + const freeVaryingVec2 = Math.max(maxVaryingRows, 0) - 1; // Because of sampleCenter + let varyingCount = Math.min(offsets.length, freeVaryingVec2); + let defines = ""; + defines += this._staticDefines; + // The DOF fragment should ignore the center pixel when looping as it is handled manually in the fragment shader. + if (this._staticDefines.indexOf("DOF") != -1) { + defines += `#define CENTER_WEIGHT ${this._glslFloat(weights[varyingCount - 1])}\n`; + varyingCount--; + } + for (let i = 0; i < varyingCount; i++) { + defines += `#define KERNEL_OFFSET${i} ${this._glslFloat(offsets[i])}\n`; + defines += `#define KERNEL_WEIGHT${i} ${this._glslFloat(weights[i])}\n`; + } + let depCount = 0; + for (let i = freeVaryingVec2; i < offsets.length; i++) { + defines += `#define KERNEL_DEP_OFFSET${depCount} ${this._glslFloat(offsets[i])}\n`; + defines += `#define KERNEL_DEP_WEIGHT${depCount} ${this._glslFloat(weights[i])}\n`; + depCount++; + } + if (this.packedFloat) { + defines += `#define PACKEDFLOAT 1`; + } + this.options.blockCompilation = false; + this.updateEffect(defines, null, null, { + varyingCount: varyingCount, + depCount: depCount, + }, onCompiled, onError); + } + /** + * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13. + * Other odd kernels optimize correctly but require proportionally more samples, even kernels are + * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we + * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard. + * The gaps between physical kernels are compensated for in the weighting of the samples + * @param idealKernel Ideal blur kernel. + * @returns Nearest best kernel. + */ + _nearestBestKernel(idealKernel) { + const v = Math.round(idealKernel); + for (const k of [v, v - 1, v + 1, v - 2, v + 2]) { + if (k % 2 !== 0 && Math.floor(k / 2) % 2 === 0 && k > 0) { + return Math.max(k, 3); + } + } + return Math.max(v, 3); + } + /** + * Calculates the value of a Gaussian distribution with sigma 3 at a given point. + * @param x The point on the Gaussian distribution to sample. + * @returns the value of the Gaussian function at x. + */ + _gaussianWeight(x) { + //reference: Engines/ImageProcessingBlur.cpp #dcc760 + // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1], + // so we truncate at three standard deviations by setting stddev (sigma) to 1/3. + // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is + // truncated at around 1.3% of peak strength. + //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size + const sigma = 1 / 3; + const denominator = Math.sqrt(2.0 * Math.PI) * sigma; + const exponent = -((x * x) / (2.0 * sigma * sigma)); + const weight = (1.0 / denominator) * Math.exp(exponent); + return weight; + } + /** + * Generates a string that can be used as a floating point number in GLSL. + * @param x Value to print. + * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s). + * @returns GLSL float string. + */ + _glslFloat(x, decimalFigures = 8) { + return x.toFixed(decimalFigures).replace(/0+$/, ""); + } +} +/** + * The vertex shader url + */ +ThinBlurPostProcess.VertexUrl = "kernelBlur"; +/** + * The fragment shader url + */ +ThinBlurPostProcess.FragmentUrl = "kernelBlur"; +/** + * The list of uniforms used by the effect + */ +ThinBlurPostProcess.Uniforms = ["delta", "direction"]; +/** + * The list of samplers used by the effect + */ +ThinBlurPostProcess.Samplers = ["circleOfConfusionSampler"]; + +/** + * The Blur Post Process which blurs an image based on a kernel and direction. + * Can be used twice in x and y directions to perform a gaussian blur in two passes. + */ +class BlurPostProcess extends PostProcess { + /** The direction in which to blur the image. */ + get direction() { + return this._effectWrapper.direction; + } + set direction(value) { + this._effectWrapper.direction = value; + } + /** + * Sets the length in pixels of the blur sample region + */ + set kernel(v) { + this._effectWrapper.kernel = v; + } + /** + * Gets the length in pixels of the blur sample region + */ + get kernel() { + return this._effectWrapper.kernel; + } + /** + * Sets whether or not the blur needs to unpack/repack floats + */ + set packedFloat(v) { + this._effectWrapper.packedFloat = v; + } + /** + * Gets whether or not the blur is unpacking/repacking floats + */ + get packedFloat() { + return this._effectWrapper.packedFloat; + } + /** + * Gets a string identifying the name of the class + * @returns "BlurPostProcess" string + */ + getClassName() { + return "BlurPostProcess"; + } + /** + * Creates a new instance BlurPostProcess + * @param name The name of the effect. + * @param direction The direction in which to blur the image. + * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it. + * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size) + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param defines + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA) + */ + constructor(name, direction, kernel, options, camera = null, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = 0, defines = "", blockCompilation = false, textureFormat = 5) { + const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation; + const localOptions = { + uniforms: ThinBlurPostProcess.Uniforms, + samplers: ThinBlurPostProcess.Samplers, + size: typeof options === "number" ? options : undefined, + camera, + samplingMode, + engine, + reusable, + textureType, + vertexUrl: ThinBlurPostProcess.VertexUrl, + indexParameters: { varyingCount: 0, depCount: 0 }, + textureFormat, + defines, + ...options, + blockCompilation: true, + }; + super(name, ThinBlurPostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBlurPostProcess(name, engine, undefined, undefined, localOptions) : undefined, + ...localOptions, + }); + this._effectWrapper.options.blockCompilation = blockCompilationFinal; + this.direction = direction; + this.onApplyObservable.add(() => { + this._effectWrapper.textureWidth = this._outputTexture ? this._outputTexture.width : this.width; + this._effectWrapper.textureHeight = this._outputTexture ? this._outputTexture.height : this.height; + }); + this.kernel = kernel; + } + updateEffect(_defines = null, _uniforms = null, _samplers = null, _indexParameters, onCompiled, onError) { + this._effectWrapper._updateParameters(onCompiled, onError); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new BlurPostProcess(parsedPostProcess.name, parsedPostProcess.direction, parsedPostProcess.kernel, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, undefined, false); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serializeAsVector2() +], BlurPostProcess.prototype, "direction", null); +__decorate([ + serialize() +], BlurPostProcess.prototype, "kernel", null); +__decorate([ + serialize() +], BlurPostProcess.prototype, "packedFloat", null); +RegisterClass("BABYLON.BlurPostProcess", BlurPostProcess); + +/** + * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance. + * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog) + */ +class EffectFallbacks { + constructor() { + this._defines = {}; + this._currentRank = 32; + this._maxRank = -1; + this._mesh = null; + } + /** + * Removes the fallback from the bound mesh. + */ + unBindMesh() { + this._mesh = null; + } + /** + * Adds a fallback on the specified property. + * @param rank The rank of the fallback (Lower ranks will be fallbacked to first) + * @param define The name of the define in the shader + */ + addFallback(rank, define) { + if (!this._defines[rank]) { + if (rank < this._currentRank) { + this._currentRank = rank; + } + if (rank > this._maxRank) { + this._maxRank = rank; + } + this._defines[rank] = new Array(); + } + this._defines[rank].push(define); + } + /** + * Sets the mesh to use CPU skinning when needing to fallback. + * @param rank The rank of the fallback (Lower ranks will be fallbacked to first) + * @param mesh The mesh to use the fallbacks. + */ + addCPUSkinningFallback(rank, mesh) { + this._mesh = mesh; + if (rank < this._currentRank) { + this._currentRank = rank; + } + if (rank > this._maxRank) { + this._maxRank = rank; + } + } + /** + * Checks to see if more fallbacks are still available. + */ + get hasMoreFallbacks() { + return this._currentRank <= this._maxRank; + } + /** + * Removes the defines that should be removed when falling back. + * @param currentDefines defines the current define statements for the shader. + * @param effect defines the current effect we try to compile + * @returns The resulting defines with defines of the current rank removed. + */ + reduce(currentDefines, effect) { + // First we try to switch to CPU skinning + if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) { + this._mesh.computeBonesUsingShaders = false; + currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0"); + effect._bonesComputationForcedToCPU = true; + const scene = this._mesh.getScene(); + for (let index = 0; index < scene.meshes.length; index++) { + const otherMesh = scene.meshes[index]; + if (!otherMesh.material) { + if (!this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) { + otherMesh.computeBonesUsingShaders = false; + } + continue; + } + if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) { + continue; + } + if (otherMesh.material.getEffect() === effect) { + otherMesh.computeBonesUsingShaders = false; + } + else if (otherMesh.subMeshes) { + for (const subMesh of otherMesh.subMeshes) { + const subMeshEffect = subMesh.effect; + if (subMeshEffect === effect) { + otherMesh.computeBonesUsingShaders = false; + break; + } + } + } + } + } + else { + const currentFallbacks = this._defines[this._currentRank]; + if (currentFallbacks) { + for (let index = 0; index < currentFallbacks.length; index++) { + currentDefines = currentDefines.replace("#define " + currentFallbacks[index], ""); + } + } + this._currentRank++; + } + return currentDefines; + } +} + +/** + * Default implementation IShadowGenerator. + * This is the main object responsible of generating shadows in the framework. + * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows + * @see [WebGL](https://playground.babylonjs.com/#IFYDRS#0) + * @see [WebGPU](https://playground.babylonjs.com/#IFYDRS#835) + */ +class ShadowGenerator { + /** + * Gets the bias: offset applied on the depth preventing acnea (in light direction). + */ + get bias() { + return this._bias; + } + /** + * Sets the bias: offset applied on the depth preventing acnea (in light direction). + */ + set bias(bias) { + this._bias = bias; + } + /** + * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle). + */ + get normalBias() { + return this._normalBias; + } + /** + * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle). + */ + set normalBias(normalBias) { + this._normalBias = normalBias; + } + /** + * Gets the blur box offset: offset applied during the blur pass. + * Only useful if useKernelBlur = false + */ + get blurBoxOffset() { + return this._blurBoxOffset; + } + /** + * Sets the blur box offset: offset applied during the blur pass. + * Only useful if useKernelBlur = false + */ + set blurBoxOffset(value) { + if (this._blurBoxOffset === value) { + return; + } + this._blurBoxOffset = value; + this._disposeBlurPostProcesses(); + } + /** + * Gets the blur scale: scale of the blurred texture compared to the main shadow map. + * 2 means half of the size. + */ + get blurScale() { + return this._blurScale; + } + /** + * Sets the blur scale: scale of the blurred texture compared to the main shadow map. + * 2 means half of the size. + */ + set blurScale(value) { + if (this._blurScale === value) { + return; + } + this._blurScale = value; + this._disposeBlurPostProcesses(); + } + /** + * Gets the blur kernel: kernel size of the blur pass. + * Only useful if useKernelBlur = true + */ + get blurKernel() { + return this._blurKernel; + } + /** + * Sets the blur kernel: kernel size of the blur pass. + * Only useful if useKernelBlur = true + */ + set blurKernel(value) { + if (this._blurKernel === value) { + return; + } + this._blurKernel = value; + this._disposeBlurPostProcesses(); + } + /** + * Gets whether the blur pass is a kernel blur (if true) or box blur. + * Only useful in filtered mode (useBlurExponentialShadowMap...) + */ + get useKernelBlur() { + return this._useKernelBlur; + } + /** + * Sets whether the blur pass is a kernel blur (if true) or box blur. + * Only useful in filtered mode (useBlurExponentialShadowMap...) + */ + set useKernelBlur(value) { + if (this._useKernelBlur === value) { + return; + } + this._useKernelBlur = value; + this._disposeBlurPostProcesses(); + } + /** + * Gets the depth scale used in ESM mode. + */ + get depthScale() { + return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale(); + } + /** + * Sets the depth scale used in ESM mode. + * This can override the scale stored on the light. + */ + set depthScale(value) { + this._depthScale = value; + } + _validateFilter(filter) { + return filter; + } + /** + * Gets the current mode of the shadow generator (normal, PCF, ESM...). + * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE + */ + get filter() { + return this._filter; + } + /** + * Sets the current mode of the shadow generator (normal, PCF, ESM...). + * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE + */ + set filter(value) { + value = this._validateFilter(value); + // Blurring the cubemap is going to be too expensive. Reverting to unblurred version + if (this._light.needCube()) { + if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { + this.useExponentialShadowMap = true; + return; + } + else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { + this.useCloseExponentialShadowMap = true; + return; + } + // PCF on cubemap would also be expensive + else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) { + this.usePoissonSampling = true; + return; + } + } + // Weblg1 fallback for PCF. + if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) { + if (!this._scene.getEngine()._features.supportShadowSamplers) { + this.usePoissonSampling = true; + return; + } + } + if (this._filter === value) { + return; + } + this._filter = value; + this._disposeBlurPostProcesses(); + this._applyFilterValues(); + this._light._markMeshesAsLightDirty(); + } + /** + * Gets if the current filter is set to Poisson Sampling. + */ + get usePoissonSampling() { + return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING; + } + /** + * Sets the current filter to Poisson Sampling. + */ + set usePoissonSampling(value) { + const filter = this._validateFilter(ShadowGenerator.FILTER_POISSONSAMPLING); + if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) { + return; + } + this.filter = value ? filter : ShadowGenerator.FILTER_NONE; + } + /** + * Gets if the current filter is set to ESM. + */ + get useExponentialShadowMap() { + return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP; + } + /** + * Sets the current filter is to ESM. + */ + set useExponentialShadowMap(value) { + const filter = this._validateFilter(ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP); + if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) { + return; + } + this.filter = value ? filter : ShadowGenerator.FILTER_NONE; + } + /** + * Gets if the current filter is set to filtered ESM. + */ + get useBlurExponentialShadowMap() { + return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP; + } + /** + * Gets if the current filter is set to filtered ESM. + */ + set useBlurExponentialShadowMap(value) { + const filter = this._validateFilter(ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP); + if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { + return; + } + this.filter = value ? filter : ShadowGenerator.FILTER_NONE; + } + /** + * Gets if the current filter is set to "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ + get useCloseExponentialShadowMap() { + return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP; + } + /** + * Sets the current filter to "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ + set useCloseExponentialShadowMap(value) { + const filter = this._validateFilter(ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP); + if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) { + return; + } + this.filter = value ? filter : ShadowGenerator.FILTER_NONE; + } + /** + * Gets if the current filter is set to filtered "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ + get useBlurCloseExponentialShadowMap() { + return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP; + } + /** + * Sets the current filter to filtered "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ + set useBlurCloseExponentialShadowMap(value) { + const filter = this._validateFilter(ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP); + if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { + return; + } + this.filter = value ? filter : ShadowGenerator.FILTER_NONE; + } + /** + * Gets if the current filter is set to "PCF" (percentage closer filtering). + */ + get usePercentageCloserFiltering() { + return this.filter === ShadowGenerator.FILTER_PCF; + } + /** + * Sets the current filter to "PCF" (percentage closer filtering). + */ + set usePercentageCloserFiltering(value) { + const filter = this._validateFilter(ShadowGenerator.FILTER_PCF); + if (!value && this.filter !== ShadowGenerator.FILTER_PCF) { + return; + } + this.filter = value ? filter : ShadowGenerator.FILTER_NONE; + } + /** + * Gets the PCF or PCSS Quality. + * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. + */ + get filteringQuality() { + return this._filteringQuality; + } + /** + * Sets the PCF or PCSS Quality. + * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. + */ + set filteringQuality(filteringQuality) { + if (this._filteringQuality === filteringQuality) { + return; + } + this._filteringQuality = filteringQuality; + this._disposeBlurPostProcesses(); + this._applyFilterValues(); + this._light._markMeshesAsLightDirty(); + } + /** + * Gets if the current filter is set to "PCSS" (contact hardening). + */ + get useContactHardeningShadow() { + return this.filter === ShadowGenerator.FILTER_PCSS; + } + /** + * Sets the current filter to "PCSS" (contact hardening). + */ + set useContactHardeningShadow(value) { + const filter = this._validateFilter(ShadowGenerator.FILTER_PCSS); + if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) { + return; + } + this.filter = value ? filter : ShadowGenerator.FILTER_NONE; + } + /** + * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. + * Using a ratio helps keeping shape stability independently of the map size. + * + * It does not account for the light projection as it was having too much + * instability during the light setup or during light position changes. + * + * Only valid if useContactHardeningShadow is true. + */ + get contactHardeningLightSizeUVRatio() { + return this._contactHardeningLightSizeUVRatio; + } + /** + * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. + * Using a ratio helps keeping shape stability independently of the map size. + * + * It does not account for the light projection as it was having too much + * instability during the light setup or during light position changes. + * + * Only valid if useContactHardeningShadow is true. + */ + set contactHardeningLightSizeUVRatio(contactHardeningLightSizeUVRatio) { + this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio; + } + /** Gets or sets the actual darkness of a shadow */ + get darkness() { + return this._darkness; + } + set darkness(value) { + this.setDarkness(value); + } + /** + * Returns the darkness value (float). This can only decrease the actual darkness of a shadow. + * 0 means strongest and 1 would means no shadow. + * @returns the darkness. + */ + getDarkness() { + return this._darkness; + } + /** + * Sets the darkness value (float). This can only decrease the actual darkness of a shadow. + * @param darkness The darkness value 0 means strongest and 1 would means no shadow. + * @returns the shadow generator allowing fluent coding. + */ + setDarkness(darkness) { + if (darkness >= 1.0) { + this._darkness = 1.0; + } + else if (darkness <= 0.0) { + this._darkness = 0.0; + } + else { + this._darkness = darkness; + } + return this; + } + /** Gets or sets the ability to have transparent shadow */ + get transparencyShadow() { + return this._transparencyShadow; + } + set transparencyShadow(value) { + this.setTransparencyShadow(value); + } + /** + * Sets the ability to have transparent shadow (boolean). + * @param transparent True if transparent else False + * @returns the shadow generator allowing fluent coding + */ + setTransparencyShadow(transparent) { + this._transparencyShadow = transparent; + return this; + } + /** + * Gets the main RTT containing the shadow map (usually storing depth from the light point of view). + * @returns The render target texture if present otherwise, null + */ + getShadowMap() { + return this._shadowMap; + } + /** + * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself). + * @returns The render target texture if the shadow map is present otherwise, null + */ + getShadowMapForRendering() { + if (this._shadowMap2) { + return this._shadowMap2; + } + return this._shadowMap; + } + /** + * Gets the class name of that object + * @returns "ShadowGenerator" + */ + getClassName() { + return ShadowGenerator.CLASSNAME; + } + /** + * Helper function to add a mesh and its descendants to the list of shadow casters. + * @param mesh Mesh to add + * @param includeDescendants boolean indicating if the descendants should be added. Default to true + * @returns the Shadow Generator itself + */ + addShadowCaster(mesh, includeDescendants = true) { + if (!this._shadowMap) { + return this; + } + if (!this._shadowMap.renderList) { + this._shadowMap.renderList = []; + } + if (this._shadowMap.renderList.indexOf(mesh) === -1) { + this._shadowMap.renderList.push(mesh); + } + if (includeDescendants) { + for (const childMesh of mesh.getChildMeshes()) { + if (this._shadowMap.renderList.indexOf(childMesh) === -1) { + this._shadowMap.renderList.push(childMesh); + } + } + } + return this; + } + /** + * Helper function to remove a mesh and its descendants from the list of shadow casters + * @param mesh Mesh to remove + * @param includeDescendants boolean indicating if the descendants should be removed. Default to true + * @returns the Shadow Generator itself + */ + removeShadowCaster(mesh, includeDescendants = true) { + if (!this._shadowMap || !this._shadowMap.renderList) { + return this; + } + const index = this._shadowMap.renderList.indexOf(mesh); + if (index !== -1) { + this._shadowMap.renderList.splice(index, 1); + } + if (includeDescendants) { + for (const child of mesh.getChildren()) { + this.removeShadowCaster(child); + } + } + return this; + } + /** + * Returns the associated light object. + * @returns the light generating the shadow + */ + getLight() { + return this._light; + } + /** + * Gets the shader language used in this generator. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + _getCamera() { + return this._camera ?? this._scene.activeCamera; + } + /** + * Gets or sets the size of the texture what stores the shadows + */ + get mapSize() { + return this._mapSize; + } + set mapSize(size) { + this._mapSize = size; + this._light._markMeshesAsLightDirty(); + this.recreateShadowMap(); + } + /** + * Creates a ShadowGenerator object. + * A ShadowGenerator is the required tool to use the shadows. + * Each light casting shadows needs to use its own ShadowGenerator. + * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows + * @param mapSize The size of the texture what stores the shadows. Example : 1024. + * @param light The light object generating the shadows. + * @param usefullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture. + * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it + * @param useRedTextureType Forces the generator to use a Red instead of a RGBA type for the shadow map texture format (default: false) + * @param forceGLSL defines a boolean indicating if the shader must be compiled in GLSL even if we are using WebGPU + */ + constructor(mapSize, light, usefullFloatFirst, camera, useRedTextureType, forceGLSL = false) { + /** + * Observable triggered before the shadow is rendered. Can be used to update internal effect state + */ + this.onBeforeShadowMapRenderObservable = new Observable(); + /** + * Observable triggered after the shadow is rendered. Can be used to restore internal effect state + */ + this.onAfterShadowMapRenderObservable = new Observable(); + /** + * Observable triggered before a mesh is rendered in the shadow map. + * Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable) + */ + this.onBeforeShadowMapRenderMeshObservable = new Observable(); + /** + * Observable triggered after a mesh is rendered in the shadow map. + * Can be used to update internal effect state (that you can get from the onAfterShadowMapRenderObservable) + */ + this.onAfterShadowMapRenderMeshObservable = new Observable(); + /** + * Specifies if the `ShadowGenerator` should be serialized, `true` to skip serialization. + * Note a `ShadowGenerator` will not be serialized if its light has `doNotSerialize=true` + */ + this.doNotSerialize = false; + this._bias = 0.00005; + this._normalBias = 0; + this._blurBoxOffset = 1; + this._blurScale = 2; + this._blurKernel = 1; + this._useKernelBlur = false; + this._filter = ShadowGenerator.FILTER_NONE; + this._filteringQuality = ShadowGenerator.QUALITY_HIGH; + this._contactHardeningLightSizeUVRatio = 0.1; + this._darkness = 0; + this._transparencyShadow = false; + /** + * Enables or disables shadows with varying strength based on the transparency + * When it is enabled, the strength of the shadow is taken equal to mesh.visibility + * If you enabled an alpha texture on your material, the alpha value red from the texture is also combined to compute the strength: + * mesh.visibility * alphaTexture.a + * The texture used is the diffuse by default, but it can be set to the opacity by setting useOpacityTextureForTransparentShadow + * Note that by definition transparencyShadow must be set to true for enableSoftTransparentShadow to work! + */ + this.enableSoftTransparentShadow = false; + /** + * If this is true, use the opacity texture's alpha channel for transparent shadows instead of the diffuse one + */ + this.useOpacityTextureForTransparentShadow = false; + /** + * Controls the extent to which the shadows fade out at the edge of the frustum + */ + this.frustumEdgeFalloff = 0; + /** Shader language used by the generator */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + /** + * If true the shadow map is generated by rendering the back face of the mesh instead of the front face. + * This can help with self-shadowing as the geometry making up the back of objects is slightly offset. + * It might on the other hand introduce peter panning. + */ + this.forceBackFacesOnly = false; + this._lightDirection = Vector3.Zero(); + this._viewMatrix = Matrix.Zero(); + this._projectionMatrix = Matrix.Zero(); + this._transformMatrix = Matrix.Zero(); + this._cachedPosition = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cachedDirection = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._currentFaceIndex = 0; + this._currentFaceIndexCache = 0; + this._defaultTextureMatrix = Matrix.Identity(); + this._shadersLoaded = false; + this._mapSize = mapSize; + this._light = light; + this._scene = light.getScene(); + this._camera = camera ?? null; + this._useRedTextureType = !!useRedTextureType; + this._initShaderSourceAsync(forceGLSL); + let shadowGenerators = light._shadowGenerators; + if (!shadowGenerators) { + shadowGenerators = light._shadowGenerators = new Map(); + } + shadowGenerators.set(this._camera, this); + this.id = light.id; + this._useUBO = this._scene.getEngine().supportsUniformBuffers; + if (this._useUBO) { + this._sceneUBOs = []; + this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`)); + } + ShadowGenerator._SceneComponentInitialization(this._scene); + // Texture type fallback from float to int if not supported. + const caps = this._scene.getEngine().getCaps(); + if (!usefullFloatFirst) { + if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { + this._textureType = 2; + } + else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { + this._textureType = 1; + } + else { + this._textureType = 0; + } + } + else { + if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { + this._textureType = 1; + } + else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { + this._textureType = 2; + } + else { + this._textureType = 0; + } + } + this._initializeGenerator(); + this._applyFilterValues(); + } + _initializeGenerator() { + this._light._markMeshesAsLightDirty(); + this._initializeShadowMap(); + } + _createTargetRenderTexture() { + const engine = this._scene.getEngine(); + if (engine._features.supportDepthStencilTexture) { + this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false, undefined, this._useRedTextureType ? 6 : 5); + this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true, undefined, undefined, undefined, `DepthStencilForShadowGenerator-${this._light.name}`); + } + else { + this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube()); + } + this._shadowMap.noPrePassRenderer = true; + } + _initializeShadowMap() { + this._createTargetRenderTexture(); + if (this._shadowMap === null) { + return; + } + this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE; + this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE; + this._shadowMap.anisotropicFilteringLevel = 1; + this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); + this._shadowMap.renderParticles = false; + this._shadowMap.ignoreCameraViewport = true; + if (this._storedUniqueId) { + this._shadowMap.uniqueId = this._storedUniqueId; + } + // Custom render function. + this._shadowMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => this._renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes); + // When preWarm is false, forces the mesh is ready function to true as we are double checking it + // in the custom render function. Also it prevents side effects and useless + // shader variations in DEPTHPREPASS mode. + this._shadowMap.customIsReadyFunction = (mesh, _refreshRate, preWarm) => { + if (!preWarm || !mesh.subMeshes) { + return true; + } + let isReady = true; + for (const subMesh of mesh.subMeshes) { + const renderingMesh = subMesh.getRenderingMesh(); + const scene = this._scene; + const engine = scene.getEngine(); + const material = subMesh.getMaterial(); + if (!material || subMesh.verticesCount === 0 || (this.customAllowRendering && !this.customAllowRendering(subMesh))) { + continue; + } + const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); + if (batch.mustReturn) { + continue; + } + const hardwareInstancedRendering = engine.getCaps().instancedArrays && + ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances); + const isTransparent = material.needAlphaBlendingForMesh(renderingMesh); + isReady = this.isReady(subMesh, hardwareInstancedRendering, isTransparent) && isReady; + } + return isReady; + }; + const engine = this._scene.getEngine(); + this._shadowMap.onBeforeBindObservable.add(() => { + this._currentSceneUBO = this._scene.getSceneUniformBuffer(); + engine._debugPushGroup?.(`shadow map generation for pass id ${engine.currentRenderPassId}`, 1); + }); + // Record Face Index before render. + this._shadowMap.onBeforeRenderObservable.add((faceIndex) => { + if (this._sceneUBOs) { + this._scene.setSceneUniformBuffer(this._sceneUBOs[0]); + } + this._currentFaceIndex = faceIndex; + if (this._filter === ShadowGenerator.FILTER_PCF) { + engine.setColorWrite(false); + } + this.getTransformMatrix(); // generate the view/projection matrix + this._scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix); + if (this._useUBO) { + this._scene.getSceneUniformBuffer().unbindEffect(); + this._scene.finalizeSceneUbo(); + } + }); + // Blur if required after render. + this._shadowMap.onAfterUnbindObservable.add(() => { + if (this._sceneUBOs) { + this._scene.setSceneUniformBuffer(this._currentSceneUBO); + } + this._scene.updateTransformMatrix(); // restore the view/projection matrices of the active camera + if (this._filter === ShadowGenerator.FILTER_PCF) { + engine.setColorWrite(true); + } + if (!this.useBlurExponentialShadowMap && !this.useBlurCloseExponentialShadowMap) { + engine._debugPopGroup?.(1); + return; + } + const shadowMap = this.getShadowMapForRendering(); + if (shadowMap) { + this._scene.postProcessManager.directRender(this._blurPostProcesses, shadowMap.renderTarget, true); + engine.unBindFramebuffer(shadowMap.renderTarget, true); + } + engine._debugPopGroup?.(1); + }); + // Clear according to the chosen filter. + const clearZero = new Color4(0, 0, 0, 0); + const clearOne = new Color4(1.0, 1.0, 1.0, 1.0); + this._shadowMap.onClearObservable.add((engine) => { + if (this._filter === ShadowGenerator.FILTER_PCF) { + engine.clear(clearOne, false, true, false); + } + else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { + engine.clear(clearZero, true, true, false); + } + else { + engine.clear(clearOne, true, true, false); + } + }); + // Recreate on resize. + this._shadowMap.onResizeObservable.add((rtt) => { + this._storedUniqueId = this._shadowMap.uniqueId; + this._mapSize = rtt.getRenderSize(); + this._light._markMeshesAsLightDirty(); + this.recreateShadowMap(); + }); + // Ensures rendering groupids do not erase the depth buffer + // or we would lose the shadows information. + for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) { + this._shadowMap.setRenderingAutoClearDepthStencil(i, false); + } + } + async _initShaderSourceAsync(forceGLSL = false) { + const engine = this._scene.getEngine(); + if (engine.isWebGPU && !forceGLSL && !ShadowGenerator.ForceGLSL) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + await Promise.all([ + Promise.resolve().then(() => shadowMap_fragment$1), + Promise.resolve().then(() => shadowMap_vertex$1), + Promise.resolve().then(() => depthBoxBlur_fragment$1), + Promise.resolve().then(() => shadowMapFragmentSoftTransparentShadow$2), + ]); + } + else { + await Promise.all([ + Promise.resolve().then(() => shadowMap_fragment), + Promise.resolve().then(() => shadowMap_vertex), + Promise.resolve().then(() => depthBoxBlur_fragment), + Promise.resolve().then(() => shadowMapFragmentSoftTransparentShadow$1), + ]); + } + this._shadersLoaded = true; + } + _initializeBlurRTTAndPostProcesses() { + const engine = this._scene.getEngine(); + const targetSize = this._mapSize / this.blurScale; + if (!this.useKernelBlur || this.blurScale !== 1.0) { + this._shadowMap2 = new RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType, undefined, undefined, false); + this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE; + this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE; + this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); + } + if (this.useKernelBlur) { + this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + "KernelBlurX", new Vector2(1, 0), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType); + this._kernelBlurXPostprocess.width = targetSize; + this._kernelBlurXPostprocess.height = targetSize; + this._kernelBlurXPostprocess.externalTextureSamplerBinding = true; + this._kernelBlurXPostprocess.onApplyObservable.add((effect) => { + effect.setTexture("textureSampler", this._shadowMap); + }); + this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + "KernelBlurY", new Vector2(0, 1), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType); + this._kernelBlurXPostprocess.autoClear = false; + this._kernelBlurYPostprocess.autoClear = false; + if (this._textureType === 0) { + this._kernelBlurXPostprocess.packedFloat = true; + this._kernelBlurYPostprocess.packedFloat = true; + } + this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess]; + } + else { + this._boxBlurPostprocess = new PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType, undefined, undefined, undefined, undefined, this._shaderLanguage); + this._boxBlurPostprocess.externalTextureSamplerBinding = true; + this._boxBlurPostprocess.onApplyObservable.add((effect) => { + effect.setFloat2("screenSize", targetSize, targetSize); + effect.setTexture("textureSampler", this._shadowMap); + }); + this._boxBlurPostprocess.autoClear = false; + this._blurPostProcesses = [this._boxBlurPostprocess]; + } + } + _renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { + let index; + if (depthOnlySubMeshes.length) { + for (index = 0; index < depthOnlySubMeshes.length; index++) { + this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]); + } + } + for (index = 0; index < opaqueSubMeshes.length; index++) { + this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]); + } + for (index = 0; index < alphaTestSubMeshes.length; index++) { + this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]); + } + if (this._transparencyShadow) { + for (index = 0; index < transparentSubMeshes.length; index++) { + this._renderSubMeshForShadowMap(transparentSubMeshes.data[index], true); + } + } + else { + for (index = 0; index < transparentSubMeshes.length; index++) { + transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false; + } + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, mesh) { + effect.setMatrix("viewProjection", this.getTransformMatrix()); + } + _renderSubMeshForShadowMap(subMesh, isTransparent = false) { + const renderingMesh = subMesh.getRenderingMesh(); + const effectiveMesh = subMesh.getEffectiveMesh(); + const scene = this._scene; + const engine = scene.getEngine(); + const material = subMesh.getMaterial(); + effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; + if (!material || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) { + return; + } + // Culling + // Note: + // In rhs mode, we assume that meshes will be rendered in right-handed space (i.e. with an RHS camera), so the default value of material.sideOrientation is updated accordingly (see material constructor). + // However, when generating a shadow map, we render from the point of view of the light, whose view/projection matrices are always in lhs mode. + // We therefore need to "undo" the sideOrientation inversion that was previously performed when constructing the material. + const useRHS = scene.useRightHandedSystem; + const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0; + let sideOrientation = material._getEffectiveOrientation(renderingMesh); + if ((detNeg && !useRHS) || (!detNeg && useRHS)) { + sideOrientation = + sideOrientation === 0 ? 1 : 0; + } + const reverseSideOrientation = sideOrientation === 0; + engine.setState(material.backFaceCulling, undefined, undefined, reverseSideOrientation, material.cullBackFaces); + // Managing instances + const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); + if (batch.mustReturn) { + return; + } + const hardwareInstancedRendering = engine.getCaps().instancedArrays && + ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances); + if (this.customAllowRendering && !this.customAllowRendering(subMesh)) { + return; + } + if (this.isReady(subMesh, hardwareInstancedRendering, isTransparent)) { + subMesh._renderId = scene.getRenderId(); + const shadowDepthWrapper = material.shadowDepthWrapper; + const drawWrapper = shadowDepthWrapper?.getEffect(subMesh, this, engine.currentRenderPassId) ?? subMesh._getDrawWrapper(); + const effect = DrawWrapper.GetEffect(drawWrapper); + engine.enableEffect(drawWrapper); + if (!hardwareInstancedRendering) { + renderingMesh._bind(subMesh, effect, material.fillMode); + } + this.getTransformMatrix(); // make sure _cachedDirection et _cachedPosition are up to date + effect.setFloat3("biasAndScaleSM", this.bias, this.normalBias, this.depthScale); + if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) { + effect.setVector3("lightDataSM", this._cachedDirection); + } + else { + effect.setVector3("lightDataSM", this._cachedPosition); + } + const camera = this._getCamera(); + effect.setFloat2("depthValuesSM", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera)); + if (isTransparent && this.enableSoftTransparentShadow) { + effect.setFloat2("softTransparentShadowSM", effectiveMesh.visibility * material.alpha, this._opacityTexture?.getAlphaFromRGB ? 1 : 0); + } + if (shadowDepthWrapper) { + subMesh._setMainDrawWrapperOverride(drawWrapper); + if (shadowDepthWrapper.standalone) { + shadowDepthWrapper.baseMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh); + } + else { + material.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh); + } + subMesh._setMainDrawWrapperOverride(null); + } + else { + // Alpha test + if (this._opacityTexture) { + effect.setTexture("diffuseSampler", this._opacityTexture); + effect.setMatrix("diffuseMatrix", this._opacityTexture.getTextureMatrix() || this._defaultTextureMatrix); + } + // Bones + if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { + const skeleton = renderingMesh.skeleton; + if (skeleton.isUsingTextureForMatrices) { + const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh); + if (!boneTexture) { + return; + } + effect.setTexture("boneSampler", boneTexture); + effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); + } + else { + effect.setMatrices("mBones", skeleton.getTransformMatrices(renderingMesh)); + } + } + // Morph targets + BindMorphTargetParameters(renderingMesh, effect); + if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { + renderingMesh.morphTargetManager._bind(effect); + } + // Baked vertex animations + const bvaManager = subMesh.getMesh().bakedVertexAnimationManager; + if (bvaManager && bvaManager.isEnabled) { + bvaManager.bind(effect, hardwareInstancedRendering); + } + // Clip planes + bindClipPlane(effect, material, scene); + } + if (!this._useUBO && !shadowDepthWrapper) { + this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, effectiveMesh); + } + BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer()); + this._scene.getSceneUniformBuffer().bindUniformBuffer(); + const world = effectiveMesh.getWorldMatrix(); + // In the non hardware instanced mode, the Mesh ubo update is done by the callback passed to renderingMesh._processRendering (see below) + if (hardwareInstancedRendering) { + effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); + effectiveMesh.transferToEffect(world); + } + if (this.forceBackFacesOnly) { + engine.setState(true, 0, false, true, material.cullBackFaces); + } + // Observables + this.onBeforeShadowMapRenderMeshObservable.notifyObservers(renderingMesh); + this.onBeforeShadowMapRenderObservable.notifyObservers(effect); + // Draw + renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, worldOverride) => { + if (effectiveMesh !== renderingMesh && !isInstance) { + renderingMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); + renderingMesh.transferToEffect(worldOverride); + } + else { + effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); + effectiveMesh.transferToEffect(isInstance ? worldOverride : world); + } + }); + if (this.forceBackFacesOnly) { + engine.setState(true, 0, false, false, material.cullBackFaces); + } + // Observables + this.onAfterShadowMapRenderObservable.notifyObservers(effect); + this.onAfterShadowMapRenderMeshObservable.notifyObservers(renderingMesh); + } + else { + // Need to reset refresh rate of the shadowMap + if (this._shadowMap) { + this._shadowMap.resetRefreshCounter(); + } + } + } + _applyFilterValues() { + if (!this._shadowMap) { + return; + } + if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) { + this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE); + } + else { + this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); + } + } + /** + * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects. + * @param onCompiled Callback triggered at the and of the effects compilation + * @param options Sets of optional options forcing the compilation with different modes + */ + forceCompilation(onCompiled, options) { + const localOptions = { + useInstances: false, + ...options, + }; + const shadowMap = this.getShadowMap(); + if (!shadowMap) { + if (onCompiled) { + onCompiled(this); + } + return; + } + const renderList = shadowMap.renderList; + if (!renderList) { + if (onCompiled) { + onCompiled(this); + } + return; + } + const subMeshes = []; + for (const mesh of renderList) { + subMeshes.push(...mesh.subMeshes); + } + if (subMeshes.length === 0) { + if (onCompiled) { + onCompiled(this); + } + return; + } + let currentIndex = 0; + const checkReady = () => { + if (!this._scene || !this._scene.getEngine()) { + return; + } + while (this.isReady(subMeshes[currentIndex], localOptions.useInstances, subMeshes[currentIndex].getMaterial()?.needAlphaBlendingForMesh(subMeshes[currentIndex].getMesh()) ?? false)) { + currentIndex++; + if (currentIndex >= subMeshes.length) { + if (onCompiled) { + onCompiled(this); + } + return; + } + } + setTimeout(checkReady, 16); + }; + checkReady(); + } + /** + * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects. + * @param options Sets of optional options forcing the compilation with different modes + * @returns A promise that resolves when the compilation completes + */ + forceCompilationAsync(options) { + return new Promise((resolve) => { + this.forceCompilation(() => { + resolve(); + }, options); + }); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _isReadyCustomDefines(defines, subMesh, useInstances) { } + _prepareShadowDefines(subMesh, useInstances, defines, isTransparent) { + defines.push("#define SM_LIGHTTYPE_" + this._light.getClassName().toUpperCase()); + defines.push("#define SM_FLOAT " + (this._textureType !== 0 ? "1" : "0")); + defines.push("#define SM_ESM " + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? "1" : "0")); + defines.push("#define SM_DEPTHTEXTURE " + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? "1" : "0")); + const mesh = subMesh.getMesh(); + // Normal bias. + defines.push("#define SM_NORMALBIAS " + (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind) ? "1" : "0")); + defines.push("#define SM_DIRECTIONINLIGHTDATA " + (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? "1" : "0")); + // Point light + defines.push("#define SM_USEDISTANCE " + (this._light.needCube() ? "1" : "0")); + // Soft transparent shadows + defines.push("#define SM_SOFTTRANSPARENTSHADOW " + (this.enableSoftTransparentShadow && isTransparent ? "1" : "0")); + this._isReadyCustomDefines(defines, subMesh, useInstances); + return defines; + } + /** + * Determine whether the shadow generator is ready or not (mainly all effects and related post processes needs to be ready). + * @param subMesh The submesh we want to render in the shadow map + * @param useInstances Defines whether will draw in the map using instances + * @param isTransparent Indicates that isReady is called for a transparent subMesh + * @returns true if ready otherwise, false + */ + isReady(subMesh, useInstances, isTransparent) { + if (!this._shadersLoaded) { + return false; + } + const material = subMesh.getMaterial(), shadowDepthWrapper = material?.shadowDepthWrapper; + this._opacityTexture = null; + if (!material) { + return false; + } + const defines = []; + this._prepareShadowDefines(subMesh, useInstances, defines, isTransparent); + if (shadowDepthWrapper) { + if (!shadowDepthWrapper.isReadyForSubMesh(subMesh, defines, this, useInstances, this._scene.getEngine().currentRenderPassId)) { + return false; + } + } + else { + const subMeshEffect = subMesh._getDrawWrapper(undefined, true); + let effect = subMeshEffect.effect; + let cachedDefines = subMeshEffect.defines; + const attribs = [VertexBuffer.PositionKind]; + const mesh = subMesh.getMesh(); + let useNormal = false; + let uv1 = false; + let uv2 = false; + const color = false; + // Normal bias. + if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) { + attribs.push(VertexBuffer.NormalKind); + defines.push("#define NORMAL"); + useNormal = true; + if (mesh.nonUniformScaling) { + defines.push("#define NONUNIFORMSCALING"); + } + } + // Alpha test + const needAlphaTesting = material.needAlphaTestingForMesh(mesh); + if (needAlphaTesting || material.needAlphaBlendingForMesh(mesh)) { + if (this.useOpacityTextureForTransparentShadow) { + this._opacityTexture = material.opacityTexture; + } + else { + this._opacityTexture = material.getAlphaTestTexture(); + } + if (this._opacityTexture) { + if (!this._opacityTexture.isReady()) { + return false; + } + const alphaCutOff = material.alphaCutOff ?? ShadowGenerator.DEFAULT_ALPHA_CUTOFF; + defines.push("#define ALPHATEXTURE"); + if (needAlphaTesting) { + defines.push(`#define ALPHATESTVALUE ${alphaCutOff}${alphaCutOff % 1 === 0 ? "." : ""}`); + } + if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { + attribs.push(VertexBuffer.UVKind); + defines.push("#define UV1"); + uv1 = true; + } + if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) { + if (this._opacityTexture.coordinatesIndex === 1) { + attribs.push(VertexBuffer.UV2Kind); + defines.push("#define UV2"); + uv2 = true; + } + } + } + } + // Bones + const fallbacks = new EffectFallbacks(); + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + attribs.push(VertexBuffer.MatricesIndicesKind); + attribs.push(VertexBuffer.MatricesWeightsKind); + if (mesh.numBoneInfluencers > 4) { + attribs.push(VertexBuffer.MatricesIndicesExtraKind); + attribs.push(VertexBuffer.MatricesWeightsExtraKind); + } + const skeleton = mesh.skeleton; + defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); + if (mesh.numBoneInfluencers > 0) { + fallbacks.addCPUSkinningFallback(0, mesh); + } + if (skeleton.isUsingTextureForMatrices) { + defines.push("#define BONETEXTURE"); + } + else { + defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); + } + } + else { + defines.push("#define NUM_BONE_INFLUENCERS 0"); + } + // Morph targets + const numMorphInfluencers = mesh.morphTargetManager + ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph + useNormal, // useNormalMorph + false, // useTangentMorph + uv1, // useUVMorph + uv2, // useUV2Morph + color // useColorMorph + ) + : 0; + // ClipPlanes + prepareStringDefinesForClipPlanes(material, this._scene, defines); + // Instances + if (useInstances) { + defines.push("#define INSTANCES"); + PushAttributesForInstances(attribs); + if (subMesh.getRenderingMesh().hasThinInstances) { + defines.push("#define THIN_INSTANCES"); + } + } + if (this.customShaderOptions) { + if (this.customShaderOptions.defines) { + for (const define of this.customShaderOptions.defines) { + if (defines.indexOf(define) === -1) { + defines.push(define); + } + } + } + } + // Baked vertex animations + const bvaManager = mesh.bakedVertexAnimationManager; + if (bvaManager && bvaManager.isEnabled) { + defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"); + if (useInstances) { + attribs.push("bakedVertexAnimationSettingsInstanced"); + } + } + // Get correct effect + const join = defines.join("\n"); + if (cachedDefines !== join) { + cachedDefines = join; + let shaderName = "shadowMap"; + const uniforms = [ + "world", + "mBones", + "viewProjection", + "diffuseMatrix", + "lightDataSM", + "depthValuesSM", + "biasAndScaleSM", + "morphTargetInfluences", + "morphTargetCount", + "boneTextureWidth", + "softTransparentShadowSM", + "morphTargetTextureInfo", + "morphTargetTextureIndices", + "bakedVertexAnimationSettings", + "bakedVertexAnimationTextureSizeInverted", + "bakedVertexAnimationTime", + "bakedVertexAnimationTexture", + ]; + const samplers = ["diffuseSampler", "boneSampler", "morphTargets", "bakedVertexAnimationTexture"]; + const uniformBuffers = ["Scene", "Mesh"]; + addClipPlaneUniforms(uniforms); + // Custom shader? + if (this.customShaderOptions) { + shaderName = this.customShaderOptions.shaderName; + if (this.customShaderOptions.attributes) { + for (const attrib of this.customShaderOptions.attributes) { + if (attribs.indexOf(attrib) === -1) { + attribs.push(attrib); + } + } + } + if (this.customShaderOptions.uniforms) { + for (const uniform of this.customShaderOptions.uniforms) { + if (uniforms.indexOf(uniform) === -1) { + uniforms.push(uniform); + } + } + } + if (this.customShaderOptions.samplers) { + for (const sampler of this.customShaderOptions.samplers) { + if (samplers.indexOf(sampler) === -1) { + samplers.push(sampler); + } + } + } + } + const engine = this._scene.getEngine(); + effect = engine.createEffect(shaderName, { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: join, + fallbacks: fallbacks, + onCompiled: null, + onError: null, + indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers }, + shaderLanguage: this._shaderLanguage, + }, engine); + subMeshEffect.setEffect(effect, cachedDefines); + } + if (!effect.isReady()) { + return false; + } + } + if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) { + if (!this._blurPostProcesses || !this._blurPostProcesses.length) { + this._initializeBlurRTTAndPostProcesses(); + } + } + if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) { + return false; + } + if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) { + return false; + } + if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) { + return false; + } + return true; + } + /** + * Prepare all the defines in a material relying on a shadow map at the specified light index. + * @param defines Defines of the material we want to update + * @param lightIndex Index of the light in the enabled light list of the material + */ + prepareDefines(defines, lightIndex) { + const scene = this._scene; + const light = this._light; + if (!scene.shadowsEnabled || !light.shadowEnabled) { + return; + } + defines["SHADOW" + lightIndex] = true; + if (this.useContactHardeningShadow) { + defines["SHADOWPCSS" + lightIndex] = true; + if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) { + defines["SHADOWLOWQUALITY" + lightIndex] = true; + } + else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) { + defines["SHADOWMEDIUMQUALITY" + lightIndex] = true; + } + // else default to high. + } + else if (this.usePercentageCloserFiltering) { + defines["SHADOWPCF" + lightIndex] = true; + if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) { + defines["SHADOWLOWQUALITY" + lightIndex] = true; + } + else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) { + defines["SHADOWMEDIUMQUALITY" + lightIndex] = true; + } + // else default to high. + } + else if (this.usePoissonSampling) { + defines["SHADOWPOISSON" + lightIndex] = true; + } + else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { + defines["SHADOWESM" + lightIndex] = true; + } + else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) { + defines["SHADOWCLOSEESM" + lightIndex] = true; + } + if (light.needCube()) { + defines["SHADOWCUBE" + lightIndex] = true; + } + } + /** + * Binds the shadow related information inside of an effect (information like near, far, darkness... + * defined in the generator but impacting the effect). + * @param lightIndex Index of the light in the enabled light list of the material owning the effect + * @param effect The effect we are binding the information for + */ + bindShadowLight(lightIndex, effect) { + const light = this._light; + const scene = this._scene; + if (!scene.shadowsEnabled || !light.shadowEnabled) { + return; + } + const camera = this._getCamera(); + const shadowMap = this.getShadowMap(); + if (!shadowMap) { + return; + } + if (!light.needCube()) { + effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix()); + } + // Only PCF uses depth stencil texture. + const shadowMapForRendering = this.getShadowMapForRendering(); + if (this._filter === ShadowGenerator.FILTER_PCF) { + effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMapForRendering); + light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex); + } + else if (this._filter === ShadowGenerator.FILTER_PCSS) { + effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMapForRendering); + effect.setTexture("depthTexture" + lightIndex, shadowMapForRendering); + light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex); + } + else { + effect.setTexture("shadowTexture" + lightIndex, shadowMapForRendering); + light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex); + } + light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex); + } + /** + * Gets the view matrix used to render the shadow map. + */ + get viewMatrix() { + return this._viewMatrix; + } + /** + * Gets the projection matrix used to render the shadow map. + */ + get projectionMatrix() { + return this._projectionMatrix; + } + /** + * Gets the transformation matrix used to project the meshes into the map from the light point of view. + * (eq to shadow projection matrix * light transform matrix) + * @returns The transform matrix used to create the shadow map + */ + getTransformMatrix() { + const scene = this._scene; + if (this._currentRenderId === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) { + return this._transformMatrix; + } + this._currentRenderId = scene.getRenderId(); + this._currentFaceIndexCache = this._currentFaceIndex; + let lightPosition = this._light.position; + if (this._light.computeTransformedInformation()) { + lightPosition = this._light.transformedPosition; + } + Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection); + if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) { + this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light + } + if (this._light.needProjectionMatrixCompute() || + !this._cachedPosition || + !this._cachedDirection || + !lightPosition.equals(this._cachedPosition) || + !this._lightDirection.equals(this._cachedDirection)) { + this._cachedPosition.copyFrom(lightPosition); + this._cachedDirection.copyFrom(this._lightDirection); + Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), Vector3.Up(), this._viewMatrix); + const shadowMap = this.getShadowMap(); + if (shadowMap) { + const renderList = shadowMap.renderList; + if (renderList) { + this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList); + } + } + this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); + } + return this._transformMatrix; + } + /** + * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between + * Cube and 2D textures for instance. + */ + recreateShadowMap() { + const shadowMap = this._shadowMap; + if (!shadowMap) { + return; + } + // Track render list. + const renderList = shadowMap.renderList; + // Clean up existing data. + this._disposeRTTandPostProcesses(); + // Reinitializes. + this._initializeGenerator(); + // Reaffect the filter to ensure a correct fallback if necessary. + this.filter = this._filter; + // Reaffect the filter. + this._applyFilterValues(); + // Reaffect Render List. + if (renderList) { + // Note: don't do this._shadowMap!.renderList = renderList; + // The renderList hooked array is accessing the old RenderTargetTexture (see RenderTargetTexture._hookArray), which is disposed at this point (by the call to _disposeRTTandPostProcesses) + if (!this._shadowMap.renderList) { + this._shadowMap.renderList = []; + } + for (const mesh of renderList) { + this._shadowMap.renderList.push(mesh); + } + } + else { + this._shadowMap.renderList = null; + } + } + _disposeBlurPostProcesses() { + if (this._shadowMap2) { + this._shadowMap2.dispose(); + this._shadowMap2 = null; + } + if (this._boxBlurPostprocess) { + this._boxBlurPostprocess.dispose(); + this._boxBlurPostprocess = null; + } + if (this._kernelBlurXPostprocess) { + this._kernelBlurXPostprocess.dispose(); + this._kernelBlurXPostprocess = null; + } + if (this._kernelBlurYPostprocess) { + this._kernelBlurYPostprocess.dispose(); + this._kernelBlurYPostprocess = null; + } + this._blurPostProcesses = []; + } + _disposeRTTandPostProcesses() { + if (this._shadowMap) { + this._shadowMap.dispose(); + this._shadowMap = null; + } + this._disposeBlurPostProcesses(); + } + _disposeSceneUBOs() { + if (this._sceneUBOs) { + for (const ubo of this._sceneUBOs) { + ubo.dispose(); + } + this._sceneUBOs = []; + } + } + /** + * Disposes the ShadowGenerator. + * Returns nothing. + */ + dispose() { + this._disposeRTTandPostProcesses(); + this._disposeSceneUBOs(); + if (this._light) { + if (this._light._shadowGenerators) { + const iterator = this._light._shadowGenerators.entries(); + for (let entry = iterator.next(); entry.done !== true; entry = iterator.next()) { + const [camera, shadowGenerator] = entry.value; + if (shadowGenerator === this) { + this._light._shadowGenerators.delete(camera); + } + } + if (this._light._shadowGenerators.size === 0) { + this._light._shadowGenerators = null; + } + } + this._light._markMeshesAsLightDirty(); + } + this.onBeforeShadowMapRenderMeshObservable.clear(); + this.onBeforeShadowMapRenderObservable.clear(); + this.onAfterShadowMapRenderMeshObservable.clear(); + this.onAfterShadowMapRenderObservable.clear(); + } + /** + * Serializes the shadow generator setup to a json object. + * @returns The serialized JSON object + */ + serialize() { + const serializationObject = {}; + const shadowMap = this.getShadowMap(); + if (!shadowMap) { + return serializationObject; + } + serializationObject.className = this.getClassName(); + serializationObject.lightId = this._light.id; + serializationObject.cameraId = this._camera?.id; + serializationObject.id = this.id; + serializationObject.mapSize = shadowMap.getRenderSize(); + serializationObject.forceBackFacesOnly = this.forceBackFacesOnly; + serializationObject.darkness = this.getDarkness(); + serializationObject.transparencyShadow = this._transparencyShadow; + serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff; + serializationObject.bias = this.bias; + serializationObject.normalBias = this.normalBias; + serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering; + serializationObject.useContactHardeningShadow = this.useContactHardeningShadow; + serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio; + serializationObject.filteringQuality = this.filteringQuality; + serializationObject.useExponentialShadowMap = this.useExponentialShadowMap; + serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap; + serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap; + serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap; + serializationObject.usePoissonSampling = this.usePoissonSampling; + serializationObject.depthScale = this.depthScale; + serializationObject.blurBoxOffset = this.blurBoxOffset; + serializationObject.blurKernel = this.blurKernel; + serializationObject.blurScale = this.blurScale; + serializationObject.useKernelBlur = this.useKernelBlur; + serializationObject.renderList = []; + if (shadowMap.renderList) { + for (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) { + const mesh = shadowMap.renderList[meshIndex]; + serializationObject.renderList.push(mesh.id); + } + } + return serializationObject; + } + /** + * Parses a serialized ShadowGenerator and returns a new ShadowGenerator. + * @param parsedShadowGenerator The JSON object to parse + * @param scene The scene to create the shadow map for + * @param constr A function that builds a shadow generator or undefined to create an instance of the default shadow generator + * @returns The parsed shadow generator + */ + static Parse(parsedShadowGenerator, scene, constr) { + const light = scene.getLightById(parsedShadowGenerator.lightId); + const camera = parsedShadowGenerator.cameraId !== undefined ? scene.getCameraById(parsedShadowGenerator.cameraId) : null; + const shadowGenerator = constr ? constr(parsedShadowGenerator.mapSize, light, camera) : new ShadowGenerator(parsedShadowGenerator.mapSize, light, undefined, camera); + const shadowMap = shadowGenerator.getShadowMap(); + for (let meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) { + const meshes = scene.getMeshesById(parsedShadowGenerator.renderList[meshIndex]); + meshes.forEach(function (mesh) { + if (!shadowMap) { + return; + } + if (!shadowMap.renderList) { + shadowMap.renderList = []; + } + shadowMap.renderList.push(mesh); + }); + } + if (parsedShadowGenerator.id !== undefined) { + shadowGenerator.id = parsedShadowGenerator.id; + } + shadowGenerator.forceBackFacesOnly = !!parsedShadowGenerator.forceBackFacesOnly; + if (parsedShadowGenerator.darkness !== undefined) { + shadowGenerator.setDarkness(parsedShadowGenerator.darkness); + } + if (parsedShadowGenerator.transparencyShadow) { + shadowGenerator.setTransparencyShadow(true); + } + if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) { + shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff; + } + if (parsedShadowGenerator.bias !== undefined) { + shadowGenerator.bias = parsedShadowGenerator.bias; + } + if (parsedShadowGenerator.normalBias !== undefined) { + shadowGenerator.normalBias = parsedShadowGenerator.normalBias; + } + if (parsedShadowGenerator.usePercentageCloserFiltering) { + shadowGenerator.usePercentageCloserFiltering = true; + } + else if (parsedShadowGenerator.useContactHardeningShadow) { + shadowGenerator.useContactHardeningShadow = true; + } + else if (parsedShadowGenerator.usePoissonSampling) { + shadowGenerator.usePoissonSampling = true; + } + else if (parsedShadowGenerator.useExponentialShadowMap) { + shadowGenerator.useExponentialShadowMap = true; + } + else if (parsedShadowGenerator.useBlurExponentialShadowMap) { + shadowGenerator.useBlurExponentialShadowMap = true; + } + else if (parsedShadowGenerator.useCloseExponentialShadowMap) { + shadowGenerator.useCloseExponentialShadowMap = true; + } + else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) { + shadowGenerator.useBlurCloseExponentialShadowMap = true; + } + // Backward compat + else if (parsedShadowGenerator.useVarianceShadowMap) { + shadowGenerator.useExponentialShadowMap = true; + } + else if (parsedShadowGenerator.useBlurVarianceShadowMap) { + shadowGenerator.useBlurExponentialShadowMap = true; + } + if (parsedShadowGenerator.contactHardeningLightSizeUVRatio !== undefined) { + shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio; + } + if (parsedShadowGenerator.filteringQuality !== undefined) { + shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality; + } + if (parsedShadowGenerator.depthScale) { + shadowGenerator.depthScale = parsedShadowGenerator.depthScale; + } + if (parsedShadowGenerator.blurScale) { + shadowGenerator.blurScale = parsedShadowGenerator.blurScale; + } + if (parsedShadowGenerator.blurBoxOffset) { + shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset; + } + if (parsedShadowGenerator.useKernelBlur) { + shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur; + } + if (parsedShadowGenerator.blurKernel) { + shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel; + } + return shadowGenerator; + } +} +/** + * Name of the shadow generator class + */ +ShadowGenerator.CLASSNAME = "ShadowGenerator"; +/** + * Force all the shadow generators to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +ShadowGenerator.ForceGLSL = false; +/** + * Shadow generator mode None: no filtering applied. + */ +ShadowGenerator.FILTER_NONE = 0; +/** + * Shadow generator mode ESM: Exponential Shadow Mapping. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ +ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1; +/** + * Shadow generator mode Poisson Sampling: Percentage Closer Filtering. + * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength) + */ +ShadowGenerator.FILTER_POISSONSAMPLING = 2; +/** + * Shadow generator mode ESM: Blurred Exponential Shadow Mapping. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ +ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3; +/** + * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing + * edge artifacts on steep falloff. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ +ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4; +/** + * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing + * edge artifacts on steep falloff. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ +ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5; +/** + * Shadow generator mode PCF: Percentage Closer Filtering + * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 + * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html) + */ +ShadowGenerator.FILTER_PCF = 6; +/** + * Shadow generator mode PCSS: Percentage Closering Soft Shadow. + * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 + * Contact Hardening + */ +ShadowGenerator.FILTER_PCSS = 7; +/** + * Reserved for PCF and PCSS + * Highest Quality. + * + * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts. + * + * Execute PCSS with 32 taps blocker search and 64 taps PCF. + */ +ShadowGenerator.QUALITY_HIGH = 0; +/** + * Reserved for PCF and PCSS + * Good tradeoff for quality/perf cross devices + * + * Execute PCF on a 3*3 kernel. + * + * Execute PCSS with 16 taps blocker search and 32 taps PCF. + */ +ShadowGenerator.QUALITY_MEDIUM = 1; +/** + * Reserved for PCF and PCSS + * The lowest quality but the fastest. + * + * Execute PCF on a 1*1 kernel. + * + * Execute PCSS with 16 taps blocker search and 16 taps PCF. + */ +ShadowGenerator.QUALITY_LOW = 2; +/** + * Defines the default alpha cutoff value used for transparent alpha tested materials. + */ +ShadowGenerator.DEFAULT_ALPHA_CUTOFF = 0.5; +/** + * @internal + */ +ShadowGenerator._SceneComponentInitialization = (_) => { + throw _WarnImport("ShadowGeneratorSceneComponent"); +}; + +// Do not edit. +const name$8g = "clipPlaneFragmentDeclaration"; +const shader$8f = `#ifdef CLIPPLANE +varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +varying float fClipDistance6; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$8g]) { + ShaderStore.IncludesShadersStore[name$8g] = shader$8f; +} +/** @internal */ +const clipPlaneFragmentDeclaration$1 = { name: name$8g, shader: shader$8f }; + +const clipPlaneFragmentDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + clipPlaneFragmentDeclaration: clipPlaneFragmentDeclaration$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$8f = "packingFunctions"; +const shader$8e = `vec4 pack(float depth) +{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} +float unpack(vec4 color) +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$8f]) { + ShaderStore.IncludesShadersStore[name$8f] = shader$8e; +} +/** @internal */ +const packingFunctions$1 = { name: name$8f, shader: shader$8e }; + +const packingFunctions$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + packingFunctions: packingFunctions$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$8e = "clipPlaneFragment"; +const shader$8d = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +if (false) {} +#endif +#ifdef CLIPPLANE +else if (fClipDistance>0.0) +{discard;} +#endif +#ifdef CLIPPLANE2 +else if (fClipDistance2>0.0) +{discard;} +#endif +#ifdef CLIPPLANE3 +else if (fClipDistance3>0.0) +{discard;} +#endif +#ifdef CLIPPLANE4 +else if (fClipDistance4>0.0) +{discard;} +#endif +#ifdef CLIPPLANE5 +else if (fClipDistance5>0.0) +{discard;} +#endif +#ifdef CLIPPLANE6 +else if (fClipDistance6>0.0) +{discard;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$8e]) { + ShaderStore.IncludesShadersStore[name$8e] = shader$8d; +} +/** @internal */ +const clipPlaneFragment$1 = { name: name$8e, shader: shader$8d }; + +const clipPlaneFragment$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + clipPlaneFragment: clipPlaneFragment$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$8d = "depthPixelShader"; +const shader$8c = `#ifdef ALPHATEST +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include +varying float vDepthMetric; +#ifdef PACKED +#include +#endif +#ifdef STORE_CAMERASPACE_Z +varying vec4 vViewPos; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +#ifdef STORE_CAMERASPACE_Z +#ifdef PACKED +gl_FragColor=pack(vViewPos.z); +#else +gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); +#endif +#else +#ifdef NONLINEARDEPTH +#ifdef PACKED +gl_FragColor=pack(gl_FragCoord.z); +#else +gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); +#endif +#else +#ifdef PACKED +gl_FragColor=pack(vDepthMetric); +#else +gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); +#endif +#endif +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$8d]) { + ShaderStore.ShadersStore[name$8d] = shader$8c; +} +/** @internal */ +const depthPixelShader = { name: name$8d, shader: shader$8c }; + +const depth_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + depthPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$8c = "bonesDeclaration"; +const shader$8b = `#if NUM_BONE_INFLUENCERS>0 +attribute vec4 matricesIndices;attribute vec4 matricesWeights; +#if NUM_BONE_INFLUENCERS>4 +attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; +#endif +#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#ifdef BONETEXTURE +uniform highp sampler2D boneSampler;uniform float boneTextureWidth; +#else +uniform mat4 mBones[BonesPerMesh]; +#endif +#ifdef BONES_VELOCITY_ENABLED +uniform mat4 mPreviousBones[BonesPerMesh]; +#endif +#ifdef BONETEXTURE +#define inline +mat4 readMatrixFromRawSampler(sampler2D smp,float index) +{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$8c]) { + ShaderStore.IncludesShadersStore[name$8c] = shader$8b; +} +/** @internal */ +const bonesDeclaration$1 = { name: name$8c, shader: shader$8b }; + +const bonesDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bonesDeclaration: bonesDeclaration$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$8b = "bakedVertexAnimationDeclaration"; +const shader$8a = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; +#ifdef INSTANCES +attribute vec4 bakedVertexAnimationSettingsInstanced; +#endif +#define inline +mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) +{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$8b]) { + ShaderStore.IncludesShadersStore[name$8b] = shader$8a; +} + +// Do not edit. +const name$8a = "morphTargetsVertexGlobalDeclaration"; +const shader$89 = `#ifdef MORPHTARGETS +uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; +#ifdef MORPHTARGETS_TEXTURE +uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) +{ +float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} +vec4 readVector4FromRawSampler(int targetIndex,float vertexIndex) +{ +float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV);} +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$8a]) { + ShaderStore.IncludesShadersStore[name$8a] = shader$89; +} +/** @internal */ +const morphTargetsVertexGlobalDeclaration$1 = { name: name$8a, shader: shader$89 }; + +const morphTargetsVertexGlobalDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + morphTargetsVertexGlobalDeclaration: morphTargetsVertexGlobalDeclaration$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$89 = "morphTargetsVertexDeclaration"; +const shader$88 = `#ifdef MORPHTARGETS +#ifndef MORPHTARGETS_TEXTURE +#ifdef MORPHTARGETS_POSITION +attribute vec3 position{X}; +#endif +#ifdef MORPHTARGETS_NORMAL +attribute vec3 normal{X}; +#endif +#ifdef MORPHTARGETS_TANGENT +attribute vec3 tangent{X}; +#endif +#ifdef MORPHTARGETS_UV +attribute vec2 uv_{X}; +#endif +#ifdef MORPHTARGETS_UV2 +attribute vec2 uv2_{X}; +#endif +#elif {X}==0 +uniform int morphTargetCount; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$89]) { + ShaderStore.IncludesShadersStore[name$89] = shader$88; +} +/** @internal */ +const morphTargetsVertexDeclaration$1 = { name: name$89, shader: shader$88 }; + +const morphTargetsVertexDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + morphTargetsVertexDeclaration: morphTargetsVertexDeclaration$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$88 = "clipPlaneVertexDeclaration"; +const shader$87 = `#ifdef CLIPPLANE +uniform vec4 vClipPlane;varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;varying float fClipDistance6; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$88]) { + ShaderStore.IncludesShadersStore[name$88] = shader$87; +} +/** @internal */ +const clipPlaneVertexDeclaration$1 = { name: name$88, shader: shader$87 }; + +const clipPlaneVertexDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + clipPlaneVertexDeclaration: clipPlaneVertexDeclaration$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$87 = "instancesDeclaration"; +const shader$86 = `#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#ifdef INSTANCESCOLOR +attribute vec4 instanceColor; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) +attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; +#ifdef THIN_INSTANCES +uniform mat4 previousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) +uniform mat4 previousWorld; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$87]) { + ShaderStore.IncludesShadersStore[name$87] = shader$86; +} + +// Do not edit. +const name$86 = "pointCloudVertexDeclaration"; +const shader$85 = `#ifdef POINTSIZE +uniform float pointSize; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$86]) { + ShaderStore.IncludesShadersStore[name$86] = shader$85; +} + +// Do not edit. +const name$85 = "morphTargetsVertexGlobal"; +const shader$84 = `#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +float vertexID; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$85]) { + ShaderStore.IncludesShadersStore[name$85] = shader$84; +} +/** @internal */ +const morphTargetsVertexGlobal$1 = { name: name$85, shader: shader$84 }; + +const morphTargetsVertexGlobal$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + morphTargetsVertexGlobal: morphTargetsVertexGlobal$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$84 = "morphTargetsVertex"; +const shader$83 = `#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +#if {X}==0 +for (int i=0; i=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x; +#ifdef MORPHTARGETS_POSITION +positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i]; +#endif +#ifdef MORPHTARGETTEXTURE_HASPOSITIONS +vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i]; +#endif +#ifdef MORPHTARGETTEXTURE_HASNORMALS +vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i]; +#endif +#ifdef MORPHTARGETTEXTURE_HASUVS +vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i]; +#endif +#ifdef MORPHTARGETTEXTURE_HASTANGENTS +vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_UV2 +uv2Updated+=(readVector3FromRawSampler(i,vertexID).xy-uv2)*morphTargetInfluences[i]; +#endif +#ifdef MORPHTARGETTEXTURE_HASUV2S +vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_COLOR +colorUpdated+=(readVector4FromRawSampler(i,vertexID)-color)*morphTargetInfluences[i]; +#endif +} +#endif +#else +#ifdef MORPHTARGETS_POSITION +positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV2 +uv2Updated+=(uv2_{X}-uv2)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_COLOR +colorUpdated+=(color{X}-color)*morphTargetInfluences[{X}]; +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$84]) { + ShaderStore.IncludesShadersStore[name$84] = shader$83; +} +/** @internal */ +const morphTargetsVertex$1 = { name: name$84, shader: shader$83 }; + +const morphTargetsVertex$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + morphTargetsVertex: morphTargetsVertex$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$83 = "instancesVertex"; +const shader$82 = `#ifdef INSTANCES +mat4 finalWorld=mat4(world0,world1,world2,world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) +mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1, +previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +finalWorld=world*finalWorld; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +mat4 finalWorld=world; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) +mat4 finalPreviousWorld=previousWorld; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$83]) { + ShaderStore.IncludesShadersStore[name$83] = shader$82; +} + +// Do not edit. +const name$82 = "bonesVertex"; +const shader$81 = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#if NUM_BONE_INFLUENCERS>0 +mat4 influence; +#ifdef BONETEXTURE +influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; +#endif +#else +influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$82]) { + ShaderStore.IncludesShadersStore[name$82] = shader$81; +} +/** @internal */ +const bonesVertex$1 = { name: name$82, shader: shader$81 }; + +const bonesVertex$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bonesVertex: bonesVertex$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$81 = "bakedVertexAnimation"; +const shader$80 = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +{ +#ifdef INSTANCES +#define BVASNAME bakedVertexAnimationSettingsInstanced +#else +#define BVASNAME bakedVertexAnimationSettings +#endif +float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; +#endif +finalWorld=finalWorld*VATInfluence;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$81]) { + ShaderStore.IncludesShadersStore[name$81] = shader$80; +} + +// Do not edit. +const name$80 = "clipPlaneVertex"; +const shader$7$ = `#ifdef CLIPPLANE +fClipDistance=dot(worldPos,vClipPlane); +#endif +#ifdef CLIPPLANE2 +fClipDistance2=dot(worldPos,vClipPlane2); +#endif +#ifdef CLIPPLANE3 +fClipDistance3=dot(worldPos,vClipPlane3); +#endif +#ifdef CLIPPLANE4 +fClipDistance4=dot(worldPos,vClipPlane4); +#endif +#ifdef CLIPPLANE5 +fClipDistance5=dot(worldPos,vClipPlane5); +#endif +#ifdef CLIPPLANE6 +fClipDistance6=dot(worldPos,vClipPlane6); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$80]) { + ShaderStore.IncludesShadersStore[name$80] = shader$7$; +} +/** @internal */ +const clipPlaneVertex$1 = { name: name$80, shader: shader$7$ }; + +const clipPlaneVertex$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + clipPlaneVertex: clipPlaneVertex$1 +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7$ = "pointCloudVertex"; +const shader$7_ = `#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$7$]) { + ShaderStore.IncludesShadersStore[name$7$] = shader$7_; +} + +// Do not edit. +const name$7_ = "depthVertexShader"; +const shader$7Z = `attribute vec3 position; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +uniform mat4 viewProjection;uniform vec2 depthValues; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#ifdef STORE_CAMERASPACE_Z +uniform mat4 view;varying vec4 vViewPos; +#endif +#include +varying float vDepthMetric; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef UV2 +vec2 uv2Updated=uv2; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#include +gl_Position=viewProjection*worldPos; +#ifdef STORE_CAMERASPACE_Z +vViewPos=view*worldPos; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); +#else +vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); +#endif +#endif +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); +#endif +#endif +#include +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7_]) { + ShaderStore.ShadersStore[name$7_] = shader$7Z; +} +/** @internal */ +const depthVertexShader = { name: name$7_, shader: shader$7Z }; + +const depth_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + depthVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This represents a depth renderer in Babylon. + * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing + */ +class DepthRenderer { + /** + * Gets the shader language used in this material. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Sets a specific material to be used to render a mesh/a list of meshes by the depth renderer + * @param mesh mesh or array of meshes + * @param material material to use by the depth render when rendering the mesh(es). If undefined is passed, the specific material created by the depth renderer will be used. + */ + setMaterialForRendering(mesh, material) { + this._depthMap.setMaterialForRendering(mesh, material); + } + /** + * Instantiates a depth renderer + * @param scene The scene the renderer belongs to + * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT) + * @param camera The camera to be used to render the depth map (default: scene's active camera) + * @param storeNonLinearDepth Defines whether the depth is stored linearly like in Babylon Shadows or directly like glFragCoord.z + * @param samplingMode The sampling mode to be used with the render target (Linear, Nearest...) (default: TRILINEAR_SAMPLINGMODE) + * @param storeCameraSpaceZ Defines whether the depth stored is the Z coordinate in camera space. If true, storeNonLinearDepth has no effect. (Default: false) + * @param name Name of the render target (default: DepthRenderer) + */ + constructor(scene, type = 1, camera = null, storeNonLinearDepth = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, storeCameraSpaceZ = false, name) { + /** Shader language used by the material */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + /** Enable or disable the depth renderer. When disabled, the depth texture is not updated */ + this.enabled = true; + /** Force writing the transparent objects into the depth map */ + this.forceDepthWriteTransparentMeshes = false; + /** + * Specifies that the depth renderer will only be used within + * the camera it is created for. + * This can help forcing its rendering during the camera processing. + */ + this.useOnlyInActiveCamera = false; + /** If true, reverse the culling of materials before writing to the depth texture. + * So, basically, when "true", back facing instead of front facing faces are rasterized into the texture + */ + this.reverseCulling = false; + this._shadersLoaded = false; + this._scene = scene; + this._storeNonLinearDepth = storeNonLinearDepth; + this._storeCameraSpaceZ = storeCameraSpaceZ; + this.isPacked = type === 0; + if (this.isPacked) { + this.clearColor = new Color4(1.0, 1.0, 1.0, 1.0); + } + else { + this.clearColor = new Color4(storeCameraSpaceZ ? 1e8 : 1.0, 0.0, 0.0, 1.0); + } + this._initShaderSourceAsync(); + DepthRenderer._SceneComponentInitialization(this._scene); + const engine = scene.getEngine(); + this._camera = camera; + if (samplingMode !== Texture.NEAREST_SAMPLINGMODE) { + if (type === 1 && !engine._caps.textureFloatLinearFiltering) { + samplingMode = Texture.NEAREST_SAMPLINGMODE; + } + if (type === 2 && !engine._caps.textureHalfFloatLinearFiltering) { + samplingMode = Texture.NEAREST_SAMPLINGMODE; + } + } + // Render target + const format = this.isPacked || !engine._features.supportExtendedTextureFormats ? 5 : 6; + this._depthMap = new RenderTargetTexture(name ?? "DepthRenderer", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type, false, samplingMode, undefined, undefined, undefined, format); + this._depthMap.wrapU = Texture.CLAMP_ADDRESSMODE; + this._depthMap.wrapV = Texture.CLAMP_ADDRESSMODE; + this._depthMap.refreshRate = 1; + this._depthMap.renderParticles = false; + this._depthMap.renderList = null; + this._depthMap.noPrePassRenderer = true; + // Camera to get depth map from to support multiple concurrent cameras + this._depthMap.activeCamera = this._camera; + this._depthMap.ignoreCameraViewport = true; + this._depthMap.useCameraPostProcesses = false; + // set default depth value to 1.0 (far away) + this._depthMap.onClearObservable.add((engine) => { + engine.clear(this.clearColor, true, true, true); + }); + this._depthMap.onBeforeBindObservable.add(() => { + engine._debugPushGroup?.("depth renderer", 1); + }); + this._depthMap.onAfterUnbindObservable.add(() => { + engine._debugPopGroup?.(1); + }); + this._depthMap.customIsReadyFunction = (mesh, refreshRate, preWarm) => { + if ((preWarm || refreshRate === 0) && mesh.subMeshes) { + for (let i = 0; i < mesh.subMeshes.length; ++i) { + const subMesh = mesh.subMeshes[i]; + const renderingMesh = subMesh.getRenderingMesh(); + const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); + const hardwareInstancedRendering = engine.getCaps().instancedArrays && + ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances); + if (!this.isReady(subMesh, hardwareInstancedRendering)) { + return false; + } + } + } + return true; + }; + // Custom render function + const renderSubMesh = (subMesh) => { + const renderingMesh = subMesh.getRenderingMesh(); + const effectiveMesh = subMesh.getEffectiveMesh(); + const scene = this._scene; + const engine = scene.getEngine(); + const material = subMesh.getMaterial(); + effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; + if (!material || effectiveMesh.infiniteDistance || material.disableDepthWrite || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) { + return; + } + // Culling + const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0; + let sideOrientation = material._getEffectiveOrientation(renderingMesh); + if (detNeg) { + sideOrientation = + sideOrientation === 0 + ? 1 + : 0; + } + const reverseSideOrientation = sideOrientation === 0; + engine.setState(material.backFaceCulling, 0, false, reverseSideOrientation, this.reverseCulling ? !material.cullBackFaces : material.cullBackFaces); + // Managing instances + const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); + if (batch.mustReturn) { + return; + } + const hardwareInstancedRendering = engine.getCaps().instancedArrays && + ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances); + const camera = this._camera || scene.activeCamera; + if (this.isReady(subMesh, hardwareInstancedRendering) && camera) { + subMesh._renderId = scene.getRenderId(); + const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine.currentRenderPassId]; + let drawWrapper = subMesh._getDrawWrapper(); + if (!drawWrapper && renderingMaterial) { + drawWrapper = renderingMaterial._getDrawWrapper(); + } + const cameraIsOrtho = camera.mode === Camera.ORTHOGRAPHIC_CAMERA; + if (!drawWrapper) { + return; + } + const effect = drawWrapper.effect; + engine.enableEffect(drawWrapper); + if (!hardwareInstancedRendering) { + renderingMesh._bind(subMesh, effect, material.fillMode); + } + if (!renderingMaterial) { + effect.setMatrix("viewProjection", scene.getTransformMatrix()); + effect.setMatrix("world", effectiveMesh.getWorldMatrix()); + if (this._storeCameraSpaceZ) { + effect.setMatrix("view", scene.getViewMatrix()); + } + } + else { + renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh); + } + let minZ, maxZ; + if (cameraIsOrtho) { + minZ = !engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1; + maxZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1; + } + else { + minZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? camera.minZ : engine.isNDCHalfZRange ? 0 : camera.minZ; + maxZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : camera.maxZ; + } + effect.setFloat2("depthValues", minZ, minZ + maxZ); + if (!renderingMaterial) { + // Alpha test + if (material.needAlphaTestingForMesh(effectiveMesh)) { + const alphaTexture = material.getAlphaTestTexture(); + if (alphaTexture) { + effect.setTexture("diffuseSampler", alphaTexture); + effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); + } + } + // Bones + BindBonesParameters(renderingMesh, effect); + // Clip planes + bindClipPlane(effect, material, scene); + // Morph targets + BindMorphTargetParameters(renderingMesh, effect); + if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { + renderingMesh.morphTargetManager._bind(effect); + } + // Baked vertex animations + const bvaManager = subMesh.getMesh().bakedVertexAnimationManager; + if (bvaManager && bvaManager.isEnabled) { + bvaManager.bind(effect, hardwareInstancedRendering); + } + // Points cloud rendering + if (material.pointsCloud) { + effect.setFloat("pointSize", material.pointSize); + } + } + // Draw + renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix("world", world)); + } + }; + this._depthMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { + let index; + if (depthOnlySubMeshes.length) { + for (index = 0; index < depthOnlySubMeshes.length; index++) { + renderSubMesh(depthOnlySubMeshes.data[index]); + } + } + for (index = 0; index < opaqueSubMeshes.length; index++) { + renderSubMesh(opaqueSubMeshes.data[index]); + } + for (index = 0; index < alphaTestSubMeshes.length; index++) { + renderSubMesh(alphaTestSubMeshes.data[index]); + } + if (this.forceDepthWriteTransparentMeshes) { + for (index = 0; index < transparentSubMeshes.length; index++) { + renderSubMesh(transparentSubMeshes.data[index]); + } + } + else { + for (index = 0; index < transparentSubMeshes.length; index++) { + transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false; + } + } + }; + } + async _initShaderSourceAsync(forceGLSL = false) { + const engine = this._scene.getEngine(); + if (engine.isWebGPU && !forceGLSL && !DepthRenderer.ForceGLSL) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + await Promise.all([Promise.resolve().then(() => depth_vertex), Promise.resolve().then(() => depth_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => depth_vertex$1), Promise.resolve().then(() => depth_fragment$1)]); + } + this._shadersLoaded = true; + } + /** + * Creates the depth rendering effect and checks if the effect is ready. + * @param subMesh The submesh to be used to render the depth map of + * @param useInstances If multiple world instances should be used + * @returns if the depth renderer is ready to render the depth map + */ + isReady(subMesh, useInstances) { + if (!this._shadersLoaded) { + return false; + } + const engine = this._scene.getEngine(); + const mesh = subMesh.getMesh(); + const scene = mesh.getScene(); + const renderingMaterial = mesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine.currentRenderPassId]; + if (renderingMaterial) { + return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances); + } + const material = subMesh.getMaterial(); + if (!material || material.disableDepthWrite) { + return false; + } + const defines = []; + const attribs = [VertexBuffer.PositionKind]; + let uv1 = false; + let uv2 = false; + const color = false; + // Alpha test + if (material.needAlphaTestingForMesh(mesh) && material.getAlphaTestTexture()) { + defines.push("#define ALPHATEST"); + if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { + attribs.push(VertexBuffer.UVKind); + defines.push("#define UV1"); + uv1 = true; + } + if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) { + attribs.push(VertexBuffer.UV2Kind); + defines.push("#define UV2"); + uv2 = true; + } + } + // Bones + const fallbacks = new EffectFallbacks(); + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + attribs.push(VertexBuffer.MatricesIndicesKind); + attribs.push(VertexBuffer.MatricesWeightsKind); + if (mesh.numBoneInfluencers > 4) { + attribs.push(VertexBuffer.MatricesIndicesExtraKind); + attribs.push(VertexBuffer.MatricesWeightsExtraKind); + } + defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); + if (mesh.numBoneInfluencers > 0) { + fallbacks.addCPUSkinningFallback(0, mesh); + } + const skeleton = mesh.skeleton; + if (skeleton.isUsingTextureForMatrices) { + defines.push("#define BONETEXTURE"); + } + else { + defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); + } + } + else { + defines.push("#define NUM_BONE_INFLUENCERS 0"); + } + // Morph targets + const numMorphInfluencers = mesh.morphTargetManager + ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph + false, // useNormalMorph + false, // useTangentMorph + uv1, // useUVMorph + uv2, // useUV2Morph + color // useColorMorph + ) + : 0; + // Points cloud rendering + if (material.pointsCloud) { + defines.push("#define POINTSIZE"); + } + // Instances + if (useInstances) { + defines.push("#define INSTANCES"); + PushAttributesForInstances(attribs); + if (subMesh.getRenderingMesh().hasThinInstances) { + defines.push("#define THIN_INSTANCES"); + } + } + // Baked vertex animations + const bvaManager = mesh.bakedVertexAnimationManager; + if (bvaManager && bvaManager.isEnabled) { + defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"); + if (useInstances) { + attribs.push("bakedVertexAnimationSettingsInstanced"); + } + } + // None linear depth + if (this._storeNonLinearDepth) { + defines.push("#define NONLINEARDEPTH"); + } + // Store camera space Z coordinate instead of NDC Z + if (this._storeCameraSpaceZ) { + defines.push("#define STORE_CAMERASPACE_Z"); + } + // Float Mode + if (this.isPacked) { + defines.push("#define PACKED"); + } + // Clip planes + prepareStringDefinesForClipPlanes(material, scene, defines); + // Get correct effect + const drawWrapper = subMesh._getDrawWrapper(undefined, true); + const cachedDefines = drawWrapper.defines; + const join = defines.join("\n"); + if (cachedDefines !== join) { + const uniforms = [ + "world", + "mBones", + "boneTextureWidth", + "pointSize", + "viewProjection", + "view", + "diffuseMatrix", + "depthValues", + "morphTargetInfluences", + "morphTargetCount", + "morphTargetTextureInfo", + "morphTargetTextureIndices", + "bakedVertexAnimationSettings", + "bakedVertexAnimationTextureSizeInverted", + "bakedVertexAnimationTime", + "bakedVertexAnimationTexture", + ]; + const samplers = ["diffuseSampler", "morphTargets", "boneSampler", "bakedVertexAnimationTexture"]; + addClipPlaneUniforms(uniforms); + drawWrapper.setEffect(engine.createEffect("depth", { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: [], + samplers: samplers, + defines: join, + fallbacks: fallbacks, + onCompiled: null, + onError: null, + indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers }, + shaderLanguage: this._shaderLanguage, + }, engine), join); + } + return drawWrapper.effect.isReady(); + } + /** + * Gets the texture which the depth map will be written to. + * @returns The depth map texture + */ + getDepthMap() { + return this._depthMap; + } + /** + * Disposes of the depth renderer. + */ + dispose() { + const keysToDelete = []; + for (const key in this._scene._depthRenderer) { + const depthRenderer = this._scene._depthRenderer[key]; + if (depthRenderer === this) { + keysToDelete.push(key); + } + } + if (keysToDelete.length > 0) { + this._depthMap.dispose(); + for (const key of keysToDelete) { + delete this._scene._depthRenderer[key]; + } + } + } +} +/** + * Force all the depth renderer to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +DepthRenderer.ForceGLSL = false; +/** + * @internal + */ +DepthRenderer._SceneComponentInitialization = (_) => { + throw _WarnImport("DepthRendererSceneComponent"); +}; + +// Do not edit. +const name$7Z = "minmaxReduxPixelShader"; +const shader$7Y = `varying vec2 vUV;uniform sampler2D textureSampler; +#if defined(INITIAL) +uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); +#ifdef DEPTH_REDUX +float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); +#else +float maxz=max(max(max(f1,f2),f3),f4); +#endif +glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(MAIN) +uniform vec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(ONEBEFORELAST) +uniform ivec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(LAST) +void main(void) +{glFragColor=vec4(0.);if (true) { +discard;}} +#endif +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7Z]) { + ShaderStore.ShadersStore[name$7Z] = shader$7Y; +} + +/** + * This class computes a min/max reduction from a texture: it means it computes the minimum + * and maximum values from all values of the texture. + * It is performed on the GPU for better performances, thanks to a succession of post processes. + * The source values are read from the red channel of the texture. + */ +class MinMaxReducer { + /** + * Creates a min/max reducer + * @param camera The camera to use for the post processes + */ + constructor(camera) { + /** + * Observable triggered when the computation has been performed + */ + this.onAfterReductionPerformed = new Observable(); + this._forceFullscreenViewport = true; + this._activated = false; + this._camera = camera; + this._postProcessManager = new PostProcessManager(camera.getScene()); + this._onContextRestoredObserver = camera.getEngine().onContextRestoredObservable.add(() => { + this._postProcessManager._rebuild(); + }); + } + /** + * Gets the texture used to read the values from. + */ + get sourceTexture() { + return this._sourceTexture; + } + /** + * Sets the source texture to read the values from. + * One must indicate if the texture is a depth texture or not through the depthRedux parameter + * because in such textures '1' value must not be taken into account to compute the maximum + * as this value is used to clear the texture. + * Note that the computation is not activated by calling this function, you must call activate() for that! + * @param sourceTexture The texture to read the values from. The values should be in the red channel. + * @param depthRedux Indicates if the texture is a depth texture or not + * @param type The type of the textures created for the reduction (defaults to TEXTURETYPE_HALF_FLOAT) + * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true) + */ + setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) { + if (sourceTexture === this._sourceTexture) { + return; + } + this.dispose(false); + this._sourceTexture = sourceTexture; + this._reductionSteps = []; + this._forceFullscreenViewport = forceFullscreenViewport; + const scene = this._camera.getScene(); + // create the first step + const reductionInitial = new PostProcess("Initial reduction phase", "minmaxRedux", // shader + ["texSize"], ["sourceTexture"], // textures + 1.0, // options + null, // camera + 1, // sampling + scene.getEngine(), // engine + false, // reusable + "#define INITIAL" + (depthRedux ? "\n#define DEPTH_REDUX" : ""), // defines + type, undefined, undefined, undefined, 7); + reductionInitial.autoClear = false; + reductionInitial.forceFullscreenViewport = forceFullscreenViewport; + let w = this._sourceTexture.getRenderWidth(), h = this._sourceTexture.getRenderHeight(); + reductionInitial.onApply = ((w, h) => { + return (effect) => { + effect.setTexture("sourceTexture", this._sourceTexture); + effect.setFloat2("texSize", w, h); + }; + })(w, h); + this._reductionSteps.push(reductionInitial); + let index = 1; + // create the additional steps + while (w > 1 || h > 1) { + w = Math.max(Math.round(w / 2), 1); + h = Math.max(Math.round(h / 2), 1); + const reduction = new PostProcess("Reduction phase " + index, "minmaxRedux", // shader + ["texSize"], null, { width: w, height: h }, // options + null, // camera + 1, // sampling + scene.getEngine(), // engine + false, // reusable + "#define " + (w == 1 && h == 1 ? "LAST" : w == 1 || h == 1 ? "ONEBEFORELAST" : "MAIN"), // defines + type, undefined, undefined, undefined, 7); + reduction.autoClear = false; + reduction.forceFullscreenViewport = forceFullscreenViewport; + reduction.onApply = ((w, h) => { + return (effect) => { + if (w == 1 || h == 1) { + effect.setInt2("texSize", w, h); + } + else { + effect.setFloat2("texSize", w, h); + } + }; + })(w, h); + this._reductionSteps.push(reduction); + index++; + if (w == 1 && h == 1) { + const func = (w, h, reduction) => { + const buffer = new Float32Array(4 * w * h), minmax = { min: 0, max: 0 }; + return () => { + scene.getEngine()._readTexturePixels(reduction.inputTexture.texture, w, h, -1, 0, buffer, false); + minmax.min = buffer[0]; + minmax.max = buffer[1]; + this.onAfterReductionPerformed.notifyObservers(minmax); + }; + }; + reduction.onAfterRenderObservable.add(func(w, h, reduction)); + } + } + } + /** + * Defines the refresh rate of the computation. + * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on... + */ + get refreshRate() { + return this._sourceTexture ? this._sourceTexture.refreshRate : -1; + } + set refreshRate(value) { + if (this._sourceTexture) { + this._sourceTexture.refreshRate = value; + } + } + /** + * Gets the activation status of the reducer + */ + get activated() { + return this._activated; + } + /** + * Activates the reduction computation. + * When activated, the observers registered in onAfterReductionPerformed are + * called after the computation is performed + */ + activate() { + if (this._onAfterUnbindObserver || !this._sourceTexture) { + return; + } + this._onAfterUnbindObserver = this._sourceTexture.onAfterUnbindObservable.add(() => { + const engine = this._camera.getScene().getEngine(); + engine._debugPushGroup?.(`min max reduction`, 1); + this._reductionSteps[0].activate(this._camera); + this._postProcessManager.directRender(this._reductionSteps, this._reductionSteps[0].inputTexture, this._forceFullscreenViewport); + engine.unBindFramebuffer(this._reductionSteps[0].inputTexture, false); + engine._debugPopGroup?.(1); + }); + this._activated = true; + } + /** + * Deactivates the reduction computation. + */ + deactivate() { + if (!this._onAfterUnbindObserver || !this._sourceTexture) { + return; + } + this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver); + this._onAfterUnbindObserver = null; + this._activated = false; + } + /** + * Disposes the min/max reducer + * @param disposeAll true to dispose all the resources. You should always call this function with true as the parameter (or without any parameter as it is the default one). This flag is meant to be used internally. + */ + dispose(disposeAll = true) { + if (disposeAll) { + this.onAfterReductionPerformed.clear(); + if (this._onContextRestoredObserver) { + this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver); + this._onContextRestoredObserver = null; + } + } + this.deactivate(); + if (this._reductionSteps) { + for (let i = 0; i < this._reductionSteps.length; ++i) { + this._reductionSteps[i].dispose(); + } + this._reductionSteps = null; + } + if (this._postProcessManager && disposeAll) { + this._postProcessManager.dispose(); + } + this._sourceTexture = null; + } +} + +/** + * This class is a small wrapper around the MinMaxReducer class to compute the min/max values of a depth texture + */ +class DepthReducer extends MinMaxReducer { + /** + * Gets the depth renderer used for the computation. + * Note that the result is null if you provide your own renderer when calling setDepthRenderer. + */ + get depthRenderer() { + return this._depthRenderer; + } + /** + * Creates a depth reducer + * @param camera The camera used to render the depth texture + */ + constructor(camera) { + super(camera); + } + /** + * Sets the depth renderer to use to generate the depth map + * @param depthRenderer The depth renderer to use. If not provided, a new one will be created automatically + * @param type The texture type of the depth map (default: TEXTURETYPE_HALF_FLOAT) + * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true) + */ + setDepthRenderer(depthRenderer = null, type = 2, forceFullscreenViewport = true) { + const scene = this._camera.getScene(); + if (this._depthRenderer) { + delete scene._depthRenderer[this._depthRendererId]; + this._depthRenderer.dispose(); + this._depthRenderer = null; + } + if (depthRenderer === null) { + if (!scene._depthRenderer) { + scene._depthRenderer = {}; + } + depthRenderer = this._depthRenderer = new DepthRenderer(scene, type, this._camera, false, 1); + depthRenderer.enabled = false; + this._depthRendererId = "minmax" + this._camera.id; + scene._depthRenderer[this._depthRendererId] = depthRenderer; + } + super.setSourceTexture(depthRenderer.getDepthMap(), true, type, forceFullscreenViewport); + } + /** + * @internal + */ + setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) { + super.setSourceTexture(sourceTexture, depthRedux, type, forceFullscreenViewport); + } + /** + * Activates the reduction computation. + * When activated, the observers registered in onAfterReductionPerformed are + * called after the computation is performed + */ + activate() { + if (this._depthRenderer) { + this._depthRenderer.enabled = true; + } + super.activate(); + } + /** + * Deactivates the reduction computation. + */ + deactivate() { + super.deactivate(); + if (this._depthRenderer) { + this._depthRenderer.enabled = false; + } + } + /** + * Disposes the depth reducer + * @param disposeAll true to dispose all the resources. You should always call this function with true as the parameter (or without any parameter as it is the default one). This flag is meant to be used internally. + */ + dispose(disposeAll = true) { + super.dispose(disposeAll); + if (this._depthRenderer && disposeAll) { + const scene = this._depthRenderer.getDepthMap().getScene(); + if (scene) { + delete scene._depthRenderer[this._depthRendererId]; + } + this._depthRenderer.dispose(); + this._depthRenderer = null; + } + } +} + +// eslint-disable-next-line @typescript-eslint/naming-convention +const UpDir = Vector3.Up(); +// eslint-disable-next-line @typescript-eslint/naming-convention +const ZeroVec = Vector3.Zero(); +const tmpv1 = new Vector3(), tmpv2 = new Vector3(), tmpMatrix = new Matrix(); +/** + * A CSM implementation allowing casting shadows on large scenes. + * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows + * Based on: https://github.com/TheRealMJP/Shadows and https://johanmedestrom.wordpress.com/2016/03/18/opengl-cascaded-shadow-maps/ + */ +class CascadedShadowGenerator extends ShadowGenerator { + _validateFilter(filter) { + if (filter === ShadowGenerator.FILTER_NONE || filter === ShadowGenerator.FILTER_PCF || filter === ShadowGenerator.FILTER_PCSS) { + return filter; + } + Logger.Error('Unsupported filter "' + filter + '"!'); + return ShadowGenerator.FILTER_NONE; + } + /** + * Gets or set the number of cascades used by the CSM. + */ + get numCascades() { + return this._numCascades; + } + set numCascades(value) { + value = Math.min(Math.max(value, CascadedShadowGenerator.MIN_CASCADES_COUNT), CascadedShadowGenerator.MAX_CASCADES_COUNT); + if (value === this._numCascades) { + return; + } + this._numCascades = value; + this.recreateShadowMap(); + this._recreateSceneUBOs(); + } + /** + * Enables or disables the shadow casters bounding info computation. + * If your shadow casters don't move, you can disable this feature. + * If it is enabled, the bounding box computation is done every frame. + */ + get freezeShadowCastersBoundingInfo() { + return this._freezeShadowCastersBoundingInfo; + } + set freezeShadowCastersBoundingInfo(freeze) { + if (this._freezeShadowCastersBoundingInfoObservable && freeze) { + this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable); + this._freezeShadowCastersBoundingInfoObservable = null; + } + if (!this._freezeShadowCastersBoundingInfoObservable && !freeze) { + this._freezeShadowCastersBoundingInfoObservable = this._scene.onBeforeRenderObservable.add(() => this._computeShadowCastersBoundingInfo()); + } + this._freezeShadowCastersBoundingInfo = freeze; + if (freeze) { + this._computeShadowCastersBoundingInfo(); + } + } + _computeShadowCastersBoundingInfo() { + this._scbiMin.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._scbiMax.copyFromFloats(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + if (this._shadowMap && this._shadowMap.renderList) { + const renderList = this._shadowMap.renderList; + for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) { + const mesh = renderList[meshIndex]; + if (!mesh) { + continue; + } + const boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox; + this._scbiMin.minimizeInPlace(boundingBox.minimumWorld); + this._scbiMax.maximizeInPlace(boundingBox.maximumWorld); + } + } + this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax); + } + /** + * Gets or sets the shadow casters bounding info. + * If you provide your own shadow casters bounding info, first enable freezeShadowCastersBoundingInfo + * so that the system won't overwrite the bounds you provide + */ + get shadowCastersBoundingInfo() { + return this._shadowCastersBoundingInfo; + } + set shadowCastersBoundingInfo(boundingInfo) { + this._shadowCastersBoundingInfo = boundingInfo; + } + /** + * Sets the minimal and maximal distances to use when computing the cascade breaks. + * + * The values of min / max are typically the depth zmin and zmax values of your scene, for a given frame. + * If you don't know these values, simply leave them to their defaults and don't call this function. + * @param min minimal distance for the breaks (default to 0.) + * @param max maximal distance for the breaks (default to 1.) + */ + setMinMaxDistance(min, max) { + if (this._minDistance === min && this._maxDistance === max) { + return; + } + if (min > max) { + min = 0; + max = 1; + } + if (min < 0) { + min = 0; + } + if (max > 1) { + max = 1; + } + this._minDistance = min; + this._maxDistance = max; + this._breaksAreDirty = true; + } + /** Gets the minimal distance used in the cascade break computation */ + get minDistance() { + return this._minDistance; + } + /** Gets the maximal distance used in the cascade break computation */ + get maxDistance() { + return this._maxDistance; + } + /** + * Gets the class name of that object + * @returns "CascadedShadowGenerator" + */ + getClassName() { + return CascadedShadowGenerator.CLASSNAME; + } + /** + * Gets a cascade minimum extents + * @param cascadeIndex index of the cascade + * @returns the minimum cascade extents + */ + getCascadeMinExtents(cascadeIndex) { + return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMinExtents[cascadeIndex] : null; + } + /** + * Gets a cascade maximum extents + * @param cascadeIndex index of the cascade + * @returns the maximum cascade extents + */ + getCascadeMaxExtents(cascadeIndex) { + return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMaxExtents[cascadeIndex] : null; + } + /** + * Gets the shadow max z distance. It's the limit beyond which shadows are not displayed. + * It defaults to camera.maxZ + */ + get shadowMaxZ() { + if (!this._getCamera()) { + return 0; + } + return this._shadowMaxZ; + } + /** + * Sets the shadow max z distance. + */ + set shadowMaxZ(value) { + const camera = this._getCamera(); + if (!camera) { + this._shadowMaxZ = value; + return; + } + if (this._shadowMaxZ === value || value < camera.minZ || (value > camera.maxZ && camera.maxZ !== 0)) { + return; + } + this._shadowMaxZ = value; + this._light._markMeshesAsLightDirty(); + this._breaksAreDirty = true; + } + /** + * Gets or sets the debug flag. + * When enabled, the cascades are materialized by different colors on the screen. + */ + get debug() { + return this._debug; + } + set debug(dbg) { + this._debug = dbg; + this._light._markMeshesAsLightDirty(); + } + /** + * Gets or sets the depth clamping value. + * + * When enabled, it improves the shadow quality because the near z plane of the light frustum don't need to be adjusted + * to account for the shadow casters far away. + * + * Note that this property is incompatible with PCSS filtering, so it won't be used in that case. + */ + get depthClamp() { + return this._depthClamp; + } + set depthClamp(value) { + this._depthClamp = value; + } + /** + * Gets or sets the percentage of blending between two cascades (value between 0. and 1.). + * It defaults to 0.1 (10% blending). + */ + get cascadeBlendPercentage() { + return this._cascadeBlendPercentage; + } + set cascadeBlendPercentage(value) { + this._cascadeBlendPercentage = value; + this._light._markMeshesAsLightDirty(); + } + /** + * Gets or set the lambda parameter. + * This parameter is used to split the camera frustum and create the cascades. + * It's a value between 0. and 1.: If 0, the split is a uniform split of the frustum, if 1 it is a logarithmic split. + * For all values in-between, it's a linear combination of the uniform and logarithm split algorithm. + */ + get lambda() { + return this._lambda; + } + set lambda(value) { + const lambda = Math.min(Math.max(value, 0), 1); + if (this._lambda == lambda) { + return; + } + this._lambda = lambda; + this._breaksAreDirty = true; + } + /** + * Gets the view matrix corresponding to a given cascade + * @param cascadeNum cascade to retrieve the view matrix from + * @returns the cascade view matrix + */ + getCascadeViewMatrix(cascadeNum) { + return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._viewMatrices[cascadeNum] : null; + } + /** + * Gets the projection matrix corresponding to a given cascade + * @param cascadeNum cascade to retrieve the projection matrix from + * @returns the cascade projection matrix + */ + getCascadeProjectionMatrix(cascadeNum) { + return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._projectionMatrices[cascadeNum] : null; + } + /** + * Gets the transformation matrix corresponding to a given cascade + * @param cascadeNum cascade to retrieve the transformation matrix from + * @returns the cascade transformation matrix + */ + getCascadeTransformMatrix(cascadeNum) { + return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._transformMatrices[cascadeNum] : null; + } + /** + * Sets the depth renderer to use when autoCalcDepthBounds is enabled. + * + * Note that if no depth renderer is set, a new one will be automatically created internally when necessary. + * + * You should call this function if you already have a depth renderer enabled in your scene, to avoid + * doing multiple depth rendering each frame. If you provide your own depth renderer, make sure it stores linear depth! + * @param depthRenderer The depth renderer to use when autoCalcDepthBounds is enabled. If you pass null or don't call this function at all, a depth renderer will be automatically created + */ + setDepthRenderer(depthRenderer) { + this._depthRenderer = depthRenderer; + if (this._depthReducer) { + this._depthReducer.setDepthRenderer(this._depthRenderer); + } + } + /** + * Gets or sets the autoCalcDepthBounds property. + * + * When enabled, a depth rendering pass is first performed (with an internally created depth renderer or with the one + * you provide by calling setDepthRenderer). Then, a min/max reducing is applied on the depth map to compute the + * minimal and maximal depth of the map and those values are used as inputs for the setMinMaxDistance() function. + * It can greatly enhance the shadow quality, at the expense of more GPU works. + * When using this option, you should increase the value of the lambda parameter, and even set it to 1 for best results. + */ + get autoCalcDepthBounds() { + return this._autoCalcDepthBounds; + } + set autoCalcDepthBounds(value) { + const camera = this._getCamera(); + if (!camera) { + return; + } + this._autoCalcDepthBounds = value; + if (!value) { + if (this._depthReducer) { + this._depthReducer.deactivate(); + } + this.setMinMaxDistance(0, 1); + return; + } + if (!this._depthReducer) { + this._depthReducer = new DepthReducer(camera); + this._depthReducer.onAfterReductionPerformed.add((minmax) => { + let min = minmax.min, max = minmax.max; + if (min >= max) { + min = 0; + max = 1; + } + if (min != this._minDistance || max != this._maxDistance) { + this.setMinMaxDistance(min, max); + } + }); + this._depthReducer.setDepthRenderer(this._depthRenderer); + } + this._depthReducer.activate(); + } + /** + * Defines the refresh rate of the min/max computation used when autoCalcDepthBounds is set to true + * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on... + * Note that if you provided your own depth renderer through a call to setDepthRenderer, you are responsible + * for setting the refresh rate on the renderer yourself! + */ + get autoCalcDepthBoundsRefreshRate() { + return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate ?? -1; + } + set autoCalcDepthBoundsRefreshRate(value) { + if (this._depthReducer?.depthRenderer) { + this._depthReducer.depthRenderer.getDepthMap().refreshRate = value; + } + } + /** + * Create the cascade breaks according to the lambda, shadowMaxZ and min/max distance properties, as well as the camera near and far planes. + * This function is automatically called when updating lambda, shadowMaxZ and min/max distances, however you should call it yourself if + * you change the camera near/far planes! + */ + splitFrustum() { + this._breaksAreDirty = true; + } + _splitFrustum() { + const camera = this._getCamera(); + if (!camera) { + return; + } + const near = camera.minZ, far = camera.maxZ || this._shadowMaxZ, // account for infinite far plane (ie. maxZ = 0) + cameraRange = far - near, minDistance = this._minDistance, maxDistance = this._shadowMaxZ < far && this._shadowMaxZ >= near ? Math.min((this._shadowMaxZ - near) / (far - near), this._maxDistance) : this._maxDistance; + const minZ = near + minDistance * cameraRange, maxZ = near + maxDistance * cameraRange; + const range = maxZ - minZ, ratio = maxZ / minZ; + for (let cascadeIndex = 0; cascadeIndex < this._cascades.length; ++cascadeIndex) { + const p = (cascadeIndex + 1) / this._numCascades, log = minZ * ratio ** p, uniform = minZ + range * p; + const d = this._lambda * (log - uniform) + uniform; + this._cascades[cascadeIndex].prevBreakDistance = cascadeIndex === 0 ? minDistance : this._cascades[cascadeIndex - 1].breakDistance; + this._cascades[cascadeIndex].breakDistance = (d - near) / cameraRange; + this._viewSpaceFrustumsZ[cascadeIndex] = d; + this._frustumLengths[cascadeIndex] = (this._cascades[cascadeIndex].breakDistance - this._cascades[cascadeIndex].prevBreakDistance) * cameraRange; + } + this._breaksAreDirty = false; + } + _computeMatrices() { + const scene = this._scene; + const camera = this._getCamera(); + if (!camera) { + return; + } + Vector3.NormalizeToRef(this._light.getShadowDirection(0), this._lightDirection); + if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) { + this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light + } + this._cachedDirection.copyFrom(this._lightDirection); + const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer; + for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) { + this._computeFrustumInWorldSpace(cascadeIndex); + this._computeCascadeFrustum(cascadeIndex); + this._cascadeMaxExtents[cascadeIndex].subtractToRef(this._cascadeMinExtents[cascadeIndex], tmpv1); // tmpv1 = cascadeExtents + // Get position of the shadow camera + this._frustumCenter[cascadeIndex].addToRef(this._lightDirection.scale(this._cascadeMinExtents[cascadeIndex].z), this._shadowCameraPos[cascadeIndex]); + // Come up with a new orthographic camera for the shadow caster + Matrix.LookAtLHToRef(this._shadowCameraPos[cascadeIndex], this._frustumCenter[cascadeIndex], UpDir, this._viewMatrices[cascadeIndex]); + // Z extents of the current cascade, in cascade view coordinate system + let viewMinZ = 0, viewMaxZ = tmpv1.z; + // Try to tighten minZ and maxZ based on the bounding box of the shadow casters + const boundingInfo = this._shadowCastersBoundingInfo; + boundingInfo.update(this._viewMatrices[cascadeIndex]); + // Note that after the call to update, the boundingInfo properties that are identified as "world" coordinates are in fact view coordinates for the current cascade! + // This is because the boundingInfo properties that are identifed as "local" are in fact world coordinates (see _computeShadowCastersBoundingInfo()), and we multiply them by the current cascade view matrix when we call update. + const castersViewMinZ = boundingInfo.boundingBox.minimumWorld.z; + const castersViewMaxZ = boundingInfo.boundingBox.maximumWorld.z; + if (castersViewMinZ > viewMaxZ) ; + else { + if (!this._depthClamp || this.filter === ShadowGenerator.FILTER_PCSS) { + // If we don't use depth clamping, we must define minZ so that all shadow casters are in the cascade frustum + viewMinZ = Math.min(viewMinZ, castersViewMinZ); + if (this.filter !== ShadowGenerator.FILTER_PCSS) { + // We do not need the actual distance between the currently shaded pixel and the occluder when generating shadows, so we can lower the far plane to increase the accuracy of the shadow map. + viewMaxZ = Math.min(viewMaxZ, castersViewMaxZ); + } + } + else { + // If we use depth clamping (but not PCSS!), we can adjust minZ/maxZ to reduce the range [minZ, maxZ] (and obtain additional precision in the shadow map) + viewMaxZ = Math.min(viewMaxZ, castersViewMaxZ); + // Thanks to depth clamping, casters won't be Z clipped even if they fall outside the [-1,1] range, so we can move the near plane to 0 if castersViewMinZ < 0. + // We will generate negative Z values in the shadow map, but that's okay (they will be clamped to the 0..1 range anyway), except in PCSS case + // where we need the actual distance between the currently shader pixel and the occluder: that's why we don't use depth clamping in PCSS case. + viewMinZ = Math.max(viewMinZ, castersViewMinZ); + // If all the casters are behind the near plane of the cascade, minZ = 0 due to the previous line, and maxZ < 0 at this point. + // We need to make sure that maxZ > minZ, so in this case we set maxZ a little higher than minZ. As we are using depth clamping, the casters won't be Z clipped, so we just need to make sure that we have a valid Z range for the cascade. + // Having a 0 range is not ok, due to undefined behavior in the calculation in this case. + viewMaxZ = Math.max(viewMinZ + 1.0, viewMaxZ); + } + } + Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[cascadeIndex].x, this._cascadeMaxExtents[cascadeIndex].x, this._cascadeMinExtents[cascadeIndex].y, this._cascadeMaxExtents[cascadeIndex].y, useReverseDepthBuffer ? viewMaxZ : viewMinZ, useReverseDepthBuffer ? viewMinZ : viewMaxZ, this._projectionMatrices[cascadeIndex], scene.getEngine().isNDCHalfZRange); + this._cascadeMinExtents[cascadeIndex].z = viewMinZ; + this._cascadeMaxExtents[cascadeIndex].z = viewMaxZ; + this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]); + // Create the rounding matrix, by projecting the world-space origin and determining + // the fractional offset in texel space + Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[cascadeIndex], tmpv1); // tmpv1 = shadowOrigin + tmpv1.scaleInPlace(this._mapSize / 2); + tmpv2.copyFromFloats(Math.round(tmpv1.x), Math.round(tmpv1.y), Math.round(tmpv1.z)); // tmpv2 = roundedOrigin + tmpv2.subtractInPlace(tmpv1).scaleInPlace(2 / this._mapSize); // tmpv2 = roundOffset + Matrix.TranslationToRef(tmpv2.x, tmpv2.y, 0.0, tmpMatrix); + this._projectionMatrices[cascadeIndex].multiplyToRef(tmpMatrix, this._projectionMatrices[cascadeIndex]); + this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]); + this._transformMatrices[cascadeIndex].copyToArray(this._transformMatricesAsArray, cascadeIndex * 16); + } + } + // Get the 8 points of the view frustum in world space + _computeFrustumInWorldSpace(cascadeIndex) { + const camera = this._getCamera(); + if (!camera) { + return; + } + const prevSplitDist = this._cascades[cascadeIndex].prevBreakDistance, splitDist = this._cascades[cascadeIndex].breakDistance; + const isNDCHalfZRange = this._scene.getEngine().isNDCHalfZRange; + camera.getViewMatrix(); // make sure the transformation matrix we get when calling 'getTransformationMatrix()' is calculated with an up to date view matrix + const cameraInfiniteFarPlane = camera.maxZ === 0; + const saveCameraMaxZ = camera.maxZ; + if (cameraInfiniteFarPlane) { + camera.maxZ = this._shadowMaxZ; + camera.getProjectionMatrix(true); + } + const invViewProj = Matrix.Invert(camera.getTransformationMatrix()); + if (cameraInfiniteFarPlane) { + camera.maxZ = saveCameraMaxZ; + camera.getProjectionMatrix(true); + } + const cornerIndexOffset = this._scene.getEngine().useReverseDepthBuffer ? 4 : 0; + for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++cornerIndex) { + tmpv1.copyFrom(CascadedShadowGenerator._FrustumCornersNDCSpace[(cornerIndex + cornerIndexOffset) % CascadedShadowGenerator._FrustumCornersNDCSpace.length]); + if (isNDCHalfZRange && tmpv1.z === -1) { + tmpv1.z = 0; + } + Vector3.TransformCoordinatesToRef(tmpv1, invViewProj, this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]); + } + // Get the corners of the current cascade slice of the view frustum + for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length / 2; ++cornerIndex) { + tmpv1.copyFrom(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4]).subtractInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]); + tmpv2.copyFrom(tmpv1).scaleInPlace(prevSplitDist); // near corner ray + tmpv1.scaleInPlace(splitDist); // far corner ray + tmpv1.addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]); + this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4].copyFrom(tmpv1); + this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].addInPlace(tmpv2); + } + } + _computeCascadeFrustum(cascadeIndex) { + this._cascadeMinExtents[cascadeIndex].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cascadeMaxExtents[cascadeIndex].copyFromFloats(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + this._frustumCenter[cascadeIndex].copyFromFloats(0, 0, 0); + const camera = this._getCamera(); + if (!camera) { + return; + } + // Calculate the centroid of the view frustum slice + for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) { + this._frustumCenter[cascadeIndex].addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]); + } + this._frustumCenter[cascadeIndex].scaleInPlace(1 / this._frustumCornersWorldSpace[cascadeIndex].length); + if (this.stabilizeCascades) { + // Calculate the radius of a bounding sphere surrounding the frustum corners + let sphereRadius = 0; + for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) { + const dist = this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].subtractToRef(this._frustumCenter[cascadeIndex], tmpv1).length(); + sphereRadius = Math.max(sphereRadius, dist); + } + sphereRadius = Math.ceil(sphereRadius * 16) / 16; + this._cascadeMaxExtents[cascadeIndex].copyFromFloats(sphereRadius, sphereRadius, sphereRadius); + this._cascadeMinExtents[cascadeIndex].copyFromFloats(-sphereRadius, -sphereRadius, -sphereRadius); + } + else { + // Create a temporary view matrix for the light + const lightCameraPos = this._frustumCenter[cascadeIndex]; + this._frustumCenter[cascadeIndex].addToRef(this._lightDirection, tmpv1); // tmpv1 = look at + Matrix.LookAtLHToRef(lightCameraPos, tmpv1, UpDir, tmpMatrix); // matrix = lightView + // Calculate an AABB around the frustum corners + for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) { + Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex], tmpMatrix, tmpv1); + this._cascadeMinExtents[cascadeIndex].minimizeInPlace(tmpv1); + this._cascadeMaxExtents[cascadeIndex].maximizeInPlace(tmpv1); + } + } + } + _recreateSceneUBOs() { + this._disposeSceneUBOs(); + if (this._sceneUBOs) { + for (let i = 0; i < this._numCascades; ++i) { + this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${i})`)); + } + } + } + /** + * Support test. + */ + static get IsSupported() { + const engine = EngineStore.LastCreatedEngine; + if (!engine) { + return false; + } + return engine._features.supportCSM; + } + /** + * Creates a Cascaded Shadow Generator object. + * A ShadowGenerator is the required tool to use the shadows. + * Each directional light casting shadows needs to use its own ShadowGenerator. + * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows + * @param mapSize The size of the texture what stores the shadows. Example : 1024. + * @param light The directional light object generating the shadows. + * @param usefulFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture. + * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it + * @param useRedTextureType Forces the generator to use a Red instead of a RGBA type for the shadow map texture format (default: true) + */ + constructor(mapSize, light, usefulFloatFirst, camera, useRedTextureType = true) { + if (!CascadedShadowGenerator.IsSupported) { + Logger.Error("CascadedShadowMap is not supported by the current engine."); + return; + } + super(mapSize, light, usefulFloatFirst, camera, useRedTextureType); + this.usePercentageCloserFiltering = true; + } + _initializeGenerator() { + this.penumbraDarkness = this.penumbraDarkness ?? 1.0; + this._numCascades = this._numCascades ?? CascadedShadowGenerator.DEFAULT_CASCADES_COUNT; + this.stabilizeCascades = this.stabilizeCascades ?? false; + this._freezeShadowCastersBoundingInfoObservable = this._freezeShadowCastersBoundingInfoObservable ?? null; + this.freezeShadowCastersBoundingInfo = this.freezeShadowCastersBoundingInfo ?? false; + this._scbiMin = this._scbiMin ?? new Vector3(0, 0, 0); + this._scbiMax = this._scbiMax ?? new Vector3(0, 0, 0); + this._shadowCastersBoundingInfo = this._shadowCastersBoundingInfo ?? new BoundingInfo(new Vector3(0, 0, 0), new Vector3(0, 0, 0)); + this._breaksAreDirty = this._breaksAreDirty ?? true; + this._minDistance = this._minDistance ?? 0; + this._maxDistance = this._maxDistance ?? 1; + this._currentLayer = this._currentLayer ?? 0; + this._shadowMaxZ = this._shadowMaxZ ?? this._getCamera()?.maxZ ?? 10000; + this._debug = this._debug ?? false; + this._depthClamp = this._depthClamp ?? true; + this._cascadeBlendPercentage = this._cascadeBlendPercentage ?? 0.1; + this._lambda = this._lambda ?? 0.5; + this._autoCalcDepthBounds = this._autoCalcDepthBounds ?? false; + this._recreateSceneUBOs(); + super._initializeGenerator(); + } + _createTargetRenderTexture() { + const engine = this._scene.getEngine(); + const size = { width: this._mapSize, height: this._mapSize, layers: this.numCascades }; + this._shadowMap = new RenderTargetTexture(this._light.name + "_CSMShadowMap", size, this._scene, false, true, this._textureType, false, undefined, false, false, undefined, this._useRedTextureType ? 6 : 5); + this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true, undefined, undefined, undefined, `DepthStencilForCSMShadowGenerator-${this._light.name}`); + this._shadowMap.noPrePassRenderer = true; + } + _initializeShadowMap() { + super._initializeShadowMap(); + if (this._shadowMap === null) { + return; + } + this._transformMatricesAsArray = new Float32Array(this._numCascades * 16); + this._viewSpaceFrustumsZ = new Array(this._numCascades); + this._frustumLengths = new Array(this._numCascades); + this._lightSizeUVCorrection = new Array(this._numCascades * 2); + this._depthCorrection = new Array(this._numCascades); + this._cascades = []; + this._viewMatrices = []; + this._projectionMatrices = []; + this._transformMatrices = []; + this._cascadeMinExtents = []; + this._cascadeMaxExtents = []; + this._frustumCenter = []; + this._shadowCameraPos = []; + this._frustumCornersWorldSpace = []; + for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) { + this._cascades[cascadeIndex] = { + prevBreakDistance: 0, + breakDistance: 0, + }; + this._viewMatrices[cascadeIndex] = Matrix.Zero(); + this._projectionMatrices[cascadeIndex] = Matrix.Zero(); + this._transformMatrices[cascadeIndex] = Matrix.Zero(); + this._cascadeMinExtents[cascadeIndex] = new Vector3(); + this._cascadeMaxExtents[cascadeIndex] = new Vector3(); + this._frustumCenter[cascadeIndex] = new Vector3(); + this._shadowCameraPos[cascadeIndex] = new Vector3(); + this._frustumCornersWorldSpace[cascadeIndex] = new Array(CascadedShadowGenerator._FrustumCornersNDCSpace.length); + for (let i = 0; i < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++i) { + this._frustumCornersWorldSpace[cascadeIndex][i] = new Vector3(); + } + } + const engine = this._scene.getEngine(); + this._shadowMap.onBeforeBindObservable.clear(); + this._shadowMap.onBeforeRenderObservable.clear(); + this._shadowMap.onBeforeRenderObservable.add((layer) => { + if (this._sceneUBOs) { + this._scene.setSceneUniformBuffer(this._sceneUBOs[layer]); + } + this._currentLayer = layer; + if (this._filter === ShadowGenerator.FILTER_PCF) { + engine.setColorWrite(false); + } + this._scene.setTransformMatrix(this.getCascadeViewMatrix(layer), this.getCascadeProjectionMatrix(layer)); + if (this._useUBO) { + this._scene.getSceneUniformBuffer().unbindEffect(); + this._scene.finalizeSceneUbo(); + } + }); + this._shadowMap.onBeforeBindObservable.add(() => { + this._currentSceneUBO = this._scene.getSceneUniformBuffer(); + engine._debugPushGroup?.(`cascaded shadow map generation for pass id ${engine.currentRenderPassId}`, 1); + if (this._breaksAreDirty) { + this._splitFrustum(); + } + this._computeMatrices(); + }); + this._splitFrustum(); + } + _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect) { + effect.setMatrix("viewProjection", this.getCascadeTransformMatrix(this._currentLayer)); + } + _isReadyCustomDefines(defines) { + defines.push("#define SM_DEPTHCLAMP " + (this._depthClamp && this._filter !== ShadowGenerator.FILTER_PCSS ? "1" : "0")); + } + /** + * Prepare all the defines in a material relying on a shadow map at the specified light index. + * @param defines Defines of the material we want to update + * @param lightIndex Index of the light in the enabled light list of the material + */ + prepareDefines(defines, lightIndex) { + super.prepareDefines(defines, lightIndex); + const scene = this._scene; + const light = this._light; + if (!scene.shadowsEnabled || !light.shadowEnabled) { + return; + } + defines["SHADOWCSM" + lightIndex] = true; + defines["SHADOWCSMDEBUG" + lightIndex] = this.debug; + defines["SHADOWCSMNUM_CASCADES" + lightIndex] = this.numCascades; + defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = scene.useRightHandedSystem; + const camera = this._getCamera(); + if (camera && this._shadowMaxZ <= (camera.maxZ || this._shadowMaxZ)) { + defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = true; + } + if (this.cascadeBlendPercentage === 0) { + defines["SHADOWCSMNOBLEND" + lightIndex] = true; + } + } + /** + * Binds the shadow related information inside of an effect (information like near, far, darkness... + * defined in the generator but impacting the effect). + * @param lightIndex Index of the light in the enabled light list of the material owning the effect + * @param effect The effect we are binfing the information for + */ + bindShadowLight(lightIndex, effect) { + const light = this._light; + const scene = this._scene; + if (!scene.shadowsEnabled || !light.shadowEnabled) { + return; + } + const camera = this._getCamera(); + if (!camera) { + return; + } + const shadowMap = this.getShadowMap(); + if (!shadowMap) { + return; + } + const width = shadowMap.getSize().width; + effect.setMatrices("lightMatrix" + lightIndex, this._transformMatricesAsArray); + effect.setArray("viewFrustumZ" + lightIndex, this._viewSpaceFrustumsZ); + effect.setFloat("cascadeBlendFactor" + lightIndex, this.cascadeBlendPercentage === 0 ? 10000 : 1 / this.cascadeBlendPercentage); + effect.setArray("frustumLengths" + lightIndex, this._frustumLengths); + // Only PCF uses depth stencil texture. + if (this._filter === ShadowGenerator.FILTER_PCF) { + effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMap); + light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex); + } + else if (this._filter === ShadowGenerator.FILTER_PCSS) { + for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) { + this._lightSizeUVCorrection[cascadeIndex * 2 + 0] = + cascadeIndex === 0 + ? 1 + : (this._cascadeMaxExtents[0].x - this._cascadeMinExtents[0].x) / (this._cascadeMaxExtents[cascadeIndex].x - this._cascadeMinExtents[cascadeIndex].x); // x correction + this._lightSizeUVCorrection[cascadeIndex * 2 + 1] = + cascadeIndex === 0 + ? 1 + : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[cascadeIndex].y - this._cascadeMinExtents[cascadeIndex].y); // y correction + this._depthCorrection[cascadeIndex] = + cascadeIndex === 0 + ? 1 + : (this._cascadeMaxExtents[cascadeIndex].z - this._cascadeMinExtents[cascadeIndex].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z); + } + effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMap); + effect.setTexture("depthTexture" + lightIndex, shadowMap); + effect.setArray2("lightSizeUVCorrection" + lightIndex, this._lightSizeUVCorrection); + effect.setArray("depthCorrection" + lightIndex, this._depthCorrection); + effect.setFloat("penumbraDarkness" + lightIndex, this.penumbraDarkness); + light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / width, this._contactHardeningLightSizeUVRatio * width, this.frustumEdgeFalloff, lightIndex); + } + else { + effect.setTexture("shadowTexture" + lightIndex, shadowMap); + light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex); + } + light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex); + } + /** + * Gets the transformation matrix of the first cascade used to project the meshes into the map from the light point of view. + * (eq to view projection * shadow projection matrices) + * @returns The transform matrix used to create the shadow map + */ + getTransformMatrix() { + return this.getCascadeTransformMatrix(0); + } + /** + * Disposes the ShadowGenerator. + * Returns nothing. + */ + dispose() { + super.dispose(); + if (this._freezeShadowCastersBoundingInfoObservable) { + this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable); + this._freezeShadowCastersBoundingInfoObservable = null; + } + if (this._depthReducer) { + this._depthReducer.dispose(); + this._depthReducer = null; + } + } + /** + * Serializes the shadow generator setup to a json object. + * @returns The serialized JSON object + */ + serialize() { + const serializationObject = super.serialize(); + const shadowMap = this.getShadowMap(); + if (!shadowMap) { + return serializationObject; + } + serializationObject.numCascades = this._numCascades; + serializationObject.debug = this._debug; + serializationObject.stabilizeCascades = this.stabilizeCascades; + serializationObject.lambda = this._lambda; + serializationObject.cascadeBlendPercentage = this.cascadeBlendPercentage; + serializationObject.depthClamp = this._depthClamp; + serializationObject.autoCalcDepthBounds = this.autoCalcDepthBounds; + serializationObject.shadowMaxZ = this._shadowMaxZ; + serializationObject.penumbraDarkness = this.penumbraDarkness; + serializationObject.freezeShadowCastersBoundingInfo = this._freezeShadowCastersBoundingInfo; + serializationObject.minDistance = this.minDistance; + serializationObject.maxDistance = this.maxDistance; + serializationObject.renderList = []; + if (shadowMap.renderList) { + for (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) { + const mesh = shadowMap.renderList[meshIndex]; + serializationObject.renderList.push(mesh.id); + } + } + return serializationObject; + } + /** + * Parses a serialized ShadowGenerator and returns a new ShadowGenerator. + * @param parsedShadowGenerator The JSON object to parse + * @param scene The scene to create the shadow map for + * @returns The parsed shadow generator + */ + static Parse(parsedShadowGenerator, scene) { + const shadowGenerator = ShadowGenerator.Parse(parsedShadowGenerator, scene, (mapSize, light, camera) => new CascadedShadowGenerator(mapSize, light, undefined, camera)); + if (parsedShadowGenerator.numCascades !== undefined) { + shadowGenerator.numCascades = parsedShadowGenerator.numCascades; + } + if (parsedShadowGenerator.debug !== undefined) { + shadowGenerator.debug = parsedShadowGenerator.debug; + } + if (parsedShadowGenerator.stabilizeCascades !== undefined) { + shadowGenerator.stabilizeCascades = parsedShadowGenerator.stabilizeCascades; + } + if (parsedShadowGenerator.lambda !== undefined) { + shadowGenerator.lambda = parsedShadowGenerator.lambda; + } + if (parsedShadowGenerator.cascadeBlendPercentage !== undefined) { + shadowGenerator.cascadeBlendPercentage = parsedShadowGenerator.cascadeBlendPercentage; + } + if (parsedShadowGenerator.depthClamp !== undefined) { + shadowGenerator.depthClamp = parsedShadowGenerator.depthClamp; + } + if (parsedShadowGenerator.autoCalcDepthBounds !== undefined) { + shadowGenerator.autoCalcDepthBounds = parsedShadowGenerator.autoCalcDepthBounds; + } + if (parsedShadowGenerator.shadowMaxZ !== undefined) { + shadowGenerator.shadowMaxZ = parsedShadowGenerator.shadowMaxZ; + } + if (parsedShadowGenerator.penumbraDarkness !== undefined) { + shadowGenerator.penumbraDarkness = parsedShadowGenerator.penumbraDarkness; + } + if (parsedShadowGenerator.freezeShadowCastersBoundingInfo !== undefined) { + shadowGenerator.freezeShadowCastersBoundingInfo = parsedShadowGenerator.freezeShadowCastersBoundingInfo; + } + if (parsedShadowGenerator.minDistance !== undefined && parsedShadowGenerator.maxDistance !== undefined) { + shadowGenerator.setMinMaxDistance(parsedShadowGenerator.minDistance, parsedShadowGenerator.maxDistance); + } + return shadowGenerator; + } +} +CascadedShadowGenerator._FrustumCornersNDCSpace = [ + new Vector3(-1, 1, -1), + new Vector3(1, 1, -1), + new Vector3(1, -1, -1), + new Vector3(-1, -1, -1), + new Vector3(-1, 1, 1), + new Vector3(1, 1, 1), + new Vector3(1, -1, 1), + new Vector3(-1, -1, 1), +]; +/** + * Name of the CSM class + */ +CascadedShadowGenerator.CLASSNAME = "CascadedShadowGenerator"; +/** + * Defines the default number of cascades used by the CSM. + */ +CascadedShadowGenerator.DEFAULT_CASCADES_COUNT = 4; +/** + * Defines the minimum number of cascades used by the CSM. + */ +CascadedShadowGenerator.MIN_CASCADES_COUNT = 2; +/** + * Defines the maximum number of cascades used by the CSM. + */ +CascadedShadowGenerator.MAX_CASCADES_COUNT = 4; +/** + * @internal + */ +CascadedShadowGenerator._SceneComponentInitialization = (_) => { + throw _WarnImport("ShadowGeneratorSceneComponent"); +}; + +/** + * Stores the list of available parsers in the application. + */ +const _BabylonFileParsers = {}; +/** + * Stores the list of available individual parsers in the application. + */ +const _IndividualBabylonFileParsers = {}; +/** + * Adds a parser in the list of available ones + * @param name Defines the name of the parser + * @param parser Defines the parser to add + */ +function AddParser(name, parser) { + _BabylonFileParsers[name] = parser; +} +/** + * Adds n individual parser in the list of available ones + * @param name Defines the name of the parser + * @param parser Defines the parser to add + */ +function AddIndividualParser(name, parser) { + _IndividualBabylonFileParsers[name] = parser; +} +/** + * Gets an individual parser from the list of available ones + * @param name Defines the name of the parser + * @returns the requested parser or null + */ +function GetIndividualParser(name) { + if (_IndividualBabylonFileParsers[name]) { + return _IndividualBabylonFileParsers[name]; + } + return null; +} +/** + * Parser json data and populate both a scene and its associated container object + * @param jsonData Defines the data to parse + * @param scene Defines the scene to parse the data for + * @param container Defines the container attached to the parsing sequence + * @param rootUrl Defines the root url of the data + */ +function Parse(jsonData, scene, container, rootUrl) { + for (const parserName in _BabylonFileParsers) { + if (Object.prototype.hasOwnProperty.call(_BabylonFileParsers, parserName)) { + _BabylonFileParsers[parserName](jsonData, scene, container, rootUrl); + } + } +} + +// Adds the parser to the scene parsers. +AddParser(SceneComponentConstants.NAME_SHADOWGENERATOR, (parsedData, scene) => { + // Shadows + if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) { + for (let index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) { + const parsedShadowGenerator = parsedData.shadowGenerators[index]; + if (parsedShadowGenerator.className === CascadedShadowGenerator.CLASSNAME) { + CascadedShadowGenerator.Parse(parsedShadowGenerator, scene); + } + else { + ShadowGenerator.Parse(parsedShadowGenerator, scene); + } + // SG would be available on their associated lights + } + } +}); +/** + * Defines the shadow generator component responsible to manage any shadow generators + * in a given scene. + */ +class ShadowGeneratorSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_SHADOWGENERATOR; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing To Do Here. + } + /** + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to + */ + serialize(serializationObject) { + // Shadows + serializationObject.shadowGenerators = []; + const lights = this.scene.lights; + for (const light of lights) { + if (light.doNotSerialize) { + continue; + } + const shadowGenerators = light.getShadowGenerators(); + if (shadowGenerators) { + const iterator = shadowGenerators.values(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const shadowGenerator = key.value; + if (shadowGenerator.doNotSerialize) { + continue; + } + serializationObject.shadowGenerators.push(shadowGenerator.serialize()); + } + } + } + } + /** + * Adds all the elements from the container to the scene + * @param container the container holding the elements + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + addFromContainer(container) { + // Nothing To Do Here. (directly attached to a light) + } + /** + * Removes all the elements in the container from the scene + * @param container contains the elements to remove + * @param dispose if the removed element should be disposed (default: false) + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + removeFromContainer(container, dispose) { + // Nothing To Do Here. (directly attached to a light) + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + dispose() { + // Nothing To Do Here. + } + _gatherRenderTargets(renderTargets) { + // Shadows + const scene = this.scene; + if (this.scene.shadowsEnabled) { + for (let lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) { + const light = scene.lights[lightIndex]; + const shadowGenerators = light.getShadowGenerators(); + if (light.isEnabled() && light.shadowEnabled && shadowGenerators) { + const iterator = shadowGenerators.values(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const shadowGenerator = key.value; + const shadowMap = shadowGenerator.getShadowMap(); + if (scene.textures.indexOf(shadowMap) !== -1) { + renderTargets.push(shadowMap); + } + } + } + } + } + } +} +ShadowGenerator._SceneComponentInitialization = (scene) => { + let component = scene._getComponent(SceneComponentConstants.NAME_SHADOWGENERATOR); + if (!component) { + component = new ShadowGeneratorSceneComponent(scene); + scene._addComponent(component); + } +}; + +class AppLight extends Monobehiver { + lightList; + shadowGenerator; + debugMarkers; + coneMesh; + updateCone; + constructor(mainApp) { + super(mainApp); + this.lightList = []; + this.shadowGenerator = null; + } + /** 初始化灯光并开启阴影 */ + Awake() { + new DirectionalLight( + "mainLight", + new Vector3(0, -0.5, -1) + ); + } +} + +/** + * Gets the file extension from a URL. + * @param url The URL to get the file extension from. + * @returns The file extension, or an empty string if no extension is found. + */ +function GetExtensionFromUrl(url) { + const urlWithoutUriParams = url.split("?")[0]; + const lastDot = urlWithoutUriParams.lastIndexOf("."); + const extension = lastDot > -1 ? urlWithoutUriParams.substring(lastDot).toLowerCase() : ""; + return extension; +} + +AbstractEngine.prototype._partialLoadFile = function (url, index, loadedFiles, onfinish, onErrorCallBack = null) { + const onload = (data) => { + loadedFiles[index] = data; + loadedFiles._internalCount++; + if (loadedFiles._internalCount === 6) { + onfinish(loadedFiles); + } + }; + const onerror = (request, exception) => { + if (onErrorCallBack && request) { + onErrorCallBack(request.status + " " + request.statusText, exception); + } + }; + this._loadFile(url, onload, undefined, undefined, true, onerror); +}; +AbstractEngine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError = null) { + const loadedFiles = []; + loadedFiles._internalCount = 0; + for (let index = 0; index < 6; index++) { + this._partialLoadFile(files[index], index, loadedFiles, onfinish, onError); + } +}; +AbstractEngine.prototype._cascadeLoadImgs = function (scene, texture, onfinish, files, onError = null, mimeType) { + const loadedImages = []; + loadedImages._internalCount = 0; + for (let index = 0; index < 6; index++) { + this._partialLoadImg(files[index], index, loadedImages, scene, texture, onfinish, onError, mimeType); + } +}; +AbstractEngine.prototype._partialLoadImg = function (url, index, loadedImages, scene, texture, onfinish, onErrorCallBack = null, mimeType) { + const tokenPendingData = RandomGUID(); + const onload = (img) => { + loadedImages[index] = img; + loadedImages._internalCount++; + if (scene) { + scene.removePendingData(tokenPendingData); + } + if (loadedImages._internalCount === 6 && onfinish) { + onfinish(texture, loadedImages); + } + }; + const onerror = (message, exception) => { + if (scene) { + scene.removePendingData(tokenPendingData); + } + if (onErrorCallBack) { + onErrorCallBack(message, exception); + } + }; + LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null, mimeType); + if (scene) { + scene.addPendingData(tokenPendingData); + } +}; +AbstractEngine.prototype.createCubeTextureBase = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, beforeLoadCubeDataCallback = null, imageHandler = null, useSRGBBuffer = false, buffer = null) { + const texture = fallback ? fallback : new InternalTexture(this, 7 /* InternalTextureSource.Cube */); + texture.isCube = true; + texture.url = rootUrl; + texture.generateMipMaps = !noMipmap; + texture._lodGenerationScale = lodScale; + texture._lodGenerationOffset = lodOffset; + texture._useSRGBBuffer = !!useSRGBBuffer && this._caps.supportSRGBBuffers && (this.version > 1 || this.isWebGPU || !!noMipmap); + if (texture !== fallback) { + texture.label = rootUrl.substring(0, 60); // default label, can be overriden by the caller + } + if (!this._doNotHandleContextLost) { + texture._extension = forcedExtension; + texture._files = files; + texture._buffer = buffer; + } + const originalRootUrl = rootUrl; + if (this._transformTextureUrl && !fallback) { + rootUrl = this._transformTextureUrl(rootUrl); + } + const extension = forcedExtension ?? GetExtensionFromUrl(rootUrl); + const loaderPromise = _GetCompatibleTextureLoader(extension); + const onInternalError = (request, exception) => { + if (rootUrl === originalRootUrl) { + if (onError && request) { + onError(request.status + " " + request.statusText, exception); + } + } + else { + // fall back to the original url if the transformed url fails to load + Logger.Warn(`Failed to load ${rootUrl}, falling back to the ${originalRootUrl}`); + this.createCubeTextureBase(originalRootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, texture, beforeLoadCubeDataCallback, imageHandler, useSRGBBuffer, buffer); + } + }; + if (loaderPromise) { + loaderPromise.then((loader) => { + const onloaddata = (data) => { + if (beforeLoadCubeDataCallback) { + beforeLoadCubeDataCallback(texture, data); + } + loader.loadCubeData(data, texture, createPolynomials, onLoad, onError); + }; + if (buffer) { + onloaddata(buffer); + } + else if (files && files.length === 6) { + if (loader.supportCascades) { + this._cascadeLoadFiles(scene, (images) => onloaddata(images.map((image) => new Uint8Array(image))), files, onError); + } + else { + if (onError) { + onError("Textures type does not support cascades."); + } + else { + Logger.Warn("Texture loader does not support cascades."); + } + } + } + else { + this._loadFile(rootUrl, (data) => onloaddata(new Uint8Array(data)), undefined, undefined, true, onInternalError); + } + }); + } + else { + if (!files || files.length === 0) { + throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found."); + } + this._cascadeLoadImgs(scene, texture, (texture, imgs) => { + if (imageHandler) { + imageHandler(texture, imgs); + } + }, files, onError); + } + this._internalTexturesCache.push(texture); + return texture; +}; + +// The default scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness +const defaultLodScale = 0.8; +/** + * Class for creating a cube texture + */ +class CubeTexture extends BaseTexture { + /** + * Gets or sets the size of the bounding box associated with the cube texture + * When defined, the cubemap will switch to local mode + * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity + * @example https://www.babylonjs-playground.com/#RNASML + */ + set boundingBoxSize(value) { + if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { + return; + } + this._boundingBoxSize = value; + const scene = this.getScene(); + if (scene) { + scene.markAllMaterialsAsDirty(1); + } + } + /** + * Returns the bounding box size + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#using-local-cubemap-mode + */ + get boundingBoxSize() { + return this._boundingBoxSize; + } + /** + * Sets texture matrix rotation angle around Y axis in radians. + */ + set rotationY(value) { + this._rotationY = value; + this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY)); + } + /** + * Gets texture matrix rotation angle around Y axis radians. + */ + get rotationY() { + return this._rotationY; + } + /** + * Are mip maps generated for this texture or not. + */ + get noMipmap() { + return this._noMipmap; + } + /** + * Gets the forced extension (if any) + */ + get forcedExtension() { + return this._forcedExtension; + } + /** + * Creates a cube texture from an array of image urls + * @param files defines an array of image urls + * @param scene defines the hosting scene + * @param noMipmap specifies if mip maps are not used + * @returns a cube texture + */ + static CreateFromImages(files, scene, noMipmap) { + let rootUrlKey = ""; + files.forEach((url) => (rootUrlKey += url)); + return new CubeTexture(rootUrlKey, scene, null, noMipmap, files); + } + /** + * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys. + * @param url defines the url of the prefiltered texture + * @param scene defines the scene the texture is attached to + * @param forcedExtension defines the extension of the file if different from the url + * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary + * @returns the prefiltered texture + */ + static CreateFromPrefilteredData(url, scene, forcedExtension = null, createPolynomials = true) { + const oldValue = scene.useDelayedTextureLoading; + scene.useDelayedTextureLoading = false; + const result = new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials); + scene.useDelayedTextureLoading = oldValue; + return result; + } + /** + * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well + * as prefiltered data. + * @param rootUrl defines the url of the texture or the root name of the six images + * @param sceneOrEngine defines the scene or engine the texture is attached to + * @param extensionsOrOptions defines the suffixes add to the picture name in case six images are in use like _px.jpg or set of all options to create the cube texture + * @param noMipmap defines if mipmaps should be created or not + * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz + * @param onLoad defines a callback triggered at the end of the file load if no errors occurred + * @param onError defines a callback triggered in case of error during load + * @param format defines the internal format to use for the texture once loaded + * @param prefiltered defines whether or not the texture is created from prefiltered data + * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name + * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary + * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness + * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness + * @param loaderOptions options to be passed to the loader + * @param useSRGBBuffer Defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU) (default: false) + * @returns the cube texture + */ + constructor(rootUrl, sceneOrEngine, extensionsOrOptions = null, noMipmap = false, files = null, onLoad = null, onError = null, format = 5, prefiltered = false, forcedExtension = null, createPolynomials = false, lodScale = defaultLodScale, lodOffset = 0, loaderOptions, useSRGBBuffer) { + super(sceneOrEngine); + /** + * Observable triggered once the texture has been loaded. + */ + this.onLoadObservable = new Observable(); + /** + * Gets or sets the center of the bounding box associated with the cube texture. + * It must define where the camera used to render the texture was set + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#using-local-cubemap-mode + */ + this.boundingBoxPosition = Vector3.Zero(); + this._rotationY = 0; + /** @internal */ + this._files = null; + this._forcedExtension = null; + this._extensions = null; + this._textureMatrixRefraction = new Matrix(); + this._buffer = null; + this.name = rootUrl; + this.url = rootUrl; + this._noMipmap = noMipmap; + this.hasAlpha = false; + this.isCube = true; + this._textureMatrix = Matrix.Identity(); + this.coordinatesMode = Texture.CUBIC_MODE; + let extensions = null; + let buffer = null; + if (extensionsOrOptions !== null && !Array.isArray(extensionsOrOptions)) { + extensions = extensionsOrOptions.extensions ?? null; + this._noMipmap = extensionsOrOptions.noMipmap ?? false; + files = extensionsOrOptions.files ?? null; + buffer = extensionsOrOptions.buffer ?? null; + this._format = extensionsOrOptions.format ?? 5; + prefiltered = extensionsOrOptions.prefiltered ?? false; + forcedExtension = extensionsOrOptions.forcedExtension ?? null; + this._createPolynomials = extensionsOrOptions.createPolynomials ?? false; + this._lodScale = extensionsOrOptions.lodScale ?? defaultLodScale; + this._lodOffset = extensionsOrOptions.lodOffset ?? 0; + this._loaderOptions = extensionsOrOptions.loaderOptions; + this._useSRGBBuffer = extensionsOrOptions.useSRGBBuffer; + onLoad = extensionsOrOptions.onLoad ?? null; + onError = extensionsOrOptions.onError ?? null; + } + else { + this._noMipmap = noMipmap; + this._format = format; + this._createPolynomials = createPolynomials; + extensions = extensionsOrOptions; + this._loaderOptions = loaderOptions; + this._useSRGBBuffer = useSRGBBuffer; + this._lodScale = lodScale; + this._lodOffset = lodOffset; + } + if (!rootUrl && !files) { + return; + } + this.updateURL(rootUrl, forcedExtension, onLoad, prefiltered, onError, extensions, this.getScene()?.useDelayedTextureLoading, files, buffer); + } + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "CubeTexture" + */ + getClassName() { + return "CubeTexture"; + } + /** + * Update the url (and optional buffer) of this texture if url was null during construction. + * @param url the url of the texture + * @param forcedExtension defines the extension to use + * @param onLoad callback called when the texture is loaded (defaults to null) + * @param prefiltered Defines whether the updated texture is prefiltered or not + * @param onError callback called if there was an error during the loading process (defaults to null) + * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg... + * @param delayLoad defines if the texture should be loaded now (false by default) + * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz + * @param buffer the buffer to use instead of loading from the url + */ + updateURL(url, forcedExtension = null, onLoad = null, prefiltered = false, onError = null, extensions = null, delayLoad = false, files = null, buffer = null) { + if (!this.name || this.name.startsWith("data:")) { + this.name = url; + } + this.url = url; + if (forcedExtension) { + this._forcedExtension = forcedExtension; + } + const lastDot = url.lastIndexOf("."); + const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : ""; + const isDDS = extension.indexOf(".dds") === 0; + const isEnv = extension.indexOf(".env") === 0; + const isBasis = extension.indexOf(".basis") === 0; + if (isEnv) { + this.gammaSpace = false; + this._prefiltered = false; + this.anisotropicFilteringLevel = 1; + } + else { + this._prefiltered = prefiltered; + if (prefiltered) { + this.gammaSpace = false; + this.anisotropicFilteringLevel = 1; + } + } + if (files) { + this._files = files; + } + else { + if (!isBasis && !isEnv && !isDDS && !extensions) { + extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"]; + } + this._files = this._files || []; + this._files.length = 0; + if (extensions) { + for (let index = 0; index < extensions.length; index++) { + this._files.push(url + extensions[index]); + } + this._extensions = extensions; + } + } + this._buffer = buffer; + if (delayLoad) { + this.delayLoadState = 4; + this._delayedOnLoad = onLoad; + this._delayedOnError = onError; + } + else { + this._loadTexture(onLoad, onError); + } + } + /** + * Delays loading of the cube texture + * @param forcedExtension defines the extension to use + */ + delayLoad(forcedExtension) { + if (this.delayLoadState !== 4) { + return; + } + if (forcedExtension) { + this._forcedExtension = forcedExtension; + } + this.delayLoadState = 1; + this._loadTexture(this._delayedOnLoad, this._delayedOnError); + } + /** + * Returns the reflection texture matrix + * @returns the reflection texture matrix + */ + getReflectionTextureMatrix() { + return this._textureMatrix; + } + /** + * Sets the reflection texture matrix + * @param value Reflection texture matrix + */ + setReflectionTextureMatrix(value) { + if (value.updateFlag === this._textureMatrix.updateFlag) { + return; + } + if (value.isIdentity() !== this._textureMatrix.isIdentity()) { + this.getScene()?.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1); + } + this._textureMatrix = value; + if (!this.getScene()?.useRightHandedSystem) { + return; + } + const scale = TmpVectors.Vector3[0]; + const quat = TmpVectors.Quaternion[0]; + const trans = TmpVectors.Vector3[1]; + this._textureMatrix.decompose(scale, quat, trans); + quat.z *= -1; // these two operations correspond to negating the x and y euler angles + quat.w *= -1; + Matrix.ComposeToRef(scale, quat, trans, this._textureMatrixRefraction); + } + /** + * Gets a suitable rotate/transform matrix when the texture is used for refraction. + * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode. + * @returns The refraction matrix + */ + getRefractionTextureMatrix() { + return this.getScene()?.useRightHandedSystem ? this._textureMatrixRefraction : this._textureMatrix; + } + _loadTexture(onLoad = null, onError = null) { + const scene = this.getScene(); + const oldTexture = this._texture; + this._texture = this._getFromCache(this.url, this._noMipmap, undefined, undefined, this._useSRGBBuffer, this.isCube); + const onLoadProcessing = () => { + this.onLoadObservable.notifyObservers(this); + if (oldTexture) { + oldTexture.dispose(); + this.getScene()?.markAllMaterialsAsDirty(1); + } + if (onLoad) { + onLoad(); + } + }; + const errorHandler = (message, exception) => { + this._loadingError = true; + this._errorObject = { message, exception }; + if (onError) { + onError(message, exception); + } + Texture.OnTextureLoadErrorObservable.notifyObservers(this); + }; + if (!this._texture) { + if (this._prefiltered) { + this._texture = this._getEngine().createPrefilteredCubeTexture(this.url, scene, this._lodScale, this._lodOffset, onLoad, errorHandler, this._format, this._forcedExtension, this._createPolynomials); + } + else { + this._texture = this._getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, onLoad, errorHandler, this._format, this._forcedExtension, false, this._lodScale, this._lodOffset, null, this._loaderOptions, !!this._useSRGBBuffer, this._buffer); + } + this._texture?.onLoadedObservable.add(() => this.onLoadObservable.notifyObservers(this)); + } + else { + if (this._texture.isReady) { + Tools.SetImmediate(() => onLoadProcessing()); + } + else { + this._texture.onLoadedObservable.add(() => onLoadProcessing()); + } + } + } + /** + * Parses text to create a cube texture + * @param parsedTexture define the serialized text to read from + * @param scene defines the hosting scene + * @param rootUrl defines the root url of the cube texture + * @returns a cube texture + */ + static Parse(parsedTexture, scene, rootUrl) { + const texture = SerializationHelper.Parse(() => { + let prefiltered = false; + if (parsedTexture.prefiltered) { + prefiltered = parsedTexture.prefiltered; + } + return new CubeTexture(rootUrl + (parsedTexture.url ?? parsedTexture.name), scene, parsedTexture.extensions, false, parsedTexture.files || null, null, null, undefined, prefiltered, parsedTexture.forcedExtension); + }, parsedTexture, scene); + // Local Cubemaps + if (parsedTexture.boundingBoxPosition) { + texture.boundingBoxPosition = Vector3.FromArray(parsedTexture.boundingBoxPosition); + } + if (parsedTexture.boundingBoxSize) { + texture.boundingBoxSize = Vector3.FromArray(parsedTexture.boundingBoxSize); + } + // Animations + if (parsedTexture.animations) { + for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) { + const parsedAnimation = parsedTexture.animations[animationIndex]; + const internalClass = GetClass("BABYLON.Animation"); + if (internalClass) { + texture.animations.push(internalClass.Parse(parsedAnimation)); + } + } + } + return texture; + } + /** + * Makes a clone, or deep copy, of the cube texture + * @returns a new cube texture + */ + clone() { + let uniqueId = 0; + const newCubeTexture = SerializationHelper.Clone(() => { + const cubeTexture = new CubeTexture(this.url, this.getScene() || this._getEngine(), this._extensions, this._noMipmap, this._files); + uniqueId = cubeTexture.uniqueId; + return cubeTexture; + }, this); + newCubeTexture.uniqueId = uniqueId; + return newCubeTexture; + } +} +__decorate([ + serialize() +], CubeTexture.prototype, "url", void 0); +__decorate([ + serializeAsVector3() +], CubeTexture.prototype, "boundingBoxPosition", void 0); +__decorate([ + serializeAsVector3() +], CubeTexture.prototype, "boundingBoxSize", null); +__decorate([ + serialize("rotationY") +], CubeTexture.prototype, "rotationY", null); +__decorate([ + serialize("files") +], CubeTexture.prototype, "_files", void 0); +__decorate([ + serialize("forcedExtension") +], CubeTexture.prototype, "_forcedExtension", void 0); +__decorate([ + serialize("extensions") +], CubeTexture.prototype, "_extensions", void 0); +__decorate([ + serializeAsMatrix("textureMatrix") +], CubeTexture.prototype, "_textureMatrix", void 0); +__decorate([ + serializeAsMatrix("textureMatrixRefraction") +], CubeTexture.prototype, "_textureMatrixRefraction", void 0); +Texture._CubeTextureParser = CubeTexture.Parse; +// Some exporters relies on Tools.Instantiate +RegisterClass("BABYLON.CubeTexture", CubeTexture); + +class AppEnv extends Monobehiver { + object; + constructor(mainApp) { + super(mainApp); + this.object = null; + } + /** 初始化 - 创建默认HDR环境 */ + Awake() { + this.createHDR(); + } + /** + * 创建HDR环境贴图 + * @param hdrPath HDR文件路径 + */ + createHDR() { + const envPath = AppConfig.env.envPath; + const intensity = AppConfig.env.intensity ?? 1.5; + const rotationY = AppConfig.env.rotationY ?? 0; + const scene = this.mainApp.appScene.object; + if (!scene) return; + if (this.object) { + this.object.dispose(); + this.object = null; + } + const reflectionTexture = CubeTexture.CreateFromPrefilteredData(envPath, scene); + reflectionTexture.rotationY = rotationY; + scene.environmentIntensity = intensity; + scene.environmentTexture = reflectionTexture; + this.object = reflectionTexture; + scene.backgroundTexture = reflectionTexture; + const box = scene.createDefaultSkybox( + reflectionTexture, + true, + 512, + 0, + true + ); + console.log("box", AppConfig.env.background); + if (AppConfig.env.background) { + if (box) box.visibility = 1; + } else { + if (box) box.visibility = 0; + } + this.object = reflectionTexture; + } + /** + * 修改HDR环境光强度 + * @param intensity 强度值 + */ + changeHDRIntensity(intensity) { + if (this.mainApp.appScene.object) { + this.mainApp.appScene.object.environmentIntensity = intensity; + } + } + /** + * 旋转HDR环境贴图 + * @param angle 旋转角度(弧度) + */ + rotateHDR(angle) { + if (this.object) this.object.rotationY = angle; + } + /** 清理资源 */ + clean() { + if (this.object) { + this.object.dispose(); + this.object = null; + } + } +} + +/** + * Fetches a resource from the network + * @param url defines the url to fetch the resource from + * @param options defines the options to use when fetching the resource + * @returns a promise that resolves when the resource is fetched + * @internal + */ +function _FetchAsync(url, options) { + const method = options.method || "GET"; + return new Promise((resolve, reject) => { + const request = new WebRequest(); + request.addEventListener("readystatechange", () => { + if (request.readyState == 4) { + if (request.status == 200) { + const headerValues = {}; + if (options.responseHeaders) { + for (const header of options.responseHeaders) { + headerValues[header] = request.getResponseHeader(header) || ""; + } + } + resolve({ response: request.response, headerValues: headerValues }); + } + else { + reject(`Unable to fetch data from ${url}. Error code: ${request.status}`); + } + } + }); + request.open(method, url); + request.send(); + }); +} + +/** + * Mode that determines how to handle old animation groups before loading new ones. + */ +var SceneLoaderAnimationGroupLoadingMode; +(function (SceneLoaderAnimationGroupLoadingMode) { + /** + * Reset all old animations to initial state then dispose them. + */ + SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Clean"] = 0] = "Clean"; + /** + * Stop all old animations. + */ + SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Stop"] = 1] = "Stop"; + /** + * Restart old animations from first frame. + */ + SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Sync"] = 2] = "Sync"; + /** + * Old animations remains untouched. + */ + SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["NoSync"] = 3] = "NoSync"; +})(SceneLoaderAnimationGroupLoadingMode || (SceneLoaderAnimationGroupLoadingMode = {})); +function isFactory(pluginOrFactory) { + return !!pluginOrFactory.createPlugin; +} +function isFile(value) { + return !!value.name; +} +const onPluginActivatedObservable = new Observable(); +const registeredPlugins = {}; +let showingLoadingScreen = false; +function getDefaultPlugin() { + return registeredPlugins[".babylon"]; +} +function getPluginForMimeType(mimeType) { + for (const registeredPluginKey in registeredPlugins) { + const registeredPlugin = registeredPlugins[registeredPluginKey]; + if (registeredPlugin.mimeType === mimeType) { + return registeredPlugin; + } + } + return undefined; +} +function getPluginForExtension(extension, returnDefault) { + const registeredPlugin = registeredPlugins[extension]; + if (registeredPlugin) { + return registeredPlugin; + } + Logger.Warn("Unable to find a plugin to load " + + extension + + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"); + return returnDefault ? getDefaultPlugin() : undefined; +} +function isPluginForExtensionAvailable(extension) { + return !!registeredPlugins[extension]; +} +function getPluginForDirectLoad(data) { + for (const extension in registeredPlugins) { + const plugin = registeredPlugins[extension].plugin; + if (plugin.canDirectLoad && plugin.canDirectLoad(data)) { + return registeredPlugins[extension]; + } + } + return getDefaultPlugin(); +} +function getFilenameExtension(sceneFilename) { + const queryStringPosition = sceneFilename.indexOf("?"); + if (queryStringPosition !== -1) { + sceneFilename = sceneFilename.substring(0, queryStringPosition); + } + const dotPosition = sceneFilename.lastIndexOf("."); + return sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase(); +} +function getDirectLoad(sceneFilename) { + if (sceneFilename.substring(0, 5) === "data:") { + return sceneFilename.substring(5); + } + return null; +} +function formatErrorMessage(fileInfo, message, exception) { + const fromLoad = fileInfo.rawData ? "binary data" : fileInfo.url; + let errorMessage = "Unable to load from " + fromLoad; + if (message) { + errorMessage += `: ${message}`; + } + else if (exception) { + errorMessage += `: ${exception}`; + } + return errorMessage; +} +async function loadDataAsync(fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension, name, pluginOptions) { + const directLoad = getDirectLoad(fileInfo.url); + if (fileInfo.rawData && !pluginExtension) { + // eslint-disable-next-line no-throw-literal + throw "When using ArrayBufferView to load data the file extension must be provided."; + } + const fileExtension = !directLoad && !pluginExtension ? getFilenameExtension(fileInfo.url) : ""; + let registeredPlugin = pluginExtension + ? getPluginForExtension(pluginExtension, true) + : directLoad + ? getPluginForDirectLoad(fileInfo.url) + : getPluginForExtension(fileExtension, false); + if (!registeredPlugin && fileExtension) { + if (fileInfo.url && !fileInfo.url.startsWith("blob:")) { + // Fetching head content to get the mime type + const response = await _FetchAsync(fileInfo.url, { method: "HEAD", responseHeaders: ["Content-Type"] }); + const mimeType = response.headerValues ? response.headerValues["Content-Type"] : ""; + if (mimeType) { + registeredPlugin = getPluginForMimeType(mimeType); + } + } + if (!registeredPlugin) { + registeredPlugin = getDefaultPlugin(); + } + } + if (!registeredPlugin) { + throw new Error(`No plugin or fallback for ${pluginExtension ?? fileInfo.url}`); + } + if (pluginOptions?.[registeredPlugin.plugin.name]?.enabled === false) { + throw new Error(`The '${registeredPlugin.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`); + } + if (fileInfo.rawData && !registeredPlugin.isBinary) { + // eslint-disable-next-line no-throw-literal + throw "Loading from ArrayBufferView can not be used with plugins that don't support binary loading."; + } + const getPluginInstance = (callback) => { + // For plugin factories, the plugin is instantiated on each SceneLoader operation. This makes options handling + // much simpler as we can just pass the options to the factory, rather than passing options through to every possible + // plugin call. Given this, options are only supported for plugins that provide a factory function. + if (isFactory(registeredPlugin.plugin)) { + const pluginFactory = registeredPlugin.plugin; + const partialPlugin = pluginFactory.createPlugin(pluginOptions ?? {}); + if (partialPlugin instanceof Promise) { + partialPlugin.then(callback).catch((error) => { + onError("Error instantiating plugin.", error); + }); + // When async factories are used, the plugin instance cannot be returned synchronously. + // In this case, the legacy loader functions will return null. + return null; + } + else { + callback(partialPlugin); + return partialPlugin; + } + } + else { + callback(registeredPlugin.plugin); + return registeredPlugin.plugin; + } + }; + return getPluginInstance((plugin) => { + if (!plugin) { + // eslint-disable-next-line no-throw-literal + throw `The loader plugin corresponding to the '${pluginExtension}' file type has not been found. If using es6, please import the plugin you wish to use before.`; + } + onPluginActivatedObservable.notifyObservers(plugin); + // Check if we have a direct load url. If the plugin is registered to handle + // it or it's not a base64 data url, then pass it through the direct load path. + if (directLoad && ((plugin.canDirectLoad && plugin.canDirectLoad(fileInfo.url)) || !IsBase64DataUrl(fileInfo.url))) { + if (plugin.directLoad) { + const result = plugin.directLoad(scene, directLoad); + if (result instanceof Promise) { + result + .then((data) => { + onSuccess(plugin, data); + }) + .catch((error) => { + onError("Error in directLoad of _loadData: " + error, error); + }); + } + else { + onSuccess(plugin, result); + } + } + else { + onSuccess(plugin, directLoad); + } + return; + } + const useArrayBuffer = registeredPlugin.isBinary; + const dataCallback = (data, responseURL) => { + if (scene.isDisposed) { + onError("Scene has been disposed"); + return; + } + onSuccess(plugin, data, responseURL); + }; + let request = null; + let pluginDisposed = false; + plugin.onDisposeObservable?.add(() => { + pluginDisposed = true; + if (request) { + request.abort(); + request = null; + } + onDispose(); + }); + const manifestChecked = () => { + if (pluginDisposed) { + return; + } + const errorCallback = (request, exception) => { + onError(request?.statusText, exception); + }; + if (!plugin.loadFile && fileInfo.rawData) { + // eslint-disable-next-line no-throw-literal + throw "Plugin does not support loading ArrayBufferView."; + } + request = plugin.loadFile + ? plugin.loadFile(scene, fileInfo.rawData || fileInfo.file || fileInfo.url, fileInfo.rootUrl, dataCallback, onProgress, useArrayBuffer, errorCallback, name) + : scene._loadFile(fileInfo.file || fileInfo.url, dataCallback, onProgress, true, useArrayBuffer, errorCallback); + }; + const engine = scene.getEngine(); + let canUseOfflineSupport = engine.enableOfflineSupport; + if (canUseOfflineSupport) { + // Also check for exceptions + let exceptionFound = false; + for (const regex of scene.disableOfflineSupportExceptionRules) { + if (regex.test(fileInfo.url)) { + exceptionFound = true; + break; + } + } + canUseOfflineSupport = !exceptionFound; + } + if (canUseOfflineSupport && AbstractEngine.OfflineProviderFactory) { + // Checking if a manifest file has been set for this scene and if offline mode has been requested + scene.offlineProvider = AbstractEngine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck); + } + else { + manifestChecked(); + } + }); +} +function _getFileInfo(rootUrl, sceneSource) { + let url; + let name; + let file = null; + let rawData = null; + if (!sceneSource) { + url = rootUrl; + name = Tools.GetFilename(rootUrl); + rootUrl = Tools.GetFolderPath(rootUrl); + } + else if (isFile(sceneSource)) { + url = `file:${sceneSource.name}`; + name = sceneSource.name; + file = sceneSource; + } + else if (ArrayBuffer.isView(sceneSource)) { + url = ""; + name = RandomGUID(); + rawData = sceneSource; + } + else if (sceneSource.startsWith("data:")) { + url = sceneSource; + name = ""; + } + else if (rootUrl) { + const filename = sceneSource; + if (filename.substring(0, 1) === "/") { + Tools.Error("Wrong sceneFilename parameter"); + return null; + } + url = rootUrl + filename; + name = filename; + } + else { + url = sceneSource; + name = Tools.GetFilename(sceneSource); + rootUrl = Tools.GetFolderPath(sceneSource); + } + return { + url: url, + rootUrl: rootUrl, + name: name, + file: file, + rawData, + }; +} +/** + * Adds a new plugin to the list of registered plugins + * @param plugin defines the plugin to add + */ +function RegisterSceneLoaderPlugin(plugin) { + if (typeof plugin.extensions === "string") { + const extension = plugin.extensions; + registeredPlugins[extension.toLowerCase()] = { + plugin: plugin, + isBinary: false, + }; + } + else { + const extensions = plugin.extensions; + Object.keys(extensions).forEach((extension) => { + registeredPlugins[extension.toLowerCase()] = { + plugin: plugin, + isBinary: extensions[extension].isBinary, + mimeType: extensions[extension].mimeType, + }; + }); + } +} +/** + * Import meshes into a scene + * @param source a string that defines the name of the scene file, or starts with "data:" following by the stringified version of the scene, or a File object, or an ArrayBufferView + * @param scene the instance of BABYLON.Scene to append to + * @param options an object that configures aspects of how the scene is loaded + * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups + */ +function ImportMeshAsync(source, scene, options) { + const { meshNames, rootUrl = "", onProgress, pluginExtension, name, pluginOptions } = options ?? {}; + return importMeshAsyncCore(meshNames, rootUrl, source, scene, onProgress, pluginExtension, name, pluginOptions); +} +async function importMeshAsync(meshNames, rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "", pluginOptions = {}) { + if (!scene) { + Logger.Error("No scene available to import mesh to"); + return null; + } + const fileInfo = _getFileInfo(rootUrl, sceneFilename); + if (!fileInfo) { + return null; + } + const loadingToken = {}; + scene.addPendingData(loadingToken); + const disposeHandler = () => { + scene.removePendingData(loadingToken); + }; + const errorHandler = (message, exception) => { + const errorMessage = formatErrorMessage(fileInfo, message, exception); + if (onError) { + onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception)); + } + else { + Logger.Error(errorMessage); + // should the exception be thrown? + } + disposeHandler(); + }; + const progressHandler = onProgress + ? (event) => { + try { + onProgress(event); + } + catch (e) { + errorHandler("Error in onProgress callback: " + e, e); + } + } + : undefined; + const successHandler = (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers) => { + scene.importedMeshesFiles.push(fileInfo.url); + if (onSuccess) { + try { + onSuccess(meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers); + } + catch (e) { + errorHandler("Error in onSuccess callback: " + e, e); + } + } + scene.removePendingData(loadingToken); + }; + return await loadDataAsync(fileInfo, scene, (plugin, data, responseURL) => { + if (plugin.rewriteRootURL) { + fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL); + } + if (plugin.importMesh) { + const syncedPlugin = plugin; + const meshes = []; + const particleSystems = []; + const skeletons = []; + if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) { + return; + } + scene.loadingPluginName = plugin.name; + successHandler(meshes, particleSystems, skeletons, [], [], [], [], []); + } + else { + const asyncedPlugin = plugin; + asyncedPlugin + .importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name) + .then((result) => { + scene.loadingPluginName = plugin.name; + successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups, result.transformNodes, result.geometries, result.lights, result.spriteManagers); + }) + .catch((error) => { + errorHandler(error.message, error); + }); + } + }, progressHandler, errorHandler, disposeHandler, pluginExtension, name, pluginOptions); +} +function importMeshAsyncCore(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name, pluginOptions) { + return new Promise((resolve, reject) => { + try { + importMeshAsync(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers) => { + resolve({ + meshes: meshes, + particleSystems: particleSystems, + skeletons: skeletons, + animationGroups: animationGroups, + transformNodes: transformNodes, + geometries: geometries, + lights: lights, + spriteManagers: spriteManagers, + }); + }, onProgress, (scene, message, exception) => { + reject(exception || new Error(message)); + }, pluginExtension, name, pluginOptions).catch(reject); + } + catch (error) { + reject(error); + } + }); +} +// This is the core implementation of load scene +async function loadSceneImplAsync(rootUrl, sceneFilename = "", engine = EngineStore.LastCreatedEngine, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "", pluginOptions = {}) { + if (!engine) { + Tools.Error("No engine available"); + return; + } + await appendSceneImplAsync(rootUrl, sceneFilename, new Scene(engine), onSuccess, onProgress, onError, pluginExtension, name, pluginOptions); +} +// This function is shared between the new module level loadSceneAsync and the legacy SceneLoader.LoadAsync +function loadSceneSharedAsync(rootUrl, sceneFilename, engine, onProgress, pluginExtension, name, pluginOptions) { + return new Promise((resolve, reject) => { + loadSceneImplAsync(rootUrl, sceneFilename, engine, (scene) => { + resolve(scene); + }, onProgress, (scene, message, exception) => { + reject(exception || new Error(message)); + }, pluginExtension, name, pluginOptions); + }); +} +// This is the core implementation of append scene +async function appendSceneImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "", pluginOptions = {}) { + if (!scene) { + Logger.Error("No scene available to append to"); + return null; + } + const fileInfo = _getFileInfo(rootUrl, sceneFilename); + if (!fileInfo) { + return null; + } + const loadingToken = {}; + scene.addPendingData(loadingToken); + const disposeHandler = () => { + scene.removePendingData(loadingToken); + }; + if (SceneLoaderFlags.ShowLoadingScreen && !showingLoadingScreen) { + showingLoadingScreen = true; + scene.getEngine().displayLoadingUI(); + scene.executeWhenReady(() => { + scene.getEngine().hideLoadingUI(); + showingLoadingScreen = false; + }); + } + const errorHandler = (message, exception) => { + const errorMessage = formatErrorMessage(fileInfo, message, exception); + if (onError) { + onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception)); + } + else { + Logger.Error(errorMessage); + // should the exception be thrown? + } + disposeHandler(); + }; + const progressHandler = onProgress + ? (event) => { + try { + onProgress(event); + } + catch (e) { + errorHandler("Error in onProgress callback", e); + } + } + : undefined; + const successHandler = () => { + if (onSuccess) { + try { + onSuccess(scene); + } + catch (e) { + errorHandler("Error in onSuccess callback", e); + } + } + scene.removePendingData(loadingToken); + }; + return await loadDataAsync(fileInfo, scene, (plugin, data) => { + if (plugin.load) { + const syncedPlugin = plugin; + if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) { + return; + } + scene.loadingPluginName = plugin.name; + successHandler(); + } + else { + const asyncedPlugin = plugin; + asyncedPlugin + .loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name) + .then(() => { + scene.loadingPluginName = plugin.name; + successHandler(); + }) + .catch((error) => { + errorHandler(error.message, error); + }); + } + }, progressHandler, errorHandler, disposeHandler, pluginExtension, name, pluginOptions); +} +// This function is shared between the new module level appendSceneAsync and the legacy SceneLoader.AppendAsync +function appendSceneSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name, pluginOptions) { + return new Promise((resolve, reject) => { + try { + appendSceneImplAsync(rootUrl, sceneFilename, scene, (scene) => { + resolve(scene); + }, onProgress, (scene, message, exception) => { + reject(exception || new Error(message)); + }, pluginExtension, name, pluginOptions).catch(reject); + } + catch (error) { + reject(error); + } + }); +} +// This is the core implementation of load asset container +async function loadAssetContainerImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "", pluginOptions = {}) { + if (!scene) { + Logger.Error("No scene available to load asset container to"); + return null; + } + const fileInfo = _getFileInfo(rootUrl, sceneFilename); + if (!fileInfo) { + return null; + } + const loadingToken = {}; + scene.addPendingData(loadingToken); + const disposeHandler = () => { + scene.removePendingData(loadingToken); + }; + const errorHandler = (message, exception) => { + const errorMessage = formatErrorMessage(fileInfo, message, exception); + if (onError) { + onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception)); + } + else { + Logger.Error(errorMessage); + // should the exception be thrown? + } + disposeHandler(); + }; + const progressHandler = onProgress + ? (event) => { + try { + onProgress(event); + } + catch (e) { + errorHandler("Error in onProgress callback", e); + } + } + : undefined; + const successHandler = (assets) => { + if (onSuccess) { + try { + onSuccess(assets); + } + catch (e) { + errorHandler("Error in onSuccess callback", e); + } + } + scene.removePendingData(loadingToken); + }; + return await loadDataAsync(fileInfo, scene, (plugin, data) => { + if (plugin.loadAssetContainer) { + const syncedPlugin = plugin; + const assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler); + if (!assetContainer) { + return; + } + assetContainer.populateRootNodes(); + scene.loadingPluginName = plugin.name; + successHandler(assetContainer); + } + else if (plugin.loadAssetContainerAsync) { + const asyncedPlugin = plugin; + asyncedPlugin + .loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name) + .then((assetContainer) => { + assetContainer.populateRootNodes(); + scene.loadingPluginName = plugin.name; + successHandler(assetContainer); + }) + .catch((error) => { + errorHandler(error.message, error); + }); + } + else { + errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method."); + } + }, progressHandler, errorHandler, disposeHandler, pluginExtension, name, pluginOptions); +} +// This function is shared between the new module level loadAssetContainerAsync and the legacy SceneLoader.LoadAssetContainerAsync +function loadAssetContainerSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name, pluginOptions) { + return new Promise((resolve, reject) => { + try { + loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, (assets) => { + resolve(assets); + }, onProgress, (scene, message, exception) => { + reject(exception || new Error(message)); + }, pluginExtension, name, pluginOptions).catch(reject); + } + catch (error) { + reject(error); + } + }); +} +// This is the core implementation of import animations +async function importAnimationsImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, overwriteAnimations = true, animationGroupLoadingMode = 0 /* SceneLoaderAnimationGroupLoadingMode.Clean */, targetConverter = null, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "", pluginOptions = {}) { + if (!scene) { + Logger.Error("No scene available to load animations to"); + return; + } + if (overwriteAnimations) { + // Reset, stop and dispose all animations before loading new ones + for (const animatable of scene.animatables) { + animatable.reset(); + } + scene.stopAllAnimations(); + scene.animationGroups.slice().forEach((animationGroup) => { + animationGroup.dispose(); + }); + const nodes = scene.getNodes(); + nodes.forEach((node) => { + if (node.animations) { + node.animations = []; + } + }); + } + else { + switch (animationGroupLoadingMode) { + case 0 /* SceneLoaderAnimationGroupLoadingMode.Clean */: + scene.animationGroups.slice().forEach((animationGroup) => { + animationGroup.dispose(); + }); + break; + case 1 /* SceneLoaderAnimationGroupLoadingMode.Stop */: + scene.animationGroups.forEach((animationGroup) => { + animationGroup.stop(); + }); + break; + case 2 /* SceneLoaderAnimationGroupLoadingMode.Sync */: + scene.animationGroups.forEach((animationGroup) => { + animationGroup.reset(); + animationGroup.restart(); + }); + break; + case 3 /* SceneLoaderAnimationGroupLoadingMode.NoSync */: + // nothing to do + break; + default: + Logger.Error("Unknown animation group loading mode value '" + animationGroupLoadingMode + "'"); + return; + } + } + const startingIndexForNewAnimatables = scene.animatables.length; + const onAssetContainerLoaded = (container) => { + container.mergeAnimationsTo(scene, scene.animatables.slice(startingIndexForNewAnimatables), targetConverter); + container.dispose(); + scene.onAnimationFileImportedObservable.notifyObservers(scene); + if (onSuccess) { + onSuccess(scene); + } + }; + await loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, onAssetContainerLoaded, onProgress, onError, pluginExtension, name, pluginOptions); +} +// This function is shared between the new module level importAnimationsAsync and the legacy SceneLoader.ImportAnimationsAsync +function importAnimationsSharedAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onProgress, pluginExtension, name, pluginOptions) { + return new Promise((resolve, reject) => { + try { + importAnimationsImplAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, (scene) => { + resolve(scene); + }, onProgress, (scene, message, exception) => { + reject(exception || new Error(message)); + }, pluginExtension, name, pluginOptions).catch(reject); + } + catch (error) { + reject(error); + } + }); +} +/** + * Class used to load scene from various file formats using registered plugins + * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes + * @deprecated The module level functions are more efficient for bundler tree shaking and allow plugin options to be passed through. Future improvements to scene loading will primarily be in the module level functions. The SceneLoader class will remain available, but it will be beneficial to prefer the module level functions. + * @see {@link ImportMeshAsync}, {@link LoadSceneAsync}, {@link AppendSceneAsync}, {@link ImportAnimationsAsync}, {@link LoadAssetContainerAsync} + */ +class SceneLoader { + /** + * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data + */ + static get ForceFullSceneLoadingForIncremental() { + return SceneLoaderFlags.ForceFullSceneLoadingForIncremental; + } + static set ForceFullSceneLoadingForIncremental(value) { + SceneLoaderFlags.ForceFullSceneLoadingForIncremental = value; + } + /** + * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene + */ + static get ShowLoadingScreen() { + return SceneLoaderFlags.ShowLoadingScreen; + } + static set ShowLoadingScreen(value) { + SceneLoaderFlags.ShowLoadingScreen = value; + } + /** + * Defines the current logging level (while loading the scene) + * @ignorenaming + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + static get loggingLevel() { + return SceneLoaderFlags.loggingLevel; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + static set loggingLevel(value) { + SceneLoaderFlags.loggingLevel = value; + } + /** + * Gets or set a boolean indicating if matrix weights must be cleaned upon loading + */ + static get CleanBoneMatrixWeights() { + return SceneLoaderFlags.CleanBoneMatrixWeights; + } + static set CleanBoneMatrixWeights(value) { + SceneLoaderFlags.CleanBoneMatrixWeights = value; + } + /** + * Gets the default plugin (used to load Babylon files) + * @returns the .babylon plugin + */ + static GetDefaultPlugin() { + return getDefaultPlugin(); + } + // Public functions + /** + * Gets a plugin that can load the given extension + * @param extension defines the extension to load + * @returns a plugin or null if none works + */ + static GetPluginForExtension(extension) { + return getPluginForExtension(extension, true)?.plugin; + } + /** + * Gets a boolean indicating that the given extension can be loaded + * @param extension defines the extension to load + * @returns true if the extension is supported + */ + static IsPluginForExtensionAvailable(extension) { + return isPluginForExtensionAvailable(extension); + } + /** + * Adds a new plugin to the list of registered plugins + * @param plugin defines the plugin to add + */ + static RegisterPlugin(plugin) { + RegisterSceneLoaderPlugin(plugin); + } + /** + * Import meshes into a scene + * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene the instance of BABYLON.Scene to append to + * @param onSuccess a callback with a list of imported meshes, particleSystems, skeletons, and animationGroups when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @param name defines the name of the file, if the data is binary + * @deprecated Please use the module level {@link ImportMeshAsync} instead + */ + static ImportMesh(meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name) { + importMeshAsync(meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name).catch((error) => onError?.(EngineStore.LastCreatedScene, error?.message, error)); + } + /** + * Import meshes into a scene + * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene the instance of BABYLON.Scene to append to + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @param name defines the name of the file + * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups + * @deprecated Please use the module level {@link ImportMeshAsync} instead + */ + static ImportMeshAsync(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name) { + return importMeshAsyncCore(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name); + } + /** + * Load a scene + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param engine is the instance of BABYLON.Engine to use to create the scene + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @param name defines the filename, if the data is binary + * @deprecated Please use the module level {@link LoadSceneAsync} instead + */ + static Load(rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension, name) { + loadSceneImplAsync(rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension, name).catch((error) => onError?.(EngineStore.LastCreatedScene, error?.message, error)); + } + /** + * Load a scene + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param engine is the instance of BABYLON.Engine to use to create the scene + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @param name defines the filename, if the data is binary + * @returns The loaded scene + * @deprecated Please use the module level {@link LoadSceneAsync} instead + */ + static LoadAsync(rootUrl, sceneFilename, engine, onProgress, pluginExtension, name) { + return loadSceneSharedAsync(rootUrl, sceneFilename, engine, onProgress, pluginExtension, name); + } + /** + * Append a scene + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @param name defines the name of the file, if the data is binary + * @deprecated Please use the module level {@link AppendSceneAsync} instead + */ + static Append(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name) { + appendSceneImplAsync(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name).catch((error) => onError?.((scene ?? EngineStore.LastCreatedScene), error?.message, error)); + } + /** + * Append a scene + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @param name defines the name of the file, if the data is binary + * @returns The given scene + * @deprecated Please use the module level {@link AppendSceneAsync} instead + */ + static AppendAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name) { + return appendSceneSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name); + } + /** + * Load a scene into an asset container + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @param name defines the filename, if the data is binary + * @deprecated Please use the module level {@link LoadAssetContainerAsync} instead + */ + static LoadAssetContainer(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name) { + loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name).catch((error) => onError?.((scene ?? EngineStore.LastCreatedScene), error?.message, error)); + } + /** + * Load a scene into an asset container + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string) + * @param scene is the instance of Scene to append to + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @param name defines the filename, if the data is binary + * @returns The loaded asset container + * @deprecated Please use the module level {@link LoadAssetContainerAsync} instead + */ + static LoadAssetContainerAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name) { + return loadAssetContainerSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name); + } + /** + * Import animations from a file into a scene + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) + * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise + * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones + * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name) + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @param name defines the filename, if the data is binary + * @deprecated Please use the module level {@link ImportAnimationsAsync} instead + */ + static ImportAnimations(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension, name) { + importAnimationsImplAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension, name).catch((error) => onError?.((scene ?? EngineStore.LastCreatedScene), error?.message, error)); + } + /** + * Import animations from a file into a scene + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) + * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise + * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones + * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name) + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @param name defines the filename, if the data is binary + * @returns the updated scene with imported animations + * @deprecated Please use the module level {@link ImportAnimationsAsync} instead + */ + static ImportAnimationsAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onSuccess, onProgress, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onError, pluginExtension, name) { + return importAnimationsSharedAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onProgress, pluginExtension, name); + } +} +/** + * No logging while loading + */ +SceneLoader.NO_LOGGING = 0; +/** + * Minimal logging while loading + */ +SceneLoader.MINIMAL_LOGGING = 1; +/** + * Summary logging while loading + */ +SceneLoader.SUMMARY_LOGGING = 2; +/** + * Detailed logging while loading + */ +SceneLoader.DETAILED_LOGGING = 3; +// Members +/** + * Event raised when a plugin is used to load a scene + */ +SceneLoader.OnPluginActivatedObservable = onPluginActivatedObservable; + +Mesh._instancedMeshFactory = (name, mesh) => { + const instance = new InstancedMesh(name, mesh); + if (mesh.instancedBuffers) { + instance.instancedBuffers = {}; + for (const key in mesh.instancedBuffers) { + instance.instancedBuffers[key] = mesh.instancedBuffers[key]; + } + } + return instance; +}; +/** + * Creates an instance based on a source mesh. + */ +class InstancedMesh extends AbstractMesh { + /** + * Creates a new InstancedMesh object from the mesh source. + * @param name defines the name of the instance + * @param source the mesh to create the instance from + */ + constructor(name, source) { + super(name, source.getScene()); + /** @internal */ + this._indexInSourceMeshInstanceArray = -1; + /** @internal */ + this._distanceToCamera = 0; + source.addInstance(this); + this._sourceMesh = source; + this._unIndexed = source._unIndexed; + this.position.copyFrom(source.position); + this.rotation.copyFrom(source.rotation); + this.scaling.copyFrom(source.scaling); + if (source.rotationQuaternion) { + this.rotationQuaternion = source.rotationQuaternion.clone(); + } + this.animations = source.animations.slice(); + for (const range of source.getAnimationRanges()) { + if (range != null) { + this.createAnimationRange(range.name, range.from, range.to); + } + } + this.infiniteDistance = source.infiniteDistance; + this.setPivotMatrix(source.getPivotMatrix()); + this.refreshBoundingInfo(true, true); + this._syncSubMeshes(); + } + /** + * @returns the string "InstancedMesh". + */ + getClassName() { + return "InstancedMesh"; + } + /** Gets the list of lights affecting that mesh */ + get lightSources() { + return this._sourceMesh._lightSources; + } + _resyncLightSources() { + // Do nothing as all the work will be done by source mesh + } + _resyncLightSource() { + // Do nothing as all the work will be done by source mesh + } + _removeLightSource() { + // Do nothing as all the work will be done by source mesh + } + // Methods + /** + * If the source mesh receives shadows + */ + get receiveShadows() { + return this._sourceMesh.receiveShadows; + } + set receiveShadows(_value) { + if (this._sourceMesh?.receiveShadows !== _value) { + Tools.Warn("Setting receiveShadows on an instanced mesh has no effect"); + } + } + /** + * The material of the source mesh + */ + get material() { + return this._sourceMesh.material; + } + set material(_value) { + if (this._sourceMesh?.material !== _value) { + Tools.Warn("Setting material on an instanced mesh has no effect"); + } + } + /** + * Visibility of the source mesh + */ + get visibility() { + return this._sourceMesh.visibility; + } + set visibility(_value) { + if (this._sourceMesh?.visibility !== _value) { + Tools.Warn("Setting visibility on an instanced mesh has no effect"); + } + } + /** + * Skeleton of the source mesh + */ + get skeleton() { + return this._sourceMesh.skeleton; + } + set skeleton(_value) { + if (this._sourceMesh?.skeleton !== _value) { + Tools.Warn("Setting skeleton on an instanced mesh has no effect"); + } + } + /** + * Rendering ground id of the source mesh + */ + get renderingGroupId() { + return this._sourceMesh.renderingGroupId; + } + set renderingGroupId(value) { + if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) { + return; + } + //no-op with warning + Logger.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene"); + } + /** + * @returns the total number of vertices (integer). + */ + getTotalVertices() { + return this._sourceMesh ? this._sourceMesh.getTotalVertices() : 0; + } + /** + * Returns a positive integer : the total number of indices in this mesh geometry. + * @returns the number of indices or zero if the mesh has no geometry. + */ + getTotalIndices() { + return this._sourceMesh.getTotalIndices(); + } + /** + * The source mesh of the instance + */ + get sourceMesh() { + return this._sourceMesh; + } + /** + * Gets the mesh internal Geometry object + */ + get geometry() { + return this._sourceMesh._geometry; + } + /** + * Creates a new InstancedMesh object from the mesh model. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances + * @param name defines the name of the new instance + * @returns a new InstancedMesh + */ + createInstance(name) { + return this._sourceMesh.createInstance(name); + } + /** + * Is this node ready to be used/rendered + * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) + * @returns {boolean} is it ready + */ + isReady(completeCheck = false) { + return this._sourceMesh.isReady(completeCheck, true); + } + /** + * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices. + * @param kind kind of verticies to retrieve (eg. positions, normals, uvs, etc.) + * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. + * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is + * @returns a float array or a Float32Array of the requested kind of data : positions, normals, uvs, etc. + */ + getVerticesData(kind, copyWhenShared, forceCopy) { + return this._sourceMesh.getVerticesData(kind, copyWhenShared, forceCopy); + } + copyVerticesData(kind, vertexData) { + this._sourceMesh.copyVerticesData(kind, vertexData); + } + /** + * Sets the vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. + * The `data` are either a numeric array either a Float32Array. + * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initially none) or updater. + * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc). + * Note that a new underlying VertexBuffer object is created each call. + * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. + * + * Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + * + * Returns the Mesh. + * @param kind defines vertex data kind + * @param data defines the data source + * @param updatable defines if the data must be flagged as updatable (false as default) + * @param stride defines the vertex stride (optional) + * @returns the current mesh + */ + setVerticesData(kind, data, updatable, stride) { + if (this.sourceMesh) { + this.sourceMesh.setVerticesData(kind, data, updatable, stride); + } + return this.sourceMesh; + } + /** + * Updates the existing vertex data of the mesh geometry for the requested `kind`. + * If the mesh has no geometry, it is simply returned as it is. + * The `data` are either a numeric array either a Float32Array. + * No new underlying VertexBuffer object is created. + * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. + * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh. + * + * Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + * + * Returns the Mesh. + * @param kind defines vertex data kind + * @param data defines the data source + * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind + * @param makeItUnique defines it the updated vertex buffer must be flagged as unique (false by default) + * @returns the source mesh + */ + updateVerticesData(kind, data, updateExtends, makeItUnique) { + if (this.sourceMesh) { + this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique); + } + return this.sourceMesh; + } + /** + * Sets the mesh indices. + * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array). + * If the mesh has no geometry, a new Geometry object is created and set to the mesh. + * This method creates a new index buffer each call. + * Returns the Mesh. + * @param indices the source data + * @param totalVertices defines the total number of vertices referenced by indices (could be null) + * @returns source mesh + */ + setIndices(indices, totalVertices = null) { + if (this.sourceMesh) { + this.sourceMesh.setIndices(indices, totalVertices); + } + return this.sourceMesh; + } + /** + * Boolean : True if the mesh owns the requested kind of data. + * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values : + * - VertexBuffer.PositionKind + * - VertexBuffer.UVKind + * - VertexBuffer.UV2Kind + * - VertexBuffer.UV3Kind + * - VertexBuffer.UV4Kind + * - VertexBuffer.UV5Kind + * - VertexBuffer.UV6Kind + * - VertexBuffer.ColorKind + * - VertexBuffer.MatricesIndicesKind + * - VertexBuffer.MatricesIndicesExtraKind + * - VertexBuffer.MatricesWeightsKind + * - VertexBuffer.MatricesWeightsExtraKind + * @returns true if data kind is present + */ + isVerticesDataPresent(kind) { + return this._sourceMesh.isVerticesDataPresent(kind); + } + /** + * @returns an array of indices (IndicesArray). + */ + getIndices() { + return this._sourceMesh.getIndices(); + } + get _positions() { + return this._sourceMesh._positions; + } + refreshBoundingInfo(applySkeletonOrOptions = false, applyMorph = false) { + if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) { + return this; + } + let options; + if (typeof applySkeletonOrOptions === "object") { + options = applySkeletonOrOptions; + } + else { + options = { + applySkeleton: applySkeletonOrOptions, + applyMorph: applyMorph, + }; + } + const bias = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null; + this._refreshBoundingInfo(this._sourceMesh._getData(options, null, VertexBuffer.PositionKind), bias); + return this; + } + /** @internal */ + _preActivate() { + if (this._currentLOD) { + this._currentLOD._preActivate(); + } + return this; + } + /** + * @internal + */ + _activate(renderId, intermediateRendering) { + super._activate(renderId, intermediateRendering); + if (!this._sourceMesh.subMeshes) { + Logger.Warn("Instances should only be created for meshes with geometry."); + } + if (this._currentLOD) { + const differentSign = this._currentLOD._getWorldMatrixDeterminant() >= 0 !== this._getWorldMatrixDeterminant() >= 0; + if (differentSign) { + this._internalAbstractMeshDataInfo._actAsRegularMesh = true; + return true; + } + this._internalAbstractMeshDataInfo._actAsRegularMesh = false; + this._currentLOD._registerInstanceForRenderId(this, renderId); + if (intermediateRendering) { + if (!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate) { + this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = true; + return true; + } + } + else { + if (!this._currentLOD._internalAbstractMeshDataInfo._isActive) { + this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances = true; + return true; + } + } + } + return false; + } + /** @internal */ + _postActivate() { + if (this._sourceMesh.edgesShareWithInstances && this._sourceMesh._edgesRenderer && this._sourceMesh._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) { + // we are using the edge renderer of the source mesh + this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer); + this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix()); + } + else if (this._edgesRenderer && this._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) { + // we are using the edge renderer defined for this instance + this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer); + } + } + getWorldMatrix() { + if (this._currentLOD && this._currentLOD.billboardMode !== TransformNode.BILLBOARDMODE_NONE && this._currentLOD._masterMesh !== this) { + if (!this._billboardWorldMatrix) { + this._billboardWorldMatrix = new Matrix(); + } + const tempMaster = this._currentLOD._masterMesh; + this._currentLOD._masterMesh = this; + TmpVectors.Vector3[7].copyFrom(this._currentLOD.position); + this._currentLOD.position.set(0, 0, 0); + this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(true)); + this._currentLOD.position.copyFrom(TmpVectors.Vector3[7]); + this._currentLOD._masterMesh = tempMaster; + return this._billboardWorldMatrix; + } + return super.getWorldMatrix(); + } + get isAnInstance() { + return true; + } + /** + * Returns the current associated LOD AbstractMesh. + * @param camera defines the camera to use to pick the LOD level + * @returns a Mesh or `null` if no LOD is associated with the AbstractMesh + */ + getLOD(camera) { + if (!camera) { + return this; + } + const sourceMeshLODLevels = this.sourceMesh.getLODLevels(); + if (!sourceMeshLODLevels || sourceMeshLODLevels.length === 0) { + this._currentLOD = this.sourceMesh; + } + else { + const boundingInfo = this.getBoundingInfo(); + this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere); + } + return this._currentLOD; + } + /** + * @internal + */ + _preActivateForIntermediateRendering(renderId) { + return this.sourceMesh._preActivateForIntermediateRendering(renderId); + } + /** @internal */ + _syncSubMeshes() { + this.releaseSubMeshes(); + if (this._sourceMesh.subMeshes) { + for (let index = 0; index < this._sourceMesh.subMeshes.length; index++) { + this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh); + } + } + return this; + } + /** @internal */ + _generatePointsArray() { + return this._sourceMesh._generatePointsArray(); + } + /** @internal */ + _updateBoundingInfo() { + if (this.hasBoundingInfo) { + this.getBoundingInfo().update(this.worldMatrixFromCache); + } + else { + this.buildBoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache); + } + this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache); + return this; + } + /** + * Creates a new InstancedMesh from the current mesh. + * + * Returns the clone. + * @param name the cloned mesh name + * @param newParent the optional Node to parent the clone to. + * @param doNotCloneChildren if `true` the model children aren't cloned. + * @param newSourceMesh if set this mesh will be used as the source mesh instead of ths instance's one + * @returns the clone + */ + clone(name, newParent = null, doNotCloneChildren, newSourceMesh) { + const result = (newSourceMesh || this._sourceMesh).createInstance(name); + // Deep copy + DeepCopier.DeepCopy(this, result, [ + "name", + "subMeshes", + "uniqueId", + "parent", + "lightSources", + "receiveShadows", + "material", + "visibility", + "skeleton", + "sourceMesh", + "isAnInstance", + "facetNb", + "isFacetDataEnabled", + "isBlocked", + "useBones", + "hasInstances", + "collider", + "edgesRenderer", + "forward", + "up", + "right", + "absolutePosition", + "absoluteScaling", + "absoluteRotationQuaternion", + "isWorldMatrixFrozen", + "nonUniformScaling", + "behaviors", + "worldMatrixFromCache", + "hasThinInstances", + "hasBoundingInfo", + ], []); + // Bounding info + this.refreshBoundingInfo(); + // Parent + if (newParent) { + result.parent = newParent; + } + if (!doNotCloneChildren) { + // Children + for (let index = 0; index < this.getScene().meshes.length; index++) { + const mesh = this.getScene().meshes[index]; + if (mesh.parent === this) { + mesh.clone(mesh.name, result); + } + } + } + result.computeWorldMatrix(true); + this.onClonedObservable.notifyObservers(result); + return result; + } + /** + * Disposes the InstancedMesh. + * Returns nothing. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse, disposeMaterialAndTextures = false) { + // Remove from mesh + this._sourceMesh.removeInstance(this); + super.dispose(doNotRecurse, disposeMaterialAndTextures); + } + /** + * @internal + */ + _serializeAsParent(serializationObject) { + super._serializeAsParent(serializationObject); + serializationObject.parentId = this._sourceMesh.uniqueId; + serializationObject.parentInstanceIndex = this._indexInSourceMeshInstanceArray; + } + /** + * Instantiate (when possible) or clone that node with its hierarchy + * @param newParent defines the new parent to use for the instance (or clone) + * @param options defines options to configure how copy is done + * @param options.doNotInstantiate defines if the model must be instantiated or just cloned + * @param options.newSourcedMesh newSourcedMesh the new source mesh for the instance (or clone) + * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created + * @returns an instance (or a clone) of the current node with its hierarchy + */ + instantiateHierarchy(newParent = null, options, onNewNodeCreated) { + const clone = this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true, options && options.newSourcedMesh); + if (clone) { + if (onNewNodeCreated) { + onNewNodeCreated(this, clone); + } + } + for (const child of this.getChildTransformNodes(true)) { + child.instantiateHierarchy(clone, options, onNewNodeCreated); + } + return clone; + } +} +Mesh.prototype.registerInstancedBuffer = function (kind, stride) { + // Remove existing one + this._userInstancedBuffersStorage?.vertexBuffers[kind]?.dispose(); + // Creates the instancedBuffer field if not present + if (!this.instancedBuffers) { + this.instancedBuffers = {}; + for (const instance of this.instances) { + instance.instancedBuffers = {}; + } + } + if (!this._userInstancedBuffersStorage) { + this._userInstancedBuffersStorage = { + data: {}, + vertexBuffers: {}, + strides: {}, + sizes: {}, + vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : undefined, + }; + } + // Creates an empty property for this kind + this.instancedBuffers[kind] = null; + this._userInstancedBuffersStorage.strides[kind] = stride; + this._userInstancedBuffersStorage.sizes[kind] = stride * 32; // Initial size + this._userInstancedBuffersStorage.data[kind] = new Float32Array(this._userInstancedBuffersStorage.sizes[kind]); + this._userInstancedBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true); + for (const instance of this.instances) { + instance.instancedBuffers[kind] = null; + } + this._invalidateInstanceVertexArrayObject(); + this._markSubMeshesAsAttributesDirty(); +}; +Mesh.prototype._processInstancedBuffers = function (visibleInstances, renderSelf) { + const instanceCount = visibleInstances ? visibleInstances.length : 0; + for (const kind in this.instancedBuffers) { + let size = this._userInstancedBuffersStorage.sizes[kind]; + const stride = this._userInstancedBuffersStorage.strides[kind]; + // Resize if required + const expectedSize = (instanceCount + 1) * stride; + while (size < expectedSize) { + size *= 2; + } + if (this._userInstancedBuffersStorage.data[kind].length != size) { + this._userInstancedBuffersStorage.data[kind] = new Float32Array(size); + this._userInstancedBuffersStorage.sizes[kind] = size; + if (this._userInstancedBuffersStorage.vertexBuffers[kind]) { + this._userInstancedBuffersStorage.vertexBuffers[kind].dispose(); + this._userInstancedBuffersStorage.vertexBuffers[kind] = null; + } + } + const data = this._userInstancedBuffersStorage.data[kind]; + // Update data buffer + let offset = 0; + if (renderSelf) { + const value = this.instancedBuffers[kind]; + if (value.toArray) { + value.toArray(data, offset); + } + else if (value.copyToArray) { + value.copyToArray(data, offset); + } + else { + data[offset] = value; + } + offset += stride; + } + for (let instanceIndex = 0; instanceIndex < instanceCount; instanceIndex++) { + const instance = visibleInstances[instanceIndex]; + const value = instance.instancedBuffers[kind]; + if (value.toArray) { + value.toArray(data, offset); + } + else if (value.copyToArray) { + value.copyToArray(data, offset); + } + else { + data[offset] = value; + } + offset += stride; + } + // Update vertex buffer + if (!this._userInstancedBuffersStorage.vertexBuffers[kind]) { + this._userInstancedBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true); + this._invalidateInstanceVertexArrayObject(); + } + else { + this._userInstancedBuffersStorage.vertexBuffers[kind].updateDirectly(data, 0); + } + } +}; +Mesh.prototype._invalidateInstanceVertexArrayObject = function () { + if (!this._userInstancedBuffersStorage || this._userInstancedBuffersStorage.vertexArrayObjects === undefined) { + return; + } + for (const kind in this._userInstancedBuffersStorage.vertexArrayObjects) { + this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[kind]); + } + this._userInstancedBuffersStorage.vertexArrayObjects = {}; +}; +Mesh.prototype._disposeInstanceSpecificData = function () { + if (this._instanceDataStorage.instancesBuffer) { + this._instanceDataStorage.instancesBuffer.dispose(); + this._instanceDataStorage.instancesBuffer = null; + } + while (this.instances.length) { + this.instances[0].dispose(); + } + for (const kind in this.instancedBuffers) { + if (this._userInstancedBuffersStorage.vertexBuffers[kind]) { + this._userInstancedBuffersStorage.vertexBuffers[kind].dispose(); + } + } + this._invalidateInstanceVertexArrayObject(); + this.instancedBuffers = {}; +}; +// Register Class Name +RegisterClass("BABYLON.InstancedMesh", InstancedMesh); + +/** + * Root class for AssetContainer and KeepAssets + */ +class AbstractAssetContainer { + constructor() { + /** + * Gets the list of root nodes (ie. nodes with no parent) + */ + this.rootNodes = []; + /** All of the cameras added to this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras + */ + this.cameras = []; + /** + * All of the lights added to this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + */ + this.lights = []; + /** + * All of the (abstract) meshes added to this scene + */ + this.meshes = []; + /** + * The list of skeletons added to the scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons + */ + this.skeletons = []; + /** + * All of the particle systems added to this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro + */ + this.particleSystems = []; + /** + * Gets a list of Animations associated with the scene + */ + this.animations = []; + /** + * All of the animation groups added to this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations + */ + this.animationGroups = []; + /** + * All of the multi-materials added to this scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials + */ + this.multiMaterials = []; + /** + * All of the materials added to this scene + * In the context of a Scene, it is not supposed to be modified manually. + * Any addition or removal should be done using the addMaterial and removeMaterial Scene methods. + * Note also that the order of the Material within the array is not significant and might change. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction + */ + this.materials = []; + /** + * The list of morph target managers added to the scene + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph + */ + this.morphTargetManagers = []; + /** + * The list of geometries used in the scene. + */ + this.geometries = []; + /** + * All of the transform nodes added to this scene + * In the context of a Scene, it is not supposed to be modified manually. + * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods. + * Note also that the order of the TransformNode within the array is not significant and might change. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node + */ + this.transformNodes = []; + /** + * ActionManagers available on the scene. + * @deprecated + */ + this.actionManagers = []; + /** + * Textures to keep. + */ + this.textures = []; + /** @internal */ + this._environmentTexture = null; + /** + * The list of postprocesses added to the scene + */ + this.postProcesses = []; + /** + * The list of sounds + */ + this.sounds = null; + /** + * The list of effect layers added to the scene + */ + this.effectLayers = []; + /** + * The list of layers added to the scene + */ + this.layers = []; + /** + * The list of reflection probes added to the scene + */ + this.reflectionProbes = []; + } + /** + * Texture used in all pbr material as the reflection texture. + * As in the majority of the scene they are the same (exception for multi room and so on), + * this is easier to reference from here than from all the materials. + */ + get environmentTexture() { + return this._environmentTexture; + } + set environmentTexture(value) { + this._environmentTexture = value; + } + /** + * @returns all meshes, lights, cameras, transformNodes and bones + */ + getNodes() { + let nodes = []; + nodes = nodes.concat(this.meshes); + nodes = nodes.concat(this.lights); + nodes = nodes.concat(this.cameras); + nodes = nodes.concat(this.transformNodes); // dummies + this.skeletons.forEach((skeleton) => (nodes = nodes.concat(skeleton.bones))); + return nodes; + } +} +/** + * Set of assets to keep when moving a scene into an asset container. + */ +class KeepAssets extends AbstractAssetContainer { +} +/** + * Class used to store the output of the AssetContainer.instantiateAllMeshesToScene function + */ +class InstantiatedEntries { + constructor() { + /** + * List of new root nodes (eg. nodes with no parent) + */ + this.rootNodes = []; + /** + * List of new skeletons + */ + this.skeletons = []; + /** + * List of new animation groups + */ + this.animationGroups = []; + } + /** + * Disposes the instantiated entries from the scene + */ + dispose() { + this.rootNodes.slice(0).forEach((o) => { + o.dispose(); + }); + this.rootNodes.length = 0; + this.skeletons.slice(0).forEach((o) => { + o.dispose(); + }); + this.skeletons.length = 0; + this.animationGroups.slice(0).forEach((o) => { + o.dispose(); + }); + this.animationGroups.length = 0; + } +} +/** + * Container with a set of assets that can be added or removed from a scene. + */ +class AssetContainer extends AbstractAssetContainer { + /** + * Instantiates an AssetContainer. + * @param scene The scene the AssetContainer belongs to. + */ + constructor(scene) { + super(); + this._wasAddedToScene = false; + scene = scene || EngineStore.LastCreatedScene; + if (!scene) { + return; + } + this.scene = scene; + this["proceduralTextures"] = []; + scene.onDisposeObservable.add(() => { + if (!this._wasAddedToScene) { + this.dispose(); + } + }); + this._onContextRestoredObserver = scene.getEngine().onContextRestoredObservable.add(() => { + for (const geometry of this.geometries) { + geometry._rebuild(); + } + for (const mesh of this.meshes) { + mesh._rebuild(); + } + for (const system of this.particleSystems) { + system.rebuild(); + } + for (const texture of this.textures) { + texture._rebuild(); + } + }); + } + /** + * Given a list of nodes, return a topological sorting of them. + * @param nodes + * @returns a sorted array of nodes + */ + _topologicalSort(nodes) { + const nodesUidMap = new Map(); + for (const node of nodes) { + nodesUidMap.set(node.uniqueId, node); + } + const dependencyGraph = { + dependsOn: new Map(), // given a node id, what are the ids of the nodes it depends on + dependedBy: new Map(), // given a node id, what are the ids of the nodes that depend on it + }; + // Build the dependency graph given the list of nodes + // First pass: Initialize the empty dependency graph + for (const node of nodes) { + const nodeId = node.uniqueId; + dependencyGraph.dependsOn.set(nodeId, new Set()); + dependencyGraph.dependedBy.set(nodeId, new Set()); + } + // Second pass: Populate the dependency graph. We assume that we + // don't need to check for cycles here, as the scene graph cannot + // contain cycles. Our graph also already contains all transitive + // dependencies because getDescendants returns the transitive + // dependencies by default. + for (const node of nodes) { + const nodeId = node.uniqueId; + const dependsOn = dependencyGraph.dependsOn.get(nodeId); + if (node instanceof InstancedMesh) { + const masterMesh = node.sourceMesh; + if (nodesUidMap.has(masterMesh.uniqueId)) { + dependsOn.add(masterMesh.uniqueId); + dependencyGraph.dependedBy.get(masterMesh.uniqueId).add(nodeId); + } + } + const dependedBy = dependencyGraph.dependedBy.get(nodeId); + for (const child of node.getDescendants()) { + const childId = child.uniqueId; + if (nodesUidMap.has(childId)) { + dependedBy.add(childId); + const childDependsOn = dependencyGraph.dependsOn.get(childId); + childDependsOn.add(nodeId); + } + } + } + // Third pass: Topological sort + const sortedNodes = []; + // First: Find all nodes that have no dependencies + const leaves = []; + for (const node of nodes) { + const nodeId = node.uniqueId; + if (dependencyGraph.dependsOn.get(nodeId).size === 0) { + leaves.push(node); + nodesUidMap.delete(nodeId); + } + } + const visitList = leaves; + while (visitList.length > 0) { + const nodeToVisit = visitList.shift(); + sortedNodes.push(nodeToVisit); + // Remove the node from the dependency graph + // When a node is visited, we know that dependsOn is empty. + // So we only need to remove the node from dependedBy. + const dependedByVisitedNode = dependencyGraph.dependedBy.get(nodeToVisit.uniqueId); + // Array.from(x.values()) is to make the TS compiler happy + for (const dependedByVisitedNodeId of Array.from(dependedByVisitedNode.values())) { + const dependsOnDependedByVisitedNode = dependencyGraph.dependsOn.get(dependedByVisitedNodeId); + dependsOnDependedByVisitedNode.delete(nodeToVisit.uniqueId); + if (dependsOnDependedByVisitedNode.size === 0 && nodesUidMap.get(dependedByVisitedNodeId)) { + visitList.push(nodesUidMap.get(dependedByVisitedNodeId)); + nodesUidMap.delete(dependedByVisitedNodeId); + } + } + } + if (nodesUidMap.size > 0) { + Logger.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"); + nodesUidMap.forEach((node) => Logger.Error(node.name)); + } + return sortedNodes; + } + _addNodeAndDescendantsToList(list, addedIds, rootNode, predicate) { + if (!rootNode || (predicate && !predicate(rootNode)) || addedIds.has(rootNode.uniqueId)) { + return; + } + list.push(rootNode); + addedIds.add(rootNode.uniqueId); + for (const child of rootNode.getDescendants(true)) { + this._addNodeAndDescendantsToList(list, addedIds, child, predicate); + } + } + /** + * Check if a specific node is contained in this asset container. + * @param node the node to check + * @returns true if the node is contained in this container, otherwise false. + */ + _isNodeInContainer(node) { + if (node instanceof AbstractMesh && this.meshes.indexOf(node) !== -1) { + return true; + } + if (node instanceof TransformNode && this.transformNodes.indexOf(node) !== -1) { + return true; + } + if (node instanceof Light && this.lights.indexOf(node) !== -1) { + return true; + } + if (node instanceof Camera && this.cameras.indexOf(node) !== -1) { + return true; + } + return false; + } + /** + * For every node in the scene, check if its parent node is also in the scene. + * @returns true if every node's parent is also in the scene, otherwise false. + */ + _isValidHierarchy() { + for (const node of this.meshes) { + if (node.parent && !this._isNodeInContainer(node.parent)) { + Logger.Warn(`Node ${node.name} has a parent that is not in the container.`); + return false; + } + } + for (const node of this.transformNodes) { + if (node.parent && !this._isNodeInContainer(node.parent)) { + Logger.Warn(`Node ${node.name} has a parent that is not in the container.`); + return false; + } + } + for (const node of this.lights) { + if (node.parent && !this._isNodeInContainer(node.parent)) { + Logger.Warn(`Node ${node.name} has a parent that is not in the container.`); + return false; + } + } + for (const node of this.cameras) { + if (node.parent && !this._isNodeInContainer(node.parent)) { + Logger.Warn(`Node ${node.name} has a parent that is not in the container.`); + return false; + } + } + return true; + } + /** + * Instantiate or clone all meshes and add the new ones to the scene. + * Skeletons and animation groups will all be cloned + * @param nameFunction defines an optional function used to get new names for clones + * @param cloneMaterials defines an optional boolean that defines if materials must be cloned as well (false by default) + * @param options defines an optional list of options to control how to instantiate / clone models + * @param options.doNotInstantiate defines if the model must be instantiated or just cloned + * @param options.predicate defines a predicate used to filter whih mesh to instantiate/clone + * @returns a list of rootNodes, skeletons and animation groups that were duplicated + */ + instantiateModelsToScene(nameFunction, cloneMaterials = false, options) { + if (!this._isValidHierarchy()) { + Tools.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid."); + } + const conversionMap = {}; + const storeMap = {}; + const result = new InstantiatedEntries(); + const alreadySwappedSkeletons = []; + const alreadySwappedMaterials = []; + const localOptions = { + doNotInstantiate: true, + ...options, + }; + const onClone = (source, clone) => { + conversionMap[source.uniqueId] = clone.uniqueId; + storeMap[clone.uniqueId] = clone; + if (nameFunction) { + clone.name = nameFunction(source.name); + } + if (clone instanceof Mesh) { + const clonedMesh = clone; + if (clonedMesh.morphTargetManager) { + const oldMorphTargetManager = source.morphTargetManager; + clonedMesh.morphTargetManager = oldMorphTargetManager.clone(); + for (let index = 0; index < oldMorphTargetManager.numTargets; index++) { + const oldTarget = oldMorphTargetManager.getTarget(index); + const newTarget = clonedMesh.morphTargetManager.getTarget(index); + conversionMap[oldTarget.uniqueId] = newTarget.uniqueId; + storeMap[newTarget.uniqueId] = newTarget; + } + } + } + }; + const nodesToSort = []; + const idsOnSortList = new Set(); + for (const transformNode of this.transformNodes) { + if (transformNode.parent === null) { + this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, transformNode, localOptions.predicate); + } + } + for (const mesh of this.meshes) { + if (mesh.parent === null) { + this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, mesh, localOptions.predicate); + } + } + // Topologically sort nodes by parenting/instancing relationships so that all resources are in place + // when a given node is instantiated. + const sortedNodes = this._topologicalSort(nodesToSort); + const onNewCreated = (source, clone) => { + onClone(source, clone); + if (source.parent) { + const replicatedParentId = conversionMap[source.parent.uniqueId]; + const replicatedParent = storeMap[replicatedParentId]; + if (replicatedParent) { + clone.parent = replicatedParent; + } + else { + clone.parent = source.parent; + } + } + if (clone.position && source.position) { + clone.position.copyFrom(source.position); + } + if (clone.rotationQuaternion && source.rotationQuaternion) { + clone.rotationQuaternion.copyFrom(source.rotationQuaternion); + } + if (clone.rotation && source.rotation) { + clone.rotation.copyFrom(source.rotation); + } + if (clone.scaling && source.scaling) { + clone.scaling.copyFrom(source.scaling); + } + if (clone.material) { + const mesh = clone; + if (mesh.material) { + if (cloneMaterials) { + const sourceMaterial = source.material; + if (alreadySwappedMaterials.indexOf(sourceMaterial) === -1) { + let swap = sourceMaterial.clone(nameFunction ? nameFunction(sourceMaterial.name) : "Clone of " + sourceMaterial.name); + alreadySwappedMaterials.push(sourceMaterial); + conversionMap[sourceMaterial.uniqueId] = swap.uniqueId; + storeMap[swap.uniqueId] = swap; + if (sourceMaterial.getClassName() === "MultiMaterial") { + const multi = sourceMaterial; + for (const material of multi.subMaterials) { + if (!material) { + continue; + } + swap = material.clone(nameFunction ? nameFunction(material.name) : "Clone of " + material.name); + alreadySwappedMaterials.push(material); + conversionMap[material.uniqueId] = swap.uniqueId; + storeMap[swap.uniqueId] = swap; + } + multi.subMaterials = multi.subMaterials.map((m) => m && storeMap[conversionMap[m.uniqueId]]); + } + } + if (mesh.getClassName() !== "InstancedMesh") { + mesh.material = storeMap[conversionMap[sourceMaterial.uniqueId]]; + } + } + else { + if (mesh.material.getClassName() === "MultiMaterial") { + if (this.scene.multiMaterials.indexOf(mesh.material) === -1) { + this.scene.addMultiMaterial(mesh.material); + } + } + else { + if (this.scene.materials.indexOf(mesh.material) === -1) { + this.scene.addMaterial(mesh.material); + } + } + } + } + } + if (clone.parent === null) { + result.rootNodes.push(clone); + } + }; + sortedNodes.forEach((node) => { + if (node.getClassName() === "InstancedMesh") { + const instancedNode = node; + const sourceMesh = instancedNode.sourceMesh; + const replicatedSourceId = conversionMap[sourceMesh.uniqueId]; + const replicatedSource = typeof replicatedSourceId === "number" ? storeMap[replicatedSourceId] : sourceMesh; + const replicatedInstancedNode = replicatedSource.createInstance(instancedNode.name); + onNewCreated(instancedNode, replicatedInstancedNode); + } + else { + // Mesh or TransformNode + let canInstance = true; + if (node.getClassName() === "TransformNode" || + node.getClassName() === "Node" || + node.skeleton || + !node.getTotalVertices || + node.getTotalVertices() === 0) { + // Transform nodes, skinned meshes, and meshes with no vertices can never be instanced! + canInstance = false; + } + else if (localOptions.doNotInstantiate) { + if (typeof localOptions.doNotInstantiate === "function") { + canInstance = !localOptions.doNotInstantiate(node); + } + else { + canInstance = !localOptions.doNotInstantiate; + } + } + const replicatedNode = canInstance ? node.createInstance(`instance of ${node.name}`) : node.clone(`Clone of ${node.name}`, null, true); + if (!replicatedNode) { + throw new Error(`Could not clone or instantiate node on Asset Container ${node.name}`); + } + onNewCreated(node, replicatedNode); + } + }); + this.skeletons.forEach((s) => { + if (localOptions.predicate && !localOptions.predicate(s)) { + return; + } + const clone = s.clone(nameFunction ? nameFunction(s.name) : "Clone of " + s.name); + for (const m of this.meshes) { + if (m.skeleton === s && !m.isAnInstance) { + const copy = storeMap[conversionMap[m.uniqueId]]; + if (!copy || copy.isAnInstance) { + continue; + } + copy.skeleton = clone; + if (alreadySwappedSkeletons.indexOf(clone) !== -1) { + continue; + } + alreadySwappedSkeletons.push(clone); + // Check if bones are mesh linked + for (const bone of clone.bones) { + if (bone._linkedTransformNode) { + bone._linkedTransformNode = storeMap[conversionMap[bone._linkedTransformNode.uniqueId]]; + } + } + } + } + result.skeletons.push(clone); + }); + this.animationGroups.forEach((o) => { + if (localOptions.predicate && !localOptions.predicate(o)) { + return; + } + const clone = o.clone(nameFunction ? nameFunction(o.name) : "Clone of " + o.name, (oldTarget) => { + const newTarget = storeMap[conversionMap[oldTarget.uniqueId]]; + return newTarget || oldTarget; + }); + result.animationGroups.push(clone); + }); + return result; + } + /** + * Adds all the assets from the container to the scene. + */ + addAllToScene() { + if (this._wasAddedToScene) { + return; + } + if (!this._isValidHierarchy()) { + Tools.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."); + } + this._wasAddedToScene = true; + this.addToScene(null); + if (this.environmentTexture) { + this.scene.environmentTexture = this.environmentTexture; + } + for (const component of this.scene._serializableComponents) { + component.addFromContainer(this); + } + this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver); + this._onContextRestoredObserver = null; + } + /** + * Adds assets from the container to the scene. + * @param predicate defines a predicate used to select which entity will be added (can be null) + */ + addToScene(predicate = null) { + const addedNodes = []; + this.cameras.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addCamera(o); + addedNodes.push(o); + }); + this.lights.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addLight(o); + addedNodes.push(o); + }); + this.meshes.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addMesh(o); + addedNodes.push(o); + }); + this.skeletons.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addSkeleton(o); + }); + this.animations.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addAnimation(o); + }); + this.animationGroups.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addAnimationGroup(o); + }); + this.multiMaterials.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addMultiMaterial(o); + }); + this.materials.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addMaterial(o); + }); + this.morphTargetManagers.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addMorphTargetManager(o); + }); + this.geometries.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addGeometry(o); + }); + this.transformNodes.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addTransformNode(o); + addedNodes.push(o); + }); + this.actionManagers.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addActionManager(o); + }); + this.textures.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addTexture(o); + }); + this.reflectionProbes.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.addReflectionProbe(o); + }); + for (const addedNode of addedNodes) { + // If node was added to the scene, but parent is not in the scene, break the relationship + if (addedNode.parent && this.scene.getNodes().indexOf(addedNode.parent) === -1) { + // Use setParent to keep transform if possible + if (addedNode.setParent) { + addedNode.setParent(null); + } + else { + addedNode.parent = null; + } + } + } + } + /** + * Removes all the assets in the container from the scene + */ + removeAllFromScene() { + if (!this._isValidHierarchy()) { + Tools.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."); + } + this._wasAddedToScene = false; + this.removeFromScene(null); + if (this.environmentTexture === this.scene.environmentTexture) { + this.scene.environmentTexture = null; + } + for (const component of this.scene._serializableComponents) { + component.removeFromContainer(this); + } + } + /** + * Removes assets in the container from the scene + * @param predicate defines a predicate used to select which entity will be added (can be null) + */ + removeFromScene(predicate = null) { + this.cameras.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeCamera(o); + }); + this.lights.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeLight(o); + }); + this.meshes.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeMesh(o, true); + }); + this.skeletons.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeSkeleton(o); + }); + this.animations.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeAnimation(o); + }); + this.animationGroups.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeAnimationGroup(o); + }); + this.multiMaterials.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeMultiMaterial(o); + }); + this.materials.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeMaterial(o); + }); + this.morphTargetManagers.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeMorphTargetManager(o); + }); + this.geometries.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeGeometry(o); + }); + this.transformNodes.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeTransformNode(o); + }); + this.actionManagers.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeActionManager(o); + }); + this.textures.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeTexture(o); + }); + this.reflectionProbes.forEach((o) => { + if (predicate && !predicate(o)) { + return; + } + this.scene.removeReflectionProbe(o); + }); + } + /** + * Disposes all the assets in the container + */ + dispose() { + this.cameras.slice(0).forEach((o) => { + o.dispose(); + }); + this.cameras.length = 0; + this.lights.slice(0).forEach((o) => { + o.dispose(); + }); + this.lights.length = 0; + this.meshes.slice(0).forEach((o) => { + o.dispose(); + }); + this.meshes.length = 0; + this.skeletons.slice(0).forEach((o) => { + o.dispose(); + }); + this.skeletons.length = 0; + this.animationGroups.slice(0).forEach((o) => { + o.dispose(); + }); + this.animationGroups.length = 0; + this.multiMaterials.slice(0).forEach((o) => { + o.dispose(); + }); + this.multiMaterials.length = 0; + this.materials.slice(0).forEach((o) => { + o.dispose(); + }); + this.materials.length = 0; + this.geometries.slice(0).forEach((o) => { + o.dispose(); + }); + this.geometries.length = 0; + this.transformNodes.slice(0).forEach((o) => { + o.dispose(); + }); + this.transformNodes.length = 0; + this.actionManagers.slice(0).forEach((o) => { + o.dispose(); + }); + this.actionManagers.length = 0; + this.textures.slice(0).forEach((o) => { + o.dispose(); + }); + this.textures.length = 0; + this.reflectionProbes.slice(0).forEach((o) => { + o.dispose(); + }); + this.reflectionProbes.length = 0; + this.morphTargetManagers.slice(0).forEach((o) => { + o.dispose(); + }); + this.morphTargetManagers.length = 0; + if (this.environmentTexture) { + this.environmentTexture.dispose(); + this.environmentTexture = null; + } + for (const component of this.scene._serializableComponents) { + component.removeFromContainer(this, true); + } + if (this._onContextRestoredObserver) { + this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver); + this._onContextRestoredObserver = null; + } + } + _moveAssets(sourceAssets, targetAssets, keepAssets) { + if (!sourceAssets || !targetAssets) { + return; + } + for (const asset of sourceAssets) { + let move = true; + if (keepAssets) { + for (const keepAsset of keepAssets) { + if (asset === keepAsset) { + move = false; + break; + } + } + } + if (move) { + targetAssets.push(asset); + asset._parentContainer = this; + } + } + } + /** + * Removes all the assets contained in the scene and adds them to the container. + * @param keepAssets Set of assets to keep in the scene. (default: empty) + */ + moveAllFromScene(keepAssets) { + this._wasAddedToScene = false; + if (keepAssets === undefined) { + keepAssets = new KeepAssets(); + } + for (const key in this) { + if (Object.prototype.hasOwnProperty.call(this, key)) { + this[key] = this[key] || (key === "_environmentTexture" ? null : []); + this._moveAssets(this.scene[key], this[key], keepAssets[key]); + } + } + this.environmentTexture = this.scene.environmentTexture; + this.removeAllFromScene(); + } + /** + * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer. + * @returns the root mesh + */ + createRootMesh() { + const rootMesh = new Mesh("assetContainerRootMesh", this.scene); + this.meshes.forEach((m) => { + if (!m.parent) { + rootMesh.addChild(m); + } + }); + this.meshes.unshift(rootMesh); + return rootMesh; + } + /** + * Merge animations (direct and animation groups) from this asset container into a scene + * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) + * @param animatables set of animatables to retarget to a node from the scene + * @param targetConverter defines a function used to convert animation targets from the asset container to the scene (default: search node by name) + * @returns an array of the new AnimationGroup added to the scene (empty array if none) + */ + mergeAnimationsTo(scene = EngineStore.LastCreatedScene, animatables, targetConverter = null) { + if (!scene) { + Logger.Error("No scene available to merge animations to"); + return []; + } + const _targetConverter = targetConverter + ? targetConverter + : (target) => { + let node = null; + const targetProperty = target.animations.length ? target.animations[0].targetProperty : ""; + /* + BabylonJS adds special naming to targets that are children of nodes. + This name attempts to remove that special naming to get the parent nodes name in case the target + can't be found in the node tree + + Ex: Torso_primitive0 likely points to a Mesh primitive. We take away primitive0 and are left with "Torso" which is the name + of the primitive's parent. + */ + const name = target.name.split(".").join("").split("_primitive")[0]; + switch (targetProperty) { + case "position": + case "rotationQuaternion": + node = scene.getTransformNodeByName(target.name) || scene.getTransformNodeByName(name); + break; + case "influence": + node = scene.getMorphTargetByName(target.name) || scene.getMorphTargetByName(name); + break; + default: + node = scene.getNodeByName(target.name) || scene.getNodeByName(name); + } + return node; + }; + // Copy new node animations + const nodesInAC = this.getNodes(); + nodesInAC.forEach((nodeInAC) => { + const nodeInScene = _targetConverter(nodeInAC); + if (nodeInScene !== null) { + // Remove old animations with same target property as a new one + for (const animationInAC of nodeInAC.animations) { + // Doing treatment on an array for safety measure + const animationsWithSameProperty = nodeInScene.animations.filter((animationInScene) => { + return animationInScene.targetProperty === animationInAC.targetProperty; + }); + for (const animationWithSameProperty of animationsWithSameProperty) { + const index = nodeInScene.animations.indexOf(animationWithSameProperty, 0); + if (index > -1) { + nodeInScene.animations.splice(index, 1); + } + } + } + // Append new animations + nodeInScene.animations = nodeInScene.animations.concat(nodeInAC.animations); + } + }); + const newAnimationGroups = []; + // Copy new animation groups + this.animationGroups.slice().forEach((animationGroupInAC) => { + // Clone the animation group and all its animatables + newAnimationGroups.push(animationGroupInAC.clone(animationGroupInAC.name, _targetConverter)); + // Remove animatables related to the asset container + animationGroupInAC.animatables.forEach((animatable) => { + animatable.stop(); + }); + }); + // Retarget animatables + animatables.forEach((animatable) => { + const target = _targetConverter(animatable.target); + if (target) { + // Clone the animatable and retarget it + scene.beginAnimation(target, animatable.fromFrame, animatable.toFrame, animatable.loopAnimation, animatable.speedRatio, animatable.onAnimationEnd ? animatable.onAnimationEnd : undefined, undefined, true, undefined, animatable.onAnimationLoop ? animatable.onAnimationLoop : undefined); + // Stop animation for the target in the asset container + scene.stopAnimation(animatable.target); + } + }); + return newAnimationGroups; + } + /** + * @since 6.15.0 + * This method checks for any node that has no parent + * and is not in the rootNodes array, and adds the node + * there, if so. + */ + populateRootNodes() { + this.rootNodes.length = 0; + this.meshes.forEach((m) => { + if (!m.parent && this.rootNodes.indexOf(m) === -1) { + this.rootNodes.push(m); + } + }); + this.transformNodes.forEach((t) => { + if (!t.parent && this.rootNodes.indexOf(t) === -1) { + this.rootNodes.push(t); + } + }); + this.lights.forEach((l) => { + if (!l.parent && this.rootNodes.indexOf(l) === -1) { + this.rootNodes.push(l); + } + }); + this.cameras.forEach((c) => { + if (!c.parent && this.rootNodes.indexOf(c) === -1) { + this.rootNodes.push(c); + } + }); + } + /** + * @since 6.26.0 + * Given a root asset, this method will traverse its hierarchy and add it, its children and any materials/skeletons/animation groups to the container. + * @param root root node + */ + addAllAssetsToContainer(root) { + if (!root) { + return; + } + const nodesToVisit = []; + const visitedNodes = new Set(); + nodesToVisit.push(root); + while (nodesToVisit.length > 0) { + const nodeToVisit = nodesToVisit.pop(); + if (nodeToVisit instanceof Mesh) { + if (nodeToVisit.geometry && this.geometries.indexOf(nodeToVisit.geometry) === -1) { + this.geometries.push(nodeToVisit.geometry); + } + this.meshes.push(nodeToVisit); + } + else if (nodeToVisit instanceof TransformNode) { + this.transformNodes.push(nodeToVisit); + } + else if (nodeToVisit instanceof Light) { + this.lights.push(nodeToVisit); + } + else if (nodeToVisit instanceof Camera) { + this.cameras.push(nodeToVisit); + } + if (nodeToVisit instanceof AbstractMesh) { + if (nodeToVisit.material && this.materials.indexOf(nodeToVisit.material) === -1) { + this.materials.push(nodeToVisit.material); + for (const texture of nodeToVisit.material.getActiveTextures()) { + if (this.textures.indexOf(texture) === -1) { + this.textures.push(texture); + } + } + } + if (nodeToVisit.skeleton && this.skeletons.indexOf(nodeToVisit.skeleton) === -1) { + this.skeletons.push(nodeToVisit.skeleton); + } + if (nodeToVisit.morphTargetManager && this.morphTargetManagers.indexOf(nodeToVisit.morphTargetManager) === -1) { + this.morphTargetManagers.push(nodeToVisit.morphTargetManager); + } + } + for (const child of nodeToVisit.getChildren()) { + if (!visitedNodes.has(child)) { + nodesToVisit.push(child); + } + } + visitedNodes.add(nodeToVisit); + } + this.populateRootNodes(); + } + /** + * Get from a list of objects by tags + * @param list the list of objects to use + * @param tagsQuery the query to use + * @param filter a predicate to filter for tags + * @returns + */ + _getByTags(list, tagsQuery, filter) { + if (tagsQuery === undefined) { + // returns the complete list (could be done with Tags.MatchesQuery but no need to have a for-loop here) + return list; + } + const listByTags = []; + for (const i in list) { + const item = list[i]; + if (Tags && Tags.MatchesQuery(item, tagsQuery) && (!filter || filter(item))) { + listByTags.push(item); + } + } + return listByTags; + } + /** + * Get a list of meshes by tags + * @param tagsQuery defines the tags query to use + * @param filter defines a predicate used to filter results + * @returns an array of Mesh + */ + getMeshesByTags(tagsQuery, filter) { + return this._getByTags(this.meshes, tagsQuery, filter); + } + /** + * Get a list of cameras by tags + * @param tagsQuery defines the tags query to use + * @param filter defines a predicate used to filter results + * @returns an array of Camera + */ + getCamerasByTags(tagsQuery, filter) { + return this._getByTags(this.cameras, tagsQuery, filter); + } + /** + * Get a list of lights by tags + * @param tagsQuery defines the tags query to use + * @param filter defines a predicate used to filter results + * @returns an array of Light + */ + getLightsByTags(tagsQuery, filter) { + return this._getByTags(this.lights, tagsQuery, filter); + } + /** + * Get a list of materials by tags + * @param tagsQuery defines the tags query to use + * @param filter defines a predicate used to filter results + * @returns an array of Material + */ + getMaterialsByTags(tagsQuery, filter) { + return this._getByTags(this.materials, tagsQuery, filter).concat(this._getByTags(this.multiMaterials, tagsQuery, filter)); + } + /** + * Get a list of transform nodes by tags + * @param tagsQuery defines the tags query to use + * @param filter defines a predicate used to filter results + * @returns an array of TransformNode + */ + getTransformNodesByTags(tagsQuery, filter) { + return this._getByTags(this.transformNodes, tagsQuery, filter); + } +} + +/** + * Utility class for reading from a data buffer + */ +class DataReader { + /** + * Constructor + * @param buffer The buffer to read + */ + constructor(buffer) { + /** + * The current byte offset from the beginning of the data buffer. + */ + this.byteOffset = 0; + this.buffer = buffer; + } + /** + * Loads the given byte length. + * @param byteLength The byte length to load + * @returns A promise that resolves when the load is complete + */ + loadAsync(byteLength) { + return this.buffer.readAsync(this.byteOffset, byteLength).then((data) => { + this._dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); + this._dataByteOffset = 0; + }); + } + /** + * Read a unsigned 32-bit integer from the currently loaded data range. + * @returns The 32-bit integer read + */ + readUint32() { + const value = this._dataView.getUint32(this._dataByteOffset, true); + this._dataByteOffset += 4; + this.byteOffset += 4; + return value; + } + /** + * Read a byte array from the currently loaded data range. + * @param byteLength The byte length to read + * @returns The byte array read + */ + readUint8Array(byteLength) { + const value = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._dataByteOffset, byteLength); + this._dataByteOffset += byteLength; + this.byteOffset += byteLength; + return value; + } + /** + * Read a string from the currently loaded data range. + * @param byteLength The byte length to read + * @returns The string read + */ + readString(byteLength) { + return Decode(this.readUint8Array(byteLength)); + } + /** + * Skips the given byte length the currently loaded data range. + * @param byteLength The byte length to skip + */ + skipBytes(byteLength) { + this._dataByteOffset += byteLength; + this.byteOffset += byteLength; + } +} + +function validateAsync(data, rootUrl, fileName, getExternalResource) { + const options = { + externalResourceFunction: getExternalResource, + }; + if (fileName) { + options.uri = rootUrl === "file:" ? fileName : rootUrl + fileName; + } + return ArrayBuffer.isView(data) ? GLTFValidator.validateBytes(data, options) : GLTFValidator.validateString(data, options); +} +/** + * The worker function that gets converted to a blob url to pass into a worker. + */ +function workerFunc() { + const pendingExternalResources = []; + onmessage = (message) => { + const data = message.data; + switch (data.id) { + case "init": { + importScripts(data.url); + break; + } + case "validate": { + validateAsync(data.data, data.rootUrl, data.fileName, (uri) => new Promise((resolve, reject) => { + const index = pendingExternalResources.length; + pendingExternalResources.push({ resolve, reject }); + postMessage({ id: "getExternalResource", index: index, uri: uri }); + })).then((value) => { + postMessage({ id: "validate.resolve", value: value }); + }, (reason) => { + postMessage({ id: "validate.reject", reason: reason }); + }); + break; + } + case "getExternalResource.resolve": { + pendingExternalResources[data.index].resolve(data.value); + break; + } + case "getExternalResource.reject": { + pendingExternalResources[data.index].reject(data.reason); + break; + } + } + }; +} +/** + * glTF validation + */ +class GLTFValidation { + /** + * Validate a glTF asset using the glTF-Validator. + * @param data The JSON of a glTF or the array buffer of a binary glTF + * @param rootUrl The root url for the glTF + * @param fileName The file name for the glTF + * @param getExternalResource The callback to get external resources for the glTF validator + * @returns A promise that resolves with the glTF validation results once complete + */ + static ValidateAsync(data, rootUrl, fileName, getExternalResource) { + if (typeof Worker === "function") { + return new Promise((resolve, reject) => { + const workerContent = `${validateAsync}(${workerFunc})()`; + const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" })); + const worker = new Worker(workerBlobUrl); + const onError = (error) => { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + reject(error); + }; + const onMessage = (message) => { + const data = message.data; + switch (data.id) { + case "getExternalResource": { + getExternalResource(data.uri).then((value) => { + worker.postMessage({ id: "getExternalResource.resolve", index: data.index, value: value }, [value.buffer]); + }, (reason) => { + worker.postMessage({ id: "getExternalResource.reject", index: data.index, reason: reason }); + }); + break; + } + case "validate.resolve": { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + resolve(data.value); + worker.terminate(); + break; + } + case "validate.reject": { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + reject(data.reason); + worker.terminate(); + } + } + }; + worker.addEventListener("error", onError); + worker.addEventListener("message", onMessage); + worker.postMessage({ id: "init", url: Tools.GetBabylonScriptURL(this.Configuration.url) }); + if (ArrayBuffer.isView(data)) { + // Slice the data to avoid copying the whole array buffer. + const slicedData = data.slice(); + worker.postMessage({ id: "validate", data: slicedData, rootUrl: rootUrl, fileName: fileName }, [slicedData.buffer]); + } + else { + worker.postMessage({ id: "validate", data: data, rootUrl: rootUrl, fileName: fileName }); + } + }); + } + else { + if (!this._LoadScriptPromise) { + this._LoadScriptPromise = Tools.LoadBabylonScriptAsync(this.Configuration.url); + } + return this._LoadScriptPromise.then(() => { + return validateAsync(data, rootUrl, fileName, getExternalResource); + }); + } + } +} +/** + * The configuration. Defaults to `{ url: "https://cdn.babylonjs.com/gltf_validator.js" }`. + */ +GLTFValidation.Configuration = { + url: `${Tools._DefaultCdnUrl}/gltf_validator.js`, +}; + +const GLTFMagicBase64Encoded = "Z2xURg"; // "glTF" base64 encoded (without the quotes!) +const GLTFFileLoaderMetadata = { + name: "gltf", + extensions: { + // eslint-disable-next-line @typescript-eslint/naming-convention + ".gltf": { isBinary: false, mimeType: "model/gltf+json" }, + // eslint-disable-next-line @typescript-eslint/naming-convention + ".glb": { isBinary: true, mimeType: "model/gltf-binary" }, + }, + canDirectLoad(data) { + return ((data.indexOf("asset") !== -1 && data.indexOf("version") !== -1) || + data.startsWith("data:base64," + GLTFMagicBase64Encoded) || // this is technically incorrect, but will continue to support for backcompat. + data.startsWith("data:;base64," + GLTFMagicBase64Encoded) || + data.startsWith("data:application/octet-stream;base64," + GLTFMagicBase64Encoded) || + data.startsWith("data:model/gltf-binary;base64," + GLTFMagicBase64Encoded)); + }, +}; + +function readAsync(arrayBuffer, byteOffset, byteLength) { + try { + return Promise.resolve(new Uint8Array(arrayBuffer, byteOffset, byteLength)); + } + catch (e) { + return Promise.reject(e); + } +} +function readViewAsync(arrayBufferView, byteOffset, byteLength) { + try { + if (byteOffset < 0 || byteOffset >= arrayBufferView.byteLength) { + throw new RangeError("Offset is out of range."); + } + if (byteOffset + byteLength > arrayBufferView.byteLength) { + throw new RangeError("Length is out of range."); + } + return Promise.resolve(new Uint8Array(arrayBufferView.buffer, arrayBufferView.byteOffset + byteOffset, byteLength)); + } + catch (e) { + return Promise.reject(e); + } +} +/** + * Mode that determines the coordinate system to use. + */ +var GLTFLoaderCoordinateSystemMode; +(function (GLTFLoaderCoordinateSystemMode) { + /** + * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene. + */ + GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO"; + /** + * Sets the useRightHandedSystem flag on the scene. + */ + GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED"; +})(GLTFLoaderCoordinateSystemMode || (GLTFLoaderCoordinateSystemMode = {})); +/** + * Mode that determines what animations will start. + */ +var GLTFLoaderAnimationStartMode; +(function (GLTFLoaderAnimationStartMode) { + /** + * No animation will start. + */ + GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE"; + /** + * The first animation will start. + */ + GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST"; + /** + * All animations will start. + */ + GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL"; +})(GLTFLoaderAnimationStartMode || (GLTFLoaderAnimationStartMode = {})); +/** + * Loader state. + */ +var GLTFLoaderState; +(function (GLTFLoaderState) { + /** + * The asset is loading. + */ + GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING"; + /** + * The asset is ready for rendering. + */ + GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY"; + /** + * The asset is completely loaded. + */ + GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE"; +})(GLTFLoaderState || (GLTFLoaderState = {})); +class GLTFLoaderOptions { + constructor() { + // ---------- + // V2 options + // ---------- + /** + * The coordinate system mode. Defaults to AUTO. + */ + this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO; + /** + * The animation start mode. Defaults to FIRST. + */ + this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST; + /** + * Defines if the loader should load node animations. Defaults to true. + * NOTE: The animation of this node will still load if the node is also a joint of a skin and `loadSkins` is true. + */ + this.loadNodeAnimations = true; + /** + * Defines if the loader should load skins. Defaults to true. + */ + this.loadSkins = true; + /** + * Defines if the loader should load morph targets. Defaults to true. + */ + this.loadMorphTargets = true; + /** + * Defines if the loader should compile materials before raising the success callback. Defaults to false. + */ + this.compileMaterials = false; + /** + * Defines if the loader should also compile materials with clip planes. Defaults to false. + */ + this.useClipPlane = false; + /** + * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false. + */ + this.compileShadowGenerators = false; + /** + * Defines if the Alpha blended materials are only applied as coverage. + * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials. + * If true, no extra effects are applied to transparent pixels. + */ + this.transparencyAsCoverage = false; + /** + * Defines if the loader should use range requests when load binary glTF files from HTTP. + * Enabling will disable offline support and glTF validator. + * Defaults to false. + */ + this.useRangeRequests = false; + /** + * Defines if the loader should create instances when multiple glTF nodes point to the same glTF mesh. Defaults to true. + */ + this.createInstances = true; + /** + * Defines if the loader should always compute the bounding boxes of meshes and not use the min/max values from the position accessor. Defaults to false. + */ + this.alwaysComputeBoundingBox = false; + /** + * If true, load all materials defined in the file, even if not used by any mesh. Defaults to false. + */ + this.loadAllMaterials = false; + /** + * If true, load only the materials defined in the file. Defaults to false. + */ + this.loadOnlyMaterials = false; + /** + * If true, do not load any materials defined in the file. Defaults to false. + */ + this.skipMaterials = false; + /** + * If true, load the color (gamma encoded) textures into sRGB buffers (if supported by the GPU), which will yield more accurate results when sampling the texture. Defaults to true. + */ + this.useSRGBBuffers = true; + /** + * When loading glTF animations, which are defined in seconds, target them to this FPS. Defaults to 60. + */ + this.targetFps = 60; + /** + * Defines if the loader should always compute the nearest common ancestor of the skeleton joints instead of using `skin.skeleton`. Defaults to false. + * Set this to true if loading assets with invalid `skin.skeleton` values. + */ + this.alwaysComputeSkeletonRootNode = false; + /** + * If true, the loader will derive the name for Babylon textures from the glTF texture name, image name, or image url. Defaults to false. + * Note that it is possible for multiple Babylon textures to share the same name when the Babylon textures load from the same glTF texture or image. + */ + this.useGltfTextureNames = false; + /** + * Function called before loading a url referenced by the asset. + * @param url url referenced by the asset + * @returns Async url to load + */ + this.preprocessUrlAsync = (url) => Promise.resolve(url); + /** + * Defines options for glTF extensions. + */ + this.extensionOptions = {}; + } + // eslint-disable-next-line babylonjs/available + copyFrom(options) { + if (options) { + this.onParsed = options.onParsed; + this.coordinateSystemMode = options.coordinateSystemMode ?? this.coordinateSystemMode; + this.animationStartMode = options.animationStartMode ?? this.animationStartMode; + this.loadNodeAnimations = options.loadNodeAnimations ?? this.loadNodeAnimations; + this.loadSkins = options.loadSkins ?? this.loadSkins; + this.loadMorphTargets = options.loadMorphTargets ?? this.loadMorphTargets; + this.compileMaterials = options.compileMaterials ?? this.compileMaterials; + this.useClipPlane = options.useClipPlane ?? this.useClipPlane; + this.compileShadowGenerators = options.compileShadowGenerators ?? this.compileShadowGenerators; + this.transparencyAsCoverage = options.transparencyAsCoverage ?? this.transparencyAsCoverage; + this.useRangeRequests = options.useRangeRequests ?? this.useRangeRequests; + this.createInstances = options.createInstances ?? this.createInstances; + this.alwaysComputeBoundingBox = options.alwaysComputeBoundingBox ?? this.alwaysComputeBoundingBox; + this.loadAllMaterials = options.loadAllMaterials ?? this.loadAllMaterials; + this.loadOnlyMaterials = options.loadOnlyMaterials ?? this.loadOnlyMaterials; + this.skipMaterials = options.skipMaterials ?? this.skipMaterials; + this.useSRGBBuffers = options.useSRGBBuffers ?? this.useSRGBBuffers; + this.targetFps = options.targetFps ?? this.targetFps; + this.alwaysComputeSkeletonRootNode = options.alwaysComputeSkeletonRootNode ?? this.alwaysComputeSkeletonRootNode; + this.useGltfTextureNames = options.useGltfTextureNames ?? this.useGltfTextureNames; + this.preprocessUrlAsync = options.preprocessUrlAsync ?? this.preprocessUrlAsync; + this.customRootNode = options.customRootNode; + this.onMeshLoaded = options.onMeshLoaded; + this.onSkinLoaded = options.onSkinLoaded; + this.onTextureLoaded = options.onTextureLoaded; + this.onMaterialLoaded = options.onMaterialLoaded; + this.onCameraLoaded = options.onCameraLoaded; + this.extensionOptions = options.extensionOptions ?? this.extensionOptions; + } + } +} +/** + * File loader for loading glTF files into a scene. + */ +class GLTFFileLoader extends GLTFLoaderOptions { + /** + * Creates a new glTF file loader. + * @param options The options for the loader + */ + constructor(options) { + super(); + // -------------------- + // Begin Common options + // -------------------- + /** + * Raised when the asset has been parsed + */ + this.onParsedObservable = new Observable(); + // -------------- + // End V1 options + // -------------- + /** + * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh. + * Note that the observable is raised as soon as the mesh object is created, meaning some data may not have been setup yet for this mesh (vertex data, morph targets, material, ...) + */ + this.onMeshLoadedObservable = new Observable(); + /** + * Observable raised when the loader creates a skin after parsing the glTF properties of the skin node. + * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/glTF/glTFSkinning#ignoring-the-transform-of-the-skinned-mesh + * @param node - the transform node that corresponds to the original glTF skin node used for animations + * @param skinnedNode - the transform node that is the skinned mesh itself or the parent of the skinned meshes + */ + this.onSkinLoadedObservable = new Observable(); + /** + * Observable raised when the loader creates a texture after parsing the glTF properties of the texture. + */ + this.onTextureLoadedObservable = new Observable(); + /** + * Observable raised when the loader creates a material after parsing the glTF properties of the material. + */ + this.onMaterialLoadedObservable = new Observable(); + /** + * Observable raised when the loader creates a camera after parsing the glTF properties of the camera. + */ + this.onCameraLoadedObservable = new Observable(); + /** + * Observable raised when the asset is completely loaded, immediately before the loader is disposed. + * For assets with LODs, raised when all of the LODs are complete. + * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise. + */ + this.onCompleteObservable = new Observable(); + /** + * Observable raised when an error occurs. + */ + this.onErrorObservable = new Observable(); + /** + * Observable raised after the loader is disposed. + */ + this.onDisposeObservable = new Observable(); + /** + * Observable raised after a loader extension is created. + * Set additional options for a loader extension in this event. + */ + this.onExtensionLoadedObservable = new Observable(); + /** + * Defines if the loader should validate the asset. + */ + this.validate = false; + /** + * Observable raised after validation when validate is set to true. The event data is the result of the validation. + */ + this.onValidatedObservable = new Observable(); + this._loader = null; + this._state = null; + this._requests = new Array(); + /** + * Name of the loader ("gltf") + */ + this.name = GLTFFileLoaderMetadata.name; + /** @internal */ + this.extensions = GLTFFileLoaderMetadata.extensions; + /** + * Observable raised when the loader state changes. + */ + this.onLoaderStateChangedObservable = new Observable(); + this._logIndentLevel = 0; + this._loggingEnabled = false; + /** @internal */ + this._log = this._logDisabled; + this._capturePerformanceCounters = false; + /** @internal */ + this._startPerformanceCounter = this._startPerformanceCounterDisabled; + /** @internal */ + this._endPerformanceCounter = this._endPerformanceCounterDisabled; + this.copyFrom(options); + } + /** + * Raised when the asset has been parsed + */ + set onParsed(callback) { + if (this._onParsedObserver) { + this.onParsedObservable.remove(this._onParsedObserver); + } + if (callback) { + this._onParsedObserver = this.onParsedObservable.add(callback); + } + } + /** + * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh. + * Note that the callback is called as soon as the mesh object is created, meaning some data may not have been setup yet for this mesh (vertex data, morph targets, material, ...) + */ + set onMeshLoaded(callback) { + if (this._onMeshLoadedObserver) { + this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver); + } + if (callback) { + this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback); + } + } + /** + * Callback raised when the loader creates a skin after parsing the glTF properties of the skin node. + * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/glTF/glTFSkinning#ignoring-the-transform-of-the-skinned-mesh + */ + set onSkinLoaded(callback) { + if (this._onSkinLoadedObserver) { + this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver); + } + if (callback) { + this._onSkinLoadedObserver = this.onSkinLoadedObservable.add((data) => callback(data.node, data.skinnedNode)); + } + } + /** + * Callback raised when the loader creates a texture after parsing the glTF properties of the texture. + */ + set onTextureLoaded(callback) { + if (this._onTextureLoadedObserver) { + this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver); + } + if (callback) { + this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback); + } + } + /** + * Callback raised when the loader creates a material after parsing the glTF properties of the material. + */ + set onMaterialLoaded(callback) { + if (this._onMaterialLoadedObserver) { + this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver); + } + if (callback) { + this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback); + } + } + /** + * Callback raised when the loader creates a camera after parsing the glTF properties of the camera. + */ + set onCameraLoaded(callback) { + if (this._onCameraLoadedObserver) { + this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver); + } + if (callback) { + this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback); + } + } + /** + * Callback raised when the asset is completely loaded, immediately before the loader is disposed. + * For assets with LODs, raised when all of the LODs are complete. + * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise. + */ + set onComplete(callback) { + if (this._onCompleteObserver) { + this.onCompleteObservable.remove(this._onCompleteObserver); + } + this._onCompleteObserver = this.onCompleteObservable.add(callback); + } + /** + * Callback raised when an error occurs. + */ + set onError(callback) { + if (this._onErrorObserver) { + this.onErrorObservable.remove(this._onErrorObserver); + } + this._onErrorObserver = this.onErrorObservable.add(callback); + } + /** + * Callback raised after the loader is disposed. + */ + set onDispose(callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + } + /** + * Callback raised after a loader extension is created. + */ + set onExtensionLoaded(callback) { + if (this._onExtensionLoadedObserver) { + this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver); + } + this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback); + } + /** + * Defines if the loader logging is enabled. + */ + get loggingEnabled() { + return this._loggingEnabled; + } + set loggingEnabled(value) { + if (this._loggingEnabled === value) { + return; + } + this._loggingEnabled = value; + if (this._loggingEnabled) { + this._log = this._logEnabled; + } + else { + this._log = this._logDisabled; + } + } + /** + * Defines if the loader should capture performance counters. + */ + get capturePerformanceCounters() { + return this._capturePerformanceCounters; + } + set capturePerformanceCounters(value) { + if (this._capturePerformanceCounters === value) { + return; + } + this._capturePerformanceCounters = value; + if (this._capturePerformanceCounters) { + this._startPerformanceCounter = this._startPerformanceCounterEnabled; + this._endPerformanceCounter = this._endPerformanceCounterEnabled; + } + else { + this._startPerformanceCounter = this._startPerformanceCounterDisabled; + this._endPerformanceCounter = this._endPerformanceCounterDisabled; + } + } + /** + * Callback raised after a loader extension is created. + */ + set onValidated(callback) { + if (this._onValidatedObserver) { + this.onValidatedObservable.remove(this._onValidatedObserver); + } + this._onValidatedObserver = this.onValidatedObservable.add(callback); + } + /** + * Disposes the loader, releases resources during load, and cancels any outstanding requests. + */ + dispose() { + if (this._loader) { + this._loader.dispose(); + this._loader = null; + } + for (const request of this._requests) { + request.abort(); + } + this._requests.length = 0; + delete this._progressCallback; + this.preprocessUrlAsync = (url) => Promise.resolve(url); + this.onMeshLoadedObservable.clear(); + this.onSkinLoadedObservable.clear(); + this.onTextureLoadedObservable.clear(); + this.onMaterialLoadedObservable.clear(); + this.onCameraLoadedObservable.clear(); + this.onCompleteObservable.clear(); + this.onExtensionLoadedObservable.clear(); + this.onDisposeObservable.notifyObservers(undefined); + this.onDisposeObservable.clear(); + } + /** + * @internal + */ + loadFile(scene, fileOrUrl, rootUrl, onSuccess, onProgress, useArrayBuffer, onError, name) { + if (ArrayBuffer.isView(fileOrUrl)) { + this._loadBinary(scene, fileOrUrl, rootUrl, onSuccess, onError, name); + return null; + } + this._progressCallback = onProgress; + const fileName = fileOrUrl.name || Tools.GetFilename(fileOrUrl); + if (useArrayBuffer) { + if (this.useRangeRequests) { + if (this.validate) { + Logger.Warn("glTF validation is not supported when range requests are enabled"); + } + const fileRequest = { + abort: () => { }, + onCompleteObservable: new Observable(), + }; + const dataBuffer = { + readAsync: (byteOffset, byteLength) => { + return new Promise((resolve, reject) => { + this._loadFile(scene, fileOrUrl, (data) => { + resolve(new Uint8Array(data)); + }, true, (error) => { + reject(error); + }, (webRequest) => { + webRequest.setRequestHeader("Range", `bytes=${byteOffset}-${byteOffset + byteLength - 1}`); + }); + }); + }, + byteLength: 0, + }; + this._unpackBinaryAsync(new DataReader(dataBuffer)).then((loaderData) => { + fileRequest.onCompleteObservable.notifyObservers(fileRequest); + onSuccess(loaderData); + }, onError ? (error) => onError(undefined, error) : undefined); + return fileRequest; + } + return this._loadFile(scene, fileOrUrl, (data) => { + this._validate(scene, new Uint8Array(data, 0, data.byteLength), rootUrl, fileName); + this._unpackBinaryAsync(new DataReader({ + readAsync: (byteOffset, byteLength) => readAsync(data, byteOffset, byteLength), + byteLength: data.byteLength, + })).then((loaderData) => { + onSuccess(loaderData); + }, onError ? (error) => onError(undefined, error) : undefined); + }, true, onError); + } + else { + return this._loadFile(scene, fileOrUrl, (data) => { + try { + this._validate(scene, data, rootUrl, fileName); + onSuccess({ json: this._parseJson(data) }); + } + catch { + if (onError) { + onError(); + } + } + }, false, onError); + } + } + _loadBinary(scene, data, rootUrl, onSuccess, onError, fileName) { + this._validate(scene, new Uint8Array(data.buffer, data.byteOffset, data.byteLength), rootUrl, fileName); + this._unpackBinaryAsync(new DataReader({ + readAsync: (byteOffset, byteLength) => readViewAsync(data, byteOffset, byteLength), + byteLength: data.byteLength, + })).then((loaderData) => { + onSuccess(loaderData); + }, onError ? (error) => onError(undefined, error) : undefined); + } + /** + * @internal + */ + importMeshAsync(meshesNames, scene, data, rootUrl, onProgress, fileName) { + return Promise.resolve().then(() => { + this.onParsedObservable.notifyObservers(data); + this.onParsedObservable.clear(); + this._log(`Loading ${fileName || ""}`); + this._loader = this._getLoader(data); + return this._loader.importMeshAsync(meshesNames, scene, null, data, rootUrl, onProgress, fileName); + }); + } + /** + * @internal + */ + loadAsync(scene, data, rootUrl, onProgress, fileName) { + return Promise.resolve().then(() => { + this.onParsedObservable.notifyObservers(data); + this.onParsedObservable.clear(); + this._log(`Loading ${fileName || ""}`); + this._loader = this._getLoader(data); + return this._loader.loadAsync(scene, data, rootUrl, onProgress, fileName); + }); + } + /** + * @internal + */ + loadAssetContainerAsync(scene, data, rootUrl, onProgress, fileName) { + return Promise.resolve().then(() => { + this.onParsedObservable.notifyObservers(data); + this.onParsedObservable.clear(); + this._log(`Loading ${fileName || ""}`); + this._loader = this._getLoader(data); + // Prepare the asset container. + const container = new AssetContainer(scene); + // Get materials/textures when loading to add to container + const materials = []; + this.onMaterialLoadedObservable.add((material) => { + materials.push(material); + }); + const textures = []; + this.onTextureLoadedObservable.add((texture) => { + textures.push(texture); + }); + const cameras = []; + this.onCameraLoadedObservable.add((camera) => { + cameras.push(camera); + }); + const morphTargetManagers = []; + this.onMeshLoadedObservable.add((mesh) => { + if (mesh.morphTargetManager) { + morphTargetManagers.push(mesh.morphTargetManager); + } + }); + return this._loader.importMeshAsync(null, scene, container, data, rootUrl, onProgress, fileName).then((result) => { + Array.prototype.push.apply(container.geometries, result.geometries); + Array.prototype.push.apply(container.meshes, result.meshes); + Array.prototype.push.apply(container.particleSystems, result.particleSystems); + Array.prototype.push.apply(container.skeletons, result.skeletons); + Array.prototype.push.apply(container.animationGroups, result.animationGroups); + Array.prototype.push.apply(container.materials, materials); + Array.prototype.push.apply(container.textures, textures); + Array.prototype.push.apply(container.lights, result.lights); + Array.prototype.push.apply(container.transformNodes, result.transformNodes); + Array.prototype.push.apply(container.cameras, cameras); + Array.prototype.push.apply(container.morphTargetManagers, morphTargetManagers); + return container; + }); + }); + } + /** + * @internal + */ + canDirectLoad(data) { + return GLTFFileLoaderMetadata.canDirectLoad(data); + } + /** + * @internal + */ + directLoad(scene, data) { + if (data.startsWith("base64," + GLTFMagicBase64Encoded) || // this is technically incorrect, but will continue to support for backcompat. + data.startsWith(";base64," + GLTFMagicBase64Encoded) || + data.startsWith("application/octet-stream;base64," + GLTFMagicBase64Encoded) || + data.startsWith("model/gltf-binary;base64," + GLTFMagicBase64Encoded)) { + const arrayBuffer = DecodeBase64UrlToBinary(data); + this._validate(scene, new Uint8Array(arrayBuffer, 0, arrayBuffer.byteLength)); + return this._unpackBinaryAsync(new DataReader({ + readAsync: (byteOffset, byteLength) => readAsync(arrayBuffer, byteOffset, byteLength), + byteLength: arrayBuffer.byteLength, + })); + } + this._validate(scene, data); + return Promise.resolve({ json: this._parseJson(data) }); + } + /** @internal */ + createPlugin(options) { + return new GLTFFileLoader(options[GLTFFileLoaderMetadata.name]); + } + /** + * The loader state or null if the loader is not active. + */ + get loaderState() { + return this._state; + } + /** + * Returns a promise that resolves when the asset is completely loaded. + * @returns a promise that resolves when the asset is completely loaded. + */ + whenCompleteAsync() { + return new Promise((resolve, reject) => { + this.onCompleteObservable.addOnce(() => { + resolve(); + }); + this.onErrorObservable.addOnce((reason) => { + reject(reason); + }); + }); + } + /** + * @internal + */ + _setState(state) { + if (this._state === state) { + return; + } + this._state = state; + this.onLoaderStateChangedObservable.notifyObservers(this._state); + this._log(GLTFLoaderState[this._state]); + } + /** + * @internal + */ + _loadFile(scene, fileOrUrl, onSuccess, useArrayBuffer, onError, onOpened) { + const request = scene._loadFile(fileOrUrl, onSuccess, (event) => { + this._onProgress(event, request); + }, true, useArrayBuffer, onError, onOpened); + request.onCompleteObservable.add(() => { + // Force the length computable to be true since we can guarantee the data is loaded. + request._lengthComputable = true; + request._total = request._loaded; + }); + this._requests.push(request); + return request; + } + _onProgress(event, request) { + if (!this._progressCallback) { + return; + } + request._lengthComputable = event.lengthComputable; + request._loaded = event.loaded; + request._total = event.total; + let lengthComputable = true; + let loaded = 0; + let total = 0; + for (const request of this._requests) { + if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) { + return; + } + lengthComputable = lengthComputable && request._lengthComputable; + loaded += request._loaded; + total += request._total; + } + this._progressCallback({ + lengthComputable: lengthComputable, + loaded: loaded, + total: lengthComputable ? total : 0, + }); + } + _validate(scene, data, rootUrl = "", fileName = "") { + if (!this.validate) { + return; + } + this._startPerformanceCounter("Validate JSON"); + GLTFValidation.ValidateAsync(data, rootUrl, fileName, (uri) => { + return this.preprocessUrlAsync(rootUrl + uri).then((url) => { + return scene._loadFileAsync(url, undefined, true, true).then((data) => { + return new Uint8Array(data, 0, data.byteLength); + }); + }); + }).then((result) => { + this._endPerformanceCounter("Validate JSON"); + this.onValidatedObservable.notifyObservers(result); + this.onValidatedObservable.clear(); + }, (reason) => { + this._endPerformanceCounter("Validate JSON"); + Tools.Warn(`Failed to validate: ${reason.message}`); + this.onValidatedObservable.clear(); + }); + } + _getLoader(loaderData) { + const asset = loaderData.json.asset || {}; + this._log(`Asset version: ${asset.version}`); + asset.minVersion && this._log(`Asset minimum version: ${asset.minVersion}`); + asset.generator && this._log(`Asset generator: ${asset.generator}`); + const version = GLTFFileLoader._parseVersion(asset.version); + if (!version) { + throw new Error("Invalid version: " + asset.version); + } + if (asset.minVersion !== undefined) { + const minVersion = GLTFFileLoader._parseVersion(asset.minVersion); + if (!minVersion) { + throw new Error("Invalid minimum version: " + asset.minVersion); + } + if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) { + throw new Error("Incompatible minimum version: " + asset.minVersion); + } + } + const createLoaders = { + 1: GLTFFileLoader._CreateGLTF1Loader, + 2: GLTFFileLoader._CreateGLTF2Loader, + }; + const createLoader = createLoaders[version.major]; + if (!createLoader) { + throw new Error("Unsupported version: " + asset.version); + } + return createLoader(this); + } + _parseJson(json) { + this._startPerformanceCounter("Parse JSON"); + this._log(`JSON length: ${json.length}`); + const parsed = JSON.parse(json); + this._endPerformanceCounter("Parse JSON"); + return parsed; + } + _unpackBinaryAsync(dataReader) { + this._startPerformanceCounter("Unpack Binary"); + // Read magic + version + length + json length + json format + return dataReader.loadAsync(20).then(() => { + const Binary = { + Magic: 0x46546c67, + }; + const magic = dataReader.readUint32(); + if (magic !== Binary.Magic) { + throw new RuntimeError("Unexpected magic: " + magic, ErrorCodes.GLTFLoaderUnexpectedMagicError); + } + const version = dataReader.readUint32(); + if (this.loggingEnabled) { + this._log(`Binary version: ${version}`); + } + const length = dataReader.readUint32(); + if (!this.useRangeRequests && length !== dataReader.buffer.byteLength) { + Logger.Warn(`Length in header does not match actual data length: ${length} != ${dataReader.buffer.byteLength}`); + } + let unpacked; + switch (version) { + case 1: { + unpacked = this._unpackBinaryV1Async(dataReader, length); + break; + } + case 2: { + unpacked = this._unpackBinaryV2Async(dataReader, length); + break; + } + default: { + throw new Error("Unsupported version: " + version); + } + } + this._endPerformanceCounter("Unpack Binary"); + return unpacked; + }); + } + _unpackBinaryV1Async(dataReader, length) { + const ContentFormat = { + JSON: 0, + }; + const contentLength = dataReader.readUint32(); + const contentFormat = dataReader.readUint32(); + if (contentFormat !== ContentFormat.JSON) { + throw new Error(`Unexpected content format: ${contentFormat}`); + } + const bodyLength = length - dataReader.byteOffset; + const data = { json: this._parseJson(dataReader.readString(contentLength)), bin: null }; + if (bodyLength !== 0) { + const startByteOffset = dataReader.byteOffset; + data.bin = { + readAsync: (byteOffset, byteLength) => dataReader.buffer.readAsync(startByteOffset + byteOffset, byteLength), + byteLength: bodyLength, + }; + } + return Promise.resolve(data); + } + _unpackBinaryV2Async(dataReader, length) { + const ChunkFormat = { + JSON: 0x4e4f534a, + BIN: 0x004e4942, + }; + // Read the JSON chunk header. + const chunkLength = dataReader.readUint32(); + const chunkFormat = dataReader.readUint32(); + if (chunkFormat !== ChunkFormat.JSON) { + throw new Error("First chunk format is not JSON"); + } + // Bail if there are no other chunks. + if (dataReader.byteOffset + chunkLength === length) { + return dataReader.loadAsync(chunkLength).then(() => { + return { json: this._parseJson(dataReader.readString(chunkLength)), bin: null }; + }); + } + // Read the JSON chunk and the length and type of the next chunk. + return dataReader.loadAsync(chunkLength + 8).then(() => { + const data = { json: this._parseJson(dataReader.readString(chunkLength)), bin: null }; + const readAsync = () => { + const chunkLength = dataReader.readUint32(); + const chunkFormat = dataReader.readUint32(); + switch (chunkFormat) { + case ChunkFormat.JSON: { + throw new Error("Unexpected JSON chunk"); + } + case ChunkFormat.BIN: { + const startByteOffset = dataReader.byteOffset; + data.bin = { + readAsync: (byteOffset, byteLength) => dataReader.buffer.readAsync(startByteOffset + byteOffset, byteLength), + byteLength: chunkLength, + }; + dataReader.skipBytes(chunkLength); + break; + } + default: { + // ignore unrecognized chunkFormat + dataReader.skipBytes(chunkLength); + break; + } + } + if (dataReader.byteOffset !== length) { + return dataReader.loadAsync(8).then(readAsync); + } + return Promise.resolve(data); + }; + return readAsync(); + }); + } + static _parseVersion(version) { + if (version === "1.0" || version === "1.0.1") { + return { + major: 1, + minor: 0, + }; + } + const match = (version + "").match(/^(\d+)\.(\d+)/); + if (!match) { + return null; + } + return { + major: parseInt(match[1]), + minor: parseInt(match[2]), + }; + } + static _compareVersion(a, b) { + if (a.major > b.major) { + return 1; + } + if (a.major < b.major) { + return -1; + } + if (a.minor > b.minor) { + return 1; + } + if (a.minor < b.minor) { + return -1; + } + return 0; + } + /** + * @internal + */ + _logOpen(message) { + this._log(message); + this._logIndentLevel++; + } + /** @internal */ + _logClose() { + --this._logIndentLevel; + } + _logEnabled(message) { + const spaces = GLTFFileLoader._logSpaces.substring(0, this._logIndentLevel * 2); + Logger.Log(`${spaces}${message}`); + } + _logDisabled(message) { } + _startPerformanceCounterEnabled(counterName) { + Tools.StartPerformanceCounter(counterName); + } + _startPerformanceCounterDisabled(counterName) { } + _endPerformanceCounterEnabled(counterName) { + Tools.EndPerformanceCounter(counterName); + } + _endPerformanceCounterDisabled(counterName) { } +} +// ------------------ +// End Common options +// ------------------ +// ---------------- +// Begin V1 options +// ---------------- +/** + * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders. + * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled. + * Defaults to true. + * @internal + */ +GLTFFileLoader.IncrementalLoading = true; +/** + * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters. + * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates. + * @internal + */ +GLTFFileLoader.HomogeneousCoordinates = false; +GLTFFileLoader._logSpaces = " "; +RegisterSceneLoaderPlugin(new GLTFFileLoader()); + +/** + * Enums + * @internal + */ +var EComponentType; +(function (EComponentType) { + EComponentType[EComponentType["BYTE"] = 5120] = "BYTE"; + EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + EComponentType[EComponentType["SHORT"] = 5122] = "SHORT"; + EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT"; +})(EComponentType || (EComponentType = {})); +/** @internal */ +var EShaderType; +(function (EShaderType) { + EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT"; + EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX"; +})(EShaderType || (EShaderType = {})); +/** @internal */ +var EParameterType; +(function (EParameterType) { + EParameterType[EParameterType["BYTE"] = 5120] = "BYTE"; + EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + EParameterType[EParameterType["SHORT"] = 5122] = "SHORT"; + EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + EParameterType[EParameterType["INT"] = 5124] = "INT"; + EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT"; + EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2"; + EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3"; + EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4"; + EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2"; + EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3"; + EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4"; + EParameterType[EParameterType["BOOL"] = 35670] = "BOOL"; + EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2"; + EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3"; + EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4"; + EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2"; + EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3"; + EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4"; + EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D"; +})(EParameterType || (EParameterType = {})); +/** @internal */ +var ETextureWrapMode; +(function (ETextureWrapMode) { + ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE"; + ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT"; +})(ETextureWrapMode || (ETextureWrapMode = {})); +/** @internal */ +var ETextureFilterType; +(function (ETextureFilterType) { + ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST"; + ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR"; + ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST"; + ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST"; + ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR"; + ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR"; +})(ETextureFilterType || (ETextureFilterType = {})); +/** @internal */ +var ETextureFormat; +(function (ETextureFormat) { + ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA"; + ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB"; + ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA"; + ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE"; + ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; +})(ETextureFormat || (ETextureFormat = {})); +/** @internal */ +var ECullingType; +(function (ECullingType) { + ECullingType[ECullingType["FRONT"] = 1028] = "FRONT"; + ECullingType[ECullingType["BACK"] = 1029] = "BACK"; + ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK"; +})(ECullingType || (ECullingType = {})); +/** @internal */ +var EBlendingFunction; +(function (EBlendingFunction) { + EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO"; + EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE"; + EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR"; + EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR"; + EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR"; + EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR"; + EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA"; + EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA"; + EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA"; + EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA"; + EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR"; + EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR"; + EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA"; + EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA"; + EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE"; +})(EBlendingFunction || (EBlendingFunction = {})); + +/** + * Manage the keyboard inputs to control the movement of a free camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FreeCameraKeyboardMoveInput { + constructor() { + /** + * Gets or Set the list of keyboard keys used to control the forward move of the camera. + */ + this.keysUp = [38]; + /** + * Gets or Set the list of keyboard keys used to control the upward move of the camera. + */ + this.keysUpward = [33]; + /** + * Gets or Set the list of keyboard keys used to control the backward move of the camera. + */ + this.keysDown = [40]; + /** + * Gets or Set the list of keyboard keys used to control the downward move of the camera. + */ + this.keysDownward = [34]; + /** + * Gets or Set the list of keyboard keys used to control the left strafe move of the camera. + */ + this.keysLeft = [37]; + /** + * Gets or Set the list of keyboard keys used to control the right strafe move of the camera. + */ + this.keysRight = [39]; + /** + * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating. + */ + this.rotationSpeed = 0.5; + /** + * Gets or Set the list of keyboard keys used to control the left rotation move of the camera. + */ + this.keysRotateLeft = []; + /** + * Gets or Set the list of keyboard keys used to control the right rotation move of the camera. + */ + this.keysRotateRight = []; + /** + * Gets or Set the list of keyboard keys used to control the up rotation move of the camera. + */ + this.keysRotateUp = []; + /** + * Gets or Set the list of keyboard keys used to control the down rotation move of the camera. + */ + this.keysRotateDown = []; + this._keys = new Array(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + if (this._onCanvasBlurObserver) { + return; + } + this._scene = this.camera.getScene(); + this._engine = this._scene.getEngine(); + this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => { + this._keys.length = 0; + }); + this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => { + const evt = info.event; + if (!evt.metaKey) { + if (info.type === KeyboardEventTypes.KEYDOWN) { + if (this.keysUp.indexOf(evt.keyCode) !== -1 || + this.keysDown.indexOf(evt.keyCode) !== -1 || + this.keysLeft.indexOf(evt.keyCode) !== -1 || + this.keysRight.indexOf(evt.keyCode) !== -1 || + this.keysUpward.indexOf(evt.keyCode) !== -1 || + this.keysDownward.indexOf(evt.keyCode) !== -1 || + this.keysRotateLeft.indexOf(evt.keyCode) !== -1 || + this.keysRotateRight.indexOf(evt.keyCode) !== -1 || + this.keysRotateUp.indexOf(evt.keyCode) !== -1 || + this.keysRotateDown.indexOf(evt.keyCode) !== -1) { + const index = this._keys.indexOf(evt.keyCode); + if (index === -1) { + this._keys.push(evt.keyCode); + } + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + else { + if (this.keysUp.indexOf(evt.keyCode) !== -1 || + this.keysDown.indexOf(evt.keyCode) !== -1 || + this.keysLeft.indexOf(evt.keyCode) !== -1 || + this.keysRight.indexOf(evt.keyCode) !== -1 || + this.keysUpward.indexOf(evt.keyCode) !== -1 || + this.keysDownward.indexOf(evt.keyCode) !== -1 || + this.keysRotateLeft.indexOf(evt.keyCode) !== -1 || + this.keysRotateRight.indexOf(evt.keyCode) !== -1 || + this.keysRotateUp.indexOf(evt.keyCode) !== -1 || + this.keysRotateDown.indexOf(evt.keyCode) !== -1) { + const index = this._keys.indexOf(evt.keyCode); + if (index >= 0) { + this._keys.splice(index, 1); + } + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + } + }); + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._scene) { + if (this._onKeyboardObserver) { + this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); + } + if (this._onCanvasBlurObserver) { + this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); + } + this._onKeyboardObserver = null; + this._onCanvasBlurObserver = null; + } + this._keys.length = 0; + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + if (this._onKeyboardObserver) { + const camera = this.camera; + // Keyboard + for (let index = 0; index < this._keys.length; index++) { + const keyCode = this._keys[index]; + const speed = camera._computeLocalCameraSpeed(); + if (this.keysLeft.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(-speed, 0, 0); + } + else if (this.keysUp.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, speed); + } + else if (this.keysRight.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(speed, 0, 0); + } + else if (this.keysDown.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, -speed); + } + else if (this.keysUpward.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, speed, 0); + } + else if (this.keysDownward.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, -speed, 0); + } + else if (this.keysRotateLeft.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, 0); + camera.cameraRotation.y -= this._getLocalRotation(); + } + else if (this.keysRotateRight.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, 0); + camera.cameraRotation.y += this._getLocalRotation(); + } + else if (this.keysRotateUp.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, 0); + camera.cameraRotation.x -= this._getLocalRotation(); + } + else if (this.keysRotateDown.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, 0); + camera.cameraRotation.x += this._getLocalRotation(); + } + if (camera.getScene().useRightHandedSystem) { + camera._localDirection.z *= -1; + } + camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); + Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); + camera.cameraDirection.addInPlace(camera._transformedDirection); + } + } + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "FreeCameraKeyboardMoveInput"; + } + /** @internal */ + _onLostFocus() { + this._keys.length = 0; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "keyboard"; + } + _getLocalRotation() { + const handednessMultiplier = this.camera._calculateHandednessMultiplier(); + const rotation = ((this.rotationSpeed * this._engine.getDeltaTime()) / 1000) * handednessMultiplier; + return rotation; + } +} +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0); +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "keysUpward", void 0); +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0); +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "keysDownward", void 0); +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0); +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0); +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "rotationSpeed", void 0); +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "keysRotateLeft", void 0); +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "keysRotateRight", void 0); +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "keysRotateUp", void 0); +__decorate([ + serialize() +], FreeCameraKeyboardMoveInput.prototype, "keysRotateDown", void 0); +CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput; + +/** + * Manage the mouse inputs to control the movement of a free camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FreeCameraMouseInput { + /** + * Manage the mouse inputs to control the movement of a free camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + * @param touchEnabled Defines if touch is enabled or not + */ + constructor( + /** + * [true] Define if touch is enabled in the mouse input + */ + touchEnabled = true) { + this.touchEnabled = touchEnabled; + /** + * Defines the buttons associated with the input to handle camera move. + */ + this.buttons = [0, 1, 2]; + /** + * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating. + */ + this.angularSensibility = 2000.0; + this._previousPosition = null; + /** + * Observable for when a pointer move event occurs containing the move offset + */ + this.onPointerMovedObservable = new Observable(); + /** + * @internal + * If the camera should be rotated automatically based on pointer movement + */ + this._allowCameraRotation = true; + this._currentActiveButton = -1; + this._activePointerId = -1; + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + const engine = this.camera.getEngine(); + const element = engine.getInputElement(); + if (!this._pointerInput) { + this._pointerInput = (p) => { + const evt = p.event; + const isTouch = evt.pointerType === "touch"; + if (!this.touchEnabled && isTouch) { + return; + } + if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) { + return; + } + const srcElement = evt.target; + if (p.type === PointerEventTypes.POINTERDOWN) { + // If the input is touch with more than one touch OR if the input is mouse and there is already an active button, return + if ((isTouch && this._activePointerId !== -1) || (!isTouch && this._currentActiveButton !== -1)) { + return; + } + this._activePointerId = evt.pointerId; + try { + srcElement?.setPointerCapture(evt.pointerId); + } + catch (e) { + //Nothing to do with the error. Execution will continue. + } + if (this._currentActiveButton === -1) { + this._currentActiveButton = evt.button; + } + this._previousPosition = { + x: evt.clientX, + y: evt.clientY, + }; + if (!noPreventDefault) { + evt.preventDefault(); + element && element.focus(); + } + // This is required to move while pointer button is down + if (engine.isPointerLock && this._onMouseMove) { + this._onMouseMove(p.event); + } + } + else if (p.type === PointerEventTypes.POINTERUP) { + // If input is touch with a different touch id OR if input is mouse with a different button, return + if ((isTouch && this._activePointerId !== evt.pointerId) || (!isTouch && this._currentActiveButton !== evt.button)) { + return; + } + try { + srcElement?.releasePointerCapture(evt.pointerId); + } + catch (e) { + //Nothing to do with the error. + } + this._currentActiveButton = -1; + this._previousPosition = null; + if (!noPreventDefault) { + evt.preventDefault(); + } + this._activePointerId = -1; + } + else if (p.type === PointerEventTypes.POINTERMOVE && (this._activePointerId === evt.pointerId || !isTouch)) { + if (engine.isPointerLock && this._onMouseMove) { + this._onMouseMove(p.event); + } + else if (this._previousPosition) { + const handednessMultiplier = this.camera._calculateHandednessMultiplier(); + const offsetX = (evt.clientX - this._previousPosition.x) * handednessMultiplier; + const offsetY = evt.clientY - this._previousPosition.y; + if (this._allowCameraRotation) { + this.camera.cameraRotation.y += offsetX / this.angularSensibility; + this.camera.cameraRotation.x += offsetY / this.angularSensibility; + } + this.onPointerMovedObservable.notifyObservers({ offsetX: offsetX, offsetY: offsetY }); + this._previousPosition = { + x: evt.clientX, + y: evt.clientY, + }; + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + }; + } + this._onMouseMove = (evt) => { + if (!engine.isPointerLock) { + return; + } + const handednessMultiplier = this.camera._calculateHandednessMultiplier(); + const offsetX = evt.movementX * handednessMultiplier; + this.camera.cameraRotation.y += offsetX / this.angularSensibility; + const offsetY = evt.movementY; + this.camera.cameraRotation.x += offsetY / this.angularSensibility; + this._previousPosition = null; + if (!noPreventDefault) { + evt.preventDefault(); + } + }; + this._observer = this.camera + .getScene() + ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE); + if (element) { + this._contextMenuBind = (evt) => this.onContextMenu(evt); + element.addEventListener("contextmenu", this._contextMenuBind, false); // TODO: We need to figure out how to handle this for Native + } + } + /** + * Called on JS contextmenu event. + * Override this method to provide functionality. + * @param evt the context menu event + */ + onContextMenu(evt) { + evt.preventDefault(); + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._observer) { + this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); + if (this._contextMenuBind) { + const engine = this.camera.getEngine(); + const element = engine.getInputElement(); + element && element.removeEventListener("contextmenu", this._contextMenuBind); + } + if (this.onPointerMovedObservable) { + this.onPointerMovedObservable.clear(); + } + this._observer = null; + this._onMouseMove = null; + this._previousPosition = null; + } + this._activePointerId = -1; + this._currentActiveButton = -1; + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "FreeCameraMouseInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "mouse"; + } +} +__decorate([ + serialize() +], FreeCameraMouseInput.prototype, "buttons", void 0); +__decorate([ + serialize() +], FreeCameraMouseInput.prototype, "angularSensibility", void 0); +CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput; + +/** + * Base class for mouse wheel input.. + * See FollowCameraMouseWheelInput in src/Cameras/Inputs/freeCameraMouseWheelInput.ts + * for example usage. + */ +class BaseCameraMouseWheelInput { + constructor() { + /** + * How fast is the camera moves in relation to X axis mouseWheel events. + * Use negative value to reverse direction. + */ + this.wheelPrecisionX = 3.0; + /** + * How fast is the camera moves in relation to Y axis mouseWheel events. + * Use negative value to reverse direction. + */ + this.wheelPrecisionY = 3.0; + /** + * How fast is the camera moves in relation to Z axis mouseWheel events. + * Use negative value to reverse direction. + */ + this.wheelPrecisionZ = 3.0; + /** + * Observable for when a mouse wheel move event occurs. + */ + this.onChangedObservable = new Observable(); + /** + * Incremental value of multiple mouse wheel movements of the X axis. + * Should be zero-ed when read. + */ + this._wheelDeltaX = 0; + /** + * Incremental value of multiple mouse wheel movements of the Y axis. + * Should be zero-ed when read. + */ + this._wheelDeltaY = 0; + /** + * Incremental value of multiple mouse wheel movements of the Z axis. + * Should be zero-ed when read. + */ + this._wheelDeltaZ = 0; + /** + * Firefox uses a different scheme to report scroll distances to other + * browsers. Rather than use complicated methods to calculate the exact + * multiple we need to apply, let's just cheat and use a constant. + * https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode + * https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line + */ + this._ffMultiplier = 12; + /** + * Different event attributes for wheel data fall into a few set ranges. + * Some relevant but dated date here: + * https://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers + */ + this._normalize = 120; + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls + * should call preventdefault(). + * (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + this._wheel = (pointer) => { + // sanity check - this should be a PointerWheel event. + if (pointer.type !== PointerEventTypes.POINTERWHEEL) { + return; + } + const event = pointer.event; + const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? this._ffMultiplier : 1; // If this happens to be set to DOM_DELTA_LINE, adjust accordingly + this._wheelDeltaX += (this.wheelPrecisionX * platformScale * event.deltaX) / this._normalize; + this._wheelDeltaY -= (this.wheelPrecisionY * platformScale * event.deltaY) / this._normalize; + this._wheelDeltaZ += (this.wheelPrecisionZ * platformScale * event.deltaZ) / this._normalize; + if (event.preventDefault) { + if (!noPreventDefault) { + event.preventDefault(); + } + } + }; + this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL); + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._observer) { + this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); + this._observer = null; + this._wheel = null; + } + if (this.onChangedObservable) { + this.onChangedObservable.clear(); + } + } + /** + * Called for each rendered frame. + */ + checkInputs() { + this.onChangedObservable.notifyObservers({ + wheelDeltaX: this._wheelDeltaX, + wheelDeltaY: this._wheelDeltaY, + wheelDeltaZ: this._wheelDeltaZ, + }); + // Clear deltas. + this._wheelDeltaX = 0; + this._wheelDeltaY = 0; + this._wheelDeltaZ = 0; + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "BaseCameraMouseWheelInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "mousewheel"; + } +} +__decorate([ + serialize() +], BaseCameraMouseWheelInput.prototype, "wheelPrecisionX", void 0); +__decorate([ + serialize() +], BaseCameraMouseWheelInput.prototype, "wheelPrecisionY", void 0); +__decorate([ + serialize() +], BaseCameraMouseWheelInput.prototype, "wheelPrecisionZ", void 0); + +// eslint-disable-next-line @typescript-eslint/naming-convention +var _CameraProperty; +(function (_CameraProperty) { + _CameraProperty[_CameraProperty["MoveRelative"] = 0] = "MoveRelative"; + _CameraProperty[_CameraProperty["RotateRelative"] = 1] = "RotateRelative"; + _CameraProperty[_CameraProperty["MoveScene"] = 2] = "MoveScene"; +})(_CameraProperty || (_CameraProperty = {})); +/** + * Manage the mouse wheel inputs to control a free camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FreeCameraMouseWheelInput extends BaseCameraMouseWheelInput { + constructor() { + super(...arguments); + this._moveRelative = Vector3.Zero(); + this._rotateRelative = Vector3.Zero(); + this._moveScene = Vector3.Zero(); + /** + * These are set to the desired default behaviour. + */ + this._wheelXAction = _CameraProperty.MoveRelative; + this._wheelXActionCoordinate = 0 /* Coordinate.X */; + this._wheelYAction = _CameraProperty.MoveRelative; + this._wheelYActionCoordinate = 2 /* Coordinate.Z */; + this._wheelZAction = null; + this._wheelZActionCoordinate = null; + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "FreeCameraMouseWheelInput"; + } + /** + * Set which movement axis (relative to camera's orientation) the mouse + * wheel's X axis controls. + * @param axis The axis to be moved. Set null to clear. + */ + set wheelXMoveRelative(axis) { + if (axis === null && this._wheelXAction !== _CameraProperty.MoveRelative) { + // Attempting to clear different _wheelXAction. + return; + } + this._wheelXAction = _CameraProperty.MoveRelative; + this._wheelXActionCoordinate = axis; + } + /** + * Get the configured movement axis (relative to camera's orientation) the + * mouse wheel's X axis controls. + * @returns The configured axis or null if none. + */ + get wheelXMoveRelative() { + if (this._wheelXAction !== _CameraProperty.MoveRelative) { + return null; + } + return this._wheelXActionCoordinate; + } + /** + * Set which movement axis (relative to camera's orientation) the mouse + * wheel's Y axis controls. + * @param axis The axis to be moved. Set null to clear. + */ + set wheelYMoveRelative(axis) { + if (axis === null && this._wheelYAction !== _CameraProperty.MoveRelative) { + // Attempting to clear different _wheelYAction. + return; + } + this._wheelYAction = _CameraProperty.MoveRelative; + this._wheelYActionCoordinate = axis; + } + /** + * Get the configured movement axis (relative to camera's orientation) the + * mouse wheel's Y axis controls. + * @returns The configured axis or null if none. + */ + get wheelYMoveRelative() { + if (this._wheelYAction !== _CameraProperty.MoveRelative) { + return null; + } + return this._wheelYActionCoordinate; + } + /** + * Set which movement axis (relative to camera's orientation) the mouse + * wheel's Z axis controls. + * @param axis The axis to be moved. Set null to clear. + */ + set wheelZMoveRelative(axis) { + if (axis === null && this._wheelZAction !== _CameraProperty.MoveRelative) { + // Attempting to clear different _wheelZAction. + return; + } + this._wheelZAction = _CameraProperty.MoveRelative; + this._wheelZActionCoordinate = axis; + } + /** + * Get the configured movement axis (relative to camera's orientation) the + * mouse wheel's Z axis controls. + * @returns The configured axis or null if none. + */ + get wheelZMoveRelative() { + if (this._wheelZAction !== _CameraProperty.MoveRelative) { + return null; + } + return this._wheelZActionCoordinate; + } + /** + * Set which rotation axis (relative to camera's orientation) the mouse + * wheel's X axis controls. + * @param axis The axis to be moved. Set null to clear. + */ + set wheelXRotateRelative(axis) { + if (axis === null && this._wheelXAction !== _CameraProperty.RotateRelative) { + // Attempting to clear different _wheelXAction. + return; + } + this._wheelXAction = _CameraProperty.RotateRelative; + this._wheelXActionCoordinate = axis; + } + /** + * Get the configured rotation axis (relative to camera's orientation) the + * mouse wheel's X axis controls. + * @returns The configured axis or null if none. + */ + get wheelXRotateRelative() { + if (this._wheelXAction !== _CameraProperty.RotateRelative) { + return null; + } + return this._wheelXActionCoordinate; + } + /** + * Set which rotation axis (relative to camera's orientation) the mouse + * wheel's Y axis controls. + * @param axis The axis to be moved. Set null to clear. + */ + set wheelYRotateRelative(axis) { + if (axis === null && this._wheelYAction !== _CameraProperty.RotateRelative) { + // Attempting to clear different _wheelYAction. + return; + } + this._wheelYAction = _CameraProperty.RotateRelative; + this._wheelYActionCoordinate = axis; + } + /** + * Get the configured rotation axis (relative to camera's orientation) the + * mouse wheel's Y axis controls. + * @returns The configured axis or null if none. + */ + get wheelYRotateRelative() { + if (this._wheelYAction !== _CameraProperty.RotateRelative) { + return null; + } + return this._wheelYActionCoordinate; + } + /** + * Set which rotation axis (relative to camera's orientation) the mouse + * wheel's Z axis controls. + * @param axis The axis to be moved. Set null to clear. + */ + set wheelZRotateRelative(axis) { + if (axis === null && this._wheelZAction !== _CameraProperty.RotateRelative) { + // Attempting to clear different _wheelZAction. + return; + } + this._wheelZAction = _CameraProperty.RotateRelative; + this._wheelZActionCoordinate = axis; + } + /** + * Get the configured rotation axis (relative to camera's orientation) the + * mouse wheel's Z axis controls. + * @returns The configured axis or null if none. + */ + get wheelZRotateRelative() { + if (this._wheelZAction !== _CameraProperty.RotateRelative) { + return null; + } + return this._wheelZActionCoordinate; + } + /** + * Set which movement axis (relative to the scene) the mouse wheel's X axis + * controls. + * @param axis The axis to be moved. Set null to clear. + */ + set wheelXMoveScene(axis) { + if (axis === null && this._wheelXAction !== _CameraProperty.MoveScene) { + // Attempting to clear different _wheelXAction. + return; + } + this._wheelXAction = _CameraProperty.MoveScene; + this._wheelXActionCoordinate = axis; + } + /** + * Get the configured movement axis (relative to the scene) the mouse wheel's + * X axis controls. + * @returns The configured axis or null if none. + */ + get wheelXMoveScene() { + if (this._wheelXAction !== _CameraProperty.MoveScene) { + return null; + } + return this._wheelXActionCoordinate; + } + /** + * Set which movement axis (relative to the scene) the mouse wheel's Y axis + * controls. + * @param axis The axis to be moved. Set null to clear. + */ + set wheelYMoveScene(axis) { + if (axis === null && this._wheelYAction !== _CameraProperty.MoveScene) { + // Attempting to clear different _wheelYAction. + return; + } + this._wheelYAction = _CameraProperty.MoveScene; + this._wheelYActionCoordinate = axis; + } + /** + * Get the configured movement axis (relative to the scene) the mouse wheel's + * Y axis controls. + * @returns The configured axis or null if none. + */ + get wheelYMoveScene() { + if (this._wheelYAction !== _CameraProperty.MoveScene) { + return null; + } + return this._wheelYActionCoordinate; + } + /** + * Set which movement axis (relative to the scene) the mouse wheel's Z axis + * controls. + * @param axis The axis to be moved. Set null to clear. + */ + set wheelZMoveScene(axis) { + if (axis === null && this._wheelZAction !== _CameraProperty.MoveScene) { + // Attempting to clear different _wheelZAction. + return; + } + this._wheelZAction = _CameraProperty.MoveScene; + this._wheelZActionCoordinate = axis; + } + /** + * Get the configured movement axis (relative to the scene) the mouse wheel's + * Z axis controls. + * @returns The configured axis or null if none. + */ + get wheelZMoveScene() { + if (this._wheelZAction !== _CameraProperty.MoveScene) { + return null; + } + return this._wheelZActionCoordinate; + } + /** + * Called for each rendered frame. + */ + checkInputs() { + if (this._wheelDeltaX === 0 && this._wheelDeltaY === 0 && this._wheelDeltaZ == 0) { + return; + } + // Clear the camera properties that we might be updating. + this._moveRelative.setAll(0); + this._rotateRelative.setAll(0); + this._moveScene.setAll(0); + // Set the camera properties that are to be updated. + this._updateCamera(); + if (this.camera.getScene().useRightHandedSystem) { + // TODO: Does this need done for worldUpdate too? + this._moveRelative.z *= -1; + } + // Convert updates relative to camera to world position update. + const cameraTransformMatrix = Matrix.Zero(); + this.camera.getViewMatrix().invertToRef(cameraTransformMatrix); + const transformedDirection = Vector3.Zero(); + Vector3.TransformNormalToRef(this._moveRelative, cameraTransformMatrix, transformedDirection); + // Apply updates to camera position. + this.camera.cameraRotation.x += this._rotateRelative.x / 200; + this.camera.cameraRotation.y += this._rotateRelative.y / 200; + this.camera.cameraDirection.addInPlace(transformedDirection); + this.camera.cameraDirection.addInPlace(this._moveScene); + // Call the base class implementation to handle observers and do cleanup. + super.checkInputs(); + } + /** + * Update the camera according to any configured properties for the 3 + * mouse-wheel axis. + */ + _updateCamera() { + // Do the camera updates for each of the 3 touch-wheel axis. + this._updateCameraProperty(this._wheelDeltaX, this._wheelXAction, this._wheelXActionCoordinate); + this._updateCameraProperty(this._wheelDeltaY, this._wheelYAction, this._wheelYActionCoordinate); + this._updateCameraProperty(this._wheelDeltaZ, this._wheelZAction, this._wheelZActionCoordinate); + } + /** + * Update one property of the camera. + * @param value + * @param cameraProperty + * @param coordinate + */ + _updateCameraProperty( + /* Mouse-wheel delta. */ + value, + /* Camera property to be changed. */ + cameraProperty, + /* Axis of Camera property to be changed. */ + coordinate) { + if (value === 0) { + // Mouse wheel has not moved. + return; + } + if (cameraProperty === null || coordinate === null) { + // Mouse wheel axis not configured. + return; + } + let action = null; + switch (cameraProperty) { + case _CameraProperty.MoveRelative: + action = this._moveRelative; + break; + case _CameraProperty.RotateRelative: + action = this._rotateRelative; + break; + case _CameraProperty.MoveScene: + action = this._moveScene; + break; + } + switch (coordinate) { + case 0 /* Coordinate.X */: + action.set(value, 0, 0); + break; + case 1 /* Coordinate.Y */: + action.set(0, value, 0); + break; + case 2 /* Coordinate.Z */: + action.set(0, 0, value); + break; + } + } +} +__decorate([ + serialize() +], FreeCameraMouseWheelInput.prototype, "wheelXMoveRelative", null); +__decorate([ + serialize() +], FreeCameraMouseWheelInput.prototype, "wheelYMoveRelative", null); +__decorate([ + serialize() +], FreeCameraMouseWheelInput.prototype, "wheelZMoveRelative", null); +__decorate([ + serialize() +], FreeCameraMouseWheelInput.prototype, "wheelXRotateRelative", null); +__decorate([ + serialize() +], FreeCameraMouseWheelInput.prototype, "wheelYRotateRelative", null); +__decorate([ + serialize() +], FreeCameraMouseWheelInput.prototype, "wheelZRotateRelative", null); +__decorate([ + serialize() +], FreeCameraMouseWheelInput.prototype, "wheelXMoveScene", null); +__decorate([ + serialize() +], FreeCameraMouseWheelInput.prototype, "wheelYMoveScene", null); +__decorate([ + serialize() +], FreeCameraMouseWheelInput.prototype, "wheelZMoveScene", null); +CameraInputTypes["FreeCameraMouseWheelInput"] = FreeCameraMouseWheelInput; + +/** + * Manage the touch inputs to control the movement of a free camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FreeCameraTouchInput { + /** + * Manage the touch inputs to control the movement of a free camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + * @param allowMouse Defines if mouse events can be treated as touch events + */ + constructor( + /** + * [false] Define if mouse events can be treated as touch events + */ + allowMouse = false) { + this.allowMouse = allowMouse; + /** + * Defines the touch sensibility for rotation. + * The lower the faster. + */ + this.touchAngularSensibility = 200000.0; + /** + * Defines the touch sensibility for move. + * The lower the faster. + */ + this.touchMoveSensibility = 250.0; + /** + * Swap touch actions so that one touch is used for rotation and multiple for movement + */ + this.singleFingerRotate = false; + this._offsetX = null; + this._offsetY = null; + this._pointerPressed = new Array(); + this._isSafari = Tools.IsSafari(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + let previousPosition = null; + if (this._pointerInput === undefined) { + this._onLostFocus = () => { + this._offsetX = null; + this._offsetY = null; + }; + this._pointerInput = (p) => { + const evt = p.event; + const isMouseEvent = evt.pointerType === "mouse" || (this._isSafari && typeof evt.pointerType === "undefined"); + if (!this.allowMouse && isMouseEvent) { + return; + } + if (p.type === PointerEventTypes.POINTERDOWN) { + if (!noPreventDefault) { + evt.preventDefault(); + } + this._pointerPressed.push(evt.pointerId); + if (this._pointerPressed.length !== 1) { + return; + } + previousPosition = { + x: evt.clientX, + y: evt.clientY, + }; + } + else if (p.type === PointerEventTypes.POINTERUP) { + if (!noPreventDefault) { + evt.preventDefault(); + } + const index = this._pointerPressed.indexOf(evt.pointerId); + if (index === -1) { + return; + } + this._pointerPressed.splice(index, 1); + if (index != 0) { + return; + } + previousPosition = null; + this._offsetX = null; + this._offsetY = null; + } + else if (p.type === PointerEventTypes.POINTERMOVE) { + if (!noPreventDefault) { + evt.preventDefault(); + } + if (!previousPosition) { + return; + } + const index = this._pointerPressed.indexOf(evt.pointerId); + if (index != 0) { + return; + } + this._offsetX = evt.clientX - previousPosition.x; + this._offsetY = -(evt.clientY - previousPosition.y); + } + }; + } + this._observer = this.camera + .getScene() + ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE); + if (this._onLostFocus) { + const engine = this.camera.getEngine(); + const element = engine.getInputElement(); + element && element.addEventListener("blur", this._onLostFocus); + } + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._pointerInput) { + if (this._observer) { + this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); + this._observer = null; + } + if (this._onLostFocus) { + const engine = this.camera.getEngine(); + const element = engine.getInputElement(); + element && element.removeEventListener("blur", this._onLostFocus); + this._onLostFocus = null; + } + this._pointerPressed.length = 0; + this._offsetX = null; + this._offsetY = null; + } + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + if (this._offsetX === null || this._offsetY === null) { + return; + } + if (this._offsetX === 0 && this._offsetY === 0) { + return; + } + const camera = this.camera; + const handednessMultiplier = camera._calculateHandednessMultiplier(); + camera.cameraRotation.y = (handednessMultiplier * this._offsetX) / this.touchAngularSensibility; + const rotateCamera = (this.singleFingerRotate && this._pointerPressed.length === 1) || (!this.singleFingerRotate && this._pointerPressed.length > 1); + if (rotateCamera) { + camera.cameraRotation.x = -this._offsetY / this.touchAngularSensibility; + } + else { + const speed = camera._computeLocalCameraSpeed(); + const direction = new Vector3(0, 0, this.touchMoveSensibility !== 0 ? (speed * this._offsetY) / this.touchMoveSensibility : 0); + Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix); + camera.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix)); + } + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "FreeCameraTouchInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "touch"; + } +} +__decorate([ + serialize() +], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0); +__decorate([ + serialize() +], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0); +CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput; + +/** + * Default Inputs manager for the FreeCamera. + * It groups all the default supported inputs for ease of use. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FreeCameraInputsManager extends CameraInputsManager { + /** + * Instantiates a new FreeCameraInputsManager. + * @param camera Defines the camera the inputs belong to + */ + constructor(camera) { + super(camera); + /** + * @internal + */ + this._mouseInput = null; + /** + * @internal + */ + this._mouseWheelInput = null; + } + /** + * Add keyboard input support to the input manager. + * @returns the current input manager + */ + addKeyboard() { + this.add(new FreeCameraKeyboardMoveInput()); + return this; + } + /** + * Add mouse input support to the input manager. + * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true) + * @returns the current input manager + */ + addMouse(touchEnabled = true) { + if (!this._mouseInput) { + this._mouseInput = new FreeCameraMouseInput(touchEnabled); + this.add(this._mouseInput); + } + return this; + } + /** + * Removes the mouse input support from the manager + * @returns the current input manager + */ + removeMouse() { + if (this._mouseInput) { + this.remove(this._mouseInput); + } + return this; + } + /** + * Add mouse wheel input support to the input manager. + * @returns the current input manager + */ + addMouseWheel() { + if (!this._mouseWheelInput) { + this._mouseWheelInput = new FreeCameraMouseWheelInput(); + this.add(this._mouseWheelInput); + } + return this; + } + /** + * Removes the mouse wheel input support from the manager + * @returns the current input manager + */ + removeMouseWheel() { + if (this._mouseWheelInput) { + this.remove(this._mouseWheelInput); + } + return this; + } + /** + * Add touch input support to the input manager. + * @returns the current input manager + */ + addTouch() { + this.add(new FreeCameraTouchInput()); + return this; + } + /** + * Remove all attached input methods from a camera + */ + clear() { + super.clear(); + this._mouseInput = null; + } +} + +/** + * This represents a free type of camera. It can be useful in First Person Shooter game for instance. + * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera + */ +class FreeCamera extends TargetCamera { + /** + * Gets the input sensibility for a mouse input. (default is 2000.0) + * Higher values reduce sensitivity. + */ + get angularSensibility() { + const mouse = this.inputs.attached["mouse"]; + if (mouse) { + return mouse.angularSensibility; + } + return 0; + } + /** + * Sets the input sensibility for a mouse input. (default is 2000.0) + * Higher values reduce sensitivity. + */ + set angularSensibility(value) { + const mouse = this.inputs.attached["mouse"]; + if (mouse) { + mouse.angularSensibility = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control the forward move of the camera. + */ + get keysUp() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysUp; + } + return []; + } + set keysUp(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysUp = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control the upward move of the camera. + */ + get keysUpward() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysUpward; + } + return []; + } + set keysUpward(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysUpward = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control the backward move of the camera. + */ + get keysDown() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysDown; + } + return []; + } + set keysDown(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysDown = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control the downward move of the camera. + */ + get keysDownward() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysDownward; + } + return []; + } + set keysDownward(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysDownward = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control the left strafe move of the camera. + */ + get keysLeft() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysLeft; + } + return []; + } + set keysLeft(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysLeft = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control the right strafe move of the camera. + */ + get keysRight() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysRight; + } + return []; + } + set keysRight(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysRight = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control the left rotation move of the camera. + */ + get keysRotateLeft() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysRotateLeft; + } + return []; + } + set keysRotateLeft(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysRotateLeft = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control the right rotation move of the camera. + */ + get keysRotateRight() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysRotateRight; + } + return []; + } + set keysRotateRight(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysRotateRight = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control the up rotation move of the camera. + */ + get keysRotateUp() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysRotateUp; + } + return []; + } + set keysRotateUp(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysRotateUp = value; + } + } + /** + * Gets or Set the list of keyboard keys used to control the down rotation move of the camera. + */ + get keysRotateDown() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysRotateDown; + } + return []; + } + set keysRotateDown(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysRotateDown = value; + } + } + /** + * Instantiates a Free Camera. + * This represents a free type of camera. It can be useful in First Person Shooter game for instance. + * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera + * @param name Define the name of the camera in the scene + * @param position Define the start position of the camera in the scene + * @param scene Define the scene the camera belongs to + * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined + */ + constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) { + super(name, position, scene, setActiveOnSceneIfNoneActive); + /** + * Define the collision ellipsoid of the camera. + * This is helpful to simulate a camera body like the player body around the camera + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera + */ + this.ellipsoid = new Vector3(0.5, 1, 0.5); + /** + * Define an offset for the position of the ellipsoid around the camera. + * This can be helpful to determine the center of the body near the gravity center of the body + * instead of its head. + */ + this.ellipsoidOffset = new Vector3(0, 0, 0); + /** + * Enable or disable collisions of the camera with the rest of the scene objects. + */ + this.checkCollisions = false; + /** + * Enable or disable gravity on the camera. + */ + this.applyGravity = false; + this._needMoveForGravity = false; + this._oldPosition = Vector3.Zero(); + this._diffPosition = Vector3.Zero(); + this._newPosition = Vector3.Zero(); + // Collisions + this._collisionMask = -1; + this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => { + this._newPosition.copyFrom(newPosition); + this._newPosition.subtractToRef(this._oldPosition, this._diffPosition); + if (this._diffPosition.length() > AbstractEngine.CollisionsEpsilon) { + this.position.addToRef(this._diffPosition, this._deferredPositionUpdate); + if (!this._deferOnly) { + this.position.copyFrom(this._deferredPositionUpdate); + } + else { + this._deferredUpdated = true; + } + // call onCollide, if defined. Note that in case of deferred update, the actual position change might happen in the next frame. + if (this.onCollide && collidedMesh) { + this.onCollide(collidedMesh); + } + } + }; + this.inputs = new FreeCameraInputsManager(this); + this.inputs.addKeyboard().addMouse(); + } + /** + * Attached controls to the current camera. + * @param ignored defines an ignored parameter kept for backward compatibility. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(ignored, noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + this.inputs.attachElement(noPreventDefault); + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + this.inputs.detachElement(); + this.cameraDirection = new Vector3(0, 0, 0); + this.cameraRotation = new Vector2(0, 0); + } + /** + * Define a collision mask to limit the list of object the camera can collide with + */ + get collisionMask() { + return this._collisionMask; + } + set collisionMask(mask) { + this._collisionMask = !isNaN(mask) ? mask : -1; + } + /** + * @internal + */ + _collideWithWorld(displacement) { + let globalPosition; + if (this.parent) { + globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix()); + } + else { + globalPosition = this.position; + } + globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition); + this._oldPosition.addInPlace(this.ellipsoidOffset); + const coordinator = this.getScene().collisionCoordinator; + if (!this._collider) { + this._collider = coordinator.createCollider(); + } + this._collider._radius = this.ellipsoid; + this._collider.collisionMask = this._collisionMask; + //no need for clone, as long as gravity is not on. + let actualDisplacement = displacement; + //add gravity to the direction to prevent the dual-collision checking + if (this.applyGravity) { + //this prevents mending with cameraDirection, a global variable of the free camera class. + actualDisplacement = displacement.add(this.getScene().gravity); + } + coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); + } + /** @internal */ + _checkInputs() { + if (!this._localDirection) { + this._localDirection = Vector3.Zero(); + this._transformedDirection = Vector3.Zero(); + } + this.inputs.checkInputs(); + super._checkInputs(); + } + /** + * Enable movement without a user input. This allows gravity to always be applied. + */ + set needMoveForGravity(value) { + this._needMoveForGravity = value; + } + /** + * When true, gravity is applied whether there is user input or not. + */ + get needMoveForGravity() { + return this._needMoveForGravity; + } + /** @internal */ + _decideIfNeedsToMove() { + return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; + } + /** @internal */ + _updatePosition() { + if (this.checkCollisions && this.getScene().collisionsEnabled) { + this._collideWithWorld(this.cameraDirection); + } + else { + super._updatePosition(); + } + } + /** + * Destroy the camera and release the current resources hold by it. + */ + dispose() { + this.inputs.clear(); + super.dispose(); + } + /** + * Gets the current object class name. + * @returns the class name + */ + getClassName() { + return "FreeCamera"; + } +} +__decorate([ + serializeAsVector3() +], FreeCamera.prototype, "ellipsoid", void 0); +__decorate([ + serializeAsVector3() +], FreeCamera.prototype, "ellipsoidOffset", void 0); +__decorate([ + serialize() +], FreeCamera.prototype, "checkCollisions", void 0); +__decorate([ + serialize() +], FreeCamera.prototype, "applyGravity", void 0); +// Register Class Name +RegisterClass("BABYLON.FreeCamera", FreeCamera); + +/** + * Class used to store bone information + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons + */ +class Bone extends Node$2 { + /** @internal */ + get _matrix() { + this._compose(); + return this._localMatrix; + } + /** @internal */ + set _matrix(value) { + // skip if the matrices are the same + if (value.updateFlag === this._localMatrix.updateFlag && !this._needToCompose) { + return; + } + this._needToCompose = false; // in case there was a pending compose + this._localMatrix.copyFrom(value); + this._markAsDirtyAndDecompose(); + } + /** + * Create a new bone + * @param name defines the bone name + * @param skeleton defines the parent skeleton + * @param parentBone defines the parent (can be null if the bone is the root) + * @param localMatrix defines the local matrix (default: identity) + * @param restMatrix defines the rest matrix (default: localMatrix) + * @param bindMatrix defines the bind matrix (default: localMatrix) + * @param index defines index of the bone in the hierarchy (default: null) + */ + constructor( + /** + * defines the bone name + */ + name, skeleton, parentBone = null, localMatrix = null, restMatrix = null, bindMatrix = null, index = null) { + super(name, skeleton.getScene(), false); + this.name = name; + /** + * Gets the list of child bones + */ + this.children = []; + /** Gets the animations associated with this bone */ + this.animations = []; + /** + * @internal Internal only + * Set this value to map this bone to a different index in the transform matrices + * Set this value to -1 to exclude the bone from the transform matrices + */ + this._index = null; + this._scalingDeterminant = 1; + this._needToDecompose = true; + this._needToCompose = false; + /** @internal */ + this._linkedTransformNode = null; + /** @internal */ + this._waitingTransformNodeId = null; + this._skeleton = skeleton; + this._localMatrix = localMatrix?.clone() ?? Matrix.Identity(); + this._restMatrix = restMatrix ?? this._localMatrix.clone(); + this._bindMatrix = bindMatrix ?? this._localMatrix.clone(); + this._index = index; + this._absoluteMatrix = new Matrix(); + this._absoluteBindMatrix = new Matrix(); + this._absoluteInverseBindMatrix = new Matrix(); + this._finalMatrix = new Matrix(); + skeleton.bones.push(this); + this.setParent(parentBone, false); + this._updateAbsoluteBindMatrices(); + } + /** + * Gets the current object class name. + * @returns the class name + */ + getClassName() { + return "Bone"; + } + // Members + /** + * Gets the parent skeleton + * @returns a skeleton + */ + getSkeleton() { + return this._skeleton; + } + get parent() { + return this._parentNode; + } + /** + * Gets parent bone + * @returns a bone or null if the bone is the root of the bone hierarchy + */ + getParent() { + return this.parent; + } + /** + * Returns an array containing the children of the bone + * @returns an array containing the children of the bone (can be empty if the bone has no children) + */ + getChildren() { + return this.children; + } + /** + * Gets the node index in matrix array generated for rendering + * @returns the node index + */ + getIndex() { + return this._index === null ? this.getSkeleton().bones.indexOf(this) : this._index; + } + set parent(newParent) { + this.setParent(newParent); + } + /** + * Sets the parent bone + * @param parent defines the parent (can be null if the bone is the root) + * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be updated + */ + setParent(parent, updateAbsoluteBindMatrices = true) { + if (this.parent === parent) { + return; + } + if (this.parent) { + const index = this.parent.children.indexOf(this); + if (index !== -1) { + this.parent.children.splice(index, 1); + } + } + this._parentNode = parent; + if (this.parent) { + this.parent.children.push(this); + } + if (updateAbsoluteBindMatrices) { + this._updateAbsoluteBindMatrices(); + } + this.markAsDirty(); + } + /** + * Gets the local matrix + * @returns the local matrix + */ + getLocalMatrix() { + this._compose(); + return this._localMatrix; + } + /** + * Gets the bind matrix + * @returns the bind matrix + */ + getBindMatrix() { + return this._bindMatrix; + } + /** + * Gets the bind matrix. + * @returns the bind matrix + * @deprecated Please use getBindMatrix instead + */ + getBaseMatrix() { + return this.getBindMatrix(); + } + /** + * Gets the rest matrix + * @returns the rest matrix + */ + getRestMatrix() { + return this._restMatrix; + } + /** + * Gets the rest matrix + * @returns the rest matrix + * @deprecated Please use getRestMatrix instead + */ + getRestPose() { + return this.getRestMatrix(); + } + /** + * Sets the rest matrix + * @param matrix the local-space rest matrix to set for this bone + */ + setRestMatrix(matrix) { + this._restMatrix.copyFrom(matrix); + } + /** + * Sets the rest matrix + * @param matrix the local-space rest to set for this bone + * @deprecated Please use setRestMatrix instead + */ + setRestPose(matrix) { + this.setRestMatrix(matrix); + } + /** + * Gets the bind matrix + * @returns the bind matrix + * @deprecated Please use getBindMatrix instead + */ + getBindPose() { + return this.getBindMatrix(); + } + /** + * Sets the bind matrix + * This will trigger a recomputation of the absolute bind and absolute inverse bind matrices for this bone and its children + * Note that the local matrix will also be set with the matrix passed in parameter! + * @param matrix the local-space bind matrix to set for this bone + */ + setBindMatrix(matrix) { + this.updateMatrix(matrix); + } + /** + * Sets the bind matrix + * @param matrix the local-space bind to set for this bone + * @deprecated Please use setBindMatrix instead + */ + setBindPose(matrix) { + this.setBindMatrix(matrix); + } + /** + * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders) + * @returns the final world matrix + */ + getFinalMatrix() { + return this._finalMatrix; + } + /** + * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders) + * @deprecated Please use getFinalMatrix instead + * @returns the final world matrix + */ + getWorldMatrix() { + return this.getFinalMatrix(); + } + /** + * Sets the local matrix to the rest matrix + */ + returnToRest() { + if (this._linkedTransformNode) { + const localScaling = TmpVectors.Vector3[0]; + const localRotation = TmpVectors.Quaternion[0]; + const localPosition = TmpVectors.Vector3[1]; + this.getRestMatrix().decompose(localScaling, localRotation, localPosition); + this._linkedTransformNode.position.copyFrom(localPosition); + this._linkedTransformNode.rotationQuaternion = this._linkedTransformNode.rotationQuaternion ?? Quaternion.Identity(); + this._linkedTransformNode.rotationQuaternion.copyFrom(localRotation); + this._linkedTransformNode.scaling.copyFrom(localScaling); + } + else { + this._matrix = this._restMatrix; + } + } + /** + * Gets the inverse of the bind matrix, in world space (relative to the skeleton root) + * @returns the inverse bind matrix, in world space + */ + getAbsoluteInverseBindMatrix() { + return this._absoluteInverseBindMatrix; + } + /** + * Gets the inverse of the bind matrix, in world space (relative to the skeleton root) + * @returns the inverse bind matrix, in world space + * @deprecated Please use getAbsoluteInverseBindMatrix instead + */ + getInvertedAbsoluteTransform() { + return this.getAbsoluteInverseBindMatrix(); + } + /** + * Gets the bone matrix, in world space (relative to the skeleton root) + * @returns the bone matrix, in world space + */ + getAbsoluteMatrix() { + return this._absoluteMatrix; + } + /** + * Gets the bone matrix, in world space (relative to the skeleton root) + * @returns the bone matrix, in world space + * @deprecated Please use getAbsoluteMatrix instead + */ + getAbsoluteTransform() { + return this._absoluteMatrix; + } + /** + * Links with the given transform node. + * The local matrix of this bone is overwritten by the transform of the node every frame. + * @param transformNode defines the transform node to link to + */ + linkTransformNode(transformNode) { + if (this._linkedTransformNode) { + this._skeleton._numBonesWithLinkedTransformNode--; + } + this._linkedTransformNode = transformNode; + if (this._linkedTransformNode) { + this._skeleton._numBonesWithLinkedTransformNode++; + } + } + // Properties (matches TransformNode properties) + /** + * Gets the node used to drive the bone's transformation + * @returns a transform node or null + */ + getTransformNode() { + return this._linkedTransformNode; + } + /** Gets or sets current position (in local space) */ + get position() { + this._decompose(); + return this._localPosition; + } + set position(newPosition) { + this._decompose(); + this._localPosition.copyFrom(newPosition); + this._markAsDirtyAndCompose(); + } + /** Gets or sets current rotation (in local space) */ + get rotation() { + return this.getRotation(); + } + set rotation(newRotation) { + this.setRotation(newRotation); + } + /** Gets or sets current rotation quaternion (in local space) */ + get rotationQuaternion() { + this._decompose(); + return this._localRotation; + } + set rotationQuaternion(newRotation) { + this.setRotationQuaternion(newRotation); + } + /** Gets or sets current scaling (in local space) */ + get scaling() { + return this.getScale(); + } + set scaling(newScaling) { + this.setScale(newScaling); + } + /** + * Gets the animation properties override + */ + get animationPropertiesOverride() { + return this._skeleton.animationPropertiesOverride; + } + // Methods + _decompose() { + if (!this._needToDecompose) { + return; + } + this._needToDecompose = false; + if (!this._localScaling) { + this._localScaling = Vector3.Zero(); + this._localRotation = Quaternion.Zero(); + this._localPosition = Vector3.Zero(); + } + this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition); + } + _compose() { + if (!this._needToCompose) { + return; + } + if (!this._localScaling) { + this._needToCompose = false; + return; + } + this._needToCompose = false; + Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix); + } + /** + * Update the bind (and optionally the local) matrix + * @param bindMatrix defines the new matrix to set to the bind/local matrix, in local space + * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be recomputed (default: true) + * @param updateLocalMatrix defines if the local matrix should also be updated with the matrix passed in parameter (default: true) + */ + updateMatrix(bindMatrix, updateAbsoluteBindMatrices = true, updateLocalMatrix = true) { + this._bindMatrix.copyFrom(bindMatrix); + if (updateAbsoluteBindMatrices) { + this._updateAbsoluteBindMatrices(); + } + if (updateLocalMatrix) { + this._matrix = bindMatrix; + } + else { + this.markAsDirty(); + } + } + /** + * @internal + */ + _updateAbsoluteBindMatrices(bindMatrix, updateChildren = true) { + if (!bindMatrix) { + bindMatrix = this._bindMatrix; + } + if (this.parent) { + bindMatrix.multiplyToRef(this.parent._absoluteBindMatrix, this._absoluteBindMatrix); + } + else { + this._absoluteBindMatrix.copyFrom(bindMatrix); + } + this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix); + if (updateChildren) { + for (let index = 0; index < this.children.length; index++) { + this.children[index]._updateAbsoluteBindMatrices(); + } + } + this._scalingDeterminant = this._absoluteBindMatrix.determinant() < 0 ? -1 : 1; + } + /** + * Flag the bone as dirty (Forcing it to update everything) + * @returns this bone + */ + markAsDirty() { + this._currentRenderId++; + this._childUpdateId++; + this._skeleton._markAsDirty(); + return this; + } + /** @internal */ + _markAsDirtyAndCompose() { + this.markAsDirty(); + this._needToCompose = true; + } + _markAsDirtyAndDecompose() { + this.markAsDirty(); + this._needToDecompose = true; + } + _updatePosition(vec, space = 0 /* Space.LOCAL */, tNode, translationMode = true) { + const lm = this.getLocalMatrix(); + if (space == 0 /* Space.LOCAL */) { + if (translationMode) { + lm.addAtIndex(12, vec.x); + lm.addAtIndex(13, vec.y); + lm.addAtIndex(14, vec.z); + } + else { + lm.setTranslationFromFloats(vec.x, vec.y, vec.z); + } + } + else { + let wm = null; + //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices() + if (tNode) { + wm = tNode.getWorldMatrix(); + } + this._skeleton.computeAbsoluteMatrices(); + const tmat = Bone._TmpMats[0]; + const tvec = Bone._TmpVecs[0]; + if (this.parent) { + if (tNode && wm) { + tmat.copyFrom(this.parent.getAbsoluteMatrix()); + tmat.multiplyToRef(wm, tmat); + } + else { + tmat.copyFrom(this.parent.getAbsoluteMatrix()); + } + } + else { + Matrix.IdentityToRef(tmat); + } + if (translationMode) { + tmat.setTranslationFromFloats(0, 0, 0); + } + tmat.invert(); + Vector3.TransformCoordinatesToRef(vec, tmat, tvec); + if (translationMode) { + lm.addAtIndex(12, tvec.x); + lm.addAtIndex(13, tvec.y); + lm.addAtIndex(14, tvec.z); + } + else { + lm.setTranslationFromFloats(tvec.x, tvec.y, tvec.z); + } + } + this._markAsDirtyAndDecompose(); + } + /** + * Translate the bone in local or world space + * @param vec The amount to translate the bone + * @param space The space that the translation is in (default: Space.LOCAL) + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + */ + translate(vec, space = 0 /* Space.LOCAL */, tNode) { + this._updatePosition(vec, space, tNode, true); + } + /** + * Set the position of the bone in local or world space + * @param position The position to set the bone + * @param space The space that the position is in (default: Space.LOCAL) + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + */ + setPosition(position, space = 0 /* Space.LOCAL */, tNode) { + this._updatePosition(position, space, tNode, false); + } + /** + * Set the absolute position of the bone (world space) + * @param position The position to set the bone + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + */ + setAbsolutePosition(position, tNode) { + this.setPosition(position, 1 /* Space.WORLD */, tNode); + } + /** + * Scale the bone on the x, y and z axes (in local space) + * @param x The amount to scale the bone on the x axis + * @param y The amount to scale the bone on the y axis + * @param z The amount to scale the bone on the z axis + * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default) + */ + scale(x, y, z, scaleChildren = false) { + const locMat = this.getLocalMatrix(); + // Apply new scaling on top of current local matrix + const scaleMat = Bone._TmpMats[0]; + Matrix.ScalingToRef(x, y, z, scaleMat); + scaleMat.multiplyToRef(locMat, locMat); + // Invert scaling matrix and apply the inverse to all children + scaleMat.invert(); + for (const child of this.children) { + const cm = child.getLocalMatrix(); + cm.multiplyToRef(scaleMat, cm); + cm.multiplyAtIndex(12, x); + cm.multiplyAtIndex(13, y); + cm.multiplyAtIndex(14, z); + child._markAsDirtyAndDecompose(); + } + this._markAsDirtyAndDecompose(); + if (scaleChildren) { + for (const child of this.children) { + child.scale(x, y, z, scaleChildren); + } + } + } + /** + * Set the bone scaling in local space + * @param scale defines the scaling vector + */ + setScale(scale) { + this._decompose(); + this._localScaling.copyFrom(scale); + this._markAsDirtyAndCompose(); + } + /** + * Gets the current scaling in local space + * @returns the current scaling vector + */ + getScale() { + this._decompose(); + return this._localScaling; + } + /** + * Gets the current scaling in local space and stores it in a target vector + * @param result defines the target vector + */ + getScaleToRef(result) { + this._decompose(); + result.copyFrom(this._localScaling); + } + /** + * Set the yaw, pitch, and roll of the bone in local or world space + * @param yaw The rotation of the bone on the y axis + * @param pitch The rotation of the bone on the x axis + * @param roll The rotation of the bone on the z axis + * @param space The space that the axes of rotation are in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + */ + setYawPitchRoll(yaw, pitch, roll, space = 0 /* Space.LOCAL */, tNode) { + if (space === 0 /* Space.LOCAL */) { + const quat = Bone._TmpQuat; + Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat); + this.setRotationQuaternion(quat, space, tNode); + return; + } + const rotMatInv = Bone._TmpMats[0]; + if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { + return; + } + const rotMat = Bone._TmpMats[1]; + Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat); + rotMatInv.multiplyToRef(rotMat, rotMat); + this._rotateWithMatrix(rotMat, space, tNode); + } + /** + * Add a rotation to the bone on an axis in local or world space + * @param axis The axis to rotate the bone on + * @param amount The amount to rotate the bone + * @param space The space that the axis is in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + */ + rotate(axis, amount, space = 0 /* Space.LOCAL */, tNode) { + const rmat = Bone._TmpMats[0]; + rmat.setTranslationFromFloats(0, 0, 0); + Matrix.RotationAxisToRef(axis, amount, rmat); + this._rotateWithMatrix(rmat, space, tNode); + } + /** + * Set the rotation of the bone to a particular axis angle in local or world space + * @param axis The axis to rotate the bone on + * @param angle The angle that the bone should be rotated to + * @param space The space that the axis is in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + */ + setAxisAngle(axis, angle, space = 0 /* Space.LOCAL */, tNode) { + if (space === 0 /* Space.LOCAL */) { + const quat = Bone._TmpQuat; + Quaternion.RotationAxisToRef(axis, angle, quat); + this.setRotationQuaternion(quat, space, tNode); + return; + } + const rotMatInv = Bone._TmpMats[0]; + if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { + return; + } + const rotMat = Bone._TmpMats[1]; + Matrix.RotationAxisToRef(axis, angle, rotMat); + rotMatInv.multiplyToRef(rotMat, rotMat); + this._rotateWithMatrix(rotMat, space, tNode); + } + /** + * Set the euler rotation of the bone in local or world space + * @param rotation The euler rotation that the bone should be set to + * @param space The space that the rotation is in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + */ + setRotation(rotation, space = 0 /* Space.LOCAL */, tNode) { + this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, tNode); + } + /** + * Set the quaternion rotation of the bone in local or world space + * @param quat The quaternion rotation that the bone should be set to + * @param space The space that the rotation is in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + */ + setRotationQuaternion(quat, space = 0 /* Space.LOCAL */, tNode) { + if (space === 0 /* Space.LOCAL */) { + this._decompose(); + this._localRotation.copyFrom(quat); + this._markAsDirtyAndCompose(); + return; + } + const rotMatInv = Bone._TmpMats[0]; + if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { + return; + } + const rotMat = Bone._TmpMats[1]; + Matrix.FromQuaternionToRef(quat, rotMat); + rotMatInv.multiplyToRef(rotMat, rotMat); + this._rotateWithMatrix(rotMat, space, tNode); + } + /** + * Set the rotation matrix of the bone in local or world space + * @param rotMat The rotation matrix that the bone should be set to + * @param space The space that the rotation is in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + */ + setRotationMatrix(rotMat, space = 0 /* Space.LOCAL */, tNode) { + if (space === 0 /* Space.LOCAL */) { + const quat = Bone._TmpQuat; + Quaternion.FromRotationMatrixToRef(rotMat, quat); + this.setRotationQuaternion(quat, space, tNode); + return; + } + const rotMatInv = Bone._TmpMats[0]; + if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { + return; + } + const rotMat2 = Bone._TmpMats[1]; + rotMat2.copyFrom(rotMat); + rotMatInv.multiplyToRef(rotMat, rotMat2); + this._rotateWithMatrix(rotMat2, space, tNode); + } + _rotateWithMatrix(rmat, space = 0 /* Space.LOCAL */, tNode) { + const lmat = this.getLocalMatrix(); + const lx = lmat.m[12]; + const ly = lmat.m[13]; + const lz = lmat.m[14]; + const parent = this.getParent(); + const parentScale = Bone._TmpMats[3]; + const parentScaleInv = Bone._TmpMats[4]; + if (parent && space == 1 /* Space.WORLD */) { + if (tNode) { + parentScale.copyFrom(tNode.getWorldMatrix()); + parent.getAbsoluteMatrix().multiplyToRef(parentScale, parentScale); + } + else { + parentScale.copyFrom(parent.getAbsoluteMatrix()); + } + parentScaleInv.copyFrom(parentScale); + parentScaleInv.invert(); + lmat.multiplyToRef(parentScale, lmat); + lmat.multiplyToRef(rmat, lmat); + lmat.multiplyToRef(parentScaleInv, lmat); + } + else { + if (space == 1 /* Space.WORLD */ && tNode) { + parentScale.copyFrom(tNode.getWorldMatrix()); + parentScaleInv.copyFrom(parentScale); + parentScaleInv.invert(); + lmat.multiplyToRef(parentScale, lmat); + lmat.multiplyToRef(rmat, lmat); + lmat.multiplyToRef(parentScaleInv, lmat); + } + else { + lmat.multiplyToRef(rmat, lmat); + } + } + lmat.setTranslationFromFloats(lx, ly, lz); + this.computeAbsoluteMatrices(); + this._markAsDirtyAndDecompose(); + } + _getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode) { + const scaleMatrix = Bone._TmpMats[2]; + rotMatInv.copyFrom(this.getAbsoluteMatrix()); + if (tNode) { + rotMatInv.multiplyToRef(tNode.getWorldMatrix(), rotMatInv); + Matrix.ScalingToRef(tNode.scaling.x, tNode.scaling.y, tNode.scaling.z, scaleMatrix); + } + else { + Matrix.IdentityToRef(scaleMatrix); + } + rotMatInv.invert(); + if (isNaN(rotMatInv.m[0])) { + // Matrix failed to invert. + // This can happen if scale is zero for example. + return false; + } + scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant); + rotMatInv.multiplyToRef(scaleMatrix, rotMatInv); + return true; + } + /** + * Get the position of the bone in local or world space + * @param space The space that the returned position is in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @returns The position of the bone + */ + getPosition(space = 0 /* Space.LOCAL */, tNode = null) { + const pos = Vector3.Zero(); + this.getPositionToRef(space, tNode, pos); + return pos; + } + /** + * Copy the position of the bone to a vector3 in local or world space + * @param space The space that the returned position is in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @param result The vector3 to copy the position to + */ + getPositionToRef(space = 0 /* Space.LOCAL */, tNode, result) { + if (space == 0 /* Space.LOCAL */) { + const lm = this.getLocalMatrix(); + result.x = lm.m[12]; + result.y = lm.m[13]; + result.z = lm.m[14]; + } + else { + let wm = null; + //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices() + if (tNode) { + wm = tNode.getWorldMatrix(); + } + this._skeleton.computeAbsoluteMatrices(); + let tmat = Bone._TmpMats[0]; + if (tNode && wm) { + tmat.copyFrom(this.getAbsoluteMatrix()); + tmat.multiplyToRef(wm, tmat); + } + else { + tmat = this.getAbsoluteMatrix(); + } + result.x = tmat.m[12]; + result.y = tmat.m[13]; + result.z = tmat.m[14]; + } + } + /** + * Get the absolute position of the bone (world space) + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @returns The absolute position of the bone + */ + getAbsolutePosition(tNode = null) { + const pos = Vector3.Zero(); + this.getPositionToRef(1 /* Space.WORLD */, tNode, pos); + return pos; + } + /** + * Copy the absolute position of the bone (world space) to the result param + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @param result The vector3 to copy the absolute position to + */ + getAbsolutePositionToRef(tNode, result) { + this.getPositionToRef(1 /* Space.WORLD */, tNode, result); + } + /** + * Compute the absolute matrices of this bone and its children + */ + computeAbsoluteMatrices() { + this._compose(); + if (this.parent) { + this._localMatrix.multiplyToRef(this.parent._absoluteMatrix, this._absoluteMatrix); + } + else { + this._absoluteMatrix.copyFrom(this._localMatrix); + const poseMatrix = this._skeleton.getPoseMatrix(); + if (poseMatrix) { + this._absoluteMatrix.multiplyToRef(poseMatrix, this._absoluteMatrix); + } + } + const children = this.children; + const len = children.length; + for (let i = 0; i < len; i++) { + children[i].computeAbsoluteMatrices(); + } + } + /** + * Compute the absolute matrices of this bone and its children + * @deprecated Please use computeAbsoluteMatrices instead + */ + computeAbsoluteTransforms() { + this.computeAbsoluteMatrices(); + } + /** + * Get the world direction from an axis that is in the local space of the bone + * @param localAxis The local direction that is used to compute the world direction + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @returns The world direction + */ + getDirection(localAxis, tNode = null) { + const result = Vector3.Zero(); + this.getDirectionToRef(localAxis, tNode, result); + return result; + } + /** + * Copy the world direction to a vector3 from an axis that is in the local space of the bone + * @param localAxis The local direction that is used to compute the world direction + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @param result The vector3 that the world direction will be copied to + */ + getDirectionToRef(localAxis, tNode = null, result) { + let wm = null; + //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices() + if (tNode) { + wm = tNode.getWorldMatrix(); + } + this._skeleton.computeAbsoluteMatrices(); + const mat = Bone._TmpMats[0]; + mat.copyFrom(this.getAbsoluteMatrix()); + if (tNode && wm) { + mat.multiplyToRef(wm, mat); + } + Vector3.TransformNormalToRef(localAxis, mat, result); + result.normalize(); + } + /** + * Get the euler rotation of the bone in local or world space + * @param space The space that the rotation should be in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @returns The euler rotation + */ + getRotation(space = 0 /* Space.LOCAL */, tNode = null) { + const result = Vector3.Zero(); + this.getRotationToRef(space, tNode, result); + return result; + } + /** + * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space + * @param space The space that the rotation should be in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @param result The vector3 that the rotation should be copied to + */ + getRotationToRef(space = 0 /* Space.LOCAL */, tNode = null, result) { + const quat = Bone._TmpQuat; + this.getRotationQuaternionToRef(space, tNode, quat); + quat.toEulerAnglesToRef(result); + } + /** + * Get the quaternion rotation of the bone in either local or world space + * @param space The space that the rotation should be in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @returns The quaternion rotation + */ + getRotationQuaternion(space = 0 /* Space.LOCAL */, tNode = null) { + const result = Quaternion.Identity(); + this.getRotationQuaternionToRef(space, tNode, result); + return result; + } + /** + * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space + * @param space The space that the rotation should be in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @param result The quaternion that the rotation should be copied to + */ + getRotationQuaternionToRef(space = 0 /* Space.LOCAL */, tNode = null, result) { + if (space == 0 /* Space.LOCAL */) { + this._decompose(); + result.copyFrom(this._localRotation); + } + else { + const mat = Bone._TmpMats[0]; + const amat = this.getAbsoluteMatrix(); + if (tNode) { + amat.multiplyToRef(tNode.getWorldMatrix(), mat); + } + else { + mat.copyFrom(amat); + } + mat.multiplyAtIndex(0, this._scalingDeterminant); + mat.multiplyAtIndex(1, this._scalingDeterminant); + mat.multiplyAtIndex(2, this._scalingDeterminant); + mat.decompose(undefined, result, undefined); + } + } + /** + * Get the rotation matrix of the bone in local or world space + * @param space The space that the rotation should be in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @returns The rotation matrix + */ + getRotationMatrix(space = 0 /* Space.LOCAL */, tNode) { + const result = Matrix.Identity(); + this.getRotationMatrixToRef(space, tNode, result); + return result; + } + /** + * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space + * @param space The space that the rotation should be in + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @param result The quaternion that the rotation should be copied to + */ + getRotationMatrixToRef(space = 0 /* Space.LOCAL */, tNode, result) { + if (space == 0 /* Space.LOCAL */) { + this.getLocalMatrix().getRotationMatrixToRef(result); + } + else { + const mat = Bone._TmpMats[0]; + const amat = this.getAbsoluteMatrix(); + if (tNode) { + amat.multiplyToRef(tNode.getWorldMatrix(), mat); + } + else { + mat.copyFrom(amat); + } + mat.multiplyAtIndex(0, this._scalingDeterminant); + mat.multiplyAtIndex(1, this._scalingDeterminant); + mat.multiplyAtIndex(2, this._scalingDeterminant); + mat.getRotationMatrixToRef(result); + } + } + /** + * Get the world position of a point that is in the local space of the bone + * @param position The local position + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @returns The world position + */ + getAbsolutePositionFromLocal(position, tNode = null) { + const result = Vector3.Zero(); + this.getAbsolutePositionFromLocalToRef(position, tNode, result); + return result; + } + /** + * Get the world position of a point that is in the local space of the bone and copy it to the result param + * @param position The local position + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @param result The vector3 that the world position should be copied to + */ + getAbsolutePositionFromLocalToRef(position, tNode = null, result) { + let wm = null; + //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices() + if (tNode) { + wm = tNode.getWorldMatrix(); + } + this._skeleton.computeAbsoluteMatrices(); + const tmat = Bone._TmpMats[0]; + tmat.copyFrom(this.getAbsoluteMatrix()); + if (tNode && wm) { + tmat.multiplyToRef(wm, tmat); + } + Vector3.TransformCoordinatesToRef(position, tmat, result); + } + /** + * Get the local position of a point that is in world space + * @param position The world position + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @returns The local position + */ + getLocalPositionFromAbsolute(position, tNode = null) { + const result = Vector3.Zero(); + this.getLocalPositionFromAbsoluteToRef(position, tNode, result); + return result; + } + /** + * Get the local position of a point that is in world space and copy it to the result param + * @param position The world position + * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD + * @param result The vector3 that the local position should be copied to + */ + getLocalPositionFromAbsoluteToRef(position, tNode = null, result) { + let wm = null; + //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices() + if (tNode) { + wm = tNode.getWorldMatrix(); + } + this._skeleton.computeAbsoluteMatrices(); + const tmat = Bone._TmpMats[0]; + tmat.copyFrom(this.getAbsoluteMatrix()); + if (tNode && wm) { + tmat.multiplyToRef(wm, tmat); + } + tmat.invert(); + Vector3.TransformCoordinatesToRef(position, tmat, result); + } + /** + * Set the current local matrix as the restMatrix for this bone. + */ + setCurrentPoseAsRest() { + this.setRestMatrix(this.getLocalMatrix()); + } + /** + * Releases associated resources + */ + dispose() { + this._linkedTransformNode = null; + const index = this._skeleton.bones.indexOf(this); + if (index !== -1) { + this._skeleton.bones.splice(index, 1); + } + if (this._parentNode && this._parentNode.children) { + const children = this._parentNode.children; + const index = children.indexOf(this); + if (index !== -1) { + children.splice(index, 1); + } + } + super.dispose(); + } +} +Bone._TmpVecs = BuildArray(2, Vector3.Zero); +Bone._TmpQuat = Quaternion.Identity(); +Bone._TmpMats = BuildArray(5, Matrix.Identity); + +/** + * Raw texture can help creating a texture directly from an array of data. + * This can be super useful if you either get the data from an uncompressed source or + * if you wish to create your texture pixel by pixel. + */ +class RawTexture extends Texture { + /** + * Instantiates a new RawTexture. + * Raw texture can help creating a texture directly from an array of data. + * This can be super useful if you either get the data from an uncompressed source or + * if you wish to create your texture pixel by pixel. + * @param data define the array of data to use to create the texture (null to create an empty texture) + * @param width define the width of the texture + * @param height define the height of the texture + * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx) + * @param sceneOrEngine defines the scene or engine the texture will belong to + * @param generateMipMaps define whether mip maps should be generated or not + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). + * @param waitDataToBeReady If set to true Rawtexture will wait data to be set in order to be flaged as ready. + */ + constructor(data, width, height, + /** + * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx) + */ + format, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags, useSRGBBuffer, waitDataToBeReady) { + super(null, sceneOrEngine, !generateMipMaps, invertY, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, creationFlags); + this.format = format; + if (!this._engine) { + return; + } + if (!this._engine._caps.textureFloatLinearFiltering && type === 1) { + samplingMode = 1; + } + if (!this._engine._caps.textureHalfFloatLinearFiltering && type === 2) { + samplingMode = 1; + } + this._texture = this._engine.createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type, creationFlags ?? 0, useSRGBBuffer ?? false); + this.wrapU = Texture.CLAMP_ADDRESSMODE; + this.wrapV = Texture.CLAMP_ADDRESSMODE; + this._waitingForData = !!waitDataToBeReady && !data; + } + /** + * Updates the texture underlying data. + * @param data Define the new data of the texture + */ + update(data) { + this._getEngine().updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type, this._texture._useSRGBBuffer); + this._waitingForData = false; + } + /** + * Clones the texture. + * @returns the cloned texture + */ + clone() { + if (!this._texture) { + return super.clone(); + } + const rawTexture = new RawTexture(null, this.getSize().width, this.getSize().height, this.format, this.getScene(), this._texture.generateMipMaps, this._invertY, this.samplingMode, this._texture.type, this._texture._creationFlags, this._useSRGBBuffer); + rawTexture._texture = this._texture; + this._texture.incrementReferences(); + return rawTexture; + } + isReady() { + return super.isReady() && !this._waitingForData; + } + /** + * Creates a luminance texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param sceneOrEngine defines the scene or engine the texture will belong to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @returns the luminance texture + */ + static CreateLuminanceTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) { + return new RawTexture(data, width, height, 1, sceneOrEngine, generateMipMaps, invertY, samplingMode); + } + /** + * Creates a luminance alpha texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param sceneOrEngine defines the scene or engine the texture will belong to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @returns the luminance alpha texture + */ + static CreateLuminanceAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) { + return new RawTexture(data, width, height, 2, sceneOrEngine, generateMipMaps, invertY, samplingMode); + } + /** + * Creates an alpha texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param sceneOrEngine defines the scene or engine the texture will belong to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @returns the alpha texture + */ + static CreateAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) { + return new RawTexture(data, width, height, 0, sceneOrEngine, generateMipMaps, invertY, samplingMode); + } + /** + * Creates a RGB texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param sceneOrEngine defines the scene or engine the texture will belong to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). + * @returns the RGB alpha texture + */ + static CreateRGBTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false) { + return new RawTexture(data, width, height, 4, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer); + } + /** + * Creates a RGBA texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param sceneOrEngine defines the scene or engine the texture will belong to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). + * @param waitDataToBeReady if set to true this will force texture to wait for data to be set before it is considered ready. + * @returns the RGBA texture + */ + static CreateRGBATexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false, waitDataToBeReady = false) { + return new RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer, waitDataToBeReady); + } + /** + * Creates a RGBA storage texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param sceneOrEngine defines the scene or engine the texture will belong to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). + * @returns the RGBA texture + */ + static CreateRGBAStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, useSRGBBuffer = false) { + return new RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1, useSRGBBuffer); + } + /** + * Creates a R texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param sceneOrEngine defines the scene or engine the texture will belong to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + * @returns the R texture + */ + static CreateRTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) { + return new RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type); + } + /** + * Creates a R storage texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param sceneOrEngine defines the scene or engine the texture will belong to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + * @returns the R texture + */ + static CreateRStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) { + return new RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1); + } +} + +/** + * Class used to handle skinning animations + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons + */ +class Skeleton { + /** + * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true). + * Please note that this option is not available if the hardware does not support it + */ + get useTextureToStoreBoneMatrices() { + return this._useTextureToStoreBoneMatrices; + } + set useTextureToStoreBoneMatrices(value) { + this._useTextureToStoreBoneMatrices = value; + this._markAsDirty(); + } + /** + * Gets or sets the animation properties override + */ + get animationPropertiesOverride() { + if (!this._animationPropertiesOverride) { + return this._scene.animationPropertiesOverride; + } + return this._animationPropertiesOverride; + } + set animationPropertiesOverride(value) { + this._animationPropertiesOverride = value; + } + /** + * Gets a boolean indicating that the skeleton effectively stores matrices into a texture + */ + get isUsingTextureForMatrices() { + return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones; + } + /** + * Gets the unique ID of this skeleton + */ + get uniqueId() { + return this._uniqueId; + } + /** + * Creates a new skeleton + * @param name defines the skeleton name + * @param id defines the skeleton Id + * @param scene defines the hosting scene + */ + constructor( + /** defines the skeleton name */ + name, + /** defines the skeleton Id */ + id, scene) { + this.name = name; + this.id = id; + /** + * Defines the list of child bones + */ + this.bones = []; + /** + * Defines a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value) + */ + this.needInitialSkinMatrix = false; + this._isDirty = true; + this._meshesWithPoseMatrix = new Array(); + this._identity = Matrix.Identity(); + this._currentRenderId = -1; + this._ranges = {}; + this._absoluteTransformIsDirty = true; + this._canUseTextureForBones = false; + this._uniqueId = 0; + /** @internal */ + this._numBonesWithLinkedTransformNode = 0; + /** @internal */ + this._hasWaitingData = null; + /** @internal */ + this._parentContainer = null; + /** + * Specifies if the skeleton should be serialized + */ + this.doNotSerialize = false; + this._useTextureToStoreBoneMatrices = true; + this._animationPropertiesOverride = null; + // Events + /** + * An observable triggered before computing the skeleton's matrices + */ + this.onBeforeComputeObservable = new Observable(); + this.bones = []; + this._scene = scene || EngineStore.LastCreatedScene; + this._uniqueId = this._scene.getUniqueId(); + this._scene.addSkeleton(this); + //make sure it will recalculate the matrix next time prepare is called. + this._isDirty = true; + const engineCaps = this._scene.getEngine().getCaps(); + this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0; + } + /** + * Gets the current object class name. + * @returns the class name + */ + getClassName() { + return "Skeleton"; + } + /** + * Returns an array containing the root bones + * @returns an array containing the root bones + */ + getChildren() { + return this.bones.filter((b) => !b.getParent()); + } + // Members + /** + * Gets the list of transform matrices to send to shaders (one matrix per bone) + * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true) + * @returns a Float32Array containing matrices data + */ + getTransformMatrices(mesh) { + if (this.needInitialSkinMatrix) { + if (!mesh) { + throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided"); + } + if (!mesh._bonesTransformMatrices) { + this.prepare(true); + } + return mesh._bonesTransformMatrices; + } + if (!this._transformMatrices || this._isDirty) { + this.prepare(!this._transformMatrices); + } + return this._transformMatrices; + } + /** + * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone) + * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true) + * @returns a raw texture containing the data + */ + getTransformMatrixTexture(mesh) { + if (this.needInitialSkinMatrix && mesh._transformMatrixTexture) { + return mesh._transformMatrixTexture; + } + return this._transformMatrixTexture; + } + /** + * Gets the current hosting scene + * @returns a scene object + */ + getScene() { + return this._scene; + } + // Methods + /** + * Gets a string representing the current skeleton data + * @param fullDetails defines a boolean indicating if we want a verbose version + * @returns a string representing the current skeleton data + */ + toString(fullDetails) { + let ret = `Name: ${this.name}, nBones: ${this.bones.length}`; + ret += `, nAnimationRanges: ${this._ranges ? Object.keys(this._ranges).length : "none"}`; + if (fullDetails) { + ret += ", Ranges: {"; + let first = true; + for (const name in this._ranges) { + if (first) { + ret += ", "; + first = false; + } + ret += name; + } + ret += "}"; + } + return ret; + } + /** + * Get bone's index searching by name + * @param name defines bone's name to search for + * @returns the indice of the bone. Returns -1 if not found + */ + getBoneIndexByName(name) { + for (let boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) { + if (this.bones[boneIndex].name === name) { + return boneIndex; + } + } + return -1; + } + /** + * Create a new animation range + * @param name defines the name of the range + * @param from defines the start key + * @param to defines the end key + */ + createAnimationRange(name, from, to) { + // check name not already in use + if (!this._ranges[name]) { + this._ranges[name] = new AnimationRange(name, from, to); + for (let i = 0, nBones = this.bones.length; i < nBones; i++) { + if (this.bones[i].animations[0]) { + this.bones[i].animations[0].createRange(name, from, to); + } + } + } + } + /** + * Delete a specific animation range + * @param name defines the name of the range + * @param deleteFrames defines if frames must be removed as well + */ + deleteAnimationRange(name, deleteFrames = true) { + for (let i = 0, nBones = this.bones.length; i < nBones; i++) { + if (this.bones[i].animations[0]) { + this.bones[i].animations[0].deleteRange(name, deleteFrames); + } + } + this._ranges[name] = null; // said much faster than 'delete this._range[name]' + } + /** + * Gets a specific animation range + * @param name defines the name of the range to look for + * @returns the requested animation range or null if not found + */ + getAnimationRange(name) { + return this._ranges[name] || null; + } + /** + * Gets the list of all animation ranges defined on this skeleton + * @returns an array + */ + getAnimationRanges() { + const animationRanges = []; + let name; + for (name in this._ranges) { + animationRanges.push(this._ranges[name]); + } + return animationRanges; + } + /** + * Copy animation range from a source skeleton. + * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences + * @param source defines the source skeleton + * @param name defines the name of the range to copy + * @param rescaleAsRequired defines if rescaling must be applied if required + * @returns true if operation was successful + */ + copyAnimationRange(source, name, rescaleAsRequired = false) { + if (this._ranges[name] || !source.getAnimationRange(name)) { + return false; + } + let ret = true; + const frameOffset = this._getHighestAnimationFrame() + 1; + // make a dictionary of source skeleton's bones, so exact same order or doubly nested loop is not required + const boneDict = {}; + const sourceBones = source.bones; + let nBones; + let i; + for (i = 0, nBones = sourceBones.length; i < nBones; i++) { + boneDict[sourceBones[i].name] = sourceBones[i]; + } + if (this.bones.length !== sourceBones.length) { + Logger.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${sourceBones.length}`); + ret = false; + } + const skelDimensionsRatio = rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null; + for (i = 0, nBones = this.bones.length; i < nBones; i++) { + const boneName = this.bones[i].name; + const sourceBone = boneDict[boneName]; + if (sourceBone) { + ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio); + } + else { + Logger.Warn("copyAnimationRange: not same rig, missing source bone " + boneName); + ret = false; + } + } + // do not call createAnimationRange(), since it also is done to bones, which was already done + const range = source.getAnimationRange(name); + if (range) { + this._ranges[name] = new AnimationRange(name, range.from + frameOffset, range.to + frameOffset); + } + return ret; + } + /** + * Forces the skeleton to go to rest pose + */ + returnToRest() { + for (const bone of this.bones) { + if (bone._index !== -1) { + bone.returnToRest(); + } + } + } + _getHighestAnimationFrame() { + let ret = 0; + for (let i = 0, nBones = this.bones.length; i < nBones; i++) { + if (this.bones[i].animations[0]) { + const highest = this.bones[i].animations[0].getHighestFrame(); + if (ret < highest) { + ret = highest; + } + } + } + return ret; + } + /** + * Begin a specific animation range + * @param name defines the name of the range to start + * @param loop defines if looping must be turned on (false by default) + * @param speedRatio defines the speed ratio to apply (1 by default) + * @param onAnimationEnd defines a callback which will be called when animation will end + * @returns a new animatable + */ + beginAnimation(name, loop, speedRatio, onAnimationEnd) { + const range = this.getAnimationRange(name); + if (!range) { + return null; + } + return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd); + } + /** + * Convert the keyframes for a range of animation on a skeleton to be relative to a given reference frame. + * @param skeleton defines the Skeleton containing the animation range to convert + * @param referenceFrame defines the frame that keyframes in the range will be relative to + * @param range defines the name of the AnimationRange belonging to the Skeleton to convert + * @returns the original skeleton + */ + static MakeAnimationAdditive(skeleton, referenceFrame = 0, range) { + const rangeValue = skeleton.getAnimationRange(range); + // We can't make a range additive if it doesn't exist + if (!rangeValue) { + return null; + } + // Find any current scene-level animatable belonging to the target that matches the range + const sceneAnimatables = skeleton._scene.getAllAnimatablesByTarget(skeleton); + let rangeAnimatable = null; + for (let index = 0; index < sceneAnimatables.length; index++) { + const sceneAnimatable = sceneAnimatables[index]; + if (sceneAnimatable.fromFrame === rangeValue?.from && sceneAnimatable.toFrame === rangeValue?.to) { + rangeAnimatable = sceneAnimatable; + break; + } + } + // Convert the animations belonging to the skeleton to additive keyframes + const animatables = skeleton.getAnimatables(); + for (let index = 0; index < animatables.length; index++) { + const animatable = animatables[index]; + const animations = animatable.animations; + if (!animations) { + continue; + } + for (let animIndex = 0; animIndex < animations.length; animIndex++) { + Animation.MakeAnimationAdditive(animations[animIndex], referenceFrame, range); + } + } + // Mark the scene-level animatable as additive + if (rangeAnimatable) { + rangeAnimatable.isAdditive = true; + } + return skeleton; + } + /** @internal */ + _markAsDirty() { + this._isDirty = true; + this._absoluteTransformIsDirty = true; + } + /** + * @internal + */ + _registerMeshWithPoseMatrix(mesh) { + this._meshesWithPoseMatrix.push(mesh); + } + /** + * @internal + */ + _unregisterMeshWithPoseMatrix(mesh) { + const index = this._meshesWithPoseMatrix.indexOf(mesh); + if (index > -1) { + this._meshesWithPoseMatrix.splice(index, 1); + } + } + _computeTransformMatrices(targetMatrix, initialSkinMatrix) { + this.onBeforeComputeObservable.notifyObservers(this); + for (let index = 0; index < this.bones.length; index++) { + const bone = this.bones[index]; + bone._childUpdateId++; + const parentBone = bone.getParent(); + if (parentBone) { + bone.getLocalMatrix().multiplyToRef(parentBone.getFinalMatrix(), bone.getFinalMatrix()); + } + else { + if (initialSkinMatrix) { + bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getFinalMatrix()); + } + else { + bone.getFinalMatrix().copyFrom(bone.getLocalMatrix()); + } + } + if (bone._index !== -1) { + const mappedIndex = bone._index === null ? index : bone._index; + bone.getAbsoluteInverseBindMatrix().multiplyToArray(bone.getFinalMatrix(), targetMatrix, mappedIndex * 16); + } + } + this._identity.copyToArray(targetMatrix, this.bones.length * 16); + } + /** + * Build all resources required to render a skeleton + * @param dontCheckFrameId defines a boolean indicating if prepare should be run without checking first the current frame id (default: false) + */ + prepare(dontCheckFrameId = false) { + if (!dontCheckFrameId) { + const currentRenderId = this.getScene().getRenderId(); + if (this._currentRenderId === currentRenderId) { + return; + } + this._currentRenderId = currentRenderId; + } + // Update the local matrix of bones with linked transform nodes. + if (this._numBonesWithLinkedTransformNode > 0) { + for (const bone of this.bones) { + if (bone._linkedTransformNode) { + const node = bone._linkedTransformNode; + bone.position = node.position; + if (node.rotationQuaternion) { + bone.rotationQuaternion = node.rotationQuaternion; + } + else { + bone.rotation = node.rotation; + } + bone.scaling = node.scaling; + } + } + } + if (this.needInitialSkinMatrix) { + for (const mesh of this._meshesWithPoseMatrix) { + const poseMatrix = mesh.getPoseMatrix(); + let needsUpdate = this._isDirty; + if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) { + mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1)); + needsUpdate = true; + } + if (!needsUpdate) { + continue; + } + if (this._synchronizedWithMesh !== mesh) { + this._synchronizedWithMesh = mesh; + // Prepare bones + for (const bone of this.bones) { + if (!bone.getParent()) { + const matrix = bone.getBindMatrix(); + matrix.multiplyToRef(poseMatrix, TmpVectors.Matrix[1]); + bone._updateAbsoluteBindMatrices(TmpVectors.Matrix[1]); + } + } + if (this.isUsingTextureForMatrices) { + const textureWidth = (this.bones.length + 1) * 4; + if (!mesh._transformMatrixTexture || mesh._transformMatrixTexture.getSize().width !== textureWidth) { + if (mesh._transformMatrixTexture) { + mesh._transformMatrixTexture.dispose(); + } + mesh._transformMatrixTexture = RawTexture.CreateRGBATexture(mesh._bonesTransformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1); + } + } + } + this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix); + if (this.isUsingTextureForMatrices && mesh._transformMatrixTexture) { + mesh._transformMatrixTexture.update(mesh._bonesTransformMatrices); + } + } + } + else { + if (!this._isDirty) { + return; + } + if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) { + this._transformMatrices = new Float32Array(16 * (this.bones.length + 1)); + if (this.isUsingTextureForMatrices) { + if (this._transformMatrixTexture) { + this._transformMatrixTexture.dispose(); + } + this._transformMatrixTexture = RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1); + } + } + this._computeTransformMatrices(this._transformMatrices, null); + if (this.isUsingTextureForMatrices && this._transformMatrixTexture) { + this._transformMatrixTexture.update(this._transformMatrices); + } + } + this._isDirty = false; + } + /** + * Gets the list of animatables currently running for this skeleton + * @returns an array of animatables + */ + getAnimatables() { + if (!this._animatables || this._animatables.length !== this.bones.length) { + this._animatables = []; + for (let index = 0; index < this.bones.length; index++) { + this._animatables.push(this.bones[index]); + } + } + return this._animatables; + } + /** + * Clone the current skeleton + * @param name defines the name of the new skeleton + * @param id defines the id of the new skeleton + * @returns the new skeleton + */ + clone(name, id) { + const result = new Skeleton(name, id || name, this._scene); + result.needInitialSkinMatrix = this.needInitialSkinMatrix; + for (let index = 0; index < this.bones.length; index++) { + const source = this.bones[index]; + let parentBone = null; + const parent = source.getParent(); + if (parent) { + const parentIndex = this.bones.indexOf(parent); + parentBone = result.bones[parentIndex]; + } + const bone = new Bone(source.name, result, parentBone, source.getBindMatrix().clone(), source.getRestMatrix().clone()); + bone._index = source._index; + if (source._linkedTransformNode) { + bone.linkTransformNode(source._linkedTransformNode); + } + DeepCopier.DeepCopy(source.animations, bone.animations); + } + if (this._ranges) { + result._ranges = {}; + for (const rangeName in this._ranges) { + const range = this._ranges[rangeName]; + if (range) { + result._ranges[rangeName] = range.clone(); + } + } + } + this._isDirty = true; + result.prepare(true); + return result; + } + /** + * Enable animation blending for this skeleton + * @param blendingSpeed defines the blending speed to apply + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending + */ + enableBlending(blendingSpeed = 0.01) { + this.bones.forEach((bone) => { + bone.animations.forEach((animation) => { + animation.enableBlending = true; + animation.blendingSpeed = blendingSpeed; + }); + }); + } + /** + * Releases all resources associated with the current skeleton + */ + dispose() { + this._meshesWithPoseMatrix.length = 0; + // Animations + this.getScene().stopAnimation(this); + // Remove from scene + this.getScene().removeSkeleton(this); + if (this._parentContainer) { + const index = this._parentContainer.skeletons.indexOf(this); + if (index > -1) { + this._parentContainer.skeletons.splice(index, 1); + } + this._parentContainer = null; + } + if (this._transformMatrixTexture) { + this._transformMatrixTexture.dispose(); + this._transformMatrixTexture = null; + } + } + /** + * Serialize the skeleton in a JSON object + * @returns a JSON object + */ + serialize() { + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.id = this.id; + if (this.dimensionsAtRest) { + serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray(); + } + serializationObject.bones = []; + serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix; + for (let index = 0; index < this.bones.length; index++) { + const bone = this.bones[index]; + const parent = bone.getParent(); + const serializedBone = { + parentBoneIndex: parent ? this.bones.indexOf(parent) : -1, + index: bone.getIndex(), + name: bone.name, + id: bone.id, + matrix: bone.getBindMatrix().asArray(), + rest: bone.getRestMatrix().asArray(), + linkedTransformNodeId: bone.getTransformNode()?.id, + }; + serializationObject.bones.push(serializedBone); + if (bone.length) { + serializedBone.length = bone.length; + } + if (bone.metadata) { + serializedBone.metadata = bone.metadata; + } + if (bone.animations && bone.animations.length > 0) { + serializedBone.animation = bone.animations[0].serialize(); + } + serializationObject.ranges = []; + for (const name in this._ranges) { + const source = this._ranges[name]; + if (!source) { + continue; + } + const range = {}; + range.name = name; + range.from = source.from; + range.to = source.to; + serializationObject.ranges.push(range); + } + } + return serializationObject; + } + /** + * Creates a new skeleton from serialized data + * @param parsedSkeleton defines the serialized data + * @param scene defines the hosting scene + * @returns a new skeleton + */ + static Parse(parsedSkeleton, scene) { + const skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene); + if (parsedSkeleton.dimensionsAtRest) { + skeleton.dimensionsAtRest = Vector3.FromArray(parsedSkeleton.dimensionsAtRest); + } + skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix; + let index; + for (index = 0; index < parsedSkeleton.bones.length; index++) { + const parsedBone = parsedSkeleton.bones[index]; + const parsedBoneIndex = parsedSkeleton.bones[index].index; + let parentBone = null; + if (parsedBone.parentBoneIndex > -1) { + parentBone = skeleton.bones[parsedBone.parentBoneIndex]; + } + const rest = parsedBone.rest ? Matrix.FromArray(parsedBone.rest) : null; + const bone = new Bone(parsedBone.name, skeleton, parentBone, Matrix.FromArray(parsedBone.matrix), rest, null, parsedBoneIndex); + if (parsedBone.id !== undefined && parsedBone.id !== null) { + bone.id = parsedBone.id; + } + if (parsedBone.length) { + bone.length = parsedBone.length; + } + if (parsedBone.metadata) { + bone.metadata = parsedBone.metadata; + } + if (parsedBone.animation) { + bone.animations.push(Animation.Parse(parsedBone.animation)); + } + if (parsedBone.linkedTransformNodeId !== undefined && parsedBone.linkedTransformNodeId !== null) { + skeleton._hasWaitingData = true; + bone._waitingTransformNodeId = parsedBone.linkedTransformNodeId; + } + } + // placed after bones, so createAnimationRange can cascade down + if (parsedSkeleton.ranges) { + for (index = 0; index < parsedSkeleton.ranges.length; index++) { + const data = parsedSkeleton.ranges[index]; + skeleton.createAnimationRange(data.name, data.from, data.to); + } + } + return skeleton; + } + /** + * Compute all node absolute matrices + * @param forceUpdate defines if computation must be done even if cache is up to date + */ + computeAbsoluteMatrices(forceUpdate = false) { + if (this._absoluteTransformIsDirty || forceUpdate) { + this.bones[0].computeAbsoluteMatrices(); + this._absoluteTransformIsDirty = false; + } + } + /** + * Compute all node absolute matrices + * @param forceUpdate defines if computation must be done even if cache is up to date + * @deprecated Please use computeAbsoluteMatrices instead + */ + computeAbsoluteTransforms(forceUpdate = false) { + this.computeAbsoluteMatrices(forceUpdate); + } + /** + * Gets the root pose matrix + * @returns a matrix + */ + getPoseMatrix() { + let poseMatrix = null; + if (this._meshesWithPoseMatrix.length > 0) { + poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix(); + } + return poseMatrix; + } + /** + * Sorts bones per internal index + */ + sortBones() { + const bones = []; + const visited = new Array(this.bones.length); + for (let index = 0; index < this.bones.length; index++) { + this._sortBones(index, bones, visited); + } + this.bones = bones; + } + _sortBones(index, bones, visited) { + if (visited[index]) { + return; + } + visited[index] = true; + const bone = this.bones[index]; + if (!bone) + return; + if (bone._index === undefined) { + bone._index = index; + } + const parentBone = bone.getParent(); + if (parentBone) { + this._sortBones(this.bones.indexOf(parentBone), bones, visited); + } + bones.push(bone); + } + /** + * Set the current local matrix as the restPose for all bones in the skeleton. + */ + setCurrentPoseAsRest() { + this.bones.forEach((b) => { + b.setCurrentPoseAsRest(); + }); + } +} + +/** + * Configuration needed for prepass-capable materials + */ +class PrePassConfiguration { + constructor() { + /** + * Previous world matrices of meshes carrying this material + * Used for computing velocity + */ + this.previousWorldMatrices = {}; + /** + * Previous bones of meshes carrying this material + * Used for computing velocity + */ + this.previousBones = {}; + } + /** + * Add the required uniforms to the current list. + * @param uniforms defines the current uniform list. + */ + static AddUniforms(uniforms) { + uniforms.push("previousWorld", "previousViewProjection", "mPreviousBones"); + } + /** + * Add the required samplers to the current list. + * @param samplers defines the current sampler list. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static AddSamplers(samplers) { + // pass + } + /** + * Binds the material data. + * @param effect defines the effect to update + * @param scene defines the scene the material belongs to. + * @param mesh The mesh + * @param world World matrix of this mesh + * @param isFrozen Is the material frozen + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + bindForSubMesh(effect, scene, mesh, world, isFrozen) { + if (scene.prePassRenderer && scene.prePassRenderer.enabled && scene.prePassRenderer.currentRTisSceneRT) { + if (scene.prePassRenderer.getIndex(2) !== -1 || + scene.prePassRenderer.getIndex(11) !== -1) { + if (!this.previousWorldMatrices[mesh.uniqueId]) { + this.previousWorldMatrices[mesh.uniqueId] = world.clone(); + } + if (!this.previousViewProjection) { + this.previousViewProjection = scene.getTransformMatrix().clone(); + this.currentViewProjection = scene.getTransformMatrix().clone(); + } + const engine = scene.getEngine(); + if (this.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) { + // First update of the prepass configuration for this rendering pass + this._lastUpdateFrameId = engine.frameId; + this.previousViewProjection.copyFrom(this.currentViewProjection); + this.currentViewProjection.copyFrom(scene.getTransformMatrix()); + } + else if (this._lastUpdateFrameId !== engine.frameId) { + // The scene transformation did not change from the previous frame (so no camera motion), we must update previousViewProjection accordingly + this._lastUpdateFrameId = engine.frameId; + this.previousViewProjection.copyFrom(this.currentViewProjection); + } + effect.setMatrix("previousWorld", this.previousWorldMatrices[mesh.uniqueId]); + effect.setMatrix("previousViewProjection", this.previousViewProjection); + this.previousWorldMatrices[mesh.uniqueId] = world.clone(); + } + } + } +} + +/** + * Manages the defines for the Material + */ +class MaterialDefines { + /** + * Creates a new instance + * @param externalProperties list of external properties to inject into the object + */ + constructor(externalProperties) { + /** @internal */ + this._keys = []; + this._isDirty = true; + /** @internal */ + this._areLightsDirty = true; + /** @internal */ + this._areLightsDisposed = false; + /** @internal */ + this._areAttributesDirty = true; + /** @internal */ + this._areTexturesDirty = true; + /** @internal */ + this._areFresnelDirty = true; + /** @internal */ + this._areMiscDirty = true; + /** @internal */ + this._arePrePassDirty = true; + /** @internal */ + this._areImageProcessingDirty = true; + /** @internal */ + this._normals = false; + /** @internal */ + this._uvs = false; + /** @internal */ + this._needNormals = false; + /** @internal */ + this._needUVs = false; + this._externalProperties = externalProperties; + // Initialize External Properties + if (externalProperties) { + for (const prop in externalProperties) { + if (Object.prototype.hasOwnProperty.call(externalProperties, prop)) { + this._setDefaultValue(prop); + } + } + } + } + /** + * Specifies if the material needs to be re-calculated + */ + get isDirty() { + return this._isDirty; + } + /** + * Marks the material to indicate that it has been re-calculated + */ + markAsProcessed() { + this._isDirty = false; + this._areAttributesDirty = false; + this._areTexturesDirty = false; + this._areFresnelDirty = false; + this._areLightsDirty = false; + this._areLightsDisposed = false; + this._areMiscDirty = false; + this._arePrePassDirty = false; + this._areImageProcessingDirty = false; + } + /** + * Marks the material to indicate that it needs to be re-calculated + */ + markAsUnprocessed() { + this._isDirty = true; + } + /** + * Marks the material to indicate all of its defines need to be re-calculated + */ + markAllAsDirty() { + this._areTexturesDirty = true; + this._areAttributesDirty = true; + this._areLightsDirty = true; + this._areFresnelDirty = true; + this._areMiscDirty = true; + this._arePrePassDirty = true; + this._areImageProcessingDirty = true; + this._isDirty = true; + } + /** + * Marks the material to indicate that image processing needs to be re-calculated + */ + markAsImageProcessingDirty() { + this._areImageProcessingDirty = true; + this._isDirty = true; + } + /** + * Marks the material to indicate the lights need to be re-calculated + * @param disposed Defines whether the light is dirty due to dispose or not + */ + markAsLightDirty(disposed = false) { + this._areLightsDirty = true; + this._areLightsDisposed = this._areLightsDisposed || disposed; + this._isDirty = true; + } + /** + * Marks the attribute state as changed + */ + markAsAttributesDirty() { + this._areAttributesDirty = true; + this._isDirty = true; + } + /** + * Marks the texture state as changed + */ + markAsTexturesDirty() { + this._areTexturesDirty = true; + this._isDirty = true; + } + /** + * Marks the fresnel state as changed + */ + markAsFresnelDirty() { + this._areFresnelDirty = true; + this._isDirty = true; + } + /** + * Marks the misc state as changed + */ + markAsMiscDirty() { + this._areMiscDirty = true; + this._isDirty = true; + } + /** + * Marks the prepass state as changed + */ + markAsPrePassDirty() { + this._arePrePassDirty = true; + this._isDirty = true; + } + /** + * Rebuilds the material defines + */ + rebuild() { + this._keys.length = 0; + for (const key of Object.keys(this)) { + if (key[0] === "_") { + continue; + } + this._keys.push(key); + } + if (this._externalProperties) { + for (const name in this._externalProperties) { + if (this._keys.indexOf(name) === -1) { + this._keys.push(name); + } + } + } + } + /** + * Specifies if two material defines are equal + * @param other - A material define instance to compare to + * @returns - Boolean indicating if the material defines are equal (true) or not (false) + */ + isEqual(other) { + if (this._keys.length !== other._keys.length) { + return false; + } + for (let index = 0; index < this._keys.length; index++) { + const prop = this._keys[index]; + if (this[prop] !== other[prop]) { + return false; + } + } + return true; + } + /** + * Clones this instance's defines to another instance + * @param other - material defines to clone values to + */ + cloneTo(other) { + if (this._keys.length !== other._keys.length) { + other._keys = this._keys.slice(0); + } + for (let index = 0; index < this._keys.length; index++) { + const prop = this._keys[index]; + other[prop] = this[prop]; + } + } + /** + * Resets the material define values + */ + reset() { + this._keys.forEach((prop) => this._setDefaultValue(prop)); + } + _setDefaultValue(prop) { + const type = this._externalProperties?.[prop]?.type ?? typeof this[prop]; + const defValue = this._externalProperties?.[prop]?.default; + switch (type) { + case "number": + this[prop] = defValue ?? 0; + break; + case "string": + this[prop] = defValue ?? ""; + break; + default: + this[prop] = defValue ?? false; + break; + } + } + /** + * Converts the material define values to a string + * @returns - String of material define information + */ + toString() { + let result = ""; + for (let index = 0; index < this._keys.length; index++) { + const prop = this._keys[index]; + const value = this[prop]; + const type = typeof value; + switch (type) { + case "number": + case "string": + result += "#define " + prop + " " + value + "\n"; + break; + default: + if (value) { + result += "#define " + prop + "\n"; + } + break; + } + } + return result; + } +} + +/** + * Base class of materials working in push mode in babylon JS + * @internal + */ +class PushMaterial extends Material { + constructor(name, scene, storeEffectOnSubMeshes = true, forceGLSL = false) { + super(name, scene, undefined, forceGLSL); + this._normalMatrix = new Matrix(); + this._storeEffectOnSubMeshes = storeEffectOnSubMeshes; + } + getEffect() { + return this._storeEffectOnSubMeshes ? this._activeEffect : super.getEffect(); + } + isReady(mesh, useInstances) { + if (!mesh) { + return false; + } + if (!this._storeEffectOnSubMeshes) { + return true; + } + if (!mesh.subMeshes || mesh.subMeshes.length === 0) { + return true; + } + return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances); + } + _isReadyForSubMesh(subMesh) { + const defines = subMesh.materialDefines; + if (!this.checkReadyOnEveryCall && subMesh.effect && defines) { + if (defines._renderId === this.getScene().getRenderId()) { + return true; + } + } + return false; + } + /** + * Binds the given world matrix to the active effect + * + * @param world the matrix to bind + */ + bindOnlyWorldMatrix(world) { + this._activeEffect.setMatrix("world", world); + } + /** + * Binds the given normal matrix to the active effect + * + * @param normalMatrix the matrix to bind + */ + bindOnlyNormalMatrix(normalMatrix) { + this._activeEffect.setMatrix("normalMatrix", normalMatrix); + } + bind(world, mesh) { + if (!mesh) { + return; + } + this.bindForSubMesh(world, mesh, mesh.subMeshes[0]); + } + _afterBind(mesh, effect = null, subMesh) { + super._afterBind(mesh, effect, subMesh); + this.getScene()._cachedEffect = effect; + if (subMesh) { + subMesh._drawWrapper._forceRebindOnNextCall = false; + } + else { + this._drawWrapper._forceRebindOnNextCall = false; + } + } + _mustRebind(scene, effect, subMesh, visibility = 1) { + return subMesh._drawWrapper._forceRebindOnNextCall || scene.isCachedMaterialInvalid(this, effect, visibility); + } + dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { + this._activeEffect = undefined; + super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh); + } +} + +/** + * This groups all the flags used to control the materials channel. + */ +class MaterialFlags { + /** + * Are diffuse textures enabled in the application. + */ + static get DiffuseTextureEnabled() { + return this._DiffuseTextureEnabled; + } + static set DiffuseTextureEnabled(value) { + if (this._DiffuseTextureEnabled === value) { + return; + } + this._DiffuseTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Is the OpenPBR Base Weight texture enabled in the application. + */ + static get BaseWeightTextureEnabled() { + return this._BaseWeightTextureEnabled; + } + static set BaseWeightTextureEnabled(value) { + if (this._BaseWeightTextureEnabled === value) { + return; + } + this._BaseWeightTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are detail textures enabled in the application. + */ + static get DetailTextureEnabled() { + return this._DetailTextureEnabled; + } + static set DetailTextureEnabled(value) { + if (this._DetailTextureEnabled === value) { + return; + } + this._DetailTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are decal maps enabled in the application. + */ + static get DecalMapEnabled() { + return this._DecalMapEnabled; + } + static set DecalMapEnabled(value) { + if (this._DecalMapEnabled === value) { + return; + } + this._DecalMapEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are ambient textures enabled in the application. + */ + static get AmbientTextureEnabled() { + return this._AmbientTextureEnabled; + } + static set AmbientTextureEnabled(value) { + if (this._AmbientTextureEnabled === value) { + return; + } + this._AmbientTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are opacity textures enabled in the application. + */ + static get OpacityTextureEnabled() { + return this._OpacityTextureEnabled; + } + static set OpacityTextureEnabled(value) { + if (this._OpacityTextureEnabled === value) { + return; + } + this._OpacityTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are reflection textures enabled in the application. + */ + static get ReflectionTextureEnabled() { + return this._ReflectionTextureEnabled; + } + static set ReflectionTextureEnabled(value) { + if (this._ReflectionTextureEnabled === value) { + return; + } + this._ReflectionTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are emissive textures enabled in the application. + */ + static get EmissiveTextureEnabled() { + return this._EmissiveTextureEnabled; + } + static set EmissiveTextureEnabled(value) { + if (this._EmissiveTextureEnabled === value) { + return; + } + this._EmissiveTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are specular textures enabled in the application. + */ + static get SpecularTextureEnabled() { + return this._SpecularTextureEnabled; + } + static set SpecularTextureEnabled(value) { + if (this._SpecularTextureEnabled === value) { + return; + } + this._SpecularTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are bump textures enabled in the application. + */ + static get BumpTextureEnabled() { + return this._BumpTextureEnabled; + } + static set BumpTextureEnabled(value) { + if (this._BumpTextureEnabled === value) { + return; + } + this._BumpTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are lightmap textures enabled in the application. + */ + static get LightmapTextureEnabled() { + return this._LightmapTextureEnabled; + } + static set LightmapTextureEnabled(value) { + if (this._LightmapTextureEnabled === value) { + return; + } + this._LightmapTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are refraction textures enabled in the application. + */ + static get RefractionTextureEnabled() { + return this._RefractionTextureEnabled; + } + static set RefractionTextureEnabled(value) { + if (this._RefractionTextureEnabled === value) { + return; + } + this._RefractionTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are color grading textures enabled in the application. + */ + static get ColorGradingTextureEnabled() { + return this._ColorGradingTextureEnabled; + } + static set ColorGradingTextureEnabled(value) { + if (this._ColorGradingTextureEnabled === value) { + return; + } + this._ColorGradingTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are fresnels enabled in the application. + */ + static get FresnelEnabled() { + return this._FresnelEnabled; + } + static set FresnelEnabled(value) { + if (this._FresnelEnabled === value) { + return; + } + this._FresnelEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(4); + } + /** + * Are clear coat textures enabled in the application. + */ + static get ClearCoatTextureEnabled() { + return this._ClearCoatTextureEnabled; + } + static set ClearCoatTextureEnabled(value) { + if (this._ClearCoatTextureEnabled === value) { + return; + } + this._ClearCoatTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are clear coat bump textures enabled in the application. + */ + static get ClearCoatBumpTextureEnabled() { + return this._ClearCoatBumpTextureEnabled; + } + static set ClearCoatBumpTextureEnabled(value) { + if (this._ClearCoatBumpTextureEnabled === value) { + return; + } + this._ClearCoatBumpTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are clear coat tint textures enabled in the application. + */ + static get ClearCoatTintTextureEnabled() { + return this._ClearCoatTintTextureEnabled; + } + static set ClearCoatTintTextureEnabled(value) { + if (this._ClearCoatTintTextureEnabled === value) { + return; + } + this._ClearCoatTintTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are sheen textures enabled in the application. + */ + static get SheenTextureEnabled() { + return this._SheenTextureEnabled; + } + static set SheenTextureEnabled(value) { + if (this._SheenTextureEnabled === value) { + return; + } + this._SheenTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are anisotropic textures enabled in the application. + */ + static get AnisotropicTextureEnabled() { + return this._AnisotropicTextureEnabled; + } + static set AnisotropicTextureEnabled(value) { + if (this._AnisotropicTextureEnabled === value) { + return; + } + this._AnisotropicTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are thickness textures enabled in the application. + */ + static get ThicknessTextureEnabled() { + return this._ThicknessTextureEnabled; + } + static set ThicknessTextureEnabled(value) { + if (this._ThicknessTextureEnabled === value) { + return; + } + this._ThicknessTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are refraction intensity textures enabled in the application. + */ + static get RefractionIntensityTextureEnabled() { + return this._ThicknessTextureEnabled; + } + static set RefractionIntensityTextureEnabled(value) { + if (this._RefractionIntensityTextureEnabled === value) { + return; + } + this._RefractionIntensityTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are translucency intensity textures enabled in the application. + */ + static get TranslucencyIntensityTextureEnabled() { + return this._TranslucencyIntensityTextureEnabled; + } + static set TranslucencyIntensityTextureEnabled(value) { + if (this._TranslucencyIntensityTextureEnabled === value) { + return; + } + this._TranslucencyIntensityTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are translucency tint textures enabled in the application. + */ + static get TranslucencyColorTextureEnabled() { + return this._TranslucencyColorTextureEnabled; + } + static set TranslucencyColorTextureEnabled(value) { + if (this._TranslucencyColorTextureEnabled === value) { + return; + } + this._TranslucencyColorTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } + /** + * Are translucency intensity textures enabled in the application. + */ + static get IridescenceTextureEnabled() { + return this._IridescenceTextureEnabled; + } + static set IridescenceTextureEnabled(value) { + if (this._IridescenceTextureEnabled === value) { + return; + } + this._IridescenceTextureEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(1); + } +} +// Flags used to enable or disable a type of texture for all Standard Materials +MaterialFlags._DiffuseTextureEnabled = true; +MaterialFlags._BaseWeightTextureEnabled = true; +MaterialFlags._DetailTextureEnabled = true; +MaterialFlags._DecalMapEnabled = true; +MaterialFlags._AmbientTextureEnabled = true; +MaterialFlags._OpacityTextureEnabled = true; +MaterialFlags._ReflectionTextureEnabled = true; +MaterialFlags._EmissiveTextureEnabled = true; +MaterialFlags._SpecularTextureEnabled = true; +MaterialFlags._BumpTextureEnabled = true; +MaterialFlags._LightmapTextureEnabled = true; +MaterialFlags._RefractionTextureEnabled = true; +MaterialFlags._ColorGradingTextureEnabled = true; +MaterialFlags._FresnelEnabled = true; +MaterialFlags._ClearCoatTextureEnabled = true; +MaterialFlags._ClearCoatBumpTextureEnabled = true; +MaterialFlags._ClearCoatTintTextureEnabled = true; +MaterialFlags._SheenTextureEnabled = true; +MaterialFlags._AnisotropicTextureEnabled = true; +MaterialFlags._ThicknessTextureEnabled = true; +MaterialFlags._RefractionIntensityTextureEnabled = true; +MaterialFlags._TranslucencyIntensityTextureEnabled = true; +MaterialFlags._TranslucencyColorTextureEnabled = true; +MaterialFlags._IridescenceTextureEnabled = true; + +const rxOption = new RegExp("^([gimus]+)!"); +/** + * Class that manages the plugins of a material + * @since 5.0 + */ +class MaterialPluginManager { + /** + * Creates a new instance of the plugin manager + * @param material material that this manager will manage the plugins for + */ + constructor(material) { + /** @internal */ + this._plugins = []; + this._activePlugins = []; + this._activePluginsForExtraEvents = []; + this._material = material; + this._scene = material.getScene(); + this._engine = this._scene.getEngine(); + } + /** + * @internal + */ + _addPlugin(plugin) { + for (let i = 0; i < this._plugins.length; ++i) { + if (this._plugins[i].name === plugin.name) { + return false; + } + } + if (this._material._uniformBufferLayoutBuilt) { + this._material.resetDrawCache(); + this._material._createUniformBuffer(); + } + if (!plugin.isCompatible(this._material.shaderLanguage)) { + // eslint-disable-next-line no-throw-literal + throw `The plugin "${plugin.name}" can't be added to the material "${this._material.name}" because the plugin is not compatible with the shader language of the material.`; + } + const pluginClassName = plugin.getClassName(); + if (!MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]) { + MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName] = "MATERIALPLUGIN_" + ++MaterialPluginManager._MaterialPluginCounter; + } + this._material._callbackPluginEventGeneric = (id, info) => this._handlePluginEvent(id, info); + this._plugins.push(plugin); + this._plugins.sort((a, b) => a.priority - b.priority); + this._codeInjectionPoints = {}; + const defineNamesFromPlugins = {}; + defineNamesFromPlugins[MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]] = { + type: "boolean", + default: true, + }; + for (const plugin of this._plugins) { + plugin.collectDefines(defineNamesFromPlugins); + this._collectPointNames("vertex", plugin.getCustomCode("vertex", this._material.shaderLanguage)); + this._collectPointNames("fragment", plugin.getCustomCode("fragment", this._material.shaderLanguage)); + } + this._defineNamesFromPlugins = defineNamesFromPlugins; + return true; + } + /** + * @internal + */ + _activatePlugin(plugin) { + if (this._activePlugins.indexOf(plugin) === -1) { + this._activePlugins.push(plugin); + this._activePlugins.sort((a, b) => a.priority - b.priority); + this._material._callbackPluginEventIsReadyForSubMesh = this._handlePluginEventIsReadyForSubMesh.bind(this); + this._material._callbackPluginEventPrepareDefinesBeforeAttributes = this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this); + this._material._callbackPluginEventPrepareDefines = this._handlePluginEventPrepareDefines.bind(this); + this._material._callbackPluginEventBindForSubMesh = this._handlePluginEventBindForSubMesh.bind(this); + if (plugin.registerForExtraEvents) { + this._activePluginsForExtraEvents.push(plugin); + this._activePluginsForExtraEvents.sort((a, b) => a.priority - b.priority); + this._material._callbackPluginEventHasRenderTargetTextures = this._handlePluginEventHasRenderTargetTextures.bind(this); + this._material._callbackPluginEventFillRenderTargetTextures = this._handlePluginEventFillRenderTargetTextures.bind(this); + this._material._callbackPluginEventHardBindForSubMesh = this._handlePluginEventHardBindForSubMesh.bind(this); + } + } + } + /** + * Gets a plugin from the list of plugins managed by this manager + * @param name name of the plugin + * @returns the plugin if found, else null + */ + getPlugin(name) { + for (let i = 0; i < this._plugins.length; ++i) { + if (this._plugins[i].name === name) { + return this._plugins[i]; + } + } + return null; + } + _handlePluginEventIsReadyForSubMesh(eventData) { + let isReady = true; + for (const plugin of this._activePlugins) { + isReady = isReady && plugin.isReadyForSubMesh(eventData.defines, this._scene, this._engine, eventData.subMesh); + } + eventData.isReadyForSubMesh = isReady; + } + _handlePluginEventPrepareDefinesBeforeAttributes(eventData) { + for (const plugin of this._activePlugins) { + plugin.prepareDefinesBeforeAttributes(eventData.defines, this._scene, eventData.mesh); + } + } + _handlePluginEventPrepareDefines(eventData) { + for (const plugin of this._activePlugins) { + plugin.prepareDefines(eventData.defines, this._scene, eventData.mesh); + } + } + _handlePluginEventHardBindForSubMesh(eventData) { + for (const plugin of this._activePluginsForExtraEvents) { + plugin.hardBindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh); + } + } + _handlePluginEventBindForSubMesh(eventData) { + for (const plugin of this._activePlugins) { + plugin.bindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh); + } + } + _handlePluginEventHasRenderTargetTextures(eventData) { + let hasRenderTargetTextures = false; + for (const plugin of this._activePluginsForExtraEvents) { + hasRenderTargetTextures = plugin.hasRenderTargetTextures(); + if (hasRenderTargetTextures) { + break; + } + } + eventData.hasRenderTargetTextures = hasRenderTargetTextures; + } + _handlePluginEventFillRenderTargetTextures(eventData) { + for (const plugin of this._activePluginsForExtraEvents) { + plugin.fillRenderTargetTextures(eventData.renderTargets); + } + } + _handlePluginEvent(id, info) { + switch (id) { + case 512 /* MaterialPluginEvent.GetActiveTextures */: { + const eventData = info; + for (const plugin of this._activePlugins) { + plugin.getActiveTextures(eventData.activeTextures); + } + break; + } + case 256 /* MaterialPluginEvent.GetAnimatables */: { + const eventData = info; + for (const plugin of this._activePlugins) { + plugin.getAnimatables(eventData.animatables); + } + break; + } + case 1024 /* MaterialPluginEvent.HasTexture */: { + const eventData = info; + let hasTexture = false; + for (const plugin of this._activePlugins) { + hasTexture = plugin.hasTexture(eventData.texture); + if (hasTexture) { + break; + } + } + eventData.hasTexture = hasTexture; + break; + } + case 2 /* MaterialPluginEvent.Disposed */: { + const eventData = info; + for (const plugin of this._plugins) { + plugin.dispose(eventData.forceDisposeTextures); + } + break; + } + case 4 /* MaterialPluginEvent.GetDefineNames */: { + const eventData = info; + eventData.defineNames = this._defineNamesFromPlugins; + break; + } + case 128 /* MaterialPluginEvent.PrepareEffect */: { + const eventData = info; + for (const plugin of this._activePlugins) { + eventData.fallbackRank = plugin.addFallbacks(eventData.defines, eventData.fallbacks, eventData.fallbackRank); + plugin.getAttributes(eventData.attributes, this._scene, eventData.mesh); + } + if (this._uniformList.length > 0) { + eventData.uniforms.push(...this._uniformList); + } + if (this._samplerList.length > 0) { + eventData.samplers.push(...this._samplerList); + } + if (this._uboList.length > 0) { + eventData.uniformBuffersNames.push(...this._uboList); + } + eventData.customCode = this._injectCustomCode(eventData, eventData.customCode); + break; + } + case 8 /* MaterialPluginEvent.PrepareUniformBuffer */: { + const eventData = info; + this._uboDeclaration = ""; + this._vertexDeclaration = ""; + this._fragmentDeclaration = ""; + this._uniformList = []; + this._samplerList = []; + this._uboList = []; + const isWebGPU = this._material.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + for (const plugin of this._plugins) { + const uniforms = plugin.getUniforms(this._material.shaderLanguage); + if (uniforms) { + if (uniforms.ubo) { + for (const uniform of uniforms.ubo) { + if (uniform.size && uniform.type) { + const arraySize = uniform.arraySize ?? 0; + eventData.ubo.addUniform(uniform.name, uniform.size, arraySize); + if (isWebGPU) { + let type; + switch (uniform.type) { + case "mat4": + type = "mat4x4f"; + break; + case "float": + type = "f32"; + break; + default: + type = `${uniform.type}f`; + break; + } + this._uboDeclaration += `uniform ${uniform.name}: ${type}${arraySize > 0 ? `[${arraySize}]` : ""};\n`; + } + else { + this._uboDeclaration += `${uniform.type} ${uniform.name}${arraySize > 0 ? `[${arraySize}]` : ""};\n`; + } + } + this._uniformList.push(uniform.name); + } + } + if (uniforms.vertex) { + this._vertexDeclaration += uniforms.vertex + "\n"; + } + if (uniforms.fragment) { + this._fragmentDeclaration += uniforms.fragment + "\n"; + } + } + plugin.getSamplers(this._samplerList); + plugin.getUniformBuffersNames(this._uboList); + } + break; + } + } + } + _collectPointNames(shaderType, customCode) { + if (!customCode) { + return; + } + for (const pointName in customCode) { + if (!this._codeInjectionPoints[shaderType]) { + this._codeInjectionPoints[shaderType] = {}; + } + this._codeInjectionPoints[shaderType][pointName] = true; + } + } + _injectCustomCode(eventData, existingCallback) { + return (shaderType, code) => { + if (existingCallback) { + code = existingCallback(shaderType, code); + } + if (this._uboDeclaration) { + code = code.replace("#define ADDITIONAL_UBO_DECLARATION", this._uboDeclaration); + } + if (this._vertexDeclaration) { + code = code.replace("#define ADDITIONAL_VERTEX_DECLARATION", this._vertexDeclaration); + } + if (this._fragmentDeclaration) { + code = code.replace("#define ADDITIONAL_FRAGMENT_DECLARATION", this._fragmentDeclaration); + } + const points = this._codeInjectionPoints?.[shaderType]; + if (!points) { + return code; + } + let processorOptions = null; + for (let pointName in points) { + let injectedCode = ""; + for (const plugin of this._activePlugins) { + let customCode = plugin.getCustomCode(shaderType, this._material.shaderLanguage)?.[pointName]; + if (!customCode) { + continue; + } + if (plugin.resolveIncludes) { + if (processorOptions === null) { + const shaderLanguage = 0 /* ShaderLanguage.GLSL */; + processorOptions = { + defines: [], // not used by _ProcessIncludes + indexParameters: eventData.indexParameters, + isFragment: false, + shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader, + processor: undefined, // not used by _ProcessIncludes + supportsUniformBuffers: this._engine.supportsUniformBuffers, + shadersRepository: ShaderStore.GetShadersRepository(shaderLanguage), + includesShadersStore: ShaderStore.GetIncludesShadersStore(shaderLanguage), + version: undefined, // not used by _ProcessIncludes + platformName: this._engine.shaderPlatformName, + processingContext: undefined, // not used by _ProcessIncludes + isNDCHalfZRange: this._engine.isNDCHalfZRange, + useReverseDepthBuffer: this._engine.useReverseDepthBuffer, + processCodeAfterIncludes: undefined, // not used by _ProcessIncludes + }; + } + processorOptions.isFragment = shaderType === "fragment"; + _ProcessIncludes(customCode, processorOptions, (code) => (customCode = code)); + } + injectedCode += customCode + "\n"; + } + if (injectedCode.length > 0) { + if (pointName.charAt(0) === "!") { + // pointName is a regular expression + pointName = pointName.substring(1); + let regexFlags = "g"; + if (pointName.charAt(0) === "!") { + // no flags + regexFlags = ""; + pointName = pointName.substring(1); + } + else { + // get the flag(s) + const matchOption = rxOption.exec(pointName); + if (matchOption && matchOption.length >= 2) { + regexFlags = matchOption[1]; + pointName = pointName.substring(regexFlags.length + 1); + } + } + if (regexFlags.indexOf("g") < 0) { + // we force the "g" flag so that the regexp object is stateful! + regexFlags += "g"; + } + const sourceCode = code; + const rx = new RegExp(pointName, regexFlags); + let match = rx.exec(sourceCode); + while (match !== null) { + let newCode = injectedCode; + for (let i = 0; i < match.length; ++i) { + newCode = newCode.replace("$" + i, match[i]); + } + code = code.replace(match[0], newCode); + match = rx.exec(sourceCode); + } + } + else { + const fullPointName = "#define " + pointName; + code = code.replace(fullPointName, "\n" + injectedCode + "\n" + fullPointName); + } + } + } + return code; + }; + } +} +/** Map a plugin class name to a #define name (used in the vertex/fragment shaders as a marker of the plugin usage) */ +MaterialPluginManager._MaterialPluginClassToMainDefine = {}; +MaterialPluginManager._MaterialPluginCounter = 0; +(() => { + EngineStore.OnEnginesDisposedObservable.add(() => { + UnregisterAllMaterialPlugins(); + }); +})(); +const plugins = []; +let inited = false; +let observer = null; +/** + * Registers a new material plugin through a factory, or updates it. This makes the plugin available to all materials instantiated after its registration. + * @param pluginName The plugin name + * @param factory The factory function which allows to create the plugin + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function RegisterMaterialPlugin(pluginName, factory) { + if (!inited) { + observer = Material.OnEventObservable.add((material) => { + for (const [, factory] of plugins) { + factory(material); + } + }, 1 /* MaterialPluginEvent.Created */); + inited = true; + } + const existing = plugins.filter(([name, _factory]) => name === pluginName); + if (existing.length > 0) { + existing[0][1] = factory; + } + else { + plugins.push([pluginName, factory]); + } +} +/** + * Clear the list of global material plugins + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function UnregisterAllMaterialPlugins() { + plugins.length = 0; + inited = false; + Material.OnEventObservable.remove(observer); + observer = null; +} + +/** + * Base class for material plugins. + * @since 5.0 + */ +class MaterialPluginBase { + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @param shaderLanguage The shader language to use. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible(shaderLanguage) { + switch (shaderLanguage) { + case 0 /* ShaderLanguage.GLSL */: + return true; + default: + return false; + } + } + _enable(enable) { + if (enable) { + this._pluginManager._activatePlugin(this); + } + } + /** + * Creates a new material plugin + * @param material parent material of the plugin + * @param name name of the plugin + * @param priority priority of the plugin + * @param defines list of defines used by the plugin. The value of the property is the default value for this property + * @param addToPluginList true to add the plugin to the list of plugins managed by the material plugin manager of the material (default: true) + * @param enable true to enable the plugin (it is handy if the plugin does not handle properties to switch its current activation) + * @param resolveIncludes Indicates that any #include directive in the plugin code must be replaced by the corresponding code (default: false) + */ + constructor(material, name, priority, defines, addToPluginList = true, enable = false, resolveIncludes = false) { + /** + * Defines the priority of the plugin. Lower numbers run first. + */ + this.priority = 500; + /** + * Indicates that any #include directive in the plugin code must be replaced by the corresponding code. + */ + this.resolveIncludes = false; + /** + * Indicates that this plugin should be notified for the extra events (HasRenderTargetTextures / FillRenderTargetTextures / HardBindForSubMesh) + */ + this.registerForExtraEvents = false; + /** + * Specifies if the material plugin should be serialized, `true` to skip serialization + */ + this.doNotSerialize = false; + this._material = material; + this.name = name; + this.priority = priority; + this.resolveIncludes = resolveIncludes; + if (!material.pluginManager) { + material.pluginManager = new MaterialPluginManager(material); + material.onDisposeObservable.add(() => { + material.pluginManager = undefined; + }); + } + this._pluginDefineNames = defines; + this._pluginManager = material.pluginManager; + if (addToPluginList) { + this._pluginManager._addPlugin(this); + } + if (enable) { + this._enable(true); + } + this.markAllDefinesAsDirty = material._dirtyCallbacks[127]; + } + /** + * Gets the current class name useful for serialization or dynamic coding. + * @returns The class name. + */ + getClassName() { + return "MaterialPluginBase"; + } + /** + * Specifies that the submesh is ready to be used. + * @param _defines the list of "defines" to update. + * @param _scene defines the scene the material belongs to. + * @param _engine the engine this scene belongs to. + * @param _subMesh the submesh to check for readiness + * @returns - boolean indicating that the submesh is ready or not. + */ + isReadyForSubMesh(_defines, _scene, _engine, _subMesh) { + return true; + } + /** + * Binds the material data (this function is called even if mustRebind() returns false) + * @param _uniformBuffer defines the Uniform buffer to fill in. + * @param _scene defines the scene the material belongs to. + * @param _engine defines the engine the material belongs to. + * @param _subMesh the submesh to bind data for + */ + hardBindForSubMesh(_uniformBuffer, _scene, _engine, _subMesh) { } + /** + * Binds the material data. + * @param _uniformBuffer defines the Uniform buffer to fill in. + * @param _scene defines the scene the material belongs to. + * @param _engine the engine this scene belongs to. + * @param _subMesh the submesh to bind data for + */ + bindForSubMesh(_uniformBuffer, _scene, _engine, _subMesh) { } + /** + * Disposes the resources of the material. + * @param _forceDisposeTextures - Forces the disposal of all textures. + */ + dispose(_forceDisposeTextures) { } + /** + * Returns a list of custom shader code fragments to customize the shader. + * @param _shaderType "vertex" or "fragment" + * @param _shaderLanguage The shader language to use. + * @returns null if no code to be added, or a list of pointName =\> code. + * Note that `pointName` can also be a regular expression if it starts with a `!`. + * In that case, the string found by the regular expression (if any) will be + * replaced by the code provided. + */ + getCustomCode(_shaderType, _shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + return null; + } + /** + * Collects all defines. + * @param defines The object to append to. + */ + collectDefines(defines) { + if (!this._pluginDefineNames) { + return; + } + for (const key of Object.keys(this._pluginDefineNames)) { + if (key[0] === "_") { + continue; + } + const type = typeof this._pluginDefineNames[key]; + defines[key] = { + type: type === "number" ? "number" : type === "string" ? "string" : type === "boolean" ? "boolean" : "object", + default: this._pluginDefineNames[key], + }; + } + } + /** + * Sets the defines for the next rendering. Called before PrepareDefinesForAttributes is called. + * @param _defines the list of "defines" to update. + * @param _scene defines the scene to the material belongs to. + * @param _mesh the mesh being rendered + */ + prepareDefinesBeforeAttributes(_defines, _scene, _mesh) { } + /** + * Sets the defines for the next rendering + * @param _defines the list of "defines" to update. + * @param _scene defines the scene to the material belongs to. + * @param _mesh the mesh being rendered + */ + prepareDefines(_defines, _scene, _mesh) { } + /** + * Checks to see if a texture is used in the material. + * @param _texture - Base texture to use. + * @returns - Boolean specifying if a texture is used in the material. + */ + hasTexture(_texture) { + return false; + } + /** + * Gets a boolean indicating that current material needs to register RTT + * @returns true if this uses a render target otherwise false. + */ + hasRenderTargetTextures() { + return false; + } + /** + * Fills the list of render target textures. + * @param _renderTargets the list of render targets to update + */ + fillRenderTargetTextures(_renderTargets) { } + /** + * Returns an array of the actively used textures. + * @param _activeTextures Array of BaseTextures + */ + getActiveTextures(_activeTextures) { } + /** + * Returns the animatable textures. + * @param _animatables Array of animatable textures. + */ + getAnimatables(_animatables) { } + /** + * Add fallbacks to the effect fallbacks list. + * @param defines defines the Base texture to use. + * @param fallbacks defines the current fallback list. + * @param currentRank defines the current fallback rank. + * @returns the new fallback rank. + */ + addFallbacks(defines, fallbacks, currentRank) { + return currentRank; + } + /** + * Gets the samplers used by the plugin. + * @param _samplers list that the sampler names should be added to. + */ + getSamplers(_samplers) { } + /** + * Gets the attributes used by the plugin. + * @param _attributes list that the attribute names should be added to. + * @param _scene the scene that the material belongs to. + * @param _mesh the mesh being rendered. + */ + getAttributes(_attributes, _scene, _mesh) { } + /** + * Gets the uniform buffers names added by the plugin. + * @param _ubos list that the ubo names should be added to. + */ + getUniformBuffersNames(_ubos) { } + /** + * Gets the description of the uniforms to add to the ubo (if engine supports ubos) or to inject directly in the vertex/fragment shaders (if engine does not support ubos) + * @param _shaderLanguage The shader language to use. + * @returns the description of the uniforms + */ + getUniforms(_shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + return {}; + } + /** + * Makes a duplicate of the current configuration into another one. + * @param plugin define the config where to copy the info + */ + copyTo(plugin) { + SerializationHelper.Clone(() => plugin, this); + } + /** + * Serializes this plugin configuration. + * @returns - An object with the serialized config. + */ + serialize() { + return SerializationHelper.Serialize(this); + } + /** + * Parses a plugin configuration from a serialized object. + * @param source - Serialized object. + * @param scene Defines the scene we are parsing for + * @param rootUrl Defines the rootUrl to load from + */ + parse(source, scene, rootUrl) { + SerializationHelper.Parse(() => this, source, scene, rootUrl); + } +} +__decorate([ + serialize() +], MaterialPluginBase.prototype, "name", void 0); +__decorate([ + serialize() +], MaterialPluginBase.prototype, "priority", void 0); +__decorate([ + serialize() +], MaterialPluginBase.prototype, "resolveIncludes", void 0); +__decorate([ + serialize() +], MaterialPluginBase.prototype, "registerForExtraEvents", void 0); +// Register Class Name +RegisterClass("BABYLON.MaterialPluginBase", MaterialPluginBase); + +/** + * @internal + */ +class MaterialDetailMapDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.DETAIL = false; + this.DETAILDIRECTUV = 0; + this.DETAIL_NORMALBLENDMETHOD = 0; + } +} +/** + * Plugin that implements the detail map component of a material + * + * Inspired from: + * Unity: https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@9.0/manual/Mask-Map-and-Detail-Map.html and https://docs.unity3d.com/Manual/StandardShaderMaterialParameterDetail.html + * Unreal: https://docs.unrealengine.com/en-US/Engine/Rendering/Materials/HowTo/DetailTexturing/index.html + * Cryengine: https://docs.cryengine.com/display/SDKDOC2/Detail+Maps + */ +class DetailMapConfiguration extends MaterialPluginBase { + /** @internal */ + _markAllSubMeshesAsTexturesDirty() { + this._enable(this._isEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + constructor(material, addToPluginList = true) { + super(material, "DetailMap", 140, new MaterialDetailMapDefines(), addToPluginList); + this._texture = null; + /** + * Defines how strongly the detail diffuse/albedo channel is blended with the regular diffuse/albedo texture + * Bigger values mean stronger blending + */ + this.diffuseBlendLevel = 1; + /** + * Defines how strongly the detail roughness channel is blended with the regular roughness value + * Bigger values mean stronger blending. Only used with PBR materials + */ + this.roughnessBlendLevel = 1; + /** + * Defines how strong the bump effect from the detail map is + * Bigger values mean stronger effect + */ + this.bumpLevel = 1; + this._normalBlendMethod = Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT; + this._isEnabled = false; + /** + * Enable or disable the detail map on this material + */ + this.isEnabled = false; + this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; + } + isReadyForSubMesh(defines, scene, engine) { + if (!this._isEnabled) { + return true; + } + if (defines._areTexturesDirty && scene.texturesEnabled) { + if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled) { + // Detail texture cannot be not blocking. + if (!this._texture.isReady()) { + return false; + } + } + } + return true; + } + prepareDefines(defines, scene) { + if (this._isEnabled) { + defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod; + const engine = scene.getEngine(); + if (defines._areTexturesDirty) { + if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled && this._isEnabled) { + PrepareDefinesForMergedUV(this._texture, defines, "DETAIL"); + defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod; + } + else { + defines.DETAIL = false; + } + } + } + else { + defines.DETAIL = false; + } + } + bindForSubMesh(uniformBuffer, scene) { + if (!this._isEnabled) { + return; + } + const isFrozen = this._material.isFrozen; + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + if (this._texture && MaterialFlags.DetailTextureEnabled) { + uniformBuffer.updateFloat4("vDetailInfos", this._texture.coordinatesIndex, this.diffuseBlendLevel, this.bumpLevel, this.roughnessBlendLevel); + BindTextureMatrix(this._texture, uniformBuffer, "detail"); + } + } + // Textures + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.DetailTextureEnabled) { + uniformBuffer.setTexture("detailSampler", this._texture); + } + } + } + hasTexture(texture) { + if (this._texture === texture) { + return true; + } + return false; + } + getActiveTextures(activeTextures) { + if (this._texture) { + activeTextures.push(this._texture); + } + } + getAnimatables(animatables) { + if (this._texture && this._texture.animations && this._texture.animations.length > 0) { + animatables.push(this._texture); + } + } + dispose(forceDisposeTextures) { + if (forceDisposeTextures) { + this._texture?.dispose(); + } + } + getClassName() { + return "DetailMapConfiguration"; + } + getSamplers(samplers) { + samplers.push("detailSampler"); + } + getUniforms() { + return { + ubo: [ + { name: "vDetailInfos", size: 4, type: "vec4" }, + { name: "detailMatrix", size: 16, type: "mat4" }, + ], + }; + } +} +__decorate([ + serializeAsTexture("detailTexture"), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], DetailMapConfiguration.prototype, "texture", void 0); +__decorate([ + serialize() +], DetailMapConfiguration.prototype, "diffuseBlendLevel", void 0); +__decorate([ + serialize() +], DetailMapConfiguration.prototype, "roughnessBlendLevel", void 0); +__decorate([ + serialize() +], DetailMapConfiguration.prototype, "bumpLevel", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], DetailMapConfiguration.prototype, "normalBlendMethod", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], DetailMapConfiguration.prototype, "isEnabled", void 0); + +/** + * Type of clear operation to perform on a geometry texture. + */ +var GeometryRenderingTextureClearType; +(function (GeometryRenderingTextureClearType) { + /** + * Clear the texture with zero. + */ + GeometryRenderingTextureClearType[GeometryRenderingTextureClearType["Zero"] = 0] = "Zero"; + /** + * Clear the texture with one. + */ + GeometryRenderingTextureClearType[GeometryRenderingTextureClearType["One"] = 1] = "One"; + /** + * Clear the texture with the maximum view Z value. + */ + GeometryRenderingTextureClearType[GeometryRenderingTextureClearType["MaxViewZ"] = 2] = "MaxViewZ"; +})(GeometryRenderingTextureClearType || (GeometryRenderingTextureClearType = {})); +/** + * Helper class to manage geometry rendering. + */ +class MaterialHelperGeometryRendering { + /** + * Creates a new geometry rendering configuration. + * @param renderPassId Render pass id the configuration is created for. + * @returns The created configuration. + */ + static CreateConfiguration(renderPassId) { + MaterialHelperGeometryRendering._Configurations[renderPassId] = { + defines: {}, + previousWorldMatrices: {}, + previousViewProjection: Matrix.Zero(), + currentViewProjection: Matrix.Zero(), + previousBones: {}, + lastUpdateFrameId: -1, + excludedSkinnedMesh: [], + reverseCulling: false, + }; + return MaterialHelperGeometryRendering._Configurations[renderPassId]; + } + /** + * Deletes a geometry rendering configuration. + * @param renderPassId The render pass id of the configuration to delete. + */ + static DeleteConfiguration(renderPassId) { + delete MaterialHelperGeometryRendering._Configurations[renderPassId]; + } + /** + * Gets a geometry rendering configuration. + * @param renderPassId The render pass id of the configuration to get. + * @returns The configuration. + */ + static GetConfiguration(renderPassId) { + return MaterialHelperGeometryRendering._Configurations[renderPassId]; + } + /** + * Adds uniforms and samplers for geometry rendering. + * @param uniforms The array of uniforms to add to. + * @param _samplers The array of samplers to add to. + */ + static AddUniformsAndSamplers(uniforms, _samplers) { + uniforms.push("previousWorld", "previousViewProjection", "mPreviousBones"); + } + /** + * Marks a list of meshes as dirty for geometry rendering. + * @param renderPassId The render pass id the meshes are marked as dirty for. + * @param meshes The list of meshes to mark as dirty. + */ + static MarkAsDirty(renderPassId, meshes) { + for (const mesh of meshes) { + if (!mesh.subMeshes) { + continue; + } + for (const subMesh of mesh.subMeshes) { + subMesh._removeDrawWrapper(renderPassId); + } + } + } + /** + * Prepares defines for geometry rendering. + * @param renderPassId The render pass id the defines are prepared for. + * @param mesh The mesh the defines are prepared for. + * @param defines The defines to update according to the geometry rendering configuration. + */ + static PrepareDefines(renderPassId, mesh, defines) { + if (!defines._arePrePassDirty) { + return; + } + const configuration = MaterialHelperGeometryRendering._Configurations[renderPassId]; + if (!configuration) { + return; + } + defines["PREPASS"] = true; + defines["PREPASS_COLOR"] = false; + defines["PREPASS_COLOR_INDEX"] = -1; + let numMRT = 0; + for (let i = 0; i < MaterialHelperGeometryRendering.GeometryTextureDescriptions.length; i++) { + const geometryTextureDescription = MaterialHelperGeometryRendering.GeometryTextureDescriptions[i]; + const defineName = geometryTextureDescription.define; + const defineIndex = geometryTextureDescription.defineIndex; + const index = configuration.defines[defineIndex]; + if (index !== undefined) { + defines[defineName] = true; + defines[defineIndex] = index; + numMRT++; + } + else { + defines[defineName] = false; + delete defines[defineIndex]; + } + } + defines["SCENE_MRT_COUNT"] = numMRT; + defines["BONES_VELOCITY_ENABLED"] = + mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton && !mesh.skeleton.isUsingTextureForMatrices && configuration.excludedSkinnedMesh.indexOf(mesh) === -1; + } + /** + * Binds geometry rendering data for a mesh. + * @param renderPassId The render pass id the geometry rendering data is bound for. + * @param effect The effect to bind the geometry rendering data to. + * @param mesh The mesh to bind the geometry rendering data for. + * @param world The world matrix of the mesh. + * @param material The material of the mesh. + */ + static Bind(renderPassId, effect, mesh, world, material) { + const configuration = MaterialHelperGeometryRendering._Configurations[renderPassId]; + if (!configuration) { + return; + } + const scene = mesh.getScene(); + const engine = scene.getEngine(); + if (configuration.reverseCulling) { + engine.setStateCullFaceType(scene._mirroredCameraPosition ? material.cullBackFaces : !material.cullBackFaces); + } + if (configuration.defines["PREPASS_VELOCITY_INDEX"] !== undefined || configuration.defines["PREPASS_VELOCITY_LINEAR_INDEX"] !== undefined) { + if (!configuration.previousWorldMatrices[mesh.uniqueId]) { + configuration.previousWorldMatrices[mesh.uniqueId] = world.clone(); + } + if (!configuration.previousViewProjection) { + configuration.previousViewProjection = scene.getTransformMatrix().clone(); + configuration.currentViewProjection = scene.getTransformMatrix().clone(); + } + if (configuration.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) { + // First update of the prepass configuration for this rendering pass + configuration.lastUpdateFrameId = engine.frameId; + configuration.previousViewProjection.copyFrom(configuration.currentViewProjection); + configuration.currentViewProjection.copyFrom(scene.getTransformMatrix()); + } + else if (configuration.lastUpdateFrameId !== engine.frameId) { + // The scene transformation did not change from the previous frame (so no camera motion), we must update previousViewProjection accordingly + configuration.lastUpdateFrameId = engine.frameId; + configuration.previousViewProjection.copyFrom(configuration.currentViewProjection); + } + effect.setMatrix("previousWorld", configuration.previousWorldMatrices[mesh.uniqueId]); + effect.setMatrix("previousViewProjection", configuration.previousViewProjection); + configuration.previousWorldMatrices[mesh.uniqueId] = world.clone(); + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + const skeleton = mesh.skeleton; + if (!skeleton.isUsingTextureForMatrices || effect.getUniformIndex("boneTextureWidth") === -1) { + const matrices = skeleton.getTransformMatrices(mesh); + if (matrices) { + if (!configuration.previousBones[mesh.uniqueId]) { + configuration.previousBones[mesh.uniqueId] = matrices.slice(); + } + effect.setMatrices("mPreviousBones", configuration.previousBones[mesh.uniqueId]); + configuration.previousBones[mesh.uniqueId].set(matrices); + } + } + } + } + } +} +/** + * Descriptions of the geometry textures. + */ +MaterialHelperGeometryRendering.GeometryTextureDescriptions = [ + { + type: 0, + name: "Irradiance", + clearType: 0 /* GeometryRenderingTextureClearType.Zero */, + define: "PREPASS_IRRADIANCE", + defineIndex: "PREPASS_IRRADIANCE_INDEX", + }, + { + type: 1, + name: "WorldPosition", + clearType: 0 /* GeometryRenderingTextureClearType.Zero */, + define: "PREPASS_POSITION", + defineIndex: "PREPASS_POSITION_INDEX", + }, + { + type: 2, + name: "Velocity", + clearType: 0 /* GeometryRenderingTextureClearType.Zero */, + define: "PREPASS_VELOCITY", + defineIndex: "PREPASS_VELOCITY_INDEX", + }, + { + type: 3, + name: "Reflectivity", + clearType: 0 /* GeometryRenderingTextureClearType.Zero */, + define: "PREPASS_REFLECTIVITY", + defineIndex: "PREPASS_REFLECTIVITY_INDEX", + }, + { + type: 5, + name: "ViewDepth", + clearType: 2 /* GeometryRenderingTextureClearType.MaxViewZ */, + define: "PREPASS_DEPTH", + defineIndex: "PREPASS_DEPTH_INDEX", + }, + { + type: 6, + name: "ViewNormal", + clearType: 0 /* GeometryRenderingTextureClearType.Zero */, + define: "PREPASS_NORMAL", + defineIndex: "PREPASS_NORMAL_INDEX", + }, + { + type: 7, + name: "AlbedoSqrt", + clearType: 0 /* GeometryRenderingTextureClearType.Zero */, + define: "PREPASS_ALBEDO_SQRT", + defineIndex: "PREPASS_ALBEDO_SQRT_INDEX", + }, + { + type: 8, + name: "WorldNormal", + clearType: 0 /* GeometryRenderingTextureClearType.Zero */, + define: "PREPASS_WORLD_NORMAL", + defineIndex: "PREPASS_WORLD_NORMAL_INDEX", + }, + { + type: 9, + name: "LocalPosition", + clearType: 0 /* GeometryRenderingTextureClearType.Zero */, + define: "PREPASS_LOCAL_POSITION", + defineIndex: "PREPASS_LOCAL_POSITION_INDEX", + }, + { + type: 10, + name: "ScreenDepth", + clearType: 1 /* GeometryRenderingTextureClearType.One */, + define: "PREPASS_SCREENSPACE_DEPTH", + defineIndex: "PREPASS_SCREENSPACE_DEPTH_INDEX", + }, + { + type: 11, + name: "LinearVelocity", + clearType: 0 /* GeometryRenderingTextureClearType.Zero */, + define: "PREPASS_VELOCITY_LINEAR", + defineIndex: "PREPASS_VELOCITY_LINEAR_INDEX", + }, + { + type: 12, + name: "Albedo", + clearType: 0 /* GeometryRenderingTextureClearType.Zero */, + define: "PREPASS_ALBEDO", + defineIndex: "PREPASS_ALBEDO_INDEX", + }, +]; +MaterialHelperGeometryRendering._Configurations = {}; + +const onCreatedEffectParameters$3 = { effect: null, subMesh: null }; +/** @internal */ +class StandardMaterialDefines extends MaterialDefines { + /** + * Initializes the Standard Material defines. + * @param externalProperties The external properties + */ + constructor(externalProperties) { + super(externalProperties); + this.MAINUV1 = false; + this.MAINUV2 = false; + this.MAINUV3 = false; + this.MAINUV4 = false; + this.MAINUV5 = false; + this.MAINUV6 = false; + this.DIFFUSE = false; + this.DIFFUSEDIRECTUV = 0; + this.BAKED_VERTEX_ANIMATION_TEXTURE = false; + this.AMBIENT = false; + this.AMBIENTDIRECTUV = 0; + this.OPACITY = false; + this.OPACITYDIRECTUV = 0; + this.OPACITYRGB = false; + this.REFLECTION = false; + this.EMISSIVE = false; + this.EMISSIVEDIRECTUV = 0; + this.SPECULAR = false; + this.SPECULARDIRECTUV = 0; + this.BUMP = false; + this.BUMPDIRECTUV = 0; + this.PARALLAX = false; + this.PARALLAX_RHS = false; + this.PARALLAXOCCLUSION = false; + this.SPECULAROVERALPHA = false; + this.CLIPPLANE = false; + this.CLIPPLANE2 = false; + this.CLIPPLANE3 = false; + this.CLIPPLANE4 = false; + this.CLIPPLANE5 = false; + this.CLIPPLANE6 = false; + this.ALPHATEST = false; + this.DEPTHPREPASS = false; + this.ALPHAFROMDIFFUSE = false; + this.POINTSIZE = false; + this.FOG = false; + this.SPECULARTERM = false; + this.DIFFUSEFRESNEL = false; + this.OPACITYFRESNEL = false; + this.REFLECTIONFRESNEL = false; + this.REFRACTIONFRESNEL = false; + this.EMISSIVEFRESNEL = false; + this.FRESNEL = false; + this.NORMAL = false; + this.TANGENT = false; + this.UV1 = false; + this.UV2 = false; + this.UV3 = false; + this.UV4 = false; + this.UV5 = false; + this.UV6 = false; + this.VERTEXCOLOR = false; + this.VERTEXALPHA = false; + this.NUM_BONE_INFLUENCERS = 0; + this.BonesPerMesh = 0; + this.BONETEXTURE = false; + this.BONES_VELOCITY_ENABLED = false; + this.INSTANCES = false; + this.THIN_INSTANCES = false; + this.INSTANCESCOLOR = false; + this.GLOSSINESS = false; + this.ROUGHNESS = false; + this.EMISSIVEASILLUMINATION = false; + this.LINKEMISSIVEWITHDIFFUSE = false; + this.REFLECTIONFRESNELFROMSPECULAR = false; + this.LIGHTMAP = false; + this.LIGHTMAPDIRECTUV = 0; + this.OBJECTSPACE_NORMALMAP = false; + this.USELIGHTMAPASSHADOWMAP = false; + this.REFLECTIONMAP_3D = false; + this.REFLECTIONMAP_SPHERICAL = false; + this.REFLECTIONMAP_PLANAR = false; + this.REFLECTIONMAP_CUBIC = false; + this.USE_LOCAL_REFLECTIONMAP_CUBIC = false; + this.USE_LOCAL_REFRACTIONMAP_CUBIC = false; + this.REFLECTIONMAP_PROJECTION = false; + this.REFLECTIONMAP_SKYBOX = false; + this.REFLECTIONMAP_EXPLICIT = false; + this.REFLECTIONMAP_EQUIRECTANGULAR = false; + this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + this.REFLECTIONMAP_OPPOSITEZ = false; + this.INVERTCUBICMAP = false; + this.LOGARITHMICDEPTH = false; + this.REFRACTION = false; + this.REFRACTIONMAP_3D = false; + this.REFLECTIONOVERALPHA = false; + this.TWOSIDEDLIGHTING = false; + this.SHADOWFLOAT = false; + this.MORPHTARGETS = false; + this.MORPHTARGETS_POSITION = false; + this.MORPHTARGETS_NORMAL = false; + this.MORPHTARGETS_TANGENT = false; + this.MORPHTARGETS_UV = false; + this.MORPHTARGETS_UV2 = false; + this.MORPHTARGETS_COLOR = false; + this.MORPHTARGETTEXTURE_HASPOSITIONS = false; + this.MORPHTARGETTEXTURE_HASNORMALS = false; + this.MORPHTARGETTEXTURE_HASTANGENTS = false; + this.MORPHTARGETTEXTURE_HASUVS = false; + this.MORPHTARGETTEXTURE_HASUV2S = false; + this.MORPHTARGETTEXTURE_HASCOLORS = false; + this.NUM_MORPH_INFLUENCERS = 0; + this.MORPHTARGETS_TEXTURE = false; + this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH + this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7 + this.ALPHATEST_AFTERALLALPHACOMPUTATIONS = false; + this.ALPHABLEND = true; + this.PREPASS = false; + this.PREPASS_COLOR = false; + this.PREPASS_COLOR_INDEX = -1; + this.PREPASS_IRRADIANCE = false; + this.PREPASS_IRRADIANCE_INDEX = -1; + this.PREPASS_ALBEDO = false; + this.PREPASS_ALBEDO_INDEX = -1; + this.PREPASS_ALBEDO_SQRT = false; + this.PREPASS_ALBEDO_SQRT_INDEX = -1; + this.PREPASS_DEPTH = false; + this.PREPASS_DEPTH_INDEX = -1; + this.PREPASS_SCREENSPACE_DEPTH = false; + this.PREPASS_SCREENSPACE_DEPTH_INDEX = -1; + this.PREPASS_NORMAL = false; + this.PREPASS_NORMAL_INDEX = -1; + this.PREPASS_NORMAL_WORLDSPACE = false; + this.PREPASS_WORLD_NORMAL = false; + this.PREPASS_WORLD_NORMAL_INDEX = -1; + this.PREPASS_POSITION = false; + this.PREPASS_POSITION_INDEX = -1; + this.PREPASS_LOCAL_POSITION = false; + this.PREPASS_LOCAL_POSITION_INDEX = -1; + this.PREPASS_VELOCITY = false; + this.PREPASS_VELOCITY_INDEX = -1; + this.PREPASS_VELOCITY_LINEAR = false; + this.PREPASS_VELOCITY_LINEAR_INDEX = -1; + this.PREPASS_REFLECTIVITY = false; + this.PREPASS_REFLECTIVITY_INDEX = -1; + this.SCENE_MRT_COUNT = 0; + this.RGBDLIGHTMAP = false; + this.RGBDREFLECTION = false; + this.RGBDREFRACTION = false; + this.IMAGEPROCESSING = false; + this.VIGNETTE = false; + this.VIGNETTEBLENDMODEMULTIPLY = false; + this.VIGNETTEBLENDMODEOPAQUE = false; + this.TONEMAPPING = 0; + this.CONTRAST = false; + this.COLORCURVES = false; + this.COLORGRADING = false; + this.COLORGRADING3D = false; + this.SAMPLER3DGREENDEPTH = false; + this.SAMPLER3DBGRMAP = false; + this.DITHER = false; + this.IMAGEPROCESSINGPOSTPROCESS = false; + this.SKIPFINALCOLORCLAMP = false; + this.MULTIVIEW = false; + this.ORDER_INDEPENDENT_TRANSPARENCY = false; + this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false; + this.CAMERA_ORTHOGRAPHIC = false; + this.CAMERA_PERSPECTIVE = false; + this.AREALIGHTSUPPORTED = true; + /** + * If the reflection texture on this material is in linear color space + * @internal + */ + this.IS_REFLECTION_LINEAR = false; + /** + * If the refraction texture on this material is in linear color space + * @internal + */ + this.IS_REFRACTION_LINEAR = false; + this.EXPOSURE = false; + this.DECAL_AFTER_DETAIL = false; + this.rebuild(); + } + setReflectionMode(modeToEnable) { + const modes = [ + "REFLECTIONMAP_CUBIC", + "REFLECTIONMAP_EXPLICIT", + "REFLECTIONMAP_PLANAR", + "REFLECTIONMAP_PROJECTION", + "REFLECTIONMAP_PROJECTION", + "REFLECTIONMAP_SKYBOX", + "REFLECTIONMAP_SPHERICAL", + "REFLECTIONMAP_EQUIRECTANGULAR", + "REFLECTIONMAP_EQUIRECTANGULAR_FIXED", + "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED", + ]; + for (const mode of modes) { + this[mode] = mode === modeToEnable; + } + } +} +/** + * This is the default material used in Babylon. It is the best trade off between quality + * and performances. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction + */ +class StandardMaterial extends PushMaterial { + /** + * Gets the image processing configuration used either in this material. + */ + get imageProcessingConfiguration() { + return this._imageProcessingConfiguration; + } + /** + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ + set imageProcessingConfiguration(value) { + this._attachImageProcessingConfiguration(value); + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + } + /** + * Attaches a new image processing configuration to the Standard Material. + * @param configuration + */ + _attachImageProcessingConfiguration(configuration) { + if (configuration === this._imageProcessingConfiguration) { + return; + } + // Detaches observer + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + // Pick the scene configuration if needed + if (!configuration) { + this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; + } + else { + this._imageProcessingConfiguration = configuration; + } + // Attaches observer + if (this._imageProcessingConfiguration) { + this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { + this._markAllSubMeshesAsImageProcessingDirty(); + }); + } + } + /** + * Can this material render to prepass + */ + get isPrePassCapable() { + return !this.disableDepthWrite; + } + /** + * Gets whether the color curves effect is enabled. + */ + get cameraColorCurvesEnabled() { + return this.imageProcessingConfiguration.colorCurvesEnabled; + } + /** + * Sets whether the color curves effect is enabled. + */ + set cameraColorCurvesEnabled(value) { + this.imageProcessingConfiguration.colorCurvesEnabled = value; + } + /** + * Gets whether the color grading effect is enabled. + */ + get cameraColorGradingEnabled() { + return this.imageProcessingConfiguration.colorGradingEnabled; + } + /** + * Gets whether the color grading effect is enabled. + */ + set cameraColorGradingEnabled(value) { + this.imageProcessingConfiguration.colorGradingEnabled = value; + } + /** + * Gets whether tonemapping is enabled or not. + */ + get cameraToneMappingEnabled() { + return this._imageProcessingConfiguration.toneMappingEnabled; + } + /** + * Sets whether tonemapping is enabled or not + */ + set cameraToneMappingEnabled(value) { + this._imageProcessingConfiguration.toneMappingEnabled = value; + } + /** + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ + get cameraExposure() { + return this._imageProcessingConfiguration.exposure; + } + /** + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ + set cameraExposure(value) { + this._imageProcessingConfiguration.exposure = value; + } + /** + * Gets The camera contrast used on this material. + */ + get cameraContrast() { + return this._imageProcessingConfiguration.contrast; + } + /** + * Sets The camera contrast used on this material. + */ + set cameraContrast(value) { + this._imageProcessingConfiguration.contrast = value; + } + /** + * Gets the Color Grading 2D Lookup Texture. + */ + get cameraColorGradingTexture() { + return this._imageProcessingConfiguration.colorGradingTexture; + } + /** + * Sets the Color Grading 2D Lookup Texture. + */ + set cameraColorGradingTexture(value) { + this._imageProcessingConfiguration.colorGradingTexture = value; + } + /** + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ + get cameraColorCurves() { + return this._imageProcessingConfiguration.colorCurves; + } + /** + * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ + set cameraColorCurves(value) { + this._imageProcessingConfiguration.colorCurves = value; + } + /** + * Can this material render to several textures at once + */ + get canRenderToMRT() { + return true; + } + /** + * Instantiates a new standard material. + * This is the default material used in Babylon. It is the best trade off between quality + * and performances. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction + * @param name Define the name of the material in the scene + * @param scene Define the scene the material belong to + * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false + */ + constructor(name, scene, forceGLSL = false) { + super(name, scene, undefined, forceGLSL || StandardMaterial.ForceGLSL); + this._diffuseTexture = null; + this._ambientTexture = null; + this._opacityTexture = null; + this._reflectionTexture = null; + this._emissiveTexture = null; + this._specularTexture = null; + this._bumpTexture = null; + this._lightmapTexture = null; + this._refractionTexture = null; + /** + * The color of the material lit by the environmental background lighting. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#ambient-color-example + */ + this.ambientColor = new Color3(0, 0, 0); + /** + * The basic color of the material as viewed under a light. + */ + this.diffuseColor = new Color3(1, 1, 1); + /** + * Define how the color and intensity of the highlight given by the light in the material. + */ + this.specularColor = new Color3(1, 1, 1); + /** + * Define the color of the material as if self lit. + * This will be mixed in the final result even in the absence of light. + */ + this.emissiveColor = new Color3(0, 0, 0); + /** + * Defines how sharp are the highlights in the material. + * The bigger the value the sharper giving a more glossy feeling to the result. + * Reversely, the smaller the value the blurrier giving a more rough feeling to the result. + */ + this.specularPower = 64; + this._useAlphaFromDiffuseTexture = false; + this._useEmissiveAsIllumination = false; + this._linkEmissiveWithDiffuse = false; + this._useSpecularOverAlpha = false; + this._useReflectionOverAlpha = false; + this._disableLighting = false; + this._useObjectSpaceNormalMap = false; + this._useParallax = false; + this._useParallaxOcclusion = false; + /** + * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion. + */ + this.parallaxScaleBias = 0.05; + this._roughness = 0; + /** + * In case of refraction, define the value of the index of refraction. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#how-to-obtain-reflections-and-refractions + */ + this.indexOfRefraction = 0.98; + /** + * Invert the refraction texture alongside the y axis. + * It can be useful with procedural textures or probe for instance. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#how-to-obtain-reflections-and-refractions + */ + this.invertRefractionY = true; + /** + * Defines the alpha limits in alpha test mode. + */ + this.alphaCutOff = 0.4; + this._useLightmapAsShadowmap = false; + this._useReflectionFresnelFromSpecular = false; + this._useGlossinessFromSpecularMapAlpha = false; + this._maxSimultaneousLights = 4; + this._invertNormalMapX = false; + this._invertNormalMapY = false; + this._twoSidedLighting = false; + this._applyDecalMapAfterDetailMap = false; + this._shadersLoaded = false; + this._renderTargets = new SmartArray(16); + this._globalAmbientColor = new Color3(0, 0, 0); + this._cacheHasRenderTargetTextures = false; + this.detailMap = new DetailMapConfiguration(this); + // Setup the default processing configuration to the scene. + this._attachImageProcessingConfiguration(null); + this.prePassConfiguration = new PrePassConfiguration(); + this.getRenderTargetTextures = () => { + this._renderTargets.reset(); + if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + this._renderTargets.push(this._reflectionTexture); + } + if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { + this._renderTargets.push(this._refractionTexture); + } + this._eventInfo.renderTargets = this._renderTargets; + this._callbackPluginEventFillRenderTargetTextures(this._eventInfo); + return this._renderTargets; + }; + } + /** + * Gets a boolean indicating that current material needs to register RTT + */ + get hasRenderTargetTextures() { + if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + return true; + } + if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { + return true; + } + return this._cacheHasRenderTargetTextures; + } + /** + * Gets the current class name of the material e.g. "StandardMaterial" + * Mainly use in serialization. + * @returns the class name + */ + getClassName() { + return "StandardMaterial"; + } + /** + * Specifies if the material will require alpha blending + * @returns a boolean specifying if alpha blending is needed + */ + needAlphaBlending() { + if (this._hasTransparencyMode) { + return this._transparencyModeIsBlend; + } + if (this._disableAlphaBlending) { + return false; + } + return (this.alpha < 1.0 || + this._opacityTexture != null || + this._shouldUseAlphaFromDiffuseTexture() || + (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled)); + } + /** + * Specifies if this material should be rendered in alpha test mode + * @returns a boolean specifying if an alpha test is needed. + */ + needAlphaTesting() { + if (this._hasTransparencyMode) { + return this._transparencyModeIsTest; + } + return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === Material.MATERIAL_ALPHATEST); + } + /** + * @returns whether or not the alpha value of the diffuse texture should be used for alpha blending. + */ + _shouldUseAlphaFromDiffuseTexture() { + return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture && this._transparencyMode !== Material.MATERIAL_OPAQUE; + } + /** + * @returns whether or not there is a usable alpha channel for transparency. + */ + _hasAlphaChannel() { + return (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._opacityTexture != null; + } + /** + * Get the texture used for alpha test purpose. + * @returns the diffuse texture in case of the standard material. + */ + getAlphaTestTexture() { + return this._diffuseTexture; + } + /** + * Get if the submesh is ready to be used and all its information available. + * Child classes can use it to update shaders + * @param mesh defines the mesh to check + * @param subMesh defines which submesh to check + * @param useInstances specifies that instances should be used + * @returns a boolean indicating that the submesh is ready or not + */ + isReadyForSubMesh(mesh, subMesh, useInstances = false) { + if (!this._uniformBufferLayoutBuilt) { + this.buildUniformLayout(); + } + const drawWrapper = subMesh._drawWrapper; + if (drawWrapper.effect && this.isFrozen) { + if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) { + return true; + } + } + if (!subMesh.materialDefines) { + this._callbackPluginEventGeneric(4 /* MaterialPluginEvent.GetDefineNames */, this._eventInfo); + subMesh.materialDefines = new StandardMaterialDefines(this._eventInfo.defineNames); + } + const scene = this.getScene(); + const defines = subMesh.materialDefines; + if (this._isReadyForSubMesh(subMesh)) { + return true; + } + const engine = scene.getEngine(); + // Lights + defines._needNormals = PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting); + // Multiview + PrepareDefinesForMultiview(scene, defines); + // PrePass + const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency; + PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit); + // Order independant transparency + PrepareDefinesForOIT(scene, defines, oit); + MaterialHelperGeometryRendering.PrepareDefines(engine.currentRenderPassId, mesh, defines); + // Textures + if (defines._areTexturesDirty) { + this._eventInfo.hasRenderTargetTextures = false; + this._callbackPluginEventHasRenderTargetTextures(this._eventInfo); + this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures; + defines._needUVs = false; + for (let i = 1; i <= 6; ++i) { + defines["MAINUV" + i] = false; + } + if (scene.texturesEnabled) { + defines.DIFFUSEDIRECTUV = 0; + defines.BUMPDIRECTUV = 0; + defines.AMBIENTDIRECTUV = 0; + defines.OPACITYDIRECTUV = 0; + defines.EMISSIVEDIRECTUV = 0; + defines.SPECULARDIRECTUV = 0; + defines.LIGHTMAPDIRECTUV = 0; + if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) { + if (!this._diffuseTexture.isReadyOrNotBlocking()) { + return false; + } + else { + PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE"); + } + } + else { + defines.DIFFUSE = false; + } + if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) { + if (!this._ambientTexture.isReadyOrNotBlocking()) { + return false; + } + else { + PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT"); + } + } + else { + defines.AMBIENT = false; + } + if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) { + if (!this._opacityTexture.isReadyOrNotBlocking()) { + return false; + } + else { + PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY"); + defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB; + } + } + else { + defines.OPACITY = false; + } + if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) { + if (!this._reflectionTexture.isReadyOrNotBlocking()) { + return false; + } + else { + defines._needNormals = true; + defines.REFLECTION = true; + defines.ROUGHNESS = this._roughness > 0; + defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha; + defines.INVERTCUBICMAP = this._reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE; + defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube; + defines.REFLECTIONMAP_OPPOSITEZ = + defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !this._reflectionTexture.invertZ : this._reflectionTexture.invertZ; + defines.RGBDREFLECTION = this._reflectionTexture.isRGBD; + switch (this._reflectionTexture.coordinatesMode) { + case Texture.EXPLICIT_MODE: + defines.setReflectionMode("REFLECTIONMAP_EXPLICIT"); + break; + case Texture.PLANAR_MODE: + defines.setReflectionMode("REFLECTIONMAP_PLANAR"); + break; + case Texture.PROJECTION_MODE: + defines.setReflectionMode("REFLECTIONMAP_PROJECTION"); + break; + case Texture.SKYBOX_MODE: + defines.setReflectionMode("REFLECTIONMAP_SKYBOX"); + break; + case Texture.SPHERICAL_MODE: + defines.setReflectionMode("REFLECTIONMAP_SPHERICAL"); + break; + case Texture.EQUIRECTANGULAR_MODE: + defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR"); + break; + case Texture.FIXED_EQUIRECTANGULAR_MODE: + defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"); + break; + case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE: + defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"); + break; + case Texture.CUBIC_MODE: + case Texture.INVCUBIC_MODE: + default: + defines.setReflectionMode("REFLECTIONMAP_CUBIC"); + break; + } + defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false; + } + } + else { + defines.REFLECTION = false; + defines.REFLECTIONMAP_OPPOSITEZ = false; + } + if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) { + if (!this._emissiveTexture.isReadyOrNotBlocking()) { + return false; + } + else { + PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE"); + } + } + else { + defines.EMISSIVE = false; + } + if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) { + if (!this._lightmapTexture.isReadyOrNotBlocking()) { + return false; + } + else { + PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP"); + defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap; + defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD; + } + } + else { + defines.LIGHTMAP = false; + } + if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) { + if (!this._specularTexture.isReadyOrNotBlocking()) { + return false; + } + else { + PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR"); + defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha; + } + } + else { + defines.SPECULAR = false; + } + if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) { + // Bump texture can not be not blocking. + if (!this._bumpTexture.isReady()) { + return false; + } + else { + PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP"); + defines.PARALLAX = this._useParallax; + defines.PARALLAX_RHS = scene.useRightHandedSystem; + defines.PARALLAXOCCLUSION = this._useParallaxOcclusion; + } + defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap; + } + else { + defines.BUMP = false; + defines.PARALLAX = false; + defines.PARALLAX_RHS = false; + defines.PARALLAXOCCLUSION = false; + } + if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) { + if (!this._refractionTexture.isReadyOrNotBlocking()) { + return false; + } + else { + defines._needUVs = true; + defines.REFRACTION = true; + defines.REFRACTIONMAP_3D = this._refractionTexture.isCube; + defines.RGBDREFRACTION = this._refractionTexture.isRGBD; + defines.USE_LOCAL_REFRACTIONMAP_CUBIC = this._refractionTexture.boundingBoxSize ? true : false; + } + } + else { + defines.REFRACTION = false; + } + defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting; + } + else { + defines.DIFFUSE = false; + defines.AMBIENT = false; + defines.OPACITY = false; + defines.REFLECTION = false; + defines.EMISSIVE = false; + defines.LIGHTMAP = false; + defines.BUMP = false; + defines.REFRACTION = false; + } + defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture(); + defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination; + defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse; + defines.SPECULAROVERALPHA = this._useSpecularOverAlpha; + defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8; + defines.ALPHATEST_AFTERALLALPHACOMPUTATIONS = this.transparencyMode !== null; + defines.ALPHABLEND = this.transparencyMode === null || this.needAlphaBlendingForMesh(mesh); // check on null for backward compatibility + } + this._eventInfo.isReadyForSubMesh = true; + this._eventInfo.defines = defines; + this._eventInfo.subMesh = subMesh; + this._callbackPluginEventIsReadyForSubMesh(this._eventInfo); + if (!this._eventInfo.isReadyForSubMesh) { + return false; + } + if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { + if (!this._imageProcessingConfiguration.isReady()) { + return false; + } + this._imageProcessingConfiguration.prepareDefines(defines); + defines.IS_REFLECTION_LINEAR = this.reflectionTexture != null && !this.reflectionTexture.gammaSpace; + defines.IS_REFRACTION_LINEAR = this.refractionTexture != null && !this.refractionTexture.gammaSpace; + } + if (defines._areFresnelDirty) { + if (StandardMaterial.FresnelEnabled) { + // Fresnel + if (this._diffuseFresnelParameters || + this._opacityFresnelParameters || + this._emissiveFresnelParameters || + this._refractionFresnelParameters || + this._reflectionFresnelParameters) { + defines.DIFFUSEFRESNEL = this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled; + defines.OPACITYFRESNEL = this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled; + defines.REFLECTIONFRESNEL = this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled; + defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular; + defines.REFRACTIONFRESNEL = this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled; + defines.EMISSIVEFRESNEL = this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled; + defines._needNormals = true; + defines.FRESNEL = true; + } + } + else { + defines.FRESNEL = false; + } + } + // Check if Area Lights have LTC texture. + if (defines["AREALIGHTUSED"]) { + for (let index = 0; index < mesh.lightSources.length; index++) { + if (!mesh.lightSources[index]._isReady()) { + return false; + } + } + } + // Misc. + PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this.needAlphaTestingForMesh(mesh), defines, this._applyDecalMapAfterDetailMap); + // Values that need to be evaluated on every frame + PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances); + // External config + this._eventInfo.defines = defines; + this._eventInfo.mesh = mesh; + this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo); + // Attribs + PrepareDefinesForAttributes(mesh, defines, true, true, true); + // External config + this._callbackPluginEventPrepareDefines(this._eventInfo); + // Get correct effect + let forceWasNotReadyPreviously = false; + if (defines.isDirty) { + const lightDisposed = defines._areLightsDisposed; + defines.markAsProcessed(); + // Fallbacks + const fallbacks = new EffectFallbacks(); + if (defines.REFLECTION) { + fallbacks.addFallback(0, "REFLECTION"); + } + if (defines.SPECULAR) { + fallbacks.addFallback(0, "SPECULAR"); + } + if (defines.BUMP) { + fallbacks.addFallback(0, "BUMP"); + } + if (defines.PARALLAX) { + fallbacks.addFallback(1, "PARALLAX"); + } + if (defines.PARALLAX_RHS) { + fallbacks.addFallback(1, "PARALLAX_RHS"); + } + if (defines.PARALLAXOCCLUSION) { + fallbacks.addFallback(0, "PARALLAXOCCLUSION"); + } + if (defines.SPECULAROVERALPHA) { + fallbacks.addFallback(0, "SPECULAROVERALPHA"); + } + if (defines.FOG) { + fallbacks.addFallback(1, "FOG"); + } + if (defines.POINTSIZE) { + fallbacks.addFallback(0, "POINTSIZE"); + } + if (defines.LOGARITHMICDEPTH) { + fallbacks.addFallback(0, "LOGARITHMICDEPTH"); + } + HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights); + if (defines.SPECULARTERM) { + fallbacks.addFallback(0, "SPECULARTERM"); + } + if (defines.DIFFUSEFRESNEL) { + fallbacks.addFallback(1, "DIFFUSEFRESNEL"); + } + if (defines.OPACITYFRESNEL) { + fallbacks.addFallback(2, "OPACITYFRESNEL"); + } + if (defines.REFLECTIONFRESNEL) { + fallbacks.addFallback(3, "REFLECTIONFRESNEL"); + } + if (defines.EMISSIVEFRESNEL) { + fallbacks.addFallback(4, "EMISSIVEFRESNEL"); + } + if (defines.FRESNEL) { + fallbacks.addFallback(4, "FRESNEL"); + } + if (defines.MULTIVIEW) { + fallbacks.addFallback(0, "MULTIVIEW"); + } + //Attributes + const attribs = [VertexBuffer.PositionKind]; + if (defines.NORMAL) { + attribs.push(VertexBuffer.NormalKind); + } + if (defines.TANGENT) { + attribs.push(VertexBuffer.TangentKind); + } + for (let i = 1; i <= 6; ++i) { + if (defines["UV" + i]) { + attribs.push(`uv${i === 1 ? "" : i}`); + } + } + if (defines.VERTEXCOLOR) { + attribs.push(VertexBuffer.ColorKind); + } + PrepareAttributesForBones(attribs, mesh, defines, fallbacks); + PrepareAttributesForInstances(attribs, defines); + PrepareAttributesForMorphTargets(attribs, mesh, defines); + PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines); + let shaderName = "default"; + const uniforms = [ + "world", + "view", + "viewProjection", + "vEyePosition", + "vLightsType", + "vAmbientColor", + "vDiffuseColor", + "vSpecularColor", + "vEmissiveColor", + "visibility", + "vFogInfos", + "vFogColor", + "pointSize", + "vDiffuseInfos", + "vAmbientInfos", + "vOpacityInfos", + "vReflectionInfos", + "vEmissiveInfos", + "vSpecularInfos", + "vBumpInfos", + "vLightmapInfos", + "vRefractionInfos", + "mBones", + "diffuseMatrix", + "ambientMatrix", + "opacityMatrix", + "reflectionMatrix", + "emissiveMatrix", + "specularMatrix", + "bumpMatrix", + "normalMatrix", + "lightmapMatrix", + "refractionMatrix", + "diffuseLeftColor", + "diffuseRightColor", + "opacityParts", + "reflectionLeftColor", + "reflectionRightColor", + "emissiveLeftColor", + "emissiveRightColor", + "refractionLeftColor", + "refractionRightColor", + "vReflectionPosition", + "vReflectionSize", + "vRefractionPosition", + "vRefractionSize", + "logarithmicDepthConstant", + "vTangentSpaceParams", + "alphaCutOff", + "boneTextureWidth", + "morphTargetTextureInfo", + "morphTargetTextureIndices", + ]; + const samplers = [ + "diffuseSampler", + "ambientSampler", + "opacitySampler", + "reflectionCubeSampler", + "reflection2DSampler", + "emissiveSampler", + "specularSampler", + "bumpSampler", + "lightmapSampler", + "refractionCubeSampler", + "refraction2DSampler", + "boneSampler", + "morphTargets", + "oitDepthSampler", + "oitFrontColorSampler", + "areaLightsLTC1Sampler", + "areaLightsLTC2Sampler", + ]; + const uniformBuffers = ["Material", "Scene", "Mesh"]; + const indexParameters = { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }; + this._eventInfo.fallbacks = fallbacks; + this._eventInfo.fallbackRank = 0; + this._eventInfo.defines = defines; + this._eventInfo.uniforms = uniforms; + this._eventInfo.attributes = attribs; + this._eventInfo.samplers = samplers; + this._eventInfo.uniformBuffersNames = uniformBuffers; + this._eventInfo.customCode = undefined; + this._eventInfo.mesh = mesh; + this._eventInfo.indexParameters = indexParameters; + this._callbackPluginEventGeneric(128 /* MaterialPluginEvent.PrepareEffect */, this._eventInfo); + MaterialHelperGeometryRendering.AddUniformsAndSamplers(uniforms, samplers); + PrePassConfiguration.AddUniforms(uniforms); + if (ImageProcessingConfiguration) { + ImageProcessingConfiguration.PrepareUniforms(uniforms, defines); + ImageProcessingConfiguration.PrepareSamplers(samplers, defines); + } + PrepareUniformsAndSamplersList({ + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: defines, + maxSimultaneousLights: this._maxSimultaneousLights, + }); + addClipPlaneUniforms(uniforms); + const csnrOptions = {}; + if (this.customShaderNameResolve) { + shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions); + } + const join = defines.toString(); + const previousEffect = subMesh.effect; + let effect = scene.getEngine().createEffect(shaderName, { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: join, + fallbacks: fallbacks, + onCompiled: this.onCompiled, + onError: this.onError, + indexParameters, + processFinalCode: csnrOptions.processFinalCode, + processCodeAfterIncludes: this._eventInfo.customCode, + multiTarget: defines.PREPASS, + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: this._shadersLoaded + ? undefined + : async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => default_vertex), Promise.resolve().then(() => default_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => default_vertex$1), Promise.resolve().then(() => default_fragment$1)]); + } + this._shadersLoaded = true; + }, + }, engine); + this._eventInfo.customCode = undefined; + if (effect) { + if (this._onEffectCreatedObservable) { + onCreatedEffectParameters$3.effect = effect; + onCreatedEffectParameters$3.subMesh = subMesh; + this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$3); + } + // Use previous effect while new one is compiling + if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) { + effect = previousEffect; + defines.markAsUnprocessed(); + forceWasNotReadyPreviously = this.isFrozen; + if (lightDisposed) { + // re register in case it takes more than one frame. + defines._areLightsDisposed = true; + return false; + } + } + else { + scene.resetCachedMaterial(); + subMesh.setEffect(effect, defines, this._materialContext); + } + } + } + if (!subMesh.effect || !subMesh.effect.isReady()) { + return false; + } + defines._renderId = scene.getRenderId(); + drawWrapper._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true; + drawWrapper._wasPreviouslyUsingInstances = useInstances; + this._checkScenePerformancePriority(); + return true; + } + /** + * Builds the material UBO layouts. + * Used internally during the effect preparation. + */ + buildUniformLayout() { + // Order is important ! + const ubo = this._uniformBuffer; + ubo.addUniform("diffuseLeftColor", 4); + ubo.addUniform("diffuseRightColor", 4); + ubo.addUniform("opacityParts", 4); + ubo.addUniform("reflectionLeftColor", 4); + ubo.addUniform("reflectionRightColor", 4); + ubo.addUniform("refractionLeftColor", 4); + ubo.addUniform("refractionRightColor", 4); + ubo.addUniform("emissiveLeftColor", 4); + ubo.addUniform("emissiveRightColor", 4); + ubo.addUniform("vDiffuseInfos", 2); + ubo.addUniform("vAmbientInfos", 2); + ubo.addUniform("vOpacityInfos", 2); + ubo.addUniform("vReflectionInfos", 2); + ubo.addUniform("vReflectionPosition", 3); + ubo.addUniform("vReflectionSize", 3); + ubo.addUniform("vEmissiveInfos", 2); + ubo.addUniform("vLightmapInfos", 2); + ubo.addUniform("vSpecularInfos", 2); + ubo.addUniform("vBumpInfos", 3); + ubo.addUniform("diffuseMatrix", 16); + ubo.addUniform("ambientMatrix", 16); + ubo.addUniform("opacityMatrix", 16); + ubo.addUniform("reflectionMatrix", 16); + ubo.addUniform("emissiveMatrix", 16); + ubo.addUniform("lightmapMatrix", 16); + ubo.addUniform("specularMatrix", 16); + ubo.addUniform("bumpMatrix", 16); + ubo.addUniform("vTangentSpaceParams", 2); + ubo.addUniform("pointSize", 1); + ubo.addUniform("alphaCutOff", 1); + ubo.addUniform("refractionMatrix", 16); + ubo.addUniform("vRefractionInfos", 4); + ubo.addUniform("vRefractionPosition", 3); + ubo.addUniform("vRefractionSize", 3); + ubo.addUniform("vSpecularColor", 4); + ubo.addUniform("vEmissiveColor", 3); + ubo.addUniform("vDiffuseColor", 4); + ubo.addUniform("vAmbientColor", 3); + super.buildUniformLayout(); + } + /** + * Binds the submesh to this material by preparing the effect and shader to draw + * @param world defines the world transformation matrix + * @param mesh defines the mesh containing the submesh + * @param subMesh defines the submesh to bind the material to + */ + bindForSubMesh(world, mesh, subMesh) { + const scene = this.getScene(); + const defines = subMesh.materialDefines; + if (!defines) { + return; + } + const effect = subMesh.effect; + if (!effect) { + return; + } + this._activeEffect = effect; + // Matrices Mesh. + mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); + mesh.transferToEffect(world); + // Binding unconditionally + this._uniformBuffer.bindToEffect(effect, "Material"); + this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen); + MaterialHelperGeometryRendering.Bind(scene.getEngine().currentRenderPassId, this._activeEffect, mesh, world, this); + this._eventInfo.subMesh = subMesh; + this._callbackPluginEventHardBindForSubMesh(this._eventInfo); + // Normal Matrix + if (defines.OBJECTSPACE_NORMALMAP) { + world.toNormalMatrix(this._normalMatrix); + this.bindOnlyNormalMatrix(this._normalMatrix); + } + const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility); + // Bones + BindBonesParameters(mesh, effect); + const ubo = this._uniformBuffer; + if (mustRebind) { + this.bindViewProjection(effect); + if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || subMesh._drawWrapper._forceRebindOnNextCall) { + if (StandardMaterial.FresnelEnabled && defines.FRESNEL) { + // Fresnel + if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) { + ubo.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power); + ubo.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias); + } + if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) { + ubo.updateColor4("opacityParts", new Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power); + } + if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) { + ubo.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power); + ubo.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias); + } + if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) { + ubo.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power); + ubo.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias); + } + if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) { + ubo.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power); + ubo.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias); + } + } + // Textures + if (scene.texturesEnabled) { + if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) { + ubo.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level); + BindTextureMatrix(this._diffuseTexture, ubo, "diffuse"); + } + if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) { + ubo.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level); + BindTextureMatrix(this._ambientTexture, ubo, "ambient"); + } + if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) { + ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level); + BindTextureMatrix(this._opacityTexture, ubo, "opacity"); + } + if (this._hasAlphaChannel()) { + ubo.updateFloat("alphaCutOff", this.alphaCutOff); + } + if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) { + ubo.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness); + ubo.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix()); + if (this._reflectionTexture.boundingBoxSize) { + const cubeTexture = this._reflectionTexture; + ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition); + ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize); + } + } + else { + ubo.updateFloat2("vReflectionInfos", 0.0, this.roughness); + } + if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) { + ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level); + BindTextureMatrix(this._emissiveTexture, ubo, "emissive"); + } + if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) { + ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level); + BindTextureMatrix(this._lightmapTexture, ubo, "lightmap"); + } + if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) { + ubo.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level); + BindTextureMatrix(this._specularTexture, ubo, "specular"); + } + if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) { + ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias); + BindTextureMatrix(this._bumpTexture, ubo, "bump"); + if (scene._mirroredCameraPosition) { + ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1, this._invertNormalMapY ? 1.0 : -1); + } + else { + ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1.0, this._invertNormalMapY ? -1 : 1.0); + } + } + if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) { + let depth = 1.0; + if (!this._refractionTexture.isCube) { + ubo.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix()); + if (this._refractionTexture.depth) { + depth = this._refractionTexture.depth; + } + } + ubo.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1); + if (this._refractionTexture.boundingBoxSize) { + const cubeTexture = this._refractionTexture; + ubo.updateVector3("vRefractionPosition", cubeTexture.boundingBoxPosition); + ubo.updateVector3("vRefractionSize", cubeTexture.boundingBoxSize); + } + } + } + // Point size + if (this.pointsCloud) { + ubo.updateFloat("pointSize", this.pointSize); + } + ubo.updateColor4("vSpecularColor", this.specularColor, this.specularPower); + ubo.updateColor3("vEmissiveColor", StandardMaterial.EmissiveTextureEnabled ? this.emissiveColor : Color3.BlackReadOnly); + ubo.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha); + scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor); + ubo.updateColor3("vAmbientColor", this._globalAmbientColor); + } + // Textures + if (scene.texturesEnabled) { + if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) { + effect.setTexture("diffuseSampler", this._diffuseTexture); + } + if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) { + effect.setTexture("ambientSampler", this._ambientTexture); + } + if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) { + effect.setTexture("opacitySampler", this._opacityTexture); + } + if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) { + if (this._reflectionTexture.isCube) { + effect.setTexture("reflectionCubeSampler", this._reflectionTexture); + } + else { + effect.setTexture("reflection2DSampler", this._reflectionTexture); + } + } + if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) { + effect.setTexture("emissiveSampler", this._emissiveTexture); + } + if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) { + effect.setTexture("lightmapSampler", this._lightmapTexture); + } + if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) { + effect.setTexture("specularSampler", this._specularTexture); + } + if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) { + effect.setTexture("bumpSampler", this._bumpTexture); + } + if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) { + if (this._refractionTexture.isCube) { + effect.setTexture("refractionCubeSampler", this._refractionTexture); + } + else { + effect.setTexture("refraction2DSampler", this._refractionTexture); + } + } + } + // OIT with depth peeling + if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) { + this.getScene().depthPeelingRenderer.bind(effect); + } + this._eventInfo.subMesh = subMesh; + this._callbackPluginEventBindForSubMesh(this._eventInfo); + // Clip plane + bindClipPlane(effect, this, scene); + // Colors + this.bindEyePosition(effect); + } + else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) { + this._needToBindSceneUbo = true; + } + if (mustRebind || !this.isFrozen) { + // Lights + if (scene.lightsEnabled && !this._disableLighting) { + BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights); + } + // View + if ((scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) || + this._reflectionTexture || + this._refractionTexture || + mesh.receiveShadows || + defines.PREPASS) { + this.bindView(effect); + } + // Fog + BindFogParameters(scene, mesh, effect); + // Morph targets + if (defines.NUM_MORPH_INFLUENCERS) { + BindMorphTargetParameters(mesh, effect); + } + if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) { + mesh.bakedVertexAnimationManager?.bind(effect, defines.INSTANCES); + } + // Log. depth + if (this.useLogarithmicDepth) { + BindLogDepth(defines, effect, scene); + } + // image processing + if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) { + this._imageProcessingConfiguration.bind(this._activeEffect); + } + } + this._afterBind(mesh, this._activeEffect, subMesh); + ubo.update(); + } + /** + * Get the list of animatables in the material. + * @returns the list of animatables object used in the material + */ + getAnimatables() { + const results = super.getAnimatables(); + if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) { + results.push(this._diffuseTexture); + } + if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) { + results.push(this._ambientTexture); + } + if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) { + results.push(this._opacityTexture); + } + if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) { + results.push(this._reflectionTexture); + } + if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) { + results.push(this._emissiveTexture); + } + if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) { + results.push(this._specularTexture); + } + if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { + results.push(this._bumpTexture); + } + if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) { + results.push(this._lightmapTexture); + } + if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) { + results.push(this._refractionTexture); + } + return results; + } + /** + * Gets the active textures from the material + * @returns an array of textures + */ + getActiveTextures() { + const activeTextures = super.getActiveTextures(); + if (this._diffuseTexture) { + activeTextures.push(this._diffuseTexture); + } + if (this._ambientTexture) { + activeTextures.push(this._ambientTexture); + } + if (this._opacityTexture) { + activeTextures.push(this._opacityTexture); + } + if (this._reflectionTexture) { + activeTextures.push(this._reflectionTexture); + } + if (this._emissiveTexture) { + activeTextures.push(this._emissiveTexture); + } + if (this._specularTexture) { + activeTextures.push(this._specularTexture); + } + if (this._bumpTexture) { + activeTextures.push(this._bumpTexture); + } + if (this._lightmapTexture) { + activeTextures.push(this._lightmapTexture); + } + if (this._refractionTexture) { + activeTextures.push(this._refractionTexture); + } + return activeTextures; + } + /** + * Specifies if the material uses a texture + * @param texture defines the texture to check against the material + * @returns a boolean specifying if the material uses the texture + */ + hasTexture(texture) { + if (super.hasTexture(texture)) { + return true; + } + if (this._diffuseTexture === texture) { + return true; + } + if (this._ambientTexture === texture) { + return true; + } + if (this._opacityTexture === texture) { + return true; + } + if (this._reflectionTexture === texture) { + return true; + } + if (this._emissiveTexture === texture) { + return true; + } + if (this._specularTexture === texture) { + return true; + } + if (this._bumpTexture === texture) { + return true; + } + if (this._lightmapTexture === texture) { + return true; + } + if (this._refractionTexture === texture) { + return true; + } + return false; + } + /** + * Disposes the material + * @param forceDisposeEffect specifies if effects should be forcefully disposed + * @param forceDisposeTextures specifies if textures should be forcefully disposed + */ + dispose(forceDisposeEffect, forceDisposeTextures) { + if (forceDisposeTextures) { + this._diffuseTexture?.dispose(); + this._ambientTexture?.dispose(); + this._opacityTexture?.dispose(); + this._reflectionTexture?.dispose(); + this._emissiveTexture?.dispose(); + this._specularTexture?.dispose(); + this._bumpTexture?.dispose(); + this._lightmapTexture?.dispose(); + this._refractionTexture?.dispose(); + } + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + super.dispose(forceDisposeEffect, forceDisposeTextures); + } + /** + * Makes a duplicate of the material, and gives it a new name + * @param name defines the new name for the duplicated material + * @param cloneTexturesOnlyOnce - if a texture is used in more than one channel (e.g diffuse and opacity), only clone it once and reuse it on the other channels. Default false. + * @param rootUrl defines the root URL to use to load textures + * @returns the cloned material + */ + clone(name, cloneTexturesOnlyOnce = true, rootUrl = "") { + const result = SerializationHelper.Clone(() => new StandardMaterial(name, this.getScene()), this, { cloneTexturesOnlyOnce }); + result.name = name; + result.id = name; + this.stencil.copyTo(result.stencil); + this._clonePlugins(result, rootUrl); + return result; + } + /** + * Creates a standard material from parsed material data + * @param source defines the JSON representation of the material + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a new standard material + */ + static Parse(source, scene, rootUrl) { + const material = SerializationHelper.Parse(() => new StandardMaterial(source.name, scene), source, scene, rootUrl); + if (source.stencil) { + material.stencil.parse(source.stencil, scene, rootUrl); + } + Material._ParsePlugins(source, material, scene, rootUrl); + return material; + } + // Flags used to enable or disable a type of texture for all Standard Materials + /** + * Are diffuse textures enabled in the application. + */ + static get DiffuseTextureEnabled() { + return MaterialFlags.DiffuseTextureEnabled; + } + static set DiffuseTextureEnabled(value) { + MaterialFlags.DiffuseTextureEnabled = value; + } + /** + * Are detail textures enabled in the application. + */ + static get DetailTextureEnabled() { + return MaterialFlags.DetailTextureEnabled; + } + static set DetailTextureEnabled(value) { + MaterialFlags.DetailTextureEnabled = value; + } + /** + * Are ambient textures enabled in the application. + */ + static get AmbientTextureEnabled() { + return MaterialFlags.AmbientTextureEnabled; + } + static set AmbientTextureEnabled(value) { + MaterialFlags.AmbientTextureEnabled = value; + } + /** + * Are opacity textures enabled in the application. + */ + static get OpacityTextureEnabled() { + return MaterialFlags.OpacityTextureEnabled; + } + static set OpacityTextureEnabled(value) { + MaterialFlags.OpacityTextureEnabled = value; + } + /** + * Are reflection textures enabled in the application. + */ + static get ReflectionTextureEnabled() { + return MaterialFlags.ReflectionTextureEnabled; + } + static set ReflectionTextureEnabled(value) { + MaterialFlags.ReflectionTextureEnabled = value; + } + /** + * Are emissive textures enabled in the application. + */ + static get EmissiveTextureEnabled() { + return MaterialFlags.EmissiveTextureEnabled; + } + static set EmissiveTextureEnabled(value) { + MaterialFlags.EmissiveTextureEnabled = value; + } + /** + * Are specular textures enabled in the application. + */ + static get SpecularTextureEnabled() { + return MaterialFlags.SpecularTextureEnabled; + } + static set SpecularTextureEnabled(value) { + MaterialFlags.SpecularTextureEnabled = value; + } + /** + * Are bump textures enabled in the application. + */ + static get BumpTextureEnabled() { + return MaterialFlags.BumpTextureEnabled; + } + static set BumpTextureEnabled(value) { + MaterialFlags.BumpTextureEnabled = value; + } + /** + * Are lightmap textures enabled in the application. + */ + static get LightmapTextureEnabled() { + return MaterialFlags.LightmapTextureEnabled; + } + static set LightmapTextureEnabled(value) { + MaterialFlags.LightmapTextureEnabled = value; + } + /** + * Are refraction textures enabled in the application. + */ + static get RefractionTextureEnabled() { + return MaterialFlags.RefractionTextureEnabled; + } + static set RefractionTextureEnabled(value) { + MaterialFlags.RefractionTextureEnabled = value; + } + /** + * Are color grading textures enabled in the application. + */ + static get ColorGradingTextureEnabled() { + return MaterialFlags.ColorGradingTextureEnabled; + } + static set ColorGradingTextureEnabled(value) { + MaterialFlags.ColorGradingTextureEnabled = value; + } + /** + * Are fresnels enabled in the application. + */ + static get FresnelEnabled() { + return MaterialFlags.FresnelEnabled; + } + static set FresnelEnabled(value) { + MaterialFlags.FresnelEnabled = value; + } +} +/** + * Force all the standard materials to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +StandardMaterial.ForceGLSL = false; +__decorate([ + serializeAsTexture("diffuseTexture") +], StandardMaterial.prototype, "_diffuseTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") +], StandardMaterial.prototype, "diffuseTexture", void 0); +__decorate([ + serializeAsTexture("ambientTexture") +], StandardMaterial.prototype, "_ambientTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "ambientTexture", void 0); +__decorate([ + serializeAsTexture("opacityTexture") +], StandardMaterial.prototype, "_opacityTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") +], StandardMaterial.prototype, "opacityTexture", void 0); +__decorate([ + serializeAsTexture("reflectionTexture") +], StandardMaterial.prototype, "_reflectionTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "reflectionTexture", void 0); +__decorate([ + serializeAsTexture("emissiveTexture") +], StandardMaterial.prototype, "_emissiveTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "emissiveTexture", void 0); +__decorate([ + serializeAsTexture("specularTexture") +], StandardMaterial.prototype, "_specularTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "specularTexture", void 0); +__decorate([ + serializeAsTexture("bumpTexture") +], StandardMaterial.prototype, "_bumpTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "bumpTexture", void 0); +__decorate([ + serializeAsTexture("lightmapTexture") +], StandardMaterial.prototype, "_lightmapTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "lightmapTexture", void 0); +__decorate([ + serializeAsTexture("refractionTexture") +], StandardMaterial.prototype, "_refractionTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "refractionTexture", void 0); +__decorate([ + serializeAsColor3("ambient") +], StandardMaterial.prototype, "ambientColor", void 0); +__decorate([ + serializeAsColor3("diffuse") +], StandardMaterial.prototype, "diffuseColor", void 0); +__decorate([ + serializeAsColor3("specular") +], StandardMaterial.prototype, "specularColor", void 0); +__decorate([ + serializeAsColor3("emissive") +], StandardMaterial.prototype, "emissiveColor", void 0); +__decorate([ + serialize() +], StandardMaterial.prototype, "specularPower", void 0); +__decorate([ + serialize("useAlphaFromDiffuseTexture") +], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") +], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0); +__decorate([ + serialize("useEmissiveAsIllumination") +], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0); +__decorate([ + serialize("linkEmissiveWithDiffuse") +], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0); +__decorate([ + serialize("useSpecularOverAlpha") +], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "useSpecularOverAlpha", void 0); +__decorate([ + serialize("useReflectionOverAlpha") +], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "useReflectionOverAlpha", void 0); +__decorate([ + serialize("disableLighting") +], StandardMaterial.prototype, "_disableLighting", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsLightsDirty") +], StandardMaterial.prototype, "disableLighting", void 0); +__decorate([ + serialize("useObjectSpaceNormalMap") +], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0); +__decorate([ + serialize("useParallax") +], StandardMaterial.prototype, "_useParallax", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "useParallax", void 0); +__decorate([ + serialize("useParallaxOcclusion") +], StandardMaterial.prototype, "_useParallaxOcclusion", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "useParallaxOcclusion", void 0); +__decorate([ + serialize() +], StandardMaterial.prototype, "parallaxScaleBias", void 0); +__decorate([ + serialize("roughness") +], StandardMaterial.prototype, "_roughness", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "roughness", void 0); +__decorate([ + serialize() +], StandardMaterial.prototype, "indexOfRefraction", void 0); +__decorate([ + serialize() +], StandardMaterial.prototype, "invertRefractionY", void 0); +__decorate([ + serialize() +], StandardMaterial.prototype, "alphaCutOff", void 0); +__decorate([ + serialize("useLightmapAsShadowmap") +], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0); +__decorate([ + serializeAsFresnelParameters("diffuseFresnelParameters") +], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsFresnelDirty") +], StandardMaterial.prototype, "diffuseFresnelParameters", void 0); +__decorate([ + serializeAsFresnelParameters("opacityFresnelParameters") +], StandardMaterial.prototype, "_opacityFresnelParameters", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty") +], StandardMaterial.prototype, "opacityFresnelParameters", void 0); +__decorate([ + serializeAsFresnelParameters("reflectionFresnelParameters") +], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsFresnelDirty") +], StandardMaterial.prototype, "reflectionFresnelParameters", void 0); +__decorate([ + serializeAsFresnelParameters("refractionFresnelParameters") +], StandardMaterial.prototype, "_refractionFresnelParameters", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsFresnelDirty") +], StandardMaterial.prototype, "refractionFresnelParameters", void 0); +__decorate([ + serializeAsFresnelParameters("emissiveFresnelParameters") +], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsFresnelDirty") +], StandardMaterial.prototype, "emissiveFresnelParameters", void 0); +__decorate([ + serialize("useReflectionFresnelFromSpecular") +], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsFresnelDirty") +], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0); +__decorate([ + serialize("useGlossinessFromSpecularMapAlpha") +], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0); +__decorate([ + serialize("maxSimultaneousLights") +], StandardMaterial.prototype, "_maxSimultaneousLights", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsLightsDirty") +], StandardMaterial.prototype, "maxSimultaneousLights", void 0); +__decorate([ + serialize("invertNormalMapX") +], StandardMaterial.prototype, "_invertNormalMapX", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "invertNormalMapX", void 0); +__decorate([ + serialize("invertNormalMapY") +], StandardMaterial.prototype, "_invertNormalMapY", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "invertNormalMapY", void 0); +__decorate([ + serialize("twoSidedLighting") +], StandardMaterial.prototype, "_twoSidedLighting", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], StandardMaterial.prototype, "twoSidedLighting", void 0); +__decorate([ + serialize("applyDecalMapAfterDetailMap") +], StandardMaterial.prototype, "_applyDecalMapAfterDetailMap", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsMiscDirty") +], StandardMaterial.prototype, "applyDecalMapAfterDetailMap", void 0); +RegisterClass("BABYLON.StandardMaterial", StandardMaterial); +Scene.DefaultMaterialFactory = (scene) => { + return new StandardMaterial("default material", scene); +}; + +const onCreatedEffectParameters$2 = { effect: null, subMesh: null }; +/** + * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh. + * + * This returned material effects how the mesh will look based on the code in the shaders. + * + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial + */ +class ShaderMaterial extends PushMaterial { + /** + * Instantiate a new shader material. + * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh. + * This returned material effects how the mesh will look based on the code in the shaders. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial + * @param name Define the name of the material in the scene + * @param scene Define the scene the material belongs to + * @param shaderPath Defines the route to the shader code. + * @param options Define the options used to create the shader + * @param storeEffectOnSubMeshes true to store effect on submeshes, false to store the effect directly in the material class. + */ + constructor(name, scene, shaderPath, options = {}, storeEffectOnSubMeshes = true) { + super(name, scene, storeEffectOnSubMeshes); + this._textures = {}; + this._textureArrays = {}; + this._externalTextures = {}; + this._floats = {}; + this._ints = {}; + this._uints = {}; + this._floatsArrays = {}; + this._colors3 = {}; + this._colors3Arrays = {}; + this._colors4 = {}; + this._colors4Arrays = {}; + this._vectors2 = {}; + this._vectors3 = {}; + this._vectors4 = {}; + this._quaternions = {}; + this._quaternionsArrays = {}; + this._matrices = {}; + this._matrixArrays = {}; + this._matrices3x3 = {}; + this._matrices2x2 = {}; + this._vectors2Arrays = {}; + this._vectors3Arrays = {}; + this._vectors4Arrays = {}; + this._uniformBuffers = {}; + this._textureSamplers = {}; + this._storageBuffers = {}; + this._cachedWorldViewMatrix = new Matrix(); + this._cachedWorldViewProjectionMatrix = new Matrix(); + this._multiview = false; + /** + * @internal + */ + this._materialHelperNeedsPreviousMatrices = false; + this._shaderPath = shaderPath; + this._options = { + needAlphaBlending: false, + needAlphaTesting: false, + attributes: ["position", "normal", "uv"], + uniforms: ["worldViewProjection"], + uniformBuffers: [], + samplers: [], + externalTextures: [], + samplerObjects: [], + storageBuffers: [], + defines: [], + useClipPlane: false, + ...options, + }; + } + /** + * Gets the shader path used to define the shader code + * It can be modified to trigger a new compilation + */ + get shaderPath() { + return this._shaderPath; + } + /** + * Sets the shader path used to define the shader code + * It can be modified to trigger a new compilation + */ + set shaderPath(shaderPath) { + this._shaderPath = shaderPath; + } + /** + * Gets the options used to compile the shader. + * They can be modified to trigger a new compilation + */ + get options() { + return this._options; + } + /** + * is multiview set to true? + */ + get isMultiview() { + return this._multiview; + } + /** + * Gets the current class name of the material e.g. "ShaderMaterial" + * Mainly use in serialization. + * @returns the class name + */ + getClassName() { + return "ShaderMaterial"; + } + /** + * Specifies if the material will require alpha blending + * @returns a boolean specifying if alpha blending is needed + */ + needAlphaBlending() { + return this.alpha < 1.0 || this._options.needAlphaBlending; + } + /** + * Specifies if this material should be rendered in alpha test mode + * @returns a boolean specifying if an alpha test is needed. + */ + needAlphaTesting() { + return this._options.needAlphaTesting; + } + _checkUniform(uniformName) { + if (this._options.uniforms.indexOf(uniformName) === -1) { + this._options.uniforms.push(uniformName); + } + } + /** + * Set a texture in the shader. + * @param name Define the name of the uniform samplers as defined in the shader + * @param texture Define the texture to bind to this sampler + * @returns the material itself allowing "fluent" like uniform updates + */ + setTexture(name, texture) { + if (this._options.samplers.indexOf(name) === -1) { + this._options.samplers.push(name); + } + this._textures[name] = texture; + return this; + } + /** + * Remove a texture from the material. + * @param name Define the name of the texture to remove + */ + removeTexture(name) { + delete this._textures[name]; + } + /** + * Set a texture array in the shader. + * @param name Define the name of the uniform sampler array as defined in the shader + * @param textures Define the list of textures to bind to this sampler + * @returns the material itself allowing "fluent" like uniform updates + */ + setTextureArray(name, textures) { + if (this._options.samplers.indexOf(name) === -1) { + this._options.samplers.push(name); + } + this._checkUniform(name); + this._textureArrays[name] = textures; + return this; + } + /** + * Set an internal texture in the shader. + * @param name Define the name of the uniform samplers as defined in the shader + * @param texture Define the texture to bind to this sampler + * @returns the material itself allowing "fluent" like uniform updates + */ + setExternalTexture(name, texture) { + if (this._options.externalTextures.indexOf(name) === -1) { + this._options.externalTextures.push(name); + } + this._externalTextures[name] = texture; + return this; + } + /** + * Set a float in the shader. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setFloat(name, value) { + this._checkUniform(name); + this._floats[name] = value; + return this; + } + /** + * Set a int in the shader. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setInt(name, value) { + this._checkUniform(name); + this._ints[name] = value; + return this; + } + /** + * Set a unsigned int in the shader. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setUInt(name, value) { + this._checkUniform(name); + this._uints[name] = value; + return this; + } + /** + * Set an array of floats in the shader. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setFloats(name, value) { + this._checkUniform(name); + this._floatsArrays[name] = value; + return this; + } + /** + * Set a vec3 in the shader from a Color3. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setColor3(name, value) { + this._checkUniform(name); + this._colors3[name] = value; + return this; + } + /** + * Set a vec3 array in the shader from a Color3 array. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setColor3Array(name, value) { + this._checkUniform(name); + this._colors3Arrays[name] = value.reduce((arr, color) => { + color.toArray(arr, arr.length); + return arr; + }, []); + return this; + } + /** + * Set a vec4 in the shader from a Color4. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setColor4(name, value) { + this._checkUniform(name); + this._colors4[name] = value; + return this; + } + /** + * Set a vec4 array in the shader from a Color4 array. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setColor4Array(name, value) { + this._checkUniform(name); + this._colors4Arrays[name] = value.reduce((arr, color) => { + color.toArray(arr, arr.length); + return arr; + }, []); + return this; + } + /** + * Set a vec2 in the shader from a Vector2. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setVector2(name, value) { + this._checkUniform(name); + this._vectors2[name] = value; + return this; + } + /** + * Set a vec3 in the shader from a Vector3. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setVector3(name, value) { + this._checkUniform(name); + this._vectors3[name] = value; + return this; + } + /** + * Set a vec4 in the shader from a Vector4. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setVector4(name, value) { + this._checkUniform(name); + this._vectors4[name] = value; + return this; + } + /** + * Set a vec4 in the shader from a Quaternion. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setQuaternion(name, value) { + this._checkUniform(name); + this._quaternions[name] = value; + return this; + } + /** + * Set a vec4 array in the shader from a Quaternion array. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setQuaternionArray(name, value) { + this._checkUniform(name); + this._quaternionsArrays[name] = value.reduce((arr, quaternion) => { + quaternion.toArray(arr, arr.length); + return arr; + }, []); + return this; + } + /** + * Set a mat4 in the shader from a Matrix. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setMatrix(name, value) { + this._checkUniform(name); + this._matrices[name] = value; + return this; + } + /** + * Set a float32Array in the shader from a matrix array. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setMatrices(name, value) { + this._checkUniform(name); + const float32Array = new Float32Array(value.length * 16); + for (let index = 0; index < value.length; index++) { + const matrix = value[index]; + matrix.copyToArray(float32Array, index * 16); + } + this._matrixArrays[name] = float32Array; + return this; + } + /** + * Set a mat3 in the shader from a Float32Array. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setMatrix3x3(name, value) { + this._checkUniform(name); + this._matrices3x3[name] = value; + return this; + } + /** + * Set a mat2 in the shader from a Float32Array. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setMatrix2x2(name, value) { + this._checkUniform(name); + this._matrices2x2[name] = value; + return this; + } + /** + * Set a vec2 array in the shader from a number array. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setArray2(name, value) { + this._checkUniform(name); + this._vectors2Arrays[name] = value; + return this; + } + /** + * Set a vec3 array in the shader from a number array. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setArray3(name, value) { + this._checkUniform(name); + this._vectors3Arrays[name] = value; + return this; + } + /** + * Set a vec4 array in the shader from a number array. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setArray4(name, value) { + this._checkUniform(name); + this._vectors4Arrays[name] = value; + return this; + } + /** + * Set a uniform buffer in the shader + * @param name Define the name of the uniform as defined in the shader + * @param buffer Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setUniformBuffer(name, buffer) { + if (this._options.uniformBuffers.indexOf(name) === -1) { + this._options.uniformBuffers.push(name); + } + this._uniformBuffers[name] = buffer; + return this; + } + /** + * Set a texture sampler in the shader + * @param name Define the name of the uniform as defined in the shader + * @param sampler Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setTextureSampler(name, sampler) { + if (this._options.samplerObjects.indexOf(name) === -1) { + this._options.samplerObjects.push(name); + } + this._textureSamplers[name] = sampler; + return this; + } + /** + * Set a storage buffer in the shader + * @param name Define the name of the storage buffer as defined in the shader + * @param buffer Define the value to give to the uniform + * @returns the material itself allowing "fluent" like uniform updates + */ + setStorageBuffer(name, buffer) { + if (this._options.storageBuffers.indexOf(name) === -1) { + this._options.storageBuffers.push(name); + } + this._storageBuffers[name] = buffer; + return this; + } + /** + * Adds, removes, or replaces the specified shader define and value. + * * setDefine("MY_DEFINE", true); // enables a boolean define + * * setDefine("MY_DEFINE", "0.5"); // adds "#define MY_DEFINE 0.5" to the shader (or sets and replaces the value of any existing define with that name) + * * setDefine("MY_DEFINE", false); // disables and removes the define + * Note if the active defines do change, the shader will be recompiled and this can be expensive. + * @param define the define name e.g., "OUTPUT_TO_SRGB" or "#define OUTPUT_TO_SRGB". If the define was passed into the constructor already, the version used should match that, and in either case, it should not include any appended value. + * @param value either the value of the define (e.g. a numerical value) or for booleans, true if the define should be enabled or false if it should be disabled + * @returns the material itself allowing "fluent" like uniform updates + */ + setDefine(define, value) { + // First remove any existing define with this name. + const defineName = define.trimEnd() + " "; + const existingDefineIdx = this.options.defines.findIndex((x) => x === define || x.startsWith(defineName)); + if (existingDefineIdx >= 0) { + this.options.defines.splice(existingDefineIdx, 1); + } + // Then add the new define value. (If it's a boolean value and false, don't add it.) + if (typeof value !== "boolean" || value) { + this.options.defines.push(defineName + value); + } + return this; + } + /** + * Specifies that the submesh is ready to be used + * @param mesh defines the mesh to check + * @param subMesh defines which submesh to check + * @param useInstances specifies that instances should be used + * @returns a boolean indicating that the submesh is ready or not + */ + isReadyForSubMesh(mesh, subMesh, useInstances) { + return this.isReady(mesh, useInstances, subMesh); + } + /** + * Checks if the material is ready to render the requested mesh + * @param mesh Define the mesh to render + * @param useInstances Define whether or not the material is used with instances + * @param subMesh defines which submesh to render + * @returns true if ready, otherwise false + */ + isReady(mesh, useInstances, subMesh) { + const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes; + if (this.isFrozen) { + const drawWrapper = storeEffectOnSubMeshes ? subMesh._drawWrapper : this._drawWrapper; + if (drawWrapper.effect && drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) { + return true; + } + } + const scene = this.getScene(); + const engine = scene.getEngine(); + // Instances + const defines = []; + const attribs = []; + let fallbacks = null; + let shaderName = this._shaderPath, uniforms = this._options.uniforms, uniformBuffers = this._options.uniformBuffers, samplers = this._options.samplers; + // global multiview + if (engine.getCaps().multiview && scene.activeCamera && scene.activeCamera.outputRenderTarget && scene.activeCamera.outputRenderTarget.getViewCount() > 1) { + this._multiview = true; + defines.push("#define MULTIVIEW"); + if (uniforms.indexOf("viewProjection") !== -1 && uniforms.indexOf("viewProjectionR") === -1) { + uniforms.push("viewProjectionR"); + } + } + for (let index = 0; index < this._options.defines.length; index++) { + const defineToAdd = this._options.defines[index].indexOf("#define") === 0 ? this._options.defines[index] : `#define ${this._options.defines[index]}`; + defines.push(defineToAdd); + } + for (let index = 0; index < this._options.attributes.length; index++) { + attribs.push(this._options.attributes[index]); + } + if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) { + if (attribs.indexOf(VertexBuffer.ColorKind) === -1) { + attribs.push(VertexBuffer.ColorKind); + } + defines.push("#define VERTEXCOLOR"); + } + if (useInstances) { + defines.push("#define INSTANCES"); + PushAttributesForInstances(attribs, this._materialHelperNeedsPreviousMatrices); + if (mesh?.hasThinInstances) { + defines.push("#define THIN_INSTANCES"); + if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorInstanceKind)) { + attribs.push(VertexBuffer.ColorInstanceKind); + defines.push("#define INSTANCESCOLOR"); + } + } + } + // Bones + if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + attribs.push(VertexBuffer.MatricesIndicesKind); + attribs.push(VertexBuffer.MatricesWeightsKind); + if (mesh.numBoneInfluencers > 4) { + attribs.push(VertexBuffer.MatricesIndicesExtraKind); + attribs.push(VertexBuffer.MatricesWeightsExtraKind); + } + const skeleton = mesh.skeleton; + defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); + fallbacks = new EffectFallbacks(); + fallbacks.addCPUSkinningFallback(0, mesh); + if (skeleton.isUsingTextureForMatrices) { + defines.push("#define BONETEXTURE"); + if (uniforms.indexOf("boneTextureWidth") === -1) { + uniforms.push("boneTextureWidth"); + } + if (this._options.samplers.indexOf("boneSampler") === -1) { + this._options.samplers.push("boneSampler"); + } + } + else { + defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); + if (uniforms.indexOf("mBones") === -1) { + uniforms.push("mBones"); + } + } + } + else { + defines.push("#define NUM_BONE_INFLUENCERS 0"); + } + // Morph + let numInfluencers = 0; + const manager = mesh ? mesh.morphTargetManager : null; + if (manager) { + const uv = defines.indexOf("#define UV1") !== -1; + const uv2 = defines.indexOf("#define UV2") !== -1; + const tangent = defines.indexOf("#define TANGENT") !== -1; + const normal = defines.indexOf("#define NORMAL") !== -1; + const color = defines.indexOf("#define VERTEXCOLOR") !== -1; + numInfluencers = PrepareDefinesAndAttributesForMorphTargets(manager, defines, attribs, mesh, true, // usePositionMorph + normal, // useNormalMorph + tangent, // useTangentMorph + uv, // useUVMorph + uv2, // useUV2Morph + color // useColorMorph + ); + if (manager.isUsingTextureForTargets) { + if (uniforms.indexOf("morphTargetTextureIndices") === -1) { + uniforms.push("morphTargetTextureIndices"); + } + if (this._options.samplers.indexOf("morphTargets") === -1) { + this._options.samplers.push("morphTargets"); + } + } + if (numInfluencers > 0) { + uniforms = uniforms.slice(); + uniforms.push("morphTargetInfluences"); + uniforms.push("morphTargetCount"); + uniforms.push("morphTargetTextureInfo"); + uniforms.push("morphTargetTextureIndices"); + } + } + else { + defines.push("#define NUM_MORPH_INFLUENCERS 0"); + } + // Baked Vertex Animation + if (mesh) { + const bvaManager = mesh.bakedVertexAnimationManager; + if (bvaManager && bvaManager.isEnabled) { + defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"); + if (uniforms.indexOf("bakedVertexAnimationSettings") === -1) { + uniforms.push("bakedVertexAnimationSettings"); + } + if (uniforms.indexOf("bakedVertexAnimationTextureSizeInverted") === -1) { + uniforms.push("bakedVertexAnimationTextureSizeInverted"); + } + if (uniforms.indexOf("bakedVertexAnimationTime") === -1) { + uniforms.push("bakedVertexAnimationTime"); + } + if (this._options.samplers.indexOf("bakedVertexAnimationTexture") === -1) { + this._options.samplers.push("bakedVertexAnimationTexture"); + } + } + PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines); + } + // Textures + for (const name in this._textures) { + if (!this._textures[name].isReady()) { + return false; + } + } + // Alpha test + if (mesh && this.needAlphaTestingForMesh(mesh)) { + defines.push("#define ALPHATEST"); + } + // Clip planes + if (this._options.useClipPlane !== false) { + addClipPlaneUniforms(uniforms); + prepareStringDefinesForClipPlanes(this, scene, defines); + } + // Fog + if (scene.fogEnabled && mesh?.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) { + defines.push("#define FOG"); + if (uniforms.indexOf("view") === -1) { + uniforms.push("view"); + } + if (uniforms.indexOf("vFogInfos") === -1) { + uniforms.push("vFogInfos"); + } + if (uniforms.indexOf("vFogColor") === -1) { + uniforms.push("vFogColor"); + } + } + // Misc + if (this._useLogarithmicDepth) { + defines.push("#define LOGARITHMICDEPTH"); + if (uniforms.indexOf("logarithmicDepthConstant") === -1) { + uniforms.push("logarithmicDepthConstant"); + } + } + if (this.customShaderNameResolve) { + uniforms = uniforms.slice(); + uniformBuffers = uniformBuffers.slice(); + samplers = samplers.slice(); + shaderName = this.customShaderNameResolve(this.name, uniforms, uniformBuffers, samplers, defines, attribs); + } + const drawWrapper = storeEffectOnSubMeshes ? subMesh._getDrawWrapper(undefined, true) : this._drawWrapper; + const previousEffect = drawWrapper?.effect ?? null; + const previousDefines = drawWrapper?.defines ?? null; + const join = defines.join("\n"); + let effect = previousEffect; + if (previousDefines !== join) { + effect = engine.createEffect(shaderName, { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: join, + fallbacks: fallbacks, + onCompiled: this.onCompiled, + onError: this.onError, + indexParameters: { maxSimultaneousMorphTargets: numInfluencers }, + shaderLanguage: this._options.shaderLanguage, + extraInitializationsAsync: this._options.extraInitializationsAsync, + }, engine); + if (storeEffectOnSubMeshes) { + subMesh.setEffect(effect, join, this._materialContext); + } + else if (drawWrapper) { + drawWrapper.setEffect(effect, join); + } + if (this._onEffectCreatedObservable) { + onCreatedEffectParameters$2.effect = effect; + onCreatedEffectParameters$2.subMesh = subMesh ?? mesh?.subMeshes[0] ?? null; + this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$2); + } + } + drawWrapper._wasPreviouslyUsingInstances = !!useInstances; + if (!effect?.isReady()) { + return false; + } + if (previousEffect !== effect) { + scene.resetCachedMaterial(); + } + drawWrapper._wasPreviouslyReady = true; + return true; + } + /** + * Binds the world matrix to the material + * @param world defines the world transformation matrix + * @param effectOverride - If provided, use this effect instead of internal effect + */ + bindOnlyWorldMatrix(world, effectOverride) { + const effect = effectOverride ?? this.getEffect(); + if (!effect) { + return; + } + const uniforms = this._options.uniforms; + if (uniforms.indexOf("world") !== -1) { + effect.setMatrix("world", world); + } + const scene = this.getScene(); + if (uniforms.indexOf("worldView") !== -1) { + world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix); + effect.setMatrix("worldView", this._cachedWorldViewMatrix); + } + if (uniforms.indexOf("worldViewProjection") !== -1) { + world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix); + effect.setMatrix("worldViewProjection", this._cachedWorldViewProjectionMatrix); + } + if (uniforms.indexOf("view") !== -1) { + effect.setMatrix("view", scene.getViewMatrix()); + } + } + /** + * Binds the submesh to this material by preparing the effect and shader to draw + * @param world defines the world transformation matrix + * @param mesh defines the mesh containing the submesh + * @param subMesh defines the submesh to bind the material to + */ + bindForSubMesh(world, mesh, subMesh) { + this.bind(world, mesh, subMesh._drawWrapperOverride?.effect, subMesh); + } + /** + * Binds the material to the mesh + * @param world defines the world transformation matrix + * @param mesh defines the mesh to bind the material to + * @param effectOverride - If provided, use this effect instead of internal effect + * @param subMesh defines the submesh to bind the material to + */ + bind(world, mesh, effectOverride, subMesh) { + // Std values + const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes; + const effect = effectOverride ?? (storeEffectOnSubMeshes ? subMesh.effect : this.getEffect()); + if (!effect) { + return; + } + const scene = this.getScene(); + this._activeEffect = effect; + this.bindOnlyWorldMatrix(world, effectOverride); + const uniformBuffers = this._options.uniformBuffers; + let useSceneUBO = false; + if (effect && uniformBuffers && uniformBuffers.length > 0 && scene.getEngine().supportsUniformBuffers) { + for (let i = 0; i < uniformBuffers.length; ++i) { + const bufferName = uniformBuffers[i]; + switch (bufferName) { + case "Mesh": + if (mesh) { + mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); + mesh.transferToEffect(world); + } + break; + case "Scene": + BindSceneUniformBuffer(effect, scene.getSceneUniformBuffer()); + scene.finalizeSceneUbo(); + useSceneUBO = true; + break; + } + } + } + const mustRebind = mesh && storeEffectOnSubMeshes ? this._mustRebind(scene, effect, subMesh, mesh.visibility) : scene.getCachedMaterial() !== this; + if (effect && mustRebind) { + if (!useSceneUBO && this._options.uniforms.indexOf("view") !== -1) { + effect.setMatrix("view", scene.getViewMatrix()); + } + if (!useSceneUBO && this._options.uniforms.indexOf("projection") !== -1) { + effect.setMatrix("projection", scene.getProjectionMatrix()); + } + if (!useSceneUBO && this._options.uniforms.indexOf("viewProjection") !== -1) { + effect.setMatrix("viewProjection", scene.getTransformMatrix()); + if (this._multiview) { + effect.setMatrix("viewProjectionR", scene._transformMatrixR); + } + } + if (scene.activeCamera && this._options.uniforms.indexOf("cameraPosition") !== -1) { + effect.setVector3("cameraPosition", scene.activeCamera.globalPosition); + } + // Bones + BindBonesParameters(mesh, effect); + // Clip plane + bindClipPlane(effect, this, scene); + // Misc + if (this._useLogarithmicDepth) { + BindLogDepth(storeEffectOnSubMeshes ? subMesh.materialDefines : effect.defines, effect, scene); + } + // Fog + if (mesh) { + BindFogParameters(scene, mesh, effect); + } + let name; + // Texture + for (name in this._textures) { + effect.setTexture(name, this._textures[name]); + } + // Texture arrays + for (name in this._textureArrays) { + effect.setTextureArray(name, this._textureArrays[name]); + } + // Int + for (name in this._ints) { + effect.setInt(name, this._ints[name]); + } + // UInt + for (name in this._uints) { + effect.setUInt(name, this._uints[name]); + } + // Float + for (name in this._floats) { + effect.setFloat(name, this._floats[name]); + } + // Floats + for (name in this._floatsArrays) { + effect.setArray(name, this._floatsArrays[name]); + } + // Color3 + for (name in this._colors3) { + effect.setColor3(name, this._colors3[name]); + } + // Color3Array + for (name in this._colors3Arrays) { + effect.setArray3(name, this._colors3Arrays[name]); + } + // Color4 + for (name in this._colors4) { + const color = this._colors4[name]; + effect.setFloat4(name, color.r, color.g, color.b, color.a); + } + // Color4Array + for (name in this._colors4Arrays) { + effect.setArray4(name, this._colors4Arrays[name]); + } + // Vector2 + for (name in this._vectors2) { + effect.setVector2(name, this._vectors2[name]); + } + // Vector3 + for (name in this._vectors3) { + effect.setVector3(name, this._vectors3[name]); + } + // Vector4 + for (name in this._vectors4) { + effect.setVector4(name, this._vectors4[name]); + } + // Quaternion + for (name in this._quaternions) { + effect.setQuaternion(name, this._quaternions[name]); + } + // Matrix + for (name in this._matrices) { + effect.setMatrix(name, this._matrices[name]); + } + // MatrixArray + for (name in this._matrixArrays) { + effect.setMatrices(name, this._matrixArrays[name]); + } + // Matrix 3x3 + for (name in this._matrices3x3) { + effect.setMatrix3x3(name, this._matrices3x3[name]); + } + // Matrix 2x2 + for (name in this._matrices2x2) { + effect.setMatrix2x2(name, this._matrices2x2[name]); + } + // Vector2Array + for (name in this._vectors2Arrays) { + effect.setArray2(name, this._vectors2Arrays[name]); + } + // Vector3Array + for (name in this._vectors3Arrays) { + effect.setArray3(name, this._vectors3Arrays[name]); + } + // Vector4Array + for (name in this._vectors4Arrays) { + effect.setArray4(name, this._vectors4Arrays[name]); + } + // QuaternionArray + for (name in this._quaternionsArrays) { + effect.setArray4(name, this._quaternionsArrays[name]); + } + // Uniform buffers + for (name in this._uniformBuffers) { + const buffer = this._uniformBuffers[name].getBuffer(); + if (buffer) { + effect.bindUniformBuffer(buffer, name); + } + } + const engineWebGPU = scene.getEngine(); + // External texture + const setExternalTexture = engineWebGPU.setExternalTexture; + if (setExternalTexture) { + for (name in this._externalTextures) { + setExternalTexture.call(engineWebGPU, name, this._externalTextures[name]); + } + } + // Samplers + const setTextureSampler = engineWebGPU.setTextureSampler; + if (setTextureSampler) { + for (name in this._textureSamplers) { + setTextureSampler.call(engineWebGPU, name, this._textureSamplers[name]); + } + } + // Storage buffers + const setStorageBuffer = engineWebGPU.setStorageBuffer; + if (setStorageBuffer) { + for (name in this._storageBuffers) { + setStorageBuffer.call(engineWebGPU, name, this._storageBuffers[name]); + } + } + } + if (effect && mesh && (mustRebind || !this.isFrozen)) { + // Morph targets + BindMorphTargetParameters(mesh, effect); + if (mesh.morphTargetManager && mesh.morphTargetManager.isUsingTextureForTargets) { + mesh.morphTargetManager._bind(effect); + } + const bvaManager = mesh.bakedVertexAnimationManager; + if (bvaManager && bvaManager.isEnabled) { + const drawWrapper = storeEffectOnSubMeshes ? subMesh._drawWrapper : this._drawWrapper; + mesh.bakedVertexAnimationManager?.bind(effect, !!drawWrapper._wasPreviouslyUsingInstances); + } + } + this._afterBind(mesh, effect, subMesh); + } + /** + * Gets the active textures from the material + * @returns an array of textures + */ + getActiveTextures() { + const activeTextures = super.getActiveTextures(); + for (const name in this._textures) { + activeTextures.push(this._textures[name]); + } + for (const name in this._textureArrays) { + const array = this._textureArrays[name]; + for (let index = 0; index < array.length; index++) { + activeTextures.push(array[index]); + } + } + return activeTextures; + } + /** + * Specifies if the material uses a texture + * @param texture defines the texture to check against the material + * @returns a boolean specifying if the material uses the texture + */ + hasTexture(texture) { + if (super.hasTexture(texture)) { + return true; + } + for (const name in this._textures) { + if (this._textures[name] === texture) { + return true; + } + } + for (const name in this._textureArrays) { + const array = this._textureArrays[name]; + for (let index = 0; index < array.length; index++) { + if (array[index] === texture) { + return true; + } + } + } + return false; + } + /** + * Makes a duplicate of the material, and gives it a new name + * @param name defines the new name for the duplicated material + * @returns the cloned material + */ + clone(name) { + const result = SerializationHelper.Clone(() => new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options, this._storeEffectOnSubMeshes), this); + result.name = name; + result.id = name; + // Shader code path + if (typeof result._shaderPath === "object") { + result._shaderPath = { ...result._shaderPath }; + } + // Options + this._options = { ...this._options }; + Object.keys(this._options).forEach((propName) => { + const propValue = this._options[propName]; + if (Array.isArray(propValue)) { + this._options[propName] = propValue.slice(0); + } + }); + // Stencil + this.stencil.copyTo(result.stencil); + // Texture + for (const key in this._textures) { + result.setTexture(key, this._textures[key]); + } + // TextureArray + for (const key in this._textureArrays) { + result.setTextureArray(key, this._textureArrays[key]); + } + // External texture + for (const key in this._externalTextures) { + result.setExternalTexture(key, this._externalTextures[key]); + } + // Int + for (const key in this._ints) { + result.setInt(key, this._ints[key]); + } + // UInt + for (const key in this._uints) { + result.setUInt(key, this._uints[key]); + } + // Float + for (const key in this._floats) { + result.setFloat(key, this._floats[key]); + } + // Floats + for (const key in this._floatsArrays) { + result.setFloats(key, this._floatsArrays[key]); + } + // Color3 + for (const key in this._colors3) { + result.setColor3(key, this._colors3[key]); + } + // Color3Array + for (const key in this._colors3Arrays) { + result._colors3Arrays[key] = this._colors3Arrays[key]; + } + // Color4 + for (const key in this._colors4) { + result.setColor4(key, this._colors4[key]); + } + // Color4Array + for (const key in this._colors4Arrays) { + result._colors4Arrays[key] = this._colors4Arrays[key]; + } + // Vector2 + for (const key in this._vectors2) { + result.setVector2(key, this._vectors2[key]); + } + // Vector3 + for (const key in this._vectors3) { + result.setVector3(key, this._vectors3[key]); + } + // Vector4 + for (const key in this._vectors4) { + result.setVector4(key, this._vectors4[key]); + } + // Quaternion + for (const key in this._quaternions) { + result.setQuaternion(key, this._quaternions[key]); + } + // QuaternionArray + for (const key in this._quaternionsArrays) { + result._quaternionsArrays[key] = this._quaternionsArrays[key]; + } + // Matrix + for (const key in this._matrices) { + result.setMatrix(key, this._matrices[key]); + } + // MatrixArray + for (const key in this._matrixArrays) { + result._matrixArrays[key] = this._matrixArrays[key].slice(); + } + // Matrix 3x3 + for (const key in this._matrices3x3) { + result.setMatrix3x3(key, this._matrices3x3[key]); + } + // Matrix 2x2 + for (const key in this._matrices2x2) { + result.setMatrix2x2(key, this._matrices2x2[key]); + } + // Vector2Array + for (const key in this._vectors2Arrays) { + result.setArray2(key, this._vectors2Arrays[key]); + } + // Vector3Array + for (const key in this._vectors3Arrays) { + result.setArray3(key, this._vectors3Arrays[key]); + } + // Vector4Array + for (const key in this._vectors4Arrays) { + result.setArray4(key, this._vectors4Arrays[key]); + } + // Uniform buffers + for (const key in this._uniformBuffers) { + result.setUniformBuffer(key, this._uniformBuffers[key]); + } + // Samplers + for (const key in this._textureSamplers) { + result.setTextureSampler(key, this._textureSamplers[key]); + } + // Storag buffers + for (const key in this._storageBuffers) { + result.setStorageBuffer(key, this._storageBuffers[key]); + } + return result; + } + /** + * Disposes the material + * @param forceDisposeEffect specifies if effects should be forcefully disposed + * @param forceDisposeTextures specifies if textures should be forcefully disposed + * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh + */ + dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { + if (forceDisposeTextures) { + let name; + for (name in this._textures) { + this._textures[name].dispose(); + } + for (name in this._textureArrays) { + const array = this._textureArrays[name]; + for (let index = 0; index < array.length; index++) { + array[index].dispose(); + } + } + } + this._textures = {}; + super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh); + } + /** + * Serializes this material in a JSON representation + * @returns the serialized material object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.customType = "BABYLON.ShaderMaterial"; + serializationObject.uniqueId = this.uniqueId; + serializationObject.options = this._options; + serializationObject.shaderPath = this._shaderPath; + serializationObject.storeEffectOnSubMeshes = this._storeEffectOnSubMeshes; + let name; + // Stencil + serializationObject.stencil = this.stencil.serialize(); + // Texture + serializationObject.textures = {}; + for (name in this._textures) { + serializationObject.textures[name] = this._textures[name].serialize(); + } + // Texture arrays + serializationObject.textureArrays = {}; + for (name in this._textureArrays) { + serializationObject.textureArrays[name] = []; + const array = this._textureArrays[name]; + for (let index = 0; index < array.length; index++) { + serializationObject.textureArrays[name].push(array[index].serialize()); + } + } + // Int + serializationObject.ints = {}; + for (name in this._ints) { + serializationObject.ints[name] = this._ints[name]; + } + // UInt + serializationObject.uints = {}; + for (name in this._uints) { + serializationObject.uints[name] = this._uints[name]; + } + // Float + serializationObject.floats = {}; + for (name in this._floats) { + serializationObject.floats[name] = this._floats[name]; + } + // Floats + serializationObject.floatsArrays = {}; + for (name in this._floatsArrays) { + serializationObject.floatsArrays[name] = this._floatsArrays[name]; + } + // Color3 + serializationObject.colors3 = {}; + for (name in this._colors3) { + serializationObject.colors3[name] = this._colors3[name].asArray(); + } + // Color3 array + serializationObject.colors3Arrays = {}; + for (name in this._colors3Arrays) { + serializationObject.colors3Arrays[name] = this._colors3Arrays[name]; + } + // Color4 + serializationObject.colors4 = {}; + for (name in this._colors4) { + serializationObject.colors4[name] = this._colors4[name].asArray(); + } + // Color4 array + serializationObject.colors4Arrays = {}; + for (name in this._colors4Arrays) { + serializationObject.colors4Arrays[name] = this._colors4Arrays[name]; + } + // Vector2 + serializationObject.vectors2 = {}; + for (name in this._vectors2) { + const v2 = this._vectors2[name]; + serializationObject.vectors2[name] = [v2.x, v2.y]; + } + // Vector3 + serializationObject.vectors3 = {}; + for (name in this._vectors3) { + const v3 = this._vectors3[name]; + serializationObject.vectors3[name] = [v3.x, v3.y, v3.z]; + } + // Vector4 + serializationObject.vectors4 = {}; + for (name in this._vectors4) { + const v4 = this._vectors4[name]; + serializationObject.vectors4[name] = [v4.x, v4.y, v4.z, v4.w]; + } + // Quaternion + serializationObject.quaternions = {}; + for (name in this._quaternions) { + serializationObject.quaternions[name] = this._quaternions[name].asArray(); + } + // Matrix + serializationObject.matrices = {}; + for (name in this._matrices) { + serializationObject.matrices[name] = this._matrices[name].asArray(); + } + // MatrixArray + serializationObject.matrixArray = {}; + for (name in this._matrixArrays) { + serializationObject.matrixArray[name] = this._matrixArrays[name]; + } + // Matrix 3x3 + serializationObject.matrices3x3 = {}; + for (name in this._matrices3x3) { + serializationObject.matrices3x3[name] = this._matrices3x3[name]; + } + // Matrix 2x2 + serializationObject.matrices2x2 = {}; + for (name in this._matrices2x2) { + serializationObject.matrices2x2[name] = this._matrices2x2[name]; + } + // Vector2Array + serializationObject.vectors2Arrays = {}; + for (name in this._vectors2Arrays) { + serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name]; + } + // Vector3Array + serializationObject.vectors3Arrays = {}; + for (name in this._vectors3Arrays) { + serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name]; + } + // Vector4Array + serializationObject.vectors4Arrays = {}; + for (name in this._vectors4Arrays) { + serializationObject.vectors4Arrays[name] = this._vectors4Arrays[name]; + } + // QuaternionArray + serializationObject.quaternionsArrays = {}; + for (name in this._quaternionsArrays) { + serializationObject.quaternionsArrays[name] = this._quaternionsArrays[name]; + } + return serializationObject; + } + /** + * Creates a shader material from parsed shader material data + * @param source defines the JSON representation of the material + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a new material + */ + static Parse(source, scene, rootUrl) { + const material = SerializationHelper.Parse(() => new ShaderMaterial(source.name, scene, source.shaderPath, source.options, source.storeEffectOnSubMeshes), source, scene, rootUrl); + let name; + // Stencil + if (source.stencil) { + material.stencil.parse(source.stencil, scene, rootUrl); + } + // Texture + for (name in source.textures) { + material.setTexture(name, Texture.Parse(source.textures[name], scene, rootUrl)); + } + // Texture arrays + for (name in source.textureArrays) { + const array = source.textureArrays[name]; + const textureArray = []; + for (let index = 0; index < array.length; index++) { + textureArray.push(Texture.Parse(array[index], scene, rootUrl)); + } + material.setTextureArray(name, textureArray); + } + // Int + for (name in source.ints) { + material.setInt(name, source.ints[name]); + } + // UInt + for (name in source.uints) { + material.setUInt(name, source.uints[name]); + } + // Float + for (name in source.floats) { + material.setFloat(name, source.floats[name]); + } + // Floats + for (name in source.floatsArrays) { + material.setFloats(name, source.floatsArrays[name]); + } + // Color3 + for (name in source.colors3) { + material.setColor3(name, Color3.FromArray(source.colors3[name])); + } + // Color3 arrays + for (name in source.colors3Arrays) { + const colors = source.colors3Arrays[name] + .reduce((arr, num, i) => { + if (i % 3 === 0) { + arr.push([num]); + } + else { + arr[arr.length - 1].push(num); + } + return arr; + }, []) + .map((color) => Color3.FromArray(color)); + material.setColor3Array(name, colors); + } + // Color4 + for (name in source.colors4) { + material.setColor4(name, Color4.FromArray(source.colors4[name])); + } + // Color4 arrays + for (name in source.colors4Arrays) { + const colors = source.colors4Arrays[name] + .reduce((arr, num, i) => { + if (i % 4 === 0) { + arr.push([num]); + } + else { + arr[arr.length - 1].push(num); + } + return arr; + }, []) + .map((color) => Color4.FromArray(color)); + material.setColor4Array(name, colors); + } + // Vector2 + for (name in source.vectors2) { + material.setVector2(name, Vector2.FromArray(source.vectors2[name])); + } + // Vector3 + for (name in source.vectors3) { + material.setVector3(name, Vector3.FromArray(source.vectors3[name])); + } + // Vector4 + for (name in source.vectors4) { + material.setVector4(name, Vector4.FromArray(source.vectors4[name])); + } + // Quaternion + for (name in source.quaternions) { + material.setQuaternion(name, Quaternion.FromArray(source.quaternions[name])); + } + // Matrix + for (name in source.matrices) { + material.setMatrix(name, Matrix.FromArray(source.matrices[name])); + } + // MatrixArray + for (name in source.matrixArray) { + material._matrixArrays[name] = new Float32Array(source.matrixArray[name]); + } + // Matrix 3x3 + for (name in source.matrices3x3) { + material.setMatrix3x3(name, source.matrices3x3[name]); + } + // Matrix 2x2 + for (name in source.matrices2x2) { + material.setMatrix2x2(name, source.matrices2x2[name]); + } + // Vector2Array + for (name in source.vectors2Arrays) { + material.setArray2(name, source.vectors2Arrays[name]); + } + // Vector3Array + for (name in source.vectors3Arrays) { + material.setArray3(name, source.vectors3Arrays[name]); + } + // Vector4Array + for (name in source.vectors4Arrays) { + material.setArray4(name, source.vectors4Arrays[name]); + } + // QuaternionArray + for (name in source.quaternionsArrays) { + material.setArray4(name, source.quaternionsArrays[name]); + } + return material; + } + /** + * Creates a new ShaderMaterial from a snippet saved in a remote file + * @param name defines the name of the ShaderMaterial to create (can be null or empty to use the one from the json data) + * @param url defines the url to load from + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a promise that will resolve to the new ShaderMaterial + */ + static ParseFromFileAsync(name, url, scene, rootUrl = "") { + return new Promise((resolve, reject) => { + const request = new WebRequest(); + request.addEventListener("readystatechange", () => { + if (request.readyState == 4) { + if (request.status == 200) { + const serializationObject = JSON.parse(request.responseText); + const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl); + if (name) { + output.name = name; + } + resolve(output); + } + else { + reject("Unable to load the ShaderMaterial"); + } + } + }); + request.open("GET", url); + request.send(); + }); + } + /** + * Creates a ShaderMaterial from a snippet saved by the Inspector + * @param snippetId defines the snippet to load + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a promise that will resolve to the new ShaderMaterial + */ + static ParseFromSnippetAsync(snippetId, scene, rootUrl = "") { + return new Promise((resolve, reject) => { + const request = new WebRequest(); + request.addEventListener("readystatechange", () => { + if (request.readyState == 4) { + if (request.status == 200) { + const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); + const serializationObject = JSON.parse(snippet.shaderMaterial); + const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl); + output.snippetId = snippetId; + resolve(output); + } + else { + reject("Unable to load the snippet " + snippetId); + } + } + }); + request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); + request.send(); + }); + } +} +/** Define the Url to load snippets */ +ShaderMaterial.SnippetUrl = `https://snippet.babylonjs.com`; +/** + * Creates a ShaderMaterial from a snippet saved by the Inspector + * @deprecated Please use ParseFromSnippetAsync instead + * @param snippetId defines the snippet to load + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a promise that will resolve to the new ShaderMaterial + */ +ShaderMaterial.CreateFromSnippetAsync = ShaderMaterial.ParseFromSnippetAsync; +RegisterClass("BABYLON.ShaderMaterial", ShaderMaterial); + +Node$2.AddNodeConstructor("Light_Type_3", (name, scene) => { + return () => new HemisphericLight(name, Vector3.Zero(), scene); +}); +/** + * The HemisphericLight simulates the ambient environment light, + * so the passed direction is the light reflection direction, not the incoming direction. + */ +class HemisphericLight extends Light { + /** + * Creates a HemisphericLight object in the scene according to the passed direction (Vector3). + * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction. + * The HemisphericLight can't cast shadows. + * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + * @param name The friendly name of the light + * @param direction The direction of the light reflection + * @param scene The scene the light belongs to + */ + constructor(name, direction, scene) { + super(name, scene); + /** + * The groundColor is the light in the opposite direction to the one specified during creation. + * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction. + */ + this.groundColor = new Color3(0.0, 0.0, 0.0); + this.direction = direction || Vector3.Up(); + } + _buildUniformLayout() { + this._uniformBuffer.addUniform("vLightData", 4); + this._uniformBuffer.addUniform("vLightDiffuse", 4); + this._uniformBuffer.addUniform("vLightSpecular", 4); + this._uniformBuffer.addUniform("vLightGround", 3); + this._uniformBuffer.addUniform("shadowsInfo", 3); + this._uniformBuffer.addUniform("depthValues", 2); + this._uniformBuffer.create(); + } + /** + * Returns the string "HemisphericLight". + * @returns The class name + */ + getClassName() { + return "HemisphericLight"; + } + /** + * Sets the HemisphericLight direction towards the passed target (Vector3). + * Returns the updated direction. + * @param target The target the direction should point to + * @returns The computed direction + */ + setDirectionToTarget(target) { + this.direction = Vector3.Normalize(target.subtract(Vector3.Zero())); + return this.direction; + } + /** + * Returns the shadow generator associated to the light. + * @returns Always null for hemispheric lights because it does not support shadows. + */ + getShadowGenerator() { + return null; + } + /** + * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string). + * @param _effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The hemispheric light + */ + transferToEffect(_effect, lightIndex) { + const normalizeDirection = Vector3.Normalize(this.direction); + this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex); + this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex); + return this; + } + transferToNodeMaterialEffect(effect, lightDataUniformName) { + const normalizeDirection = Vector3.Normalize(this.direction); + effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z); + return this; + } + /** + * Computes the world matrix of the node + * @returns the world matrix + */ + computeWorldMatrix() { + if (!this._worldMatrix) { + this._worldMatrix = Matrix.Identity(); + } + return this._worldMatrix; + } + /** + * Returns the integer 3. + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + getTypeID() { + return Light.LIGHTTYPEID_HEMISPHERICLIGHT; + } + /** + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect + */ + prepareLightSpecificDefines(defines, lightIndex) { + defines["HEMILIGHT" + lightIndex] = true; + } +} +__decorate([ + serializeAsColor3() +], HemisphericLight.prototype, "groundColor", void 0); +__decorate([ + serializeAsVector3() +], HemisphericLight.prototype, "direction", void 0); +// Register Class Name +RegisterClass("BABYLON.HemisphericLight", HemisphericLight); + +Node$2.AddNodeConstructor("Light_Type_0", (name, scene) => { + return () => new PointLight(name, Vector3.Zero(), scene); +}); +/** + * A point light is a light defined by an unique point in world space. + * The light is emitted in every direction from this point. + * A good example of a point light is a standard light bulb. + * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + */ +class PointLight extends ShadowLight { + /** + * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + * This specifies what angle the shadow will use to be created. + * + * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. + */ + get shadowAngle() { + return this._shadowAngle; + } + /** + * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + * This specifies what angle the shadow will use to be created. + * + * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. + */ + set shadowAngle(value) { + this._shadowAngle = value; + this.forceProjectionMatrixCompute(); + } + /** + * Gets the direction if it has been set. + * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + */ + get direction() { + return this._direction; + } + /** + * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + */ + set direction(value) { + const previousNeedCube = this.needCube(); + this._direction = value; + if (this.needCube() !== previousNeedCube && this._shadowGenerators) { + const iterator = this._shadowGenerators.values(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const shadowGenerator = key.value; + shadowGenerator.recreateShadowMap(); + } + } + } + /** + * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene. + * A PointLight emits the light in every direction. + * It can cast shadows. + * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it : + * ```javascript + * var pointLight = new PointLight("pl", camera.position, scene); + * ``` + * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + * @param name The light friendly name + * @param position The position of the point light in the scene + * @param scene The scene the lights belongs to + */ + constructor(name, position, scene) { + super(name, scene); + this._shadowAngle = Math.PI / 2; + this.position = position; + } + /** + * Returns the string "PointLight" + * @returns the class name + */ + getClassName() { + return "PointLight"; + } + /** + * Returns the integer 0. + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + getTypeID() { + return Light.LIGHTTYPEID_POINTLIGHT; + } + /** + * Specifies whether or not the shadowmap should be a cube texture. + * @returns true if the shadowmap needs to be a cube texture. + */ + needCube() { + return !this.direction; + } + /** + * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer). + * @param faceIndex The index of the face we are computed the direction to generate shadow + * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true + */ + getShadowDirection(faceIndex) { + if (this.direction) { + return super.getShadowDirection(faceIndex); + } + else { + switch (faceIndex) { + case 0: + return new Vector3(1.0, 0.0, 0.0); + case 1: + return new Vector3(-1, 0.0, 0.0); + case 2: + return new Vector3(0.0, -1, 0.0); + case 3: + return new Vector3(0.0, 1.0, 0.0); + case 4: + return new Vector3(0.0, 0.0, 1.0); + case 5: + return new Vector3(0.0, 0.0, -1); + } + } + return Vector3.Zero(); + } + /** + * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings : + * - fov = PI / 2 + * - aspect ratio : 1.0 + * - z-near and far equal to the active camera minZ and maxZ. + * Returns the PointLight. + * @param matrix + * @param viewMatrix + * @param renderList + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) { + const activeCamera = this.getScene().activeCamera; + if (!activeCamera) { + return; + } + const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ; + const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ; + const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer; + Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer); + } + _buildUniformLayout() { + this._uniformBuffer.addUniform("vLightData", 4); + this._uniformBuffer.addUniform("vLightDiffuse", 4); + this._uniformBuffer.addUniform("vLightSpecular", 4); + this._uniformBuffer.addUniform("vLightFalloff", 4); + this._uniformBuffer.addUniform("shadowsInfo", 3); + this._uniformBuffer.addUniform("depthValues", 2); + this._uniformBuffer.create(); + } + /** + * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string). + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The point light + */ + transferToEffect(effect, lightIndex) { + if (this.computeTransformedInformation()) { + this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex); + } + else { + this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex); + } + this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex); + return this; + } + transferToNodeMaterialEffect(effect, lightDataUniformName) { + if (this.computeTransformedInformation()) { + effect.setFloat3(lightDataUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z); + } + else { + effect.setFloat3(lightDataUniformName, this.position.x, this.position.y, this.position.z); + } + return this; + } + /** + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect + */ + prepareLightSpecificDefines(defines, lightIndex) { + defines["POINTLIGHT" + lightIndex] = true; + } +} +__decorate([ + serialize() +], PointLight.prototype, "shadowAngle", null); +// Register Class Name +RegisterClass("BABYLON.PointLight", PointLight); + +Node$2.AddNodeConstructor("Light_Type_2", (name, scene) => { + return () => new SpotLight(name, Vector3.Zero(), Vector3.Zero(), 0, 0, scene); +}); +/** + * A spot light is defined by a position, a direction, an angle, and an exponent. + * These values define a cone of light starting from the position, emitting toward the direction. + * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam, + * and the exponent defines the speed of the decay of the light with distance (reach). + * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + */ +class SpotLight extends ShadowLight { + /** + * Gets or sets the IES profile texture used to create the spotlight + * @see https://playground.babylonjs.com/#UIAXAU#1 + */ + get iesProfileTexture() { + return this._iesProfileTexture; + } + set iesProfileTexture(value) { + if (this._iesProfileTexture === value) { + return; + } + this._iesProfileTexture = value; + if (this._iesProfileTexture && SpotLight._IsTexture(this._iesProfileTexture)) { + this._iesProfileTexture.onLoadObservable.addOnce(() => { + this._markMeshesAsLightDirty(); + }); + } + } + /** + * Gets the cone angle of the spot light in Radians. + */ + get angle() { + return this._angle; + } + /** + * Sets the cone angle of the spot light in Radians. + */ + set angle(value) { + this._angle = value; + this._cosHalfAngle = Math.cos(value * 0.5); + this._projectionTextureProjectionLightDirty = true; + this.forceProjectionMatrixCompute(); + this._computeAngleValues(); + } + /** + * Only used in gltf falloff mode, this defines the angle where + * the directional falloff will start before cutting at angle which could be seen + * as outer angle. + */ + get innerAngle() { + return this._innerAngle; + } + /** + * Only used in gltf falloff mode, this defines the angle where + * the directional falloff will start before cutting at angle which could be seen + * as outer angle. + */ + set innerAngle(value) { + this._innerAngle = value; + this._computeAngleValues(); + } + /** + * Allows scaling the angle of the light for shadow generation only. + */ + get shadowAngleScale() { + return this._shadowAngleScale; + } + /** + * Allows scaling the angle of the light for shadow generation only. + */ + set shadowAngleScale(value) { + this._shadowAngleScale = value; + this.forceProjectionMatrixCompute(); + } + /** + * Allows reading the projection texture + */ + get projectionTextureMatrix() { + return this._projectionTextureMatrix; + } + /** + * Gets the near clip of the Spotlight for texture projection. + */ + get projectionTextureLightNear() { + return this._projectionTextureLightNear; + } + /** + * Sets the near clip of the Spotlight for texture projection. + */ + set projectionTextureLightNear(value) { + this._projectionTextureLightNear = value; + this._projectionTextureProjectionLightDirty = true; + } + /** + * Gets the far clip of the Spotlight for texture projection. + */ + get projectionTextureLightFar() { + return this._projectionTextureLightFar; + } + /** + * Sets the far clip of the Spotlight for texture projection. + */ + set projectionTextureLightFar(value) { + this._projectionTextureLightFar = value; + this._projectionTextureProjectionLightDirty = true; + } + /** + * Gets the Up vector of the Spotlight for texture projection. + */ + get projectionTextureUpDirection() { + return this._projectionTextureUpDirection; + } + /** + * Sets the Up vector of the Spotlight for texture projection. + */ + set projectionTextureUpDirection(value) { + this._projectionTextureUpDirection = value; + this._projectionTextureProjectionLightDirty = true; + } + /** + * Gets the projection texture of the light. + */ + get projectionTexture() { + return this._projectionTexture; + } + /** + * Sets the projection texture of the light. + */ + set projectionTexture(value) { + if (this._projectionTexture === value) { + return; + } + this._projectionTexture = value; + this._projectionTextureDirty = true; + if (this._projectionTexture && !this._projectionTexture.isReady()) { + if (SpotLight._IsProceduralTexture(this._projectionTexture)) { + this._projectionTexture.getEffect().executeWhenCompiled(() => { + this._markMeshesAsLightDirty(); + }); + } + else if (SpotLight._IsTexture(this._projectionTexture)) { + this._projectionTexture.onLoadObservable.addOnce(() => { + this._markMeshesAsLightDirty(); + }); + } + } + } + static _IsProceduralTexture(texture) { + return texture.onGeneratedObservable !== undefined; + } + static _IsTexture(texture) { + return texture.onLoadObservable !== undefined; + } + /** + * Gets or sets the light projection matrix as used by the projection texture + */ + get projectionTextureProjectionLightMatrix() { + return this._projectionTextureProjectionLightMatrix; + } + set projectionTextureProjectionLightMatrix(projection) { + this._projectionTextureProjectionLightMatrix = projection; + this._projectionTextureProjectionLightDirty = false; + this._projectionTextureDirty = true; + } + /** + * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone. + * It can cast shadows. + * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + * @param name The light friendly name + * @param position The position of the spot light in the scene + * @param direction The direction of the light in the scene + * @param angle The cone angle of the light in Radians + * @param exponent The light decay speed with the distance from the emission spot + * @param scene The scene the lights belongs to + */ + constructor(name, position, direction, angle, exponent, scene) { + super(name, scene); + this._innerAngle = 0; + this._iesProfileTexture = null; + this._projectionTextureMatrix = Matrix.Zero(); + this._projectionTextureLightNear = 1e-6; + this._projectionTextureLightFar = 1000.0; + this._projectionTextureUpDirection = Vector3.Up(); + this._projectionTextureViewLightDirty = true; + this._projectionTextureProjectionLightDirty = true; + this._projectionTextureDirty = true; + this._projectionTextureViewTargetVector = Vector3.Zero(); + this._projectionTextureViewLightMatrix = Matrix.Zero(); + this._projectionTextureProjectionLightMatrix = Matrix.Zero(); + this._projectionTextureScalingMatrix = Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0); + this.position = position; + this.direction = direction; + this.angle = angle; + this.exponent = exponent; + } + /** + * Returns the string "SpotLight". + * @returns the class name + */ + getClassName() { + return "SpotLight"; + } + /** + * Returns the integer 2. + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + getTypeID() { + return Light.LIGHTTYPEID_SPOTLIGHT; + } + /** + * Overrides the direction setter to recompute the projection texture view light Matrix. + * @param value + */ + _setDirection(value) { + super._setDirection(value); + this._projectionTextureViewLightDirty = true; + } + /** + * Overrides the position setter to recompute the projection texture view light Matrix. + * @param value + */ + _setPosition(value) { + super._setPosition(value); + this._projectionTextureViewLightDirty = true; + } + /** + * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0. + * Returns the SpotLight. + * @param matrix + * @param viewMatrix + * @param renderList + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) { + const activeCamera = this.getScene().activeCamera; + if (!activeCamera) { + return; + } + this._shadowAngleScale = this._shadowAngleScale || 1; + const angle = this._shadowAngleScale * this._angle; + const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ; + const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ; + const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer; + Matrix.PerspectiveFovLHToRef(angle, 1.0, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer); + } + _computeProjectionTextureViewLightMatrix() { + this._projectionTextureViewLightDirty = false; + this._projectionTextureDirty = true; + this.getAbsolutePosition().addToRef(this.getShadowDirection(), this._projectionTextureViewTargetVector); + Matrix.LookAtLHToRef(this.getAbsolutePosition(), this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix); + } + _computeProjectionTextureProjectionLightMatrix() { + this._projectionTextureProjectionLightDirty = false; + this._projectionTextureDirty = true; + const lightFar = this.projectionTextureLightFar; + const lightNear = this.projectionTextureLightNear; + const P = lightFar / (lightFar - lightNear); + const Q = -P * lightNear; + const S = 1.0 / Math.tan(this._angle / 2.0); + const A = 1.0; + Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix); + } + /** + * Main function for light texture projection matrix computing. + */ + _computeProjectionTextureMatrix() { + this._projectionTextureDirty = false; + this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix); + if (this._projectionTexture instanceof Texture) { + const u = this._projectionTexture.uScale / 2.0; + const v = this._projectionTexture.vScale / 2.0; + Matrix.FromValuesToRef(u, 0.0, 0.0, 0.0, 0.0, v, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0, this._projectionTextureScalingMatrix); + } + this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix); + } + _buildUniformLayout() { + this._uniformBuffer.addUniform("vLightData", 4); + this._uniformBuffer.addUniform("vLightDiffuse", 4); + this._uniformBuffer.addUniform("vLightSpecular", 4); + this._uniformBuffer.addUniform("vLightDirection", 3); + this._uniformBuffer.addUniform("vLightFalloff", 4); + this._uniformBuffer.addUniform("shadowsInfo", 3); + this._uniformBuffer.addUniform("depthValues", 2); + this._uniformBuffer.create(); + } + _computeAngleValues() { + this._lightAngleScale = 1.0 / Math.max(0.001, Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle); + this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale; + } + /** + * Sets the passed Effect "effect" with the Light textures. + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The light + */ + transferTexturesToEffect(effect, lightIndex) { + if (this.projectionTexture && this.projectionTexture.isReady()) { + if (this._projectionTextureViewLightDirty) { + this._computeProjectionTextureViewLightMatrix(); + } + if (this._projectionTextureProjectionLightDirty) { + this._computeProjectionTextureProjectionLightMatrix(); + } + if (this._projectionTextureDirty) { + this._computeProjectionTextureMatrix(); + } + effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix); + effect.setTexture("projectionLightTexture" + lightIndex, this.projectionTexture); + } + if (this._iesProfileTexture && this._iesProfileTexture.isReady()) { + effect.setTexture("iesLightTexture" + lightIndex, this._iesProfileTexture); + } + return this; + } + /** + * Sets the passed Effect object with the SpotLight transformed position (or position if not parented) and normalized direction. + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The spot light + */ + transferToEffect(effect, lightIndex) { + let normalizeDirection; + if (this.computeTransformedInformation()) { + this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex); + normalizeDirection = Vector3.Normalize(this.transformedDirection); + } + else { + this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex); + normalizeDirection = Vector3.Normalize(this.direction); + } + this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex); + this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex); + return this; + } + transferToNodeMaterialEffect(effect, lightDataUniformName) { + let normalizeDirection; + if (this.computeTransformedInformation()) { + normalizeDirection = Vector3.Normalize(this.transformedDirection); + } + else { + normalizeDirection = Vector3.Normalize(this.direction); + } + if (this.getScene().useRightHandedSystem) { + effect.setFloat3(lightDataUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z); + } + else { + effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z); + } + return this; + } + /** + * Disposes the light and the associated resources. + */ + dispose() { + super.dispose(); + if (this._projectionTexture) { + this._projectionTexture.dispose(); + } + if (this._iesProfileTexture) { + this._iesProfileTexture.dispose(); + this._iesProfileTexture = null; + } + } + /** + * Gets the minZ used for shadow according to both the scene and the light. + * @param activeCamera The camera we are returning the min for + * @returns the depth min z + */ + getDepthMinZ(activeCamera) { + const engine = this._scene.getEngine(); + const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : (activeCamera?.minZ ?? 0); + return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? minZ : this._scene.getEngine().isNDCHalfZRange ? 0 : minZ; + } + /** + * Gets the maxZ used for shadow according to both the scene and the light. + * @param activeCamera The camera we are returning the max for + * @returns the depth max z + */ + getDepthMaxZ(activeCamera) { + const engine = this._scene.getEngine(); + const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : (activeCamera?.maxZ ?? 10000); + return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : maxZ; + } + /** + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect + */ + prepareLightSpecificDefines(defines, lightIndex) { + defines["SPOTLIGHT" + lightIndex] = true; + defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture && this.projectionTexture.isReady() ? true : false; + defines["IESLIGHTTEXTURE" + lightIndex] = this._iesProfileTexture && this._iesProfileTexture.isReady() ? true : false; + } +} +__decorate([ + serialize() +], SpotLight.prototype, "angle", null); +__decorate([ + serialize() +], SpotLight.prototype, "innerAngle", null); +__decorate([ + serialize() +], SpotLight.prototype, "shadowAngleScale", null); +__decorate([ + serialize() +], SpotLight.prototype, "exponent", void 0); +__decorate([ + serialize() +], SpotLight.prototype, "projectionTextureLightNear", null); +__decorate([ + serialize() +], SpotLight.prototype, "projectionTextureLightFar", null); +__decorate([ + serialize() +], SpotLight.prototype, "projectionTextureUpDirection", null); +__decorate([ + serializeAsTexture("projectedLightTexture") +], SpotLight.prototype, "_projectionTexture", void 0); +// Register Class Name +RegisterClass("BABYLON.SpotLight", SpotLight); + +/** + * Utils functions for GLTF + * @internal + * @deprecated + */ +class GLTFUtils { + /** + * Sets the given "parameter" matrix + * @param scene the Scene object + * @param source the source node where to pick the matrix + * @param parameter the GLTF technique parameter + * @param uniformName the name of the shader's uniform + * @param shaderMaterial the shader material + */ + static SetMatrix(scene, source, parameter, uniformName, shaderMaterial) { + let mat = null; + if (parameter.semantic === "MODEL") { + mat = source.getWorldMatrix(); + } + else if (parameter.semantic === "PROJECTION") { + mat = scene.getProjectionMatrix(); + } + else if (parameter.semantic === "VIEW") { + mat = scene.getViewMatrix(); + } + else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") { + mat = Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert()); + } + else if (parameter.semantic === "MODELVIEW") { + mat = source.getWorldMatrix().multiply(scene.getViewMatrix()); + } + else if (parameter.semantic === "MODELVIEWPROJECTION") { + mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()); + } + else if (parameter.semantic === "MODELINVERSE") { + mat = source.getWorldMatrix().invert(); + } + else if (parameter.semantic === "VIEWINVERSE") { + mat = scene.getViewMatrix().invert(); + } + else if (parameter.semantic === "PROJECTIONINVERSE") { + mat = scene.getProjectionMatrix().invert(); + } + else if (parameter.semantic === "MODELVIEWINVERSE") { + mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert(); + } + else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") { + mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert(); + } + else if (parameter.semantic === "MODELINVERSETRANSPOSE") { + mat = Matrix.Transpose(source.getWorldMatrix().invert()); + } + if (mat) { + switch (parameter.type) { + case EParameterType.FLOAT_MAT2: + shaderMaterial.setMatrix2x2(uniformName, Matrix.GetAsMatrix2x2(mat)); + break; + case EParameterType.FLOAT_MAT3: + shaderMaterial.setMatrix3x3(uniformName, Matrix.GetAsMatrix3x3(mat)); + break; + case EParameterType.FLOAT_MAT4: + shaderMaterial.setMatrix(uniformName, mat); + break; + } + } + } + /** + * Sets the given "parameter" matrix + * @param shaderMaterial the shader material + * @param uniform the name of the shader's uniform + * @param value the value of the uniform + * @param type the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4) + * @returns true if set, else false + */ + static SetUniform(shaderMaterial, uniform, value, type) { + switch (type) { + case EParameterType.FLOAT: + shaderMaterial.setFloat(uniform, value); + return true; + case EParameterType.FLOAT_VEC2: + shaderMaterial.setVector2(uniform, Vector2.FromArray(value)); + return true; + case EParameterType.FLOAT_VEC3: + shaderMaterial.setVector3(uniform, Vector3.FromArray(value)); + return true; + case EParameterType.FLOAT_VEC4: + shaderMaterial.setVector4(uniform, Vector4.FromArray(value)); + return true; + default: + return false; + } + } + /** + * Returns the wrap mode of the texture + * @param mode the mode value + * @returns the wrap mode (TEXTURE_WRAP_ADDRESSMODE, MIRROR_ADDRESSMODE or CLAMP_ADDRESSMODE) + */ + static GetWrapMode(mode) { + switch (mode) { + case ETextureWrapMode.CLAMP_TO_EDGE: + return Texture.CLAMP_ADDRESSMODE; + case ETextureWrapMode.MIRRORED_REPEAT: + return Texture.MIRROR_ADDRESSMODE; + case ETextureWrapMode.REPEAT: + return Texture.WRAP_ADDRESSMODE; + default: + return Texture.WRAP_ADDRESSMODE; + } + } + /** + * Returns the byte stride giving an accessor + * @param accessor the GLTF accessor objet + * @returns the byte stride + */ + static GetByteStrideFromType(accessor) { + // Needs this function since "byteStride" isn't requiered in glTF format + const type = accessor.type; + switch (type) { + case "VEC2": + return 2; + case "VEC3": + return 3; + case "VEC4": + return 4; + case "MAT2": + return 4; + case "MAT3": + return 9; + case "MAT4": + return 16; + default: + return 1; + } + } + /** + * Returns the texture filter mode giving a mode value + * @param mode the filter mode value + * @returns the filter mode (TODO - needs to be a type?) + */ + static GetTextureFilterMode(mode) { + switch (mode) { + case ETextureFilterType.LINEAR: + case ETextureFilterType.LINEAR_MIPMAP_NEAREST: + case ETextureFilterType.LINEAR_MIPMAP_LINEAR: + return Texture.TRILINEAR_SAMPLINGMODE; + case ETextureFilterType.NEAREST: + case ETextureFilterType.NEAREST_MIPMAP_NEAREST: + return Texture.NEAREST_SAMPLINGMODE; + default: + return Texture.BILINEAR_SAMPLINGMODE; + } + } + static GetBufferFromBufferView(gltfRuntime, bufferView, byteOffset, byteLength, componentType) { + byteOffset = bufferView.byteOffset + byteOffset; + const loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer]; + if (byteOffset + byteLength > loadedBufferView.byteLength) { + throw new Error("Buffer access is out of range"); + } + const buffer = loadedBufferView.buffer; + byteOffset += loadedBufferView.byteOffset; + switch (componentType) { + case EComponentType.BYTE: + return new Int8Array(buffer, byteOffset, byteLength); + case EComponentType.UNSIGNED_BYTE: + return new Uint8Array(buffer, byteOffset, byteLength); + case EComponentType.SHORT: + return new Int16Array(buffer, byteOffset, byteLength); + case EComponentType.UNSIGNED_SHORT: + return new Uint16Array(buffer, byteOffset, byteLength); + default: + return new Float32Array(buffer, byteOffset, byteLength); + } + } + /** + * Returns a buffer from its accessor + * @param gltfRuntime the GLTF runtime + * @param accessor the GLTF accessor + * @returns an array buffer view + */ + static GetBufferFromAccessor(gltfRuntime, accessor) { + const bufferView = gltfRuntime.bufferViews[accessor.bufferView]; + const byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor); + return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType); + } + /** + * Decodes a buffer view into a string + * @param view the buffer view + * @returns a string + */ + static DecodeBufferToText(view) { + let result = ""; + const length = view.byteLength; + for (let i = 0; i < length; ++i) { + result += String.fromCharCode(view[i]); + } + return result; + } + /** + * Returns the default material of gltf. Related to + * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material + * @param scene the Babylon.js scene + * @returns the default Babylon material + */ + static GetDefaultMaterial(scene) { + if (!GLTFUtils._DefaultMaterial) { + Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [ + "precision highp float;", + "", + "uniform mat4 worldView;", + "uniform mat4 projection;", + "", + "attribute vec3 position;", + "", + "void main(void)", + "{", + " gl_Position = projection * worldView * vec4(position, 1.0);", + "}", + ].join("\n"); + Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [ + "precision highp float;", + "", + "uniform vec4 u_emission;", + "", + "void main(void)", + "{", + " gl_FragColor = u_emission;", + "}", + ].join("\n"); + const shaderPath = { + vertex: "GLTFDefaultMaterial", + fragment: "GLTFDefaultMaterial", + }; + const options = { + attributes: ["position"], + uniforms: ["worldView", "projection", "u_emission"], + samplers: new Array(), + needAlphaBlending: false, + }; + GLTFUtils._DefaultMaterial = new ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options); + GLTFUtils._DefaultMaterial.setColor4("u_emission", new Color4(0.5, 0.5, 0.5, 1.0)); + } + return GLTFUtils._DefaultMaterial; + } +} +// The GLTF default material +GLTFUtils._DefaultMaterial = null; + +/* eslint-disable @typescript-eslint/naming-convention */ +/** Defines the cross module used constants to avoid circular dependencies */ +class Constants { +} +/** Sampler suffix when associated with a texture name */ +Constants.AUTOSAMPLERSUFFIX = "Sampler"; +/** Flag used to disable diagnostics for WebGPU */ +Constants.DISABLEUA = "#define DISABLE_UNIFORMITY_ANALYSIS"; +/** Defines that alpha blending is disabled */ +Constants.ALPHA_DISABLE = 0; +/** Defines that alpha blending is SRC ALPHA * SRC + DEST */ +Constants.ALPHA_ADD = 1; +/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */ +Constants.ALPHA_COMBINE = 2; +/** Defines that alpha blending is DEST - SRC * DEST */ +Constants.ALPHA_SUBTRACT = 3; +/** Defines that alpha blending is SRC * DEST */ +Constants.ALPHA_MULTIPLY = 4; +/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC) * DEST */ +Constants.ALPHA_MAXIMIZED = 5; +/** Defines that alpha blending is SRC + DEST */ +Constants.ALPHA_ONEONE = 6; +/** Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST */ +Constants.ALPHA_PREMULTIPLIED = 7; +/** + * Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST + * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA + */ +Constants.ALPHA_PREMULTIPLIED_PORTERDUFF = 8; +/** Defines that alpha blending is CST * SRC + (1 - CST) * DEST */ +Constants.ALPHA_INTERPOLATE = 9; +/** + * Defines that alpha blending is SRC + (1 - SRC) * DEST + * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA + */ +Constants.ALPHA_SCREENMODE = 10; +/** + * Defines that alpha blending is SRC + DST + * Alpha will be set to SRC ALPHA + DST ALPHA + */ +Constants.ALPHA_ONEONE_ONEONE = 11; +/** + * Defines that alpha blending is SRC * DST ALPHA + DST + * Alpha will be set to 0 + */ +Constants.ALPHA_ALPHATOCOLOR = 12; +/** + * Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC) + */ +Constants.ALPHA_REVERSEONEMINUS = 13; +/** + * Defines that alpha blending is SRC + DST * (1 - SRC ALPHA) + * Alpha will be set to SRC ALPHA + DST ALPHA * (1 - SRC ALPHA) + */ +Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA = 14; +/** + * Defines that alpha blending is SRC + DST + * Alpha will be set to SRC ALPHA + */ +Constants.ALPHA_ONEONE_ONEZERO = 15; +/** + * Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC) + * Alpha will be set to DST ALPHA + */ +Constants.ALPHA_EXCLUSION = 16; +/** + * Defines that alpha blending is SRC * SRC ALPHA + DST * (1 - SRC ALPHA) + * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DST ALPHA + */ +Constants.ALPHA_LAYER_ACCUMULATE = 17; +/** Defines that alpha blending equation a SUM */ +Constants.ALPHA_EQUATION_ADD = 0; +/** Defines that alpha blending equation a SUBSTRACTION */ +Constants.ALPHA_EQUATION_SUBSTRACT = 1; +/** Defines that alpha blending equation a REVERSE SUBSTRACTION */ +Constants.ALPHA_EQUATION_REVERSE_SUBTRACT = 2; +/** Defines that alpha blending equation a MAX operation */ +Constants.ALPHA_EQUATION_MAX = 3; +/** Defines that alpha blending equation a MIN operation */ +Constants.ALPHA_EQUATION_MIN = 4; +/** + * Defines that alpha blending equation a DARKEN operation: + * It takes the min of the src and sums the alpha channels. + */ +Constants.ALPHA_EQUATION_DARKEN = 5; +/** Defines that the resource is not delayed*/ +Constants.DELAYLOADSTATE_NONE = 0; +/** Defines that the resource was successfully delay loaded */ +Constants.DELAYLOADSTATE_LOADED = 1; +/** Defines that the resource is currently delay loading */ +Constants.DELAYLOADSTATE_LOADING = 2; +/** Defines that the resource is delayed and has not started loading */ +Constants.DELAYLOADSTATE_NOTLOADED = 4; +// Depth or Stencil test Constants. +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */ +Constants.NEVER = 0x0200; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */ +Constants.ALWAYS = 0x0207; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */ +Constants.LESS = 0x0201; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */ +Constants.EQUAL = 0x0202; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */ +Constants.LEQUAL = 0x0203; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */ +Constants.GREATER = 0x0204; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */ +Constants.GEQUAL = 0x0206; +/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */ +Constants.NOTEQUAL = 0x0205; +// Stencil Actions Constants. +/** Passed to stencilOperation to specify that stencil value must be kept */ +Constants.KEEP = 0x1e00; +/** Passed to stencilOperation to specify that stencil value must be zero */ +Constants.ZERO = 0x0000; +/** Passed to stencilOperation to specify that stencil value must be replaced */ +Constants.REPLACE = 0x1e01; +/** Passed to stencilOperation to specify that stencil value must be incremented */ +Constants.INCR = 0x1e02; +/** Passed to stencilOperation to specify that stencil value must be decremented */ +Constants.DECR = 0x1e03; +/** Passed to stencilOperation to specify that stencil value must be inverted */ +Constants.INVERT = 0x150a; +/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */ +Constants.INCR_WRAP = 0x8507; +/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */ +Constants.DECR_WRAP = 0x8508; +/** Texture is not repeating outside of 0..1 UVs */ +Constants.TEXTURE_CLAMP_ADDRESSMODE = 0; +/** Texture is repeating outside of 0..1 UVs */ +Constants.TEXTURE_WRAP_ADDRESSMODE = 1; +/** Texture is repeating and mirrored */ +Constants.TEXTURE_MIRROR_ADDRESSMODE = 2; +/** Flag to create a storage texture */ +Constants.TEXTURE_CREATIONFLAG_STORAGE = 1; +/** ALPHA */ +Constants.TEXTUREFORMAT_ALPHA = 0; +/** LUMINANCE */ +Constants.TEXTUREFORMAT_LUMINANCE = 1; +/** LUMINANCE_ALPHA */ +Constants.TEXTUREFORMAT_LUMINANCE_ALPHA = 2; +/** RGB */ +Constants.TEXTUREFORMAT_RGB = 4; +/** RGBA */ +Constants.TEXTUREFORMAT_RGBA = 5; +/** RED */ +Constants.TEXTUREFORMAT_RED = 6; +/** RED (2nd reference) */ +Constants.TEXTUREFORMAT_R = 6; +/** RED unsigned short normed to [0, 1] **/ +Constants.TEXTUREFORMAT_R16_UNORM = 0x822a; +/** RG unsigned short normed to [0, 1] **/ +Constants.TEXTUREFORMAT_RG16_UNORM = 0x822c; +/** RGB unsigned short normed to [0, 1] **/ +Constants.TEXTUREFORMAT_RGB16_UNORM = 0x8054; +/** RGBA unsigned short normed to [0, 1] **/ +Constants.TEXTUREFORMAT_RGBA16_UNORM = 0x805b; +/** RED signed short normed to [-1, 1] **/ +Constants.TEXTUREFORMAT_R16_SNORM = 0x8f98; +/** RG signed short normed to [-1, 1] **/ +Constants.TEXTUREFORMAT_RG16_SNORM = 0x8f99; +/** RGB signed short normed to [-1, 1] **/ +Constants.TEXTUREFORMAT_RGB16_SNORM = 0x8f9a; +/** RGBA signed short normed to [-1, 1] **/ +Constants.TEXTUREFORMAT_RGBA16_SNORM = 0x8f9b; +/** RG */ +Constants.TEXTUREFORMAT_RG = 7; +/** RED_INTEGER */ +Constants.TEXTUREFORMAT_RED_INTEGER = 8; +/** RED_INTEGER (2nd reference) */ +Constants.TEXTUREFORMAT_R_INTEGER = 8; +/** RG_INTEGER */ +Constants.TEXTUREFORMAT_RG_INTEGER = 9; +/** RGB_INTEGER */ +Constants.TEXTUREFORMAT_RGB_INTEGER = 10; +/** RGBA_INTEGER */ +Constants.TEXTUREFORMAT_RGBA_INTEGER = 11; +/** BGRA */ +Constants.TEXTUREFORMAT_BGRA = 12; +/** Depth 24 bits + Stencil 8 bits */ +Constants.TEXTUREFORMAT_DEPTH24_STENCIL8 = 13; +/** Depth 32 bits float */ +Constants.TEXTUREFORMAT_DEPTH32_FLOAT = 14; +/** Depth 16 bits */ +Constants.TEXTUREFORMAT_DEPTH16 = 15; +/** Depth 24 bits */ +Constants.TEXTUREFORMAT_DEPTH24 = 16; +/** Depth 24 bits unorm + Stencil 8 bits */ +Constants.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8 = 17; +/** Depth 32 bits float + Stencil 8 bits */ +Constants.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8 = 18; +/** Stencil 8 bits */ +Constants.TEXTUREFORMAT_STENCIL8 = 19; +/** UNDEFINED */ +Constants.TEXTUREFORMAT_UNDEFINED = 0xffffffff; +/** Compressed BC7 */ +Constants.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM = 36492; +/** Compressed BC7 (SRGB) */ +Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM = 36493; +/** Compressed BC6 unsigned float */ +Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 36495; +/** Compressed BC6 signed float */ +Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 36494; +/** Compressed BC3 */ +Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5 = 33779; +/** Compressed BC3 (SRGB) */ +Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 35919; +/** Compressed BC2 */ +Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3 = 33778; +/** Compressed BC2 (SRGB) */ +Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 35918; +/** Compressed BC1 (RGBA) */ +Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1 = 33777; +/** Compressed BC1 (RGB) */ +Constants.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1 = 33776; +/** Compressed BC1 (SRGB+A) */ +Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 35917; +/** Compressed BC1 (SRGB) */ +Constants.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT = 35916; +/** Compressed ASTC 4x4 */ +Constants.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4 = 37808; +/** Compressed ASTC 4x4 (SRGB) */ +Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 37840; +/** Compressed ETC1 (RGB) */ +Constants.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL = 36196; +/** Compressed ETC2 (RGB) */ +Constants.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2 = 37492; +/** Compressed ETC2 (SRGB) */ +Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2 = 37493; +/** Compressed ETC2 (RGB+A1) */ +Constants.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37494; +/** Compressed ETC2 (SRGB+A1)*/ +Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37495; +/** Compressed ETC2 (RGB+A) */ +Constants.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC = 37496; +/** Compressed ETC2 (SRGB+1) */ +Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 37497; +/** UNSIGNED_BYTE */ +Constants.TEXTURETYPE_UNSIGNED_BYTE = 0; +/** @deprecated use more explicit TEXTURETYPE_UNSIGNED_BYTE instead. Use TEXTURETYPE_UNSIGNED_INTEGER for 32bits values.*/ +Constants.TEXTURETYPE_UNSIGNED_INT = 0; +/** FLOAT */ +Constants.TEXTURETYPE_FLOAT = 1; +/** HALF_FLOAT */ +Constants.TEXTURETYPE_HALF_FLOAT = 2; +/** BYTE */ +Constants.TEXTURETYPE_BYTE = 3; +/** SHORT */ +Constants.TEXTURETYPE_SHORT = 4; +/** UNSIGNED_SHORT */ +Constants.TEXTURETYPE_UNSIGNED_SHORT = 5; +/** INT */ +Constants.TEXTURETYPE_INT = 6; +/** UNSIGNED_INT */ +Constants.TEXTURETYPE_UNSIGNED_INTEGER = 7; +/** UNSIGNED_SHORT_4_4_4_4 */ +Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8; +/** UNSIGNED_SHORT_5_5_5_1 */ +Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9; +/** UNSIGNED_SHORT_5_6_5 */ +Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10; +/** UNSIGNED_INT_2_10_10_10_REV */ +Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11; +/** UNSIGNED_INT_24_8 */ +Constants.TEXTURETYPE_UNSIGNED_INT_24_8 = 12; +/** UNSIGNED_INT_10F_11F_11F_REV */ +Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13; +/** UNSIGNED_INT_5_9_9_9_REV */ +Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14; +/** FLOAT_32_UNSIGNED_INT_24_8_REV */ +Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15; +/** UNDEFINED */ +Constants.TEXTURETYPE_UNDEFINED = 16; +/** 2D Texture target*/ +Constants.TEXTURE_2D = 3553; +/** 2D Array Texture target */ +Constants.TEXTURE_2D_ARRAY = 35866; +/** Cube Map Texture target */ +Constants.TEXTURE_CUBE_MAP = 34067; +/** Cube Map Array Texture target */ +Constants.TEXTURE_CUBE_MAP_ARRAY = 0xdeadbeef; +/** 3D Texture target */ +Constants.TEXTURE_3D = 32879; +/** nearest is mag = nearest and min = nearest and no mip */ +Constants.TEXTURE_NEAREST_SAMPLINGMODE = 1; +/** mag = nearest and min = nearest and mip = none */ +Constants.TEXTURE_NEAREST_NEAREST = 1; +/** Bilinear is mag = linear and min = linear and no mip */ +Constants.TEXTURE_BILINEAR_SAMPLINGMODE = 2; +/** mag = linear and min = linear and mip = none */ +Constants.TEXTURE_LINEAR_LINEAR = 2; +/** Trilinear is mag = linear and min = linear and mip = linear */ +Constants.TEXTURE_TRILINEAR_SAMPLINGMODE = 3; +/** Trilinear is mag = linear and min = linear and mip = linear */ +Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3; +/** mag = nearest and min = nearest and mip = nearest */ +Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4; +/** mag = nearest and min = linear and mip = nearest */ +Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5; +/** mag = nearest and min = linear and mip = linear */ +Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6; +/** mag = nearest and min = linear and mip = none */ +Constants.TEXTURE_NEAREST_LINEAR = 7; +/** nearest is mag = nearest and min = nearest and mip = linear */ +Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8; +/** mag = linear and min = nearest and mip = nearest */ +Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9; +/** mag = linear and min = nearest and mip = linear */ +Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10; +/** Bilinear is mag = linear and min = linear and mip = nearest */ +Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11; +/** mag = linear and min = nearest and mip = none */ +Constants.TEXTURE_LINEAR_NEAREST = 12; +/** Explicit coordinates mode */ +Constants.TEXTURE_EXPLICIT_MODE = 0; +/** Spherical coordinates mode */ +Constants.TEXTURE_SPHERICAL_MODE = 1; +/** Planar coordinates mode */ +Constants.TEXTURE_PLANAR_MODE = 2; +/** Cubic coordinates mode */ +Constants.TEXTURE_CUBIC_MODE = 3; +/** Projection coordinates mode */ +Constants.TEXTURE_PROJECTION_MODE = 4; +/** Skybox coordinates mode */ +Constants.TEXTURE_SKYBOX_MODE = 5; +/** Inverse Cubic coordinates mode */ +Constants.TEXTURE_INVCUBIC_MODE = 6; +/** Equirectangular coordinates mode */ +Constants.TEXTURE_EQUIRECTANGULAR_MODE = 7; +/** Equirectangular Fixed coordinates mode */ +Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8; +/** Equirectangular Fixed Mirrored coordinates mode */ +Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; +/** Offline (baking) quality for texture filtering */ +Constants.TEXTURE_FILTERING_QUALITY_OFFLINE = 4096; +/** High quality for texture filtering */ +Constants.TEXTURE_FILTERING_QUALITY_HIGH = 64; +/** Medium quality for texture filtering */ +Constants.TEXTURE_FILTERING_QUALITY_MEDIUM = 16; +/** Low quality for texture filtering */ +Constants.TEXTURE_FILTERING_QUALITY_LOW = 8; +// Texture rescaling mode +/** Defines that texture rescaling will use a floor to find the closer power of 2 size */ +Constants.SCALEMODE_FLOOR = 1; +/** Defines that texture rescaling will look for the nearest power of 2 size */ +Constants.SCALEMODE_NEAREST = 2; +/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */ +Constants.SCALEMODE_CEILING = 3; +/** + * The dirty texture flag value + */ +Constants.MATERIAL_TextureDirtyFlag = 1; +/** + * The dirty light flag value + */ +Constants.MATERIAL_LightDirtyFlag = 2; +/** + * The dirty fresnel flag value + */ +Constants.MATERIAL_FresnelDirtyFlag = 4; +/** + * The dirty attribute flag value + */ +Constants.MATERIAL_AttributesDirtyFlag = 8; +/** + * The dirty misc flag value + */ +Constants.MATERIAL_MiscDirtyFlag = 16; +/** + * The dirty prepass flag value + */ +Constants.MATERIAL_PrePassDirtyFlag = 32; +/** + * The dirty image processing flag value + */ +Constants.MATERIAL_ImageProcessingDirtyFlag = 64; +/** + * The all dirty flag value + */ +Constants.MATERIAL_AllDirtyFlag = 127; +/** + * Returns the triangle fill mode + */ +Constants.MATERIAL_TriangleFillMode = 0; +/** + * Returns the wireframe mode + */ +Constants.MATERIAL_WireFrameFillMode = 1; +/** + * Returns the point fill mode + */ +Constants.MATERIAL_PointFillMode = 2; +/** + * Returns the point list draw mode + */ +Constants.MATERIAL_PointListDrawMode = 3; +/** + * Returns the line list draw mode + */ +Constants.MATERIAL_LineListDrawMode = 4; +/** + * Returns the line loop draw mode + */ +Constants.MATERIAL_LineLoopDrawMode = 5; +/** + * Returns the line strip draw mode + */ +Constants.MATERIAL_LineStripDrawMode = 6; +/** + * Returns the triangle strip draw mode + */ +Constants.MATERIAL_TriangleStripDrawMode = 7; +/** + * Returns the triangle fan draw mode + */ +Constants.MATERIAL_TriangleFanDrawMode = 8; +/** + * Stores the clock-wise side orientation + */ +Constants.MATERIAL_ClockWiseSideOrientation = 0; +/** + * Stores the counter clock-wise side orientation + */ +Constants.MATERIAL_CounterClockWiseSideOrientation = 1; +/** + * Nothing + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_NothingTrigger = 0; +/** + * On pick + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnPickTrigger = 1; +/** + * On left pick + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnLeftPickTrigger = 2; +/** + * On right pick + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnRightPickTrigger = 3; +/** + * On center pick + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnCenterPickTrigger = 4; +/** + * On pick down + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnPickDownTrigger = 5; +/** + * On double pick + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnDoublePickTrigger = 6; +/** + * On pick up + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnPickUpTrigger = 7; +/** + * On pick out. + * This trigger will only be raised if you also declared a OnPickDown + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnPickOutTrigger = 16; +/** + * On long press + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnLongPressTrigger = 8; +/** + * On pointer over + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnPointerOverTrigger = 9; +/** + * On pointer out + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnPointerOutTrigger = 10; +/** + * On every frame + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnEveryFrameTrigger = 11; +/** + * On intersection enter + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnIntersectionEnterTrigger = 12; +/** + * On intersection exit + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnIntersectionExitTrigger = 13; +/** + * On key down + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnKeyDownTrigger = 14; +/** + * On key up + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +Constants.ACTION_OnKeyUpTrigger = 15; +/** + * Billboard mode will only apply to Y axis + */ +Constants.PARTICLES_BILLBOARDMODE_Y = 2; +/** + * Billboard mode will apply to all axes + */ +Constants.PARTICLES_BILLBOARDMODE_ALL = 7; +/** + * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction + */ +Constants.PARTICLES_BILLBOARDMODE_STRETCHED = 8; +/** + * Special billboard mode where the particle will be billboard to the camera but only around the axis of the direction of particle emission + */ +Constants.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL = 9; +/** Default culling strategy : this is an exclusion test and it's the more accurate. + * Test order : + * Is the bounding sphere outside the frustum ? + * If not, are the bounding box vertices outside the frustum ? + * It not, then the cullable object is in the frustum. + */ +Constants.MESHES_CULLINGSTRATEGY_STANDARD = 0; +/** Culling strategy : Bounding Sphere Only. + * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested. + * It's also less accurate than the standard because some not visible objects can still be selected. + * Test : is the bounding sphere outside the frustum ? + * If not, then the cullable object is in the frustum. + */ +Constants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1; +/** Culling strategy : Optimistic Inclusion. + * This in an inclusion test first, then the standard exclusion test. + * This can be faster when a cullable object is expected to be almost always in the camera frustum. + * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside. + * Anyway, it's as accurate as the standard strategy. + * Test : + * Is the cullable object bounding sphere center in the frustum ? + * If not, apply the default culling strategy. + */ +Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2; +/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only. + * This in an inclusion test first, then the bounding sphere only exclusion test. + * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum. + * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it. + * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy. + * Test : + * Is the cullable object bounding sphere center in the frustum ? + * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here. + */ +Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3; +/** + * No logging while loading + */ +Constants.SCENELOADER_NO_LOGGING = 0; +/** + * Minimal logging while loading + */ +Constants.SCENELOADER_MINIMAL_LOGGING = 1; +/** + * Summary logging while loading + */ +Constants.SCENELOADER_SUMMARY_LOGGING = 2; +/** + * Detailed logging while loading + */ +Constants.SCENELOADER_DETAILED_LOGGING = 3; +/** + * Constant used to retrieve the irradiance texture index in the textures array in the prepass + * using getIndex(Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE) + */ +Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE = 0; +/** + * Constant used to retrieve the position texture index in the textures array in the prepass + * using getIndex(Constants.PREPASS_POSITION_TEXTURE_INDEX) + */ +Constants.PREPASS_POSITION_TEXTURE_TYPE = 1; +/** + * Constant used to retrieve the velocity texture index in the textures array in the prepass + * using getIndex(Constants.PREPASS_VELOCITY_TEXTURE_TYPE) + */ +Constants.PREPASS_VELOCITY_TEXTURE_TYPE = 2; +/** + * Constant used to retrieve the reflectivity texture index in the textures array in the prepass + * using the getIndex(Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE) + */ +Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE = 3; +/** + * Constant used to retrieve the lit color texture index in the textures array in the prepass + * using the getIndex(Constants.PREPASS_COLOR_TEXTURE_TYPE) + */ +Constants.PREPASS_COLOR_TEXTURE_TYPE = 4; +/** + * Constant used to retrieve depth index in the textures array in the prepass + * using the getIndex(Constants.PREPASS_DEPTH_TEXTURE_TYPE) + */ +Constants.PREPASS_DEPTH_TEXTURE_TYPE = 5; +/** + * Constant used to retrieve normal index in the textures array in the prepass + * using the getIndex(Constants.PREPASS_NORMAL_TEXTURE_TYPE) + */ +Constants.PREPASS_NORMAL_TEXTURE_TYPE = 6; +/** + * Constant used to retrieve (sqrt) albedo index in the textures array in the prepass + * using the getIndex(Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE) + */ +Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE = 7; +/** + * Constant used to retrieve world normal index in the textures array in the prepass + * using the getIndex(Constants.PREPASS_WORLD_NORMAL_TEXTURE_TYPE) + */ +Constants.PREPASS_WORLD_NORMAL_TEXTURE_TYPE = 8; +/** + * Constant used to retrieve the local position texture index in the textures array in the prepass + * using getIndex(Constants.PREPASS_LOCAL_POSITION_TEXTURE_TYPE) + */ +Constants.PREPASS_LOCAL_POSITION_TEXTURE_TYPE = 9; +/** + * Constant used to retrieve screen-space (non-linear) depth index in the textures array in the prepass + * using the getIndex(Constants.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE) + */ +Constants.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE = 10; +/** + * Constant used to retrieve the velocity texture index in the textures array in the prepass + * using getIndex(Constants.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE) + */ +Constants.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE = 11; +/** + * Constant used to retrieve albedo index in the textures array in the prepass + * using the getIndex(Constants.PREPASS_ALBEDO_TEXTURE_TYPE) + */ +Constants.PREPASS_ALBEDO_TEXTURE_TYPE = 12; +/** Flag to create a readable buffer (the buffer can be the source of a copy) */ +Constants.BUFFER_CREATIONFLAG_READ = 1; +/** Flag to create a writable buffer (the buffer can be the destination of a copy) */ +Constants.BUFFER_CREATIONFLAG_WRITE = 2; +/** Flag to create a readable and writable buffer */ +Constants.BUFFER_CREATIONFLAG_READWRITE = 3; +/** Flag to create a buffer suitable to be used as a uniform buffer */ +Constants.BUFFER_CREATIONFLAG_UNIFORM = 4; +/** Flag to create a buffer suitable to be used as a vertex buffer */ +Constants.BUFFER_CREATIONFLAG_VERTEX = 8; +/** Flag to create a buffer suitable to be used as an index buffer */ +Constants.BUFFER_CREATIONFLAG_INDEX = 16; +/** Flag to create a buffer suitable to be used as a storage buffer */ +Constants.BUFFER_CREATIONFLAG_STORAGE = 32; +/** Flag to create a buffer suitable to be used for indirect calls, such as `dispatchIndirect` */ +Constants.BUFFER_CREATIONFLAG_INDIRECT = 64; +/** + * Prefixes used by the engine for sub mesh draw wrappers + */ +/** @internal */ +Constants.RENDERPASS_MAIN = 0; +/** + * Constant used as key code for Alt key + */ +Constants.INPUT_ALT_KEY = 18; +/** + * Constant used as key code for Ctrl key + */ +Constants.INPUT_CTRL_KEY = 17; +/** + * Constant used as key code for Meta key (Left Win, Left Cmd) + */ +Constants.INPUT_META_KEY1 = 91; +/** + * Constant used as key code for Meta key (Right Win) + */ +Constants.INPUT_META_KEY2 = 92; +/** + * Constant used as key code for Meta key (Right Win, Right Cmd) + */ +Constants.INPUT_META_KEY3 = 93; +/** + * Constant used as key code for Shift key + */ +Constants.INPUT_SHIFT_KEY = 16; +/** Standard snapshot rendering. In this mode, some form of dynamic behavior is possible (for eg, uniform buffers are still updated) */ +Constants.SNAPSHOTRENDERING_STANDARD = 0; +/** Fast snapshot rendering. In this mode, everything is static and only some limited form of dynamic behaviour is possible */ +Constants.SNAPSHOTRENDERING_FAST = 1; +/** + * This is the default projection mode used by the cameras. + * It helps recreating a feeling of perspective and better appreciate depth. + * This is the best way to simulate real life cameras. + */ +Constants.PERSPECTIVE_CAMERA = 0; +/** + * This helps creating camera with an orthographic mode. + * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object. + */ +Constants.ORTHOGRAPHIC_CAMERA = 1; +/** + * This is the default FOV mode for perspective cameras. + * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum. + */ +Constants.FOVMODE_VERTICAL_FIXED = 0; +/** + * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum. + */ +Constants.FOVMODE_HORIZONTAL_FIXED = 1; +/** + * This specifies there is no need for a camera rig. + * Basically only one eye is rendered corresponding to the camera. + */ +Constants.RIG_MODE_NONE = 0; +/** + * Simulates a camera Rig with one blue eye and one red eye. + * This can be use with 3d blue and red glasses. + */ +Constants.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10; +/** + * Defines that both eyes of the camera will be rendered side by side with a parallel target. + */ +Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11; +/** + * Defines that both eyes of the camera will be rendered side by side with a none parallel target. + */ +Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12; +/** + * Defines that both eyes of the camera will be rendered over under each other. + */ +Constants.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13; +/** + * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors. + */ +Constants.RIG_MODE_STEREOSCOPIC_INTERLACED = 14; +/** + * Defines that both eyes of the camera should be renderered in a VR mode (carbox). + */ +Constants.RIG_MODE_VR = 20; +/** + * Custom rig mode allowing rig cameras to be populated manually with any number of cameras + */ +Constants.RIG_MODE_CUSTOM = 22; +/** + * Maximum number of uv sets supported + */ +Constants.MAX_SUPPORTED_UV_SETS = 6; +/** + * GL constants + */ +/** Alpha blend equation: ADD */ +Constants.GL_ALPHA_EQUATION_ADD = 0x8006; +/** Alpha equation: MIN */ +Constants.GL_ALPHA_EQUATION_MIN = 0x8007; +/** Alpha equation: MAX */ +Constants.GL_ALPHA_EQUATION_MAX = 0x8008; +/** Alpha equation: SUBTRACT */ +Constants.GL_ALPHA_EQUATION_SUBTRACT = 0x800a; +/** Alpha equation: REVERSE_SUBTRACT */ +Constants.GL_ALPHA_EQUATION_REVERSE_SUBTRACT = 0x800b; +/** Alpha blend function: SRC */ +Constants.GL_ALPHA_FUNCTION_SRC = 0x0300; +/** Alpha blend function: ONE_MINUS_SRC */ +Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR = 0x0301; +/** Alpha blend function: SRC_ALPHA */ +Constants.GL_ALPHA_FUNCTION_SRC_ALPHA = 0x0302; +/** Alpha blend function: ONE_MINUS_SRC_ALPHA */ +Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA = 0x0303; +/** Alpha blend function: DST_ALPHA */ +Constants.GL_ALPHA_FUNCTION_DST_ALPHA = 0x0304; +/** Alpha blend function: ONE_MINUS_DST_ALPHA */ +Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA = 0x0305; +/** Alpha blend function: ONE_MINUS_DST */ +Constants.GL_ALPHA_FUNCTION_DST_COLOR = 0x0306; +/** Alpha blend function: ONE_MINUS_DST */ +Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR = 0x0307; +/** Alpha blend function: SRC_ALPHA_SATURATED */ +Constants.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED = 0x0308; +/** Alpha blend function: CONSTANT */ +Constants.GL_ALPHA_FUNCTION_CONSTANT_COLOR = 0x8001; +/** Alpha blend function: ONE_MINUS_CONSTANT */ +Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR = 0x8002; +/** Alpha blend function: CONSTANT_ALPHA */ +Constants.GL_ALPHA_FUNCTION_CONSTANT_ALPHA = 0x8003; +/** Alpha blend function: ONE_MINUS_CONSTANT_ALPHA */ +Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA = 0x8004; +/** Alpha blend function: SRC1 */ +Constants.GL_ALPHA_FUNCTION_SRC1_COLOR = 0x88f9; +/** Alpha blend function: SRC1 */ +Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR = 0x88fa; +/** Alpha blend function: SRC1 */ +Constants.GL_ALPHA_FUNCTION_SRC1_ALPHA = 0x8589; +/** Alpha blend function: SRC1 */ +Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA = 0x88fb; +/** URL to the snippet server. Points to the public snippet server by default */ +Constants.SnippetUrl = "https://snippet.babylonjs.com"; +/** The fog is deactivated */ +Constants.FOGMODE_NONE = 0; +/** The fog density is following an exponential function */ +Constants.FOGMODE_EXP = 1; +/** The fog density is following an exponential function faster than FOGMODE_EXP */ +Constants.FOGMODE_EXP2 = 2; +/** The fog density is following a linear function. */ +Constants.FOGMODE_LINEAR = 3; +/** + * The byte type. + */ +Constants.BYTE = 5120; +/** + * The unsigned byte type. + */ +Constants.UNSIGNED_BYTE = 5121; +/** + * The short type. + */ +Constants.SHORT = 5122; +/** + * The unsigned short type. + */ +Constants.UNSIGNED_SHORT = 5123; +/** + * The integer type. + */ +Constants.INT = 5124; +/** + * The unsigned integer type. + */ +Constants.UNSIGNED_INT = 5125; +/** + * The float type. + */ +Constants.FLOAT = 5126; +/** + * Positions + */ +Constants.PositionKind = "position"; +/** + * Normals + */ +Constants.NormalKind = "normal"; +/** + * Tangents + */ +Constants.TangentKind = "tangent"; +/** + * Texture coordinates + */ +Constants.UVKind = "uv"; +/** + * Texture coordinates 2 + */ +Constants.UV2Kind = "uv2"; +/** + * Texture coordinates 3 + */ +Constants.UV3Kind = "uv3"; +/** + * Texture coordinates 4 + */ +Constants.UV4Kind = "uv4"; +/** + * Texture coordinates 5 + */ +Constants.UV5Kind = "uv5"; +/** + * Texture coordinates 6 + */ +Constants.UV6Kind = "uv6"; +/** + * Colors + */ +Constants.ColorKind = "color"; +/** + * Instance Colors + */ +Constants.ColorInstanceKind = "instanceColor"; +/** + * Matrix indices (for bones) + */ +Constants.MatricesIndicesKind = "matricesIndices"; +/** + * Matrix weights (for bones) + */ +Constants.MatricesWeightsKind = "matricesWeights"; +/** + * Additional matrix indices (for bones) + */ +Constants.MatricesIndicesExtraKind = "matricesIndicesExtra"; +/** + * Additional matrix weights (for bones) + */ +Constants.MatricesWeightsExtraKind = "matricesWeightsExtra"; +// Animation type +/** + * Float animation type + */ +Constants.ANIMATIONTYPE_FLOAT = 0; +/** + * Vector3 animation type + */ +Constants.ANIMATIONTYPE_VECTOR3 = 1; +/** + * Quaternion animation type + */ +Constants.ANIMATIONTYPE_QUATERNION = 2; +/** + * Matrix animation type + */ +Constants.ANIMATIONTYPE_MATRIX = 3; +/** + * Color3 animation type + */ +Constants.ANIMATIONTYPE_COLOR3 = 4; +/** + * Color3 animation type + */ +Constants.ANIMATIONTYPE_COLOR4 = 7; +/** + * Vector2 animation type + */ +Constants.ANIMATIONTYPE_VECTOR2 = 5; +/** + * Size animation type + */ +Constants.ANIMATIONTYPE_SIZE = 6; +/** + * The default minZ value for the near plane of a frustum light + */ +Constants.ShadowMinZ = 0; +/** + * The default maxZ value for the far plane of a frustum light + */ +Constants.ShadowMaxZ = 10000; + +/** + * Tokenizer. Used for shaders compatibility + * Automatically map world, view, projection, worldViewProjection, attributes and so on + */ +var ETokenType; +(function (ETokenType) { + ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER"; + ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN"; + ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT"; +})(ETokenType || (ETokenType = {})); +class Tokenizer { + constructor(toParse) { + this._pos = 0; + this.currentToken = ETokenType.UNKNOWN; + this.currentIdentifier = ""; + this.currentString = ""; + this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/; + this._toParse = toParse; + this._maxPos = toParse.length; + } + getNextToken() { + if (this.isEnd()) { + return ETokenType.END_OF_INPUT; + } + this.currentString = this.read(); + this.currentToken = ETokenType.UNKNOWN; + if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) { + this.currentToken = ETokenType.IDENTIFIER; + this.currentIdentifier = this.currentString; + while (!this.isEnd() && (this.isLetterOrDigitPattern.test((this.currentString = this.peek())) || this.currentString === "_")) { + this.currentIdentifier += this.currentString; + this.forward(); + } + } + return this.currentToken; + } + peek() { + return this._toParse[this._pos]; + } + read() { + return this._toParse[this._pos++]; + } + forward() { + this._pos++; + } + isEnd() { + return this._pos >= this._maxPos; + } +} +/** + * Values + */ +const glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"]; +const babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"]; +const glTFAnimationPaths = ["translation", "rotation", "scale"]; +const babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"]; +/** + * Parse + * @param parsedBuffers + * @param gltfRuntime + */ +const parseBuffers = (parsedBuffers, gltfRuntime) => { + for (const buf in parsedBuffers) { + const parsedBuffer = parsedBuffers[buf]; + gltfRuntime.buffers[buf] = parsedBuffer; + gltfRuntime.buffersCount++; + } +}; +const parseShaders = (parsedShaders, gltfRuntime) => { + for (const sha in parsedShaders) { + const parsedShader = parsedShaders[sha]; + gltfRuntime.shaders[sha] = parsedShader; + gltfRuntime.shaderscount++; + } +}; +const parseObject = (parsedObjects, runtimeProperty, gltfRuntime) => { + for (const object in parsedObjects) { + const parsedObject = parsedObjects[object]; + gltfRuntime[runtimeProperty][object] = parsedObject; + } +}; +/** + * Utils + * @param buffer + */ +const normalizeUVs = (buffer) => { + if (!buffer) { + return; + } + for (let i = 0; i < buffer.length / 2; i++) { + buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1]; + } +}; +const getAttribute = (attributeParameter) => { + if (attributeParameter.semantic === "NORMAL") { + return "normal"; + } + else if (attributeParameter.semantic === "POSITION") { + return "position"; + } + else if (attributeParameter.semantic === "JOINT") { + return "matricesIndices"; + } + else if (attributeParameter.semantic === "WEIGHT") { + return "matricesWeights"; + } + else if (attributeParameter.semantic === "COLOR") { + return "color"; + } + else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) { + const channel = Number(attributeParameter.semantic.split("_")[1]); + return "uv" + (channel === 0 ? "" : channel + 1); + } + return null; +}; +/** + * Loads and creates animations + * @param gltfRuntime + */ +const loadAnimations = (gltfRuntime) => { + for (const anim in gltfRuntime.animations) { + const animation = gltfRuntime.animations[anim]; + if (!animation.channels || !animation.samplers) { + continue; + } + let lastAnimation = null; + for (let i = 0; i < animation.channels.length; i++) { + // Get parameters and load buffers + const channel = animation.channels[i]; + const sampler = animation.samplers[channel.sampler]; + if (!sampler) { + continue; + } + let inputData = null; + let outputData = null; + if (animation.parameters) { + inputData = animation.parameters[sampler.input]; + outputData = animation.parameters[sampler.output]; + } + else { + inputData = sampler.input; + outputData = sampler.output; + } + const bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]); + const bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]); + const targetId = channel.target.id; + let targetNode = gltfRuntime.scene.getNodeById(targetId); + if (targetNode === null) { + targetNode = gltfRuntime.scene.getNodeByName(targetId); + } + if (targetNode === null) { + Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetId + " to attach to"); + continue; + } + const isBone = targetNode instanceof Bone; + // Get target path (position, rotation or scaling) + let targetPath = channel.target.path; + const targetPathIndex = glTFAnimationPaths.indexOf(targetPath); + if (targetPathIndex !== -1) { + targetPath = babylonAnimationPaths[targetPathIndex]; + } + // Determine animation type + let animationType = Animation.ANIMATIONTYPE_MATRIX; + if (!isBone) { + if (targetPath === "rotationQuaternion") { + animationType = Animation.ANIMATIONTYPE_QUATERNION; + targetNode.rotationQuaternion = new Quaternion(); + } + else { + animationType = Animation.ANIMATIONTYPE_VECTOR3; + } + } + // Create animation and key frames + let babylonAnimation = null; + const keys = []; + let arrayOffset = 0; + let modifyKey = false; + if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) { + babylonAnimation = lastAnimation; + modifyKey = true; + } + if (!modifyKey) { + gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer; + babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE); + gltfRuntime.scene._blockEntityCollection = false; + } + // For each frame + for (let j = 0; j < bufferInput.length; j++) { + let value = null; + if (targetPath === "rotationQuaternion") { + // VEC4 + value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]); + arrayOffset += 4; + } + else { + // Position and scaling are VEC3 + value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]); + arrayOffset += 3; + } + if (isBone) { + const bone = targetNode; + let translation = Vector3.Zero(); + let rotationQuaternion = new Quaternion(); + let scaling = Vector3.Zero(); + // Warning on decompose + let mat = bone.getBaseMatrix(); + if (modifyKey && lastAnimation) { + mat = lastAnimation.getKeys()[j].value; + } + mat.decompose(scaling, rotationQuaternion, translation); + if (targetPath === "position") { + translation = value; + } + else if (targetPath === "rotationQuaternion") { + rotationQuaternion = value; + } + else { + scaling = value; + } + value = Matrix.Compose(scaling, rotationQuaternion, translation); + } + if (!modifyKey) { + keys.push({ + frame: bufferInput[j], + value: value, + }); + } + else if (lastAnimation) { + lastAnimation.getKeys()[j].value = value; + } + } + // Finish + if (!modifyKey && babylonAnimation) { + babylonAnimation.setKeys(keys); + targetNode.animations.push(babylonAnimation); + } + lastAnimation = babylonAnimation; + gltfRuntime.scene.stopAnimation(targetNode); + gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0); + } + } +}; +/** + * @returns the bones transformation matrix + * @param node + */ +const configureBoneTransformation = (node) => { + let mat = null; + if (node.translation || node.rotation || node.scale) { + const scale = Vector3.FromArray(node.scale || [1, 1, 1]); + const rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]); + const position = Vector3.FromArray(node.translation || [0, 0, 0]); + mat = Matrix.Compose(scale, rotation, position); + } + else { + mat = Matrix.FromArray(node.matrix); + } + return mat; +}; +/** + * Returns the parent bone + * @param gltfRuntime + * @param skins + * @param jointName + * @param newSkeleton + * @returns the parent bone + */ +const getParentBone = (gltfRuntime, skins, jointName, newSkeleton) => { + // Try to find + for (let i = 0; i < newSkeleton.bones.length; i++) { + if (newSkeleton.bones[i].name === jointName) { + return newSkeleton.bones[i]; + } + } + // Not found, search in gltf nodes + const nodes = gltfRuntime.nodes; + for (const nde in nodes) { + const node = nodes[nde]; + if (!node.jointName) { + continue; + } + const children = node.children; + for (let i = 0; i < children.length; i++) { + const child = gltfRuntime.nodes[children[i]]; + if (!child.jointName) { + continue; + } + if (child.jointName === jointName) { + const mat = configureBoneTransformation(node); + const bone = new Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat); + bone.id = nde; + return bone; + } + } + } + return null; +}; +/** + * Returns the appropriate root node + * @param nodesToRoot + * @param id + * @returns the root node + */ +const getNodeToRoot = (nodesToRoot, id) => { + for (let i = 0; i < nodesToRoot.length; i++) { + const nodeToRoot = nodesToRoot[i]; + for (let j = 0; j < nodeToRoot.node.children.length; j++) { + const child = nodeToRoot.node.children[j]; + if (child === id) { + return nodeToRoot.bone; + } + } + } + return null; +}; +/** + * Returns the node with the joint name + * @param gltfRuntime + * @param jointName + * @returns the node with the joint name + */ +const getJointNode = (gltfRuntime, jointName) => { + const nodes = gltfRuntime.nodes; + let node = nodes[jointName]; + if (node) { + return { + node: node, + id: jointName, + }; + } + for (const nde in nodes) { + node = nodes[nde]; + if (node.jointName === jointName) { + return { + node: node, + id: nde, + }; + } + } + return null; +}; +/** + * Checks if a nodes is in joints + * @param skins + * @param id + * @returns true if the node is in joints, else false + */ +const nodeIsInJoints = (skins, id) => { + for (let i = 0; i < skins.jointNames.length; i++) { + if (skins.jointNames[i] === id) { + return true; + } + } + return false; +}; +/** + * Fills the nodes to root for bones and builds hierarchy + * @param gltfRuntime + * @param newSkeleton + * @param skins + * @param nodesToRoot + */ +const getNodesToRoot = (gltfRuntime, newSkeleton, skins, nodesToRoot) => { + // Creates nodes for root + for (const nde in gltfRuntime.nodes) { + const node = gltfRuntime.nodes[nde]; + const id = nde; + if (!node.jointName || nodeIsInJoints(skins, node.jointName)) { + continue; + } + // Create node to root bone + const mat = configureBoneTransformation(node); + const bone = new Bone(node.name || "", newSkeleton, null, mat); + bone.id = id; + nodesToRoot.push({ bone: bone, node: node, id: id }); + } + // Parenting + for (let i = 0; i < nodesToRoot.length; i++) { + const nodeToRoot = nodesToRoot[i]; + const children = nodeToRoot.node.children; + for (let j = 0; j < children.length; j++) { + let child = null; + for (let k = 0; k < nodesToRoot.length; k++) { + if (nodesToRoot[k].id === children[j]) { + child = nodesToRoot[k]; + break; + } + } + if (child) { + child.bone._parent = nodeToRoot.bone; + nodeToRoot.bone.children.push(child.bone); + } + } + } +}; +/** + * Imports a skeleton + * @param gltfRuntime + * @param skins + * @param mesh + * @param newSkeleton + * @returns the bone name + */ +const importSkeleton = (gltfRuntime, skins, mesh, newSkeleton) => { + if (!newSkeleton) { + newSkeleton = new Skeleton(skins.name || "", "", gltfRuntime.scene); + } + if (!skins.babylonSkeleton) { + return newSkeleton; + } + // Find the root bones + const nodesToRoot = []; + const nodesToRootToAdd = []; + getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot); + newSkeleton.bones = []; + // Joints + for (let i = 0; i < skins.jointNames.length; i++) { + const jointNode = getJointNode(gltfRuntime, skins.jointNames[i]); + if (!jointNode) { + continue; + } + const node = jointNode.node; + if (!node) { + Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist"); + continue; + } + const id = jointNode.id; + // Optimize, if the bone already exists... + const existingBone = gltfRuntime.scene.getBoneById(id); + if (existingBone) { + newSkeleton.bones.push(existingBone); + continue; + } + // Search for parent bone + let foundBone = false; + let parentBone = null; + for (let j = 0; j < i; j++) { + const jointNode = getJointNode(gltfRuntime, skins.jointNames[j]); + if (!jointNode) { + continue; + } + const joint = jointNode.node; + if (!joint) { + Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent"); + continue; + } + const children = joint.children; + if (!children) { + continue; + } + foundBone = false; + for (let k = 0; k < children.length; k++) { + if (children[k] === id) { + parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton); + foundBone = true; + break; + } + } + if (foundBone) { + break; + } + } + // Create bone + const mat = configureBoneTransformation(node); + if (!parentBone && nodesToRoot.length > 0) { + parentBone = getNodeToRoot(nodesToRoot, id); + if (parentBone) { + if (nodesToRootToAdd.indexOf(parentBone) === -1) { + nodesToRootToAdd.push(parentBone); + } + } + } + const bone = new Bone(node.jointName || "", newSkeleton, parentBone, mat); + bone.id = id; + } + // Polish + const bones = newSkeleton.bones; + newSkeleton.bones = []; + for (let i = 0; i < skins.jointNames.length; i++) { + const jointNode = getJointNode(gltfRuntime, skins.jointNames[i]); + if (!jointNode) { + continue; + } + for (let j = 0; j < bones.length; j++) { + if (bones[j].id === jointNode.id) { + newSkeleton.bones.push(bones[j]); + break; + } + } + } + newSkeleton.prepare(); + // Finish + for (let i = 0; i < nodesToRootToAdd.length; i++) { + newSkeleton.bones.push(nodesToRootToAdd[i]); + } + return newSkeleton; +}; +/** + * Imports a mesh and its geometries + * @param gltfRuntime + * @param node + * @param meshes + * @param id + * @param newMesh + * @returns the new mesh + */ +const importMesh = (gltfRuntime, node, meshes, id, newMesh) => { + if (!newMesh) { + gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer; + newMesh = new Mesh(node.name || "", gltfRuntime.scene); + newMesh._parentContainer = gltfRuntime.assetContainer; + gltfRuntime.scene._blockEntityCollection = false; + newMesh.id = id; + } + if (!node.babylonNode) { + return newMesh; + } + const subMaterials = []; + let vertexData = null; + const verticesStarts = []; + const verticesCounts = []; + const indexStarts = []; + const indexCounts = []; + for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) { + const meshId = meshes[meshIndex]; + const mesh = gltfRuntime.meshes[meshId]; + if (!mesh) { + continue; + } + // Positions, normals and UVs + for (let i = 0; i < mesh.primitives.length; i++) { + // Temporary vertex data + const tempVertexData = new VertexData(); + const primitive = mesh.primitives[i]; + if (primitive.mode !== 4) ; + const attributes = primitive.attributes; + let accessor = null; + let buffer = null; + // Set positions, normal and uvs + for (const semantic in attributes) { + // Link accessor and buffer view + accessor = gltfRuntime.accessors[attributes[semantic]]; + buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor); + if (semantic === "NORMAL") { + tempVertexData.normals = new Float32Array(buffer.length); + tempVertexData.normals.set(buffer); + } + else if (semantic === "POSITION") { + if (GLTFFileLoader.HomogeneousCoordinates) { + tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4); + for (let j = 0; j < buffer.length; j += 4) { + tempVertexData.positions[j] = buffer[j]; + tempVertexData.positions[j + 1] = buffer[j + 1]; + tempVertexData.positions[j + 2] = buffer[j + 2]; + } + } + else { + tempVertexData.positions = new Float32Array(buffer.length); + tempVertexData.positions.set(buffer); + } + verticesCounts.push(tempVertexData.positions.length); + } + else if (semantic.indexOf("TEXCOORD_") !== -1) { + const channel = Number(semantic.split("_")[1]); + const uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : channel + 1); + const uvs = new Float32Array(buffer.length); + uvs.set(buffer); + normalizeUVs(uvs); + tempVertexData.set(uvs, uvKind); + } + else if (semantic === "JOINT") { + tempVertexData.matricesIndices = new Float32Array(buffer.length); + tempVertexData.matricesIndices.set(buffer); + } + else if (semantic === "WEIGHT") { + tempVertexData.matricesWeights = new Float32Array(buffer.length); + tempVertexData.matricesWeights.set(buffer); + } + else if (semantic === "COLOR") { + tempVertexData.colors = new Float32Array(buffer.length); + tempVertexData.colors.set(buffer); + } + } + // Indices + accessor = gltfRuntime.accessors[primitive.indices]; + if (accessor) { + buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor); + tempVertexData.indices = new Int32Array(buffer.length); + tempVertexData.indices.set(buffer); + indexCounts.push(tempVertexData.indices.length); + } + else { + // Set indices on the fly + const indices = []; + for (let j = 0; j < tempVertexData.positions.length / 3; j++) { + indices.push(j); + } + tempVertexData.indices = new Int32Array(indices); + indexCounts.push(tempVertexData.indices.length); + } + if (!vertexData) { + vertexData = tempVertexData; + } + else { + vertexData.merge(tempVertexData); + } + // Sub material + const material = gltfRuntime.scene.getMaterialById(primitive.material); + subMaterials.push(material === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material); + // Update vertices start and index start + verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]); + indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]); + } + } + let material; + gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer; + if (subMaterials.length > 1) { + material = new MultiMaterial("multimat" + id, gltfRuntime.scene); + material.subMaterials = subMaterials; + } + else { + material = new StandardMaterial("multimat" + id, gltfRuntime.scene); + } + if (subMaterials.length === 1) { + material = subMaterials[0]; + } + material._parentContainer = gltfRuntime.assetContainer; + if (!newMesh.material) { + newMesh.material = material; + } + // Apply geometry + new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh); + newMesh.computeWorldMatrix(true); + gltfRuntime.scene._blockEntityCollection = false; + // Apply submeshes + newMesh.subMeshes = []; + let index = 0; + for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) { + const meshId = meshes[meshIndex]; + const mesh = gltfRuntime.meshes[meshId]; + if (!mesh) { + continue; + } + for (let i = 0; i < mesh.primitives.length; i++) { + if (mesh.primitives[i].mode !== 4) ; + SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true); + index++; + } + } + // Finish + return newMesh; +}; +/** + * Configure node transformation from position, rotation and scaling + * @param newNode + * @param position + * @param rotation + * @param scaling + */ +const configureNode = (newNode, position, rotation, scaling) => { + if (newNode.position) { + newNode.position = position; + } + if (newNode.rotationQuaternion || newNode.rotation) { + newNode.rotationQuaternion = rotation; + } + if (newNode.scaling) { + newNode.scaling = scaling; + } +}; +/** + * Configures node from transformation matrix + * @param newNode + * @param node + */ +const configureNodeFromMatrix = (newNode, node) => { + if (node.matrix) { + const position = new Vector3(0, 0, 0); + const rotation = new Quaternion(); + const scaling = new Vector3(0, 0, 0); + const mat = Matrix.FromArray(node.matrix); + mat.decompose(scaling, rotation, position); + configureNode(newNode, position, rotation, scaling); + } + else if (node.translation && node.rotation && node.scale) { + configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale)); + } + newNode.computeWorldMatrix(true); +}; +/** + * Imports a node + * @param gltfRuntime + * @param node + * @param id + * @returns the newly imported node + */ +const importNode = (gltfRuntime, node, id) => { + let lastNode = null; + if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) { + if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) { + return null; + } + } + // Meshes + if (node.skin) { + if (node.meshes) { + const skin = gltfRuntime.skins[node.skin]; + const newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode); + newMesh.skeleton = gltfRuntime.scene.getLastSkeletonById(node.skin); + if (newMesh.skeleton === null) { + newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton); + if (!skin.babylonSkeleton) { + skin.babylonSkeleton = newMesh.skeleton; + } + } + lastNode = newMesh; + } + } + else if (node.meshes) { + /** + * Improve meshes property + */ + const newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode); + lastNode = newMesh; + } + // Lights + else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) { + const light = gltfRuntime.lights[node.light]; + if (light) { + if (light.type === "ambient") { + const ambienLight = light[light.type]; + const hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene); + hemiLight.name = node.name || ""; + if (ambienLight.color) { + hemiLight.diffuse = Color3.FromArray(ambienLight.color); + } + lastNode = hemiLight; + } + else if (light.type === "directional") { + const directionalLight = light[light.type]; + const dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene); + dirLight.name = node.name || ""; + if (directionalLight.color) { + dirLight.diffuse = Color3.FromArray(directionalLight.color); + } + lastNode = dirLight; + } + else if (light.type === "point") { + const pointLight = light[light.type]; + const ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene); + ptLight.name = node.name || ""; + if (pointLight.color) { + ptLight.diffuse = Color3.FromArray(pointLight.color); + } + lastNode = ptLight; + } + else if (light.type === "spot") { + const spotLight = light[light.type]; + const spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene); + spLight.name = node.name || ""; + if (spotLight.color) { + spLight.diffuse = Color3.FromArray(spotLight.color); + } + if (spotLight.fallOfAngle) { + spLight.angle = spotLight.fallOfAngle; + } + if (spotLight.fallOffExponent) { + spLight.exponent = spotLight.fallOffExponent; + } + lastNode = spLight; + } + } + } + // Cameras + else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) { + const camera = gltfRuntime.cameras[node.camera]; + if (camera) { + gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer; + if (camera.type === "orthographic") { + const orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false); + orthoCamera.name = node.name || ""; + orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA; + orthoCamera.attachControl(); + lastNode = orthoCamera; + orthoCamera._parentContainer = gltfRuntime.assetContainer; + } + else if (camera.type === "perspective") { + const perspectiveCamera = camera[camera.type]; + const persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false); + persCamera.name = node.name || ""; + persCamera.attachControl(); + if (!perspectiveCamera.aspectRatio) { + perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight(); + } + if (perspectiveCamera.znear && perspectiveCamera.zfar) { + persCamera.maxZ = perspectiveCamera.zfar; + persCamera.minZ = perspectiveCamera.znear; + } + lastNode = persCamera; + persCamera._parentContainer = gltfRuntime.assetContainer; + } + gltfRuntime.scene._blockEntityCollection = false; + } + } + // Empty node + if (!node.jointName) { + if (node.babylonNode) { + return node.babylonNode; + } + else if (lastNode === null) { + gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer; + const dummy = new Mesh(node.name || "", gltfRuntime.scene); + dummy._parentContainer = gltfRuntime.assetContainer; + gltfRuntime.scene._blockEntityCollection = false; + node.babylonNode = dummy; + lastNode = dummy; + } + } + if (lastNode !== null) { + if (node.matrix && lastNode instanceof Mesh) { + configureNodeFromMatrix(lastNode, node); + } + else { + const translation = node.translation || [0, 0, 0]; + const rotation = node.rotation || [0, 0, 0, 1]; + const scale = node.scale || [1, 1, 1]; + configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale)); + } + lastNode.updateCache(true); + node.babylonNode = lastNode; + } + return lastNode; +}; +/** + * Traverses nodes and creates them + * @param gltfRuntime + * @param id + * @param parent + * @param meshIncluded + */ +const traverseNodes = (gltfRuntime, id, parent, meshIncluded = false) => { + const node = gltfRuntime.nodes[id]; + let newNode = null; + if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) { + if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) { + meshIncluded = true; + } + else { + meshIncluded = false; + } + } + else { + meshIncluded = true; + } + if (!node.jointName && meshIncluded) { + newNode = importNode(gltfRuntime, node, id); + if (newNode !== null) { + newNode.id = id; + newNode.parent = parent; + } + } + if (node.children) { + for (let i = 0; i < node.children.length; i++) { + traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded); + } + } +}; +/** + * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.) + * @param gltfRuntime + */ +const postLoad = (gltfRuntime) => { + // Nodes + let currentScene = gltfRuntime.currentScene; + if (currentScene) { + for (let i = 0; i < currentScene.nodes.length; i++) { + traverseNodes(gltfRuntime, currentScene.nodes[i], null); + } + } + else { + for (const thing in gltfRuntime.scenes) { + currentScene = gltfRuntime.scenes[thing]; + for (let i = 0; i < currentScene.nodes.length; i++) { + traverseNodes(gltfRuntime, currentScene.nodes[i], null); + } + } + } + // Set animations + loadAnimations(gltfRuntime); + for (let i = 0; i < gltfRuntime.scene.skeletons.length; i++) { + const skeleton = gltfRuntime.scene.skeletons[i]; + gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0); + } +}; +/** + * onBind shaderrs callback to set uniforms and matrices + * @param mesh + * @param gltfRuntime + * @param unTreatedUniforms + * @param shaderMaterial + * @param technique + * @param material + * @param onSuccess + */ +const onBindShaderMaterial = (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) => { + const materialValues = material.values || technique.parameters; + for (const unif in unTreatedUniforms) { + const uniform = unTreatedUniforms[unif]; + const type = uniform.type; + if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) { + if (uniform.semantic && !uniform.source && !uniform.node) { + GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect()); + } + else if (uniform.semantic && (uniform.source || uniform.node)) { + let source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || ""); + if (source === null) { + source = gltfRuntime.scene.getNodeById(uniform.source || uniform.node || ""); + } + if (source === null) { + continue; + } + GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect()); + } + } + else { + const value = materialValues[technique.uniforms[unif]]; + if (!value) { + continue; + } + if (type === EParameterType.SAMPLER_2D) { + const texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture; + if (texture === null || texture === undefined) { + continue; + } + shaderMaterial.getEffect().setTexture(unif, texture); + } + else { + GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type); + } + } + } + onSuccess(shaderMaterial); +}; +/** + * Prepare uniforms to send the only one time + * Loads the appropriate textures + * @param gltfRuntime + * @param shaderMaterial + * @param technique + * @param material + */ +const prepareShaderMaterialUniforms = (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) => { + const materialValues = material.values || technique.parameters; + const techniqueUniforms = technique.uniforms; + /** + * Prepare values here (not matrices) + */ + for (const unif in unTreatedUniforms) { + const uniform = unTreatedUniforms[unif]; + const type = uniform.type; + let value = materialValues[techniqueUniforms[unif]]; + if (value === undefined) { + // In case the value is the same for all materials + value = uniform.value; + } + if (!value) { + continue; + } + const onLoadTexture = (uniformName) => { + return (texture) => { + if (uniform.value && uniformName) { + // Static uniform + shaderMaterial.setTexture(uniformName, texture); + delete unTreatedUniforms[uniformName]; + } + }; + }; + // Texture (sampler2D) + if (type === EParameterType.SAMPLER_2D) { + GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), () => onLoadTexture(null)); + } + // Others + else { + if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) { + // Static uniform + delete unTreatedUniforms[unif]; + } + } + } +}; +/** + * Shader compilation failed + * @param program + * @param shaderMaterial + * @param onError + * @returns callback when shader is compiled + */ +const onShaderCompileError = (program, shaderMaterial, onError) => { + return (effect, error) => { + shaderMaterial.dispose(true); + onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied"); + }; +}; +/** + * Shader compilation success + * @param gltfRuntime + * @param shaderMaterial + * @param technique + * @param material + * @param unTreatedUniforms + * @param onSuccess + * @returns callback when shader is compiled + */ +const onShaderCompileSuccess = (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) => { + return (_) => { + prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms); + shaderMaterial.onBind = (mesh) => { + onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess); + }; + }; +}; +/** + * Returns the appropriate uniform if already handled by babylon + * @param tokenizer + * @param technique + * @param unTreatedUniforms + * @returns the name of the uniform handled by babylon + */ +const parseShaderUniforms = (tokenizer, technique, unTreatedUniforms) => { + for (const unif in technique.uniforms) { + const uniform = technique.uniforms[unif]; + const uniformParameter = technique.parameters[uniform]; + if (tokenizer.currentIdentifier === unif) { + if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) { + const transformIndex = glTFTransforms.indexOf(uniformParameter.semantic); + if (transformIndex !== -1) { + delete unTreatedUniforms[unif]; + return babylonTransforms[transformIndex]; + } + } + } + } + return tokenizer.currentIdentifier; +}; +/** + * All shaders loaded. Create materials one by one + * @param gltfRuntime + */ +const importMaterials = (gltfRuntime) => { + // Create materials + for (const mat in gltfRuntime.materials) { + GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, () => { }, () => { }); + } +}; +/** + * Implementation of the base glTF spec + * @internal + */ +class GLTFLoaderBase { + static CreateRuntime(parsedData, scene, rootUrl) { + const gltfRuntime = { + extensions: {}, + accessors: {}, + buffers: {}, + bufferViews: {}, + meshes: {}, + lights: {}, + cameras: {}, + nodes: {}, + images: {}, + textures: {}, + shaders: {}, + programs: {}, + samplers: {}, + techniques: {}, + materials: {}, + animations: {}, + skins: {}, + extensionsUsed: [], + scenes: {}, + buffersCount: 0, + shaderscount: 0, + scene: scene, + rootUrl: rootUrl, + loadedBufferCount: 0, + loadedBufferViews: {}, + loadedShaderCount: 0, + importOnlyMeshes: false, + dummyNodes: [], + assetContainer: null, + }; + // Parse + if (parsedData.extensions) { + parseObject(parsedData.extensions, "extensions", gltfRuntime); + } + if (parsedData.extensionsUsed) { + parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime); + } + if (parsedData.buffers) { + parseBuffers(parsedData.buffers, gltfRuntime); + } + if (parsedData.bufferViews) { + parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime); + } + if (parsedData.accessors) { + parseObject(parsedData.accessors, "accessors", gltfRuntime); + } + if (parsedData.meshes) { + parseObject(parsedData.meshes, "meshes", gltfRuntime); + } + if (parsedData.lights) { + parseObject(parsedData.lights, "lights", gltfRuntime); + } + if (parsedData.cameras) { + parseObject(parsedData.cameras, "cameras", gltfRuntime); + } + if (parsedData.nodes) { + parseObject(parsedData.nodes, "nodes", gltfRuntime); + } + if (parsedData.images) { + parseObject(parsedData.images, "images", gltfRuntime); + } + if (parsedData.textures) { + parseObject(parsedData.textures, "textures", gltfRuntime); + } + if (parsedData.shaders) { + parseShaders(parsedData.shaders, gltfRuntime); + } + if (parsedData.programs) { + parseObject(parsedData.programs, "programs", gltfRuntime); + } + if (parsedData.samplers) { + parseObject(parsedData.samplers, "samplers", gltfRuntime); + } + if (parsedData.techniques) { + parseObject(parsedData.techniques, "techniques", gltfRuntime); + } + if (parsedData.materials) { + parseObject(parsedData.materials, "materials", gltfRuntime); + } + if (parsedData.animations) { + parseObject(parsedData.animations, "animations", gltfRuntime); + } + if (parsedData.skins) { + parseObject(parsedData.skins, "skins", gltfRuntime); + } + if (parsedData.scenes) { + gltfRuntime.scenes = parsedData.scenes; + } + if (parsedData.scene && parsedData.scenes) { + gltfRuntime.currentScene = parsedData.scenes[parsedData.scene]; + } + return gltfRuntime; + } + static LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) { + const buffer = gltfRuntime.buffers[id]; + if (Tools.IsBase64(buffer.uri)) { + setTimeout(() => onSuccess(new Uint8Array(Tools.DecodeBase64(buffer.uri)))); + } + else { + Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, (data) => onSuccess(new Uint8Array(data)), onProgress, undefined, true, (request) => { + if (request) { + onError(request.status + " " + request.statusText); + } + }); + } + } + static LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) { + const texture = gltfRuntime.textures[id]; + if (!texture || !texture.source) { + onError(""); + return; + } + if (texture.babylonTexture) { + onSuccess(null); + return; + } + const source = gltfRuntime.images[texture.source]; + if (Tools.IsBase64(source.uri)) { + setTimeout(() => onSuccess(new Uint8Array(Tools.DecodeBase64(source.uri)))); + } + else { + Tools.LoadFile(gltfRuntime.rootUrl + source.uri, (data) => onSuccess(new Uint8Array(data)), undefined, undefined, true, (request) => { + if (request) { + onError(request.status + " " + request.statusText); + } + }); + } + } + static CreateTextureAsync(gltfRuntime, id, buffer, onSuccess) { + const texture = gltfRuntime.textures[id]; + if (texture.babylonTexture) { + onSuccess(texture.babylonTexture); + return; + } + const sampler = gltfRuntime.samplers[texture.sampler]; + const createMipMaps = sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST || + sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR || + sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST || + sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR; + const samplingMode = Texture.BILINEAR_SAMPLINGMODE; + const blob = buffer == null ? new Blob() : new Blob([buffer]); + const blobURL = URL.createObjectURL(blob); + const revokeBlobURL = () => URL.revokeObjectURL(blobURL); + const newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL); + if (sampler.wrapS !== undefined) { + newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS); + } + if (sampler.wrapT !== undefined) { + newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT); + } + newTexture.name = id; + texture.babylonTexture = newTexture; + onSuccess(newTexture); + } + static LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError) { + const shader = gltfRuntime.shaders[id]; + if (Tools.IsBase64(shader.uri)) { + const shaderString = atob(shader.uri.split(",")[1]); + if (onSuccess) { + onSuccess(shaderString); + } + } + else { + Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, (request) => { + if (request && onError) { + onError(request.status + " " + request.statusText); + } + }); + } + } + static LoadMaterialAsync(gltfRuntime, id, onSuccess, onError) { + const material = gltfRuntime.materials[id]; + if (!material.technique) { + if (onError) { + onError("No technique found."); + } + return; + } + const technique = gltfRuntime.techniques[material.technique]; + if (!technique) { + gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer; + const defaultMaterial = new StandardMaterial(id, gltfRuntime.scene); + defaultMaterial._parentContainer = gltfRuntime.assetContainer; + gltfRuntime.scene._blockEntityCollection = false; + defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5); + defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation; + onSuccess(defaultMaterial); + return; + } + const program = gltfRuntime.programs[technique.program]; + const states = technique.states; + const vertexShader = Effect.ShadersStore[program.vertexShader + "VertexShader"]; + const pixelShader = Effect.ShadersStore[program.fragmentShader + "PixelShader"]; + let newVertexShader = ""; + let newPixelShader = ""; + const vertexTokenizer = new Tokenizer(vertexShader); + const pixelTokenizer = new Tokenizer(pixelShader); + const unTreatedUniforms = {}; + const uniforms = []; + const attributes = []; + const samplers = []; + // Fill uniform, sampler2D and attributes + for (const unif in technique.uniforms) { + const uniform = technique.uniforms[unif]; + const uniformParameter = technique.parameters[uniform]; + unTreatedUniforms[unif] = uniformParameter; + if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) { + const transformIndex = glTFTransforms.indexOf(uniformParameter.semantic); + if (transformIndex !== -1) { + uniforms.push(babylonTransforms[transformIndex]); + delete unTreatedUniforms[unif]; + } + else { + uniforms.push(unif); + } + } + else if (uniformParameter.type === EParameterType.SAMPLER_2D) { + samplers.push(unif); + } + else { + uniforms.push(unif); + } + } + for (const attr in technique.attributes) { + const attribute = technique.attributes[attr]; + const attributeParameter = technique.parameters[attribute]; + if (attributeParameter.semantic) { + const name = getAttribute(attributeParameter); + if (name) { + attributes.push(name); + } + } + } + // Configure vertex shader + while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) { + const tokenType = vertexTokenizer.currentToken; + if (tokenType !== ETokenType.IDENTIFIER) { + newVertexShader += vertexTokenizer.currentString; + continue; + } + let foundAttribute = false; + for (const attr in technique.attributes) { + const attribute = technique.attributes[attr]; + const attributeParameter = technique.parameters[attribute]; + if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) { + newVertexShader += getAttribute(attributeParameter); + foundAttribute = true; + break; + } + } + if (foundAttribute) { + continue; + } + newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms); + } + // Configure pixel shader + while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) { + const tokenType = pixelTokenizer.currentToken; + if (tokenType !== ETokenType.IDENTIFIER) { + newPixelShader += pixelTokenizer.currentString; + continue; + } + newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms); + } + // Create shader material + const shaderPath = { + vertex: program.vertexShader + id, + fragment: program.fragmentShader + id, + }; + const options = { + attributes: attributes, + uniforms: uniforms, + samplers: samplers, + needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1, + }; + Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader; + Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader; + const shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options); + shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError); + shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess); + shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation; + if (states && states.functions) { + const functions = states.functions; + if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) { + shaderMaterial.backFaceCulling = false; + } + const blendFunc = functions.blendFuncSeparate; + if (blendFunc) { + if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && + blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA && + blendFunc[2] === EBlendingFunction.ONE && + blendFunc[3] === EBlendingFunction.ONE) { + shaderMaterial.alphaMode = Constants.ALPHA_COMBINE; + } + else if (blendFunc[0] === EBlendingFunction.ONE && + blendFunc[1] === EBlendingFunction.ONE && + blendFunc[2] === EBlendingFunction.ZERO && + blendFunc[3] === EBlendingFunction.ONE) { + shaderMaterial.alphaMode = Constants.ALPHA_ONEONE; + } + else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && + blendFunc[1] === EBlendingFunction.ONE && + blendFunc[2] === EBlendingFunction.ZERO && + blendFunc[3] === EBlendingFunction.ONE) { + shaderMaterial.alphaMode = Constants.ALPHA_ADD; + } + else if (blendFunc[0] === EBlendingFunction.ZERO && + blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && + blendFunc[2] === EBlendingFunction.ONE && + blendFunc[3] === EBlendingFunction.ONE) { + shaderMaterial.alphaMode = Constants.ALPHA_SUBTRACT; + } + else if (blendFunc[0] === EBlendingFunction.DST_COLOR && + blendFunc[1] === EBlendingFunction.ZERO && + blendFunc[2] === EBlendingFunction.ONE && + blendFunc[3] === EBlendingFunction.ONE) { + shaderMaterial.alphaMode = Constants.ALPHA_MULTIPLY; + } + else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && + blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && + blendFunc[2] === EBlendingFunction.ONE && + blendFunc[3] === EBlendingFunction.ONE) { + shaderMaterial.alphaMode = Constants.ALPHA_MAXIMIZED; + } + } + } + } +} +/** + * glTF V1 Loader + * @internal + * @deprecated + */ +let GLTFLoader$1 = class GLTFLoader { + static RegisterExtension(extension) { + if (GLTFLoader.Extensions[extension.name]) { + Tools.Error('Tool with the same name "' + extension.name + '" already exists'); + return; + } + GLTFLoader.Extensions[extension.name] = extension; + } + dispose() { + // do nothing + } + _importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, onSuccess, onProgress, onError) { + scene.useRightHandedSystem = true; + GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, (gltfRuntime) => { + gltfRuntime.assetContainer = assetContainer; + gltfRuntime.importOnlyMeshes = true; + if (meshesNames === "") { + gltfRuntime.importMeshesNames = []; + } + else if (typeof meshesNames === "string") { + gltfRuntime.importMeshesNames = [meshesNames]; + } + else if (meshesNames && !(meshesNames instanceof Array)) { + gltfRuntime.importMeshesNames = [meshesNames]; + } + else { + gltfRuntime.importMeshesNames = []; + Tools.Warn("Argument meshesNames must be of type string or string[]"); + } + // Create nodes + this._createNodes(gltfRuntime); + const meshes = []; + const skeletons = []; + // Fill arrays of meshes and skeletons + for (const nde in gltfRuntime.nodes) { + const node = gltfRuntime.nodes[nde]; + if (node.babylonNode instanceof AbstractMesh) { + meshes.push(node.babylonNode); + } + } + for (const skl in gltfRuntime.skins) { + const skin = gltfRuntime.skins[skl]; + if (skin.babylonSkeleton instanceof Skeleton) { + skeletons.push(skin.babylonSkeleton); + } + } + // Load buffers, shaders, materials, etc. + this._loadBuffersAsync(gltfRuntime, () => { + this._loadShadersAsync(gltfRuntime, () => { + importMaterials(gltfRuntime); + postLoad(gltfRuntime); + if (!GLTFFileLoader.IncrementalLoading && onSuccess) { + onSuccess(meshes, skeletons); + } + }); + }); + if (GLTFFileLoader.IncrementalLoading && onSuccess) { + onSuccess(meshes, skeletons); + } + }, onError); + return true; + } + /** + * Imports one or more meshes from a loaded gltf file and adds them to the scene + * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file + * @param scene the scene the meshes should be added to + * @param assetContainer defines the asset container to use (can be null) + * @param data gltf data containing information of the meshes in a loaded file + * @param rootUrl root url to load from + * @param onProgress event that fires when loading progress has occured + * @returns a promise containg the loaded meshes, particles, skeletons and animations + */ + importMeshAsync(meshesNames, scene, assetContainer, data, rootUrl, onProgress) { + return new Promise((resolve, reject) => { + this._importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, (meshes, skeletons) => { + resolve({ + meshes: meshes, + particleSystems: [], + skeletons: skeletons, + animationGroups: [], + lights: [], + transformNodes: [], + geometries: [], + spriteManagers: [], + }); + }, onProgress, (message) => { + reject(new Error(message)); + }); + }); + } + _loadAsync(scene, data, rootUrl, onSuccess, onProgress, onError) { + scene.useRightHandedSystem = true; + GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, (gltfRuntime) => { + // Load runtime extensios + GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, () => { + // Create nodes + this._createNodes(gltfRuntime); + // Load buffers, shaders, materials, etc. + this._loadBuffersAsync(gltfRuntime, () => { + this._loadShadersAsync(gltfRuntime, () => { + importMaterials(gltfRuntime); + postLoad(gltfRuntime); + if (!GLTFFileLoader.IncrementalLoading) { + onSuccess(); + } + }); + }); + if (GLTFFileLoader.IncrementalLoading) { + onSuccess(); + } + }, onError); + }, onError); + } + /** + * Imports all objects from a loaded gltf file and adds them to the scene + * @param scene the scene the objects should be added to + * @param data gltf data containing information of the meshes in a loaded file + * @param rootUrl root url to load from + * @param onProgress event that fires when loading progress has occured + * @returns a promise which completes when objects have been loaded to the scene + */ + loadAsync(scene, data, rootUrl, onProgress) { + return new Promise((resolve, reject) => { + this._loadAsync(scene, data, rootUrl, () => { + resolve(); + }, onProgress, (message) => { + reject(new Error(message)); + }); + }); + } + _loadShadersAsync(gltfRuntime, onload) { + let hasShaders = false; + const processShader = (sha, shader) => { + GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, (shaderString) => { + if (shaderString instanceof ArrayBuffer) { + return; + } + gltfRuntime.loadedShaderCount++; + if (shaderString) { + Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString; + } + if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) { + onload(); + } + }, () => { + Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri); + }); + }; + for (const sha in gltfRuntime.shaders) { + hasShaders = true; + const shader = gltfRuntime.shaders[sha]; + if (shader) { + processShader.bind(this, sha, shader)(); + } + else { + Tools.Error("No shader named: " + sha); + } + } + if (!hasShaders) { + onload(); + } + } + _loadBuffersAsync(gltfRuntime, onLoad) { + let hasBuffers = false; + const processBuffer = (buf, buffer) => { + GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, (bufferView) => { + gltfRuntime.loadedBufferCount++; + if (bufferView) { + if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) { + Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message + } + gltfRuntime.loadedBufferViews[buf] = bufferView; + } + if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) { + onLoad(); + } + }, () => { + Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri); + }); + }; + for (const buf in gltfRuntime.buffers) { + hasBuffers = true; + const buffer = gltfRuntime.buffers[buf]; + if (buffer) { + processBuffer.bind(this, buf, buffer)(); + } + else { + Tools.Error("No buffer named: " + buf); + } + } + if (!hasBuffers) { + onLoad(); + } + } + _createNodes(gltfRuntime) { + let currentScene = gltfRuntime.currentScene; + if (currentScene) { + // Only one scene even if multiple scenes are defined + for (let i = 0; i < currentScene.nodes.length; i++) { + traverseNodes(gltfRuntime, currentScene.nodes[i], null); + } + } + else { + // Load all scenes + for (const thing in gltfRuntime.scenes) { + currentScene = gltfRuntime.scenes[thing]; + for (let i = 0; i < currentScene.nodes.length; i++) { + traverseNodes(gltfRuntime, currentScene.nodes[i], null); + } + } + } + } +}; +GLTFLoader$1.Extensions = {}; +/** @internal */ +class GLTFLoaderExtension { + constructor(name) { + this._name = name; + } + get name() { + return this._name; + } + /** + * Defines an override for loading the runtime + * Return true to stop further extensions from loading the runtime + * @param scene + * @param data + * @param rootUrl + * @param onSuccess + * @param onError + * @returns true to stop further extensions from loading the runtime + */ + loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError) { + return false; + } + /** + * Defines an onverride for creating gltf runtime + * Return true to stop further extensions from creating the runtime + * @param gltfRuntime + * @param onSuccess + * @param onError + * @returns true to stop further extensions from creating the runtime + */ + loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError) { + return false; + } + /** + * Defines an override for loading buffers + * Return true to stop further extensions from loading this buffer + * @param gltfRuntime + * @param id + * @param onSuccess + * @param onError + * @param onProgress + * @returns true to stop further extensions from loading this buffer + */ + loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) { + return false; + } + /** + * Defines an override for loading texture buffers + * Return true to stop further extensions from loading this texture data + * @param gltfRuntime + * @param id + * @param onSuccess + * @param onError + * @returns true to stop further extensions from loading this texture data + */ + loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) { + return false; + } + /** + * Defines an override for creating textures + * Return true to stop further extensions from loading this texture + * @param gltfRuntime + * @param id + * @param buffer + * @param onSuccess + * @param onError + * @returns true to stop further extensions from loading this texture + */ + createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError) { + return false; + } + /** + * Defines an override for loading shader strings + * Return true to stop further extensions from loading this shader data + * @param gltfRuntime + * @param id + * @param onSuccess + * @param onError + * @returns true to stop further extensions from loading this shader data + */ + loadShaderStringAsync(gltfRuntime, id, onSuccess, onError) { + return false; + } + /** + * Defines an override for loading materials + * Return true to stop further extensions from loading this material + * @param gltfRuntime + * @param id + * @param onSuccess + * @param onError + * @returns true to stop further extensions from loading this material + */ + loadMaterialAsync(gltfRuntime, id, onSuccess, onError) { + return false; + } + // --------- + // Utilities + // --------- + static LoadRuntimeAsync(scene, data, rootUrl, onSuccess, onError) { + GLTFLoaderExtension._ApplyExtensions((loaderExtension) => { + return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError); + }, () => { + setTimeout(() => { + if (!onSuccess) { + return; + } + onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl)); + }); + }); + } + static LoadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError) { + GLTFLoaderExtension._ApplyExtensions((loaderExtension) => { + return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError); + }, () => { + setTimeout(() => { + onSuccess(); + }); + }); + } + static LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) { + GLTFLoaderExtension._ApplyExtensions((loaderExtension) => { + return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress); + }, () => { + GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress); + }); + } + static LoadTextureAsync(gltfRuntime, id, onSuccess, onError) { + GLTFLoaderExtension._LoadTextureBufferAsync(gltfRuntime, id, (buffer) => { + if (buffer) { + GLTFLoaderExtension._CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); + } + }, onError); + } + static LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError) { + GLTFLoaderExtension._ApplyExtensions((loaderExtension) => { + return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError); + }, () => { + GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError); + }); + } + static LoadMaterialAsync(gltfRuntime, id, onSuccess, onError) { + GLTFLoaderExtension._ApplyExtensions((loaderExtension) => { + return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError); + }, () => { + GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError); + }); + } + static _LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) { + GLTFLoaderExtension._ApplyExtensions((loaderExtension) => { + return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError); + }, () => { + GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError); + }); + } + static _CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError) { + GLTFLoaderExtension._ApplyExtensions((loaderExtension) => { + return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); + }, () => { + GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess); + }); + } + static _ApplyExtensions(func, defaultFunc) { + for (const extensionName in GLTFLoader$1.Extensions) { + const loaderExtension = GLTFLoader$1.Extensions[extensionName]; + if (func(loaderExtension)) { + return; + } + } + defaultFunc(); + } +} +GLTFFileLoader._CreateGLTF1Loader = () => new GLTFLoader$1(); + +const BinaryExtensionBufferName = "binary_glTF"; +/** + * @internal + * @deprecated + */ +class GLTFBinaryExtension extends GLTFLoaderExtension { + constructor() { + super("KHR_binary_glTF"); + } + loadRuntimeAsync(scene, data, rootUrl, onSuccess) { + const extensionsUsed = data.json.extensionsUsed; + if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) { + return false; + } + this._bin = data.bin; + onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl)); + return true; + } + loadBufferAsync(gltfRuntime, id, onSuccess, onError) { + if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) { + return false; + } + if (id !== BinaryExtensionBufferName) { + return false; + } + this._bin.readAsync(0, this._bin.byteLength).then(onSuccess, (error) => onError(error.message)); + return true; + } + loadTextureBufferAsync(gltfRuntime, id, onSuccess) { + const texture = gltfRuntime.textures[id]; + const source = gltfRuntime.images[texture.source]; + if (!source.extensions || !(this.name in source.extensions)) { + return false; + } + const sourceExt = source.extensions[this.name]; + const bufferView = gltfRuntime.bufferViews[sourceExt.bufferView]; + const buffer = GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE); + onSuccess(buffer); + return true; + } + loadShaderStringAsync(gltfRuntime, id, onSuccess) { + const shader = gltfRuntime.shaders[id]; + if (!shader.extensions || !(this.name in shader.extensions)) { + return false; + } + const binaryExtensionShader = shader.extensions[this.name]; + const bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView]; + const shaderBytes = GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE); + setTimeout(() => { + const shaderString = GLTFUtils.DecodeBufferToText(shaderBytes); + onSuccess(shaderString); + }); + return true; + } +} +GLTFLoader$1.RegisterExtension(new GLTFBinaryExtension()); + +/** + * @internal + * @deprecated + */ +class GLTFMaterialsCommonExtension extends GLTFLoaderExtension { + constructor() { + super("KHR_materials_common"); + } + loadRuntimeExtensionsAsync(gltfRuntime) { + if (!gltfRuntime.extensions) { + return false; + } + const extension = gltfRuntime.extensions[this.name]; + if (!extension) { + return false; + } + // Create lights + const lights = extension.lights; + if (lights) { + for (const thing in lights) { + const light = lights[thing]; + switch (light.type) { + case "ambient": { + const ambientLight = new HemisphericLight(light.name, new Vector3(0, 1, 0), gltfRuntime.scene); + const ambient = light.ambient; + if (ambient) { + ambientLight.diffuse = Color3.FromArray(ambient.color || [1, 1, 1]); + } + break; + } + case "point": { + const pointLight = new PointLight(light.name, new Vector3(10, 10, 10), gltfRuntime.scene); + const point = light.point; + if (point) { + pointLight.diffuse = Color3.FromArray(point.color || [1, 1, 1]); + } + break; + } + case "directional": { + const dirLight = new DirectionalLight(light.name, new Vector3(0, -1, 0), gltfRuntime.scene); + const directional = light.directional; + if (directional) { + dirLight.diffuse = Color3.FromArray(directional.color || [1, 1, 1]); + } + break; + } + case "spot": { + const spot = light.spot; + if (spot) { + const spotLight = new SpotLight(light.name, new Vector3(0, 10, 0), new Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene); + spotLight.diffuse = Color3.FromArray(spot.color || [1, 1, 1]); + } + break; + } + default: + Tools.Warn('GLTF Material Common extension: light type "' + light.type + "” not supported"); + break; + } + } + } + return false; + } + loadMaterialAsync(gltfRuntime, id, onSuccess, onError) { + const material = gltfRuntime.materials[id]; + if (!material || !material.extensions) { + return false; + } + const extension = material.extensions[this.name]; + if (!extension) { + return false; + } + const standardMaterial = new StandardMaterial(id, gltfRuntime.scene); + standardMaterial.sideOrientation = Material.CounterClockWiseSideOrientation; + if (extension.technique === "CONSTANT") { + standardMaterial.disableLighting = true; + } + standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided; + standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency; + standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess; + // Ambient + if (typeof extension.values.ambient === "string") { + this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError); + } + else { + standardMaterial.ambientColor = Color3.FromArray(extension.values.ambient || [0, 0, 0]); + } + // Diffuse + if (typeof extension.values.diffuse === "string") { + this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError); + } + else { + standardMaterial.diffuseColor = Color3.FromArray(extension.values.diffuse || [0, 0, 0]); + } + // Emission + if (typeof extension.values.emission === "string") { + this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError); + } + else { + standardMaterial.emissiveColor = Color3.FromArray(extension.values.emission || [0, 0, 0]); + } + // Specular + if (typeof extension.values.specular === "string") { + this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError); + } + else { + standardMaterial.specularColor = Color3.FromArray(extension.values.specular || [0, 0, 0]); + } + return true; + } + _loadTexture(gltfRuntime, id, material, propertyPath, onError) { + // Create buffer from texture url + GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, (buffer) => { + // Create texture from buffer + GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, (texture) => (material[propertyPath] = texture)); + }, onError); + } +} +GLTFLoader$1.RegisterExtension(new GLTFMaterialsCommonExtension()); + +/** + * Wrapper class for promise with external resolve and reject. + */ +class Deferred { + /** + * The resolve method of the promise associated with this deferred object. + */ + get resolve() { + return this._resolve; + } + /** + * The reject method of the promise associated with this deferred object. + */ + get reject() { + return this._reject; + } + /** + * Constructor for this deferred object. + */ + constructor() { + this.promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + } +} + +/** + * PassPostProcess which produces an output the same as it's input + */ +class ThinPassPostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => pass_fragment)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => pass_fragment$1)])); + } + super._gatherImports(useWebGPU, list); + } + /** + * Constructs a new pass post process + * @param name Name of the effect + * @param engine Engine to use to render the effect. If not provided, the last created engine will be used + * @param options Options to configure the effect + */ + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinPassPostProcess.FragmentUrl, + }); + } +} +/** + * The fragment shader url + */ +ThinPassPostProcess.FragmentUrl = "pass"; +/** + * PassCubePostProcess which produces an output the same as it's input (which must be a cube texture) + */ +class ThinPassCubePostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => passCube_fragment)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => passCube_fragment$1)])); + } + super._gatherImports(useWebGPU, list); + } + /** + * Creates the PassCubePostProcess + * @param name Name of the effect + * @param engine Engine to use to render the effect. If not provided, the last created engine will be used + * @param options Options to configure the effect + */ + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinPassCubePostProcess.FragmentUrl, + defines: "#define POSITIVEX", + }); + this._face = 0; + } + /** + * Gets or sets the cube face to display. + * * 0 is +X + * * 1 is -X + * * 2 is +Y + * * 3 is -Y + * * 4 is +Z + * * 5 is -Z + */ + get face() { + return this._face; + } + set face(value) { + if (value < 0 || value > 5) { + return; + } + this._face = value; + switch (this._face) { + case 0: + this.updateEffect("#define POSITIVEX"); + break; + case 1: + this.updateEffect("#define NEGATIVEX"); + break; + case 2: + this.updateEffect("#define POSITIVEY"); + break; + case 3: + this.updateEffect("#define NEGATIVEY"); + break; + case 4: + this.updateEffect("#define POSITIVEZ"); + break; + case 5: + this.updateEffect("#define NEGATIVEZ"); + break; + } + } +} +/** + * The fragment shader url + */ +ThinPassCubePostProcess.FragmentUrl = "passCube"; + +/** + * PassPostProcess which produces an output the same as it's input + */ +class PassPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "PassPostProcess" string + */ + getClassName() { + return "PassPostProcess"; + } + /** + * Creates the PassPostProcess + * @param name The name of the effect. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType The type of texture to be used when performing the post processing. + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { + const localOptions = { + size: typeof options === "number" ? options : undefined, + camera, + samplingMode, + engine, + reusable, + textureType, + blockCompilation, + ...options, + }; + super(name, ThinPassPostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinPassPostProcess(name, engine, localOptions) : undefined, + ...localOptions, + }); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new PassPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +RegisterClass("BABYLON.PassPostProcess", PassPostProcess); +/** + * PassCubePostProcess which produces an output the same as it's input (which must be a cube texture) + */ +class PassCubePostProcess extends PostProcess { + /** + * Gets or sets the cube face to display. + * * 0 is +X + * * 1 is -X + * * 2 is +Y + * * 3 is -Y + * * 4 is +Z + * * 5 is -Z + */ + get face() { + return this._effectWrapper.face; + } + set face(value) { + this._effectWrapper.face = value; + } + /** + * Gets a string identifying the name of the class + * @returns "PassCubePostProcess" string + */ + getClassName() { + return "PassCubePostProcess"; + } + /** + * Creates the PassCubePostProcess + * @param name The name of the effect. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType The type of texture to be used when performing the post processing. + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { + const localOptions = { + size: typeof options === "number" ? options : undefined, + camera, + samplingMode, + engine, + reusable, + textureType, + blockCompilation, + ...options, + }; + super(name, ThinPassPostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinPassCubePostProcess(name, engine, localOptions) : undefined, + ...localOptions, + }); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new PassCubePostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], PassCubePostProcess.prototype, "face", null); +AbstractEngine._RescalePostProcessFactory = (engine) => { + return new PassPostProcess("rescale", 1, null, 2, engine, false, 0); +}; + +/** + * Uses the GPU to create a copy texture rescaled at a given size + * @param texture Texture to copy from + * @param width defines the desired width + * @param height defines the desired height + * @param useBilinearMode defines if bilinear mode has to be used + * @returns the generated texture + */ +function CreateResizedCopy(texture, width, height, useBilinearMode = true) { + const scene = texture.getScene(); + const engine = scene.getEngine(); + const rtt = new RenderTargetTexture("resized" + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture.samplingMode, false); + rtt.wrapU = texture.wrapU; + rtt.wrapV = texture.wrapV; + rtt.uOffset = texture.uOffset; + rtt.vOffset = texture.vOffset; + rtt.uScale = texture.uScale; + rtt.vScale = texture.vScale; + rtt.uAng = texture.uAng; + rtt.vAng = texture.vAng; + rtt.wAng = texture.wAng; + rtt.coordinatesIndex = texture.coordinatesIndex; + rtt.level = texture.level; + rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel; + rtt._texture.isReady = false; + texture.wrapU = Texture.CLAMP_ADDRESSMODE; + texture.wrapV = Texture.CLAMP_ADDRESSMODE; + const passPostProcess = new PassPostProcess("pass", 1, null, useBilinearMode ? Texture.BILINEAR_SAMPLINGMODE : Texture.NEAREST_SAMPLINGMODE, engine, false, 0); + passPostProcess.externalTextureSamplerBinding = true; + passPostProcess.onEffectCreatedObservable.addOnce((e) => { + e.executeWhenCompiled(() => { + passPostProcess.onApply = function (effect) { + effect.setTexture("textureSampler", texture); + }; + const internalTexture = rtt.renderTarget; + if (internalTexture) { + scene.postProcessManager.directRender([passPostProcess], internalTexture); + engine.unBindFramebuffer(internalTexture); + rtt.disposeFramebufferObjects(); + passPostProcess.dispose(); + rtt.getInternalTexture().isReady = true; + } + }); + }); + return rtt; +} +/** + * Apply a post process to a texture + * @param postProcessName name of the fragment post process + * @param internalTexture the texture to encode + * @param scene the scene hosting the texture + * @param type type of the output texture. If not provided, use the one from internalTexture + * @param samplingMode sampling mode to use to sample the source texture. If not provided, use the one from internalTexture + * @param format format of the output texture. If not provided, use the one from internalTexture + * @param width width of the output texture. If not provided, use the one from internalTexture + * @param height height of the output texture. If not provided, use the one from internalTexture + * @returns a promise with the internalTexture having its texture replaced by the result of the processing + */ +function ApplyPostProcess(postProcessName, internalTexture, scene, type, samplingMode, format, width, height) { + // Gets everything ready. + const engine = internalTexture.getEngine(); + internalTexture.isReady = false; + samplingMode = samplingMode ?? internalTexture.samplingMode; + type = type ?? internalTexture.type; + format = format ?? internalTexture.format; + width = width ?? internalTexture.width; + height = height ?? internalTexture.height; + if (type === -1) { + type = 0; + } + return new Promise((resolve) => { + // Create the post process + const postProcess = new PostProcess("postprocess", postProcessName, null, null, 1, null, samplingMode, engine, false, undefined, type, undefined, null, false, format); + postProcess.externalTextureSamplerBinding = true; + // Hold the output of the decoding. + const encodedTexture = engine.createRenderTargetTexture({ width: width, height: height }, { + generateDepthBuffer: false, + generateMipMaps: false, + generateStencilBuffer: false, + samplingMode, + type, + format, + }); + postProcess.onEffectCreatedObservable.addOnce((e) => { + e.executeWhenCompiled(() => { + // PP Render Pass + postProcess.onApply = (effect) => { + effect._bindTexture("textureSampler", internalTexture); + effect.setFloat2("scale", 1, 1); + }; + scene.postProcessManager.directRender([postProcess], encodedTexture, true); + // Cleanup + engine.restoreDefaultFramebuffer(); + engine._releaseTexture(internalTexture); + if (postProcess) { + postProcess.dispose(); + } + // Internal Swap + encodedTexture._swapAndDie(internalTexture); + // Ready to get rolling again. + internalTexture.type = type; + internalTexture.format = 5; + internalTexture.isReady = true; + resolve(internalTexture); + }); + }); + }); +} +// ref: http://stackoverflow.com/questions/32633585/how-do-you-convert-to-half-floats-in-javascript +let floatView; +let int32View; +/** + * Converts a number to half float + * @param value number to convert + * @returns converted number + */ +function ToHalfFloat$1(value) { + if (!floatView) { + floatView = new Float32Array(1); + int32View = new Int32Array(floatView.buffer); + } + floatView[0] = value; + const x = int32View[0]; + let bits = (x >> 16) & 0x8000; /* Get the sign */ + let m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */ + const e = (x >> 23) & 0xff; /* Using int is faster here */ + /* If zero, or denormal, or exponent underflows too much for a denormal + * half, return signed zero. */ + if (e < 103) { + return bits; + } + /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */ + if (e > 142) { + bits |= 0x7c00; + /* If exponent was 0xff and one mantissa bit was set, it means NaN, + * not Inf, so make sure we set one mantissa bit too. */ + bits |= (e == 255 ? 0 : 1) && x & 0x007fffff; + return bits; + } + /* If exponent underflows but not too much, return a denormal */ + if (e < 113) { + m |= 0x0800; + /* Extra rounding may overflow and set mantissa to 0 and exponent + * to 1, which is OK. */ + bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1); + return bits; + } + bits |= ((e - 112) << 10) | (m >> 1); + bits += m & 1; + return bits; +} +/** + * Converts a half float to a number + * @param value half float to convert + * @returns converted half float + */ +function FromHalfFloat(value) { + const s = (value & 0x8000) >> 15; + const e = (value & 0x7c00) >> 10; + const f = value & 0x03ff; + if (e === 0) { + return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10)); + } + else if (e == 0x1f) { + return f ? NaN : (s ? -1 : 1) * Infinity; + } + return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + f / Math.pow(2, 10)); +} +const ProcessAsync = async (texture, width, height, face, lod) => { + const scene = texture.getScene(); + const engine = scene.getEngine(); + if (!engine.isWebGPU) { + if (texture.isCube) { + await Promise.resolve().then(() => lodCube_fragment$1); + } + else { + await Promise.resolve().then(() => lod_fragment$1); + } + } + else { + if (texture.isCube) { + await Promise.resolve().then(() => lodCube_fragment); + } + else { + await Promise.resolve().then(() => lod_fragment); + } + } + let lodPostProcess; + if (!texture.isCube) { + lodPostProcess = new PostProcess("lod", "lod", { + uniforms: ["lod", "gamma"], + samplingMode: Texture.NEAREST_NEAREST_MIPNEAREST, + engine, + shaderLanguage: engine.isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, + }); + } + else { + const faceDefines = ["#define POSITIVEX", "#define NEGATIVEX", "#define POSITIVEY", "#define NEGATIVEY", "#define POSITIVEZ", "#define NEGATIVEZ"]; + lodPostProcess = new PostProcess("lodCube", "lodCube", { + uniforms: ["lod", "gamma"], + samplingMode: Texture.NEAREST_NEAREST_MIPNEAREST, + engine, + defines: faceDefines[face], + shaderLanguage: engine.isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, + }); + } + await new Promise((resolve) => { + lodPostProcess.onEffectCreatedObservable.addOnce((e) => { + e.executeWhenCompiled(() => { + resolve(0); + }); + }); + }); + const rtt = new RenderTargetTexture("temp", { width: width, height: height }, scene, false); + lodPostProcess.onApply = function (effect) { + effect.setTexture("textureSampler", texture); + effect.setFloat("lod", lod); + effect.setInt("gamma", texture.gammaSpace ? 1 : 0); + }; + const internalTexture = texture.getInternalTexture(); + try { + if (rtt.renderTarget && internalTexture) { + const samplingMode = internalTexture.samplingMode; + if (lod !== 0) { + texture.updateSamplingMode(Texture.NEAREST_NEAREST_MIPNEAREST); + } + else { + texture.updateSamplingMode(Texture.NEAREST_NEAREST); + } + scene.postProcessManager.directRender([lodPostProcess], rtt.renderTarget, true); + texture.updateSamplingMode(samplingMode); + //Reading datas from WebGL + const bufferView = await engine.readPixels(0, 0, width, height); + const data = new Uint8Array(bufferView.buffer, 0, bufferView.byteLength); + // Unbind + engine.unBindFramebuffer(rtt.renderTarget); + return data; + } + else { + throw Error("Render to texture failed."); + } + } + finally { + rtt.dispose(); + lodPostProcess.dispose(); + } +}; +/** + * Gets the data of the specified texture by rendering it to an intermediate RGBA texture and retrieving the bytes from it. + * This is convienent to get 8-bit RGBA values for a texture in a GPU compressed format. + * @param texture the source texture + * @param width the width of the result, which does not have to match the source texture width + * @param height the height of the result, which does not have to match the source texture height + * @param face if the texture has multiple faces, the face index to use for the source + * @param lod if the texture has multiple LODs, the lod index to use for the source + * @returns the 8-bit texture data + */ +async function GetTextureDataAsync(texture, width, height, face = 0, lod = 0) { + if (!texture.isReady() && texture._texture) { + await new Promise((resolve, reject) => { + if (texture._texture === null) { + reject(0); + return; + } + texture._texture.onLoadedObservable.addOnce(() => { + resolve(0); + }); + }); + } + return await ProcessAsync(texture, width, height, face, lod); +} +/** + * Class used to host texture specific utilities + */ +const TextureTools = { + /** + * Uses the GPU to create a copy texture rescaled at a given size + * @param texture Texture to copy from + * @param width defines the desired width + * @param height defines the desired height + * @param useBilinearMode defines if bilinear mode has to be used + * @returns the generated texture + */ + CreateResizedCopy, + /** + * Apply a post process to a texture + * @param postProcessName name of the fragment post process + * @param internalTexture the texture to encode + * @param scene the scene hosting the texture + * @param type type of the output texture. If not provided, use the one from internalTexture + * @param samplingMode sampling mode to use to sample the source texture. If not provided, use the one from internalTexture + * @param format format of the output texture. If not provided, use the one from internalTexture + * @returns a promise with the internalTexture having its texture replaced by the result of the processing + */ + ApplyPostProcess, + /** + * Converts a number to half float + * @param value number to convert + * @returns converted number + */ + ToHalfFloat: ToHalfFloat$1, + /** + * Converts a half float to a number + * @param value half float to convert + * @returns converted half float + */ + FromHalfFloat, + /** + * Gets the data of the specified texture by rendering it to an intermediate RGBA texture and retrieving the bytes from it. + * This is convienent to get 8-bit RGBA values for a texture in a GPU compressed format. + * @param texture the source texture + * @param width the width of the result, which does not have to match the source texture width + * @param height the height of the result, which does not have to match the source texture height + * @param face if the texture has multiple faces, the face index to use for the source + * @param channels a filter for which of the RGBA channels to return in the result + * @param lod if the texture has multiple LODs, the lod index to use for the source + * @returns the 8-bit texture data + */ + GetTextureDataAsync, +}; + +/** + * Class used to host RGBD texture specific utilities + */ +class RGBDTextureTools { + /** + * Expand the RGBD Texture from RGBD to Half Float if possible. + * @param texture the texture to expand. + */ + static ExpandRGBDTexture(texture) { + const internalTexture = texture._texture; + if (!internalTexture || !texture.isRGBD) { + return; + } + // Gets everything ready. + const engine = internalTexture.getEngine(); + const caps = engine.getCaps(); + const isReady = internalTexture.isReady; + let expandTexture = false; + // If half float available we can uncompress the texture + if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { + expandTexture = true; + internalTexture.type = 2; + } + // If full float available we can uncompress the texture + else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { + expandTexture = true; + internalTexture.type = 1; + } + if (expandTexture) { + // Do not use during decode. + internalTexture.isReady = false; + internalTexture._isRGBD = false; + internalTexture.invertY = false; + } + const expandRGBDTexture = async () => { + const isWebGPU = engine.isWebGPU; + const shaderLanguage = isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */; + internalTexture.isReady = false; + if (isWebGPU) { + await Promise.resolve().then(() => rgbdDecode_fragment); + } + else { + await Promise.resolve().then(() => rgbdDecode_fragment$1); + } + // Expand the texture if possible + // Simply run through the decode PP. + const rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, 3, engine, false, undefined, internalTexture.type, undefined, null, false, undefined, shaderLanguage); + rgbdPostProcess.externalTextureSamplerBinding = true; + // Hold the output of the decoding. + const expandedTexture = engine.createRenderTargetTexture(internalTexture.width, { + generateDepthBuffer: false, + generateMipMaps: false, + generateStencilBuffer: false, + samplingMode: internalTexture.samplingMode, + type: internalTexture.type, + format: 5, + }); + rgbdPostProcess.onEffectCreatedObservable.addOnce((e) => { + e.executeWhenCompiled(() => { + // PP Render Pass + rgbdPostProcess.onApply = (effect) => { + effect._bindTexture("textureSampler", internalTexture); + effect.setFloat2("scale", 1, 1); + }; + texture.getScene().postProcessManager.directRender([rgbdPostProcess], expandedTexture, true); + // Cleanup + engine.restoreDefaultFramebuffer(); + engine._releaseTexture(internalTexture); + if (rgbdPostProcess) { + rgbdPostProcess.dispose(); + } + // Internal Swap + expandedTexture._swapAndDie(internalTexture); + // Ready to get rolling again. + internalTexture.isReady = true; + }); + }); + }; + if (expandTexture) { + if (isReady) { + expandRGBDTexture(); + } + else { + texture.onLoadObservable.addOnce(expandRGBDTexture); + } + } + } + /** + * Encode the texture to RGBD if possible. + * @param internalTexture the texture to encode + * @param scene the scene hosting the texture + * @param outputTextureType type of the texture in which the encoding is performed + * @returns a promise with the internalTexture having its texture replaced by the result of the processing + */ + static async EncodeTextureToRGBD(internalTexture, scene, outputTextureType = 0) { + if (!scene.getEngine().isWebGPU) { + await Promise.resolve().then(() => rgbdEncode_fragment$1); + } + else { + await Promise.resolve().then(() => rgbdEncode_fragment); + } + return ApplyPostProcess("rgbdEncode", internalTexture, scene, outputTextureType, 1, 5); + } +} + +// eslint-disable-next-line @typescript-eslint/naming-convention +const _environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg=="; +let _instanceNumber = 0; +/** + * Gets a default environment BRDF for MS-BRDF Height Correlated BRDF + * @param scene defines the hosting scene + * @returns the environment BRDF texture + */ +const GetEnvironmentBRDFTexture = (scene) => { + if (!scene.environmentBRDFTexture) { + // Forces Delayed Texture Loading to prevent undefined error whilst setting RGBD values. + const useDelayedTextureLoading = scene.useDelayedTextureLoading; + scene.useDelayedTextureLoading = false; + const previousState = scene._blockEntityCollection; + scene._blockEntityCollection = false; + const texture = Texture.CreateFromBase64String(_environmentBRDFBase64Texture, "EnvironmentBRDFTexture" + _instanceNumber++, scene, true, false, Texture.BILINEAR_SAMPLINGMODE); + scene._blockEntityCollection = previousState; + // BRDF Texture should not be cached here due to pre processing and redundant scene caches. + const texturesCache = scene.getEngine().getLoadedTexturesCache(); + const index = texturesCache.indexOf(texture.getInternalTexture()); + if (index !== -1) { + texturesCache.splice(index, 1); + } + texture.isRGBD = true; + texture.wrapU = Texture.CLAMP_ADDRESSMODE; + texture.wrapV = Texture.CLAMP_ADDRESSMODE; + scene.environmentBRDFTexture = texture; + scene.useDelayedTextureLoading = useDelayedTextureLoading; + RGBDTextureTools.ExpandRGBDTexture(texture); + const observer = scene.getEngine().onContextRestoredObservable.add(() => { + texture.isRGBD = true; + /** + * Using scene.onBeforeRenderObservable instead of Tools.SetImmediate to check the texture's state of readiness allows us to check before any rendering occurs. + * When a context restore occurs, it gives ExpandRGBDTexture the ability to reset the state to false, preventing the texture from being used in any rendering. + * In WebGPU, not doing so would generate an error because ExpandRGBDTexture performs a _swapAndDie on the texture, which causes WebGPU caches to fail if the texture has already been used for rendering. + * Only when ExpandRGBDTexture has finished its work, the texture is ready to be used again. + */ + const oo = scene.onBeforeRenderObservable.add(() => { + if (texture.isReady()) { + scene.onBeforeRenderObservable.remove(oo); + RGBDTextureTools.ExpandRGBDTexture(texture); + } + }); + }); + scene.onDisposeObservable.add(() => { + scene.getEngine().onContextRestoredObservable.remove(observer); + }); + } + return scene.environmentBRDFTexture; +}; + +/** + * @internal + */ +class MaterialBRDFDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.BRDF_V_HEIGHT_CORRELATED = false; + this.MS_BRDF_ENERGY_CONSERVATION = false; + this.SPHERICAL_HARMONICS = false; + this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = false; + this.MIX_IBL_RADIANCE_WITH_IRRADIANCE = true; + } +} +/** + * Plugin that implements the BRDF component of the PBR material + */ +class PBRBRDFConfiguration extends MaterialPluginBase { + /** @internal */ + _markAllSubMeshesAsMiscDirty() { + this._internalMarkAllSubMeshesAsMiscDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + constructor(material, addToPluginList = true) { + super(material, "PBRBRDF", 90, new MaterialBRDFDefines(), addToPluginList); + this._useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION; + /** + * Defines if the material uses energy conservation. + */ + this.useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION; + this._useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED; + /** + * LEGACY Mode set to false + * Defines if the material uses height smith correlated visibility term. + * If you intent to not use our default BRDF, you need to load a separate BRDF Texture for the PBR + * You can either load https://assets.babylonjs.com/environments/uncorrelatedBRDF.png + * or https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds to have more precision + * Not relying on height correlated will also disable energy conservation. + */ + this.useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED; + this._useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS; + /** + * LEGACY Mode set to false + * Defines if the material uses spherical harmonics vs spherical polynomials for the + * diffuse part of the IBL. + * The harmonics despite a tiny bigger cost has been proven to provide closer results + * to the ground truth. + */ + this.useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS; + this._useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION; + /** + * Defines if the material uses energy conservation, when the specular workflow is active. + * If activated, the albedo color is multiplied with (1. - maxChannel(specular color)). + * If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1. + * In the deactivated case, the material author has to ensure energy conservation, for a physically plausible rendering. + */ + this.useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION; + this._mixIblRadianceWithIrradiance = PBRBRDFConfiguration.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE; + /** + * Defines if IBL irradiance is used to augment rough radiance. + * If activated, irradiance is blended into the radiance contribution when the material is rough. + * This better approximates raytracing results for rough surfaces. + */ + this.mixIblRadianceWithIrradiance = PBRBRDFConfiguration.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE; + this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16]; + this._enable(true); + } + prepareDefines(defines) { + defines.BRDF_V_HEIGHT_CORRELATED = this._useSmithVisibilityHeightCorrelated; + defines.MS_BRDF_ENERGY_CONSERVATION = this._useEnergyConservation && this._useSmithVisibilityHeightCorrelated; + defines.SPHERICAL_HARMONICS = this._useSphericalHarmonics; + defines.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = this._useSpecularGlossinessInputEnergyConservation; + defines.MIX_IBL_RADIANCE_WITH_IRRADIANCE = this._mixIblRadianceWithIrradiance; + } + getClassName() { + return "PBRBRDFConfiguration"; + } +} +/** + * Default value used for the energy conservation. + * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture. + */ +PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION = true; +/** + * Default value used for the Smith Visibility Height Correlated mode. + * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture. + */ +PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = true; +/** + * Default value used for the IBL diffuse part. + * This can help switching back to the polynomials mode globally which is a tiny bit + * less GPU intensive at the drawback of a lower quality. + */ +PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS = true; +/** + * Default value used for activating energy conservation for the specular workflow. + * If activated, the albedo color is multiplied with (1. - maxChannel(specular color)). + * If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1. + */ +PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION = true; +/** + * Default value for whether IBL irradiance is used to augment rough radiance. + * If activated, irradiance is blended into the radiance contribution when the material is rough. + * This better approximates raytracing results for rough surfaces. + */ +PBRBRDFConfiguration.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE = true; +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsMiscDirty") +], PBRBRDFConfiguration.prototype, "useEnergyConservation", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsMiscDirty") +], PBRBRDFConfiguration.prototype, "useSmithVisibilityHeightCorrelated", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsMiscDirty") +], PBRBRDFConfiguration.prototype, "useSphericalHarmonics", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsMiscDirty") +], PBRBRDFConfiguration.prototype, "useSpecularGlossinessInputEnergyConservation", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsMiscDirty") +], PBRBRDFConfiguration.prototype, "mixIblRadianceWithIrradiance", void 0); + +class FileFaceOrientation { + constructor(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) { + this.name = name; + this.worldAxisForNormal = worldAxisForNormal; + this.worldAxisForFileX = worldAxisForFileX; + this.worldAxisForFileY = worldAxisForFileY; + } +} +/** + * Helper class dealing with the extraction of spherical polynomial dataArray + * from a cube map. + */ +class CubeMapToSphericalPolynomialTools { + /** + * Converts a texture to the according Spherical Polynomial data. + * This extracts the first 3 orders only as they are the only one used in the lighting. + * + * @param texture The texture to extract the information from. + * @returns The Spherical Polynomial data. + */ + static ConvertCubeMapTextureToSphericalPolynomial(texture) { + if (!texture.isCube) { + // Only supports cube Textures currently. + return null; + } + texture.getScene()?.getEngine().flushFramebuffer(); + const size = texture.getSize().width; + const rightPromise = texture.readPixels(0, undefined, undefined, false); + const leftPromise = texture.readPixels(1, undefined, undefined, false); + let upPromise; + let downPromise; + if (texture.isRenderTarget) { + upPromise = texture.readPixels(3, undefined, undefined, false); + downPromise = texture.readPixels(2, undefined, undefined, false); + } + else { + upPromise = texture.readPixels(2, undefined, undefined, false); + downPromise = texture.readPixels(3, undefined, undefined, false); + } + const frontPromise = texture.readPixels(4, undefined, undefined, false); + const backPromise = texture.readPixels(5, undefined, undefined, false); + const gammaSpace = texture.gammaSpace; + // Always read as RGBA. + const format = 5; + let type = 0; + if (texture.textureType == 1 || texture.textureType == 2) { + type = 1; + } + return new Promise((resolve) => { + Promise.all([leftPromise, rightPromise, upPromise, downPromise, frontPromise, backPromise]).then(([left, right, up, down, front, back]) => { + const cubeInfo = { + size, + right, + left, + up, + down, + front, + back, + format, + type, + gammaSpace, + }; + resolve(this.ConvertCubeMapToSphericalPolynomial(cubeInfo)); + }); + }); + } + /** + * Compute the area on the unit sphere of the rectangle defined by (x,y) and the origin + * See https://www.rorydriscoll.com/2012/01/15/cubemap-texel-solid-angle/ + * @param x + * @param y + * @returns the area + */ + static _AreaElement(x, y) { + return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1)); + } + /** + * Converts a cubemap to the according Spherical Polynomial data. + * This extracts the first 3 orders only as they are the only one used in the lighting. + * + * @param cubeInfo The Cube map to extract the information from. + * @returns The Spherical Polynomial data. + */ + static ConvertCubeMapToSphericalPolynomial(cubeInfo) { + const sphericalHarmonics = new SphericalHarmonics(); + let totalSolidAngle = 0.0; + // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size. + const du = 2.0 / cubeInfo.size; + const dv = du; + const halfTexel = 0.5 * du; + // The (u,v) of the first texel is half a texel from the corner (-1,-1). + const minUV = halfTexel - 1.0; + for (let faceIndex = 0; faceIndex < 6; faceIndex++) { + const fileFace = this._FileFaces[faceIndex]; + const dataArray = cubeInfo[fileFace.name]; + let v = minUV; + // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH). + // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality. + // Because SP is still linear, so summation is fine in that basis. + const stride = cubeInfo.format === 5 ? 4 : 3; + for (let y = 0; y < cubeInfo.size; y++) { + let u = minUV; + for (let x = 0; x < cubeInfo.size; x++) { + // World direction (not normalised) + const worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal); + worldDirection.normalize(); + const deltaSolidAngle = this._AreaElement(u - halfTexel, v - halfTexel) - + this._AreaElement(u - halfTexel, v + halfTexel) - + this._AreaElement(u + halfTexel, v - halfTexel) + + this._AreaElement(u + halfTexel, v + halfTexel); + let r = dataArray[y * cubeInfo.size * stride + x * stride + 0]; + let g = dataArray[y * cubeInfo.size * stride + x * stride + 1]; + let b = dataArray[y * cubeInfo.size * stride + x * stride + 2]; + // Prevent NaN harmonics with extreme HDRI data. + if (isNaN(r)) { + r = 0; + } + if (isNaN(g)) { + g = 0; + } + if (isNaN(b)) { + b = 0; + } + // Handle Integer types. + if (cubeInfo.type === 0) { + r /= 255; + g /= 255; + b /= 255; + } + // Handle Gamma space textures. + if (cubeInfo.gammaSpace) { + r = Math.pow(Clamp(r), ToLinearSpace); + g = Math.pow(Clamp(g), ToLinearSpace); + b = Math.pow(Clamp(b), ToLinearSpace); + } + // Prevent to explode in case of really high dynamic ranges. + // sh 3 would not be enough to accurately represent it. + const max = this.MAX_HDRI_VALUE; + if (this.PRESERVE_CLAMPED_COLORS) { + const currentMax = Math.max(r, g, b); + if (currentMax > max) { + const factor = max / currentMax; + r *= factor; + g *= factor; + b *= factor; + } + } + else { + r = Clamp(r, 0, max); + g = Clamp(g, 0, max); + b = Clamp(b, 0, max); + } + const color = new Color3(r, g, b); + sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle); + totalSolidAngle += deltaSolidAngle; + u += du; + } + v += dv; + } + } + // Solid angle for entire sphere is 4*pi + const sphereSolidAngle = 4.0 * Math.PI; + // Adjust the solid angle to allow for how many faces we processed. + const facesProcessed = 6.0; + const expectedSolidAngle = (sphereSolidAngle * facesProcessed) / 6.0; + // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle. + // This is needed because the numerical integration over the cube uses a + // small angle approximation of solid angle for each texel (see deltaSolidAngle), + // and also to compensate for accumulative error due to float precision in the summation. + const correctionFactor = expectedSolidAngle / totalSolidAngle; + sphericalHarmonics.scaleInPlace(correctionFactor); + sphericalHarmonics.convertIncidentRadianceToIrradiance(); + sphericalHarmonics.convertIrradianceToLambertianRadiance(); + return SphericalPolynomial.FromHarmonics(sphericalHarmonics); + } +} +CubeMapToSphericalPolynomialTools._FileFaces = [ + new FileFaceOrientation("right", new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)), // +X east + new FileFaceOrientation("left", new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, -1, 0)), // -X west + new FileFaceOrientation("up", new Vector3(0, 1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, 1)), // +Y north + new FileFaceOrientation("down", new Vector3(0, -1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, -1)), // -Y south + new FileFaceOrientation("front", new Vector3(0, 0, 1), new Vector3(1, 0, 0), new Vector3(0, -1, 0)), // +Z top + new FileFaceOrientation("back", new Vector3(0, 0, -1), new Vector3(-1, 0, 0), new Vector3(0, -1, 0)), // -Z bottom +]; +/** @internal */ +CubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE = 4096; +/** @internal */ +CubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS = false; + +BaseTexture.prototype.forceSphericalPolynomialsRecompute = function () { + if (this._texture) { + this._texture._sphericalPolynomial = null; + this._texture._sphericalPolynomialPromise = null; + this._texture._sphericalPolynomialComputed = false; + } +}; +Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", { + get: function () { + if (this._texture) { + if (this._texture._sphericalPolynomial || this._texture._sphericalPolynomialComputed) { + return this._texture._sphericalPolynomial; + } + if (this._texture.isReady) { + if (!this._texture._sphericalPolynomialPromise) { + this._texture._sphericalPolynomialPromise = CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this); + if (this._texture._sphericalPolynomialPromise === null) { + this._texture._sphericalPolynomialComputed = true; + } + else { + this._texture._sphericalPolynomialPromise.then((sphericalPolynomial) => { + this._texture._sphericalPolynomial = sphericalPolynomial; + this._texture._sphericalPolynomialComputed = true; + }); + } + } + return null; + } + } + return null; + }, + set: function (value) { + if (this._texture) { + this._texture._sphericalPolynomial = value; + } + }, + enumerable: true, + configurable: true, +}); + +/** + * @internal + */ +class MaterialClearCoatDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.CLEARCOAT = false; + this.CLEARCOAT_DEFAULTIOR = false; + this.CLEARCOAT_TEXTURE = false; + this.CLEARCOAT_TEXTURE_ROUGHNESS = false; + this.CLEARCOAT_TEXTUREDIRECTUV = 0; + this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0; + this.CLEARCOAT_BUMP = false; + this.CLEARCOAT_BUMPDIRECTUV = 0; + this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false; + this.CLEARCOAT_REMAP_F0 = false; + this.CLEARCOAT_TINT = false; + this.CLEARCOAT_TINT_TEXTURE = false; + this.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0; + this.CLEARCOAT_TINT_GAMMATEXTURE = false; + } +} +/** + * Plugin that implements the clear coat component of the PBR material + */ +class PBRClearCoatConfiguration extends MaterialPluginBase { + /** @internal */ + _markAllSubMeshesAsTexturesDirty() { + this._enable(this._isEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + constructor(material, addToPluginList = true) { + super(material, "PBRClearCoat", 100, new MaterialClearCoatDefines(), addToPluginList); + this._isEnabled = false; + /** + * Defines if the clear coat is enabled in the material. + */ + this.isEnabled = false; + /** + * Defines the clear coat layer strength (between 0 and 1) it defaults to 1. + */ + this.intensity = 1; + /** + * Defines the clear coat layer roughness. + */ + this.roughness = 0; + this._indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction; + /** + * Defines the index of refraction of the clear coat. + * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence + * The default fits with a polyurethane material. + * Changing the default value is more performance intensive. + */ + this.indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction; + this._texture = null; + /** + * Stores the clear coat values in a texture (red channel is intensity and green channel is roughness) + * If useRoughnessFromMainTexture is false, the green channel of texture is not used and the green channel of textureRoughness is used instead + * if textureRoughness is not empty, else no texture roughness is used + */ + this.texture = null; + this._useRoughnessFromMainTexture = true; + /** + * Indicates that the green channel of the texture property will be used for roughness (default: true) + * If false, the green channel from textureRoughness is used for roughness + */ + this.useRoughnessFromMainTexture = true; + this._textureRoughness = null; + /** + * Stores the clear coat roughness in a texture (green channel) + * Not used if useRoughnessFromMainTexture is true + */ + this.textureRoughness = null; + this._remapF0OnInterfaceChange = true; + /** + * Defines if the F0 value should be remapped to account for the interface change in the material. + */ + this.remapF0OnInterfaceChange = true; + this._bumpTexture = null; + /** + * Define the clear coat specific bump texture. + */ + this.bumpTexture = null; + this._isTintEnabled = false; + /** + * Defines if the clear coat tint is enabled in the material. + */ + this.isTintEnabled = false; + /** + * Defines the clear coat tint of the material. + * This is only use if tint is enabled + */ + this.tintColor = Color3.White(); + /** + * Defines the distance at which the tint color should be found in the + * clear coat media. + * This is only use if tint is enabled + */ + this.tintColorAtDistance = 1; + /** + * Defines the clear coat layer thickness. + * This is only use if tint is enabled + */ + this.tintThickness = 1; + this._tintTexture = null; + /** + * Stores the clear tint values in a texture. + * rgb is tint + * a is a thickness factor + */ + this.tintTexture = null; + this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; + } + isReadyForSubMesh(defines, scene, engine) { + if (!this._isEnabled) { + return true; + } + const disableBumpMap = this._material._disableBumpMap; + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.ClearCoatTextureEnabled) { + if (!this._texture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) { + if (!this._textureRoughness.isReadyOrNotBlocking()) { + return false; + } + } + if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) { + // Bump texture cannot be not blocking. + if (!this._bumpTexture.isReady()) { + return false; + } + } + if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) { + if (!this._tintTexture.isReadyOrNotBlocking()) { + return false; + } + } + } + } + return true; + } + prepareDefinesBeforeAttributes(defines, scene) { + if (this._isEnabled) { + defines.CLEARCOAT = true; + defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture; + defines.CLEARCOAT_REMAP_F0 = this._remapF0OnInterfaceChange; + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.ClearCoatTextureEnabled) { + PrepareDefinesForMergedUV(this._texture, defines, "CLEARCOAT_TEXTURE"); + } + else { + defines.CLEARCOAT_TEXTURE = false; + } + if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) { + PrepareDefinesForMergedUV(this._textureRoughness, defines, "CLEARCOAT_TEXTURE_ROUGHNESS"); + } + else { + defines.CLEARCOAT_TEXTURE_ROUGHNESS = false; + } + if (this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled) { + PrepareDefinesForMergedUV(this._bumpTexture, defines, "CLEARCOAT_BUMP"); + } + else { + defines.CLEARCOAT_BUMP = false; + } + defines.CLEARCOAT_DEFAULTIOR = this._indexOfRefraction === PBRClearCoatConfiguration._DefaultIndexOfRefraction; + if (this._isTintEnabled) { + defines.CLEARCOAT_TINT = true; + if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) { + PrepareDefinesForMergedUV(this._tintTexture, defines, "CLEARCOAT_TINT_TEXTURE"); + defines.CLEARCOAT_TINT_GAMMATEXTURE = this._tintTexture.gammaSpace; + } + else { + defines.CLEARCOAT_TINT_TEXTURE = false; + } + } + else { + defines.CLEARCOAT_TINT = false; + defines.CLEARCOAT_TINT_TEXTURE = false; + } + } + } + } + else { + defines.CLEARCOAT = false; + defines.CLEARCOAT_TEXTURE = false; + defines.CLEARCOAT_TEXTURE_ROUGHNESS = false; + defines.CLEARCOAT_BUMP = false; + defines.CLEARCOAT_TINT = false; + defines.CLEARCOAT_TINT_TEXTURE = false; + defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false; + defines.CLEARCOAT_DEFAULTIOR = false; + defines.CLEARCOAT_TEXTUREDIRECTUV = 0; + defines.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0; + defines.CLEARCOAT_BUMPDIRECTUV = 0; + defines.CLEARCOAT_REMAP_F0 = false; + defines.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0; + defines.CLEARCOAT_TINT_GAMMATEXTURE = false; + } + } + bindForSubMesh(uniformBuffer, scene, engine, subMesh) { + if (!this._isEnabled) { + return; + } + const defines = subMesh.materialDefines; + const isFrozen = this._material.isFrozen; + const disableBumpMap = this._material._disableBumpMap; + const invertNormalMapX = this._material._invertNormalMapX; + const invertNormalMapY = this._material._invertNormalMapY; + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + if ((this._texture || this._textureRoughness) && MaterialFlags.ClearCoatTextureEnabled) { + uniformBuffer.updateFloat4("vClearCoatInfos", this._texture?.coordinatesIndex ?? 0, this._texture?.level ?? 0, this._textureRoughness?.coordinatesIndex ?? 0, this._textureRoughness?.level ?? 0); + if (this._texture) { + BindTextureMatrix(this._texture, uniformBuffer, "clearCoat"); + } + if (this._textureRoughness && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) { + BindTextureMatrix(this._textureRoughness, uniformBuffer, "clearCoatRoughness"); + } + } + if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.ClearCoatTextureEnabled && !disableBumpMap) { + uniformBuffer.updateFloat2("vClearCoatBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level); + BindTextureMatrix(this._bumpTexture, uniformBuffer, "clearCoatBump"); + if (scene._mirroredCameraPosition) { + uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? 1.0 : -1, invertNormalMapY ? 1.0 : -1); + } + else { + uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? -1 : 1.0, invertNormalMapY ? -1 : 1.0); + } + } + if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) { + uniformBuffer.updateFloat2("vClearCoatTintInfos", this._tintTexture.coordinatesIndex, this._tintTexture.level); + BindTextureMatrix(this._tintTexture, uniformBuffer, "clearCoatTint"); + } + // Clear Coat General params + uniformBuffer.updateFloat2("vClearCoatParams", this.intensity, this.roughness); + // Clear Coat Refraction params + const a = 1 - this._indexOfRefraction; + const b = 1 + this._indexOfRefraction; + const f0 = Math.pow(-a / b, 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1. + const eta = 1 / this._indexOfRefraction; + uniformBuffer.updateFloat4("vClearCoatRefractionParams", f0, eta, a, b); + if (this._isTintEnabled) { + uniformBuffer.updateFloat4("vClearCoatTintParams", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintThickness)); + uniformBuffer.updateFloat("clearCoatColorAtDistance", Math.max(0.00001, this.tintColorAtDistance)); + } + } + // Textures + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.ClearCoatTextureEnabled) { + uniformBuffer.setTexture("clearCoatSampler", this._texture); + } + if (this._textureRoughness && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.ClearCoatTextureEnabled) { + uniformBuffer.setTexture("clearCoatRoughnessSampler", this._textureRoughness); + } + if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) { + uniformBuffer.setTexture("clearCoatBumpSampler", this._bumpTexture); + } + if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) { + uniformBuffer.setTexture("clearCoatTintSampler", this._tintTexture); + } + } + } + hasTexture(texture) { + if (this._texture === texture) { + return true; + } + if (this._textureRoughness === texture) { + return true; + } + if (this._bumpTexture === texture) { + return true; + } + if (this._tintTexture === texture) { + return true; + } + return false; + } + getActiveTextures(activeTextures) { + if (this._texture) { + activeTextures.push(this._texture); + } + if (this._textureRoughness) { + activeTextures.push(this._textureRoughness); + } + if (this._bumpTexture) { + activeTextures.push(this._bumpTexture); + } + if (this._tintTexture) { + activeTextures.push(this._tintTexture); + } + } + getAnimatables(animatables) { + if (this._texture && this._texture.animations && this._texture.animations.length > 0) { + animatables.push(this._texture); + } + if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) { + animatables.push(this._textureRoughness); + } + if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { + animatables.push(this._bumpTexture); + } + if (this._tintTexture && this._tintTexture.animations && this._tintTexture.animations.length > 0) { + animatables.push(this._tintTexture); + } + } + dispose(forceDisposeTextures) { + if (forceDisposeTextures) { + this._texture?.dispose(); + this._textureRoughness?.dispose(); + this._bumpTexture?.dispose(); + this._tintTexture?.dispose(); + } + } + getClassName() { + return "PBRClearCoatConfiguration"; + } + addFallbacks(defines, fallbacks, currentRank) { + if (defines.CLEARCOAT_BUMP) { + fallbacks.addFallback(currentRank++, "CLEARCOAT_BUMP"); + } + if (defines.CLEARCOAT_TINT) { + fallbacks.addFallback(currentRank++, "CLEARCOAT_TINT"); + } + if (defines.CLEARCOAT) { + fallbacks.addFallback(currentRank++, "CLEARCOAT"); + } + return currentRank; + } + getSamplers(samplers) { + samplers.push("clearCoatSampler", "clearCoatRoughnessSampler", "clearCoatBumpSampler", "clearCoatTintSampler"); + } + getUniforms() { + return { + ubo: [ + { name: "vClearCoatParams", size: 2, type: "vec2" }, + { name: "vClearCoatRefractionParams", size: 4, type: "vec4" }, + { name: "vClearCoatInfos", size: 4, type: "vec4" }, + { name: "clearCoatMatrix", size: 16, type: "mat4" }, + { name: "clearCoatRoughnessMatrix", size: 16, type: "mat4" }, + { name: "vClearCoatBumpInfos", size: 2, type: "vec2" }, + { name: "vClearCoatTangentSpaceParams", size: 2, type: "vec2" }, + { name: "clearCoatBumpMatrix", size: 16, type: "mat4" }, + { name: "vClearCoatTintParams", size: 4, type: "vec4" }, + { name: "clearCoatColorAtDistance", size: 1, type: "float" }, + { name: "vClearCoatTintInfos", size: 2, type: "vec2" }, + { name: "clearCoatTintMatrix", size: 16, type: "mat4" }, + ], + }; + } +} +/** + * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence + * The default fits with a polyurethane material. + * @internal + */ +PBRClearCoatConfiguration._DefaultIndexOfRefraction = 1.5; +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRClearCoatConfiguration.prototype, "isEnabled", void 0); +__decorate([ + serialize() +], PBRClearCoatConfiguration.prototype, "intensity", void 0); +__decorate([ + serialize() +], PBRClearCoatConfiguration.prototype, "roughness", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRClearCoatConfiguration.prototype, "indexOfRefraction", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRClearCoatConfiguration.prototype, "texture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRClearCoatConfiguration.prototype, "useRoughnessFromMainTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRClearCoatConfiguration.prototype, "textureRoughness", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRClearCoatConfiguration.prototype, "remapF0OnInterfaceChange", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRClearCoatConfiguration.prototype, "bumpTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRClearCoatConfiguration.prototype, "isTintEnabled", void 0); +__decorate([ + serializeAsColor3() +], PBRClearCoatConfiguration.prototype, "tintColor", void 0); +__decorate([ + serialize() +], PBRClearCoatConfiguration.prototype, "tintColorAtDistance", void 0); +__decorate([ + serialize() +], PBRClearCoatConfiguration.prototype, "tintThickness", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRClearCoatConfiguration.prototype, "tintTexture", void 0); + +/** + * @internal + */ +class MaterialIridescenceDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.IRIDESCENCE = false; + this.IRIDESCENCE_TEXTURE = false; + this.IRIDESCENCE_TEXTUREDIRECTUV = 0; + this.IRIDESCENCE_THICKNESS_TEXTURE = false; + this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0; + } +} +/** + * Plugin that implements the iridescence (thin film) component of the PBR material + */ +class PBRIridescenceConfiguration extends MaterialPluginBase { + /** @internal */ + _markAllSubMeshesAsTexturesDirty() { + this._enable(this._isEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + constructor(material, addToPluginList = true) { + super(material, "PBRIridescence", 110, new MaterialIridescenceDefines(), addToPluginList); + this._isEnabled = false; + /** + * Defines if the iridescence is enabled in the material. + */ + this.isEnabled = false; + /** + * Defines the iridescence layer strength (between 0 and 1) it defaults to 1. + */ + this.intensity = 1; + /** + * Defines the minimum thickness of the thin-film layer given in nanometers (nm). + */ + this.minimumThickness = PBRIridescenceConfiguration._DefaultMinimumThickness; + /** + * Defines the maximum thickness of the thin-film layer given in nanometers (nm). This will be the thickness used if not thickness texture has been set. + */ + this.maximumThickness = PBRIridescenceConfiguration._DefaultMaximumThickness; + /** + * Defines the maximum thickness of the thin-film layer given in nanometers (nm). + */ + this.indexOfRefraction = PBRIridescenceConfiguration._DefaultIndexOfRefraction; + this._texture = null; + /** + * Stores the iridescence intensity in a texture (red channel) + */ + this.texture = null; + this._thicknessTexture = null; + /** + * Stores the iridescence thickness in a texture (green channel) + */ + this.thicknessTexture = null; + this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; + } + isReadyForSubMesh(defines, scene) { + if (!this._isEnabled) { + return true; + } + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.IridescenceTextureEnabled) { + if (!this._texture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) { + if (!this._thicknessTexture.isReadyOrNotBlocking()) { + return false; + } + } + } + } + return true; + } + prepareDefinesBeforeAttributes(defines, scene) { + if (this._isEnabled) { + defines.IRIDESCENCE = true; + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.IridescenceTextureEnabled) { + PrepareDefinesForMergedUV(this._texture, defines, "IRIDESCENCE_TEXTURE"); + } + else { + defines.IRIDESCENCE_TEXTURE = false; + } + if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) { + PrepareDefinesForMergedUV(this._thicknessTexture, defines, "IRIDESCENCE_THICKNESS_TEXTURE"); + } + else { + defines.IRIDESCENCE_THICKNESS_TEXTURE = false; + } + } + } + } + else { + defines.IRIDESCENCE = false; + defines.IRIDESCENCE_TEXTURE = false; + defines.IRIDESCENCE_THICKNESS_TEXTURE = false; + defines.IRIDESCENCE_TEXTUREDIRECTUV = 0; + defines.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0; + } + } + bindForSubMesh(uniformBuffer, scene) { + if (!this._isEnabled) { + return; + } + const isFrozen = this._material.isFrozen; + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + if ((this._texture || this._thicknessTexture) && MaterialFlags.IridescenceTextureEnabled) { + uniformBuffer.updateFloat4("vIridescenceInfos", this._texture?.coordinatesIndex ?? 0, this._texture?.level ?? 0, this._thicknessTexture?.coordinatesIndex ?? 0, this._thicknessTexture?.level ?? 0); + if (this._texture) { + BindTextureMatrix(this._texture, uniformBuffer, "iridescence"); + } + if (this._thicknessTexture) { + BindTextureMatrix(this._thicknessTexture, uniformBuffer, "iridescenceThickness"); + } + } + // Clear Coat General params + uniformBuffer.updateFloat4("vIridescenceParams", this.intensity, this.indexOfRefraction, this.minimumThickness, this.maximumThickness); + } + // Textures + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.IridescenceTextureEnabled) { + uniformBuffer.setTexture("iridescenceSampler", this._texture); + } + if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) { + uniformBuffer.setTexture("iridescenceThicknessSampler", this._thicknessTexture); + } + } + } + hasTexture(texture) { + if (this._texture === texture) { + return true; + } + if (this._thicknessTexture === texture) { + return true; + } + return false; + } + getActiveTextures(activeTextures) { + if (this._texture) { + activeTextures.push(this._texture); + } + if (this._thicknessTexture) { + activeTextures.push(this._thicknessTexture); + } + } + getAnimatables(animatables) { + if (this._texture && this._texture.animations && this._texture.animations.length > 0) { + animatables.push(this._texture); + } + if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) { + animatables.push(this._thicknessTexture); + } + } + dispose(forceDisposeTextures) { + if (forceDisposeTextures) { + this._texture?.dispose(); + this._thicknessTexture?.dispose(); + } + } + getClassName() { + return "PBRIridescenceConfiguration"; + } + addFallbacks(defines, fallbacks, currentRank) { + if (defines.IRIDESCENCE) { + fallbacks.addFallback(currentRank++, "IRIDESCENCE"); + } + return currentRank; + } + getSamplers(samplers) { + samplers.push("iridescenceSampler", "iridescenceThicknessSampler"); + } + getUniforms() { + return { + ubo: [ + { name: "vIridescenceParams", size: 4, type: "vec4" }, + { name: "vIridescenceInfos", size: 4, type: "vec4" }, + { name: "iridescenceMatrix", size: 16, type: "mat4" }, + { name: "iridescenceThicknessMatrix", size: 16, type: "mat4" }, + ], + }; + } +} +/** + * The default minimum thickness of the thin-film layer given in nanometers (nm). + * Defaults to 100 nm. + * @internal + */ +PBRIridescenceConfiguration._DefaultMinimumThickness = 100; +/** + * The default maximum thickness of the thin-film layer given in nanometers (nm). + * Defaults to 400 nm. + * @internal + */ +PBRIridescenceConfiguration._DefaultMaximumThickness = 400; +/** + * The default index of refraction of the thin-film layer. + * Defaults to 1.3 + * @internal + */ +PBRIridescenceConfiguration._DefaultIndexOfRefraction = 1.3; +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRIridescenceConfiguration.prototype, "isEnabled", void 0); +__decorate([ + serialize() +], PBRIridescenceConfiguration.prototype, "intensity", void 0); +__decorate([ + serialize() +], PBRIridescenceConfiguration.prototype, "minimumThickness", void 0); +__decorate([ + serialize() +], PBRIridescenceConfiguration.prototype, "maximumThickness", void 0); +__decorate([ + serialize() +], PBRIridescenceConfiguration.prototype, "indexOfRefraction", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRIridescenceConfiguration.prototype, "texture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRIridescenceConfiguration.prototype, "thicknessTexture", void 0); + +/** + * @internal + */ +class MaterialAnisotropicDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.ANISOTROPIC = false; + this.ANISOTROPIC_TEXTURE = false; + this.ANISOTROPIC_TEXTUREDIRECTUV = 0; + this.ANISOTROPIC_LEGACY = false; + this.MAINUV1 = false; + } +} +/** + * Plugin that implements the anisotropic component of the PBR material + */ +class PBRAnisotropicConfiguration extends MaterialPluginBase { + /** + * Sets the anisotropy direction as an angle. + */ + set angle(value) { + this.direction.x = Math.cos(value); + this.direction.y = Math.sin(value); + } + /** + * Gets the anisotropy angle value in radians. + * @returns the anisotropy angle value in radians. + */ + get angle() { + return Math.atan2(this.direction.y, this.direction.x); + } + /** @internal */ + _markAllSubMeshesAsTexturesDirty() { + this._enable(this._isEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + } + /** @internal */ + _markAllSubMeshesAsMiscDirty() { + this._enable(this._isEnabled); + this._internalMarkAllSubMeshesAsMiscDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + constructor(material, addToPluginList = true) { + super(material, "PBRAnisotropic", 110, new MaterialAnisotropicDefines(), addToPluginList); + this._isEnabled = false; + /** + * Defines if the anisotropy is enabled in the material. + */ + this.isEnabled = false; + /** + * Defines the anisotropy strength (between 0 and 1) it defaults to 1. + */ + this.intensity = 1; + /** + * Defines if the effect is along the tangents, bitangents or in between. + * By default, the effect is "stretching" the highlights along the tangents. + */ + this.direction = new Vector2(1, 0); + this._texture = null; + /** + * Stores the anisotropy values in a texture. + * rg is direction (like normal from -1 to 1) + * b is a intensity + */ + this.texture = null; + this._legacy = false; + /** + * Defines if the anisotropy is in legacy mode for backwards compatibility before 6.4.0. + */ + this.legacy = false; + this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; + this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16]; + } + isReadyForSubMesh(defines, scene) { + if (!this._isEnabled) { + return true; + } + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.AnisotropicTextureEnabled) { + if (!this._texture.isReadyOrNotBlocking()) { + return false; + } + } + } + } + return true; + } + prepareDefinesBeforeAttributes(defines, scene, mesh) { + if (this._isEnabled) { + defines.ANISOTROPIC = this._isEnabled; + if (this._isEnabled && !mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) { + defines._needUVs = true; + defines.MAINUV1 = true; + } + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.AnisotropicTextureEnabled) { + PrepareDefinesForMergedUV(this._texture, defines, "ANISOTROPIC_TEXTURE"); + } + else { + defines.ANISOTROPIC_TEXTURE = false; + } + } + } + if (defines._areMiscDirty) { + defines.ANISOTROPIC_LEGACY = this._legacy; + } + } + else { + defines.ANISOTROPIC = false; + defines.ANISOTROPIC_TEXTURE = false; + defines.ANISOTROPIC_TEXTUREDIRECTUV = 0; + defines.ANISOTROPIC_LEGACY = false; + } + } + bindForSubMesh(uniformBuffer, scene) { + if (!this._isEnabled) { + return; + } + const isFrozen = this._material.isFrozen; + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + if (this._texture && MaterialFlags.AnisotropicTextureEnabled) { + uniformBuffer.updateFloat2("vAnisotropyInfos", this._texture.coordinatesIndex, this._texture.level); + BindTextureMatrix(this._texture, uniformBuffer, "anisotropy"); + } + // Anisotropy + uniformBuffer.updateFloat3("vAnisotropy", this.direction.x, this.direction.y, this.intensity); + } + // Textures + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.AnisotropicTextureEnabled) { + uniformBuffer.setTexture("anisotropySampler", this._texture); + } + } + } + hasTexture(texture) { + if (this._texture === texture) { + return true; + } + return false; + } + getActiveTextures(activeTextures) { + if (this._texture) { + activeTextures.push(this._texture); + } + } + getAnimatables(animatables) { + if (this._texture && this._texture.animations && this._texture.animations.length > 0) { + animatables.push(this._texture); + } + } + dispose(forceDisposeTextures) { + if (forceDisposeTextures) { + if (this._texture) { + this._texture.dispose(); + } + } + } + getClassName() { + return "PBRAnisotropicConfiguration"; + } + addFallbacks(defines, fallbacks, currentRank) { + if (defines.ANISOTROPIC) { + fallbacks.addFallback(currentRank++, "ANISOTROPIC"); + } + return currentRank; + } + getSamplers(samplers) { + samplers.push("anisotropySampler"); + } + getUniforms() { + return { + ubo: [ + { name: "vAnisotropy", size: 3, type: "vec3" }, + { name: "vAnisotropyInfos", size: 2, type: "vec2" }, + { name: "anisotropyMatrix", size: 16, type: "mat4" }, + ], + }; + } + /** + * Parses a anisotropy Configuration from a serialized object. + * @param source - Serialized object. + * @param scene Defines the scene we are parsing for + * @param rootUrl Defines the rootUrl to load from + */ + parse(source, scene, rootUrl) { + super.parse(source, scene, rootUrl); + // Backward compatibility + if (source.legacy === undefined) { + this.legacy = true; + } + } +} +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRAnisotropicConfiguration.prototype, "isEnabled", void 0); +__decorate([ + serialize() +], PBRAnisotropicConfiguration.prototype, "intensity", void 0); +__decorate([ + serializeAsVector2() +], PBRAnisotropicConfiguration.prototype, "direction", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRAnisotropicConfiguration.prototype, "texture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsMiscDirty") +], PBRAnisotropicConfiguration.prototype, "legacy", void 0); + +/** + * @internal + */ +class MaterialSheenDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.SHEEN = false; + this.SHEEN_TEXTURE = false; + this.SHEEN_GAMMATEXTURE = false; + this.SHEEN_TEXTURE_ROUGHNESS = false; + this.SHEEN_TEXTUREDIRECTUV = 0; + this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0; + this.SHEEN_LINKWITHALBEDO = false; + this.SHEEN_ROUGHNESS = false; + this.SHEEN_ALBEDOSCALING = false; + this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false; + } +} +/** + * Plugin that implements the sheen component of the PBR material. + */ +class PBRSheenConfiguration extends MaterialPluginBase { + /** @internal */ + _markAllSubMeshesAsTexturesDirty() { + this._enable(this._isEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + constructor(material, addToPluginList = true) { + super(material, "Sheen", 120, new MaterialSheenDefines(), addToPluginList); + this._isEnabled = false; + /** + * Defines if the material uses sheen. + */ + this.isEnabled = false; + this._linkSheenWithAlbedo = false; + /** + * Defines if the sheen is linked to the sheen color. + */ + this.linkSheenWithAlbedo = false; + /** + * Defines the sheen intensity. + */ + this.intensity = 1; + /** + * Defines the sheen color. + */ + this.color = Color3.White(); + this._texture = null; + /** + * Stores the sheen tint values in a texture. + * rgb is tint + * a is a intensity or roughness if the roughness property has been defined and useRoughnessFromTexture is true (in that case, textureRoughness won't be used) + * If the roughness property has been defined and useRoughnessFromTexture is false then the alpha channel is not used to modulate roughness + */ + this.texture = null; + this._useRoughnessFromMainTexture = true; + /** + * Indicates that the alpha channel of the texture property will be used for roughness. + * Has no effect if the roughness (and texture!) property is not defined + */ + this.useRoughnessFromMainTexture = true; + this._roughness = null; + /** + * Defines the sheen roughness. + * It is not taken into account if linkSheenWithAlbedo is true. + * To stay backward compatible, material roughness is used instead if sheen roughness = null + */ + this.roughness = null; + this._textureRoughness = null; + /** + * Stores the sheen roughness in a texture. + * alpha channel is the roughness. This texture won't be used if the texture property is not empty and useRoughnessFromTexture is true + */ + this.textureRoughness = null; + this._albedoScaling = false; + /** + * If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique. + * It allows the strength of the sheen effect to not depend on the base color of the material, + * making it easier to setup and tweak the effect + */ + this.albedoScaling = false; + this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; + } + isReadyForSubMesh(defines, scene) { + if (!this._isEnabled) { + return true; + } + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.SheenTextureEnabled) { + if (!this._texture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) { + if (!this._textureRoughness.isReadyOrNotBlocking()) { + return false; + } + } + } + } + return true; + } + prepareDefinesBeforeAttributes(defines, scene) { + if (this._isEnabled) { + defines.SHEEN = true; + defines.SHEEN_LINKWITHALBEDO = this._linkSheenWithAlbedo; + defines.SHEEN_ROUGHNESS = this._roughness !== null; + defines.SHEEN_ALBEDOSCALING = this._albedoScaling; + defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture; + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.SheenTextureEnabled) { + PrepareDefinesForMergedUV(this._texture, defines, "SHEEN_TEXTURE"); + defines.SHEEN_GAMMATEXTURE = this._texture.gammaSpace; + } + else { + defines.SHEEN_TEXTURE = false; + } + if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) { + PrepareDefinesForMergedUV(this._textureRoughness, defines, "SHEEN_TEXTURE_ROUGHNESS"); + } + else { + defines.SHEEN_TEXTURE_ROUGHNESS = false; + } + } + } + } + else { + defines.SHEEN = false; + defines.SHEEN_TEXTURE = false; + defines.SHEEN_TEXTURE_ROUGHNESS = false; + defines.SHEEN_LINKWITHALBEDO = false; + defines.SHEEN_ROUGHNESS = false; + defines.SHEEN_ALBEDOSCALING = false; + defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false; + defines.SHEEN_GAMMATEXTURE = false; + defines.SHEEN_TEXTUREDIRECTUV = 0; + defines.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0; + } + } + bindForSubMesh(uniformBuffer, scene, engine, subMesh) { + if (!this._isEnabled) { + return; + } + const defines = subMesh.materialDefines; + const isFrozen = this._material.isFrozen; + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + if ((this._texture || this._textureRoughness) && MaterialFlags.SheenTextureEnabled) { + uniformBuffer.updateFloat4("vSheenInfos", this._texture?.coordinatesIndex ?? 0, this._texture?.level ?? 0, this._textureRoughness?.coordinatesIndex ?? 0, this._textureRoughness?.level ?? 0); + if (this._texture) { + BindTextureMatrix(this._texture, uniformBuffer, "sheen"); + } + if (this._textureRoughness && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) { + BindTextureMatrix(this._textureRoughness, uniformBuffer, "sheenRoughness"); + } + } + // Sheen + uniformBuffer.updateFloat4("vSheenColor", this.color.r, this.color.g, this.color.b, this.intensity); + if (this._roughness !== null) { + uniformBuffer.updateFloat("vSheenRoughness", this._roughness); + } + } + // Textures + if (scene.texturesEnabled) { + if (this._texture && MaterialFlags.SheenTextureEnabled) { + uniformBuffer.setTexture("sheenSampler", this._texture); + } + if (this._textureRoughness && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.SheenTextureEnabled) { + uniformBuffer.setTexture("sheenRoughnessSampler", this._textureRoughness); + } + } + } + hasTexture(texture) { + if (this._texture === texture) { + return true; + } + if (this._textureRoughness === texture) { + return true; + } + return false; + } + getActiveTextures(activeTextures) { + if (this._texture) { + activeTextures.push(this._texture); + } + if (this._textureRoughness) { + activeTextures.push(this._textureRoughness); + } + } + getAnimatables(animatables) { + if (this._texture && this._texture.animations && this._texture.animations.length > 0) { + animatables.push(this._texture); + } + if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) { + animatables.push(this._textureRoughness); + } + } + dispose(forceDisposeTextures) { + if (forceDisposeTextures) { + this._texture?.dispose(); + this._textureRoughness?.dispose(); + } + } + getClassName() { + return "PBRSheenConfiguration"; + } + addFallbacks(defines, fallbacks, currentRank) { + if (defines.SHEEN) { + fallbacks.addFallback(currentRank++, "SHEEN"); + } + return currentRank; + } + getSamplers(samplers) { + samplers.push("sheenSampler", "sheenRoughnessSampler"); + } + getUniforms() { + return { + ubo: [ + { name: "vSheenColor", size: 4, type: "vec4" }, + { name: "vSheenRoughness", size: 1, type: "float" }, + { name: "vSheenInfos", size: 4, type: "vec4" }, + { name: "sheenMatrix", size: 16, type: "mat4" }, + { name: "sheenRoughnessMatrix", size: 16, type: "mat4" }, + ], + }; + } +} +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSheenConfiguration.prototype, "isEnabled", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSheenConfiguration.prototype, "linkSheenWithAlbedo", void 0); +__decorate([ + serialize() +], PBRSheenConfiguration.prototype, "intensity", void 0); +__decorate([ + serializeAsColor3() +], PBRSheenConfiguration.prototype, "color", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSheenConfiguration.prototype, "texture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSheenConfiguration.prototype, "useRoughnessFromMainTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSheenConfiguration.prototype, "roughness", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSheenConfiguration.prototype, "textureRoughness", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSheenConfiguration.prototype, "albedoScaling", void 0); + +/** + * @internal + */ +class MaterialSubSurfaceDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.SUBSURFACE = false; + this.SS_REFRACTION = false; + this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = false; + this.SS_TRANSLUCENCY = false; + this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = false; + this.SS_SCATTERING = false; + this.SS_DISPERSION = false; + this.SS_THICKNESSANDMASK_TEXTURE = false; + this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0; + this.SS_HAS_THICKNESS = false; + this.SS_REFRACTIONINTENSITY_TEXTURE = false; + this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0; + this.SS_TRANSLUCENCYINTENSITY_TEXTURE = false; + this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0; + this.SS_TRANSLUCENCYCOLOR_TEXTURE = false; + this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV = 0; + this.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA = false; + this.SS_REFRACTIONMAP_3D = false; + this.SS_REFRACTIONMAP_OPPOSITEZ = false; + this.SS_LODINREFRACTIONALPHA = false; + this.SS_GAMMAREFRACTION = false; + this.SS_RGBDREFRACTION = false; + this.SS_LINEARSPECULARREFRACTION = false; + this.SS_LINKREFRACTIONTOTRANSPARENCY = false; + this.SS_ALBEDOFORREFRACTIONTINT = false; + this.SS_ALBEDOFORTRANSLUCENCYTINT = false; + this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false; + this.SS_USE_THICKNESS_AS_DEPTH = false; + this.SS_USE_GLTF_TEXTURES = false; + } +} +/** + * Plugin that implements the sub surface component of the PBR material + */ +class PBRSubSurfaceConfiguration extends MaterialPluginBase { + /** + * Diffusion profile for subsurface scattering. + * Useful for better scattering in the skins or foliages. + */ + get scatteringDiffusionProfile() { + if (!this._scene.subSurfaceConfiguration) { + return null; + } + return this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]; + } + set scatteringDiffusionProfile(c) { + if (!this._scene.enableSubSurfaceForPrePass()) { + // Not supported + return; + } + // addDiffusionProfile automatically checks for doubles + if (c) { + this._scatteringDiffusionProfileIndex = this._scene.subSurfaceConfiguration.addDiffusionProfile(c); + } + } + /** + * Index of refraction of the material's volume. + * https://en.wikipedia.org/wiki/List_of_refractive_indices + * + * This ONLY impacts refraction. If not provided or given a non-valid value, + * the volume will use the same IOR as the surface. + */ + get volumeIndexOfRefraction() { + if (this._volumeIndexOfRefraction >= 1.0) { + return this._volumeIndexOfRefraction; + } + return this._indexOfRefraction; + } + set volumeIndexOfRefraction(value) { + if (value >= 1.0) { + this._volumeIndexOfRefraction = value; + } + else { + this._volumeIndexOfRefraction = -1; + } + } + /** @internal */ + _markAllSubMeshesAsTexturesDirty() { + this._enable(this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + } + /** @internal */ + _markScenePrePassDirty() { + this._enable(this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + this._internalMarkScenePrePassDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + constructor(material, addToPluginList = true) { + super(material, "PBRSubSurface", 130, new MaterialSubSurfaceDefines(), addToPluginList); + this._isRefractionEnabled = false; + /** + * Defines if the refraction is enabled in the material. + */ + this.isRefractionEnabled = false; + this._isTranslucencyEnabled = false; + /** + * Defines if the translucency is enabled in the material. + */ + this.isTranslucencyEnabled = false; + this._isDispersionEnabled = false; + /** + * Defines if dispersion is enabled in the material. + */ + this.isDispersionEnabled = false; + this._isScatteringEnabled = false; + /** + * Defines if the sub surface scattering is enabled in the material. + */ + this.isScatteringEnabled = false; + this._scatteringDiffusionProfileIndex = 0; + /** + * Defines the refraction intensity of the material. + * The refraction when enabled replaces the Diffuse part of the material. + * The intensity helps transitioning between diffuse and refraction. + */ + this.refractionIntensity = 1; + /** + * Defines the translucency intensity of the material. + * When translucency has been enabled, this defines how much of the "translucency" + * is added to the diffuse part of the material. + */ + this.translucencyIntensity = 1; + /** + * When enabled, transparent surfaces will be tinted with the albedo colour (independent of thickness) + */ + this.useAlbedoToTintRefraction = false; + /** + * When enabled, translucent surfaces will be tinted with the albedo colour (independent of thickness) + */ + this.useAlbedoToTintTranslucency = false; + this._thicknessTexture = null; + /** + * Stores the average thickness of a mesh in a texture (The texture is holding the values linearly). + * The red (or green if useGltfStyleTextures=true) channel of the texture should contain the thickness remapped between 0 and 1. + * 0 would mean minimumThickness + * 1 would mean maximumThickness + * The other channels might be use as a mask to vary the different effects intensity. + */ + this.thicknessTexture = null; + this._refractionTexture = null; + /** + * Defines the texture to use for refraction. + */ + this.refractionTexture = null; + /** @internal */ + this._indexOfRefraction = 1.5; + /** + * Index of refraction of the material base layer. + * https://en.wikipedia.org/wiki/List_of_refractive_indices + * + * This does not only impact refraction but also the Base F0 of Dielectric Materials. + * + * From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI)) + */ + this.indexOfRefraction = 1.5; + this._volumeIndexOfRefraction = -1; + this._invertRefractionY = false; + /** + * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. + */ + this.invertRefractionY = false; + /** @internal */ + this._linkRefractionWithTransparency = false; + /** + * This parameters will make the material used its opacity to control how much it is refracting against not. + * Materials half opaque for instance using refraction could benefit from this control. + */ + this.linkRefractionWithTransparency = false; + /** + * Defines the minimum thickness stored in the thickness map. + * If no thickness map is defined, this value will be used to simulate thickness. + */ + this.minimumThickness = 0; + /** + * Defines the maximum thickness stored in the thickness map. + */ + this.maximumThickness = 1; + /** + * Defines that the thickness should be used as a measure of the depth volume. + */ + this.useThicknessAsDepth = false; + /** + * Defines the volume tint of the material. + * This is used for both translucency and scattering. + */ + this.tintColor = Color3.White(); + /** + * Defines the distance at which the tint color should be found in the media. + * This is used for refraction only. + */ + this.tintColorAtDistance = 1; + /** + * Defines the Abbe number for the volume. + */ + this.dispersion = 0; + /** + * Defines how far each channel transmit through the media. + * It is defined as a color to simplify it selection. + */ + this.diffusionDistance = Color3.White(); + this._useMaskFromThicknessTexture = false; + /** + * Stores the intensity of the different subsurface effects in the thickness texture. + * Note that if refractionIntensityTexture and/or translucencyIntensityTexture is provided it takes precedence over thicknessTexture + useMaskFromThicknessTexture + * * the green (red if useGltfStyleTextures = true) channel is the refraction intensity. + * * the blue (alpha if useGltfStyleTextures = true) channel is the translucency intensity. + */ + this.useMaskFromThicknessTexture = false; + this._refractionIntensityTexture = null; + /** + * Stores the intensity of the refraction. If provided, it takes precedence over thicknessTexture + useMaskFromThicknessTexture + * * the green (red if useGltfStyleTextures = true) channel is the refraction intensity. + */ + this.refractionIntensityTexture = null; + this._translucencyIntensityTexture = null; + /** + * Stores the intensity of the translucency. If provided, it takes precedence over thicknessTexture + useMaskFromThicknessTexture + * * the blue (alpha if useGltfStyleTextures = true) channel is the translucency intensity. + */ + this.translucencyIntensityTexture = null; + /** + * Defines the translucency tint of the material. + * If not set, the tint color will be used instead. + */ + this.translucencyColor = null; + this._translucencyColorTexture = null; + /** + * Defines the translucency tint color of the material as a texture. + * This is multiplied against the translucency color to add variety and realism to the material. + * If translucencyColor is not set, the tint color will be used instead. + */ + this.translucencyColorTexture = null; + this._useGltfStyleTextures = true; + /** + * Use channels layout used by glTF: + * * thicknessTexture: the green (instead of red) channel is the thickness + * * thicknessTexture/refractionIntensityTexture: the red (instead of green) channel is the refraction intensity + * * thicknessTexture/translucencyIntensityTexture: the alpha (instead of blue) channel is the translucency intensity + */ + this.useGltfStyleTextures = true; + this._scene = material.getScene(); + this.registerForExtraEvents = true; + this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; + this._internalMarkScenePrePassDirty = material._dirtyCallbacks[32]; + } + isReadyForSubMesh(defines, scene) { + if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) { + return true; + } + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) { + if (!this._thicknessTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled) { + if (!this._translucencyColorTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled) { + if (!this._translucencyIntensityTexture.isReadyOrNotBlocking()) { + return false; + } + } + const refractionTexture = this._getRefractionTexture(scene); + if (refractionTexture && MaterialFlags.RefractionTextureEnabled) { + if (!refractionTexture.isReadyOrNotBlocking()) { + return false; + } + } + } + } + return true; + } + prepareDefinesBeforeAttributes(defines, scene) { + if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) { + defines.SUBSURFACE = false; + defines.SS_DISPERSION = false; + defines.SS_TRANSLUCENCY = false; + defines.SS_SCATTERING = false; + defines.SS_REFRACTION = false; + defines.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = false; + defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = false; + defines.SS_THICKNESSANDMASK_TEXTURE = false; + defines.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0; + defines.SS_HAS_THICKNESS = false; + defines.SS_REFRACTIONINTENSITY_TEXTURE = false; + defines.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0; + defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false; + defines.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0; + defines.SS_REFRACTIONMAP_3D = false; + defines.SS_REFRACTIONMAP_OPPOSITEZ = false; + defines.SS_LODINREFRACTIONALPHA = false; + defines.SS_GAMMAREFRACTION = false; + defines.SS_RGBDREFRACTION = false; + defines.SS_LINEARSPECULARREFRACTION = false; + defines.SS_LINKREFRACTIONTOTRANSPARENCY = false; + defines.SS_ALBEDOFORREFRACTIONTINT = false; + defines.SS_ALBEDOFORTRANSLUCENCYTINT = false; + defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false; + defines.SS_USE_THICKNESS_AS_DEPTH = false; + defines.SS_USE_GLTF_TEXTURES = false; + defines.SS_TRANSLUCENCYCOLOR_TEXTURE = false; + defines.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV = 0; + defines.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA = false; + return; + } + if (defines._areTexturesDirty) { + defines.SUBSURFACE = true; + defines.SS_DISPERSION = this._isDispersionEnabled; + defines.SS_TRANSLUCENCY = this._isTranslucencyEnabled; + defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = false; + defines.SS_SCATTERING = this._isScatteringEnabled; + defines.SS_THICKNESSANDMASK_TEXTURE = false; + defines.SS_REFRACTIONINTENSITY_TEXTURE = false; + defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false; + defines.SS_HAS_THICKNESS = false; + defines.SS_USE_GLTF_TEXTURES = false; + defines.SS_REFRACTION = false; + defines.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = false; + defines.SS_REFRACTIONMAP_3D = false; + defines.SS_GAMMAREFRACTION = false; + defines.SS_RGBDREFRACTION = false; + defines.SS_LINEARSPECULARREFRACTION = false; + defines.SS_REFRACTIONMAP_OPPOSITEZ = false; + defines.SS_LODINREFRACTIONALPHA = false; + defines.SS_LINKREFRACTIONTOTRANSPARENCY = false; + defines.SS_ALBEDOFORREFRACTIONTINT = false; + defines.SS_ALBEDOFORTRANSLUCENCYTINT = false; + defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false; + defines.SS_USE_THICKNESS_AS_DEPTH = false; + defines.SS_TRANSLUCENCYCOLOR_TEXTURE = false; + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) { + PrepareDefinesForMergedUV(this._thicknessTexture, defines, "SS_THICKNESSANDMASK_TEXTURE"); + } + if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled) { + PrepareDefinesForMergedUV(this._refractionIntensityTexture, defines, "SS_REFRACTIONINTENSITY_TEXTURE"); + } + if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled) { + PrepareDefinesForMergedUV(this._translucencyIntensityTexture, defines, "SS_TRANSLUCENCYINTENSITY_TEXTURE"); + } + if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled) { + PrepareDefinesForMergedUV(this._translucencyColorTexture, defines, "SS_TRANSLUCENCYCOLOR_TEXTURE"); + defines.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA = this._translucencyColorTexture.gammaSpace; + } + } + } + defines.SS_HAS_THICKNESS = this.maximumThickness - this.minimumThickness !== 0.0; + defines.SS_USE_GLTF_TEXTURES = this._useGltfStyleTextures; + defines.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = this._useMaskFromThicknessTexture && !this._refractionIntensityTexture; + defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = this._useMaskFromThicknessTexture && !this._translucencyIntensityTexture; + if (this._isRefractionEnabled) { + if (scene.texturesEnabled) { + const refractionTexture = this._getRefractionTexture(scene); + if (refractionTexture && MaterialFlags.RefractionTextureEnabled) { + defines.SS_REFRACTION = true; + defines.SS_REFRACTIONMAP_3D = refractionTexture.isCube; + defines.SS_GAMMAREFRACTION = refractionTexture.gammaSpace; + defines.SS_RGBDREFRACTION = refractionTexture.isRGBD; + defines.SS_LINEARSPECULARREFRACTION = refractionTexture.linearSpecularLOD; + defines.SS_REFRACTIONMAP_OPPOSITEZ = this._scene.useRightHandedSystem && refractionTexture.isCube ? !refractionTexture.invertZ : refractionTexture.invertZ; + defines.SS_LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha; + defines.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency; + defines.SS_ALBEDOFORREFRACTIONTINT = this.useAlbedoToTintRefraction; + defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = refractionTexture.isCube && refractionTexture.boundingBoxSize; + defines.SS_USE_THICKNESS_AS_DEPTH = this.useThicknessAsDepth; + } + } + } + if (this._isTranslucencyEnabled) { + defines.SS_ALBEDOFORTRANSLUCENCYTINT = this.useAlbedoToTintTranslucency; + } + } + } + /** + * Binds the material data (this function is called even if mustRebind() returns false) + * @param uniformBuffer defines the Uniform buffer to fill in. + * @param scene defines the scene the material belongs to. + * @param engine defines the engine the material belongs to. + * @param subMesh the submesh to bind data for + */ + hardBindForSubMesh(uniformBuffer, scene, engine, subMesh) { + if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) { + return; + } + // If min/max thickness is 0, avoid decompising to determine the scaled thickness (it's always zero). + if (this.maximumThickness === 0.0 && this.minimumThickness === 0.0) { + uniformBuffer.updateFloat2("vThicknessParam", 0, 0); + } + else { + subMesh.getRenderingMesh().getWorldMatrix().decompose(TmpVectors.Vector3[0]); + const thicknessScale = Math.max(Math.abs(TmpVectors.Vector3[0].x), Math.abs(TmpVectors.Vector3[0].y), Math.abs(TmpVectors.Vector3[0].z)); + uniformBuffer.updateFloat2("vThicknessParam", this.minimumThickness * thicknessScale, (this.maximumThickness - this.minimumThickness) * thicknessScale); + } + } + bindForSubMesh(uniformBuffer, scene, engine, subMesh) { + if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) { + return; + } + const defines = subMesh.materialDefines; + const isFrozen = this._material.isFrozen; + const realTimeFiltering = this._material.realTimeFiltering; + const lodBasedMicrosurface = defines.LODBASEDMICROSFURACE; + const refractionTexture = this._getRefractionTexture(scene); + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) { + uniformBuffer.updateFloat2("vThicknessInfos", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level); + BindTextureMatrix(this._thicknessTexture, uniformBuffer, "thickness"); + } + if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) { + uniformBuffer.updateFloat2("vRefractionIntensityInfos", this._refractionIntensityTexture.coordinatesIndex, this._refractionIntensityTexture.level); + BindTextureMatrix(this._refractionIntensityTexture, uniformBuffer, "refractionIntensity"); + } + if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled && defines.SS_TRANSLUCENCYCOLOR_TEXTURE) { + uniformBuffer.updateFloat2("vTranslucencyColorInfos", this._translucencyColorTexture.coordinatesIndex, this._translucencyColorTexture.level); + BindTextureMatrix(this._translucencyColorTexture, uniformBuffer, "translucencyColor"); + } + if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) { + uniformBuffer.updateFloat2("vTranslucencyIntensityInfos", this._translucencyIntensityTexture.coordinatesIndex, this._translucencyIntensityTexture.level); + BindTextureMatrix(this._translucencyIntensityTexture, uniformBuffer, "translucencyIntensity"); + } + if (refractionTexture && MaterialFlags.RefractionTextureEnabled) { + uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getRefractionTextureMatrix()); + let depth = 1.0; + if (!refractionTexture.isCube) { + if (refractionTexture.depth) { + depth = refractionTexture.depth; + } + } + const width = refractionTexture.getSize().width; + const refractionIor = this.volumeIndexOfRefraction; + uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, 1 / refractionIor, depth, this._invertRefractionY ? -1 : 1); + uniformBuffer.updateFloat4("vRefractionMicrosurfaceInfos", width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset, 1.0 / this.indexOfRefraction); + if (realTimeFiltering) { + uniformBuffer.updateFloat2("vRefractionFilteringInfo", width, Math.log2(width)); + } + if (refractionTexture.boundingBoxSize) { + const cubeTexture = refractionTexture; + uniformBuffer.updateVector3("vRefractionPosition", cubeTexture.boundingBoxPosition); + uniformBuffer.updateVector3("vRefractionSize", cubeTexture.boundingBoxSize); + } + } + if (this._isScatteringEnabled) { + uniformBuffer.updateFloat("scatteringDiffusionProfile", this._scatteringDiffusionProfileIndex); + } + uniformBuffer.updateColor3("vDiffusionDistance", this.diffusionDistance); + uniformBuffer.updateFloat4("vTintColor", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintColorAtDistance)); + uniformBuffer.updateColor4("vTranslucencyColor", this.translucencyColor ?? this.tintColor, 0); + uniformBuffer.updateFloat3("vSubSurfaceIntensity", this.refractionIntensity, this.translucencyIntensity, 0); + uniformBuffer.updateFloat("dispersion", this.dispersion); + } + // Textures + if (scene.texturesEnabled) { + if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) { + uniformBuffer.setTexture("thicknessSampler", this._thicknessTexture); + } + if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) { + uniformBuffer.setTexture("refractionIntensitySampler", this._refractionIntensityTexture); + } + if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) { + uniformBuffer.setTexture("translucencyIntensitySampler", this._translucencyIntensityTexture); + } + if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled && defines.SS_TRANSLUCENCYCOLOR_TEXTURE) { + uniformBuffer.setTexture("translucencyColorSampler", this._translucencyColorTexture); + } + if (refractionTexture && MaterialFlags.RefractionTextureEnabled) { + if (lodBasedMicrosurface) { + uniformBuffer.setTexture("refractionSampler", refractionTexture); + } + else { + uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture); + uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture); + uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture); + } + } + } + } + /** + * Returns the texture used for refraction or null if none is used. + * @param scene defines the scene the material belongs to. + * @returns - Refraction texture if present. If no refraction texture and refraction + * is linked with transparency, returns environment texture. Otherwise, returns null. + */ + _getRefractionTexture(scene) { + if (this._refractionTexture) { + return this._refractionTexture; + } + if (this._isRefractionEnabled) { + return scene.environmentTexture; + } + return null; + } + /** + * Returns true if alpha blending should be disabled. + */ + get disableAlphaBlending() { + return this._isRefractionEnabled && this._linkRefractionWithTransparency; + } + /** + * Fills the list of render target textures. + * @param renderTargets the list of render targets to update + */ + fillRenderTargetTextures(renderTargets) { + if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { + renderTargets.push(this._refractionTexture); + } + } + hasTexture(texture) { + if (this._thicknessTexture === texture) { + return true; + } + if (this._refractionTexture === texture) { + return true; + } + if (this._refractionIntensityTexture === texture) { + return true; + } + if (this._translucencyIntensityTexture === texture) { + return true; + } + if (this._translucencyColorTexture === texture) { + return true; + } + return false; + } + hasRenderTargetTextures() { + if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { + return true; + } + return false; + } + getActiveTextures(activeTextures) { + if (this._thicknessTexture) { + activeTextures.push(this._thicknessTexture); + } + if (this._refractionTexture) { + activeTextures.push(this._refractionTexture); + } + if (this._translucencyColorTexture) { + activeTextures.push(this._translucencyColorTexture); + } + if (this._translucencyIntensityTexture) { + activeTextures.push(this._translucencyIntensityTexture); + } + } + getAnimatables(animatables) { + if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) { + animatables.push(this._thicknessTexture); + } + if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) { + animatables.push(this._refractionTexture); + } + if (this._translucencyColorTexture && this._translucencyColorTexture.animations && this._translucencyColorTexture.animations.length > 0) { + animatables.push(this._translucencyColorTexture); + } + if (this._translucencyIntensityTexture && this._translucencyIntensityTexture.animations && this._translucencyIntensityTexture.animations.length > 0) { + animatables.push(this._translucencyIntensityTexture); + } + } + dispose(forceDisposeTextures) { + if (forceDisposeTextures) { + if (this._thicknessTexture) { + this._thicknessTexture.dispose(); + } + if (this._refractionTexture) { + this._refractionTexture.dispose(); + } + if (this._translucencyColorTexture) { + this._translucencyColorTexture.dispose(); + } + if (this._translucencyIntensityTexture) { + this._translucencyIntensityTexture.dispose(); + } + } + } + getClassName() { + return "PBRSubSurfaceConfiguration"; + } + addFallbacks(defines, fallbacks, currentRank) { + if (defines.SS_SCATTERING) { + fallbacks.addFallback(currentRank++, "SS_SCATTERING"); + } + if (defines.SS_TRANSLUCENCY) { + fallbacks.addFallback(currentRank++, "SS_TRANSLUCENCY"); + } + return currentRank; + } + getSamplers(samplers) { + samplers.push("thicknessSampler", "refractionIntensitySampler", "translucencyIntensitySampler", "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh", "translucencyColorSampler"); + } + getUniforms() { + return { + ubo: [ + { name: "vRefractionMicrosurfaceInfos", size: 4, type: "vec4" }, + { name: "vRefractionFilteringInfo", size: 2, type: "vec2" }, + { name: "vTranslucencyIntensityInfos", size: 2, type: "vec2" }, + { name: "vRefractionInfos", size: 4, type: "vec4" }, + { name: "refractionMatrix", size: 16, type: "mat4" }, + { name: "vThicknessInfos", size: 2, type: "vec2" }, + { name: "vRefractionIntensityInfos", size: 2, type: "vec2" }, + { name: "thicknessMatrix", size: 16, type: "mat4" }, + { name: "refractionIntensityMatrix", size: 16, type: "mat4" }, + { name: "translucencyIntensityMatrix", size: 16, type: "mat4" }, + { name: "vThicknessParam", size: 2, type: "vec2" }, + { name: "vDiffusionDistance", size: 3, type: "vec3" }, + { name: "vTintColor", size: 4, type: "vec4" }, + { name: "vSubSurfaceIntensity", size: 3, type: "vec3" }, + { name: "vRefractionPosition", size: 3, type: "vec3" }, + { name: "vRefractionSize", size: 3, type: "vec3" }, + { name: "scatteringDiffusionProfile", size: 1, type: "float" }, + { name: "dispersion", size: 1, type: "float" }, + { name: "vTranslucencyColor", size: 4, type: "vec4" }, + { name: "vTranslucencyColorInfos", size: 2, type: "vec2" }, + { name: "translucencyColorMatrix", size: 16, type: "mat4" }, + ], + }; + } +} +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "isRefractionEnabled", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "isTranslucencyEnabled", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "isDispersionEnabled", void 0); +__decorate([ + serialize(), + expandToProperty("_markScenePrePassDirty") +], PBRSubSurfaceConfiguration.prototype, "isScatteringEnabled", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "_scatteringDiffusionProfileIndex", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "refractionIntensity", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "translucencyIntensity", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "useAlbedoToTintRefraction", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "useAlbedoToTintTranslucency", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "thicknessTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "refractionTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "indexOfRefraction", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "_volumeIndexOfRefraction", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "volumeIndexOfRefraction", null); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "invertRefractionY", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "linkRefractionWithTransparency", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "minimumThickness", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "maximumThickness", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "useThicknessAsDepth", void 0); +__decorate([ + serializeAsColor3() +], PBRSubSurfaceConfiguration.prototype, "tintColor", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "tintColorAtDistance", void 0); +__decorate([ + serialize() +], PBRSubSurfaceConfiguration.prototype, "dispersion", void 0); +__decorate([ + serializeAsColor3() +], PBRSubSurfaceConfiguration.prototype, "diffusionDistance", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "useMaskFromThicknessTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "refractionIntensityTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "translucencyIntensityTexture", void 0); +__decorate([ + serializeAsColor3() +], PBRSubSurfaceConfiguration.prototype, "translucencyColor", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "translucencyColorTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRSubSurfaceConfiguration.prototype, "useGltfStyleTextures", void 0); + +const onCreatedEffectParameters$1 = { effect: null, subMesh: null }; +/** + * Manages the defines for the PBR Material. + * @internal + */ +class PBRMaterialDefines extends MaterialDefines { + /** + * Initializes the PBR Material defines. + * @param externalProperties The external properties + */ + constructor(externalProperties) { + super(externalProperties); + this.PBR = true; + this.NUM_SAMPLES = "0"; + this.REALTIME_FILTERING = false; + this.IBL_CDF_FILTERING = false; + this.MAINUV1 = false; + this.MAINUV2 = false; + this.MAINUV3 = false; + this.MAINUV4 = false; + this.MAINUV5 = false; + this.MAINUV6 = false; + this.UV1 = false; + this.UV2 = false; + this.UV3 = false; + this.UV4 = false; + this.UV5 = false; + this.UV6 = false; + this.ALBEDO = false; + this.GAMMAALBEDO = false; + this.ALBEDODIRECTUV = 0; + this.VERTEXCOLOR = false; + this.BASEWEIGHT = false; + this.BASEWEIGHTDIRECTUV = 0; + this.BAKED_VERTEX_ANIMATION_TEXTURE = false; + this.AMBIENT = false; + this.AMBIENTDIRECTUV = 0; + this.AMBIENTINGRAYSCALE = false; + this.OPACITY = false; + this.VERTEXALPHA = false; + this.OPACITYDIRECTUV = 0; + this.OPACITYRGB = false; + this.ALPHATEST = false; + this.DEPTHPREPASS = false; + this.ALPHABLEND = false; + this.ALPHAFROMALBEDO = false; + this.ALPHATESTVALUE = "0.5"; + this.SPECULAROVERALPHA = false; + this.RADIANCEOVERALPHA = false; + this.ALPHAFRESNEL = false; + this.LINEARALPHAFRESNEL = false; + this.PREMULTIPLYALPHA = false; + this.EMISSIVE = false; + this.EMISSIVEDIRECTUV = 0; + this.GAMMAEMISSIVE = false; + this.REFLECTIVITY = false; + this.REFLECTIVITY_GAMMA = false; + this.REFLECTIVITYDIRECTUV = 0; + this.SPECULARTERM = false; + this.MICROSURFACEFROMREFLECTIVITYMAP = false; + this.MICROSURFACEAUTOMATIC = false; + this.LODBASEDMICROSFURACE = false; + this.MICROSURFACEMAP = false; + this.MICROSURFACEMAPDIRECTUV = 0; + this.METALLICWORKFLOW = false; + this.ROUGHNESSSTOREINMETALMAPALPHA = false; + this.ROUGHNESSSTOREINMETALMAPGREEN = false; + this.METALLNESSSTOREINMETALMAPBLUE = false; + this.AOSTOREINMETALMAPRED = false; + this.METALLIC_REFLECTANCE = false; + this.METALLIC_REFLECTANCE_GAMMA = false; + this.METALLIC_REFLECTANCEDIRECTUV = 0; + this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = false; + this.REFLECTANCE = false; + this.REFLECTANCE_GAMMA = false; + this.REFLECTANCEDIRECTUV = 0; + this.ENVIRONMENTBRDF = false; + this.ENVIRONMENTBRDF_RGBD = false; + this.NORMAL = false; + this.TANGENT = false; + this.BUMP = false; + this.BUMPDIRECTUV = 0; + this.OBJECTSPACE_NORMALMAP = false; + this.PARALLAX = false; + this.PARALLAX_RHS = false; + this.PARALLAXOCCLUSION = false; + this.NORMALXYSCALE = true; + this.LIGHTMAP = false; + this.LIGHTMAPDIRECTUV = 0; + this.USELIGHTMAPASSHADOWMAP = false; + this.GAMMALIGHTMAP = false; + this.RGBDLIGHTMAP = false; + this.REFLECTION = false; + this.REFLECTIONMAP_3D = false; + this.REFLECTIONMAP_SPHERICAL = false; + this.REFLECTIONMAP_PLANAR = false; + this.REFLECTIONMAP_CUBIC = false; + this.USE_LOCAL_REFLECTIONMAP_CUBIC = false; + this.REFLECTIONMAP_PROJECTION = false; + this.REFLECTIONMAP_SKYBOX = false; + this.REFLECTIONMAP_EXPLICIT = false; + this.REFLECTIONMAP_EQUIRECTANGULAR = false; + this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + this.INVERTCUBICMAP = false; + this.USESPHERICALFROMREFLECTIONMAP = false; + this.USEIRRADIANCEMAP = false; + this.USESPHERICALINVERTEX = false; + this.REFLECTIONMAP_OPPOSITEZ = false; + this.LODINREFLECTIONALPHA = false; + this.GAMMAREFLECTION = false; + this.RGBDREFLECTION = false; + this.LINEARSPECULARREFLECTION = false; + this.RADIANCEOCCLUSION = false; + this.HORIZONOCCLUSION = false; + this.INSTANCES = false; + this.THIN_INSTANCES = false; + this.INSTANCESCOLOR = false; + this.PREPASS = false; + this.PREPASS_COLOR = false; + this.PREPASS_COLOR_INDEX = -1; + this.PREPASS_IRRADIANCE = false; + this.PREPASS_IRRADIANCE_INDEX = -1; + this.PREPASS_ALBEDO = false; + this.PREPASS_ALBEDO_INDEX = -1; + this.PREPASS_ALBEDO_SQRT = false; + this.PREPASS_ALBEDO_SQRT_INDEX = -1; + this.PREPASS_DEPTH = false; + this.PREPASS_DEPTH_INDEX = -1; + this.PREPASS_SCREENSPACE_DEPTH = false; + this.PREPASS_SCREENSPACE_DEPTH_INDEX = -1; + this.PREPASS_NORMAL = false; + this.PREPASS_NORMAL_INDEX = -1; + this.PREPASS_NORMAL_WORLDSPACE = false; + this.PREPASS_WORLD_NORMAL = false; + this.PREPASS_WORLD_NORMAL_INDEX = -1; + this.PREPASS_POSITION = false; + this.PREPASS_POSITION_INDEX = -1; + this.PREPASS_LOCAL_POSITION = false; + this.PREPASS_LOCAL_POSITION_INDEX = -1; + this.PREPASS_VELOCITY = false; + this.PREPASS_VELOCITY_INDEX = -1; + this.PREPASS_VELOCITY_LINEAR = false; + this.PREPASS_VELOCITY_LINEAR_INDEX = -1; + this.PREPASS_REFLECTIVITY = false; + this.PREPASS_REFLECTIVITY_INDEX = -1; + this.SCENE_MRT_COUNT = 0; + this.NUM_BONE_INFLUENCERS = 0; + this.BonesPerMesh = 0; + this.BONETEXTURE = false; + this.BONES_VELOCITY_ENABLED = false; + this.NONUNIFORMSCALING = false; + this.MORPHTARGETS = false; + this.MORPHTARGETS_POSITION = false; + this.MORPHTARGETS_NORMAL = false; + this.MORPHTARGETS_TANGENT = false; + this.MORPHTARGETS_UV = false; + this.MORPHTARGETS_UV2 = false; + this.MORPHTARGETS_COLOR = false; + this.MORPHTARGETTEXTURE_HASPOSITIONS = false; + this.MORPHTARGETTEXTURE_HASNORMALS = false; + this.MORPHTARGETTEXTURE_HASTANGENTS = false; + this.MORPHTARGETTEXTURE_HASUVS = false; + this.MORPHTARGETTEXTURE_HASUV2S = false; + this.MORPHTARGETTEXTURE_HASCOLORS = false; + this.NUM_MORPH_INFLUENCERS = 0; + this.MORPHTARGETS_TEXTURE = false; + this.IMAGEPROCESSING = false; + this.VIGNETTE = false; + this.VIGNETTEBLENDMODEMULTIPLY = false; + this.VIGNETTEBLENDMODEOPAQUE = false; + this.TONEMAPPING = 0; + this.CONTRAST = false; + this.COLORCURVES = false; + this.COLORGRADING = false; + this.COLORGRADING3D = false; + this.SAMPLER3DGREENDEPTH = false; + this.SAMPLER3DBGRMAP = false; + this.DITHER = false; + this.IMAGEPROCESSINGPOSTPROCESS = false; + this.SKIPFINALCOLORCLAMP = false; + this.EXPOSURE = false; + this.MULTIVIEW = false; + this.ORDER_INDEPENDENT_TRANSPARENCY = false; + this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false; + this.USEPHYSICALLIGHTFALLOFF = false; + this.USEGLTFLIGHTFALLOFF = false; + this.TWOSIDEDLIGHTING = false; + this.SHADOWFLOAT = false; + this.CLIPPLANE = false; + this.CLIPPLANE2 = false; + this.CLIPPLANE3 = false; + this.CLIPPLANE4 = false; + this.CLIPPLANE5 = false; + this.CLIPPLANE6 = false; + this.POINTSIZE = false; + this.FOG = false; + this.LOGARITHMICDEPTH = false; + this.CAMERA_ORTHOGRAPHIC = false; + this.CAMERA_PERSPECTIVE = false; + this.AREALIGHTSUPPORTED = true; + this.FORCENORMALFORWARD = false; + this.SPECULARAA = false; + this.UNLIT = false; + this.DECAL_AFTER_DETAIL = false; + this.DEBUGMODE = 0; + this.rebuild(); + } + /** + * Resets the PBR Material defines. + */ + reset() { + super.reset(); + this.ALPHATESTVALUE = "0.5"; + this.PBR = true; + this.NORMALXYSCALE = true; + } +} +/** + * The Physically based material base class of BJS. + * + * This offers the main features of a standard PBR material. + * For more information, please refer to the documentation : + * https://doc.babylonjs.com/features/featuresDeepDive/materials/using/introToPBR + * @see [WebGL](https://playground.babylonjs.com/#CGHTSM#1) + * @see [WebGPU](https://playground.babylonjs.com/#CGHTSM#2) + */ +class PBRBaseMaterial extends PushMaterial { + /** + * Enables realtime filtering on the texture. + */ + get realTimeFiltering() { + return this._realTimeFiltering; + } + set realTimeFiltering(b) { + this._realTimeFiltering = b; + this.markAsDirty(1); + } + /** + * Quality switch for realtime filtering + */ + get realTimeFilteringQuality() { + return this._realTimeFilteringQuality; + } + set realTimeFilteringQuality(n) { + this._realTimeFilteringQuality = n; + this.markAsDirty(1); + } + /** + * Can this material render to several textures at once + */ + get canRenderToMRT() { + return true; + } + /** + * Attaches a new image processing configuration to the PBR Material. + * @param configuration + */ + _attachImageProcessingConfiguration(configuration) { + if (configuration === this._imageProcessingConfiguration) { + return; + } + // Detaches observer. + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + // Pick the scene configuration if needed. + if (!configuration) { + this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; + } + else { + this._imageProcessingConfiguration = configuration; + } + // Attaches observer. + if (this._imageProcessingConfiguration) { + this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { + this._markAllSubMeshesAsImageProcessingDirty(); + }); + } + } + /** + * Instantiates a new PBRMaterial instance. + * + * @param name The material name + * @param scene The scene the material will be use in. + * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false + */ + constructor(name, scene, forceGLSL = false) { + super(name, scene, undefined, forceGLSL || PBRBaseMaterial.ForceGLSL); + /** + * Intensity of the direct lights e.g. the four lights available in your scene. + * This impacts both the direct diffuse and specular highlights. + * @internal + */ + this._directIntensity = 1.0; + /** + * Intensity of the emissive part of the material. + * This helps controlling the emissive effect without modifying the emissive color. + * @internal + */ + this._emissiveIntensity = 1.0; + /** + * Intensity of the environment e.g. how much the environment will light the object + * either through harmonics for rough material or through the reflection for shiny ones. + * @internal + */ + this._environmentIntensity = 1.0; + /** + * This is a special control allowing the reduction of the specular highlights coming from the + * four lights of the scene. Those highlights may not be needed in full environment lighting. + * @internal + */ + this._specularIntensity = 1.0; + /** + * This stores the direct, emissive, environment, and specular light intensities into a Vector4. + */ + this._lightingInfos = new Vector4(this._directIntensity, this._emissiveIntensity, this._environmentIntensity, this._specularIntensity); + /** + * Debug Control allowing disabling the bump map on this material. + * @internal + */ + this._disableBumpMap = false; + /** + * AKA Diffuse Texture in standard nomenclature. + * @internal + */ + this._albedoTexture = null; + /** + * OpenPBR Base Weight (multiplier to the diffuse and metal lobes). + * @internal + */ + this._baseWeightTexture = null; + /** + * AKA Occlusion Texture in other nomenclature. + * @internal + */ + this._ambientTexture = null; + /** + * AKA Occlusion Texture Intensity in other nomenclature. + * @internal + */ + this._ambientTextureStrength = 1.0; + /** + * Defines how much the AO map is occluding the analytical lights (point spot...). + * 1 means it completely occludes it + * 0 mean it has no impact + * @internal + */ + this._ambientTextureImpactOnAnalyticalLights = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS; + /** + * Stores the alpha values in a texture. + * @internal + */ + this._opacityTexture = null; + /** + * Stores the reflection values in a texture. + * @internal + */ + this._reflectionTexture = null; + /** + * Stores the emissive values in a texture. + * @internal + */ + this._emissiveTexture = null; + /** + * AKA Specular texture in other nomenclature. + * @internal + */ + this._reflectivityTexture = null; + /** + * Used to switch from specular/glossiness to metallic/roughness workflow. + * @internal + */ + this._metallicTexture = null; + /** + * Specifies the metallic scalar of the metallic/roughness workflow. + * Can also be used to scale the metalness values of the metallic texture. + * @internal + */ + this._metallic = null; + /** + * Specifies the roughness scalar of the metallic/roughness workflow. + * Can also be used to scale the roughness values of the metallic texture. + * @internal + */ + this._roughness = null; + /** + * In metallic workflow, specifies an F0 factor to help configuring the material F0. + * By default the indexOfrefraction is used to compute F0; + * + * This is used as a factor against the default reflectance at normal incidence to tweak it. + * + * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor; + * F90 = metallicReflectanceColor; + * @internal + */ + this._metallicF0Factor = 1; + /** + * In metallic workflow, specifies an F0 color. + * By default the F90 is always 1; + * + * Please note that this factor is also used as a factor against the default reflectance at normal incidence. + * + * F0 = defaultF0_from_IOR * metallicF0Factor * metallicReflectanceColor + * F90 = metallicF0Factor; + * @internal + */ + this._metallicReflectanceColor = Color3.White(); + /** + * Specifies that only the A channel from _metallicReflectanceTexture should be used. + * If false, both RGB and A channels will be used + * @internal + */ + this._useOnlyMetallicFromMetallicReflectanceTexture = false; + /** + * Defines to store metallicReflectanceColor in RGB and metallicF0Factor in A + * This is multiply against the scalar values defined in the material. + * @internal + */ + this._metallicReflectanceTexture = null; + /** + * Defines to store reflectanceColor in RGB + * This is multiplied against the scalar values defined in the material. + * If both _reflectanceTexture and _metallicReflectanceTexture textures are provided and _useOnlyMetallicFromMetallicReflectanceTexture + * is false, _metallicReflectanceTexture takes precedence and _reflectanceTexture is not used + * @internal + */ + this._reflectanceTexture = null; + /** + * Used to enable roughness/glossiness fetch from a separate channel depending on the current mode. + * Gray Scale represents roughness in metallic mode and glossiness in specular mode. + * @internal + */ + this._microSurfaceTexture = null; + /** + * Stores surface normal data used to displace a mesh in a texture. + * @internal + */ + this._bumpTexture = null; + /** + * Stores the pre-calculated light information of a mesh in a texture. + * @internal + */ + this._lightmapTexture = null; + /** + * The color of a material in ambient lighting. + * @internal + */ + this._ambientColor = new Color3(0, 0, 0); + /** + * AKA Diffuse Color in other nomenclature. + * @internal + */ + this._albedoColor = new Color3(1, 1, 1); + /** + * OpenPBR Base Weight (multiplier to the diffuse and metal lobes). + * @internal + */ + this._baseWeight = 1; + /** + * AKA Specular Color in other nomenclature. + * @internal + */ + this._reflectivityColor = new Color3(1, 1, 1); + /** + * The color applied when light is reflected from a material. + * @internal + */ + this._reflectionColor = new Color3(1, 1, 1); + /** + * The color applied when light is emitted from a material. + * @internal + */ + this._emissiveColor = new Color3(0, 0, 0); + /** + * AKA Glossiness in other nomenclature. + * @internal + */ + this._microSurface = 0.9; + /** + * Specifies that the material will use the light map as a show map. + * @internal + */ + this._useLightmapAsShadowmap = false; + /** + * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal + * makes the reflect vector face the model (under horizon). + * @internal + */ + this._useHorizonOcclusion = true; + /** + * This parameters will enable/disable radiance occlusion by preventing the radiance to lit + * too much the area relying on ambient texture to define their ambient occlusion. + * @internal + */ + this._useRadianceOcclusion = true; + /** + * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending. + * @internal + */ + this._useAlphaFromAlbedoTexture = false; + /** + * Specifies that the material will keeps the specular highlights over a transparent surface (only the most luminous ones). + * A car glass is a good example of that. When sun reflects on it you can not see what is behind. + * @internal + */ + this._useSpecularOverAlpha = true; + /** + * Specifies if the reflectivity texture contains the glossiness information in its alpha channel. + * @internal + */ + this._useMicroSurfaceFromReflectivityMapAlpha = false; + /** + * Specifies if the metallic texture contains the roughness information in its alpha channel. + * @internal + */ + this._useRoughnessFromMetallicTextureAlpha = true; + /** + * Specifies if the metallic texture contains the roughness information in its green channel. + * @internal + */ + this._useRoughnessFromMetallicTextureGreen = false; + /** + * Specifies if the metallic texture contains the metallness information in its blue channel. + * @internal + */ + this._useMetallnessFromMetallicTextureBlue = false; + /** + * Specifies if the metallic texture contains the ambient occlusion information in its red channel. + * @internal + */ + this._useAmbientOcclusionFromMetallicTextureRed = false; + /** + * Specifies if the ambient texture contains the ambient occlusion information in its red channel only. + * @internal + */ + this._useAmbientInGrayScale = false; + /** + * In case the reflectivity map does not contain the microsurface information in its alpha channel, + * The material will try to infer what glossiness each pixel should be. + * @internal + */ + this._useAutoMicroSurfaceFromReflectivityMap = false; + /** + * Defines the falloff type used in this material. + * It by default is Physical. + * @internal + */ + this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL; + /** + * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones). + * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind. + * @internal + */ + this._useRadianceOverAlpha = true; + /** + * Allows using an object space normal map (instead of tangent space). + * @internal + */ + this._useObjectSpaceNormalMap = false; + /** + * Allows using the bump map in parallax mode. + * @internal + */ + this._useParallax = false; + /** + * Allows using the bump map in parallax occlusion mode. + * @internal + */ + this._useParallaxOcclusion = false; + /** + * Controls the scale bias of the parallax mode. + * @internal + */ + this._parallaxScaleBias = 0.05; + /** + * If sets to true, disables all the lights affecting the material. + * @internal + */ + this._disableLighting = false; + /** + * Number of Simultaneous lights allowed on the material. + * @internal + */ + this._maxSimultaneousLights = 4; + /** + * If sets to true, x component of normal map value will be inverted (x = 1.0 - x). + * @internal + */ + this._invertNormalMapX = false; + /** + * If sets to true, y component of normal map value will be inverted (y = 1.0 - y). + * @internal + */ + this._invertNormalMapY = false; + /** + * If sets to true and backfaceCulling is false, normals will be flipped on the backside. + * @internal + */ + this._twoSidedLighting = false; + /** + * Defines the alpha limits in alpha test mode. + * @internal + */ + this._alphaCutOff = 0.4; + /** + * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. + * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel) + * @internal + */ + this._useAlphaFresnel = false; + /** + * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. + * And/Or occlude the blended part. (alpha stays linear to compute the fresnel) + * @internal + */ + this._useLinearAlphaFresnel = false; + /** + * Specifies the environment BRDF texture used to compute the scale and offset roughness values + * from cos theta and roughness: + * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf + * @internal + */ + this._environmentBRDFTexture = null; + /** + * Force the shader to compute irradiance in the fragment shader in order to take bump in account. + * @internal + */ + this._forceIrradianceInFragment = false; + this._realTimeFiltering = false; + this._realTimeFilteringQuality = 8; + /** + * Force normal to face away from face. + * @internal + */ + this._forceNormalForward = false; + /** + * Enables specular anti aliasing in the PBR shader. + * It will both interacts on the Geometry for analytical and IBL lighting. + * It also prefilter the roughness map based on the bump values. + * @internal + */ + this._enableSpecularAntiAliasing = false; + /** + * Keep track of the image processing observer to allow dispose and replace. + */ + this._imageProcessingObserver = null; + /** + * Stores the available render targets. + */ + this._renderTargets = new SmartArray(16); + /** + * Sets the global ambient color for the material used in lighting calculations. + */ + this._globalAmbientColor = new Color3(0, 0, 0); + /** + * If set to true, no lighting calculations will be applied. + */ + this._unlit = false; + /** + * If sets to true, the decal map will be applied after the detail map. Else, it is applied before (default: false) + */ + this._applyDecalMapAfterDetailMap = false; + this._debugMode = 0; + this._shadersLoaded = false; + this._breakShaderLoadedCheck = false; + /** + * @internal + * This is reserved for the inspector. + * Defines the material debug mode. + * It helps seeing only some components of the material while troubleshooting. + */ + this.debugMode = 0; + /** + * @internal + * This is reserved for the inspector. + * Specify from where on screen the debug mode should start. + * The value goes from -1 (full screen) to 1 (not visible) + * It helps with side by side comparison against the final render + * This defaults to -1 + */ + this.debugLimit = -1; + /** + * @internal + * This is reserved for the inspector. + * As the default viewing range might not be enough (if the ambient is really small for instance) + * You can use the factor to better multiply the final value. + */ + this.debugFactor = 1; + this._cacheHasRenderTargetTextures = false; + this.brdf = new PBRBRDFConfiguration(this); + this.clearCoat = new PBRClearCoatConfiguration(this); + this.iridescence = new PBRIridescenceConfiguration(this); + this.anisotropy = new PBRAnisotropicConfiguration(this); + this.sheen = new PBRSheenConfiguration(this); + this.subSurface = new PBRSubSurfaceConfiguration(this); + this.detailMap = new DetailMapConfiguration(this); + // Setup the default processing configuration to the scene. + this._attachImageProcessingConfiguration(null); + this.getRenderTargetTextures = () => { + this._renderTargets.reset(); + if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + this._renderTargets.push(this._reflectionTexture); + } + this._eventInfo.renderTargets = this._renderTargets; + this._callbackPluginEventFillRenderTargetTextures(this._eventInfo); + return this._renderTargets; + }; + this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene()); + this.prePassConfiguration = new PrePassConfiguration(); + } + /** + * Gets a boolean indicating that current material needs to register RTT + */ + get hasRenderTargetTextures() { + if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + return true; + } + return this._cacheHasRenderTargetTextures; + } + /** + * Can this material render to prepass + */ + get isPrePassCapable() { + return !this.disableDepthWrite; + } + /** + * @returns the name of the material class. + */ + getClassName() { + return "PBRBaseMaterial"; + } + /** + * Returns true if alpha blending should be disabled. + */ + get _disableAlphaBlending() { + return (this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_OPAQUE || + this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST || + this.subSurface?.disableAlphaBlending); + } + /** + * @returns whether or not this material should be rendered in alpha blend mode. + */ + needAlphaBlending() { + if (this._hasTransparencyMode) { + return this._transparencyModeIsBlend; + } + if (this._disableAlphaBlending) { + return false; + } + return this.alpha < 1.0 || this._opacityTexture != null || this._shouldUseAlphaFromAlbedoTexture(); + } + /** + * @returns whether or not this material should be rendered in alpha test mode. + */ + needAlphaTesting() { + if (this._hasTransparencyMode) { + return this._transparencyModeIsTest; + } + if (this.subSurface?.disableAlphaBlending) { + return false; + } + return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST); + } + /** + * @returns whether or not the alpha value of the albedo texture should be used for alpha blending. + */ + _shouldUseAlphaFromAlbedoTexture() { + return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE; + } + /** + * @returns whether or not there is a usable alpha channel for transparency. + */ + _hasAlphaChannel() { + return (this._albedoTexture != null && this._albedoTexture.hasAlpha) || this._opacityTexture != null; + } + /** + * @returns the texture used for the alpha test. + */ + getAlphaTestTexture() { + return this._albedoTexture; + } + /** + * Specifies that the submesh is ready to be used. + * @param mesh - BJS mesh. + * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready. + * @param useInstances - Specifies that instances should be used. + * @returns - boolean indicating that the submesh is ready or not. + */ + isReadyForSubMesh(mesh, subMesh, useInstances) { + if (!this._uniformBufferLayoutBuilt) { + this.buildUniformLayout(); + } + const drawWrapper = subMesh._drawWrapper; + if (drawWrapper.effect && this.isFrozen) { + if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) { + return true; + } + } + if (!subMesh.materialDefines) { + this._callbackPluginEventGeneric(4 /* MaterialPluginEvent.GetDefineNames */, this._eventInfo); + subMesh.materialDefines = new PBRMaterialDefines(this._eventInfo.defineNames); + } + const defines = subMesh.materialDefines; + if (this._isReadyForSubMesh(subMesh)) { + return true; + } + const scene = this.getScene(); + const engine = scene.getEngine(); + if (defines._areTexturesDirty) { + this._eventInfo.hasRenderTargetTextures = false; + this._callbackPluginEventHasRenderTargetTextures(this._eventInfo); + this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures; + if (scene.texturesEnabled) { + if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) { + if (!this._albedoTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) { + if (!this._baseWeightTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) { + if (!this._ambientTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) { + if (!this._opacityTexture.isReadyOrNotBlocking()) { + return false; + } + } + const reflectionTexture = this._getReflectionTexture(); + if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { + if (!reflectionTexture.isReadyOrNotBlocking()) { + return false; + } + if (reflectionTexture.irradianceTexture) { + if (!reflectionTexture.irradianceTexture.isReadyOrNotBlocking()) { + return false; + } + } + else { + // Not ready until spherical are ready too. + if (!reflectionTexture.sphericalPolynomial && reflectionTexture.getInternalTexture()?._sphericalPolynomialPromise) { + return false; + } + } + } + if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) { + if (!this._lightmapTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) { + if (!this._emissiveTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (MaterialFlags.SpecularTextureEnabled) { + if (this._metallicTexture) { + if (!this._metallicTexture.isReadyOrNotBlocking()) { + return false; + } + } + else if (this._reflectivityTexture) { + if (!this._reflectivityTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._metallicReflectanceTexture) { + if (!this._metallicReflectanceTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._reflectanceTexture) { + if (!this._reflectanceTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._microSurfaceTexture) { + if (!this._microSurfaceTexture.isReadyOrNotBlocking()) { + return false; + } + } + } + if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) { + // Bump texture cannot be not blocking. + if (!this._bumpTexture.isReady()) { + return false; + } + } + if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) { + // This is blocking. + if (!this._environmentBRDFTexture.isReady()) { + return false; + } + } + } + } + this._eventInfo.isReadyForSubMesh = true; + this._eventInfo.defines = defines; + this._eventInfo.subMesh = subMesh; + this._callbackPluginEventIsReadyForSubMesh(this._eventInfo); + if (!this._eventInfo.isReadyForSubMesh) { + return false; + } + if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { + if (!this._imageProcessingConfiguration.isReady()) { + return false; + } + } + // Check if Area Lights have LTC texture. + if (defines["AREALIGHTUSED"]) { + for (let index = 0; index < mesh.lightSources.length; index++) { + if (!mesh.lightSources[index]._isReady()) { + return false; + } + } + } + if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) { + mesh.createNormals(true); + Logger.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name); + } + const previousEffect = subMesh.effect; + const lightDisposed = defines._areLightsDisposed; + let effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances, null, subMesh.getRenderingMesh().hasThinInstances); + let forceWasNotReadyPreviously = false; + if (effect) { + if (this._onEffectCreatedObservable) { + onCreatedEffectParameters$1.effect = effect; + onCreatedEffectParameters$1.subMesh = subMesh; + this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$1); + } + // Use previous effect while new one is compiling + if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) { + effect = previousEffect; + defines.markAsUnprocessed(); + forceWasNotReadyPreviously = this.isFrozen; + if (lightDisposed) { + // re register in case it takes more than one frame. + defines._areLightsDisposed = true; + return false; + } + } + else { + scene.resetCachedMaterial(); + subMesh.setEffect(effect, defines, this._materialContext); + } + } + if (!subMesh.effect || !subMesh.effect.isReady()) { + return false; + } + defines._renderId = scene.getRenderId(); + drawWrapper._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true; + drawWrapper._wasPreviouslyUsingInstances = !!useInstances; + this._checkScenePerformancePriority(); + return true; + } + /** + * Specifies if the material uses metallic roughness workflow. + * @returns boolean specifying if the material uses metallic roughness workflow. + */ + isMetallicWorkflow() { + if (this._metallic != null || this._roughness != null || this._metallicTexture) { + return true; + } + return false; + } + _prepareEffect(mesh, defines, onCompiled = null, onError = null, useInstances = null, useClipPlane = null, useThinInstances) { + this._prepareDefines(mesh, defines, useInstances, useClipPlane, useThinInstances); + if (!defines.isDirty) { + return null; + } + defines.markAsProcessed(); + const scene = this.getScene(); + const engine = scene.getEngine(); + // Fallbacks + const fallbacks = new EffectFallbacks(); + let fallbackRank = 0; + if (defines.USESPHERICALINVERTEX) { + fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX"); + } + if (defines.FOG) { + fallbacks.addFallback(fallbackRank, "FOG"); + } + if (defines.SPECULARAA) { + fallbacks.addFallback(fallbackRank, "SPECULARAA"); + } + if (defines.POINTSIZE) { + fallbacks.addFallback(fallbackRank, "POINTSIZE"); + } + if (defines.LOGARITHMICDEPTH) { + fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH"); + } + if (defines.PARALLAX) { + fallbacks.addFallback(fallbackRank, "PARALLAX"); + } + if (defines.PARALLAX_RHS) { + fallbacks.addFallback(fallbackRank, "PARALLAX_RHS"); + } + if (defines.PARALLAXOCCLUSION) { + fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION"); + } + if (defines.ENVIRONMENTBRDF) { + fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF"); + } + if (defines.TANGENT) { + fallbacks.addFallback(fallbackRank++, "TANGENT"); + } + if (defines.BUMP) { + fallbacks.addFallback(fallbackRank++, "BUMP"); + } + fallbackRank = HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++); + if (defines.SPECULARTERM) { + fallbacks.addFallback(fallbackRank++, "SPECULARTERM"); + } + if (defines.USESPHERICALFROMREFLECTIONMAP) { + fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP"); + } + if (defines.USEIRRADIANCEMAP) { + fallbacks.addFallback(fallbackRank++, "USEIRRADIANCEMAP"); + } + if (defines.LIGHTMAP) { + fallbacks.addFallback(fallbackRank++, "LIGHTMAP"); + } + if (defines.NORMAL) { + fallbacks.addFallback(fallbackRank++, "NORMAL"); + } + if (defines.AMBIENT) { + fallbacks.addFallback(fallbackRank++, "AMBIENT"); + } + if (defines.EMISSIVE) { + fallbacks.addFallback(fallbackRank++, "EMISSIVE"); + } + if (defines.VERTEXCOLOR) { + fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR"); + } + if (defines.MORPHTARGETS) { + fallbacks.addFallback(fallbackRank++, "MORPHTARGETS"); + } + if (defines.MULTIVIEW) { + fallbacks.addFallback(0, "MULTIVIEW"); + } + //Attributes + const attribs = [VertexBuffer.PositionKind]; + if (defines.NORMAL) { + attribs.push(VertexBuffer.NormalKind); + } + if (defines.TANGENT) { + attribs.push(VertexBuffer.TangentKind); + } + for (let i = 1; i <= 6; ++i) { + if (defines["UV" + i]) { + attribs.push(`uv${i === 1 ? "" : i}`); + } + } + if (defines.VERTEXCOLOR) { + attribs.push(VertexBuffer.ColorKind); + } + PrepareAttributesForBones(attribs, mesh, defines, fallbacks); + PrepareAttributesForInstances(attribs, defines); + PrepareAttributesForMorphTargets(attribs, mesh, defines); + PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines); + let shaderName = "pbr"; + const uniforms = [ + "world", + "view", + "viewProjection", + "vEyePosition", + "vLightsType", + "vAmbientColor", + "vAlbedoColor", + "baseWeight", + "vReflectivityColor", + "vMetallicReflectanceFactors", + "vEmissiveColor", + "visibility", + "vReflectionColor", + "vFogInfos", + "vFogColor", + "pointSize", + "vAlbedoInfos", + "vBaseWeightInfos", + "vAmbientInfos", + "vOpacityInfos", + "vReflectionInfos", + "vReflectionPosition", + "vReflectionSize", + "vEmissiveInfos", + "vReflectivityInfos", + "vReflectionFilteringInfo", + "vMetallicReflectanceInfos", + "vReflectanceInfos", + "vMicroSurfaceSamplerInfos", + "vBumpInfos", + "vLightmapInfos", + "mBones", + "albedoMatrix", + "baseWeightMatrix", + "ambientMatrix", + "opacityMatrix", + "reflectionMatrix", + "emissiveMatrix", + "reflectivityMatrix", + "normalMatrix", + "microSurfaceSamplerMatrix", + "bumpMatrix", + "lightmapMatrix", + "metallicReflectanceMatrix", + "reflectanceMatrix", + "vLightingIntensity", + "logarithmicDepthConstant", + "vSphericalX", + "vSphericalY", + "vSphericalZ", + "vSphericalXX_ZZ", + "vSphericalYY_ZZ", + "vSphericalZZ", + "vSphericalXY", + "vSphericalYZ", + "vSphericalZX", + "vSphericalL00", + "vSphericalL1_1", + "vSphericalL10", + "vSphericalL11", + "vSphericalL2_2", + "vSphericalL2_1", + "vSphericalL20", + "vSphericalL21", + "vSphericalL22", + "vReflectionMicrosurfaceInfos", + "vTangentSpaceParams", + "boneTextureWidth", + "vDebugMode", + "morphTargetTextureInfo", + "morphTargetTextureIndices", + ]; + const samplers = [ + "albedoSampler", + "baseWeightSampler", + "reflectivitySampler", + "ambientSampler", + "emissiveSampler", + "bumpSampler", + "lightmapSampler", + "opacitySampler", + "reflectionSampler", + "reflectionSamplerLow", + "reflectionSamplerHigh", + "irradianceSampler", + "microSurfaceSampler", + "environmentBrdfSampler", + "boneSampler", + "metallicReflectanceSampler", + "reflectanceSampler", + "morphTargets", + "oitDepthSampler", + "oitFrontColorSampler", + "icdfSampler", + "areaLightsLTC1Sampler", + "areaLightsLTC2Sampler", + ]; + const uniformBuffers = ["Material", "Scene", "Mesh"]; + const indexParameters = { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }; + this._eventInfo.fallbacks = fallbacks; + this._eventInfo.fallbackRank = fallbackRank; + this._eventInfo.defines = defines; + this._eventInfo.uniforms = uniforms; + this._eventInfo.attributes = attribs; + this._eventInfo.samplers = samplers; + this._eventInfo.uniformBuffersNames = uniformBuffers; + this._eventInfo.customCode = undefined; + this._eventInfo.mesh = mesh; + this._eventInfo.indexParameters = indexParameters; + this._callbackPluginEventGeneric(128 /* MaterialPluginEvent.PrepareEffect */, this._eventInfo); + MaterialHelperGeometryRendering.AddUniformsAndSamplers(uniforms, samplers); + PrePassConfiguration.AddUniforms(uniforms); + addClipPlaneUniforms(uniforms); + if (ImageProcessingConfiguration) { + ImageProcessingConfiguration.PrepareUniforms(uniforms, defines); + ImageProcessingConfiguration.PrepareSamplers(samplers, defines); + } + PrepareUniformsAndSamplersList({ + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: defines, + maxSimultaneousLights: this._maxSimultaneousLights, + }); + const csnrOptions = {}; + if (this.customShaderNameResolve) { + shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions); + } + const join = defines.toString(); + const effect = engine.createEffect(shaderName, { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: join, + fallbacks: fallbacks, + onCompiled: onCompiled, + onError: onError, + indexParameters, + processFinalCode: csnrOptions.processFinalCode, + processCodeAfterIncludes: this._eventInfo.customCode, + multiTarget: defines.PREPASS, + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: this._shadersLoaded + ? undefined + : async () => { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => pbr_vertex$1), Promise.resolve().then(() => pbr_fragment$1)]); + } + else { + await Promise.all([Promise.resolve().then(() => pbr_vertex), Promise.resolve().then(() => pbr_fragment)]); + } + this._shadersLoaded = true; + }, + }, engine); + this._eventInfo.customCode = undefined; + return effect; + } + _prepareDefines(mesh, defines, useInstances = null, useClipPlane = null, useThinInstances = false) { + const scene = this.getScene(); + const engine = scene.getEngine(); + // Lights + PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting); + defines._needNormals = true; + // Multiview + PrepareDefinesForMultiview(scene, defines); + // PrePass + const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency; + PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit); + // Order independant transparency + PrepareDefinesForOIT(scene, defines, oit); + MaterialHelperGeometryRendering.PrepareDefines(engine.currentRenderPassId, mesh, defines); + // Textures + defines.METALLICWORKFLOW = this.isMetallicWorkflow(); + if (defines._areTexturesDirty) { + defines._needUVs = false; + for (let i = 1; i <= 6; ++i) { + defines["MAINUV" + i] = false; + } + if (scene.texturesEnabled) { + defines.ALBEDODIRECTUV = 0; + defines.BASEWEIGHTDIRECTUV = 0; + defines.AMBIENTDIRECTUV = 0; + defines.OPACITYDIRECTUV = 0; + defines.EMISSIVEDIRECTUV = 0; + defines.REFLECTIVITYDIRECTUV = 0; + defines.MICROSURFACEMAPDIRECTUV = 0; + defines.METALLIC_REFLECTANCEDIRECTUV = 0; + defines.REFLECTANCEDIRECTUV = 0; + defines.BUMPDIRECTUV = 0; + defines.LIGHTMAPDIRECTUV = 0; + if (engine.getCaps().textureLOD) { + defines.LODBASEDMICROSFURACE = true; + } + if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) { + PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO"); + defines.GAMMAALBEDO = this._albedoTexture.gammaSpace; + } + else { + defines.ALBEDO = false; + } + if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) { + PrepareDefinesForMergedUV(this._baseWeightTexture, defines, "BASEWEIGHT"); + } + else { + defines.BASEWEIGHT = false; + } + if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) { + PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT"); + defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale; + } + else { + defines.AMBIENT = false; + } + if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) { + PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY"); + defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB; + } + else { + defines.OPACITY = false; + } + const reflectionTexture = this._getReflectionTexture(); + if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { + defines.REFLECTION = true; + defines.GAMMAREFLECTION = reflectionTexture.gammaSpace; + defines.RGBDREFLECTION = reflectionTexture.isRGBD; + defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha; + defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD; + if (this.realTimeFiltering && this.realTimeFilteringQuality > 0) { + defines.NUM_SAMPLES = "" + this.realTimeFilteringQuality; + if (engine._features.needTypeSuffixInShaderConstants) { + defines.NUM_SAMPLES = defines.NUM_SAMPLES + "u"; + } + defines.REALTIME_FILTERING = true; + if (this.getScene().iblCdfGenerator) { + defines.IBL_CDF_FILTERING = true; + } + } + else { + defines.REALTIME_FILTERING = false; + } + defines.INVERTCUBICMAP = reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE; + defines.REFLECTIONMAP_3D = reflectionTexture.isCube; + defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ; + defines.REFLECTIONMAP_CUBIC = false; + defines.REFLECTIONMAP_EXPLICIT = false; + defines.REFLECTIONMAP_PLANAR = false; + defines.REFLECTIONMAP_PROJECTION = false; + defines.REFLECTIONMAP_SKYBOX = false; + defines.REFLECTIONMAP_SPHERICAL = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + switch (reflectionTexture.coordinatesMode) { + case Texture.EXPLICIT_MODE: + defines.REFLECTIONMAP_EXPLICIT = true; + break; + case Texture.PLANAR_MODE: + defines.REFLECTIONMAP_PLANAR = true; + break; + case Texture.PROJECTION_MODE: + defines.REFLECTIONMAP_PROJECTION = true; + break; + case Texture.SKYBOX_MODE: + defines.REFLECTIONMAP_SKYBOX = true; + break; + case Texture.SPHERICAL_MODE: + defines.REFLECTIONMAP_SPHERICAL = true; + break; + case Texture.EQUIRECTANGULAR_MODE: + defines.REFLECTIONMAP_EQUIRECTANGULAR = true; + break; + case Texture.FIXED_EQUIRECTANGULAR_MODE: + defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true; + break; + case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE: + defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true; + break; + case Texture.CUBIC_MODE: + case Texture.INVCUBIC_MODE: + default: + defines.REFLECTIONMAP_CUBIC = true; + defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false; + break; + } + if (reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) { + if (reflectionTexture.irradianceTexture) { + defines.USEIRRADIANCEMAP = true; + defines.USESPHERICALFROMREFLECTIONMAP = false; + defines.USESPHERICALINVERTEX = false; + } + // Assume using spherical polynomial if the reflection texture is a cube map + else if (reflectionTexture.isCube) { + defines.USESPHERICALFROMREFLECTIONMAP = true; + defines.USEIRRADIANCEMAP = false; + if (this._forceIrradianceInFragment || this.realTimeFiltering || this._twoSidedLighting || engine.getCaps().maxVaryingVectors <= 8) { + defines.USESPHERICALINVERTEX = false; + } + else { + defines.USESPHERICALINVERTEX = true; + } + } + } + } + else { + defines.REFLECTION = false; + defines.REFLECTIONMAP_3D = false; + defines.REFLECTIONMAP_SPHERICAL = false; + defines.REFLECTIONMAP_PLANAR = false; + defines.REFLECTIONMAP_CUBIC = false; + defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false; + defines.REFLECTIONMAP_PROJECTION = false; + defines.REFLECTIONMAP_SKYBOX = false; + defines.REFLECTIONMAP_EXPLICIT = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + defines.INVERTCUBICMAP = false; + defines.USESPHERICALFROMREFLECTIONMAP = false; + defines.USEIRRADIANCEMAP = false; + defines.USESPHERICALINVERTEX = false; + defines.REFLECTIONMAP_OPPOSITEZ = false; + defines.LODINREFLECTIONALPHA = false; + defines.GAMMAREFLECTION = false; + defines.RGBDREFLECTION = false; + defines.LINEARSPECULARREFLECTION = false; + } + if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) { + PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP"); + defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap; + defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace; + defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD; + } + else { + defines.LIGHTMAP = false; + } + if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) { + PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE"); + defines.GAMMAEMISSIVE = this._emissiveTexture.gammaSpace; + } + else { + defines.EMISSIVE = false; + } + if (MaterialFlags.SpecularTextureEnabled) { + if (this._metallicTexture) { + PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY"); + defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha; + defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen; + defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue; + defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed; + defines.REFLECTIVITY_GAMMA = false; + } + else if (this._reflectivityTexture) { + PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY"); + defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha; + defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap; + defines.REFLECTIVITY_GAMMA = this._reflectivityTexture.gammaSpace; + } + else { + defines.REFLECTIVITY = false; + } + if (this._metallicReflectanceTexture || this._reflectanceTexture) { + defines.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = this._useOnlyMetallicFromMetallicReflectanceTexture; + if (this._metallicReflectanceTexture) { + PrepareDefinesForMergedUV(this._metallicReflectanceTexture, defines, "METALLIC_REFLECTANCE"); + defines.METALLIC_REFLECTANCE_GAMMA = this._metallicReflectanceTexture.gammaSpace; + } + else { + defines.METALLIC_REFLECTANCE = false; + } + if (this._reflectanceTexture && + (!this._metallicReflectanceTexture || (this._metallicReflectanceTexture && this._useOnlyMetallicFromMetallicReflectanceTexture))) { + PrepareDefinesForMergedUV(this._reflectanceTexture, defines, "REFLECTANCE"); + defines.REFLECTANCE_GAMMA = this._reflectanceTexture.gammaSpace; + } + else { + defines.REFLECTANCE = false; + } + } + else { + defines.METALLIC_REFLECTANCE = false; + defines.REFLECTANCE = false; + } + if (this._microSurfaceTexture) { + PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP"); + } + else { + defines.MICROSURFACEMAP = false; + } + } + else { + defines.REFLECTIVITY = false; + defines.MICROSURFACEMAP = false; + } + if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) { + PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP"); + if (this._useParallax && this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) { + defines.PARALLAX = true; + defines.PARALLAX_RHS = scene.useRightHandedSystem; + defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion; + } + else { + defines.PARALLAX = false; + } + defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap; + } + else { + defines.BUMP = false; + defines.PARALLAX = false; + defines.PARALLAX_RHS = false; + defines.PARALLAXOCCLUSION = false; + defines.OBJECTSPACE_NORMALMAP = false; + } + if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) { + defines.ENVIRONMENTBRDF = true; + defines.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD; + } + else { + defines.ENVIRONMENTBRDF = false; + defines.ENVIRONMENTBRDF_RGBD = false; + } + if (this._shouldUseAlphaFromAlbedoTexture()) { + defines.ALPHAFROMALBEDO = true; + } + else { + defines.ALPHAFROMALBEDO = false; + } + } + defines.SPECULAROVERALPHA = this._useSpecularOverAlpha; + if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) { + defines.USEPHYSICALLIGHTFALLOFF = false; + defines.USEGLTFLIGHTFALLOFF = false; + } + else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) { + defines.USEPHYSICALLIGHTFALLOFF = false; + defines.USEGLTFLIGHTFALLOFF = true; + } + else { + defines.USEPHYSICALLIGHTFALLOFF = true; + defines.USEGLTFLIGHTFALLOFF = false; + } + defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha; + if (!this.backFaceCulling && this._twoSidedLighting) { + defines.TWOSIDEDLIGHTING = true; + } + else { + defines.TWOSIDEDLIGHTING = false; + } + defines.SPECULARAA = engine.getCaps().standardDerivatives && this._enableSpecularAntiAliasing; + } + if (defines._areTexturesDirty || defines._areMiscDirty) { + defines.ALPHATESTVALUE = `${this._alphaCutOff}${this._alphaCutOff % 1 === 0 ? "." : ""}`; + defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8; + defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh); + defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel; + defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel; + } + if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { + this._imageProcessingConfiguration.prepareDefines(defines); + } + defines.FORCENORMALFORWARD = this._forceNormalForward; + defines.RADIANCEOCCLUSION = this._useRadianceOcclusion; + defines.HORIZONOCCLUSION = this._useHorizonOcclusion; + // Misc. + if (defines._areMiscDirty) { + PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this.needAlphaTestingForMesh(mesh), defines, this._applyDecalMapAfterDetailMap); + defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)); + defines.DEBUGMODE = this._debugMode; + } + // Values that need to be evaluated on every frame + PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances ? true : false, useClipPlane, useThinInstances); + // External config + this._eventInfo.defines = defines; + this._eventInfo.mesh = mesh; + this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo); + // Attribs + PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE); + // External config + this._callbackPluginEventPrepareDefines(this._eventInfo); + } + /** + * Force shader compilation + * @param mesh - Define the mesh we want to force the compilation for + * @param onCompiled - Define a callback triggered when the compilation completes + * @param options - Define the options used to create the compilation + */ + forceCompilation(mesh, onCompiled, options) { + const localOptions = { + clipPlane: false, + useInstances: false, + ...options, + }; + if (!this._uniformBufferLayoutBuilt) { + this.buildUniformLayout(); + } + this._callbackPluginEventGeneric(4 /* MaterialPluginEvent.GetDefineNames */, this._eventInfo); + const checkReady = () => { + if (this._breakShaderLoadedCheck) { + return; + } + const defines = new PBRMaterialDefines(this._eventInfo.defineNames); + const effect = this._prepareEffect(mesh, defines, undefined, undefined, localOptions.useInstances, localOptions.clipPlane, mesh.hasThinInstances); + if (this._onEffectCreatedObservable) { + onCreatedEffectParameters$1.effect = effect; + onCreatedEffectParameters$1.subMesh = null; + this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$1); + } + if (effect.isReady()) { + if (onCompiled) { + onCompiled(this); + } + } + else { + effect.onCompileObservable.add(() => { + if (onCompiled) { + onCompiled(this); + } + }); + } + }; + checkReady(); + } + /** + * Initializes the uniform buffer layout for the shader. + */ + buildUniformLayout() { + // Order is important ! + const ubo = this._uniformBuffer; + ubo.addUniform("vAlbedoInfos", 2); + ubo.addUniform("vBaseWeightInfos", 2); + ubo.addUniform("vAmbientInfos", 4); + ubo.addUniform("vOpacityInfos", 2); + ubo.addUniform("vEmissiveInfos", 2); + ubo.addUniform("vLightmapInfos", 2); + ubo.addUniform("vReflectivityInfos", 3); + ubo.addUniform("vMicroSurfaceSamplerInfos", 2); + ubo.addUniform("vReflectionInfos", 2); + ubo.addUniform("vReflectionFilteringInfo", 2); + ubo.addUniform("vReflectionPosition", 3); + ubo.addUniform("vReflectionSize", 3); + ubo.addUniform("vBumpInfos", 3); + ubo.addUniform("albedoMatrix", 16); + ubo.addUniform("baseWeightMatrix", 16); + ubo.addUniform("ambientMatrix", 16); + ubo.addUniform("opacityMatrix", 16); + ubo.addUniform("emissiveMatrix", 16); + ubo.addUniform("lightmapMatrix", 16); + ubo.addUniform("reflectivityMatrix", 16); + ubo.addUniform("microSurfaceSamplerMatrix", 16); + ubo.addUniform("bumpMatrix", 16); + ubo.addUniform("vTangentSpaceParams", 2); + ubo.addUniform("reflectionMatrix", 16); + ubo.addUniform("vReflectionColor", 3); + ubo.addUniform("vAlbedoColor", 4); + ubo.addUniform("baseWeight", 1); + ubo.addUniform("vLightingIntensity", 4); + ubo.addUniform("vReflectionMicrosurfaceInfos", 3); + ubo.addUniform("pointSize", 1); + ubo.addUniform("vReflectivityColor", 4); + ubo.addUniform("vEmissiveColor", 3); + ubo.addUniform("vAmbientColor", 3); + ubo.addUniform("vDebugMode", 2); + ubo.addUniform("vMetallicReflectanceFactors", 4); + ubo.addUniform("vMetallicReflectanceInfos", 2); + ubo.addUniform("metallicReflectanceMatrix", 16); + ubo.addUniform("vReflectanceInfos", 2); + ubo.addUniform("reflectanceMatrix", 16); + ubo.addUniform("vSphericalL00", 3); + ubo.addUniform("vSphericalL1_1", 3); + ubo.addUniform("vSphericalL10", 3); + ubo.addUniform("vSphericalL11", 3); + ubo.addUniform("vSphericalL2_2", 3); + ubo.addUniform("vSphericalL2_1", 3); + ubo.addUniform("vSphericalL20", 3); + ubo.addUniform("vSphericalL21", 3); + ubo.addUniform("vSphericalL22", 3); + ubo.addUniform("vSphericalX", 3); + ubo.addUniform("vSphericalY", 3); + ubo.addUniform("vSphericalZ", 3); + ubo.addUniform("vSphericalXX_ZZ", 3); + ubo.addUniform("vSphericalYY_ZZ", 3); + ubo.addUniform("vSphericalZZ", 3); + ubo.addUniform("vSphericalXY", 3); + ubo.addUniform("vSphericalYZ", 3); + ubo.addUniform("vSphericalZX", 3); + super.buildUniformLayout(); + } + /** + * Binds the submesh data. + * @param world - The world matrix. + * @param mesh - The BJS mesh. + * @param subMesh - A submesh of the BJS mesh. + */ + bindForSubMesh(world, mesh, subMesh) { + const scene = this.getScene(); + const defines = subMesh.materialDefines; + if (!defines) { + return; + } + const effect = subMesh.effect; + if (!effect) { + return; + } + this._activeEffect = effect; + // Matrices Mesh. + mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); + mesh.transferToEffect(world); + const engine = scene.getEngine(); + // Binding unconditionally + this._uniformBuffer.bindToEffect(effect, "Material"); + this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen); + MaterialHelperGeometryRendering.Bind(engine.currentRenderPassId, this._activeEffect, mesh, world, this); + this._eventInfo.subMesh = subMesh; + this._callbackPluginEventHardBindForSubMesh(this._eventInfo); + // Normal Matrix + if (defines.OBJECTSPACE_NORMALMAP) { + world.toNormalMatrix(this._normalMatrix); + this.bindOnlyNormalMatrix(this._normalMatrix); + } + const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility); + // Bones + BindBonesParameters(mesh, this._activeEffect, this.prePassConfiguration); + let reflectionTexture = null; + const ubo = this._uniformBuffer; + if (mustRebind) { + this.bindViewProjection(effect); + reflectionTexture = this._getReflectionTexture(); + if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || subMesh._drawWrapper._forceRebindOnNextCall) { + // Texture uniforms + if (scene.texturesEnabled) { + if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) { + ubo.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level); + BindTextureMatrix(this._albedoTexture, ubo, "albedo"); + } + if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) { + ubo.updateFloat2("vBaseWeightInfos", this._baseWeightTexture.coordinatesIndex, this._baseWeightTexture.level); + BindTextureMatrix(this._baseWeightTexture, ubo, "baseWeight"); + } + if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) { + ubo.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights); + BindTextureMatrix(this._ambientTexture, ubo, "ambient"); + } + if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) { + ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level); + BindTextureMatrix(this._opacityTexture, ubo, "opacity"); + } + if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { + ubo.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix()); + ubo.updateFloat2("vReflectionInfos", reflectionTexture.level * scene.iblIntensity, 0); + if (reflectionTexture.boundingBoxSize) { + const cubeTexture = reflectionTexture; + ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition); + ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize); + } + if (this.realTimeFiltering) { + const width = reflectionTexture.getSize().width; + ubo.updateFloat2("vReflectionFilteringInfo", width, Math.log2(width)); + } + if (!defines.USEIRRADIANCEMAP) { + const polynomials = reflectionTexture.sphericalPolynomial; + if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) { + if (defines.SPHERICAL_HARMONICS) { + const preScaledHarmonics = polynomials.preScaledHarmonics; + ubo.updateVector3("vSphericalL00", preScaledHarmonics.l00); + ubo.updateVector3("vSphericalL1_1", preScaledHarmonics.l1_1); + ubo.updateVector3("vSphericalL10", preScaledHarmonics.l10); + ubo.updateVector3("vSphericalL11", preScaledHarmonics.l11); + ubo.updateVector3("vSphericalL2_2", preScaledHarmonics.l2_2); + ubo.updateVector3("vSphericalL2_1", preScaledHarmonics.l2_1); + ubo.updateVector3("vSphericalL20", preScaledHarmonics.l20); + ubo.updateVector3("vSphericalL21", preScaledHarmonics.l21); + ubo.updateVector3("vSphericalL22", preScaledHarmonics.l22); + } + else { + ubo.updateFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z); + ubo.updateFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z); + ubo.updateFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z); + ubo.updateFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z); + ubo.updateFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z); + ubo.updateFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z); + ubo.updateFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z); + ubo.updateFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z); + ubo.updateFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z); + } + } + } + ubo.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); + } + if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) { + ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level); + BindTextureMatrix(this._emissiveTexture, ubo, "emissive"); + } + if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) { + ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level); + BindTextureMatrix(this._lightmapTexture, ubo, "lightmap"); + } + if (MaterialFlags.SpecularTextureEnabled) { + if (this._metallicTexture) { + ubo.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength); + BindTextureMatrix(this._metallicTexture, ubo, "reflectivity"); + } + else if (this._reflectivityTexture) { + ubo.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0); + BindTextureMatrix(this._reflectivityTexture, ubo, "reflectivity"); + } + if (this._metallicReflectanceTexture) { + ubo.updateFloat2("vMetallicReflectanceInfos", this._metallicReflectanceTexture.coordinatesIndex, this._metallicReflectanceTexture.level); + BindTextureMatrix(this._metallicReflectanceTexture, ubo, "metallicReflectance"); + } + if (this._reflectanceTexture && defines.REFLECTANCE) { + ubo.updateFloat2("vReflectanceInfos", this._reflectanceTexture.coordinatesIndex, this._reflectanceTexture.level); + BindTextureMatrix(this._reflectanceTexture, ubo, "reflectance"); + } + if (this._microSurfaceTexture) { + ubo.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level); + BindTextureMatrix(this._microSurfaceTexture, ubo, "microSurfaceSampler"); + } + } + if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) { + ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias); + BindTextureMatrix(this._bumpTexture, ubo, "bump"); + if (scene._mirroredCameraPosition) { + ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1, this._invertNormalMapY ? 1.0 : -1); + } + else { + ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1.0, this._invertNormalMapY ? -1 : 1.0); + } + } + } + // Point size + if (this.pointsCloud) { + ubo.updateFloat("pointSize", this.pointSize); + } + // Colors + if (defines.METALLICWORKFLOW) { + TmpColors.Color3[0].r = this._metallic === undefined || this._metallic === null ? 1 : this._metallic; + TmpColors.Color3[0].g = this._roughness === undefined || this._roughness === null ? 1 : this._roughness; + ubo.updateColor4("vReflectivityColor", TmpColors.Color3[0], 1); + const ior = this.subSurface?._indexOfRefraction ?? 1.5; + const outsideIOR = 1; // consider air as clear coat and other layers would remap in the shader. + // We are here deriving our default reflectance from a common value for none metallic surface. + // Based of the schlick fresnel approximation model + // for dielectrics. + const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2); + // Tweak the default F0 and F90 based on our given setup + this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]); + const metallicF90 = this._metallicF0Factor; + ubo.updateColor4("vMetallicReflectanceFactors", TmpColors.Color3[0], metallicF90); + } + else { + ubo.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface); + } + ubo.updateColor3("vEmissiveColor", MaterialFlags.EmissiveTextureEnabled ? this._emissiveColor : Color3.BlackReadOnly); + ubo.updateColor3("vReflectionColor", this._reflectionColor); + if (!defines.SS_REFRACTION && this.subSurface?._linkRefractionWithTransparency) { + ubo.updateColor4("vAlbedoColor", this._albedoColor, 1); + } + else { + ubo.updateColor4("vAlbedoColor", this._albedoColor, this.alpha); + } + ubo.updateFloat("baseWeight", this._baseWeight); + // Misc + this._lightingInfos.x = this._directIntensity; + this._lightingInfos.y = this._emissiveIntensity; + this._lightingInfos.z = this._environmentIntensity * scene.environmentIntensity; + this._lightingInfos.w = this._specularIntensity; + ubo.updateVector4("vLightingIntensity", this._lightingInfos); + // Colors + scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor); + ubo.updateColor3("vAmbientColor", this._globalAmbientColor); + ubo.updateFloat2("vDebugMode", this.debugLimit, this.debugFactor); + } + // Textures + if (scene.texturesEnabled) { + if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) { + ubo.setTexture("albedoSampler", this._albedoTexture); + } + if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) { + ubo.setTexture("baseWeightSampler", this._baseWeightTexture); + } + if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) { + ubo.setTexture("ambientSampler", this._ambientTexture); + } + if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) { + ubo.setTexture("opacitySampler", this._opacityTexture); + } + if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { + if (defines.LODBASEDMICROSFURACE) { + ubo.setTexture("reflectionSampler", reflectionTexture); + } + else { + ubo.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture); + ubo.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture); + ubo.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture); + } + if (defines.USEIRRADIANCEMAP) { + ubo.setTexture("irradianceSampler", reflectionTexture.irradianceTexture); + } + //if realtime filtering and using CDF maps, set them. + const cdfGenerator = this.getScene().iblCdfGenerator; + if (this.realTimeFiltering && cdfGenerator) { + ubo.setTexture("icdfSampler", cdfGenerator.getIcdfTexture()); + } + } + if (defines.ENVIRONMENTBRDF) { + ubo.setTexture("environmentBrdfSampler", this._environmentBRDFTexture); + } + if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) { + ubo.setTexture("emissiveSampler", this._emissiveTexture); + } + if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) { + ubo.setTexture("lightmapSampler", this._lightmapTexture); + } + if (MaterialFlags.SpecularTextureEnabled) { + if (this._metallicTexture) { + ubo.setTexture("reflectivitySampler", this._metallicTexture); + } + else if (this._reflectivityTexture) { + ubo.setTexture("reflectivitySampler", this._reflectivityTexture); + } + if (this._metallicReflectanceTexture) { + ubo.setTexture("metallicReflectanceSampler", this._metallicReflectanceTexture); + } + if (this._reflectanceTexture && defines.REFLECTANCE) { + ubo.setTexture("reflectanceSampler", this._reflectanceTexture); + } + if (this._microSurfaceTexture) { + ubo.setTexture("microSurfaceSampler", this._microSurfaceTexture); + } + } + if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) { + ubo.setTexture("bumpSampler", this._bumpTexture); + } + } + // OIT with depth peeling + if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) { + this.getScene().depthPeelingRenderer.bind(effect); + } + this._eventInfo.subMesh = subMesh; + this._callbackPluginEventBindForSubMesh(this._eventInfo); + // Clip plane + bindClipPlane(this._activeEffect, this, scene); + this.bindEyePosition(effect); + } + else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) { + this._needToBindSceneUbo = true; + } + if (mustRebind || !this.isFrozen) { + // Lights + if (scene.lightsEnabled && !this._disableLighting) { + BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights); + } + // View + if ((scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) || + reflectionTexture || + this.subSurface.refractionTexture || + mesh.receiveShadows || + defines.PREPASS) { + this.bindView(effect); + } + // Fog + BindFogParameters(scene, mesh, this._activeEffect, true); + // Morph targets + if (defines.NUM_MORPH_INFLUENCERS) { + BindMorphTargetParameters(mesh, this._activeEffect); + } + if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) { + mesh.bakedVertexAnimationManager?.bind(effect, defines.INSTANCES); + } + // image processing + this._imageProcessingConfiguration.bind(this._activeEffect); + // Log. depth + BindLogDepth(defines, this._activeEffect, scene); + } + this._afterBind(mesh, this._activeEffect, subMesh); + ubo.update(); + } + /** + * Returns the animatable textures. + * If material have animatable metallic texture, then reflectivity texture will not be returned, even if it has animations. + * @returns - Array of animatable textures. + */ + getAnimatables() { + const results = super.getAnimatables(); + if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) { + results.push(this._albedoTexture); + } + if (this._baseWeightTexture && this._baseWeightTexture.animations && this._baseWeightTexture.animations.length > 0) { + results.push(this._baseWeightTexture); + } + if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) { + results.push(this._ambientTexture); + } + if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) { + results.push(this._opacityTexture); + } + if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) { + results.push(this._reflectionTexture); + } + if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) { + results.push(this._emissiveTexture); + } + if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) { + results.push(this._metallicTexture); + } + else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) { + results.push(this._reflectivityTexture); + } + if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { + results.push(this._bumpTexture); + } + if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) { + results.push(this._lightmapTexture); + } + if (this._metallicReflectanceTexture && this._metallicReflectanceTexture.animations && this._metallicReflectanceTexture.animations.length > 0) { + results.push(this._metallicReflectanceTexture); + } + if (this._reflectanceTexture && this._reflectanceTexture.animations && this._reflectanceTexture.animations.length > 0) { + results.push(this._reflectanceTexture); + } + if (this._microSurfaceTexture && this._microSurfaceTexture.animations && this._microSurfaceTexture.animations.length > 0) { + results.push(this._microSurfaceTexture); + } + return results; + } + /** + * Returns the texture used for reflections. + * @returns - Reflection texture if present. Otherwise, returns the environment texture. + */ + _getReflectionTexture() { + if (this._reflectionTexture) { + return this._reflectionTexture; + } + return this.getScene().environmentTexture; + } + /** + * Returns an array of the actively used textures. + * @returns - Array of BaseTextures + */ + getActiveTextures() { + const activeTextures = super.getActiveTextures(); + if (this._albedoTexture) { + activeTextures.push(this._albedoTexture); + } + if (this._baseWeightTexture) { + activeTextures.push(this._baseWeightTexture); + } + if (this._ambientTexture) { + activeTextures.push(this._ambientTexture); + } + if (this._opacityTexture) { + activeTextures.push(this._opacityTexture); + } + if (this._reflectionTexture) { + activeTextures.push(this._reflectionTexture); + } + if (this._emissiveTexture) { + activeTextures.push(this._emissiveTexture); + } + if (this._reflectivityTexture) { + activeTextures.push(this._reflectivityTexture); + } + if (this._metallicTexture) { + activeTextures.push(this._metallicTexture); + } + if (this._metallicReflectanceTexture) { + activeTextures.push(this._metallicReflectanceTexture); + } + if (this._reflectanceTexture) { + activeTextures.push(this._reflectanceTexture); + } + if (this._microSurfaceTexture) { + activeTextures.push(this._microSurfaceTexture); + } + if (this._bumpTexture) { + activeTextures.push(this._bumpTexture); + } + if (this._lightmapTexture) { + activeTextures.push(this._lightmapTexture); + } + return activeTextures; + } + /** + * Checks to see if a texture is used in the material. + * @param texture - Base texture to use. + * @returns - Boolean specifying if a texture is used in the material. + */ + hasTexture(texture) { + if (super.hasTexture(texture)) { + return true; + } + if (this._albedoTexture === texture) { + return true; + } + if (this._baseWeightTexture === texture) { + return true; + } + if (this._ambientTexture === texture) { + return true; + } + if (this._opacityTexture === texture) { + return true; + } + if (this._reflectionTexture === texture) { + return true; + } + if (this._emissiveTexture === texture) { + return true; + } + if (this._reflectivityTexture === texture) { + return true; + } + if (this._metallicTexture === texture) { + return true; + } + if (this._metallicReflectanceTexture === texture) { + return true; + } + if (this._reflectanceTexture === texture) { + return true; + } + if (this._microSurfaceTexture === texture) { + return true; + } + if (this._bumpTexture === texture) { + return true; + } + if (this._lightmapTexture === texture) { + return true; + } + return false; + } + /** + * Sets the required values to the prepass renderer. + * It can't be sets when subsurface scattering of this material is disabled. + * When scene have ability to enable subsurface prepass effect, it will enable. + * @returns - If prepass is enabled or not. + */ + setPrePassRenderer() { + if (!this.subSurface?.isScatteringEnabled) { + return false; + } + const subSurfaceConfiguration = this.getScene().enableSubSurfaceForPrePass(); + if (subSurfaceConfiguration) { + subSurfaceConfiguration.enabled = true; + } + return true; + } + /** + * Disposes the resources of the material. + * @param forceDisposeEffect - Forces the disposal of effects. + * @param forceDisposeTextures - Forces the disposal of all textures. + */ + dispose(forceDisposeEffect, forceDisposeTextures) { + this._breakShaderLoadedCheck = true; + if (forceDisposeTextures) { + if (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture) { + this._environmentBRDFTexture.dispose(); + } + this._albedoTexture?.dispose(); + this._baseWeightTexture?.dispose(); + this._ambientTexture?.dispose(); + this._opacityTexture?.dispose(); + this._reflectionTexture?.dispose(); + this._emissiveTexture?.dispose(); + this._metallicTexture?.dispose(); + this._reflectivityTexture?.dispose(); + this._bumpTexture?.dispose(); + this._lightmapTexture?.dispose(); + this._metallicReflectanceTexture?.dispose(); + this._reflectanceTexture?.dispose(); + this._microSurfaceTexture?.dispose(); + } + this._renderTargets.dispose(); + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + super.dispose(forceDisposeEffect, forceDisposeTextures); + } +} +/** + * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use. + */ +PBRBaseMaterial.PBRMATERIAL_OPAQUE = Material.MATERIAL_OPAQUE; +/** + * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value. + */ +PBRBaseMaterial.PBRMATERIAL_ALPHATEST = Material.MATERIAL_ALPHATEST; +/** + * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. + */ +PBRBaseMaterial.PBRMATERIAL_ALPHABLEND = Material.MATERIAL_ALPHABLEND; +/** + * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. + * They are also discarded below the alpha cutoff threshold to improve performances. + */ +PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND = Material.MATERIAL_ALPHATESTANDBLEND; +/** + * Defines the default value of how much AO map is occluding the analytical lights + * (point spot...). + */ +PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0; +/** + * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law. + */ +PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0; +/** + * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document + * to enhance interoperability with other engines. + */ +PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1; +/** + * PBRMaterialLightFalloff Standard: light is falling off like in the standard material + * to enhance interoperability with other materials. + */ +PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2; +/** + * Force all the PBR materials to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +PBRBaseMaterial.ForceGLSL = false; +__decorate([ + serializeAsImageProcessingConfiguration() +], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsMiscDirty") +], PBRBaseMaterial.prototype, "debugMode", void 0); + +/** + * The Physically based material of BJS. + * + * This offers the main features of a standard PBR material. + * For more information, please refer to the documentation : + * https://doc.babylonjs.com/features/featuresDeepDive/materials/using/introToPBR + */ +class PBRMaterial extends PBRBaseMaterial { + /** + * Stores the refracted light information in a texture. + */ + get refractionTexture() { + return this.subSurface.refractionTexture; + } + set refractionTexture(value) { + this.subSurface.refractionTexture = value; + if (value) { + this.subSurface.isRefractionEnabled = true; + } + else if (!this.subSurface.linkRefractionWithTransparency) { + this.subSurface.isRefractionEnabled = false; + } + } + /** + * Index of refraction of the material base layer. + * https://en.wikipedia.org/wiki/List_of_refractive_indices + * + * This does not only impact refraction but also the Base F0 of Dielectric Materials. + * + * From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI)) + */ + get indexOfRefraction() { + return this.subSurface.indexOfRefraction; + } + set indexOfRefraction(value) { + this.subSurface.indexOfRefraction = value; + } + /** + * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. + */ + get invertRefractionY() { + return this.subSurface.invertRefractionY; + } + set invertRefractionY(value) { + this.subSurface.invertRefractionY = value; + } + /** + * This parameters will make the material used its opacity to control how much it is refracting against not. + * Materials half opaque for instance using refraction could benefit from this control. + */ + get linkRefractionWithTransparency() { + return this.subSurface.linkRefractionWithTransparency; + } + set linkRefractionWithTransparency(value) { + this.subSurface.linkRefractionWithTransparency = value; + if (value) { + this.subSurface.isRefractionEnabled = true; + } + } + /** + * BJS is using an hardcoded light falloff based on a manually sets up range. + * In PBR, one way to represents the falloff is to use the inverse squared root algorithm. + * This parameter can help you switch back to the BJS mode in order to create scenes using both materials. + */ + get usePhysicalLightFalloff() { + return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL; + } + /** + * BJS is using an hardcoded light falloff based on a manually sets up range. + * In PBR, one way to represents the falloff is to use the inverse squared root algorithm. + * This parameter can help you switch back to the BJS mode in order to create scenes using both materials. + */ + set usePhysicalLightFalloff(value) { + if (value !== this.usePhysicalLightFalloff) { + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + if (value) { + this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL; + } + else { + this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD; + } + } + } + /** + * In order to support the falloff compatibility with gltf, a special mode has been added + * to reproduce the gltf light falloff. + */ + get useGLTFLightFalloff() { + return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF; + } + /** + * In order to support the falloff compatibility with gltf, a special mode has been added + * to reproduce the gltf light falloff. + */ + set useGLTFLightFalloff(value) { + if (value !== this.useGLTFLightFalloff) { + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + if (value) { + this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_GLTF; + } + else { + this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD; + } + } + } + /** + * Gets the image processing configuration used either in this material. + */ + get imageProcessingConfiguration() { + return this._imageProcessingConfiguration; + } + /** + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ + set imageProcessingConfiguration(value) { + this._attachImageProcessingConfiguration(value); + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + } + /** + * Gets whether the color curves effect is enabled. + */ + get cameraColorCurvesEnabled() { + return this.imageProcessingConfiguration.colorCurvesEnabled; + } + /** + * Sets whether the color curves effect is enabled. + */ + set cameraColorCurvesEnabled(value) { + this.imageProcessingConfiguration.colorCurvesEnabled = value; + } + /** + * Gets whether the color grading effect is enabled. + */ + get cameraColorGradingEnabled() { + return this.imageProcessingConfiguration.colorGradingEnabled; + } + /** + * Gets whether the color grading effect is enabled. + */ + set cameraColorGradingEnabled(value) { + this.imageProcessingConfiguration.colorGradingEnabled = value; + } + /** + * Gets whether tonemapping is enabled or not. + */ + get cameraToneMappingEnabled() { + return this._imageProcessingConfiguration.toneMappingEnabled; + } + /** + * Sets whether tonemapping is enabled or not + */ + set cameraToneMappingEnabled(value) { + this._imageProcessingConfiguration.toneMappingEnabled = value; + } + /** + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ + get cameraExposure() { + return this._imageProcessingConfiguration.exposure; + } + /** + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ + set cameraExposure(value) { + this._imageProcessingConfiguration.exposure = value; + } + /** + * Gets The camera contrast used on this material. + */ + get cameraContrast() { + return this._imageProcessingConfiguration.contrast; + } + /** + * Sets The camera contrast used on this material. + */ + set cameraContrast(value) { + this._imageProcessingConfiguration.contrast = value; + } + /** + * Gets the Color Grading 2D Lookup Texture. + */ + get cameraColorGradingTexture() { + return this._imageProcessingConfiguration.colorGradingTexture; + } + /** + * Sets the Color Grading 2D Lookup Texture. + */ + set cameraColorGradingTexture(value) { + this._imageProcessingConfiguration.colorGradingTexture = value; + } + /** + * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ + get cameraColorCurves() { + return this._imageProcessingConfiguration.colorCurves; + } + /** + * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ + set cameraColorCurves(value) { + this._imageProcessingConfiguration.colorCurves = value; + } + /** + * Instantiates a new PBRMaterial instance. + * + * @param name The material name + * @param scene The scene the material will be use in. + * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false + */ + constructor(name, scene, forceGLSL = false) { + super(name, scene, forceGLSL); + /** + * Intensity of the direct lights e.g. the four lights available in your scene. + * This impacts both the direct diffuse and specular highlights. + */ + this.directIntensity = 1.0; + /** + * Intensity of the emissive part of the material. + * This helps controlling the emissive effect without modifying the emissive color. + */ + this.emissiveIntensity = 1.0; + /** + * Intensity of the environment e.g. how much the environment will light the object + * either through harmonics for rough material or through the reflection for shiny ones. + */ + this.environmentIntensity = 1.0; + /** + * This is a special control allowing the reduction of the specular highlights coming from the + * four lights of the scene. Those highlights may not be needed in full environment lighting. + */ + this.specularIntensity = 1.0; + /** + * Debug Control allowing disabling the bump map on this material. + */ + this.disableBumpMap = false; + /** + * AKA Occlusion Texture Intensity in other nomenclature. + */ + this.ambientTextureStrength = 1.0; + /** + * Defines how much the AO map is occluding the analytical lights (point spot...). + * 1 means it completely occludes it + * 0 mean it has no impact + */ + this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS; + /** + * In metallic workflow, specifies an F0 factor to help configuring the material F0. + * By default the indexOfrefraction is used to compute F0; + * + * This is used as a factor against the default reflectance at normal incidence to tweak it. + * + * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor; + * F90 = metallicReflectanceColor; + */ + this.metallicF0Factor = 1; + /** + * In metallic workflow, specifies an F0 color. + * By default the F90 is always 1; + * + * Please note that this factor is also used as a factor against the default reflectance at normal incidence. + * + * F0 = defaultF0_from_IOR * metallicF0Factor * metallicReflectanceColor + * F90 = metallicF0Factor; + */ + this.metallicReflectanceColor = Color3.White(); + /** + * Specifies that only the A channel from metallicReflectanceTexture should be used. + * If false, both RGB and A channels will be used + */ + this.useOnlyMetallicFromMetallicReflectanceTexture = false; + /** + * The color of a material in ambient lighting. + */ + this.ambientColor = new Color3(0, 0, 0); + /** + * AKA Diffuse Color in other nomenclature. + */ + this.albedoColor = new Color3(1, 1, 1); + /** + * OpenPBR Base Weight (multiplier to the diffuse and metal lobes). + */ + this.baseWeight = 1; + /** + * AKA Specular Color in other nomenclature. + */ + this.reflectivityColor = new Color3(1, 1, 1); + /** + * The color reflected from the material. + */ + this.reflectionColor = new Color3(1.0, 1.0, 1.0); + /** + * The color emitted from the material. + */ + this.emissiveColor = new Color3(0, 0, 0); + /** + * AKA Glossiness in other nomenclature. + */ + this.microSurface = 1.0; + /** + * If true, the light map contains occlusion information instead of lighting info. + */ + this.useLightmapAsShadowmap = false; + /** + * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending. + */ + this.useAlphaFromAlbedoTexture = false; + /** + * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations. + */ + this.forceAlphaTest = false; + /** + * Defines the alpha limits in alpha test mode. + */ + this.alphaCutOff = 0.4; + /** + * Specifies that the material will keep the specular highlights over a transparent surface (only the most luminous ones). + * A car glass is a good example of that. When sun reflects on it you can not see what is behind. + */ + this.useSpecularOverAlpha = true; + /** + * Specifies if the reflectivity texture contains the glossiness information in its alpha channel. + */ + this.useMicroSurfaceFromReflectivityMapAlpha = false; + /** + * Specifies if the metallic texture contains the roughness information in its alpha channel. + */ + this.useRoughnessFromMetallicTextureAlpha = true; + /** + * Specifies if the metallic texture contains the roughness information in its green channel. + * Needs useRoughnessFromMetallicTextureAlpha to be false. + */ + this.useRoughnessFromMetallicTextureGreen = false; + /** + * Specifies if the metallic texture contains the metallness information in its blue channel. + */ + this.useMetallnessFromMetallicTextureBlue = false; + /** + * Specifies if the metallic texture contains the ambient occlusion information in its red channel. + */ + this.useAmbientOcclusionFromMetallicTextureRed = false; + /** + * Specifies if the ambient texture contains the ambient occlusion information in its red channel only. + */ + this.useAmbientInGrayScale = false; + /** + * In case the reflectivity map does not contain the microsurface information in its alpha channel, + * The material will try to infer what glossiness each pixel should be. + */ + this.useAutoMicroSurfaceFromReflectivityMap = false; + /** + * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones). + * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind. + */ + this.useRadianceOverAlpha = true; + /** + * Allows using an object space normal map (instead of tangent space). + */ + this.useObjectSpaceNormalMap = false; + /** + * Allows using the bump map in parallax mode. + */ + this.useParallax = false; + /** + * Allows using the bump map in parallax occlusion mode. + */ + this.useParallaxOcclusion = false; + /** + * Controls the scale bias of the parallax mode. + */ + this.parallaxScaleBias = 0.05; + /** + * If sets to true, disables all the lights affecting the material. + */ + this.disableLighting = false; + /** + * Force the shader to compute irradiance in the fragment shader in order to take bump in account. + */ + this.forceIrradianceInFragment = false; + /** + * Number of Simultaneous lights allowed on the material. + */ + this.maxSimultaneousLights = 4; + /** + * If sets to true, x component of normal map value will invert (x = 1.0 - x). + */ + this.invertNormalMapX = false; + /** + * If sets to true, y component of normal map value will invert (y = 1.0 - y). + */ + this.invertNormalMapY = false; + /** + * If sets to true and backfaceCulling is false, normals will be flipped on the backside. + */ + this.twoSidedLighting = false; + /** + * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. + * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel) + */ + this.useAlphaFresnel = false; + /** + * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. + * And/Or occlude the blended part. (alpha stays linear to compute the fresnel) + */ + this.useLinearAlphaFresnel = false; + /** + * Let user defines the brdf lookup texture used for IBL. + * A default 8bit version is embedded but you could point at : + * * Default texture: https://assets.babylonjs.com/environments/correlatedMSBRDF_RGBD.png + * * Default 16bit pixel depth texture: https://assets.babylonjs.com/environments/correlatedMSBRDF.dds + * * LEGACY Default None correlated https://assets.babylonjs.com/environments/uncorrelatedBRDF_RGBD.png + * * LEGACY Default None correlated 16bit pixel depth https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds + */ + this.environmentBRDFTexture = null; + /** + * Force normal to face away from face. + */ + this.forceNormalForward = false; + /** + * Enables specular anti aliasing in the PBR shader. + * It will both interacts on the Geometry for analytical and IBL lighting. + * It also prefilter the roughness map based on the bump values. + */ + this.enableSpecularAntiAliasing = false; + /** + * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal + * makes the reflect vector face the model (under horizon). + */ + this.useHorizonOcclusion = true; + /** + * This parameters will enable/disable radiance occlusion by preventing the radiance to lit + * too much the area relying on ambient texture to define their ambient occlusion. + */ + this.useRadianceOcclusion = true; + /** + * If set to true, no lighting calculations will be applied. + */ + this.unlit = false; + /** + * If sets to true, the decal map will be applied after the detail map. Else, it is applied before (default: false) + */ + this.applyDecalMapAfterDetailMap = false; + this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene()); + } + /** + * @returns the name of this material class. + */ + getClassName() { + return "PBRMaterial"; + } + /** + * Makes a duplicate of the current material. + * @param name - name to use for the new material. + * @param cloneTexturesOnlyOnce - if a texture is used in more than one channel (e.g diffuse and opacity), only clone it once and reuse it on the other channels. Default false. + * @param rootUrl defines the root URL to use to load textures + * @returns cloned material instance + */ + clone(name, cloneTexturesOnlyOnce = true, rootUrl = "") { + const clone = SerializationHelper.Clone(() => new PBRMaterial(name, this.getScene()), this, { cloneTexturesOnlyOnce }); + clone.id = name; + clone.name = name; + this.stencil.copyTo(clone.stencil); + this._clonePlugins(clone, rootUrl); + return clone; + } + /** + * Serializes this PBR Material. + * @returns - An object with the serialized material. + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.customType = "BABYLON.PBRMaterial"; + return serializationObject; + } + // Statics + /** + * Parses a PBR Material from a serialized object. + * @param source - Serialized object. + * @param scene - BJS scene instance. + * @param rootUrl - url for the scene object + * @returns - PBRMaterial + */ + static Parse(source, scene, rootUrl) { + const material = SerializationHelper.Parse(() => new PBRMaterial(source.name, scene), source, scene, rootUrl); + if (source.stencil) { + material.stencil.parse(source.stencil, scene, rootUrl); + } + Material._ParsePlugins(source, material, scene, rootUrl); + // The code block below ensures backward compatibility with serialized materials before plugins are automatically serialized. + if (source.clearCoat) { + material.clearCoat.parse(source.clearCoat, scene, rootUrl); + } + if (source.anisotropy) { + material.anisotropy.parse(source.anisotropy, scene, rootUrl); + } + if (source.brdf) { + material.brdf.parse(source.brdf, scene, rootUrl); + } + if (source.sheen) { + material.sheen.parse(source.sheen, scene, rootUrl); + } + if (source.subSurface) { + material.subSurface.parse(source.subSurface, scene, rootUrl); + } + if (source.iridescence) { + material.iridescence.parse(source.iridescence, scene, rootUrl); + } + return material; + } +} +/** + * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use. + */ +PBRMaterial.PBRMATERIAL_OPAQUE = PBRBaseMaterial.PBRMATERIAL_OPAQUE; +/** + * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value. + */ +PBRMaterial.PBRMATERIAL_ALPHATEST = PBRBaseMaterial.PBRMATERIAL_ALPHATEST; +/** + * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. + */ +PBRMaterial.PBRMATERIAL_ALPHABLEND = PBRBaseMaterial.PBRMATERIAL_ALPHABLEND; +/** + * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. + * They are also discarded below the alpha cutoff threshold to improve performances. + */ +PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND; +/** + * Defines the default value of how much AO map is occluding the analytical lights + * (point spot...). + */ +PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS; +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "directIntensity", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "emissiveIntensity", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "environmentIntensity", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "specularIntensity", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "disableBumpMap", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "albedoTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "baseWeightTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "ambientTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "ambientTextureStrength", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") +], PBRMaterial.prototype, "opacityTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "reflectionTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "emissiveTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "reflectivityTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "metallicTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "metallic", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "roughness", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "metallicF0Factor", void 0); +__decorate([ + serializeAsColor3(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "metallicReflectanceColor", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useOnlyMetallicFromMetallicReflectanceTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "metallicReflectanceTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "reflectanceTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "microSurfaceTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "bumpTexture", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", null) +], PBRMaterial.prototype, "lightmapTexture", void 0); +__decorate([ + serializeAsColor3("ambient"), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "ambientColor", void 0); +__decorate([ + serializeAsColor3("albedo"), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "albedoColor", void 0); +__decorate([ + serialize("baseWeight"), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "baseWeight", void 0); +__decorate([ + serializeAsColor3("reflectivity"), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "reflectivityColor", void 0); +__decorate([ + serializeAsColor3("reflection"), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "reflectionColor", void 0); +__decorate([ + serializeAsColor3("emissive"), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "emissiveColor", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "microSurface", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") +], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") +], PBRMaterial.prototype, "forceAlphaTest", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") +], PBRMaterial.prototype, "alphaCutOff", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useSpecularOverAlpha", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useAmbientInGrayScale", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0); +__decorate([ + serialize() +], PBRMaterial.prototype, "usePhysicalLightFalloff", null); +__decorate([ + serialize() +], PBRMaterial.prototype, "useGLTFLightFalloff", null); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useRadianceOverAlpha", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useParallax", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useParallaxOcclusion", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "parallaxScaleBias", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsLightsDirty") +], PBRMaterial.prototype, "disableLighting", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "forceIrradianceInFragment", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsLightsDirty") +], PBRMaterial.prototype, "maxSimultaneousLights", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "invertNormalMapX", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "invertNormalMapY", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "twoSidedLighting", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useAlphaFresnel", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "environmentBRDFTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "forceNormalForward", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useHorizonOcclusion", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMaterial.prototype, "useRadianceOcclusion", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsMiscDirty") +], PBRMaterial.prototype, "unlit", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsMiscDirty") +], PBRMaterial.prototype, "applyDecalMapAfterDetailMap", void 0); +RegisterClass("BABYLON.PBRMaterial", PBRMaterial); + +/** + * Defines a target to use with MorphTargetManager + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets + */ +class MorphTarget { + /** + * Gets or sets the influence of this target (ie. its weight in the overall morphing) + */ + get influence() { + return this._influence; + } + set influence(influence) { + if (this._influence === influence) { + return; + } + const previous = this._influence; + this._influence = influence; + if (this.onInfluenceChanged.hasObservers()) { + this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0); + } + } + /** + * Gets or sets the animation properties override + */ + get animationPropertiesOverride() { + if (!this._animationPropertiesOverride && this._scene) { + return this._scene.animationPropertiesOverride; + } + return this._animationPropertiesOverride; + } + set animationPropertiesOverride(value) { + this._animationPropertiesOverride = value; + } + /** + * Creates a new MorphTarget + * @param name defines the name of the target + * @param influence defines the influence to use + * @param scene defines the scene the morphtarget belongs to + */ + constructor( + /** defines the name of the target */ + name, influence = 0, scene = null) { + this.name = name; + /** + * Gets or sets the list of animations + */ + this.animations = []; + this._positions = null; + this._normals = null; + this._tangents = null; + this._uvs = null; + this._uv2s = null; + this._colors = null; + this._uniqueId = 0; + /** + * Observable raised when the influence changes + */ + this.onInfluenceChanged = new Observable(); + /** @internal */ + this._onDataLayoutChanged = new Observable(); + this._animationPropertiesOverride = null; + this.id = name; + this._scene = scene || EngineStore.LastCreatedScene; + this.influence = influence; + if (this._scene) { + this._uniqueId = this._scene.getUniqueId(); + } + } + /** + * Gets the unique ID of this manager + */ + get uniqueId() { + return this._uniqueId; + } + /** + * Gets a boolean defining if the target contains position data + */ + get hasPositions() { + return !!this._positions; + } + /** + * Gets a boolean defining if the target contains normal data + */ + get hasNormals() { + return !!this._normals; + } + /** + * Gets a boolean defining if the target contains tangent data + */ + get hasTangents() { + return !!this._tangents; + } + /** + * Gets a boolean defining if the target contains texture coordinates data + */ + get hasUVs() { + return !!this._uvs; + } + /** + * Gets a boolean defining if the target contains texture coordinates 2 data + */ + get hasUV2s() { + return !!this._uv2s; + } + get hasColors() { + return !!this._colors; + } + /** + * Gets the number of vertices stored in this target + */ + get vertexCount() { + return this._positions + ? this._positions.length / 3 + : this._normals + ? this._normals.length / 3 + : this._tangents + ? this._tangents.length / 3 + : this._uvs + ? this._uvs.length / 2 + : this._uv2s + ? this._uv2s.length / 2 + : this._colors + ? this._colors.length / 4 + : 0; + } + /** + * Affects position data to this target + * @param data defines the position data to use + */ + setPositions(data) { + const hadPositions = this.hasPositions; + this._positions = data; + if (hadPositions !== this.hasPositions) { + this._onDataLayoutChanged.notifyObservers(undefined); + } + } + /** + * Gets the position data stored in this target + * @returns a FloatArray containing the position data (or null if not present) + */ + getPositions() { + return this._positions; + } + /** + * Affects normal data to this target + * @param data defines the normal data to use + */ + setNormals(data) { + const hadNormals = this.hasNormals; + this._normals = data; + if (hadNormals !== this.hasNormals) { + this._onDataLayoutChanged.notifyObservers(undefined); + } + } + /** + * Gets the normal data stored in this target + * @returns a FloatArray containing the normal data (or null if not present) + */ + getNormals() { + return this._normals; + } + /** + * Affects tangent data to this target + * @param data defines the tangent data to use + */ + setTangents(data) { + const hadTangents = this.hasTangents; + this._tangents = data; + if (hadTangents !== this.hasTangents) { + this._onDataLayoutChanged.notifyObservers(undefined); + } + } + /** + * Gets the tangent data stored in this target + * @returns a FloatArray containing the tangent data (or null if not present) + */ + getTangents() { + return this._tangents; + } + /** + * Affects texture coordinates data to this target + * @param data defines the texture coordinates data to use + */ + setUVs(data) { + const hadUVs = this.hasUVs; + this._uvs = data; + if (hadUVs !== this.hasUVs) { + this._onDataLayoutChanged.notifyObservers(undefined); + } + } + /** + * Gets the texture coordinates data stored in this target + * @returns a FloatArray containing the texture coordinates data (or null if not present) + */ + getUVs() { + return this._uvs; + } + /** + * Affects texture coordinates 2 data to this target + * @param data defines the texture coordinates 2 data to use + */ + setUV2s(data) { + const hadUV2s = this.hasUV2s; + this._uv2s = data; + if (hadUV2s !== this.hasUV2s) { + this._onDataLayoutChanged.notifyObservers(undefined); + } + } + /** + * Gets the texture coordinates 2 data stored in this target + * @returns a FloatArray containing the texture coordinates 2 data (or null if not present) + */ + getUV2s() { + return this._uv2s; + } + /** + * Affects color data to this target + * @param data defines the color data to use + */ + setColors(data) { + const hadColors = this.hasColors; + this._colors = data; + if (hadColors !== this.hasColors) { + this._onDataLayoutChanged.notifyObservers(undefined); + } + } + /** + * Gets the color data stored in this target + * @returns a FloatArray containing the color data (or null if not present) + */ + getColors() { + return this._colors; + } + /** + * Clone the current target + * @returns a new MorphTarget + */ + clone() { + const newOne = SerializationHelper.Clone(() => new MorphTarget(this.name, this.influence, this._scene), this); + newOne._positions = this._positions; + newOne._normals = this._normals; + newOne._tangents = this._tangents; + newOne._uvs = this._uvs; + newOne._uv2s = this._uv2s; + newOne._colors = this._colors; + return newOne; + } + /** + * Serializes the current target into a Serialization object + * @returns the serialized object + */ + serialize() { + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.influence = this.influence; + serializationObject.positions = Array.prototype.slice.call(this.getPositions()); + if (this.id != null) { + serializationObject.id = this.id; + } + if (this.hasNormals) { + serializationObject.normals = Array.prototype.slice.call(this.getNormals()); + } + if (this.hasTangents) { + serializationObject.tangents = Array.prototype.slice.call(this.getTangents()); + } + if (this.hasUVs) { + serializationObject.uvs = Array.prototype.slice.call(this.getUVs()); + } + if (this.hasUV2s) { + serializationObject.uv2s = Array.prototype.slice.call(this.getUV2s()); + } + if (this.hasColors) { + serializationObject.colors = Array.prototype.slice.call(this.getColors()); + } + // Animations + SerializationHelper.AppendSerializedAnimations(this, serializationObject); + return serializationObject; + } + /** + * Returns the string "MorphTarget" + * @returns "MorphTarget" + */ + getClassName() { + return "MorphTarget"; + } + // Statics + /** + * Creates a new target from serialized data + * @param serializationObject defines the serialized data to use + * @param scene defines the hosting scene + * @returns a new MorphTarget + */ + static Parse(serializationObject, scene) { + const result = new MorphTarget(serializationObject.name, serializationObject.influence); + result.setPositions(serializationObject.positions); + if (serializationObject.id != null) { + result.id = serializationObject.id; + } + if (serializationObject.normals) { + result.setNormals(serializationObject.normals); + } + if (serializationObject.tangents) { + result.setTangents(serializationObject.tangents); + } + if (serializationObject.uvs) { + result.setUVs(serializationObject.uvs); + } + if (serializationObject.uv2s) { + result.setUV2s(serializationObject.uv2s); + } + if (serializationObject.colors) { + result.setColors(serializationObject.colors); + } + // Animations + if (serializationObject.animations) { + for (let animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) { + const parsedAnimation = serializationObject.animations[animationIndex]; + const internalClass = GetClass("BABYLON.Animation"); + if (internalClass) { + result.animations.push(internalClass.Parse(parsedAnimation)); + } + } + if (serializationObject.autoAnimate && scene) { + scene.beginAnimation(result, serializationObject.autoAnimateFrom, serializationObject.autoAnimateTo, serializationObject.autoAnimateLoop, serializationObject.autoAnimateSpeed || 1.0); + } + } + return result; + } + /** + * Creates a MorphTarget from mesh data + * @param mesh defines the source mesh + * @param name defines the name to use for the new target + * @param influence defines the influence to attach to the target + * @returns a new MorphTarget + */ + static FromMesh(mesh, name, influence) { + if (!name) { + name = mesh.name; + } + const result = new MorphTarget(name, influence, mesh.getScene()); + result.setPositions(mesh.getVerticesData(VertexBuffer.PositionKind)); + if (mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) { + result.setNormals(mesh.getVerticesData(VertexBuffer.NormalKind)); + } + if (mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) { + result.setTangents(mesh.getVerticesData(VertexBuffer.TangentKind)); + } + if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { + result.setUVs(mesh.getVerticesData(VertexBuffer.UVKind)); + } + if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) { + result.setUV2s(mesh.getVerticesData(VertexBuffer.UV2Kind)); + } + if (mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) { + result.setColors(mesh.getVerticesData(VertexBuffer.ColorKind)); + } + return result; + } +} +__decorate([ + serialize() +], MorphTarget.prototype, "id", void 0); + +/** + * Class used to store 2D array textures containing user data + */ +class RawTexture2DArray extends Texture { + /** + * Gets the number of layers of the texture + */ + get depth() { + return this._depth; + } + /** + * Create a new RawTexture2DArray + * @param data defines the data of the texture + * @param width defines the width of the texture + * @param height defines the height of the texture + * @param depth defines the number of layers of the texture + * @param format defines the texture format to use + * @param scene defines the hosting scene + * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default) + * @param invertY defines if texture must be stored with Y axis inverted + * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default) + * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_BYTE, Engine.TEXTURETYPE_FLOAT...) + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + */ + constructor(data, width, height, depth, + /** Gets or sets the texture format to use */ + format, scene, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, textureType = 0, creationFlags) { + super(null, scene, !generateMipMaps, invertY); + this.format = format; + this._texture = scene.getEngine().createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, null, textureType, creationFlags); + this._depth = depth; + this.is2DArray = true; + } + /** + * Update the texture with new data + * @param data defines the data to store in the texture + */ + update(data) { + if (!this._texture) { + return; + } + this._getEngine().updateRawTexture2DArray(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type); + } + /** + * Creates a RGBA texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param depth defines the number of layers of the texture + * @param scene defines the scene the texture will belong to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + * @returns the RGBA texture + */ + static CreateRGBATexture(data, width, height, depth, scene, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0) { + return new RawTexture2DArray(data, width, height, depth, 5, scene, generateMipMaps, invertY, samplingMode, type); + } +} + +/** + * This class is used to deform meshes using morphing between different targets + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets + */ +class MorphTargetManager { + /** + * Sets a boolean indicating that adding new target or updating an existing target will not update the underlying data buffers + */ + set areUpdatesFrozen(block) { + if (block) { + this._blockCounter++; + } + else { + this._blockCounter--; + if (this._blockCounter <= 0) { + this._blockCounter = 0; + this._syncActiveTargets(this._forceUpdateWhenUnfrozen); + this._forceUpdateWhenUnfrozen = false; + } + } + } + get areUpdatesFrozen() { + return this._blockCounter > 0; + } + /** + * Creates a new MorphTargetManager + * @param scene defines the current scene + */ + constructor(scene = null) { + this._targets = new Array(); + this._targetInfluenceChangedObservers = new Array(); + this._targetDataLayoutChangedObservers = new Array(); + this._activeTargets = new SmartArray(16); + this._supportsPositions = false; + this._supportsNormals = false; + this._supportsTangents = false; + this._supportsUVs = false; + this._supportsUV2s = false; + this._supportsColors = false; + this._vertexCount = 0; + this._uniqueId = 0; + this._tempInfluences = new Array(); + this._canUseTextureForTargets = false; + this._blockCounter = 0; + this._mustSynchronize = true; + this._forceUpdateWhenUnfrozen = false; + /** @internal */ + this._textureVertexStride = 0; + /** @internal */ + this._textureWidth = 0; + /** @internal */ + this._textureHeight = 1; + /** @internal */ + this._parentContainer = null; + /** + * Gets or sets a boolean indicating if influencers must be optimized (eg. recompiling the shader if less influencers are used) + */ + this.optimizeInfluencers = true; + /** + * Gets or sets a boolean indicating if positions must be morphed + */ + this.enablePositionMorphing = true; + /** + * Gets or sets a boolean indicating if normals must be morphed + */ + this.enableNormalMorphing = true; + /** + * Gets or sets a boolean indicating if tangents must be morphed + */ + this.enableTangentMorphing = true; + /** + * Gets or sets a boolean indicating if UV must be morphed + */ + this.enableUVMorphing = true; + /** + * Gets or sets a boolean indicating if UV2 must be morphed + */ + this.enableUV2Morphing = true; + /** + * Gets or sets a boolean indicating if colors must be morphed + */ + this.enableColorMorphing = true; + this._numMaxInfluencers = 0; + this._useTextureToStoreTargets = true; + if (!scene) { + scene = EngineStore.LastCreatedScene; + } + this._scene = scene; + if (this._scene) { + this._scene.addMorphTargetManager(this); + this._uniqueId = this._scene.getUniqueId(); + const engineCaps = this._scene.getEngine().getCaps(); + this._canUseTextureForTargets = + engineCaps.canUseGLVertexID && engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0 && engineCaps.texture2DArrayMaxLayerCount > 1; + } + } + /** + * Gets or sets the maximum number of influencers (targets) (default value: 0). + * Setting a value for this property can lead to a smoother experience, as only one shader will be compiled, which will use this value as the maximum number of influencers. + * If you leave the value at 0 (default), a new shader will be compiled every time the number of active influencers changes. This can cause problems, as compiling a shader takes time. + * If you assign a non-zero value to this property, you need to ensure that this value is greater than the maximum number of (active) influencers you'll need for this morph manager. + * Otherwise, the number of active influencers will be truncated at the value you set for this property, which can lead to unexpected results. + * Note that this property has no effect if "useTextureToStoreTargets" is false. + */ + get numMaxInfluencers() { + return this._numMaxInfluencers; + } + set numMaxInfluencers(value) { + if (this._numMaxInfluencers === value) { + return; + } + this._numMaxInfluencers = value; + this._mustSynchronize = true; + this._syncActiveTargets(); + } + /** + * Gets the unique ID of this manager + */ + get uniqueId() { + return this._uniqueId; + } + /** + * Gets the number of vertices handled by this manager + */ + get vertexCount() { + return this._vertexCount; + } + /** + * Gets a boolean indicating if this manager supports morphing of positions + */ + get supportsPositions() { + return this._supportsPositions && this.enablePositionMorphing; + } + /** + * Gets a boolean indicating if this manager supports morphing of normals + */ + get supportsNormals() { + return this._supportsNormals && this.enableNormalMorphing; + } + /** + * Gets a boolean indicating if this manager supports morphing of tangents + */ + get supportsTangents() { + return this._supportsTangents && this.enableTangentMorphing; + } + /** + * Gets a boolean indicating if this manager supports morphing of texture coordinates + */ + get supportsUVs() { + return this._supportsUVs && this.enableUVMorphing; + } + /** + * Gets a boolean indicating if this manager supports morphing of texture coordinates 2 + */ + get supportsUV2s() { + return this._supportsUV2s && this.enableUV2Morphing; + } + /** + * Gets a boolean indicating if this manager supports morphing of colors + */ + get supportsColors() { + return this._supportsColors && this.enableColorMorphing; + } + /** + * Gets a boolean indicating if this manager has data for morphing positions + */ + get hasPositions() { + return this._supportsPositions; + } + /** + * Gets a boolean indicating if this manager has data for morphing normals + */ + get hasNormals() { + return this._supportsNormals; + } + /** + * Gets a boolean indicating if this manager has data for morphing tangents + */ + get hasTangents() { + return this._supportsTangents; + } + /** + * Gets a boolean indicating if this manager has data for morphing texture coordinates + */ + get hasUVs() { + return this._supportsUVs; + } + /** + * Gets a boolean indicating if this manager has data for morphing texture coordinates 2 + */ + get hasUV2s() { + return this._supportsUV2s; + } + /** + * Gets a boolean indicating if this manager has data for morphing colors + */ + get hasColors() { + return this._supportsColors; + } + /** + * Gets the number of targets stored in this manager + */ + get numTargets() { + return this._targets.length; + } + /** + * Gets the number of influencers (ie. the number of targets with influences > 0) + */ + get numInfluencers() { + return this._activeTargets.length; + } + /** + * Gets the list of influences (one per target) + */ + get influences() { + return this._influences; + } + /** + * Gets or sets a boolean indicating that targets should be stored as a texture instead of using vertex attributes (default is true). + * Please note that this option is not available if the hardware does not support it + */ + get useTextureToStoreTargets() { + return this._useTextureToStoreTargets; + } + set useTextureToStoreTargets(value) { + if (this._useTextureToStoreTargets === value) { + return; + } + this._useTextureToStoreTargets = value; + this._mustSynchronize = true; + this._syncActiveTargets(); + } + /** + * Gets a boolean indicating that the targets are stored into a texture (instead of as attributes) + */ + get isUsingTextureForTargets() { + return (MorphTargetManager.EnableTextureStorage && + this.useTextureToStoreTargets && + this._canUseTextureForTargets && + !this._scene?.getEngine().getCaps().disableMorphTargetTexture); + } + /** + * Gets the active target at specified index. An active target is a target with an influence > 0 + * @param index defines the index to check + * @returns the requested target + */ + getActiveTarget(index) { + return this._activeTargets.data[index]; + } + /** + * Gets the target at specified index + * @param index defines the index to check + * @returns the requested target + */ + getTarget(index) { + return this._targets[index]; + } + /** + * Gets the first target with the specified name + * @param name defines the name to check + * @returns the requested target + */ + getTargetByName(name) { + for (const target of this._targets) { + if (target.name === name) { + return target; + } + } + return null; + } + /** + * Add a new target to this manager + * @param target defines the target to add + */ + addTarget(target) { + this._targets.push(target); + this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add((needUpdate) => { + if (this.areUpdatesFrozen && needUpdate) { + this._forceUpdateWhenUnfrozen = true; + } + this._syncActiveTargets(needUpdate); + })); + this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(() => { + this._mustSynchronize = true; + this._syncActiveTargets(); + })); + this._mustSynchronize = true; + this._syncActiveTargets(); + } + /** + * Removes a target from the manager + * @param target defines the target to remove + */ + removeTarget(target) { + const index = this._targets.indexOf(target); + if (index >= 0) { + this._targets.splice(index, 1); + target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]); + target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]); + this._mustSynchronize = true; + this._syncActiveTargets(); + } + if (this._scene) { + this._scene.stopAnimation(target); + } + } + /** + * @internal + */ + _bind(effect) { + effect.setFloat3("morphTargetTextureInfo", this._textureVertexStride, this._textureWidth, this._textureHeight); + effect.setFloatArray("morphTargetTextureIndices", this._morphTargetTextureIndices); + effect.setTexture("morphTargets", this._targetStoreTexture); + effect.setInt("morphTargetCount", this.numInfluencers); + } + /** + * Clone the current manager + * @returns a new MorphTargetManager + */ + clone() { + const copy = new MorphTargetManager(this._scene); + for (const target of this._targets) { + copy.addTarget(target.clone()); + } + copy.enablePositionMorphing = this.enablePositionMorphing; + copy.enableNormalMorphing = this.enableNormalMorphing; + copy.enableTangentMorphing = this.enableTangentMorphing; + copy.enableUVMorphing = this.enableUVMorphing; + copy.enableUV2Morphing = this.enableUV2Morphing; + copy.enableColorMorphing = this.enableColorMorphing; + return copy; + } + /** + * Serializes the current manager into a Serialization object + * @returns the serialized object + */ + serialize() { + const serializationObject = {}; + serializationObject.id = this.uniqueId; + serializationObject.targets = []; + for (const target of this._targets) { + serializationObject.targets.push(target.serialize()); + } + return serializationObject; + } + _syncActiveTargets(needUpdate = false) { + if (this.areUpdatesFrozen) { + return; + } + const wasUsingTextureForTargets = !!this._targetStoreTexture; + const isUsingTextureForTargets = this.isUsingTextureForTargets; + if (this._mustSynchronize || wasUsingTextureForTargets !== isUsingTextureForTargets) { + this._mustSynchronize = false; + this.synchronize(); + } + let influenceCount = 0; + this._activeTargets.reset(); + if (!this._morphTargetTextureIndices || this._morphTargetTextureIndices.length !== this._targets.length) { + this._morphTargetTextureIndices = new Float32Array(this._targets.length); + } + let targetIndex = -1; + for (const target of this._targets) { + targetIndex++; + if (target.influence === 0 && this.optimizeInfluencers) { + continue; + } + if (this._activeTargets.length >= MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode && !this.isUsingTextureForTargets) { + break; + } + this._activeTargets.push(target); + this._morphTargetTextureIndices[influenceCount] = targetIndex; + this._tempInfluences[influenceCount++] = target.influence; + } + if (this._morphTargetTextureIndices.length !== influenceCount) { + this._morphTargetTextureIndices = this._morphTargetTextureIndices.slice(0, influenceCount); + } + if (!this._influences || this._influences.length !== influenceCount) { + this._influences = new Float32Array(influenceCount); + } + for (let index = 0; index < influenceCount; index++) { + this._influences[index] = this._tempInfluences[index]; + } + if (needUpdate && this._scene) { + for (const mesh of this._scene.meshes) { + if (mesh.morphTargetManager === this) { + if (isUsingTextureForTargets) { + mesh._markSubMeshesAsAttributesDirty(); + } + else { + mesh._syncGeometryWithMorphTargetManager(); + } + } + } + } + } + /** + * Synchronize the targets with all the meshes using this morph target manager + */ + synchronize() { + if (!this._scene || this.areUpdatesFrozen) { + return; + } + const engine = this._scene.getEngine(); + this._supportsPositions = true; + this._supportsNormals = true; + this._supportsTangents = true; + this._supportsUVs = true; + this._supportsUV2s = true; + this._supportsColors = true; + this._vertexCount = 0; + this._targetStoreTexture?.dispose(); + this._targetStoreTexture = null; + if (this.isUsingTextureForTargets && this._targets.length > engine.getCaps().texture2DArrayMaxLayerCount) { + this.useTextureToStoreTargets = false; + } + for (const target of this._targets) { + this._supportsPositions = this._supportsPositions && target.hasPositions; + this._supportsNormals = this._supportsNormals && target.hasNormals; + this._supportsTangents = this._supportsTangents && target.hasTangents; + this._supportsUVs = this._supportsUVs && target.hasUVs; + this._supportsUV2s = this._supportsUV2s && target.hasUV2s; + this._supportsColors = this._supportsColors && target.hasColors; + const vertexCount = target.vertexCount; + if (this._vertexCount === 0) { + this._vertexCount = vertexCount; + } + else if (this._vertexCount !== vertexCount) { + Logger.Error(`Incompatible target. Targets must all have the same vertices count. Current vertex count: ${this._vertexCount}, vertex count for target "${target.name}": ${vertexCount}`); + return; + } + } + if (this.isUsingTextureForTargets) { + this._textureVertexStride = 0; + this._supportsPositions && this._textureVertexStride++; + this._supportsNormals && this._textureVertexStride++; + this._supportsTangents && this._textureVertexStride++; + this._supportsUVs && this._textureVertexStride++; + this._supportsUV2s && this._textureVertexStride++; + this._supportsColors && this._textureVertexStride++; + this._textureWidth = this._vertexCount * this._textureVertexStride || 1; + this._textureHeight = 1; + const maxTextureSize = engine.getCaps().maxTextureSize; + if (this._textureWidth > maxTextureSize) { + this._textureHeight = Math.ceil(this._textureWidth / maxTextureSize); + this._textureWidth = maxTextureSize; + } + const targetCount = this._targets.length; + const data = new Float32Array(targetCount * this._textureWidth * this._textureHeight * 4); + let offset = 0; + for (let index = 0; index < targetCount; index++) { + const target = this._targets[index]; + const positions = target.getPositions(); + const normals = target.getNormals(); + const uvs = target.getUVs(); + const tangents = target.getTangents(); + const uv2s = target.getUV2s(); + const colors = target.getColors(); + offset = index * this._textureWidth * this._textureHeight * 4; + for (let vertex = 0; vertex < this._vertexCount; vertex++) { + if (this._supportsPositions && positions) { + data[offset] = positions[vertex * 3]; + data[offset + 1] = positions[vertex * 3 + 1]; + data[offset + 2] = positions[vertex * 3 + 2]; + offset += 4; + } + if (this._supportsNormals && normals) { + data[offset] = normals[vertex * 3]; + data[offset + 1] = normals[vertex * 3 + 1]; + data[offset + 2] = normals[vertex * 3 + 2]; + offset += 4; + } + if (this._supportsUVs && uvs) { + data[offset] = uvs[vertex * 2]; + data[offset + 1] = uvs[vertex * 2 + 1]; + offset += 4; + } + if (this._supportsTangents && tangents) { + data[offset] = tangents[vertex * 3]; + data[offset + 1] = tangents[vertex * 3 + 1]; + data[offset + 2] = tangents[vertex * 3 + 2]; + offset += 4; + } + if (this._supportsUV2s && uv2s) { + data[offset] = uv2s[vertex * 2]; + data[offset + 1] = uv2s[vertex * 2 + 1]; + offset += 4; + } + if (this._supportsColors && colors) { + data[offset] = colors[vertex * 4]; + data[offset + 1] = colors[vertex * 4 + 1]; + data[offset + 2] = colors[vertex * 4 + 2]; + data[offset + 3] = colors[vertex * 4 + 3]; + offset += 4; + } + } + } + this._targetStoreTexture = RawTexture2DArray.CreateRGBATexture(data, this._textureWidth, this._textureHeight, targetCount, this._scene, false, false, 1, 1); + this._targetStoreTexture.name = `Morph texture_${this.uniqueId}`; + } + // Flag meshes as dirty to resync with the active targets + for (const mesh of this._scene.meshes) { + if (mesh.morphTargetManager === this) { + mesh._syncGeometryWithMorphTargetManager(); + } + } + } + /** + * Release all resources + */ + dispose() { + if (this._targetStoreTexture) { + this._targetStoreTexture.dispose(); + } + this._targetStoreTexture = null; + // Remove from scene + if (this._scene) { + this._scene.removeMorphTargetManager(this); + if (this._parentContainer) { + const index = this._parentContainer.morphTargetManagers.indexOf(this); + if (index > -1) { + this._parentContainer.morphTargetManagers.splice(index, 1); + } + this._parentContainer = null; + } + for (const morph of this._targets) { + this._scene.stopAnimation(morph); + } + } + } + // Statics + /** + * Creates a new MorphTargetManager from serialized data + * @param serializationObject defines the serialized data + * @param scene defines the hosting scene + * @returns the new MorphTargetManager + */ + static Parse(serializationObject, scene) { + const result = new MorphTargetManager(scene); + for (const targetData of serializationObject.targets) { + result.addTarget(MorphTarget.Parse(targetData, scene)); + } + return result; + } +} +/** Enable storing morph target data into textures when set to true (true by default) */ +MorphTargetManager.EnableTextureStorage = true; +/** Maximum number of active morph targets supported in the "vertex attribute" mode (i.e., not the "texture" mode) */ +MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode = 8; + +const _registeredGLTFExtensions = new Map(); +/** + * All currently registered glTF 2.0 loader extensions. + */ +const registeredGLTFExtensions = _registeredGLTFExtensions; +/** + * Registers a loader extension. + * @param name The name of the loader extension. + * @param isGLTFExtension If the loader extension is a glTF extension, then it will only be used for glTF files that use the corresponding glTF extension. Otherwise, it will be used for all loaded glTF files. + * @param factory The factory function that creates the loader extension. + */ +function registerGLTFExtension(name, isGLTFExtension, factory) { + if (unregisterGLTFExtension(name)) { + Logger.Warn(`Extension with the name '${name}' already exists`); + } + _registeredGLTFExtensions.set(name, { + isGLTFExtension, + factory, + }); +} +/** + * Unregisters a loader extension. + * @param name The name of the loader extension. + * @returns A boolean indicating whether the extension has been unregistered + */ +function unregisterGLTFExtension(name) { + return _registeredGLTFExtensions.delete(name); +} + +/** + * A converter that takes a glTF Object Model JSON Pointer + * and transforms it into an ObjectAccessorContainer, allowing + * objects referenced in the glTF to be associated with their + * respective Babylon.js objects. + */ +class GLTFPathToObjectConverter { + constructor(_gltf, _infoTree) { + this._gltf = _gltf; + this._infoTree = _infoTree; + } + /** + * The pointer string is represented by a [JSON pointer](https://datatracker.ietf.org/doc/html/rfc6901). + * See also https://github.com/KhronosGroup/glTF/blob/main/specification/2.0/ObjectModel.adoc#core-pointers + * := /// + * := "nodes" | "materials" | "meshes" | "cameras" | "extensions" + * := | + * := | + * := "extensions"// + * := | / + * := W+ + * := D+ + * + * Examples: + * - "/nodes/0/rotation" + * - "/nodes.length" + * - "/materials/2/emissiveFactor" + * - "/materials/2/pbrMetallicRoughness/baseColorFactor" + * - "/materials/2/extensions/KHR_materials_emissive_strength/emissiveStrength" + * + * @param path The path to convert + * @returns The object and info associated with the path + */ + convert(path) { + let objectTree = this._gltf; + let infoTree = this._infoTree; + let target = undefined; + if (!path.startsWith("/")) { + throw new Error("Path must start with a /"); + } + const parts = path.split("/"); + parts.shift(); + //if the last part has ".length" in it, separate that as an extra part + if (parts[parts.length - 1].includes(".length")) { + const lastPart = parts[parts.length - 1]; + const split = lastPart.split("."); + parts.pop(); + parts.push(...split); + } + let ignoreObjectTree = false; + for (const part of parts) { + const isLength = part === "length"; + if (isLength && !infoTree.__array__) { + throw new Error(`Path ${path} is invalid`); + } + if (infoTree.__ignoreObjectTree__) { + ignoreObjectTree = true; + } + if (infoTree.__array__ && !isLength) { + infoTree = infoTree.__array__; + } + else { + infoTree = infoTree[part]; + if (!infoTree) { + throw new Error(`Path ${path} is invalid`); + } + } + if (!ignoreObjectTree) { + if (objectTree === undefined) { + throw new Error(`Path ${path} is invalid`); + } + if (!isLength) { + objectTree = objectTree?.[part]; + } + } + if (infoTree.__target__ || isLength) { + target = objectTree; + } + } + return { + object: target, + info: infoTree, + }; + } +} + +/* eslint-disable @typescript-eslint/naming-convention */ +const nodesTree = { + length: { + type: "number", + get: (nodes) => nodes.length, + getTarget: (nodes) => nodes.map((node) => node._babylonTransformNode), + getPropertyName: [() => "length"], + }, + __array__: { + __target__: true, + translation: { + type: "Vector3", + get: (node) => node._babylonTransformNode?.position, + set: (value, node) => node._babylonTransformNode?.position.copyFrom(value), + getTarget: (node) => node._babylonTransformNode, + getPropertyName: [() => "position"], + }, + rotation: { + type: "Quaternion", + get: (node) => node._babylonTransformNode?.rotationQuaternion, + set: (value, node) => node._babylonTransformNode?.rotationQuaternion?.copyFrom(value), + getTarget: (node) => node._babylonTransformNode, + getPropertyName: [() => "rotationQuaternion"], + }, + scale: { + type: "Vector3", + get: (node) => node._babylonTransformNode?.scaling, + set: (value, node) => node._babylonTransformNode?.scaling.copyFrom(value), + getTarget: (node) => node._babylonTransformNode, + getPropertyName: [() => "scaling"], + }, + weights: { + length: { + type: "number", + get: (node) => node._numMorphTargets, + getTarget: (node) => node._babylonTransformNode, + getPropertyName: [() => "influence"], + }, + __array__: { + __target__: true, + type: "number", + get: (node, index) => (index !== undefined ? node._primitiveBabylonMeshes?.[0].morphTargetManager?.getTarget(index).influence : undefined), + // set: (value: number, node: INode, index?: number) => node._babylonTransformNode?.getMorphTargetManager()?.getTarget(index)?.setInfluence(value), + getTarget: (node) => node._babylonTransformNode, + getPropertyName: [() => "influence"], + }, + type: "number[]", + get: (node, index) => [0], // TODO: get the weights correctly + // set: (value: number, node: INode, index?: number) => node._babylonTransformNode?.getMorphTargetManager()?.getTarget(index)?.setInfluence(value), + getTarget: (node) => node._babylonTransformNode, + getPropertyName: [() => "influence"], + }, + // readonly! + matrix: { + type: "Matrix", + get: (node) => Matrix.Compose(node._babylonTransformNode?.scaling, node._babylonTransformNode?.rotationQuaternion, node._babylonTransformNode?.position), + getTarget: (node) => node._babylonTransformNode, + isReadOnly: true, + }, + globalMatrix: { + type: "Matrix", + get: (node) => { + const matrix = Matrix.Identity(); + // RHS/LHS support + let rootNode = node.parent; + while (rootNode && rootNode.parent) { + rootNode = rootNode.parent; + } + const forceUpdate = node._babylonTransformNode?.position._isDirty || node._babylonTransformNode?.rotationQuaternion?._isDirty || node._babylonTransformNode?.scaling._isDirty; + if (rootNode) { + // take the parent root node's world matrix, invert it, and multiply it with the current node's world matrix + // This will provide the global matrix, ignoring the RHS->LHS conversion + const rootMatrix = rootNode._babylonTransformNode?.computeWorldMatrix(true).invert(); + if (rootMatrix) { + node._babylonTransformNode?.computeWorldMatrix(forceUpdate)?.multiplyToRef(rootMatrix, matrix); + } + } + else if (node._babylonTransformNode) { + matrix.copyFrom(node._babylonTransformNode.computeWorldMatrix(forceUpdate)); + } + return matrix; + }, + getTarget: (node) => node._babylonTransformNode, + isReadOnly: true, + }, + extensions: { + EXT_lights_ies: { + multiplier: { + type: "number", + get: (node) => { + return node._babylonTransformNode?.getChildren((child) => child instanceof SpotLight, true)[0]?.intensity; + }, + getTarget: (node) => node._babylonTransformNode?.getChildren((child) => child instanceof SpotLight, true)[0], + set: (value, node) => { + if (node._babylonTransformNode) { + const light = node._babylonTransformNode.getChildren((child) => child instanceof SpotLight, true)[0]; + if (light) { + light.intensity = value; + } + } + }, + }, + color: { + type: "Color3", + get: (node) => { + return node._babylonTransformNode?.getChildren((child) => child instanceof SpotLight, true)[0]?.diffuse; + }, + getTarget: (node) => node._babylonTransformNode?.getChildren((child) => child instanceof SpotLight, true)[0], + set: (value, node) => { + if (node._babylonTransformNode) { + const light = node._babylonTransformNode.getChildren((child) => child instanceof SpotLight, true)[0]; + if (light) { + light.diffuse = value; + } + } + }, + }, + }, + }, + }, +}; +const animationsTree = { + length: { + type: "number", + get: (animations) => animations.length, + getTarget: (animations) => animations.map((animation) => animation._babylonAnimationGroup), + getPropertyName: [() => "length"], + }, + __array__: {}, +}; +const meshesTree = { + length: { + type: "number", + get: (meshes) => meshes.length, + getTarget: (meshes) => meshes.map((mesh) => mesh.primitives[0]._instanceData?.babylonSourceMesh), + getPropertyName: [() => "length"], + }, + __array__: {}, +}; +const camerasTree = { + __array__: { + __target__: true, + orthographic: { + xmag: { + componentsCount: 2, + type: "Vector2", + get: (camera) => new Vector2(camera._babylonCamera?.orthoLeft ?? 0, camera._babylonCamera?.orthoRight ?? 0), + set: (value, camera) => { + if (camera._babylonCamera) { + camera._babylonCamera.orthoLeft = value.x; + camera._babylonCamera.orthoRight = value.y; + } + }, + getTarget: (camera) => camera, + getPropertyName: [() => "orthoLeft", () => "orthoRight"], + }, + ymag: { + componentsCount: 2, + type: "Vector2", + get: (camera) => new Vector2(camera._babylonCamera?.orthoBottom ?? 0, camera._babylonCamera?.orthoTop ?? 0), + set: (value, camera) => { + if (camera._babylonCamera) { + camera._babylonCamera.orthoBottom = value.x; + camera._babylonCamera.orthoTop = value.y; + } + }, + getTarget: (camera) => camera, + getPropertyName: [() => "orthoBottom", () => "orthoTop"], + }, + zfar: { + type: "number", + get: (camera) => camera._babylonCamera?.maxZ, + set: (value, camera) => { + if (camera._babylonCamera) { + camera._babylonCamera.maxZ = value; + } + }, + getTarget: (camera) => camera, + getPropertyName: [() => "maxZ"], + }, + znear: { + type: "number", + get: (camera) => camera._babylonCamera?.minZ, + set: (value, camera) => { + if (camera._babylonCamera) { + camera._babylonCamera.minZ = value; + } + }, + getTarget: (camera) => camera, + getPropertyName: [() => "minZ"], + }, + }, + perspective: { + aspectRatio: { + type: "number", + get: (camera) => camera._babylonCamera?.getEngine().getAspectRatio(camera._babylonCamera), + getTarget: (camera) => camera, + getPropertyName: [() => "aspectRatio"], + isReadOnly: true, // might not be the case for glTF? + }, + yfov: { + type: "number", + get: (camera) => camera._babylonCamera?.fov, + set: (value, camera) => { + if (camera._babylonCamera) { + camera._babylonCamera.fov = value; + } + }, + getTarget: (camera) => camera, + getPropertyName: [() => "fov"], + }, + zfar: { + type: "number", + get: (camera) => camera._babylonCamera?.maxZ, + set: (value, camera) => { + if (camera._babylonCamera) { + camera._babylonCamera.maxZ = value; + } + }, + getTarget: (camera) => camera, + getPropertyName: [() => "maxZ"], + }, + znear: { + type: "number", + get: (camera) => camera._babylonCamera?.minZ, + set: (value, camera) => { + if (camera._babylonCamera) { + camera._babylonCamera.minZ = value; + } + }, + getTarget: (camera) => camera, + getPropertyName: [() => "minZ"], + }, + }, + }, +}; +const materialsTree = { + __array__: { + __target__: true, + emissiveFactor: { + type: "Color3", + get: (material, index, payload) => _GetMaterial(material, index, payload).emissiveColor, + set: (value, material, index, payload) => _GetMaterial(material, index, payload).emissiveColor.copyFrom(value), + getTarget: (material, index, payload) => _GetMaterial(material, index, payload), + getPropertyName: [() => "emissiveColor"], + }, + emissiveTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("emissiveTexture"), + }, + }, + normalTexture: { + scale: { + type: "number", + get: (material, index, payload) => _GetTexture(material, payload, "bumpTexture")?.level, + set: (value, material, index, payload) => { + const texture = _GetTexture(material, payload, "bumpTexture"); + if (texture) { + texture.level = value; + } + }, + getTarget: (material, index, payload) => _GetMaterial(material, index, payload), + getPropertyName: [() => "level"], + }, + extensions: { + KHR_texture_transform: _GenerateTextureMap("bumpTexture"), + }, + }, + occlusionTexture: { + strength: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).ambientTextureStrength, + set: (value, material, index, payload) => { + const mat = _GetMaterial(material, index, payload); + if (mat) { + mat.ambientTextureStrength = value; + } + }, + getTarget: (material, index, payload) => _GetMaterial(material, index, payload), + getPropertyName: [() => "ambientTextureStrength"], + }, + extensions: { + KHR_texture_transform: _GenerateTextureMap("ambientTexture"), + }, + }, + pbrMetallicRoughness: { + baseColorFactor: { + type: "Color4", + get: (material, index, payload) => { + const mat = _GetMaterial(material, index, payload); + return Color4.FromColor3(mat.albedoColor, mat.alpha); + }, + set: (value, material, index, payload) => { + const mat = _GetMaterial(material, index, payload); + mat.albedoColor.set(value.r, value.g, value.b); + mat.alpha = value.a; + }, + getTarget: (material, index, payload) => _GetMaterial(material, index, payload), + // This is correct on the animation level, but incorrect as a single property of a type Color4 + getPropertyName: [() => "albedoColor", () => "alpha"], + }, + baseColorTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("albedoTexture"), + }, + }, + metallicFactor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).metallic, + set: (value, material, index, payload) => { + const mat = _GetMaterial(material, index, payload); + if (mat) { + mat.metallic = value; + } + }, + getTarget: (material, index, payload) => _GetMaterial(material, index, payload), + getPropertyName: [() => "metallic"], + }, + roughnessFactor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).roughness, + set: (value, material, index, payload) => { + const mat = _GetMaterial(material, index, payload); + if (mat) { + mat.roughness = value; + } + }, + getTarget: (material, index, payload) => _GetMaterial(material, index, payload), + getPropertyName: [() => "roughness"], + }, + metallicRoughnessTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("metallicTexture"), + }, + }, + }, + extensions: { + KHR_materials_anisotropy: { + anisotropyStrength: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).anisotropy.intensity, + set: (value, material, index, payload) => { + _GetMaterial(material, index, payload).anisotropy.intensity = value; + }, + getTarget: (material, index, payload) => _GetMaterial(material, index, payload), + getPropertyName: [() => "anisotropy.intensity"], + }, + anisotropyRotation: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).anisotropy.angle, + set: (value, material, index, payload) => { + _GetMaterial(material, index, payload).anisotropy.angle = value; + }, + getTarget: (material, index, payload) => _GetMaterial(material, index, payload), + getPropertyName: [() => "anisotropy.angle"], + }, + anisotropyTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("anisotropy", "texture"), + }, + }, + }, + KHR_materials_clearcoat: { + clearcoatFactor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).clearCoat.intensity, + set: (value, material, index, payload) => { + _GetMaterial(material, index, payload).clearCoat.intensity = value; + }, + getTarget: (material, index, payload) => _GetMaterial(material, index, payload), + getPropertyName: [() => "clearCoat.intensity"], + }, + clearcoatRoughnessFactor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).clearCoat.roughness, + set: (value, material, index, payload) => { + _GetMaterial(material, index, payload).clearCoat.roughness = value; + }, + getTarget: (material, index, payload) => _GetMaterial(material, index, payload), + getPropertyName: [() => "clearCoat.roughness"], + }, + clearcoatTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("clearCoat", "texture"), + }, + }, + clearcoatNormalTexture: { + scale: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).clearCoat.bumpTexture?.level, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).clearCoat.bumpTexture.level = value), + }, + extensions: { + KHR_texture_transform: _GenerateTextureMap("clearCoat", "bumpTexture"), + }, + }, + clearcoatRoughnessTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("clearCoat", "textureRoughness"), + }, + }, + }, + KHR_materials_dispersion: { + dispersion: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.dispersion, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).subSurface.dispersion = value), + }, + }, + KHR_materials_emissive_strength: { + emissiveStrength: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).emissiveIntensity, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).emissiveIntensity = value), + }, + }, + KHR_materials_ior: { + ior: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).indexOfRefraction, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).indexOfRefraction = value), + }, + }, + KHR_materials_iridescence: { + iridescenceFactor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).iridescence.intensity, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).iridescence.intensity = value), + }, + iridescenceIor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).iridescence.indexOfRefraction, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).iridescence.indexOfRefraction = value), + }, + iridescenceTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("iridescence", "texture"), + }, + }, + iridescenceThicknessMaximum: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).iridescence.maximumThickness, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).iridescence.maximumThickness = value), + }, + iridescenceThicknessMinimum: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).iridescence.minimumThickness, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).iridescence.minimumThickness = value), + }, + iridescenceThicknessTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("iridescence", "thicknessTexture"), + }, + }, + }, + KHR_materials_sheen: { + sheenColorFactor: { + type: "Color3", + get: (material, index, payload) => _GetMaterial(material, index, payload).sheen.color, + getTarget: _GetMaterial, + set: (value, material, index, payload) => _GetMaterial(material, index, payload).sheen.color.copyFrom(value), + }, + sheenColorTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("sheen", "texture"), + }, + }, + sheenRoughnessFactor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).sheen.intensity, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).sheen.intensity = value), + }, + sheenRoughnessTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("sheen", "thicknessTexture"), + }, + }, + }, + KHR_materials_specular: { + specularFactor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).metallicF0Factor, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).metallicF0Factor = value), + getPropertyName: [() => "metallicF0Factor"], + }, + specularColorFactor: { + type: "Color3", + get: (material, index, payload) => _GetMaterial(material, index, payload).metallicReflectanceColor, + getTarget: _GetMaterial, + set: (value, material, index, payload) => _GetMaterial(material, index, payload).metallicReflectanceColor.copyFrom(value), + getPropertyName: [() => "metallicReflectanceColor"], + }, + specularTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("metallicReflectanceTexture"), + }, + }, + specularColorTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("reflectanceTexture"), + }, + }, + }, + KHR_materials_transmission: { + transmissionFactor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.refractionIntensity, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).subSurface.refractionIntensity = value), + getPropertyName: [() => "subSurface.refractionIntensity"], + }, + transmissionTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("subSurface", "refractionIntensityTexture"), + }, + }, + }, + KHR_materials_diffuse_transmission: { + diffuseTransmissionFactor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.translucencyIntensity, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).subSurface.translucencyIntensity = value), + }, + diffuseTransmissionTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("subSurface", "translucencyIntensityTexture"), + }, + }, + diffuseTransmissionColorFactor: { + type: "Color3", + get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.translucencyColor, + getTarget: _GetMaterial, + set: (value, material, index, payload) => value && _GetMaterial(material, index, payload).subSurface.translucencyColor?.copyFrom(value), + }, + diffuseTransmissionColorTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("subSurface", "translucencyColorTexture"), + }, + }, + }, + KHR_materials_volume: { + attenuationColor: { + type: "Color3", + get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.tintColor, + getTarget: _GetMaterial, + set: (value, material, index, payload) => _GetMaterial(material, index, payload).subSurface.tintColor.copyFrom(value), + }, + attenuationDistance: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.tintColorAtDistance, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).subSurface.tintColorAtDistance = value), + }, + thicknessFactor: { + type: "number", + get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.maximumThickness, + getTarget: _GetMaterial, + set: (value, material, index, payload) => (_GetMaterial(material, index, payload).subSurface.maximumThickness = value), + }, + thicknessTexture: { + extensions: { + KHR_texture_transform: _GenerateTextureMap("subSurface", "thicknessTexture"), + }, + }, + }, + }, + }, +}; +const extensionsTree = { + KHR_lights_punctual: { + lights: { + length: { + type: "number", + get: (lights) => lights.length, + getTarget: (lights) => lights.map((light) => light._babylonLight), + getPropertyName: [(_lights) => "length"], + }, + __array__: { + __target__: true, + color: { + type: "Color3", + get: (light) => light._babylonLight?.diffuse, + set: (value, light) => light._babylonLight?.diffuse.copyFrom(value), + getTarget: (light) => light._babylonLight, + getPropertyName: [(_light) => "diffuse"], + }, + intensity: { + type: "number", + get: (light) => light._babylonLight?.intensity, + set: (value, light) => (light._babylonLight ? (light._babylonLight.intensity = value) : undefined), + getTarget: (light) => light._babylonLight, + getPropertyName: [(_light) => "intensity"], + }, + range: { + type: "number", + get: (light) => light._babylonLight?.range, + set: (value, light) => (light._babylonLight ? (light._babylonLight.range = value) : undefined), + getTarget: (light) => light._babylonLight, + getPropertyName: [(_light) => "range"], + }, + spot: { + innerConeAngle: { + type: "number", + get: (light) => light._babylonLight?.innerAngle, + set: (value, light) => (light._babylonLight ? (light._babylonLight.innerAngle = value) : undefined), + getTarget: (light) => light._babylonLight, + getPropertyName: [(_light) => "innerConeAngle"], + }, + outerConeAngle: { + type: "number", + get: (light) => light._babylonLight?.angle, + set: (value, light) => (light._babylonLight ? (light._babylonLight.angle = value) : undefined), + getTarget: (light) => light._babylonLight, + getPropertyName: [(_light) => "outerConeAngle"], + }, + }, + }, + }, + }, + EXT_lights_ies: { + lights: { + length: { + type: "number", + get: (lights) => lights.length, + getTarget: (lights) => lights.map((light) => light._babylonLight), + getPropertyName: [(_lights) => "length"], + }, + }, + }, + EXT_lights_image_based: { + lights: { + length: { + type: "number", + get: (lights) => lights.length, + getTarget: (lights) => lights.map((light) => light._babylonTexture), + getPropertyName: [(_lights) => "length"], + }, + __array__: { + __target__: true, + intensity: { + type: "number", + get: (light) => light._babylonTexture?.level, + set: (value, light) => { + if (light._babylonTexture) + light._babylonTexture.level = value; + }, + getTarget: (light) => light._babylonTexture, + }, + rotation: { + type: "Quaternion", + get: (light) => light._babylonTexture && Quaternion.FromRotationMatrix(light._babylonTexture?.getReflectionTextureMatrix()), + set: (value, light) => { + if (!light._babylonTexture) + return; + // Invert the rotation so that positive rotation is counter-clockwise. + if (!light._babylonTexture.getScene()?.useRightHandedSystem) { + value = Quaternion.Inverse(value); + } + Matrix.FromQuaternionToRef(value, light._babylonTexture.getReflectionTextureMatrix()); + }, + getTarget: (light) => light._babylonTexture, + }, + }, + }, + }, +}; +function _GetTexture(material, payload, textureType, textureInObject) { + const babylonMaterial = _GetMaterial(material); + return textureInObject ? babylonMaterial[textureType][textureInObject] : babylonMaterial[textureType]; +} +function _GetMaterial(material, _index, payload) { + return material._data?.[payload?.fillMode ?? Constants.MATERIAL_TriangleFillMode]?.babylonMaterial; +} +function _GenerateTextureMap(textureType, textureInObject) { + return { + offset: { + componentsCount: 2, + // assuming two independent values for u and v, and NOT a Vector2 + type: "Vector2", + get: (material, _index, payload) => { + const texture = _GetTexture(material, payload, textureType, textureInObject); + return new Vector2(texture?.uOffset, texture?.vOffset); + }, + getTarget: _GetMaterial, + set: (value, material, _index, payload) => { + const texture = _GetTexture(material, payload, textureType, textureInObject); + (texture.uOffset = value.x), (texture.vOffset = value.y); + }, + getPropertyName: [ + () => `${textureType}${textureInObject ? "." + textureInObject : ""}.uOffset`, + () => `${textureType}${textureInObject ? "." + textureInObject : ""}.vOffset`, + ], + }, + rotation: { + type: "number", + get: (material, _index, payload) => _GetTexture(material, payload, textureType, textureInObject)?.wAng, + getTarget: _GetMaterial, + set: (value, material, _index, payload) => (_GetTexture(material, payload, textureType, textureInObject).wAng = value), + getPropertyName: [() => `${textureType}${textureInObject ? "." + textureInObject : ""}.wAng`], + }, + scale: { + componentsCount: 2, + type: "Vector2", + get: (material, _index, payload) => { + const texture = _GetTexture(material, payload, textureType, textureInObject); + return new Vector2(texture?.uScale, texture?.vScale); + }, + getTarget: _GetMaterial, + set: (value, material, index, payload) => { + const texture = _GetTexture(material, payload, textureType, textureInObject); + (texture.uScale = value.x), (texture.vScale = value.y); + }, + getPropertyName: [ + () => `${textureType}${textureInObject ? "." + textureInObject : ""}.uScale`, + () => `${textureType}${textureInObject ? "." + textureInObject : ""}.vScale`, + ], + }, + }; +} +const objectModelMapping = { + cameras: camerasTree, + nodes: nodesTree, + materials: materialsTree, + extensions: extensionsTree, + animations: animationsTree, + meshes: meshesTree, +}; +/** + * get a path-to-object converter for the given glTF tree + * @param gltf the glTF tree to use + * @returns a path-to-object converter for the given glTF tree + */ +function GetPathToObjectConverter(gltf) { + return new GLTFPathToObjectConverter(gltf, objectModelMapping); +} +/** + * This function will return the object accessor for the given key in the object model + * If the key is not found, it will return undefined + * @param key the key to get the mapping for, for example /materials/\{\}/emissiveFactor + * @returns an object accessor for the given key, or undefined if the key is not found + */ +function GetMappingForKey(key) { + // replace every `{}` in key with __array__ to match the object model + const keyParts = key.split("/").map((part) => part.replace(/{}/g, "__array__")); + let current = objectModelMapping; + for (const part of keyParts) { + // make sure part is not empty + if (!part) { + continue; + } + current = current[part]; + } + // validate that current is an object accessor + if (current && current.type && current.get) { + return current; + } + return undefined; +} +/** + * Set interpolation for a specific key in the object model + * @param key the key to set, for example /materials/\{\}/emissiveFactor + * @param interpolation the interpolation elements array + */ +function SetInterpolationForKey(key, interpolation) { + // replace every `{}` in key with __array__ to match the object model + const keyParts = key.split("/").map((part) => part.replace(/{}/g, "__array__")); + let current = objectModelMapping; + for (const part of keyParts) { + // make sure part is not empty + if (!part) { + continue; + } + current = current[part]; + } + // validate that the current object is an object accessor + if (current && current.type && current.get) { + current.interpolation = interpolation; + } +} +/** + * This will ad a new object accessor in the object model at the given key. + * Note that this will NOT change the typescript types. To do that you will need to change the interface itself (extending it in the module that uses it) + * @param key the key to add the object accessor at. For example /cameras/\{\}/perspective/aspectRatio + * @param accessor the object accessor to add + */ +function AddObjectAccessorToKey(key, accessor) { + // replace every `{}` in key with __array__ to match the object model + const keyParts = key.split("/").map((part) => part.replace(/{}/g, "__array__")); + let current = objectModelMapping; + for (const part of keyParts) { + // make sure part is not empty + if (!part) { + continue; + } + if (!current[part]) { + if (part === "?") { + current.__ignoreObjectTree__ = true; + continue; + } + current[part] = {}; + // if the part is __array__ then add the __target__ property + if (part === "__array__") { + current[part].__target__ = true; + } + } + current = current[part]; + } + Object.assign(current, accessor); +} + +// https://stackoverflow.com/a/48218209 +/** + * Merges a series of objects into a single object, deeply. + * @param objects The objects to merge (objects later in the list take precedence). + * @returns The merged object. + */ +function deepMerge(...objects) { + const isRecord = (obj) => !!obj && typeof obj === "object"; + return objects.reduce((prev, obj) => { + Object.keys(obj).forEach((key) => { + const pVal = prev[key]; + const oVal = obj[key]; + if (Array.isArray(pVal) && Array.isArray(oVal)) { + prev[key] = pVal.concat(...oVal); + } + else if (isRecord(pVal) && isRecord(oVal)) { + prev[key] = deepMerge(pVal, oVal); + } + else { + prev[key] = oVal; + } + }); + return prev; + }, {}); +} + +/** + * Helper class for working with arrays when loading the glTF asset + */ +class ArrayItem { + /** + * Gets an item from the given array. + * @param context The context when loading the asset + * @param array The array to get the item from + * @param index The index to the array + * @returns The array item + */ + static Get(context, array, index) { + if (!array || index == undefined || !array[index]) { + throw new Error(`${context}: Failed to find index (${index})`); + } + return array[index]; + } + /** + * Gets an item from the given array or returns null if not available. + * @param array The array to get the item from + * @param index The index to the array + * @returns The array item or null + */ + static TryGet(array, index) { + if (!array || index == undefined || !array[index]) { + return null; + } + return array[index]; + } + /** + * Assign an `index` field to each item of the given array. + * @param array The array of items + */ + static Assign(array) { + if (array) { + for (let index = 0; index < array.length; index++) { + array[index].index = index; + } + } + } +} +/** @internal */ +function LoadBoundingInfoFromPositionAccessor(accessor) { + if (accessor.min && accessor.max) { + const minArray = accessor.min; + const maxArray = accessor.max; + const minVector = TmpVectors.Vector3[0].copyFromFloats(minArray[0], minArray[1], minArray[2]); + const maxVector = TmpVectors.Vector3[1].copyFromFloats(maxArray[0], maxArray[1], maxArray[2]); + if (accessor.normalized && accessor.componentType !== 5126 /* AccessorComponentType.FLOAT */) { + let divider = 1; + switch (accessor.componentType) { + case 5120 /* AccessorComponentType.BYTE */: + divider = 127.0; + break; + case 5121 /* AccessorComponentType.UNSIGNED_BYTE */: + divider = 255.0; + break; + case 5122 /* AccessorComponentType.SHORT */: + divider = 32767.0; + break; + case 5123 /* AccessorComponentType.UNSIGNED_SHORT */: + divider = 65535.0; + break; + } + const oneOverDivider = 1 / divider; + minVector.scaleInPlace(oneOverDivider); + maxVector.scaleInPlace(oneOverDivider); + } + return new BoundingInfo(minVector, maxVector); + } + return null; +} +/** + * The glTF 2.0 loader + */ +class GLTFLoader { + /** + * Registers a loader extension. + * @param name The name of the loader extension. + * @param factory The factory function that creates the loader extension. + * @deprecated Please use registerGLTFExtension instead. + */ + static RegisterExtension(name, factory) { + registerGLTFExtension(name, false, factory); + } + /** + * Unregisters a loader extension. + * @param name The name of the loader extension. + * @returns A boolean indicating whether the extension has been unregistered + * @deprecated Please use unregisterGLTFExtension instead. + */ + static UnregisterExtension(name) { + return unregisterGLTFExtension(name); + } + /** + * The object that represents the glTF JSON. + */ + get gltf() { + if (!this._gltf) { + throw new Error("glTF JSON is not available"); + } + return this._gltf; + } + /** + * The BIN chunk of a binary glTF. + */ + get bin() { + return this._bin; + } + /** + * The parent file loader. + */ + get parent() { + return this._parent; + } + /** + * The Babylon scene when loading the asset. + */ + get babylonScene() { + if (!this._babylonScene) { + throw new Error("Scene is not available"); + } + return this._babylonScene; + } + /** + * The root Babylon node when loading the asset. + */ + get rootBabylonMesh() { + return this._rootBabylonMesh; + } + /** + * The root url when loading the asset. + */ + get rootUrl() { + return this._rootUrl; + } + /** + * @internal + */ + constructor(parent) { + /** @internal */ + this._completePromises = new Array(); + /** @internal */ + this._assetContainer = null; + /** Storage */ + this._babylonLights = []; + /** @internal */ + this._disableInstancedMesh = 0; + /** @internal */ + this._allMaterialsDirtyRequired = false; + /** @internal */ + this._skipStartAnimationStep = false; + this._extensions = new Array(); + this._disposed = false; + this._rootUrl = null; + this._fileName = null; + this._uniqueRootUrl = null; + this._bin = null; + this._rootBabylonMesh = null; + this._defaultBabylonMaterialData = {}; + this._postSceneLoadActions = new Array(); + this._parent = parent; + } + /** @internal */ + dispose() { + if (this._disposed) { + return; + } + this._disposed = true; + this._completePromises.length = 0; + this._extensions.forEach((extension) => extension.dispose && extension.dispose()); + this._extensions.length = 0; + this._gltf = null; // TODO + this._bin = null; + this._babylonScene = null; // TODO + this._rootBabylonMesh = null; + this._defaultBabylonMaterialData = {}; + this._postSceneLoadActions.length = 0; + this._parent.dispose(); + } + /** + * @internal + */ + importMeshAsync(meshesNames, scene, container, data, rootUrl, onProgress, fileName = "") { + return Promise.resolve().then(() => { + this._babylonScene = scene; + this._assetContainer = container; + this._loadData(data); + let nodes = null; + if (meshesNames) { + const nodeMap = {}; + if (this._gltf.nodes) { + for (const node of this._gltf.nodes) { + if (node.name) { + nodeMap[node.name] = node.index; + } + } + } + const names = meshesNames instanceof Array ? meshesNames : [meshesNames]; + nodes = names.map((name) => { + const node = nodeMap[name]; + if (node === undefined) { + throw new Error(`Failed to find node '${name}'`); + } + return node; + }); + } + return this._loadAsync(rootUrl, fileName, nodes, () => { + return { + meshes: this._getMeshes(), + particleSystems: [], + skeletons: this._getSkeletons(), + animationGroups: this._getAnimationGroups(), + lights: this._babylonLights, + transformNodes: this._getTransformNodes(), + geometries: this._getGeometries(), + spriteManagers: [], + }; + }); + }); + } + /** + * @internal + */ + loadAsync(scene, data, rootUrl, onProgress, fileName = "") { + return Promise.resolve().then(() => { + this._babylonScene = scene; + this._loadData(data); + return this._loadAsync(rootUrl, fileName, null, () => undefined); + }); + } + _loadAsync(rootUrl, fileName, nodes, resultFunc) { + return Promise.resolve() + .then(async () => { + this._rootUrl = rootUrl; + this._uniqueRootUrl = !rootUrl.startsWith("file:") && fileName ? rootUrl : `${rootUrl}${Date.now()}/`; + this._fileName = fileName; + this._allMaterialsDirtyRequired = false; + await this._loadExtensionsAsync(); + const loadingToReadyCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.READY]}`; + const loadingToCompleteCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.COMPLETE]}`; + this._parent._startPerformanceCounter(loadingToReadyCounterName); + this._parent._startPerformanceCounter(loadingToCompleteCounterName); + this._parent._setState(GLTFLoaderState.LOADING); + this._extensionsOnLoading(); + const promises = new Array(); + // Block the marking of materials dirty until the scene is loaded. + const oldBlockMaterialDirtyMechanism = this._babylonScene.blockMaterialDirtyMechanism; + this._babylonScene.blockMaterialDirtyMechanism = true; + if (!this.parent.loadOnlyMaterials) { + if (nodes) { + promises.push(this.loadSceneAsync("/nodes", { nodes: nodes, index: -1 })); + } + else if (this._gltf.scene != undefined || (this._gltf.scenes && this._gltf.scenes[0])) { + const scene = ArrayItem.Get(`/scene`, this._gltf.scenes, this._gltf.scene || 0); + promises.push(this.loadSceneAsync(`/scenes/${scene.index}`, scene)); + } + } + if (!this.parent.skipMaterials && this.parent.loadAllMaterials && this._gltf.materials) { + for (let m = 0; m < this._gltf.materials.length; ++m) { + const material = this._gltf.materials[m]; + const context = "/materials/" + m; + const babylonDrawMode = Material.TriangleFillMode; + promises.push(this._loadMaterialAsync(context, material, null, babylonDrawMode, () => { })); + } + } + // Restore the blocking of material dirty. + if (this._allMaterialsDirtyRequired) { + // This can happen if we add a light for instance as it will impact the whole scene. + // This automatically resets everything if needed. + this._babylonScene.blockMaterialDirtyMechanism = oldBlockMaterialDirtyMechanism; + } + else { + // By default a newly created material is dirty so there is no need to flag the full scene as dirty. + // For perf reasons, we then bypass blockMaterialDirtyMechanism as this would "dirty" the entire scene. + this._babylonScene._forceBlockMaterialDirtyMechanism(oldBlockMaterialDirtyMechanism); + } + if (this._parent.compileMaterials) { + promises.push(this._compileMaterialsAsync()); + } + if (this._parent.compileShadowGenerators) { + promises.push(this._compileShadowGeneratorsAsync()); + } + const resultPromise = Promise.all(promises).then(() => { + if (this._rootBabylonMesh && this._rootBabylonMesh !== this._parent.customRootNode) { + this._rootBabylonMesh.setEnabled(true); + } + // Making sure we enable enough lights to have all lights together + for (const material of this._babylonScene.materials) { + const mat = material; + if (mat.maxSimultaneousLights !== undefined) { + mat.maxSimultaneousLights = Math.max(mat.maxSimultaneousLights, this._babylonScene.lights.length); + } + } + this._extensionsOnReady(); + this._parent._setState(GLTFLoaderState.READY); + if (!this._skipStartAnimationStep) { + this._startAnimations(); + } + return resultFunc(); + }); + return resultPromise.then((result) => { + this._parent._endPerformanceCounter(loadingToReadyCounterName); + Tools.SetImmediate(() => { + if (!this._disposed) { + Promise.all(this._completePromises).then(() => { + this._parent._endPerformanceCounter(loadingToCompleteCounterName); + this._parent._setState(GLTFLoaderState.COMPLETE); + this._parent.onCompleteObservable.notifyObservers(undefined); + this._parent.onCompleteObservable.clear(); + this.dispose(); + }, (error) => { + this._parent.onErrorObservable.notifyObservers(error); + this._parent.onErrorObservable.clear(); + this.dispose(); + }); + } + }); + return result; + }); + }) + .catch((error) => { + if (!this._disposed) { + this._parent.onErrorObservable.notifyObservers(error); + this._parent.onErrorObservable.clear(); + this.dispose(); + } + throw error; + }); + } + _loadData(data) { + this._gltf = data.json; + this._setupData(); + if (data.bin) { + const buffers = this._gltf.buffers; + if (buffers && buffers[0] && !buffers[0].uri) { + const binaryBuffer = buffers[0]; + if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) { + Logger.Warn(`Binary buffer length (${binaryBuffer.byteLength}) from JSON does not match chunk length (${data.bin.byteLength})`); + } + this._bin = data.bin; + } + else { + Logger.Warn("Unexpected BIN chunk"); + } + } + } + _setupData() { + ArrayItem.Assign(this._gltf.accessors); + ArrayItem.Assign(this._gltf.animations); + ArrayItem.Assign(this._gltf.buffers); + ArrayItem.Assign(this._gltf.bufferViews); + ArrayItem.Assign(this._gltf.cameras); + ArrayItem.Assign(this._gltf.images); + ArrayItem.Assign(this._gltf.materials); + ArrayItem.Assign(this._gltf.meshes); + ArrayItem.Assign(this._gltf.nodes); + ArrayItem.Assign(this._gltf.samplers); + ArrayItem.Assign(this._gltf.scenes); + ArrayItem.Assign(this._gltf.skins); + ArrayItem.Assign(this._gltf.textures); + if (this._gltf.nodes) { + const nodeParents = {}; + for (const node of this._gltf.nodes) { + if (node.children) { + for (const index of node.children) { + nodeParents[index] = node.index; + } + } + } + const rootNode = this._createRootNode(); + for (const node of this._gltf.nodes) { + const parentIndex = nodeParents[node.index]; + node.parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex]; + } + } + } + async _loadExtensionsAsync() { + const extensionPromises = []; + registeredGLTFExtensions.forEach((registeredExtension, name) => { + // Don't load explicitly disabled extensions. + if (this.parent.extensionOptions[name]?.enabled === false) { + // But warn if the disabled extension is used by the model. + if (registeredExtension.isGLTFExtension && this.isExtensionUsed(name)) { + Logger.Warn(`Extension ${name} is used but has been explicitly disabled.`); + } + } + // Load loader extensions that are not a glTF extension, as well as extensions that are glTF extensions and are used by the model. + else if (!registeredExtension.isGLTFExtension || this.isExtensionUsed(name)) { + extensionPromises.push((async () => { + const extension = await registeredExtension.factory(this); + if (extension.name !== name) { + Logger.Warn(`The name of the glTF loader extension instance does not match the registered name: ${extension.name} !== ${name}`); + } + this._parent.onExtensionLoadedObservable.notifyObservers(extension); + return extension; + })()); + } + }); + this._extensions.push(...(await Promise.all(extensionPromises))); + this._extensions.sort((a, b) => (a.order || Number.MAX_VALUE) - (b.order || Number.MAX_VALUE)); + this._parent.onExtensionLoadedObservable.clear(); + if (this._gltf.extensionsRequired) { + for (const name of this._gltf.extensionsRequired) { + const available = this._extensions.some((extension) => extension.name === name && extension.enabled); + if (!available) { + if (this.parent.extensionOptions[name]?.enabled === false) { + throw new Error(`Required extension ${name} is disabled`); + } + throw new Error(`Required extension ${name} is not available`); + } + } + } + } + _createRootNode() { + if (this._parent.customRootNode !== undefined) { + this._rootBabylonMesh = this._parent.customRootNode; + return { + // eslint-disable-next-line @typescript-eslint/naming-convention + _babylonTransformNode: this._rootBabylonMesh === null ? undefined : this._rootBabylonMesh, + index: -1, + }; + } + this._babylonScene._blockEntityCollection = !!this._assetContainer; + const rootMesh = new Mesh("__root__", this._babylonScene); + this._rootBabylonMesh = rootMesh; + this._rootBabylonMesh._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + this._rootBabylonMesh.setEnabled(false); + const rootNode = { + // eslint-disable-next-line @typescript-eslint/naming-convention + _babylonTransformNode: this._rootBabylonMesh, + index: -1, + }; + switch (this._parent.coordinateSystemMode) { + case GLTFLoaderCoordinateSystemMode.AUTO: { + if (!this._babylonScene.useRightHandedSystem) { + rootNode.rotation = [0, 1, 0, 0]; + rootNode.scale = [1, 1, -1]; + GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh); + } + break; + } + case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: { + this._babylonScene.useRightHandedSystem = true; + break; + } + default: { + throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`); + } + } + this._parent.onMeshLoadedObservable.notifyObservers(rootMesh); + return rootNode; + } + /** + * Loads a glTF scene. + * @param context The context when loading the asset + * @param scene The glTF scene property + * @returns A promise that resolves when the load is complete + */ + loadSceneAsync(context, scene) { + const extensionPromise = this._extensionsLoadSceneAsync(context, scene); + if (extensionPromise) { + return extensionPromise; + } + const promises = new Array(); + this.logOpen(`${context} ${scene.name || ""}`); + if (scene.nodes) { + for (const index of scene.nodes) { + const node = ArrayItem.Get(`${context}/nodes/${index}`, this._gltf.nodes, index); + promises.push(this.loadNodeAsync(`/nodes/${node.index}`, node, (babylonMesh) => { + babylonMesh.parent = this._rootBabylonMesh; + })); + } + } + for (const action of this._postSceneLoadActions) { + action(); + } + promises.push(this._loadAnimationsAsync()); + this.logClose(); + return Promise.all(promises).then(() => { }); + } + _forEachPrimitive(node, callback) { + if (node._primitiveBabylonMeshes) { + for (const babylonMesh of node._primitiveBabylonMeshes) { + callback(babylonMesh); + } + } + } + _getGeometries() { + const geometries = []; + const nodes = this._gltf.nodes; + if (nodes) { + for (const node of nodes) { + this._forEachPrimitive(node, (babylonMesh) => { + const geometry = babylonMesh.geometry; + if (geometry && geometries.indexOf(geometry) === -1) { + geometries.push(geometry); + } + }); + } + } + return geometries; + } + _getMeshes() { + const meshes = []; + // Root mesh is always first, if available. + if (this._rootBabylonMesh instanceof AbstractMesh) { + meshes.push(this._rootBabylonMesh); + } + const nodes = this._gltf.nodes; + if (nodes) { + for (const node of nodes) { + this._forEachPrimitive(node, (babylonMesh) => { + meshes.push(babylonMesh); + }); + } + } + return meshes; + } + _getTransformNodes() { + const transformNodes = []; + const nodes = this._gltf.nodes; + if (nodes) { + for (const node of nodes) { + if (node._babylonTransformNode && node._babylonTransformNode.getClassName() === "TransformNode") { + transformNodes.push(node._babylonTransformNode); + } + if (node._babylonTransformNodeForSkin) { + transformNodes.push(node._babylonTransformNodeForSkin); + } + } + } + return transformNodes; + } + _getSkeletons() { + const skeletons = []; + const skins = this._gltf.skins; + if (skins) { + for (const skin of skins) { + if (skin._data) { + skeletons.push(skin._data.babylonSkeleton); + } + } + } + return skeletons; + } + _getAnimationGroups() { + const animationGroups = []; + const animations = this._gltf.animations; + if (animations) { + for (const animation of animations) { + if (animation._babylonAnimationGroup) { + animationGroups.push(animation._babylonAnimationGroup); + } + } + } + return animationGroups; + } + _startAnimations() { + switch (this._parent.animationStartMode) { + case GLTFLoaderAnimationStartMode.NONE: { + // do nothing + break; + } + case GLTFLoaderAnimationStartMode.FIRST: { + const babylonAnimationGroups = this._getAnimationGroups(); + if (babylonAnimationGroups.length !== 0) { + babylonAnimationGroups[0].start(true); + } + break; + } + case GLTFLoaderAnimationStartMode.ALL: { + const babylonAnimationGroups = this._getAnimationGroups(); + for (const babylonAnimationGroup of babylonAnimationGroups) { + babylonAnimationGroup.start(true); + } + break; + } + default: { + Logger.Error(`Invalid animation start mode (${this._parent.animationStartMode})`); + return; + } + } + } + /** + * Loads a glTF node. + * @param context The context when loading the asset + * @param node The glTF node property + * @param assign A function called synchronously after parsing the glTF properties + * @returns A promise that resolves with the loaded Babylon mesh when the load is complete + */ + loadNodeAsync(context, node, assign = () => { }) { + const extensionPromise = this._extensionsLoadNodeAsync(context, node, assign); + if (extensionPromise) { + return extensionPromise; + } + if (node._babylonTransformNode) { + throw new Error(`${context}: Invalid recursive node hierarchy`); + } + const promises = new Array(); + this.logOpen(`${context} ${node.name || ""}`); + const loadNode = (babylonTransformNode) => { + GLTFLoader.AddPointerMetadata(babylonTransformNode, context); + GLTFLoader._LoadTransform(node, babylonTransformNode); + if (node.camera != undefined) { + const camera = ArrayItem.Get(`${context}/camera`, this._gltf.cameras, node.camera); + promises.push(this.loadCameraAsync(`/cameras/${camera.index}`, camera, (babylonCamera) => { + babylonCamera.parent = babylonTransformNode; + })); + } + if (node.children) { + for (const index of node.children) { + const childNode = ArrayItem.Get(`${context}/children/${index}`, this._gltf.nodes, index); + promises.push(this.loadNodeAsync(`/nodes/${childNode.index}`, childNode, (childBabylonMesh) => { + childBabylonMesh.parent = babylonTransformNode; + })); + } + } + assign(babylonTransformNode); + }; + const hasMesh = node.mesh != undefined; + const hasSkin = this._parent.loadSkins && node.skin != undefined; + if (!hasMesh || hasSkin) { + const nodeName = node.name || `node${node.index}`; + this._babylonScene._blockEntityCollection = !!this._assetContainer; + const transformNode = new TransformNode(nodeName, this._babylonScene); + transformNode._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + if (node.mesh == undefined) { + node._babylonTransformNode = transformNode; + } + else { + node._babylonTransformNodeForSkin = transformNode; + } + loadNode(transformNode); + } + if (hasMesh) { + if (hasSkin) { + // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note) + // This code path will place the skinned mesh as a sibling of the skeleton root node without loading the + // transform, which effectively ignores the transform of the skinned mesh, as per spec. + const mesh = ArrayItem.Get(`${context}/mesh`, this._gltf.meshes, node.mesh); + promises.push(this._loadMeshAsync(`/meshes/${mesh.index}`, node, mesh, (babylonTransformNode) => { + const babylonTransformNodeForSkin = node._babylonTransformNodeForSkin; + // Merge the metadata from the skin node to the skinned mesh in case a loader extension added metadata. + babylonTransformNode.metadata = deepMerge(babylonTransformNodeForSkin.metadata, babylonTransformNode.metadata || {}); + const skin = ArrayItem.Get(`${context}/skin`, this._gltf.skins, node.skin); + promises.push(this._loadSkinAsync(`/skins/${skin.index}`, node, skin, (babylonSkeleton) => { + this._forEachPrimitive(node, (babylonMesh) => { + babylonMesh.skeleton = babylonSkeleton; + }); + // Wait until all the nodes are parented before parenting the skinned mesh. + this._postSceneLoadActions.push(() => { + if (skin.skeleton != undefined) { + // Place the skinned mesh node as a sibling of the skeleton root node. + // Handle special case when the parent of the skeleton root is the skinned mesh. + const parentNode = ArrayItem.Get(`/skins/${skin.index}/skeleton`, this._gltf.nodes, skin.skeleton).parent; + if (node.index === parentNode.index) { + babylonTransformNode.parent = babylonTransformNodeForSkin.parent; + } + else { + babylonTransformNode.parent = parentNode._babylonTransformNode; + } + } + else { + babylonTransformNode.parent = this._rootBabylonMesh; + } + this._parent.onSkinLoadedObservable.notifyObservers({ node: babylonTransformNodeForSkin, skinnedNode: babylonTransformNode }); + }); + })); + })); + } + else { + const mesh = ArrayItem.Get(`${context}/mesh`, this._gltf.meshes, node.mesh); + promises.push(this._loadMeshAsync(`/meshes/${mesh.index}`, node, mesh, loadNode)); + } + } + this.logClose(); + return Promise.all(promises).then(() => { + this._forEachPrimitive(node, (babylonMesh) => { + const asMesh = babylonMesh; + if (!asMesh.isAnInstance && asMesh.geometry && asMesh.geometry.useBoundingInfoFromGeometry) { + // simply apply the world matrices to the bounding info - the extends are already ok + babylonMesh._updateBoundingInfo(); + } + else { + babylonMesh.refreshBoundingInfo(true, true); + } + }); + return node._babylonTransformNode; + }); + } + _loadMeshAsync(context, node, mesh, assign) { + const primitives = mesh.primitives; + if (!primitives || !primitives.length) { + throw new Error(`${context}: Primitives are missing`); + } + if (primitives[0].index == undefined) { + ArrayItem.Assign(primitives); + } + const promises = new Array(); + this.logOpen(`${context} ${mesh.name || ""}`); + const name = node.name || `node${node.index}`; + if (primitives.length === 1) { + const primitive = mesh.primitives[0]; + promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, name, node, mesh, primitive, (babylonMesh) => { + node._babylonTransformNode = babylonMesh; + node._primitiveBabylonMeshes = [babylonMesh]; + })); + } + else { + this._babylonScene._blockEntityCollection = !!this._assetContainer; + node._babylonTransformNode = new TransformNode(name, this._babylonScene); + node._babylonTransformNode._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + node._primitiveBabylonMeshes = []; + for (const primitive of primitives) { + promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, `${name}_primitive${primitive.index}`, node, mesh, primitive, (babylonMesh) => { + babylonMesh.parent = node._babylonTransformNode; + node._primitiveBabylonMeshes.push(babylonMesh); + })); + } + } + assign(node._babylonTransformNode); + this.logClose(); + return Promise.all(promises).then(() => { + return node._babylonTransformNode; + }); + } + /** + * @internal Define this method to modify the default behavior when loading data for mesh primitives. + * @param context The context when loading the asset + * @param name The mesh name when loading the asset + * @param node The glTF node when loading the asset + * @param mesh The glTF mesh when loading the asset + * @param primitive The glTF mesh primitive property + * @param assign A function called synchronously after parsing the glTF properties + * @returns A promise that resolves with the loaded mesh when the load is complete or null if not handled + */ + _loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign) { + const extensionPromise = this._extensionsLoadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign); + if (extensionPromise) { + return extensionPromise; + } + this.logOpen(`${context}`); + const shouldInstance = this._disableInstancedMesh === 0 && this._parent.createInstances && node.skin == undefined && !mesh.primitives[0].targets; + let babylonAbstractMesh; + let promise; + if (shouldInstance && primitive._instanceData) { + this._babylonScene._blockEntityCollection = !!this._assetContainer; + babylonAbstractMesh = primitive._instanceData.babylonSourceMesh.createInstance(name); + babylonAbstractMesh._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + promise = primitive._instanceData.promise; + } + else { + const promises = new Array(); + this._babylonScene._blockEntityCollection = !!this._assetContainer; + const babylonMesh = new Mesh(name, this._babylonScene); + babylonMesh._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + babylonMesh.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation; + this._createMorphTargets(context, node, mesh, primitive, babylonMesh); + promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then((babylonGeometry) => { + return this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(() => { + if (this._disposed) { + return; + } + this._babylonScene._blockEntityCollection = !!this._assetContainer; + babylonGeometry.applyToMesh(babylonMesh); + babylonGeometry._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + }); + })); + const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode); + if (primitive.material == undefined) { + let babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode]; + if (!babylonMaterial) { + babylonMaterial = this._createDefaultMaterial("__GLTFLoader._default", babylonDrawMode); + this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial); + this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial; + } + babylonMesh.material = babylonMaterial; + } + else if (!this.parent.skipMaterials) { + const material = ArrayItem.Get(`${context}/material`, this._gltf.materials, primitive.material); + promises.push(this._loadMaterialAsync(`/materials/${material.index}`, material, babylonMesh, babylonDrawMode, (babylonMaterial) => { + babylonMesh.material = babylonMaterial; + })); + } + promise = Promise.all(promises); + if (shouldInstance) { + primitive._instanceData = { + babylonSourceMesh: babylonMesh, + promise: promise, + }; + } + babylonAbstractMesh = babylonMesh; + } + GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context); + this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh); + assign(babylonAbstractMesh); + this.logClose(); + return promise.then(() => { + return babylonAbstractMesh; + }); + } + _loadVertexDataAsync(context, primitive, babylonMesh) { + const extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh); + if (extensionPromise) { + return extensionPromise; + } + const attributes = primitive.attributes; + if (!attributes) { + throw new Error(`${context}: Attributes are missing`); + } + const promises = new Array(); + const babylonGeometry = new Geometry(babylonMesh.name, this._babylonScene); + if (primitive.indices == undefined) { + babylonMesh.isUnIndexed = true; + } + else { + const accessor = ArrayItem.Get(`${context}/indices`, this._gltf.accessors, primitive.indices); + promises.push(this._loadIndicesAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => { + babylonGeometry.setIndices(data); + })); + } + const loadAttribute = (name, kind, callback) => { + if (attributes[name] == undefined) { + return; + } + babylonMesh._delayInfo = babylonMesh._delayInfo || []; + if (babylonMesh._delayInfo.indexOf(kind) === -1) { + babylonMesh._delayInfo.push(kind); + } + const accessor = ArrayItem.Get(`${context}/attributes/${name}`, this._gltf.accessors, attributes[name]); + promises.push(this._loadVertexAccessorAsync(`/accessors/${accessor.index}`, accessor, kind).then((babylonVertexBuffer) => { + if (babylonVertexBuffer.getKind() === VertexBuffer.PositionKind && !this.parent.alwaysComputeBoundingBox && !babylonMesh.skeleton) { + const babylonBoundingInfo = LoadBoundingInfoFromPositionAccessor(accessor); + if (babylonBoundingInfo) { + babylonGeometry._boundingInfo = babylonBoundingInfo; + babylonGeometry.useBoundingInfoFromGeometry = true; + } + } + babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count); + })); + if (kind == VertexBuffer.MatricesIndicesExtraKind) { + babylonMesh.numBoneInfluencers = 8; + } + if (callback) { + callback(accessor); + } + }; + loadAttribute("POSITION", VertexBuffer.PositionKind); + loadAttribute("NORMAL", VertexBuffer.NormalKind); + loadAttribute("TANGENT", VertexBuffer.TangentKind); + loadAttribute("TEXCOORD_0", VertexBuffer.UVKind); + loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind); + loadAttribute("TEXCOORD_2", VertexBuffer.UV3Kind); + loadAttribute("TEXCOORD_3", VertexBuffer.UV4Kind); + loadAttribute("TEXCOORD_4", VertexBuffer.UV5Kind); + loadAttribute("TEXCOORD_5", VertexBuffer.UV6Kind); + loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind); + loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind); + loadAttribute("JOINTS_1", VertexBuffer.MatricesIndicesExtraKind); + loadAttribute("WEIGHTS_1", VertexBuffer.MatricesWeightsExtraKind); + loadAttribute("COLOR_0", VertexBuffer.ColorKind, (accessor) => { + if (accessor.type === "VEC4" /* AccessorType.VEC4 */) { + babylonMesh.hasVertexAlpha = true; + } + }); + return Promise.all(promises).then(() => { + return babylonGeometry; + }); + } + _createMorphTargets(context, node, mesh, primitive, babylonMesh) { + if (!primitive.targets || !this._parent.loadMorphTargets) { + return; + } + if (node._numMorphTargets == undefined) { + node._numMorphTargets = primitive.targets.length; + } + else if (primitive.targets.length !== node._numMorphTargets) { + throw new Error(`${context}: Primitives do not have the same number of targets`); + } + const targetNames = mesh.extras ? mesh.extras.targetNames : null; + this._babylonScene._blockEntityCollection = !!this._assetContainer; + babylonMesh.morphTargetManager = new MorphTargetManager(this._babylonScene); + babylonMesh.morphTargetManager._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + babylonMesh.morphTargetManager.areUpdatesFrozen = true; + for (let index = 0; index < primitive.targets.length; index++) { + const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0; + const name = targetNames ? targetNames[index] : `morphTarget${index}`; + babylonMesh.morphTargetManager.addTarget(new MorphTarget(name, weight, babylonMesh.getScene())); + // TODO: tell the target whether it has positions, normals, tangents + } + } + _loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry) { + if (!primitive.targets || !this._parent.loadMorphTargets) { + return Promise.resolve(); + } + const promises = new Array(); + const morphTargetManager = babylonMesh.morphTargetManager; + for (let index = 0; index < morphTargetManager.numTargets; index++) { + const babylonMorphTarget = morphTargetManager.getTarget(index); + promises.push(this._loadMorphTargetVertexDataAsync(`${context}/targets/${index}`, babylonGeometry, primitive.targets[index], babylonMorphTarget)); + } + return Promise.all(promises).then(() => { + morphTargetManager.areUpdatesFrozen = false; + }); + } + _loadMorphTargetVertexDataAsync(context, babylonGeometry, attributes, babylonMorphTarget) { + const promises = new Array(); + const loadAttribute = (attribute, kind, setData) => { + if (attributes[attribute] == undefined) { + return; + } + const babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind); + if (!babylonVertexBuffer) { + return; + } + const accessor = ArrayItem.Get(`${context}/${attribute}`, this._gltf.accessors, attributes[attribute]); + promises.push(this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => { + setData(babylonVertexBuffer, data); + })); + }; + loadAttribute("POSITION", VertexBuffer.PositionKind, (babylonVertexBuffer, data) => { + const positions = new Float32Array(data.length); + babylonVertexBuffer.forEach(data.length, (value, index) => { + positions[index] = data[index] + value; + }); + babylonMorphTarget.setPositions(positions); + }); + loadAttribute("NORMAL", VertexBuffer.NormalKind, (babylonVertexBuffer, data) => { + const normals = new Float32Array(data.length); + babylonVertexBuffer.forEach(normals.length, (value, index) => { + normals[index] = data[index] + value; + }); + babylonMorphTarget.setNormals(normals); + }); + loadAttribute("TANGENT", VertexBuffer.TangentKind, (babylonVertexBuffer, data) => { + const tangents = new Float32Array((data.length / 3) * 4); + let dataIndex = 0; + babylonVertexBuffer.forEach((data.length / 3) * 4, (value, index) => { + // Tangent data for morph targets is stored as xyz delta. + // The vertexData.tangent is stored as xyzw. + // So we need to skip every fourth vertexData.tangent. + if ((index + 1) % 4 !== 0) { + tangents[dataIndex] = data[dataIndex] + value; + dataIndex++; + } + }); + babylonMorphTarget.setTangents(tangents); + }); + loadAttribute("TEXCOORD_0", VertexBuffer.UVKind, (babylonVertexBuffer, data) => { + const uvs = new Float32Array(data.length); + babylonVertexBuffer.forEach(data.length, (value, index) => { + uvs[index] = data[index] + value; + }); + babylonMorphTarget.setUVs(uvs); + }); + loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind, (babylonVertexBuffer, data) => { + const uvs = new Float32Array(data.length); + babylonVertexBuffer.forEach(data.length, (value, index) => { + uvs[index] = data[index] + value; + }); + babylonMorphTarget.setUV2s(uvs); + }); + loadAttribute("COLOR_0", VertexBuffer.ColorKind, (babylonVertexBuffer, data) => { + let colors = null; + const componentSize = babylonVertexBuffer.getSize(); + if (componentSize === 3) { + colors = new Float32Array((data.length / 3) * 4); + babylonVertexBuffer.forEach(data.length, (value, index) => { + const pixid = Math.floor(index / 3); + const channel = index % 3; + colors[4 * pixid + channel] = data[3 * pixid + channel] + value; + }); + for (let i = 0; i < data.length / 3; ++i) { + colors[4 * i + 3] = 1; + } + } + else if (componentSize === 4) { + colors = new Float32Array(data.length); + babylonVertexBuffer.forEach(data.length, (value, index) => { + colors[index] = data[index] + value; + }); + } + else { + throw new Error(`${context}: Invalid number of components (${componentSize}) for COLOR_0 attribute`); + } + babylonMorphTarget.setColors(colors); + }); + return Promise.all(promises).then(() => { }); + } + static _LoadTransform(node, babylonNode) { + // Ignore the TRS of skinned nodes. + // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note) + if (node.skin != undefined) { + return; + } + let position = Vector3.Zero(); + let rotation = Quaternion.Identity(); + let scaling = Vector3.One(); + if (node.matrix) { + const matrix = Matrix.FromArray(node.matrix); + matrix.decompose(scaling, rotation, position); + } + else { + if (node.translation) { + position = Vector3.FromArray(node.translation); + } + if (node.rotation) { + rotation = Quaternion.FromArray(node.rotation); + } + if (node.scale) { + scaling = Vector3.FromArray(node.scale); + } + } + babylonNode.position = position; + babylonNode.rotationQuaternion = rotation; + babylonNode.scaling = scaling; + } + _loadSkinAsync(context, node, skin, assign) { + if (!this._parent.loadSkins) { + return Promise.resolve(); + } + const extensionPromise = this._extensionsLoadSkinAsync(context, node, skin); + if (extensionPromise) { + return extensionPromise; + } + if (skin._data) { + assign(skin._data.babylonSkeleton); + return skin._data.promise; + } + const skeletonId = `skeleton${skin.index}`; + this._babylonScene._blockEntityCollection = !!this._assetContainer; + const babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene); + babylonSkeleton._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + this._loadBones(context, skin, babylonSkeleton); + const promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then((inverseBindMatricesData) => { + this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData); + }); + skin._data = { + babylonSkeleton: babylonSkeleton, + promise: promise, + }; + assign(babylonSkeleton); + return promise; + } + _loadBones(context, skin, babylonSkeleton) { + if (skin.skeleton == undefined || this._parent.alwaysComputeSkeletonRootNode) { + const rootNode = this._findSkeletonRootNode(`${context}/joints`, skin.joints); + if (rootNode) { + if (skin.skeleton === undefined) { + skin.skeleton = rootNode.index; + } + else { + const isParent = (a, b) => { + for (; b.parent; b = b.parent) { + if (b.parent === a) { + return true; + } + } + return false; + }; + const skeletonNode = ArrayItem.Get(`${context}/skeleton`, this._gltf.nodes, skin.skeleton); + if (skeletonNode !== rootNode && !isParent(skeletonNode, rootNode)) { + Logger.Warn(`${context}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`); + skin.skeleton = rootNode.index; + } + } + } + else { + Logger.Warn(`${context}: Failed to find common root`); + } + } + const babylonBones = {}; + for (const index of skin.joints) { + const node = ArrayItem.Get(`${context}/joints/${index}`, this._gltf.nodes, index); + this._loadBone(node, skin, babylonSkeleton, babylonBones); + } + } + _findSkeletonRootNode(context, joints) { + if (joints.length === 0) { + return null; + } + const paths = {}; + for (const index of joints) { + const path = []; + let node = ArrayItem.Get(`${context}/${index}`, this._gltf.nodes, index); + while (node.index !== -1) { + path.unshift(node); + node = node.parent; + } + paths[index] = path; + } + let rootNode = null; + for (let i = 0;; ++i) { + let path = paths[joints[0]]; + if (i >= path.length) { + return rootNode; + } + const node = path[i]; + for (let j = 1; j < joints.length; ++j) { + path = paths[joints[j]]; + if (i >= path.length || node !== path[i]) { + return rootNode; + } + } + rootNode = node; + } + } + _loadBone(node, skin, babylonSkeleton, babylonBones) { + node._isJoint = true; + let babylonBone = babylonBones[node.index]; + if (babylonBone) { + return babylonBone; + } + let parentBabylonBone = null; + if (node.index !== skin.skeleton) { + if (node.parent && node.parent.index !== -1) { + parentBabylonBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones); + } + else if (skin.skeleton !== undefined) { + Logger.Warn(`/skins/${skin.index}/skeleton: Skeleton node is not a common root`); + } + } + const boneIndex = skin.joints.indexOf(node.index); + babylonBone = new Bone(node.name || `joint${node.index}`, babylonSkeleton, parentBabylonBone, this._getNodeMatrix(node), null, null, boneIndex); + babylonBones[node.index] = babylonBone; + // Wait until the scene is loaded to ensure the transform nodes are loaded. + this._postSceneLoadActions.push(() => { + // Link the Babylon bone with the corresponding Babylon transform node. + // A glTF joint is a pointer to a glTF node in the glTF node hierarchy similar to Unity3D. + babylonBone.linkTransformNode(node._babylonTransformNode); + }); + return babylonBone; + } + _loadSkinInverseBindMatricesDataAsync(context, skin) { + if (skin.inverseBindMatrices == undefined) { + return Promise.resolve(null); + } + const accessor = ArrayItem.Get(`${context}/inverseBindMatrices`, this._gltf.accessors, skin.inverseBindMatrices); + return this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor); + } + _updateBoneMatrices(babylonSkeleton, inverseBindMatricesData) { + for (const babylonBone of babylonSkeleton.bones) { + const baseMatrix = Matrix.Identity(); + const boneIndex = babylonBone._index; + if (inverseBindMatricesData && boneIndex !== -1) { + Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix); + baseMatrix.invertToRef(baseMatrix); + } + const babylonParentBone = babylonBone.getParent(); + if (babylonParentBone) { + baseMatrix.multiplyToRef(babylonParentBone.getAbsoluteInverseBindMatrix(), baseMatrix); + } + babylonBone.updateMatrix(baseMatrix, false, false); + babylonBone._updateAbsoluteBindMatrices(undefined, false); + } + } + _getNodeMatrix(node) { + return node.matrix + ? Matrix.FromArray(node.matrix) + : Matrix.Compose(node.scale ? Vector3.FromArray(node.scale) : Vector3.One(), node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(), node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero()); + } + /** + * Loads a glTF camera. + * @param context The context when loading the asset + * @param camera The glTF camera property + * @param assign A function called synchronously after parsing the glTF properties + * @returns A promise that resolves with the loaded Babylon camera when the load is complete + */ + loadCameraAsync(context, camera, assign = () => { }) { + const extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign); + if (extensionPromise) { + return extensionPromise; + } + const promises = new Array(); + this.logOpen(`${context} ${camera.name || ""}`); + this._babylonScene._blockEntityCollection = !!this._assetContainer; + const babylonCamera = new FreeCamera(camera.name || `camera${camera.index}`, Vector3.Zero(), this._babylonScene, false); + babylonCamera._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + babylonCamera.ignoreParentScaling = true; + camera._babylonCamera = babylonCamera; + // Rotation by 180 as glTF has a different convention than Babylon. + babylonCamera.rotation.set(0, Math.PI, 0); + switch (camera.type) { + case "perspective" /* CameraType.PERSPECTIVE */: { + const perspective = camera.perspective; + if (!perspective) { + throw new Error(`${context}: Camera perspective properties are missing`); + } + babylonCamera.fov = perspective.yfov; + babylonCamera.minZ = perspective.znear; + babylonCamera.maxZ = perspective.zfar || 0; + break; + } + case "orthographic" /* CameraType.ORTHOGRAPHIC */: { + if (!camera.orthographic) { + throw new Error(`${context}: Camera orthographic properties are missing`); + } + babylonCamera.mode = Camera.ORTHOGRAPHIC_CAMERA; + babylonCamera.orthoLeft = -camera.orthographic.xmag; + babylonCamera.orthoRight = camera.orthographic.xmag; + babylonCamera.orthoBottom = -camera.orthographic.ymag; + babylonCamera.orthoTop = camera.orthographic.ymag; + babylonCamera.minZ = camera.orthographic.znear; + babylonCamera.maxZ = camera.orthographic.zfar; + break; + } + default: { + throw new Error(`${context}: Invalid camera type (${camera.type})`); + } + } + GLTFLoader.AddPointerMetadata(babylonCamera, context); + this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera); + assign(babylonCamera); + this.logClose(); + return Promise.all(promises).then(() => { + return babylonCamera; + }); + } + _loadAnimationsAsync() { + const animations = this._gltf.animations; + if (!animations) { + return Promise.resolve(); + } + const promises = new Array(); + for (let index = 0; index < animations.length; index++) { + const animation = animations[index]; + promises.push(this.loadAnimationAsync(`/animations/${animation.index}`, animation).then((animationGroup) => { + // Delete the animation group if it ended up not having any animations in it. + if (animationGroup.targetedAnimations.length === 0) { + animationGroup.dispose(); + } + })); + } + return Promise.all(promises).then(() => { }); + } + /** + * Loads a glTF animation. + * @param context The context when loading the asset + * @param animation The glTF animation property + * @returns A promise that resolves with the loaded Babylon animation group when the load is complete + */ + loadAnimationAsync(context, animation) { + const promise = this._extensionsLoadAnimationAsync(context, animation); + if (promise) { + return promise; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + return Promise.resolve().then(() => animationGroup).then(({ AnimationGroup }) => { + this._babylonScene._blockEntityCollection = !!this._assetContainer; + const babylonAnimationGroup = new AnimationGroup(animation.name || `animation${animation.index}`, this._babylonScene); + babylonAnimationGroup._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + animation._babylonAnimationGroup = babylonAnimationGroup; + const promises = new Array(); + ArrayItem.Assign(animation.channels); + ArrayItem.Assign(animation.samplers); + for (const channel of animation.channels) { + promises.push(this._loadAnimationChannelAsync(`${context}/channels/${channel.index}`, context, animation, channel, (babylonTarget, babylonAnimation) => { + babylonTarget.animations = babylonTarget.animations || []; + babylonTarget.animations.push(babylonAnimation); + babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonTarget); + })); + } + return Promise.all(promises).then(() => { + babylonAnimationGroup.normalize(0); + return babylonAnimationGroup; + }); + }); + } + /** + * @hidden + * Loads a glTF animation channel. + * @param context The context when loading the asset + * @param animationContext The context of the animation when loading the asset + * @param animation The glTF animation property + * @param channel The glTF animation channel property + * @param onLoad Called for each animation loaded + * @returns A void promise that resolves when the load is complete + */ + async _loadAnimationChannelAsync(context, animationContext, animation, channel, onLoad) { + const promise = this._extensionsLoadAnimationChannelAsync(context, animationContext, animation, channel, onLoad); + if (promise) { + return promise; + } + if (channel.target.node == undefined) { + return Promise.resolve(); + } + const targetNode = ArrayItem.Get(`${context}/target/node`, this._gltf.nodes, channel.target.node); + const channelTargetPath = channel.target.path; + const pathIsWeights = channelTargetPath === "weights" /* AnimationChannelTargetPath.WEIGHTS */; + // Ignore animations that have no animation targets. + if ((pathIsWeights && !targetNode._numMorphTargets) || (!pathIsWeights && !targetNode._babylonTransformNode)) { + return Promise.resolve(); + } + // Don't load node animations if disabled. + if (!this._parent.loadNodeAnimations && !pathIsWeights && !targetNode._isJoint) { + return Promise.resolve(); + } + // async-load the animation sampler to provide the interpolation of the channelTargetPath + await Promise.resolve().then(() => glTFLoaderAnimation); + let properties; + switch (channelTargetPath) { + case "translation" /* AnimationChannelTargetPath.TRANSLATION */: { + properties = GetMappingForKey("/nodes/{}/translation")?.interpolation; + break; + } + case "rotation" /* AnimationChannelTargetPath.ROTATION */: { + properties = GetMappingForKey("/nodes/{}/rotation")?.interpolation; + break; + } + case "scale" /* AnimationChannelTargetPath.SCALE */: { + properties = GetMappingForKey("/nodes/{}/scale")?.interpolation; + break; + } + case "weights" /* AnimationChannelTargetPath.WEIGHTS */: { + properties = GetMappingForKey("/nodes/{}/weights")?.interpolation; + break; + } + default: { + throw new Error(`${context}/target/path: Invalid value (${channel.target.path})`); + } + } + // stay safe + if (!properties) { + throw new Error(`${context}/target/path: Could not find interpolation properties for target path (${channel.target.path})`); + } + const targetInfo = { + object: targetNode, + info: properties, + }; + return this._loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, targetInfo, onLoad); + } + /** + * @hidden + * Loads a glTF animation channel. + * @param context The context when loading the asset + * @param animationContext The context of the animation when loading the asset + * @param animation The glTF animation property + * @param channel The glTF animation channel property + * @param targetInfo The glTF target and properties + * @param onLoad Called for each animation loaded + * @returns A void promise that resolves when the load is complete + */ + _loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, targetInfo, onLoad) { + const fps = this.parent.targetFps; + const invfps = 1 / fps; + const sampler = ArrayItem.Get(`${context}/sampler`, animation.samplers, channel.sampler); + return this._loadAnimationSamplerAsync(`${animationContext}/samplers/${channel.sampler}`, sampler).then((data) => { + let numAnimations = 0; + const target = targetInfo.object; + const propertyInfos = targetInfo.info; + // Extract the corresponding values from the read value. + // GLTF values may be dispatched to several Babylon properties. + // For example, baseColorFactor [`r`, `g`, `b`, `a`] is dispatched to + // - albedoColor as Color3(`r`, `g`, `b`) + // - alpha as `a` + for (const propertyInfo of propertyInfos) { + const stride = propertyInfo.getStride(target); + const input = data.input; + const output = data.output; + const keys = new Array(input.length); + let outputOffset = 0; + switch (data.interpolation) { + case "STEP" /* AnimationSamplerInterpolation.STEP */: { + for (let index = 0; index < input.length; index++) { + const value = propertyInfo.getValue(target, output, outputOffset, 1); + outputOffset += stride; + keys[index] = { + frame: input[index] * fps, + value: value, + interpolation: 1 /* AnimationKeyInterpolation.STEP */, + }; + } + break; + } + case "CUBICSPLINE" /* AnimationSamplerInterpolation.CUBICSPLINE */: { + for (let index = 0; index < input.length; index++) { + const inTangent = propertyInfo.getValue(target, output, outputOffset, invfps); + outputOffset += stride; + const value = propertyInfo.getValue(target, output, outputOffset, 1); + outputOffset += stride; + const outTangent = propertyInfo.getValue(target, output, outputOffset, invfps); + outputOffset += stride; + keys[index] = { + frame: input[index] * fps, + inTangent: inTangent, + value: value, + outTangent: outTangent, + }; + } + break; + } + case "LINEAR" /* AnimationSamplerInterpolation.LINEAR */: { + for (let index = 0; index < input.length; index++) { + const value = propertyInfo.getValue(target, output, outputOffset, 1); + outputOffset += stride; + keys[index] = { + frame: input[index] * fps, + value: value, + }; + } + break; + } + } + if (outputOffset > 0) { + const name = `${animation.name || `animation${animation.index}`}_channel${channel.index}_${numAnimations}`; + const babylonAnimations = propertyInfo.buildAnimations(target, name, fps, keys); + for (const babylonAnimation of babylonAnimations) { + numAnimations++; + onLoad(babylonAnimation.babylonAnimatable, babylonAnimation.babylonAnimation); + } + } + } + }); + } + _loadAnimationSamplerAsync(context, sampler) { + if (sampler._data) { + return sampler._data; + } + const interpolation = sampler.interpolation || "LINEAR" /* AnimationSamplerInterpolation.LINEAR */; + switch (interpolation) { + case "STEP" /* AnimationSamplerInterpolation.STEP */: + case "LINEAR" /* AnimationSamplerInterpolation.LINEAR */: + case "CUBICSPLINE" /* AnimationSamplerInterpolation.CUBICSPLINE */: { + break; + } + default: { + throw new Error(`${context}/interpolation: Invalid value (${sampler.interpolation})`); + } + } + const inputAccessor = ArrayItem.Get(`${context}/input`, this._gltf.accessors, sampler.input); + const outputAccessor = ArrayItem.Get(`${context}/output`, this._gltf.accessors, sampler.output); + sampler._data = Promise.all([ + this._loadFloatAccessorAsync(`/accessors/${inputAccessor.index}`, inputAccessor), + this._loadFloatAccessorAsync(`/accessors/${outputAccessor.index}`, outputAccessor), + ]).then(([inputData, outputData]) => { + return { + input: inputData, + interpolation: interpolation, + output: outputData, + }; + }); + return sampler._data; + } + /** + * Loads a glTF buffer. + * @param context The context when loading the asset + * @param buffer The glTF buffer property + * @param byteOffset The byte offset to use + * @param byteLength The byte length to use + * @returns A promise that resolves with the loaded data when the load is complete + */ + loadBufferAsync(context, buffer, byteOffset, byteLength) { + const extensionPromise = this._extensionsLoadBufferAsync(context, buffer, byteOffset, byteLength); + if (extensionPromise) { + return extensionPromise; + } + if (!buffer._data) { + if (buffer.uri) { + buffer._data = this.loadUriAsync(`${context}/uri`, buffer, buffer.uri); + } + else { + if (!this._bin) { + throw new Error(`${context}: Uri is missing or the binary glTF is missing its binary chunk`); + } + buffer._data = this._bin.readAsync(0, buffer.byteLength); + } + } + return buffer._data.then((data) => { + try { + return new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength); + } + catch (e) { + throw new Error(`${context}: ${e.message}`); + } + }); + } + /** + * Loads a glTF buffer view. + * @param context The context when loading the asset + * @param bufferView The glTF buffer view property + * @returns A promise that resolves with the loaded data when the load is complete + */ + loadBufferViewAsync(context, bufferView) { + const extensionPromise = this._extensionsLoadBufferViewAsync(context, bufferView); + if (extensionPromise) { + return extensionPromise; + } + if (bufferView._data) { + return bufferView._data; + } + const buffer = ArrayItem.Get(`${context}/buffer`, this._gltf.buffers, bufferView.buffer); + bufferView._data = this.loadBufferAsync(`/buffers/${buffer.index}`, buffer, bufferView.byteOffset || 0, bufferView.byteLength); + return bufferView._data; + } + _loadAccessorAsync(context, accessor, constructor) { + if (accessor._data) { + return accessor._data; + } + const numComponents = GLTFLoader._GetNumComponents(context, accessor.type); + const byteStride = numComponents * VertexBuffer.GetTypeByteLength(accessor.componentType); + const length = numComponents * accessor.count; + if (accessor.bufferView == undefined) { + accessor._data = Promise.resolve(new constructor(length)); + } + else { + const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView); + accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => { + if (accessor.componentType === 5126 /* AccessorComponentType.FLOAT */ && !accessor.normalized && (!bufferView.byteStride || bufferView.byteStride === byteStride)) { + return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length); + } + else { + const typedArray = new constructor(length); + VertexBuffer.ForEach(data, accessor.byteOffset || 0, bufferView.byteStride || byteStride, numComponents, accessor.componentType, typedArray.length, accessor.normalized || false, (value, index) => { + typedArray[index] = value; + }); + return typedArray; + } + }); + } + if (accessor.sparse) { + const sparse = accessor.sparse; + accessor._data = accessor._data.then((data) => { + const typedArray = data; + const indicesBufferView = ArrayItem.Get(`${context}/sparse/indices/bufferView`, this._gltf.bufferViews, sparse.indices.bufferView); + const valuesBufferView = ArrayItem.Get(`${context}/sparse/values/bufferView`, this._gltf.bufferViews, sparse.values.bufferView); + return Promise.all([ + this.loadBufferViewAsync(`/bufferViews/${indicesBufferView.index}`, indicesBufferView), + this.loadBufferViewAsync(`/bufferViews/${valuesBufferView.index}`, valuesBufferView), + ]).then(([indicesData, valuesData]) => { + const indices = GLTFLoader._GetTypedArray(`${context}/sparse/indices`, sparse.indices.componentType, indicesData, sparse.indices.byteOffset, sparse.count); + const sparseLength = numComponents * sparse.count; + let values; + if (accessor.componentType === 5126 /* AccessorComponentType.FLOAT */ && !accessor.normalized) { + values = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, sparseLength); + } + else { + const sparseData = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, sparseLength); + values = new constructor(sparseLength); + VertexBuffer.ForEach(sparseData, 0, byteStride, numComponents, accessor.componentType, values.length, accessor.normalized || false, (value, index) => { + values[index] = value; + }); + } + let valuesIndex = 0; + for (let indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) { + let dataIndex = indices[indicesIndex] * numComponents; + for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) { + typedArray[dataIndex++] = values[valuesIndex++]; + } + } + return typedArray; + }); + }); + } + return accessor._data; + } + /** + * @internal + */ + _loadFloatAccessorAsync(context, accessor) { + return this._loadAccessorAsync(context, accessor, Float32Array); + } + /** + * @internal + */ + _loadIndicesAccessorAsync(context, accessor) { + if (accessor.type !== "SCALAR" /* AccessorType.SCALAR */) { + throw new Error(`${context}/type: Invalid value ${accessor.type}`); + } + if (accessor.componentType !== 5121 /* AccessorComponentType.UNSIGNED_BYTE */ && + accessor.componentType !== 5123 /* AccessorComponentType.UNSIGNED_SHORT */ && + accessor.componentType !== 5125 /* AccessorComponentType.UNSIGNED_INT */) { + throw new Error(`${context}/componentType: Invalid value ${accessor.componentType}`); + } + if (accessor._data) { + return accessor._data; + } + if (accessor.sparse) { + const constructor = GLTFLoader._GetTypedArrayConstructor(`${context}/componentType`, accessor.componentType); + accessor._data = this._loadAccessorAsync(context, accessor, constructor); + } + else { + const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView); + accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => { + return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count); + }); + } + return accessor._data; + } + /** + * @internal + */ + _loadVertexBufferViewAsync(bufferView) { + if (bufferView._babylonBuffer) { + return bufferView._babylonBuffer; + } + const engine = this._babylonScene.getEngine(); + bufferView._babylonBuffer = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => { + return new Buffer(engine, data, false); + }); + return bufferView._babylonBuffer; + } + /** + * @internal + */ + _loadVertexAccessorAsync(context, accessor, kind) { + if (accessor._babylonVertexBuffer?.[kind]) { + return accessor._babylonVertexBuffer[kind]; + } + if (!accessor._babylonVertexBuffer) { + accessor._babylonVertexBuffer = {}; + } + const engine = this._babylonScene.getEngine(); + if (accessor.sparse || accessor.bufferView == undefined) { + accessor._babylonVertexBuffer[kind] = this._loadFloatAccessorAsync(context, accessor).then((data) => { + return new VertexBuffer(engine, data, kind, false); + }); + } + else { + const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView); + accessor._babylonVertexBuffer[kind] = this._loadVertexBufferViewAsync(bufferView).then((babylonBuffer) => { + const numComponents = GLTFLoader._GetNumComponents(context, accessor.type); + return new VertexBuffer(engine, babylonBuffer, kind, false, undefined, bufferView.byteStride, undefined, accessor.byteOffset, numComponents, accessor.componentType, accessor.normalized, true, undefined, true); + }); + } + return accessor._babylonVertexBuffer[kind]; + } + _loadMaterialMetallicRoughnessPropertiesAsync(context, properties, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const promises = new Array(); + if (properties) { + if (properties.baseColorFactor) { + babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor); + babylonMaterial.alpha = properties.baseColorFactor[3]; + } + else { + babylonMaterial.albedoColor = Color3.White(); + } + babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor; + babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor; + if (properties.baseColorTexture) { + promises.push(this.loadTextureInfoAsync(`${context}/baseColorTexture`, properties.baseColorTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Base Color)`; + babylonMaterial.albedoTexture = texture; + })); + } + if (properties.metallicRoughnessTexture) { + properties.metallicRoughnessTexture.nonColorData = true; + promises.push(this.loadTextureInfoAsync(`${context}/metallicRoughnessTexture`, properties.metallicRoughnessTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Metallic Roughness)`; + babylonMaterial.metallicTexture = texture; + })); + babylonMaterial.useMetallnessFromMetallicTextureBlue = true; + babylonMaterial.useRoughnessFromMetallicTextureGreen = true; + babylonMaterial.useRoughnessFromMetallicTextureAlpha = false; + } + } + return Promise.all(promises).then(() => { }); + } + /** + * @internal + */ + _loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign = () => { }) { + const extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); + if (extensionPromise) { + return extensionPromise; + } + material._data = material._data || {}; + let babylonData = material._data[babylonDrawMode]; + if (!babylonData) { + this.logOpen(`${context} ${material.name || ""}`); + const babylonMaterial = this.createMaterial(context, material, babylonDrawMode); + babylonData = { + babylonMaterial: babylonMaterial, + babylonMeshes: [], + promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial), + }; + material._data[babylonDrawMode] = babylonData; + GLTFLoader.AddPointerMetadata(babylonMaterial, context); + this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial); + this.logClose(); + } + if (babylonMesh) { + babylonData.babylonMeshes.push(babylonMesh); + babylonMesh.onDisposeObservable.addOnce(() => { + const index = babylonData.babylonMeshes.indexOf(babylonMesh); + if (index !== -1) { + babylonData.babylonMeshes.splice(index, 1); + } + }); + } + assign(babylonData.babylonMaterial); + return babylonData.promise.then(() => { + return babylonData.babylonMaterial; + }); + } + _createDefaultMaterial(name, babylonDrawMode) { + this._babylonScene._blockEntityCollection = !!this._assetContainer; + const babylonMaterial = new PBRMaterial(name, this._babylonScene); + babylonMaterial._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + // Moved to mesh so user can change materials on gltf meshes: babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation; + babylonMaterial.fillMode = babylonDrawMode; + babylonMaterial.enableSpecularAntiAliasing = true; + babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage; + babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage; + babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE; + babylonMaterial.metallic = 1; + babylonMaterial.roughness = 1; + return babylonMaterial; + } + /** + * Creates a Babylon material from a glTF material. + * @param context The context when loading the asset + * @param material The glTF material property + * @param babylonDrawMode The draw mode for the Babylon material + * @returns The Babylon material + */ + createMaterial(context, material, babylonDrawMode) { + const extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode); + if (extensionPromise) { + return extensionPromise; + } + const name = material.name || `material${material.index}`; + const babylonMaterial = this._createDefaultMaterial(name, babylonDrawMode); + return babylonMaterial; + } + /** + * Loads properties from a glTF material into a Babylon material. + * @param context The context when loading the asset + * @param material The glTF material property + * @param babylonMaterial The Babylon material + * @returns A promise that resolves when the load is complete + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + const extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial); + if (extensionPromise) { + return extensionPromise; + } + const promises = new Array(); + promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial)); + if (material.pbrMetallicRoughness) { + promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${context}/pbrMetallicRoughness`, material.pbrMetallicRoughness, babylonMaterial)); + } + this.loadMaterialAlphaProperties(context, material, babylonMaterial); + return Promise.all(promises).then(() => { }); + } + /** + * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material. + * @param context The context when loading the asset + * @param material The glTF material property + * @param babylonMaterial The Babylon material + * @returns A promise that resolves when the load is complete + */ + loadMaterialBasePropertiesAsync(context, material, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const promises = new Array(); + babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0); + if (material.doubleSided) { + babylonMaterial.backFaceCulling = false; + babylonMaterial.twoSidedLighting = true; + } + if (material.normalTexture) { + material.normalTexture.nonColorData = true; + promises.push(this.loadTextureInfoAsync(`${context}/normalTexture`, material.normalTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Normal)`; + babylonMaterial.bumpTexture = texture; + })); + babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem; + babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem; + if (material.normalTexture.scale != undefined && babylonMaterial.bumpTexture) { + babylonMaterial.bumpTexture.level = material.normalTexture.scale; + } + babylonMaterial.forceIrradianceInFragment = true; + } + if (material.occlusionTexture) { + material.occlusionTexture.nonColorData = true; + promises.push(this.loadTextureInfoAsync(`${context}/occlusionTexture`, material.occlusionTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Occlusion)`; + babylonMaterial.ambientTexture = texture; + })); + babylonMaterial.useAmbientInGrayScale = true; + if (material.occlusionTexture.strength != undefined) { + babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength; + } + } + if (material.emissiveTexture) { + promises.push(this.loadTextureInfoAsync(`${context}/emissiveTexture`, material.emissiveTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Emissive)`; + babylonMaterial.emissiveTexture = texture; + })); + } + return Promise.all(promises).then(() => { }); + } + /** + * Loads the alpha properties from a glTF material into a Babylon material. + * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture. + * @param context The context when loading the asset + * @param material The glTF material property + * @param babylonMaterial The Babylon material + */ + loadMaterialAlphaProperties(context, material, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const alphaMode = material.alphaMode || "OPAQUE" /* MaterialAlphaMode.OPAQUE */; + switch (alphaMode) { + case "OPAQUE" /* MaterialAlphaMode.OPAQUE */: { + babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE; + babylonMaterial.alpha = 1.0; // Force alpha to 1.0 for opaque mode. + break; + } + case "MASK" /* MaterialAlphaMode.MASK */: { + babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST; + babylonMaterial.alphaCutOff = material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff; + if (babylonMaterial.albedoTexture) { + babylonMaterial.albedoTexture.hasAlpha = true; + } + break; + } + case "BLEND" /* MaterialAlphaMode.BLEND */: { + babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND; + if (babylonMaterial.albedoTexture) { + babylonMaterial.albedoTexture.hasAlpha = true; + babylonMaterial.useAlphaFromAlbedoTexture = true; + } + break; + } + default: { + throw new Error(`${context}/alphaMode: Invalid value (${material.alphaMode})`); + } + } + } + /** + * Loads a glTF texture info. + * @param context The context when loading the asset + * @param textureInfo The glTF texture info property + * @param assign A function called synchronously after parsing the glTF properties + * @returns A promise that resolves with the loaded Babylon texture when the load is complete + */ + loadTextureInfoAsync(context, textureInfo, assign = () => { }) { + const extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign); + if (extensionPromise) { + return extensionPromise; + } + this.logOpen(`${context}`); + if (textureInfo.texCoord >= 6) { + throw new Error(`${context}/texCoord: Invalid value (${textureInfo.texCoord})`); + } + const texture = ArrayItem.Get(`${context}/index`, this._gltf.textures, textureInfo.index); + texture._textureInfo = textureInfo; + const promise = this._loadTextureAsync(`/textures/${textureInfo.index}`, texture, (babylonTexture) => { + babylonTexture.coordinatesIndex = textureInfo.texCoord || 0; + GLTFLoader.AddPointerMetadata(babylonTexture, context); + this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture); + assign(babylonTexture); + }); + this.logClose(); + return promise; + } + /** + * @internal + */ + _loadTextureAsync(context, texture, assign = () => { }) { + const extensionPromise = this._extensionsLoadTextureAsync(context, texture, assign); + if (extensionPromise) { + return extensionPromise; + } + this.logOpen(`${context} ${texture.name || ""}`); + const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._gltf.samplers, texture.sampler); + const image = ArrayItem.Get(`${context}/source`, this._gltf.images, texture.source); + const promise = this._createTextureAsync(context, sampler, image, assign, undefined, !texture._textureInfo.nonColorData); + this.logClose(); + return promise; + } + /** + * @internal + */ + _createTextureAsync(context, sampler, image, assign = () => { }, textureLoaderOptions, useSRGBBuffer) { + const samplerData = this._loadSampler(`/samplers/${sampler.index}`, sampler); + const promises = new Array(); + const deferred = new Deferred(); + this._babylonScene._blockEntityCollection = !!this._assetContainer; + const textureCreationOptions = { + noMipmap: samplerData.noMipMaps, + invertY: false, + samplingMode: samplerData.samplingMode, + onLoad: () => { + if (!this._disposed) { + deferred.resolve(); + } + }, + onError: (message, exception) => { + if (!this._disposed) { + deferred.reject(new Error(`${context}: ${exception && exception.message ? exception.message : message || "Failed to load texture"}`)); + } + }, + mimeType: image.mimeType, + loaderOptions: textureLoaderOptions, + useSRGBBuffer: !!useSRGBBuffer && this._parent.useSRGBBuffers, + }; + const babylonTexture = new Texture(null, this._babylonScene, textureCreationOptions); + babylonTexture._parentContainer = this._assetContainer; + this._babylonScene._blockEntityCollection = false; + promises.push(deferred.promise); + promises.push(this.loadImageAsync(`/images/${image.index}`, image).then((data) => { + const name = image.uri || `${this._fileName}#image${image.index}`; + const dataUrl = `data:${this._uniqueRootUrl}${name}`; + babylonTexture.updateURL(dataUrl, data); + // Set the internal texture label. + const internalTexture = babylonTexture.getInternalTexture(); + if (internalTexture) { + internalTexture.label = image.name; + } + })); + babylonTexture.wrapU = samplerData.wrapU; + babylonTexture.wrapV = samplerData.wrapV; + assign(babylonTexture); + if (this._parent.useGltfTextureNames) { + babylonTexture.name = image.name || image.uri || `image${image.index}`; + } + return Promise.all(promises).then(() => { + return babylonTexture; + }); + } + _loadSampler(context, sampler) { + if (!sampler._data) { + sampler._data = { + noMipMaps: sampler.minFilter === 9728 /* TextureMinFilter.NEAREST */ || sampler.minFilter === 9729 /* TextureMinFilter.LINEAR */, + samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler), + wrapU: GLTFLoader._GetTextureWrapMode(`${context}/wrapS`, sampler.wrapS), + wrapV: GLTFLoader._GetTextureWrapMode(`${context}/wrapT`, sampler.wrapT), + }; + } + return sampler._data; + } + /** + * Loads a glTF image. + * @param context The context when loading the asset + * @param image The glTF image property + * @returns A promise that resolves with the loaded data when the load is complete + */ + loadImageAsync(context, image) { + if (!image._data) { + this.logOpen(`${context} ${image.name || ""}`); + if (image.uri) { + image._data = this.loadUriAsync(`${context}/uri`, image, image.uri); + } + else { + const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, image.bufferView); + image._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView); + } + this.logClose(); + } + return image._data; + } + /** + * Loads a glTF uri. + * @param context The context when loading the asset + * @param property The glTF property associated with the uri + * @param uri The base64 or relative uri + * @returns A promise that resolves with the loaded data when the load is complete + */ + loadUriAsync(context, property, uri) { + const extensionPromise = this._extensionsLoadUriAsync(context, property, uri); + if (extensionPromise) { + return extensionPromise; + } + if (!GLTFLoader._ValidateUri(uri)) { + throw new Error(`${context}: '${uri}' is invalid`); + } + if (IsBase64DataUrl(uri)) { + const data = new Uint8Array(DecodeBase64UrlToBinary(uri)); + this.log(`${context}: Decoded ${uri.substring(0, 64)}... (${data.length} bytes)`); + return Promise.resolve(data); + } + this.log(`${context}: Loading ${uri}`); + return this._parent.preprocessUrlAsync(this._rootUrl + uri).then((url) => { + return new Promise((resolve, reject) => { + this._parent._loadFile(this._babylonScene, url, (data) => { + if (!this._disposed) { + this.log(`${context}: Loaded ${uri} (${data.byteLength} bytes)`); + resolve(new Uint8Array(data)); + } + }, true, (request) => { + reject(new LoadFileError(`${context}: Failed to load '${uri}'${request ? ": " + request.status + " " + request.statusText : ""}`, request)); + }); + }); + }); + } + /** + * Adds a JSON pointer to the _internalMetadata of the Babylon object at `._internalMetadata.gltf.pointers`. + * @param babylonObject the Babylon object with _internalMetadata + * @param pointer the JSON pointer + */ + static AddPointerMetadata(babylonObject, pointer) { + babylonObject.metadata = babylonObject.metadata || {}; + const metadata = (babylonObject._internalMetadata = babylonObject._internalMetadata || {}); + const gltf = (metadata.gltf = metadata.gltf || {}); + const pointers = (gltf.pointers = gltf.pointers || []); + pointers.push(pointer); + } + static _GetTextureWrapMode(context, mode) { + // Set defaults if undefined + mode = mode == undefined ? 10497 /* TextureWrapMode.REPEAT */ : mode; + switch (mode) { + case 33071 /* TextureWrapMode.CLAMP_TO_EDGE */: + return Texture.CLAMP_ADDRESSMODE; + case 33648 /* TextureWrapMode.MIRRORED_REPEAT */: + return Texture.MIRROR_ADDRESSMODE; + case 10497 /* TextureWrapMode.REPEAT */: + return Texture.WRAP_ADDRESSMODE; + default: + Logger.Warn(`${context}: Invalid value (${mode})`); + return Texture.WRAP_ADDRESSMODE; + } + } + static _GetTextureSamplingMode(context, sampler) { + // Set defaults if undefined + const magFilter = sampler.magFilter == undefined ? 9729 /* TextureMagFilter.LINEAR */ : sampler.magFilter; + const minFilter = sampler.minFilter == undefined ? 9987 /* TextureMinFilter.LINEAR_MIPMAP_LINEAR */ : sampler.minFilter; + if (magFilter === 9729 /* TextureMagFilter.LINEAR */) { + switch (minFilter) { + case 9728 /* TextureMinFilter.NEAREST */: + return Texture.LINEAR_NEAREST; + case 9729 /* TextureMinFilter.LINEAR */: + return Texture.LINEAR_LINEAR; + case 9984 /* TextureMinFilter.NEAREST_MIPMAP_NEAREST */: + return Texture.LINEAR_NEAREST_MIPNEAREST; + case 9985 /* TextureMinFilter.LINEAR_MIPMAP_NEAREST */: + return Texture.LINEAR_LINEAR_MIPNEAREST; + case 9986 /* TextureMinFilter.NEAREST_MIPMAP_LINEAR */: + return Texture.LINEAR_NEAREST_MIPLINEAR; + case 9987 /* TextureMinFilter.LINEAR_MIPMAP_LINEAR */: + return Texture.LINEAR_LINEAR_MIPLINEAR; + default: + Logger.Warn(`${context}/minFilter: Invalid value (${minFilter})`); + return Texture.LINEAR_LINEAR_MIPLINEAR; + } + } + else { + if (magFilter !== 9728 /* TextureMagFilter.NEAREST */) { + Logger.Warn(`${context}/magFilter: Invalid value (${magFilter})`); + } + switch (minFilter) { + case 9728 /* TextureMinFilter.NEAREST */: + return Texture.NEAREST_NEAREST; + case 9729 /* TextureMinFilter.LINEAR */: + return Texture.NEAREST_LINEAR; + case 9984 /* TextureMinFilter.NEAREST_MIPMAP_NEAREST */: + return Texture.NEAREST_NEAREST_MIPNEAREST; + case 9985 /* TextureMinFilter.LINEAR_MIPMAP_NEAREST */: + return Texture.NEAREST_LINEAR_MIPNEAREST; + case 9986 /* TextureMinFilter.NEAREST_MIPMAP_LINEAR */: + return Texture.NEAREST_NEAREST_MIPLINEAR; + case 9987 /* TextureMinFilter.LINEAR_MIPMAP_LINEAR */: + return Texture.NEAREST_LINEAR_MIPLINEAR; + default: + Logger.Warn(`${context}/minFilter: Invalid value (${minFilter})`); + return Texture.NEAREST_NEAREST_MIPNEAREST; + } + } + } + static _GetTypedArrayConstructor(context, componentType) { + try { + return GetTypedArrayConstructor(componentType); + } + catch (e) { + throw new Error(`${context}: ${e.message}`); + } + } + static _GetTypedArray(context, componentType, bufferView, byteOffset, length) { + const buffer = bufferView.buffer; + byteOffset = bufferView.byteOffset + (byteOffset || 0); + const constructor = GLTFLoader._GetTypedArrayConstructor(`${context}/componentType`, componentType); + const componentTypeLength = VertexBuffer.GetTypeByteLength(componentType); + if (byteOffset % componentTypeLength !== 0) { + // HACK: Copy the buffer if byte offset is not a multiple of component type byte length. + Logger.Warn(`${context}: Copying buffer as byte offset (${byteOffset}) is not a multiple of component type byte length (${componentTypeLength})`); + return new constructor(buffer.slice(byteOffset, byteOffset + length * componentTypeLength), 0); + } + return new constructor(buffer, byteOffset, length); + } + static _GetNumComponents(context, type) { + switch (type) { + case "SCALAR": + return 1; + case "VEC2": + return 2; + case "VEC3": + return 3; + case "VEC4": + return 4; + case "MAT2": + return 4; + case "MAT3": + return 9; + case "MAT4": + return 16; + } + throw new Error(`${context}: Invalid type (${type})`); + } + static _ValidateUri(uri) { + return Tools.IsBase64(uri) || uri.indexOf("..") === -1; + } + /** + * @internal + */ + static _GetDrawMode(context, mode) { + if (mode == undefined) { + mode = 4 /* MeshPrimitiveMode.TRIANGLES */; + } + switch (mode) { + case 0 /* MeshPrimitiveMode.POINTS */: + return Material.PointListDrawMode; + case 1 /* MeshPrimitiveMode.LINES */: + return Material.LineListDrawMode; + case 2 /* MeshPrimitiveMode.LINE_LOOP */: + return Material.LineLoopDrawMode; + case 3 /* MeshPrimitiveMode.LINE_STRIP */: + return Material.LineStripDrawMode; + case 4 /* MeshPrimitiveMode.TRIANGLES */: + return Material.TriangleFillMode; + case 5 /* MeshPrimitiveMode.TRIANGLE_STRIP */: + return Material.TriangleStripDrawMode; + case 6 /* MeshPrimitiveMode.TRIANGLE_FAN */: + return Material.TriangleFanDrawMode; + } + throw new Error(`${context}: Invalid mesh primitive mode (${mode})`); + } + _compileMaterialsAsync() { + this._parent._startPerformanceCounter("Compile materials"); + const promises = new Array(); + if (this._gltf.materials) { + for (const material of this._gltf.materials) { + if (material._data) { + for (const babylonDrawMode in material._data) { + const babylonData = material._data[babylonDrawMode]; + for (const babylonMesh of babylonData.babylonMeshes) { + // Ensure nonUniformScaling is set if necessary. + babylonMesh.computeWorldMatrix(true); + const babylonMaterial = babylonData.babylonMaterial; + promises.push(babylonMaterial.forceCompilationAsync(babylonMesh)); + promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { useInstances: true })); + if (this._parent.useClipPlane) { + promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true })); + promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true, useInstances: true })); + } + } + } + } + } + } + return Promise.all(promises).then(() => { + this._parent._endPerformanceCounter("Compile materials"); + }); + } + _compileShadowGeneratorsAsync() { + this._parent._startPerformanceCounter("Compile shadow generators"); + const promises = new Array(); + const lights = this._babylonScene.lights; + for (const light of lights) { + const generator = light.getShadowGenerator(); + if (generator) { + promises.push(generator.forceCompilationAsync()); + } + } + return Promise.all(promises).then(() => { + this._parent._endPerformanceCounter("Compile shadow generators"); + }); + } + _forEachExtensions(action) { + for (const extension of this._extensions) { + if (extension.enabled) { + action(extension); + } + } + } + _applyExtensions(property, functionName, actionAsync) { + for (const extension of this._extensions) { + if (extension.enabled) { + const id = `${extension.name}.${functionName}`; + const loaderProperty = property; + loaderProperty._activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions || {}; + const activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions; + if (!activeLoaderExtensionFunctions[id]) { + activeLoaderExtensionFunctions[id] = true; + try { + const result = actionAsync(extension); + if (result) { + return result; + } + } + finally { + delete activeLoaderExtensionFunctions[id]; + } + } + } + } + return null; + } + _extensionsOnLoading() { + this._forEachExtensions((extension) => extension.onLoading && extension.onLoading()); + } + _extensionsOnReady() { + this._forEachExtensions((extension) => extension.onReady && extension.onReady()); + } + _extensionsLoadSceneAsync(context, scene) { + return this._applyExtensions(scene, "loadScene", (extension) => extension.loadSceneAsync && extension.loadSceneAsync(context, scene)); + } + _extensionsLoadNodeAsync(context, node, assign) { + return this._applyExtensions(node, "loadNode", (extension) => extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign)); + } + _extensionsLoadCameraAsync(context, camera, assign) { + return this._applyExtensions(camera, "loadCamera", (extension) => extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign)); + } + _extensionsLoadVertexDataAsync(context, primitive, babylonMesh) { + return this._applyExtensions(primitive, "loadVertexData", (extension) => extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh)); + } + _extensionsLoadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign) { + return this._applyExtensions(primitive, "loadMeshPrimitive", (extension) => extension._loadMeshPrimitiveAsync && extension._loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign)); + } + _extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign) { + return this._applyExtensions(material, "loadMaterial", (extension) => extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign)); + } + _extensionsCreateMaterial(context, material, babylonDrawMode) { + return this._applyExtensions(material, "createMaterial", (extension) => extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode)); + } + _extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial) { + return this._applyExtensions(material, "loadMaterialProperties", (extension) => extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + } + _extensionsLoadTextureInfoAsync(context, textureInfo, assign) { + return this._applyExtensions(textureInfo, "loadTextureInfo", (extension) => extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign)); + } + _extensionsLoadTextureAsync(context, texture, assign) { + return this._applyExtensions(texture, "loadTexture", (extension) => extension._loadTextureAsync && extension._loadTextureAsync(context, texture, assign)); + } + _extensionsLoadAnimationAsync(context, animation) { + return this._applyExtensions(animation, "loadAnimation", (extension) => extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation)); + } + _extensionsLoadAnimationChannelAsync(context, animationContext, animation, channel, onLoad) { + return this._applyExtensions(animation, "loadAnimationChannel", (extension) => extension._loadAnimationChannelAsync && extension._loadAnimationChannelAsync(context, animationContext, animation, channel, onLoad)); + } + _extensionsLoadSkinAsync(context, node, skin) { + return this._applyExtensions(skin, "loadSkin", (extension) => extension._loadSkinAsync && extension._loadSkinAsync(context, node, skin)); + } + _extensionsLoadUriAsync(context, property, uri) { + return this._applyExtensions(property, "loadUri", (extension) => extension._loadUriAsync && extension._loadUriAsync(context, property, uri)); + } + _extensionsLoadBufferViewAsync(context, bufferView) { + return this._applyExtensions(bufferView, "loadBufferView", (extension) => extension.loadBufferViewAsync && extension.loadBufferViewAsync(context, bufferView)); + } + _extensionsLoadBufferAsync(context, buffer, byteOffset, byteLength) { + return this._applyExtensions(buffer, "loadBuffer", (extension) => extension.loadBufferAsync && extension.loadBufferAsync(context, buffer, byteOffset, byteLength)); + } + /** + * Helper method called by a loader extension to load an glTF extension. + * @param context The context when loading the asset + * @param property The glTF property to load the extension from + * @param extensionName The name of the extension to load + * @param actionAsync The action to run + * @returns The promise returned by actionAsync or null if the extension does not exist + */ + static LoadExtensionAsync(context, property, extensionName, actionAsync) { + if (!property.extensions) { + return null; + } + const extensions = property.extensions; + const extension = extensions[extensionName]; + if (!extension) { + return null; + } + return actionAsync(`${context}/extensions/${extensionName}`, extension); + } + /** + * Helper method called by a loader extension to load a glTF extra. + * @param context The context when loading the asset + * @param property The glTF property to load the extra from + * @param extensionName The name of the extension to load + * @param actionAsync The action to run + * @returns The promise returned by actionAsync or null if the extra does not exist + */ + static LoadExtraAsync(context, property, extensionName, actionAsync) { + if (!property.extras) { + return null; + } + const extras = property.extras; + const extra = extras[extensionName]; + if (!extra) { + return null; + } + return actionAsync(`${context}/extras/${extensionName}`, extra); + } + /** + * Checks for presence of an extension. + * @param name The name of the extension to check + * @returns A boolean indicating the presence of the given extension name in `extensionsUsed` + */ + isExtensionUsed(name) { + return !!this._gltf.extensionsUsed && this._gltf.extensionsUsed.indexOf(name) !== -1; + } + /** + * Increments the indentation level and logs a message. + * @param message The message to log + */ + logOpen(message) { + this._parent._logOpen(message); + } + /** + * Decrements the indentation level. + */ + logClose() { + this._parent._logClose(); + } + /** + * Logs a message + * @param message The message to log + */ + log(message) { + this._parent._log(message); + } + /** + * Starts a performance counter. + * @param counterName The name of the performance counter + */ + startPerformanceCounter(counterName) { + this._parent._startPerformanceCounter(counterName); + } + /** + * Ends a performance counter. + * @param counterName The name of the performance counter + */ + endPerformanceCounter(counterName) { + this._parent._endPerformanceCounter(counterName); + } +} +/** + * The default glTF sampler. + */ +GLTFLoader.DefaultSampler = { index: -1 }; +GLTFFileLoader._CreateGLTF2Loader = (parent) => new GLTFLoader(parent); + +/** @internal */ +function getVector3(_target, source, offset, scale) { + return Vector3.FromArray(source, offset).scaleInPlace(scale); +} +/** @internal */ +function getQuaternion(_target, source, offset, scale) { + return Quaternion.FromArray(source, offset).scaleInPlace(scale); +} +/** @internal */ +function getWeights(target, source, offset, scale) { + const value = new Array(target._numMorphTargets); + for (let i = 0; i < value.length; i++) { + value[i] = source[offset++] * scale; + } + return value; +} +/** @internal */ +class AnimationPropertyInfo { + /** @internal */ + constructor(type, name, getValue, getStride) { + this.type = type; + this.name = name; + this.getValue = getValue; + this.getStride = getStride; + } + _buildAnimation(name, fps, keys) { + const babylonAnimation = new Animation(name, this.name, fps, this.type); + babylonAnimation.setKeys(keys); + return babylonAnimation; + } +} +/** @internal */ +class TransformNodeAnimationPropertyInfo extends AnimationPropertyInfo { + /** @internal */ + buildAnimations(target, name, fps, keys) { + const babylonAnimations = []; + babylonAnimations.push({ babylonAnimatable: target._babylonTransformNode, babylonAnimation: this._buildAnimation(name, fps, keys) }); + return babylonAnimations; + } +} +/** @internal */ +class WeightAnimationPropertyInfo extends AnimationPropertyInfo { + buildAnimations(target, name, fps, keys) { + const babylonAnimations = []; + if (target._numMorphTargets) { + for (let targetIndex = 0; targetIndex < target._numMorphTargets; targetIndex++) { + const babylonAnimation = new Animation(`${name}_${targetIndex}`, this.name, fps, this.type); + babylonAnimation.setKeys(keys.map((key) => ({ + frame: key.frame, + inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined, + value: key.value[targetIndex], + outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined, + interpolation: key.interpolation, + }))); + if (target._primitiveBabylonMeshes) { + for (const babylonMesh of target._primitiveBabylonMeshes) { + if (babylonMesh.morphTargetManager) { + const morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex); + const babylonAnimationClone = babylonAnimation.clone(); + morphTarget.animations.push(babylonAnimationClone); + babylonAnimations.push({ babylonAnimatable: morphTarget, babylonAnimation: babylonAnimationClone }); + } + } + } + } + } + return babylonAnimations; + } +} +SetInterpolationForKey("/nodes/{}/translation", [new TransformNodeAnimationPropertyInfo(Animation.ANIMATIONTYPE_VECTOR3, "position", getVector3, () => 3)]); +SetInterpolationForKey("/nodes/{}/rotation", [new TransformNodeAnimationPropertyInfo(Animation.ANIMATIONTYPE_QUATERNION, "rotationQuaternion", getQuaternion, () => 4)]); +SetInterpolationForKey("/nodes/{}/scale", [new TransformNodeAnimationPropertyInfo(Animation.ANIMATIONTYPE_VECTOR3, "scaling", getVector3, () => 3)]); +SetInterpolationForKey("/nodes/{}/weights", [new WeightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "influence", getWeights, (target) => target._numMorphTargets)]); + +const glTFLoaderAnimation = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + AnimationPropertyInfo, + TransformNodeAnimationPropertyInfo, + WeightAnimationPropertyInfo, + getQuaternion, + getVector3, + getWeights +}, Symbol.toStringTag, { value: 'Module' })); + +let _dumpToolsEngine; +let _enginePromise = null; +async function _CreateDumpRenderer() { + if (!_enginePromise) { + _enginePromise = new Promise((resolve, reject) => { + let canvas; + let engine = null; + const options = { + preserveDrawingBuffer: true, + depth: false, + stencil: false, + alpha: true, + premultipliedAlpha: false, + antialias: false, + failIfMajorPerformanceCaveat: false, + }; + Promise.resolve().then(() => thinEngine) + .then(({ ThinEngine: thinEngineClass }) => { + const engineInstanceCount = EngineStore.Instances.length; + try { + canvas = new OffscreenCanvas(100, 100); // will be resized later + engine = new thinEngineClass(canvas, false, options); + } + catch (e) { + if (engineInstanceCount < EngineStore.Instances.length) { + // The engine was created by another instance, let's use it + EngineStore.Instances.pop()?.dispose(); + } + // The browser either does not support OffscreenCanvas or WebGL context in OffscreenCanvas, fallback on a regular canvas + canvas = document.createElement("canvas"); + engine = new thinEngineClass(canvas, false, options); + } + // remove this engine from the list of instances to avoid using it for other purposes + EngineStore.Instances.pop(); + // However, make sure to dispose it when no other engines are left + EngineStore.OnEnginesDisposedObservable.add((e) => { + // guaranteed to run when no other instances are left + // only dispose if it's not the current engine + if (engine && e !== engine && !engine.isDisposed && EngineStore.Instances.length === 0) { + // Dump the engine and the associated resources + Dispose(); + } + }); + engine.getCaps().parallelShaderCompile = undefined; + const renderer = new EffectRenderer(engine); + Promise.resolve().then(() => pass_fragment$1).then(({ passPixelShader }) => { + if (!engine) { + reject("Engine is not defined"); + return; + } + const wrapper = new EffectWrapper({ + engine, + name: passPixelShader.name, + fragmentShader: passPixelShader.shader, + samplerNames: ["textureSampler"], + }); + _dumpToolsEngine = { + canvas, + engine, + renderer, + wrapper, + }; + resolve(_dumpToolsEngine); + }); + }) + .catch(reject); + }); + } + return await _enginePromise; +} +/** + * Dumps the current bound framebuffer + * @param width defines the rendering width + * @param height defines the rendering height + * @param engine defines the hosting engine + * @param successCallback defines the callback triggered once the data are available + * @param mimeType defines the mime type of the result + * @param fileName defines the filename to download. If present, the result will automatically be downloaded + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @returns a void promise + */ +async function DumpFramebuffer(width, height, engine, successCallback, mimeType = "image/png", fileName, quality) { + // Read the contents of the framebuffer + const bufferView = await engine.readPixels(0, 0, width, height); + const data = new Uint8Array(bufferView.buffer); + DumpData(width, height, data, successCallback, mimeType, fileName, true, undefined, quality); +} +/** + * Dumps an array buffer + * @param width defines the rendering width + * @param height defines the rendering height + * @param data the data array + * @param mimeType defines the mime type of the result + * @param fileName defines the filename to download. If present, the result will automatically be downloaded + * @param invertY true to invert the picture in the Y dimension + * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @returns a promise that resolve to the final data + */ +function DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { + return new Promise((resolve) => { + DumpData(width, height, data, (result) => resolve(result), mimeType, fileName, invertY, toArrayBuffer, quality); + }); +} +/** + * Dumps an array buffer + * @param width defines the rendering width + * @param height defines the rendering height + * @param data the data array + * @param successCallback defines the callback triggered once the data are available + * @param mimeType defines the mime type of the result + * @param fileName defines the filename to download. If present, the result will automatically be downloaded + * @param invertY true to invert the picture in the Y dimension + * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + */ +function DumpData(width, height, data, successCallback, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { + _CreateDumpRenderer().then((renderer) => { + renderer.engine.setSize(width, height, true); + // Convert if data are float32 + if (data instanceof Float32Array) { + const data2 = new Uint8Array(data.length); + let n = data.length; + while (n--) { + const v = data[n]; + data2[n] = Math.round(Clamp(v) * 255); + } + data = data2; + } + // Create the image + const texture = renderer.engine.createRawTexture(data, width, height, 5, false, !invertY, 1); + renderer.renderer.setViewport(); + renderer.renderer.applyEffectWrapper(renderer.wrapper); + renderer.wrapper.effect._bindTexture("textureSampler", texture); + renderer.renderer.draw(); + if (toArrayBuffer) { + Tools.ToBlob(renderer.canvas, (blob) => { + const fileReader = new FileReader(); + fileReader.onload = (event) => { + const arrayBuffer = event.target.result; + if (successCallback) { + successCallback(arrayBuffer); + } + }; + fileReader.readAsArrayBuffer(blob); + }, mimeType, quality); + } + else { + Tools.EncodeScreenshotCanvasData(renderer.canvas, successCallback, mimeType, fileName, quality); + } + texture.dispose(); + }); +} +/** + * Dispose the dump tools associated resources + */ +function Dispose() { + if (_dumpToolsEngine) { + _dumpToolsEngine.wrapper.dispose(); + _dumpToolsEngine.renderer.dispose(); + _dumpToolsEngine.engine.dispose(); + } + else { + // in cases where the engine is not yet created, we need to wait for it to dispose it + _enginePromise?.then((dumpToolsEngine) => { + dumpToolsEngine.wrapper.dispose(); + dumpToolsEngine.renderer.dispose(); + dumpToolsEngine.engine.dispose(); + }); + } + _enginePromise = null; + _dumpToolsEngine = null; +} +/** + * Object containing a set of static utilities functions to dump data from a canvas + * @deprecated use functions + */ +const DumpTools = { + // eslint-disable-next-line @typescript-eslint/naming-convention + DumpData, + // eslint-disable-next-line @typescript-eslint/naming-convention + DumpDataAsync, + // eslint-disable-next-line @typescript-eslint/naming-convention + DumpFramebuffer, + // eslint-disable-next-line @typescript-eslint/naming-convention + Dispose, +}; +/** + * This will be executed automatically for UMD and es5. + * If esm dev wants the side effects to execute they will have to run it manually + * Once we build native modules those need to be exported. + * @internal + */ +const initSideEffects$1 = () => { + // References the dependencies. + Tools.DumpData = DumpData; + Tools.DumpDataAsync = DumpDataAsync; + Tools.DumpFramebuffer = DumpFramebuffer; +}; +initSideEffects$1(); + +const dumpTools = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + Dispose, + DumpData, + DumpDataAsync, + DumpFramebuffer, + DumpTools +}, Symbol.toStringTag, { value: 'Module' })); + +const DefaultEnvironmentTextureImageType = "image/png"; +const CurrentVersion = 2; +/** + * Magic number identifying the env file. + */ +const MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36]; +/** + * Gets the environment info from an env file. + * @param data The array buffer containing the .env bytes. + * @returns the environment file info (the json header) if successfully parsed, normalized to the latest supported version. + */ +function GetEnvInfo(data) { + const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); + let pos = 0; + for (let i = 0; i < MagicBytes.length; i++) { + if (dataView.getUint8(pos++) !== MagicBytes[i]) { + Logger.Error("Not a babylon environment map"); + return null; + } + } + // Read json manifest - collect characters up to null terminator + let manifestString = ""; + let charCode = 0x00; + while ((charCode = dataView.getUint8(pos++))) { + manifestString += String.fromCharCode(charCode); + } + let manifest = JSON.parse(manifestString); + manifest = normalizeEnvInfo(manifest); + // Extend the header with the position of the payload. + manifest.binaryDataPosition = pos; + if (manifest.specular) { + // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility. + manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8; + } + return manifest; +} +/** + * Normalizes any supported version of the environment file info to the latest version + * @param info environment file info on any supported version + * @returns environment file info in the latest supported version + * @private + */ +function normalizeEnvInfo(info) { + if (info.version > CurrentVersion) { + throw new Error(`Unsupported babylon environment map version "${info.version}". Latest supported version is "${CurrentVersion}".`); + } + if (info.version === 2) { + return info; + } + // Migrate a v1 info to v2 + info = { ...info, version: 2, imageType: DefaultEnvironmentTextureImageType }; + return info; +} +/** + * Creates the ArrayBufferViews used for initializing environment texture image data. + * @param data the image data + * @param info parameters that determine what views will be created for accessing the underlying buffer + * @returns the views described by info providing access to the underlying buffer + */ +function CreateRadianceImageDataArrayBufferViews(data, info) { + info = normalizeEnvInfo(info); + const specularInfo = info.specular; + // Double checks the enclosed info + let mipmapsCount = Math.log2(info.width); + mipmapsCount = Math.round(mipmapsCount) + 1; + if (specularInfo.mipmaps.length !== 6 * mipmapsCount) { + throw new Error(`Unsupported specular mipmaps number "${specularInfo.mipmaps.length}"`); + } + const imageData = new Array(mipmapsCount); + for (let i = 0; i < mipmapsCount; i++) { + imageData[i] = new Array(6); + for (let face = 0; face < 6; face++) { + const imageInfo = specularInfo.mipmaps[i * 6 + face]; + imageData[i][face] = new Uint8Array(data.buffer, data.byteOffset + info.binaryDataPosition + imageInfo.position, imageInfo.length); + } + } + return imageData; +} +/** + * Creates the ArrayBufferViews used for initializing environment texture image data. + * @param data the image data + * @param info parameters that determine what views will be created for accessing the underlying buffer + * @returns the views described by info providing access to the underlying buffer + */ +function CreateIrradianceImageDataArrayBufferViews(data, info) { + info = normalizeEnvInfo(info); + const imageData = new Array(6); + const irradianceTexture = info.irradiance?.irradianceTexture; + if (irradianceTexture) { + if (irradianceTexture.faces.length !== 6) { + throw new Error(`Incorrect irradiance texture faces number "${irradianceTexture.faces.length}"`); + } + for (let face = 0; face < 6; face++) { + const imageInfo = irradianceTexture.faces[face]; + imageData[face] = new Uint8Array(data.buffer, data.byteOffset + info.binaryDataPosition + imageInfo.position, imageInfo.length); + } + } + return imageData; +} +/** + * Uploads the texture info contained in the env file to the GPU. + * @param texture defines the internal texture to upload to + * @param data defines the data to load + * @param info defines the texture info retrieved through the GetEnvInfo method + * @returns a promise + */ +function UploadEnvLevelsAsync(texture, data, info) { + info = normalizeEnvInfo(info); + const specularInfo = info.specular; + if (!specularInfo) { + // Nothing else parsed so far + return Promise.resolve([]); + } + texture._lodGenerationScale = specularInfo.lodGenerationScale; + const promises = []; + const radianceImageData = CreateRadianceImageDataArrayBufferViews(data, info); + promises.push(UploadRadianceLevelsAsync(texture, radianceImageData, info.imageType)); + const irradianceTexture = info.irradiance?.irradianceTexture; + if (irradianceTexture) { + const irradianceImageData = CreateIrradianceImageDataArrayBufferViews(data, info); + promises.push(UploadIrradianceLevelsAsync(texture, irradianceImageData, irradianceTexture.size, info.imageType)); + } + return Promise.all(promises); +} +function _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture) { + return new Promise((resolve, reject) => { + if (expandTexture) { + const tempTexture = engine.createTexture(null, true, true, null, 1, null, (message) => { + reject(message); + }, image); + rgbdPostProcess?.onEffectCreatedObservable.addOnce((effect) => { + effect.executeWhenCompiled(() => { + // Uncompress the data to a RTT + rgbdPostProcess.externalTextureSamplerBinding = true; + rgbdPostProcess.onApply = (effect) => { + effect._bindTexture("textureSampler", tempTexture); + effect.setFloat2("scale", 1, engine._features.needsInvertingBitmap && image instanceof ImageBitmap ? -1 : 1); + }; + if (!engine.scenes.length) { + return; + } + engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i); + // Cleanup + engine.restoreDefaultFramebuffer(); + tempTexture.dispose(); + URL.revokeObjectURL(url); + resolve(); + }); + }); + } + else { + engine._uploadImageToTexture(texture, image, face, i); + // Upload the face to the non lod texture support + if (generateNonLODTextures) { + const lodTexture = lodTextures[i]; + if (lodTexture) { + engine._uploadImageToTexture(lodTexture._texture, image, face, 0); + } + } + resolve(); + } + }); +} +/** + * Uploads the levels of image data to the GPU. + * @param texture defines the internal texture to upload to + * @param imageData defines the array buffer views of image data [mipmap][face] + * @param imageType the mime type of the image data + * @returns a promise + */ +async function UploadRadianceLevelsAsync(texture, imageData, imageType = DefaultEnvironmentTextureImageType) { + const engine = texture.getEngine(); + texture.format = 5; + texture.type = 0; + texture.generateMipMaps = true; + texture._cachedAnisotropicFilteringLevel = null; + engine.updateTextureSamplingMode(3, texture); + await _UploadLevelsAsync(texture, imageData, true, imageType); + // Flag internal texture as ready in case they are in use. + texture.isReady = true; +} +/** + * Uploads the levels of image data to the GPU. + * @param mainTexture defines the internal texture to upload to + * @param imageData defines the array buffer views of image data [mipmap][face] + * @param size defines the size of the texture faces + * @param imageType the mime type of the image data + * @returns a promise + */ +async function UploadIrradianceLevelsAsync(mainTexture, imageData, size, imageType = DefaultEnvironmentTextureImageType) { + // Gets everything ready. + const engine = mainTexture.getEngine(); + const texture = new InternalTexture(engine, 5 /* InternalTextureSource.RenderTarget */); + const baseTexture = new BaseTexture(engine, texture); + mainTexture._irradianceTexture = baseTexture; + texture.isCube = true; + texture.format = 5; + texture.type = 0; + texture.generateMipMaps = true; + texture._cachedAnisotropicFilteringLevel = null; + texture.generateMipMaps = true; + texture.width = size; + texture.height = size; + engine.updateTextureSamplingMode(3, texture); + await _UploadLevelsAsync(texture, [imageData], false, imageType); + engine.generateMipMapsForCubemap(texture); + // Flag internal texture as ready in case they are in use. + texture.isReady = true; +} +/** + * Uploads the levels of image data to the GPU. + * @param texture defines the internal texture to upload to + * @param imageData defines the array buffer views of image data [mipmap][face] + * @param canGenerateNonLODTextures defines whether or not to generate non lod textures + * @param imageType the mime type of the image data + * @returns a promise + */ +async function _UploadLevelsAsync(texture, imageData, canGenerateNonLODTextures, imageType = DefaultEnvironmentTextureImageType) { + if (!Tools.IsExponentOfTwo(texture.width)) { + throw new Error("Texture size must be a power of two"); + } + const mipmapsCount = ILog2(texture.width) + 1; + // Gets everything ready. + const engine = texture.getEngine(); + let expandTexture = false; + let generateNonLODTextures = false; + let rgbdPostProcess = null; + let cubeRtt = null; + let lodTextures = null; + const caps = engine.getCaps(); + if (!caps.textureLOD) { + expandTexture = false; + generateNonLODTextures = canGenerateNonLODTextures; + } + else if (!engine._features.supportRenderAndCopyToLodForFloatTextures) { + expandTexture = false; + } + // If half float available we can uncompress the texture + else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { + expandTexture = true; + texture.type = 2; + } + // If full float available we can uncompress the texture + else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { + expandTexture = true; + texture.type = 1; + } + // Expand the texture if possible + let shaderLanguage = 0 /* ShaderLanguage.GLSL */; + if (expandTexture) { + if (engine.isWebGPU) { + shaderLanguage = 1 /* ShaderLanguage.WGSL */; + await Promise.resolve().then(() => rgbdDecode_fragment); + } + else { + await Promise.resolve().then(() => rgbdDecode_fragment$1); + } + // Simply run through the decode PP + rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, 3, engine, false, undefined, texture.type, undefined, null, false, undefined, shaderLanguage); + texture._isRGBD = false; + texture.invertY = false; + cubeRtt = engine.createRenderTargetCubeTexture(texture.width, { + generateDepthBuffer: false, + generateMipMaps: true, + generateStencilBuffer: false, + samplingMode: 3, + type: texture.type, + format: 5, + }); + } + else { + texture._isRGBD = true; + texture.invertY = true; + // In case of missing support, applies the same patch than DDS files. + if (generateNonLODTextures) { + const mipSlices = 3; + lodTextures = {}; + const scale = texture._lodGenerationScale; + const offset = texture._lodGenerationOffset; + for (let i = 0; i < mipSlices; i++) { + //compute LOD from even spacing in smoothness (matching shader calculation) + const smoothness = i / (mipSlices - 1); + const roughness = 1 - smoothness; + const minLODIndex = offset; // roughness = 0 + const maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0) + const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness; + const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex)); + //compute LOD from even spacing in smoothness (matching shader calculation) + const glTextureFromLod = new InternalTexture(engine, 2 /* InternalTextureSource.Temp */); + glTextureFromLod.isCube = true; + glTextureFromLod.invertY = true; + glTextureFromLod.generateMipMaps = false; + engine.updateTextureSamplingMode(2, glTextureFromLod); + // Wrap in a base texture for easy binding. + const lodTexture = new BaseTexture(null); + lodTexture._isCube = true; + lodTexture._texture = glTextureFromLod; + lodTextures[mipmapIndex] = lodTexture; + switch (i) { + case 0: + texture._lodTextureLow = lodTexture; + break; + case 1: + texture._lodTextureMid = lodTexture; + break; + case 2: + texture._lodTextureHigh = lodTexture; + break; + } + } + } + } + const promises = []; + // All mipmaps up to provided number of images + for (let i = 0; i < imageData.length; i++) { + // All faces + for (let face = 0; face < 6; face++) { + // Constructs an image element from image data + const bytes = imageData[i][face]; + const blob = new Blob([bytes], { type: imageType }); + const url = URL.createObjectURL(blob); + let promise; + if (engine._features.forceBitmapOverHTMLImageElement) { + promise = engine.createImageBitmap(blob, { premultiplyAlpha: "none" }).then((img) => { + return _OnImageReadyAsync(img, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture); + }); + } + else { + const image = new Image(); + image.src = url; + // Enqueue promise to upload to the texture. + promise = new Promise((resolve, reject) => { + image.onload = () => { + _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture) + .then(() => resolve()) + .catch((reason) => { + reject(reason); + }); + }; + image.onerror = (error) => { + reject(error); + }; + }); + } + promises.push(promise); + } + } + await Promise.all(promises); + // Fill remaining mipmaps with black textures. + if (imageData.length < mipmapsCount) { + let data; + const size = Math.pow(2, mipmapsCount - 1 - imageData.length); + const dataLength = size * size * 4; + switch (texture.type) { + case 0: { + data = new Uint8Array(dataLength); + break; + } + case 2: { + data = new Uint16Array(dataLength); + break; + } + case 1: { + data = new Float32Array(dataLength); + break; + } + } + for (let i = imageData.length; i < mipmapsCount; i++) { + for (let face = 0; face < 6; face++) { + engine._uploadArrayBufferViewToTexture(cubeRtt?.texture || texture, data, face, i); + } + } + } + // Release temp RTT. + if (cubeRtt) { + const irradiance = texture._irradianceTexture; + texture._irradianceTexture = null; + engine._releaseTexture(texture); + cubeRtt._swapAndDie(texture); + texture._irradianceTexture = irradiance; + } + // Release temp Post Process. + if (rgbdPostProcess) { + rgbdPostProcess.dispose(); + } + // Flag internal texture as ready in case they are in use. + if (generateNonLODTextures) { + if (texture._lodTextureHigh && texture._lodTextureHigh._texture) { + texture._lodTextureHigh._texture.isReady = true; + } + if (texture._lodTextureMid && texture._lodTextureMid._texture) { + texture._lodTextureMid._texture.isReady = true; + } + if (texture._lodTextureLow && texture._lodTextureLow._texture) { + texture._lodTextureLow._texture.isReady = true; + } + } +} +/** + * Uploads spherical polynomials information to the texture. + * @param texture defines the texture we are trying to upload the information to + * @param info defines the environment texture info retrieved through the GetEnvInfo method + */ +function UploadEnvSpherical(texture, info) { + info = normalizeEnvInfo(info); + const irradianceInfo = info.irradiance; + if (!irradianceInfo) { + return; + } + const sp = new SphericalPolynomial(); + Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x); + Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y); + Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z); + Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx); + Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy); + Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz); + Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz); + Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx); + Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy); + texture._sphericalPolynomial = sp; +} +/** + * @internal + */ +function _UpdateRGBDAsync(internalTexture, data, sphericalPolynomial, lodScale, lodOffset) { + const proxy = internalTexture + .getEngine() + .createRawCubeTexture(null, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression); + const proxyPromise = UploadRadianceLevelsAsync(proxy, data).then(() => internalTexture); + internalTexture.onRebuildCallback = (_internalTexture) => { + return { + proxy: proxyPromise, + isReady: true, + isAsync: true, + }; + }; + internalTexture._source = 13 /* InternalTextureSource.CubeRawRGBD */; + internalTexture._bufferViewArrayArray = data; + internalTexture._lodGenerationScale = lodScale; + internalTexture._lodGenerationOffset = lodOffset; + internalTexture._sphericalPolynomial = sphericalPolynomial; + return UploadRadianceLevelsAsync(internalTexture, data).then(() => { + internalTexture.isReady = true; + return internalTexture; + }); +} + +/** + * Raw cube texture where the raw buffers are passed in + */ +class RawCubeTexture extends CubeTexture { + /** + * Creates a cube texture where the raw buffers are passed in. + * @param scene defines the scene the texture is attached to + * @param data defines the array of data to use to create each face + * @param size defines the size of the textures + * @param format defines the format of the data + * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_BYTE) + * @param generateMipMaps defines if the engine should generate the mip levels + * @param invertY defines if data must be stored with Y axis inverted + * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) + * @param compression defines the compression used (null by default) + */ + constructor(scene, data, size, format = 5, type = 0, generateMipMaps = false, invertY = false, samplingMode = 3, compression = null) { + super("", scene); + this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression); + } + /** + * Updates the raw cube texture. + * @param data defines the data to store + * @param format defines the data format + * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_BYTE by default) + * @param invertY defines if data must be stored with Y axis inverted + * @param compression defines the compression used (null by default) + */ + update(data, format, type, invertY, compression = null) { + this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression); + } + /** + * Updates a raw cube texture with RGBD encoded data. + * @param data defines the array of data [mipmap][face] to use to create each face + * @param sphericalPolynomial defines the spherical polynomial for irradiance + * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness + * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness + * @returns a promise that resolves when the operation is complete + */ + updateRGBDAsync(data, sphericalPolynomial = null, lodScale = 0.8, lodOffset = 0) { + return _UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset).then(() => { }); + } + /** + * Clones the raw cube texture. + * @returns a new cube texture + */ + clone() { + return SerializationHelper.Clone(() => { + const scene = this.getScene(); + const internalTexture = this._texture; + const texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression); + if (internalTexture.source === 13 /* InternalTextureSource.CubeRawRGBD */) { + texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset); + } + return texture; + }, this); + } +} + +const NAME$z = "EXT_lights_image_based"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_lights_image_based/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class EXT_lights_image_based { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$z; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$z); + } + /** @internal */ + dispose() { + this._loader = null; + delete this._lights; + } + /** @internal */ + onLoading() { + const extensions = this._loader.gltf.extensions; + if (extensions && extensions[this.name]) { + const extension = extensions[this.name]; + this._lights = extension.lights; + } + } + /** + * @internal + */ + loadSceneAsync(context, scene) { + return GLTFLoader.LoadExtensionAsync(context, scene, this.name, (extensionContext, extension) => { + this._loader._allMaterialsDirtyRequired = true; + const promises = new Array(); + promises.push(this._loader.loadSceneAsync(context, scene)); + this._loader.logOpen(`${extensionContext}`); + const light = ArrayItem.Get(`${extensionContext}/light`, this._lights, extension.light); + promises.push(this._loadLightAsync(`/extensions/${this.name}/lights/${extension.light}`, light).then((texture) => { + this._loader.babylonScene.environmentTexture = texture; + })); + this._loader.logClose(); + return Promise.all(promises).then(() => { }); + }); + } + _loadLightAsync(context, light) { + if (!light._loaded) { + const promises = new Array(); + this._loader.logOpen(`${context}`); + const imageData = new Array(light.specularImages.length); + for (let mipmap = 0; mipmap < light.specularImages.length; mipmap++) { + const faces = light.specularImages[mipmap]; + imageData[mipmap] = new Array(faces.length); + for (let face = 0; face < faces.length; face++) { + const specularImageContext = `${context}/specularImages/${mipmap}/${face}`; + this._loader.logOpen(`${specularImageContext}`); + const index = faces[face]; + const image = ArrayItem.Get(specularImageContext, this._loader.gltf.images, index); + promises.push(this._loader.loadImageAsync(`/images/${index}`, image).then((data) => { + imageData[mipmap][face] = data; + })); + this._loader.logClose(); + } + } + this._loader.logClose(); + light._loaded = Promise.all(promises).then(() => { + const babylonTexture = new RawCubeTexture(this._loader.babylonScene, null, light.specularImageSize); + babylonTexture.name = light.name || "environment"; + light._babylonTexture = babylonTexture; + if (light.intensity != undefined) { + babylonTexture.level = light.intensity; + } + if (light.rotation) { + let rotation = Quaternion.FromArray(light.rotation); + // Invert the rotation so that positive rotation is counter-clockwise. + if (!this._loader.babylonScene.useRightHandedSystem) { + rotation = Quaternion.Inverse(rotation); + } + Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix()); + } + if (!light.irradianceCoefficients) { + throw new Error(`${context}: Irradiance coefficients are missing`); + } + const sphericalHarmonics = SphericalHarmonics.FromArray(light.irradianceCoefficients); + sphericalHarmonics.scaleInPlace(light.intensity); + sphericalHarmonics.convertIrradianceToLambertianRadiance(); + const sphericalPolynomial = SphericalPolynomial.FromHarmonics(sphericalHarmonics); + // Compute the lod generation scale to fit exactly to the number of levels available. + const lodGenerationScale = (imageData.length - 1) / Math.log2(light.specularImageSize); + return babylonTexture.updateRGBDAsync(imageData, sphericalPolynomial, lodGenerationScale); + }); + } + return light._loaded.then(() => { + return light._babylonTexture; + }); + } +} +unregisterGLTFExtension(NAME$z); +registerGLTFExtension(NAME$z, true, (loader) => new EXT_lights_image_based(loader)); + +Mesh.prototype.thinInstanceAdd = function (matrix, refresh = true) { + if (!this.getScene().getEngine().getCaps().instancedArrays) { + Logger.Error("Thin Instances are not supported on this device as Instanced Array extension not supported"); + return -1; + } + this._thinInstanceUpdateBufferSize("matrix", Array.isArray(matrix) ? matrix.length : 1); + const index = this._thinInstanceDataStorage.instancesCount; + if (Array.isArray(matrix)) { + for (let i = 0; i < matrix.length; ++i) { + this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++, matrix[i], i === matrix.length - 1 && refresh); + } + } + else { + this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++, matrix, refresh); + } + return index; +}; +Mesh.prototype.thinInstanceAddSelf = function (refresh = true) { + return this.thinInstanceAdd(Matrix.IdentityReadOnly, refresh); +}; +Mesh.prototype.thinInstanceRegisterAttribute = function (kind, stride) { + // preserve backward compatibility + if (kind === VertexBuffer.ColorKind) { + kind = VertexBuffer.ColorInstanceKind; + } + this.removeVerticesData(kind); + this._thinInstanceInitializeUserStorage(); + this._userThinInstanceBuffersStorage.strides[kind] = stride; + this._userThinInstanceBuffersStorage.sizes[kind] = stride * Math.max(32, this._thinInstanceDataStorage.instancesCount); // Initial size + this._userThinInstanceBuffersStorage.data[kind] = new Float32Array(this._userThinInstanceBuffersStorage.sizes[kind]); + this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userThinInstanceBuffersStorage.data[kind], kind, true, false, stride, true); + this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]); +}; +Mesh.prototype.thinInstanceSetMatrixAt = function (index, matrix, refresh = true) { + if (!this._thinInstanceDataStorage.matrixData || index >= this._thinInstanceDataStorage.instancesCount) { + return false; + } + const matrixData = this._thinInstanceDataStorage.matrixData; + matrix.copyToArray(matrixData, index * 16); + if (this._thinInstanceDataStorage.worldMatrices) { + this._thinInstanceDataStorage.worldMatrices[index] = matrix; + } + if (refresh) { + this.thinInstanceBufferUpdated("matrix"); + if (!this.doNotSyncBoundingInfo) { + this.thinInstanceRefreshBoundingInfo(false); + } + } + return true; +}; +Mesh.prototype.thinInstanceSetAttributeAt = function (kind, index, value, refresh = true) { + // preserve backward compatibility + if (kind === VertexBuffer.ColorKind) { + kind = VertexBuffer.ColorInstanceKind; + } + if (!this._userThinInstanceBuffersStorage || !this._userThinInstanceBuffersStorage.data[kind] || index >= this._thinInstanceDataStorage.instancesCount) { + return false; + } + this._thinInstanceUpdateBufferSize(kind, 0); // make sur the buffer for the kind attribute is big enough + this._userThinInstanceBuffersStorage.data[kind].set(value, index * this._userThinInstanceBuffersStorage.strides[kind]); + if (refresh) { + this.thinInstanceBufferUpdated(kind); + } + return true; +}; +Object.defineProperty(Mesh.prototype, "thinInstanceCount", { + get: function () { + return this._thinInstanceDataStorage.instancesCount; + }, + set: function (value) { + const matrixData = this._thinInstanceDataStorage.matrixData ?? this.source?._thinInstanceDataStorage.matrixData; + const numMaxInstances = matrixData ? matrixData.length / 16 : 0; + if (value <= numMaxInstances) { + this._thinInstanceDataStorage.instancesCount = value; + } + }, + enumerable: true, + configurable: true, +}); +Mesh.prototype._thinInstanceCreateMatrixBuffer = function (kind, buffer, staticBuffer = true) { + const matrixBuffer = new Buffer(this.getEngine(), buffer, !staticBuffer, 16, false, true); + for (let i = 0; i < 4; i++) { + this.setVerticesBuffer(matrixBuffer.createVertexBuffer(kind + i, i * 4, 4)); + } + return matrixBuffer; +}; +Mesh.prototype.thinInstanceSetBuffer = function (kind, buffer, stride = 0, staticBuffer = true) { + stride = stride || 16; + if (kind === "matrix") { + this._thinInstanceDataStorage.matrixBuffer?.dispose(); + this._thinInstanceDataStorage.matrixBuffer = null; + this._thinInstanceDataStorage.matrixBufferSize = buffer ? buffer.length : 32 * stride; + this._thinInstanceDataStorage.matrixData = buffer; + this._thinInstanceDataStorage.worldMatrices = null; + if (buffer !== null) { + this._thinInstanceDataStorage.instancesCount = buffer.length / stride; + this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer("world", buffer, staticBuffer); + if (!this.doNotSyncBoundingInfo) { + this.thinInstanceRefreshBoundingInfo(false); + } + } + else { + this._thinInstanceDataStorage.instancesCount = 0; + if (!this.doNotSyncBoundingInfo) { + // mesh has no more thin instances, so need to recompute the bounding box because it's the regular mesh that will now be displayed + this.refreshBoundingInfo(); + } + } + } + else if (kind === "previousMatrix") { + this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(); + this._thinInstanceDataStorage.previousMatrixBuffer = null; + this._thinInstanceDataStorage.previousMatrixData = buffer; + if (buffer !== null) { + this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", buffer, staticBuffer); + } + } + else { + // color for instanced mesh is ColorInstanceKind and not ColorKind because of native that needs to do the differenciation + // hot switching kind here to preserve backward compatibility + if (kind === VertexBuffer.ColorKind) { + kind = VertexBuffer.ColorInstanceKind; + } + if (buffer === null) { + if (this._userThinInstanceBuffersStorage?.data[kind]) { + this.removeVerticesData(kind); + delete this._userThinInstanceBuffersStorage.data[kind]; + delete this._userThinInstanceBuffersStorage.strides[kind]; + delete this._userThinInstanceBuffersStorage.sizes[kind]; + delete this._userThinInstanceBuffersStorage.vertexBuffers[kind]; + } + } + else { + this._thinInstanceInitializeUserStorage(); + this._userThinInstanceBuffersStorage.data[kind] = buffer; + this._userThinInstanceBuffersStorage.strides[kind] = stride; + this._userThinInstanceBuffersStorage.sizes[kind] = buffer.length; + this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), buffer, kind, !staticBuffer, false, stride, true); + this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]); + } + } +}; +Mesh.prototype.thinInstanceBufferUpdated = function (kind) { + if (kind === "matrix") { + if (this.thinInstanceAllowAutomaticStaticBufferRecreation && this._thinInstanceDataStorage.matrixBuffer && !this._thinInstanceDataStorage.matrixBuffer.isUpdatable()) { + this._thinInstanceRecreateBuffer(kind); + } + this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, this._thinInstanceDataStorage.instancesCount); + } + else if (kind === "previousMatrix") { + if (this.thinInstanceAllowAutomaticStaticBufferRecreation && + this._thinInstanceDataStorage.previousMatrixBuffer && + !this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()) { + this._thinInstanceRecreateBuffer(kind); + } + this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData, 0, this._thinInstanceDataStorage.instancesCount); + } + else { + // preserve backward compatibility + if (kind === VertexBuffer.ColorKind) { + kind = VertexBuffer.ColorInstanceKind; + } + if (this._userThinInstanceBuffersStorage?.vertexBuffers[kind]) { + if (this.thinInstanceAllowAutomaticStaticBufferRecreation && !this._userThinInstanceBuffersStorage.vertexBuffers[kind].isUpdatable()) { + this._thinInstanceRecreateBuffer(kind); + } + this._userThinInstanceBuffersStorage.vertexBuffers[kind].updateDirectly(this._userThinInstanceBuffersStorage.data[kind], 0); + } + } +}; +Mesh.prototype.thinInstancePartialBufferUpdate = function (kind, data, offset) { + if (kind === "matrix") { + if (this._thinInstanceDataStorage.matrixBuffer) { + this._thinInstanceDataStorage.matrixBuffer.updateDirectly(data, offset); + } + } + else { + // preserve backward compatibility + if (kind === VertexBuffer.ColorKind) { + kind = VertexBuffer.ColorInstanceKind; + } + if (this._userThinInstanceBuffersStorage?.vertexBuffers[kind]) { + this._userThinInstanceBuffersStorage.vertexBuffers[kind].updateDirectly(data, offset); + } + } +}; +Mesh.prototype.thinInstanceGetWorldMatrices = function () { + if (!this._thinInstanceDataStorage.matrixData || !this._thinInstanceDataStorage.matrixBuffer) { + return []; + } + const matrixData = this._thinInstanceDataStorage.matrixData; + if (!this._thinInstanceDataStorage.worldMatrices) { + this._thinInstanceDataStorage.worldMatrices = []; + for (let i = 0; i < this._thinInstanceDataStorage.instancesCount; ++i) { + this._thinInstanceDataStorage.worldMatrices[i] = Matrix.FromArray(matrixData, i * 16); + } + } + return this._thinInstanceDataStorage.worldMatrices; +}; +Mesh.prototype.thinInstanceRefreshBoundingInfo = function (forceRefreshParentInfo = false, applySkeleton = false, applyMorph = false) { + if (!this._thinInstanceDataStorage.matrixData || !this._thinInstanceDataStorage.matrixBuffer) { + return; + } + const vectors = this._thinInstanceDataStorage.boundingVectors; + if (forceRefreshParentInfo || !this.rawBoundingInfo) { + vectors.length = 0; + this.refreshBoundingInfo(applySkeleton, applyMorph); + const boundingInfo = this.getBoundingInfo(); + this.rawBoundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum); + } + const boundingInfo = this.getBoundingInfo(); + const matrixData = this._thinInstanceDataStorage.matrixData; + if (vectors.length === 0) { + for (let v = 0; v < boundingInfo.boundingBox.vectors.length; ++v) { + vectors.push(boundingInfo.boundingBox.vectors[v].clone()); + } + } + TmpVectors.Vector3[0].setAll(Number.POSITIVE_INFINITY); // min + TmpVectors.Vector3[1].setAll(Number.NEGATIVE_INFINITY); // max + for (let i = 0; i < this._thinInstanceDataStorage.instancesCount; ++i) { + Matrix.FromArrayToRef(matrixData, i * 16, TmpVectors.Matrix[0]); + for (let v = 0; v < vectors.length; ++v) { + Vector3.TransformCoordinatesToRef(vectors[v], TmpVectors.Matrix[0], TmpVectors.Vector3[2]); + TmpVectors.Vector3[0].minimizeInPlace(TmpVectors.Vector3[2]); + TmpVectors.Vector3[1].maximizeInPlace(TmpVectors.Vector3[2]); + } + } + boundingInfo.reConstruct(TmpVectors.Vector3[0], TmpVectors.Vector3[1]); + this._updateBoundingInfo(); +}; +Mesh.prototype._thinInstanceRecreateBuffer = function (kind, staticBuffer = true) { + if (kind === "matrix") { + this._thinInstanceDataStorage.matrixBuffer?.dispose(); + this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer("world", this._thinInstanceDataStorage.matrixData, staticBuffer); + } + else if (kind === "previousMatrix") { + if (this._scene.needsPreviousWorldMatrices) { + this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(); + this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", this._thinInstanceDataStorage.previousMatrixData ?? this._thinInstanceDataStorage.matrixData, staticBuffer); + } + } + else { + if (kind === VertexBuffer.ColorKind) { + kind = VertexBuffer.ColorInstanceKind; + } + this._userThinInstanceBuffersStorage.vertexBuffers[kind]?.dispose(); + this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userThinInstanceBuffersStorage.data[kind], kind, !staticBuffer, false, this._userThinInstanceBuffersStorage.strides[kind], true); + this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]); + } +}; +Mesh.prototype._thinInstanceUpdateBufferSize = function (kind, numInstances = 1) { + // preserve backward compatibility + if (kind === VertexBuffer.ColorKind) { + kind = VertexBuffer.ColorInstanceKind; + } + const kindIsMatrix = kind === "matrix"; + if (!kindIsMatrix && (!this._userThinInstanceBuffersStorage || !this._userThinInstanceBuffersStorage.strides[kind])) { + return; + } + const stride = kindIsMatrix ? 16 : this._userThinInstanceBuffersStorage.strides[kind]; + const currentSize = kindIsMatrix ? this._thinInstanceDataStorage.matrixBufferSize : this._userThinInstanceBuffersStorage.sizes[kind]; + let data = kindIsMatrix ? this._thinInstanceDataStorage.matrixData : this._userThinInstanceBuffersStorage.data[kind]; + const bufferSize = (this._thinInstanceDataStorage.instancesCount + numInstances) * stride; + let newSize = currentSize; + while (newSize < bufferSize) { + newSize *= 2; + } + if (!data || currentSize != newSize) { + if (!data) { + data = new Float32Array(newSize); + } + else { + const newData = new Float32Array(newSize); + newData.set(data, 0); + data = newData; + } + if (kindIsMatrix) { + this._thinInstanceDataStorage.matrixBuffer?.dispose(); + this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer("world", data, false); + this._thinInstanceDataStorage.matrixData = data; + this._thinInstanceDataStorage.matrixBufferSize = newSize; + if (this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData) { + this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(); + this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", data, false); + } + } + else { + this._userThinInstanceBuffersStorage.vertexBuffers[kind]?.dispose(); + this._userThinInstanceBuffersStorage.data[kind] = data; + this._userThinInstanceBuffersStorage.sizes[kind] = newSize; + this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), data, kind, true, false, stride, true); + this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]); + } + } +}; +Mesh.prototype._thinInstanceInitializeUserStorage = function () { + if (!this._userThinInstanceBuffersStorage) { + this._userThinInstanceBuffersStorage = { + data: {}, + sizes: {}, + vertexBuffers: {}, + strides: {}, + }; + } +}; +Mesh.prototype._disposeThinInstanceSpecificData = function () { + if (this._thinInstanceDataStorage?.matrixBuffer) { + this._thinInstanceDataStorage.matrixBuffer.dispose(); + this._thinInstanceDataStorage.matrixBuffer = null; + } +}; + +const NAME$y = "EXT_mesh_gpu_instancing"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_mesh_gpu_instancing/README.md) + * [Playground Sample](https://playground.babylonjs.com/#QFIGLW#9) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class EXT_mesh_gpu_instancing { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$y; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$y); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadNodeAsync(context, node, assign) { + return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => { + this._loader._disableInstancedMesh++; + const promise = this._loader.loadNodeAsync(`/nodes/${node.index}`, node, assign); + this._loader._disableInstancedMesh--; + if (!node._primitiveBabylonMeshes) { + return promise; + } + const promises = new Array(); + let instanceCount = 0; + const loadAttribute = (attribute) => { + if (extension.attributes[attribute] == undefined) { + promises.push(Promise.resolve(null)); + return; + } + const accessor = ArrayItem.Get(`${extensionContext}/attributes/${attribute}`, this._loader.gltf.accessors, extension.attributes[attribute]); + promises.push(this._loader._loadFloatAccessorAsync(`/accessors/${accessor.bufferView}`, accessor)); + if (instanceCount === 0) { + instanceCount = accessor.count; + } + else if (instanceCount !== accessor.count) { + throw new Error(`${extensionContext}/attributes: Instance buffer accessors do not have the same count.`); + } + }; + loadAttribute("TRANSLATION"); + loadAttribute("ROTATION"); + loadAttribute("SCALE"); + return promise.then((babylonTransformNode) => { + return Promise.all(promises).then(([translationBuffer, rotationBuffer, scaleBuffer]) => { + const matrices = new Float32Array(instanceCount * 16); + TmpVectors.Vector3[0].copyFromFloats(0, 0, 0); // translation + TmpVectors.Quaternion[0].copyFromFloats(0, 0, 0, 1); // rotation + TmpVectors.Vector3[1].copyFromFloats(1, 1, 1); // scale + for (let i = 0; i < instanceCount; ++i) { + translationBuffer && Vector3.FromArrayToRef(translationBuffer, i * 3, TmpVectors.Vector3[0]); + rotationBuffer && Quaternion.FromArrayToRef(rotationBuffer, i * 4, TmpVectors.Quaternion[0]); + scaleBuffer && Vector3.FromArrayToRef(scaleBuffer, i * 3, TmpVectors.Vector3[1]); + Matrix.ComposeToRef(TmpVectors.Vector3[1], TmpVectors.Quaternion[0], TmpVectors.Vector3[0], TmpVectors.Matrix[0]); + TmpVectors.Matrix[0].copyToArray(matrices, i * 16); + } + for (const babylonMesh of node._primitiveBabylonMeshes) { + babylonMesh.thinInstanceSetBuffer("matrix", matrices, 16, true); + } + return babylonTransformNode; + }); + }); + }); + } +} +unregisterGLTFExtension(NAME$y); +registerGLTFExtension(NAME$y, true, (loader) => new EXT_mesh_gpu_instancing(loader)); + +// eslint-disable-next-line @typescript-eslint/naming-convention +let NumberOfWorkers = 0; +// eslint-disable-next-line @typescript-eslint/naming-convention +let WorkerTimeout = null; +/** + * Meshopt compression (https://github.com/zeux/meshoptimizer) + * + * This class wraps the meshopt library from https://github.com/zeux/meshoptimizer/tree/master/js. + * + * **Encoder** + * + * The encoder is not currently implemented. + * + * **Decoder** + * + * By default, the configuration points to a copy of the meshopt files on the Babylon.js preview CDN (e.g. https://preview.babylonjs.com/meshopt_decoder.js). + * + * To update the configuration, use the following code: + * ```javascript + * MeshoptCompression.Configuration = { + * decoder: { + * url: "" + * } + * }; + * ``` + */ +class MeshoptCompression { + /** + * Default instance for the meshoptimizer object. + */ + static get Default() { + if (!MeshoptCompression._Default) { + MeshoptCompression._Default = new MeshoptCompression(); + } + return MeshoptCompression._Default; + } + /** + * Constructor + */ + constructor() { + const decoder = MeshoptCompression.Configuration.decoder; + this._decoderModulePromise = Tools.LoadBabylonScriptAsync(decoder.url).then(() => { + // Wait for WebAssembly compilation before resolving promise + return MeshoptDecoder.ready; + }); + } + /** + * Stop all async operations and release resources. + */ + dispose() { + delete this._decoderModulePromise; + } + /** + * Decode meshopt data. + * @see https://github.com/zeux/meshoptimizer/tree/master/js#decoder + * @param source The input data. + * @param count The number of elements. + * @param stride The stride in bytes. + * @param mode The compression mode. + * @param filter The compression filter. + * @returns a Promise that resolves to the decoded data + */ + decodeGltfBufferAsync(source, count, stride, mode, filter) { + return this._decoderModulePromise.then(async () => { + if (NumberOfWorkers === 0) { + MeshoptDecoder.useWorkers(1); + NumberOfWorkers = 1; + } + const result = await MeshoptDecoder.decodeGltfBufferAsync(count, stride, source, mode, filter); + // a simple debounce to avoid switching back and forth between workers and no workers while decoding + if (WorkerTimeout !== null) { + clearTimeout(WorkerTimeout); + } + WorkerTimeout = setTimeout(() => { + MeshoptDecoder.useWorkers(0); + NumberOfWorkers = 0; + WorkerTimeout = null; + }, 1000); + return result; + }); + } +} +/** + * The configuration. Defaults to the following: + * ```javascript + * decoder: { + * url: "https://cdn.babylonjs.com/meshopt_decoder.js" + * } + * ``` + */ +MeshoptCompression.Configuration = { + decoder: { + url: `${Tools._DefaultCdnUrl}/meshopt_decoder.js`, + }, +}; +MeshoptCompression._Default = null; + +const NAME$x = "EXT_meshopt_compression"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_meshopt_compression/README.md) + * + * This extension uses a WebAssembly decoder module from https://github.com/zeux/meshoptimizer/tree/master/js + * @since 5.0.0 + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class EXT_meshopt_compression { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$x; + this.enabled = loader.isExtensionUsed(NAME$x); + this._loader = loader; + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadBufferViewAsync(context, bufferView) { + return GLTFLoader.LoadExtensionAsync(context, bufferView, this.name, (extensionContext, extension) => { + const bufferViewMeshopt = bufferView; + if (bufferViewMeshopt._meshOptData) { + return bufferViewMeshopt._meshOptData; + } + const buffer = ArrayItem.Get(`${context}/buffer`, this._loader.gltf.buffers, extension.buffer); + bufferViewMeshopt._meshOptData = this._loader.loadBufferAsync(`/buffers/${buffer.index}`, buffer, extension.byteOffset || 0, extension.byteLength).then((buffer) => { + return MeshoptCompression.Default.decodeGltfBufferAsync(buffer, extension.count, extension.byteStride, extension.mode, extension.filter); + }); + return bufferViewMeshopt._meshOptData; + }); + } +} +unregisterGLTFExtension(NAME$x); +registerGLTFExtension(NAME$x, true, (loader) => new EXT_meshopt_compression(loader)); + +const NAME$w = "EXT_texture_webp"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_texture_webp/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class EXT_texture_webp { + /** + * @internal + */ + constructor(loader) { + /** The name of this extension. */ + this.name = NAME$w; + this._loader = loader; + this.enabled = loader.isExtensionUsed(NAME$w); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + _loadTextureAsync(context, texture, assign) { + return GLTFLoader.LoadExtensionAsync(context, texture, this.name, (extensionContext, extension) => { + const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._loader.gltf.samplers, texture.sampler); + const image = ArrayItem.Get(`${extensionContext}/source`, this._loader.gltf.images, extension.source); + return this._loader._createTextureAsync(context, sampler, image, (babylonTexture) => { + assign(babylonTexture); + }, undefined, !texture._textureInfo.nonColorData); + }); + } +} +unregisterGLTFExtension(NAME$w); +registerGLTFExtension(NAME$w, true, (loader) => new EXT_texture_webp(loader)); + +const NAME$v = "EXT_texture_avif"; +/** + * [glTF PR](https://github.com/KhronosGroup/glTF/pull/2235) + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_texture_avif/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class EXT_texture_avif { + /** + * @internal + */ + constructor(loader) { + /** The name of this extension. */ + this.name = NAME$v; + this._loader = loader; + this.enabled = loader.isExtensionUsed(NAME$v); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + _loadTextureAsync(context, texture, assign) { + return GLTFLoader.LoadExtensionAsync(context, texture, this.name, (extensionContext, extension) => { + const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._loader.gltf.samplers, texture.sampler); + const image = ArrayItem.Get(`${extensionContext}/source`, this._loader.gltf.images, extension.source); + return this._loader._createTextureAsync(context, sampler, image, (babylonTexture) => { + assign(babylonTexture); + }, undefined, !texture._textureInfo.nonColorData); + }); + } +} +unregisterGLTFExtension(NAME$v); +registerGLTFExtension(NAME$v, true, (loader) => new EXT_texture_avif(loader)); + +const NAME$u = "EXT_lights_ies"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Vendor/EXT_lights_ies) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class EXT_lights_ies { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$u; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$u); + } + /** @internal */ + dispose() { + this._loader = null; + delete this._lights; + } + /** @internal */ + onLoading() { + const extensions = this._loader.gltf.extensions; + if (extensions && extensions[this.name]) { + const extension = extensions[this.name]; + this._lights = extension.lights; + ArrayItem.Assign(this._lights); + } + } + /** + * @internal + */ + loadNodeAsync(context, node, assign) { + return GLTFLoader.LoadExtensionAsync(context, node, this.name, async (extensionContext, extension) => { + this._loader._allMaterialsDirtyRequired = true; + let babylonSpotLight; + let light; + const transformNode = await this._loader.loadNodeAsync(context, node, (babylonMesh) => { + light = ArrayItem.Get(extensionContext, this._lights, extension.light); + const name = light.name || babylonMesh.name; + this._loader.babylonScene._blockEntityCollection = !!this._loader._assetContainer; + babylonSpotLight = new SpotLight(name, Vector3.Zero(), Vector3.Backward(), 0, 1, this._loader.babylonScene); + babylonSpotLight.angle = Math.PI / 2; + babylonSpotLight.innerAngle = 0; + babylonSpotLight._parentContainer = this._loader._assetContainer; + this._loader.babylonScene._blockEntityCollection = false; + light._babylonLight = babylonSpotLight; + babylonSpotLight.falloffType = Light.FALLOFF_GLTF; + babylonSpotLight.diffuse = extension.color ? Color3.FromArray(extension.color) : Color3.White(); + babylonSpotLight.intensity = extension.multiplier || 1; + babylonSpotLight.range = Number.MAX_VALUE; + babylonSpotLight.parent = babylonMesh; + this._loader._babylonLights.push(babylonSpotLight); + GLTFLoader.AddPointerMetadata(babylonSpotLight, extensionContext); + assign(babylonMesh); + }); + // Load the profile + let bufferData; + if (light.uri) { + bufferData = await this._loader.loadUriAsync(context, light, light.uri); + } + else { + const bufferView = ArrayItem.Get(`${context}/bufferView`, this._loader.gltf.bufferViews, light.bufferView); + bufferData = await this._loader.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView); + } + babylonSpotLight.iesProfileTexture = new Texture(name + "_iesProfile", this._loader.babylonScene, true, false, undefined, null, null, bufferData, true, undefined, undefined, undefined, undefined, ".ies"); + return transformNode; + }); + } +} +unregisterGLTFExtension(NAME$u); +registerGLTFExtension(NAME$u, true, (loader) => new EXT_lights_ies(loader)); + +/** + * Helper class to push actions to a pool of workers. + */ +class WorkerPool { + /** + * Constructor + * @param workers Array of workers to use for actions + */ + constructor(workers) { + this._pendingActions = new Array(); + this._workerInfos = workers.map((worker) => ({ + workerPromise: Promise.resolve(worker), + idle: true, + })); + } + /** + * Terminates all workers and clears any pending actions. + */ + dispose() { + for (const workerInfo of this._workerInfos) { + workerInfo.workerPromise.then((worker) => { + worker.terminate(); + }); + } + this._workerInfos.length = 0; + this._pendingActions.length = 0; + } + /** + * Pushes an action to the worker pool. If all the workers are active, the action will be + * pended until a worker has completed its action. + * @param action The action to perform. Call onComplete when the action is complete. + */ + push(action) { + if (!this._executeOnIdleWorker(action)) { + this._pendingActions.push(action); + } + } + _executeOnIdleWorker(action) { + for (const workerInfo of this._workerInfos) { + if (workerInfo.idle) { + this._execute(workerInfo, action); + return true; + } + } + return false; + } + _execute(workerInfo, action) { + workerInfo.idle = false; + workerInfo.workerPromise.then((worker) => { + action(worker, () => { + const nextAction = this._pendingActions.shift(); + if (nextAction) { + this._execute(workerInfo, nextAction); + } + else { + workerInfo.idle = true; + } + }); + }); + } +} +/** + * Similar to the WorkerPool class except it creates and destroys workers automatically with a maximum of `maxWorkers` workers. + * Workers are terminated when it is idle for at least `idleTimeElapsedBeforeRelease` milliseconds. + */ +class AutoReleaseWorkerPool extends WorkerPool { + constructor(maxWorkers, createWorkerAsync, options = AutoReleaseWorkerPool.DefaultOptions) { + super([]); + this._maxWorkers = maxWorkers; + this._createWorkerAsync = createWorkerAsync; + this._options = options; + } + push(action) { + if (!this._executeOnIdleWorker(action)) { + if (this._workerInfos.length < this._maxWorkers) { + const workerInfo = { + workerPromise: this._createWorkerAsync(), + idle: false, + }; + this._workerInfos.push(workerInfo); + this._execute(workerInfo, action); + } + else { + this._pendingActions.push(action); + } + } + } + _execute(workerInfo, action) { + // Reset the idle timeout. + if (workerInfo.timeoutId) { + clearTimeout(workerInfo.timeoutId); + delete workerInfo.timeoutId; + } + super._execute(workerInfo, (worker, onComplete) => { + action(worker, () => { + onComplete(); + if (workerInfo.idle) { + // Schedule the worker to be terminated after the elapsed time. + workerInfo.timeoutId = setTimeout(() => { + workerInfo.workerPromise.then((worker) => { + worker.terminate(); + }); + const indexOf = this._workerInfos.indexOf(workerInfo); + if (indexOf !== -1) { + this._workerInfos.splice(indexOf, 1); + } + }, this._options.idleTimeElapsedBeforeRelease); + } + }); + }); + } +} +/** + * Default options for the constructor. + * Override to change the defaults. + */ +AutoReleaseWorkerPool.DefaultOptions = { + idleTimeElapsedBeforeRelease: 1000, +}; + +/** + * @internal + */ +function EncodeMesh(module /** EncoderModule */, attributes, indices, options) { + const encoderModule = module; + let encoder = null; + let meshBuilder = null; + let mesh = null; + let encodedNativeBuffer = null; + const attributeIDs = {}; // Babylon kind -> Draco unique id + // Double-check that at least a position attribute is provided + const positionAttribute = attributes.find((a) => a.dracoName === "POSITION"); + if (!positionAttribute) { + throw new Error("Position attribute is required for Draco encoding"); + } + // If no indices are provided, assume mesh is unindexed. Let's generate them, since Draco meshes require them. + // TODO: This may be the POINT_CLOUD case, but need to investigate. Should work for now-- just less efficient. + if (!indices) { + // Assume position attribute is the largest attribute. + const positionVerticesCount = positionAttribute.data.length / positionAttribute.size; + indices = new (positionVerticesCount > 65535 ? Uint32Array : Uint16Array)(positionVerticesCount); + for (let i = 0; i < positionVerticesCount; i++) { + indices[i] = i; + } + } + try { + encoder = new encoderModule.Encoder(); + meshBuilder = new encoderModule.MeshBuilder(); + mesh = new encoderModule.Mesh(); + // Add the faces + meshBuilder.AddFacesToMesh(mesh, indices.length / 3, indices); + const addAttributeMap = new Map([ + [Float32Array, (mb, m, a, c, s, d) => mb.AddFloatAttribute(m, a, c, s, d)], + [Uint32Array, (mb, m, a, c, s, d) => mb.AddUInt32Attribute(m, a, c, s, d)], + [Uint16Array, (mb, m, a, c, s, d) => mb.AddUInt16Attribute(m, a, c, s, d)], + [Uint8Array, (mb, m, a, c, s, d) => mb.AddUInt8Attribute(m, a, c, s, d)], + [Int32Array, (mb, m, a, c, s, d) => mb.AddInt32Attribute(m, a, c, s, d)], + [Int16Array, (mb, m, a, c, s, d) => mb.AddInt16Attribute(m, a, c, s, d)], + [Int8Array, (mb, m, a, c, s, d) => mb.AddInt8Attribute(m, a, c, s, d)], + ]); + // Add the attributes + for (const attribute of attributes) { + if (attribute.data instanceof Uint8ClampedArray) { + attribute.data = new Uint8Array(attribute.data); // Draco does not support Uint8ClampedArray + } + const addAttribute = addAttributeMap.get(attribute.data.constructor); + const verticesCount = attribute.data.length / attribute.size; + attributeIDs[attribute.kind] = addAttribute(meshBuilder, mesh, encoderModule[attribute.dracoName], verticesCount, attribute.size, attribute.data); + if (options.quantizationBits && options.quantizationBits[attribute.dracoName]) { + encoder.SetAttributeQuantization(encoderModule[attribute.dracoName], options.quantizationBits[attribute.dracoName]); + } + } + // Set the options + if (options.method) { + encoder.SetEncodingMethod(encoderModule[options.method]); + } + if (options.encodeSpeed !== undefined && options.decodeSpeed !== undefined) { + encoder.SetSpeedOptions(options.encodeSpeed, options.decodeSpeed); + } + // Encode to native buffer + encodedNativeBuffer = new encoderModule.DracoInt8Array(); + const encodedLength = encoder.EncodeMeshToDracoBuffer(mesh, encodedNativeBuffer); + if (encodedLength <= 0) { + throw new Error("Draco encoding failed."); + } + // Copy the native buffer data to worker heap + const encodedData = new Int8Array(encodedLength); + for (let i = 0; i < encodedLength; i++) { + encodedData[i] = encodedNativeBuffer.GetValue(i); + } + return { data: encodedData, attributeIDs: attributeIDs }; + } + finally { + if (mesh) { + encoderModule.destroy(mesh); + } + if (meshBuilder) { + encoderModule.destroy(meshBuilder); + } + if (encoder) { + encoderModule.destroy(encoder); + } + if (encodedNativeBuffer) { + encoderModule.destroy(encodedNativeBuffer); + } + } +} +/** + * The worker function that gets converted to a blob url to pass into a worker. + * To be used if a developer wants to create their own worker instance and inject it instead of using the default worker. + */ +function EncoderWorkerFunction() { + let encoderPromise; + onmessage = (event) => { + const message = event.data; + switch (message.id) { + case "init": { + // if URL is provided then load the script. Otherwise expect the script to be loaded already + if (message.url) { + importScripts(message.url); + } + const initEncoderObject = message.wasmBinary ? { wasmBinary: message.wasmBinary } : {}; + encoderPromise = DracoEncoderModule(initEncoderObject); + postMessage({ id: "initDone" }); + break; + } + case "encodeMesh": { + if (!encoderPromise) { + throw new Error("Draco encoder module is not available"); + } + encoderPromise.then((encoder) => { + const result = EncodeMesh(encoder, message.attributes, message.indices, message.options); + postMessage({ id: "encodeMeshDone", encodedMeshData: result }, result ? [result.data.buffer] : undefined); + }); + break; + } + } + }; +} +/** + * @internal + */ +function DecodeMesh(module /** DecoderModule */, data, attributeIDs, onIndicesData, onAttributeData) { + const decoderModule = module; + let decoder = null; + let buffer = null; + let geometry = null; + try { + decoder = new decoderModule.Decoder(); + buffer = new decoderModule.DecoderBuffer(); + buffer.Init(data, data.byteLength); + let status; + const type = decoder.GetEncodedGeometryType(buffer); + switch (type) { + case decoderModule.TRIANGULAR_MESH: { + const mesh = new decoderModule.Mesh(); + status = decoder.DecodeBufferToMesh(buffer, mesh); + if (!status.ok() || mesh.ptr === 0) { + throw new Error(status.error_msg()); + } + const numFaces = mesh.num_faces(); + const numIndices = numFaces * 3; + const byteLength = numIndices * 4; + const ptr = decoderModule._malloc(byteLength); + try { + decoder.GetTrianglesUInt32Array(mesh, byteLength, ptr); + const indices = new Uint32Array(numIndices); + indices.set(new Uint32Array(decoderModule.HEAPF32.buffer, ptr, numIndices)); + onIndicesData(indices); + } + finally { + decoderModule._free(ptr); + } + geometry = mesh; + break; + } + case decoderModule.POINT_CLOUD: { + const pointCloud = new decoderModule.PointCloud(); + status = decoder.DecodeBufferToPointCloud(buffer, pointCloud); + if (!status.ok() || !pointCloud.ptr) { + throw new Error(status.error_msg()); + } + geometry = pointCloud; + break; + } + default: { + throw new Error(`Invalid geometry type ${type}`); + } + } + const numPoints = geometry.num_points(); + const processAttribute = (decoder, geometry, kind, attribute /** Attribute */) => { + const dataType = attribute.data_type(); + const numComponents = attribute.num_components(); + const normalized = attribute.normalized(); + const byteStride = attribute.byte_stride(); + const byteOffset = attribute.byte_offset(); + const dataTypeInfo = { + [decoderModule.DT_FLOAT32]: { typedArrayConstructor: Float32Array, heap: decoderModule.HEAPF32 }, + [decoderModule.DT_INT8]: { typedArrayConstructor: Int8Array, heap: decoderModule.HEAP8 }, + [decoderModule.DT_INT16]: { typedArrayConstructor: Int16Array, heap: decoderModule.HEAP16 }, + [decoderModule.DT_INT32]: { typedArrayConstructor: Int32Array, heap: decoderModule.HEAP32 }, + [decoderModule.DT_UINT8]: { typedArrayConstructor: Uint8Array, heap: decoderModule.HEAPU8 }, + [decoderModule.DT_UINT16]: { typedArrayConstructor: Uint16Array, heap: decoderModule.HEAPU16 }, + [decoderModule.DT_UINT32]: { typedArrayConstructor: Uint32Array, heap: decoderModule.HEAPU32 }, + }; + const info = dataTypeInfo[dataType]; + if (!info) { + throw new Error(`Invalid data type ${dataType}`); + } + const numValues = numPoints * numComponents; + const byteLength = numValues * info.typedArrayConstructor.BYTES_PER_ELEMENT; + const ptr = decoderModule._malloc(byteLength); + try { + decoder.GetAttributeDataArrayForAllPoints(geometry, attribute, dataType, byteLength, ptr); + const data = new info.typedArrayConstructor(info.heap.buffer, ptr, numValues); + onAttributeData(kind, data.slice(), numComponents, byteOffset, byteStride, normalized); + } + finally { + decoderModule._free(ptr); + } + }; + if (attributeIDs) { + for (const kind in attributeIDs) { + const id = attributeIDs[kind]; + const attribute = decoder.GetAttributeByUniqueId(geometry, id); + processAttribute(decoder, geometry, kind, attribute); + } + } + else { + const dracoAttributeTypes = { + position: decoderModule.POSITION, + normal: decoderModule.NORMAL, + color: decoderModule.COLOR, + uv: decoderModule.TEX_COORD, + }; + for (const kind in dracoAttributeTypes) { + const id = decoder.GetAttributeId(geometry, dracoAttributeTypes[kind]); + if (id !== -1) { + const attribute = decoder.GetAttribute(geometry, id); + processAttribute(decoder, geometry, kind, attribute); + } + } + } + return numPoints; + } + finally { + if (geometry) { + decoderModule.destroy(geometry); + } + if (buffer) { + decoderModule.destroy(buffer); + } + if (decoder) { + decoderModule.destroy(decoder); + } + } +} +/** + * The worker function that gets converted to a blob url to pass into a worker. + * To be used if a developer wants to create their own worker instance and inject it instead of using the default worker. + */ +function DecoderWorkerFunction() { + let decoderPromise; + onmessage = (event) => { + const message = event.data; + switch (message.id) { + case "init": { + // if URL is provided then load the script. Otherwise expect the script to be loaded already + if (message.url) { + importScripts(message.url); + } + const initDecoderObject = message.wasmBinary ? { wasmBinary: message.wasmBinary } : {}; + decoderPromise = DracoDecoderModule(initDecoderObject); + postMessage({ id: "initDone" }); + break; + } + case "decodeMesh": { + if (!decoderPromise) { + throw new Error("Draco decoder module is not available"); + } + decoderPromise.then((decoder) => { + const numPoints = DecodeMesh(decoder, message.dataView, message.attributes, (indices) => { + postMessage({ id: "indices", data: indices }, [indices.buffer]); + }, (kind, data, size, offset, stride, normalized) => { + postMessage({ id: "attribute", kind, data, size, byteOffset: offset, byteStride: stride, normalized }, [data.buffer]); + }); + postMessage({ id: "decodeMeshDone", totalVertices: numPoints }); + }); + break; + } + } + }; +} +/** + * Initializes a worker that was created for the draco agent pool + * @param worker The worker to initialize + * @param wasmBinary The wasm binary to load into the worker + * @param moduleUrl The url to the draco decoder module (optional) + * @returns A promise that resolves when the worker is initialized + */ +function initializeWebWorker$2(worker, wasmBinary, moduleUrl) { + return new Promise((resolve, reject) => { + const onError = (error) => { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + reject(error); + }; + const onMessage = (event) => { + if (event.data.id === "initDone") { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + resolve(worker); + } + }; + worker.addEventListener("error", onError); + worker.addEventListener("message", onMessage); + // Load with either JS-only or WASM version + if (!wasmBinary) { + worker.postMessage({ + id: "init", + url: moduleUrl, + }); + } + else { + // clone the array buffer to make it transferable + const clone = wasmBinary.slice(0); + worker.postMessage({ + id: "init", + url: moduleUrl, + wasmBinary: clone, + }, [clone]); + } + // note: no transfer list as the ArrayBuffer is shared across main thread and pool workers + }); +} + +/** + * @internal + */ +function _GetDefaultNumWorkers() { + if (typeof navigator !== "object" || !navigator.hardwareConcurrency) { + return 1; + } + // Use 50% of the available logical processors but capped at 4. + return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4); +} +/** + * @internal + */ +function _IsConfigurationAvailable(config) { + return !!((config.wasmUrl && (config.wasmBinary || config.wasmBinaryUrl) && typeof WebAssembly === "object") || config.fallbackUrl); + // TODO: Account for jsModule +} +/** + * Base class for a Draco codec. + * @internal + */ +class DracoCodec { + /** + * Constructor + * @param configuration The configuration for the DracoCodec instance. + */ + constructor(configuration) { + // check if the codec binary and worker pool was injected + // Note - it is expected that the developer checked if WebWorker, WebAssembly and the URL object are available + if (configuration.workerPool) { + // Set the promise accordingly + this._workerPoolPromise = Promise.resolve(configuration.workerPool); + return; + } + // to avoid making big changes to the code here, if wasmBinary is provided use it in the wasmBinaryPromise + const wasmBinaryProvided = configuration.wasmBinary; + const numberOfWorkers = configuration.numWorkers ?? _GetDefaultNumWorkers(); + const useWorkers = numberOfWorkers && typeof Worker === "function" && typeof URL === "function"; + const urlNeeded = useWorkers || !configuration.jsModule; + // code maintained here for back-compat with no changes + const codecInfo = configuration.wasmUrl && configuration.wasmBinaryUrl && typeof WebAssembly === "object" + ? { + url: urlNeeded ? Tools.GetBabylonScriptURL(configuration.wasmUrl, true) : "", + wasmBinaryPromise: wasmBinaryProvided + ? Promise.resolve(wasmBinaryProvided) + : Tools.LoadFileAsync(Tools.GetBabylonScriptURL(configuration.wasmBinaryUrl, true)), + } + : { + url: urlNeeded ? Tools.GetBabylonScriptURL(configuration.fallbackUrl) : "", + wasmBinaryPromise: Promise.resolve(undefined), + }; + // If using workers, initialize a worker pool with either the wasm or url? + if (useWorkers) { + this._workerPoolPromise = codecInfo.wasmBinaryPromise.then((wasmBinary) => { + const workerContent = this._getWorkerContent(); + const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" })); + return new AutoReleaseWorkerPool(numberOfWorkers, () => { + const worker = new Worker(workerBlobUrl); + return initializeWebWorker$2(worker, wasmBinary, codecInfo.url); + }); + }); + } + else { + this._modulePromise = codecInfo.wasmBinaryPromise.then(async (wasmBinary) => { + if (!this._isModuleAvailable()) { + if (!configuration.jsModule) { + if (!codecInfo.url) { + throw new Error("Draco codec module is not available"); + } + await Tools.LoadBabylonScriptAsync(codecInfo.url); + } + } + return this._createModuleAsync(wasmBinary, configuration.jsModule); + }); + } + } + /** + * Returns a promise that resolves when ready. Call this manually to ensure the draco codec is ready before use. + * @returns a promise that resolves when ready + */ + async whenReadyAsync() { + if (this._workerPoolPromise) { + await this._workerPoolPromise; + return; + } + if (this._modulePromise) { + await this._modulePromise; + return; + } + } + /** + * Stop all async operations and release resources. + */ + dispose() { + if (this._workerPoolPromise) { + this._workerPoolPromise.then((workerPool) => { + workerPool.dispose(); + }); + } + delete this._workerPoolPromise; + delete this._modulePromise; + } +} + +/** + * @experimental This class is an experimental version of `DracoCompression` and is subject to change. + * + * Draco Decoder (https://google.github.io/draco/) + * + * This class wraps the Draco decoder module. + * + * By default, the configuration points to a copy of the Draco decoder files for glTF from the Babylon.js cdn https://cdn.babylonjs.com/draco_wasm_wrapper_gltf.js. + * + * To update the configuration, use the following code: + * ```javascript + * DracoDecoder.DefaultConfiguration = { + * wasmUrl: "", + * wasmBinaryUrl: "", + * fallbackUrl: "", + * }; + * ``` + * + * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support WebAssembly or only support the JavaScript version. + * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser. + * Use `DracoDecoder.DefaultAvailable` to determine if the decoder configuration is available for the current context. + * + * To decode Draco compressed data, get the default DracoDecoder object and call decodeMeshToGeometryAsync: + * ```javascript + * var geometry = await DracoDecoder.Default.decodeMeshToGeometryAsync(data); + * ``` + */ +class DracoDecoder extends DracoCodec { + /** + * Returns true if the decoder's `DefaultConfiguration` is available. + */ + static get DefaultAvailable() { + return _IsConfigurationAvailable(DracoDecoder.DefaultConfiguration); + } + /** + * Default instance for the DracoDecoder. + */ + static get Default() { + DracoDecoder._Default ?? (DracoDecoder._Default = new DracoDecoder()); + return DracoDecoder._Default; + } + /** + * Reset the default DracoDecoder object to null and disposing the removed default instance. + * Note that if the workerPool is a member of the static DefaultConfiguration object it is recommended not to run dispose, + * unless the static worker pool is no longer needed. + * @param skipDispose set to true to not dispose the removed default instance + */ + static ResetDefault(skipDispose) { + if (DracoDecoder._Default) { + if (!skipDispose) { + DracoDecoder._Default.dispose(); + } + DracoDecoder._Default = null; + } + } + _isModuleAvailable() { + return typeof DracoDecoderModule !== "undefined"; + } + async _createModuleAsync(wasmBinary, jsModule /** DracoDecoderModule */) { + const module = await (jsModule || DracoDecoderModule)({ wasmBinary }); + return { module }; + } + _getWorkerContent() { + return `${DecodeMesh}(${DecoderWorkerFunction})()`; + } + /** + * Creates a new Draco decoder. + * @param configuration Optional override of the configuration for the DracoDecoder. If not provided, defaults to {@link DracoDecoder.DefaultConfiguration}. + */ + constructor(configuration = DracoDecoder.DefaultConfiguration) { + super(configuration); + } + /** + * Decode Draco compressed mesh data to mesh data. + * @param data The ArrayBuffer or ArrayBufferView of the compressed Draco data + * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids + * @param gltfNormalizedOverride A map of attributes from vertex buffer kinds to normalized flags to override the Draco normalization + * @returns A promise that resolves with the decoded mesh data + */ + decodeMeshToMeshDataAsync(data, attributes, gltfNormalizedOverride) { + const dataView = data instanceof ArrayBuffer ? new Int8Array(data) : new Int8Array(data.buffer, data.byteOffset, data.byteLength); + const applyGltfNormalizedOverride = (kind, normalized) => { + if (gltfNormalizedOverride && gltfNormalizedOverride[kind] !== undefined) { + if (normalized !== gltfNormalizedOverride[kind]) { + Logger.Warn(`Normalized flag from Draco data (${normalized}) does not match normalized flag from glTF accessor (${gltfNormalizedOverride[kind]}). Using flag from glTF accessor.`); + } + return gltfNormalizedOverride[kind]; + } + else { + return normalized; + } + }; + if (this._workerPoolPromise) { + return this._workerPoolPromise.then((workerPool) => { + return new Promise((resolve, reject) => { + workerPool.push((worker, onComplete) => { + let resultIndices = null; + const resultAttributes = []; + const onError = (error) => { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + reject(error); + onComplete(); + }; + const onMessage = (event) => { + const message = event.data; + switch (message.id) { + case "indices": { + resultIndices = message.data; + break; + } + case "attribute": { + resultAttributes.push({ + kind: message.kind, + data: message.data, + size: message.size, + byteOffset: message.byteOffset, + byteStride: message.byteStride, + normalized: applyGltfNormalizedOverride(message.kind, message.normalized), + }); + break; + } + case "decodeMeshDone": { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + resolve({ indices: resultIndices, attributes: resultAttributes, totalVertices: message.totalVertices }); + onComplete(); + break; + } + } + }; + worker.addEventListener("error", onError); + worker.addEventListener("message", onMessage); + const dataViewCopy = dataView.slice(); + worker.postMessage({ id: "decodeMesh", dataView: dataViewCopy, attributes: attributes }, [dataViewCopy.buffer]); + }); + }); + }); + } + if (this._modulePromise) { + return this._modulePromise.then((decoder) => { + let resultIndices = null; + const resultAttributes = []; + const numPoints = DecodeMesh(decoder.module, dataView, attributes, (indices) => { + resultIndices = indices; + }, (kind, data, size, byteOffset, byteStride, normalized) => { + resultAttributes.push({ + kind, + data, + size, + byteOffset, + byteStride, + normalized, + }); + }); + return { indices: resultIndices, attributes: resultAttributes, totalVertices: numPoints }; + }); + } + throw new Error("Draco decoder module is not available"); + } + /** + * Decode Draco compressed mesh data to Babylon geometry. + * @param name The name to use when creating the geometry + * @param scene The scene to use when creating the geometry + * @param data The ArrayBuffer or ArrayBufferView of the Draco compressed data + * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids + * @returns A promise that resolves with the decoded geometry + */ + async decodeMeshToGeometryAsync(name, scene, data, attributes) { + const meshData = await this.decodeMeshToMeshDataAsync(data, attributes); + const geometry = new Geometry(name, scene); + if (meshData.indices) { + geometry.setIndices(meshData.indices); + } + for (const attribute of meshData.attributes) { + geometry.setVerticesBuffer(new VertexBuffer(scene.getEngine(), attribute.data, attribute.kind, false, undefined, attribute.byteStride, undefined, attribute.byteOffset, attribute.size, undefined, attribute.normalized, true), meshData.totalVertices); + } + return geometry; + } + /** @internal */ + async _decodeMeshToGeometryForGltfAsync(name, scene, data, attributes, gltfNormalizedOverride, boundingInfo) { + const meshData = await this.decodeMeshToMeshDataAsync(data, attributes, gltfNormalizedOverride); + const geometry = new Geometry(name, scene); + if (boundingInfo) { + geometry._boundingInfo = boundingInfo; + geometry.useBoundingInfoFromGeometry = true; + } + if (meshData.indices) { + geometry.setIndices(meshData.indices); + } + for (const attribute of meshData.attributes) { + geometry.setVerticesBuffer(new VertexBuffer(scene.getEngine(), attribute.data, attribute.kind, false, undefined, attribute.byteStride, undefined, attribute.byteOffset, attribute.size, undefined, attribute.normalized, true), meshData.totalVertices); + } + return geometry; + } +} +/** + * Default configuration for the DracoDecoder. Defaults to the following: + * - numWorkers: 50% of the available logical processors, capped to 4. If no logical processors are available, defaults to 1. + * - wasmUrl: `"https://cdn.babylonjs.com/draco_wasm_wrapper_gltf.js"` + * - wasmBinaryUrl: `"https://cdn.babylonjs.com/draco_decoder_gltf.wasm"` + * - fallbackUrl: `"https://cdn.babylonjs.com/draco_decoder_gltf.js"` + */ +DracoDecoder.DefaultConfiguration = { + wasmUrl: `${Tools._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`, + wasmBinaryUrl: `${Tools._DefaultCdnUrl}/draco_decoder_gltf.wasm`, + fallbackUrl: `${Tools._DefaultCdnUrl}/draco_decoder_gltf.js`, +}; +DracoDecoder._Default = null; + +const NAME$t = "KHR_draco_mesh_compression"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_draco_mesh_compression/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_draco_mesh_compression { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$t; + /** + * Defines whether to use the normalized flag from the glTF accessor instead of the Draco data. Defaults to true. + */ + this.useNormalizedFlagFromAccessor = true; + this._loader = loader; + this.enabled = DracoDecoder.DefaultAvailable && this._loader.isExtensionUsed(NAME$t); + } + /** @internal */ + dispose() { + delete this.dracoDecoder; + this._loader = null; + } + /** + * @internal + */ + _loadVertexDataAsync(context, primitive, babylonMesh) { + return GLTFLoader.LoadExtensionAsync(context, primitive, this.name, (extensionContext, extension) => { + if (primitive.mode != undefined) { + if (primitive.mode !== 4 /* MeshPrimitiveMode.TRIANGLES */ && primitive.mode !== 5 /* MeshPrimitiveMode.TRIANGLE_STRIP */) { + throw new Error(`${context}: Unsupported mode ${primitive.mode}`); + } + } + const attributes = {}; + const normalized = {}; + const loadAttribute = (name, kind) => { + const uniqueId = extension.attributes[name]; + if (uniqueId == undefined) { + return; + } + babylonMesh._delayInfo = babylonMesh._delayInfo || []; + if (babylonMesh._delayInfo.indexOf(kind) === -1) { + babylonMesh._delayInfo.push(kind); + } + attributes[kind] = uniqueId; + if (this.useNormalizedFlagFromAccessor) { + const accessor = ArrayItem.TryGet(this._loader.gltf.accessors, primitive.attributes[name]); + if (accessor) { + normalized[kind] = accessor.normalized || false; + } + } + }; + loadAttribute("POSITION", VertexBuffer.PositionKind); + loadAttribute("NORMAL", VertexBuffer.NormalKind); + loadAttribute("TANGENT", VertexBuffer.TangentKind); + loadAttribute("TEXCOORD_0", VertexBuffer.UVKind); + loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind); + loadAttribute("TEXCOORD_2", VertexBuffer.UV3Kind); + loadAttribute("TEXCOORD_3", VertexBuffer.UV4Kind); + loadAttribute("TEXCOORD_4", VertexBuffer.UV5Kind); + loadAttribute("TEXCOORD_5", VertexBuffer.UV6Kind); + loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind); + loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind); + loadAttribute("COLOR_0", VertexBuffer.ColorKind); + const bufferView = ArrayItem.Get(extensionContext, this._loader.gltf.bufferViews, extension.bufferView); + if (!bufferView._dracoBabylonGeometry) { + bufferView._dracoBabylonGeometry = this._loader.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => { + const dracoDecoder = this.dracoDecoder || DracoDecoder.Default; + const positionAccessor = ArrayItem.TryGet(this._loader.gltf.accessors, primitive.attributes["POSITION"]); + const babylonBoundingInfo = !this._loader.parent.alwaysComputeBoundingBox && !babylonMesh.skeleton && positionAccessor ? LoadBoundingInfoFromPositionAccessor(positionAccessor) : null; + return dracoDecoder + ._decodeMeshToGeometryForGltfAsync(babylonMesh.name, this._loader.babylonScene, data, attributes, normalized, babylonBoundingInfo) + .catch((error) => { + throw new Error(`${context}: ${error.message}`); + }); + }); + } + return bufferView._dracoBabylonGeometry; + }); + } +} +unregisterGLTFExtension(NAME$t); +registerGLTFExtension(NAME$t, true, (loader) => new KHR_draco_mesh_compression(loader)); + +const NAME$s = "KHR_lights_punctual"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_lights_punctual/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_lights { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$s; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$s); + } + /** @internal */ + dispose() { + this._loader = null; + delete this._lights; + } + /** @internal */ + onLoading() { + const extensions = this._loader.gltf.extensions; + if (extensions && extensions[this.name]) { + const extension = extensions[this.name]; + this._lights = extension.lights; + ArrayItem.Assign(this._lights); + } + } + /** + * @internal + */ + loadNodeAsync(context, node, assign) { + return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => { + this._loader._allMaterialsDirtyRequired = true; + return this._loader.loadNodeAsync(context, node, (babylonMesh) => { + let babylonLight; + const light = ArrayItem.Get(extensionContext, this._lights, extension.light); + const name = light.name || babylonMesh.name; + this._loader.babylonScene._blockEntityCollection = !!this._loader._assetContainer; + switch (light.type) { + case "directional" /* KHRLightsPunctual_LightType.DIRECTIONAL */: { + const babylonDirectionalLight = new DirectionalLight(name, Vector3.Backward(), this._loader.babylonScene); + babylonDirectionalLight.position.setAll(0); + babylonLight = babylonDirectionalLight; + break; + } + case "point" /* KHRLightsPunctual_LightType.POINT */: { + babylonLight = new PointLight(name, Vector3.Zero(), this._loader.babylonScene); + break; + } + case "spot" /* KHRLightsPunctual_LightType.SPOT */: { + const babylonSpotLight = new SpotLight(name, Vector3.Zero(), Vector3.Backward(), 0, 1, this._loader.babylonScene); + babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2; + babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2; + babylonLight = babylonSpotLight; + break; + } + default: { + this._loader.babylonScene._blockEntityCollection = false; + throw new Error(`${extensionContext}: Invalid light type (${light.type})`); + } + } + babylonLight._parentContainer = this._loader._assetContainer; + this._loader.babylonScene._blockEntityCollection = false; + light._babylonLight = babylonLight; + babylonLight.falloffType = Light.FALLOFF_GLTF; + babylonLight.diffuse = light.color ? Color3.FromArray(light.color) : Color3.White(); + babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity; + babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range; + babylonLight.parent = babylonMesh; + this._loader._babylonLights.push(babylonLight); + GLTFLoader.AddPointerMetadata(babylonLight, extensionContext); + assign(babylonMesh); + }); + }); + } +} +unregisterGLTFExtension(NAME$s); +registerGLTFExtension(NAME$s, true, (loader) => new KHR_lights(loader)); + +const NAME$r = "KHR_materials_pbrSpecularGlossiness"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_pbrSpecularGlossiness { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$r; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 200; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$r); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadSpecularGlossinessPropertiesAsync(extensionContext, extension, babylonMaterial)); + this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial); + return Promise.all(promises).then(() => { }); + }); + } + _loadSpecularGlossinessPropertiesAsync(context, properties, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const promises = new Array(); + babylonMaterial.metallic = null; + babylonMaterial.roughness = null; + if (properties.diffuseFactor) { + babylonMaterial.albedoColor = Color3.FromArray(properties.diffuseFactor); + babylonMaterial.alpha = properties.diffuseFactor[3]; + } + else { + babylonMaterial.albedoColor = Color3.White(); + } + babylonMaterial.reflectivityColor = properties.specularFactor ? Color3.FromArray(properties.specularFactor) : Color3.White(); + babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor; + if (properties.diffuseTexture) { + promises.push(this._loader.loadTextureInfoAsync(`${context}/diffuseTexture`, properties.diffuseTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Diffuse)`; + babylonMaterial.albedoTexture = texture; + })); + } + if (properties.specularGlossinessTexture) { + promises.push(this._loader.loadTextureInfoAsync(`${context}/specularGlossinessTexture`, properties.specularGlossinessTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Specular Glossiness)`; + babylonMaterial.reflectivityTexture = texture; + babylonMaterial.reflectivityTexture.hasAlpha = true; + })); + babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true; + } + return Promise.all(promises).then(() => { }); + } +} +unregisterGLTFExtension(NAME$r); +registerGLTFExtension(NAME$r, true, (loader) => new KHR_materials_pbrSpecularGlossiness(loader)); + +const NAME$q = "KHR_materials_unlit"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_unlit/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_unlit { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$q; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 210; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$q); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, () => { + return this._loadUnlitPropertiesAsync(context, material, babylonMaterial); + }); + } + _loadUnlitPropertiesAsync(context, material, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const promises = new Array(); + babylonMaterial.unlit = true; + const properties = material.pbrMetallicRoughness; + if (properties) { + if (properties.baseColorFactor) { + babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor); + babylonMaterial.alpha = properties.baseColorFactor[3]; + } + else { + babylonMaterial.albedoColor = Color3.White(); + } + if (properties.baseColorTexture) { + promises.push(this._loader.loadTextureInfoAsync(`${context}/baseColorTexture`, properties.baseColorTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Base Color)`; + babylonMaterial.albedoTexture = texture; + })); + } + } + if (material.doubleSided) { + babylonMaterial.backFaceCulling = false; + babylonMaterial.twoSidedLighting = true; + } + this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial); + return Promise.all(promises).then(() => { }); + } +} +unregisterGLTFExtension(NAME$q); +registerGLTFExtension(NAME$q, true, (loader) => new KHR_materials_unlit(loader)); + +const NAME$p = "KHR_materials_clearcoat"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_clearcoat/README.md) + * [Playground Sample](https://www.babylonjs-playground.com/frame.html#7F7PN6#8) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_clearcoat { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$p; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 190; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$p); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadClearCoatPropertiesAsync(extensionContext, extension, babylonMaterial)); + return Promise.all(promises).then(() => { }); + }); + } + _loadClearCoatPropertiesAsync(context, properties, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const promises = new Array(); + babylonMaterial.clearCoat.isEnabled = true; + babylonMaterial.clearCoat.useRoughnessFromMainTexture = false; + babylonMaterial.clearCoat.remapF0OnInterfaceChange = false; + if (properties.clearcoatFactor != undefined) { + babylonMaterial.clearCoat.intensity = properties.clearcoatFactor; + } + else { + babylonMaterial.clearCoat.intensity = 0; + } + if (properties.clearcoatTexture) { + promises.push(this._loader.loadTextureInfoAsync(`${context}/clearcoatTexture`, properties.clearcoatTexture, (texture) => { + texture.name = `${babylonMaterial.name} (ClearCoat)`; + babylonMaterial.clearCoat.texture = texture; + })); + } + if (properties.clearcoatRoughnessFactor != undefined) { + babylonMaterial.clearCoat.roughness = properties.clearcoatRoughnessFactor; + } + else { + babylonMaterial.clearCoat.roughness = 0; + } + if (properties.clearcoatRoughnessTexture) { + properties.clearcoatRoughnessTexture.nonColorData = true; + promises.push(this._loader.loadTextureInfoAsync(`${context}/clearcoatRoughnessTexture`, properties.clearcoatRoughnessTexture, (texture) => { + texture.name = `${babylonMaterial.name} (ClearCoat Roughness)`; + babylonMaterial.clearCoat.textureRoughness = texture; + })); + } + if (properties.clearcoatNormalTexture) { + properties.clearcoatNormalTexture.nonColorData = true; + promises.push(this._loader.loadTextureInfoAsync(`${context}/clearcoatNormalTexture`, properties.clearcoatNormalTexture, (texture) => { + texture.name = `${babylonMaterial.name} (ClearCoat Normal)`; + babylonMaterial.clearCoat.bumpTexture = texture; + })); + babylonMaterial.invertNormalMapX = !babylonMaterial.getScene().useRightHandedSystem; + babylonMaterial.invertNormalMapY = babylonMaterial.getScene().useRightHandedSystem; + if (properties.clearcoatNormalTexture.scale != undefined) { + babylonMaterial.clearCoat.bumpTexture.level = properties.clearcoatNormalTexture.scale; + } + } + return Promise.all(promises).then(() => { }); + } +} +unregisterGLTFExtension(NAME$p); +registerGLTFExtension(NAME$p, true, (loader) => new KHR_materials_clearcoat(loader)); + +const NAME$o = "KHR_materials_iridescence"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_iridescence/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_iridescence { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$o; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 195; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$o); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadIridescencePropertiesAsync(extensionContext, extension, babylonMaterial)); + return Promise.all(promises).then(() => { }); + }); + } + _loadIridescencePropertiesAsync(context, properties, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const promises = new Array(); + babylonMaterial.iridescence.isEnabled = true; + babylonMaterial.iridescence.intensity = properties.iridescenceFactor ?? 0; + babylonMaterial.iridescence.indexOfRefraction = properties.iridescenceIor ?? properties.iridescenceIOR ?? 1.3; + babylonMaterial.iridescence.minimumThickness = properties.iridescenceThicknessMinimum ?? 100; + babylonMaterial.iridescence.maximumThickness = properties.iridescenceThicknessMaximum ?? 400; + if (properties.iridescenceTexture) { + promises.push(this._loader.loadTextureInfoAsync(`${context}/iridescenceTexture`, properties.iridescenceTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Iridescence)`; + babylonMaterial.iridescence.texture = texture; + })); + } + if (properties.iridescenceThicknessTexture) { + promises.push(this._loader.loadTextureInfoAsync(`${context}/iridescenceThicknessTexture`, properties.iridescenceThicknessTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Iridescence Thickness)`; + babylonMaterial.iridescence.thicknessTexture = texture; + })); + } + return Promise.all(promises).then(() => { }); + } +} +unregisterGLTFExtension(NAME$o); +registerGLTFExtension(NAME$o, true, (loader) => new KHR_materials_iridescence(loader)); + +const NAME$n = "KHR_materials_anisotropy"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_anisotropy) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_anisotropy { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$n; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 195; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$n); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadIridescencePropertiesAsync(extensionContext, extension, babylonMaterial)); + return Promise.all(promises).then(() => { }); + }); + } + _loadIridescencePropertiesAsync(context, properties, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const promises = new Array(); + babylonMaterial.anisotropy.isEnabled = true; + babylonMaterial.anisotropy.intensity = properties.anisotropyStrength ?? 0; + babylonMaterial.anisotropy.angle = properties.anisotropyRotation ?? 0; + if (properties.anisotropyTexture) { + properties.anisotropyTexture.nonColorData = true; + promises.push(this._loader.loadTextureInfoAsync(`${context}/anisotropyTexture`, properties.anisotropyTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Anisotropy Intensity)`; + babylonMaterial.anisotropy.texture = texture; + })); + } + return Promise.all(promises).then(() => { }); + } +} +unregisterGLTFExtension(NAME$n); +registerGLTFExtension(NAME$n, true, (loader) => new KHR_materials_anisotropy(loader)); + +const NAME$m = "KHR_materials_emissive_strength"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_emissive_strength { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$m; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 170; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$m); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + return this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial).then(() => { + this._loadEmissiveProperties(extensionContext, extension, babylonMaterial); + }); + }); + } + _loadEmissiveProperties(context, properties, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + if (properties.emissiveStrength !== undefined) { + babylonMaterial.emissiveIntensity = properties.emissiveStrength; + } + } +} +unregisterGLTFExtension(NAME$m); +registerGLTFExtension(NAME$m, true, (loader) => new KHR_materials_emissive_strength(loader)); + +const NAME$l = "KHR_materials_sheen"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_sheen/README.md) + * [Playground Sample](https://www.babylonjs-playground.com/frame.html#BNIZX6#4) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_sheen { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$l; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 190; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$l); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadSheenPropertiesAsync(extensionContext, extension, babylonMaterial)); + return Promise.all(promises).then(() => { }); + }); + } + _loadSheenPropertiesAsync(context, properties, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const promises = new Array(); + babylonMaterial.sheen.isEnabled = true; + babylonMaterial.sheen.intensity = 1; + if (properties.sheenColorFactor != undefined) { + babylonMaterial.sheen.color = Color3.FromArray(properties.sheenColorFactor); + } + else { + babylonMaterial.sheen.color = Color3.Black(); + } + if (properties.sheenColorTexture) { + promises.push(this._loader.loadTextureInfoAsync(`${context}/sheenColorTexture`, properties.sheenColorTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Sheen Color)`; + babylonMaterial.sheen.texture = texture; + })); + } + if (properties.sheenRoughnessFactor !== undefined) { + babylonMaterial.sheen.roughness = properties.sheenRoughnessFactor; + } + else { + babylonMaterial.sheen.roughness = 0; + } + if (properties.sheenRoughnessTexture) { + properties.sheenRoughnessTexture.nonColorData = true; + promises.push(this._loader.loadTextureInfoAsync(`${context}/sheenRoughnessTexture`, properties.sheenRoughnessTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Sheen Roughness)`; + babylonMaterial.sheen.textureRoughness = texture; + })); + } + babylonMaterial.sheen.albedoScaling = true; + babylonMaterial.sheen.useRoughnessFromMainTexture = false; + return Promise.all(promises).then(() => { }); + } +} +unregisterGLTFExtension(NAME$l); +registerGLTFExtension(NAME$l, true, (loader) => new KHR_materials_sheen(loader)); + +const NAME$k = "KHR_materials_specular"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_specular/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_specular { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$k; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 190; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$k); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadSpecularPropertiesAsync(extensionContext, extension, babylonMaterial)); + return Promise.all(promises).then(() => { }); + }); + } + _loadSpecularPropertiesAsync(context, properties, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const promises = new Array(); + if (properties.specularFactor !== undefined) { + babylonMaterial.metallicF0Factor = properties.specularFactor; + } + if (properties.specularColorFactor !== undefined) { + babylonMaterial.metallicReflectanceColor = Color3.FromArray(properties.specularColorFactor); + } + if (properties.specularTexture) { + properties.specularTexture.nonColorData = true; + promises.push(this._loader.loadTextureInfoAsync(`${context}/specularTexture`, properties.specularTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Specular)`; + babylonMaterial.metallicReflectanceTexture = texture; + babylonMaterial.useOnlyMetallicFromMetallicReflectanceTexture = true; + })); + } + if (properties.specularColorTexture) { + promises.push(this._loader.loadTextureInfoAsync(`${context}/specularColorTexture`, properties.specularColorTexture, (texture) => { + texture.name = `${babylonMaterial.name} (Specular Color)`; + babylonMaterial.reflectanceTexture = texture; + })); + } + return Promise.all(promises).then(() => { }); + } +} +unregisterGLTFExtension(NAME$k); +registerGLTFExtension(NAME$k, true, (loader) => new KHR_materials_specular(loader)); + +const NAME$j = "KHR_materials_ior"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_ior/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_ior { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$j; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 180; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$j); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadIorPropertiesAsync(extensionContext, extension, babylonMaterial)); + return Promise.all(promises).then(() => { }); + }); + } + _loadIorPropertiesAsync(context, properties, babylonMaterial) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + if (properties.ior !== undefined) { + babylonMaterial.indexOfRefraction = properties.ior; + } + else { + babylonMaterial.indexOfRefraction = KHR_materials_ior._DEFAULT_IOR; + } + return Promise.resolve(); + } +} +/** + * Default ior Value from the spec. + */ +KHR_materials_ior._DEFAULT_IOR = 1.5; +unregisterGLTFExtension(NAME$j); +registerGLTFExtension(NAME$j, true, (loader) => new KHR_materials_ior(loader)); + +const NAME$i = "KHR_materials_variants"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_variants/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_variants { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$i; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$i); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * Gets the list of available variant names for this asset. + * @param rootNode The glTF root node + * @returns the list of all the variant names for this model + */ + static GetAvailableVariants(rootNode) { + const extensionMetadata = this._GetExtensionMetadata(rootNode); + if (!extensionMetadata) { + return []; + } + return Object.keys(extensionMetadata.variants); + } + /** + * Gets the list of available variant names for this asset. + * @param rootNode The glTF root node + * @returns the list of all the variant names for this model + */ + getAvailableVariants(rootNode) { + return KHR_materials_variants.GetAvailableVariants(rootNode); + } + /** + * Select a variant given a variant name or a list of variant names. + * @param rootNode The glTF root node + * @param variantName The variant name(s) to select. + */ + static SelectVariant(rootNode, variantName) { + const extensionMetadata = this._GetExtensionMetadata(rootNode); + if (!extensionMetadata) { + throw new Error(`Cannot select variant on a glTF mesh that does not have the ${NAME$i} extension`); + } + const select = (variantName) => { + const entries = extensionMetadata.variants[variantName]; + if (entries) { + for (const entry of entries) { + entry.mesh.material = entry.material; + } + } + }; + if (variantName instanceof Array) { + for (const name of variantName) { + select(name); + } + } + else { + select(variantName); + } + extensionMetadata.lastSelected = variantName; + } + /** + * Select a variant given a variant name or a list of variant names. + * @param rootNode The glTF root node + * @param variantName The variant name(s) to select. + */ + selectVariant(rootNode, variantName) { + KHR_materials_variants.SelectVariant(rootNode, variantName); + } + /** + * Reset back to the original before selecting a variant. + * @param rootNode The glTF root node + */ + static Reset(rootNode) { + const extensionMetadata = this._GetExtensionMetadata(rootNode); + if (!extensionMetadata) { + throw new Error(`Cannot reset on a glTF mesh that does not have the ${NAME$i} extension`); + } + for (const entry of extensionMetadata.original) { + entry.mesh.material = entry.material; + } + extensionMetadata.lastSelected = null; + } + /** + * Reset back to the original before selecting a variant. + * @param rootNode The glTF root node + */ + reset(rootNode) { + KHR_materials_variants.Reset(rootNode); + } + /** + * Gets the last selected variant name(s) or null if original. + * @param rootNode The glTF root node + * @returns The selected variant name(s). + */ + static GetLastSelectedVariant(rootNode) { + const extensionMetadata = this._GetExtensionMetadata(rootNode); + if (!extensionMetadata) { + throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${NAME$i} extension`); + } + return extensionMetadata.lastSelected; + } + /** + * Gets the last selected variant name(s) or null if original. + * @param rootNode The glTF root node + * @returns The selected variant name(s). + */ + getLastSelectedVariant(rootNode) { + return KHR_materials_variants.GetLastSelectedVariant(rootNode); + } + static _GetExtensionMetadata(rootNode) { + return rootNode?._internalMetadata?.gltf?.[NAME$i] || null; + } + /** @internal */ + onLoading() { + const extensions = this._loader.gltf.extensions; + if (extensions && extensions[this.name]) { + const extension = extensions[this.name]; + this._variants = extension.variants; + } + } + /** @internal */ + onReady() { + const rootNode = this._loader.rootBabylonMesh; + if (rootNode) { + const options = this._loader.parent.extensionOptions[NAME$i]; + if (options?.defaultVariant) { + KHR_materials_variants.SelectVariant(rootNode, options.defaultVariant); + } + options?.onLoaded?.({ + get variants() { + return KHR_materials_variants.GetAvailableVariants(rootNode); + }, + get selectedVariant() { + const lastSelectedVariant = KHR_materials_variants.GetLastSelectedVariant(rootNode); + if (!lastSelectedVariant) { + return KHR_materials_variants.GetAvailableVariants(rootNode)[0]; + } + if (Array.isArray(lastSelectedVariant)) { + return lastSelectedVariant[0]; + } + return lastSelectedVariant; + }, + set selectedVariant(variantName) { + KHR_materials_variants.SelectVariant(rootNode, variantName); + }, + }); + } + } + /** + * @internal + */ + _loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign) { + return GLTFLoader.LoadExtensionAsync(context, primitive, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader._loadMeshPrimitiveAsync(context, name, node, mesh, primitive, (babylonMesh) => { + assign(babylonMesh); + if (babylonMesh instanceof Mesh) { + const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode); + const root = this._loader.rootBabylonMesh; + const metadata = root ? (root._internalMetadata = root._internalMetadata || {}) : {}; + const gltf = (metadata.gltf = metadata.gltf || {}); + const extensionMetadata = (gltf[NAME$i] = gltf[NAME$i] || { lastSelected: null, original: [], variants: {} }); + // Store the original material. + extensionMetadata.original.push({ mesh: babylonMesh, material: babylonMesh.material }); + // For each mapping, look at the variants and make a new entry for them. + for (let mappingIndex = 0; mappingIndex < extension.mappings.length; ++mappingIndex) { + const mapping = extension.mappings[mappingIndex]; + const material = ArrayItem.Get(`${extensionContext}/mappings/${mappingIndex}/material`, this._loader.gltf.materials, mapping.material); + promises.push(this._loader._loadMaterialAsync(`#/materials/${mapping.material}`, material, babylonMesh, babylonDrawMode, (babylonMaterial) => { + for (let mappingVariantIndex = 0; mappingVariantIndex < mapping.variants.length; ++mappingVariantIndex) { + const variantIndex = mapping.variants[mappingVariantIndex]; + const variant = ArrayItem.Get(`/extensions/${NAME$i}/variants/${variantIndex}`, this._variants, variantIndex); + extensionMetadata.variants[variant.name] = extensionMetadata.variants[variant.name] || []; + extensionMetadata.variants[variant.name].push({ + mesh: babylonMesh, + material: babylonMaterial, + }); + // Replace the target when original mesh is cloned + babylonMesh.onClonedObservable.add((newOne) => { + const newMesh = newOne; + let metadata = null; + let newRoot = newMesh; + // Find root to get medata + do { + newRoot = newRoot.parent; + if (!newRoot) { + return; + } + metadata = KHR_materials_variants._GetExtensionMetadata(newRoot); + } while (metadata === null); + // Need to clone the metadata on the root (first time only) + if (root && metadata === KHR_materials_variants._GetExtensionMetadata(root)) { + // Copy main metadata + newRoot._internalMetadata = {}; + for (const key in root._internalMetadata) { + newRoot._internalMetadata[key] = root._internalMetadata[key]; + } + // Copy the gltf metadata + newRoot._internalMetadata.gltf = []; + for (const key in root._internalMetadata.gltf) { + newRoot._internalMetadata.gltf[key] = root._internalMetadata.gltf[key]; + } + // Duplicate the extension specific metadata + newRoot._internalMetadata.gltf[NAME$i] = { lastSelected: null, original: [], variants: {} }; + for (const original of metadata.original) { + newRoot._internalMetadata.gltf[NAME$i].original.push({ + mesh: original.mesh, + material: original.material, + }); + } + for (const key in metadata.variants) { + if (Object.prototype.hasOwnProperty.call(metadata.variants, key)) { + newRoot._internalMetadata.gltf[NAME$i].variants[key] = []; + for (const variantEntry of metadata.variants[key]) { + newRoot._internalMetadata.gltf[NAME$i].variants[key].push({ + mesh: variantEntry.mesh, + material: variantEntry.material, + }); + } + } + } + metadata = newRoot._internalMetadata.gltf[NAME$i]; + } + // Relocate + for (const target of metadata.original) { + if (target.mesh === babylonMesh) { + target.mesh = newMesh; + } + } + for (const target of metadata.variants[variant.name]) { + if (target.mesh === babylonMesh) { + target.mesh = newMesh; + } + } + }); + } + })); + } + } + })); + return Promise.all(promises).then(([babylonMesh]) => { + return babylonMesh; + }); + }); + } +} +unregisterGLTFExtension(NAME$i); +registerGLTFExtension(NAME$i, true, (loader) => new KHR_materials_variants(loader)); + +/** + * A class to handle setting up the rendering of opaque objects to be shown through transmissive objects. + */ +class TransmissionHelper { + /** + * Creates the default options for the helper. + * @returns the default options + */ + static _GetDefaultOptions() { + return { + renderSize: 1024, + samples: 4, + lodGenerationScale: 1, + lodGenerationOffset: -4, + renderTargetTextureType: Constants.TEXTURETYPE_HALF_FLOAT, + generateMipmaps: true, + }; + } + /** + * constructor + * @param options Defines the options we want to customize the helper + * @param scene The scene to add the material to + */ + constructor(options, scene) { + this._opaqueRenderTarget = null; + this._opaqueMeshesCache = []; + this._transparentMeshesCache = []; + this._materialObservers = {}; + this._options = { + ...TransmissionHelper._GetDefaultOptions(), + ...options, + }; + this._scene = scene; + this._scene._transmissionHelper = this; + this.onErrorObservable = new Observable(); + this._scene.onDisposeObservable.addOnce(() => { + this.dispose(); + }); + this._parseScene(); + this._setupRenderTargets(); + } + /** + * Updates the background according to the new options + * @param options + */ + updateOptions(options) { + // First check if any options are actually being changed. If not, exit. + const newValues = Object.keys(options).filter((key) => this._options[key] !== options[key]); + if (!newValues.length) { + return; + } + const newOptions = { + ...this._options, + ...options, + }; + const oldOptions = this._options; + this._options = newOptions; + // If size changes, recreate everything + if (newOptions.renderSize !== oldOptions.renderSize || + newOptions.renderTargetTextureType !== oldOptions.renderTargetTextureType || + newOptions.generateMipmaps !== oldOptions.generateMipmaps || + !this._opaqueRenderTarget) { + this._setupRenderTargets(); + } + else { + this._opaqueRenderTarget.samples = newOptions.samples; + this._opaqueRenderTarget.lodGenerationScale = newOptions.lodGenerationScale; + this._opaqueRenderTarget.lodGenerationOffset = newOptions.lodGenerationOffset; + } + } + /** + * @returns the opaque render target texture or null if not available. + */ + getOpaqueTarget() { + return this._opaqueRenderTarget; + } + _shouldRenderAsTransmission(material) { + if (!material) { + return false; + } + if (material instanceof PBRMaterial && material.subSurface.isRefractionEnabled) { + return true; + } + return false; + } + _addMesh(mesh) { + this._materialObservers[mesh.uniqueId] = mesh.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)); + // we need to defer the processing because _addMesh may be called as part as an instance mesh creation, in which case some + // internal properties are not setup yet, like _sourceMesh (needed when doing mesh.material below) + Tools.SetImmediate(() => { + if (this._shouldRenderAsTransmission(mesh.material)) { + mesh.material.refractionTexture = this._opaqueRenderTarget; + if (this._transparentMeshesCache.indexOf(mesh) === -1) { + this._transparentMeshesCache.push(mesh); + } + } + else { + if (this._opaqueMeshesCache.indexOf(mesh) === -1) { + this._opaqueMeshesCache.push(mesh); + } + } + }); + } + _removeMesh(mesh) { + mesh.onMaterialChangedObservable.remove(this._materialObservers[mesh.uniqueId]); + delete this._materialObservers[mesh.uniqueId]; + let idx = this._transparentMeshesCache.indexOf(mesh); + if (idx !== -1) { + this._transparentMeshesCache.splice(idx, 1); + } + idx = this._opaqueMeshesCache.indexOf(mesh); + if (idx !== -1) { + this._opaqueMeshesCache.splice(idx, 1); + } + } + _parseScene() { + this._scene.meshes.forEach(this._addMesh.bind(this)); + // Listen for when a mesh is added to the scene and add it to our cache lists. + this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)); + // Listen for when a mesh is removed from to the scene and remove it from our cache lists. + this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this)); + } + // When one of the meshes in the scene has its material changed, make sure that it's in the correct cache list. + _onMeshMaterialChanged(mesh) { + const transparentIdx = this._transparentMeshesCache.indexOf(mesh); + const opaqueIdx = this._opaqueMeshesCache.indexOf(mesh); + // If the material is transparent, make sure that it's added to the transparent list and removed from the opaque list + const useTransmission = this._shouldRenderAsTransmission(mesh.material); + if (useTransmission) { + if (mesh.material instanceof PBRMaterial) { + mesh.material.subSurface.refractionTexture = this._opaqueRenderTarget; + } + if (opaqueIdx !== -1) { + this._opaqueMeshesCache.splice(opaqueIdx, 1); + this._transparentMeshesCache.push(mesh); + } + else if (transparentIdx === -1) { + this._transparentMeshesCache.push(mesh); + } + // If the material is opaque, make sure that it's added to the opaque list and removed from the transparent list + } + else { + if (transparentIdx !== -1) { + this._transparentMeshesCache.splice(transparentIdx, 1); + this._opaqueMeshesCache.push(mesh); + } + else if (opaqueIdx === -1) { + this._opaqueMeshesCache.push(mesh); + } + } + } + /** + * @internal + * Check if the opaque render target has not been disposed and can still be used. + * @returns + */ + _isRenderTargetValid() { + return this._opaqueRenderTarget?.getInternalTexture() !== null; + } + /** + * @internal + * Setup the render targets according to the specified options. + */ + _setupRenderTargets() { + if (this._opaqueRenderTarget) { + this._opaqueRenderTarget.dispose(); + } + this._opaqueRenderTarget = new RenderTargetTexture("opaqueSceneTexture", this._options.renderSize, this._scene, this._options.generateMipmaps, undefined, this._options.renderTargetTextureType); + this._opaqueRenderTarget.ignoreCameraViewport = true; + this._opaqueRenderTarget.renderList = this._opaqueMeshesCache; + this._opaqueRenderTarget.clearColor = this._options.clearColor?.clone() ?? this._scene.clearColor.clone(); + this._opaqueRenderTarget.gammaSpace = false; + this._opaqueRenderTarget.lodGenerationScale = this._options.lodGenerationScale; + this._opaqueRenderTarget.lodGenerationOffset = this._options.lodGenerationOffset; + this._opaqueRenderTarget.samples = this._options.samples; + this._opaqueRenderTarget.renderSprites = true; + this._opaqueRenderTarget.renderParticles = true; + this._opaqueRenderTarget.renderInLinearSpace = true; + let saveSceneEnvIntensity; + this._opaqueRenderTarget.onBeforeBindObservable.add((opaqueRenderTarget) => { + saveSceneEnvIntensity = this._scene.environmentIntensity; + this._scene.environmentIntensity = 1.0; + if (!this._options.clearColor) { + this._scene.clearColor.toLinearSpaceToRef(opaqueRenderTarget.clearColor, this._scene.getEngine().useExactSrgbConversions); + } + else { + opaqueRenderTarget.clearColor.copyFrom(this._options.clearColor); + } + }); + this._opaqueRenderTarget.onAfterUnbindObservable.add(() => { + this._scene.environmentIntensity = saveSceneEnvIntensity; + }); + this._transparentMeshesCache.forEach((mesh) => { + if (this._shouldRenderAsTransmission(mesh.material)) { + mesh.material.refractionTexture = this._opaqueRenderTarget; + } + }); + } + /** + * Dispose all the elements created by the Helper. + */ + dispose() { + this._scene._transmissionHelper = undefined; + if (this._opaqueRenderTarget) { + this._opaqueRenderTarget.dispose(); + this._opaqueRenderTarget = null; + } + this._transparentMeshesCache = []; + this._opaqueMeshesCache = []; + } +} +const NAME$h = "KHR_materials_transmission"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_transmission/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_transmission { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$h; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 175; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$h); + if (this.enabled) { + loader.parent.transparencyAsCoverage = true; + } + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadTransparentPropertiesAsync(extensionContext, material, babylonMaterial, extension)); + return Promise.all(promises).then(() => { }); + }); + } + _loadTransparentPropertiesAsync(context, material, babylonMaterial, extension) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const pbrMaterial = babylonMaterial; + // Enables "refraction" texture which represents transmitted light. + pbrMaterial.subSurface.isRefractionEnabled = true; + // Since this extension models thin-surface transmission only, we must make IOR = 1.0 + pbrMaterial.subSurface.volumeIndexOfRefraction = 1.0; + // Albedo colour will tint transmission. + pbrMaterial.subSurface.useAlbedoToTintRefraction = true; + if (extension.transmissionFactor !== undefined) { + pbrMaterial.subSurface.refractionIntensity = extension.transmissionFactor; + const scene = pbrMaterial.getScene(); + if (pbrMaterial.subSurface.refractionIntensity && !scene._transmissionHelper) { + new TransmissionHelper({}, pbrMaterial.getScene()); + } + else if (pbrMaterial.subSurface.refractionIntensity && !scene._transmissionHelper?._isRenderTargetValid()) { + // If the render target is not valid, recreate it. + scene._transmissionHelper?._setupRenderTargets(); + } + } + else { + pbrMaterial.subSurface.refractionIntensity = 0.0; + pbrMaterial.subSurface.isRefractionEnabled = false; + return Promise.resolve(); + } + pbrMaterial.subSurface.minimumThickness = 0.0; + pbrMaterial.subSurface.maximumThickness = 0.0; + if (extension.transmissionTexture) { + extension.transmissionTexture.nonColorData = true; + return this._loader.loadTextureInfoAsync(`${context}/transmissionTexture`, extension.transmissionTexture, undefined).then((texture) => { + texture.name = `${babylonMaterial.name} (Transmission)`; + pbrMaterial.subSurface.refractionIntensityTexture = texture; + pbrMaterial.subSurface.useGltfStyleTextures = true; + }); + } + else { + return Promise.resolve(); + } + } +} +unregisterGLTFExtension(NAME$h); +registerGLTFExtension(NAME$h, true, (loader) => new KHR_materials_transmission(loader)); + +const NAME$g = "KHR_materials_diffuse_transmission"; +/** + * [Proposed Specification](https://github.com/KhronosGroup/glTF/pull/1825) + * !!! Experimental Extension Subject to Changes !!! + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_diffuse_transmission { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$g; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 174; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$g); + if (this.enabled) { + loader.parent.transparencyAsCoverage = true; + } + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadTranslucentPropertiesAsync(extensionContext, material, babylonMaterial, extension)); + return Promise.all(promises).then(() => { }); + }); + } + _loadTranslucentPropertiesAsync(context, material, babylonMaterial, extension) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + const pbrMaterial = babylonMaterial; + // Enables "translucency" texture which represents diffusely-transmitted light. + pbrMaterial.subSurface.isTranslucencyEnabled = true; + // Since this extension models thin-surface transmission only, we must make the + // internal IOR == 1.0 and set the thickness to 0. + pbrMaterial.subSurface.volumeIndexOfRefraction = 1.0; + pbrMaterial.subSurface.minimumThickness = 0.0; + pbrMaterial.subSurface.maximumThickness = 0.0; + // Tint color will be used for transmission. + pbrMaterial.subSurface.useAlbedoToTintTranslucency = false; + if (extension.diffuseTransmissionFactor !== undefined) { + pbrMaterial.subSurface.translucencyIntensity = extension.diffuseTransmissionFactor; + } + else { + pbrMaterial.subSurface.translucencyIntensity = 0.0; + pbrMaterial.subSurface.isTranslucencyEnabled = false; + return Promise.resolve(); + } + const promises = new Array(); + pbrMaterial.subSurface.useGltfStyleTextures = true; + if (extension.diffuseTransmissionTexture) { + extension.diffuseTransmissionTexture.nonColorData = true; + promises.push(this._loader.loadTextureInfoAsync(`${context}/diffuseTransmissionTexture`, extension.diffuseTransmissionTexture).then((texture) => { + texture.name = `${babylonMaterial.name} (Diffuse Transmission)`; + pbrMaterial.subSurface.translucencyIntensityTexture = texture; + })); + } + if (extension.diffuseTransmissionColorFactor !== undefined) { + pbrMaterial.subSurface.translucencyColor = Color3.FromArray(extension.diffuseTransmissionColorFactor); + } + else { + pbrMaterial.subSurface.translucencyColor = Color3.White(); + } + if (extension.diffuseTransmissionColorTexture) { + promises.push(this._loader.loadTextureInfoAsync(`${context}/diffuseTransmissionColorTexture`, extension.diffuseTransmissionColorTexture).then((texture) => { + texture.name = `${babylonMaterial.name} (Diffuse Transmission Color)`; + pbrMaterial.subSurface.translucencyColorTexture = texture; + })); + } + return Promise.all(promises).then(() => { }); + } +} +unregisterGLTFExtension(NAME$g); +registerGLTFExtension(NAME$g, true, (loader) => new KHR_materials_diffuse_transmission(loader)); + +const NAME$f = "KHR_materials_volume"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_volume/README.md) + * @since 5.0.0 + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_volume { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$f; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 173; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$f); + if (this.enabled) { + // We need to disable instance usage because the attenuation factor depends on the node scale of each individual mesh + this._loader._disableInstancedMesh++; + } + } + /** @internal */ + dispose() { + if (this.enabled) { + this._loader._disableInstancedMesh--; + } + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadVolumePropertiesAsync(extensionContext, material, babylonMaterial, extension)); + return Promise.all(promises).then(() => { }); + }); + } + _loadVolumePropertiesAsync(context, material, babylonMaterial, extension) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + // If transparency isn't enabled already, this extension shouldn't do anything. + // i.e. it requires either the KHR_materials_transmission or KHR_materials_diffuse_transmission extensions. + if ((!babylonMaterial.subSurface.isRefractionEnabled && !babylonMaterial.subSurface.isTranslucencyEnabled) || !extension.thicknessFactor) { + return Promise.resolve(); + } + // IOR in this extension only affects interior. + babylonMaterial.subSurface.volumeIndexOfRefraction = babylonMaterial.indexOfRefraction; + const attenuationDistance = extension.attenuationDistance !== undefined ? extension.attenuationDistance : Number.MAX_VALUE; + babylonMaterial.subSurface.tintColorAtDistance = attenuationDistance; + if (extension.attenuationColor !== undefined && extension.attenuationColor.length == 3) { + babylonMaterial.subSurface.tintColor.copyFromFloats(extension.attenuationColor[0], extension.attenuationColor[1], extension.attenuationColor[2]); + } + babylonMaterial.subSurface.minimumThickness = 0.0; + babylonMaterial.subSurface.maximumThickness = extension.thicknessFactor; + babylonMaterial.subSurface.useThicknessAsDepth = true; + if (extension.thicknessTexture) { + extension.thicknessTexture.nonColorData = true; + return this._loader.loadTextureInfoAsync(`${context}/thicknessTexture`, extension.thicknessTexture).then((texture) => { + texture.name = `${babylonMaterial.name} (Thickness)`; + babylonMaterial.subSurface.thicknessTexture = texture; + babylonMaterial.subSurface.useGltfStyleTextures = true; + }); + } + else { + return Promise.resolve(); + } + } +} +unregisterGLTFExtension(NAME$f); +registerGLTFExtension(NAME$f, true, (loader) => new KHR_materials_volume(loader)); + +const NAME$e = "KHR_materials_dispersion"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/87bd64a7f5e23c84b6aef2e6082069583ed0ddb4/extensions/2.0/Khronos/KHR_materials_dispersion/README.md) + * @experimental + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_materials_dispersion { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$e; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 174; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$e); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial)); + promises.push(this._loadDispersionPropertiesAsync(extensionContext, material, babylonMaterial, extension)); + return Promise.all(promises).then(() => { }); + }); + } + _loadDispersionPropertiesAsync(context, material, babylonMaterial, extension) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${context}: Material type not supported`); + } + // If transparency isn't enabled already, this extension shouldn't do anything. + // i.e. it requires either the KHR_materials_transmission or KHR_materials_diffuse_transmission extensions. + if (!babylonMaterial.subSurface.isRefractionEnabled || !extension.dispersion) { + return Promise.resolve(); + } + babylonMaterial.subSurface.isDispersionEnabled = true; + babylonMaterial.subSurface.dispersion = extension.dispersion; + return Promise.resolve(); + } +} +unregisterGLTFExtension(NAME$e); +registerGLTFExtension(NAME$e, true, (loader) => new KHR_materials_dispersion(loader)); + +const NAME$d = "KHR_mesh_quantization"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_mesh_quantization { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$d; + this.enabled = loader.isExtensionUsed(NAME$d); + } + /** @internal */ + dispose() { } +} +unregisterGLTFExtension(NAME$d); +registerGLTFExtension(NAME$d, true, (loader) => new KHR_mesh_quantization(loader)); + +const NAME$c = "KHR_texture_basisu"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_texture_basisu/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_texture_basisu { + /** + * @internal + */ + constructor(loader) { + /** The name of this extension. */ + this.name = NAME$c; + this._loader = loader; + this.enabled = loader.isExtensionUsed(NAME$c); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + _loadTextureAsync(context, texture, assign) { + return GLTFLoader.LoadExtensionAsync(context, texture, this.name, (extensionContext, extension) => { + const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._loader.gltf.samplers, texture.sampler); + const image = ArrayItem.Get(`${extensionContext}/source`, this._loader.gltf.images, extension.source); + return this._loader._createTextureAsync(context, sampler, image, (babylonTexture) => { + assign(babylonTexture); + }, texture._textureInfo.nonColorData ? { useRGBAIfASTCBC7NotAvailableWhenUASTC: true } : undefined, !texture._textureInfo.nonColorData); + }); + } +} +unregisterGLTFExtension(NAME$c); +registerGLTFExtension(NAME$c, true, (loader) => new KHR_texture_basisu(loader)); + +const NAME$b = "KHR_texture_transform"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_texture_transform/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_texture_transform { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$b; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$b); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadTextureInfoAsync(context, textureInfo, assign) { + return GLTFLoader.LoadExtensionAsync(context, textureInfo, this.name, (extensionContext, extension) => { + return this._loader.loadTextureInfoAsync(context, textureInfo, (babylonTexture) => { + if (!(babylonTexture instanceof Texture)) { + throw new Error(`${extensionContext}: Texture type not supported`); + } + if (extension.offset) { + babylonTexture.uOffset = extension.offset[0]; + babylonTexture.vOffset = extension.offset[1]; + } + // Always rotate around the origin. + babylonTexture.uRotationCenter = 0; + babylonTexture.vRotationCenter = 0; + if (extension.rotation) { + babylonTexture.wAng = -extension.rotation; + } + if (extension.scale) { + babylonTexture.uScale = extension.scale[0]; + babylonTexture.vScale = extension.scale[1]; + } + if (extension.texCoord != undefined) { + babylonTexture.coordinatesIndex = extension.texCoord; + } + assign(babylonTexture); + }); + }); + } +} +unregisterGLTFExtension(NAME$b); +registerGLTFExtension(NAME$b, true, (loader) => new KHR_texture_transform(loader)); + +const NAME$a = "KHR_xmp_json_ld"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_xmp_json_ld/README.md) + * @since 5.0.0 + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_xmp_json_ld { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$a; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 100; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$a); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * Called after the loader state changes to LOADING. + */ + onLoading() { + if (this._loader.rootBabylonMesh === null) { + return; + } + const xmp_gltf = this._loader.gltf.extensions?.KHR_xmp_json_ld; + const xmp_node = this._loader.gltf.asset?.extensions?.KHR_xmp_json_ld; + if (xmp_gltf && xmp_node) { + const packet = +xmp_node.packet; + if (xmp_gltf.packets && packet < xmp_gltf.packets.length) { + this._loader.rootBabylonMesh.metadata = this._loader.rootBabylonMesh.metadata || {}; + this._loader.rootBabylonMesh.metadata.xmp = xmp_gltf.packets[packet]; + } + } + } +} +unregisterGLTFExtension(NAME$a); +registerGLTFExtension(NAME$a, true, (loader) => new KHR_xmp_json_ld(loader)); + +/* eslint-disable @typescript-eslint/naming-convention */ +function getColor3(_target, source, offset, scale) { + return Color3.FromArray(source, offset).scale(scale); +} +function getAlpha(_target, source, offset, scale) { + return source[offset + 3] * scale; +} +function getFloat(_target, source, offset, scale) { + return source[offset] * scale; +} +function getMinusFloat(_target, source, offset, scale) { + return -source[offset] * scale; +} +function getNextFloat(_target, source, offset, scale) { + return source[offset + 1] * scale; +} +function getFloatBy2(_target, source, offset, scale) { + return source[offset] * scale * 2; +} +function getTextureTransformTree(textureName) { + return { + scale: [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.uScale`, getFloat, () => 2), + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.vScale`, getNextFloat, () => 2), + ], + offset: [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.uOffset`, getFloat, () => 2), + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.vOffset`, getNextFloat, () => 2), + ], + rotation: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.wAng`, getMinusFloat, () => 1)], + }; +} +class CameraAnimationPropertyInfo extends AnimationPropertyInfo { + /** @internal */ + buildAnimations(target, name, fps, keys) { + return [{ babylonAnimatable: target._babylonCamera, babylonAnimation: this._buildAnimation(name, fps, keys) }]; + } +} +class MaterialAnimationPropertyInfo extends AnimationPropertyInfo { + /** @internal */ + buildAnimations(target, name, fps, keys) { + const babylonAnimations = []; + for (const fillMode in target._data) { + babylonAnimations.push({ + babylonAnimatable: target._data[fillMode].babylonMaterial, + babylonAnimation: this._buildAnimation(name, fps, keys), + }); + } + return babylonAnimations; + } +} +class LightAnimationPropertyInfo extends AnimationPropertyInfo { + /** @internal */ + buildAnimations(target, name, fps, keys) { + return [{ babylonAnimatable: target._babylonLight, babylonAnimation: this._buildAnimation(name, fps, keys) }]; + } +} +SetInterpolationForKey("/cameras/{}/orthographic/xmag", [ + new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "orthoLeft", getMinusFloat, () => 1), + new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "orthoRight", getNextFloat, () => 1), +]); +SetInterpolationForKey("/cameras/{}/orthographic/ymag", [ + new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "orthoBottom", getMinusFloat, () => 1), + new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "orthoTop", getNextFloat, () => 1), +]); +SetInterpolationForKey("/cameras/{}/orthographic/zfar", [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "maxZ", getFloat, () => 1)]); +SetInterpolationForKey("/cameras/{}/orthographic/znear", [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "minZ", getFloat, () => 1)]); +SetInterpolationForKey("/cameras/{}/perspective/yfov", [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "fov", getFloat, () => 1)]); +SetInterpolationForKey("/cameras/{}/perspective/zfar", [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "maxZ", getFloat, () => 1)]); +SetInterpolationForKey("/cameras/{}/perspective/znear", [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "minZ", getFloat, () => 1)]); +// add interpolation to the materials mapping +SetInterpolationForKey("/materials/{}/pbrMetallicRoughness/baseColorFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, "albedoColor", getColor3, () => 4), + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "alpha", getAlpha, () => 4), +]); +SetInterpolationForKey("/materials/{}/pbrMetallicRoughness/metallicFactor", [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "metallic", getFloat, () => 1)]); +SetInterpolationForKey("/materials/{}/pbrMetallicRoughness/metallicFactor", [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "roughness", getFloat, () => 1)]); +const baseColorTextureInterpolation = getTextureTransformTree("albedoTexture"); +SetInterpolationForKey("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale", baseColorTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset", baseColorTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/rotation", baseColorTextureInterpolation.rotation); +const metallicRoughnessTextureInterpolation = getTextureTransformTree("metallicTexture"); +SetInterpolationForKey("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/scale", metallicRoughnessTextureInterpolation.scale); +SetInterpolationForKey("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/offset", metallicRoughnessTextureInterpolation.offset); +SetInterpolationForKey("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/rotation", metallicRoughnessTextureInterpolation.rotation); +SetInterpolationForKey("/materials/{}/emissiveFactor", [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, "emissiveColor", getColor3, () => 3)]); +const normalTextureInterpolation = getTextureTransformTree("bumpTexture"); +SetInterpolationForKey("/materials/{}/normalTexture/scale", [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "bumpTexture.level", getFloat, () => 1)]); +SetInterpolationForKey("/materials/{}/normalTexture/extensions/KHR_texture_transform/scale", normalTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/normalTexture/extensions/KHR_texture_transform/offset", normalTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/normalTexture/extensions/KHR_texture_transform/rotation", normalTextureInterpolation.rotation); +SetInterpolationForKey("/materials/{}/occlusionTexture/strength", [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "ambientTextureStrength", getFloat, () => 1)]); +const occlusionTextureInterpolation = getTextureTransformTree("ambientTexture"); +SetInterpolationForKey("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/scale", occlusionTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/offset", occlusionTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/rotation", occlusionTextureInterpolation.rotation); +const emissiveTextureInterpolation = getTextureTransformTree("emissiveTexture"); +SetInterpolationForKey("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/scale", emissiveTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/offset", emissiveTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/rotation", emissiveTextureInterpolation.rotation); +// materials extensions +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyStrength", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "anisotropy.intensity", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyRotation", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "anisotropy.angle", getFloat, () => 1), +]); +const anisotropyTextureInterpolation = getTextureTransformTree("anisotropy.texture"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/scale", anisotropyTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/offset", anisotropyTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/rotation", anisotropyTextureInterpolation.rotation); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "clearCoat.intensity", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "clearCoat.roughness", getFloat, () => 1), +]); +const clearcoatTextureInterpolation = getTextureTransformTree("clearCoat.texture"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/scale", clearcoatTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/offset", clearcoatTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/rotation", clearcoatTextureInterpolation.rotation); +const clearcoatNormalTextureInterpolation = getTextureTransformTree("clearCoat.bumpTexture"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "clearCoat.bumpTexture.level", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/scale", clearcoatNormalTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/offset", clearcoatNormalTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/rotation", clearcoatNormalTextureInterpolation.rotation); +const clearcoatRoughnessTextureInterpolation = getTextureTransformTree("clearCoat.textureRoughness"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/scale", clearcoatRoughnessTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/offset", clearcoatRoughnessTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/rotation", clearcoatRoughnessTextureInterpolation.rotation); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_dispersion/dispersionFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "subSurface.dispersion", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_emissive_strength/emissiveStrength", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "emissiveIntensity", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_ior/ior", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "indexOfRefraction", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_iridescence/iridescenceFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "iridescence.intensity", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_iridescence/iridescenceIor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "iridescence.indexOfRefraction", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMinimum", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "iridescence.minimumThickness", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMaximum", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "iridescence.maximumThickness", getFloat, () => 1), +]); +const iridescenceTextureInterpolation = getTextureTransformTree("iridescence.texture"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/scale", iridescenceTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/offset", iridescenceTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/rotation", iridescenceTextureInterpolation.rotation); +const iridescenceThicknessTextureInterpolation = getTextureTransformTree("iridescence.thicknessTexture"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/scale", iridescenceThicknessTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/offset", iridescenceThicknessTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/rotation", iridescenceThicknessTextureInterpolation.rotation); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_sheen/sheenColorFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, "sheen.color", getColor3, () => 3), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "sheen.roughness", getFloat, () => 1), +]); +const sheenTextureInterpolation = getTextureTransformTree("sheen.texture"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/scale", sheenTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/offset", sheenTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/rotation", sheenTextureInterpolation.rotation); +const sheenRoughnessTextureInterpolation = getTextureTransformTree("sheen.textureRoughness"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/scale", sheenRoughnessTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/offset", sheenRoughnessTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/rotation", sheenRoughnessTextureInterpolation.rotation); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_specular/specularFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "metallicF0Factor", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_specular/specularColorFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, "metallicReflectanceColor", getColor3, () => 3), +]); +const specularTextureInterpolation = getTextureTransformTree("metallicReflectanceTexture"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/scale", specularTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/offset", specularTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/rotation", specularTextureInterpolation.rotation); +const specularColorTextureInterpolation = getTextureTransformTree("reflectanceTexture"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/scale", specularColorTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/offset", specularColorTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/rotation", specularColorTextureInterpolation.rotation); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_transmission/transmissionFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "subSurface.refractionIntensity", getFloat, () => 1), +]); +const transmissionTextureInterpolation = getTextureTransformTree("subSurface.refractionIntensityTexture"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/scale", transmissionTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/offset", transmissionTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/rotation", transmissionTextureInterpolation.rotation); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_volume/attenuationColor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, "subSurface.tintColor", getColor3, () => 3), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_volume/attenuationDistance", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "subSurface.tintColorAtDistance", getFloat, () => 1), +]); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_volume/thicknessFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "subSurface.maximumThickness", getFloat, () => 1), +]); +const thicknessTextureInterpolation = getTextureTransformTree("subSurface.thicknessTexture"); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/scale", thicknessTextureInterpolation.scale); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/offset", thicknessTextureInterpolation.offset); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/rotation", thicknessTextureInterpolation.rotation); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "subSurface.translucencyIntensity", getFloat, () => 1), +]); +const diffuseTransmissionTextureInterpolation = getTextureTransformTree("subSurface.translucencyIntensityTexture"); +SetInterpolationForKey("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/scale", diffuseTransmissionTextureInterpolation.scale); +SetInterpolationForKey("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/offset", diffuseTransmissionTextureInterpolation.offset); +SetInterpolationForKey("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/rotation", diffuseTransmissionTextureInterpolation.rotation); +SetInterpolationForKey("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorFactor", [ + new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, "subSurface.translucencyColor", getColor3, () => 3), +]); +const diffuseTransmissionColorTextureInterpolation = getTextureTransformTree("subSurface.translucencyColorTexture"); +SetInterpolationForKey("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/scale", diffuseTransmissionColorTextureInterpolation.scale); +SetInterpolationForKey("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/offset", diffuseTransmissionColorTextureInterpolation.offset); +SetInterpolationForKey("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/rotation", diffuseTransmissionColorTextureInterpolation.rotation); +SetInterpolationForKey("/extensions/KHR_lights_punctual/lights/{}/color", [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, "diffuse", getColor3, () => 3)]); +SetInterpolationForKey("/extensions/KHR_lights_punctual/lights/{}/intensity", [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "intensity", getFloat, () => 1)]); +SetInterpolationForKey("/extensions/KHR_lights_punctual/lights/{}/range", [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "range", getFloat, () => 1)]); +SetInterpolationForKey("/extensions/KHR_lights_punctual/lights/{}/spot/innerConeAngle", [ + new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "innerAngle", getFloatBy2, () => 1), +]); +SetInterpolationForKey("/extensions/KHR_lights_punctual/lights/{}/spot/outerConeAngle", [ + new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "angle", getFloatBy2, () => 1), +]); +SetInterpolationForKey("/nodes/{}/extensions/EXT_lights_ies/color", [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, "diffuse", getColor3, () => 3)]); +SetInterpolationForKey("/nodes/{}/extensions/EXT_lights_ies/multiplier", [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, "intensity", getFloat, () => 1)]); + +const NAME$9 = "KHR_animation_pointer"; +/** + * [Specification PR](https://github.com/KhronosGroup/glTF/pull/2147) + * !!! Experimental Extension Subject to Changes !!! + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_animation_pointer { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$9; + this._loader = loader; + this._pathToObjectConverter = GetPathToObjectConverter(this._loader.gltf); + } + /** + * Defines whether this extension is enabled. + */ + get enabled() { + return this._loader.isExtensionUsed(NAME$9); + } + /** @internal */ + dispose() { + this._loader = null; + delete this._pathToObjectConverter; // GC + } + /** + * Loads a glTF animation channel. + * @param context The context when loading the asset + * @param animationContext The context of the animation when loading the asset + * @param animation The glTF animation property + * @param channel The glTF animation channel property + * @param onLoad Called for each animation loaded + * @returns A void promise that resolves when the load is complete or null if not handled + */ + _loadAnimationChannelAsync(context, animationContext, animation, channel, onLoad) { + const extension = channel.target.extensions?.KHR_animation_pointer; + if (!extension || !this._pathToObjectConverter) { + return null; + } + if (channel.target.path !== "pointer" /* AnimationChannelTargetPath.POINTER */) { + Logger.Warn(`${context}/target/path: Value (${channel.target.path}) must be (${"pointer" /* AnimationChannelTargetPath.POINTER */}) when using the ${this.name} extension`); + } + if (channel.target.node != undefined) { + Logger.Warn(`${context}/target/node: Value (${channel.target.node}) must not be present when using the ${this.name} extension`); + } + const extensionContext = `${context}/extensions/${this.name}`; + const pointer = extension.pointer; + if (!pointer) { + throw new Error(`${extensionContext}: Pointer is missing`); + } + try { + const obj = this._pathToObjectConverter.convert(pointer); + if (!obj.info.interpolation) { + throw new Error(`${extensionContext}/pointer: Interpolation is missing`); + } + return this._loader._loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, { + object: obj.object, + info: obj.info.interpolation, + }, onLoad); + } + catch (e) { + Logger.Warn(`${extensionContext}/pointer: Invalid pointer (${pointer}) skipped`); + return null; + } + } +} +unregisterGLTFExtension(NAME$9); +registerGLTFExtension(NAME$9, true, (loader) => new KHR_animation_pointer(loader)); + +/** + * Composed of a frame, and an action function + */ +class AnimationEvent { + /** + * Initializes the animation event + * @param frame The frame for which the event is triggered + * @param action The event to perform when triggered + * @param onlyOnce Specifies if the event should be triggered only once + */ + constructor( + /** The frame for which the event is triggered **/ + frame, + /** The event to perform when triggered **/ + action, + /** Specifies if the event should be triggered only once**/ + onlyOnce) { + this.frame = frame; + this.action = action; + this.onlyOnce = onlyOnce; + /** + * Specifies if the animation event is done + */ + this.isDone = false; + } + /** @internal */ + _clone() { + return new AnimationEvent(this.frame, this.action, this.onlyOnce); + } +} + +/** + * Defines a sound that can be played in the application. + * The sound can either be an ambient track or a simple sound played in reaction to a user action. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic + */ +class Sound { + /** + * Does the sound loop after it finishes playing once. + */ + get loop() { + return this._loop; + } + set loop(value) { + if (value === this._loop) { + return; + } + this._loop = value; + this.updateOptions({ loop: value }); + } + /** + * Gets the current time for the sound. + */ + get currentTime() { + if (this._htmlAudioElement) { + return this._htmlAudioElement.currentTime; + } + if (AbstractEngine.audioEngine?.audioContext && (this.isPlaying || this.isPaused)) { + // The `_currentTime` member is only updated when the sound is paused. Add the time since the last start + // to get the actual current time. + const timeSinceLastStart = this.isPaused ? 0 : AbstractEngine.audioEngine.audioContext.currentTime - this._startTime; + return this._currentTime + timeSinceLastStart; + } + return 0; + } + /** + * Does this sound enables spatial sound. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound + */ + get spatialSound() { + return this._spatialSound; + } + /** + * Does this sound enables spatial sound. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound + */ + set spatialSound(newValue) { + if (newValue == this._spatialSound) { + return; + } + const wasPlaying = this.isPlaying; + this.pause(); + if (newValue) { + this._spatialSound = newValue; + this._updateSpatialParameters(); + } + else { + this._disableSpatialSound(); + } + if (wasPlaying) { + this.play(); + } + } + /** + * Create a sound and attach it to a scene + * @param name Name of your sound + * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams and AudioBuffers + * @param scene defines the scene the sound belongs to + * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played + * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming + */ + constructor(name, urlOrArrayBuffer, scene, readyToPlayCallback = null, options) { + /** + * Does the sound autoplay once loaded. + */ + this.autoplay = false; + this._loop = false; + /** + * Does the sound use a custom attenuation curve to simulate the falloff + * happening when the source gets further away from the camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-your-own-custom-attenuation-function + */ + this.useCustomAttenuation = false; + /** + * Is this sound currently played. + */ + this.isPlaying = false; + /** + * Is this sound currently paused. + */ + this.isPaused = false; + /** + * Define the reference distance the sound should be heard perfectly. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound + */ + this.refDistance = 1; + /** + * Define the roll off factor of spatial sounds. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound + */ + this.rolloffFactor = 1; + /** + * Define the max distance the sound should be heard (intensity just became 0 at this point). + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound + */ + this.maxDistance = 100; + /** + * Define the distance attenuation model the sound will follow. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound + */ + this.distanceModel = "linear"; + /** + * Gets or sets an object used to store user defined information for the sound. + */ + this.metadata = null; + /** + * Observable event when the current playing sound finishes. + */ + this.onEndedObservable = new Observable(); + this._spatialSound = false; + this._panningModel = "equalpower"; + this._playbackRate = 1; + this._streaming = false; + this._startTime = 0; + this._currentTime = 0; + this._position = Vector3.Zero(); + this._localDirection = new Vector3(1, 0, 0); + this._volume = 1; + this._isReadyToPlay = false; + this._isDirectional = false; + // Used if you'd like to create a directional sound. + // If not set, the sound will be omnidirectional + this._coneInnerAngle = 360; + this._coneOuterAngle = 360; + this._coneOuterGain = 0; + this._isOutputConnected = false; + this._urlType = "Unknown"; + this.name = name; + scene = scene || EngineStore.LastCreatedScene; + if (!scene) { + return; + } + this._scene = scene; + Sound._SceneComponentInitialization(scene); + this._readyToPlayCallback = readyToPlayCallback; + // Default custom attenuation function is a linear attenuation + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._customAttenuationFunction = (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) => { + if (currentDistance < maxDistance) { + return currentVolume * (1 - currentDistance / maxDistance); + } + else { + return 0; + } + }; + if (options) { + this.autoplay = options.autoplay || false; + this._loop = options.loop || false; + // if volume === 0, we need another way to check this option + if (options.volume !== undefined) { + this._volume = options.volume; + } + this._spatialSound = options.spatialSound ?? false; + this.maxDistance = options.maxDistance ?? 100; + this.useCustomAttenuation = options.useCustomAttenuation ?? false; + this.rolloffFactor = options.rolloffFactor || 1; + this.refDistance = options.refDistance || 1; + this.distanceModel = options.distanceModel || "linear"; + this._playbackRate = options.playbackRate || 1; + this._streaming = options.streaming ?? false; + this._length = options.length; + this._offset = options.offset; + } + if (AbstractEngine.audioEngine?.canUseWebAudio && AbstractEngine.audioEngine.audioContext) { + this._soundGain = AbstractEngine.audioEngine.audioContext.createGain(); + this._soundGain.gain.value = this._volume; + this._inputAudioNode = this._soundGain; + this._outputAudioNode = this._soundGain; + if (this._spatialSound) { + this._createSpatialParameters(); + } + this._scene.mainSoundTrack.addSound(this); + let validParameter = true; + // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound + if (urlOrArrayBuffer) { + try { + if (typeof urlOrArrayBuffer === "string") { + this._urlType = "String"; + this._url = urlOrArrayBuffer; + } + else if (urlOrArrayBuffer instanceof ArrayBuffer) { + this._urlType = "ArrayBuffer"; + } + else if (urlOrArrayBuffer instanceof HTMLMediaElement) { + this._urlType = "MediaElement"; + } + else if (urlOrArrayBuffer instanceof MediaStream) { + this._urlType = "MediaStream"; + } + else if (urlOrArrayBuffer instanceof AudioBuffer) { + this._urlType = "AudioBuffer"; + } + else if (Array.isArray(urlOrArrayBuffer)) { + this._urlType = "Array"; + } + let urls = []; + let codecSupportedFound = false; + switch (this._urlType) { + case "MediaElement": + this._streaming = true; + this._isReadyToPlay = true; + this._streamingSource = AbstractEngine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer); + if (this.autoplay) { + this.play(0, this._offset, this._length); + } + if (this._readyToPlayCallback) { + this._readyToPlayCallback(); + } + break; + case "MediaStream": + this._streaming = true; + this._isReadyToPlay = true; + this._streamingSource = AbstractEngine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer); + if (this.autoplay) { + this.play(0, this._offset, this._length); + } + if (this._readyToPlayCallback) { + this._readyToPlayCallback(); + } + break; + case "ArrayBuffer": + if (urlOrArrayBuffer.byteLength > 0) { + codecSupportedFound = true; + this._soundLoaded(urlOrArrayBuffer); + } + break; + case "AudioBuffer": + this._audioBufferLoaded(urlOrArrayBuffer); + break; + case "String": + urls.push(urlOrArrayBuffer); + // eslint-disable-next-line no-fallthrough + case "Array": + if (urls.length === 0) { + urls = urlOrArrayBuffer; + } + // If we found a supported format, we load it immediately and stop the loop + for (let i = 0; i < urls.length; i++) { + const url = urls[i]; + codecSupportedFound = + (options && options.skipCodecCheck) || + (url.indexOf(".mp3", url.length - 4) !== -1 && AbstractEngine.audioEngine.isMP3supported) || + (url.indexOf(".ogg", url.length - 4) !== -1 && AbstractEngine.audioEngine.isOGGsupported) || + url.indexOf(".wav", url.length - 4) !== -1 || + url.indexOf(".m4a", url.length - 4) !== -1 || + url.indexOf(".mp4", url.length - 4) !== -1 || + url.indexOf("blob:") !== -1; + if (codecSupportedFound) { + // Loading sound + if (!this._streaming) { + this._scene._loadFile(url, (data) => { + this._soundLoaded(data); + }, undefined, true, true, (exception) => { + if (exception) { + Logger.Error("XHR " + exception.status + " error on: " + url + "."); + } + Logger.Error("Sound creation aborted."); + this._scene.mainSoundTrack.removeSound(this); + }); + } + // Streaming sound using HTML5 Audio tag + else { + this._htmlAudioElement = new Audio(url); + this._htmlAudioElement.controls = false; + this._htmlAudioElement.loop = this.loop; + Tools.SetCorsBehavior(url, this._htmlAudioElement); + this._htmlAudioElement.preload = "auto"; + this._htmlAudioElement.addEventListener("canplaythrough", () => { + this._isReadyToPlay = true; + if (this.autoplay) { + this.play(0, this._offset, this._length); + } + if (this._readyToPlayCallback) { + this._readyToPlayCallback(); + } + }, { once: true }); + document.body.appendChild(this._htmlAudioElement); + this._htmlAudioElement.load(); + } + break; + } + } + break; + default: + validParameter = false; + break; + } + if (!validParameter) { + Logger.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound."); + } + else { + if (!codecSupportedFound) { + this._isReadyToPlay = true; + // Simulating a ready to play event to avoid breaking code path + if (this._readyToPlayCallback) { + setTimeout(() => { + if (this._readyToPlayCallback) { + this._readyToPlayCallback(); + } + }, 1000); + } + } + } + } + catch (ex) { + Logger.Error("Unexpected error. Sound creation aborted."); + this._scene.mainSoundTrack.removeSound(this); + } + } + } + else { + // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers + this._scene.mainSoundTrack.addSound(this); + if (AbstractEngine.audioEngine && !AbstractEngine.audioEngine.WarnedWebAudioUnsupported) { + Logger.Error("Web Audio is not supported by your browser."); + AbstractEngine.audioEngine.WarnedWebAudioUnsupported = true; + } + // Simulating a ready to play event to avoid breaking code for non web audio browsers + if (this._readyToPlayCallback) { + setTimeout(() => { + if (this._readyToPlayCallback) { + this._readyToPlayCallback(); + } + }, 1000); + } + } + } + /** + * Release the sound and its associated resources + */ + dispose() { + if (AbstractEngine.audioEngine?.canUseWebAudio) { + if (this.isPlaying) { + this.stop(); + } + this._isReadyToPlay = false; + if (this.soundTrackId === -1) { + this._scene.mainSoundTrack.removeSound(this); + } + else if (this._scene.soundTracks) { + this._scene.soundTracks[this.soundTrackId].removeSound(this); + } + if (this._soundGain) { + this._soundGain.disconnect(); + this._soundGain = null; + } + if (this._soundPanner) { + this._soundPanner.disconnect(); + this._soundPanner = null; + } + if (this._soundSource) { + this._soundSource.disconnect(); + this._soundSource = null; + } + this._audioBuffer = null; + if (this._htmlAudioElement) { + this._htmlAudioElement.pause(); + this._htmlAudioElement.src = ""; + document.body.removeChild(this._htmlAudioElement); + this._htmlAudioElement = null; + } + if (this._streamingSource) { + this._streamingSource.disconnect(); + this._streamingSource = null; + } + if (this._connectedTransformNode && this._registerFunc) { + this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); + this._connectedTransformNode = null; + } + this._clearTimeoutsAndObservers(); + } + } + /** + * Gets if the sounds is ready to be played or not. + * @returns true if ready, otherwise false + */ + isReady() { + return this._isReadyToPlay; + } + /** + * Get the current class name. + * @returns current class name + */ + getClassName() { + return "Sound"; + } + _audioBufferLoaded(buffer) { + if (!AbstractEngine.audioEngine?.audioContext) { + return; + } + this._audioBuffer = buffer; + this._isReadyToPlay = true; + if (this.autoplay) { + this.play(0, this._offset, this._length); + } + if (this._readyToPlayCallback) { + this._readyToPlayCallback(); + } + } + _soundLoaded(audioData) { + if (!AbstractEngine.audioEngine?.audioContext) { + return; + } + AbstractEngine.audioEngine.audioContext.decodeAudioData(audioData, (buffer) => { + this._audioBufferLoaded(buffer); + }, (err) => { + Logger.Error("Error while decoding audio data for: " + this.name + " / Error: " + err); + }); + } + /** + * Sets the data of the sound from an audiobuffer + * @param audioBuffer The audioBuffer containing the data + */ + setAudioBuffer(audioBuffer) { + if (AbstractEngine.audioEngine?.canUseWebAudio) { + this._audioBuffer = audioBuffer; + this._isReadyToPlay = true; + } + } + /** + * Updates the current sounds options such as maxdistance, loop... + * @param options A JSON object containing values named as the object properties + */ + updateOptions(options) { + if (options) { + this.loop = options.loop ?? this.loop; + this.maxDistance = options.maxDistance ?? this.maxDistance; + this.useCustomAttenuation = options.useCustomAttenuation ?? this.useCustomAttenuation; + this.rolloffFactor = options.rolloffFactor ?? this.rolloffFactor; + this.refDistance = options.refDistance ?? this.refDistance; + this.distanceModel = options.distanceModel ?? this.distanceModel; + this._playbackRate = options.playbackRate ?? this._playbackRate; + this._length = options.length ?? undefined; + this.spatialSound = options.spatialSound ?? this._spatialSound; + this._setOffset(options.offset ?? undefined); + this.setVolume(options.volume ?? this._volume); + this._updateSpatialParameters(); + if (this.isPlaying) { + if (this._streaming && this._htmlAudioElement) { + this._htmlAudioElement.playbackRate = this._playbackRate; + if (this._htmlAudioElement.loop !== this.loop) { + this._htmlAudioElement.loop = this.loop; + } + } + else { + if (this._soundSource) { + this._soundSource.playbackRate.value = this._playbackRate; + if (this._soundSource.loop !== this.loop) { + this._soundSource.loop = this.loop; + } + if (this._offset !== undefined && this._soundSource.loopStart !== this._offset) { + this._soundSource.loopStart = this._offset; + } + if (this._length !== undefined && this._length !== this._soundSource.loopEnd) { + this._soundSource.loopEnd = (this._offset | 0) + this._length; + } + } + } + } + } + } + _createSpatialParameters() { + if (AbstractEngine.audioEngine?.canUseWebAudio && AbstractEngine.audioEngine.audioContext) { + if (this._scene.headphone) { + this._panningModel = "HRTF"; + } + this._soundPanner = this._soundPanner ?? AbstractEngine.audioEngine.audioContext.createPanner(); + if (this._soundPanner && this._outputAudioNode) { + this._updateSpatialParameters(); + this._soundPanner.connect(this._outputAudioNode); + this._inputAudioNode = this._soundPanner; + } + } + } + _disableSpatialSound() { + if (!this._spatialSound) { + return; + } + this._inputAudioNode = this._soundGain; + this._soundPanner?.disconnect(); + this._soundPanner = null; + this._spatialSound = false; + } + _updateSpatialParameters() { + if (!this._spatialSound) { + return; + } + if (this._soundPanner) { + if (this.useCustomAttenuation) { + // Tricks to disable in a way embedded Web Audio attenuation + this._soundPanner.distanceModel = "linear"; + this._soundPanner.maxDistance = Number.MAX_VALUE; + this._soundPanner.refDistance = 1; + this._soundPanner.rolloffFactor = 1; + this._soundPanner.panningModel = this._panningModel; + } + else { + this._soundPanner.distanceModel = this.distanceModel; + this._soundPanner.maxDistance = this.maxDistance; + this._soundPanner.refDistance = this.refDistance; + this._soundPanner.rolloffFactor = this.rolloffFactor; + this._soundPanner.panningModel = this._panningModel; + } + } + else { + this._createSpatialParameters(); + } + } + /** + * Switch the panning model to HRTF: + * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound + */ + switchPanningModelToHRTF() { + this._panningModel = "HRTF"; + this._switchPanningModel(); + } + /** + * Switch the panning model to Equal Power: + * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound + */ + switchPanningModelToEqualPower() { + this._panningModel = "equalpower"; + this._switchPanningModel(); + } + _switchPanningModel() { + if (AbstractEngine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner) { + this._soundPanner.panningModel = this._panningModel; + } + } + /** + * Connect this sound to a sound track audio node like gain... + * @param soundTrackAudioNode the sound track audio node to connect to + */ + connectToSoundTrackAudioNode(soundTrackAudioNode) { + if (AbstractEngine.audioEngine?.canUseWebAudio && this._outputAudioNode) { + if (this._isOutputConnected) { + this._outputAudioNode.disconnect(); + } + this._outputAudioNode.connect(soundTrackAudioNode); + this._isOutputConnected = true; + } + } + /** + * Transform this sound into a directional source + * @param coneInnerAngle Size of the inner cone in degree + * @param coneOuterAngle Size of the outer cone in degree + * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0) + */ + setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) { + if (coneOuterAngle < coneInnerAngle) { + Logger.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."); + return; + } + this._coneInnerAngle = coneInnerAngle; + this._coneOuterAngle = coneOuterAngle; + this._coneOuterGain = coneOuterGain; + this._isDirectional = true; + if (this.isPlaying && this.loop) { + this.stop(); + this.play(0, this._offset, this._length); + } + } + /** + * Gets or sets the inner angle for the directional cone. + */ + get directionalConeInnerAngle() { + return this._coneInnerAngle; + } + /** + * Gets or sets the inner angle for the directional cone. + */ + set directionalConeInnerAngle(value) { + if (value != this._coneInnerAngle) { + if (this._coneOuterAngle < value) { + Logger.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle."); + return; + } + this._coneInnerAngle = value; + if (AbstractEngine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner) { + this._soundPanner.coneInnerAngle = this._coneInnerAngle; + } + } + } + /** + * Gets or sets the outer angle for the directional cone. + */ + get directionalConeOuterAngle() { + return this._coneOuterAngle; + } + /** + * Gets or sets the outer angle for the directional cone. + */ + set directionalConeOuterAngle(value) { + if (value != this._coneOuterAngle) { + if (value < this._coneInnerAngle) { + Logger.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle."); + return; + } + this._coneOuterAngle = value; + if (AbstractEngine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner) { + this._soundPanner.coneOuterAngle = this._coneOuterAngle; + } + } + } + /** + * Sets the position of the emitter if spatial sound is enabled + * @param newPosition Defines the new position + */ + setPosition(newPosition) { + if (newPosition.equals(this._position)) { + return; + } + this._position.copyFrom(newPosition); + if (AbstractEngine.audioEngine?.canUseWebAudio && + this._spatialSound && + this._soundPanner && + !isNaN(this._position.x) && + !isNaN(this._position.y) && + !isNaN(this._position.z)) { + this._soundPanner.positionX.value = this._position.x; + this._soundPanner.positionY.value = this._position.y; + this._soundPanner.positionZ.value = this._position.z; + } + } + /** + * Sets the local direction of the emitter if spatial sound is enabled + * @param newLocalDirection Defines the new local direction + */ + setLocalDirectionToMesh(newLocalDirection) { + this._localDirection = newLocalDirection; + if (AbstractEngine.audioEngine?.canUseWebAudio && this._connectedTransformNode && this.isPlaying) { + this._updateDirection(); + } + } + _updateDirection() { + if (!this._connectedTransformNode || !this._soundPanner) { + return; + } + const mat = this._connectedTransformNode.getWorldMatrix(); + const direction = Vector3.TransformNormal(this._localDirection, mat); + direction.normalize(); + this._soundPanner.orientationX.value = direction.x; + this._soundPanner.orientationY.value = direction.y; + this._soundPanner.orientationZ.value = direction.z; + } + /** @internal */ + updateDistanceFromListener() { + if (AbstractEngine.audioEngine?.canUseWebAudio && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) { + const distance = this._scene.audioListenerPositionProvider + ? this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length() + : this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera); + this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor); + } + } + /** + * Sets a new custom attenuation function for the sound. + * @param callback Defines the function used for the attenuation + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-your-own-custom-attenuation-function + */ + setAttenuationFunction(callback) { + this._customAttenuationFunction = callback; + } + /** + * Play the sound + * @param time (optional) Start the sound after X seconds. Start immediately (0) by default. + * @param offset (optional) Start the sound at a specific time in seconds + * @param length (optional) Sound duration (in seconds) + */ + play(time, offset, length) { + if (this._isReadyToPlay && this._scene.audioEnabled && AbstractEngine.audioEngine?.audioContext) { + try { + this._clearTimeoutsAndObservers(); + let startTime = time ? AbstractEngine.audioEngine?.audioContext.currentTime + time : AbstractEngine.audioEngine?.audioContext.currentTime; + if (!this._soundSource || !this._streamingSource) { + if (this._spatialSound && this._soundPanner) { + if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) { + this._soundPanner.positionX.value = this._position.x; + this._soundPanner.positionY.value = this._position.y; + this._soundPanner.positionZ.value = this._position.z; + } + if (this._isDirectional) { + this._soundPanner.coneInnerAngle = this._coneInnerAngle; + this._soundPanner.coneOuterAngle = this._coneOuterAngle; + this._soundPanner.coneOuterGain = this._coneOuterGain; + if (this._connectedTransformNode) { + this._updateDirection(); + } + else { + this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z); + } + } + } + } + if (this._streaming) { + if (!this._streamingSource && this._htmlAudioElement) { + this._streamingSource = AbstractEngine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement); + this._htmlAudioElement.onended = () => { + this._onended(); + }; + this._htmlAudioElement.playbackRate = this._playbackRate; + } + if (this._streamingSource) { + this._streamingSource.disconnect(); + if (this._inputAudioNode) { + this._streamingSource.connect(this._inputAudioNode); + } + } + if (this._htmlAudioElement) { + // required to manage properly the new suspended default state of Chrome + // When the option 'streaming: true' is used, we need first to wait for + // the audio engine to be unlocked by a user gesture before trying to play + // an HTML Audio element + const tryToPlay = () => { + if (AbstractEngine.audioEngine?.unlocked) { + if (!this._htmlAudioElement) { + return; + } + this._htmlAudioElement.currentTime = offset ?? 0; + const playPromise = this._htmlAudioElement.play(); + // In browsers that don’t yet support this functionality, + // playPromise won’t be defined. + if (playPromise !== undefined) { + playPromise.catch(() => { + // Automatic playback failed. + // Waiting for the audio engine to be unlocked by user click on unmute + AbstractEngine.audioEngine?.lock(); + if (this.loop || this.autoplay) { + this._audioUnlockedObserver = AbstractEngine.audioEngine?.onAudioUnlockedObservable.addOnce(() => { + tryToPlay(); + }); + } + }); + } + } + else { + if (this.loop || this.autoplay) { + this._audioUnlockedObserver = AbstractEngine.audioEngine?.onAudioUnlockedObservable.addOnce(() => { + tryToPlay(); + }); + } + } + }; + tryToPlay(); + } + } + else { + const tryToPlay = () => { + if (AbstractEngine.audioEngine?.audioContext) { + length = length || this._length; + if (offset !== undefined) { + this._setOffset(offset); + } + if (this._soundSource) { + const oldSource = this._soundSource; + oldSource.onended = () => { + oldSource.disconnect(); + }; + } + this._soundSource = AbstractEngine.audioEngine?.audioContext.createBufferSource(); + if (this._soundSource && this._inputAudioNode) { + this._soundSource.buffer = this._audioBuffer; + this._soundSource.connect(this._inputAudioNode); + this._soundSource.loop = this.loop; + if (offset !== undefined) { + this._soundSource.loopStart = offset; + } + if (length !== undefined) { + this._soundSource.loopEnd = (offset | 0) + length; + } + this._soundSource.playbackRate.value = this._playbackRate; + this._soundSource.onended = () => { + this._onended(); + }; + startTime = time ? AbstractEngine.audioEngine?.audioContext.currentTime + time : AbstractEngine.audioEngine.audioContext.currentTime; + const actualOffset = ((this.isPaused ? this.currentTime : 0) + (this._offset ?? 0)) % this._soundSource.buffer.duration; + this._soundSource.start(startTime, actualOffset, this.loop ? undefined : length); + } + } + }; + if (AbstractEngine.audioEngine?.audioContext.state === "suspended") { + // Wait a bit for FF as context seems late to be ready. + this._tryToPlayTimeout = setTimeout(() => { + if (AbstractEngine.audioEngine?.audioContext.state === "suspended") { + // Automatic playback failed. + // Waiting for the audio engine to be unlocked by user click on unmute + AbstractEngine.audioEngine.lock(); + if (this.loop || this.autoplay) { + this._audioUnlockedObserver = AbstractEngine.audioEngine.onAudioUnlockedObservable.addOnce(() => { + tryToPlay(); + }); + } + } + else { + tryToPlay(); + } + }, 500); + } + else { + tryToPlay(); + } + } + this._startTime = startTime; + this.isPlaying = true; + this.isPaused = false; + } + catch (ex) { + Logger.Error("Error while trying to play audio: " + this.name + ", " + ex.message); + } + } + } + _onended() { + this.isPlaying = false; + this._startTime = 0; + this._currentTime = 0; + if (this.onended) { + this.onended(); + } + this.onEndedObservable.notifyObservers(this); + } + /** + * Stop the sound + * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. + */ + stop(time) { + if (this.isPlaying) { + this._clearTimeoutsAndObservers(); + if (this._streaming) { + if (this._htmlAudioElement) { + this._htmlAudioElement.pause(); + // Test needed for Firefox or it will generate an Invalid State Error + if (this._htmlAudioElement.currentTime > 0) { + this._htmlAudioElement.currentTime = 0; + } + } + else { + this._streamingSource?.disconnect(); + } + this.isPlaying = false; + } + else if (AbstractEngine.audioEngine?.audioContext && this._soundSource) { + const stopTime = time ? AbstractEngine.audioEngine.audioContext.currentTime + time : undefined; + this._soundSource.onended = () => { + this.isPlaying = false; + this.isPaused = false; + this._startTime = 0; + this._currentTime = 0; + if (this._soundSource) { + this._soundSource.onended = () => void 0; + } + this._onended(); + }; + this._soundSource.stop(stopTime); + } + else { + this.isPlaying = false; + } + } + else if (this.isPaused) { + this.isPaused = false; + this._startTime = 0; + this._currentTime = 0; + } + } + /** + * Put the sound in pause + */ + pause() { + if (this.isPlaying) { + this._clearTimeoutsAndObservers(); + if (this._streaming) { + if (this._htmlAudioElement) { + this._htmlAudioElement.pause(); + } + else { + this._streamingSource?.disconnect(); + } + this.isPlaying = false; + this.isPaused = true; + } + else if (AbstractEngine.audioEngine?.audioContext && this._soundSource) { + this._soundSource.onended = () => void 0; + this._soundSource.stop(); + this.isPlaying = false; + this.isPaused = true; + this._currentTime += AbstractEngine.audioEngine.audioContext.currentTime - this._startTime; + } + } + } + /** + * Sets a dedicated volume for this sounds + * @param newVolume Define the new volume of the sound + * @param time Define time for gradual change to new volume + */ + setVolume(newVolume, time) { + if (AbstractEngine.audioEngine?.canUseWebAudio && this._soundGain) { + if (time && AbstractEngine.audioEngine.audioContext) { + this._soundGain.gain.cancelScheduledValues(AbstractEngine.audioEngine.audioContext.currentTime); + this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, AbstractEngine.audioEngine.audioContext.currentTime); + this._soundGain.gain.linearRampToValueAtTime(newVolume, AbstractEngine.audioEngine.audioContext.currentTime + time); + } + else { + this._soundGain.gain.value = newVolume; + } + } + this._volume = newVolume; + } + /** + * Set the sound play back rate + * @param newPlaybackRate Define the playback rate the sound should be played at + */ + setPlaybackRate(newPlaybackRate) { + this._playbackRate = newPlaybackRate; + if (this.isPlaying) { + if (this._streaming && this._htmlAudioElement) { + this._htmlAudioElement.playbackRate = this._playbackRate; + } + else if (this._soundSource) { + this._soundSource.playbackRate.value = this._playbackRate; + } + } + } + /** + * Gets the sound play back rate. + * @returns the play back rate of the sound + */ + getPlaybackRate() { + return this._playbackRate; + } + /** + * Gets the volume of the sound. + * @returns the volume of the sound + */ + getVolume() { + return this._volume; + } + /** + * Attach the sound to a dedicated mesh + * @param transformNode The transform node to connect the sound with + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#attaching-a-sound-to-a-mesh + */ + attachToMesh(transformNode) { + if (this._connectedTransformNode && this._registerFunc) { + this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); + this._registerFunc = null; + } + this._connectedTransformNode = transformNode; + if (!this._spatialSound) { + this._spatialSound = true; + this._createSpatialParameters(); + if (this.isPlaying && this.loop) { + this.stop(); + this.play(0, this._offset, this._length); + } + } + this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode); + this._registerFunc = (transformNode) => this._onRegisterAfterWorldMatrixUpdate(transformNode); + this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc); + } + /** + * Detach the sound from the previously attached mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#attaching-a-sound-to-a-mesh + */ + detachFromMesh() { + if (this._connectedTransformNode && this._registerFunc) { + this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); + this._registerFunc = null; + this._connectedTransformNode = null; + } + } + _onRegisterAfterWorldMatrixUpdate(node) { + if (!node.getBoundingInfo) { + this.setPosition(node.absolutePosition); + } + else { + const mesh = node; + const boundingInfo = mesh.getBoundingInfo(); + this.setPosition(boundingInfo.boundingSphere.centerWorld); + } + if (AbstractEngine.audioEngine?.canUseWebAudio && this._isDirectional && this.isPlaying) { + this._updateDirection(); + } + } + /** + * Clone the current sound in the scene. + * @returns the new sound clone + */ + clone() { + if (!this._streaming) { + const setBufferAndRun = () => { + _retryWithInterval(() => this._isReadyToPlay, () => { + clonedSound._audioBuffer = this.getAudioBuffer(); + clonedSound._isReadyToPlay = true; + if (clonedSound.autoplay) { + clonedSound.play(0, this._offset, this._length); + } + }, undefined, 300); + }; + const currentOptions = { + autoplay: this.autoplay, + loop: this.loop, + volume: this._volume, + spatialSound: this._spatialSound, + maxDistance: this.maxDistance, + useCustomAttenuation: this.useCustomAttenuation, + rolloffFactor: this.rolloffFactor, + refDistance: this.refDistance, + distanceModel: this.distanceModel, + }; + const clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions); + if (this.useCustomAttenuation) { + clonedSound.setAttenuationFunction(this._customAttenuationFunction); + } + clonedSound.setPosition(this._position); + clonedSound.setPlaybackRate(this._playbackRate); + setBufferAndRun(); + return clonedSound; + } + // Can't clone a streaming sound + else { + return null; + } + } + /** + * Gets the current underlying audio buffer containing the data + * @returns the audio buffer + */ + getAudioBuffer() { + return this._audioBuffer; + } + /** + * Gets the WebAudio AudioBufferSourceNode, lets you keep track of and stop instances of this Sound. + * @returns the source node + */ + getSoundSource() { + return this._soundSource; + } + /** + * Gets the WebAudio GainNode, gives you precise control over the gain of instances of this Sound. + * @returns the gain node + */ + getSoundGain() { + return this._soundGain; + } + /** + * Serializes the Sound in a JSON representation + * @returns the JSON representation of the sound + */ + serialize() { + const serializationObject = { + name: this.name, + url: this._url, + autoplay: this.autoplay, + loop: this.loop, + volume: this._volume, + spatialSound: this._spatialSound, + maxDistance: this.maxDistance, + rolloffFactor: this.rolloffFactor, + refDistance: this.refDistance, + distanceModel: this.distanceModel, + playbackRate: this._playbackRate, + panningModel: this._panningModel, + soundTrackId: this.soundTrackId, + metadata: this.metadata, + }; + if (this._spatialSound) { + if (this._connectedTransformNode) { + serializationObject.connectedMeshId = this._connectedTransformNode.id; + } + serializationObject.position = this._position.asArray(); + serializationObject.refDistance = this.refDistance; + serializationObject.distanceModel = this.distanceModel; + serializationObject.isDirectional = this._isDirectional; + serializationObject.localDirectionToMesh = this._localDirection.asArray(); + serializationObject.coneInnerAngle = this._coneInnerAngle; + serializationObject.coneOuterAngle = this._coneOuterAngle; + serializationObject.coneOuterGain = this._coneOuterGain; + } + return serializationObject; + } + /** + * Parse a JSON representation of a sound to instantiate in a given scene + * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method) + * @param scene Define the scene the new parsed sound should be created in + * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies + * @param sourceSound Define a sound place holder if do not need to instantiate a new one + * @returns the newly parsed sound + */ + static Parse(parsedSound, scene, rootUrl, sourceSound) { + const soundName = parsedSound.name; + let soundUrl; + if (parsedSound.url) { + soundUrl = rootUrl + parsedSound.url; + } + else { + soundUrl = rootUrl + soundName; + } + const options = { + autoplay: parsedSound.autoplay, + loop: parsedSound.loop, + volume: parsedSound.volume, + spatialSound: parsedSound.spatialSound, + maxDistance: parsedSound.maxDistance, + rolloffFactor: parsedSound.rolloffFactor, + refDistance: parsedSound.refDistance, + distanceModel: parsedSound.distanceModel, + playbackRate: parsedSound.playbackRate, + }; + let newSound; + if (!sourceSound) { + newSound = new Sound(soundName, soundUrl, scene, () => { + scene.removePendingData(newSound); + }, options); + scene.addPendingData(newSound); + } + else { + const setBufferAndRun = () => { + _retryWithInterval(() => sourceSound._isReadyToPlay, () => { + newSound._audioBuffer = sourceSound.getAudioBuffer(); + newSound._isReadyToPlay = true; + if (newSound.autoplay) { + newSound.play(0, newSound._offset, newSound._length); + } + }, undefined, 300); + }; + newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options); + setBufferAndRun(); + } + if (parsedSound.position) { + const soundPosition = Vector3.FromArray(parsedSound.position); + newSound.setPosition(soundPosition); + } + if (parsedSound.isDirectional) { + newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0); + if (parsedSound.localDirectionToMesh) { + const localDirectionToMesh = Vector3.FromArray(parsedSound.localDirectionToMesh); + newSound.setLocalDirectionToMesh(localDirectionToMesh); + } + } + if (parsedSound.connectedMeshId) { + const connectedMesh = scene.getMeshById(parsedSound.connectedMeshId); + if (connectedMesh) { + newSound.attachToMesh(connectedMesh); + } + } + if (parsedSound.metadata) { + newSound.metadata = parsedSound.metadata; + } + return newSound; + } + _setOffset(value) { + if (this._offset === value) { + return; + } + if (this.isPaused) { + this.stop(); + this.isPaused = false; + } + this._offset = value; + } + _clearTimeoutsAndObservers() { + if (this._tryToPlayTimeout) { + clearTimeout(this._tryToPlayTimeout); + this._tryToPlayTimeout = null; + } + if (this._audioUnlockedObserver) { + AbstractEngine.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver); + this._audioUnlockedObserver = null; + } + } +} +/** + * @internal + */ +Sound._SceneComponentInitialization = (_) => { + throw _WarnImport("AudioSceneComponent"); +}; +// Register Class Name +RegisterClass("BABYLON.Sound", Sound); + +/** + * Wraps one or more Sound objects and selects one with random weight for playback. + */ +class WeightedSound { + /** + * Creates a new WeightedSound from the list of sounds given. + * @param loop When true a Sound will be selected and played when the current playing Sound completes. + * @param sounds Array of Sounds that will be selected from. + * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1 + */ + constructor(loop, sounds, weights) { + /** When true a Sound will be selected and played when the current playing Sound completes. */ + this.loop = false; + this._coneInnerAngle = 360; + this._coneOuterAngle = 360; + this._volume = 1; + /** A Sound is currently playing. */ + this.isPlaying = false; + /** A Sound is currently paused. */ + this.isPaused = false; + this._sounds = []; + this._weights = []; + if (sounds.length !== weights.length) { + throw new Error("Sounds length does not equal weights length"); + } + this.loop = loop; + this._weights = weights; + // Normalize the weights + let weightSum = 0; + for (const weight of weights) { + weightSum += weight; + } + const invWeightSum = weightSum > 0 ? 1 / weightSum : 0; + for (let i = 0; i < this._weights.length; i++) { + this._weights[i] *= invWeightSum; + } + this._sounds = sounds; + for (const sound of this._sounds) { + sound.onEndedObservable.add(() => { + this._onended(); + }); + } + } + /** + * The size of cone in degrees for a directional sound in which there will be no attenuation. + */ + get directionalConeInnerAngle() { + return this._coneInnerAngle; + } + /** + * The size of cone in degrees for a directional sound in which there will be no attenuation. + */ + set directionalConeInnerAngle(value) { + if (value !== this._coneInnerAngle) { + if (this._coneOuterAngle < value) { + Logger.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle."); + return; + } + this._coneInnerAngle = value; + for (const sound of this._sounds) { + sound.directionalConeInnerAngle = value; + } + } + } + /** + * Size of cone in degrees for a directional sound outside of which there will be no sound. + * Listener angles between innerAngle and outerAngle will falloff linearly. + */ + get directionalConeOuterAngle() { + return this._coneOuterAngle; + } + /** + * Size of cone in degrees for a directional sound outside of which there will be no sound. + * Listener angles between innerAngle and outerAngle will falloff linearly. + */ + set directionalConeOuterAngle(value) { + if (value !== this._coneOuterAngle) { + if (value < this._coneInnerAngle) { + Logger.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle."); + return; + } + this._coneOuterAngle = value; + for (const sound of this._sounds) { + sound.directionalConeOuterAngle = value; + } + } + } + /** + * Playback volume. + */ + get volume() { + return this._volume; + } + /** + * Playback volume. + */ + set volume(value) { + if (value !== this._volume) { + for (const sound of this._sounds) { + sound.setVolume(value); + } + } + } + _onended() { + if (this._currentIndex !== undefined) { + this._sounds[this._currentIndex].autoplay = false; + } + if (this.loop && this.isPlaying) { + this.play(); + } + else { + this.isPlaying = false; + } + } + /** + * Suspend playback + */ + pause() { + if (this.isPlaying) { + this.isPaused = true; + if (this._currentIndex !== undefined) { + this._sounds[this._currentIndex].pause(); + } + } + } + /** + * Stop playback + */ + stop() { + this.isPlaying = false; + if (this._currentIndex !== undefined) { + this._sounds[this._currentIndex].stop(); + } + } + /** + * Start playback. + * @param startOffset Position the clip head at a specific time in seconds. + */ + play(startOffset) { + if (!this.isPaused) { + this.stop(); + const randomValue = Math.random(); + let total = 0; + for (let i = 0; i < this._weights.length; i++) { + total += this._weights[i]; + if (randomValue <= total) { + this._currentIndex = i; + break; + } + } + } + const sound = this._sounds[this._currentIndex ?? 0]; + if (sound.isReady()) { + sound.play(0, this.isPaused ? undefined : startOffset); + } + else { + sound.autoplay = true; + } + this.isPlaying = true; + this.isPaused = false; + } +} + +/** + * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds. + * It will be also used in a future release to apply effects on a specific track. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-sound-tracks + */ +class SoundTrack { + /** + * Creates a new sound track. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-sound-tracks + * @param scene Define the scene the sound track belongs to + * @param options + */ + constructor(scene, options = {}) { + /** + * The unique identifier of the sound track in the scene. + */ + this.id = -1; + this._isInitialized = false; + scene = scene || EngineStore.LastCreatedScene; + if (!scene) { + return; + } + this._scene = scene; + this.soundCollection = []; + this._options = options; + if (!this._options.mainTrack && this._scene.soundTracks) { + this._scene.soundTracks.push(this); + this.id = this._scene.soundTracks.length - 1; + } + } + _initializeSoundTrackAudioGraph() { + if (AbstractEngine.audioEngine?.canUseWebAudio && AbstractEngine.audioEngine.audioContext) { + this._outputAudioNode = AbstractEngine.audioEngine.audioContext.createGain(); + this._outputAudioNode.connect(AbstractEngine.audioEngine.masterGain); + if (this._options) { + if (this._options.volume) { + this._outputAudioNode.gain.value = this._options.volume; + } + } + this._isInitialized = true; + } + } + /** + * Release the sound track and its associated resources + */ + dispose() { + if (AbstractEngine.audioEngine && AbstractEngine.audioEngine.canUseWebAudio) { + if (this._connectedAnalyser) { + this._connectedAnalyser.stopDebugCanvas(); + } + while (this.soundCollection.length) { + this.soundCollection[0].dispose(); + } + if (this._outputAudioNode) { + this._outputAudioNode.disconnect(); + } + this._outputAudioNode = null; + } + } + /** + * Adds a sound to this sound track + * @param sound define the sound to add + * @ignoreNaming + */ + addSound(sound) { + if (!this._isInitialized) { + this._initializeSoundTrackAudioGraph(); + } + if (AbstractEngine.audioEngine?.canUseWebAudio && this._outputAudioNode) { + sound.connectToSoundTrackAudioNode(this._outputAudioNode); + } + if (sound.soundTrackId !== undefined) { + if (sound.soundTrackId === -1) { + this._scene.mainSoundTrack.removeSound(sound); + } + else if (this._scene.soundTracks) { + this._scene.soundTracks[sound.soundTrackId].removeSound(sound); + } + } + this.soundCollection.push(sound); + sound.soundTrackId = this.id; + } + /** + * Removes a sound to this sound track + * @param sound define the sound to remove + * @ignoreNaming + */ + removeSound(sound) { + const index = this.soundCollection.indexOf(sound); + if (index !== -1) { + this.soundCollection.splice(index, 1); + } + } + /** + * Set a global volume for the full sound track. + * @param newVolume Define the new volume of the sound track + */ + setVolume(newVolume) { + if (AbstractEngine.audioEngine?.canUseWebAudio && this._outputAudioNode) { + this._outputAudioNode.gain.value = newVolume; + } + } + /** + * Switch the panning model to HRTF: + * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound + */ + switchPanningModelToHRTF() { + if (AbstractEngine.audioEngine?.canUseWebAudio) { + for (let i = 0; i < this.soundCollection.length; i++) { + this.soundCollection[i].switchPanningModelToHRTF(); + } + } + } + /** + * Switch the panning model to Equal Power: + * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound + */ + switchPanningModelToEqualPower() { + if (AbstractEngine.audioEngine?.canUseWebAudio) { + for (let i = 0; i < this.soundCollection.length; i++) { + this.soundCollection[i].switchPanningModelToEqualPower(); + } + } + } + /** + * Connect the sound track to an audio analyser allowing some amazing + * synchronization between the sounds/music and your visualization (VuMeter for instance). + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-the-analyser + * @param analyser The analyser to connect to the engine + */ + connectToAnalyser(analyser) { + if (this._connectedAnalyser) { + this._connectedAnalyser.stopDebugCanvas(); + } + this._connectedAnalyser = analyser; + if (AbstractEngine.audioEngine?.canUseWebAudio && this._outputAudioNode) { + this._outputAudioNode.disconnect(); + this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, AbstractEngine.audioEngine.masterGain); + } + } +} + +// Sets the default audio engine to Babylon.js +AbstractEngine.AudioEngineFactory = (hostElement, audioContext, audioDestination) => { + return new AudioEngine(hostElement, audioContext, audioDestination); +}; +/** + * This represents the default audio engine used in babylon. + * It is responsible to play, synchronize and analyse sounds throughout the application. + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic + */ +class AudioEngine { + /** + * Gets the current AudioContext if available. + */ + get audioContext() { + if (!this._audioContextInitialized) { + this._initializeAudioContext(); + } + return this._audioContext; + } + /** + * Instantiates a new audio engine. + * + * There should be only one per page as some browsers restrict the number + * of audio contexts you can create. + * @param hostElement defines the host element where to display the mute icon if necessary + * @param audioContext defines the audio context to be used by the audio engine + * @param audioDestination defines the audio destination node to be used by audio engine + */ + constructor(hostElement = null, audioContext = null, audioDestination = null) { + this._audioContext = null; + this._audioContextInitialized = false; + this._muteButton = null; + this._audioDestination = null; + /** + * Gets whether the current host supports Web Audio and thus could create AudioContexts. + */ + this.canUseWebAudio = false; + /** + * Defines if Babylon should emit a warning if WebAudio is not supported. + * @ignoreNaming + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + this.WarnedWebAudioUnsupported = false; + /** + * Gets whether or not mp3 are supported by your browser. + */ + this.isMP3supported = false; + /** + * Gets whether or not ogg are supported by your browser. + */ + this.isOGGsupported = false; + /** + * Gets whether audio has been unlocked on the device. + * Some Browsers have strong restrictions about Audio and won't autoplay unless + * a user interaction has happened. + */ + this.unlocked = false; + /** + * Defines if the audio engine relies on a custom unlocked button. + * In this case, the embedded button will not be displayed. + */ + this.useCustomUnlockedButton = false; + /** + * Event raised when audio has been unlocked on the browser. + */ + this.onAudioUnlockedObservable = new Observable(); + /** + * Event raised when audio has been locked on the browser. + */ + this.onAudioLockedObservable = new Observable(); + this._tryToRun = false; + this._onResize = () => { + this._moveButtonToTopLeft(); + }; + if (!IsWindowObjectExist()) { + return; + } + if (typeof window.AudioContext !== "undefined") { + this.canUseWebAudio = true; + } + const audioElem = document.createElement("audio"); + this._hostElement = hostElement; + this._audioContext = audioContext; + this._audioDestination = audioDestination; + try { + if (audioElem && + !!audioElem.canPlayType && + (audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, "") || audioElem.canPlayType("audio/mp3").replace(/^no$/, ""))) { + this.isMP3supported = true; + } + } + catch (e) { + // protect error during capability check. + } + try { + if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, "")) { + this.isOGGsupported = true; + } + } + catch (e) { + // protect error during capability check. + } + } + /** + * Flags the audio engine in Locked state. + * This happens due to new browser policies preventing audio to autoplay. + */ + lock() { + this._triggerSuspendedState(); + } + /** + * Unlocks the audio engine once a user action has been done on the dom. + * This is helpful to resume play once browser policies have been satisfied. + */ + unlock() { + if (this._audioContext?.state === "running") { + this._hideMuteButton(); + if (!this.unlocked) { + // Notify users that the audio stack is unlocked/unmuted + this.unlocked = true; + this.onAudioUnlockedObservable.notifyObservers(this); + } + return; + } + // On iOS, if the audio context resume request was sent from an event other than a `click` event, then + // the resume promise will never resolve and the only way to get the audio context unstuck is to + // suspend it and make another resume request. + if (this._tryToRun) { + this._audioContext?.suspend().then(() => { + this._tryToRun = false; + this._triggerRunningState(); + }); + } + else { + this._triggerRunningState(); + } + } + /** @internal */ + _resumeAudioContextOnStateChange() { + this._audioContext?.addEventListener("statechange", () => { + if (this.unlocked && this._audioContext?.state !== "running") { + this._resumeAudioContext(); + } + }, { + once: true, + passive: true, + signal: AbortSignal.timeout(3000), + }); + } + _resumeAudioContext() { + if (this._audioContext?.resume) { + return this._audioContext.resume(); + } + return Promise.resolve(); + } + _initializeAudioContext() { + try { + if (this.canUseWebAudio) { + if (!this._audioContext) { + this._audioContext = new AudioContext(); + } + // create a global volume gain node + this.masterGain = this._audioContext.createGain(); + this.masterGain.gain.value = 1; + if (!this._audioDestination) { + this._audioDestination = this._audioContext.destination; + } + this.masterGain.connect(this._audioDestination); + this._audioContextInitialized = true; + if (this._audioContext.state === "running") { + // Do not wait for the promise to unlock. + this._triggerRunningState(); + } + } + } + catch (e) { + this.canUseWebAudio = false; + Logger.Error("Web Audio: " + e.message); + } + } + _triggerRunningState() { + if (this._tryToRun) { + return; + } + this._tryToRun = true; + this._resumeAudioContext() + .then(() => { + this._tryToRun = false; + if (this._muteButton) { + this._hideMuteButton(); + } + // Notify users that the audio stack is unlocked/unmuted + this.unlocked = true; + this.onAudioUnlockedObservable.notifyObservers(this); + }) + .catch(() => { + this._tryToRun = false; + this.unlocked = false; + }); + } + _triggerSuspendedState() { + this.unlocked = false; + this.onAudioLockedObservable.notifyObservers(this); + this._displayMuteButton(); + } + _displayMuteButton() { + if (this.useCustomUnlockedButton || this._muteButton) { + return; + } + this._muteButton = document.createElement("BUTTON"); + this._muteButton.className = "babylonUnmuteIcon"; + this._muteButton.id = "babylonUnmuteIconBtn"; + this._muteButton.title = "Unmute"; + const imageUrl = !window.SVGSVGElement + ? "https://cdn.babylonjs.com/Assets/audio.png" + : "data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E"; + const css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(" + + imageUrl + + "); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }"; + const style = document.createElement("style"); + style.appendChild(document.createTextNode(css)); + document.getElementsByTagName("head")[0].appendChild(style); + document.body.appendChild(this._muteButton); + this._moveButtonToTopLeft(); + this._muteButton.addEventListener("touchend", () => { + this._triggerRunningState(); + }, true); + this._muteButton.addEventListener("click", () => { + this.unlock(); + }, true); + window.addEventListener("resize", this._onResize); + } + _moveButtonToTopLeft() { + if (this._hostElement && this._muteButton) { + this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px"; + this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px"; + } + } + _hideMuteButton() { + if (this._muteButton) { + document.body.removeChild(this._muteButton); + this._muteButton = null; + } + } + /** + * Destroy and release the resources associated with the audio context. + */ + dispose() { + if (this.canUseWebAudio && this._audioContextInitialized) { + if (this._connectedAnalyser && this._audioContext) { + this._connectedAnalyser.stopDebugCanvas(); + this._connectedAnalyser.dispose(); + this.masterGain.disconnect(); + this.masterGain.connect(this._audioContext.destination); + this._connectedAnalyser = null; + } + this.masterGain.gain.value = 1; + } + this.WarnedWebAudioUnsupported = false; + this._hideMuteButton(); + window.removeEventListener("resize", this._onResize); + this.onAudioUnlockedObservable.clear(); + this.onAudioLockedObservable.clear(); + } + /** + * Gets the global volume sets on the master gain. + * @returns the global volume if set or -1 otherwise + */ + getGlobalVolume() { + if (this.canUseWebAudio && this._audioContextInitialized) { + return this.masterGain.gain.value; + } + else { + return -1; + } + } + /** + * Sets the global volume of your experience (sets on the master gain). + * @param newVolume Defines the new global volume of the application + */ + setGlobalVolume(newVolume) { + if (this.canUseWebAudio && this._audioContextInitialized) { + this.masterGain.gain.value = newVolume; + } + } + /** + * Connect the audio engine to an audio analyser allowing some amazing + * synchronization between the sounds/music and your visualization (VuMeter for instance). + * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-the-analyser + * @param analyser The analyser to connect to the engine + */ + connectToAnalyser(analyser) { + if (this._connectedAnalyser) { + this._connectedAnalyser.stopDebugCanvas(); + } + if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) { + this._connectedAnalyser = analyser; + this.masterGain.disconnect(); + this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination); + } + } +} + +// Adds the parser to the scene parsers. +AddParser(SceneComponentConstants.NAME_AUDIO, (parsedData, scene, container, rootUrl) => { + // TODO: add sound + let loadedSounds = []; + let loadedSound; + container.sounds = container.sounds || []; + if (parsedData.sounds !== undefined && parsedData.sounds !== null) { + for (let index = 0, cache = parsedData.sounds.length; index < cache; index++) { + const parsedSound = parsedData.sounds[index]; + if (AbstractEngine.audioEngine?.canUseWebAudio) { + if (!parsedSound.url) { + parsedSound.url = parsedSound.name; + } + if (!loadedSounds[parsedSound.url]) { + loadedSound = Sound.Parse(parsedSound, scene, rootUrl); + loadedSounds[parsedSound.url] = loadedSound; + container.sounds.push(loadedSound); + } + else { + container.sounds.push(Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url])); + } + } + else { + container.sounds.push(new Sound(parsedSound.name, null, scene)); + } + } + } + loadedSounds = []; +}); +Object.defineProperty(Scene.prototype, "mainSoundTrack", { + get: function () { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + if (!this._mainSoundTrack) { + this._mainSoundTrack = new SoundTrack(this, { mainTrack: true }); + } + return this._mainSoundTrack; + }, + enumerable: true, + configurable: true, +}); +Scene.prototype.getSoundByName = function (name) { + let index; + for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) { + if (this.mainSoundTrack.soundCollection[index].name === name) { + return this.mainSoundTrack.soundCollection[index]; + } + } + if (this.soundTracks) { + for (let sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) { + for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) { + if (this.soundTracks[sdIndex].soundCollection[index].name === name) { + return this.soundTracks[sdIndex].soundCollection[index]; + } + } + } + } + return null; +}; +Object.defineProperty(Scene.prototype, "audioEnabled", { + get: function () { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + return compo.audioEnabled; + }, + set: function (value) { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + if (value) { + compo.enableAudio(); + } + else { + compo.disableAudio(); + } + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(Scene.prototype, "headphone", { + get: function () { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + return compo.headphone; + }, + set: function (value) { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + if (value) { + compo.switchAudioModeForHeadphones(); + } + else { + compo.switchAudioModeForNormalSpeakers(); + } + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(Scene.prototype, "audioListenerPositionProvider", { + get: function () { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + return compo.audioListenerPositionProvider; + }, + set: function (value) { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + if (value && typeof value !== "function") { + throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3"); + } + else { + compo.audioListenerPositionProvider = value; + } + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(Scene.prototype, "audioListenerRotationProvider", { + get: function () { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + return compo.audioListenerRotationProvider; + }, + set: function (value) { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + if (value && typeof value !== "function") { + throw new Error("The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3"); + } + else { + compo.audioListenerRotationProvider = value; + } + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(Scene.prototype, "audioPositioningRefreshRate", { + get: function () { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + return compo.audioPositioningRefreshRate; + }, + set: function (value) { + let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + compo.audioPositioningRefreshRate = value; + }, + enumerable: true, + configurable: true, +}); +/** + * Defines the sound scene component responsible to manage any sounds + * in a given scene. + */ +class AudioSceneComponent { + /** + * Gets whether audio is enabled or not. + * Please use related enable/disable method to switch state. + */ + get audioEnabled() { + return this._audioEnabled; + } + /** + * Gets whether audio is outputting to headphone or not. + * Please use the according Switch methods to change output. + */ + get headphone() { + return this._headphone; + } + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_AUDIO; + this._audioEnabled = true; + this._headphone = false; + /** + * Gets or sets a refresh rate when using 3D audio positioning + */ + this.audioPositioningRefreshRate = 500; + /** + * Gets or Sets a custom listener position for all sounds in the scene + * By default, this is the position of the first active camera + */ + this.audioListenerPositionProvider = null; + /** + * Gets or Sets a custom listener rotation for all sounds in the scene + * By default, this is the rotation of the first active camera + */ + this.audioListenerRotationProvider = null; + this._cachedCameraDirection = new Vector3(); + this._cachedCameraPosition = new Vector3(); + this._lastCheck = 0; + this._invertMatrixTemp = new Matrix(); + this._cameraDirectionTemp = new Vector3(); + scene = scene || EngineStore.LastCreatedScene; + if (!scene) { + return; + } + this.scene = scene; + scene.soundTracks = []; + scene.sounds = []; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._afterRenderStage.registerStep(SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do here. (Not rendering related) + } + /** + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to + */ + serialize(serializationObject) { + serializationObject.sounds = []; + if (this.scene.soundTracks) { + for (let index = 0; index < this.scene.soundTracks.length; index++) { + const soundtrack = this.scene.soundTracks[index]; + for (let soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) { + serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize()); + } + } + } + } + /** + * Adds all the elements from the container to the scene + * @param container the container holding the elements + */ + addFromContainer(container) { + if (!container.sounds) { + return; + } + container.sounds.forEach((sound) => { + sound.play(); + sound.autoplay = true; + this.scene.mainSoundTrack.addSound(sound); + }); + } + /** + * Removes all the elements in the container from the scene + * @param container contains the elements to remove + * @param dispose if the removed element should be disposed (default: false) + */ + removeFromContainer(container, dispose = false) { + if (!container.sounds) { + return; + } + container.sounds.forEach((sound) => { + sound.stop(); + sound.autoplay = false; + this.scene.mainSoundTrack.removeSound(sound); + if (dispose) { + sound.dispose(); + } + }); + } + /** + * Disposes the component and the associated resources. + */ + dispose() { + const scene = this.scene; + if (scene._mainSoundTrack) { + scene.mainSoundTrack.dispose(); + } + if (scene.soundTracks) { + for (let scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) { + scene.soundTracks[scIndex].dispose(); + } + } + } + /** + * Disables audio in the associated scene. + */ + disableAudio() { + const scene = this.scene; + this._audioEnabled = false; + if (AbstractEngine.audioEngine && AbstractEngine.audioEngine.audioContext) { + AbstractEngine.audioEngine.audioContext.suspend(); + } + let i; + for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { + scene.mainSoundTrack.soundCollection[i].pause(); + } + if (scene.soundTracks) { + for (i = 0; i < scene.soundTracks.length; i++) { + for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { + scene.soundTracks[i].soundCollection[j].pause(); + } + } + } + } + /** + * Enables audio in the associated scene. + */ + enableAudio() { + const scene = this.scene; + this._audioEnabled = true; + if (AbstractEngine.audioEngine && AbstractEngine.audioEngine.audioContext) { + AbstractEngine.audioEngine.audioContext.resume(); + } + let i; + for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { + if (scene.mainSoundTrack.soundCollection[i].isPaused) { + scene.mainSoundTrack.soundCollection[i].play(); + } + } + if (scene.soundTracks) { + for (i = 0; i < scene.soundTracks.length; i++) { + for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { + if (scene.soundTracks[i].soundCollection[j].isPaused) { + scene.soundTracks[i].soundCollection[j].play(); + } + } + } + } + } + /** + * Switch audio to headphone output. + */ + switchAudioModeForHeadphones() { + const scene = this.scene; + this._headphone = true; + scene.mainSoundTrack.switchPanningModelToHRTF(); + if (scene.soundTracks) { + for (let i = 0; i < scene.soundTracks.length; i++) { + scene.soundTracks[i].switchPanningModelToHRTF(); + } + } + } + /** + * Switch audio to normal speakers. + */ + switchAudioModeForNormalSpeakers() { + const scene = this.scene; + this._headphone = false; + scene.mainSoundTrack.switchPanningModelToEqualPower(); + if (scene.soundTracks) { + for (let i = 0; i < scene.soundTracks.length; i++) { + scene.soundTracks[i].switchPanningModelToEqualPower(); + } + } + } + _afterRender() { + const now = PrecisionDate.Now; + if (this._lastCheck && now - this._lastCheck < this.audioPositioningRefreshRate) { + return; + } + this._lastCheck = now; + const scene = this.scene; + if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) { + return; + } + const audioEngine = AbstractEngine.audioEngine; + if (!audioEngine) { + return; + } + if (audioEngine.audioContext) { + let listeningCamera = scene.activeCamera; + if (scene.activeCameras && scene.activeCameras.length > 0) { + listeningCamera = scene.activeCameras[0]; + } + // A custom listener position provider was set + // Use the users provided position instead of camera's + if (this.audioListenerPositionProvider) { + const position = this.audioListenerPositionProvider(); + // Set the listener position + audioEngine.audioContext.listener.setPosition(position.x || 0, position.y || 0, position.z || 0); + // Check if there is a listening camera + } + else if (listeningCamera) { + // Set the listener position to the listening camera global position + if (!this._cachedCameraPosition.equals(listeningCamera.globalPosition)) { + this._cachedCameraPosition.copyFrom(listeningCamera.globalPosition); + audioEngine.audioContext.listener.setPosition(listeningCamera.globalPosition.x, listeningCamera.globalPosition.y, listeningCamera.globalPosition.z); + } + } + // Otherwise set the listener position to 0, 0 ,0 + else { + // Set the listener position + audioEngine.audioContext.listener.setPosition(0, 0, 0); + } + // A custom listener rotation provider was set + // Use the users provided rotation instead of camera's + if (this.audioListenerRotationProvider) { + const rotation = this.audioListenerRotationProvider(); + audioEngine.audioContext.listener.setOrientation(rotation.x || 0, rotation.y || 0, rotation.z || 0, 0, 1, 0); + // Check if there is a listening camera + } + else if (listeningCamera) { + // for VR cameras + if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) { + listeningCamera = listeningCamera.rigCameras[0]; + } + listeningCamera.getViewMatrix().invertToRef(this._invertMatrixTemp); + Vector3.TransformNormalToRef(AudioSceneComponent._CameraDirection, this._invertMatrixTemp, this._cameraDirectionTemp); + this._cameraDirectionTemp.normalize(); + // To avoid some errors on GearVR + if (!isNaN(this._cameraDirectionTemp.x) && !isNaN(this._cameraDirectionTemp.y) && !isNaN(this._cameraDirectionTemp.z)) { + if (!this._cachedCameraDirection.equals(this._cameraDirectionTemp)) { + this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp); + audioEngine.audioContext.listener.setOrientation(this._cameraDirectionTemp.x, this._cameraDirectionTemp.y, this._cameraDirectionTemp.z, 0, 1, 0); + } + } + } + // Otherwise set the listener rotation to 0, 0 ,0 + else { + // Set the listener position + audioEngine.audioContext.listener.setOrientation(0, 0, 0, 0, 1, 0); + } + let i; + for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { + const sound = scene.mainSoundTrack.soundCollection[i]; + if (sound.useCustomAttenuation) { + sound.updateDistanceFromListener(); + } + } + if (scene.soundTracks) { + for (i = 0; i < scene.soundTracks.length; i++) { + for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { + const sound = scene.soundTracks[i].soundCollection[j]; + if (sound.useCustomAttenuation) { + sound.updateDistanceFromListener(); + } + } + } + } + } + } +} +AudioSceneComponent._CameraDirection = new Vector3(0, 0, -1); +Sound._SceneComponentInitialization = (scene) => { + let compo = scene._getComponent(SceneComponentConstants.NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(scene); + scene._addComponent(compo); + } +}; + +const NAME$8 = "MSFT_audio_emitter"; +/** + * [Specification](https://github.com/najadojo/glTF/blob/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter/README.md) + * !!! Experimental Extension Subject to Changes !!! + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class MSFT_audio_emitter { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$8; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$8); + } + /** @internal */ + dispose() { + this._loader = null; + this._clips = null; + this._emitters = null; + } + /** @internal */ + onLoading() { + const extensions = this._loader.gltf.extensions; + if (extensions && extensions[this.name]) { + const extension = extensions[this.name]; + this._clips = extension.clips; + this._emitters = extension.emitters; + ArrayItem.Assign(this._clips); + ArrayItem.Assign(this._emitters); + } + } + /** + * @internal + */ + loadSceneAsync(context, scene) { + return GLTFLoader.LoadExtensionAsync(context, scene, this.name, (extensionContext, extension) => { + const promises = new Array(); + promises.push(this._loader.loadSceneAsync(context, scene)); + for (const emitterIndex of extension.emitters) { + const emitter = ArrayItem.Get(`${extensionContext}/emitters`, this._emitters, emitterIndex); + if (emitter.refDistance != undefined || + emitter.maxDistance != undefined || + emitter.rolloffFactor != undefined || + emitter.distanceModel != undefined || + emitter.innerAngle != undefined || + emitter.outerAngle != undefined) { + throw new Error(`${extensionContext}: Direction or Distance properties are not allowed on emitters attached to a scene`); + } + promises.push(this._loadEmitterAsync(`${extensionContext}/emitters/${emitter.index}`, emitter)); + } + return Promise.all(promises).then(() => { }); + }); + } + /** + * @internal + */ + loadNodeAsync(context, node, assign) { + return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => { + const promises = new Array(); + return this._loader + .loadNodeAsync(extensionContext, node, (babylonMesh) => { + for (const emitterIndex of extension.emitters) { + const emitter = ArrayItem.Get(`${extensionContext}/emitters`, this._emitters, emitterIndex); + promises.push(this._loadEmitterAsync(`${extensionContext}/emitters/${emitter.index}`, emitter).then(() => { + for (const sound of emitter._babylonSounds) { + sound.attachToMesh(babylonMesh); + if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) { + sound.setLocalDirectionToMesh(Vector3.Forward()); + sound.setDirectionalCone(2 * Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0); + } + } + })); + } + assign(babylonMesh); + }) + .then((babylonMesh) => { + return Promise.all(promises).then(() => { + return babylonMesh; + }); + }); + }); + } + /** + * @internal + */ + loadAnimationAsync(context, animation) { + return GLTFLoader.LoadExtensionAsync(context, animation, this.name, (extensionContext, extension) => { + return this._loader.loadAnimationAsync(context, animation).then((babylonAnimationGroup) => { + const promises = new Array(); + ArrayItem.Assign(extension.events); + for (const event of extension.events) { + promises.push(this._loadAnimationEventAsync(`${extensionContext}/events/${event.index}`, context, animation, event, babylonAnimationGroup)); + } + return Promise.all(promises).then(() => { + return babylonAnimationGroup; + }); + }); + }); + } + _loadClipAsync(context, clip) { + if (clip._objectURL) { + return clip._objectURL; + } + let promise; + if (clip.uri) { + promise = this._loader.loadUriAsync(context, clip, clip.uri); + } + else { + const bufferView = ArrayItem.Get(`${context}/bufferView`, this._loader.gltf.bufferViews, clip.bufferView); + promise = this._loader.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView); + } + clip._objectURL = promise.then((data) => { + return URL.createObjectURL(new Blob([data], { type: clip.mimeType })); + }); + return clip._objectURL; + } + _loadEmitterAsync(context, emitter) { + emitter._babylonSounds = emitter._babylonSounds || []; + if (!emitter._babylonData) { + const clipPromises = new Array(); + const name = emitter.name || `emitter${emitter.index}`; + const options = { + loop: false, + autoplay: false, + volume: emitter.volume == undefined ? 1 : emitter.volume, + }; + for (let i = 0; i < emitter.clips.length; i++) { + const clipContext = `/extensions/${this.name}/clips`; + const clip = ArrayItem.Get(clipContext, this._clips, emitter.clips[i].clip); + clipPromises.push(this._loadClipAsync(`${clipContext}/${emitter.clips[i].clip}`, clip).then((objectURL) => { + const sound = (emitter._babylonSounds[i] = new Sound(name, objectURL, this._loader.babylonScene, null, options)); + sound.refDistance = emitter.refDistance || 1; + sound.maxDistance = emitter.maxDistance || 256; + sound.rolloffFactor = emitter.rolloffFactor || 1; + sound.distanceModel = emitter.distanceModel || "exponential"; + })); + } + const promise = Promise.all(clipPromises).then(() => { + const weights = emitter.clips.map((clip) => { + return clip.weight || 1; + }); + const weightedSound = new WeightedSound(emitter.loop || false, emitter._babylonSounds, weights); + if (emitter.innerAngle) { + weightedSound.directionalConeInnerAngle = 2 * Tools.ToDegrees(emitter.innerAngle); + } + if (emitter.outerAngle) { + weightedSound.directionalConeOuterAngle = 2 * Tools.ToDegrees(emitter.outerAngle); + } + if (emitter.volume) { + weightedSound.volume = emitter.volume; + } + emitter._babylonData.sound = weightedSound; + }); + emitter._babylonData = { + loaded: promise, + }; + } + return emitter._babylonData.loaded; + } + _getEventAction(context, sound, action, time, startOffset) { + switch (action) { + case "play" /* IMSFTAudioEmitter_AnimationEventAction.play */: { + return (currentFrame) => { + const frameOffset = (startOffset || 0) + (currentFrame - time); + sound.play(frameOffset); + }; + } + case "stop" /* IMSFTAudioEmitter_AnimationEventAction.stop */: { + return () => { + sound.stop(); + }; + } + case "pause" /* IMSFTAudioEmitter_AnimationEventAction.pause */: { + return () => { + sound.pause(); + }; + } + default: { + throw new Error(`${context}: Unsupported action ${action}`); + } + } + } + _loadAnimationEventAsync(context, animationContext, animation, event, babylonAnimationGroup) { + if (babylonAnimationGroup.targetedAnimations.length == 0) { + return Promise.resolve(); + } + const babylonAnimation = babylonAnimationGroup.targetedAnimations[0]; + const emitterIndex = event.emitter; + const emitter = ArrayItem.Get(`/extensions/${this.name}/emitters`, this._emitters, emitterIndex); + return this._loadEmitterAsync(context, emitter).then(() => { + const sound = emitter._babylonData.sound; + if (sound) { + const babylonAnimationEvent = new AnimationEvent(event.time, this._getEventAction(context, sound, event.action, event.time, event.startOffset)); + babylonAnimation.animation.addEvent(babylonAnimationEvent); + // Make sure all started audio stops when this animation is terminated. + babylonAnimationGroup.onAnimationGroupEndObservable.add(() => { + sound.stop(); + }); + babylonAnimationGroup.onAnimationGroupPauseObservable.add(() => { + sound.pause(); + }); + } + }); + } +} +unregisterGLTFExtension(NAME$8); +registerGLTFExtension(NAME$8, true, (loader) => new MSFT_audio_emitter(loader)); + +const NAME$7 = "MSFT_lod"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/MSFT_lod/README.md) + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class MSFT_lod { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$7; + /** + * Defines a number that determines the order the extensions are applied. + */ + this.order = 100; + /** + * Maximum number of LODs to load, starting from the lowest LOD. + */ + this.maxLODsToLoad = 10; + /** + * Observable raised when all node LODs of one level are loaded. + * The event data is the index of the loaded LOD starting from zero. + * Dispose the loader to cancel the loading of the next level of LODs. + */ + this.onNodeLODsLoadedObservable = new Observable(); + /** + * Observable raised when all material LODs of one level are loaded. + * The event data is the index of the loaded LOD starting from zero. + * Dispose the loader to cancel the loading of the next level of LODs. + */ + this.onMaterialLODsLoadedObservable = new Observable(); + this._bufferLODs = new Array(); + this._nodeIndexLOD = null; + this._nodeSignalLODs = new Array(); + this._nodePromiseLODs = new Array(); + this._nodeBufferLODs = new Array(); + this._materialIndexLOD = null; + this._materialSignalLODs = new Array(); + this._materialPromiseLODs = new Array(); + this._materialBufferLODs = new Array(); + this._loader = loader; + // Options takes precedence. The maxLODsToLoad extension property is retained for back compat. + // For new extensions, they should only use options. + this.maxLODsToLoad = this._loader.parent.extensionOptions[NAME$7]?.maxLODsToLoad ?? this.maxLODsToLoad; + this.enabled = this._loader.isExtensionUsed(NAME$7); + } + /** @internal */ + dispose() { + this._loader = null; + this._nodeIndexLOD = null; + this._nodeSignalLODs.length = 0; + this._nodePromiseLODs.length = 0; + this._nodeBufferLODs.length = 0; + this._materialIndexLOD = null; + this._materialSignalLODs.length = 0; + this._materialPromiseLODs.length = 0; + this._materialBufferLODs.length = 0; + this.onMaterialLODsLoadedObservable.clear(); + this.onNodeLODsLoadedObservable.clear(); + } + /** @internal */ + onReady() { + for (let indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) { + const promise = Promise.all(this._nodePromiseLODs[indexLOD]).then(() => { + if (indexLOD !== 0) { + this._loader.endPerformanceCounter(`Node LOD ${indexLOD}`); + this._loader.log(`Loaded node LOD ${indexLOD}`); + } + this.onNodeLODsLoadedObservable.notifyObservers(indexLOD); + if (indexLOD !== this._nodePromiseLODs.length - 1) { + this._loader.startPerformanceCounter(`Node LOD ${indexLOD + 1}`); + this._loadBufferLOD(this._nodeBufferLODs, indexLOD + 1); + if (this._nodeSignalLODs[indexLOD]) { + this._nodeSignalLODs[indexLOD].resolve(); + } + } + }); + this._loader._completePromises.push(promise); + } + for (let indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) { + const promise = Promise.all(this._materialPromiseLODs[indexLOD]).then(() => { + if (indexLOD !== 0) { + this._loader.endPerformanceCounter(`Material LOD ${indexLOD}`); + this._loader.log(`Loaded material LOD ${indexLOD}`); + } + this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD); + if (indexLOD !== this._materialPromiseLODs.length - 1) { + this._loader.startPerformanceCounter(`Material LOD ${indexLOD + 1}`); + this._loadBufferLOD(this._materialBufferLODs, indexLOD + 1); + if (this._materialSignalLODs[indexLOD]) { + this._materialSignalLODs[indexLOD].resolve(); + } + } + }); + this._loader._completePromises.push(promise); + } + } + /** + * @internal + */ + loadSceneAsync(context, scene) { + const promise = this._loader.loadSceneAsync(context, scene); + this._loadBufferLOD(this._bufferLODs, 0); + return promise; + } + /** + * @internal + */ + loadNodeAsync(context, node, assign) { + return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => { + let firstPromise; + const nodeLODs = this._getLODs(extensionContext, node, this._loader.gltf.nodes, extension.ids); + this._loader.logOpen(`${extensionContext}`); + for (let indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) { + const nodeLOD = nodeLODs[indexLOD]; + if (indexLOD !== 0) { + this._nodeIndexLOD = indexLOD; + this._nodeSignalLODs[indexLOD] = this._nodeSignalLODs[indexLOD] || new Deferred(); + } + const assignWrap = (babylonTransformNode) => { + assign(babylonTransformNode); + babylonTransformNode.setEnabled(false); + }; + const promise = this._loader.loadNodeAsync(`/nodes/${nodeLOD.index}`, nodeLOD, assignWrap).then((babylonMesh) => { + if (indexLOD !== 0) { + // TODO: should not rely on _babylonTransformNode + const previousNodeLOD = nodeLODs[indexLOD - 1]; + if (previousNodeLOD._babylonTransformNode) { + this._disposeTransformNode(previousNodeLOD._babylonTransformNode); + delete previousNodeLOD._babylonTransformNode; + } + } + babylonMesh.setEnabled(true); + return babylonMesh; + }); + this._nodePromiseLODs[indexLOD] = this._nodePromiseLODs[indexLOD] || []; + if (indexLOD === 0) { + firstPromise = promise; + } + else { + this._nodeIndexLOD = null; + this._nodePromiseLODs[indexLOD].push(promise); + } + } + this._loader.logClose(); + return firstPromise; + }); + } + /** + * @internal + */ + _loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign) { + // Don't load material LODs if already loading a node LOD. + if (this._nodeIndexLOD) { + return null; + } + return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => { + let firstPromise; + const materialLODs = this._getLODs(extensionContext, material, this._loader.gltf.materials, extension.ids); + this._loader.logOpen(`${extensionContext}`); + for (let indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) { + const materialLOD = materialLODs[indexLOD]; + if (indexLOD !== 0) { + this._materialIndexLOD = indexLOD; + } + const promise = this._loader + ._loadMaterialAsync(`/materials/${materialLOD.index}`, materialLOD, babylonMesh, babylonDrawMode, (babylonMaterial) => { + if (indexLOD === 0) { + assign(babylonMaterial); + } + }) + .then((babylonMaterial) => { + if (indexLOD !== 0) { + assign(babylonMaterial); + // TODO: should not rely on _data + const previousDataLOD = materialLODs[indexLOD - 1]._data; + if (previousDataLOD[babylonDrawMode]) { + this._disposeMaterials([previousDataLOD[babylonDrawMode].babylonMaterial]); + delete previousDataLOD[babylonDrawMode]; + } + } + return babylonMaterial; + }); + this._materialPromiseLODs[indexLOD] = this._materialPromiseLODs[indexLOD] || []; + if (indexLOD === 0) { + firstPromise = promise; + } + else { + this._materialIndexLOD = null; + this._materialPromiseLODs[indexLOD].push(promise); + } + } + this._loader.logClose(); + return firstPromise; + }); + } + /** + * @internal + */ + _loadUriAsync(context, property, uri) { + // Defer the loading of uris if loading a node or material LOD. + if (this._nodeIndexLOD !== null) { + this._loader.log(`deferred`); + const previousIndexLOD = this._nodeIndexLOD - 1; + this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new Deferred(); + return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(() => { + return this._loader.loadUriAsync(context, property, uri); + }); + } + else if (this._materialIndexLOD !== null) { + this._loader.log(`deferred`); + const previousIndexLOD = this._materialIndexLOD - 1; + this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new Deferred(); + return this._materialSignalLODs[previousIndexLOD].promise.then(() => { + return this._loader.loadUriAsync(context, property, uri); + }); + } + return null; + } + /** + * @internal + */ + loadBufferAsync(context, buffer, byteOffset, byteLength) { + if (this._loader.parent.useRangeRequests && !buffer.uri) { + if (!this._loader.bin) { + throw new Error(`${context}: Uri is missing or the binary glTF is missing its binary chunk`); + } + const loadAsync = (bufferLODs, indexLOD) => { + const start = byteOffset; + const end = start + byteLength - 1; + let bufferLOD = bufferLODs[indexLOD]; + if (bufferLOD) { + bufferLOD.start = Math.min(bufferLOD.start, start); + bufferLOD.end = Math.max(bufferLOD.end, end); + } + else { + bufferLOD = { start: start, end: end, loaded: new Deferred() }; + bufferLODs[indexLOD] = bufferLOD; + } + return bufferLOD.loaded.promise.then((data) => { + return new Uint8Array(data.buffer, data.byteOffset + byteOffset - bufferLOD.start, byteLength); + }); + }; + this._loader.log(`deferred`); + if (this._nodeIndexLOD !== null) { + return loadAsync(this._nodeBufferLODs, this._nodeIndexLOD); + } + else if (this._materialIndexLOD !== null) { + return loadAsync(this._materialBufferLODs, this._materialIndexLOD); + } + else { + return loadAsync(this._bufferLODs, 0); + } + } + return null; + } + _loadBufferLOD(bufferLODs, indexLOD) { + const bufferLOD = bufferLODs[indexLOD]; + if (bufferLOD) { + this._loader.log(`Loading buffer range [${bufferLOD.start}-${bufferLOD.end}]`); + this._loader.bin.readAsync(bufferLOD.start, bufferLOD.end - bufferLOD.start + 1).then((data) => { + bufferLOD.loaded.resolve(data); + }, (error) => { + bufferLOD.loaded.reject(error); + }); + } + } + /** + * @returns an array of LOD properties from lowest to highest. + * @param context + * @param property + * @param array + * @param ids + */ + _getLODs(context, property, array, ids) { + if (this.maxLODsToLoad <= 0) { + throw new Error("maxLODsToLoad must be greater than zero"); + } + const properties = []; + for (let i = ids.length - 1; i >= 0; i--) { + properties.push(ArrayItem.Get(`${context}/ids/${ids[i]}`, array, ids[i])); + if (properties.length === this.maxLODsToLoad) { + return properties; + } + } + properties.push(property); + return properties; + } + _disposeTransformNode(babylonTransformNode) { + const babylonMaterials = []; + const babylonMaterial = babylonTransformNode.material; + if (babylonMaterial) { + babylonMaterials.push(babylonMaterial); + } + for (const babylonMesh of babylonTransformNode.getChildMeshes()) { + if (babylonMesh.material) { + babylonMaterials.push(babylonMesh.material); + } + } + babylonTransformNode.dispose(); + const babylonMaterialsToDispose = babylonMaterials.filter((babylonMaterial) => this._loader.babylonScene.meshes.every((mesh) => mesh.material != babylonMaterial)); + this._disposeMaterials(babylonMaterialsToDispose); + } + _disposeMaterials(babylonMaterials) { + const babylonTextures = {}; + for (const babylonMaterial of babylonMaterials) { + for (const babylonTexture of babylonMaterial.getActiveTextures()) { + babylonTextures[babylonTexture.uniqueId] = babylonTexture; + } + babylonMaterial.dispose(); + } + for (const uniqueId in babylonTextures) { + for (const babylonMaterial of this._loader.babylonScene.materials) { + if (babylonMaterial.hasTexture(babylonTextures[uniqueId])) { + delete babylonTextures[uniqueId]; + } + } + } + for (const uniqueId in babylonTextures) { + babylonTextures[uniqueId].dispose(); + } + } +} +unregisterGLTFExtension(NAME$7); +registerGLTFExtension(NAME$7, true, (loader) => new MSFT_lod(loader)); + +const NAME$6 = "MSFT_minecraftMesh"; +/** @internal */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class MSFT_minecraftMesh { + /** @internal */ + constructor(loader) { + /** @internal */ + this.name = NAME$6; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$6); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** @internal */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtraAsync(context, material, this.name, (extraContext, extra) => { + if (extra) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${extraContext}: Material type not supported`); + } + const promise = this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial); + if (babylonMaterial.needAlphaBlending()) { + babylonMaterial.forceDepthWrite = true; + babylonMaterial.separateCullingPass = true; + } + babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite; + babylonMaterial.twoSidedLighting = true; + return promise; + } + return null; + }); + } +} +unregisterGLTFExtension(NAME$6); +registerGLTFExtension(NAME$6, true, (loader) => new MSFT_minecraftMesh(loader)); + +const NAME$5 = "MSFT_sRGBFactors"; +/** @internal */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class MSFT_sRGBFactors { + /** @internal */ + constructor(loader) { + /** @internal */ + this.name = NAME$5; + this._loader = loader; + this.enabled = this._loader.isExtensionUsed(NAME$5); + } + /** @internal */ + dispose() { + this._loader = null; + } + /** @internal */ + loadMaterialPropertiesAsync(context, material, babylonMaterial) { + return GLTFLoader.LoadExtraAsync(context, material, this.name, (extraContext, extra) => { + if (extra) { + if (!(babylonMaterial instanceof PBRMaterial)) { + throw new Error(`${extraContext}: Material type not supported`); + } + const promise = this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial); + const useExactSrgbConversions = babylonMaterial.getScene().getEngine().useExactSrgbConversions; + if (!babylonMaterial.albedoTexture) { + babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor, useExactSrgbConversions); + } + if (!babylonMaterial.reflectivityTexture) { + babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor, useExactSrgbConversions); + } + return promise; + } + return null; + }); + } +} +unregisterGLTFExtension(NAME$5); +registerGLTFExtension(NAME$5, true, (loader) => new MSFT_sRGBFactors(loader)); + +/** + * Class that represents an integer value. + */ +class FlowGraphInteger { + constructor(value) { + this.value = this._toInt(value); + } + /** + * Converts a float to an integer. + * @param n the float to convert + * @returns the result of n | 0 - converting it to a int + */ + _toInt(n) { + return n | 0; + } + /** + * Adds two integers together. + * @param other the other integer to add + * @returns a FlowGraphInteger with the result of the addition + */ + add(other) { + return new FlowGraphInteger(this.value + other.value); + } + /** + * Subtracts two integers. + * @param other the other integer to subtract + * @returns a FlowGraphInteger with the result of the subtraction + */ + subtract(other) { + return new FlowGraphInteger(this.value - other.value); + } + /** + * Multiplies two integers. + * @param other the other integer to multiply + * @returns a FlowGraphInteger with the result of the multiplication + */ + multiply(other) { + return new FlowGraphInteger(Math.imul(this.value, other.value)); + } + /** + * Divides two integers. + * @param other the other integer to divide + * @returns a FlowGraphInteger with the result of the division + */ + divide(other) { + return new FlowGraphInteger(this.value / other.value); + } + /** + * The class name of this type. + * @returns + */ + getClassName() { + return FlowGraphInteger.ClassName; + } + /** + * Compares two integers for equality. + * @param other the other integer to compare + * @returns + */ + equals(other) { + return this.value === other.value; + } + /** + * Parses a FlowGraphInteger from a serialization object. + * @param value te number to parse + * @returns + */ + static FromValue(value) { + return new FlowGraphInteger(value); + } + toString() { + return this.value.toString(); + } +} +FlowGraphInteger.ClassName = "FlowGraphInteger"; +RegisterClass("FlowGraphInteger", FlowGraphInteger); + +// Note - the matrix classes are basically column-major, and work similarly to Babylon.js' Matrix class. +/** + * A 2x2 matrix. + */ +class FlowGraphMatrix2D { + constructor(m = [1, 0, 0, 1]) { + this._m = m; + } + get m() { + return this._m; + } + transformVector(v) { + return this.transformVectorToRef(v, new Vector2()); + } + transformVectorToRef(v, result) { + result.x = v.x * this._m[0] + v.y * this._m[1]; + result.y = v.x * this._m[2] + v.y * this._m[3]; + return result; + } + asArray() { + return this.toArray(); + } + toArray(emptyArray = []) { + for (let i = 0; i < 4; i++) { + emptyArray[i] = this._m[i]; + } + return emptyArray; + } + fromArray(array) { + for (let i = 0; i < 4; i++) { + this._m[i] = array[i]; + } + return this; + } + multiplyToRef(other, result) { + const otherMatrix = other._m; + const thisMatrix = this._m; + const r = result._m; + // other * this + r[0] = otherMatrix[0] * thisMatrix[0] + otherMatrix[1] * thisMatrix[2]; + r[1] = otherMatrix[0] * thisMatrix[1] + otherMatrix[1] * thisMatrix[3]; + r[2] = otherMatrix[2] * thisMatrix[0] + otherMatrix[3] * thisMatrix[2]; + r[3] = otherMatrix[2] * thisMatrix[1] + otherMatrix[3] * thisMatrix[3]; + return result; + } + multiply(other) { + return this.multiplyToRef(other, new FlowGraphMatrix2D()); + } + divideToRef(other, result) { + const m = this._m; + const o = other._m; + const r = result._m; + r[0] = m[0] / o[0]; + r[1] = m[1] / o[1]; + r[2] = m[2] / o[2]; + r[3] = m[3] / o[3]; + return result; + } + divide(other) { + return this.divideToRef(other, new FlowGraphMatrix2D()); + } + addToRef(other, result) { + const m = this._m; + const o = other.m; + const r = result.m; + r[0] = m[0] + o[0]; + r[1] = m[1] + o[1]; + r[2] = m[2] + o[2]; + r[3] = m[3] + o[3]; + return result; + } + add(other) { + return this.addToRef(other, new FlowGraphMatrix2D()); + } + subtractToRef(other, result) { + const m = this._m; + const o = other.m; + const r = result.m; + r[0] = m[0] - o[0]; + r[1] = m[1] - o[1]; + r[2] = m[2] - o[2]; + r[3] = m[3] - o[3]; + return result; + } + subtract(other) { + return this.subtractToRef(other, new FlowGraphMatrix2D()); + } + transpose() { + const m = this._m; + return new FlowGraphMatrix2D([m[0], m[2], m[1], m[3]]); + } + determinant() { + const m = this._m; + return m[0] * m[3] - m[1] * m[2]; + } + inverse() { + const det = this.determinant(); + if (det === 0) { + throw new Error("Matrix is not invertible"); + } + const m = this._m; + const invDet = 1 / det; + return new FlowGraphMatrix2D([m[3] * invDet, -m[1] * invDet, -m[2] * invDet, m[0] * invDet]); + } + equals(other, epsilon = 0) { + const m = this._m; + const o = other.m; + if (epsilon === 0) { + return m[0] === o[0] && m[1] === o[1] && m[2] === o[2] && m[3] === o[3]; + } + return Math.abs(m[0] - o[0]) < epsilon && Math.abs(m[1] - o[1]) < epsilon && Math.abs(m[2] - o[2]) < epsilon && Math.abs(m[3] - o[3]) < epsilon; + } + getClassName() { + return "FlowGraphMatrix2D"; + } + toString() { + return `FlowGraphMatrix2D(${this._m.join(", ")})`; + } +} +/** + * A 3x3 matrix. + */ +class FlowGraphMatrix3D { + constructor(array = [1, 0, 0, 0, 1, 0, 0, 0, 1]) { + this._m = array; + } + get m() { + return this._m; + } + transformVector(v) { + return this.transformVectorToRef(v, new Vector3()); + } + transformVectorToRef(v, result) { + const m = this._m; + result.x = v.x * m[0] + v.y * m[1] + v.z * m[2]; + result.y = v.x * m[3] + v.y * m[4] + v.z * m[5]; + result.z = v.x * m[6] + v.y * m[7] + v.z * m[8]; + return result; + } + multiplyToRef(other, result) { + const otherMatrix = other._m; + const thisMatrix = this._m; + const r = result.m; + r[0] = otherMatrix[0] * thisMatrix[0] + otherMatrix[1] * thisMatrix[3] + otherMatrix[2] * thisMatrix[6]; + r[1] = otherMatrix[0] * thisMatrix[1] + otherMatrix[1] * thisMatrix[4] + otherMatrix[2] * thisMatrix[7]; + r[2] = otherMatrix[0] * thisMatrix[2] + otherMatrix[1] * thisMatrix[5] + otherMatrix[2] * thisMatrix[8]; + r[3] = otherMatrix[3] * thisMatrix[0] + otherMatrix[4] * thisMatrix[3] + otherMatrix[5] * thisMatrix[6]; + r[4] = otherMatrix[3] * thisMatrix[1] + otherMatrix[4] * thisMatrix[4] + otherMatrix[5] * thisMatrix[7]; + r[5] = otherMatrix[3] * thisMatrix[2] + otherMatrix[4] * thisMatrix[5] + otherMatrix[5] * thisMatrix[8]; + r[6] = otherMatrix[6] * thisMatrix[0] + otherMatrix[7] * thisMatrix[3] + otherMatrix[8] * thisMatrix[6]; + r[7] = otherMatrix[6] * thisMatrix[1] + otherMatrix[7] * thisMatrix[4] + otherMatrix[8] * thisMatrix[7]; + r[8] = otherMatrix[6] * thisMatrix[2] + otherMatrix[7] * thisMatrix[5] + otherMatrix[8] * thisMatrix[8]; + return result; + } + multiply(other) { + return this.multiplyToRef(other, new FlowGraphMatrix3D()); + } + divideToRef(other, result) { + const m = this._m; + const o = other.m; + const r = result.m; + r[0] = m[0] / o[0]; + r[1] = m[1] / o[1]; + r[2] = m[2] / o[2]; + r[3] = m[3] / o[3]; + r[4] = m[4] / o[4]; + r[5] = m[5] / o[5]; + r[6] = m[6] / o[6]; + r[7] = m[7] / o[7]; + r[8] = m[8] / o[8]; + return result; + } + divide(other) { + return this.divideToRef(other, new FlowGraphMatrix3D()); + } + addToRef(other, result) { + const m = this._m; + const o = other.m; + const r = result.m; + r[0] = m[0] + o[0]; + r[1] = m[1] + o[1]; + r[2] = m[2] + o[2]; + r[3] = m[3] + o[3]; + r[4] = m[4] + o[4]; + r[5] = m[5] + o[5]; + r[6] = m[6] + o[6]; + r[7] = m[7] + o[7]; + r[8] = m[8] + o[8]; + return result; + } + add(other) { + return this.addToRef(other, new FlowGraphMatrix3D()); + } + subtractToRef(other, result) { + const m = this._m; + const o = other.m; + const r = result.m; + r[0] = m[0] - o[0]; + r[1] = m[1] - o[1]; + r[2] = m[2] - o[2]; + r[3] = m[3] - o[3]; + r[4] = m[4] - o[4]; + r[5] = m[5] - o[5]; + r[6] = m[6] - o[6]; + r[7] = m[7] - o[7]; + r[8] = m[8] - o[8]; + return result; + } + subtract(other) { + return this.subtractToRef(other, new FlowGraphMatrix3D()); + } + toArray(emptyArray = []) { + for (let i = 0; i < 9; i++) { + emptyArray[i] = this._m[i]; + } + return emptyArray; + } + asArray() { + return this.toArray(); + } + fromArray(array) { + for (let i = 0; i < 9; i++) { + this._m[i] = array[i]; + } + return this; + } + transpose() { + const m = this._m; + return new FlowGraphMatrix3D([m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8]]); + } + determinant() { + const m = this._m; + return m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]); + } + inverse() { + const det = this.determinant(); + if (det === 0) { + throw new Error("Matrix is not invertible"); + } + const m = this._m; + const invDet = 1 / det; + return new FlowGraphMatrix3D([ + (m[4] * m[8] - m[5] * m[7]) * invDet, + (m[2] * m[7] - m[1] * m[8]) * invDet, + (m[1] * m[5] - m[2] * m[4]) * invDet, + (m[5] * m[6] - m[3] * m[8]) * invDet, + (m[0] * m[8] - m[2] * m[6]) * invDet, + (m[2] * m[3] - m[0] * m[5]) * invDet, + (m[3] * m[7] - m[4] * m[6]) * invDet, + (m[1] * m[6] - m[0] * m[7]) * invDet, + (m[0] * m[4] - m[1] * m[3]) * invDet, + ]); + } + equals(other, epsilon = 0) { + const m = this._m; + const o = other.m; + // performance shortcut + if (epsilon === 0) { + return m[0] === o[0] && m[1] === o[1] && m[2] === o[2] && m[3] === o[3] && m[4] === o[4] && m[5] === o[5] && m[6] === o[6] && m[7] === o[7] && m[8] === o[8]; + } + return (Math.abs(m[0] - o[0]) < epsilon && + Math.abs(m[1] - o[1]) < epsilon && + Math.abs(m[2] - o[2]) < epsilon && + Math.abs(m[3] - o[3]) < epsilon && + Math.abs(m[4] - o[4]) < epsilon && + Math.abs(m[5] - o[5]) < epsilon && + Math.abs(m[6] - o[6]) < epsilon && + Math.abs(m[7] - o[7]) < epsilon && + Math.abs(m[8] - o[8]) < epsilon); + } + getClassName() { + return "FlowGraphMatrix3D"; + } + toString() { + return `FlowGraphMatrix3D(${this._m.join(", ")})`; + } +} + +/** + * The types supported by the flow graph. + */ +var FlowGraphTypes; +(function (FlowGraphTypes) { + FlowGraphTypes["Any"] = "any"; + FlowGraphTypes["String"] = "string"; + FlowGraphTypes["Number"] = "number"; + FlowGraphTypes["Boolean"] = "boolean"; + FlowGraphTypes["Object"] = "object"; + FlowGraphTypes["Integer"] = "FlowGraphInteger"; + FlowGraphTypes["Vector2"] = "Vector2"; + FlowGraphTypes["Vector3"] = "Vector3"; + FlowGraphTypes["Vector4"] = "Vector4"; + FlowGraphTypes["Quaternion"] = "Quaternion"; + FlowGraphTypes["Matrix"] = "Matrix"; + FlowGraphTypes["Matrix2D"] = "Matrix2D"; + FlowGraphTypes["Matrix3D"] = "Matrix3D"; + FlowGraphTypes["Color3"] = "Color3"; + FlowGraphTypes["Color4"] = "Color4"; +})(FlowGraphTypes || (FlowGraphTypes = {})); +/** + * A rich type represents extra information about a type, + * such as its name and a default value constructor. + */ +class RichType { + constructor( + /** + * The name given to the type. + */ + typeName, + /** + * The default value of the type. + */ + defaultValue, + /** + * [-1] The ANIMATIONTYPE of the type, if available + */ + animationType = -1) { + this.typeName = typeName; + this.defaultValue = defaultValue; + this.animationType = animationType; + } + /** + * Serializes this rich type into a serialization object. + * @param serializationObject the object to serialize to + */ + serialize(serializationObject) { + serializationObject.typeName = this.typeName; + serializationObject.defaultValue = this.defaultValue; + } +} +const RichTypeAny = new RichType("any" /* FlowGraphTypes.Any */, undefined); +const RichTypeString = new RichType("string" /* FlowGraphTypes.String */, ""); +const RichTypeNumber = new RichType("number" /* FlowGraphTypes.Number */, 0, 0); +const RichTypeBoolean = new RichType("boolean" /* FlowGraphTypes.Boolean */, false); +const RichTypeVector2 = new RichType("Vector2" /* FlowGraphTypes.Vector2 */, Vector2.Zero(), 5); +const RichTypeVector3 = new RichType("Vector3" /* FlowGraphTypes.Vector3 */, Vector3.Zero(), 1); +const RichTypeVector4 = new RichType("Vector4" /* FlowGraphTypes.Vector4 */, Vector4.Zero()); +const RichTypeMatrix = new RichType("Matrix" /* FlowGraphTypes.Matrix */, Matrix.Identity(), 3); +const RichTypeMatrix2D = new RichType("Matrix2D" /* FlowGraphTypes.Matrix2D */, new FlowGraphMatrix2D()); +const RichTypeMatrix3D = new RichType("Matrix3D" /* FlowGraphTypes.Matrix3D */, new FlowGraphMatrix3D()); +const RichTypeColor3 = new RichType("Color3" /* FlowGraphTypes.Color3 */, Color3.Black(), 4); +const RichTypeColor4 = new RichType("Color4" /* FlowGraphTypes.Color4 */, new Color4(0, 0, 0, 0), 7); +const RichTypeQuaternion = new RichType("Quaternion" /* FlowGraphTypes.Quaternion */, Quaternion.Identity(), 2); +RichTypeQuaternion.typeTransformer = (value) => { + if (value.getClassName && value.getClassName() === "Vector4" /* FlowGraphTypes.Vector4 */) { + return Quaternion.FromArray(value.asArray()); + } + else if (value.getClassName && value.getClassName() === "Vector3" /* FlowGraphTypes.Vector3 */) { + return Quaternion.FromEulerVector(value); + } + else if (value.getClassName && value.getClassName() === "Matrix" /* FlowGraphTypes.Matrix */) { + return Quaternion.FromRotationMatrix(value); + } + return value; +}; +const RichTypeFlowGraphInteger = new RichType("FlowGraphInteger" /* FlowGraphTypes.Integer */, new FlowGraphInteger(0), 0); +/** + * Given a value, try to deduce its rich type. + * @param value the value to deduce the rich type from + * @returns the value's rich type, or RichTypeAny if the type could not be deduced. + */ +function getRichTypeFromValue(value) { + const anyValue = value; + switch (typeof value) { + case "string" /* FlowGraphTypes.String */: + return RichTypeString; + case "number" /* FlowGraphTypes.Number */: + return RichTypeNumber; + case "boolean" /* FlowGraphTypes.Boolean */: + return RichTypeBoolean; + case "object" /* FlowGraphTypes.Object */: + if (anyValue.getClassName) { + switch (anyValue.getClassName()) { + case "Vector2" /* FlowGraphTypes.Vector2 */: + return RichTypeVector2; + case "Vector3" /* FlowGraphTypes.Vector3 */: + return RichTypeVector3; + case "Vector4" /* FlowGraphTypes.Vector4 */: + return RichTypeVector4; + case "Matrix" /* FlowGraphTypes.Matrix */: + return RichTypeMatrix; + case "Color3" /* FlowGraphTypes.Color3 */: + return RichTypeColor3; + case "Color4" /* FlowGraphTypes.Color4 */: + return RichTypeColor4; + case "Quaternion" /* FlowGraphTypes.Quaternion */: + return RichTypeQuaternion; + case "FlowGraphInteger" /* FlowGraphTypes.Integer */: + return RichTypeFlowGraphInteger; + case "Matrix2D" /* FlowGraphTypes.Matrix2D */: + return RichTypeMatrix2D; + case "Matrix3D" /* FlowGraphTypes.Matrix3D */: + return RichTypeMatrix3D; + } + } + return RichTypeAny; + default: + return RichTypeAny; + } +} +/** + * Given a flow graph type, return the rich type that corresponds to it. + * @param flowGraphType the flow graph type + * @returns the rich type that corresponds to the flow graph type + */ +function getRichTypeByFlowGraphType(flowGraphType) { + switch (flowGraphType) { + case "string" /* FlowGraphTypes.String */: + return RichTypeString; + case "number" /* FlowGraphTypes.Number */: + return RichTypeNumber; + case "boolean" /* FlowGraphTypes.Boolean */: + return RichTypeBoolean; + case "Vector2" /* FlowGraphTypes.Vector2 */: + return RichTypeVector2; + case "Vector3" /* FlowGraphTypes.Vector3 */: + return RichTypeVector3; + case "Vector4" /* FlowGraphTypes.Vector4 */: + return RichTypeVector4; + case "Matrix" /* FlowGraphTypes.Matrix */: + return RichTypeMatrix; + case "Color3" /* FlowGraphTypes.Color3 */: + return RichTypeColor3; + case "Color4" /* FlowGraphTypes.Color4 */: + return RichTypeColor4; + case "Quaternion" /* FlowGraphTypes.Quaternion */: + return RichTypeQuaternion; + case "FlowGraphInteger" /* FlowGraphTypes.Integer */: + return RichTypeFlowGraphInteger; + case "Matrix2D" /* FlowGraphTypes.Matrix2D */: + return RichTypeMatrix2D; + case "Matrix3D" /* FlowGraphTypes.Matrix3D */: + return RichTypeMatrix3D; + default: + return RichTypeAny; + } +} +/** + * get the animation type for a given flow graph type + * @param flowGraphType the flow graph type + * @returns the animation type for this flow graph type + */ +function getAnimationTypeByFlowGraphType(flowGraphType) { + switch (flowGraphType) { + case "number" /* FlowGraphTypes.Number */: + return 0; + case "Vector2" /* FlowGraphTypes.Vector2 */: + return 5; + case "Vector3" /* FlowGraphTypes.Vector3 */: + return 1; + case "Matrix" /* FlowGraphTypes.Matrix */: + return 3; + case "Color3" /* FlowGraphTypes.Color3 */: + return 4; + case "Color4" /* FlowGraphTypes.Color4 */: + return 7; + case "Quaternion" /* FlowGraphTypes.Quaternion */: + return 2; + default: + return 0; + } +} +/** + * Given an animation type, return the rich type that corresponds to it. + * @param animationType the animation type + * @returns the rich type that corresponds to the animation type + */ +function getRichTypeByAnimationType(animationType) { + switch (animationType) { + case 0: + return RichTypeNumber; + case 5: + return RichTypeVector2; + case 1: + return RichTypeVector3; + case 3: + return RichTypeMatrix; + case 4: + return RichTypeColor3; + case 7: + return RichTypeColor4; + case 2: + return RichTypeQuaternion; + default: + return RichTypeAny; + } +} + +function isMeshClassName(className) { + return (className === "Mesh" || + className === "AbstractMesh" || + className === "GroundMesh" || + className === "InstanceMesh" || + className === "LinesMesh" || + className === "GoldbergMesh" || + className === "GreasedLineMesh" || + className === "TrailMesh"); +} +function isVectorClassName(className) { + return (className === "Vector2" /* FlowGraphTypes.Vector2 */ || + className === "Vector3" /* FlowGraphTypes.Vector3 */ || + className === "Vector4" /* FlowGraphTypes.Vector4 */ || + className === "Quaternion" /* FlowGraphTypes.Quaternion */ || + className === "Color3" /* FlowGraphTypes.Color3 */ || + className === "Color4" /* FlowGraphTypes.Color4 */); +} +function isMatrixClassName(className) { + return className === "Matrix" /* FlowGraphTypes.Matrix */ || className === "Matrix2D" /* FlowGraphTypes.Matrix2D */ || className === "Matrix3D" /* FlowGraphTypes.Matrix3D */; +} +function isAnimationGroupClassName(className) { + return className === "AnimationGroup"; +} +function parseVector(className, value, flipHandedness = false) { + if (className === "Vector2" /* FlowGraphTypes.Vector2 */) { + return Vector2.FromArray(value); + } + else if (className === "Vector3" /* FlowGraphTypes.Vector3 */) { + if (flipHandedness) { + value[2] *= -1; + } + return Vector3.FromArray(value); + } + else if (className === "Vector4" /* FlowGraphTypes.Vector4 */) { + return Vector4.FromArray(value); + } + else if (className === "Quaternion" /* FlowGraphTypes.Quaternion */) { + if (flipHandedness) { + value[2] *= -1; + value[3] *= -1; + } + return Quaternion.FromArray(value); + } + else if (className === "Color3" /* FlowGraphTypes.Color3 */) { + return new Color3(value[0], value[1], value[2]); + } + else if (className === "Color4" /* FlowGraphTypes.Color4 */) { + return new Color4(value[0], value[1], value[2], value[3]); + } + else { + throw new Error(`Unknown vector class name ${className}`); + } +} +/** + * The default function that serializes values in a context object to a serialization object + * @param key the key where the value should be stored in the serialization object + * @param value the value to store + * @param serializationObject the object where the value will be stored + */ +function defaultValueSerializationFunction(key, value, serializationObject) { + const className = value?.getClassName?.() ?? ""; + if (isVectorClassName(className) || isMatrixClassName(className)) { + serializationObject[key] = { + value: value.asArray(), + className, + }; + } + else if (className === "FlowGraphInteger" /* FlowGraphTypes.Integer */) { + serializationObject[key] = { + value: value.value, + className, + }; + } + else { + if (className && (value.id || value.name)) { + serializationObject[key] = { + id: value.id, + name: value.name, + className, + }; + } + else { + // only if it is not an object + if (typeof value !== "object") { + serializationObject[key] = value; + } + else { + throw new Error(`Could not serialize value ${value}`); + } + } + } +} +/** + * The default function that parses values stored in a serialization object + * @param key the key to the value that will be parsed + * @param serializationObject the object that will be parsed + * @param assetsContainer the assets container that will be used to find the objects + * @param scene + * @returns + */ +function defaultValueParseFunction(key, serializationObject, assetsContainer, scene) { + const intermediateValue = serializationObject[key]; + let finalValue; + const className = intermediateValue?.type ?? intermediateValue?.className; + if (isMeshClassName(className)) { + let nodes = scene.meshes.filter((m) => (intermediateValue.id ? m.id === intermediateValue.id : m.name === intermediateValue.name)); + if (nodes.length === 0) { + nodes = scene.transformNodes.filter((m) => (intermediateValue.id ? m.id === intermediateValue.id : m.name === intermediateValue.name)); + } + finalValue = intermediateValue.uniqueId ? nodes.find((m) => m.uniqueId === intermediateValue.uniqueId) : nodes[0]; + } + else if (isVectorClassName(className)) { + finalValue = parseVector(className, intermediateValue.value); + } + else if (isAnimationGroupClassName(className)) { + // do not use the scene.getAnimationGroupByName because it is possible that two AGs will have the same name + const ags = scene.animationGroups.filter((ag) => ag.name === intermediateValue.name); + // uniqueId changes on each load. this is used for the glTF loader, that uses serialization after the scene was loaded. + finalValue = ags.length === 1 ? ags[0] : ags.find((ag) => ag.uniqueId === intermediateValue.uniqueId); + } + else if (className === "Matrix" /* FlowGraphTypes.Matrix */) { + finalValue = Matrix.FromArray(intermediateValue.value); + } + else if (className === "Matrix2D" /* FlowGraphTypes.Matrix2D */) { + finalValue = new FlowGraphMatrix2D(intermediateValue.value); + } + else if (className === "Matrix3D" /* FlowGraphTypes.Matrix3D */) { + finalValue = new FlowGraphMatrix3D(intermediateValue.value); + } + else if (className === "FlowGraphInteger" /* FlowGraphTypes.Integer */) { + finalValue = FlowGraphInteger.FromValue(intermediateValue.value); + } + else if (className === "number" /* FlowGraphTypes.Number */ || className === "string" /* FlowGraphTypes.String */ || className === "boolean" /* FlowGraphTypes.Boolean */) { + finalValue = intermediateValue.value[0]; + } + else if (intermediateValue && intermediateValue.value !== undefined) { + finalValue = intermediateValue.value; + } + else { + if (Array.isArray(intermediateValue)) { + // configuration data of an event + finalValue = intermediateValue.reduce((acc, val) => { + if (!val.eventData) { + return acc; + } + acc[val.id] = { + type: getRichTypeByFlowGraphType(val.type), + }; + if (typeof val.value !== "undefined") { + acc[val.id].value = defaultValueParseFunction("value", val, assetsContainer, scene); + } + return acc; + }, {}); + } + else { + finalValue = intermediateValue; + } + } + return finalValue; +} +/** + * Given a name of a flow graph block class, return if this + * class needs to be created with a path converter. Used in + * parsing. + * @param className the name of the flow graph block class + * @returns a boolean indicating if the class needs a path converter + */ +function needsPathConverter(className) { + // I am not using the ClassName property here because it was causing a circular dependency + // that jest didn't like! + return className === "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */; +} + +/** + * The type of the assets that flow graph supports + */ +var FlowGraphAssetType; +(function (FlowGraphAssetType) { + FlowGraphAssetType["Animation"] = "Animation"; + FlowGraphAssetType["AnimationGroup"] = "AnimationGroup"; + FlowGraphAssetType["Mesh"] = "Mesh"; + FlowGraphAssetType["Material"] = "Material"; + FlowGraphAssetType["Camera"] = "Camera"; + FlowGraphAssetType["Light"] = "Light"; + // Further asset types will be added here when needed. +})(FlowGraphAssetType || (FlowGraphAssetType = {})); +/** + * Returns the asset with the given index and type from the assets context. + * @param assetsContext The assets context to get the asset from + * @param type The type of the asset + * @param index The index of the asset + * @param useIndexAsUniqueId If set to true, instead of the index in the array it will search for the unique id of the asset. + * @returns The asset or null if not found + */ +function GetFlowGraphAssetWithType(assetsContext, type, index, useIndexAsUniqueId) { + switch (type) { + case "Animation" /* FlowGraphAssetType.Animation */: + return useIndexAsUniqueId + ? (assetsContext.animations.find((a) => a.uniqueId === index) ?? null) + : (assetsContext.animations[index] ?? null); + case "AnimationGroup" /* FlowGraphAssetType.AnimationGroup */: + return useIndexAsUniqueId + ? (assetsContext.animationGroups.find((a) => a.uniqueId === index) ?? null) + : (assetsContext.animationGroups[index] ?? null); + case "Mesh" /* FlowGraphAssetType.Mesh */: + return useIndexAsUniqueId + ? (assetsContext.meshes.find((a) => a.uniqueId === index) ?? null) + : (assetsContext.meshes[index] ?? null); + case "Material" /* FlowGraphAssetType.Material */: + return useIndexAsUniqueId + ? (assetsContext.materials.find((a) => a.uniqueId === index) ?? null) + : (assetsContext.materials[index] ?? null); + case "Camera" /* FlowGraphAssetType.Camera */: + return useIndexAsUniqueId + ? (assetsContext.cameras.find((a) => a.uniqueId === index) ?? null) + : (assetsContext.cameras[index] ?? null); + case "Light" /* FlowGraphAssetType.Light */: + return useIndexAsUniqueId + ? (assetsContext.lights.find((a) => a.uniqueId === index) ?? null) + : (assetsContext.lights[index] ?? null); + default: + return null; + } +} + +var FlowGraphAction; +(function (FlowGraphAction) { + FlowGraphAction["ExecuteBlock"] = "ExecuteBlock"; + FlowGraphAction["ExecuteEvent"] = "ExecuteEvent"; + FlowGraphAction["TriggerConnection"] = "TriggerConnection"; + FlowGraphAction["ContextVariableSet"] = "ContextVariableSet"; + FlowGraphAction["GlobalVariableSet"] = "GlobalVariableSet"; + FlowGraphAction["GlobalVariableDelete"] = "GlobalVariableDelete"; + FlowGraphAction["GlobalVariableGet"] = "GlobalVariableGet"; + FlowGraphAction["AddConnection"] = "AddConnection"; + FlowGraphAction["GetConnectionValue"] = "GetConnectionValue"; + FlowGraphAction["SetConnectionValue"] = "SetConnectionValue"; + FlowGraphAction["ActivateSignal"] = "ActivateSignal"; + FlowGraphAction["ContextVariableGet"] = "ContextVariableGet"; +})(FlowGraphAction || (FlowGraphAction = {})); +/** + * This class will be responsible of logging the flow graph activity. + * Note that using this class might reduce performance, as it will log every action, according to the configuration. + * It attaches to a flow graph and uses meta-programming to replace the methods of the flow graph to add logging abilities. + */ +class FlowGraphLogger { + constructor() { + /** + * Whether to log to the console. + */ + this.logToConsole = false; + /** + * The log cache of the flow graph. + * Each item is a logged item, in order of execution. + */ + this.log = []; + } + addLogItem(item) { + if (!item.time) { + item.time = Date.now(); + } + this.log.push(item); + if (this.logToConsole) { + const value = item.payload?.value; + if (typeof value === "object" && value.getClassName) { + Logger.Log(`[FGLog] ${item.className}:${item.uniqueId.split("-")[0]} ${item.action} - ${JSON.stringify(value.getClassName())}: ${value.toString()}`); + } + else { + Logger.Log(`[FGLog] ${item.className}:${item.uniqueId.split("-")[0]} ${item.action} - ${JSON.stringify(item.payload)}`); + } + } + } + getItemsOfType(action) { + return this.log.filter((i) => i.action === action); + } +} + +/** + * The context represents the current state and execution of the flow graph. + * It contains both user-defined variables, which are derived from + * a more general variable definition, and execution variables that + * are set by the blocks. + */ +class FlowGraphContext { + /** + * Enable logging on this context + */ + get enableLogging() { + return this._enableLogging; + } + set enableLogging(value) { + if (this._enableLogging === value) { + return; + } + this._enableLogging = value; + if (this._enableLogging) { + this.logger = new FlowGraphLogger(); + this.logger.logToConsole = true; + } + else { + this.logger = null; + } + } + constructor(params) { + /** + * A randomly generated GUID for each context. + */ + this.uniqueId = RandomGUID(); + /** + * These are the variables defined by a user. + */ + this._userVariables = {}; + /** + * These are the variables set by the blocks. + */ + this._executionVariables = {}; + /** + * A context-specific global variables, available to all blocks in the context. + */ + this._globalContextVariables = {}; + /** + * These are the values for the data connection points + */ + this._connectionValues = {}; + /** + * These are blocks that have currently pending tasks/listeners that need to be cleaned up. + */ + this._pendingBlocks = []; + /** + * A monotonically increasing ID for each execution. + * Incremented for every block executed. + */ + this._executionId = 0; + /** + * Observable that is triggered when a node is executed. + */ + this.onNodeExecutedObservable = new Observable(); + /** + * Whether to treat data as right-handed. + * This is used when serializing data from a right-handed system, while running the context in a left-handed system, for example in glTF parsing. + * Default is false. + */ + this.treatDataAsRightHanded = false; + this._enableLogging = false; + this._configuration = params; + this.assetsContext = params.assetsContext ?? params.scene; + } + /** + * Check if a user-defined variable is defined. + * @param name the name of the variable + * @returns true if the variable is defined + */ + hasVariable(name) { + return name in this._userVariables; + } + /** + * Set a user-defined variable. + * @param name the name of the variable + * @param value the value of the variable + */ + setVariable(name, value) { + this._userVariables[name] = value; + this.logger?.addLogItem({ + time: Date.now(), + className: this.getClassName(), + uniqueId: this.uniqueId, + action: "ContextVariableSet" /* FlowGraphAction.ContextVariableSet */, + payload: { + name, + value, + }, + }); + } + /** + * Get an assets from the assets context based on its type and index in the array + * @param type The type of the asset + * @param index The index of the asset + * @returns The asset or null if not found + */ + getAsset(type, index) { + return GetFlowGraphAssetWithType(this.assetsContext, type, index); + } + /** + * Get a user-defined variable. + * @param name the name of the variable + * @returns the value of the variable + */ + getVariable(name) { + this.logger?.addLogItem({ + time: Date.now(), + className: this.getClassName(), + uniqueId: this.uniqueId, + action: "ContextVariableGet" /* FlowGraphAction.ContextVariableGet */, + payload: { + name, + value: this._userVariables[name], + }, + }); + return this._userVariables[name]; + } + /** + * Gets all user variables map + */ + get userVariables() { + return this._userVariables; + } + /** + * Get the scene that the context belongs to. + * @returns the scene + */ + getScene() { + return this._configuration.scene; + } + _getUniqueIdPrefixedName(obj, name) { + return `${obj.uniqueId}_${name}`; + } + /** + * @internal + * @param name name of the variable + * @param defaultValue default value to return if the variable is not defined + * @returns the variable value or the default value if the variable is not defined + */ + _getGlobalContextVariable(name, defaultValue) { + this.logger?.addLogItem({ + time: Date.now(), + className: this.getClassName(), + uniqueId: this.uniqueId, + action: "GlobalVariableGet" /* FlowGraphAction.GlobalVariableGet */, + payload: { + name, + defaultValue, + possibleValue: this._globalContextVariables[name], + }, + }); + if (this._hasGlobalContextVariable(name)) { + return this._globalContextVariables[name]; + } + else { + return defaultValue; + } + } + /** + * Set a global context variable + * @internal + * @param name the name of the variable + * @param value the value of the variable + */ + _setGlobalContextVariable(name, value) { + this.logger?.addLogItem({ + time: Date.now(), + className: this.getClassName(), + uniqueId: this.uniqueId, + action: "GlobalVariableSet" /* FlowGraphAction.GlobalVariableSet */, + payload: { name, value }, + }); + this._globalContextVariables[name] = value; + } + /** + * Delete a global context variable + * @internal + * @param name the name of the variable + */ + _deleteGlobalContextVariable(name) { + this.logger?.addLogItem({ + time: Date.now(), + className: this.getClassName(), + uniqueId: this.uniqueId, + action: "GlobalVariableDelete" /* FlowGraphAction.GlobalVariableDelete */, + payload: { name }, + }); + delete this._globalContextVariables[name]; + } + /** + * Check if a global context variable is defined + * @internal + * @param name the name of the variable + * @returns true if the variable is defined + */ + _hasGlobalContextVariable(name) { + return name in this._globalContextVariables; + } + /** + * Set an internal execution variable + * @internal + * @param name + * @param value + */ + _setExecutionVariable(block, name, value) { + this._executionVariables[this._getUniqueIdPrefixedName(block, name)] = value; + } + /** + * Get an internal execution variable + * @internal + * @param name + * @returns + */ + _getExecutionVariable(block, name, defaultValue) { + if (this._hasExecutionVariable(block, name)) { + return this._executionVariables[this._getUniqueIdPrefixedName(block, name)]; + } + else { + return defaultValue; + } + } + /** + * Delete an internal execution variable + * @internal + * @param block + * @param name + */ + _deleteExecutionVariable(block, name) { + delete this._executionVariables[this._getUniqueIdPrefixedName(block, name)]; + } + /** + * Check if an internal execution variable is defined + * @internal + * @param block + * @param name + * @returns + */ + _hasExecutionVariable(block, name) { + return this._getUniqueIdPrefixedName(block, name) in this._executionVariables; + } + /** + * Check if a connection value is defined + * @internal + * @param connectionPoint + * @returns + */ + _hasConnectionValue(connectionPoint) { + return connectionPoint.uniqueId in this._connectionValues; + } + /** + * Set a connection value + * @internal + * @param connectionPoint + * @param value + */ + _setConnectionValue(connectionPoint, value) { + this._connectionValues[connectionPoint.uniqueId] = value; + this.logger?.addLogItem({ + time: Date.now(), + className: this.getClassName(), + uniqueId: this.uniqueId, + action: "SetConnectionValue" /* FlowGraphAction.SetConnectionValue */, + payload: { + connectionPointId: connectionPoint.uniqueId, + value, + }, + }); + } + /** + * Set a connection value by key + * @internal + * @param key the key of the connection value + * @param value the value of the connection + */ + _setConnectionValueByKey(key, value) { + this._connectionValues[key] = value; + } + /** + * Get a connection value + * @internal + * @param connectionPoint + * @returns + */ + _getConnectionValue(connectionPoint) { + this.logger?.addLogItem({ + time: Date.now(), + className: this.getClassName(), + uniqueId: this.uniqueId, + action: "GetConnectionValue" /* FlowGraphAction.GetConnectionValue */, + payload: { + connectionPointId: connectionPoint.uniqueId, + value: this._connectionValues[connectionPoint.uniqueId], + }, + }); + return this._connectionValues[connectionPoint.uniqueId]; + } + /** + * Get the configuration + * @internal + * @param name + * @param value + */ + get configuration() { + return this._configuration; + } + /** + * Check if there are any pending blocks in this context + * @returns true if there are pending blocks + */ + get hasPendingBlocks() { + return this._pendingBlocks.length > 0; + } + /** + * Add a block to the list of blocks that have pending tasks. + * @internal + * @param block + */ + _addPendingBlock(block) { + // check if block is already in the array + if (this._pendingBlocks.includes(block)) { + return; + } + this._pendingBlocks.push(block); + // sort pending blocks by priority + this._pendingBlocks.sort((a, b) => a.priority - b.priority); + } + /** + * Remove a block from the list of blocks that have pending tasks. + * @internal + * @param block + */ + _removePendingBlock(block) { + const index = this._pendingBlocks.indexOf(block); + if (index !== -1) { + this._pendingBlocks.splice(index, 1); + } + } + /** + * Clear all pending blocks. + * @internal + */ + _clearPendingBlocks() { + for (const block of this._pendingBlocks) { + block._cancelPendingTasks(this); + } + this._pendingBlocks.length = 0; + } + /** + * @internal + * Function that notifies the node executed observable + * @param node + */ + _notifyExecuteNode(node) { + this.onNodeExecutedObservable.notifyObservers(node); + this.logger?.addLogItem({ + time: Date.now(), + className: node.getClassName(), + uniqueId: node.uniqueId, + action: "ExecuteBlock" /* FlowGraphAction.ExecuteBlock */, + }); + } + _notifyOnTick(framePayload) { + // set the values as global variables + this._setGlobalContextVariable("timeSinceStart", framePayload.timeSinceStart); + this._setGlobalContextVariable("deltaTime", framePayload.deltaTime); + // iterate the pending blocks and run each one's onFrame function + for (const block of this._pendingBlocks) { + block._executeOnTick?.(this); + } + } + /** + * @internal + */ + _increaseExecutionId() { + this._executionId++; + } + /** + * A monotonically increasing ID for each execution. + * Incremented for every block executed. + */ + get executionId() { + return this._executionId; + } + /** + * Serializes a context + * @param serializationObject the object to write the values in + * @param valueSerializationFunction a function to serialize complex values + */ + serialize(serializationObject = {}, valueSerializationFunction = defaultValueSerializationFunction) { + serializationObject.uniqueId = this.uniqueId; + serializationObject._userVariables = {}; + for (const key in this._userVariables) { + valueSerializationFunction(key, this._userVariables[key], serializationObject._userVariables); + } + serializationObject._connectionValues = {}; + for (const key in this._connectionValues) { + valueSerializationFunction(key, this._connectionValues[key], serializationObject._connectionValues); + } + // serialize assets context, if not scene + if (this.assetsContext !== this.getScene()) { + serializationObject._assetsContext = { + meshes: this.assetsContext.meshes.map((m) => m.id), + materials: this.assetsContext.materials.map((m) => m.id), + textures: this.assetsContext.textures.map((m) => m.name), + animations: this.assetsContext.animations.map((m) => m.name), + lights: this.assetsContext.lights.map((m) => m.id), + cameras: this.assetsContext.cameras.map((m) => m.id), + sounds: this.assetsContext.sounds?.map((m) => m.name), + skeletons: this.assetsContext.skeletons.map((m) => m.id), + particleSystems: this.assetsContext.particleSystems.map((m) => m.name), + geometries: this.assetsContext.geometries.map((m) => m.id), + multiMaterials: this.assetsContext.multiMaterials.map((m) => m.id), + transformNodes: this.assetsContext.transformNodes.map((m) => m.id), + }; + } + } + /** + * @returns the class name of the object. + */ + getClassName() { + return "FlowGraphContext"; + } +} +__decorate([ + serialize() +], FlowGraphContext.prototype, "uniqueId", void 0); + +/** + * The type of a connection point - input or output. + */ +var FlowGraphConnectionType; +(function (FlowGraphConnectionType) { + FlowGraphConnectionType[FlowGraphConnectionType["Input"] = 0] = "Input"; + FlowGraphConnectionType[FlowGraphConnectionType["Output"] = 1] = "Output"; +})(FlowGraphConnectionType || (FlowGraphConnectionType = {})); +/** + * The base connection class. + */ +class FlowGraphConnection { + constructor(name, _connectionType, + /* @internal */ _ownerBlock) { + this._ownerBlock = _ownerBlock; + /** @internal */ + this._connectedPoint = []; + /** + * A uniquely identifying string for the connection. + */ + this.uniqueId = RandomGUID(); + /** + * Used for parsing connections. + * @internal + */ + // disable warning as this is used for parsing + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this.connectedPointIds = []; + this.name = name; + this._connectionType = _connectionType; + } + /** + * The type of the connection + */ + get connectionType() { + return this._connectionType; + } + /** + * @internal + * Override this to indicate if a point can connect to more than one point. + */ + _isSingularConnection() { + return true; + } + /** + * Returns if a point is connected to any other point. + * @returns boolean indicating if the point is connected. + */ + isConnected() { + return this._connectedPoint.length > 0; + } + /** + * Connects two connections together. + * @param point the connection to connect to. + */ + connectTo(point) { + if (this._connectionType === point._connectionType) { + throw new Error(`Cannot connect two points of type ${this.connectionType}`); + } + if ((this._isSingularConnection() && this._connectedPoint.length > 0) || (point._isSingularConnection() && point._connectedPoint.length > 0)) { + throw new Error("Max number of connections for point reached"); + } + this._connectedPoint.push(point); + point._connectedPoint.push(this); + } + /** + * Disconnects two connections. + * @param point the connection to disconnect from. + * @param removeFromLocal if true, the connection will be removed from the local connection list. + */ + disconnectFrom(point, removeFromLocal = true) { + const indexLocal = this._connectedPoint.indexOf(point); + const indexConnected = point._connectedPoint.indexOf(this); + if (indexLocal === -1 || indexConnected === -1) { + return; + } + if (removeFromLocal) { + this._connectedPoint.splice(indexLocal, 1); + } + point._connectedPoint.splice(indexConnected, 1); + } + /** + * Disconnects all connected points. + */ + disconnectFromAll() { + for (const point of this._connectedPoint) { + this.disconnectFrom(point, false); + } + this._connectedPoint.length = 0; + } + dispose() { + for (const point of this._connectedPoint) { + this.disconnectFrom(point); + } + } + /** + * Saves the connection to a JSON object. + * @param serializationObject the object to serialize to. + */ + serialize(serializationObject = {}) { + serializationObject.uniqueId = this.uniqueId; + serializationObject.name = this.name; + serializationObject._connectionType = this._connectionType; + serializationObject.connectedPointIds = []; + serializationObject.className = this.getClassName(); + for (const point of this._connectedPoint) { + serializationObject.connectedPointIds.push(point.uniqueId); + } + } + /** + * @returns class name of the connection. + */ + getClassName() { + return "FGConnection"; + } + /** + * Deserialize from a object into this + * @param serializationObject the object to deserialize from. + */ + deserialize(serializationObject) { + this.uniqueId = serializationObject.uniqueId; + this.name = serializationObject.name; + this._connectionType = serializationObject._connectionType; + this.connectedPointIds = serializationObject.connectedPointIds; + } +} + +/** + * Represents a connection point for data. + * An unconnected input point can have a default value. + * An output point will only have a value if it is connected to an input point. Furthermore, + * if the point belongs to a "function" node, the node will run its function to update the value. + */ +class FlowGraphDataConnection extends FlowGraphConnection { + /** + * Create a new data connection point. + * @param name the name of the connection + * @param connectionType the type of the connection + * @param ownerBlock the block that owns this connection + * @param richType the type of the data in this block + * @param _defaultValue the default value of the connection + * @param _optional if the connection is optional + */ + constructor(name, connectionType, ownerBlock, + /** + * the type of the data in this block + */ + richType, + /** + * [any] the default value of the connection + */ + _defaultValue = richType.defaultValue, + /** + * [false] if the connection is optional + */ + _optional = false) { + super(name, connectionType, ownerBlock); + this.richType = richType; + this._defaultValue = _defaultValue; + this._optional = _optional; + this._isDisabled = false; + /** + * This is used for debugging purposes! It is the last value that was set to this connection with ANY context. + * Do not use this value for anything else, as it might be wrong if used in a different context. + */ + this._lastValue = null; + /** + * a data transformer function, if needed. + * This can be used, for example, to force seconds into milliseconds output, if it makes sense in your case. + */ + this.dataTransformer = null; + /** + * An observable that is triggered when the value of the connection changes. + */ + this.onValueChangedObservable = new Observable(); + } + /** + * Whether or not the connection is optional. + * Currently only used for UI control. + */ + get optional() { + return this._optional; + } + /** + * is this connection disabled + * If the connection is disabled you will not be able to connect anything to it. + */ + get isDisabled() { + return this._isDisabled; + } + set isDisabled(value) { + if (this._isDisabled === value) { + return; + } + this._isDisabled = value; + if (this._isDisabled) { + this.disconnectFromAll(); + } + } + /** + * An output data block can connect to multiple input data blocks, + * but an input data block can only connect to one output data block. + * @returns true if the connection is singular + */ + _isSingularConnection() { + return this.connectionType === 0 /* FlowGraphConnectionType.Input */; + } + /** + * Set the value of the connection in a specific context. + * @param value the value to set + * @param context the context to which the value is set + */ + setValue(value, context) { + // check if the value is different + if (context._getConnectionValue(this) === value) { + return; + } + context._setConnectionValue(this, value); + this.onValueChangedObservable.notifyObservers(value); + } + /** + * Reset the value of the connection to the default value. + * @param context the context in which the value is reset + */ + resetToDefaultValue(context) { + context._setConnectionValue(this, this._defaultValue); + } + /** + * Connect this point to another point. + * @param point the point to connect to. + */ + connectTo(point) { + if (this._isDisabled) { + return; + } + super.connectTo(point); + } + _getValueOrDefault(context) { + const val = context._getConnectionValue(this) ?? this._defaultValue; + return this.dataTransformer ? this.dataTransformer(val) : val; + } + /** + * Gets the value of the connection in a specific context. + * @param context the context from which the value is retrieved + * @returns the value of the connection + */ + getValue(context) { + if (this.connectionType === 1 /* FlowGraphConnectionType.Output */) { + context._notifyExecuteNode(this._ownerBlock); + this._ownerBlock._updateOutputs(context); + const value = this._getValueOrDefault(context); + this._lastValue = value; + return this.richType.typeTransformer ? this.richType.typeTransformer(value) : value; + } + const value = !this.isConnected() ? this._getValueOrDefault(context) : this._connectedPoint[0].getValue(context); + this._lastValue = value; + return this.richType.typeTransformer ? this.richType.typeTransformer(value) : value; + } + /** + * @internal + */ + _getLastValue() { + return this._lastValue; + } + /** + * @returns class name of the object. + */ + getClassName() { + return "FlowGraphDataConnection"; + } + /** + * Serializes this object. + * @param serializationObject the object to serialize to + */ + serialize(serializationObject = {}) { + super.serialize(serializationObject); + serializationObject.richType = {}; + this.richType.serialize(serializationObject.richType); + serializationObject.optional = this._optional; + defaultValueSerializationFunction("defaultValue", this._defaultValue, serializationObject); + } +} +RegisterClass("FlowGraphDataConnection", FlowGraphDataConnection); + +/** + * A block in a flow graph. The most basic form + * of a block has inputs and outputs that contain + * data. + */ +class FlowGraphBlock { + /** Constructor is protected so only subclasses can be instantiated + * @param config optional configuration for this block + * @internal - do not use directly. Extend this class instead. + */ + constructor( + /** + * the configuration of the block + */ + config) { + this.config = config; + /** + * A randomly generated GUID for each block. + */ + this.uniqueId = RandomGUID(); + this.name = this.config?.name ?? this.getClassName(); + this.dataInputs = []; + this.dataOutputs = []; + } + /** + * @internal + * This function is called when the block needs to update its output flows. + * @param _context the context in which it is running + */ + _updateOutputs(_context) { + // empty by default, overridden in data blocks + } + /** + * Registers a data input on the block. + * @param name the name of the input + * @param richType the type of the input + * @param defaultValue optional default value of the input. If not set, the rich type's default value will be used. + * @returns the created connection + */ + registerDataInput(name, richType, defaultValue) { + const input = new FlowGraphDataConnection(name, 0 /* FlowGraphConnectionType.Input */, this, richType, defaultValue); + this.dataInputs.push(input); + return input; + } + /** + * Registers a data output on the block. + * @param name the name of the input + * @param richType the type of the input + * @param defaultValue optional default value of the input. If not set, the rich type's default value will be used. + * @returns the created connection + */ + registerDataOutput(name, richType, defaultValue) { + const output = new FlowGraphDataConnection(name, 1 /* FlowGraphConnectionType.Output */, this, richType, defaultValue); + this.dataOutputs.push(output); + return output; + } + /** + * Given the name of a data input, returns the connection if it exists + * @param name the name of the input + * @returns the connection if it exists, undefined otherwise + */ + getDataInput(name) { + return this.dataInputs.find((i) => i.name === name); + } + /** + * Given the name of a data output, returns the connection if it exists + * @param name the name of the output + * @returns the connection if it exists, undefined otherwise + */ + getDataOutput(name) { + return this.dataOutputs.find((i) => i.name === name); + } + /** + * Serializes this block + * @param serializationObject the object to serialize to + * @param _valueSerializeFunction a function that serializes a specific value + */ + serialize(serializationObject = {}, _valueSerializeFunction = defaultValueSerializationFunction) { + serializationObject.uniqueId = this.uniqueId; + serializationObject.config = {}; + if (this.config) { + const config = this.config; + Object.keys(this.config).forEach((key) => { + _valueSerializeFunction(key, config[key], serializationObject.config); + }); + } + serializationObject.dataInputs = []; + serializationObject.dataOutputs = []; + serializationObject.className = this.getClassName(); + for (const input of this.dataInputs) { + const serializedInput = {}; + input.serialize(serializedInput); + serializationObject.dataInputs.push(serializedInput); + } + for (const output of this.dataOutputs) { + const serializedOutput = {}; + output.serialize(serializedOutput); + serializationObject.dataOutputs.push(serializedOutput); + } + } + /** + * Deserializes this block + * @param _serializationObject the object to deserialize from + */ + deserialize(_serializationObject) { + // no-op by default + } + _log(context, action, payload) { + context.logger?.addLogItem({ + action, + payload, + className: this.getClassName(), + uniqueId: this.uniqueId, + }); + } + /** + * Gets the class name of this block + * @returns the class name + */ + getClassName() { + return "FlowGraphBlock"; + } +} + +/** + * Represents a connection point for a signal. + * When an output point is activated, it will activate the connected input point. + * When an input point is activated, it will execute the block it belongs to. + */ +class FlowGraphSignalConnection extends FlowGraphConnection { + constructor() { + super(...arguments); + /** + * The priority of the signal. Signals with higher priority will be executed first. + * Set priority before adding the connection as sorting happens only when the connection is added. + */ + this.priority = 0; + } + _isSingularConnection() { + return false; + } + connectTo(point) { + super.connectTo(point); + // sort according to priority to handle execution order + this._connectedPoint.sort((a, b) => b.priority - a.priority); + } + /** + * @internal + */ + _activateSignal(context) { + context.logger?.addLogItem({ + action: "ActivateSignal" /* FlowGraphAction.ActivateSignal */, + className: this._ownerBlock.getClassName(), + uniqueId: this._ownerBlock.uniqueId, + payload: { + connectionType: this.connectionType, + name: this.name, + }, + }); + if (this.connectionType === 0 /* FlowGraphConnectionType.Input */) { + context._notifyExecuteNode(this._ownerBlock); + this._ownerBlock._execute(context, this); + context._increaseExecutionId(); + } + else { + for (const connectedPoint of this._connectedPoint) { + connectedPoint._activateSignal(context); + } + } + } +} +RegisterClass("FlowGraphSignalConnection", FlowGraphSignalConnection); + +/** + * A block that executes some action. Always has an input signal (which is not used by event blocks). + * Can have one or more output signals. + */ +class FlowGraphExecutionBlock extends FlowGraphBlock { + constructor(config) { + super(config); + /** + * The priority of the block. Higher priority blocks will be executed first. + * Note that priority cannot be change AFTER the block was added as sorting happens when the block is added to the execution queue. + */ + this.priority = 0; + this.signalInputs = []; + this.signalOutputs = []; + this.in = this._registerSignalInput("in"); + this.error = this._registerSignalOutput("error"); + } + _registerSignalInput(name) { + const input = new FlowGraphSignalConnection(name, 0 /* FlowGraphConnectionType.Input */, this); + this.signalInputs.push(input); + return input; + } + _registerSignalOutput(name) { + const output = new FlowGraphSignalConnection(name, 1 /* FlowGraphConnectionType.Output */, this); + this.signalOutputs.push(output); + return output; + } + _unregisterSignalInput(name) { + const index = this.signalInputs.findIndex((input) => input.name === name); + if (index !== -1) { + this.signalInputs[index].dispose(); + this.signalInputs.splice(index, 1); + } + } + _unregisterSignalOutput(name) { + const index = this.signalOutputs.findIndex((output) => output.name === name); + if (index !== -1) { + this.signalOutputs[index].dispose(); + this.signalOutputs.splice(index, 1); + } + } + _reportError(context, error) { + this.error.payload = typeof error === "string" ? new Error(error) : error; + this.error._activateSignal(context); + } + /** + * Given a name of a signal input, return that input if it exists + * @param name the name of the input + * @returns if the input exists, the input. Otherwise, undefined. + */ + getSignalInput(name) { + return this.signalInputs.find((input) => input.name === name); + } + /** + * Given a name of a signal output, return that input if it exists + * @param name the name of the input + * @returns if the input exists, the input. Otherwise, undefined. + */ + getSignalOutput(name) { + return this.signalOutputs.find((output) => output.name === name); + } + /** + * Serializes this block + * @param serializationObject the object to serialize in + */ + serialize(serializationObject = {}) { + super.serialize(serializationObject); + serializationObject.signalInputs = []; + serializationObject.signalOutputs = []; + for (const input of this.signalInputs) { + const serializedInput = {}; + input.serialize(serializedInput); + serializationObject.signalInputs.push(serializedInput); + } + for (const output of this.signalOutputs) { + const serializedOutput = {}; + output.serialize(serializedOutput); + serializationObject.signalOutputs.push(serializedOutput); + } + } + /** + * Deserializes from an object + * @param serializationObject the object to deserialize from + */ + deserialize(serializationObject) { + for (let i = 0; i < serializationObject.signalInputs.length; i++) { + const signalInput = this.getSignalInput(serializationObject.signalInputs[i].name); + if (signalInput) { + signalInput.deserialize(serializationObject.signalInputs[i]); + } + else { + throw new Error("Could not find signal input with name " + serializationObject.signalInputs[i].name + " in block " + serializationObject.className); + } + } + for (let i = 0; i < serializationObject.signalOutputs.length; i++) { + const signalOutput = this.getSignalOutput(serializationObject.signalOutputs[i].name); + if (signalOutput) { + signalOutput.deserialize(serializationObject.signalOutputs[i]); + } + else { + throw new Error("Could not find signal output with name " + serializationObject.signalOutputs[i].name + " in block " + serializationObject.className); + } + } + } + /** + * @returns the class name + */ + getClassName() { + return "FlowGraphExecutionBlock"; + } +} + +/** + * This class is responsible for coordinating the events that are triggered in the scene. + * It registers all observers needed to track certain events and triggers the blocks that are listening to them. + * Abstracting the events from the class will allow us to easily change the events that are being listened to, and trigger them in any order. + */ +class FlowGraphSceneEventCoordinator { + constructor(scene) { + /** + * register to this observable to get flow graph event notifications. + */ + this.onEventTriggeredObservable = new Observable(); + /** + * Was scene-ready already triggered? + */ + this.sceneReadyTriggered = false; + this._pointerUnderMeshState = {}; + this._startingTime = 0; + this._scene = scene; + this._initialize(); + } + _initialize() { + this._sceneReadyObserver = this._scene.onReadyObservable.add(() => { + if (!this.sceneReadyTriggered) { + this.onEventTriggeredObservable.notifyObservers({ type: "SceneReady" /* FlowGraphEventType.SceneReady */ }); + this.sceneReadyTriggered = true; + } + }); + this._sceneDisposeObserver = this._scene.onDisposeObservable.add(() => { + this.onEventTriggeredObservable.notifyObservers({ type: "SceneDispose" /* FlowGraphEventType.SceneDispose */ }); + }); + this._sceneOnBeforeRenderObserver = this._scene.onBeforeRenderObservable.add(() => { + const deltaTime = this._scene.getEngine().getDeltaTime() / 1000; // set in seconds + this.onEventTriggeredObservable.notifyObservers({ + type: "SceneBeforeRender" /* FlowGraphEventType.SceneBeforeRender */, + payload: { + timeSinceStart: this._startingTime, + deltaTime, + }, + }); + this._startingTime += deltaTime; + }); + this._meshPickedObserver = this._scene.onPointerObservable.add((pointerInfo) => { + this.onEventTriggeredObservable.notifyObservers({ type: "MeshPick" /* FlowGraphEventType.MeshPick */, payload: pointerInfo }); + }, PointerEventTypes.POINTERPICK); // should it be pointerdown? + this._meshUnderPointerObserver = this._scene.onMeshUnderPointerUpdatedObservable.add((data) => { + // check if the data has changed. Check the state of the last change and see if it is a mesh or null. + // if it is a mesh and the previous state was null, trigger over event. If it is null and the previous state was a mesh, trigger out event. + // if it is a mesh and the previous state was a mesh, trigger out from the old mesh and over the new mesh + // if it is null and the previous state was null, do nothing. + const pointerId = data.pointerId; + const mesh = data.mesh; + const previousState = this._pointerUnderMeshState[pointerId]; + if (!previousState && mesh) { + this.onEventTriggeredObservable.notifyObservers({ type: "PointerOver" /* FlowGraphEventType.PointerOver */, payload: { pointerId, mesh } }); + } + else if (previousState && !mesh) { + this.onEventTriggeredObservable.notifyObservers({ type: "PointerOut" /* FlowGraphEventType.PointerOut */, payload: { pointerId, mesh: previousState } }); + } + else if (previousState && mesh && previousState !== mesh) { + this.onEventTriggeredObservable.notifyObservers({ type: "PointerOut" /* FlowGraphEventType.PointerOut */, payload: { pointerId, mesh: previousState, over: mesh } }); + this.onEventTriggeredObservable.notifyObservers({ type: "PointerOver" /* FlowGraphEventType.PointerOver */, payload: { pointerId, mesh, out: previousState } }); + } + this._pointerUnderMeshState[pointerId] = mesh; + }, PointerEventTypes.POINTERMOVE); + } + dispose() { + this._sceneDisposeObserver?.remove(); + this._sceneReadyObserver?.remove(); + this._sceneOnBeforeRenderObserver?.remove(); + this._meshPickedObserver?.remove(); + this._meshUnderPointerObserver?.remove(); + this.onEventTriggeredObservable.clear(); + } +} + +/** + * @internal + * Returns if mesh1 is a descendant of mesh2 + * @param mesh1 + * @param mesh2 + * @returns + */ +function _isADescendantOf(mesh1, mesh2) { + return !!(mesh1.parent && (mesh1.parent === mesh2 || _isADescendantOf(mesh1.parent, mesh2))); +} +/** + * @internal + */ +function _getClassNameOf(v) { + if (v.getClassName) { + return v.getClassName(); + } + return; +} +/** + * @internal + * Check if two classname are the same and are vector classes. + * @param className the first class name + * @param className2 the second class name + * @returns whether the two class names are the same and are vector classes. + */ +function _areSameVectorClass(className, className2) { + return className === className2 && (className === "Vector2" /* FlowGraphTypes.Vector2 */ || className === "Vector3" /* FlowGraphTypes.Vector3 */ || className === "Vector4" /* FlowGraphTypes.Vector4 */); +} +/** + * @internal + * Check if two classname are the same and are matrix classes. + * @param className the first class name + * @param className2 the second class name + * @returns whether the two class names are the same and are matrix classes. + */ +function _areSameMatrixClass(className, className2) { + return className === className2 && (className === "Matrix" /* FlowGraphTypes.Matrix */ || className === "Matrix2D" /* FlowGraphTypes.Matrix2D */ || className === "Matrix3D" /* FlowGraphTypes.Matrix3D */); +} +/** + * @internal + * Check if two classname are the same and are integer classes. + * @param className the first class name + * @param className2 the second class name + * @returns whether the two class names are the same and are integer classes. + */ +function _areSameIntegerClass(className, className2) { + return className === "FlowGraphInteger" && className2 === "FlowGraphInteger"; +} +/** + * Check if an object has a numeric value. + * @param a the object to check if it is a number. + * @param validIfNaN whether to consider NaN as a valid number. + * @returns whether a is a FlowGraphNumber (Integer or number). + */ +function isNumeric(a, validIfNaN) { + const isNumeric = typeof a === "number" || typeof a?.value === "number"; + if (isNumeric && true) { + return !isNaN(getNumericValue(a)); + } + return isNumeric; +} +/** + * Get the numeric value of a FlowGraphNumber. + * @param a the object to get the numeric value from. + * @returns the numeric value. + */ +function getNumericValue(a) { + return typeof a === "number" ? a : a.value; +} + +var FlowGraphState; +(function (FlowGraphState) { + /** + * The graph is stopped + */ + FlowGraphState[FlowGraphState["Stopped"] = 0] = "Stopped"; + /** + * The graph is running + */ + FlowGraphState[FlowGraphState["Started"] = 1] = "Started"; +})(FlowGraphState || (FlowGraphState = {})); +/** + * Class used to represent a flow graph. + * A flow graph is a graph of blocks that can be used to create complex logic. + * Blocks can be added to the graph and connected to each other. + * The graph can then be started, which will init and start all of its event blocks. + * + * @experimental FlowGraph is still in development and is subject to change. + */ +class FlowGraph { + /** + * The state of the graph + */ + get state() { + return this._state; + } + /** + * The state of the graph + */ + set state(value) { + this._state = value; + this.onStateChangedObservable.notifyObservers(value); + } + /** + * Construct a Flow Graph + * @param params construction parameters. currently only the scene + */ + constructor(params) { + /** + * An observable that is triggered when the state of the graph changes. + */ + this.onStateChangedObservable = new Observable(); + /** @internal */ + this._eventBlocks = { + ["SceneReady" /* FlowGraphEventType.SceneReady */]: [], + ["SceneDispose" /* FlowGraphEventType.SceneDispose */]: [], + ["SceneBeforeRender" /* FlowGraphEventType.SceneBeforeRender */]: [], + ["MeshPick" /* FlowGraphEventType.MeshPick */]: [], + ["PointerDown" /* FlowGraphEventType.PointerDown */]: [], + ["PointerUp" /* FlowGraphEventType.PointerUp */]: [], + ["PointerMove" /* FlowGraphEventType.PointerMove */]: [], + ["PointerOver" /* FlowGraphEventType.PointerOver */]: [], + ["PointerOut" /* FlowGraphEventType.PointerOut */]: [], + ["SceneAfterRender" /* FlowGraphEventType.SceneAfterRender */]: [], + ["NoTrigger" /* FlowGraphEventType.NoTrigger */]: [], + }; + this._executionContexts = []; + /** + * The state of the graph + */ + this._state = 0 /* FlowGraphState.Stopped */; + this._scene = params.scene; + this._sceneEventCoordinator = new FlowGraphSceneEventCoordinator(this._scene); + this._coordinator = params.coordinator; + this._eventObserver = this._sceneEventCoordinator.onEventTriggeredObservable.add((event) => { + for (const context of this._executionContexts) { + const order = this._getContextualOrder(event.type, context); + for (const block of order) { + // iterate contexts + if (!block._executeEvent(context, event.payload)) { + break; + } + } + } + // custom behavior(s) of specific events + switch (event.type) { + case "SceneReady" /* FlowGraphEventType.SceneReady */: + this._sceneEventCoordinator.sceneReadyTriggered = true; + break; + case "SceneBeforeRender" /* FlowGraphEventType.SceneBeforeRender */: + for (const context of this._executionContexts) { + context._notifyOnTick(event.payload); + } + break; + case "SceneDispose" /* FlowGraphEventType.SceneDispose */: + this.dispose(); + break; + } + }); + } + /** + * Create a context. A context represents one self contained execution for the graph, with its own variables. + * @returns the context, where you can get and set variables + */ + createContext() { + const context = new FlowGraphContext({ scene: this._scene, coordinator: this._coordinator }); + this._executionContexts.push(context); + return context; + } + /** + * Returns the execution context at a given index + * @param index the index of the context + * @returns the execution context at that index + */ + getContext(index) { + return this._executionContexts[index]; + } + /** + * Add an event block. When the graph is started, it will start listening to events + * from the block and execute the graph when they are triggered. + * @param block the event block to be added + */ + addEventBlock(block) { + if (block.type === "PointerOver" /* FlowGraphEventType.PointerOver */ || block.type === "PointerOut" /* FlowGraphEventType.PointerOut */) { + this._scene.constantlyUpdateMeshUnderPointer = true; + } + // don't add if NoTrigger, but still start the pending tasks + if (block.type !== "NoTrigger" /* FlowGraphEventType.NoTrigger */) { + this._eventBlocks[block.type].push(block); + } + // if already started, sort and add to the pending + if (this.state === 1 /* FlowGraphState.Started */) { + for (const context of this._executionContexts) { + block._startPendingTasks(context); + } + } + else { + this.onStateChangedObservable.addOnce((state) => { + if (state === 1 /* FlowGraphState.Started */) { + for (const context of this._executionContexts) { + block._startPendingTasks(context); + } + } + }); + } + } + /** + * Starts the flow graph. Initializes the event blocks and starts listening to events. + */ + start() { + if (this.state === 1 /* FlowGraphState.Started */) { + return; + } + if (this._executionContexts.length === 0) { + this.createContext(); + } + this.onStateChangedObservable.add((state) => { + if (state === 1 /* FlowGraphState.Started */) { + this._startPendingEvents(); + // the only event we need to check is the scene ready event. If the scene is already ready when the graph starts, we should start the pending tasks. + if (this._scene.isReady(true)) { + this._sceneEventCoordinator.onEventTriggeredObservable.notifyObservers({ type: "SceneReady" /* FlowGraphEventType.SceneReady */ }); + } + } + }); + this.state = 1 /* FlowGraphState.Started */; + } + _startPendingEvents() { + for (const context of this._executionContexts) { + for (const type in this._eventBlocks) { + const order = this._getContextualOrder(type, context); + for (const block of order) { + block._startPendingTasks(context); + } + } + } + } + _getContextualOrder(type, context) { + const order = this._eventBlocks[type].sort((a, b) => b.initPriority - a.initPriority); + if (type === "MeshPick" /* FlowGraphEventType.MeshPick */) { + const meshPickOrder = []; + for (const block1 of order) { + // If the block is a mesh pick, guarantee that picks of children meshes come before picks of parent meshes + const mesh1 = block1.asset.getValue(context); + let i = 0; + for (; i < order.length; i++) { + const block2 = order[i]; + const mesh2 = block2.asset.getValue(context); + if (mesh1 && mesh2 && _isADescendantOf(mesh1, mesh2)) { + break; + } + } + meshPickOrder.splice(i, 0, block1); + } + return meshPickOrder; + } + return order; + } + /** + * Disposes of the flow graph. Cancels any pending tasks and removes all event listeners. + */ + dispose() { + if (this.state === 0 /* FlowGraphState.Stopped */) { + return; + } + this.state = 0 /* FlowGraphState.Stopped */; + for (const context of this._executionContexts) { + context._clearPendingBlocks(); + } + this._executionContexts.length = 0; + for (const type in this._eventBlocks) { + this._eventBlocks[type].length = 0; + } + this._eventObserver?.remove(); + this._sceneEventCoordinator.dispose(); + } + /** + * Executes a function in all blocks of a flow graph, starting with the event blocks. + * @param visitor the function to execute. + */ + visitAllBlocks(visitor) { + const visitList = []; + const idsAddedToVisitList = new Set(); + for (const type in this._eventBlocks) { + for (const block of this._eventBlocks[type]) { + visitList.push(block); + idsAddedToVisitList.add(block.uniqueId); + } + } + while (visitList.length > 0) { + const block = visitList.pop(); + visitor(block); + for (const dataIn of block.dataInputs) { + for (const connection of dataIn._connectedPoint) { + if (!idsAddedToVisitList.has(connection._ownerBlock.uniqueId)) { + visitList.push(connection._ownerBlock); + idsAddedToVisitList.add(connection._ownerBlock.uniqueId); + } + } + } + if (block instanceof FlowGraphExecutionBlock) { + for (const signalOut of block.signalOutputs) { + for (const connection of signalOut._connectedPoint) { + if (!idsAddedToVisitList.has(connection._ownerBlock.uniqueId)) { + visitList.push(connection._ownerBlock); + idsAddedToVisitList.add(connection._ownerBlock.uniqueId); + } + } + } + } + } + } + /** + * Serializes a graph + * @param serializationObject the object to write the values in + * @param valueSerializeFunction a function to serialize complex values + */ + serialize(serializationObject = {}, valueSerializeFunction) { + serializationObject.allBlocks = []; + this.visitAllBlocks((block) => { + const serializedBlock = {}; + block.serialize(serializedBlock); + serializationObject.allBlocks.push(serializedBlock); + }); + serializationObject.executionContexts = []; + for (const context of this._executionContexts) { + const serializedContext = {}; + context.serialize(serializedContext, valueSerializeFunction); + serializationObject.executionContexts.push(serializedContext); + } + } +} + +/** + * This class holds all of the existing flow graphs and is responsible for creating new ones. + * It also handles starting/stopping multiple graphs and communication between them through an Event Coordinator + * This is the entry point for the flow graph system. + * @experimental This class is still in development and is subject to change. + */ +class FlowGraphCoordinator { + constructor( + /** + * the configuration of the block + */ + config) { + this.config = config; + /** + * When set to true (default) custom events will be dispatched synchronously. + * This means that the events will be dispatched immediately when they are triggered. + */ + this.dispatchEventsSynchronously = true; + this._flowGraphs = []; + this._customEventsMap = new Map(); + this._eventExecutionCounter = new Map(); + this._executeOnNextFrame = []; + // When the scene is disposed, dispose all graphs currently running on it. + this._disposeObserver = this.config.scene.onDisposeObservable.add(() => { + this.dispose(); + }); + this._onBeforeRenderObserver = this.config.scene.onBeforeRenderObservable.add(() => { + // Reset the event execution counter at the beginning of each frame. + this._eventExecutionCounter.clear(); + if (this._executeOnNextFrame.length) { + // Execute the events that were triggered on the next frame. + this._executeOnNextFrame.forEach((event) => { + this.notifyCustomEvent(event.id, event.data, false); + }); + this._executeOnNextFrame.length = 0; + } + }); + // Add itself to the SceneCoordinators list for the Inspector. + const coordinators = FlowGraphCoordinator.SceneCoordinators.get(this.config.scene) ?? []; + coordinators.push(this); + } + /** + * Creates a new flow graph and adds it to the list of existing flow graphs + * @returns a new flow graph + */ + createGraph() { + const graph = new FlowGraph({ scene: this.config.scene, coordinator: this }); + this._flowGraphs.push(graph); + return graph; + } + /** + * Removes a flow graph from the list of existing flow graphs and disposes it + * @param graph the graph to remove + */ + removeGraph(graph) { + const index = this._flowGraphs.indexOf(graph); + if (index !== -1) { + graph.dispose(); + this._flowGraphs.splice(index, 1); + } + } + /** + * Starts all graphs + */ + start() { + this._flowGraphs.forEach((graph) => graph.start()); + } + /** + * Disposes all graphs + */ + dispose() { + this._flowGraphs.forEach((graph) => graph.dispose()); + this._flowGraphs.length = 0; + this._disposeObserver?.remove(); + this._onBeforeRenderObserver?.remove(); + // Remove itself from the SceneCoordinators list for the Inspector. + const coordinators = FlowGraphCoordinator.SceneCoordinators.get(this.config.scene) ?? []; + const index = coordinators.indexOf(this); + if (index !== -1) { + coordinators.splice(index, 1); + } + } + /** + * Serializes this coordinator to a JSON object. + * @param serializationObject the object to serialize to + * @param valueSerializeFunction the function to use to serialize the value + */ + serialize(serializationObject, valueSerializeFunction) { + serializationObject._flowGraphs = []; + this._flowGraphs.forEach((graph) => { + const serializedGraph = {}; + graph.serialize(serializedGraph, valueSerializeFunction); + serializationObject._flowGraphs.push(serializedGraph); + }); + serializationObject.dispatchEventsSynchronously = this.dispatchEventsSynchronously; + } + /** + * Gets the list of flow graphs + */ + get flowGraphs() { + return this._flowGraphs; + } + /** + * Get an observable that will be notified when the event with the given id is fired. + * @param id the id of the event + * @returns the observable for the event + */ + getCustomEventObservable(id) { + let observable = this._customEventsMap.get(id); + if (!observable) { + // receive event is initialized before scene start, so no need to notify if triggered. but possible! + observable = new Observable( /*undefined, true*/); + this._customEventsMap.set(id, observable); + } + return observable; + } + /** + * Notifies the observable for the given event id with the given data. + * @param id the id of the event + * @param data the data to send with the event + * @param async if true, the event will be dispatched asynchronously + */ + notifyCustomEvent(id, data, async = !this.dispatchEventsSynchronously) { + if (async) { + this._executeOnNextFrame.push({ id, data }); + return; + } + // check if we are not exceeding the max number of events + if (this._eventExecutionCounter.has(id)) { + const count = this._eventExecutionCounter.get(id); + this._eventExecutionCounter.set(id, count + 1); + if (count >= FlowGraphCoordinator.MaxEventTypeExecutionPerFrame) { + count === FlowGraphCoordinator.MaxEventTypeExecutionPerFrame && Logger.Warn(`FlowGraphCoordinator: Too many executions of event "${id}".`); + return; + } + } + else { + this._eventExecutionCounter.set(id, 1); + } + const observable = this._customEventsMap.get(id); + if (observable) { + observable.notifyObservers(data); + } + } +} +/** + * The maximum number of events per type. + * This is used to limit the number of events that can be created in a single scene. + * This is to prevent infinite loops. + */ +FlowGraphCoordinator.MaxEventsPerType = 30; +/** + * The maximum number of execution of a specific event in a single frame. + */ +FlowGraphCoordinator.MaxEventTypeExecutionPerFrame = 30; +/** + * @internal + * A list of all the coordinators per scene. Will be used by the inspector + */ +FlowGraphCoordinator.SceneCoordinators = new Map(); + +/** + * Any external module that wishes to add a new block to the flow graph can add to this object using the helper function. + */ +const customBlocks = {}; +/** + * If you want to add a new block to the block factory, you should use this function. + * Please be sure to choose a unique name and define the responsible module. + * @param module the name of the module that is responsible for the block + * @param blockName the name of the block. This should be unique. + * @param factory an async factory function to generate the block + */ +function addToBlockFactory(module, blockName, factory) { + customBlocks[`${module}/${blockName}`] = factory; +} +/** + * a function to get a factory function for a block. + * @param blockName the block name to initialize. If the block comes from an external module, the name should be in the format "module/blockName" + * @returns an async factory function that will return the block class when called. + */ +function blockFactory(blockName) { + switch (blockName) { + case "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */: + return async () => (await Promise.resolve().then(() => flowGraphPlayAnimationBlock)).FlowGraphPlayAnimationBlock; + case "FlowGraphStopAnimationBlock" /* FlowGraphBlockNames.StopAnimation */: + return async () => (await Promise.resolve().then(() => flowGraphStopAnimationBlock)).FlowGraphStopAnimationBlock; + case "FlowGraphPauseAnimationBlock" /* FlowGraphBlockNames.PauseAnimation */: + return async () => (await Promise.resolve().then(() => flowGraphPauseAnimationBlock)).FlowGraphPauseAnimationBlock; + case "FlowGraphInterpolationBlock" /* FlowGraphBlockNames.ValueInterpolation */: + return async () => (await Promise.resolve().then(() => flowGraphInterpolationBlock)).FlowGraphInterpolationBlock; + case "FlowGraphSceneReadyEventBlock" /* FlowGraphBlockNames.SceneReadyEvent */: + return async () => (await Promise.resolve().then(() => flowGraphSceneReadyEventBlock)).FlowGraphSceneReadyEventBlock; + case "FlowGraphSceneTickEventBlock" /* FlowGraphBlockNames.SceneTickEvent */: + return async () => (await Promise.resolve().then(() => flowGraphSceneTickEventBlock)).FlowGraphSceneTickEventBlock; + case "FlowGraphSendCustomEventBlock" /* FlowGraphBlockNames.SendCustomEvent */: + return async () => (await Promise.resolve().then(() => flowGraphSendCustomEventBlock)).FlowGraphSendCustomEventBlock; + case "FlowGraphReceiveCustomEventBlock" /* FlowGraphBlockNames.ReceiveCustomEvent */: + return async () => (await Promise.resolve().then(() => flowGraphReceiveCustomEventBlock)).FlowGraphReceiveCustomEventBlock; + case "FlowGraphMeshPickEventBlock" /* FlowGraphBlockNames.MeshPickEvent */: + return async () => (await Promise.resolve().then(() => flowGraphMeshPickEventBlock)).FlowGraphMeshPickEventBlock; + case "FlowGraphEBlock" /* FlowGraphBlockNames.E */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphEBlock; + case "FlowGraphPIBlock" /* FlowGraphBlockNames.PI */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphPiBlock; + case "FlowGraphInfBlock" /* FlowGraphBlockNames.Inf */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphInfBlock; + case "FlowGraphNaNBlock" /* FlowGraphBlockNames.NaN */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphNaNBlock; + case "FlowGraphRandomBlock" /* FlowGraphBlockNames.Random */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphRandomBlock; + case "FlowGraphAddBlock" /* FlowGraphBlockNames.Add */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphAddBlock; + case "FlowGraphSubtractBlock" /* FlowGraphBlockNames.Subtract */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphSubtractBlock; + case "FlowGraphMultiplyBlock" /* FlowGraphBlockNames.Multiply */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphMultiplyBlock; + case "FlowGraphDivideBlock" /* FlowGraphBlockNames.Divide */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphDivideBlock; + case "FlowGraphAbsBlock" /* FlowGraphBlockNames.Abs */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphAbsBlock; + case "FlowGraphSignBlock" /* FlowGraphBlockNames.Sign */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphSignBlock; + case "FlowGraphTruncBlock" /* FlowGraphBlockNames.Trunc */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphTruncBlock; + case "FlowGraphFloorBlock" /* FlowGraphBlockNames.Floor */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphFloorBlock; + case "FlowGraphCeilBlock" /* FlowGraphBlockNames.Ceil */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphCeilBlock; + case "FlowGraphRoundBlock" /* FlowGraphBlockNames.Round */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphRoundBlock; + case "FlowGraphFractBlock" /* FlowGraphBlockNames.Fraction */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphFractionBlock; + case "FlowGraphNegationBlock" /* FlowGraphBlockNames.Negation */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphNegationBlock; + case "FlowGraphModuloBlock" /* FlowGraphBlockNames.Modulo */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphModuloBlock; + case "FlowGraphMinBlock" /* FlowGraphBlockNames.Min */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphMinBlock; + case "FlowGraphMaxBlock" /* FlowGraphBlockNames.Max */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphMaxBlock; + case "FlowGraphClampBlock" /* FlowGraphBlockNames.Clamp */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphClampBlock; + case "FlowGraphSaturateBlock" /* FlowGraphBlockNames.Saturate */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphSaturateBlock; + case "FlowGraphMathInterpolationBlock" /* FlowGraphBlockNames.MathInterpolation */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphMathInterpolationBlock; + case "FlowGraphEqualityBlock" /* FlowGraphBlockNames.Equality */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphEqualityBlock; + case "FlowGraphLessThanBlock" /* FlowGraphBlockNames.LessThan */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphLessThanBlock; + case "FlowGraphLessThanOrEqualBlock" /* FlowGraphBlockNames.LessThanOrEqual */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphLessThanOrEqualBlock; + case "FlowGraphGreaterThanBlock" /* FlowGraphBlockNames.GreaterThan */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphGreaterThanBlock; + case "FlowGraphGreaterThanOrEqualBlock" /* FlowGraphBlockNames.GreaterThanOrEqual */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphGreaterThanOrEqualBlock; + case "FlowGraphIsNaNBlock" /* FlowGraphBlockNames.IsNaN */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphIsNanBlock; + case "FlowGraphIsInfBlock" /* FlowGraphBlockNames.IsInfinity */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphIsInfinityBlock; + case "FlowGraphDegToRadBlock" /* FlowGraphBlockNames.DegToRad */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphDegToRadBlock; + case "FlowGraphRadToDegBlock" /* FlowGraphBlockNames.RadToDeg */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphRadToDegBlock; + case "FlowGraphSinBlock" /* FlowGraphBlockNames.Sin */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphSinBlock; + case "FlowGraphCosBlock" /* FlowGraphBlockNames.Cos */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphCosBlock; + case "FlowGraphTanBlock" /* FlowGraphBlockNames.Tan */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphTanBlock; + case "FlowGraphASinBlock" /* FlowGraphBlockNames.Asin */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphAsinBlock; + case "FlowGraphACosBlock" /* FlowGraphBlockNames.Acos */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphAcosBlock; + case "FlowGraphATanBlock" /* FlowGraphBlockNames.Atan */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphAtanBlock; + case "FlowGraphATan2Block" /* FlowGraphBlockNames.Atan2 */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphAtan2Block; + case "FlowGraphSinhBlock" /* FlowGraphBlockNames.Sinh */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphSinhBlock; + case "FlowGraphCoshBlock" /* FlowGraphBlockNames.Cosh */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphCoshBlock; + case "FlowGraphTanhBlock" /* FlowGraphBlockNames.Tanh */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphTanhBlock; + case "FlowGraphASinhBlock" /* FlowGraphBlockNames.Asinh */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphAsinhBlock; + case "FlowGraphACoshBlock" /* FlowGraphBlockNames.Acosh */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphAcoshBlock; + case "FlowGraphATanhBlock" /* FlowGraphBlockNames.Atanh */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphAtanhBlock; + case "FlowGraphExponentialBlock" /* FlowGraphBlockNames.Exponential */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphExpBlock; + case "FlowGraphLogBlock" /* FlowGraphBlockNames.Log */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphLogBlock; + case "FlowGraphLog2Block" /* FlowGraphBlockNames.Log2 */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphLog2Block; + case "FlowGraphLog10Block" /* FlowGraphBlockNames.Log10 */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphLog10Block; + case "FlowGraphSquareRootBlock" /* FlowGraphBlockNames.SquareRoot */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphSquareRootBlock; + case "FlowGraphPowerBlock" /* FlowGraphBlockNames.Power */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphPowerBlock; + case "FlowGraphCubeRootBlock" /* FlowGraphBlockNames.CubeRoot */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphCubeRootBlock; + case "FlowGraphBitwiseAndBlock" /* FlowGraphBlockNames.BitwiseAnd */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphBitwiseAndBlock; + case "FlowGraphBitwiseOrBlock" /* FlowGraphBlockNames.BitwiseOr */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphBitwiseOrBlock; + case "FlowGraphBitwiseNotBlock" /* FlowGraphBlockNames.BitwiseNot */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphBitwiseNotBlock; + case "FlowGraphBitwiseXorBlock" /* FlowGraphBlockNames.BitwiseXor */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphBitwiseXorBlock; + case "FlowGraphBitwiseLeftShiftBlock" /* FlowGraphBlockNames.BitwiseLeftShift */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphBitwiseLeftShiftBlock; + case "FlowGraphBitwiseRightShiftBlock" /* FlowGraphBlockNames.BitwiseRightShift */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphBitwiseRightShiftBlock; + case "FlowGraphLengthBlock" /* FlowGraphBlockNames.Length */: + return async () => (await Promise.resolve().then(() => flowGraphVectorMathBlocks)).FlowGraphLengthBlock; + case "FlowGraphNormalizeBlock" /* FlowGraphBlockNames.Normalize */: + return async () => (await Promise.resolve().then(() => flowGraphVectorMathBlocks)).FlowGraphNormalizeBlock; + case "FlowGraphDotBlock" /* FlowGraphBlockNames.Dot */: + return async () => (await Promise.resolve().then(() => flowGraphVectorMathBlocks)).FlowGraphDotBlock; + case "FlowGraphCrossBlock" /* FlowGraphBlockNames.Cross */: + return async () => (await Promise.resolve().then(() => flowGraphVectorMathBlocks)).FlowGraphCrossBlock; + case "FlowGraphRotate2DBlock" /* FlowGraphBlockNames.Rotate2D */: + return async () => (await Promise.resolve().then(() => flowGraphVectorMathBlocks)).FlowGraphRotate2DBlock; + case "FlowGraphRotate3DBlock" /* FlowGraphBlockNames.Rotate3D */: + return async () => (await Promise.resolve().then(() => flowGraphVectorMathBlocks)).FlowGraphRotate3DBlock; + case "FlowGraphTransposeBlock" /* FlowGraphBlockNames.Transpose */: + return async () => (await Promise.resolve().then(() => flowGraphMatrixMathBlocks)).FlowGraphTransposeBlock; + case "FlowGraphDeterminantBlock" /* FlowGraphBlockNames.Determinant */: + return async () => (await Promise.resolve().then(() => flowGraphMatrixMathBlocks)).FlowGraphDeterminantBlock; + case "FlowGraphInvertMatrixBlock" /* FlowGraphBlockNames.InvertMatrix */: + return async () => (await Promise.resolve().then(() => flowGraphMatrixMathBlocks)).FlowGraphInvertMatrixBlock; + case "FlowGraphMatrixMultiplicationBlock" /* FlowGraphBlockNames.MatrixMultiplication */: + return async () => (await Promise.resolve().then(() => flowGraphMatrixMathBlocks)).FlowGraphMatrixMultiplicationBlock; + case "FlowGraphBranchBlock" /* FlowGraphBlockNames.Branch */: + return async () => (await Promise.resolve().then(() => flowGraphBranchBlock)).FlowGraphBranchBlock; + case "FlowGraphSetDelayBlock" /* FlowGraphBlockNames.SetDelay */: + return async () => (await Promise.resolve().then(() => flowGraphSetDelayBlock)).FlowGraphSetDelayBlock; + case "FlowGraphCancelDelayBlock" /* FlowGraphBlockNames.CancelDelay */: + return async () => (await Promise.resolve().then(() => flowGraphCancelDelayBlock)).FlowGraphCancelDelayBlock; + case "FlowGraphCallCounterBlock" /* FlowGraphBlockNames.CallCounter */: + return async () => (await Promise.resolve().then(() => flowGraphCounterBlock)).FlowGraphCallCounterBlock; + case "FlowGraphDebounceBlock" /* FlowGraphBlockNames.Debounce */: + return async () => (await Promise.resolve().then(() => flowGraphDebounceBlock)).FlowGraphDebounceBlock; + case "FlowGraphThrottleBlock" /* FlowGraphBlockNames.Throttle */: + return async () => (await Promise.resolve().then(() => flowGraphThrottleBlock)).FlowGraphThrottleBlock; + case "FlowGraphDoNBlock" /* FlowGraphBlockNames.DoN */: + return async () => (await Promise.resolve().then(() => flowGraphDoNBlock)).FlowGraphDoNBlock; + case "FlowGraphFlipFlopBlock" /* FlowGraphBlockNames.FlipFlop */: + return async () => (await Promise.resolve().then(() => flowGraphFlipFlopBlock)).FlowGraphFlipFlopBlock; + case "FlowGraphForLoopBlock" /* FlowGraphBlockNames.ForLoop */: + return async () => (await Promise.resolve().then(() => flowGraphForLoopBlock)).FlowGraphForLoopBlock; + case "FlowGraphMultiGateBlock" /* FlowGraphBlockNames.MultiGate */: + return async () => (await Promise.resolve().then(() => flowGraphMultiGateBlock)).FlowGraphMultiGateBlock; + case "FlowGraphSequenceBlock" /* FlowGraphBlockNames.Sequence */: + return async () => (await Promise.resolve().then(() => flowGraphSequenceBlock)).FlowGraphSequenceBlock; + case "FlowGraphSwitchBlock" /* FlowGraphBlockNames.Switch */: + return async () => (await Promise.resolve().then(() => flowGraphSwitchBlock)).FlowGraphSwitchBlock; + case "FlowGraphWaitAllBlock" /* FlowGraphBlockNames.WaitAll */: + return async () => (await Promise.resolve().then(() => flowGraphWaitAllBlock)).FlowGraphWaitAllBlock; + case "FlowGraphWhileLoopBlock" /* FlowGraphBlockNames.WhileLoop */: + return async () => (await Promise.resolve().then(() => flowGraphWhileLoopBlock)).FlowGraphWhileLoopBlock; + case "FlowGraphConsoleLogBlock" /* FlowGraphBlockNames.ConsoleLog */: + return async () => (await Promise.resolve().then(() => flowGraphConsoleLogBlock)).FlowGraphConsoleLogBlock; + case "FlowGraphConditionalBlock" /* FlowGraphBlockNames.Conditional */: + return async () => (await Promise.resolve().then(() => flowGraphConditionalDataBlock)).FlowGraphConditionalDataBlock; + case "FlowGraphConstantBlock" /* FlowGraphBlockNames.Constant */: + return async () => (await Promise.resolve().then(() => flowGraphConstantBlock)).FlowGraphConstantBlock; + case "FlowGraphTransformCoordinatesSystemBlock" /* FlowGraphBlockNames.TransformCoordinatesSystem */: + return async () => (await Promise.resolve().then(() => flowGraphTransformCoordinatesSystemBlock)).FlowGraphTransformCoordinatesSystemBlock; + case "FlowGraphGetAssetBlock" /* FlowGraphBlockNames.GetAsset */: + return async () => (await Promise.resolve().then(() => flowGraphGetAssetBlock)).FlowGraphGetAssetBlock; + case "FlowGraphGetPropertyBlock" /* FlowGraphBlockNames.GetProperty */: + return async () => (await Promise.resolve().then(() => flowGraphGetPropertyBlock)).FlowGraphGetPropertyBlock; + case "FlowGraphSetPropertyBlock" /* FlowGraphBlockNames.SetProperty */: + return async () => (await Promise.resolve().then(() => flowGraphSetPropertyBlock)).FlowGraphSetPropertyBlock; + case "FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */: + return async () => (await Promise.resolve().then(() => flowGraphGetVariableBlock)).FlowGraphGetVariableBlock; + case "FlowGraphSetVariableBlock" /* FlowGraphBlockNames.SetVariable */: + return async () => (await Promise.resolve().then(() => flowGraphSetVariableBlock)).FlowGraphSetVariableBlock; + case "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */: + return async () => (await Promise.resolve().then(() => flowGraphJsonPointerParserBlock)).FlowGraphJsonPointerParserBlock; + case "FlowGraphLeadingZerosBlock" /* FlowGraphBlockNames.LeadingZeros */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphLeadingZerosBlock; + case "FlowGraphTrailingZerosBlock" /* FlowGraphBlockNames.TrailingZeros */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphTrailingZerosBlock; + case "FlowGraphOneBitsCounterBlock" /* FlowGraphBlockNames.OneBitsCounter */: + return async () => (await Promise.resolve().then(() => flowGraphMathBlocks)).FlowGraphOneBitsCounterBlock; + case "FlowGraphCombineVector2Block" /* FlowGraphBlockNames.CombineVector2 */: + return async () => (await Promise.resolve().then(() => flowGraphMathCombineExtractBlocks)).FlowGraphCombineVector2Block; + case "FlowGraphCombineVector3Block" /* FlowGraphBlockNames.CombineVector3 */: + return async () => (await Promise.resolve().then(() => flowGraphMathCombineExtractBlocks)).FlowGraphCombineVector3Block; + case "FlowGraphCombineVector4Block" /* FlowGraphBlockNames.CombineVector4 */: + return async () => (await Promise.resolve().then(() => flowGraphMathCombineExtractBlocks)).FlowGraphCombineVector4Block; + case "FlowGraphCombineMatrixBlock" /* FlowGraphBlockNames.CombineMatrix */: + return async () => (await Promise.resolve().then(() => flowGraphMathCombineExtractBlocks)).FlowGraphCombineMatrixBlock; + case "FlowGraphExtractVector2Block" /* FlowGraphBlockNames.ExtractVector2 */: + return async () => (await Promise.resolve().then(() => flowGraphMathCombineExtractBlocks)).FlowGraphExtractVector2Block; + case "FlowGraphExtractVector3Block" /* FlowGraphBlockNames.ExtractVector3 */: + return async () => (await Promise.resolve().then(() => flowGraphMathCombineExtractBlocks)).FlowGraphExtractVector3Block; + case "FlowGraphExtractVector4Block" /* FlowGraphBlockNames.ExtractVector4 */: + return async () => (await Promise.resolve().then(() => flowGraphMathCombineExtractBlocks)).FlowGraphExtractVector4Block; + case "FlowGraphExtractMatrixBlock" /* FlowGraphBlockNames.ExtractMatrix */: + return async () => (await Promise.resolve().then(() => flowGraphMathCombineExtractBlocks)).FlowGraphExtractMatrixBlock; + case "FlowGraphTransformVectorBlock" /* FlowGraphBlockNames.TransformVector */: + return async () => (await Promise.resolve().then(() => flowGraphVectorMathBlocks)).FlowGraphTransformBlock; + case "FlowGraphTransformCoordinatesBlock" /* FlowGraphBlockNames.TransformCoordinates */: + return async () => (await Promise.resolve().then(() => flowGraphVectorMathBlocks)).FlowGraphTransformCoordinatesBlock; + case "FlowGraphMatrixDecompose" /* FlowGraphBlockNames.MatrixDecompose */: + return async () => (await Promise.resolve().then(() => flowGraphMatrixMathBlocks)).FlowGraphMatrixDecomposeBlock; + case "FlowGraphMatrixCompose" /* FlowGraphBlockNames.MatrixCompose */: + return async () => (await Promise.resolve().then(() => flowGraphMatrixMathBlocks)).FlowGraphMatrixComposeBlock; + case "FlowGraphBooleanToFloat" /* FlowGraphBlockNames.BooleanToFloat */: + return async () => (await Promise.resolve().then(() => flowGraphTypeToTypeBlocks)).FlowGraphBooleanToFloat; + case "FlowGraphBooleanToInt" /* FlowGraphBlockNames.BooleanToInt */: + return async () => (await Promise.resolve().then(() => flowGraphTypeToTypeBlocks)).FlowGraphBooleanToInt; + case "FlowGraphFloatToBoolean" /* FlowGraphBlockNames.FloatToBoolean */: + return async () => (await Promise.resolve().then(() => flowGraphTypeToTypeBlocks)).FlowGraphFloatToBoolean; + case "FlowGraphIntToBoolean" /* FlowGraphBlockNames.IntToBoolean */: + return async () => (await Promise.resolve().then(() => flowGraphTypeToTypeBlocks)).FlowGraphIntToBoolean; + case "FlowGraphIntToFloat" /* FlowGraphBlockNames.IntToFloat */: + return async () => (await Promise.resolve().then(() => flowGraphTypeToTypeBlocks)).FlowGraphIntToFloat; + case "FlowGraphFloatToInt" /* FlowGraphBlockNames.FloatToInt */: + return async () => (await Promise.resolve().then(() => flowGraphTypeToTypeBlocks)).FlowGraphFloatToInt; + case "FlowGraphEasingBlock" /* FlowGraphBlockNames.Easing */: + return async () => (await Promise.resolve().then(() => flowGraphEasingBlock)).FlowGraphEasingBlock; + case "FlowGraphBezierCurveEasing" /* FlowGraphBlockNames.BezierCurveEasing */: + return async () => (await Promise.resolve().then(() => flowGraphBezierCurveEasingBlock)).FlowGraphBezierCurveEasingBlock; + case "FlowGraphPointerOverEventBlock" /* FlowGraphBlockNames.PointerOverEvent */: + return async () => (await Promise.resolve().then(() => flowGraphPointerOverEventBlock)).FlowGraphPointerOverEventBlock; + case "FlowGraphPointerOutEventBlock" /* FlowGraphBlockNames.PointerOutEvent */: + return async () => (await Promise.resolve().then(() => flowGraphPointerOutEventBlock)).FlowGraphPointerOutEventBlock; + case "FlowGraphContextBlock" /* FlowGraphBlockNames.Context */: + return async () => (await Promise.resolve().then(() => flowGraphContextBlock)).FlowGraphContextBlock; + case "FlowGraphArrayIndexBlock" /* FlowGraphBlockNames.ArrayIndex */: + return async () => (await Promise.resolve().then(() => flowGraphArrayIndexBlock)).FlowGraphArrayIndexBlock; + case "FlowGraphCodeExecutionBlock" /* FlowGraphBlockNames.CodeExecution */: + return async () => (await Promise.resolve().then(() => flowGraphCodeExecutionBlock)).FlowGraphCodeExecutionBlock; + case "FlowGraphIndexOfBlock" /* FlowGraphBlockNames.IndexOf */: + return async () => (await Promise.resolve().then(() => flowGraphIndexOfBlock)).FlowGraphIndexOfBlock; + case "FlowGraphFunctionReference" /* FlowGraphBlockNames.FunctionReference */: + return async () => (await Promise.resolve().then(() => flowGraphFunctionReferenceBlock)).FlowGraphFunctionReferenceBlock; + case "FlowGraphDataSwitchBlock" /* FlowGraphBlockNames.DataSwitch */: + return async () => (await Promise.resolve().then(() => flowGraphDataSwitchBlock)).FlowGraphDataSwitchBlock; + default: + // check if the block is a custom block + if (customBlocks[blockName]) { + return customBlocks[blockName]; + } + throw new Error(`Unknown block name ${blockName}`); + } +} + +/** + * An execution block that has an out signal. This signal is triggered when the synchronous execution of this block is done. + * Most execution blocks will inherit from this, except for the ones that have multiple signals to be triggered. + * (such as if blocks) + */ +class FlowGraphExecutionBlockWithOutSignal extends FlowGraphExecutionBlock { + constructor(config) { + super(config); + this.out = this._registerSignalOutput("out"); + } +} + +/** + * An async execution block can start tasks that will be executed asynchronously. + * It should also be responsible for clearing it in _cancelPendingTasks. + */ +class FlowGraphAsyncExecutionBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor(config, events) { + super(config); + this._eventsSignalOutputs = {}; + this.done = this._registerSignalOutput("done"); + events?.forEach((eventName) => { + this._eventsSignalOutputs[eventName] = this._registerSignalOutput(eventName + "Event"); + }); + } + /** + * @internal + * This function can be overridden to execute any + * logic that should be executed on every frame + * while the async task is pending. + * @param context the context in which it is running + */ + _executeOnTick(_context) { } + /** + * @internal + * @param context + */ + _startPendingTasks(context) { + if (context._getExecutionVariable(this, "_initialized", false)) { + this._cancelPendingTasks(context); + this._resetAfterCanceled(context); + } + this._preparePendingTasks(context); + context._addPendingBlock(this); + this.out._activateSignal(context); + context._setExecutionVariable(this, "_initialized", true); + } + _resetAfterCanceled(context) { + context._deleteExecutionVariable(this, "_initialized"); + context._removePendingBlock(this); + } +} + +/** + * A type of block that listens to an event observable and activates + * its output signal when the event is triggered. + */ +class FlowGraphEventBlock extends FlowGraphAsyncExecutionBlock { + constructor() { + super(...arguments); + /** + * the priority of initialization of this block. + * For example, scene start should have a negative priority because it should be initialized last. + */ + this.initPriority = 0; + /** + * The type of the event + */ + this.type = "NoTrigger" /* FlowGraphEventType.NoTrigger */; + } + /** + * @internal + */ + _execute(context) { + context._notifyExecuteNode(this); + this.done._activateSignal(context); + } +} + +/** + * Given a list of blocks, find an output data connection that has a specific unique id + * @param blocks a list of flow graph blocks + * @param uniqueId the unique id of a connection + * @returns the connection that has this unique id. throws an error if none was found + */ +function GetDataOutConnectionByUniqueId(blocks, uniqueId) { + for (const block of blocks) { + for (const dataOut of block.dataOutputs) { + if (dataOut.uniqueId === uniqueId) { + return dataOut; + } + } + } + throw new Error("Could not find data out connection with unique id " + uniqueId); +} +/** + * Given a list of blocks, find an input signal connection that has a specific unique id + * @param blocks a list of flow graph blocks + * @param uniqueId the unique id of a connection + * @returns the connection that has this unique id. throws an error if none was found + */ +function GetSignalInConnectionByUniqueId(blocks, uniqueId) { + for (const block of blocks) { + if (block instanceof FlowGraphExecutionBlock) { + for (const signalIn of block.signalInputs) { + if (signalIn.uniqueId === uniqueId) { + return signalIn; + } + } + } + } + throw new Error("Could not find signal in connection with unique id " + uniqueId); +} +/** + * Parses a graph from a given serialization object + * @param serializationObject the object where the values are written + * @param options options for parsing the graph + * @returns the parsed graph + */ +async function ParseFlowGraphAsync(serializationObject, options) { + // get all classes types needed for the blocks using the block factory + const resolvedClasses = await Promise.all(serializationObject.allBlocks.map(async (serializedBlock) => { + const classFactory = blockFactory(serializedBlock.className); + return classFactory(); + })); + // async will be used when we start using the block async factory + return ParseFlowGraph(serializationObject, options, resolvedClasses); +} +/** + * Parses a graph from a given serialization object + * @param serializationObject the object where the values are written + * @param options options for parsing the graph + * @param resolvedClasses the resolved classes for the blocks + * @returns the parsed graph + */ +function ParseFlowGraph(serializationObject, options, resolvedClasses) { + const graph = options.coordinator.createGraph(); + const blocks = []; + const valueParseFunction = options.valueParseFunction ?? defaultValueParseFunction; + // Parse all blocks + // for (const serializedBlock of serializationObject.allBlocks) { + for (let i = 0; i < serializationObject.allBlocks.length; i++) { + const serializedBlock = serializationObject.allBlocks[i]; + const block = ParseFlowGraphBlockWithClassType(serializedBlock, { scene: options.coordinator.config.scene, pathConverter: options.pathConverter, assetsContainer: options.coordinator.config.scene, valueParseFunction }, resolvedClasses[i]); + blocks.push(block); + if (block instanceof FlowGraphEventBlock) { + graph.addEventBlock(block); + } + } + // After parsing all blocks, connect them + for (const block of blocks) { + for (const dataIn of block.dataInputs) { + for (const serializedConnection of dataIn.connectedPointIds) { + const connection = GetDataOutConnectionByUniqueId(blocks, serializedConnection); + dataIn.connectTo(connection); + } + } + if (block instanceof FlowGraphExecutionBlock) { + for (const signalOut of block.signalOutputs) { + for (const serializedConnection of signalOut.connectedPointIds) { + const connection = GetSignalInConnectionByUniqueId(blocks, serializedConnection); + signalOut.connectTo(connection); + } + } + } + } + for (const serializedContext of serializationObject.executionContexts) { + ParseFlowGraphContext(serializedContext, { graph, valueParseFunction }, serializationObject.rightHanded); + } + return graph; +} +/** + * Parses a context + * @param serializationObject the object containing the context serialization values + * @param options the options for parsing the context + * @param rightHanded whether the serialized data is right handed + * @returns + */ +function ParseFlowGraphContext(serializationObject, options, rightHanded) { + const result = options.graph.createContext(); + if (serializationObject.enableLogging) { + result.enableLogging = true; + } + result.treatDataAsRightHanded = rightHanded || false; + const valueParseFunction = options.valueParseFunction ?? defaultValueParseFunction; + result.uniqueId = serializationObject.uniqueId; + const scene = result.getScene(); + // check if assets context is available + if (serializationObject._assetsContext) { + const ac = serializationObject._assetsContext; + const assetsContext = { + meshes: ac.meshes?.map((m) => scene.getMeshById(m)), + lights: ac.lights?.map((l) => scene.getLightByName(l)), + cameras: ac.cameras?.map((c) => scene.getCameraByName(c)), + materials: ac.materials?.map((m) => scene.getMaterialById(m)), + textures: ac.textures?.map((t) => scene.getTextureByName(t)), + animations: ac.animations?.map((a) => scene.animations.find((anim) => anim.name === a)), + skeletons: ac.skeletons?.map((s) => scene.getSkeletonByName(s)), + particleSystems: ac.particleSystems?.map((ps) => scene.getParticleSystemById(ps)), + animationGroups: ac.animationGroups?.map((ag) => scene.getAnimationGroupByName(ag)), + transformNodes: ac.transformNodes?.map((tn) => scene.getTransformNodeById(tn)), + rootNodes: [], + multiMaterials: [], + morphTargetManagers: [], + geometries: [], + actionManagers: [], + environmentTexture: null, + postProcesses: [], + sounds: null, + effectLayers: [], + layers: [], + reflectionProbes: [], + lensFlareSystems: [], + proceduralTextures: [], + getNodes: function () { + throw new Error("Function not implemented."); + }, + }; + result.assetsContext = assetsContext; + } + for (const key in serializationObject._userVariables) { + const value = valueParseFunction(key, serializationObject._userVariables, result.assetsContext, scene); + result.userVariables[key] = value; + } + for (const key in serializationObject._connectionValues) { + const value = valueParseFunction(key, serializationObject._connectionValues, result.assetsContext, scene); + result._setConnectionValueByKey(key, value); + } + return result; +} +/** + * Parses a block from a serialization object + * @param serializationObject the object to parse from + * @param parseOptions options for parsing the block + * @param classType the class type of the block. This is used when the class is not loaded asynchronously + * @returns the parsed block + */ +function ParseFlowGraphBlockWithClassType(serializationObject, parseOptions, classType) { + const parsedConfig = {}; + const valueParseFunction = parseOptions.valueParseFunction ?? defaultValueParseFunction; + if (serializationObject.config) { + for (const key in serializationObject.config) { + parsedConfig[key] = valueParseFunction(key, serializationObject.config, parseOptions.assetsContainer || parseOptions.scene, parseOptions.scene); + } + } + if (needsPathConverter(serializationObject.className)) { + if (!parseOptions.pathConverter) { + throw new Error("Path converter is required for this block"); + } + parsedConfig.pathConverter = parseOptions.pathConverter; + } + const obj = new classType(parsedConfig); + obj.uniqueId = serializationObject.uniqueId; + for (let i = 0; i < serializationObject.dataInputs.length; i++) { + const dataInput = obj.getDataInput(serializationObject.dataInputs[i].name); + if (dataInput) { + dataInput.deserialize(serializationObject.dataInputs[i]); + } + else { + throw new Error("Could not find data input with name " + serializationObject.dataInputs[i].name + " in block " + serializationObject.className); + } + } + for (let i = 0; i < serializationObject.dataOutputs.length; i++) { + const dataOutput = obj.getDataOutput(serializationObject.dataOutputs[i].name); + if (dataOutput) { + dataOutput.deserialize(serializationObject.dataOutputs[i]); + } + else { + throw new Error("Could not find data output with name " + serializationObject.dataOutputs[i].name + " in block " + serializationObject.className); + } + } + obj.metadata = serializationObject.metadata; + obj.deserialize && obj.deserialize(serializationObject); + return obj; +} + +function getMappingForFullOperationName(fullOperationName) { + const [op, extension] = fullOperationName.split(":"); + return getMappingForDeclaration({ op, extension }); +} +function getMappingForDeclaration(declaration, returnNoOpIfNotAvailable = true) { + const mapping = declaration.extension ? gltfExtensionsToFlowGraphMapping[declaration.extension]?.[declaration.op] : gltfToFlowGraphMapping[declaration.op]; + if (!mapping) { + Logger.Warn(`No mapping found for operation ${declaration.op} and extension ${declaration.extension || "KHR_interactivity"}`); + if (returnNoOpIfNotAvailable) { + const inputs = {}; + const outputs = { + flows: {}, + }; + if (declaration.inputValueSockets) { + inputs.values = {}; + for (const key in declaration.inputValueSockets) { + inputs.values[key] = { + name: key, + }; + } + } + if (declaration.outputValueSockets) { + outputs.values = {}; + Object.keys(declaration.outputValueSockets).forEach((key) => { + outputs.values[key] = { + name: key, + }; + }); + } + return { + blocks: [], // no blocks, just mapping + inputs, + outputs, + }; + } + } + return mapping; +} +/** + * This function will add new mapping to glTF interactivity. + * Other extensions can define new types of blocks, this is the way to let interactivity know how to parse them. + * @param key the type of node, i.e. "variable/get" + * @param extension the extension of the interactivity operation, i.e. "KHR_selectability" + * @param mapping The mapping object. See documentation or examples below. + */ +function addNewInteractivityFlowGraphMapping(key, extension, mapping) { + gltfExtensionsToFlowGraphMapping[extension] || (gltfExtensionsToFlowGraphMapping[extension] = {}); + gltfExtensionsToFlowGraphMapping[extension][key] = mapping; +} +const gltfExtensionsToFlowGraphMapping = { + /** + * This is the BABYLON extension for glTF interactivity. + * It defines babylon-specific blocks and operations. + */ + BABYLON: { + /** + * flow/log is a flow node that logs input to the console. + * It has "in" and "out" flows, and takes a message as input. + * The message can be any type of value. + * The message is logged to the console when the "in" flow is triggered. + * The "out" flow is triggered when the message is logged. + */ + "flow/log": { + blocks: ["FlowGraphConsoleLogBlock" /* FlowGraphBlockNames.ConsoleLog */], + inputs: { + values: { + message: { name: "message" }, + }, + }, + }, + }, +}; +// this mapper is just a way to convert the glTF nodes to FlowGraph nodes in terms of input/output connection names and values. +const gltfToFlowGraphMapping = { + "event/onStart": { + blocks: ["FlowGraphSceneReadyEventBlock" /* FlowGraphBlockNames.SceneReadyEvent */], + outputs: { + flows: { + out: { name: "done" }, + }, + }, + }, + "event/onTick": { + blocks: ["FlowGraphSceneTickEventBlock" /* FlowGraphBlockNames.SceneTickEvent */], + inputs: {}, + outputs: { + values: { + timeSinceLastTick: { name: "deltaTime", gltfType: "number" /*, dataTransformer: (time: number) => time / 1000*/ }, + }, + flows: { + out: { name: "done" }, + }, + }, + }, + "event/send": { + blocks: ["FlowGraphSendCustomEventBlock" /* FlowGraphBlockNames.SendCustomEvent */], + outputs: { + flows: { + out: { name: "done" }, + }, + }, + extraProcessor(gltfBlock, declaration, _mapping, parser, serializedObjects) { + // set eventId and eventData. The configuration object of the glTF should have a single object. + // validate that we are running it on the right block. + if (declaration.op !== "event/send" || !gltfBlock.configuration || Object.keys(gltfBlock.configuration).length !== 1) { + throw new Error("Receive event should have a single configuration object, the event itself"); + } + const eventConfiguration = gltfBlock.configuration["event"]; + const eventId = eventConfiguration.value[0]; + if (typeof eventId !== "number") { + throw new Error("Event id should be a number"); + } + const event = parser.arrays.events[eventId]; + const serializedObject = serializedObjects[0]; + serializedObject.config || (serializedObject.config = {}); + serializedObject.config.eventId = event.eventId; + serializedObject.config.eventData = event.eventData; + return serializedObjects; + }, + }, + "event/receive": { + blocks: ["FlowGraphReceiveCustomEventBlock" /* FlowGraphBlockNames.ReceiveCustomEvent */], + outputs: { + flows: { + out: { name: "done" }, + }, + }, + validation(gltfBlock, interactivityGraph) { + if (!gltfBlock.configuration) { + Logger.Error("Receive event should have a configuration object"); + return false; + } + const eventConfiguration = gltfBlock.configuration["event"]; + if (!eventConfiguration) { + Logger.Error("Receive event should have a single configuration object, the event itself"); + return false; + } + const eventId = eventConfiguration.value[0]; + if (typeof eventId !== "number") { + Logger.Error("Event id should be a number"); + return false; + } + const event = interactivityGraph.events?.[eventId]; + if (!event) { + Logger.Error(`Event with id ${eventId} not found`); + return false; + } + return true; + }, + extraProcessor(gltfBlock, declaration, _mapping, parser, serializedObjects) { + // set eventId and eventData. The configuration object of the glTF should have a single object. + // validate that we are running it on the right block. + if (declaration.op !== "event/receive" || !gltfBlock.configuration || Object.keys(gltfBlock.configuration).length !== 1) { + throw new Error("Receive event should have a single configuration object, the event itself"); + } + const eventConfiguration = gltfBlock.configuration["event"]; + const eventId = eventConfiguration.value[0]; + if (typeof eventId !== "number") { + throw new Error("Event id should be a number"); + } + const event = parser.arrays.events[eventId]; + const serializedObject = serializedObjects[0]; + serializedObject.config || (serializedObject.config = {}); + serializedObject.config.eventId = event.eventId; + serializedObject.config.eventData = event.eventData; + return serializedObjects; + }, + }, + "math/e": getSimpleInputMapping("FlowGraphEBlock" /* FlowGraphBlockNames.E */), + "math/pi": getSimpleInputMapping("FlowGraphPIBlock" /* FlowGraphBlockNames.PI */), + "math/inf": getSimpleInputMapping("FlowGraphInfBlock" /* FlowGraphBlockNames.Inf */), + "math/nan": getSimpleInputMapping("FlowGraphNaNBlock" /* FlowGraphBlockNames.NaN */), + "math/abs": getSimpleInputMapping("FlowGraphAbsBlock" /* FlowGraphBlockNames.Abs */), + "math/sign": getSimpleInputMapping("FlowGraphSignBlock" /* FlowGraphBlockNames.Sign */), + "math/trunc": getSimpleInputMapping("FlowGraphTruncBlock" /* FlowGraphBlockNames.Trunc */), + "math/floor": getSimpleInputMapping("FlowGraphFloorBlock" /* FlowGraphBlockNames.Floor */), + "math/ceil": getSimpleInputMapping("FlowGraphCeilBlock" /* FlowGraphBlockNames.Ceil */), + "math/round": { + blocks: ["FlowGraphRoundBlock" /* FlowGraphBlockNames.Round */], + configuration: {}, + inputs: { + values: { + a: { name: "a" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + extraProcessor(gltfBlock, declaration, _mapping, parser, serializedObjects) { + // configure it to work the way glTF specifies + serializedObjects[0].config = serializedObjects[0].config || {}; + serializedObjects[0].config.roundHalfAwayFromZero = true; + return serializedObjects; + }, + }, + "math/fract": getSimpleInputMapping("FlowGraphFractBlock" /* FlowGraphBlockNames.Fraction */), + "math/neg": getSimpleInputMapping("FlowGraphNegationBlock" /* FlowGraphBlockNames.Negation */), + "math/add": getSimpleInputMapping("FlowGraphAddBlock" /* FlowGraphBlockNames.Add */, ["a", "b"], true), + "math/sub": getSimpleInputMapping("FlowGraphSubtractBlock" /* FlowGraphBlockNames.Subtract */, ["a", "b"], true), + "math/mul": { + blocks: ["FlowGraphMultiplyBlock" /* FlowGraphBlockNames.Multiply */], + extraProcessor(_gltfBlock, _declaration, _mapping, _parser, serializedObjects) { + // configure it to work the way glTF specifies + serializedObjects[0].config = serializedObjects[0].config || {}; + serializedObjects[0].config.useMatrixPerComponent = true; + // try to infer the type or fallback to Integer + // check the gltf block for the inputs, see if they have a type + let type = -1; + Object.keys(_gltfBlock.values || {}).find((value) => { + if (_gltfBlock.values?.[value].type !== undefined) { + type = _gltfBlock.values[value].type; + return true; + } + return false; + }); + if (type !== -1) { + serializedObjects[0].config.type = _parser.arrays.types[type].flowGraphType; + } + return serializedObjects; + }, + }, + "math/div": getSimpleInputMapping("FlowGraphDivideBlock" /* FlowGraphBlockNames.Divide */, ["a", "b"], true), + "math/rem": getSimpleInputMapping("FlowGraphModuloBlock" /* FlowGraphBlockNames.Modulo */, ["a", "b"]), + "math/min": getSimpleInputMapping("FlowGraphMinBlock" /* FlowGraphBlockNames.Min */, ["a", "b"]), + "math/max": getSimpleInputMapping("FlowGraphMaxBlock" /* FlowGraphBlockNames.Max */, ["a", "b"]), + "math/clamp": getSimpleInputMapping("FlowGraphClampBlock" /* FlowGraphBlockNames.Clamp */, ["a", "b", "c"]), + "math/saturate": getSimpleInputMapping("FlowGraphSaturateBlock" /* FlowGraphBlockNames.Saturate */), + "math/mix": getSimpleInputMapping("FlowGraphMathInterpolationBlock" /* FlowGraphBlockNames.MathInterpolation */, ["a", "b", "c"]), + "math/eq": getSimpleInputMapping("FlowGraphEqualityBlock" /* FlowGraphBlockNames.Equality */, ["a", "b"]), + "math/lt": getSimpleInputMapping("FlowGraphLessThanBlock" /* FlowGraphBlockNames.LessThan */, ["a", "b"]), + "math/le": getSimpleInputMapping("FlowGraphLessThanOrEqualBlock" /* FlowGraphBlockNames.LessThanOrEqual */, ["a", "b"]), + "math/gt": getSimpleInputMapping("FlowGraphGreaterThanBlock" /* FlowGraphBlockNames.GreaterThan */, ["a", "b"]), + "math/ge": getSimpleInputMapping("FlowGraphGreaterThanOrEqualBlock" /* FlowGraphBlockNames.GreaterThanOrEqual */, ["a", "b"]), + "math/isnan": getSimpleInputMapping("FlowGraphIsNaNBlock" /* FlowGraphBlockNames.IsNaN */), + "math/isinf": getSimpleInputMapping("FlowGraphIsInfBlock" /* FlowGraphBlockNames.IsInfinity */), + "math/select": { + blocks: ["FlowGraphConditionalBlock" /* FlowGraphBlockNames.Conditional */], + inputs: { + values: { + condition: { name: "condition" }, + // Should we validate those have the same type here, or assume it is already validated? + a: { name: "onTrue" }, + b: { name: "onFalse" }, + }, + }, + outputs: { + values: { + value: { name: "output" }, + }, + }, + }, + "math/random": { + blocks: ["FlowGraphRandomBlock" /* FlowGraphBlockNames.Random */], + outputs: { + values: { + value: { name: "value" }, + }, + }, + }, + "math/sin": getSimpleInputMapping("FlowGraphSinBlock" /* FlowGraphBlockNames.Sin */), + "math/cos": getSimpleInputMapping("FlowGraphCosBlock" /* FlowGraphBlockNames.Cos */), + "math/tan": getSimpleInputMapping("FlowGraphTanBlock" /* FlowGraphBlockNames.Tan */), + "math/asin": getSimpleInputMapping("FlowGraphASinBlock" /* FlowGraphBlockNames.Asin */), + "math/acos": getSimpleInputMapping("FlowGraphACosBlock" /* FlowGraphBlockNames.Acos */), + "math/atan": getSimpleInputMapping("FlowGraphATanBlock" /* FlowGraphBlockNames.Atan */), + "math/atan2": getSimpleInputMapping("FlowGraphATan2Block" /* FlowGraphBlockNames.Atan2 */, ["a", "b"]), + "math/sinh": getSimpleInputMapping("FlowGraphSinhBlock" /* FlowGraphBlockNames.Sinh */), + "math/cosh": getSimpleInputMapping("FlowGraphCoshBlock" /* FlowGraphBlockNames.Cosh */), + "math/tanh": getSimpleInputMapping("FlowGraphTanhBlock" /* FlowGraphBlockNames.Tanh */), + "math/asinh": getSimpleInputMapping("FlowGraphASinhBlock" /* FlowGraphBlockNames.Asinh */), + "math/acosh": getSimpleInputMapping("FlowGraphACoshBlock" /* FlowGraphBlockNames.Acosh */), + "math/atanh": getSimpleInputMapping("FlowGraphATanhBlock" /* FlowGraphBlockNames.Atanh */), + "math/exp": getSimpleInputMapping("FlowGraphExponentialBlock" /* FlowGraphBlockNames.Exponential */), + "math/log": getSimpleInputMapping("FlowGraphLogBlock" /* FlowGraphBlockNames.Log */), + "math/log2": getSimpleInputMapping("FlowGraphLog2Block" /* FlowGraphBlockNames.Log2 */), + "math/log10": getSimpleInputMapping("FlowGraphLog10Block" /* FlowGraphBlockNames.Log10 */), + "math/sqrt": getSimpleInputMapping("FlowGraphSquareRootBlock" /* FlowGraphBlockNames.SquareRoot */), + "math/cbrt": getSimpleInputMapping("FlowGraphCubeRootBlock" /* FlowGraphBlockNames.CubeRoot */), + "math/pow": getSimpleInputMapping("FlowGraphPowerBlock" /* FlowGraphBlockNames.Power */, ["a", "b"]), + "math/length": getSimpleInputMapping("FlowGraphLengthBlock" /* FlowGraphBlockNames.Length */), + "math/normalize": getSimpleInputMapping("FlowGraphNormalizeBlock" /* FlowGraphBlockNames.Normalize */), + "math/dot": getSimpleInputMapping("FlowGraphDotBlock" /* FlowGraphBlockNames.Dot */, ["a", "b"]), + "math/cross": getSimpleInputMapping("FlowGraphCrossBlock" /* FlowGraphBlockNames.Cross */, ["a", "b"]), + "math/rotate2d": getSimpleInputMapping("FlowGraphRotate2DBlock" /* FlowGraphBlockNames.Rotate2D */, ["a", "b"]), + "math/rotate3d": getSimpleInputMapping("FlowGraphRotate3DBlock" /* FlowGraphBlockNames.Rotate3D */, ["a", "b", "c"]), + "math/transform": { + // glTF transform is vectorN with matrixN + blocks: ["FlowGraphTransformVectorBlock" /* FlowGraphBlockNames.TransformVector */], + inputs: { + values: { + a: { name: "a" }, + b: { name: "b" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + }, + "math/combine2": { + blocks: ["FlowGraphCombineVector2Block" /* FlowGraphBlockNames.CombineVector2 */], + inputs: { + values: { + a: { name: "input_0", gltfType: "number" }, + b: { name: "input_1", gltfType: "number" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + }, + "math/combine3": { + blocks: ["FlowGraphCombineVector3Block" /* FlowGraphBlockNames.CombineVector3 */], + inputs: { + values: { + a: { name: "input_0", gltfType: "number" }, + b: { name: "input_1", gltfType: "number" }, + c: { name: "input_2", gltfType: "number" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + }, + "math/combine4": { + blocks: ["FlowGraphCombineVector4Block" /* FlowGraphBlockNames.CombineVector4 */], + inputs: { + values: { + a: { name: "input_0", gltfType: "number" }, + b: { name: "input_1", gltfType: "number" }, + c: { name: "input_2", gltfType: "number" }, + d: { name: "input_3", gltfType: "number" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + }, + // one input, N outputs! outputs named using numbers. + "math/extract2": { + blocks: ["FlowGraphExtractVector2Block" /* FlowGraphBlockNames.ExtractVector2 */], + inputs: { + values: { + a: { name: "input", gltfType: "number" }, + }, + }, + outputs: { + values: { + "0": { name: "output_0" }, + "1": { name: "output_1" }, + }, + }, + }, + "math/extract3": { + blocks: ["FlowGraphExtractVector3Block" /* FlowGraphBlockNames.ExtractVector3 */], + inputs: { + values: { + a: { name: "input", gltfType: "number" }, + }, + }, + outputs: { + values: { + "0": { name: "output_0" }, + "1": { name: "output_1" }, + "2": { name: "output_2" }, + }, + }, + }, + "math/extract4": { + blocks: ["FlowGraphExtractVector4Block" /* FlowGraphBlockNames.ExtractVector4 */], + inputs: { + values: { + a: { name: "input", gltfType: "number" }, + }, + }, + outputs: { + values: { + "0": { name: "output_0" }, + "1": { name: "output_1" }, + "2": { name: "output_2" }, + "3": { name: "output_3" }, + }, + }, + }, + "math/transpose": getSimpleInputMapping("FlowGraphTransposeBlock" /* FlowGraphBlockNames.Transpose */), + "math/determinant": getSimpleInputMapping("FlowGraphDeterminantBlock" /* FlowGraphBlockNames.Determinant */), + "math/inverse": getSimpleInputMapping("FlowGraphInvertMatrixBlock" /* FlowGraphBlockNames.InvertMatrix */), + "math/matmul": getSimpleInputMapping("FlowGraphMatrixMultiplicationBlock" /* FlowGraphBlockNames.MatrixMultiplication */, ["a", "b"]), + "math/matCompose": { + blocks: ["FlowGraphMatrixCompose" /* FlowGraphBlockNames.MatrixCompose */], + inputs: { + values: { + translation: { name: "position", gltfType: "float3" }, + rotation: { name: "rotationQuaternion", gltfType: "float4" }, + scale: { name: "scaling", gltfType: "float3" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + extraProcessor(_gltfBlock, _declaration, _mapping, _parser, serializedObjects, context) { + // configure it to work the way glTF specifies + const d = serializedObjects[0].dataInputs.find((input) => input.name === "rotationQuaternion"); + if (!d) { + throw new Error("Rotation quaternion input not found"); + } + // if value is defined, set the type to quaternion + if (context._connectionValues[d.uniqueId]) { + context._connectionValues[d.uniqueId].type = "Quaternion" /* FlowGraphTypes.Quaternion */; + } + return serializedObjects; + }, + }, + "math/matDecompose": { + blocks: ["FlowGraphMatrixDecompose" /* FlowGraphBlockNames.MatrixDecompose */], + inputs: { + values: { + a: { name: "input", gltfType: "number" }, + }, + }, + outputs: { + values: { + translation: { name: "position" }, + rotation: { name: "rotationQuaternion" }, + scale: { name: "scaling" }, + }, + }, + }, + "math/combine2x2": { + blocks: ["FlowGraphCombineMatrix2DBlock" /* FlowGraphBlockNames.CombineMatrix2D */], + inputs: { + values: { + a: { name: "input_0", gltfType: "number" }, + b: { name: "input_1", gltfType: "number" }, + c: { name: "input_2", gltfType: "number" }, + d: { name: "input_3", gltfType: "number" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + extraProcessor(_gltfBlock, _declaration, _mapping, _parser, serializedObjects) { + // configure it to work the way glTF specifies + serializedObjects[0].config = serializedObjects[0].config || {}; + serializedObjects[0].config.inputIsColumnMajor = true; + return serializedObjects; + }, + }, + "math/extract2x2": { + blocks: ["FlowGraphExtractMatrix2DBlock" /* FlowGraphBlockNames.ExtractMatrix2D */], + inputs: { + values: { + a: { name: "input", gltfType: "float2x2" }, + }, + }, + outputs: { + values: { + "0": { name: "output_0" }, + "1": { name: "output_1" }, + "2": { name: "output_2" }, + "3": { name: "output_3" }, + }, + }, + }, + "math/combine3x3": { + blocks: ["FlowGraphCombineMatrix3DBlock" /* FlowGraphBlockNames.CombineMatrix3D */], + inputs: { + values: { + a: { name: "input_0", gltfType: "number" }, + b: { name: "input_1", gltfType: "number" }, + c: { name: "input_2", gltfType: "number" }, + d: { name: "input_3", gltfType: "number" }, + e: { name: "input_4", gltfType: "number" }, + f: { name: "input_5", gltfType: "number" }, + g: { name: "input_6", gltfType: "number" }, + h: { name: "input_7", gltfType: "number" }, + i: { name: "input_8", gltfType: "number" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + extraProcessor(_gltfBlock, _declaration, _mapping, _parser, serializedObjects) { + // configure it to work the way glTF specifies + serializedObjects[0].config = serializedObjects[0].config || {}; + serializedObjects[0].config.inputIsColumnMajor = true; + return serializedObjects; + }, + }, + "math/extract3x3": { + blocks: ["FlowGraphExtractMatrix3DBlock" /* FlowGraphBlockNames.ExtractMatrix3D */], + inputs: { + values: { + a: { name: "input", gltfType: "float3x3" }, + }, + }, + outputs: { + values: { + "0": { name: "output_0" }, + "1": { name: "output_1" }, + "2": { name: "output_2" }, + "3": { name: "output_3" }, + "4": { name: "output_4" }, + "5": { name: "output_5" }, + "6": { name: "output_6" }, + "7": { name: "output_7" }, + "8": { name: "output_8" }, + }, + }, + }, + "math/combine4x4": { + blocks: ["FlowGraphCombineMatrixBlock" /* FlowGraphBlockNames.CombineMatrix */], + inputs: { + values: { + a: { name: "input_0", gltfType: "number" }, + b: { name: "input_1", gltfType: "number" }, + c: { name: "input_2", gltfType: "number" }, + d: { name: "input_3", gltfType: "number" }, + e: { name: "input_4", gltfType: "number" }, + f: { name: "input_5", gltfType: "number" }, + g: { name: "input_6", gltfType: "number" }, + h: { name: "input_7", gltfType: "number" }, + i: { name: "input_8", gltfType: "number" }, + j: { name: "input_9", gltfType: "number" }, + k: { name: "input_10", gltfType: "number" }, + l: { name: "input_11", gltfType: "number" }, + m: { name: "input_12", gltfType: "number" }, + n: { name: "input_13", gltfType: "number" }, + o: { name: "input_14", gltfType: "number" }, + p: { name: "input_15", gltfType: "number" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + extraProcessor(_gltfBlock, _declaration, _mapping, _parser, serializedObjects) { + // configure it to work the way glTF specifies + serializedObjects[0].config = serializedObjects[0].config || {}; + serializedObjects[0].config.inputIsColumnMajor = true; + return serializedObjects; + }, + }, + "math/extract4x4": { + blocks: ["FlowGraphExtractMatrixBlock" /* FlowGraphBlockNames.ExtractMatrix */], + configuration: {}, + inputs: { + values: { + a: { name: "input", gltfType: "number" }, + }, + }, + outputs: { + values: { + "0": { name: "output_0" }, + "1": { name: "output_1" }, + "2": { name: "output_2" }, + "3": { name: "output_3" }, + "4": { name: "output_4" }, + "5": { name: "output_5" }, + "6": { name: "output_6" }, + "7": { name: "output_7" }, + "8": { name: "output_8" }, + "9": { name: "output_9" }, + "10": { name: "output_10" }, + "11": { name: "output_11" }, + "12": { name: "output_12" }, + "13": { name: "output_13" }, + "14": { name: "output_14" }, + "15": { name: "output_15" }, + }, + }, + }, + "math/compose": { + blocks: ["FlowGraphMatrixCompose" /* FlowGraphBlockNames.MatrixCompose */], + configuration: {}, + inputs: { + values: { + translation: { name: "position", gltfType: "float3" }, + rotation: { name: "rotationQuaternion", gltfType: "float4" }, + scale: { name: "scaling", gltfType: "float3" }, + }, + }, + outputs: { + values: { + value: { name: "output" }, + }, + }, + }, + "math/decompose": { + blocks: ["FlowGraphMatrixDecompose" /* FlowGraphBlockNames.MatrixDecompose */], + configuration: {}, + inputs: { + values: { + a: { name: "input" }, + }, + }, + outputs: { + values: { + translation: { name: "position" }, + rotation: { name: "rotationQuaternion" }, + scale: { name: "scaling" }, + }, + }, + }, + "math/not": { + blocks: ["FlowGraphBitwiseNotBlock" /* FlowGraphBlockNames.BitwiseNot */], + inputs: { + values: { + a: { name: "a" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + extraProcessor(_gltfBlock, _declaration, _mapping, _parser, serializedObjects, context) { + // configure it to work the way glTF specifies + serializedObjects[0].config = serializedObjects[0].config || {}; + // try to infer the type or fallback to Integer + const socketIn = serializedObjects[0].dataInputs[0]; + serializedObjects[0].config.valueType = context._connectionValues[socketIn.uniqueId]?.type ?? "FlowGraphInteger" /* FlowGraphTypes.Integer */; + return serializedObjects; + }, + }, + "math/and": { + blocks: ["FlowGraphBitwiseAndBlock" /* FlowGraphBlockNames.BitwiseAnd */], + inputs: { + values: { + a: { name: "a" }, + b: { name: "b" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + extraProcessor(_gltfBlock, _declaration, _mapping, _parser, serializedObjects, context) { + // configure it to work the way glTF specifies + serializedObjects[0].config = serializedObjects[0].config || {}; + // try to infer the type or fallback to Integer + const socketInA = serializedObjects[0].dataInputs[0]; + const socketInB = serializedObjects[0].dataInputs[1]; + serializedObjects[0].config.valueType = + context._connectionValues[socketInA.uniqueId]?.type ?? context._connectionValues[socketInB.uniqueId]?.type ?? "FlowGraphInteger" /* FlowGraphTypes.Integer */; + return serializedObjects; + }, + }, + "math/or": { + blocks: ["FlowGraphBitwiseOrBlock" /* FlowGraphBlockNames.BitwiseOr */], + inputs: { + values: { + a: { name: "a" }, + b: { name: "b" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + extraProcessor(_gltfBlock, _declaration, _mapping, _parser, serializedObjects, context) { + // configure it to work the way glTF specifies + serializedObjects[0].config = serializedObjects[0].config || {}; + // try to infer the type or fallback to Integer + const socketInA = serializedObjects[0].dataInputs[0]; + const socketInB = serializedObjects[0].dataInputs[1]; + serializedObjects[0].config.valueType = + context._connectionValues[socketInA.uniqueId]?.type ?? context._connectionValues[socketInB.uniqueId]?.type ?? "FlowGraphInteger" /* FlowGraphTypes.Integer */; + return serializedObjects; + }, + }, + "math/xor": { + blocks: ["FlowGraphBitwiseXorBlock" /* FlowGraphBlockNames.BitwiseXor */], + inputs: { + values: { + a: { name: "a" }, + b: { name: "b" }, + }, + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + extraProcessor(_gltfBlock, _declaration, _mapping, _parser, serializedObjects, context) { + // configure it to work the way glTF specifies + serializedObjects[0].config = serializedObjects[0].config || {}; + // try to infer the type or fallback to Integer + const socketInA = serializedObjects[0].dataInputs[0]; + const socketInB = serializedObjects[0].dataInputs[1]; + serializedObjects[0].config.valueType = + context._connectionValues[socketInA.uniqueId]?.type ?? context._connectionValues[socketInB.uniqueId]?.type ?? "FlowGraphInteger" /* FlowGraphTypes.Integer */; + return serializedObjects; + }, + }, + "math/asr": getSimpleInputMapping("FlowGraphBitwiseRightShiftBlock" /* FlowGraphBlockNames.BitwiseRightShift */, ["a", "b"]), + "math/lsl": getSimpleInputMapping("FlowGraphBitwiseLeftShiftBlock" /* FlowGraphBlockNames.BitwiseLeftShift */, ["a", "b"]), + "math/clz": getSimpleInputMapping("FlowGraphLeadingZerosBlock" /* FlowGraphBlockNames.LeadingZeros */), + "math/ctz": getSimpleInputMapping("FlowGraphTrailingZerosBlock" /* FlowGraphBlockNames.TrailingZeros */), + "math/popcnt": getSimpleInputMapping("FlowGraphOneBitsCounterBlock" /* FlowGraphBlockNames.OneBitsCounter */), + "math/rad": getSimpleInputMapping("FlowGraphDegToRadBlock" /* FlowGraphBlockNames.DegToRad */), + "math/deg": getSimpleInputMapping("FlowGraphRadToDegBlock" /* FlowGraphBlockNames.RadToDeg */), + "type/boolToInt": getSimpleInputMapping("FlowGraphBooleanToInt" /* FlowGraphBlockNames.BooleanToInt */), + "type/boolToFloat": getSimpleInputMapping("FlowGraphBooleanToFloat" /* FlowGraphBlockNames.BooleanToFloat */), + "type/intToBool": getSimpleInputMapping("FlowGraphIntToBoolean" /* FlowGraphBlockNames.IntToBoolean */), + "type/intToFloat": getSimpleInputMapping("FlowGraphIntToFloat" /* FlowGraphBlockNames.IntToFloat */), + "type/floatToInt": getSimpleInputMapping("FlowGraphFloatToInt" /* FlowGraphBlockNames.FloatToInt */), + "type/floatToBool": getSimpleInputMapping("FlowGraphFloatToBoolean" /* FlowGraphBlockNames.FloatToBoolean */), + // flows + "flow/sequence": { + blocks: ["FlowGraphSequenceBlock" /* FlowGraphBlockNames.Sequence */], + extraProcessor(gltfBlock, _declaration, _mapping, _arrays, serializedObjects) { + const serializedObject = serializedObjects[0]; + serializedObject.config || (serializedObject.config = {}); + serializedObject.config.outputSignalCount = Object.keys(gltfBlock.flows || []).length; + serializedObject.signalOutputs.forEach((output, index) => { + output.name = "out_" + index; + }); + return serializedObjects; + }, + }, + "flow/branch": { + blocks: ["FlowGraphBranchBlock" /* FlowGraphBlockNames.Branch */], + outputs: { + flows: { + true: { name: "onTrue" }, + false: { name: "onFalse" }, + }, + }, + }, + "flow/switch": { + blocks: ["FlowGraphSwitchBlock" /* FlowGraphBlockNames.Switch */], + configuration: { + cases: { name: "cases", inOptions: true, defaultValue: [] }, + }, + inputs: { + values: { + selection: { name: "case" }, + }, + }, + validation(gltfBlock) { + if (gltfBlock.configuration && gltfBlock.configuration.cases) { + const cases = gltfBlock.configuration.cases.value; + const onlyIntegers = cases.every((caseValue) => { + // case value should be an integer. Since Number.isInteger(1.0) is true, we need to check if toString has only digits. + return typeof caseValue === "number" && /^\d+$/.test(caseValue.toString()); + }); + if (!onlyIntegers) { + gltfBlock.configuration.cases.value = []; + return true; + } + // check for duplicates + const uniqueCases = new Set(cases); + gltfBlock.configuration.cases.value = Array.from(uniqueCases); + } + return true; + }, + extraProcessor(gltfBlock, declaration, _mapping, _arrays, serializedObjects) { + // convert all names of output flow to out_$1 apart from "default" + if (declaration.op !== "flow/switch" || !gltfBlock.flows || Object.keys(gltfBlock.flows).length === 0) { + throw new Error("Switch should have a single configuration object, the cases array"); + } + const serializedObject = serializedObjects[0]; + serializedObject.signalOutputs.forEach((output) => { + if (output.name !== "default") { + output.name = "out_" + output.name; + } + }); + return serializedObjects; + }, + }, + "flow/while": { + blocks: ["FlowGraphWhileLoopBlock" /* FlowGraphBlockNames.WhileLoop */], + outputs: { + flows: { + loopBody: { name: "executionFlow" }, + }, + }, + }, + "flow/for": { + blocks: ["FlowGraphForLoopBlock" /* FlowGraphBlockNames.ForLoop */], + configuration: { + initialIndex: { name: "initialIndex", gltfType: "number", inOptions: true, defaultValue: 0 }, + }, + inputs: { + values: { + startIndex: { name: "startIndex", gltfType: "number" }, + endIndex: { name: "endIndex", gltfType: "number" }, + }, + }, + outputs: { + values: { + index: { name: "index" }, + }, + flows: { + loopBody: { name: "executionFlow" }, + }, + }, + }, + "flow/doN": { + blocks: ["FlowGraphDoNBlock" /* FlowGraphBlockNames.DoN */], + configuration: {}, + inputs: { + values: { + n: { name: "maxExecutions", gltfType: "number" }, + }, + }, + outputs: { + values: { + currentCount: { name: "executionCount" }, + }, + }, + }, + "flow/multiGate": { + blocks: ["FlowGraphMultiGateBlock" /* FlowGraphBlockNames.MultiGate */], + configuration: { + isRandom: { name: "isRandom", gltfType: "boolean", inOptions: true, defaultValue: false }, + isLoop: { name: "isLoop", gltfType: "boolean", inOptions: true, defaultValue: false }, + }, + extraProcessor(gltfBlock, declaration, _mapping, _arrays, serializedObjects) { + if (declaration.op !== "flow/multiGate" || !gltfBlock.flows || Object.keys(gltfBlock.flows).length === 0) { + throw new Error("MultiGate should have a single configuration object, the number of output flows"); + } + const serializedObject = serializedObjects[0]; + serializedObject.config || (serializedObject.config = {}); + serializedObject.config.outputSignalCount = Object.keys(gltfBlock.flows).length; + serializedObject.signalOutputs.forEach((output, index) => { + output.name = "out_" + index; + }); + return serializedObjects; + }, + }, + "flow/waitAll": { + blocks: ["FlowGraphWaitAllBlock" /* FlowGraphBlockNames.WaitAll */], + configuration: { + inputFlows: { name: "inputSignalCount", gltfType: "number", inOptions: true, defaultValue: 0 }, + }, + inputs: { + flows: { + "[segment]": { name: "in_$1" }, + }, + }, + validation(gltfBlock) { + // check that the configuration value is an integer + if (typeof gltfBlock.configuration?.inputFlows?.value[0] !== "number") { + gltfBlock.configuration = gltfBlock.configuration || { + inputFlows: { value: [0] }, + }; + gltfBlock.configuration.inputFlows.value = [0]; + } + return true; + }, + }, + "flow/throttle": { + blocks: ["FlowGraphThrottleBlock" /* FlowGraphBlockNames.Throttle */], + outputs: { + flows: { + err: { name: "error" }, + }, + }, + }, + "flow/setDelay": { + blocks: ["FlowGraphSetDelayBlock" /* FlowGraphBlockNames.SetDelay */], + outputs: { + flows: { + err: { name: "error" }, + }, + }, + }, + "flow/cancelDelay": { + blocks: ["FlowGraphCancelDelayBlock" /* FlowGraphBlockNames.CancelDelay */], + }, + "variable/get": { + blocks: ["FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */], + validation(gltfBlock) { + if (!gltfBlock.configuration?.variable?.value) { + Logger.Error("Variable get block should have a variable configuration"); + return false; + } + return true; + }, + configuration: { + variable: { + name: "variable", + gltfType: "number", + flowGraphType: "string", + inOptions: true, + isVariable: true, + dataTransformer(index, parser) { + return [parser.getVariableName(index[0])]; + }, + }, + }, + }, + "variable/set": { + blocks: ["FlowGraphSetVariableBlock" /* FlowGraphBlockNames.SetVariable */], + configuration: { + variable: { + name: "variable", + gltfType: "number", + flowGraphType: "string", + inOptions: true, + isVariable: true, + dataTransformer(index, parser) { + return [parser.getVariableName(index[0])]; + }, + }, + }, + }, + "variable/setMultiple": { + blocks: ["FlowGraphSetVariableBlock" /* FlowGraphBlockNames.SetVariable */], + configuration: { + variables: { + name: "variables", + gltfType: "number", + flowGraphType: "string", + inOptions: true, + dataTransformer(index, parser) { + return [index[0].map((i) => parser.getVariableName(i))]; + }, + }, + }, + extraProcessor(_gltfBlock, _declaration, _mapping, parser, serializedObjects) { + // variable/get configuration + const serializedGetVariable = serializedObjects[0]; + serializedGetVariable.dataInputs.forEach((input) => { + input.name = parser.getVariableName(+input.name); + }); + return serializedObjects; + }, + }, + "variable/interpolate": { + blocks: [ + "FlowGraphInterpolationBlock" /* FlowGraphBlockNames.ValueInterpolation */, + "FlowGraphContextBlock" /* FlowGraphBlockNames.Context */, + "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */, + "FlowGraphBezierCurveEasing" /* FlowGraphBlockNames.BezierCurveEasing */, + "FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */, + ], + configuration: { + variable: { + name: "propertyName", + inOptions: true, + isVariable: true, + dataTransformer(index, parser) { + return [parser.getVariableName(index[0])]; + }, + }, + useSlerp: { + name: "animationType", + inOptions: true, + defaultValue: false, + dataTransformer: (value) => { + if (value[0] === true) { + return ["Quaternion" /* FlowGraphTypes.Quaternion */]; + } + else { + return [undefined]; + } + }, + }, + }, + inputs: { + values: { + value: { name: "value_1" }, + duration: { name: "duration_1", gltfType: "number" }, + p1: { name: "controlPoint1", toBlock: "FlowGraphBezierCurveEasing" /* FlowGraphBlockNames.BezierCurveEasing */ }, + p2: { name: "controlPoint2", toBlock: "FlowGraphBezierCurveEasing" /* FlowGraphBlockNames.BezierCurveEasing */ }, + }, + flows: { + in: { name: "in", toBlock: "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */ }, + }, + }, + outputs: { + flows: { + err: { name: "error", toBlock: "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */ }, + out: { name: "out", toBlock: "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */ }, + done: { name: "done", toBlock: "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */ }, + }, + }, + interBlockConnectors: [ + { + input: "object", + output: "userVariables", + inputBlockIndex: 2, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "animation", + output: "animation", + inputBlockIndex: 2, + outputBlockIndex: 0, + isVariable: true, + }, + { + input: "easingFunction", + output: "easingFunction", + inputBlockIndex: 0, + outputBlockIndex: 3, + isVariable: true, + }, + { + input: "value_0", + output: "value", + inputBlockIndex: 0, + outputBlockIndex: 4, + isVariable: true, + }, + ], + extraProcessor(gltfBlock, _declaration, _mapping, parser, serializedObjects) { + var _a, _b; + // is useSlerp is used, animationType should be set to be quaternion! + const serializedValueInterpolation = serializedObjects[0]; + const propertyIndex = gltfBlock.configuration?.variable.value[0]; + if (typeof propertyIndex !== "number") { + Logger.Error("Variable index is not defined for variable interpolation block"); + throw new Error("Variable index is not defined for variable interpolation block"); + } + const variable = parser.arrays.staticVariables[propertyIndex]; + // if not set by useSlerp + if (typeof serializedValueInterpolation.config.animationType.value === "undefined") { + // get the value type + parser.arrays.staticVariables; + serializedValueInterpolation.config.animationType.value = getAnimationTypeByFlowGraphType(variable.type); + } + // variable/get configuration + const serializedGetVariable = serializedObjects[4]; + serializedGetVariable.config || (serializedGetVariable.config = {}); + (_a = serializedGetVariable.config).variable || (_a.variable = {}); + serializedGetVariable.config.variable.value = parser.getVariableName(propertyIndex); + // get the control points from the easing block + (_b = serializedObjects[3]).config || (_b.config = {}); + return serializedObjects; + }, + }, + "pointer/get": { + blocks: ["FlowGraphGetPropertyBlock" /* FlowGraphBlockNames.GetProperty */, "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */], + configuration: { + pointer: { name: "jsonPointer", toBlock: "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */ }, + }, + inputs: { + values: { + "[segment]": { name: "$1", toBlock: "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */ }, + }, + }, + interBlockConnectors: [ + { + input: "object", + output: "object", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "propertyName", + output: "propertyName", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "customGetFunction", + output: "getFunction", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + ], + extraProcessor(gltfBlock, _declaration, _mapping, parser, serializedObjects) { + serializedObjects.forEach((serializedObject) => { + // check if it is the json pointer block + if (serializedObject.className === "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */) { + serializedObject.config || (serializedObject.config = {}); + serializedObject.config.outputValue = true; + } + }); + return serializedObjects; + }, + }, + "pointer/set": { + blocks: ["FlowGraphSetPropertyBlock" /* FlowGraphBlockNames.SetProperty */, "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */], + configuration: { + pointer: { name: "jsonPointer", toBlock: "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */ }, + }, + inputs: { + values: { + // must be defined due to the array taking over + value: { name: "value" }, + "[segment]": { name: "$1", toBlock: "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */ }, + }, + }, + outputs: { + flows: { + err: { name: "error" }, + }, + }, + interBlockConnectors: [ + { + input: "object", + output: "object", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "propertyName", + output: "propertyName", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "customSetFunction", + output: "setFunction", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + ], + extraProcessor(gltfBlock, _declaration, _mapping, parser, serializedObjects) { + serializedObjects.forEach((serializedObject) => { + // check if it is the json pointer block + if (serializedObject.className === "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */) { + serializedObject.config || (serializedObject.config = {}); + serializedObject.config.outputValue = true; + } + }); + return serializedObjects; + }, + }, + "pointer/interpolate": { + // interpolate, parse the pointer and play the animation generated. 3 blocks! + blocks: ["FlowGraphInterpolationBlock" /* FlowGraphBlockNames.ValueInterpolation */, "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */, "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */, "FlowGraphEasingBlock" /* FlowGraphBlockNames.Easing */], + configuration: { + pointer: { name: "jsonPointer", toBlock: "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */ }, + }, + inputs: { + values: { + value: { name: "value_1" }, + "[segment]": { name: "$1", toBlock: "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */ }, + duration: { name: "duration_1", gltfType: "number" /*, inOptions: true */ }, + p1: { name: "controlPoint1", toBlock: "FlowGraphEasingBlock" /* FlowGraphBlockNames.Easing */ }, + p2: { name: "controlPoint2", toBlock: "FlowGraphEasingBlock" /* FlowGraphBlockNames.Easing */ }, + }, + flows: { + in: { name: "in", toBlock: "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */ }, + }, + }, + outputs: { + flows: { + err: { name: "error", toBlock: "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */ }, + out: { name: "out", toBlock: "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */ }, + done: { name: "done", toBlock: "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */ }, + }, + }, + interBlockConnectors: [ + { + input: "object", + output: "object", + inputBlockIndex: 2, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "propertyName", + output: "propertyName", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "customBuildAnimation", + output: "generateAnimationsFunction", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "animation", + output: "animation", + inputBlockIndex: 2, + outputBlockIndex: 0, + isVariable: true, + }, + { + input: "easingFunction", + output: "easingFunction", + inputBlockIndex: 0, + outputBlockIndex: 3, + isVariable: true, + }, + { + input: "value_0", + output: "value", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + ], + extraProcessor(gltfBlock, _declaration, _mapping, parser, serializedObjects) { + serializedObjects.forEach((serializedObject) => { + // check if it is the json pointer block + if (serializedObject.className === "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */) { + serializedObject.config || (serializedObject.config = {}); + serializedObject.config.outputValue = true; + } + else if (serializedObject.className === "FlowGraphInterpolationBlock" /* FlowGraphBlockNames.ValueInterpolation */) { + serializedObject.config || (serializedObject.config = {}); + Object.keys(gltfBlock.values || []).forEach((key) => { + const value = gltfBlock.values?.[key]; + if (key === "value" && value) { + // get the type of the value + const type = value.type; + if (type !== undefined) { + serializedObject.config.animationType = parser.arrays.types[type].flowGraphType; + } + } + }); + } + }); + return serializedObjects; + }, + }, + "animation/start": { + blocks: ["FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */, "FlowGraphArrayIndexBlock" /* FlowGraphBlockNames.ArrayIndex */, "KHR_interactivity/FlowGraphGLTFDataProvider"], + inputs: { + values: { + animation: { name: "index", gltfType: "number", toBlock: "FlowGraphArrayIndexBlock" /* FlowGraphBlockNames.ArrayIndex */ }, + speed: { name: "speed", gltfType: "number" }, + // 60 is a const from the glTF loader + startTime: { name: "from", gltfType: "number", dataTransformer: (time, parser) => [time[0] * parser._loader.parent.targetFps] }, + endTime: { name: "to", gltfType: "number", dataTransformer: (time, parser) => [time[0] * parser._loader.parent.targetFps] }, + }, + }, + outputs: { + flows: { + err: { name: "error" }, + }, + }, + interBlockConnectors: [ + { + input: "animationGroup", + output: "value", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "array", + output: "animationGroups", + inputBlockIndex: 1, + outputBlockIndex: 2, + isVariable: true, + }, + ], + extraProcessor(_gltfBlock, _declaration, _mapping, _arrays, serializedObjects, _context, globalGLTF) { + // add the glTF to the configuration of the last serialized object + const serializedObject = serializedObjects[serializedObjects.length - 1]; + serializedObject.config || (serializedObject.config = {}); + serializedObject.config.glTF = globalGLTF; + return serializedObjects; + }, + }, + "animation/stop": { + blocks: ["FlowGraphStopAnimationBlock" /* FlowGraphBlockNames.StopAnimation */, "FlowGraphArrayIndexBlock" /* FlowGraphBlockNames.ArrayIndex */, "KHR_interactivity/FlowGraphGLTFDataProvider"], + inputs: { + values: { + animation: { name: "index", gltfType: "number", toBlock: "FlowGraphArrayIndexBlock" /* FlowGraphBlockNames.ArrayIndex */ }, + }, + }, + outputs: { + flows: { + err: { name: "error" }, + }, + }, + interBlockConnectors: [ + { + input: "animationGroup", + output: "value", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "array", + output: "animationGroups", + inputBlockIndex: 1, + outputBlockIndex: 2, + isVariable: true, + }, + ], + extraProcessor(_gltfBlock, _declaration, _mapping, _arrays, serializedObjects, _context, globalGLTF) { + // add the glTF to the configuration of the last serialized object + const serializedObject = serializedObjects[serializedObjects.length - 1]; + serializedObject.config || (serializedObject.config = {}); + serializedObject.config.glTF = globalGLTF; + return serializedObjects; + }, + }, + "animation/stopAt": { + blocks: ["FlowGraphStopAnimationBlock" /* FlowGraphBlockNames.StopAnimation */, "FlowGraphArrayIndexBlock" /* FlowGraphBlockNames.ArrayIndex */, "KHR_interactivity/FlowGraphGLTFDataProvider"], + configuration: {}, + inputs: { + values: { + animation: { name: "index", gltfType: "number", toBlock: "FlowGraphArrayIndexBlock" /* FlowGraphBlockNames.ArrayIndex */ }, + stopTime: { name: "stopAtFrame", gltfType: "number", dataTransformer: (time, parser) => [time[0] * parser._loader.parent.targetFps] }, + }, + }, + outputs: { + flows: { + err: { name: "error" }, + }, + }, + interBlockConnectors: [ + { + input: "animationGroup", + output: "value", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "array", + output: "animationGroups", + inputBlockIndex: 1, + outputBlockIndex: 2, + isVariable: true, + }, + ], + extraProcessor(_gltfBlock, _declaration, _mapping, _arrays, serializedObjects, _context, globalGLTF) { + // add the glTF to the configuration of the last serialized object + const serializedObject = serializedObjects[serializedObjects.length - 1]; + serializedObject.config || (serializedObject.config = {}); + serializedObject.config.glTF = globalGLTF; + return serializedObjects; + }, + }, + "math/switch": { + blocks: ["FlowGraphDataSwitchBlock" /* FlowGraphBlockNames.DataSwitch */], + configuration: { + cases: { name: "cases", inOptions: true, defaultValue: [] }, + }, + inputs: { + values: { + selection: { name: "case" }, + }, + }, + validation(gltfBlock) { + if (gltfBlock.configuration && gltfBlock.configuration.cases) { + const cases = gltfBlock.configuration.cases.value; + const onlyIntegers = cases.every((caseValue) => { + // case value should be an integer. Since Number.isInteger(1.0) is true, we need to check if toString has only digits. + return typeof caseValue === "number" && /^\d+$/.test(caseValue.toString()); + }); + if (!onlyIntegers) { + gltfBlock.configuration.cases.value = []; + return true; + } + // check for duplicates + const uniqueCases = new Set(cases); + gltfBlock.configuration.cases.value = Array.from(uniqueCases); + } + return true; + }, + extraProcessor(_gltfBlock, _declaration, _mapping, _arrays, serializedObjects) { + const serializedObject = serializedObjects[0]; + serializedObject.dataInputs.forEach((input) => { + if (input.name !== "default" && input.name !== "case") { + input.name = "in_" + input.name; + } + }); + return serializedObjects; + }, + }, + "debug/log": { + blocks: ["FlowGraphConsoleLogBlock" /* FlowGraphBlockNames.ConsoleLog */], + configuration: { + message: { name: "messageTemplate", inOptions: true }, + }, + }, +}; +function getSimpleInputMapping(type, inputs = ["a"], inferType) { + return { + blocks: [type], + inputs: { + values: inputs.reduce((acc, input) => { + acc[input] = { name: input }; + return acc; + }, {}), + }, + outputs: { + values: { + value: { name: "value" }, + }, + }, + extraProcessor(_gltfBlock, _declaration, _mapping, _parser, serializedObjects) { + if (inferType) { + // configure it to work the way glTF specifies + serializedObjects[0].config = serializedObjects[0].config || {}; + // try to infer the type or fallback to Integer + // check the gltf block for the inputs, see if they have a type + let type = -1; + Object.keys(_gltfBlock.values || {}).find((value) => { + if (_gltfBlock.values?.[value].type !== undefined) { + type = _gltfBlock.values[value].type; + return true; + } + return false; + }); + if (type !== -1) { + serializedObjects[0].config.type = _parser.arrays.types[type].flowGraphType; + } + } + return serializedObjects; + }, + }; +} +/** + * + * These are the nodes from the specs: + +### Math Nodes +1. **Constants** + - E (`math/e`) FlowGraphBlockNames.E + - Pi (`math/pi`) FlowGraphBlockNames.PI + - Infinity (`math/inf`) FlowGraphBlockNames.Inf + - Not a Number (`math/nan`) FlowGraphBlockNames.NaN +2. **Arithmetic Nodes** + - Absolute Value (`math/abs`) FlowGraphBlockNames.Abs + - Sign (`math/sign`) FlowGraphBlockNames.Sign + - Truncate (`math/trunc`) FlowGraphBlockNames.Trunc + - Floor (`math/floor`) FlowGraphBlockNames.Floor + - Ceil (`math/ceil`) FlowGraphBlockNames.Ceil + - Round (`math/round`) FlowGraphBlockNames.Round + - Fraction (`math/fract`) FlowGraphBlockNames.Fract + - Negation (`math/neg`) FlowGraphBlockNames.Negation + - Addition (`math/add`) FlowGraphBlockNames.Add + - Subtraction (`math/sub`) FlowGraphBlockNames.Subtract + - Multiplication (`math/mul`) FlowGraphBlockNames.Multiply + - Division (`math/div`) FlowGraphBlockNames.Divide + - Remainder (`math/rem`) FlowGraphBlockNames.Modulo + - Minimum (`math/min`) FlowGraphBlockNames.Min + - Maximum (`math/max`) FlowGraphBlockNames.Max + - Clamp (`math/clamp`) FlowGraphBlockNames.Clamp + - Saturate (`math/saturate`) FlowGraphBlockNames.Saturate + - Interpolate (`math/mix`) FlowGraphBlockNames.MathInterpolation +3. **Comparison Nodes** + - Equality (`math/eq`) FlowGraphBlockNames.Equality + - Less Than (`math/lt`) FlowGraphBlockNames.LessThan + - Less Than Or Equal To (`math/le`) FlowGraphBlockNames.LessThanOrEqual + - Greater Than (`math/gt`) FlowGraphBlockNames.GreaterThan + - Greater Than Or Equal To (`math/ge`) FlowGraphBlockNames.GreaterThanOrEqual +4. **Special Nodes** + - Is Not a Number (`math/isnan`) FlowGraphBlockNames.IsNaN + - Is Infinity (`math/isinf`) FlowGraphBlockNames.IsInfinity + - Select (`math/select`) FlowGraphBlockNames.Conditional + - Random (`math/random`) FlowGraphBlockNames.Random +5. **Angle and Trigonometry Nodes** + - Degrees-To-Radians (`math/rad`) FlowGraphBlockNames.DegToRad + - Radians-To-Degrees (`math/deg`) FlowGraphBlockNames.RadToDeg + - Sine (`math/sin`) FlowGraphBlockNames.Sin + - Cosine (`math/cos`) FlowGraphBlockNames.Cos + - Tangent (`math/tan`) FlowGraphBlockNames.Tan + - Arcsine (`math/asin`) FlowGraphBlockNames.Asin + - Arccosine (`math/acos`) FlowGraphBlockNames.Acos + - Arctangent (`math/atan`) FlowGraphBlockNames.Atan + - Arctangent 2 (`math/atan2`) FlowGraphBlockNames.Atan2 +6. **Hyperbolic Nodes** + - Hyperbolic Sine (`math/sinh`) FlowGraphBlockNames.Sinh + - Hyperbolic Cosine (`math/cosh`) FlowGraphBlockNames.Cosh + - Hyperbolic Tangent (`math/tanh`) FlowGraphBlockNames.Tanh + - Inverse Hyperbolic Sine (`math/asinh`) FlowGraphBlockNames.Asinh + - Inverse Hyperbolic Cosine (`math/acosh`) FlowGraphBlockNames.Acosh + - Inverse Hyperbolic Tangent (`math/atanh`) FlowGraphBlockNames.Atanh +7. **Exponential Nodes** + - Exponent (`math/exp`) FlowGraphBlockNames.Exponential + - Natural Logarithm (`math/log`) FlowGraphBlockNames.Log + - Base-2 Logarithm (`math/log2`) FlowGraphBlockNames.Log2 + - Base-10 Logarithm (`math/log10`) FlowGraphBlockNames.Log10 + - Square Root (`math/sqrt`) FlowGraphBlockNames.SquareRoot + - Cube Root (`math/cbrt`) FlowGraphBlockNames.CubeRoot + - Power (`math/pow`) FlowGraphBlockNames.Power +8. **Vector Nodes** + - Length (`math/length`) FlowGraphBlockNames.Length + - Normalize (`math/normalize`) FlowGraphBlockNames.Normalize + - Dot Product (`math/dot`) FlowGraphBlockNames.Dot + - Cross Product (`math/cross`) FlowGraphBlockNames.Cross + - Rotate 2D (`math/rotate2d`) FlowGraphBlockNames.Rotate2D + - Rotate 3D (`math/rotate3d`) FlowGraphBlockNames.Rotate3D + - Transform (`math/transform`) FlowGraphBlockNames.TransformVector +9. **Matrix Nodes** + - Transpose (`math/transpose`) FlowGraphBlockNames.Transpose + - Determinant (`math/determinant`) FlowGraphBlockNames.Determinant + - Inverse (`math/inverse`) FlowGraphBlockNames.InvertMatrix + - Multiplication (`math/matmul`) FlowGraphBlockNames.MatrixMultiplication +10. **Swizzle Nodes** + - Combine (`math/combine2`, `math/combine3`, `math/combine4`, `math/combine2x2`, `math/combine3x3`, `math/combine4x4`) + FlowGraphBlockNames.CombineVector2, FlowGraphBlockNames.CombineVector3, FlowGraphBlockNames.CombineVector4 + FlowGraphBlockNames.CombineMatrix2D, FlowGraphBlockNames.CombineMatrix3D, FlowGraphBlockNames.CombineMatrix + - Extract (`math/extract2`, `math/extract3`, `math/extract4`, `math/extract2x2`, `math/extract3x3`, `math/extract4x4`) + FlowGraphBlockNames.ExtractVector2, FlowGraphBlockNames.ExtractVector3, FlowGraphBlockNames.ExtractVector4 + FlowGraphBlockNames.ExtractMatrix2D, FlowGraphBlockNames.ExtractMatrix3D, FlowGraphBlockNames.ExtractMatrix +11. **Integer Arithmetic Nodes** + - Absolute Value (`math/abs`) FlowGraphBlockNames.Abs + - Sign (`math/sign`) FlowGraphBlockNames.Sign + - Negation (`math/neg`) FlowGraphBlockNames.Negation + - Addition (`math/add`) FlowGraphBlockNames.Add + - Subtraction (`math/sub`) FlowGraphBlockNames.Subtract + - Multiplication (`math/mul`) FlowGraphBlockNames.Multiply + - Division (`math/div`) FlowGraphBlockNames.Divide + - Remainder (`math/rem`) FlowGraphBlockNames.Modulo + - Minimum (`math/min`) FlowGraphBlockNames.Min + - Maximum (`math/max`) FlowGraphBlockNames.Max + - Clamp (`math/clamp`) FlowGraphBlockNames.Clamp +12. **Integer Comparison Nodes** + - Equality (`math/eq`) FlowGraphBlockNames.Equality + - Less Than (`math/lt`) FlowGraphBlockNames.LessThan + - Less Than Or Equal To (`math/le`) FlowGraphBlockNames.LessThanOrEqual + - Greater Than (`math/gt`) FlowGraphBlockNames.GreaterThan + - Greater Than Or Equal To (`math/ge`) FlowGraphBlockNames.GreaterThanOrEqual +13. **Integer Bitwise Nodes** + - Bitwise NOT (`math/not`) FlowGraphBlockNames.BitwiseNot + - Bitwise AND (`math/and`) FlowGraphBlockNames.BitwiseAnd + - Bitwise OR (`math/or`) FlowGraphBlockNames.BitwiseOr + - Bitwise XOR (`math/xor`) FlowGraphBlockNames.BitwiseXor + - Right Shift (`math/asr`) FlowGraphBlockNames.BitwiseRightShift + - Left Shift (`math/lsl`) FlowGraphBlockNames.BitwiseLeftShift + - Count Leading Zeros (`math/clz`) FlowGraphBlockNames.LeadingZeros + - Count Trailing Zeros (`math/ctz`) FlowGraphBlockNames.TrailingZeros + - Count One Bits (`math/popcnt`) FlowGraphBlockNames.OneBitsCounter +14. **Boolean Arithmetic Nodes** + - Equality (`math/eq`) FlowGraphBlockNames.Equality + - Boolean NOT (`math/not`) FlowGraphBlockNames.BitwiseNot + - Boolean AND (`math/and`) FlowGraphBlockNames.BitwiseAnd + - Boolean OR (`math/or`) FlowGraphBlockNames.BitwiseOr + - Boolean XOR (`math/xor`) FlowGraphBlockNames.BitwiseXor + +### Type Conversion Nodes +1. **Boolean Conversion Nodes** + - Boolean to Integer (`type/boolToInt`) FlowGraphBlockNames.BooleanToInt + - Boolean to Float (`type/boolToFloat`) FlowGraphBlockNames.BooleanToFloat +2. **Integer Conversion Nodes** + - Integer to Boolean (`type/intToBool`) FlowGraphBlockNames.IntToBoolean + - Integer to Float (`type/intToFloat`) FlowGraphBlockNames.IntToFloat +3. **Float Conversion Nodes** + - Float to Boolean (`type/floatToBool`) FlowGraphBlockNames.FloatToBoolean + - Float to Integer (`type/floatToInt`) FlowGraphBlockNames.FloatToInt + +### Control Flow Nodes +1. **Sync Nodes** + - Sequence (`flow/sequence`) FlowGraphBlockNames.Sequence + - Branch (`flow/branch`) FlowGraphBlockNames.Branch + - Switch (`flow/switch`) FlowGraphBlockNames.Switch + - While Loop (`flow/while`) FlowGraphBlockNames.WhileLoop + - For Loop (`flow/for`) FlowGraphBlockNames.ForLoop + - Do N (`flow/doN`) FlowGraphBlockNames.DoN + - Multi Gate (`flow/multiGate`) FlowGraphBlockNames.MultiGate + - Wait All (`flow/waitAll`) FlowGraphBlockNames.WaitAll + - Throttle (`flow/throttle`) FlowGraphBlockNames.Throttle +2. **Delay Nodes** + - Set Delay (`flow/setDelay`) FlowGraphBlockNames.SetDelay + - Cancel Delay (`flow/cancelDelay`) FlowGraphBlockNames.CancelDelay + +### State Manipulation Nodes +1. **Custom Variable Access** + - Variable Get (`variable/get`) FlowGraphBlockNames.GetVariable + - Variable Set (`variable/set`) FlowGraphBlockNames.SetVariable + - Variable Interpolate (`variable/interpolate`) +2. **Object Model Access** // TODO fully test this!!! + - JSON Pointer Template Parsing (`pointer/get`) [FlowGraphBlockNames.GetProperty, FlowGraphBlockNames.JsonPointerParser] + - Effective JSON Pointer Generation (`pointer/set`) [FlowGraphBlockNames.SetProperty, FlowGraphBlockNames.JsonPointerParser] + - Pointer Get (`pointer/get`) [FlowGraphBlockNames.GetProperty, FlowGraphBlockNames.JsonPointerParser] + - Pointer Set (`pointer/set`) [FlowGraphBlockNames.SetProperty, FlowGraphBlockNames.JsonPointerParser] + - Pointer Interpolate (`pointer/interpolate`) [FlowGraphBlockNames.ValueInterpolation, FlowGraphBlockNames.JsonPointerParser, FlowGraphBlockNames.PlayAnimation, FlowGraphBlockNames.Easing] + +### Animation Control Nodes +1. **Animation Play** (`animation/start`) FlowGraphBlockNames.PlayAnimation +2. **Animation Stop** (`animation/stop`) FlowGraphBlockNames.StopAnimation +3. **Animation Stop At** (`animation/stopAt`) FlowGraphBlockNames.StopAnimation + +### Event Nodes +1. **Lifecycle Event Nodes** + - On Start (`event/onStart`) FlowGraphBlockNames.SceneReadyEvent + - On Tick (`event/onTick`) FlowGraphBlockNames.SceneTickEvent +2. **Custom Event Nodes** + - Receive (`event/receive`) FlowGraphBlockNames.ReceiveCustomEvent + - Send (`event/send`) FlowGraphBlockNames.SendCustomEvent + + */ + +const gltfTypeToBabylonType = { + float: { length: 1, flowGraphType: "number" /* FlowGraphTypes.Number */, elementType: "number" }, + bool: { length: 1, flowGraphType: "boolean" /* FlowGraphTypes.Boolean */, elementType: "boolean" }, + float2: { length: 2, flowGraphType: "Vector2" /* FlowGraphTypes.Vector2 */, elementType: "number" }, + float3: { length: 3, flowGraphType: "Vector3" /* FlowGraphTypes.Vector3 */, elementType: "number" }, + float4: { length: 4, flowGraphType: "Vector4" /* FlowGraphTypes.Vector4 */, elementType: "number" }, + float4x4: { length: 16, flowGraphType: "Matrix" /* FlowGraphTypes.Matrix */, elementType: "number" }, + float2x2: { length: 4, flowGraphType: "Matrix2D" /* FlowGraphTypes.Matrix2D */, elementType: "number" }, + float3x3: { length: 9, flowGraphType: "Matrix3D" /* FlowGraphTypes.Matrix3D */, elementType: "number" }, + int: { length: 1, flowGraphType: "FlowGraphInteger" /* FlowGraphTypes.Integer */, elementType: "number" }, +}; +class InteractivityGraphToFlowGraphParser { + constructor(_interactivityGraph, _gltf, _loader) { + this._interactivityGraph = _interactivityGraph; + this._gltf = _gltf; + this._loader = _loader; + /** + * Note - the graph should be rejected if the same type is defined twice. + * We currently don't validate that. + */ + this._types = []; + this._mappings = []; + this._staticVariables = []; + this._events = []; + this._internalEventsCounter = 0; + this._nodes = []; + // start with types + this._parseTypes(); + // continue with declarations + this._parseDeclarations(); + this._parseVariables(); + this._parseEvents(); + this._parseNodes(); + } + get arrays() { + return { + types: this._types, + mappings: this._mappings, + staticVariables: this._staticVariables, + events: this._events, + nodes: this._nodes, + }; + } + _parseTypes() { + if (!this._interactivityGraph.types) { + return; + } + for (const type of this._interactivityGraph.types) { + this._types.push(gltfTypeToBabylonType[type.signature]); + } + } + _parseDeclarations() { + if (!this._interactivityGraph.declarations) { + return; + } + for (const declaration of this._interactivityGraph.declarations) { + // make sure we have the mapping for this operation + const mapping = getMappingForDeclaration(declaration); + // mapping is defined, because we generate an empty mapping if it's not found + if (!mapping) { + Logger.Error(["No mapping found for declaration", declaration]); + throw new Error("Error parsing declarations"); + } + this._mappings.push({ + flowGraphMapping: mapping, + fullOperationName: declaration.extension ? declaration.op + ":" + declaration.extension : declaration.op, + }); + } + } + _parseVariables() { + if (!this._interactivityGraph.variables) { + return; + } + for (const variable of this._interactivityGraph.variables) { + const parsed = this._parseVariable(variable); + // set the default values here + this._staticVariables.push(parsed); + } + } + _parseVariable(variable, dataTransform) { + const type = this._types[variable.type]; + if (!type) { + Logger.Error(["No type found for variable", variable]); + throw new Error("Error parsing variables"); + } + if (variable.value) { + if (variable.value.length !== type.length) { + Logger.Error(["Invalid value length for variable", variable, type]); + throw new Error("Error parsing variables"); + } + } + const value = variable.value || []; + if (!value.length) { + switch (type.flowGraphType) { + case "boolean" /* FlowGraphTypes.Boolean */: + value.push(false); + break; + case "FlowGraphInteger" /* FlowGraphTypes.Integer */: + value.push(0); + break; + case "number" /* FlowGraphTypes.Number */: + value.push(NaN); + break; + case "Vector2" /* FlowGraphTypes.Vector2 */: + value.push(NaN, NaN); + break; + case "Vector3" /* FlowGraphTypes.Vector3 */: + value.push(NaN, NaN, NaN); + break; + case "Vector4" /* FlowGraphTypes.Vector4 */: + case "Matrix2D" /* FlowGraphTypes.Matrix2D */: + case "Quaternion" /* FlowGraphTypes.Quaternion */: + value.fill(NaN, 0, 4); + break; + case "Matrix" /* FlowGraphTypes.Matrix */: + value.fill(NaN, 0, 16); + break; + case "Matrix3D" /* FlowGraphTypes.Matrix3D */: + value.fill(NaN, 0, 9); + break; + } + } + return { type: type.flowGraphType, value: dataTransform ? dataTransform(value, this) : value }; + } + _parseEvents() { + if (!this._interactivityGraph.events) { + return; + } + for (const event of this._interactivityGraph.events) { + const converted = { + eventId: event.id || "internalEvent_" + this._internalEventsCounter++, + }; + if (event.values) { + converted.eventData = Object.keys(event.values).map((key) => { + const eventValue = event.values?.[key]; + if (!eventValue) { + Logger.Error(["No value found for event key", key]); + throw new Error("Error parsing events"); + } + const type = this._types[eventValue.type]; + if (!type) { + Logger.Error(["No type found for event value", eventValue]); + throw new Error("Error parsing events"); + } + const value = typeof eventValue.value !== "undefined" ? this._parseVariable(eventValue) : undefined; + return { + id: key, + type: type.flowGraphType, + eventData: true, + value, + }; + }); + } + this._events.push(converted); + } + } + _parseNodes() { + if (!this._interactivityGraph.nodes) { + return; + } + for (const node of this._interactivityGraph.nodes) { + // some validation + if (typeof node.declaration !== "number") { + Logger.Error(["No declaration found for node", node]); + throw new Error("Error parsing nodes"); + } + const mapping = this._mappings[node.declaration]; + if (!mapping) { + Logger.Error(["No mapping found for node", node]); + throw new Error("Error parsing nodes"); + } + if (mapping.flowGraphMapping.validation) { + if (!mapping.flowGraphMapping.validation(node, this._interactivityGraph, this._gltf)) { + throw new Error(`Error validating interactivity node ${node}`); + } + } + const blocks = []; + // create block(s) for this node using the mapping + for (const blockType of mapping.flowGraphMapping.blocks) { + const block = this._getEmptyBlock(blockType, mapping.fullOperationName); + this._parseNodeConfiguration(node, block, mapping.flowGraphMapping, blockType); + blocks.push(block); + } + this._nodes.push({ blocks, fullOperationName: mapping.fullOperationName }); + } + } + _getEmptyBlock(className, type) { + const uniqueId = RandomGUID(); + const dataInputs = []; + const dataOutputs = []; + const signalInputs = []; + const signalOutputs = []; + const config = {}; + const metadata = {}; + return { + uniqueId, + className, + dataInputs, + dataOutputs, + signalInputs, + signalOutputs, + config, + type, + metadata, + }; + } + _parseNodeConfiguration(node, block, nodeMapping, blockType) { + const configuration = block.config; + if (node.configuration) { + Object.keys(node.configuration).forEach((key) => { + const value = node.configuration?.[key]; + // value is always an array, never a number or string + if (!value) { + Logger.Error(["No value found for node configuration", key]); + throw new Error("Error parsing node configuration"); + } + const configMapping = nodeMapping.configuration?.[key]; + const belongsToBlock = configMapping && configMapping.toBlock ? configMapping.toBlock === blockType : nodeMapping.blocks.indexOf(blockType) === 0; + if (belongsToBlock) { + // get the right name for the configuration key + const configKey = configMapping?.name || key; + if ((!value || typeof value.value === "undefined") && typeof configMapping?.defaultValue !== "undefined") { + configuration[configKey] = { + value: configMapping.defaultValue, + }; + } + else if (value.value.length >= 1) { + // supporting int[] and int/boolean/string + configuration[configKey] = { + value: value.value.length === 1 ? value.value[0] : value.value, + }; + } + else { + Logger.Warn(["Invalid value for node configuration", value]); + } + // make sure we transform the data if needed + if (configMapping && configMapping.dataTransformer) { + configuration[configKey].value = configMapping.dataTransformer([configuration[configKey].value], this)[0]; + } + } + }); + } + } + _parseNodeConnections(context) { + for (let i = 0; i < this._nodes.length; i++) { + // get the corresponding gltf node + const gltfNode = this._interactivityGraph.nodes?.[i]; + if (!gltfNode) { + // should never happen but let's still check + Logger.Error(["No node found for interactivity node", this._nodes[i]]); + throw new Error("Error parsing node connections"); + } + const flowGraphBlocks = this._nodes[i]; + const outputMapper = this._mappings[gltfNode.declaration]; + // validate + if (!outputMapper) { + Logger.Error(["No mapping found for node", gltfNode]); + throw new Error("Error parsing node connections"); + } + const flowsFromGLTF = gltfNode.flows || {}; + const flowsKeys = Object.keys(flowsFromGLTF).sort(); // sorting as some operations require sorted keys + // connect the flows + for (const flowKey of flowsKeys) { + const flow = flowsFromGLTF[flowKey]; + const flowMapping = outputMapper.flowGraphMapping.outputs?.flows?.[flowKey]; + const socketOutName = flowMapping?.name || flowKey; + // create a serialized socket + const socketOut = this._createNewSocketConnection(socketOutName, true); + const block = (flowMapping && flowMapping.toBlock && flowGraphBlocks.blocks.find((b) => b.className === flowMapping.toBlock)) || flowGraphBlocks.blocks[0]; + block.signalOutputs.push(socketOut); + // get the input node of this block + const inputNodeId = flow.node; + const nodeIn = this._nodes[inputNodeId]; + if (!nodeIn) { + Logger.Error(["No node found for input node id", inputNodeId]); + throw new Error("Error parsing node connections"); + } + // get the mapper for the input node - in case it mapped to multiple blocks + const inputMapper = getMappingForFullOperationName(nodeIn.fullOperationName); + if (!inputMapper) { + Logger.Error(["No mapping found for input node", nodeIn]); + throw new Error("Error parsing node connections"); + } + let flowInMapping = inputMapper.inputs?.flows?.[flow.socket || "in"]; + let arrayMapping = false; + if (!flowInMapping) { + for (const key in inputMapper.inputs?.flows) { + if (key.startsWith("[") && key.endsWith("]")) { + arrayMapping = true; + flowInMapping = inputMapper.inputs?.flows?.[key]; + } + } + } + const nodeInSocketName = flowInMapping ? (arrayMapping ? flowInMapping.name.replace("$1", flow.socket || "") : flowInMapping.name) : flow.socket || "in"; + const inputBlock = (flowInMapping && flowInMapping.toBlock && nodeIn.blocks.find((b) => b.className === flowInMapping.toBlock)) || nodeIn.blocks[0]; + // in all of the flow graph input connections, find the one with the same name as the socket + let socketIn = inputBlock.signalInputs.find((s) => s.name === nodeInSocketName); + // if the socket doesn't exist, create the input socket for the connection + if (!socketIn) { + socketIn = this._createNewSocketConnection(nodeInSocketName); + inputBlock.signalInputs.push(socketIn); + } + // connect the sockets + socketIn.connectedPointIds.push(socketOut.uniqueId); + socketOut.connectedPointIds.push(socketIn.uniqueId); + } + // connect the values + const valuesFromGLTF = gltfNode.values || {}; + const valuesKeys = Object.keys(valuesFromGLTF); + for (const valueKey of valuesKeys) { + const value = valuesFromGLTF[valueKey]; + let valueMapping = outputMapper.flowGraphMapping.inputs?.values?.[valueKey]; + let arrayMapping = false; + if (!valueMapping) { + for (const key in outputMapper.flowGraphMapping.inputs?.values) { + if (key.startsWith("[") && key.endsWith("]")) { + arrayMapping = true; + valueMapping = outputMapper.flowGraphMapping.inputs?.values?.[key]; + } + } + } + const socketInName = valueMapping ? (arrayMapping ? valueMapping.name.replace("$1", valueKey) : valueMapping.name) : valueKey; + // create a serialized socket + const socketIn = this._createNewSocketConnection(socketInName); + const block = (valueMapping && valueMapping.toBlock && flowGraphBlocks.blocks.find((b) => b.className === valueMapping.toBlock)) || flowGraphBlocks.blocks[0]; + block.dataInputs.push(socketIn); + if (value.value !== undefined) { + const convertedValue = this._parseVariable(value, valueMapping && valueMapping.dataTransformer); + context._connectionValues[socketIn.uniqueId] = convertedValue; + } + else if (typeof value.node !== "undefined") { + const nodeOutId = value.node; + const nodeOutSocketName = value.socket || "value"; + const nodeOut = this._nodes[nodeOutId]; + if (!nodeOut) { + Logger.Error(["No node found for output socket reference", value]); + throw new Error("Error parsing node connections"); + } + const outputMapper = getMappingForFullOperationName(nodeOut.fullOperationName); + if (!outputMapper) { + Logger.Error(["No mapping found for output socket reference", value]); + throw new Error("Error parsing node connections"); + } + let valueMapping = outputMapper.outputs?.values?.[nodeOutSocketName]; + let arrayMapping = false; + // check if there is an array mapping defined + if (!valueMapping) { + // search for a value mapping that has an array mapping + for (const key in outputMapper.outputs?.values) { + if (key.startsWith("[") && key.endsWith("]")) { + arrayMapping = true; + valueMapping = outputMapper.outputs?.values?.[key]; + } + } + } + const socketOutName = valueMapping ? (arrayMapping ? valueMapping.name.replace("$1", nodeOutSocketName) : valueMapping?.name) : nodeOutSocketName; + const outBlock = (valueMapping && valueMapping.toBlock && nodeOut.blocks.find((b) => b.className === valueMapping.toBlock)) || nodeOut.blocks[0]; + let socketOut = outBlock.dataOutputs.find((s) => s.name === socketOutName); + // if the socket doesn't exist, create it + if (!socketOut) { + socketOut = this._createNewSocketConnection(socketOutName, true); + outBlock.dataOutputs.push(socketOut); + } + // connect the sockets + socketIn.connectedPointIds.push(socketOut.uniqueId); + socketOut.connectedPointIds.push(socketIn.uniqueId); + } + else { + Logger.Error(["Invalid value for value connection", value]); + throw new Error("Error parsing node connections"); + } + } + // inter block connections + if (outputMapper.flowGraphMapping.interBlockConnectors) { + for (const connector of outputMapper.flowGraphMapping.interBlockConnectors) { + const input = connector.input; + const output = connector.output; + const isVariable = connector.isVariable; + this._connectFlowGraphNodes(input, output, flowGraphBlocks.blocks[connector.inputBlockIndex], flowGraphBlocks.blocks[connector.outputBlockIndex], isVariable); + } + } + if (outputMapper.flowGraphMapping.extraProcessor) { + const declaration = this._interactivityGraph.declarations?.[gltfNode.declaration]; + if (!declaration) { + Logger.Error(["No declaration found for extra processor", gltfNode]); + throw new Error("Error parsing node connections"); + } + flowGraphBlocks.blocks = outputMapper.flowGraphMapping.extraProcessor(gltfNode, declaration, outputMapper.flowGraphMapping, this, flowGraphBlocks.blocks, context, this._gltf); + } + } + } + _createNewSocketConnection(name, isOutput) { + return { + uniqueId: RandomGUID(), + name, + _connectionType: isOutput ? 1 /* FlowGraphConnectionType.Output */ : 0 /* FlowGraphConnectionType.Input */, + connectedPointIds: [], + }; + } + _connectFlowGraphNodes(input, output, serializedInput, serializedOutput, isVariable) { + const inputArray = isVariable ? serializedInput.dataInputs : serializedInput.signalInputs; + const outputArray = isVariable ? serializedOutput.dataOutputs : serializedOutput.signalOutputs; + const inputConnection = inputArray.find((s) => s.name === input) || this._createNewSocketConnection(input); + const outputConnection = outputArray.find((s) => s.name === output) || this._createNewSocketConnection(output, true); + // of not found add it to the array + if (!inputArray.find((s) => s.name === input)) { + inputArray.push(inputConnection); + } + if (!outputArray.find((s) => s.name === output)) { + outputArray.push(outputConnection); + } + // connect the sockets + inputConnection.connectedPointIds.push(outputConnection.uniqueId); + outputConnection.connectedPointIds.push(inputConnection.uniqueId); + } + getVariableName(index) { + return "staticVariable_" + index; + } + serializeToFlowGraph() { + const context = { + uniqueId: RandomGUID(), + _userVariables: {}, + _connectionValues: {}, + }; + this._parseNodeConnections(context); + for (let i = 0; i < this._staticVariables.length; i++) { + const variable = this._staticVariables[i]; + context._userVariables[this.getVariableName(i)] = variable; + } + const allBlocks = this._nodes.reduce((acc, val) => acc.concat(val.blocks), []); + return { + rightHanded: true, + allBlocks, + executionContexts: [context], + }; + } +} + +const NAME$4 = "KHR_interactivity"; +/** + * Loader extension for KHR_interactivity + */ +class KHR_interactivity { + /** + * @internal + * @param _loader + */ + constructor(_loader) { + this._loader = _loader; + /** + * The name of this extension. + */ + this.name = NAME$4; + this.enabled = this._loader.isExtensionUsed(NAME$4); + this._pathConverter = GetPathToObjectConverter(this._loader.gltf); + // avoid starting animations automatically. + _loader._skipStartAnimationStep = true; + // Update object model with new pointers + const scene = _loader.babylonScene; + if (scene) { + _AddInteractivityObjectModel(scene); + } + } + dispose() { + this._loader = null; + delete this._pathConverter; + } + async onReady() { + if (!this._loader.babylonScene || !this._pathConverter) { + return; + } + const scene = this._loader.babylonScene; + const interactivityDefinition = this._loader.gltf.extensions?.KHR_interactivity; + if (!interactivityDefinition) { + // This can technically throw, but it's not a critical error + return; + } + const coordinator = new FlowGraphCoordinator({ scene }); + const graphs = interactivityDefinition.graphs.map((graph) => { + const parser = new InteractivityGraphToFlowGraphParser(graph, this._loader.gltf, this._loader); + return parser.serializeToFlowGraph(); + }); + // parse each graph async + await Promise.all(graphs.map((graph) => ParseFlowGraphAsync(graph, { coordinator, pathConverter: this._pathConverter }))); + coordinator.start(); + } +} +/** + * @internal + * populates the object model with the interactivity extension + */ +function _AddInteractivityObjectModel(scene) { + // Note - all of those are read-only, as per the specs! + // active camera rotation + AddObjectAccessorToKey("/extensions/KHR_interactivity/?/activeCamera/rotation", { + get: () => { + if (!scene.activeCamera) { + return new Quaternion(NaN, NaN, NaN, NaN); + } + return Quaternion.FromRotationMatrix(scene.activeCamera.getWorldMatrix()).normalize(); + }, + type: "Quaternion", + getTarget: () => scene.activeCamera, + }); + // activeCamera position + AddObjectAccessorToKey("/extensions/KHR_interactivity/?/activeCamera/position", { + get: () => { + if (!scene.activeCamera) { + return new Vector3(NaN, NaN, NaN); + } + return scene.activeCamera.position; // not global position + }, + type: "Vector3", + getTarget: () => scene.activeCamera, + }); + // /animations/{} pointers: + AddObjectAccessorToKey("/animations/{}/extensions/KHR_interactivity/isPlaying", { + get: (animation) => { + return animation._babylonAnimationGroup?.isPlaying ?? false; + }, + type: "boolean", + getTarget: (animation) => { + return animation._babylonAnimationGroup; + }, + }); + AddObjectAccessorToKey("/animations/{}/extensions/KHR_interactivity/minTime", { + get: (animation) => { + return (animation._babylonAnimationGroup?.from ?? 0) / 60; // fixed factor for duration-to-frames conversion + }, + type: "number", + getTarget: (animation) => { + return animation._babylonAnimationGroup; + }, + }); + AddObjectAccessorToKey("/animations/{}/extensions/KHR_interactivity/maxTime", { + get: (animation) => { + return (animation._babylonAnimationGroup?.to ?? 0) / 60; // fixed factor for duration-to-frames conversion + }, + type: "number", + getTarget: (animation) => { + return animation._babylonAnimationGroup; + }, + }); + // playhead + AddObjectAccessorToKey("/animations/{}/extensions/KHR_interactivity/playhead", { + get: (animation) => { + return (animation._babylonAnimationGroup?.getCurrentFrame() ?? 0) / 60; // fixed factor for duration-to-frames conversion + }, + type: "number", + getTarget: (animation) => { + return animation._babylonAnimationGroup; + }, + }); + //virtualPlayhead - TODO, do we support this property in our animations? getCurrentFrame is the only method we have for this. + AddObjectAccessorToKey("/animations/{}/extensions/KHR_interactivity/virtualPlayhead", { + get: (animation) => { + return (animation._babylonAnimationGroup?.getCurrentFrame() ?? 0) / 60; // fixed factor for duration-to-frames conversion + }, + type: "number", + getTarget: (animation) => { + return animation._babylonAnimationGroup; + }, + }); +} +// Register flow graph blocks. Do it here so they are available when the extension is enabled. +addToBlockFactory(NAME$4, "FlowGraphGLTFDataProvider", async () => { + return (await Promise.resolve().then(() => flowGraphGLTFDataProvider)).FlowGraphGLTFDataProvider; +}); +unregisterGLTFExtension(NAME$4); +registerGLTFExtension(NAME$4, true, (loader) => new KHR_interactivity(loader)); + +const NAME$3 = "KHR_node_visibility"; +// object model extension for visibility +AddObjectAccessorToKey("/nodes/{}/extensions/KHR_node_visibility/visible", { + get: (node) => { + const tn = node._babylonTransformNode; + if (tn && tn.isVisible !== undefined) { + return tn.isVisible; + } + return true; + }, + set: (value, node) => { + node._primitiveBabylonMeshes?.forEach((mesh) => { + mesh.inheritVisibility = true; + }); + if (node._babylonTransformNode) { + node._babylonTransformNode.isVisible = value; + } + node._primitiveBabylonMeshes?.forEach((mesh) => { + mesh.isVisible = value; + }); + }, + getTarget: (node) => node._babylonTransformNode, + getPropertyName: [() => "isVisible"], + type: "boolean", +}); +/** + * Loader extension for KHR_node_visibility + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_node_visibility { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$3; + this._loader = loader; + this.enabled = loader.isExtensionUsed(NAME$3); + } + async onReady() { + this._loader.gltf.nodes?.forEach((node) => { + node._primitiveBabylonMeshes?.forEach((mesh) => { + mesh.inheritVisibility = true; + }); + // When the JSON Pointer is used we need to change both the transform node and the primitive meshes to the new value. + if (node.extensions?.KHR_node_visibility) { + if (node.extensions?.KHR_node_visibility.visible === false) { + if (node._babylonTransformNode) { + node._babylonTransformNode.isVisible = false; + } + node._primitiveBabylonMeshes?.forEach((mesh) => { + mesh.isVisible = false; + }); + } + } + }); + } + dispose() { + this._loader = null; + } +} +unregisterGLTFExtension(NAME$3); +registerGLTFExtension(NAME$3, true, (loader) => new KHR_node_visibility(loader)); + +const NAME$2 = "KHR_node_selectability"; +// add the interactivity mapping for the onSelect event +addNewInteractivityFlowGraphMapping("event/onSelect", NAME$2, { + // using GetVariable as the nodeIndex is a configuration and not a value (i.e. it's not mutable) + blocks: ["FlowGraphMeshPickEventBlock" /* FlowGraphBlockNames.MeshPickEvent */, "FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */, "FlowGraphIndexOfBlock" /* FlowGraphBlockNames.IndexOf */, "KHR_interactivity/FlowGraphGLTFDataProvider"], + configuration: { + stopPropagation: { name: "stopPropagation" }, + nodeIndex: { + name: "variable", + toBlock: "FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */, + dataTransformer(data) { + return ["pickedMesh_" + data[0]]; + }, + }, + }, + outputs: { + values: { + selectedNodeIndex: { name: "index", toBlock: "FlowGraphIndexOfBlock" /* FlowGraphBlockNames.IndexOf */ }, + controllerIndex: { name: "pointerId" }, + selectionPoint: { name: "pickedPoint" }, + selectionRayOrigin: { name: "pickOrigin" }, + }, + flows: { + out: { name: "done" }, + }, + }, + interBlockConnectors: [ + { + input: "asset", + output: "value", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "array", + output: "nodes", + inputBlockIndex: 2, + outputBlockIndex: 3, + isVariable: true, + }, + { + input: "object", + output: "pickedMesh", + inputBlockIndex: 2, + outputBlockIndex: 0, + isVariable: true, + }, + ], + extraProcessor(gltfBlock, _declaration, _mapping, _arrays, serializedObjects, context, globalGLTF) { + // add the glTF to the configuration of the last serialized object + const serializedObject = serializedObjects[serializedObjects.length - 1]; + serializedObject.config = serializedObject.config || {}; + serializedObject.config.glTF = globalGLTF; + // find the listener nodeIndex value + const nodeIndex = gltfBlock.configuration?.["nodeIndex"]?.value[0]; + if (nodeIndex === undefined || typeof nodeIndex !== "number") { + throw new Error("nodeIndex not found in configuration"); + } + const variableName = "pickedMesh_" + nodeIndex; + // find the nodeIndex value + serializedObjects[1].config.variable = variableName; + context._userVariables[variableName] = { + className: "Mesh", + id: globalGLTF?.nodes?.[nodeIndex]._babylonTransformNode?.id, + uniqueId: globalGLTF?.nodes?.[nodeIndex]._babylonTransformNode?.uniqueId, + }; + return serializedObjects; + }, +}); +// object model extension for selectable +AddObjectAccessorToKey("/nodes/{}/extensions/KHR_node_selectability/selectable", { + get: (node) => { + const tn = node._babylonTransformNode; + if (tn && tn.isPickable !== undefined) { + return tn.isPickable; + } + return true; + }, + set: (value, node) => { + node._primitiveBabylonMeshes?.forEach((mesh) => { + mesh.isPickable = value; + }); + }, + getTarget: (node) => node._babylonTransformNode, + getPropertyName: [() => "isPickable"], + type: "boolean", +}); +/** + * Loader extension for KHR_selectability + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_node_selectability { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$2; + this._loader = loader; + this.enabled = loader.isExtensionUsed(NAME$2); + } + async onReady() { + this._loader.gltf.nodes?.forEach((node) => { + if (node.extensions?.KHR_node_selectability && node.extensions?.KHR_node_selectability.selectable === false) { + node._babylonTransformNode?.getChildMeshes().forEach((mesh) => { + mesh.isPickable = false; + }); + } + }); + } + dispose() { + this._loader = null; + } +} +unregisterGLTFExtension(NAME$2); +registerGLTFExtension(NAME$2, true, (loader) => new KHR_node_selectability(loader)); + +const NAME$1 = "KHR_node_hoverability"; +// interactivity +const meshPointerOverPrefix = "targetMeshPointerOver_"; +addNewInteractivityFlowGraphMapping("event/onHoverIn", NAME$1, { + // using GetVariable as the nodeIndex is a configuration and not a value (i.e. it's not mutable) + blocks: ["FlowGraphPointerOverEventBlock" /* FlowGraphBlockNames.PointerOverEvent */, "FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */, "FlowGraphIndexOfBlock" /* FlowGraphBlockNames.IndexOf */, "KHR_interactivity/FlowGraphGLTFDataProvider"], + configuration: { + stopPropagation: { name: "stopPropagation" }, + nodeIndex: { + name: "variable", + toBlock: "FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */, + dataTransformer(data) { + return [meshPointerOverPrefix + data[0]]; + }, + }, + }, + outputs: { + values: { + hoverNodeIndex: { name: "index", toBlock: "FlowGraphIndexOfBlock" /* FlowGraphBlockNames.IndexOf */ }, + controllerIndex: { name: "pointerId" }, + }, + flows: { + out: { name: "done" }, + }, + }, + interBlockConnectors: [ + { + input: "targetMesh", + output: "value", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "array", + output: "nodes", + inputBlockIndex: 2, + outputBlockIndex: 3, + isVariable: true, + }, + { + input: "object", + output: "meshUnderPointer", + inputBlockIndex: 2, + outputBlockIndex: 0, + isVariable: true, + }, + ], + extraProcessor(gltfBlock, _declaration, _mapping, _arrays, serializedObjects, context, globalGLTF) { + // add the glTF to the configuration of the last serialized object + const serializedObject = serializedObjects[serializedObjects.length - 1]; + serializedObject.config = serializedObject.config || {}; + serializedObject.config.glTF = globalGLTF; + // find the listener nodeIndex value + const nodeIndex = gltfBlock.configuration?.["nodeIndex"]?.value[0]; + if (nodeIndex === undefined || typeof nodeIndex !== "number") { + throw new Error("nodeIndex not found in configuration"); + } + const variableName = meshPointerOverPrefix + nodeIndex; + // find the nodeIndex value + serializedObjects[1].config.variable = variableName; + context._userVariables[variableName] = { + className: "Mesh", + id: globalGLTF?.nodes?.[nodeIndex]._babylonTransformNode?.id, + uniqueId: globalGLTF?.nodes?.[nodeIndex]._babylonTransformNode?.uniqueId, + }; + return serializedObjects; + }, +}); +const meshPointerOutPrefix = "targetMeshPointerOut_"; +addNewInteractivityFlowGraphMapping("event/onHoverOut", NAME$1, { + // using GetVariable as the nodeIndex is a configuration and not a value (i.e. it's not mutable) + blocks: ["FlowGraphPointerOutEventBlock" /* FlowGraphBlockNames.PointerOutEvent */, "FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */, "FlowGraphIndexOfBlock" /* FlowGraphBlockNames.IndexOf */, "KHR_interactivity/FlowGraphGLTFDataProvider"], + configuration: { + stopPropagation: { name: "stopPropagation" }, + nodeIndex: { + name: "variable", + toBlock: "FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */, + dataTransformer(data) { + return [meshPointerOutPrefix + data[0]]; + }, + }, + }, + outputs: { + values: { + hoverNodeIndex: { name: "index", toBlock: "FlowGraphIndexOfBlock" /* FlowGraphBlockNames.IndexOf */ }, + controllerIndex: { name: "pointerId" }, + }, + flows: { + out: { name: "done" }, + }, + }, + interBlockConnectors: [ + { + input: "targetMesh", + output: "value", + inputBlockIndex: 0, + outputBlockIndex: 1, + isVariable: true, + }, + { + input: "array", + output: "nodes", + inputBlockIndex: 2, + outputBlockIndex: 3, + isVariable: true, + }, + { + input: "object", + output: "meshOutOfPointer", + inputBlockIndex: 2, + outputBlockIndex: 0, + isVariable: true, + }, + ], + extraProcessor(gltfBlock, _declaration, _mapping, _arrays, serializedObjects, context, globalGLTF) { + // add the glTF to the configuration of the last serialized object + const serializedObject = serializedObjects[serializedObjects.length - 1]; + serializedObject.config = serializedObject.config || {}; + serializedObject.config.glTF = globalGLTF; + const nodeIndex = gltfBlock.configuration?.["nodeIndex"]?.value[0]; + if (nodeIndex === undefined || typeof nodeIndex !== "number") { + throw new Error("nodeIndex not found in configuration"); + } + const variableName = meshPointerOutPrefix + nodeIndex; + // find the nodeIndex value + serializedObjects[1].config.variable = variableName; + context._userVariables[variableName] = { + className: "Mesh", + id: globalGLTF?.nodes?.[nodeIndex]._babylonTransformNode?.id, + uniqueId: globalGLTF?.nodes?.[nodeIndex]._babylonTransformNode?.uniqueId, + }; + return serializedObjects; + }, +}); +AddObjectAccessorToKey("/nodes/{}/extensions/KHR_node_hoverability/hoverable", { + get: (node) => { + const tn = node._babylonTransformNode; + if (tn && tn.pointerOverDisableMeshTesting !== undefined) { + return tn.pointerOverDisableMeshTesting; + } + return true; + }, + set: (value, node) => { + node._primitiveBabylonMeshes?.forEach((mesh) => { + mesh.pointerOverDisableMeshTesting = !value; + }); + }, + getTarget: (node) => node._babylonTransformNode, + getPropertyName: [() => "pointerOverDisableMeshTesting"], + type: "boolean", +}); +/** + * Loader extension for KHR_node_hoverability + * @see https://github.com/KhronosGroup/glTF/pull/2426 + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class KHR_node_hoverability { + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME$1; + this._loader = loader; + this.enabled = loader.isExtensionUsed(NAME$1); + } + async onReady() { + this._loader.gltf.nodes?.forEach((node) => { + // default is true, so only apply if false + if (node.extensions?.KHR_node_hoverability && node.extensions?.KHR_node_hoverability.hoverable === false) { + node._babylonTransformNode?.getChildMeshes().forEach((mesh) => { + mesh.pointerOverDisableMeshTesting = true; + }); + } + }); + } + dispose() { + this._loader = null; + } +} +unregisterGLTFExtension(NAME$1); +registerGLTFExtension(NAME$1, true, (loader) => new KHR_node_hoverability(loader)); + +const NAME = "ExtrasAsMetadata"; +/** + * Store glTF extras (if present) in BJS objects' metadata + */ +class ExtrasAsMetadata { + _assignExtras(babylonObject, gltfProp) { + if (gltfProp.extras && Object.keys(gltfProp.extras).length > 0) { + const metadata = (babylonObject.metadata = babylonObject.metadata || {}); + const gltf = (metadata.gltf = metadata.gltf || {}); + gltf.extras = gltfProp.extras; + } + } + /** + * @internal + */ + constructor(loader) { + /** + * The name of this extension. + */ + this.name = NAME; + /** + * Defines whether this extension is enabled. + */ + this.enabled = true; + this._loader = loader; + } + /** @internal */ + dispose() { + this._loader = null; + } + /** + * @internal + */ + loadNodeAsync(context, node, assign) { + return this._loader.loadNodeAsync(context, node, (babylonTransformNode) => { + this._assignExtras(babylonTransformNode, node); + assign(babylonTransformNode); + }); + } + /** + * @internal + */ + loadCameraAsync(context, camera, assign) { + return this._loader.loadCameraAsync(context, camera, (babylonCamera) => { + this._assignExtras(babylonCamera, camera); + assign(babylonCamera); + }); + } + /** + * @internal + */ + createMaterial(context, material, babylonDrawMode) { + const babylonMaterial = this._loader.createMaterial(context, material, babylonDrawMode); + this._assignExtras(babylonMaterial, material); + return babylonMaterial; + } +} +unregisterGLTFExtension(NAME); +registerGLTFExtension(NAME, false, (loader) => new ExtrasAsMetadata(loader)); + +/** + * a glTF-based FlowGraph block that provides arrays with babylon object, based on the glTF tree + * Can be used, for example, to get animation index from a glTF animation + */ +class FlowGraphGLTFDataProvider extends FlowGraphBlock { + constructor(config) { + super(); + const glTF = config.glTF; + const animationGroups = glTF.animations?.map((a) => a._babylonAnimationGroup) || []; + this.animationGroups = this.registerDataOutput("animationGroups", RichTypeAny, animationGroups); + const nodes = glTF.nodes?.map((n) => n._babylonTransformNode) || []; + this.nodes = this.registerDataOutput("nodes", RichTypeAny, nodes); + } + getClassName() { + return "FlowGraphGLTFDataProvider"; + } +} + +const flowGraphGLTFDataProvider = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphGLTFDataProvider +}, Symbol.toStringTag, { value: 'Module' })); + +class Dictionary { + items = {}; + /** 检查是否存在指定键 */ + Has(key) { + return key in this.items; + } + /** 设置键值对 */ + Set(key, value) { + this.items[key] = value; + } + /** 移除指定键 */ + Remove(key) { + if (this.Has(key)) { + delete this.items[key]; + return true; + } + return false; + } + /** 获取指定键的值 */ + Get(key) { + return this.Has(key) ? this.items[key] : void 0; + } + /** 获取所有键 */ + Keys() { + return Object.keys(this.items); + } + /** 获取所有值 */ + Values() { + return Object.values(this.items); + } + /** 清空字典 */ + Clear() { + this.items = {}; + } +} + +class Emitter { + _events = {}; + on(name, callback, context) { + if (!this._events[name]) { + this._events[name] = []; + } + this._events[name].push({ callback, context }); + return this; + } + once(name, callback, context) { + const onceWrapper = (...args) => { + this.off(name, onceWrapper); + callback.apply(context, args); + }; + return this.on(name, onceWrapper, context); + } + off(name, callback) { + if (!name) { + this._events = {}; + return this; + } + if (!this._events[name]) return this; + if (!callback) { + delete this._events[name]; + return this; + } + this._events[name] = this._events[name].filter( + (listener) => listener.callback !== callback + ); + return this; + } + removeAllListeners() { + this._events = {}; + return this; + } + emit(name, ...args) { + if (!this._events[name]) return this; + this._events[name].forEach((listener) => { + listener.callback.apply(listener.context, args); + }); + return this; + } + listenerCount(name) { + return this._events[name]?.length ?? 0; + } +} +class EventBus extends Emitter { +} +const eventBus = new EventBus(); +const on = (eventName, callback, context) => { + return eventBus.on(eventName, callback, context); +}; +const off = (eventName, callback) => { + return eventBus.off(eventName, callback); +}; +const once = (eventName, callback, context) => { + return eventBus.once(eventName, callback, context); +}; +const emit = (eventName, ...args) => { + return eventBus.emit(eventName, ...args); +}; + +class EventBridge { + // Emits + static modelLoadProgress(payload) { + return emit("model:load:progress", payload); + } + static modelLoadError(payload) { + return emit("model:load:error", payload); + } + static modelLoaded(payload) { + return emit("model:loaded", payload); + } + static modelClick(payload) { + return emit("model:click", payload); + } + static sceneReady(payload) { + return emit("scene:ready", payload); + } + static allReady(payload) { + return emit("all:ready", payload); + } + static hotspotClick(payload) { + return emit("hotspot:click", payload); + } + // Listeners + static onModelLoadProgress(callback, context) { + return on("model:load:progress", callback, context); + } + static onModelLoadError(callback, context) { + return on("model:load:error", callback, context); + } + static onModelLoaded(callback, context) { + return on("model:loaded", callback, context); + } + static onModelClick(callback, context) { + return on("model:click", callback, context); + } + static onSceneReady(callback, context) { + return on("scene:ready", callback, context); + } + static onAllReady(callback, context) { + return on("all:ready", callback, context); + } + static onHotspotClick(callback, context) { + return on("hotspot:click", callback, context); + } + static onceSceneReady(callback, context) { + return once("scene:ready", callback, context); + } + static off(eventName, callback) { + return off(eventName, callback); + } +} + +class AppModel extends Monobehiver { + modelDic; + loadedMeshes; + isLoading; + constructor(mainApp) { + super(mainApp); + this.modelDic = new Dictionary(); + this.loadedMeshes = []; + this.isLoading = false; + } + initManagers() { + } + /** 加载配置中的所有模型 */ + async loadModel() { + if (!AppConfig.modelUrlList?.length || this.isLoading) return; + this.isLoading = true; + try { + await this.loadMultipleModels(AppConfig.modelUrlList); + EventBridge.modelLoaded({ urls: AppConfig.modelUrlList }); + } finally { + this.isLoading = false; + } + } + /** + * 批量加载模型(内部方法) + * @param urls 模型URL数组 + */ + async loadMultipleModels(urls) { + const total = urls.length; + EventBridge.modelLoadProgress({ loaded: 0, total, urls, progress: 0, percentage: 0 }); + for (let i = 0; i < urls.length; i++) { + const url = urls[i]; + const result = await this.loadSingleModel(url, (event) => { + this.emitProgress(i, total, url, event); + }); + this.emitProgress(i + 1, total, url, null, result.success); + if (!result.success) { + EventBridge.modelLoadError({ url, error: result.error }); + } + } + } + /** + * 发送加载进度事件 + */ + emitProgress(loaded, total, url, event, success) { + const currentProgress = event?.lengthComputable && event.total > 0 ? Math.min(1, event.loaded / event.total) : 0; + const overallProgress = Math.min(1, (loaded + (event ? currentProgress : 0)) / total); + EventBridge.modelLoadProgress({ + loaded: loaded + (event ? currentProgress : 0), + total, + url, + success, + progress: overallProgress, + percentage: Number((overallProgress * 100).toFixed(2)), + detail: event ? { + url, + lengthComputable: event.lengthComputable, + loadedBytes: event.loaded, + totalBytes: event.total + } : void 0 + }); + } + /** + * 加载单个模型文件 + * @param modelUrl 模型URL + * @param onProgress 进度回调 + */ + async loadSingleModel(modelUrl, onProgress) { + try { + const scene = this.mainApp.appScene.object; + if (!scene) return { success: false, error: "场景未初始化" }; + const result = await ImportMeshAsync(modelUrl, scene, { onProgress }); + if (!result?.meshes?.length) return { success: false, error: "未找到网格" }; + this.loadedMeshes.push(...result.meshes); + return { success: true, meshes: result.meshes, skeletons: result.skeletons }; + } catch (e) { + console.error(`模型加载失败: ${modelUrl}`, e); + return { success: false, error: e?.message }; + } + } + /** + * 克隆模型材质,避免多个模型共享同名材质 + * @param meshes 网格数组 + * @param modelName 模型名称 + */ + cloneMaterials(meshes, modelName) { + meshes.forEach((mesh) => { + if (mesh.material) { + const originalMaterial = mesh.material; + const clonedMaterial = originalMaterial.clone(`${originalMaterial.name}_${modelName}`); + mesh.material = clonedMaterial; + } + }); + } + /** 为网格设置阴影(投射和接收) */ + setupShadows(meshes) { + const appLight = this.mainApp.appLight; + if (!appLight) return; + meshes.forEach((mesh) => { + if (mesh.getTotalVertices() > 0) { + appLight.addShadowCaster(mesh); + mesh.receiveShadows = true; + } + }); + } + /** 获取缓存的网格 */ + getCachedMeshes(name) { + return this.modelDic.Get(name); + } + /** 清理所有资源 */ + clean() { + this.modelDic.Clear(); + this.loadedMeshes.forEach((m) => m?.dispose()); + this.loadedMeshes = []; + this.isLoading = false; + } + /** + * 添加模型到场景(支持单个或批量) + * @param modelName 模型名称 或 模型配置数组 + * @param modelUrl 模型URL(单个模型时使用) + */ + async add(modelName, modelUrl) { + if (Array.isArray(modelName)) { + return await this.addMultiple(modelName); + } + if (!modelUrl) { + return { success: false, error: "缺少模型URL参数" }; + } + return await this.addSingle(modelName, modelUrl); + } + /** + * 添加单个模型 + */ + async addSingle(modelName, modelUrl) { + const existingMeshes = this.modelDic.Get(modelName); + if (existingMeshes?.length && !existingMeshes[0].isDisposed()) { + console.log(`模型 ${modelName} 已存在,直接显示`); + this.showMeshes(existingMeshes); + return { success: true, meshes: existingMeshes }; + } + const result = await this.loadSingleModel(modelUrl, (event) => { + this.emitSingleProgress(modelUrl, event); + }); + if (result.success && result.meshes) { + this.modelDic.Set(modelName, result.meshes); + this.mainApp.gameManager?.updateDictionaries(); + EventBridge.modelLoaded({ urls: [modelUrl] }); + } else { + EventBridge.modelLoadError({ url: modelUrl, error: result.error }); + } + return result; + } + /** + * 批量添加模型 + */ + async addMultiple(models) { + const total = models.length; + const results = []; + EventBridge.modelLoadProgress({ loaded: 0, total, progress: 0, percentage: 0 }); + for (let i = 0; i < models.length; i++) { + const { name, url } = models[i]; + const result = await this.loadSingleModel(url, (event) => { + this.emitProgress(i, total, url, event); + }); + if (result.success && result.meshes) { + this.cloneMaterials(result.meshes, name); + this.modelDic.Set(name, result.meshes); + } + results.push(result); + this.emitProgress(i + 1, total, url, null, result.success); + } + this.mainApp.gameManager?.updateDictionaries(); + EventBridge.modelLoaded({ urls: models.map((m) => m.url) }); + return { + success: results.every((r) => r.success), + results + }; + } + /** + * 显示网格 + */ + showMeshes(meshes) { + meshes.forEach((mesh) => { + mesh.setEnabled(true); + mesh.getChildMeshes().forEach((child) => child.setEnabled(true)); + }); + } + /** + * 发送单个模型加载进度 + */ + emitSingleProgress(url, event) { + const progress = event.lengthComputable && event.total > 0 ? Math.min(1, event.loaded / event.total) : 0; + EventBridge.modelLoadProgress({ + loaded: progress, + total: 1, + url, + progress, + percentage: Number((progress * 100).toFixed(2)), + detail: { + url, + lengthComputable: event.lengthComputable, + loadedBytes: event.loaded, + totalBytes: event.total + } + }); + } + /** + * 根据 mesh 名称查找 mesh 对象 + * @param meshName mesh 名称 + * @returns mesh 对象,未找到返回 undefined + */ + findMeshByName(meshName) { + const keys = this.modelDic.Keys(); + for (const key of keys) { + const meshes = this.modelDic.Get(key); + const found = meshes?.find((m) => m.name === meshName); + if (found) return found; + } + return void 0; + } + /** + * 根据 mesh 查找所属的模型名称 + * @param mesh 网格对象 + * @returns 模型名称,未找到返回 undefined + */ + findModelNameByMesh(mesh) { + const keys = this.modelDic.Keys(); + for (const key of keys) { + const meshes = this.modelDic.Get(key); + if (meshes?.some((m) => m === mesh || m.uniqueId === mesh.uniqueId)) { + return key; + } + } + return void 0; + } + /** + * 根据 mesh 或 mesh 名称移除所属的整个模型 + * @param meshOrName 网格对象或网格名称 + * @returns 是否成功移除 + */ + remove(meshOrName) { + let mesh; + if (typeof meshOrName === "string") { + mesh = this.findMeshByName(meshOrName); + if (!mesh) { + console.warn(`未找到名为 ${meshOrName} 的网格`); + return false; + } + } else { + mesh = meshOrName; + } + const modelName = this.findModelNameByMesh(mesh); + if (modelName) { + this.removeByName(modelName); + return true; + } + console.warn("未找到该 mesh 所属的模型"); + return false; + } + /** + * 替换模型 + * @param modelName 模型名称 + * @param newModelUrl 新模型URL + */ + async replaceModel(modelName, newModelUrl) { + console.log(modelName, this.modelDic); + this.removeByName(modelName); + return await this.addSingle(modelName, newModelUrl); + } + /** + * 销毁指定模型 + * @param modelName 模型名称 + */ + removeByName(modelName) { + const meshes = this.modelDic.Get(modelName); + if (!meshes?.length) { + console.warn(`Model not found: ${modelName}`); + return; + } + meshes.forEach((mesh) => mesh.dispose()); + this.modelDic.Remove(modelName); + console.log(`Model removed: ${modelName}`); + } +} + +/** + * The action to be carried out following a trigger + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#available-actions + */ +class Action { + /** + * Creates a new Action + * @param triggerOptions the trigger, with or without parameters, for the action + * @param condition an optional determinant of action + */ + constructor( + /** the trigger, with or without parameters, for the action */ + triggerOptions, condition) { + this.triggerOptions = triggerOptions; + /** + * An event triggered prior to action being executed. + */ + this.onBeforeExecuteObservable = new Observable(); + if (triggerOptions.parameter) { + this.trigger = triggerOptions.trigger; + this._triggerParameter = triggerOptions.parameter; + } + else if (triggerOptions.trigger) { + this.trigger = triggerOptions.trigger; + } + else { + this.trigger = triggerOptions; + } + this._nextActiveAction = this; + this._condition = condition; + } + /** + * Internal only + * @internal + */ + _prepare() { } + /** + * Gets the trigger parameter + * @returns the trigger parameter + */ + getTriggerParameter() { + return this._triggerParameter; + } + /** + * Sets the trigger parameter + * @param value defines the new trigger parameter + */ + setTriggerParameter(value) { + this._triggerParameter = value; + } + /** + * Internal only - Returns if the current condition allows to run the action + * @internal + */ + _evaluateConditionForCurrentFrame() { + const condition = this._condition; + if (!condition) { + return true; + } + const currentRenderId = this._actionManager.getScene().getRenderId(); + // We cache the current evaluation for the current frame + if (condition._evaluationId !== currentRenderId) { + condition._evaluationId = currentRenderId; + condition._currentResult = condition.isValid(); + } + return condition._currentResult; + } + /** + * Internal only - executes current action event + * @internal + */ + _executeCurrent(evt) { + const isConditionValid = this._evaluateConditionForCurrentFrame(); + if (!isConditionValid) { + return; + } + this.onBeforeExecuteObservable.notifyObservers(this); + this._nextActiveAction.execute(evt); + this.skipToNextActiveAction(); + } + /** + * Execute placeholder for child classes + * @param evt optional action event + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + execute(evt) { } + /** + * Skips to next active action + */ + skipToNextActiveAction() { + if (this._nextActiveAction._child) { + if (!this._nextActiveAction._child._actionManager) { + this._nextActiveAction._child._actionManager = this._actionManager; + } + this._nextActiveAction = this._nextActiveAction._child; + } + else { + this._nextActiveAction = this; + } + } + /** + * Adds action to chain of actions, may be a DoNothingAction + * @param action defines the next action to execute + * @returns The action passed in + * @see https://www.babylonjs-playground.com/#1T30HR#0 + */ + then(action) { + this._child = action; + action._actionManager = this._actionManager; + action._prepare(); + return action; + } + /** + * Internal only + * @internal + */ + _getProperty(propertyPath) { + return this._actionManager._getProperty(propertyPath); + } + /** + * @internal + */ + _getEffectiveTarget(target, propertyPath) { + return this._actionManager._getEffectiveTarget(target, propertyPath); + } + /** + * Serialize placeholder for child classes + * @param parent of child + * @returns the serialized object + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + serialize(parent) { + return null; + } + /** + * Internal only called by serialize + * @internal + */ + _serialize(serializedAction, parent) { + const serializationObject = { + type: 1, + children: [], + name: serializedAction.name, + properties: serializedAction.properties || [], + }; + // Serialize child + if (this._child) { + this._child.serialize(serializationObject); + } + // Check if "this" has a condition + if (this._condition) { + const serializedCondition = this._condition.serialize(); + serializedCondition.children.push(serializationObject); + if (parent) { + parent.children.push(serializedCondition); + } + return serializedCondition; + } + if (parent) { + parent.children.push(serializationObject); + } + return serializationObject; + } +} +/** + * Internal only + * @internal + */ +Action._SerializeValueAsString = (value) => { + if (typeof value === "number") { + return value.toString(); + } + if (typeof value === "boolean") { + return value ? "true" : "false"; + } + if (value instanceof Vector2) { + return value.x + ", " + value.y; + } + if (value instanceof Vector3) { + return value.x + ", " + value.y + ", " + value.z; + } + if (value instanceof Color3) { + return value.r + ", " + value.g + ", " + value.b; + } + if (value instanceof Color4) { + return value.r + ", " + value.g + ", " + value.b + ", " + value.a; + } + return value; // string +}; +/** + * Internal only + * @internal + */ +Action._GetTargetProperty = (target) => { + return { + name: "target", + targetType: target._isMesh + ? "MeshProperties" + : target._isLight + ? "LightProperties" + : target._isCamera + ? "CameraProperties" + : target._isMaterial + ? "MaterialProperties" + : "SceneProperties", + value: target._isScene ? "Scene" : target.name, + }; +}; +RegisterClass("BABYLON.Action", Action); + +/** + * A Condition applied to an Action + */ +class Condition { + /** + * Creates a new Condition + * @param actionManager the manager of the action the condition is applied to + */ + constructor(actionManager) { + this._actionManager = actionManager; + } + /** + * Check if the current condition is valid + * @returns a boolean + */ + isValid() { + return true; + } + /** + * @internal + */ + _getProperty(propertyPath) { + return this._actionManager._getProperty(propertyPath); + } + /** + * @internal + */ + _getEffectiveTarget(target, propertyPath) { + return this._actionManager._getEffectiveTarget(target, propertyPath); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Serialize placeholder for child classes + * @returns the serialized object + */ + serialize() { } + /** + * @internal + */ + _serialize(serializedCondition) { + return { + type: 2, // Condition + children: [], + name: serializedCondition.name, + properties: serializedCondition.properties, + }; + } +} +/** + * Defines specific conditional operators as extensions of Condition + */ +class ValueCondition extends Condition { + /** + * returns the number for IsEqual + */ + static get IsEqual() { + return ValueCondition._IsEqual; + } + /** + * Returns the number for IsDifferent + */ + static get IsDifferent() { + return ValueCondition._IsDifferent; + } + /** + * Returns the number for IsGreater + */ + static get IsGreater() { + return ValueCondition._IsGreater; + } + /** + * Returns the number for IsLesser + */ + static get IsLesser() { + return ValueCondition._IsLesser; + } + /** + * Creates a new ValueCondition + * @param actionManager manager for the action the condition applies to + * @param target for the action + * @param propertyPath path to specify the property of the target the conditional operator uses + * @param value the value compared by the conditional operator against the current value of the property + * @param operator the conditional operator, default ValueCondition.IsEqual + */ + constructor(actionManager, target, + /** path to specify the property of the target the conditional operator uses */ + propertyPath, + /** the value compared by the conditional operator against the current value of the property */ + value, + /** [number] the conditional operator, default ValueCondition.IsEqual */ + operator = ValueCondition.IsEqual) { + super(actionManager); + this.propertyPath = propertyPath; + this.value = value; + this.operator = operator; + this._target = target; + this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath); + this._property = this._getProperty(this.propertyPath); + } + /** + * Compares the given value with the property value for the specified conditional operator + * @returns the result of the comparison + */ + isValid() { + switch (this.operator) { + case ValueCondition.IsGreater: + return this._effectiveTarget[this._property] > this.value; + case ValueCondition.IsLesser: + return this._effectiveTarget[this._property] < this.value; + case ValueCondition.IsEqual: + case ValueCondition.IsDifferent: { + let check; + if (this.value.equals) { + check = this.value.equals(this._effectiveTarget[this._property]); + } + else { + check = this.value === this._effectiveTarget[this._property]; + } + return this.operator === ValueCondition.IsEqual ? check : !check; + } + } + return false; + } + /** + * Serialize the ValueCondition into a JSON compatible object + * @returns serialization object + */ + serialize() { + return this._serialize({ + name: "ValueCondition", + properties: [ + Action._GetTargetProperty(this._target), + { name: "propertyPath", value: this.propertyPath }, + { name: "value", value: Action._SerializeValueAsString(this.value) }, + { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }, + ], + }); + } + /** + * Gets the name of the conditional operator for the ValueCondition + * @param operator the conditional operator + * @returns the name + */ + static GetOperatorName(operator) { + switch (operator) { + case ValueCondition._IsEqual: + return "IsEqual"; + case ValueCondition._IsDifferent: + return "IsDifferent"; + case ValueCondition._IsGreater: + return "IsGreater"; + case ValueCondition._IsLesser: + return "IsLesser"; + default: + return ""; + } + } +} +ValueCondition._IsEqual = 0; +ValueCondition._IsDifferent = 1; +ValueCondition._IsGreater = 2; +ValueCondition._IsLesser = 3; +/** + * Defines a predicate condition as an extension of Condition + */ +class PredicateCondition extends Condition { + /** + * Creates a new PredicateCondition + * @param actionManager manager for the action the condition applies to + * @param predicate defines the predicate function used to validate the condition + */ + constructor(actionManager, + /** defines the predicate function used to validate the condition */ + predicate) { + super(actionManager); + this.predicate = predicate; + } + /** + * @returns the validity of the predicate condition + */ + isValid() { + return this.predicate(); + } +} +/** + * Defines a state condition as an extension of Condition + */ +class StateCondition extends Condition { + /** + * Creates a new StateCondition + * @param actionManager manager for the action the condition applies to + * @param target of the condition + * @param value to compare with target state + */ + constructor(actionManager, target, + /** Value to compare with target state */ + value) { + super(actionManager); + this.value = value; + this._target = target; + } + /** + * Gets a boolean indicating if the current condition is met + * @returns the validity of the state + */ + isValid() { + return this._target.state === this.value; + } + /** + * Serialize the StateCondition into a JSON compatible object + * @returns serialization object + */ + serialize() { + return this._serialize({ + name: "StateCondition", + properties: [Action._GetTargetProperty(this._target), { name: "value", value: this.value }], + }); + } +} +RegisterClass("BABYLON.ValueCondition", ValueCondition); +RegisterClass("BABYLON.PredicateCondition", PredicateCondition); +RegisterClass("BABYLON.StateCondition", StateCondition); + +/** + * This defines an action responsible to toggle a boolean once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class SwitchBooleanAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the object containing the boolean + * @param propertyPath defines the path to the boolean property in the target object + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions, target, propertyPath, condition) { + super(triggerOptions, condition); + this.propertyPath = propertyPath; + this._target = this._effectiveTarget = target; + } + /** @internal */ + _prepare() { + this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); + this._property = this._getProperty(this.propertyPath); + } + /** + * Execute the action toggle the boolean value. + */ + execute() { + this._effectiveTarget[this._property] = !this._effectiveTarget[this._property]; + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "SwitchBooleanAction", + properties: [Action._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }], + }, parent); + } +} +/** + * This defines an action responsible to set a the state field of the target + * to a desired value once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class SetStateAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the object containing the state property + * @param value defines the value to store in the state field + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions, target, value, condition) { + super(triggerOptions, condition); + this.value = value; + this._target = target; + } + /** + * Execute the action and store the value on the target state property. + */ + execute() { + this._target.state = this.value; + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "SetStateAction", + properties: [Action._GetTargetProperty(this._target), { name: "value", value: this.value }], + }, parent); + } +} +/** + * This defines an action responsible to set a property of the target + * to a desired value once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class SetValueAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the object containing the property + * @param propertyPath defines the path of the property to set in the target + * @param value defines the value to set in the property + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions, target, propertyPath, value, condition) { + super(triggerOptions, condition); + this.propertyPath = propertyPath; + this.value = value; + this._target = this._effectiveTarget = target; + } + /** @internal */ + _prepare() { + this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); + this._property = this._getProperty(this.propertyPath); + } + /** + * Execute the action and set the targeted property to the desired value. + */ + execute() { + this._effectiveTarget[this._property] = this.value; + if (this._target.markAsDirty) { + this._target.markAsDirty(this._property); + } + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "SetValueAction", + properties: [ + Action._GetTargetProperty(this._target), + { name: "propertyPath", value: this.propertyPath }, + { name: "value", value: Action._SerializeValueAsString(this.value) }, + ], + }, parent); + } +} +/** + * This defines an action responsible to increment the target value + * to a desired value once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class IncrementValueAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the object containing the property + * @param propertyPath defines the path of the property to increment in the target + * @param value defines the value value we should increment the property by + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions, target, propertyPath, value, condition) { + super(triggerOptions, condition); + this.propertyPath = propertyPath; + this.value = value; + this._target = this._effectiveTarget = target; + } + /** @internal */ + _prepare() { + this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); + this._property = this._getProperty(this.propertyPath); + if (typeof this._effectiveTarget[this._property] !== "number") { + Logger.Warn("Warning: IncrementValueAction can only be used with number values"); + } + } + /** + * Execute the action and increment the target of the value amount. + */ + execute() { + this._effectiveTarget[this._property] += this.value; + if (this._target.markAsDirty) { + this._target.markAsDirty(this._property); + } + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "IncrementValueAction", + properties: [ + Action._GetTargetProperty(this._target), + { name: "propertyPath", value: this.propertyPath }, + { name: "value", value: Action._SerializeValueAsString(this.value) }, + ], + }, parent); + } +} +/** + * This defines an action responsible to start an animation once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class PlayAnimationAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the target animation or animation name + * @param from defines from where the animation should start (animation frame) + * @param to defines where the animation should stop (animation frame) + * @param loop defines if the animation should loop or stop after the first play + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions, target, from, to, loop, condition) { + super(triggerOptions, condition); + this.from = from; + this.to = to; + this.loop = loop; + this._target = target; + } + /** @internal */ + _prepare() { } + /** + * Execute the action and play the animation. + */ + execute() { + const scene = this._actionManager.getScene(); + scene.beginAnimation(this._target, this.from, this.to, this.loop); + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "PlayAnimationAction", + properties: [ + Action._GetTargetProperty(this._target), + { name: "from", value: String(this.from) }, + { name: "to", value: String(this.to) }, + { name: "loop", value: Action._SerializeValueAsString(this.loop) || false }, + ], + }, parent); + } +} +/** + * This defines an action responsible to stop an animation once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class StopAnimationAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the target animation or animation name + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions, target, condition) { + super(triggerOptions, condition); + this._target = target; + } + /** @internal */ + _prepare() { } + /** + * Execute the action and stop the animation. + */ + execute() { + const scene = this._actionManager.getScene(); + scene.stopAnimation(this._target); + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "StopAnimationAction", + properties: [Action._GetTargetProperty(this._target)], + }, parent); + } +} +/** + * This defines an action responsible that does nothing once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class DoNothingAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions = 0, condition) { + super(triggerOptions, condition); + } + /** + * Execute the action and do nothing. + */ + execute() { } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "DoNothingAction", + properties: [], + }, parent); + } +} +/** + * This defines an action responsible to trigger several actions once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class CombineAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param children defines the list of aggregated animations to run + * @param condition defines the trigger related conditions + * @param enableChildrenConditions defines if the children actions conditions should be check before execution + */ + constructor(triggerOptions, children, condition, enableChildrenConditions = true) { + super(triggerOptions, condition); + this.children = children; + this.enableChildrenConditions = enableChildrenConditions; + } + /** @internal */ + _prepare() { + for (let index = 0; index < this.children.length; index++) { + this.children[index]._actionManager = this._actionManager; + this.children[index]._prepare(); + } + } + /** + * Execute the action and executes all the aggregated actions. + * @param evt event to execute + */ + execute(evt) { + for (const action of this.children) { + if (!this.enableChildrenConditions || action._evaluateConditionForCurrentFrame()) { + action.execute(evt); + } + } + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + const serializationObject = super._serialize({ + name: "CombineAction", + properties: [], + combine: [], + }, parent); + for (let i = 0; i < this.children.length; i++) { + serializationObject.combine.push(this.children[i].serialize(null)); + } + return serializationObject; + } +} +/** + * This defines an action responsible to run code (external event) once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class ExecuteCodeAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param func defines the callback function to run + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions, func, condition) { + super(triggerOptions, condition); + this.func = func; + } + /** + * Execute the action and run the attached code. + * @param evt event to execute + */ + execute(evt) { + this.func(evt); + } +} +/** + * This defines an action responsible to set the parent property of the target once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class SetParentAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the target containing the parent property + * @param parent defines from where the animation should start (animation frame) + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions, target, parent, condition) { + super(triggerOptions, condition); + this._target = target; + this._parent = parent; + } + /** @internal */ + _prepare() { } + /** + * Execute the action and set the parent property. + */ + execute() { + if (this._target.parent === this._parent) { + return; + } + const invertParentWorldMatrix = this._parent.getWorldMatrix().clone(); + invertParentWorldMatrix.invert(); + this._target.position = Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix); + this._target.parent = this._parent; + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "SetParentAction", + properties: [Action._GetTargetProperty(this._target), Action._GetTargetProperty(this._parent)], + }, parent); + } +} +RegisterClass("BABYLON.SetParentAction", SetParentAction); +RegisterClass("BABYLON.ExecuteCodeAction", ExecuteCodeAction); +RegisterClass("BABYLON.DoNothingAction", DoNothingAction); +RegisterClass("BABYLON.StopAnimationAction", StopAnimationAction); +RegisterClass("BABYLON.PlayAnimationAction", PlayAnimationAction); +RegisterClass("BABYLON.IncrementValueAction", IncrementValueAction); +RegisterClass("BABYLON.SetValueAction", SetValueAction); +RegisterClass("BABYLON.SetStateAction", SetStateAction); +RegisterClass("BABYLON.SetParentAction", SetParentAction); +RegisterClass("BABYLON.SwitchBooleanAction", SwitchBooleanAction); +RegisterClass("BABYLON.CombineAction", CombineAction); + +/** + * Action Manager manages all events to be triggered on a given mesh or the global scene. + * A single scene can have many Action Managers to handle predefined actions on specific meshes. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class ActionManager extends AbstractActionManager { + /** + * Creates a new action manager + * @param scene defines the hosting scene + */ + constructor(scene) { + super(); + scene = scene || EngineStore.LastCreatedScene; + if (!scene) { + return; + } + this._scene = scene; + scene.actionManagers.push(this); + } + // Methods + /** + * Releases all associated resources + */ + dispose() { + const sceneIndex = this._scene.actionManagers.indexOf(this); + for (let i = 0; i < this.actions.length; i++) { + const action = this.actions[i]; + ActionManager.Triggers[action.trigger]--; + if (ActionManager.Triggers[action.trigger] === 0) { + delete ActionManager.Triggers[action.trigger]; + } + } + this.actions.length = 0; + if (sceneIndex > -1) { + this._scene.actionManagers.splice(sceneIndex, 1); + } + const ownerMeshes = this._scene.meshes.filter((m) => m.actionManager === this); + for (const ownerMesh of ownerMeshes) { + ownerMesh.actionManager = null; + } + } + /** + * Gets hosting scene + * @returns the hosting scene + */ + getScene() { + return this._scene; + } + /** + * Does this action manager handles actions of any of the given triggers + * @param triggers defines the triggers to be tested + * @returns a boolean indicating whether one (or more) of the triggers is handled + */ + hasSpecificTriggers(triggers) { + for (let index = 0; index < this.actions.length; index++) { + const action = this.actions[index]; + if (triggers.indexOf(action.trigger) > -1) { + return true; + } + } + return false; + } + /** + * Does this action manager handles actions of any of the given triggers. This function takes two arguments for + * speed. + * @param triggerA defines the trigger to be tested + * @param triggerB defines the trigger to be tested + * @returns a boolean indicating whether one (or more) of the triggers is handled + */ + hasSpecificTriggers2(triggerA, triggerB) { + for (let index = 0; index < this.actions.length; index++) { + const action = this.actions[index]; + if (triggerA == action.trigger || triggerB == action.trigger) { + return true; + } + } + return false; + } + /** + * Does this action manager handles actions of a given trigger + * @param trigger defines the trigger to be tested + * @param parameterPredicate defines an optional predicate to filter triggers by parameter + * @returns whether the trigger is handled + */ + hasSpecificTrigger(trigger, parameterPredicate) { + for (let index = 0; index < this.actions.length; index++) { + const action = this.actions[index]; + if (action.trigger === trigger) { + if (parameterPredicate) { + if (parameterPredicate(action.getTriggerParameter())) { + return true; + } + } + else { + return true; + } + } + } + return false; + } + /** + * Does this action manager has pointer triggers + */ + get hasPointerTriggers() { + for (let index = 0; index < this.actions.length; index++) { + const action = this.actions[index]; + if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) { + return true; + } + } + return false; + } + /** + * Does this action manager has pick triggers + */ + get hasPickTriggers() { + for (let index = 0; index < this.actions.length; index++) { + const action = this.actions[index]; + if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) { + return true; + } + } + return false; + } + /** + * Registers an action to this action manager + * @param action defines the action to be registered + * @returns the action amended (prepared) after registration + */ + registerAction(action) { + if (action.trigger === ActionManager.OnEveryFrameTrigger) { + if (this.getScene().actionManager !== this) { + Logger.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"); + return null; + } + } + this.actions.push(action); + this.getScene()._registeredActions++; + if (ActionManager.Triggers[action.trigger]) { + ActionManager.Triggers[action.trigger]++; + } + else { + ActionManager.Triggers[action.trigger] = 1; + } + action._actionManager = this; + action._prepare(); + return action; + } + /** + * Unregisters an action to this action manager + * @param action defines the action to be unregistered + * @returns a boolean indicating whether the action has been unregistered + */ + unregisterAction(action) { + const index = this.actions.indexOf(action); + if (index !== -1) { + this.actions.splice(index, 1); + ActionManager.Triggers[action.trigger] -= 1; + if (ActionManager.Triggers[action.trigger] === 0) { + delete ActionManager.Triggers[action.trigger]; + } + action._actionManager = null; + this.getScene()._registeredActions--; + return true; + } + return false; + } + /** + * Process a specific trigger + * @param trigger defines the trigger to process + * @param evt defines the event details to be processed + */ + processTrigger(trigger, evt) { + for (let index = 0; index < this.actions.length; index++) { + const action = this.actions[index]; + if (action.trigger === trigger) { + if (evt) { + if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) { + const parameter = action.getTriggerParameter(); + if (typeof parameter === "function") { + if (!parameter(evt)) { + continue; + } + } + else if (parameter && parameter !== evt.sourceEvent.keyCode) { + if (!parameter.toLowerCase) { + continue; + } + const lowerCase = parameter.toLowerCase(); + if (lowerCase !== evt.sourceEvent.key) { + const unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode; + const actualkey = String.fromCharCode(unicode).toLowerCase(); + if (actualkey !== lowerCase) { + continue; + } + } + } + } + } + action._executeCurrent(evt); + } + } + } + /** + * @internal + */ + _getEffectiveTarget(target, propertyPath) { + const properties = propertyPath.split("."); + for (let index = 0; index < properties.length - 1; index++) { + target = target[properties[index]]; + } + return target; + } + /** + * @internal + */ + _getProperty(propertyPath) { + const properties = propertyPath.split("."); + return properties[properties.length - 1]; + } + /** + * Serialize this manager to a JSON object + * @param name defines the property name to store this manager + * @returns a JSON representation of this manager + */ + serialize(name) { + const root = { + children: new Array(), + name: name, + type: 3, // Root node + properties: new Array(), // Empty for root but required + }; + for (let i = 0; i < this.actions.length; i++) { + const triggerObject = { + type: 0, // Trigger + children: new Array(), + name: ActionManager.GetTriggerName(this.actions[i].trigger), + properties: new Array(), + }; + const triggerOptions = this.actions[i].triggerOptions; + if (triggerOptions && typeof triggerOptions !== "number") { + if (triggerOptions.parameter instanceof Node) { + triggerObject.properties.push(Action._GetTargetProperty(triggerOptions.parameter)); + } + else if (typeof triggerOptions.parameter === "object") { + const parameter = {}; + DeepCopier.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]); + if (triggerOptions.parameter && triggerOptions.parameter.mesh) { + parameter._meshId = triggerOptions.parameter.mesh.id; + } + triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter }); + } + else { + triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter }); + } + } + // Serialize child action, recursively + this.actions[i].serialize(triggerObject); + // Add serialized trigger + root.children.push(triggerObject); + } + return root; + } + /** + * Creates a new ActionManager from a JSON data + * @param parsedActions defines the JSON data to read from + * @param object defines the hosting mesh + * @param scene defines the hosting scene + */ + static Parse(parsedActions, object, scene) { + const actionManager = new ActionManager(scene); + if (object === null) { + scene.actionManager = actionManager; + } + else { + object.actionManager = actionManager; + } + // instantiate a new object + const instantiate = (name, params) => { + const internalClassType = GetClass("BABYLON." + name); + return internalClassType && new internalClassType(...params); + }; + const parseParameter = (name, value, target, propertyPath) => { + if (propertyPath === null) { + // String, boolean or float + const floatValue = parseFloat(value); + if (value === "true" || value === "false") { + return value === "true"; + } + else { + return isNaN(floatValue) ? value : floatValue; + } + } + const effectiveTarget = propertyPath.split("."); + const values = value.split(","); + // Get effective Target + for (let i = 0; i < effectiveTarget.length; i++) { + target = target[effectiveTarget[i]]; + } + // Return appropriate value with its type + if (typeof target === "boolean") { + return values[0] === "true"; + } + if (typeof target === "string") { + return values[0]; + } + // Parameters with multiple values such as Vector3 etc. + const split = []; + for (let i = 0; i < values.length; i++) { + split.push(parseFloat(values[i])); + } + if (target instanceof Vector3) { + return Vector3.FromArray(split); + } + if (target instanceof Vector4) { + return Vector4.FromArray(split); + } + if (target instanceof Color3) { + return Color3.FromArray(split); + } + if (target instanceof Color4) { + return Color4.FromArray(split); + } + return parseFloat(values[0]); + }; + // traverse graph per trigger + const traverse = (parsedAction, trigger, condition, action, combineArray = null) => { + if (parsedAction.detached) { + return; + } + const parameters = []; + let target = null; + let propertyPath = null; + const combine = parsedAction.combine && parsedAction.combine.length > 0; + // Parameters + if (parsedAction.type === 2) { + parameters.push(actionManager); + } + else { + parameters.push(trigger); + } + if (combine) { + const actions = []; + for (let j = 0; j < parsedAction.combine.length; j++) { + traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions); + } + parameters.push(actions); + } + else { + for (let i = 0; i < parsedAction.properties.length; i++) { + let value = parsedAction.properties[i].value; + const name = parsedAction.properties[i].name; + const targetType = parsedAction.properties[i].targetType; + if (name === "target") { + if (targetType === "SceneProperties") { + value = target = scene; + } + else if (targetType === "MaterialProperties") { + value = target = scene.getMaterialByName(value); + } + else { + value = target = scene.getNodeByName(value); + } + } + else if (name === "parent") { + value = scene.getNodeByName(value); + } + else if (name === "sound") { + // Can not externalize to component, so only checks for the presence off the API. + if (scene.getSoundByName) { + value = scene.getSoundByName(value); + } + } + else if (name !== "propertyPath") { + if (parsedAction.type === 2 && name === "operator") { + value = ValueCondition[value]; + } + else { + value = parseParameter(name, value, target, name === "value" ? propertyPath : null); + } + } + else { + propertyPath = value; + } + parameters.push(value); + } + } + if (combineArray === null) { + parameters.push(condition); + } + else { + parameters.push(null); + } + // If interpolate value action + if (parsedAction.name === "InterpolateValueAction") { + const param = parameters[parameters.length - 2]; + parameters[parameters.length - 1] = param; + parameters[parameters.length - 2] = condition; + } + // Action or condition(s) and not CombineAction + let newAction = instantiate(parsedAction.name, parameters); + if (newAction instanceof Condition && condition !== null) { + const nothing = new DoNothingAction(trigger, condition); + if (action) { + action.then(nothing); + } + else { + actionManager.registerAction(nothing); + } + action = nothing; + } + if (combineArray === null) { + if (newAction instanceof Condition) { + condition = newAction; + newAction = action; + } + else { + condition = null; + if (action) { + action.then(newAction); + } + else { + actionManager.registerAction(newAction); + } + } + } + else { + combineArray.push(newAction); + } + for (let i = 0; i < parsedAction.children.length; i++) { + traverse(parsedAction.children[i], trigger, condition, newAction, null); + } + }; + // triggers + for (let i = 0; i < parsedActions.children.length; i++) { + let triggerParams; + const trigger = parsedActions.children[i]; + if (trigger.properties.length > 0) { + const param = trigger.properties[0].value; + const value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param); + if (value._meshId) { + value.mesh = scene.getMeshById(value._meshId); + } + triggerParams = { trigger: ActionManager[trigger.name], parameter: value }; + } + else { + triggerParams = ActionManager[trigger.name]; + } + for (let j = 0; j < trigger.children.length; j++) { + if (!trigger.detached) { + traverse(trigger.children[j], triggerParams, null, null); + } + } + } + } + /** + * Get a trigger name by index + * @param trigger defines the trigger index + * @returns a trigger name + */ + static GetTriggerName(trigger) { + switch (trigger) { + case 0: + return "NothingTrigger"; + case 1: + return "OnPickTrigger"; + case 2: + return "OnLeftPickTrigger"; + case 3: + return "OnRightPickTrigger"; + case 4: + return "OnCenterPickTrigger"; + case 5: + return "OnPickDownTrigger"; + case 6: + return "OnDoublePickTrigger"; // start; + case 7: + return "OnPickUpTrigger"; + case 8: + return "OnLongPressTrigger"; + case 9: + return "OnPointerOverTrigger"; + case 10: + return "OnPointerOutTrigger"; + case 11: + return "OnEveryFrameTrigger"; + case 12: + return "OnIntersectionEnterTrigger"; + case 13: + return "OnIntersectionExitTrigger"; + case 14: + return "OnKeyDownTrigger"; + case 15: + return "OnKeyUpTrigger"; + case 16: + return "OnPickOutTrigger"; + default: + return ""; + } + } +} +/** + * Nothing + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.NothingTrigger = 0; +/** + * On pick + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnPickTrigger = 1; +/** + * On left pick + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnLeftPickTrigger = 2; +/** + * On right pick + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnRightPickTrigger = 3; +/** + * On center pick + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnCenterPickTrigger = 4; +/** + * On pick down + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnPickDownTrigger = 5; +/** + * On double pick + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnDoublePickTrigger = 6; +/** + * On pick up + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnPickUpTrigger = 7; +/** + * On pick out. + * This trigger will only be raised if you also declared a OnPickDown + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnPickOutTrigger = 16; +/** + * On long press + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnLongPressTrigger = 8; +/** + * On pointer over + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnPointerOverTrigger = 9; +/** + * On pointer out + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnPointerOutTrigger = 10; +/** + * On every frame + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnEveryFrameTrigger = 11; +/** + * On intersection enter + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnIntersectionEnterTrigger = 12; +/** + * On intersection exit + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnIntersectionExitTrigger = 13; +/** + * On key down + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnKeyDownTrigger = 14; +/** + * On key up + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers + */ +ActionManager.OnKeyUpTrigger = 15; + +/** + * This defines an action helpful to play a defined sound on a triggered action. + */ +class PlaySoundAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param sound defines the sound to play + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions, sound, condition) { + super(triggerOptions, condition); + this._sound = sound; + } + /** @internal */ + _prepare() { } + /** + * Execute the action and play the sound. + */ + execute() { + if (this._sound !== undefined) { + this._sound.play(); + } + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "PlaySoundAction", + properties: [{ name: "sound", value: this._sound.name }], + }, parent); + } +} +/** + * This defines an action helpful to stop a defined sound on a triggered action. + */ +class StopSoundAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param sound defines the sound to stop + * @param condition defines the trigger related conditions + */ + constructor(triggerOptions, sound, condition) { + super(triggerOptions, condition); + this._sound = sound; + } + /** @internal */ + _prepare() { } + /** + * Execute the action and stop the sound. + */ + execute() { + if (this._sound !== undefined) { + this._sound.stop(); + } + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "StopSoundAction", + properties: [{ name: "sound", value: this._sound.name }], + }, parent); + } +} +RegisterClass("BABYLON.PlaySoundAction", PlaySoundAction); +RegisterClass("BABYLON.StopSoundAction", StopSoundAction); + +/** + * This defines an action responsible to change the value of a property + * by interpolating between its current value and the newly set one once triggered. + * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions + */ +class InterpolateValueAction extends Action { + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the object containing the value to interpolate + * @param propertyPath defines the path to the property in the target object + * @param value defines the target value at the end of the interpolation + * @param duration defines the time it will take for the property to interpolate to the value. + * @param condition defines the trigger related conditions + * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered + * @param onInterpolationDone defines a callback raised once the interpolation animation has been done + */ + constructor(triggerOptions, target, propertyPath, value, duration = 1000, condition, stopOtherAnimations, onInterpolationDone) { + super(triggerOptions, condition); + /** + * Defines the time it will take for the property to interpolate to the value. + */ + this.duration = 1000; + /** + * Observable triggered once the interpolation animation has been done. + */ + this.onInterpolationDoneObservable = new Observable(); + this.propertyPath = propertyPath; + this.value = value; + this.duration = duration; + this.stopOtherAnimations = stopOtherAnimations; + this.onInterpolationDone = onInterpolationDone; + this._target = this._effectiveTarget = target; + } + /** @internal */ + _prepare() { + this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); + this._property = this._getProperty(this.propertyPath); + } + /** + * Execute the action starts the value interpolation. + */ + execute() { + const scene = this._actionManager.getScene(); + const keys = [ + { + frame: 0, + value: this._effectiveTarget[this._property], + }, + { + frame: 100, + value: this.value, + }, + ]; + let dataType; + if (typeof this.value === "number") { + dataType = Animation.ANIMATIONTYPE_FLOAT; + } + else if (this.value instanceof Color3) { + dataType = Animation.ANIMATIONTYPE_COLOR3; + } + else if (this.value instanceof Vector3) { + dataType = Animation.ANIMATIONTYPE_VECTOR3; + } + else if (this.value instanceof Matrix) { + dataType = Animation.ANIMATIONTYPE_MATRIX; + } + else if (this.value instanceof Quaternion) { + dataType = Animation.ANIMATIONTYPE_QUATERNION; + } + else { + Logger.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")"); + return; + } + const animation = new Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, Animation.ANIMATIONLOOPMODE_CONSTANT); + animation.setKeys(keys); + if (this.stopOtherAnimations) { + scene.stopAnimation(this._effectiveTarget); + } + const wrapper = () => { + this.onInterpolationDoneObservable.notifyObservers(this); + if (this.onInterpolationDone) { + this.onInterpolationDone(); + } + }; + scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper); + } + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + serialize(parent) { + return super._serialize({ + name: "InterpolateValueAction", + properties: [ + Action._GetTargetProperty(this._target), + { name: "propertyPath", value: this.propertyPath }, + { name: "value", value: Action._SerializeValueAsString(this.value) }, + { name: "duration", value: Action._SerializeValueAsString(this.duration) }, + { name: "stopOtherAnimations", value: Action._SerializeValueAsString(this.stopOtherAnimations) || false }, + ], + }, parent); + } +} +RegisterClass("BABYLON.InterpolateValueAction", InterpolateValueAction); + +/** + * Defines a runtime animation + */ +class RuntimeAnimation { + /** + * Gets the current frame of the runtime animation + */ + get currentFrame() { + return this._currentFrame; + } + /** + * Gets the weight of the runtime animation + */ + get weight() { + return this._weight; + } + /** + * Gets the current value of the runtime animation + */ + get currentValue() { + return this._currentValue; + } + /** + * Gets or sets the target path of the runtime animation + */ + get targetPath() { + return this._targetPath; + } + /** + * Gets the actual target of the runtime animation + */ + get target() { + return this._currentActiveTarget; + } + /** + * Gets the additive state of the runtime animation + */ + get isAdditive() { + return this._host && this._host.isAdditive; + } + /** + * Create a new RuntimeAnimation object + * @param target defines the target of the animation + * @param animation defines the source animation object + * @param scene defines the hosting scene + * @param host defines the initiating Animatable + */ + constructor(target, animation, scene, host) { + this._events = new Array(); + /** + * The current frame of the runtime animation + */ + this._currentFrame = 0; + /** + * The original value of the runtime animation + */ + this._originalValue = new Array(); + /** + * The original blend value of the runtime animation + */ + this._originalBlendValue = null; + /** + * The offsets cache of the runtime animation + */ + this._offsetsCache = {}; + /** + * The high limits cache of the runtime animation + */ + this._highLimitsCache = {}; + /** + * Specifies if the runtime animation has been stopped + */ + this._stopped = false; + /** + * The blending factor of the runtime animation + */ + this._blendingFactor = 0; + /** + * The current value of the runtime animation + */ + this._currentValue = null; + this._currentActiveTarget = null; + this._directTarget = null; + /** + * The target path of the runtime animation + */ + this._targetPath = ""; + /** + * The weight of the runtime animation + */ + this._weight = 1.0; + /** + * The absolute frame offset of the runtime animation + */ + this._absoluteFrameOffset = 0; + /** + * The previous elapsed time (since start of animation) of the runtime animation + */ + this._previousElapsedTime = 0; + this._yoyoDirection = 1; + /** + * The previous absolute frame of the runtime animation (meaning, without taking into account the from/to values, only the elapsed time and the fps) + */ + this._previousAbsoluteFrame = 0; + this._targetIsArray = false; + this._animation = animation; + this._target = target; + this._scene = scene; + this._host = host; + this._activeTargets = []; + animation._runtimeAnimations.push(this); + // State + this._animationState = { + key: 0, + repeatCount: 0, + loopMode: this._getCorrectLoopMode(), + }; + if (this._animation.dataType === Animation.ANIMATIONTYPE_MATRIX) { + this._animationState.workValue = Matrix.Zero(); + } + // Limits + this._keys = this._animation.getKeys(); + this._minFrame = this._keys[0].frame; + this._maxFrame = this._keys[this._keys.length - 1].frame; + this._minValue = this._keys[0].value; + this._maxValue = this._keys[this._keys.length - 1].value; + // Add a start key at frame 0 if missing + if (this._minFrame !== 0) { + const newKey = { frame: 0, value: this._minValue }; + this._keys.splice(0, 0, newKey); + } + // Check data + if (this._target instanceof Array) { + let index = 0; + for (const target of this._target) { + this._preparePath(target, index); + this._getOriginalValues(index); + index++; + } + this._targetIsArray = true; + } + else { + this._preparePath(this._target); + this._getOriginalValues(); + this._targetIsArray = false; + this._directTarget = this._activeTargets[0]; + } + // Cloning events locally + const events = animation.getEvents(); + if (events && events.length > 0) { + events.forEach((e) => { + this._events.push(e._clone()); + }); + } + this._enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending; + } + _preparePath(target, targetIndex = 0) { + const targetPropertyPath = this._animation.targetPropertyPath; + if (targetPropertyPath.length > 1) { + let property = target; + for (let index = 0; index < targetPropertyPath.length - 1; index++) { + const name = targetPropertyPath[index]; + property = property[name]; + if (property === undefined) { + throw new Error(`Invalid property (${name}) in property path (${targetPropertyPath.join(".")})`); + } + } + this._targetPath = targetPropertyPath[targetPropertyPath.length - 1]; + this._activeTargets[targetIndex] = property; + } + else { + this._targetPath = targetPropertyPath[0]; + this._activeTargets[targetIndex] = target; + } + if (this._activeTargets[targetIndex][this._targetPath] === undefined) { + throw new Error(`Invalid property (${this._targetPath}) in property path (${targetPropertyPath.join(".")})`); + } + } + /** + * Gets the animation from the runtime animation + */ + get animation() { + return this._animation; + } + /** + * Resets the runtime animation to the beginning + * @param restoreOriginal defines whether to restore the target property to the original value + */ + reset(restoreOriginal = false) { + if (restoreOriginal) { + if (this._target instanceof Array) { + let index = 0; + for (const target of this._target) { + if (this._originalValue[index] !== undefined) { + this._setValue(target, this._activeTargets[index], this._originalValue[index], -1, index); + } + index++; + } + } + else { + if (this._originalValue[0] !== undefined) { + this._setValue(this._target, this._directTarget, this._originalValue[0], -1, 0); + } + } + } + this._offsetsCache = {}; + this._highLimitsCache = {}; + this._currentFrame = 0; + this._blendingFactor = 0; + // Events + for (let index = 0; index < this._events.length; index++) { + this._events[index].isDone = false; + } + } + /** + * Specifies if the runtime animation is stopped + * @returns Boolean specifying if the runtime animation is stopped + */ + isStopped() { + return this._stopped; + } + /** + * Disposes of the runtime animation + */ + dispose() { + const index = this._animation.runtimeAnimations.indexOf(this); + if (index > -1) { + this._animation.runtimeAnimations.splice(index, 1); + } + } + /** + * Apply the interpolated value to the target + * @param currentValue defines the value computed by the animation + * @param weight defines the weight to apply to this value (Defaults to 1.0) + */ + setValue(currentValue, weight) { + if (this._targetIsArray) { + for (let index = 0; index < this._target.length; index++) { + const target = this._target[index]; + this._setValue(target, this._activeTargets[index], currentValue, weight, index); + } + return; + } + this._setValue(this._target, this._directTarget, currentValue, weight, 0); + } + _getOriginalValues(targetIndex = 0) { + let originalValue; + const target = this._activeTargets[targetIndex]; + if (target.getLocalMatrix && this._targetPath === "_matrix") { + // For bones + originalValue = target.getLocalMatrix(); + } + else { + originalValue = target[this._targetPath]; + } + if (originalValue && originalValue.clone) { + this._originalValue[targetIndex] = originalValue.clone(); + } + else { + this._originalValue[targetIndex] = originalValue; + } + } + _registerTargetForLateAnimationBinding(runtimeAnimation, originalValue) { + const target = runtimeAnimation.target; + this._scene._registeredForLateAnimationBindings.pushNoDuplicate(target); + if (!target._lateAnimationHolders) { + target._lateAnimationHolders = {}; + } + if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) { + target._lateAnimationHolders[runtimeAnimation.targetPath] = { + totalWeight: 0, + totalAdditiveWeight: 0, + animations: [], + additiveAnimations: [], + originalValue: originalValue, + }; + } + if (runtimeAnimation.isAdditive) { + target._lateAnimationHolders[runtimeAnimation.targetPath].additiveAnimations.push(runtimeAnimation); + target._lateAnimationHolders[runtimeAnimation.targetPath].totalAdditiveWeight += runtimeAnimation.weight; + } + else { + target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation); + target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight; + } + } + _setValue(target, destination, currentValue, weight, targetIndex) { + // Set value + this._currentActiveTarget = destination; + this._weight = weight; + if (this._enableBlending && this._blendingFactor <= 1.0) { + if (!this._originalBlendValue) { + const originalValue = destination[this._targetPath]; + if (originalValue.clone) { + this._originalBlendValue = originalValue.clone(); + } + else { + this._originalBlendValue = originalValue; + } + } + if (this._originalBlendValue.m) { + // Matrix + if (Animation.AllowMatrixDecomposeForInterpolation) { + if (this._currentValue) { + Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); + } + else { + this._currentValue = Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor); + } + } + else { + if (this._currentValue) { + Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); + } + else { + this._currentValue = Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor); + } + } + } + else { + this._currentValue = Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor); + } + const blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed; + this._blendingFactor += blendingSpeed; + } + else { + if (!this._currentValue) { + if (currentValue?.clone) { + this._currentValue = currentValue.clone(); + } + else { + this._currentValue = currentValue; + } + } + else if (this._currentValue.copyFrom) { + this._currentValue.copyFrom(currentValue); + } + else { + this._currentValue = currentValue; + } + } + if (weight !== -1) { + this._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]); + } + else { + if (this._animationState.loopMode === Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT) { + if (this._currentValue.addToRef) { + this._currentValue.addToRef(this._originalValue[targetIndex], destination[this._targetPath]); + } + else { + destination[this._targetPath] = this._originalValue[targetIndex] + this._currentValue; + } + } + else { + destination[this._targetPath] = this._currentValue; + } + } + if (target.markAsDirty) { + target.markAsDirty(this._animation.targetProperty); + } + } + /** + * Gets the loop pmode of the runtime animation + * @returns Loop Mode + */ + _getCorrectLoopMode() { + if (this._target && this._target.animationPropertiesOverride) { + return this._target.animationPropertiesOverride.loopMode; + } + return this._animation.loopMode; + } + /** + * Move the current animation to a given frame + * @param frame defines the frame to move to + * @param weight defines the weight to apply to the animation (-1.0 by default) + */ + goToFrame(frame, weight = -1) { + const keys = this._animation.getKeys(); + if (frame < keys[0].frame) { + frame = keys[0].frame; + } + else if (frame > keys[keys.length - 1].frame) { + frame = keys[keys.length - 1].frame; + } + // Need to reset animation events + const events = this._events; + if (events.length) { + for (let index = 0; index < events.length; index++) { + if (!events[index].onlyOnce) { + // reset events in the future + events[index].isDone = events[index].frame < frame; + } + } + } + this._currentFrame = frame; + const currentValue = this._animation._interpolate(frame, this._animationState); + this.setValue(currentValue, weight); + } + /** + * @internal Internal use only + */ + _prepareForSpeedRatioChange(newSpeedRatio) { + const newAbsoluteFrame = (this._previousElapsedTime * (this._animation.framePerSecond * newSpeedRatio)) / 1000.0; + this._absoluteFrameOffset = this._previousAbsoluteFrame - newAbsoluteFrame; + } + /** + * Execute the current animation + * @param elapsedTimeSinceAnimationStart defines the elapsed time (in milliseconds) since the animation was started + * @param from defines the lower frame of the animation range + * @param to defines the upper frame of the animation range + * @param loop defines if the current animation must loop + * @param speedRatio defines the current speed ratio + * @param weight defines the weight of the animation (default is -1 so no weight) + * @returns a boolean indicating if the animation is running + */ + animate(elapsedTimeSinceAnimationStart, from, to, loop, speedRatio, weight = -1) { + const animation = this._animation; + const targetPropertyPath = animation.targetPropertyPath; + if (!targetPropertyPath || targetPropertyPath.length < 1) { + this._stopped = true; + return false; + } + let returnValue = true; + // Check limits + if (from < this._minFrame || from > this._maxFrame) { + from = this._minFrame; + } + if (to < this._minFrame || to > this._maxFrame) { + to = this._maxFrame; + } + const frameRange = to - from; + let offsetValue; + // Compute the frame according to the elapsed time and the fps of the animation ("from" and "to" are not factored in!) + let absoluteFrame = (elapsedTimeSinceAnimationStart * (animation.framePerSecond * speedRatio)) / 1000.0 + this._absoluteFrameOffset; + let highLimitValue = 0; + // Apply the yoyo function if required + let yoyoLoop = false; + const yoyoMode = loop && this._animationState.loopMode === Animation.ANIMATIONLOOPMODE_YOYO; + if (yoyoMode) { + const position = (absoluteFrame - from) / frameRange; + // Apply the yoyo curve + const sin = Math.sin(position * Math.PI); + const yoyoPosition = Math.abs(sin); + // Map the yoyo position back to the range + absoluteFrame = yoyoPosition * frameRange + from; + const direction = sin >= 0 ? 1 : -1; + if (this._yoyoDirection !== direction) { + yoyoLoop = true; + } + this._yoyoDirection = direction; + } + this._previousElapsedTime = elapsedTimeSinceAnimationStart; + this._previousAbsoluteFrame = absoluteFrame; + if (!loop && to >= from && ((absoluteFrame >= frameRange && speedRatio > 0) || (absoluteFrame <= 0 && speedRatio < 0))) { + // If we are out of range and not looping get back to caller + returnValue = false; + highLimitValue = animation._getKeyValue(this._maxValue); + } + else if (!loop && from >= to && ((absoluteFrame <= frameRange && speedRatio < 0) || (absoluteFrame >= 0 && speedRatio > 0))) { + returnValue = false; + highLimitValue = animation._getKeyValue(this._minValue); + } + else if (this._animationState.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) { + const keyOffset = to.toString() + from.toString(); + if (!this._offsetsCache[keyOffset]) { + this._animationState.repeatCount = 0; + this._animationState.loopMode = Animation.ANIMATIONLOOPMODE_CYCLE; // force a specific codepath in animation._interpolate()! + const fromValue = animation._interpolate(from, this._animationState); + const toValue = animation._interpolate(to, this._animationState); + this._animationState.loopMode = this._getCorrectLoopMode(); + switch (animation.dataType) { + // Float + case Animation.ANIMATIONTYPE_FLOAT: + this._offsetsCache[keyOffset] = toValue - fromValue; + break; + // Quaternion + case Animation.ANIMATIONTYPE_QUATERNION: + this._offsetsCache[keyOffset] = toValue.subtract(fromValue); + break; + // Vector3 + case Animation.ANIMATIONTYPE_VECTOR3: + this._offsetsCache[keyOffset] = toValue.subtract(fromValue); + break; + // Vector2 + case Animation.ANIMATIONTYPE_VECTOR2: + this._offsetsCache[keyOffset] = toValue.subtract(fromValue); + break; + // Size + case Animation.ANIMATIONTYPE_SIZE: + this._offsetsCache[keyOffset] = toValue.subtract(fromValue); + break; + // Color3 + case Animation.ANIMATIONTYPE_COLOR3: + this._offsetsCache[keyOffset] = toValue.subtract(fromValue); + break; + } + this._highLimitsCache[keyOffset] = toValue; + } + highLimitValue = this._highLimitsCache[keyOffset]; + offsetValue = this._offsetsCache[keyOffset]; + } + if (offsetValue === undefined) { + switch (animation.dataType) { + // Float + case Animation.ANIMATIONTYPE_FLOAT: + offsetValue = 0; + break; + // Quaternion + case Animation.ANIMATIONTYPE_QUATERNION: + offsetValue = _staticOffsetValueQuaternion; + break; + // Vector3 + case Animation.ANIMATIONTYPE_VECTOR3: + offsetValue = _staticOffsetValueVector3; + break; + // Vector2 + case Animation.ANIMATIONTYPE_VECTOR2: + offsetValue = _staticOffsetValueVector2; + break; + // Size + case Animation.ANIMATIONTYPE_SIZE: + offsetValue = _staticOffsetValueSize; + break; + // Color3 + case Animation.ANIMATIONTYPE_COLOR3: + offsetValue = _staticOffsetValueColor3; + break; + case Animation.ANIMATIONTYPE_COLOR4: + offsetValue = _staticOffsetValueColor4; + break; + } + } + // Compute value + let currentFrame; + if (this._host && this._host.syncRoot) { + // If we must sync with an animatable, calculate the current frame based on the frame of the root animatable + const syncRoot = this._host.syncRoot; + const hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame); + currentFrame = from + frameRange * hostNormalizedFrame; + } + else { + if ((absoluteFrame > 0 && from > to) || (absoluteFrame < 0 && from < to)) { + currentFrame = returnValue && frameRange !== 0 ? to + (absoluteFrame % frameRange) : from; + } + else { + currentFrame = returnValue && frameRange !== 0 ? from + (absoluteFrame % frameRange) : to; + } + } + const events = this._events; + // Reset event/state if looping + if ((!yoyoMode && ((speedRatio > 0 && this.currentFrame > currentFrame) || (speedRatio < 0 && this.currentFrame < currentFrame))) || (yoyoMode && yoyoLoop)) { + this._onLoop(); + // Need to reset animation events + for (let index = 0; index < events.length; index++) { + if (!events[index].onlyOnce) { + // reset event, the animation is looping + events[index].isDone = false; + } + } + this._animationState.key = speedRatio > 0 ? 0 : animation.getKeys().length - 1; + } + this._currentFrame = currentFrame; + this._animationState.repeatCount = frameRange === 0 ? 0 : (absoluteFrame / frameRange) >> 0; + this._animationState.highLimitValue = highLimitValue; + this._animationState.offsetValue = offsetValue; + const currentValue = animation._interpolate(currentFrame, this._animationState); + // Set value + this.setValue(currentValue, weight); + // Check events + if (events.length) { + for (let index = 0; index < events.length; index++) { + // Make sure current frame has passed event frame and that event frame is within the current range + // Also, handle both forward and reverse animations + if ((frameRange >= 0 && currentFrame >= events[index].frame && events[index].frame >= from) || + (frameRange < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) { + const event = events[index]; + if (!event.isDone) { + // If event should be done only once, remove it. + if (event.onlyOnce) { + events.splice(index, 1); + index--; + } + event.isDone = true; + event.action(currentFrame); + } // Don't do anything if the event has already been done. + } + } + } + if (!returnValue) { + this._stopped = true; + } + return returnValue; + } +} + +/** + * Class used to store an actual running animation + */ +class Animatable { + /** + * Gets the root Animatable used to synchronize and normalize animations + */ + get syncRoot() { + return this._syncRoot; + } + /** + * Gets the current frame of the first RuntimeAnimation + * Used to synchronize Animatables + */ + get masterFrame() { + if (this._runtimeAnimations.length === 0) { + return 0; + } + return this._runtimeAnimations[0].currentFrame; + } + /** + * Gets or sets the animatable weight (-1.0 by default meaning not weighted) + */ + get weight() { + return this._weight; + } + set weight(value) { + if (value === -1) { + // -1 is ok and means no weight + this._weight = -1; + return; + } + // Else weight must be in [0, 1] range + this._weight = Math.min(Math.max(value, 0), 1.0); + } + /** + * Gets or sets the speed ratio to apply to the animatable (1.0 by default) + */ + get speedRatio() { + return this._speedRatio; + } + set speedRatio(value) { + for (let index = 0; index < this._runtimeAnimations.length; index++) { + const animation = this._runtimeAnimations[index]; + animation._prepareForSpeedRatioChange(value); + } + this._speedRatio = value; + // Resync _manualJumpDelay in case goToFrame was called before speedRatio was set. + if (this._goToFrame !== null) { + this.goToFrame(this._goToFrame); + } + } + /** + * Gets the elapsed time since the animatable started in milliseconds + */ + get elapsedTime() { + return this._localDelayOffset === null ? 0 : this._scene._animationTime - this._localDelayOffset; + } + /** + * Creates a new Animatable + * @param scene defines the hosting scene + * @param target defines the target object + * @param fromFrame defines the starting frame number (default is 0) + * @param toFrame defines the ending frame number (default is 100) + * @param loopAnimation defines if the animation must loop (default is false) + * @param speedRatio defines the factor to apply to animation speed (default is 1) + * @param onAnimationEnd defines a callback to call when animation ends if it is not looping + * @param animations defines a group of animation to add to the new Animatable + * @param onAnimationLoop defines a callback to call when animation loops + * @param isAdditive defines whether the animation should be evaluated additively + * @param playOrder defines the order in which this animatable should be processed in the list of active animatables (default: 0) + */ + constructor(scene, + /** defines the target object */ + target, + /** [0] defines the starting frame number (default is 0) */ + fromFrame = 0, + /** [100] defines the ending frame number (default is 100) */ + toFrame = 100, + /** [false] defines if the animation must loop (default is false) */ + loopAnimation = false, speedRatio = 1.0, + /** defines a callback to call when animation ends if it is not looping */ + onAnimationEnd, animations, + /** defines a callback to call when animation loops */ + onAnimationLoop, + /** [false] defines whether the animation should be evaluated additively */ + isAdditive = false, + /** [0] defines the order in which this animatable should be processed in the list of active animatables (default: 0) */ + playOrder = 0) { + this.target = target; + this.fromFrame = fromFrame; + this.toFrame = toFrame; + this.loopAnimation = loopAnimation; + this.onAnimationEnd = onAnimationEnd; + this.onAnimationLoop = onAnimationLoop; + this.isAdditive = isAdditive; + this.playOrder = playOrder; + this._localDelayOffset = null; + this._pausedDelay = null; + this._manualJumpDelay = null; + /** @hidden */ + this._runtimeAnimations = new Array(); + this._paused = false; + this._speedRatio = 1; + this._weight = -1; + this._previousWeight = -1; + this._syncRoot = null; + this._frameToSyncFromJump = null; + this._goToFrame = null; + /** + * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation. + * This will only apply for non looping animation (default is true) + */ + this.disposeOnEnd = true; + /** + * Gets a boolean indicating if the animation has started + */ + this.animationStarted = false; + /** + * Observer raised when the animation ends + */ + this.onAnimationEndObservable = new Observable(); + /** + * Observer raised when the animation loops + */ + this.onAnimationLoopObservable = new Observable(); + this._scene = scene; + if (animations) { + this.appendAnimations(target, animations); + } + this._speedRatio = speedRatio; + scene._activeAnimatables.push(this); + } + // Methods + /** + * Synchronize and normalize current Animatable with a source Animatable + * This is useful when using animation weights and when animations are not of the same length + * @param root defines the root Animatable to synchronize with (null to stop synchronizing) + * @returns the current Animatable + */ + syncWith(root) { + this._syncRoot = root; + if (root) { + // Make sure this animatable will animate after the root + const index = this._scene._activeAnimatables.indexOf(this); + if (index > -1) { + this._scene._activeAnimatables.splice(index, 1); + this._scene._activeAnimatables.push(this); + } + } + return this; + } + /** + * Gets the list of runtime animations + * @returns an array of RuntimeAnimation + */ + getAnimations() { + return this._runtimeAnimations; + } + /** + * Adds more animations to the current animatable + * @param target defines the target of the animations + * @param animations defines the new animations to add + */ + appendAnimations(target, animations) { + for (let index = 0; index < animations.length; index++) { + const animation = animations[index]; + const newRuntimeAnimation = new RuntimeAnimation(target, animation, this._scene, this); + newRuntimeAnimation._onLoop = () => { + this.onAnimationLoopObservable.notifyObservers(this); + if (this.onAnimationLoop) { + this.onAnimationLoop(); + } + }; + this._runtimeAnimations.push(newRuntimeAnimation); + } + } + /** + * Gets the source animation for a specific property + * @param property defines the property to look for + * @returns null or the source animation for the given property + */ + getAnimationByTargetProperty(property) { + const runtimeAnimations = this._runtimeAnimations; + for (let index = 0; index < runtimeAnimations.length; index++) { + if (runtimeAnimations[index].animation.targetProperty === property) { + return runtimeAnimations[index].animation; + } + } + return null; + } + /** + * Gets the runtime animation for a specific property + * @param property defines the property to look for + * @returns null or the runtime animation for the given property + */ + getRuntimeAnimationByTargetProperty(property) { + const runtimeAnimations = this._runtimeAnimations; + for (let index = 0; index < runtimeAnimations.length; index++) { + if (runtimeAnimations[index].animation.targetProperty === property) { + return runtimeAnimations[index]; + } + } + return null; + } + /** + * Resets the animatable to its original state + */ + reset() { + const runtimeAnimations = this._runtimeAnimations; + for (let index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].reset(true); + } + this._localDelayOffset = null; + this._pausedDelay = null; + } + /** + * Allows the animatable to blend with current running animations + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending + * @param blendingSpeed defines the blending speed to use + */ + enableBlending(blendingSpeed) { + const runtimeAnimations = this._runtimeAnimations; + for (let index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].animation.enableBlending = true; + runtimeAnimations[index].animation.blendingSpeed = blendingSpeed; + } + } + /** + * Disable animation blending + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending + */ + disableBlending() { + const runtimeAnimations = this._runtimeAnimations; + for (let index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].animation.enableBlending = false; + } + } + /** + * Jump directly to a given frame + * @param frame defines the frame to jump to + * @param useWeight defines whether the animation weight should be applied to the image to be jumped to (false by default) + */ + goToFrame(frame, useWeight = false) { + const runtimeAnimations = this._runtimeAnimations; + if (runtimeAnimations[0]) { + const fps = runtimeAnimations[0].animation.framePerSecond; + this._frameToSyncFromJump = this._frameToSyncFromJump ?? runtimeAnimations[0].currentFrame; + const delay = this.speedRatio === 0 ? 0 : (((frame - this._frameToSyncFromJump) / fps) * 1000) / this.speedRatio; + this._manualJumpDelay = -delay; + } + for (let index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].goToFrame(frame, useWeight ? this._weight : -1); + } + this._goToFrame = frame; + } + /** + * Returns true if the animations for this animatable are paused + */ + get paused() { + return this._paused; + } + /** + * Pause the animation + */ + pause() { + if (this._paused) { + return; + } + this._paused = true; + } + /** + * Restart the animation + */ + restart() { + this._paused = false; + } + _raiseOnAnimationEnd() { + if (this.onAnimationEnd) { + this.onAnimationEnd(); + } + this.onAnimationEndObservable.notifyObservers(this); + } + /** + * Stop and delete the current animation + * @param animationName defines a string used to only stop some of the runtime animations instead of all + * @param targetMask a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty) + * @param useGlobalSplice if true, the animatables will be removed by the caller of this function (false by default) + * @param skipOnAnimationEnd defines if the system should not raise onAnimationEnd. Default is false + */ + stop(animationName, targetMask, useGlobalSplice = false, skipOnAnimationEnd = false) { + if (animationName || targetMask) { + const idx = this._scene._activeAnimatables.indexOf(this); + if (idx > -1) { + const runtimeAnimations = this._runtimeAnimations; + for (let index = runtimeAnimations.length - 1; index >= 0; index--) { + const runtimeAnimation = runtimeAnimations[index]; + if (animationName && runtimeAnimation.animation.name != animationName) { + continue; + } + if (targetMask && !targetMask(runtimeAnimation.target)) { + continue; + } + runtimeAnimation.dispose(); + runtimeAnimations.splice(index, 1); + } + if (runtimeAnimations.length == 0) { + if (!useGlobalSplice) { + this._scene._activeAnimatables.splice(idx, 1); + } + if (!skipOnAnimationEnd) { + this._raiseOnAnimationEnd(); + } + } + } + } + else { + const index = this._scene._activeAnimatables.indexOf(this); + if (index > -1) { + if (!useGlobalSplice) { + this._scene._activeAnimatables.splice(index, 1); + } + const runtimeAnimations = this._runtimeAnimations; + for (let index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].dispose(); + } + this._runtimeAnimations.length = 0; + if (!skipOnAnimationEnd) { + this._raiseOnAnimationEnd(); + } + } + } + } + /** + * Wait asynchronously for the animation to end + * @returns a promise which will be fulfilled when the animation ends + */ + waitAsync() { + return new Promise((resolve) => { + this.onAnimationEndObservable.add(() => { + resolve(this); + }, undefined, undefined, this, true); + }); + } + /** + * @internal + */ + _animate(delay) { + if (this._paused) { + this.animationStarted = false; + if (this._pausedDelay === null) { + this._pausedDelay = delay; + } + return true; + } + if (this._localDelayOffset === null) { + this._localDelayOffset = delay; + this._pausedDelay = null; + } + else if (this._pausedDelay !== null) { + this._localDelayOffset += delay - this._pausedDelay; + this._pausedDelay = null; + } + if (this._manualJumpDelay !== null) { + this._localDelayOffset += this._manualJumpDelay; + this._manualJumpDelay = null; + this._frameToSyncFromJump = null; + } + this._goToFrame = null; + if (this._weight === 0 && this._previousWeight === 0) { + // We consider that an animatable with a weight === 0 is "actively" paused + return true; + } + this._previousWeight = this._weight; + // Animating + let running = false; + const runtimeAnimations = this._runtimeAnimations; + let index; + for (index = 0; index < runtimeAnimations.length; index++) { + const animation = runtimeAnimations[index]; + const isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight); + running = running || isRunning; + } + this.animationStarted = running; + if (!running) { + if (this.disposeOnEnd) { + // Remove from active animatables + index = this._scene._activeAnimatables.indexOf(this); + this._scene._activeAnimatables.splice(index, 1); + // Dispose all runtime animations + for (index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].dispose(); + } + } + this._raiseOnAnimationEnd(); + if (this.disposeOnEnd) { + this.onAnimationEnd = null; + this.onAnimationLoop = null; + this.onAnimationLoopObservable.clear(); + this.onAnimationEndObservable.clear(); + } + } + return running; + } +} +/** @internal */ +function ProcessLateAnimationBindingsForMatrices(holder) { + if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) { + return holder.originalValue; + } + let normalizer = 1.0; + const finalPosition = TmpVectors.Vector3[0]; + const finalScaling = TmpVectors.Vector3[1]; + const finalQuaternion = TmpVectors.Quaternion[0]; + let startIndex = 0; + const originalAnimation = holder.animations[0]; + const originalValue = holder.originalValue; + let scale = 1; + let skipOverride = false; + if (holder.totalWeight < 1.0) { + // We need to mix the original value in + scale = 1.0 - holder.totalWeight; + originalValue.decompose(finalScaling, finalQuaternion, finalPosition); + } + else { + startIndex = 1; + // We need to normalize the weights + normalizer = holder.totalWeight; + scale = originalAnimation.weight / normalizer; + if (scale == 1) { + if (holder.totalAdditiveWeight) { + skipOverride = true; + } + else { + return originalAnimation.currentValue; + } + } + originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition); + } + // Add up the override animations + if (!skipOverride) { + finalScaling.scaleInPlace(scale); + finalPosition.scaleInPlace(scale); + finalQuaternion.scaleInPlace(scale); + for (let animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { + const runtimeAnimation = holder.animations[animIndex]; + if (runtimeAnimation.weight === 0) { + continue; + } + scale = runtimeAnimation.weight / normalizer; + const currentPosition = TmpVectors.Vector3[2]; + const currentScaling = TmpVectors.Vector3[3]; + const currentQuaternion = TmpVectors.Quaternion[1]; + runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); + currentScaling.scaleAndAddToRef(scale, finalScaling); + currentQuaternion.scaleAndAddToRef(Quaternion.Dot(finalQuaternion, currentQuaternion) > 0 ? scale : -scale, finalQuaternion); + currentPosition.scaleAndAddToRef(scale, finalPosition); + } + finalQuaternion.normalize(); + } + // Add up the additive animations + for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) { + const runtimeAnimation = holder.additiveAnimations[animIndex]; + if (runtimeAnimation.weight === 0) { + continue; + } + const currentPosition = TmpVectors.Vector3[2]; + const currentScaling = TmpVectors.Vector3[3]; + const currentQuaternion = TmpVectors.Quaternion[1]; + runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); + currentScaling.multiplyToRef(finalScaling, currentScaling); + Vector3.LerpToRef(finalScaling, currentScaling, runtimeAnimation.weight, finalScaling); + finalQuaternion.multiplyToRef(currentQuaternion, currentQuaternion); + Quaternion.SlerpToRef(finalQuaternion, currentQuaternion, runtimeAnimation.weight, finalQuaternion); + currentPosition.scaleAndAddToRef(runtimeAnimation.weight, finalPosition); + } + const workValue = originalAnimation ? originalAnimation._animationState.workValue : TmpVectors.Matrix[0].clone(); + Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, workValue); + return workValue; +} +/** @internal */ +function ProcessLateAnimationBindingsForQuaternions(holder, refQuaternion) { + if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) { + return refQuaternion; + } + const originalAnimation = holder.animations[0]; + const originalValue = holder.originalValue; + let cumulativeQuaternion = refQuaternion; + if (holder.totalWeight === 0 && holder.totalAdditiveWeight > 0) { + cumulativeQuaternion.copyFrom(originalValue); + } + else if (holder.animations.length === 1) { + Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), cumulativeQuaternion); + if (holder.totalAdditiveWeight === 0) { + return cumulativeQuaternion; + } + } + else if (holder.animations.length > 1) { + // Add up the override animations + let normalizer = 1.0; + let quaternions; + let weights; + if (holder.totalWeight < 1.0) { + const scale = 1.0 - holder.totalWeight; + quaternions = []; + weights = []; + quaternions.push(originalValue); + weights.push(scale); + } + else { + if (holder.animations.length === 2) { + // Slerp as soon as we can + Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion); + if (holder.totalAdditiveWeight === 0) { + return refQuaternion; + } + } + quaternions = []; + weights = []; + normalizer = holder.totalWeight; + } + for (let animIndex = 0; animIndex < holder.animations.length; animIndex++) { + const runtimeAnimation = holder.animations[animIndex]; + quaternions.push(runtimeAnimation.currentValue); + weights.push(runtimeAnimation.weight / normalizer); + } + // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions + let cumulativeAmount = 0; + for (let index = 0; index < quaternions.length;) { + if (!index) { + Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion); + cumulativeQuaternion = refQuaternion; + cumulativeAmount = weights[index] + weights[index + 1]; + index += 2; + continue; + } + cumulativeAmount += weights[index]; + Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion); + index++; + } + } + // Add up the additive animations + for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) { + const runtimeAnimation = holder.additiveAnimations[animIndex]; + if (runtimeAnimation.weight === 0) { + continue; + } + cumulativeQuaternion.multiplyToRef(runtimeAnimation.currentValue, TmpVectors.Quaternion[0]); + Quaternion.SlerpToRef(cumulativeQuaternion, TmpVectors.Quaternion[0], runtimeAnimation.weight, cumulativeQuaternion); + } + return cumulativeQuaternion; +} +/** @internal */ +function ProcessLateAnimationBindings(scene) { + if (!scene._registeredForLateAnimationBindings.length) { + return; + } + for (let index = 0; index < scene._registeredForLateAnimationBindings.length; index++) { + const target = scene._registeredForLateAnimationBindings.data[index]; + for (const path in target._lateAnimationHolders) { + const holder = target._lateAnimationHolders[path]; + const originalAnimation = holder.animations[0]; + const originalValue = holder.originalValue; + if (originalValue === undefined || originalValue === null) { + continue; + } + const matrixDecomposeMode = Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix + let finalValue = target[path]; + if (matrixDecomposeMode) { + finalValue = ProcessLateAnimationBindingsForMatrices(holder); + } + else { + const quaternionMode = originalValue.w !== undefined; + if (quaternionMode) { + finalValue = ProcessLateAnimationBindingsForQuaternions(holder, finalValue || Quaternion.Identity()); + } + else { + let startIndex = 0; + let normalizer = 1.0; + const originalAnimationIsLoopRelativeFromCurrent = originalAnimation && originalAnimation._animationState.loopMode === Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT; + if (holder.totalWeight < 1.0) { + // We need to mix the original value in + if (originalAnimationIsLoopRelativeFromCurrent) { + finalValue = originalValue.clone ? originalValue.clone() : originalValue; + } + else if (originalAnimation && originalValue.scale) { + finalValue = originalValue.scale(1.0 - holder.totalWeight); + } + else if (originalAnimation) { + finalValue = originalValue * (1.0 - holder.totalWeight); + } + else if (originalValue.clone) { + finalValue = originalValue.clone(); + } + else { + finalValue = originalValue; + } + } + else if (originalAnimation) { + // We need to normalize the weights + normalizer = holder.totalWeight; + const scale = originalAnimation.weight / normalizer; + if (scale !== 1) { + if (originalAnimation.currentValue.scale) { + finalValue = originalAnimation.currentValue.scale(scale); + } + else { + finalValue = originalAnimation.currentValue * scale; + } + } + else { + finalValue = originalAnimation.currentValue; + } + if (originalAnimationIsLoopRelativeFromCurrent) { + if (finalValue.addToRef) { + finalValue.addToRef(originalValue, finalValue); + } + else { + finalValue += originalValue; + } + } + startIndex = 1; + } + // Add up the override animations + for (let animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { + const runtimeAnimation = holder.animations[animIndex]; + const scale = runtimeAnimation.weight / normalizer; + if (!scale) { + continue; + } + else if (runtimeAnimation.currentValue.scaleAndAddToRef) { + runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue); + } + else { + finalValue += runtimeAnimation.currentValue * scale; + } + } + // Add up the additive animations + for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) { + const runtimeAnimation = holder.additiveAnimations[animIndex]; + const scale = runtimeAnimation.weight; + if (!scale) { + continue; + } + else if (runtimeAnimation.currentValue.scaleAndAddToRef) { + runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue); + } + else { + finalValue += runtimeAnimation.currentValue * scale; + } + } + } + } + target[path] = finalValue; + } + target._lateAnimationHolders = {}; + } + scene._registeredForLateAnimationBindings.reset(); +} +/** + * Initialize all the inter dependecies between the animations and Scene and Bone + * @param sceneClass defines the scene prototype to use + * @param boneClass defines the bone prototype to use + */ +function AddAnimationExtensions(sceneClass, boneClass) { + if (boneClass) { + boneClass.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired = false, skelDimensionsRatio = null) { + // all animation may be coming from a library skeleton, so may need to create animation + if (this.animations.length === 0) { + this.animations.push(new Animation(this.name, "_matrix", source.animations[0].framePerSecond, Animation.ANIMATIONTYPE_MATRIX, 0)); + this.animations[0].setKeys([]); + } + // get animation info / verify there is such a range from the source bone + const sourceRange = source.animations[0].getRange(rangeName); + if (!sourceRange) { + return false; + } + const from = sourceRange.from; + const to = sourceRange.to; + const sourceKeys = source.animations[0].getKeys(); + // rescaling prep + const sourceBoneLength = source.length; + const sourceParent = source.getParent(); + const parent = this.getParent(); + const parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length; + const parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1; + const dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1); + const destKeys = this.animations[0].getKeys(); + // loop vars declaration + let orig; + let origTranslation; + let mat; + for (let key = 0, nKeys = sourceKeys.length; key < nKeys; key++) { + orig = sourceKeys[key]; + if (orig.frame >= from && orig.frame <= to) { + if (rescaleAsRequired) { + mat = orig.value.clone(); + // scale based on parent ratio, when bone has parent + if (parentScalingReqd) { + origTranslation = mat.getTranslation(); + mat.setTranslation(origTranslation.scaleInPlace(parentRatio)); + // scale based on skeleton dimension ratio when root bone, and value is passed + } + else if (dimensionsScalingReqd && skelDimensionsRatio) { + origTranslation = mat.getTranslation(); + mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio)); + // use original when root bone, and no data for skelDimensionsRatio + } + else { + mat = orig.value; + } + } + else { + mat = orig.value; + } + destKeys.push({ frame: orig.frame + frameOffset, value: mat }); + } + } + this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset); + return true; + }; + } + if (!sceneClass) { + return; + } + sceneClass.prototype._animate = function (customDeltaTime) { + if (!this.animationsEnabled) { + return; + } + // Getting time + const now = PrecisionDate.Now; + if (!this._animationTimeLast) { + if (this._pendingData.length > 0) { + return; + } + this._animationTimeLast = now; + } + this.deltaTime = customDeltaTime !== undefined ? customDeltaTime : this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale; + this._animationTimeLast = now; + const animatables = this._activeAnimatables; + if (animatables.length === 0) { + return; + } + this._animationTime += this.deltaTime; + const animationTime = this._animationTime; + for (let index = 0; index < animatables.length; index++) { + const animatable = animatables[index]; + if (!animatable._animate(animationTime) && animatable.disposeOnEnd) { + index--; // Array was updated + } + } + // Late animation bindings + ProcessLateAnimationBindings(this); + }; + sceneClass.prototype.sortActiveAnimatables = function () { + this._activeAnimatables.sort((a, b) => { + return a.playOrder - b.playOrder; + }); + }; + sceneClass.prototype.beginWeightedAnimation = function (target, from, to, weight = 1.0, loop, speedRatio = 1.0, onAnimationEnd, animatable, targetMask, onAnimationLoop, isAdditive = false) { + const returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop, isAdditive); + returnedAnimatable.weight = weight; + return returnedAnimatable; + }; + sceneClass.prototype.beginAnimation = function (target, from, to, loop, speedRatio = 1.0, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) { + // get speed speedRatio, to and from, based on the sign and value(s) + if (speedRatio < 0) { + const tmp = from; + from = to; + to = tmp; + speedRatio = -speedRatio; + } + // if from > to switch speed ratio + if (from > to) { + speedRatio = -speedRatio; + } + if (stopCurrent) { + this.stopAnimation(target, undefined, targetMask); + } + if (!animatable) { + animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, undefined, onAnimationLoop, isAdditive); + } + const shouldRunTargetAnimations = targetMask ? targetMask(target) : true; + // Local animations + if (target.animations && shouldRunTargetAnimations) { + animatable.appendAnimations(target, target.animations); + } + // Children animations + if (target.getAnimatables) { + const animatables = target.getAnimatables(); + for (let index = 0; index < animatables.length; index++) { + this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop); + } + } + animatable.reset(); + return animatable; + }; + sceneClass.prototype.beginHierarchyAnimation = function (target, directDescendantsOnly, from, to, loop, speedRatio = 1.0, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) { + const children = target.getDescendants(directDescendantsOnly); + const result = []; + result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, undefined, isAdditive)); + for (const child of children) { + result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, undefined, isAdditive)); + } + return result; + }; + sceneClass.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio = 1.0, onAnimationEnd, onAnimationLoop, isAdditive = false) { + // get speed speedRatio, to and from, based on the sign and value(s) + if (speedRatio < 0) { + const tmp = from; + from = to; + to = tmp; + speedRatio = -speedRatio; + } + // if from > to switch speed ratio + if (from > to) { + speedRatio = -speedRatio; + } + const animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop, isAdditive); + return animatable; + }; + sceneClass.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive = false) { + const children = target.getDescendants(directDescendantsOnly); + const result = []; + result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive)); + for (const child of children) { + result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive)); + } + return result; + }; + sceneClass.prototype.getAnimatableByTarget = function (target) { + for (let index = 0; index < this._activeAnimatables.length; index++) { + if (this._activeAnimatables[index].target === target) { + return this._activeAnimatables[index]; + } + } + return null; + }; + sceneClass.prototype.getAllAnimatablesByTarget = function (target) { + const result = []; + for (let index = 0; index < this._activeAnimatables.length; index++) { + if (this._activeAnimatables[index].target === target) { + result.push(this._activeAnimatables[index]); + } + } + return result; + }; + sceneClass.prototype.stopAnimation = function (target, animationName, targetMask) { + const animatables = this.getAllAnimatablesByTarget(target); + for (const animatable of animatables) { + animatable.stop(animationName, targetMask); + } + }; + sceneClass.prototype.stopAllAnimations = function () { + if (this._activeAnimatables) { + for (let i = 0; i < this._activeAnimatables.length; i++) { + this._activeAnimatables[i].stop(undefined, undefined, true); + } + this._activeAnimatables.length = 0; + } + for (const group of this.animationGroups) { + group.stop(); + } + }; +} + +// Connect everything! +AddAnimationExtensions(Scene, Bone); + +/** + * This class defines the direct association between an animation and a target + */ +class TargetedAnimation { + /** + * Returns the string "TargetedAnimation" + * @returns "TargetedAnimation" + */ + getClassName() { + return "TargetedAnimation"; + } + /** + * Serialize the object + * @returns the JSON object representing the current entity + */ + serialize() { + const serializationObject = {}; + serializationObject.animation = this.animation.serialize(); + serializationObject.targetId = this.target.id; + return serializationObject; + } +} +/** + * Use this class to create coordinated animations on multiple targets + */ +class AnimationGroup { + /** + * Gets or sets the mask associated with this animation group. This mask is used to filter which objects should be animated. + */ + get mask() { + return this._mask; + } + set mask(value) { + if (this._mask === value) { + return; + } + this._mask = value; + this.syncWithMask(true); + } + /** + * Makes sure that the animations are either played or stopped according to the animation group mask. + * Note however that the call won't have any effect if the animation group has not been started yet. + * @param forceUpdate If true, forces to loop over the animatables even if no mask is defined (used internally, you shouldn't need to use it). Default: false. + */ + syncWithMask(forceUpdate = false) { + if (!this.mask && !forceUpdate) { + this._numActiveAnimatables = this._targetedAnimations.length; + return; + } + this._numActiveAnimatables = 0; + for (let i = 0; i < this._animatables.length; ++i) { + const animatable = this._animatables[i]; + if (!this.mask || this.mask.disabled || this.mask.retainsTarget(animatable.target.name)) { + this._numActiveAnimatables++; + if (animatable.paused) { + animatable.restart(); + } + } + else { + if (!animatable.paused) { + animatable.pause(); + } + } + } + } + /** + * Removes all animations for the targets not retained by the animation group mask. + * Use this function if you know you won't need those animations anymore and if you want to free memory. + */ + removeUnmaskedAnimations() { + if (!this.mask || this.mask.disabled) { + return; + } + // Removes all animatables (in case the animation group has already been started) + for (let i = 0; i < this._animatables.length; ++i) { + const animatable = this._animatables[i]; + if (!this.mask.retainsTarget(animatable.target.name)) { + animatable.stop(); + this._animatables.splice(i, 1); + --i; + } + } + // Removes the targeted animations + for (let index = 0; index < this._targetedAnimations.length; index++) { + const targetedAnimation = this._targetedAnimations[index]; + if (!this.mask.retainsTarget(targetedAnimation.target.name)) { + this._targetedAnimations.splice(index, 1); + --index; + } + } + } + /** + * Gets or sets the first frame + */ + get from() { + return this._from; + } + set from(value) { + if (this._from === value) { + return; + } + this._from = value; + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.fromFrame = this._from; + } + } + /** + * Gets or sets the last frame + */ + get to() { + return this._to; + } + set to(value) { + if (this._to === value) { + return; + } + this._to = value; + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.toFrame = this._to; + } + } + /** + * Define if the animations are started + */ + get isStarted() { + return this._isStarted; + } + /** + * Gets a value indicating that the current group is playing + */ + get isPlaying() { + return this._isStarted && !this._isPaused; + } + /** + * Gets or sets the speed ratio to use for all animations + */ + get speedRatio() { + return this._speedRatio; + } + /** + * Gets or sets the speed ratio to use for all animations + */ + set speedRatio(value) { + if (this._speedRatio === value) { + return; + } + this._speedRatio = value; + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.speedRatio = this._speedRatio; + } + } + /** + * Gets or sets if all animations should loop or not + */ + get loopAnimation() { + return this._loopAnimation; + } + set loopAnimation(value) { + if (this._loopAnimation === value) { + return; + } + this._loopAnimation = value; + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.loopAnimation = this._loopAnimation; + } + } + /** + * Gets or sets if all animations should be evaluated additively + */ + get isAdditive() { + return this._isAdditive; + } + set isAdditive(value) { + if (this._isAdditive === value) { + return; + } + this._isAdditive = value; + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.isAdditive = this._isAdditive; + } + } + /** + * Gets or sets the weight to apply to all animations of the group + */ + get weight() { + return this._weight; + } + set weight(value) { + if (this._weight === value) { + return; + } + this._weight = value; + this.setWeightForAllAnimatables(this._weight); + } + /** + * Gets the targeted animations for this animation group + */ + get targetedAnimations() { + return this._targetedAnimations; + } + /** + * returning the list of animatables controlled by this animation group. + */ + get animatables() { + return this._animatables; + } + /** + * Gets the list of target animations + */ + get children() { + return this._targetedAnimations; + } + /** + * Gets or sets the order of play of the animation group (default: 0) + */ + get playOrder() { + return this._playOrder; + } + set playOrder(value) { + if (this._playOrder === value) { + return; + } + this._playOrder = value; + if (this._animatables.length > 0) { + for (let i = 0; i < this._animatables.length; i++) { + this._animatables[i].playOrder = this._playOrder; + } + this._scene.sortActiveAnimatables(); + } + } + /** + * Allows the animations of the animation group to blend with current running animations + * Note that a null value means that each animation will use their own existing blending configuration (Animation.enableBlending) + */ + get enableBlending() { + return this._enableBlending; + } + set enableBlending(value) { + if (this._enableBlending === value) { + return; + } + this._enableBlending = value; + if (value !== null) { + for (let i = 0; i < this._targetedAnimations.length; ++i) { + this._targetedAnimations[i].animation.enableBlending = value; + } + } + } + /** + * Gets or sets the animation blending speed + * Note that a null value means that each animation will use their own existing blending configuration (Animation.blendingSpeed) + */ + get blendingSpeed() { + return this._blendingSpeed; + } + set blendingSpeed(value) { + if (this._blendingSpeed === value) { + return; + } + this._blendingSpeed = value; + if (value !== null) { + for (let i = 0; i < this._targetedAnimations.length; ++i) { + this._targetedAnimations[i].animation.blendingSpeed = value; + } + } + } + /** + * Gets the length (in seconds) of the animation group + * This function assumes that all animations are played at the same framePerSecond speed! + * Note: you can only call this method after you've added at least one targeted animation! + * @param from Starting frame range (default is AnimationGroup.from) + * @param to Ending frame range (default is AnimationGroup.to) + * @returns The length in seconds + */ + getLength(from, to) { + from = from ?? this._from; + to = to ?? this._to; + const fps = this.targetedAnimations[0].animation.framePerSecond * this._speedRatio; + return (to - from) / fps; + } + /** + * Merge the array of animation groups into a new animation group + * @param animationGroups List of animation groups to merge + * @param disposeSource If true, animation groups will be disposed after being merged (default: true) + * @param normalize If true, animation groups will be normalized before being merged, so that all animations have the same "from" and "to" frame (default: false) + * @param weight Weight for the new animation group. If not provided, it will inherit the weight from the first animation group of the array + * @returns The new animation group or null if no animation groups were passed + */ + static MergeAnimationGroups(animationGroups, disposeSource = true, normalize = false, weight) { + if (animationGroups.length === 0) { + return null; + } + weight = weight ?? animationGroups[0].weight; + let beginFrame = Number.MAX_VALUE; + let endFrame = -Number.MAX_VALUE; + if (normalize) { + for (const animationGroup of animationGroups) { + if (animationGroup.from < beginFrame) { + beginFrame = animationGroup.from; + } + if (animationGroup.to > endFrame) { + endFrame = animationGroup.to; + } + } + } + const mergedAnimationGroup = new AnimationGroup(animationGroups[0].name + "_merged", animationGroups[0]._scene, weight); + for (const animationGroup of animationGroups) { + if (normalize) { + animationGroup.normalize(beginFrame, endFrame); + } + for (const targetedAnimation of animationGroup.targetedAnimations) { + mergedAnimationGroup.addTargetedAnimation(targetedAnimation.animation, targetedAnimation.target); + } + if (disposeSource) { + animationGroup.dispose(); + } + } + return mergedAnimationGroup; + } + /** + * Instantiates a new Animation Group. + * This helps managing several animations at once. + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations + * @param name Defines the name of the group + * @param scene Defines the scene the group belongs to + * @param weight Defines the weight to use for animations in the group (-1.0 by default, meaning "no weight") + * @param playOrder Defines the order of play of the animation group (default is 0) + */ + constructor( + /** The name of the animation group */ + name, scene = null, weight = -1, playOrder = 0) { + this.name = name; + this._targetedAnimations = new Array(); + this._animatables = new Array(); + this._from = Number.MAX_VALUE; + this._to = -Number.MAX_VALUE; + this._speedRatio = 1; + this._loopAnimation = false; + this._isAdditive = false; + this._weight = -1; + this._playOrder = 0; + this._enableBlending = null; + this._blendingSpeed = null; + this._numActiveAnimatables = 0; + this._shouldStart = true; + /** @internal */ + this._parentContainer = null; + /** + * This observable will notify when one animation have ended + */ + this.onAnimationEndObservable = new Observable(); + /** + * Observer raised when one animation loops + */ + this.onAnimationLoopObservable = new Observable(); + /** + * Observer raised when all animations have looped + */ + this.onAnimationGroupLoopObservable = new Observable(); + /** + * This observable will notify when all animations have ended. + */ + this.onAnimationGroupEndObservable = new Observable(); + /** + * This observable will notify when all animations have paused. + */ + this.onAnimationGroupPauseObservable = new Observable(); + /** + * This observable will notify when all animations are playing. + */ + this.onAnimationGroupPlayObservable = new Observable(); + /** + * Gets or sets an object used to store user defined information for the node + */ + this.metadata = null; + this._mask = null; + this._animationLoopFlags = []; + this._scene = scene || EngineStore.LastCreatedScene; + this._weight = weight; + this._playOrder = playOrder; + this.uniqueId = this._scene.getUniqueId(); + this._scene.addAnimationGroup(this); + } + /** + * Add an animation (with its target) in the group + * @param animation defines the animation we want to add + * @param target defines the target of the animation + * @returns the TargetedAnimation object + */ + addTargetedAnimation(animation, target) { + const targetedAnimation = new TargetedAnimation(); + targetedAnimation.animation = animation; + targetedAnimation.target = target; + const keys = animation.getKeys(); + if (this._from > keys[0].frame) { + this._from = keys[0].frame; + } + if (this._to < keys[keys.length - 1].frame) { + this._to = keys[keys.length - 1].frame; + } + if (this._enableBlending !== null) { + animation.enableBlending = this._enableBlending; + } + if (this._blendingSpeed !== null) { + animation.blendingSpeed = this._blendingSpeed; + } + this._targetedAnimations.push(targetedAnimation); + this._shouldStart = true; + return targetedAnimation; + } + /** + * Remove an animation from the group + * @param animation defines the animation we want to remove + */ + removeTargetedAnimation(animation) { + for (let index = this._targetedAnimations.length - 1; index > -1; index--) { + const targetedAnimation = this._targetedAnimations[index]; + if (targetedAnimation.animation === animation) { + this._targetedAnimations.splice(index, 1); + } + } + } + /** + * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame + * It can add constant keys at begin or end + * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null) + * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null) + * @returns the animation group + */ + normalize(beginFrame = null, endFrame = null) { + if (beginFrame == null) { + beginFrame = this._from; + } + if (endFrame == null) { + endFrame = this._to; + } + for (let index = 0; index < this._targetedAnimations.length; index++) { + const targetedAnimation = this._targetedAnimations[index]; + const keys = targetedAnimation.animation.getKeys(); + const startKey = keys[0]; + const endKey = keys[keys.length - 1]; + if (startKey.frame > beginFrame) { + const newKey = { + frame: beginFrame, + value: startKey.value, + inTangent: startKey.inTangent, + outTangent: startKey.outTangent, + interpolation: startKey.interpolation, + }; + keys.splice(0, 0, newKey); + } + if (endKey.frame < endFrame) { + const newKey = { + frame: endFrame, + value: endKey.value, + inTangent: endKey.inTangent, + outTangent: endKey.outTangent, + interpolation: endKey.interpolation, + }; + keys.push(newKey); + } + } + this._from = beginFrame; + this._to = endFrame; + return this; + } + _processLoop(animatable, targetedAnimation, index) { + animatable.onAnimationLoop = () => { + this.onAnimationLoopObservable.notifyObservers(targetedAnimation); + if (this._animationLoopFlags[index]) { + return; + } + this._animationLoopFlags[index] = true; + this._animationLoopCount++; + if (this._animationLoopCount === this._numActiveAnimatables) { + this.onAnimationGroupLoopObservable.notifyObservers(this); + this._animationLoopCount = 0; + this._animationLoopFlags.length = 0; + } + }; + } + /** + * Start all animations on given targets + * @param loop defines if animations must loop + * @param speedRatio defines the ratio to apply to animation speed (1 by default) + * @param from defines the from key (optional) + * @param to defines the to key (optional) + * @param isAdditive defines the additive state for the resulting animatables (optional) + * @returns the current animation group + */ + start(loop = false, speedRatio = 1, from, to, isAdditive) { + if (this._isStarted || this._targetedAnimations.length === 0) { + return this; + } + this._loopAnimation = loop; + this._shouldStart = false; + this._animationLoopCount = 0; + this._animationLoopFlags.length = 0; + for (let index = 0; index < this._targetedAnimations.length; index++) { + const targetedAnimation = this._targetedAnimations[index]; + const animatable = this._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this._from, to !== undefined ? to : this._to, loop, speedRatio, undefined, undefined, isAdditive !== undefined ? isAdditive : this._isAdditive); + animatable.weight = this._weight; + animatable.playOrder = this._playOrder; + animatable.onAnimationEnd = () => { + this.onAnimationEndObservable.notifyObservers(targetedAnimation); + this._checkAnimationGroupEnded(animatable); + }; + this._processLoop(animatable, targetedAnimation, index); + this._animatables.push(animatable); + } + this.syncWithMask(); + this._scene.sortActiveAnimatables(); + this._speedRatio = speedRatio; + this._isStarted = true; + this._isPaused = false; + this.onAnimationGroupPlayObservable.notifyObservers(this); + return this; + } + /** + * Pause all animations + * @returns the animation group + */ + pause() { + if (!this._isStarted) { + return this; + } + this._isPaused = true; + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.pause(); + } + this.onAnimationGroupPauseObservable.notifyObservers(this); + return this; + } + /** + * Play all animations to initial state + * This function will start() the animations if they were not started or will restart() them if they were paused + * @param loop defines if animations must loop + * @returns the animation group + */ + play(loop) { + // only if there are animatable available + if (this.isStarted && this._animatables.length && !this._shouldStart) { + if (loop !== undefined) { + this.loopAnimation = loop; + } + this.restart(); + } + else { + this.stop(); + this.start(loop, this._speedRatio); + } + return this; + } + /** + * Reset all animations to initial state + * @returns the animation group + */ + reset() { + if (!this._isStarted) { + this.play(); + this.goToFrame(0); + this.stop(true); + return this; + } + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.reset(); + } + return this; + } + /** + * Restart animations from after pausing it + * @returns the animation group + */ + restart() { + if (!this._isStarted) { + return this; + } + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.restart(); + } + this.syncWithMask(); + this._isPaused = false; + this.onAnimationGroupPlayObservable.notifyObservers(this); + return this; + } + /** + * Stop all animations + * @param skipOnAnimationEnd defines if the system should not raise onAnimationEnd. Default is false + * @returns the animation group + */ + stop(skipOnAnimationEnd = false) { + if (!this._isStarted) { + return this; + } + const list = this._animatables.slice(); + for (let index = 0; index < list.length; index++) { + list[index].stop(undefined, undefined, true, skipOnAnimationEnd); + } + // We will take care of removing all stopped animatables + let curIndex = 0; + for (let index = 0; index < this._scene._activeAnimatables.length; index++) { + const animatable = this._scene._activeAnimatables[index]; + if (animatable._runtimeAnimations.length > 0) { + this._scene._activeAnimatables[curIndex++] = animatable; + } + else if (skipOnAnimationEnd) { + // We normally rely on the onAnimationEnd callback (assigned in the start function) to be notified when an animatable + // ends and should be removed from the active animatables array. However, if the animatable is stopped with the skipOnAnimationEnd + // flag set to true, then we need to explicitly remove it from the active animatables array. + this._checkAnimationGroupEnded(animatable, skipOnAnimationEnd); + } + } + this._scene._activeAnimatables.length = curIndex; + this._isStarted = false; + return this; + } + /** + * Set animation weight for all animatables + * + * @since 6.12.4 + * You can pass the weight to the AnimationGroup constructor, or use the weight property to set it after the group has been created, + * making it easier to define the overall animation weight than calling setWeightForAllAnimatables() after the animation group has been started + * @param weight defines the weight to use + * @returns the animationGroup + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-weights + */ + setWeightForAllAnimatables(weight) { + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.weight = weight; + } + return this; + } + /** + * Synchronize and normalize all animatables with a source animatable + * @param root defines the root animatable to synchronize with (null to stop synchronizing) + * @returns the animationGroup + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-weights + */ + syncAllAnimationsWith(root) { + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.syncWith(root); + } + return this; + } + /** + * Goes to a specific frame in this animation group. Note that the animation group must be in playing or paused status + * @param frame the frame number to go to + * @param useWeight defines whether the animation weight should be applied to the image to be jumped to (false by default) + * @returns the animationGroup + */ + goToFrame(frame, useWeight = false) { + if (!this._isStarted) { + return this; + } + for (let index = 0; index < this._animatables.length; index++) { + const animatable = this._animatables[index]; + animatable.goToFrame(frame, useWeight); + } + return this; + } + /** + * Helper to get the current frame. This will return 0 if the AnimationGroup is not running, and it might return wrong results if multiple animations are running in different frames. + * @returns current animation frame. + */ + getCurrentFrame() { + return this.animatables[0]?.masterFrame || 0; + } + /** + * Dispose all associated resources + */ + dispose() { + if (this.isStarted) { + this.stop(); + } + this._targetedAnimations.length = 0; + this._animatables.length = 0; + // Remove from scene + const index = this._scene.animationGroups.indexOf(this); + if (index > -1) { + this._scene.animationGroups.splice(index, 1); + } + if (this._parentContainer) { + const index = this._parentContainer.animationGroups.indexOf(this); + if (index > -1) { + this._parentContainer.animationGroups.splice(index, 1); + } + this._parentContainer = null; + } + this.onAnimationEndObservable.clear(); + this.onAnimationGroupEndObservable.clear(); + this.onAnimationGroupPauseObservable.clear(); + this.onAnimationGroupPlayObservable.clear(); + this.onAnimationLoopObservable.clear(); + this.onAnimationGroupLoopObservable.clear(); + } + _checkAnimationGroupEnded(animatable, skipOnAnimationEnd = false) { + // animatable should be taken out of the array + const idx = this._animatables.indexOf(animatable); + if (idx > -1) { + this._animatables.splice(idx, 1); + } + // all animatables were removed? animation group ended! + if (this._animatables.length === this._targetedAnimations.length - this._numActiveAnimatables) { + this._isStarted = false; + if (!skipOnAnimationEnd) { + this.onAnimationGroupEndObservable.notifyObservers(this); + } + this._animatables.length = 0; + } + } + /** + * Clone the current animation group and returns a copy + * @param newName defines the name of the new group + * @param targetConverter defines an optional function used to convert current animation targets to new ones + * @param cloneAnimations defines if the animations should be cloned or referenced + * @returns the new animation group + */ + clone(newName, targetConverter, cloneAnimations = false) { + const newGroup = new AnimationGroup(newName || this.name, this._scene, this._weight, this._playOrder); + newGroup._from = this.from; + newGroup._to = this.to; + newGroup._speedRatio = this.speedRatio; + newGroup._loopAnimation = this.loopAnimation; + newGroup._isAdditive = this.isAdditive; + newGroup._enableBlending = this.enableBlending; + newGroup._blendingSpeed = this.blendingSpeed; + newGroup.metadata = this.metadata; + newGroup.mask = this.mask; + for (const targetAnimation of this._targetedAnimations) { + newGroup.addTargetedAnimation(cloneAnimations ? targetAnimation.animation.clone() : targetAnimation.animation, targetConverter ? targetConverter(targetAnimation.target) : targetAnimation.target); + } + return newGroup; + } + /** + * Serializes the animationGroup to an object + * @returns Serialized object + */ + serialize() { + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.from = this.from; + serializationObject.to = this.to; + serializationObject.speedRatio = this.speedRatio; + serializationObject.loopAnimation = this.loopAnimation; + serializationObject.isAdditive = this.isAdditive; + serializationObject.weight = this.weight; + serializationObject.playOrder = this.playOrder; + serializationObject.enableBlending = this.enableBlending; + serializationObject.blendingSpeed = this.blendingSpeed; + serializationObject.targetedAnimations = []; + for (let targetedAnimationIndex = 0; targetedAnimationIndex < this.targetedAnimations.length; targetedAnimationIndex++) { + const targetedAnimation = this.targetedAnimations[targetedAnimationIndex]; + serializationObject.targetedAnimations[targetedAnimationIndex] = targetedAnimation.serialize(); + } + if (Tags && Tags.HasTags(this)) { + serializationObject.tags = Tags.GetTags(this); + } + // Metadata + if (this.metadata) { + serializationObject.metadata = this.metadata; + } + return serializationObject; + } + // Statics + /** + * Returns a new AnimationGroup object parsed from the source provided. + * @param parsedAnimationGroup defines the source + * @param scene defines the scene that will receive the animationGroup + * @returns a new AnimationGroup + */ + static Parse(parsedAnimationGroup, scene) { + const animationGroup = new AnimationGroup(parsedAnimationGroup.name, scene, parsedAnimationGroup.weight, parsedAnimationGroup.playOrder); + for (let i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) { + const targetedAnimation = parsedAnimationGroup.targetedAnimations[i]; + const animation = Animation.Parse(targetedAnimation.animation); + const id = targetedAnimation.targetId; + if (targetedAnimation.animation.property === "influence") { + // morph target animation + const morphTarget = scene.getMorphTargetById(id); + if (morphTarget) { + animationGroup.addTargetedAnimation(animation, morphTarget); + } + } + else { + const targetNode = scene.getNodeById(id); + if (targetNode != null) { + animationGroup.addTargetedAnimation(animation, targetNode); + } + } + } + if (Tags) { + Tags.AddTagsTo(animationGroup, parsedAnimationGroup.tags); + } + if (parsedAnimationGroup.from !== null && parsedAnimationGroup.to !== null) { + animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to); + } + if (parsedAnimationGroup.speedRatio !== undefined) { + animationGroup._speedRatio = parsedAnimationGroup.speedRatio; + } + if (parsedAnimationGroup.loopAnimation !== undefined) { + animationGroup._loopAnimation = parsedAnimationGroup.loopAnimation; + } + if (parsedAnimationGroup.isAdditive !== undefined) { + animationGroup._isAdditive = parsedAnimationGroup.isAdditive; + } + if (parsedAnimationGroup.weight !== undefined) { + animationGroup._weight = parsedAnimationGroup.weight; + } + if (parsedAnimationGroup.playOrder !== undefined) { + animationGroup._playOrder = parsedAnimationGroup.playOrder; + } + if (parsedAnimationGroup.enableBlending !== undefined) { + animationGroup._enableBlending = parsedAnimationGroup.enableBlending; + } + if (parsedAnimationGroup.blendingSpeed !== undefined) { + animationGroup._blendingSpeed = parsedAnimationGroup.blendingSpeed; + } + if (parsedAnimationGroup.metadata !== undefined) { + animationGroup.metadata = parsedAnimationGroup.metadata; + } + return animationGroup; + } + /** @internal */ + static MakeAnimationAdditive(sourceAnimationGroup, referenceFrameOrOptions, range, cloneOriginal = false, clonedName) { + let options; + if (typeof referenceFrameOrOptions === "object") { + options = referenceFrameOrOptions; + } + else { + options = { + referenceFrame: referenceFrameOrOptions, + range: range, + cloneOriginalAnimationGroup: cloneOriginal, + clonedAnimationName: clonedName, + }; + } + let animationGroup = sourceAnimationGroup; + if (options.cloneOriginalAnimationGroup) { + animationGroup = sourceAnimationGroup.clone(options.clonedAnimationGroupName || animationGroup.name); + } + const targetedAnimations = animationGroup.targetedAnimations; + for (let index = 0; index < targetedAnimations.length; index++) { + const targetedAnimation = targetedAnimations[index]; + targetedAnimation.animation = Animation.MakeAnimationAdditive(targetedAnimation.animation, options); + } + animationGroup.isAdditive = true; + if (options.clipKeys) { + // We need to recalculate the from/to frames for the animation group because some keys may have been removed + let from = Number.MAX_VALUE; + let to = -Number.MAX_VALUE; + const targetedAnimations = animationGroup.targetedAnimations; + for (let index = 0; index < targetedAnimations.length; index++) { + const targetedAnimation = targetedAnimations[index]; + const animation = targetedAnimation.animation; + const keys = animation.getKeys(); + if (from > keys[0].frame) { + from = keys[0].frame; + } + if (to < keys[keys.length - 1].frame) { + to = keys[keys.length - 1].frame; + } + } + animationGroup._from = from; + animationGroup._to = to; + } + return animationGroup; + } + /** + * Creates a new animation, keeping only the keys that are inside a given key range + * @param sourceAnimationGroup defines the animation group on which to operate + * @param fromKey defines the lower bound of the range + * @param toKey defines the upper bound of the range + * @param name defines the name of the new animation group. If not provided, use the same name as animationGroup + * @param dontCloneAnimations defines whether or not the animations should be cloned before clipping the keys. Default is false, so animations will be cloned + * @returns a new animation group stripped from all the keys outside the given range + */ + static ClipKeys(sourceAnimationGroup, fromKey, toKey, name, dontCloneAnimations) { + const animationGroup = sourceAnimationGroup.clone(name || sourceAnimationGroup.name); + return AnimationGroup.ClipKeysInPlace(animationGroup, fromKey, toKey, dontCloneAnimations); + } + /** + * Updates an existing animation, keeping only the keys that are inside a given key range + * @param animationGroup defines the animation group on which to operate + * @param fromKey defines the lower bound of the range + * @param toKey defines the upper bound of the range + * @param dontCloneAnimations defines whether or not the animations should be cloned before clipping the keys. Default is false, so animations will be cloned + * @returns the animationGroup stripped from all the keys outside the given range + */ + static ClipKeysInPlace(animationGroup, fromKey, toKey, dontCloneAnimations) { + return AnimationGroup.ClipInPlace(animationGroup, fromKey, toKey, dontCloneAnimations, false); + } + /** + * Creates a new animation, keeping only the frames that are inside a given frame range + * @param sourceAnimationGroup defines the animation group on which to operate + * @param fromFrame defines the lower bound of the range + * @param toFrame defines the upper bound of the range + * @param name defines the name of the new animation group. If not provided, use the same name as animationGroup + * @param dontCloneAnimations defines whether or not the animations should be cloned before clipping the frames. Default is false, so animations will be cloned + * @returns a new animation group stripped from all the frames outside the given range + */ + static ClipFrames(sourceAnimationGroup, fromFrame, toFrame, name, dontCloneAnimations) { + const animationGroup = sourceAnimationGroup.clone(name || sourceAnimationGroup.name); + return AnimationGroup.ClipFramesInPlace(animationGroup, fromFrame, toFrame, dontCloneAnimations); + } + /** + * Updates an existing animation, keeping only the frames that are inside a given frame range + * @param animationGroup defines the animation group on which to operate + * @param fromFrame defines the lower bound of the range + * @param toFrame defines the upper bound of the range + * @param dontCloneAnimations defines whether or not the animations should be cloned before clipping the frames. Default is false, so animations will be cloned + * @returns the animationGroup stripped from all the frames outside the given range + */ + static ClipFramesInPlace(animationGroup, fromFrame, toFrame, dontCloneAnimations) { + return AnimationGroup.ClipInPlace(animationGroup, fromFrame, toFrame, dontCloneAnimations, true); + } + /** + * Updates an existing animation, keeping only the keys that are inside a given key or frame range + * @param animationGroup defines the animation group on which to operate + * @param start defines the lower bound of the range + * @param end defines the upper bound of the range + * @param dontCloneAnimations defines whether or not the animations should be cloned before clipping the keys. Default is false, so animations will be cloned + * @param useFrame defines if the range is defined by frame numbers or key indices (default is false which means use key indices) + * @returns the animationGroup stripped from all the keys outside the given range + */ + static ClipInPlace(animationGroup, start, end, dontCloneAnimations, useFrame = false) { + let from = Number.MAX_VALUE; + let to = -Number.MAX_VALUE; + const targetedAnimations = animationGroup.targetedAnimations; + for (let index = 0; index < targetedAnimations.length; index++) { + const targetedAnimation = targetedAnimations[index]; + const animation = dontCloneAnimations ? targetedAnimation.animation : targetedAnimation.animation.clone(); + if (useFrame) { + // Make sure we have keys corresponding to the bounds of the frame range + animation.createKeyForFrame(start); + animation.createKeyForFrame(end); + } + const keys = animation.getKeys(); + const newKeys = []; + let startFrame = Number.MAX_VALUE; + for (let k = 0; k < keys.length; k++) { + const key = keys[k]; + if ((!useFrame && k >= start && k <= end) || (useFrame && key.frame >= start && key.frame <= end)) { + const newKey = { + frame: key.frame, + value: key.value.clone ? key.value.clone() : key.value, + inTangent: key.inTangent, + outTangent: key.outTangent, + interpolation: key.interpolation, + lockedTangent: key.lockedTangent, + }; + if (startFrame === Number.MAX_VALUE) { + startFrame = newKey.frame; + } + newKey.frame -= startFrame; + newKeys.push(newKey); + } + } + if (newKeys.length === 0) { + targetedAnimations.splice(index, 1); + index--; + continue; + } + if (from > newKeys[0].frame) { + from = newKeys[0].frame; + } + if (to < newKeys[newKeys.length - 1].frame) { + to = newKeys[newKeys.length - 1].frame; + } + animation.setKeys(newKeys, true); + targetedAnimation.animation = animation; // in case the animation has been cloned + } + animationGroup._from = from; + animationGroup._to = to; + return animationGroup; + } + /** + * Returns the string "AnimationGroup" + * @returns "AnimationGroup" + */ + getClassName() { + return "AnimationGroup"; + } + /** + * Creates a detailed string about the object + * @param fullDetails defines if the output string will support multiple levels of logging within scene loading + * @returns a string representing the object + */ + toString(fullDetails) { + let ret = "Name: " + this.name; + ret += ", type: " + this.getClassName(); + if (fullDetails) { + ret += ", from: " + this._from; + ret += ", to: " + this._to; + ret += ", isStarted: " + this._isStarted; + ret += ", speedRatio: " + this._speedRatio; + ret += ", targetedAnimations length: " + this._targetedAnimations.length; + ret += ", animatables length: " + this._animatables; + } + return ret; + } +} + +const animationGroup = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + AnimationGroup, + TargetedAnimation +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Enum for the animation key frame interpolation type + */ +var AnimationKeyInterpolation; +(function (AnimationKeyInterpolation) { + /** + * Use tangents to interpolate between start and end values. + */ + AnimationKeyInterpolation[AnimationKeyInterpolation["NONE"] = 0] = "NONE"; + /** + * Do not interpolate between keys and use the start key value only. Tangents are ignored + */ + AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP"; +})(AnimationKeyInterpolation || (AnimationKeyInterpolation = {})); + +/** + * Enum used to define the mode for an animation group mask + */ +var AnimationGroupMaskMode; +(function (AnimationGroupMaskMode) { + /** + * The mask defines the animatable target names that should be included + */ + AnimationGroupMaskMode[AnimationGroupMaskMode["Include"] = 0] = "Include"; + /** + * The mask defines the animatable target names in a "exclude" mode: all animatable targets will be animated except the ones defined in the mask + */ + AnimationGroupMaskMode[AnimationGroupMaskMode["Exclude"] = 1] = "Exclude"; +})(AnimationGroupMaskMode || (AnimationGroupMaskMode = {})); + +var AudioNodeType; +(function (AudioNodeType) { + AudioNodeType[AudioNodeType["HAS_INPUTS"] = 1] = "HAS_INPUTS"; + AudioNodeType[AudioNodeType["HAS_OUTPUTS"] = 2] = "HAS_OUTPUTS"; + AudioNodeType[AudioNodeType["HAS_INPUTS_AND_OUTPUTS"] = 3] = "HAS_INPUTS_AND_OUTPUTS"; +})(AudioNodeType || (AudioNodeType = {})); + +({ + position: Vector3.Zero(), + rotation: Vector3.Zero()}); + +({ + position: Vector3.Zero(), + rotation: Vector3.Zero()}); + +/** + * The state of a sound. + */ +var SoundState; +(function (SoundState) { + /** + * The sound is waiting for its instances to stop. + */ + SoundState[SoundState["Stopping"] = 0] = "Stopping"; + /** + * The sound is stopped. + */ + SoundState[SoundState["Stopped"] = 1] = "Stopped"; + /** + * The sound is waiting for its instances to start. + */ + SoundState[SoundState["Starting"] = 2] = "Starting"; + /** + * The sound has started playing. + */ + SoundState[SoundState["Started"] = 3] = "Started"; + /** + * The sound failed to start, most likely due to the user not interacting with the page, yet. + */ + SoundState[SoundState["FailedToStart"] = 4] = "FailedToStart"; + /** + * The sound is paused. + */ + SoundState[SoundState["Paused"] = 5] = "Paused"; +})(SoundState || (SoundState = {})); + +var SpatialAudioAttachmentType; +(function (SpatialAudioAttachmentType) { + SpatialAudioAttachmentType[SpatialAudioAttachmentType["Position"] = 1] = "Position"; + SpatialAudioAttachmentType[SpatialAudioAttachmentType["Rotation"] = 2] = "Rotation"; + SpatialAudioAttachmentType[SpatialAudioAttachmentType["PositionAndRotation"] = 3] = "PositionAndRotation"; +})(SpatialAudioAttachmentType || (SpatialAudioAttachmentType = {})); + +Matrix.Zero(); +Vector3.Zero(); + +Matrix.Zero(); +Vector3.Zero(); + +/** + * This class is used to animate meshes using a baked vertex animation texture + * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/baked_texture_animations + * @since 5.0 + */ +class BakedVertexAnimationManager { + /** + * Creates a new BakedVertexAnimationManager + * @param scene defines the current scene + */ + constructor(scene) { + this._texture = null; + this._isEnabled = true; + /** + * Enable or disable the vertex animation manager + */ + this.isEnabled = true; + /** + * The time counter, to pick the correct animation frame. + */ + this.time = 0; + scene = scene || EngineStore.LastCreatedScene; + if (!scene) { + return; + } + this._scene = scene; + this.animationParameters = new Vector4(0, 0, 0, 30); + } + /** @internal */ + _markSubMeshesAsAttributesDirty() { + for (const mesh of this._scene.meshes) { + if (mesh.bakedVertexAnimationManager === this) { + mesh._markSubMeshesAsAttributesDirty(); + } + } + } + /** + * Binds to the effect. + * @param effect The effect to bind to. + * @param useInstances True when it's an instance. + */ + bind(effect, useInstances = false) { + if (!this._texture || !this._isEnabled) { + return; + } + const size = this._texture.getSize(); + effect.setFloat2("bakedVertexAnimationTextureSizeInverted", 1.0 / size.width, 1.0 / size.height); + effect.setFloat("bakedVertexAnimationTime", this.time); + if (!useInstances) { + effect.setVector4("bakedVertexAnimationSettings", this.animationParameters); + } + effect.setTexture("bakedVertexAnimationTexture", this._texture); + } + /** + * Clone the current manager + * @returns a new BakedVertexAnimationManager + */ + clone() { + const copy = new BakedVertexAnimationManager(this._scene); + this.copyTo(copy); + return copy; + } + /** + * Sets animation parameters. + * @param startFrame The first frame of the animation. + * @param endFrame The last frame of the animation. + * @param offset The offset when starting the animation. + * @param speedFramesPerSecond The frame rate. + */ + setAnimationParameters(startFrame, endFrame, offset = 0, speedFramesPerSecond = 30) { + this.animationParameters = new Vector4(startFrame, endFrame, offset, speedFramesPerSecond); + } + /** + * Disposes the resources of the manager. + * @param forceDisposeTextures - Forces the disposal of all textures. + */ + dispose(forceDisposeTextures) { + if (forceDisposeTextures) { + this._texture?.dispose(); + } + } + /** + * Get the current class name useful for serialization or dynamic coding. + * @returns "BakedVertexAnimationManager" + */ + getClassName() { + return "BakedVertexAnimationManager"; + } + /** + * Makes a duplicate of the current instance into another one. + * @param vatMap define the instance where to copy the info + */ + copyTo(vatMap) { + SerializationHelper.Clone(() => vatMap, this); + } + /** + * Serializes this vertex animation instance + * @returns - An object with the serialized instance. + */ + serialize() { + return SerializationHelper.Serialize(this); + } + /** + * Parses a vertex animation setting from a serialized object. + * @param source - Serialized object. + * @param scene Defines the scene we are parsing for + * @param rootUrl Defines the rootUrl to load from + */ + parse(source, scene, rootUrl) { + SerializationHelper.Parse(() => this, source, scene, rootUrl); + } +} +__decorate([ + serializeAsTexture(), + expandToProperty("_markSubMeshesAsAttributesDirty") +], BakedVertexAnimationManager.prototype, "texture", void 0); +__decorate([ + serialize(), + expandToProperty("_markSubMeshesAsAttributesDirty") +], BakedVertexAnimationManager.prototype, "isEnabled", void 0); +__decorate([ + serialize() +], BakedVertexAnimationManager.prototype, "animationParameters", void 0); +__decorate([ + serialize() +], BakedVertexAnimationManager.prototype, "time", void 0); + +/** + * Class representing a ray with position and direction + */ +class Ray { + /** + * Creates a new ray + * @param origin origin point + * @param direction direction + * @param length length of the ray + * @param epsilon The epsilon value to use when calculating the ray/triangle intersection (default: 0) + */ + constructor( + /** origin point */ + origin, + /** direction */ + direction, + /** [Number.MAX_VALUE] length of the ray */ + length = Number.MAX_VALUE, + /** [Epsilon] The epsilon value to use when calculating the ray/triangle intersection (default: Epsilon from math constants) */ + epsilon = Epsilon) { + this.origin = origin; + this.direction = direction; + this.length = length; + this.epsilon = epsilon; + } + // Methods + /** + * Clone the current ray + * @returns a new ray + */ + clone() { + return new Ray(this.origin.clone(), this.direction.clone(), this.length); + } + /** + * Checks if the ray intersects a box + * This does not account for the ray length by design to improve perfs. + * @param minimum bound of the box + * @param maximum bound of the box + * @param intersectionTreshold extra extend to be added to the box in all direction + * @returns if the box was hit + */ + intersectsBoxMinMax(minimum, maximum, intersectionTreshold = 0) { + const newMinimum = Ray._TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold); + const newMaximum = Ray._TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold); + let d = 0.0; + let maxValue = Number.MAX_VALUE; + let inv; + let min; + let max; + let temp; + if (Math.abs(this.direction.x) < 0.0000001) { + if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) { + return false; + } + } + else { + inv = 1.0 / this.direction.x; + min = (newMinimum.x - this.origin.x) * inv; + max = (newMaximum.x - this.origin.x) * inv; + if (max === -Infinity) { + max = Infinity; + } + if (min > max) { + temp = min; + min = max; + max = temp; + } + d = Math.max(min, d); + maxValue = Math.min(max, maxValue); + if (d > maxValue) { + return false; + } + } + if (Math.abs(this.direction.y) < 0.0000001) { + if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) { + return false; + } + } + else { + inv = 1.0 / this.direction.y; + min = (newMinimum.y - this.origin.y) * inv; + max = (newMaximum.y - this.origin.y) * inv; + if (max === -Infinity) { + max = Infinity; + } + if (min > max) { + temp = min; + min = max; + max = temp; + } + d = Math.max(min, d); + maxValue = Math.min(max, maxValue); + if (d > maxValue) { + return false; + } + } + if (Math.abs(this.direction.z) < 0.0000001) { + if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) { + return false; + } + } + else { + inv = 1.0 / this.direction.z; + min = (newMinimum.z - this.origin.z) * inv; + max = (newMaximum.z - this.origin.z) * inv; + if (max === -Infinity) { + max = Infinity; + } + if (min > max) { + temp = min; + min = max; + max = temp; + } + d = Math.max(min, d); + maxValue = Math.min(max, maxValue); + if (d > maxValue) { + return false; + } + } + return true; + } + /** + * Checks if the ray intersects a box + * This does not account for the ray lenght by design to improve perfs. + * @param box the bounding box to check + * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction + * @returns if the box was hit + */ + intersectsBox(box, intersectionTreshold = 0) { + return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold); + } + /** + * If the ray hits a sphere + * @param sphere the bounding sphere to check + * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction + * @returns true if it hits the sphere + */ + intersectsSphere(sphere, intersectionTreshold = 0) { + const x = sphere.center.x - this.origin.x; + const y = sphere.center.y - this.origin.y; + const z = sphere.center.z - this.origin.z; + const pyth = x * x + y * y + z * z; + const radius = sphere.radius + intersectionTreshold; + const rr = radius * radius; + if (pyth <= rr) { + return true; + } + const dot = x * this.direction.x + y * this.direction.y + z * this.direction.z; + if (dot < 0.0) { + return false; + } + const temp = pyth - dot * dot; + return temp <= rr; + } + /** + * If the ray hits a triange + * @param vertex0 triangle vertex + * @param vertex1 triangle vertex + * @param vertex2 triangle vertex + * @returns intersection information if hit + */ + intersectsTriangle(vertex0, vertex1, vertex2) { + const edge1 = Ray._TmpVector3[0]; + const edge2 = Ray._TmpVector3[1]; + const pvec = Ray._TmpVector3[2]; + const tvec = Ray._TmpVector3[3]; + const qvec = Ray._TmpVector3[4]; + vertex1.subtractToRef(vertex0, edge1); + vertex2.subtractToRef(vertex0, edge2); + Vector3.CrossToRef(this.direction, edge2, pvec); + const det = Vector3.Dot(edge1, pvec); + if (det === 0) { + return null; + } + const invdet = 1 / det; + this.origin.subtractToRef(vertex0, tvec); + const bv = Vector3.Dot(tvec, pvec) * invdet; + if (bv < -this.epsilon || bv > 1.0 + this.epsilon) { + return null; + } + Vector3.CrossToRef(tvec, edge1, qvec); + const bw = Vector3.Dot(this.direction, qvec) * invdet; + if (bw < -this.epsilon || bv + bw > 1.0 + this.epsilon) { + return null; + } + //check if the distance is longer than the predefined length. + const distance = Vector3.Dot(edge2, qvec) * invdet; + if (distance > this.length) { + return null; + } + return new IntersectionInfo(1 - bv - bw, bv, distance); + } + /** + * Checks if ray intersects a plane + * @param plane the plane to check + * @returns the distance away it was hit + */ + intersectsPlane(plane) { + let distance; + const result1 = Vector3.Dot(plane.normal, this.direction); + if (Math.abs(result1) < 9.99999997475243e-7) { + return null; + } + else { + const result2 = Vector3.Dot(plane.normal, this.origin); + distance = (-plane.d - result2) / result1; + if (distance < 0.0) { + if (distance < -9.99999997475243e-7) { + return null; + } + else { + return 0; + } + } + return distance; + } + } + /** + * Calculate the intercept of a ray on a given axis + * @param axis to check 'x' | 'y' | 'z' + * @param offset from axis interception (i.e. an offset of 1y is intercepted above ground) + * @returns a vector containing the coordinates where 'axis' is equal to zero (else offset), or null if there is no intercept. + */ + intersectsAxis(axis, offset = 0) { + switch (axis) { + case "y": { + const t = (this.origin.y - offset) / this.direction.y; + if (t > 0) { + return null; + } + return new Vector3(this.origin.x + this.direction.x * -t, offset, this.origin.z + this.direction.z * -t); + } + case "x": { + const t = (this.origin.x - offset) / this.direction.x; + if (t > 0) { + return null; + } + return new Vector3(offset, this.origin.y + this.direction.y * -t, this.origin.z + this.direction.z * -t); + } + case "z": { + const t = (this.origin.z - offset) / this.direction.z; + if (t > 0) { + return null; + } + return new Vector3(this.origin.x + this.direction.x * -t, this.origin.y + this.direction.y * -t, offset); + } + default: + return null; + } + } + /** + * Checks if ray intersects a mesh. The ray is defined in WORLD space. A mesh triangle can be picked both from its front and back sides, + * irrespective of orientation. + * @param mesh the mesh to check + * @param fastCheck defines if the first intersection will be used (and not the closest) + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default) + * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point + * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check + * @returns picking info of the intersection + */ + intersectsMesh(mesh, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) { + const tm = TmpVectors.Matrix[0]; + mesh.getWorldMatrix().invertToRef(tm); + if (this._tmpRay) { + Ray.TransformToRef(this, tm, this._tmpRay); + } + else { + this._tmpRay = Ray.Transform(this, tm); + } + return mesh.intersects(this._tmpRay, fastCheck, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo); + } + /** + * Checks if ray intersects a mesh + * @param meshes the meshes to check + * @param fastCheck defines if the first intersection will be used (and not the closest) + * @param results array to store result in + * @returns Array of picking infos + */ + intersectsMeshes(meshes, fastCheck, results) { + if (results) { + results.length = 0; + } + else { + results = []; + } + for (let i = 0; i < meshes.length; i++) { + const pickInfo = this.intersectsMesh(meshes[i], fastCheck); + if (pickInfo.hit) { + results.push(pickInfo); + } + } + results.sort(this._comparePickingInfo); + return results; + } + _comparePickingInfo(pickingInfoA, pickingInfoB) { + if (pickingInfoA.distance < pickingInfoB.distance) { + return -1; + } + else if (pickingInfoA.distance > pickingInfoB.distance) { + return 1; + } + else { + return 0; + } + } + /** + * Intersection test between the ray and a given segment within a given tolerance (threshold) + * @param sega the first point of the segment to test the intersection against + * @param segb the second point of the segment to test the intersection against + * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful + * @returns the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection + */ + intersectionSegment(sega, segb, threshold) { + const o = this.origin; + const u = TmpVectors.Vector3[0]; + const rsegb = TmpVectors.Vector3[1]; + const v = TmpVectors.Vector3[2]; + const w = TmpVectors.Vector3[3]; + segb.subtractToRef(sega, u); + this.direction.scaleToRef(Ray._Rayl, v); + o.addToRef(v, rsegb); + sega.subtractToRef(o, w); + const a = Vector3.Dot(u, u); // always >= 0 + const b = Vector3.Dot(u, v); + const c = Vector3.Dot(v, v); // always >= 0 + const d = Vector3.Dot(u, w); + const e = Vector3.Dot(v, w); + const D = a * c - b * b; // always >= 0 + let sN, sD = D; // sc = sN / sD, default sD = D >= 0 + let tN, tD = D; // tc = tN / tD, default tD = D >= 0 + // compute the line parameters of the two closest points + if (D < Ray._Smallnum) { + // the lines are almost parallel + sN = 0.0; // force using point P0 on segment S1 + sD = 1.0; // to prevent possible division by 0.0 later + tN = e; + tD = c; + } + else { + // get the closest points on the infinite lines + sN = b * e - c * d; + tN = a * e - b * d; + if (sN < 0.0) { + // sc < 0 => the s=0 edge is visible + sN = 0.0; + tN = e; + tD = c; + } + else if (sN > sD) { + // sc > 1 => the s=1 edge is visible + sN = sD; + tN = e + b; + tD = c; + } + } + if (tN < 0.0) { + // tc < 0 => the t=0 edge is visible + tN = 0.0; + // recompute sc for this edge + if (-d < 0.0) { + sN = 0.0; + } + else if (-d > a) { + sN = sD; + } + else { + sN = -d; + sD = a; + } + } + else if (tN > tD) { + // tc > 1 => the t=1 edge is visible + tN = tD; + // recompute sc for this edge + if (-d + b < 0.0) { + sN = 0; + } + else if (-d + b > a) { + sN = sD; + } + else { + sN = -d + b; + sD = a; + } + } + // finally do the division to get sc and tc + const sc = Math.abs(sN) < Ray._Smallnum ? 0.0 : sN / sD; + const tc = Math.abs(tN) < Ray._Smallnum ? 0.0 : tN / tD; + // get the difference of the two closest points + const qtc = TmpVectors.Vector3[4]; + v.scaleToRef(tc, qtc); + const qsc = TmpVectors.Vector3[5]; + u.scaleToRef(sc, qsc); + qsc.addInPlace(w); + const dP = TmpVectors.Vector3[6]; + qsc.subtractToRef(qtc, dP); // = S1(sc) - S2(tc) + const isIntersected = tc > 0 && tc <= this.length && dP.lengthSquared() < threshold * threshold; // return intersection result + if (isIntersected) { + return qsc.length(); + } + return -1; + } + /** + * Update the ray from viewport position + * @param x position + * @param y y position + * @param viewportWidth viewport width + * @param viewportHeight viewport height + * @param world world matrix + * @param view view matrix + * @param projection projection matrix + * @param enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default) + * @returns this ray updated + */ + update(x, y, viewportWidth, viewportHeight, world, view, projection, enableDistantPicking = false) { + if (enableDistantPicking) { + // With world matrices having great values (like 8000000000 on 1 or more scaling or position axis), + // multiplying view/projection/world and doing invert will result in loss of float precision in the matrix. + // One way to fix it is to compute the ray with world at identity then transform the ray in object space. + // This is slower (2 matrix inverts instead of 1) but precision is preserved. + // This is hidden behind `EnableDistantPicking` flag (default is false) + if (!Ray._RayDistant) { + Ray._RayDistant = Ray.Zero(); + } + Ray._RayDistant.unprojectRayToRef(x, y, viewportWidth, viewportHeight, Matrix.IdentityReadOnly, view, projection); + const tm = TmpVectors.Matrix[0]; + world.invertToRef(tm); + Ray.TransformToRef(Ray._RayDistant, tm, this); + } + else { + this.unprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection); + } + return this; + } + // Statics + /** + * Creates a ray with origin and direction of 0,0,0 + * @returns the new ray + */ + static Zero() { + return new Ray(Vector3.Zero(), Vector3.Zero()); + } + /** + * Creates a new ray from screen space and viewport + * @param x position + * @param y y position + * @param viewportWidth viewport width + * @param viewportHeight viewport height + * @param world world matrix + * @param view view matrix + * @param projection projection matrix + * @returns new ray + */ + static CreateNew(x, y, viewportWidth, viewportHeight, world, view, projection) { + const result = Ray.Zero(); + return result.update(x, y, viewportWidth, viewportHeight, world, view, projection); + } + /** + * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be + * transformed to the given world matrix. + * @param origin The origin point + * @param end The end point + * @param world a matrix to transform the ray to. Default is the identity matrix. + * @returns the new ray + */ + static CreateNewFromTo(origin, end, world = Matrix.IdentityReadOnly) { + const result = new Ray(new Vector3(0, 0, 0), new Vector3(0, 0, 0)); + return Ray.CreateFromToToRef(origin, end, result, world); + } + /** + * Function will update a transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be + * transformed to the given world matrix. + * @param origin The origin point + * @param end The end point + * @param result the object to store the result + * @param world a matrix to transform the ray to. Default is the identity matrix. + * @returns the ref ray + */ + static CreateFromToToRef(origin, end, result, world = Matrix.IdentityReadOnly) { + result.origin.copyFrom(origin); + const direction = end.subtractToRef(origin, result.direction); + const length = Math.sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + result.length = length; + result.direction.normalize(); + return Ray.TransformToRef(result, world, result); + } + /** + * Transforms a ray by a matrix + * @param ray ray to transform + * @param matrix matrix to apply + * @returns the resulting new ray + */ + static Transform(ray, matrix) { + const result = new Ray(new Vector3(0, 0, 0), new Vector3(0, 0, 0)); + Ray.TransformToRef(ray, matrix, result); + return result; + } + /** + * Transforms a ray by a matrix + * @param ray ray to transform + * @param matrix matrix to apply + * @param result ray to store result in + * @returns the updated result ray + */ + static TransformToRef(ray, matrix, result) { + Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin); + Vector3.TransformNormalToRef(ray.direction, matrix, result.direction); + result.length = ray.length; + result.epsilon = ray.epsilon; + const dir = result.direction; + const len = dir.length(); + if (!(len === 0 || len === 1)) { + const num = 1.0 / len; + dir.x *= num; + dir.y *= num; + dir.z *= num; + result.length *= len; + } + return result; + } + /** + * Unproject a ray from screen space to object space + * @param sourceX defines the screen space x coordinate to use + * @param sourceY defines the screen space y coordinate to use + * @param viewportWidth defines the current width of the viewport + * @param viewportHeight defines the current height of the viewport + * @param world defines the world matrix to use (can be set to Identity to go to world space) + * @param view defines the view matrix to use + * @param projection defines the projection matrix to use + */ + unprojectRayToRef(sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection) { + const matrix = TmpVectors.Matrix[0]; + world.multiplyToRef(view, matrix); + matrix.multiplyToRef(projection, matrix); + matrix.invert(); + const engine = EngineStore.LastCreatedEngine; + const nearScreenSource = TmpVectors.Vector3[0]; + nearScreenSource.x = (sourceX / viewportWidth) * 2 - 1; + nearScreenSource.y = -((sourceY / viewportHeight) * 2 - 1); + nearScreenSource.z = engine?.useReverseDepthBuffer ? 1 : engine?.isNDCHalfZRange ? 0 : -1; + // far Z need to be close but < to 1 or camera projection matrix with maxZ = 0 will NaN + const farScreenSource = TmpVectors.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0 - 1e-8); + const nearVec3 = TmpVectors.Vector3[2]; + const farVec3 = TmpVectors.Vector3[3]; + Vector3._UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3); + Vector3._UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3); + this.origin.copyFrom(nearVec3); + farVec3.subtractToRef(nearVec3, this.direction); + this.direction.normalize(); + } +} +Ray._TmpVector3 = BuildArray(6, Vector3.Zero); +Ray._RayDistant = Ray.Zero(); +Ray._Smallnum = 0.00000001; +Ray._Rayl = 10e8; +/** + * Creates a ray that can be used to pick in the scene + * @param scene defines the scene to use for the picking + * @param x defines the x coordinate of the origin (on-screen) + * @param y defines the y coordinate of the origin (on-screen) + * @param world defines the world matrix to use if you want to pick in object space (instead of world space) + * @param camera defines the camera to use for the picking + * @param cameraViewSpace defines if picking will be done in view space (false by default) + * @returns a Ray + */ +function CreatePickingRay(scene, x, y, world, camera, cameraViewSpace = false) { + const result = Ray.Zero(); + CreatePickingRayToRef(scene, x, y, world, result, camera, cameraViewSpace); + return result; +} +/** + * Creates a ray that can be used to pick in the scene + * @param scene defines the scene to use for the picking + * @param x defines the x coordinate of the origin (on-screen) + * @param y defines the y coordinate of the origin (on-screen) + * @param world defines the world matrix to use if you want to pick in object space (instead of world space) + * @param result defines the ray where to store the picking ray + * @param camera defines the camera to use for the picking + * @param cameraViewSpace defines if picking will be done in view space (false by default) + * @param enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default) + * @returns the current scene + */ +function CreatePickingRayToRef(scene, x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) { + const engine = scene.getEngine(); + if (!camera && !(camera = scene.activeCamera)) { + return scene; + } + const cameraViewport = camera.viewport; + const renderHeight = engine.getRenderHeight(); + const { x: vx, y: vy, width, height } = cameraViewport.toGlobal(engine.getRenderWidth(), renderHeight); + // Moving coordinates to local viewport world + const levelInv = 1 / engine.getHardwareScalingLevel(); + x = x * levelInv - vx; + y = y * levelInv - (renderHeight - vy - height); + result.update(x, y, width, height, world ? world : Matrix.IdentityReadOnly, cameraViewSpace ? Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix(), enableDistantPicking); + return scene; +} +/** + * Creates a ray that can be used to pick in the scene + * @param scene defines the scene to use for the picking + * @param x defines the x coordinate of the origin (on-screen) + * @param y defines the y coordinate of the origin (on-screen) + * @param camera defines the camera to use for the picking + * @returns a Ray + */ +function CreatePickingRayInCameraSpace(scene, x, y, camera) { + const result = Ray.Zero(); + CreatePickingRayInCameraSpaceToRef(scene, x, y, result, camera); + return result; +} +/** + * Creates a ray that can be used to pick in the scene + * @param scene defines the scene to use for the picking + * @param x defines the x coordinate of the origin (on-screen) + * @param y defines the y coordinate of the origin (on-screen) + * @param result defines the ray where to store the picking ray + * @param camera defines the camera to use for the picking + * @returns the current scene + */ +function CreatePickingRayInCameraSpaceToRef(scene, x, y, result, camera) { + if (!PickingInfo) { + return scene; + } + const engine = scene.getEngine(); + if (!camera && !(camera = scene.activeCamera)) { + throw new Error("Active camera not set"); + } + const cameraViewport = camera.viewport; + const renderHeight = engine.getRenderHeight(); + const { x: vx, y: vy, width, height } = cameraViewport.toGlobal(engine.getRenderWidth(), renderHeight); + const identity = Matrix.Identity(); + // Moving coordinates to local viewport world + const levelInv = 1 / engine.getHardwareScalingLevel(); + x = x * levelInv - vx; + y = y * levelInv - (renderHeight - vy - height); + result.update(x, y, width, height, identity, identity, camera.getProjectionMatrix()); + return scene; +} +function InternalPickForMesh(pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate, skipBoundingInfo) { + const ray = rayFunction(world, mesh.enableDistantPicking); + const result = mesh.intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo, world, skipBoundingInfo); + if (!result || !result.hit) { + return null; + } + if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) { + return null; + } + return result; +} +function InternalPick(scene, rayFunction, predicate, fastCheck, onlyBoundingInfo, trianglePredicate) { + let pickingInfo = null; + const computeWorldMatrixForCamera = !!(scene.activeCameras && scene.activeCameras.length > 1 && scene.cameraToUseForPointers !== scene.activeCamera); + const currentCamera = scene.cameraToUseForPointers || scene.activeCamera; + const picker = InternalPickForMesh; + for (let meshIndex = 0; meshIndex < scene.meshes.length; meshIndex++) { + const mesh = scene.meshes[meshIndex]; + if (predicate) { + if (!predicate(mesh, -1)) { + continue; + } + } + else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) { + continue; + } + const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent(); + const world = mesh.computeWorldMatrix(forceCompute, currentCamera); + if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) { + // first check if the ray intersects the whole bounding box/sphere of the mesh + const result = picker(pickingInfo, rayFunction, mesh, world, true, true, trianglePredicate); + if (result) { + if (onlyBoundingInfo) { + // the user only asked for a bounding info check so we can return + return result; + } + const tmpMatrix = TmpVectors.Matrix[1]; + const thinMatrices = mesh.thinInstanceGetWorldMatrices(); + for (let index = 0; index < thinMatrices.length; index++) { + if (predicate && !predicate(mesh, index)) { + continue; + } + const thinMatrix = thinMatrices[index]; + thinMatrix.multiplyToRef(world, tmpMatrix); + const result = picker(pickingInfo, rayFunction, mesh, tmpMatrix, fastCheck, onlyBoundingInfo, trianglePredicate, true); + if (result) { + pickingInfo = result; + pickingInfo.thinInstanceIndex = index; + if (fastCheck) { + return pickingInfo; + } + } + } + } + } + else { + const result = picker(pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate); + if (result) { + pickingInfo = result; + if (fastCheck) { + return pickingInfo; + } + } + } + } + return pickingInfo || new PickingInfo(); +} +function InternalMultiPick(scene, rayFunction, predicate, trianglePredicate) { + if (!PickingInfo) { + return null; + } + const pickingInfos = []; + const computeWorldMatrixForCamera = !!(scene.activeCameras && scene.activeCameras.length > 1 && scene.cameraToUseForPointers !== scene.activeCamera); + const currentCamera = scene.cameraToUseForPointers || scene.activeCamera; + const picker = InternalPickForMesh; + for (let meshIndex = 0; meshIndex < scene.meshes.length; meshIndex++) { + const mesh = scene.meshes[meshIndex]; + if (predicate) { + if (!predicate(mesh, -1)) { + continue; + } + } + else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) { + continue; + } + const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent(); + const world = mesh.computeWorldMatrix(forceCompute, currentCamera); + if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) { + const result = picker(null, rayFunction, mesh, world, true, true, trianglePredicate); + if (result) { + const tmpMatrix = TmpVectors.Matrix[1]; + const thinMatrices = mesh.thinInstanceGetWorldMatrices(); + for (let index = 0; index < thinMatrices.length; index++) { + if (predicate && !predicate(mesh, index)) { + continue; + } + const thinMatrix = thinMatrices[index]; + thinMatrix.multiplyToRef(world, tmpMatrix); + const result = picker(null, rayFunction, mesh, tmpMatrix, false, false, trianglePredicate, true); + if (result) { + result.thinInstanceIndex = index; + pickingInfos.push(result); + } + } + } + } + else { + const result = picker(null, rayFunction, mesh, world, false, false, trianglePredicate); + if (result) { + pickingInfos.push(result); + } + } + } + return pickingInfos; +} +/** Launch a ray to try to pick a mesh in the scene using only bounding information of the main mesh (not using submeshes) + * @param scene defines the scene to use for the picking + * @param x position on screen + * @param y position on screen + * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced + * @param fastCheck defines if the first intersection will be used (and not the closest) + * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used + * @returns a PickingInfo (Please note that some info will not be set like distance, bv, bu and everything that cannot be capture by only using bounding infos) + */ +function PickWithBoundingInfo(scene, x, y, predicate, fastCheck, camera) { + if (!PickingInfo) { + return null; + } + const result = InternalPick(scene, (world) => { + if (!scene._tempPickingRay) { + scene._tempPickingRay = Ray.Zero(); + } + CreatePickingRayToRef(scene, x, y, world, scene._tempPickingRay, camera || null); + return scene._tempPickingRay; + }, predicate, fastCheck, true); + if (result) { + result.ray = CreatePickingRay(scene, x, y, Matrix.Identity(), camera || null); + } + return result; +} +/** Launch a ray to try to pick a mesh in the scene + * @param scene defines the scene to use for the picking + * @param x position on screen + * @param y position on screen + * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced + * @param fastCheck defines if the first intersection will be used (and not the closest) + * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @param _enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default) + * @returns a PickingInfo + */ +function Pick(scene, x, y, predicate, fastCheck, camera, trianglePredicate, _enableDistantPicking = false) { + const result = InternalPick(scene, (world, enableDistantPicking) => { + if (!scene._tempPickingRay) { + scene._tempPickingRay = Ray.Zero(); + } + CreatePickingRayToRef(scene, x, y, world, scene._tempPickingRay, camera || null, false, enableDistantPicking); + return scene._tempPickingRay; + }, predicate, fastCheck, false, trianglePredicate); + if (result) { + result.ray = CreatePickingRay(scene, x, y, Matrix.Identity(), camera || null); + } + return result; +} +/** + * Use the given ray to pick a mesh in the scene. A mesh triangle can be picked both from its front and back sides, + * irrespective of orientation. + * @param scene defines the scene to use for the picking + * @param ray The ray to use to pick meshes + * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced + * @param fastCheck defines if the first intersection will be used (and not the closest) + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @returns a PickingInfo + */ +function PickWithRay(scene, ray, predicate, fastCheck, trianglePredicate) { + const result = InternalPick(scene, (world) => { + if (!scene._pickWithRayInverseMatrix) { + scene._pickWithRayInverseMatrix = Matrix.Identity(); + } + world.invertToRef(scene._pickWithRayInverseMatrix); + if (!scene._cachedRayForTransform) { + scene._cachedRayForTransform = Ray.Zero(); + } + Ray.TransformToRef(ray, scene._pickWithRayInverseMatrix, scene._cachedRayForTransform); + return scene._cachedRayForTransform; + }, predicate, fastCheck, false, trianglePredicate); + if (result) { + result.ray = ray; + } + return result; +} +/** + * Launch a ray to try to pick a mesh in the scene. A mesh triangle can be picked both from its front and back sides, + * irrespective of orientation. + * @param scene defines the scene to use for the picking + * @param x X position on screen + * @param y Y position on screen + * @param predicate Predicate function used to determine eligible meshes and instances. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced + * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @returns an array of PickingInfo + */ +function MultiPick(scene, x, y, predicate, camera, trianglePredicate) { + return InternalMultiPick(scene, (world) => CreatePickingRay(scene, x, y, world, camera || null), predicate, trianglePredicate); +} +/** + * Launch a ray to try to pick a mesh in the scene + * @param scene defines the scene to use for the picking + * @param ray Ray to use + * @param predicate Predicate function used to determine eligible meshes and instances. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced + * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected + * @returns an array of PickingInfo + */ +function MultiPickWithRay(scene, ray, predicate, trianglePredicate) { + return InternalMultiPick(scene, (world) => { + if (!scene._pickWithRayInverseMatrix) { + scene._pickWithRayInverseMatrix = Matrix.Identity(); + } + world.invertToRef(scene._pickWithRayInverseMatrix); + if (!scene._cachedRayForTransform) { + scene._cachedRayForTransform = Ray.Zero(); + } + Ray.TransformToRef(ray, scene._pickWithRayInverseMatrix, scene._cachedRayForTransform); + return scene._cachedRayForTransform; + }, predicate, trianglePredicate); +} +/** + * Gets a ray in the forward direction from the camera. + * @param camera Defines the camera to use to get the ray from + * @param refRay the ray to (re)use when setting the values + * @param length Defines the length of the ray to create + * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray + * @param origin Defines the start point of the ray which defaults to the camera position + * @returns the forward ray + */ +function GetForwardRayToRef(camera, refRay, length = 100, transform, origin) { + if (!transform) { + transform = camera.getWorldMatrix(); + } + refRay.length = length; + if (origin) { + refRay.origin.copyFrom(origin); + } + else { + refRay.origin.copyFrom(camera.position); + } + const forward = TmpVectors.Vector3[2]; + forward.set(0, 0, camera._scene.useRightHandedSystem ? -1 : 1); + const worldForward = TmpVectors.Vector3[3]; + Vector3.TransformNormalToRef(forward, transform, worldForward); + Vector3.NormalizeToRef(worldForward, refRay.direction); + return refRay; +} +/** + * Initialize the minimal interdependecies between the Ray and Scene and Camera + * @param sceneClass defines the scene prototype to use + * @param cameraClass defines the camera prototype to use + */ +function AddRayExtensions(sceneClass, cameraClass) { + if (cameraClass) { + cameraClass.prototype.getForwardRay = function (length = 100, transform, origin) { + return GetForwardRayToRef(this, new Ray(Vector3.Zero(), Vector3.Zero(), length), length, transform, origin); + }; + cameraClass.prototype.getForwardRayToRef = function (refRay, length = 100, transform, origin) { + return GetForwardRayToRef(this, refRay, length, transform, origin); + }; + } + if (!sceneClass) { + return; + } + _ImportHelper._IsPickingAvailable = true; + sceneClass.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace = false) { + return CreatePickingRay(this, x, y, world, camera, cameraViewSpace); + }; +} + +// Picking +AddRayExtensions(Scene, Camera); +Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) { + return CreatePickingRayToRef(this, x, y, world, result, camera, cameraViewSpace, enableDistantPicking); +}; +Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) { + return CreatePickingRayInCameraSpace(this, x, y, camera); +}; +Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) { + return CreatePickingRayInCameraSpaceToRef(this, x, y, result, camera); +}; +Scene.prototype.pickWithBoundingInfo = function (x, y, predicate, fastCheck, camera) { + return PickWithBoundingInfo(this, x, y, predicate, fastCheck, camera); +}; +Scene.prototype.pick = function (x, y, predicate, fastCheck, camera, trianglePredicate, _enableDistantPicking = false) { + return Pick(this, x, y, predicate, fastCheck, camera, trianglePredicate, _enableDistantPicking); +}; +Scene.prototype.pickWithRay = function (ray, predicate, fastCheck, trianglePredicate) { + return PickWithRay(this, ray, predicate, fastCheck, trianglePredicate); +}; +Scene.prototype.multiPick = function (x, y, predicate, camera, trianglePredicate) { + return MultiPick(this, x, y, predicate, camera, trianglePredicate); +}; +Scene.prototype.multiPickWithRay = function (ray, predicate, trianglePredicate) { + return MultiPickWithRay(this, ray, predicate, trianglePredicate); +}; + +/** + * Creates the VertexData for a Plane + * @param options an object used to set the following optional parameters for the plane, required but can be empty + * * size sets the width and height of the plane to the value of size, optional default 1 + * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size + * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box + */ +function CreatePlaneVertexData(options) { + const indices = []; + const positions = []; + const normals = []; + const uvs = []; + const width = options.width !== undefined ? options.width : options.size !== undefined ? options.size : 1; + const height = options.height !== undefined ? options.height : options.size !== undefined ? options.size : 1; + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + // Vertices + const halfWidth = width / 2.0; + const halfHeight = height / 2.0; + positions.push(-halfWidth, -halfHeight, 0); + normals.push(0, 0, -1); + uvs.push(0.0, 0.0); + positions.push(halfWidth, -halfHeight, 0); + normals.push(0, 0, -1); + uvs.push(1.0, 0.0); + positions.push(halfWidth, halfHeight, 0); + normals.push(0, 0, -1); + uvs.push(1.0, 1.0); + positions.push(-halfWidth, halfHeight, 0); + normals.push(0, 0, -1); + uvs.push(0.0, 1.0); + // Indices + indices.push(0); + indices.push(1); + indices.push(2); + indices.push(0); + indices.push(2); + indices.push(3); + // Sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + return vertexData; +} +/** + * Creates a plane mesh + * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1) + * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`) + * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the plane mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#plane + */ +function CreatePlane(name, options = {}, scene = null) { + const plane = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + plane._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreatePlaneVertexData(options); + vertexData.applyToMesh(plane, options.updatable); + if (options.sourcePlane) { + plane.translate(options.sourcePlane.normal, -options.sourcePlane.d); + plane.setDirection(options.sourcePlane.normal.scale(-1)); + } + return plane; +} +VertexData.CreatePlane = CreatePlaneVertexData; +Mesh.CreatePlane = (name, size, scene, updatable, sideOrientation) => { + const options = { + size, + width: size, + height: size, + sideOrientation, + updatable, + }; + return CreatePlane(name, options, scene); +}; + +/** + * A list of the currently available features without referencing them + */ +class WebXRFeatureName { +} +/** + * The name of the anchor system feature + */ +WebXRFeatureName.ANCHOR_SYSTEM = "xr-anchor-system"; +/** + * The name of the background remover feature + */ +WebXRFeatureName.BACKGROUND_REMOVER = "xr-background-remover"; +/** + * The name of the hit test feature + */ +WebXRFeatureName.HIT_TEST = "xr-hit-test"; +/** + * The name of the mesh detection feature + */ +WebXRFeatureName.MESH_DETECTION = "xr-mesh-detection"; +/** + * physics impostors for xr controllers feature + */ +WebXRFeatureName.PHYSICS_CONTROLLERS = "xr-physics-controller"; +/** + * The name of the plane detection feature + */ +WebXRFeatureName.PLANE_DETECTION = "xr-plane-detection"; +/** + * The name of the pointer selection feature + */ +WebXRFeatureName.POINTER_SELECTION = "xr-controller-pointer-selection"; +/** + * The name of the teleportation feature + */ +WebXRFeatureName.TELEPORTATION = "xr-controller-teleportation"; +/** + * The name of the feature points feature. + */ +WebXRFeatureName.FEATURE_POINTS = "xr-feature-points"; +/** + * The name of the hand tracking feature. + */ +WebXRFeatureName.HAND_TRACKING = "xr-hand-tracking"; +/** + * The name of the image tracking feature + */ +WebXRFeatureName.IMAGE_TRACKING = "xr-image-tracking"; +/** + * The name of the near interaction feature + */ +WebXRFeatureName.NEAR_INTERACTION = "xr-near-interaction"; +/** + * The name of the DOM overlay feature + */ +WebXRFeatureName.DOM_OVERLAY = "xr-dom-overlay"; +/** + * The name of the movement feature + */ +WebXRFeatureName.MOVEMENT = "xr-controller-movement"; +/** + * The name of the light estimation feature + */ +WebXRFeatureName.LIGHT_ESTIMATION = "xr-light-estimation"; +/** + * The name of the eye tracking feature + */ +WebXRFeatureName.EYE_TRACKING = "xr-eye-tracking"; +/** + * The name of the walking locomotion feature + */ +WebXRFeatureName.WALKING_LOCOMOTION = "xr-walking-locomotion"; +/** + * The name of the composition layers feature + */ +WebXRFeatureName.LAYERS = "xr-layers"; +/** + * The name of the depth sensing feature + */ +WebXRFeatureName.DEPTH_SENSING = "xr-depth-sensing"; +/** + * The name of the WebXR Space Warp feature + */ +WebXRFeatureName.SPACE_WARP = "xr-space-warp"; +/** + * The name of the WebXR Raw Camera Access feature + */ +WebXRFeatureName.RAW_CAMERA_ACCESS = "xr-raw-camera-access"; +/** + * The WebXR features manager is responsible of enabling or disabling features required for the current XR session. + * It is mainly used in AR sessions. + * + * A feature can have a version that is defined by Babylon (and does not correspond with the webxr version). + */ +class WebXRFeaturesManager { + /** + * constructs a new features manages. + * + * @param _xrSessionManager an instance of WebXRSessionManager + */ + constructor(_xrSessionManager) { + this._xrSessionManager = _xrSessionManager; + this._features = {}; + // when session starts / initialized - attach + this._xrSessionManager.onXRSessionInit.add(() => { + this.getEnabledFeatures().forEach((featureName) => { + const feature = this._features[featureName]; + if (feature.enabled && !feature.featureImplementation.attached && !feature.featureImplementation.disableAutoAttach) { + this.attachFeature(featureName); + } + }); + }); + // when session ends - detach + this._xrSessionManager.onXRSessionEnded.add(() => { + this.getEnabledFeatures().forEach((featureName) => { + const feature = this._features[featureName]; + if (feature.enabled && feature.featureImplementation.attached) { + // detach, but don't disable! + this.detachFeature(featureName); + } + }); + }); + } + /** + * Used to register a module. After calling this function a developer can use this feature in the scene. + * Mainly used internally. + * + * @param featureName the name of the feature to register + * @param constructorFunction the function used to construct the module + * @param version the (babylon) version of the module + * @param stable is that a stable version of this module + */ + static AddWebXRFeature(featureName, constructorFunction, version = 1, stable = false) { + this._AvailableFeatures[featureName] = this._AvailableFeatures[featureName] || { latest: version }; + if (version > this._AvailableFeatures[featureName].latest) { + this._AvailableFeatures[featureName].latest = version; + } + if (stable) { + this._AvailableFeatures[featureName].stable = version; + } + this._AvailableFeatures[featureName][version] = constructorFunction; + } + /** + * Returns a constructor of a specific feature. + * + * @param featureName the name of the feature to construct + * @param version the version of the feature to load + * @param xrSessionManager the xrSessionManager. Used to construct the module + * @param options optional options provided to the module. + * @returns a function that, when called, will return a new instance of this feature + */ + static ConstructFeature(featureName, version = 1, xrSessionManager, options) { + const constructorFunction = this._AvailableFeatures[featureName][version]; + if (!constructorFunction) { + // throw an error? return nothing? + throw new Error("feature not found"); + } + return constructorFunction(xrSessionManager, options); + } + /** + * Can be used to return the list of features currently registered + * + * @returns an Array of available features + */ + static GetAvailableFeatures() { + return Object.keys(this._AvailableFeatures); + } + /** + * Gets the versions available for a specific feature + * @param featureName the name of the feature + * @returns an array with the available versions + */ + static GetAvailableVersions(featureName) { + return Object.keys(this._AvailableFeatures[featureName]); + } + /** + * Return the latest unstable version of this feature + * @param featureName the name of the feature to search + * @returns the version number. if not found will return -1 + */ + static GetLatestVersionOfFeature(featureName) { + return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].latest) || -1; + } + /** + * Return the latest stable version of this feature + * @param featureName the name of the feature to search + * @returns the version number. if not found will return -1 + */ + static GetStableVersionOfFeature(featureName) { + return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].stable) || -1; + } + /** + * Attach a feature to the current session. Mainly used when session started to start the feature effect. + * Can be used during a session to start a feature + * @param featureName the name of feature to attach + */ + attachFeature(featureName) { + const feature = this._features[featureName]; + if (feature && feature.enabled && !feature.featureImplementation.attached) { + const attached = feature.featureImplementation.attach(); + if (!attached) { + Tools.Warn(`Feature ${featureName} failed to attach`); + } + } + } + /** + * Can be used inside a session or when the session ends to detach a specific feature + * @param featureName the name of the feature to detach + */ + detachFeature(featureName) { + const feature = this._features[featureName]; + if (feature && feature.featureImplementation.attached) { + const detached = feature.featureImplementation.detach(); + if (!detached) { + Tools.Warn(`Feature ${featureName} failed to detach`); + } + } + } + /** + * Used to disable an already-enabled feature + * The feature will be disposed and will be recreated once enabled. + * @param featureName the feature to disable + * @returns true if disable was successful + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + disableFeature(featureName) { + const name = typeof featureName === "string" ? featureName : featureName.Name; + const feature = this._features[name]; + if (feature && feature.enabled) { + feature.enabled = false; + this.detachFeature(name); + feature.featureImplementation.dispose(); + delete this._features[name]; + return true; + } + return false; + } + /** + * dispose this features manager + */ + dispose() { + this.getEnabledFeatures().forEach((feature) => { + this.disableFeature(feature); + }); + } + /** + * Enable a feature using its name and a version. This will enable it in the scene, and will be responsible to attach it when the session starts. + * If used twice, the old version will be disposed and a new one will be constructed. This way you can re-enable with different configuration. + * + * @param featureName the name of the feature to load or the class of the feature + * @param version optional version to load. if not provided the latest version will be enabled + * @param moduleOptions options provided to the module. Ses the module documentation / constructor + * @param attachIfPossible if set to true (default) the feature will be automatically attached, if it is currently possible + * @param required is this feature required to the app. If set to true the session init will fail if the feature is not available. + * @returns a new constructed feature or throws an error if feature not found or conflicts with another enabled feature. + */ + enableFeature( + // eslint-disable-next-line @typescript-eslint/naming-convention + featureName, version = "latest", moduleOptions = {}, attachIfPossible = true, required = true) { + const name = typeof featureName === "string" ? featureName : featureName.Name; + let versionToLoad = 0; + if (typeof version === "string") { + if (!version) { + throw new Error(`Error in provided version - ${name} (${version})`); + } + if (version === "stable") { + versionToLoad = WebXRFeaturesManager.GetStableVersionOfFeature(name); + } + else if (version === "latest") { + versionToLoad = WebXRFeaturesManager.GetLatestVersionOfFeature(name); + } + else { + // try loading the number the string represents + versionToLoad = +version; + } + if (versionToLoad === -1 || isNaN(versionToLoad)) { + throw new Error(`feature not found - ${name} (${version})`); + } + } + else { + versionToLoad = version; + } + // check if there is a feature conflict + const conflictingFeature = WebXRFeaturesManager._ConflictingFeatures[name]; + if (conflictingFeature !== undefined && this.getEnabledFeatures().indexOf(conflictingFeature) !== -1) { + throw new Error(`Feature ${name} cannot be enabled while ${conflictingFeature} is enabled.`); + } + // check if already initialized + const feature = this._features[name]; + const constructFunction = WebXRFeaturesManager.ConstructFeature(name, versionToLoad, this._xrSessionManager, moduleOptions); + if (!constructFunction) { + // report error? + throw new Error(`feature not found - ${name}`); + } + /* If the feature is already enabled, detach and dispose it, and create a new one */ + if (feature) { + this.disableFeature(name); + } + const constructed = constructFunction(); + if (constructed.dependsOn) { + const dependentsFound = constructed.dependsOn.every((featureName) => !!this._features[featureName]); + if (!dependentsFound) { + throw new Error(`Dependant features missing. Make sure the following features are enabled - ${constructed.dependsOn.join(", ")}`); + } + } + if (constructed.isCompatible()) { + this._features[name] = { + featureImplementation: constructed, + enabled: true, + version: versionToLoad, + required, + }; + if (attachIfPossible) { + // if session started already, request and enable + if (this._xrSessionManager.session && !this._features[name].featureImplementation.attached) { + // enable feature + this.attachFeature(name); + } + } + else { + // disable auto-attach when session starts + this._features[name].featureImplementation.disableAutoAttach = true; + } + return this._features[name].featureImplementation; + } + else { + if (required) { + throw new Error("required feature not compatible"); + } + else { + Tools.Warn(`Feature ${name} not compatible with the current environment/browser and was not enabled.`); + return constructed; + } + } + } + /** + * get the implementation of an enabled feature. + * @param featureName the name of the feature to load + * @returns the feature class, if found + */ + getEnabledFeature(featureName) { + return this._features[featureName] && this._features[featureName].featureImplementation; + } + /** + * Get the list of enabled features + * @returns an array of enabled features + */ + getEnabledFeatures() { + return Object.keys(this._features); + } + /** + * This function will extend the session creation configuration object with enabled features. + * If, for example, the anchors feature is enabled, it will be automatically added to the optional or required features list, + * according to the defined "required" variable, provided during enableFeature call + * @param xrSessionInit the xr Session init object to extend + * + * @returns an extended XRSessionInit object + */ + async _extendXRSessionInitObject(xrSessionInit) { + const enabledFeatures = this.getEnabledFeatures(); + for (const featureName of enabledFeatures) { + const feature = this._features[featureName]; + const nativeName = feature.featureImplementation.xrNativeFeatureName; + if (nativeName) { + if (feature.required) { + xrSessionInit.requiredFeatures = xrSessionInit.requiredFeatures || []; + if (xrSessionInit.requiredFeatures.indexOf(nativeName) === -1) { + xrSessionInit.requiredFeatures.push(nativeName); + } + } + else { + xrSessionInit.optionalFeatures = xrSessionInit.optionalFeatures || []; + if (xrSessionInit.optionalFeatures.indexOf(nativeName) === -1) { + xrSessionInit.optionalFeatures.push(nativeName); + } + } + } + if (feature.featureImplementation.getXRSessionInitExtension) { + const extended = await feature.featureImplementation.getXRSessionInitExtension(); + xrSessionInit = { + ...xrSessionInit, + ...extended, + }; + } + } + return xrSessionInit; + } +} +WebXRFeaturesManager._AvailableFeatures = {}; +/** + * The key is the feature to check and the value is the feature that conflicts. + */ +WebXRFeaturesManager._ConflictingFeatures = { + [WebXRFeatureName.TELEPORTATION]: WebXRFeatureName.MOVEMENT, + [WebXRFeatureName.MOVEMENT]: WebXRFeatureName.TELEPORTATION, +}; + +/** + * Zones around the hand + */ +var HandConstraintZone; +(function (HandConstraintZone) { + /** + * Above finger tips + */ + HandConstraintZone[HandConstraintZone["ABOVE_FINGER_TIPS"] = 0] = "ABOVE_FINGER_TIPS"; + /** + * Next to the thumb + */ + HandConstraintZone[HandConstraintZone["RADIAL_SIDE"] = 1] = "RADIAL_SIDE"; + /** + * Next to the pinky finger + */ + HandConstraintZone[HandConstraintZone["ULNAR_SIDE"] = 2] = "ULNAR_SIDE"; + /** + * Below the wrist + */ + HandConstraintZone[HandConstraintZone["BELOW_WRIST"] = 3] = "BELOW_WRIST"; +})(HandConstraintZone || (HandConstraintZone = {})); +/** + * Orientations for the hand zones and for the attached node + */ +var HandConstraintOrientation; +(function (HandConstraintOrientation) { + /** + * Orientation is towards the camera + */ + HandConstraintOrientation[HandConstraintOrientation["LOOK_AT_CAMERA"] = 0] = "LOOK_AT_CAMERA"; + /** + * Orientation is determined by the rotation of the palm + */ + HandConstraintOrientation[HandConstraintOrientation["HAND_ROTATION"] = 1] = "HAND_ROTATION"; +})(HandConstraintOrientation || (HandConstraintOrientation = {})); +/** + * Orientations for the hand zones and for the attached node + */ +var HandConstraintVisibility; +(function (HandConstraintVisibility) { + /** + * Constraint is always visible + */ + HandConstraintVisibility[HandConstraintVisibility["ALWAYS_VISIBLE"] = 0] = "ALWAYS_VISIBLE"; + /** + * Constraint is only visible when the palm is up + */ + HandConstraintVisibility[HandConstraintVisibility["PALM_UP"] = 1] = "PALM_UP"; + /** + * Constraint is only visible when the user is looking at the constraint. + * Uses XR Eye Tracking if enabled/available, otherwise uses camera direction + */ + HandConstraintVisibility[HandConstraintVisibility["GAZE_FOCUS"] = 2] = "GAZE_FOCUS"; + /** + * Constraint is only visible when the palm is up and the user is looking at it + */ + HandConstraintVisibility[HandConstraintVisibility["PALM_AND_GAZE"] = 3] = "PALM_AND_GAZE"; +})(HandConstraintVisibility || (HandConstraintVisibility = {})); + +[Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; +[Matrix.Identity(), Matrix.Identity()]; + +BuildArray(10, Vector3.Zero); +BuildArray(5, Matrix.Identity); + +/** + * This class is a small wrapper around a native buffer that can be read and/or written + */ +class StorageBuffer { + /** + * Creates a new storage buffer instance + * @param engine The engine the buffer will be created inside + * @param size The size of the buffer in bytes + * @param creationFlags flags to use when creating the buffer (see undefined). The BUFFER_CREATIONFLAG_STORAGE flag will be automatically added. + * @param label defines the label of the buffer (for debug purpose) + */ + constructor(engine, size, creationFlags = 3, label) { + this._engine = engine; + this._label = label; + this._engine._storageBuffers.push(this); + this._create(size, creationFlags); + } + _create(size, creationFlags) { + this._bufferSize = size; + this._creationFlags = creationFlags; + this._buffer = this._engine.createStorageBuffer(size, creationFlags, this._label); + } + /** @internal */ + _rebuild() { + this._create(this._bufferSize, this._creationFlags); + } + /** + * Gets underlying native buffer + * @returns underlying native buffer + */ + getBuffer() { + return this._buffer; + } + /** + * Updates the storage buffer + * @param data the data used to update the storage buffer + * @param byteOffset the byte offset of the data (optional) + * @param byteLength the byte length of the data (optional) + */ + update(data, byteOffset, byteLength) { + if (!this._buffer) { + return; + } + this._engine.updateStorageBuffer(this._buffer, data, byteOffset, byteLength); + } + /** + * Reads data from the storage buffer + * @param offset The offset in the storage buffer to start reading from (default: 0) + * @param size The number of bytes to read from the storage buffer (default: capacity of the buffer) + * @param buffer The buffer to write the data we have read from the storage buffer to (optional) + * @param noDelay If true, a call to flushFramebuffer will be issued so that the data can be read back immediately. This can speed up data retrieval, at the cost of a small perf penalty (default: false). + * @returns If not undefined, returns the (promise) buffer (as provided by the 4th parameter) filled with the data, else it returns a (promise) Uint8Array with the data read from the storage buffer + */ + read(offset, size, buffer, noDelay) { + return this._engine.readFromStorageBuffer(this._buffer, offset, size, buffer, noDelay); + } + /** + * Disposes the storage buffer + */ + dispose() { + const storageBuffers = this._engine._storageBuffers; + const index = storageBuffers.indexOf(this); + if (index !== -1) { + storageBuffers[index] = storageBuffers[storageBuffers.length - 1]; + storageBuffers.pop(); + } + this._engine._releaseBuffer(this._buffer); + this._buffer = null; + } +} + +const isLittleEndian = (() => { + const array = new Uint8Array(4); + const view = new Uint32Array(array.buffer); + return !!((view[0] = 1) & array[0]); +})(); +Object.defineProperty(VertexBuffer.prototype, "effectiveByteStride", { + get: function () { + return (this._alignedBuffer && this._alignedBuffer.byteStride) || this.byteStride; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(VertexBuffer.prototype, "effectiveByteOffset", { + get: function () { + return this._alignedBuffer ? 0 : this.byteOffset; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(VertexBuffer.prototype, "effectiveBuffer", { + get: function () { + return (this._alignedBuffer && this._alignedBuffer.getBuffer()) || this._buffer.getBuffer(); + }, + enumerable: true, + configurable: true, +}); +VertexBuffer.prototype._rebuild = function () { + this._buffer?._rebuild(); + this._alignedBuffer?._rebuild(); +}; +VertexBuffer.prototype.dispose = function () { + if (this._ownsBuffer) { + this._buffer.dispose(); + } + this._alignedBuffer?.dispose(); + this._alignedBuffer = undefined; + this._isDisposed = true; +}; +VertexBuffer.prototype.getWrapperBuffer = function () { + return this._alignedBuffer || this._buffer; +}; +VertexBuffer.prototype._alignBuffer = function () { + const data = this._buffer.getData(); + if (!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes || (this.byteStride % 4 === 0 && this.byteOffset % 4 === 0) || !data) { + return; + } + const typeByteLength = VertexBuffer.GetTypeByteLength(this.type); + const alignedByteStride = (this.byteStride + 3) & -4; + const alignedSize = alignedByteStride / typeByteLength; + const totalVertices = this._maxVerticesCount; + const totalByteLength = totalVertices * alignedByteStride; + const totalLength = totalByteLength / typeByteLength; + let sourceData; + if (Array.isArray(data)) { + const sourceDataAsFloat = new Float32Array(data); + sourceData = new DataView(sourceDataAsFloat.buffer, sourceDataAsFloat.byteOffset, sourceDataAsFloat.byteLength); + } + else if (data instanceof ArrayBuffer) { + sourceData = new DataView(data, 0, data.byteLength); + } + else { + sourceData = new DataView(data.buffer, data.byteOffset, data.byteLength); + } + let alignedData; + if (this.type === VertexBuffer.BYTE) { + alignedData = new Int8Array(totalLength); + } + else if (this.type === VertexBuffer.UNSIGNED_BYTE) { + alignedData = new Uint8Array(totalLength); + } + else if (this.type === VertexBuffer.SHORT) { + alignedData = new Int16Array(totalLength); + } + else if (this.type === VertexBuffer.UNSIGNED_SHORT) { + alignedData = new Uint16Array(totalLength); + } + else if (this.type === VertexBuffer.INT) { + alignedData = new Int32Array(totalLength); + } + else if (this.type === VertexBuffer.UNSIGNED_INT) { + alignedData = new Uint32Array(totalLength); + } + else { + alignedData = new Float32Array(totalLength); + } + const numComponents = this.getSize(); + let sourceOffset = this.byteOffset; + for (let i = 0; i < totalVertices; ++i) { + for (let j = 0; j < numComponents; ++j) { + switch (this.type) { + case VertexBuffer.BYTE: + alignedData[i * alignedSize + j] = sourceData.getInt8(sourceOffset + j); + break; + case VertexBuffer.UNSIGNED_BYTE: + alignedData[i * alignedSize + j] = sourceData.getUint8(sourceOffset + j); + break; + case VertexBuffer.SHORT: + alignedData[i * alignedSize + j] = sourceData.getInt16(sourceOffset + j * 2, isLittleEndian); + break; + case VertexBuffer.UNSIGNED_SHORT: + alignedData[i * alignedSize + j] = sourceData.getUint16(sourceOffset + j * 2, isLittleEndian); + break; + case VertexBuffer.INT: + alignedData[i * alignedSize + j] = sourceData.getInt32(sourceOffset + j * 4, isLittleEndian); + break; + case VertexBuffer.UNSIGNED_INT: + alignedData[i * alignedSize + j] = sourceData.getUint32(sourceOffset + j * 4, isLittleEndian); + break; + case VertexBuffer.FLOAT: + alignedData[i * alignedSize + j] = sourceData.getFloat32(sourceOffset + j * 4, isLittleEndian); + break; + } + } + sourceOffset += this.byteStride; + } + this._alignedBuffer?.dispose(); + this._alignedBuffer = new Buffer(this.engine, alignedData, false, alignedByteStride, false, this.getIsInstanced(), true, this.instanceDivisor, (this._label ?? "VertexBuffer") + "_aligned"); +}; + +/** + * Represents a gamepad + */ +class Gamepad { + /** + * Specifies if the gamepad has been connected + */ + get isConnected() { + return this._isConnected; + } + /** + * Initializes the gamepad + * @param id The id of the gamepad + * @param index The index of the gamepad + * @param browserGamepad The browser gamepad + * @param leftStickX The x component of the left joystick + * @param leftStickY The y component of the left joystick + * @param rightStickX The x component of the right joystick + * @param rightStickY The y component of the right joystick + */ + constructor( + /** + * The id of the gamepad + */ + id, + /** + * The index of the gamepad + */ + index, + /** + * The browser gamepad + */ + browserGamepad, leftStickX = 0, leftStickY = 1, rightStickX = 2, rightStickY = 3) { + this.id = id; + this.index = index; + this.browserGamepad = browserGamepad; + this._leftStick = { x: 0, y: 0 }; + this._rightStick = { x: 0, y: 0 }; + /** @internal */ + this._isConnected = true; + /** + * Specifies whether the left control stick should be Y-inverted + */ + this._invertLeftStickY = false; + this.type = Gamepad.GAMEPAD; + this._leftStickAxisX = leftStickX; + this._leftStickAxisY = leftStickY; + this._rightStickAxisX = rightStickX; + this._rightStickAxisY = rightStickY; + if (this.browserGamepad.axes.length >= 2) { + this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] }; + } + if (this.browserGamepad.axes.length >= 4) { + this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] }; + } + } + /** + * Callback triggered when the left joystick has changed + * @param callback callback to trigger + */ + onleftstickchanged(callback) { + this._onleftstickchanged = callback; + } + /** + * Callback triggered when the right joystick has changed + * @param callback callback to trigger + */ + onrightstickchanged(callback) { + this._onrightstickchanged = callback; + } + /** + * Gets the left joystick + */ + get leftStick() { + return this._leftStick; + } + /** + * Sets the left joystick values + */ + set leftStick(newValues) { + if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) { + this._onleftstickchanged(newValues); + } + this._leftStick = newValues; + } + /** + * Gets the right joystick + */ + get rightStick() { + return this._rightStick; + } + /** + * Sets the right joystick value + */ + set rightStick(newValues) { + if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) { + this._onrightstickchanged(newValues); + } + this._rightStick = newValues; + } + /** + * Updates the gamepad joystick positions + */ + update() { + if (this._leftStick) { + this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] }; + if (this._invertLeftStickY) { + this.leftStick.y *= -1; + } + } + if (this._rightStick) { + this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] }; + } + } + /** + * Disposes the gamepad + */ + dispose() { } +} +/** + * Represents a gamepad controller + */ +Gamepad.GAMEPAD = 0; +/** + * Represents a generic controller + */ +Gamepad.GENERIC = 1; +/** + * Represents an XBox controller + */ +Gamepad.XBOX = 2; +/** + * Represents a pose-enabled controller + */ +Gamepad.POSE_ENABLED = 3; +/** + * Represents an Dual Shock controller + */ +Gamepad.DUALSHOCK = 4; +/** + * Represents a generic gamepad + */ +class GenericPad extends Gamepad { + /** + * Callback triggered when a button has been pressed + * @param callback Called when a button has been pressed + */ + onbuttondown(callback) { + this._onbuttondown = callback; + } + /** + * Callback triggered when a button has been released + * @param callback Called when a button has been released + */ + onbuttonup(callback) { + this._onbuttonup = callback; + } + /** + * Initializes the generic gamepad + * @param id The id of the generic gamepad + * @param index The index of the generic gamepad + * @param browserGamepad The browser gamepad + */ + constructor(id, index, browserGamepad) { + super(id, index, browserGamepad); + /** + * Observable triggered when a button has been pressed + */ + this.onButtonDownObservable = new Observable(); + /** + * Observable triggered when a button has been released + */ + this.onButtonUpObservable = new Observable(); + this.type = Gamepad.GENERIC; + this._buttons = new Array(browserGamepad.buttons.length); + } + _setButtonValue(newValue, currentValue, buttonIndex) { + if (newValue !== currentValue) { + if (newValue === 1) { + if (this._onbuttondown) { + this._onbuttondown(buttonIndex); + } + this.onButtonDownObservable.notifyObservers(buttonIndex); + } + if (newValue === 0) { + if (this._onbuttonup) { + this._onbuttonup(buttonIndex); + } + this.onButtonUpObservable.notifyObservers(buttonIndex); + } + } + return newValue; + } + /** + * Updates the generic gamepad + */ + update() { + super.update(); + for (let index = 0; index < this._buttons.length; index++) { + this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index); + } + } + /** + * Disposes the generic gamepad + */ + dispose() { + super.dispose(); + this.onButtonDownObservable.clear(); + this.onButtonUpObservable.clear(); + } +} + +/** + * Manage the gamepad inputs to control an arc rotate camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class ArcRotateCameraGamepadInput { + constructor() { + /** + * Defines the gamepad rotation sensibility. + * This is the threshold from when rotation starts to be accounted for to prevent jittering. + */ + this.gamepadRotationSensibility = 80; + /** + * Defines the gamepad move sensibility. + * This is the threshold from when moving starts to be accounted for for to prevent jittering. + */ + this.gamepadMoveSensibility = 40; + this._yAxisScale = 1.0; + } + /** + * Gets or sets a boolean indicating that Yaxis (for right stick) should be inverted + */ + get invertYAxis() { + return this._yAxisScale !== 1.0; + } + set invertYAxis(value) { + this._yAxisScale = value ? -1 : 1.0; + } + /** + * Attach the input controls to a specific dom element to get the input from. + */ + attachControl() { + const manager = this.camera.getScene().gamepadManager; + this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => { + if (gamepad.type !== Gamepad.POSE_ENABLED) { + // prioritize XBOX gamepads. + if (!this.gamepad || gamepad.type === Gamepad.XBOX) { + this.gamepad = gamepad; + } + } + }); + this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => { + if (this.gamepad === gamepad) { + this.gamepad = null; + } + }); + this.gamepad = manager.getGamepadByType(Gamepad.XBOX); + // if no xbox controller was found, but there are gamepad controllers, take the first one + if (!this.gamepad && manager.gamepads.length) { + this.gamepad = manager.gamepads[0]; + } + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); + this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); + this.gamepad = null; + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + if (this.gamepad) { + const camera = this.camera; + const rsValues = this.gamepad.rightStick; + if (rsValues) { + if (rsValues.x != 0) { + const normalizedRX = rsValues.x / this.gamepadRotationSensibility; + if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) { + camera.inertialAlphaOffset += normalizedRX; + } + } + if (rsValues.y != 0) { + const normalizedRY = (rsValues.y / this.gamepadRotationSensibility) * this._yAxisScale; + if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) { + camera.inertialBetaOffset += normalizedRY; + } + } + } + const lsValues = this.gamepad.leftStick; + if (lsValues && lsValues.y != 0) { + const normalizedLY = lsValues.y / this.gamepadMoveSensibility; + if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) { + this.camera.inertialRadiusOffset -= normalizedLY; + } + } + } + } + /** + * Gets the class name of the current intput. + * @returns the class name + */ + getClassName() { + return "ArcRotateCameraGamepadInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "gamepad"; + } +} +__decorate([ + serialize() +], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0); +__decorate([ + serialize() +], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); +CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput; + +/** + * Add orientation input support to the input manager. + * @returns the current input manager + */ +ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () { + this.add(new ArcRotateCameraVRDeviceOrientationInput()); + return this; +}; +/** + * Manage the device orientation inputs (gyroscope) to control an arc rotate camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class ArcRotateCameraVRDeviceOrientationInput { + /** + * Instantiate a new ArcRotateCameraVRDeviceOrientationInput. + */ + constructor() { + /** + * Defines a correction factor applied on the alpha value retrieved from the orientation events. + */ + this.alphaCorrection = 1; + /** + * Defines a correction factor applied on the gamma value retrieved from the orientation events. + */ + this.gammaCorrection = 1; + this._alpha = 0; + this._gamma = 0; + this._dirty = false; + this._deviceOrientationHandler = (evt) => this._onOrientationEvent(evt); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + this.camera.attachControl(noPreventDefault); + const hostWindow = this.camera.getScene().getEngine().getHostWindow(); + if (hostWindow) { + // check iOS 13+ support + if (typeof DeviceOrientationEvent !== "undefined" && typeof DeviceOrientationEvent.requestPermission === "function") { + DeviceOrientationEvent + .requestPermission() + .then((response) => { + if (response === "granted") { + hostWindow.addEventListener("deviceorientation", this._deviceOrientationHandler); + } + else { + Tools.Warn("Permission not granted."); + } + }) + .catch((error) => { + Tools.Error(error); + }); + } + else { + hostWindow.addEventListener("deviceorientation", this._deviceOrientationHandler); + } + } + } + /** + * @internal + */ + _onOrientationEvent(evt) { + if (evt.alpha !== null) { + this._alpha = (+evt.alpha | 0) * this.alphaCorrection; + } + if (evt.gamma !== null) { + this._gamma = (+evt.gamma | 0) * this.gammaCorrection; + } + this._dirty = true; + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + if (this._dirty) { + this._dirty = false; + if (this._gamma < 0) { + this._gamma = 180 + this._gamma; + } + this.camera.alpha = (((-this._alpha / 180.0) * Math.PI) % Math.PI) * 2; + this.camera.beta = (this._gamma / 180.0) * Math.PI; + } + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + window.removeEventListener("deviceorientation", this._deviceOrientationHandler); + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "ArcRotateCameraVRDeviceOrientationInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "VRDeviceOrientation"; + } +} +CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput; + +/** + * Listen to keyboard events to control the camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FlyCameraKeyboardInput { + constructor() { + /** + * The list of keyboard keys used to control the forward move of the camera. + */ + this.keysForward = [87]; + /** + * The list of keyboard keys used to control the backward move of the camera. + */ + this.keysBackward = [83]; + /** + * The list of keyboard keys used to control the forward move of the camera. + */ + this.keysUp = [69]; + /** + * The list of keyboard keys used to control the backward move of the camera. + */ + this.keysDown = [81]; + /** + * The list of keyboard keys used to control the right strafe move of the camera. + */ + this.keysRight = [68]; + /** + * The list of keyboard keys used to control the left strafe move of the camera. + */ + this.keysLeft = [65]; + this._keys = new Array(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + if (this._onCanvasBlurObserver) { + return; + } + this._scene = this.camera.getScene(); + this._engine = this._scene.getEngine(); + this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => { + this._keys.length = 0; + }); + this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => { + const evt = info.event; + if (info.type === KeyboardEventTypes.KEYDOWN) { + if (this.keysForward.indexOf(evt.keyCode) !== -1 || + this.keysBackward.indexOf(evt.keyCode) !== -1 || + this.keysUp.indexOf(evt.keyCode) !== -1 || + this.keysDown.indexOf(evt.keyCode) !== -1 || + this.keysLeft.indexOf(evt.keyCode) !== -1 || + this.keysRight.indexOf(evt.keyCode) !== -1) { + const index = this._keys.indexOf(evt.keyCode); + if (index === -1) { + this._keys.push(evt.keyCode); + } + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + else { + if (this.keysForward.indexOf(evt.keyCode) !== -1 || + this.keysBackward.indexOf(evt.keyCode) !== -1 || + this.keysUp.indexOf(evt.keyCode) !== -1 || + this.keysDown.indexOf(evt.keyCode) !== -1 || + this.keysLeft.indexOf(evt.keyCode) !== -1 || + this.keysRight.indexOf(evt.keyCode) !== -1) { + const index = this._keys.indexOf(evt.keyCode); + if (index >= 0) { + this._keys.splice(index, 1); + } + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + }); + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._scene) { + if (this._onKeyboardObserver) { + this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); + } + if (this._onCanvasBlurObserver) { + this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); + } + this._onKeyboardObserver = null; + this._onCanvasBlurObserver = null; + } + this._keys.length = 0; + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "FlyCameraKeyboardInput"; + } + /** + * @internal + */ + _onLostFocus() { + this._keys.length = 0; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "keyboard"; + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + if (this._onKeyboardObserver) { + const camera = this.camera; + // Keyboard + for (let index = 0; index < this._keys.length; index++) { + const keyCode = this._keys[index]; + const speed = camera._computeLocalCameraSpeed(); + if (this.keysForward.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, speed); + } + else if (this.keysBackward.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, -speed); + } + else if (this.keysUp.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, speed, 0); + } + else if (this.keysDown.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, -speed, 0); + } + else if (this.keysRight.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(speed, 0, 0); + } + else if (this.keysLeft.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(-speed, 0, 0); + } + if (camera.getScene().useRightHandedSystem) { + camera._localDirection.z *= -1; + } + camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); + Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); + camera.cameraDirection.addInPlace(camera._transformedDirection); + } + } + } +} +__decorate([ + serialize() +], FlyCameraKeyboardInput.prototype, "keysForward", void 0); +__decorate([ + serialize() +], FlyCameraKeyboardInput.prototype, "keysBackward", void 0); +__decorate([ + serialize() +], FlyCameraKeyboardInput.prototype, "keysUp", void 0); +__decorate([ + serialize() +], FlyCameraKeyboardInput.prototype, "keysDown", void 0); +__decorate([ + serialize() +], FlyCameraKeyboardInput.prototype, "keysRight", void 0); +__decorate([ + serialize() +], FlyCameraKeyboardInput.prototype, "keysLeft", void 0); +CameraInputTypes["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput; + +/** + * Listen to mouse events to control the camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FlyCameraMouseInput { + /** + * Listen to mouse events to control the camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ + constructor() { + /** + * Defines the buttons associated with the input to handle camera rotation. + */ + this.buttons = [0, 1, 2]; + /** + * Assign buttons for Yaw control. + */ + this.buttonsYaw = [-1, 0, 1]; + /** + * Assign buttons for Pitch control. + */ + this.buttonsPitch = [-1, 0, 1]; + /** + * Assign buttons for Roll control. + */ + this.buttonsRoll = [2]; + /** + * Detect if any button is being pressed while mouse is moved. + * -1 = Mouse locked. + * 0 = Left button. + * 1 = Middle Button. + * 2 = Right Button. + */ + this.activeButton = -1; + /** + * Defines the pointer's angular sensibility, to control the camera rotation speed. + * Higher values reduce its sensitivity. + */ + this.angularSensibility = 1000.0; + this._previousPosition = null; + } + /** + * Attach the mouse control to the HTML DOM element. + * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). + */ + attachControl(noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + this._noPreventDefault = noPreventDefault; + this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver((p) => { + this._pointerInput(p); + }, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE); + // Correct Roll by rate, if enabled. + this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(() => { + if (this.camera.rollCorrect) { + this.camera.restoreRoll(this.camera.rollCorrect); + } + }); + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._observer) { + this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); + this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver); + this._observer = null; + this._rollObserver = null; + this._previousPosition = null; + this._noPreventDefault = undefined; + } + } + /** + * Gets the class name of the current input. + * @returns the class name. + */ + getClassName() { + return "FlyCameraMouseInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input's friendly name. + */ + getSimpleName() { + return "mouse"; + } + // Track mouse movement, when the pointer is not locked. + _pointerInput(p) { + const e = p.event; + const camera = this.camera; + const engine = camera.getEngine(); + if (!this.touchEnabled && e.pointerType === "touch") { + return; + } + // Mouse is moved but an unknown mouse button is pressed. + if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) { + return; + } + const srcElement = e.target; + // Mouse down. + if (p.type === PointerEventTypes.POINTERDOWN) { + try { + srcElement?.setPointerCapture(e.pointerId); + } + catch (e) { + // Nothing to do with the error. Execution continues. + } + this._previousPosition = { + x: e.clientX, + y: e.clientY, + }; + this.activeButton = e.button; + if (!this._noPreventDefault) { + e.preventDefault(); + } + // This is required to move while pointer button is down + if (engine.isPointerLock) { + this._onMouseMove(p.event); + } + } + // Mouse up. + else if (p.type === PointerEventTypes.POINTERUP) { + try { + srcElement?.releasePointerCapture(e.pointerId); + } + catch (e) { + // Nothing to do with the error. Execution continues. + } + this.activeButton = -1; + this._previousPosition = null; + if (!this._noPreventDefault) { + e.preventDefault(); + } + } + // Mouse move. + else if (p.type === PointerEventTypes.POINTERMOVE) { + if (!this._previousPosition) { + if (engine.isPointerLock) { + this._onMouseMove(p.event); + } + return; + } + const offsetX = e.clientX - this._previousPosition.x; + const offsetY = e.clientY - this._previousPosition.y; + this._rotateCamera(offsetX, offsetY); + this._previousPosition = { + x: e.clientX, + y: e.clientY, + }; + if (!this._noPreventDefault) { + e.preventDefault(); + } + } + } + // Track mouse movement, when pointer is locked. + _onMouseMove(e) { + const camera = this.camera; + const engine = camera.getEngine(); + if (!engine.isPointerLock) { + return; + } + const offsetX = e.movementX; + const offsetY = e.movementY; + this._rotateCamera(offsetX, offsetY); + this._previousPosition = null; + if (!this._noPreventDefault) { + e.preventDefault(); + } + } + /** + * Rotate camera by mouse offset. + * @param offsetX + * @param offsetY + */ + _rotateCamera(offsetX, offsetY) { + const camera = this.camera; + const handednessMultiplier = camera._calculateHandednessMultiplier(); + offsetX *= handednessMultiplier; + const x = offsetX / this.angularSensibility; + const y = offsetY / this.angularSensibility; + // Initialize to current rotation. + const currentRotation = Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z); + let rotationChange; + // Pitch. + if (this.buttonsPitch.some((v) => { + return v === this.activeButton; + })) { + // Apply change in Radians to vector Angle. + rotationChange = Quaternion.RotationAxis(Axis.X, y); + // Apply Pitch to quaternion. + currentRotation.multiplyInPlace(rotationChange); + } + // Yaw. + if (this.buttonsYaw.some((v) => { + return v === this.activeButton; + })) { + // Apply change in Radians to vector Angle. + rotationChange = Quaternion.RotationAxis(Axis.Y, x); + // Apply Yaw to quaternion. + currentRotation.multiplyInPlace(rotationChange); + // Add Roll, if banked turning is enabled, within Roll limit. + const limit = camera.bankedTurnLimit + camera._trackRoll; // Defaults to 90° plus manual roll. + if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) { + const bankingDelta = camera.bankedTurnMultiplier * -x; + // Apply change in Radians to vector Angle. + rotationChange = Quaternion.RotationAxis(Axis.Z, bankingDelta); + // Apply Yaw to quaternion. + currentRotation.multiplyInPlace(rotationChange); + } + } + // Roll. + if (this.buttonsRoll.some((v) => { + return v === this.activeButton; + })) { + // Apply change in Radians to vector Angle. + rotationChange = Quaternion.RotationAxis(Axis.Z, -x); + // Track Rolling. + camera._trackRoll -= x; + // Apply Pitch to quaternion. + currentRotation.multiplyInPlace(rotationChange); + } + // Apply rotationQuaternion to Euler camera.rotation. + currentRotation.toEulerAnglesToRef(camera.rotation); + } +} +__decorate([ + serialize() +], FlyCameraMouseInput.prototype, "buttons", void 0); +__decorate([ + serialize() +], FlyCameraMouseInput.prototype, "angularSensibility", void 0); +CameraInputTypes["FlyCameraMouseInput"] = FlyCameraMouseInput; + +/** + * Manage the keyboard inputs to control the movement of a follow camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FollowCameraKeyboardMoveInput { + constructor() { + /** + * Defines the list of key codes associated with the up action (increase heightOffset) + */ + this.keysHeightOffsetIncr = [38]; + /** + * Defines the list of key codes associated with the down action (decrease heightOffset) + */ + this.keysHeightOffsetDecr = [40]; + /** + * Defines whether the Alt modifier key is required to move up/down (alter heightOffset) + */ + this.keysHeightOffsetModifierAlt = false; + /** + * Defines whether the Ctrl modifier key is required to move up/down (alter heightOffset) + */ + this.keysHeightOffsetModifierCtrl = false; + /** + * Defines whether the Shift modifier key is required to move up/down (alter heightOffset) + */ + this.keysHeightOffsetModifierShift = false; + /** + * Defines the list of key codes associated with the left action (increase rotationOffset) + */ + this.keysRotationOffsetIncr = [37]; + /** + * Defines the list of key codes associated with the right action (decrease rotationOffset) + */ + this.keysRotationOffsetDecr = [39]; + /** + * Defines whether the Alt modifier key is required to move left/right (alter rotationOffset) + */ + this.keysRotationOffsetModifierAlt = false; + /** + * Defines whether the Ctrl modifier key is required to move left/right (alter rotationOffset) + */ + this.keysRotationOffsetModifierCtrl = false; + /** + * Defines whether the Shift modifier key is required to move left/right (alter rotationOffset) + */ + this.keysRotationOffsetModifierShift = false; + /** + * Defines the list of key codes associated with the zoom-in action (decrease radius) + */ + this.keysRadiusIncr = [40]; + /** + * Defines the list of key codes associated with the zoom-out action (increase radius) + */ + this.keysRadiusDecr = [38]; + /** + * Defines whether the Alt modifier key is required to zoom in/out (alter radius value) + */ + this.keysRadiusModifierAlt = true; + /** + * Defines whether the Ctrl modifier key is required to zoom in/out (alter radius value) + */ + this.keysRadiusModifierCtrl = false; + /** + * Defines whether the Shift modifier key is required to zoom in/out (alter radius value) + */ + this.keysRadiusModifierShift = false; + /** + * Defines the rate of change of heightOffset. + */ + this.heightSensibility = 1; + /** + * Defines the rate of change of rotationOffset. + */ + this.rotationSensibility = 1; + /** + * Defines the rate of change of radius. + */ + this.radiusSensibility = 1; + this._keys = new Array(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + if (this._onCanvasBlurObserver) { + return; + } + this._scene = this.camera.getScene(); + this._engine = this._scene.getEngine(); + this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => { + this._keys.length = 0; + }); + this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => { + const evt = info.event; + if (!evt.metaKey) { + if (info.type === KeyboardEventTypes.KEYDOWN) { + this._ctrlPressed = evt.ctrlKey; + this._altPressed = evt.altKey; + this._shiftPressed = evt.shiftKey; + if (this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || + this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || + this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || + this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || + this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || + this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) { + const index = this._keys.indexOf(evt.keyCode); + if (index === -1) { + this._keys.push(evt.keyCode); + } + if (evt.preventDefault) { + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + } + else { + if (this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || + this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || + this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || + this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || + this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || + this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) { + const index = this._keys.indexOf(evt.keyCode); + if (index >= 0) { + this._keys.splice(index, 1); + } + if (evt.preventDefault) { + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + } + } + }); + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._scene) { + if (this._onKeyboardObserver) { + this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); + } + if (this._onCanvasBlurObserver) { + this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); + } + this._onKeyboardObserver = null; + this._onCanvasBlurObserver = null; + } + this._keys.length = 0; + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + if (this._onKeyboardObserver) { + this._keys.forEach((keyCode) => { + if (this.keysHeightOffsetIncr.indexOf(keyCode) !== -1 && this._modifierHeightOffset()) { + this.camera.heightOffset += this.heightSensibility; + } + else if (this.keysHeightOffsetDecr.indexOf(keyCode) !== -1 && this._modifierHeightOffset()) { + this.camera.heightOffset -= this.heightSensibility; + } + else if (this.keysRotationOffsetIncr.indexOf(keyCode) !== -1 && this._modifierRotationOffset()) { + this.camera.rotationOffset += this.rotationSensibility; + this.camera.rotationOffset %= 360; + } + else if (this.keysRotationOffsetDecr.indexOf(keyCode) !== -1 && this._modifierRotationOffset()) { + this.camera.rotationOffset -= this.rotationSensibility; + this.camera.rotationOffset %= 360; + } + else if (this.keysRadiusIncr.indexOf(keyCode) !== -1 && this._modifierRadius()) { + this.camera.radius += this.radiusSensibility; + } + else if (this.keysRadiusDecr.indexOf(keyCode) !== -1 && this._modifierRadius()) { + this.camera.radius -= this.radiusSensibility; + } + }); + } + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "FollowCameraKeyboardMoveInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "keyboard"; + } + /** + * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to + * allow modification of the heightOffset value. + * @returns true if modifier keys match + */ + _modifierHeightOffset() { + return (this.keysHeightOffsetModifierAlt === this._altPressed && + this.keysHeightOffsetModifierCtrl === this._ctrlPressed && + this.keysHeightOffsetModifierShift === this._shiftPressed); + } + /** + * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to + * allow modification of the rotationOffset value. + * @returns true if modifier keys match + */ + _modifierRotationOffset() { + return (this.keysRotationOffsetModifierAlt === this._altPressed && + this.keysRotationOffsetModifierCtrl === this._ctrlPressed && + this.keysRotationOffsetModifierShift === this._shiftPressed); + } + /** + * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to + * allow modification of the radius value. + * @returns true if modifier keys match + */ + _modifierRadius() { + return this.keysRadiusModifierAlt === this._altPressed && this.keysRadiusModifierCtrl === this._ctrlPressed && this.keysRadiusModifierShift === this._shiftPressed; + } +} +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetIncr", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetDecr", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierAlt", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierCtrl", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierShift", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetIncr", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetDecr", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierAlt", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierCtrl", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierShift", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysRadiusIncr", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysRadiusDecr", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierAlt", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierCtrl", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierShift", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "heightSensibility", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "rotationSensibility", void 0); +__decorate([ + serialize() +], FollowCameraKeyboardMoveInput.prototype, "radiusSensibility", void 0); +CameraInputTypes["FollowCameraKeyboardMoveInput"] = FollowCameraKeyboardMoveInput; + +/** + * Manage the mouse wheel inputs to control a follow camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FollowCameraMouseWheelInput { + constructor() { + /** + * Moue wheel controls zoom. (Mouse wheel modifies camera.radius value.) + */ + this.axisControlRadius = true; + /** + * Moue wheel controls height. (Mouse wheel modifies camera.heightOffset value.) + */ + this.axisControlHeight = false; + /** + * Moue wheel controls angle. (Mouse wheel modifies camera.rotationOffset value.) + */ + this.axisControlRotation = false; + /** + * Gets or Set the mouse wheel precision or how fast is the camera moves in + * relation to mouseWheel events. + */ + this.wheelPrecision = 3.0; + /** + * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0. + * It defines the percentage of current camera.radius to use as delta when wheel is used. + */ + this.wheelDeltaPercentage = 0; + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(noPreventDefault) { + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + this._wheel = (p) => { + // sanity check - this should be a PointerWheel event. + if (p.type !== PointerEventTypes.POINTERWHEEL) { + return; + } + const event = p.event; + let delta = 0; + const wheelDelta = Math.max(-1, Math.min(1, event.deltaY)); + if (this.wheelDeltaPercentage) { + if (+this.axisControlRadius + +this.axisControlHeight + +this.axisControlRotation) { + Logger.Warn("wheelDeltaPercentage only usable when mouse wheel " + + "controls ONE axis. " + + "Currently enabled: " + + "axisControlRadius: " + + this.axisControlRadius + + ", axisControlHeightOffset: " + + this.axisControlHeight + + ", axisControlRotationOffset: " + + this.axisControlRotation); + } + if (this.axisControlRadius) { + delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.radius; + } + else if (this.axisControlHeight) { + delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.heightOffset; + } + else if (this.axisControlRotation) { + delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.rotationOffset; + } + } + else { + delta = wheelDelta * this.wheelPrecision; + } + if (delta) { + if (this.axisControlRadius) { + this.camera.radius += delta; + } + else if (this.axisControlHeight) { + this.camera.heightOffset -= delta; + } + else if (this.axisControlRotation) { + this.camera.rotationOffset -= delta; + } + } + if (event.preventDefault) { + if (!noPreventDefault) { + event.preventDefault(); + } + } + }; + this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL); + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + if (this._observer) { + this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); + this._observer = null; + this._wheel = null; + } + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "ArcRotateCameraMouseWheelInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "mousewheel"; + } +} +__decorate([ + serialize() +], FollowCameraMouseWheelInput.prototype, "axisControlRadius", void 0); +__decorate([ + serialize() +], FollowCameraMouseWheelInput.prototype, "axisControlHeight", void 0); +__decorate([ + serialize() +], FollowCameraMouseWheelInput.prototype, "axisControlRotation", void 0); +__decorate([ + serialize() +], FollowCameraMouseWheelInput.prototype, "wheelPrecision", void 0); +__decorate([ + serialize() +], FollowCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0); +CameraInputTypes["FollowCameraMouseWheelInput"] = FollowCameraMouseWheelInput; + +/** + * Manage the pointers inputs to control an follow camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FollowCameraPointersInput extends BaseCameraPointersInput { + constructor() { + super(...arguments); + /** + * Defines the pointer angular sensibility along the X axis or how fast is + * the camera rotating. + * A negative number will reverse the axis direction. + */ + this.angularSensibilityX = 1; + /** + * Defines the pointer angular sensibility along the Y axis or how fast is + * the camera rotating. + * A negative number will reverse the axis direction. + */ + this.angularSensibilityY = 1; + /** + * Defines the pointer pinch precision or how fast is the camera zooming. + * A negative number will reverse the axis direction. + */ + this.pinchPrecision = 10000.0; + /** + * pinchDeltaPercentage will be used instead of pinchPrecision if different + * from 0. + * It defines the percentage of current camera.radius to use as delta when + * pinch zoom is used. + */ + this.pinchDeltaPercentage = 0; + /** + * Pointer X axis controls zoom. (X axis modifies camera.radius value.) + */ + this.axisXControlRadius = false; + /** + * Pointer X axis controls height. (X axis modifies camera.heightOffset value.) + */ + this.axisXControlHeight = false; + /** + * Pointer X axis controls angle. (X axis modifies camera.rotationOffset value.) + */ + this.axisXControlRotation = true; + /** + * Pointer Y axis controls zoom. (Y axis modifies camera.radius value.) + */ + this.axisYControlRadius = false; + /** + * Pointer Y axis controls height. (Y axis modifies camera.heightOffset value.) + */ + this.axisYControlHeight = true; + /** + * Pointer Y axis controls angle. (Y axis modifies camera.rotationOffset value.) + */ + this.axisYControlRotation = false; + /** + * Pinch controls zoom. (Pinch modifies camera.radius value.) + */ + this.axisPinchControlRadius = true; + /** + * Pinch controls height. (Pinch modifies camera.heightOffset value.) + */ + this.axisPinchControlHeight = false; + /** + * Pinch controls angle. (Pinch modifies camera.rotationOffset value.) + */ + this.axisPinchControlRotation = false; + /** + * Log error messages if basic misconfiguration has occurred. + */ + this.warningEnable = true; + /* Check for obvious misconfiguration. */ + this._warningCounter = 0; + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "FollowCameraPointersInput"; + } + onTouch(pointA, offsetX, offsetY) { + this._warning(); + if (this.axisXControlRotation) { + this.camera.rotationOffset += offsetX / this.angularSensibilityX; + } + else if (this.axisYControlRotation) { + this.camera.rotationOffset += offsetY / this.angularSensibilityX; + } + if (this.axisXControlHeight) { + this.camera.heightOffset += offsetX / this.angularSensibilityY; + } + else if (this.axisYControlHeight) { + this.camera.heightOffset += offsetY / this.angularSensibilityY; + } + if (this.axisXControlRadius) { + this.camera.radius -= offsetX / this.angularSensibilityY; + } + else if (this.axisYControlRadius) { + this.camera.radius -= offsetY / this.angularSensibilityY; + } + } + onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { + if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) { + // First time this method is called for new pinch. + // Next time this is called there will be a + // previousPinchSquaredDistance and pinchSquaredDistance to compare. + return; + } + if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) { + // Last time this method is called at the end of a pinch. + return; + } + let pinchDelta = (pinchSquaredDistance - previousPinchSquaredDistance) / ((this.pinchPrecision * (this.angularSensibilityX + this.angularSensibilityY)) / 2); + if (this.pinchDeltaPercentage) { + pinchDelta *= 0.01 * this.pinchDeltaPercentage; + if (this.axisPinchControlRotation) { + this.camera.rotationOffset += pinchDelta * this.camera.rotationOffset; + } + if (this.axisPinchControlHeight) { + this.camera.heightOffset += pinchDelta * this.camera.heightOffset; + } + if (this.axisPinchControlRadius) { + this.camera.radius -= pinchDelta * this.camera.radius; + } + } + else { + if (this.axisPinchControlRotation) { + this.camera.rotationOffset += pinchDelta; + } + if (this.axisPinchControlHeight) { + this.camera.heightOffset += pinchDelta; + } + if (this.axisPinchControlRadius) { + this.camera.radius -= pinchDelta; + } + } + } + _warning() { + if (!this.warningEnable || this._warningCounter++ % 100 !== 0) { + return; + } + const warn = "It probably only makes sense to control ONE camera " + "property with each pointer axis. Set 'warningEnable = false' " + "if you are sure. Currently enabled: "; + if (+this.axisXControlRotation + +this.axisXControlHeight + +this.axisXControlRadius <= 1) { + Logger.Warn(warn + + "axisXControlRotation: " + + this.axisXControlRotation + + ", axisXControlHeight: " + + this.axisXControlHeight + + ", axisXControlRadius: " + + this.axisXControlRadius); + } + if (+this.axisYControlRotation + +this.axisYControlHeight + +this.axisYControlRadius <= 1) { + Logger.Warn(warn + + "axisYControlRotation: " + + this.axisYControlRotation + + ", axisYControlHeight: " + + this.axisYControlHeight + + ", axisYControlRadius: " + + this.axisYControlRadius); + } + if (+this.axisPinchControlRotation + +this.axisPinchControlHeight + +this.axisPinchControlRadius <= 1) { + Logger.Warn(warn + + "axisPinchControlRotation: " + + this.axisPinchControlRotation + + ", axisPinchControlHeight: " + + this.axisPinchControlHeight + + ", axisPinchControlRadius: " + + this.axisPinchControlRadius); + } + } +} +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "angularSensibilityX", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "angularSensibilityY", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "pinchPrecision", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "pinchDeltaPercentage", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "axisXControlRadius", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "axisXControlHeight", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "axisXControlRotation", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "axisYControlRadius", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "axisYControlHeight", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "axisYControlRotation", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "axisPinchControlRadius", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "axisPinchControlHeight", void 0); +__decorate([ + serialize() +], FollowCameraPointersInput.prototype, "axisPinchControlRotation", void 0); +CameraInputTypes["FollowCameraPointersInput"] = FollowCameraPointersInput; + +/** + * Add orientation input support to the input manager. + * @param smoothFactor deviceOrientation smoothing. 0: no smoothing, 1: new data ignored, 0.9 recommended for smoothing + * @returns the current input manager + */ +FreeCameraInputsManager.prototype.addDeviceOrientation = function (smoothFactor) { + if (!this._deviceOrientationInput) { + this._deviceOrientationInput = new FreeCameraDeviceOrientationInput(); + if (smoothFactor) { + this._deviceOrientationInput.smoothFactor = smoothFactor; + } + this.add(this._deviceOrientationInput); + } + return this; +}; +/** + * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera. + * Screen rotation is taken into account. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FreeCameraDeviceOrientationInput { + /** + * Can be used to detect if a device orientation sensor is available on a device + * @param timeout amount of time in milliseconds to wait for a response from the sensor (default: infinite) + * @returns a promise that will resolve on orientation change + */ + static WaitForOrientationChangeAsync(timeout) { + return new Promise((res, rej) => { + let gotValue = false; + const eventHandler = () => { + window.removeEventListener("deviceorientation", eventHandler); + gotValue = true; + res(); + }; + // If timeout is populated reject the promise + if (timeout) { + setTimeout(() => { + if (!gotValue) { + window.removeEventListener("deviceorientation", eventHandler); + rej("WaitForOrientationChangeAsync timed out"); + } + }, timeout); + } + if (typeof DeviceOrientationEvent !== "undefined" && typeof DeviceOrientationEvent.requestPermission === "function") { + DeviceOrientationEvent + .requestPermission() + .then((response) => { + if (response == "granted") { + window.addEventListener("deviceorientation", eventHandler); + } + else { + Tools.Warn("Permission not granted."); + } + }) + .catch((error) => { + Tools.Error(error); + }); + } + else { + window.addEventListener("deviceorientation", eventHandler); + } + }); + } + /** + * Instantiates a new input + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ + constructor() { + this._screenOrientationAngle = 0; + this._screenQuaternion = new Quaternion(); + this._alpha = 0; + this._beta = 0; + this._gamma = 0; + /** alpha+beta+gamma smoothing. 0: no smoothing, 1: new data ignored, 0.9 recommended for smoothing */ + this.smoothFactor = 0; + /** + * @internal + */ + this._onDeviceOrientationChangedObservable = new Observable(); + this._orientationChanged = () => { + this._screenOrientationAngle = + window.orientation !== undefined + ? +window.orientation + : window.screen.orientation && window.screen.orientation["angle"] + ? window.screen.orientation.angle + : 0; + this._screenOrientationAngle = -Tools.ToRadians(this._screenOrientationAngle / 2); + this._screenQuaternion.copyFromFloats(0, Math.sin(this._screenOrientationAngle), 0, Math.cos(this._screenOrientationAngle)); + }; + this._deviceOrientation = (evt) => { + if (this.smoothFactor) { + this._alpha = evt.alpha !== null ? Tools.SmoothAngleChange(this._alpha, evt.alpha, this.smoothFactor) : 0; + this._beta = evt.beta !== null ? Tools.SmoothAngleChange(this._beta, evt.beta, this.smoothFactor) : 0; + this._gamma = evt.gamma !== null ? Tools.SmoothAngleChange(this._gamma, evt.gamma, this.smoothFactor) : 0; + } + else { + this._alpha = evt.alpha !== null ? evt.alpha : 0; + this._beta = evt.beta !== null ? evt.beta : 0; + this._gamma = evt.gamma !== null ? evt.gamma : 0; + } + if (evt.alpha !== null) { + this._onDeviceOrientationChangedObservable.notifyObservers(); + } + }; + this._constantTransform = new Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); + this._orientationChanged(); + } + /** + * Define the camera controlled by the input. + */ + get camera() { + return this._camera; + } + set camera(camera) { + this._camera = camera; + if (this._camera != null && !this._camera.rotationQuaternion) { + this._camera.rotationQuaternion = new Quaternion(); + } + if (this._camera) { + this._camera.onDisposeObservable.add(() => { + this._onDeviceOrientationChangedObservable.clear(); + }); + } + } + /** + * Attach the input controls to a specific dom element to get the input from. + */ + attachControl() { + const hostWindow = this.camera.getScene().getEngine().getHostWindow(); + if (hostWindow) { + const eventHandler = () => { + hostWindow.addEventListener("orientationchange", this._orientationChanged); + hostWindow.addEventListener("deviceorientation", this._deviceOrientation); + //In certain cases, the attach control is called AFTER orientation was changed, + //So this is needed. + this._orientationChanged(); + }; + if (typeof DeviceOrientationEvent !== "undefined" && typeof DeviceOrientationEvent.requestPermission === "function") { + DeviceOrientationEvent + .requestPermission() + .then((response) => { + if (response === "granted") { + eventHandler(); + } + else { + Tools.Warn("Permission not granted."); + } + }) + .catch((error) => { + Tools.Error(error); + }); + } + else { + eventHandler(); + } + } + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + window.removeEventListener("orientationchange", this._orientationChanged); + window.removeEventListener("deviceorientation", this._deviceOrientation); + this._alpha = 0; + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + // if no device orientation provided, don't update the rotation. + // Only testing against alpha under the assumption that orientation will never be so exact when set. + if (!this._alpha) { + return; + } + Quaternion.RotationYawPitchRollToRef(Tools.ToRadians(this._alpha), Tools.ToRadians(this._beta), -Tools.ToRadians(this._gamma), this.camera.rotationQuaternion); + this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion); + this._camera.rotationQuaternion.multiplyInPlace(this._constantTransform); + if (this._camera.getScene().useRightHandedSystem) { + this._camera.rotationQuaternion.y *= -1; + } + else { + this._camera.rotationQuaternion.z *= -1; + } + this._camera.rotationQuaternion.w *= -1; + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "FreeCameraDeviceOrientationInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "deviceOrientation"; + } +} +CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput; + +/** + * Manage the gamepad inputs to control a free camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FreeCameraGamepadInput { + constructor() { + /** + * Defines the gamepad rotation sensibility. + * This is the threshold from when rotation starts to be accounted for to prevent jittering. + */ + this.gamepadAngularSensibility = 200; + /** + * Defines the gamepad move sensibility. + * This is the threshold from when moving starts to be accounted for for to prevent jittering. + */ + this.gamepadMoveSensibility = 40; + /** + * Defines the minimum value at which any analog stick input is ignored. + * Note: This value should only be a value between 0 and 1. + */ + this.deadzoneDelta = 0.1; + this._yAxisScale = 1.0; + this._cameraTransform = Matrix.Identity(); + this._deltaTransform = Vector3.Zero(); + this._vector3 = Vector3.Zero(); + this._vector2 = Vector2.Zero(); + } + /** + * Gets or sets a boolean indicating that Yaxis (for right stick) should be inverted + */ + get invertYAxis() { + return this._yAxisScale !== 1.0; + } + set invertYAxis(value) { + this._yAxisScale = value ? -1 : 1.0; + } + /** + * Attach the input controls to a specific dom element to get the input from. + */ + attachControl() { + const manager = this.camera.getScene().gamepadManager; + this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => { + if (gamepad.type !== Gamepad.POSE_ENABLED) { + // prioritize XBOX gamepads. + if (!this.gamepad || gamepad.type === Gamepad.XBOX) { + this.gamepad = gamepad; + } + } + }); + this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => { + if (this.gamepad === gamepad) { + this.gamepad = null; + } + }); + // check if there are already other controllers connected + this.gamepad = manager.getGamepadByType(Gamepad.XBOX); + // if no xbox controller was found, but there are gamepad controllers, take the first one + if (!this.gamepad && manager.gamepads.length) { + this.gamepad = manager.gamepads[0]; + } + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); + this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); + this.gamepad = null; + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + if (this.gamepad && this.gamepad.leftStick) { + const camera = this.camera; + const lsValues = this.gamepad.leftStick; + if (this.gamepadMoveSensibility !== 0) { + lsValues.x = Math.abs(lsValues.x) > this.deadzoneDelta ? lsValues.x / this.gamepadMoveSensibility : 0; + lsValues.y = Math.abs(lsValues.y) > this.deadzoneDelta ? lsValues.y / this.gamepadMoveSensibility : 0; + } + let rsValues = this.gamepad.rightStick; + if (rsValues && this.gamepadAngularSensibility !== 0) { + rsValues.x = Math.abs(rsValues.x) > this.deadzoneDelta ? rsValues.x / this.gamepadAngularSensibility : 0; + rsValues.y = (Math.abs(rsValues.y) > this.deadzoneDelta ? rsValues.y / this.gamepadAngularSensibility : 0) * this._yAxisScale; + } + else { + rsValues = { x: 0, y: 0 }; + } + if (!camera.rotationQuaternion) { + Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform); + } + else { + camera.rotationQuaternion.toRotationMatrix(this._cameraTransform); + } + const speed = camera._computeLocalCameraSpeed() * 50.0; + this._vector3.copyFromFloats(lsValues.x * speed, 0, -lsValues.y * speed); + Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform); + camera.cameraDirection.addInPlace(this._deltaTransform); + this._vector2.copyFromFloats(rsValues.y, rsValues.x); + camera.cameraRotation.addInPlace(this._vector2); + } + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "FreeCameraGamepadInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "gamepad"; + } +} +__decorate([ + serialize() +], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0); +__decorate([ + serialize() +], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); +CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput; + +// Mainly based on these 2 articles : +// Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx +// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/ +/** + * Defines the potential axis of a Joystick + */ +var JoystickAxis; +(function (JoystickAxis) { + /** X axis */ + JoystickAxis[JoystickAxis["X"] = 0] = "X"; + /** Y axis */ + JoystickAxis[JoystickAxis["Y"] = 1] = "Y"; + /** Z axis */ + JoystickAxis[JoystickAxis["Z"] = 2] = "Z"; +})(JoystickAxis || (JoystickAxis = {})); +/** + * Class used to define virtual joystick (used in touch mode) + */ +class VirtualJoystick { + static _GetDefaultOptions() { + return { + puckSize: 40, + containerSize: 60, + color: "cyan", + puckImage: undefined, + containerImage: undefined, + position: undefined, + alwaysVisible: false, + limitToContainer: false, + }; + } + /** + * Creates a new virtual joystick + * @param leftJoystick defines that the joystick is for left hand (false by default) + * @param customizations Defines the options we want to customize the VirtualJoystick + */ + constructor(leftJoystick, customizations) { + this._released = false; + const options = { + ...VirtualJoystick._GetDefaultOptions(), + ...customizations, + }; + if (leftJoystick) { + this._leftJoystick = true; + } + else { + this._leftJoystick = false; + } + VirtualJoystick._GlobalJoystickIndex++; + // By default left & right arrow keys are moving the X + // and up & down keys are moving the Y + this._axisTargetedByLeftAndRight = 0 /* JoystickAxis.X */; + this._axisTargetedByUpAndDown = 1 /* JoystickAxis.Y */; + this.reverseLeftRight = false; + this.reverseUpDown = false; + // collections of pointers + this._touches = new StringDictionary(); + this.deltaPosition = Vector3.Zero(); + this._joystickSensibility = 25; + this._inversedSensibility = 1 / (this._joystickSensibility / 1000); + this._onResize = () => { + VirtualJoystick._VJCanvasWidth = window.innerWidth; + VirtualJoystick._VJCanvasHeight = window.innerHeight; + if (VirtualJoystick.Canvas) { + VirtualJoystick.Canvas.width = VirtualJoystick._VJCanvasWidth; + VirtualJoystick.Canvas.height = VirtualJoystick._VJCanvasHeight; + } + VirtualJoystick._HalfWidth = VirtualJoystick._VJCanvasWidth / 2; + }; + // injecting a canvas element on top of the canvas 3D game + if (!VirtualJoystick.Canvas) { + window.addEventListener("resize", this._onResize, false); + VirtualJoystick.Canvas = document.createElement("canvas"); + VirtualJoystick._VJCanvasWidth = window.innerWidth; + VirtualJoystick._VJCanvasHeight = window.innerHeight; + VirtualJoystick.Canvas.width = window.innerWidth; + VirtualJoystick.Canvas.height = window.innerHeight; + VirtualJoystick.Canvas.style.width = "100%"; + VirtualJoystick.Canvas.style.height = "100%"; + VirtualJoystick.Canvas.style.position = "absolute"; + VirtualJoystick.Canvas.style.backgroundColor = "transparent"; + VirtualJoystick.Canvas.style.top = "0px"; + VirtualJoystick.Canvas.style.left = "0px"; + VirtualJoystick.Canvas.style.zIndex = "5"; + VirtualJoystick.Canvas.style.touchAction = "none"; // fix https://forum.babylonjs.com/t/virtualjoystick-needs-to-set-style-touch-action-none-explicitly/9562 + // Support for jQuery PEP polyfill + VirtualJoystick.Canvas.setAttribute("touch-action", "none"); + const context = VirtualJoystick.Canvas.getContext("2d"); + if (!context) { + throw new Error("Unable to create canvas for virtual joystick"); + } + VirtualJoystick._VJCanvasContext = context; + VirtualJoystick._VJCanvasContext.strokeStyle = "#ffffff"; + VirtualJoystick._VJCanvasContext.lineWidth = 2; + document.body.appendChild(VirtualJoystick.Canvas); + } + VirtualJoystick._HalfWidth = VirtualJoystick.Canvas.width / 2; + this.pressed = false; + this.limitToContainer = options.limitToContainer; + // default joystick color + this._joystickColor = options.color; + // default joystick size + this.containerSize = options.containerSize; + this.puckSize = options.puckSize; + if (options.position) { + this.setPosition(options.position.x, options.position.y); + } + if (options.puckImage) { + this.setPuckImage(options.puckImage); + } + if (options.containerImage) { + this.setContainerImage(options.containerImage); + } + if (options.alwaysVisible) { + VirtualJoystick._AlwaysVisibleSticks++; + } + // must come after position potentially set + this.alwaysVisible = options.alwaysVisible; + this._joystickPointerId = -1; + // current joystick position + this._joystickPointerPos = new Vector2(0, 0); + this._joystickPreviousPointerPos = new Vector2(0, 0); + // origin joystick position + this._joystickPointerStartPos = new Vector2(0, 0); + this._deltaJoystickVector = new Vector2(0, 0); + this._onPointerDownHandlerRef = (evt) => { + this._onPointerDown(evt); + }; + this._onPointerMoveHandlerRef = (evt) => { + this._onPointerMove(evt); + }; + this._onPointerUpHandlerRef = (evt) => { + this._onPointerUp(evt); + }; + VirtualJoystick.Canvas.addEventListener("pointerdown", this._onPointerDownHandlerRef, false); + VirtualJoystick.Canvas.addEventListener("pointermove", this._onPointerMoveHandlerRef, false); + VirtualJoystick.Canvas.addEventListener("pointerup", this._onPointerUpHandlerRef, false); + VirtualJoystick.Canvas.addEventListener("pointerout", this._onPointerUpHandlerRef, false); + VirtualJoystick.Canvas.addEventListener("pointercancel", this._onPointerUpHandlerRef, false); + VirtualJoystick.Canvas.addEventListener("contextmenu", (evt) => { + evt.preventDefault(); // Disables system menu + }, false); + requestAnimationFrame(() => { + this._drawVirtualJoystick(); + }); + } + /** + * Defines joystick sensibility (ie. the ratio between a physical move and virtual joystick position change) + * @param newJoystickSensibility defines the new sensibility + */ + setJoystickSensibility(newJoystickSensibility) { + this._joystickSensibility = newJoystickSensibility; + this._inversedSensibility = 1 / (this._joystickSensibility / 1000); + } + _onPointerDown(e) { + let positionOnScreenCondition; + e.preventDefault(); + if (this._leftJoystick === true) { + positionOnScreenCondition = e.clientX < VirtualJoystick._HalfWidth; + } + else { + positionOnScreenCondition = e.clientX > VirtualJoystick._HalfWidth; + } + if (positionOnScreenCondition && this._joystickPointerId < 0) { + // First contact will be dedicated to the virtual joystick + this._joystickPointerId = e.pointerId; + if (this._joystickPosition) { + this._joystickPointerStartPos = this._joystickPosition.clone(); + this._joystickPointerPos = this._joystickPosition.clone(); + this._joystickPreviousPointerPos = this._joystickPosition.clone(); + // in case the user only clicks down && doesn't move: + // this ensures the delta is properly set + this._onPointerMove(e); + } + else { + this._joystickPointerStartPos.x = e.clientX; + this._joystickPointerStartPos.y = e.clientY; + this._joystickPointerPos = this._joystickPointerStartPos.clone(); + this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone(); + } + this._deltaJoystickVector.x = 0; + this._deltaJoystickVector.y = 0; + this.pressed = true; + this._touches.add(e.pointerId.toString(), e); + } + else { + // You can only trigger the action buttons with a joystick declared + if (VirtualJoystick._GlobalJoystickIndex < 2 && this._action) { + this._action(); + this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY }); + } + } + } + _onPointerMove(e) { + // If the current pointer is the one associated to the joystick (first touch contact) + if (this._joystickPointerId == e.pointerId) { + // limit to container if need be + if (this.limitToContainer) { + const vector = new Vector2(e.clientX - this._joystickPointerStartPos.x, e.clientY - this._joystickPointerStartPos.y); + const distance = vector.length(); + if (distance > this.containerSize) { + vector.scaleInPlace(this.containerSize / distance); + } + this._joystickPointerPos.x = this._joystickPointerStartPos.x + vector.x; + this._joystickPointerPos.y = this._joystickPointerStartPos.y + vector.y; + } + else { + this._joystickPointerPos.x = e.clientX; + this._joystickPointerPos.y = e.clientY; + } + // create delta vector + this._deltaJoystickVector = this._joystickPointerPos.clone(); + this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos); + // if a joystick is always visible, there will be clipping issues if + // you drag the puck from one over the container of the other + if (0 < VirtualJoystick._AlwaysVisibleSticks) { + if (this._leftJoystick) { + this._joystickPointerPos.x = Math.min(VirtualJoystick._HalfWidth, this._joystickPointerPos.x); + } + else { + this._joystickPointerPos.x = Math.max(VirtualJoystick._HalfWidth, this._joystickPointerPos.x); + } + } + const directionLeftRight = this.reverseLeftRight ? -1 : 1; + const deltaJoystickX = (directionLeftRight * this._deltaJoystickVector.x) / this._inversedSensibility; + switch (this._axisTargetedByLeftAndRight) { + case 0 /* JoystickAxis.X */: + this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX)); + break; + case 1 /* JoystickAxis.Y */: + this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX)); + break; + case 2 /* JoystickAxis.Z */: + this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX)); + break; + } + const directionUpDown = this.reverseUpDown ? 1 : -1; + const deltaJoystickY = (directionUpDown * this._deltaJoystickVector.y) / this._inversedSensibility; + switch (this._axisTargetedByUpAndDown) { + case 0 /* JoystickAxis.X */: + this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY)); + break; + case 1 /* JoystickAxis.Y */: + this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY)); + break; + case 2 /* JoystickAxis.Z */: + this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY)); + break; + } + } + else { + const data = this._touches.get(e.pointerId.toString()); + if (data) { + data.x = e.clientX; + data.y = e.clientY; + } + } + } + _onPointerUp(e) { + if (this._joystickPointerId == e.pointerId) { + this._clearPreviousDraw(); + this._joystickPointerId = -1; + this.pressed = false; + } + else { + const touch = this._touches.get(e.pointerId.toString()); + if (touch) { + VirtualJoystick._VJCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88); + } + } + this._deltaJoystickVector.x = 0; + this._deltaJoystickVector.y = 0; + this._touches.remove(e.pointerId.toString()); + } + /** + * Change the color of the virtual joystick + * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000") + */ + setJoystickColor(newColor) { + this._joystickColor = newColor; + } + /** + * Size of the joystick's container + */ + set containerSize(newSize) { + this._joystickContainerSize = newSize; + this._clearContainerSize = ~~(this._joystickContainerSize * 2.1); + this._clearContainerSizeOffset = ~~(this._clearContainerSize / 2); + } + get containerSize() { + return this._joystickContainerSize; + } + /** + * Size of the joystick's puck + */ + set puckSize(newSize) { + this._joystickPuckSize = newSize; + this._clearPuckSize = ~~(this._joystickPuckSize * 2.1); + this._clearPuckSizeOffset = ~~(this._clearPuckSize / 2); + } + get puckSize() { + return this._joystickPuckSize; + } + /** + * Clears the set position of the joystick + */ + clearPosition() { + this.alwaysVisible = false; + this._joystickPosition = null; + } + /** + * Defines whether or not the joystick container is always visible + */ + set alwaysVisible(value) { + if (this._alwaysVisible === value) { + return; + } + if (value && this._joystickPosition) { + VirtualJoystick._AlwaysVisibleSticks++; + this._alwaysVisible = true; + } + else { + VirtualJoystick._AlwaysVisibleSticks--; + this._alwaysVisible = false; + } + } + get alwaysVisible() { + return this._alwaysVisible; + } + /** + * Sets the constant position of the Joystick container + * @param x X axis coordinate + * @param y Y axis coordinate + */ + setPosition(x, y) { + // just in case position is moved while the container is visible + if (this._joystickPointerStartPos) { + this._clearPreviousDraw(); + } + this._joystickPosition = new Vector2(x, y); + } + /** + * Defines a callback to call when the joystick is touched + * @param action defines the callback + */ + setActionOnTouch(action) { + this._action = action; + } + /** + * Defines which axis you'd like to control for left & right + * @param axis defines the axis to use + */ + setAxisForLeftRight(axis) { + switch (axis) { + case 0 /* JoystickAxis.X */: + case 1 /* JoystickAxis.Y */: + case 2 /* JoystickAxis.Z */: + this._axisTargetedByLeftAndRight = axis; + break; + default: + this._axisTargetedByLeftAndRight = 0 /* JoystickAxis.X */; + break; + } + } + /** + * Defines which axis you'd like to control for up & down + * @param axis defines the axis to use + */ + setAxisForUpDown(axis) { + switch (axis) { + case 0 /* JoystickAxis.X */: + case 1 /* JoystickAxis.Y */: + case 2 /* JoystickAxis.Z */: + this._axisTargetedByUpAndDown = axis; + break; + default: + this._axisTargetedByUpAndDown = 1 /* JoystickAxis.Y */; + break; + } + } + /** + * Clears the canvas from the previous puck / container draw + */ + _clearPreviousDraw() { + const jp = this._joystickPosition || this._joystickPointerStartPos; + // clear container pixels + VirtualJoystick._VJCanvasContext.clearRect(jp.x - this._clearContainerSizeOffset, jp.y - this._clearContainerSizeOffset, this._clearContainerSize, this._clearContainerSize); + // clear puck pixels + 1 pixel for the change made before it moved + VirtualJoystick._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x - this._clearPuckSizeOffset - 1, this._joystickPreviousPointerPos.y - this._clearPuckSizeOffset - 1, this._clearPuckSize + 2, this._clearPuckSize + 2); + } + /** + * Loads `urlPath` to be used for the container's image + * @param urlPath defines the urlPath of an image to use + */ + setContainerImage(urlPath) { + const image = new Image(); + image.src = urlPath; + image.onload = () => (this._containerImage = image); + } + /** + * Loads `urlPath` to be used for the puck's image + * @param urlPath defines the urlPath of an image to use + */ + setPuckImage(urlPath) { + const image = new Image(); + image.src = urlPath; + image.onload = () => (this._puckImage = image); + } + /** + * Draws the Virtual Joystick's container + */ + _drawContainer() { + const jp = this._joystickPosition || this._joystickPointerStartPos; + this._clearPreviousDraw(); + if (this._containerImage) { + VirtualJoystick._VJCanvasContext.drawImage(this._containerImage, jp.x - this.containerSize, jp.y - this.containerSize, this.containerSize * 2, this.containerSize * 2); + } + else { + // outer container + VirtualJoystick._VJCanvasContext.beginPath(); + VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor; + VirtualJoystick._VJCanvasContext.lineWidth = 2; + VirtualJoystick._VJCanvasContext.arc(jp.x, jp.y, this.containerSize, 0, Math.PI * 2, true); + VirtualJoystick._VJCanvasContext.stroke(); + VirtualJoystick._VJCanvasContext.closePath(); + // inner container + VirtualJoystick._VJCanvasContext.beginPath(); + VirtualJoystick._VJCanvasContext.lineWidth = 6; + VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor; + VirtualJoystick._VJCanvasContext.arc(jp.x, jp.y, this.puckSize, 0, Math.PI * 2, true); + VirtualJoystick._VJCanvasContext.stroke(); + VirtualJoystick._VJCanvasContext.closePath(); + } + } + /** + * Draws the Virtual Joystick's puck + */ + _drawPuck() { + if (this._puckImage) { + VirtualJoystick._VJCanvasContext.drawImage(this._puckImage, this._joystickPointerPos.x - this.puckSize, this._joystickPointerPos.y - this.puckSize, this.puckSize * 2, this.puckSize * 2); + } + else { + VirtualJoystick._VJCanvasContext.beginPath(); + VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor; + VirtualJoystick._VJCanvasContext.lineWidth = 2; + VirtualJoystick._VJCanvasContext.arc(this._joystickPointerPos.x, this._joystickPointerPos.y, this.puckSize, 0, Math.PI * 2, true); + VirtualJoystick._VJCanvasContext.stroke(); + VirtualJoystick._VJCanvasContext.closePath(); + } + } + _drawVirtualJoystick() { + // canvas released? don't continue iterating + if (this._released) { + return; + } + if (this.alwaysVisible) { + this._drawContainer(); + } + if (this.pressed) { + this._touches.forEach((key, touch) => { + if (touch.pointerId === this._joystickPointerId) { + if (!this.alwaysVisible) { + this._drawContainer(); + } + this._drawPuck(); + // store current pointer for next clear + this._joystickPreviousPointerPos = this._joystickPointerPos.clone(); + } + else { + VirtualJoystick._VJCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88); + VirtualJoystick._VJCanvasContext.beginPath(); + VirtualJoystick._VJCanvasContext.fillStyle = "white"; + VirtualJoystick._VJCanvasContext.beginPath(); + VirtualJoystick._VJCanvasContext.strokeStyle = "red"; + VirtualJoystick._VJCanvasContext.lineWidth = 6; + VirtualJoystick._VJCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true); + VirtualJoystick._VJCanvasContext.stroke(); + VirtualJoystick._VJCanvasContext.closePath(); + touch.prevX = touch.x; + touch.prevY = touch.y; + } + }); + } + requestAnimationFrame(() => { + this._drawVirtualJoystick(); + }); + } + /** + * Release internal HTML canvas + */ + releaseCanvas() { + if (VirtualJoystick.Canvas) { + VirtualJoystick.Canvas.removeEventListener("pointerdown", this._onPointerDownHandlerRef); + VirtualJoystick.Canvas.removeEventListener("pointermove", this._onPointerMoveHandlerRef); + VirtualJoystick.Canvas.removeEventListener("pointerup", this._onPointerUpHandlerRef); + VirtualJoystick.Canvas.removeEventListener("pointerout", this._onPointerUpHandlerRef); + VirtualJoystick.Canvas.removeEventListener("pointercancel", this._onPointerUpHandlerRef); + window.removeEventListener("resize", this._onResize); + document.body.removeChild(VirtualJoystick.Canvas); + VirtualJoystick.Canvas = null; + } + this._released = true; + } +} +// Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas +VirtualJoystick._GlobalJoystickIndex = 0; +VirtualJoystick._AlwaysVisibleSticks = 0; + +/** + * Add virtual joystick input support to the input manager. + * @returns the current input manager + */ +FreeCameraInputsManager.prototype.addVirtualJoystick = function () { + this.add(new FreeCameraVirtualJoystickInput()); + return this; +}; +/** + * Manage the Virtual Joystick inputs to control the movement of a free camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FreeCameraVirtualJoystickInput { + /** + * Gets the left stick of the virtual joystick. + * @returns The virtual Joystick + */ + getLeftJoystick() { + return this._leftjoystick; + } + /** + * Gets the right stick of the virtual joystick. + * @returns The virtual Joystick + */ + getRightJoystick() { + return this._rightjoystick; + } + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + checkInputs() { + if (this._leftjoystick) { + const camera = this.camera; + const speed = camera._computeLocalCameraSpeed() * 50; + const cameraTransform = Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0); + const deltaTransform = Vector3.TransformCoordinates(new Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform); + camera.cameraDirection = camera.cameraDirection.add(deltaTransform); + camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition); + if (!this._leftjoystick.pressed) { + this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9); + } + if (!this._rightjoystick.pressed) { + this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9); + } + } + } + /** + * Attach the input controls to a specific dom element to get the input from. + */ + attachControl() { + this._leftjoystick = new VirtualJoystick(true); + this._leftjoystick.setAxisForUpDown(2 /* JoystickAxis.Z */); + this._leftjoystick.setAxisForLeftRight(0 /* JoystickAxis.X */); + this._leftjoystick.setJoystickSensibility(0.15); + this._rightjoystick = new VirtualJoystick(false); + this._rightjoystick.setAxisForUpDown(0 /* JoystickAxis.X */); + this._rightjoystick.setAxisForLeftRight(1 /* JoystickAxis.Y */); + this._rightjoystick.reverseUpDown = true; + this._rightjoystick.setJoystickSensibility(0.05); + this._rightjoystick.setJoystickColor("yellow"); + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + this._leftjoystick.releaseCanvas(); + this._rightjoystick.releaseCanvas(); + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + getClassName() { + return "FreeCameraVirtualJoystickInput"; + } + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + getSimpleName() { + return "virtualJoystick"; + } +} +CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput; + +Node$2.AddNodeConstructor("TouchCamera", (name, scene) => { + return () => new TouchCamera(name, Vector3.Zero(), scene); +}); +/** + * This represents a FPS type of camera controlled by touch. + * This is like a universal camera minus the Gamepad controls. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera + */ +class TouchCamera extends FreeCamera { + /** + * Defines the touch sensibility for rotation. + * The higher the faster. + */ + get touchAngularSensibility() { + const touch = this.inputs.attached["touch"]; + if (touch) { + return touch.touchAngularSensibility; + } + return 0; + } + set touchAngularSensibility(value) { + const touch = this.inputs.attached["touch"]; + if (touch) { + touch.touchAngularSensibility = value; + } + } + /** + * Defines the touch sensibility for move. + * The higher the faster. + */ + get touchMoveSensibility() { + const touch = this.inputs.attached["touch"]; + if (touch) { + return touch.touchMoveSensibility; + } + return 0; + } + set touchMoveSensibility(value) { + const touch = this.inputs.attached["touch"]; + if (touch) { + touch.touchMoveSensibility = value; + } + } + /** + * Instantiates a new touch camera. + * This represents a FPS type of camera controlled by touch. + * This is like a universal camera minus the Gamepad controls. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera + * @param name Define the name of the camera in the scene + * @param position Define the start position of the camera in the scene + * @param scene Define the scene the camera belongs to + */ + constructor(name, position, scene) { + super(name, position, scene); + this.inputs.addTouch(); + this._setupInputs(); + } + /** + * Gets the current object class name. + * @returns the class name + */ + getClassName() { + return "TouchCamera"; + } + /** @internal */ + _setupInputs() { + const touch = this.inputs.attached["touch"]; + const mouse = this.inputs.attached["mouse"]; + if (mouse) { + // enable touch in mouse input if touch module is not enabled + mouse.touchEnabled = !touch; + } + else { + // allow mouse in touch input if mouse module is not available + touch.allowMouse = !mouse; + } + } +} + +Node$2.AddNodeConstructor("DeviceOrientationCamera", (name, scene) => { + return () => new DeviceOrientationCamera(name, Vector3.Zero(), scene); +}); +// We're mainly based on the logic defined into the FreeCamera code +/** + * This is a camera specifically designed to react to device orientation events such as a modern mobile device + * being tilted forward or back and left or right. + */ +class DeviceOrientationCamera extends FreeCamera { + /** + * Creates a new device orientation camera + * @param name The name of the camera + * @param position The start position camera + * @param scene The scene the camera belongs to + */ + constructor(name, position, scene) { + super(name, position, scene); + this._tmpDragQuaternion = new Quaternion(); + this._disablePointerInputWhenUsingDeviceOrientation = true; + this._dragFactor = 0; + this._quaternionCache = new Quaternion(); + this.inputs.addDeviceOrientation(); + // When the orientation sensor fires it's first event, disable mouse input + if (this.inputs._deviceOrientationInput) { + this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(() => { + if (this._disablePointerInputWhenUsingDeviceOrientation) { + if (this.inputs._mouseInput) { + this.inputs._mouseInput._allowCameraRotation = false; + this.inputs._mouseInput.onPointerMovedObservable.add((e) => { + if (this._dragFactor != 0) { + if (!this._initialQuaternion) { + this._initialQuaternion = new Quaternion(); + } + // Rotate the initial space around the y axis to allow users to "turn around" via touch/mouse + Quaternion.FromEulerAnglesToRef(0, e.offsetX * this._dragFactor, 0, this._tmpDragQuaternion); + this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion, this._initialQuaternion); + } + }); + } + } + }); + } + } + /** + * Gets or sets a boolean indicating that pointer input must be disabled on first orientation sensor update (Default: true) + */ + get disablePointerInputWhenUsingDeviceOrientation() { + return this._disablePointerInputWhenUsingDeviceOrientation; + } + set disablePointerInputWhenUsingDeviceOrientation(value) { + this._disablePointerInputWhenUsingDeviceOrientation = value; + } + /** + * Enabled turning on the y axis when the orientation sensor is active + * @param dragFactor the factor that controls the turn speed (default: 1/300) + */ + enableHorizontalDragging(dragFactor = 1 / 300) { + this._dragFactor = dragFactor; + } + /** + * Gets the current instance class name ("DeviceOrientationCamera"). + * This helps avoiding instanceof at run time. + * @returns the class name + */ + getClassName() { + return "DeviceOrientationCamera"; + } + /** + * @internal + * Checks and applies the current values of the inputs to the camera. (Internal use only) + */ + _checkInputs() { + super._checkInputs(); + this._quaternionCache.copyFrom(this.rotationQuaternion); + if (this._initialQuaternion) { + this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); + } + } + /** + * Reset the camera to its default orientation on the specified axis only. + * @param axis The axis to reset + */ + resetToCurrentRotation(axis = Axis.Y) { + //can only work if this camera has a rotation quaternion already. + if (!this.rotationQuaternion) { + return; + } + if (!this._initialQuaternion) { + this._initialQuaternion = new Quaternion(); + } + this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion); + ["x", "y", "z"].forEach((axisName) => { + if (!axis[axisName]) { + this._initialQuaternion[axisName] = 0; + } + else { + this._initialQuaternion[axisName] *= -1; + } + }); + this._initialQuaternion.normalize(); + //force rotation update + this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); + } +} + +/** + * Default Inputs manager for the FlyCamera. + * It groups all the default supported inputs for ease of use. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FlyCameraInputsManager extends CameraInputsManager { + /** + * Instantiates a new FlyCameraInputsManager. + * @param camera Defines the camera the inputs belong to. + */ + constructor(camera) { + super(camera); + } + /** + * Add keyboard input support to the input manager. + * @returns the new FlyCameraKeyboardMoveInput(). + */ + addKeyboard() { + this.add(new FlyCameraKeyboardInput()); + return this; + } + /** + * Add mouse input support to the input manager. + * @returns the new FlyCameraMouseInput(). + */ + addMouse() { + this.add(new FlyCameraMouseInput()); + return this; + } +} + +/** + * This is a flying camera, designed for 3D movement and rotation in all directions, + * such as in a 3D Space Shooter or a Flight Simulator. + */ +class FlyCamera extends TargetCamera { + /** + * Gets the input sensibility for mouse input. + * Higher values reduce sensitivity. + */ + get angularSensibility() { + const mouse = this.inputs.attached["mouse"]; + if (mouse) { + return mouse.angularSensibility; + } + return 0; + } + /** + * Sets the input sensibility for a mouse input. + * Higher values reduce sensitivity. + */ + set angularSensibility(value) { + const mouse = this.inputs.attached["mouse"]; + if (mouse) { + mouse.angularSensibility = value; + } + } + /** + * Get the keys for camera movement forward. + */ + get keysForward() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysForward; + } + return []; + } + /** + * Set the keys for camera movement forward. + */ + set keysForward(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysForward = value; + } + } + /** + * Get the keys for camera movement backward. + */ + get keysBackward() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysBackward; + } + return []; + } + set keysBackward(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysBackward = value; + } + } + /** + * Get the keys for camera movement up. + */ + get keysUp() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysUp; + } + return []; + } + /** + * Set the keys for camera movement up. + */ + set keysUp(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysUp = value; + } + } + /** + * Get the keys for camera movement down. + */ + get keysDown() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysDown; + } + return []; + } + /** + * Set the keys for camera movement down. + */ + set keysDown(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysDown = value; + } + } + /** + * Get the keys for camera movement left. + */ + get keysLeft() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysLeft; + } + return []; + } + /** + * Set the keys for camera movement left. + */ + set keysLeft(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysLeft = value; + } + } + /** + * Set the keys for camera movement right. + */ + get keysRight() { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysRight; + } + return []; + } + /** + * Set the keys for camera movement right. + */ + set keysRight(value) { + const keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysRight = value; + } + } + /** + * Instantiates a FlyCamera. + * This is a flying camera, designed for 3D movement and rotation in all directions, + * such as in a 3D Space Shooter or a Flight Simulator. + * @param name Define the name of the camera in the scene. + * @param position Define the starting position of the camera in the scene. + * @param scene Define the scene the camera belongs to. + * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active, if no other camera has been defined as active. + */ + constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) { + super(name, position, scene, setActiveOnSceneIfNoneActive); + /** + * Define the collision ellipsoid of the camera. + * This is helpful for simulating a camera body, like a player's body. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera + */ + this.ellipsoid = new Vector3(1, 1, 1); + /** + * Define an offset for the position of the ellipsoid around the camera. + * This can be helpful if the camera is attached away from the player's body center, + * such as at its head. + */ + this.ellipsoidOffset = new Vector3(0, 0, 0); + /** + * Enable or disable collisions of the camera with the rest of the scene objects. + */ + this.checkCollisions = false; + /** + * Enable or disable gravity on the camera. + */ + this.applyGravity = false; + /** + * Define the current direction the camera is moving to. + */ + this.cameraDirection = Vector3.Zero(); + /** + * Track Roll to maintain the wanted Rolling when looking around. + */ + this._trackRoll = 0; + /** + * Slowly correct the Roll to its original value after a Pitch+Yaw rotation. + */ + this.rollCorrect = 100; + /** + * Mimic a banked turn, Rolling the camera when Yawing. + * It's recommended to use rollCorrect = 10 for faster banking correction. + */ + this.bankedTurn = false; + /** + * Limit in radians for how much Roll banking will add. (Default: 90°) + */ + this.bankedTurnLimit = Math.PI / 2; + /** + * Value of 0 disables the banked Roll. + * Value of 1 is equal to the Yaw angle in radians. + */ + this.bankedTurnMultiplier = 1; + this._needMoveForGravity = false; + this._oldPosition = Vector3.Zero(); + this._diffPosition = Vector3.Zero(); + this._newPosition = Vector3.Zero(); + // Collisions. + this._collisionMask = -1; + /** + * @internal + */ + this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => { + const updatePosition = (newPos) => { + this._newPosition.copyFrom(newPos); + this._newPosition.subtractToRef(this._oldPosition, this._diffPosition); + if (this._diffPosition.length() > AbstractEngine.CollisionsEpsilon) { + this.position.addInPlace(this._diffPosition); + if (this.onCollide && collidedMesh) { + this.onCollide(collidedMesh); + } + } + }; + updatePosition(newPosition); + }; + this.inputs = new FlyCameraInputsManager(this); + this.inputs.addKeyboard().addMouse(); + } + /** + * Attached controls to the current camera. + * @param ignored defines an ignored parameter kept for backward compatibility. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(ignored, noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + this.inputs.attachElement(noPreventDefault); + } + /** + * Detach a control from the HTML DOM element. + * The camera will stop reacting to that input. + */ + detachControl() { + this.inputs.detachElement(); + this.cameraDirection = new Vector3(0, 0, 0); + } + /** + * Get the mask that the camera ignores in collision events. + */ + get collisionMask() { + return this._collisionMask; + } + /** + * Set the mask that the camera ignores in collision events. + */ + set collisionMask(mask) { + this._collisionMask = !isNaN(mask) ? mask : -1; + } + /** + * @internal + */ + _collideWithWorld(displacement) { + let globalPosition; + if (this.parent) { + globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix()); + } + else { + globalPosition = this.position; + } + globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition); + this._oldPosition.addInPlace(this.ellipsoidOffset); + const coordinator = this.getScene().collisionCoordinator; + if (!this._collider) { + this._collider = coordinator.createCollider(); + } + this._collider._radius = this.ellipsoid; + this._collider.collisionMask = this._collisionMask; + // No need for clone, as long as gravity is not on. + let actualDisplacement = displacement; + // Add gravity to direction to prevent dual-collision checking. + if (this.applyGravity) { + // This prevents mending with cameraDirection, a global variable of the fly camera class. + actualDisplacement = displacement.add(this.getScene().gravity); + } + coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); + } + /** @internal */ + _checkInputs() { + if (!this._localDirection) { + this._localDirection = Vector3.Zero(); + this._transformedDirection = Vector3.Zero(); + } + this.inputs.checkInputs(); + super._checkInputs(); + } + /** + * Enable movement without a user input. This allows gravity to always be applied. + */ + set needMoveForGravity(value) { + this._needMoveForGravity = value; + } + /** + * When true, gravity is applied whether there is user input or not. + */ + get needMoveForGravity() { + return this._needMoveForGravity; + } + /** @internal */ + _decideIfNeedsToMove() { + return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; + } + /** @internal */ + _updatePosition() { + if (this.checkCollisions && this.getScene().collisionsEnabled) { + this._collideWithWorld(this.cameraDirection); + } + else { + super._updatePosition(); + } + } + /** + * Restore the Roll to its target value at the rate specified. + * @param rate - Higher means slower restoring. + * @internal + */ + restoreRoll(rate) { + const limit = this._trackRoll; // Target Roll. + const z = this.rotation.z; // Current Roll. + const delta = limit - z; // Difference in Roll. + const minRad = 0.001; // Tenth of a radian is a barely noticable difference. + // If the difference is noticable, restore the Roll. + if (Math.abs(delta) >= minRad) { + // Change Z rotation towards the target Roll. + this.rotation.z += delta / rate; + // Match when near enough. + if (Math.abs(limit - this.rotation.z) <= minRad) { + this.rotation.z = limit; + } + } + } + /** + * Destroy the camera and release the current resources held by it. + */ + dispose() { + this.inputs.clear(); + super.dispose(); + } + /** + * Get the current object class name. + * @returns the class name. + */ + getClassName() { + return "FlyCamera"; + } +} +__decorate([ + serializeAsVector3() +], FlyCamera.prototype, "ellipsoid", void 0); +__decorate([ + serializeAsVector3() +], FlyCamera.prototype, "ellipsoidOffset", void 0); +__decorate([ + serialize() +], FlyCamera.prototype, "checkCollisions", void 0); +__decorate([ + serialize() +], FlyCamera.prototype, "applyGravity", void 0); +// Register Class Name +RegisterClass("BABYLON.FlyCamera", FlyCamera); + +/** + * Default Inputs manager for the FollowCamera. + * It groups all the default supported inputs for ease of use. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs + */ +class FollowCameraInputsManager extends CameraInputsManager { + /** + * Instantiates a new FollowCameraInputsManager. + * @param camera Defines the camera the inputs belong to + */ + constructor(camera) { + super(camera); + } + /** + * Add keyboard input support to the input manager. + * @returns the current input manager + */ + addKeyboard() { + this.add(new FollowCameraKeyboardMoveInput()); + return this; + } + /** + * Add mouse wheel input support to the input manager. + * @returns the current input manager + */ + addMouseWheel() { + this.add(new FollowCameraMouseWheelInput()); + return this; + } + /** + * Add pointers input support to the input manager. + * @returns the current input manager + */ + addPointers() { + this.add(new FollowCameraPointersInput()); + return this; + } + /** + * Add orientation input support to the input manager. + * @returns the current input manager + */ + addVRDeviceOrientation() { + Logger.Warn("DeviceOrientation support not yet implemented for FollowCamera."); + return this; + } +} + +Node$2.AddNodeConstructor("FollowCamera", (name, scene) => { + return () => new FollowCamera(name, Vector3.Zero(), scene); +}); +Node$2.AddNodeConstructor("ArcFollowCamera", (name, scene) => { + return () => new ArcFollowCamera(name, 0, 0, 1.0, null, scene); +}); +/** + * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and + * an arc rotate version arcFollowCamera are available. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera + */ +class FollowCamera extends TargetCamera { + /** + * Instantiates the follow camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera + * @param name Define the name of the camera in the scene + * @param position Define the position of the camera + * @param scene Define the scene the camera belong to + * @param lockedTarget Define the target of the camera + */ + constructor(name, position, scene, lockedTarget = null) { + super(name, position, scene); + /** + * Distance the follow camera should follow an object at + */ + this.radius = 12; + /** + * Minimum allowed distance of the camera to the axis of rotation + * (The camera can not get closer). + * This can help limiting how the Camera is able to move in the scene. + */ + this.lowerRadiusLimit = null; + /** + * Maximum allowed distance of the camera to the axis of rotation + * (The camera can not get further). + * This can help limiting how the Camera is able to move in the scene. + */ + this.upperRadiusLimit = null; + /** + * Define a rotation offset between the camera and the object it follows + */ + this.rotationOffset = 0; + /** + * Minimum allowed angle to camera position relative to target object. + * This can help limiting how the Camera is able to move in the scene. + */ + this.lowerRotationOffsetLimit = null; + /** + * Maximum allowed angle to camera position relative to target object. + * This can help limiting how the Camera is able to move in the scene. + */ + this.upperRotationOffsetLimit = null; + /** + * Define a height offset between the camera and the object it follows. + * It can help following an object from the top (like a car chasing a plane) + */ + this.heightOffset = 4; + /** + * Minimum allowed height of camera position relative to target object. + * This can help limiting how the Camera is able to move in the scene. + */ + this.lowerHeightOffsetLimit = null; + /** + * Maximum allowed height of camera position relative to target object. + * This can help limiting how the Camera is able to move in the scene. + */ + this.upperHeightOffsetLimit = null; + /** + * Define how fast the camera can accelerate to follow it s target. + */ + this.cameraAcceleration = 0.05; + /** + * Define the speed limit of the camera following an object. + */ + this.maxCameraSpeed = 20; + this.lockedTarget = lockedTarget; + this.inputs = new FollowCameraInputsManager(this); + this.inputs.addKeyboard().addMouseWheel().addPointers(); + // Uncomment the following line when the relevant handlers have been implemented. + // this.inputs.addKeyboard().addMouseWheel().addPointers().addVRDeviceOrientation(); + } + _follow(cameraTarget) { + if (!cameraTarget) { + return; + } + const rotMatrix = TmpVectors.Matrix[0]; + cameraTarget.absoluteRotationQuaternion.toRotationMatrix(rotMatrix); + const yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]); + const radians = Tools.ToRadians(this.rotationOffset) + yRotation; + const targetPosition = cameraTarget.getAbsolutePosition(); + const targetX = targetPosition.x + Math.sin(radians) * this.radius; + const targetZ = targetPosition.z + Math.cos(radians) * this.radius; + const dx = targetX - this.position.x; + const dy = targetPosition.y + this.heightOffset - this.position.y; + const dz = targetZ - this.position.z; + let vx = dx * this.cameraAcceleration * 2; //this is set to .05 + let vy = dy * this.cameraAcceleration; + let vz = dz * this.cameraAcceleration * 2; + if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) { + vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; + } + if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) { + vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; + } + if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) { + vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; + } + this.position = new Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz); + this.setTarget(targetPosition); + } + /** + * Attached controls to the current camera. + * @param ignored defines an ignored parameter kept for backward compatibility. + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + attachControl(ignored, noPreventDefault) { + // eslint-disable-next-line prefer-rest-params + noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments); + this.inputs.attachElement(noPreventDefault); + this._reset = () => { }; + } + /** + * Detach the current controls from the specified dom element. + */ + detachControl() { + this.inputs.detachElement(); + if (this._reset) { + this._reset(); + } + } + /** @internal */ + _checkInputs() { + this.inputs.checkInputs(); + this._checkLimits(); + super._checkInputs(); + if (this.lockedTarget) { + this._follow(this.lockedTarget); + } + } + _checkLimits() { + if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) { + this.radius = this.lowerRadiusLimit; + } + if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) { + this.radius = this.upperRadiusLimit; + } + if (this.lowerHeightOffsetLimit !== null && this.heightOffset < this.lowerHeightOffsetLimit) { + this.heightOffset = this.lowerHeightOffsetLimit; + } + if (this.upperHeightOffsetLimit !== null && this.heightOffset > this.upperHeightOffsetLimit) { + this.heightOffset = this.upperHeightOffsetLimit; + } + if (this.lowerRotationOffsetLimit !== null && this.rotationOffset < this.lowerRotationOffsetLimit) { + this.rotationOffset = this.lowerRotationOffsetLimit; + } + if (this.upperRotationOffsetLimit !== null && this.rotationOffset > this.upperRotationOffsetLimit) { + this.rotationOffset = this.upperRotationOffsetLimit; + } + } + /** + * Gets the camera class name. + * @returns the class name + */ + getClassName() { + return "FollowCamera"; + } +} +__decorate([ + serialize() +], FollowCamera.prototype, "radius", void 0); +__decorate([ + serialize() +], FollowCamera.prototype, "lowerRadiusLimit", void 0); +__decorate([ + serialize() +], FollowCamera.prototype, "upperRadiusLimit", void 0); +__decorate([ + serialize() +], FollowCamera.prototype, "rotationOffset", void 0); +__decorate([ + serialize() +], FollowCamera.prototype, "lowerRotationOffsetLimit", void 0); +__decorate([ + serialize() +], FollowCamera.prototype, "upperRotationOffsetLimit", void 0); +__decorate([ + serialize() +], FollowCamera.prototype, "heightOffset", void 0); +__decorate([ + serialize() +], FollowCamera.prototype, "lowerHeightOffsetLimit", void 0); +__decorate([ + serialize() +], FollowCamera.prototype, "upperHeightOffsetLimit", void 0); +__decorate([ + serialize() +], FollowCamera.prototype, "cameraAcceleration", void 0); +__decorate([ + serialize() +], FollowCamera.prototype, "maxCameraSpeed", void 0); +__decorate([ + serializeAsMeshReference("lockedTargetId") +], FollowCamera.prototype, "lockedTarget", void 0); +/** + * Arc Rotate version of the follow camera. + * It still follows a Defined mesh but in an Arc Rotate Camera fashion. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera + */ +class ArcFollowCamera extends TargetCamera { + /** + * Instantiates a new ArcFollowCamera + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera + * @param name Define the name of the camera + * @param alpha Define the rotation angle of the camera around the longitudinal axis + * @param beta Define the rotation angle of the camera around the elevation axis + * @param radius Define the radius of the camera from its target point + * @param target Define the target of the camera + * @param scene Define the scene the camera belongs to + */ + constructor(name, + /** The longitudinal angle of the camera */ + alpha, + /** The latitudinal angle of the camera */ + beta, + /** The radius of the camera from its target */ + radius, + /** Define the camera target (the mesh it should follow) */ + target, scene) { + super(name, Vector3.Zero(), scene); + this.alpha = alpha; + this.beta = beta; + this.radius = radius; + this._cartesianCoordinates = Vector3.Zero(); + this.setMeshTarget(target); + } + /** + * Sets the mesh to follow with this camera. + * @param target the target to follow + */ + setMeshTarget(target) { + this._meshTarget = target; + this._follow(); + } + _follow() { + if (!this._meshTarget) { + return; + } + this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta); + this._cartesianCoordinates.y = this.radius * Math.sin(this.beta); + this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta); + const targetPosition = this._meshTarget.getAbsolutePosition(); + this.position = targetPosition.add(this._cartesianCoordinates); + this.setTarget(targetPosition); + } + /** @internal */ + _checkInputs() { + super._checkInputs(); + this._follow(); + } + /** + * Returns the class name of the object. + * It is mostly used internally for serialization purposes. + * @returns the class name + */ + getClassName() { + return "ArcFollowCamera"; + } +} +// Register Class Name +RegisterClass("BABYLON.FollowCamera", FollowCamera); +RegisterClass("BABYLON.ArcFollowCamera", ArcFollowCamera); + +/** + * Defines supported buttons for XBox360 compatible gamepads + */ +var Xbox360Button; +(function (Xbox360Button) { + /** A */ + Xbox360Button[Xbox360Button["A"] = 0] = "A"; + /** B */ + Xbox360Button[Xbox360Button["B"] = 1] = "B"; + /** X */ + Xbox360Button[Xbox360Button["X"] = 2] = "X"; + /** Y */ + Xbox360Button[Xbox360Button["Y"] = 3] = "Y"; + /** Left button */ + Xbox360Button[Xbox360Button["LB"] = 4] = "LB"; + /** Right button */ + Xbox360Button[Xbox360Button["RB"] = 5] = "RB"; + /** Back */ + Xbox360Button[Xbox360Button["Back"] = 8] = "Back"; + /** Start */ + Xbox360Button[Xbox360Button["Start"] = 9] = "Start"; + /** Left stick */ + Xbox360Button[Xbox360Button["LeftStick"] = 10] = "LeftStick"; + /** Right stick */ + Xbox360Button[Xbox360Button["RightStick"] = 11] = "RightStick"; +})(Xbox360Button || (Xbox360Button = {})); +/** Defines values for XBox360 DPad */ +var Xbox360Dpad; +(function (Xbox360Dpad) { + /** Up */ + Xbox360Dpad[Xbox360Dpad["Up"] = 12] = "Up"; + /** Down */ + Xbox360Dpad[Xbox360Dpad["Down"] = 13] = "Down"; + /** Left */ + Xbox360Dpad[Xbox360Dpad["Left"] = 14] = "Left"; + /** Right */ + Xbox360Dpad[Xbox360Dpad["Right"] = 15] = "Right"; +})(Xbox360Dpad || (Xbox360Dpad = {})); +/** + * Defines a XBox360 gamepad + */ +class Xbox360Pad extends Gamepad { + /** + * Creates a new XBox360 gamepad object + * @param id defines the id of this gamepad + * @param index defines its index + * @param gamepad defines the internal HTML gamepad object + * @param xboxOne defines if it is a XBox One gamepad + */ + constructor(id, index, gamepad, xboxOne = false) { + super(id, index, gamepad, 0, 1, 2, 3); + this._leftTrigger = 0; + this._rightTrigger = 0; + /** Observable raised when a button is pressed */ + this.onButtonDownObservable = new Observable(); + /** Observable raised when a button is released */ + this.onButtonUpObservable = new Observable(); + /** Observable raised when a pad is pressed */ + this.onPadDownObservable = new Observable(); + /** Observable raised when a pad is released */ + this.onPadUpObservable = new Observable(); + this._buttonA = 0; + this._buttonB = 0; + this._buttonX = 0; + this._buttonY = 0; + this._buttonBack = 0; + this._buttonStart = 0; + this._buttonLB = 0; + this._buttonRB = 0; + this._buttonLeftStick = 0; + this._buttonRightStick = 0; + this._dPadUp = 0; + this._dPadDown = 0; + this._dPadLeft = 0; + this._dPadRight = 0; + this._isXboxOnePad = false; + this.type = Gamepad.XBOX; + this._isXboxOnePad = xboxOne; + } + /** + * Defines the callback to call when left trigger is pressed + * @param callback defines the callback to use + */ + onlefttriggerchanged(callback) { + this._onlefttriggerchanged = callback; + } + /** + * Defines the callback to call when right trigger is pressed + * @param callback defines the callback to use + */ + onrighttriggerchanged(callback) { + this._onrighttriggerchanged = callback; + } + /** + * Gets the left trigger value + */ + get leftTrigger() { + return this._leftTrigger; + } + /** + * Sets the left trigger value + */ + set leftTrigger(newValue) { + if (this._onlefttriggerchanged && this._leftTrigger !== newValue) { + this._onlefttriggerchanged(newValue); + } + this._leftTrigger = newValue; + } + /** + * Gets the right trigger value + */ + get rightTrigger() { + return this._rightTrigger; + } + /** + * Sets the right trigger value + */ + set rightTrigger(newValue) { + if (this._onrighttriggerchanged && this._rightTrigger !== newValue) { + this._onrighttriggerchanged(newValue); + } + this._rightTrigger = newValue; + } + /** + * Defines the callback to call when a button is pressed + * @param callback defines the callback to use + */ + onbuttondown(callback) { + this._onbuttondown = callback; + } + /** + * Defines the callback to call when a button is released + * @param callback defines the callback to use + */ + onbuttonup(callback) { + this._onbuttonup = callback; + } + /** + * Defines the callback to call when a pad is pressed + * @param callback defines the callback to use + */ + ondpaddown(callback) { + this._ondpaddown = callback; + } + /** + * Defines the callback to call when a pad is released + * @param callback defines the callback to use + */ + ondpadup(callback) { + this._ondpadup = callback; + } + _setButtonValue(newValue, currentValue, buttonType) { + if (newValue !== currentValue) { + if (newValue === 1) { + if (this._onbuttondown) { + this._onbuttondown(buttonType); + } + this.onButtonDownObservable.notifyObservers(buttonType); + } + if (newValue === 0) { + if (this._onbuttonup) { + this._onbuttonup(buttonType); + } + this.onButtonUpObservable.notifyObservers(buttonType); + } + } + return newValue; + } + _setDPadValue(newValue, currentValue, buttonType) { + if (newValue !== currentValue) { + if (newValue === 1) { + if (this._ondpaddown) { + this._ondpaddown(buttonType); + } + this.onPadDownObservable.notifyObservers(buttonType); + } + if (newValue === 0) { + if (this._ondpadup) { + this._ondpadup(buttonType); + } + this.onPadUpObservable.notifyObservers(buttonType); + } + } + return newValue; + } + /** + * Gets the value of the `A` button + */ + get buttonA() { + return this._buttonA; + } + /** + * Sets the value of the `A` button + */ + set buttonA(value) { + this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* Xbox360Button.A */); + } + /** + * Gets the value of the `B` button + */ + get buttonB() { + return this._buttonB; + } + /** + * Sets the value of the `B` button + */ + set buttonB(value) { + this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* Xbox360Button.B */); + } + /** + * Gets the value of the `X` button + */ + get buttonX() { + return this._buttonX; + } + /** + * Sets the value of the `X` button + */ + set buttonX(value) { + this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* Xbox360Button.X */); + } + /** + * Gets the value of the `Y` button + */ + get buttonY() { + return this._buttonY; + } + /** + * Sets the value of the `Y` button + */ + set buttonY(value) { + this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Xbox360Button.Y */); + } + /** + * Gets the value of the `Start` button + */ + get buttonStart() { + return this._buttonStart; + } + /** + * Sets the value of the `Start` button + */ + set buttonStart(value) { + this._buttonStart = this._setButtonValue(value, this._buttonStart, 9 /* Xbox360Button.Start */); + } + /** + * Gets the value of the `Back` button + */ + get buttonBack() { + return this._buttonBack; + } + /** + * Sets the value of the `Back` button + */ + set buttonBack(value) { + this._buttonBack = this._setButtonValue(value, this._buttonBack, 8 /* Xbox360Button.Back */); + } + /** + * Gets the value of the `Left` button + */ + get buttonLB() { + return this._buttonLB; + } + /** + * Sets the value of the `Left` button + */ + set buttonLB(value) { + this._buttonLB = this._setButtonValue(value, this._buttonLB, 4 /* Xbox360Button.LB */); + } + /** + * Gets the value of the `Right` button + */ + get buttonRB() { + return this._buttonRB; + } + /** + * Sets the value of the `Right` button + */ + set buttonRB(value) { + this._buttonRB = this._setButtonValue(value, this._buttonRB, 5 /* Xbox360Button.RB */); + } + /** + * Gets the value of the Left joystick + */ + get buttonLeftStick() { + return this._buttonLeftStick; + } + /** + * Sets the value of the Left joystick + */ + set buttonLeftStick(value) { + this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 10 /* Xbox360Button.LeftStick */); + } + /** + * Gets the value of the Right joystick + */ + get buttonRightStick() { + return this._buttonRightStick; + } + /** + * Sets the value of the Right joystick + */ + set buttonRightStick(value) { + this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 11 /* Xbox360Button.RightStick */); + } + /** + * Gets the value of D-pad up + */ + get dPadUp() { + return this._dPadUp; + } + /** + * Sets the value of D-pad up + */ + set dPadUp(value) { + this._dPadUp = this._setDPadValue(value, this._dPadUp, 12 /* Xbox360Dpad.Up */); + } + /** + * Gets the value of D-pad down + */ + get dPadDown() { + return this._dPadDown; + } + /** + * Sets the value of D-pad down + */ + set dPadDown(value) { + this._dPadDown = this._setDPadValue(value, this._dPadDown, 13 /* Xbox360Dpad.Down */); + } + /** + * Gets the value of D-pad left + */ + get dPadLeft() { + return this._dPadLeft; + } + /** + * Sets the value of D-pad left + */ + set dPadLeft(value) { + this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 14 /* Xbox360Dpad.Left */); + } + /** + * Gets the value of D-pad right + */ + get dPadRight() { + return this._dPadRight; + } + /** + * Sets the value of D-pad right + */ + set dPadRight(value) { + this._dPadRight = this._setDPadValue(value, this._dPadRight, 15 /* Xbox360Dpad.Right */); + } + /** + * Force the gamepad to synchronize with device values + */ + update() { + super.update(); + if (this._isXboxOnePad) { + this.buttonA = this.browserGamepad.buttons[0].value; + this.buttonB = this.browserGamepad.buttons[1].value; + this.buttonX = this.browserGamepad.buttons[2].value; + this.buttonY = this.browserGamepad.buttons[3].value; + this.buttonLB = this.browserGamepad.buttons[4].value; + this.buttonRB = this.browserGamepad.buttons[5].value; + this.leftTrigger = this.browserGamepad.buttons[6].value; + this.rightTrigger = this.browserGamepad.buttons[7].value; + this.buttonBack = this.browserGamepad.buttons[8].value; + this.buttonStart = this.browserGamepad.buttons[9].value; + this.buttonLeftStick = this.browserGamepad.buttons[10].value; + this.buttonRightStick = this.browserGamepad.buttons[11].value; + this.dPadUp = this.browserGamepad.buttons[12].value; + this.dPadDown = this.browserGamepad.buttons[13].value; + this.dPadLeft = this.browserGamepad.buttons[14].value; + this.dPadRight = this.browserGamepad.buttons[15].value; + } + else { + this.buttonA = this.browserGamepad.buttons[0].value; + this.buttonB = this.browserGamepad.buttons[1].value; + this.buttonX = this.browserGamepad.buttons[2].value; + this.buttonY = this.browserGamepad.buttons[3].value; + this.buttonLB = this.browserGamepad.buttons[4].value; + this.buttonRB = this.browserGamepad.buttons[5].value; + this.leftTrigger = this.browserGamepad.buttons[6].value; + this.rightTrigger = this.browserGamepad.buttons[7].value; + this.buttonBack = this.browserGamepad.buttons[8].value; + this.buttonStart = this.browserGamepad.buttons[9].value; + this.buttonLeftStick = this.browserGamepad.buttons[10].value; + this.buttonRightStick = this.browserGamepad.buttons[11].value; + this.dPadUp = this.browserGamepad.buttons[12].value; + this.dPadDown = this.browserGamepad.buttons[13].value; + this.dPadLeft = this.browserGamepad.buttons[14].value; + this.dPadRight = this.browserGamepad.buttons[15].value; + } + } + /** + * Disposes the gamepad + */ + dispose() { + super.dispose(); + this.onButtonDownObservable.clear(); + this.onButtonUpObservable.clear(); + this.onPadDownObservable.clear(); + this.onPadUpObservable.clear(); + } +} + +/** + * Defines supported buttons for DualShock compatible gamepads + */ +var DualShockButton; +(function (DualShockButton) { + /** Cross */ + DualShockButton[DualShockButton["Cross"] = 0] = "Cross"; + /** Circle */ + DualShockButton[DualShockButton["Circle"] = 1] = "Circle"; + /** Square */ + DualShockButton[DualShockButton["Square"] = 2] = "Square"; + /** Triangle */ + DualShockButton[DualShockButton["Triangle"] = 3] = "Triangle"; + /** L1 */ + DualShockButton[DualShockButton["L1"] = 4] = "L1"; + /** R1 */ + DualShockButton[DualShockButton["R1"] = 5] = "R1"; + /** Share */ + DualShockButton[DualShockButton["Share"] = 8] = "Share"; + /** Options */ + DualShockButton[DualShockButton["Options"] = 9] = "Options"; + /** Left stick */ + DualShockButton[DualShockButton["LeftStick"] = 10] = "LeftStick"; + /** Right stick */ + DualShockButton[DualShockButton["RightStick"] = 11] = "RightStick"; +})(DualShockButton || (DualShockButton = {})); +/** Defines values for DualShock DPad */ +var DualShockDpad; +(function (DualShockDpad) { + /** Up */ + DualShockDpad[DualShockDpad["Up"] = 12] = "Up"; + /** Down */ + DualShockDpad[DualShockDpad["Down"] = 13] = "Down"; + /** Left */ + DualShockDpad[DualShockDpad["Left"] = 14] = "Left"; + /** Right */ + DualShockDpad[DualShockDpad["Right"] = 15] = "Right"; +})(DualShockDpad || (DualShockDpad = {})); +/** + * Defines a DualShock gamepad + */ +class DualShockPad extends Gamepad { + /** + * Creates a new DualShock gamepad object + * @param id defines the id of this gamepad + * @param index defines its index + * @param gamepad defines the internal HTML gamepad object + */ + constructor(id, index, gamepad) { + super(id.replace("STANDARD GAMEPAD", "SONY PLAYSTATION DUALSHOCK"), index, gamepad, 0, 1, 2, 3); + this._leftTrigger = 0; + this._rightTrigger = 0; + /** Observable raised when a button is pressed */ + this.onButtonDownObservable = new Observable(); + /** Observable raised when a button is released */ + this.onButtonUpObservable = new Observable(); + /** Observable raised when a pad is pressed */ + this.onPadDownObservable = new Observable(); + /** Observable raised when a pad is released */ + this.onPadUpObservable = new Observable(); + this._buttonCross = 0; + this._buttonCircle = 0; + this._buttonSquare = 0; + this._buttonTriangle = 0; + this._buttonShare = 0; + this._buttonOptions = 0; + this._buttonL1 = 0; + this._buttonR1 = 0; + this._buttonLeftStick = 0; + this._buttonRightStick = 0; + this._dPadUp = 0; + this._dPadDown = 0; + this._dPadLeft = 0; + this._dPadRight = 0; + this.type = Gamepad.DUALSHOCK; + } + /** + * Defines the callback to call when left trigger is pressed + * @param callback defines the callback to use + */ + onlefttriggerchanged(callback) { + this._onlefttriggerchanged = callback; + } + /** + * Defines the callback to call when right trigger is pressed + * @param callback defines the callback to use + */ + onrighttriggerchanged(callback) { + this._onrighttriggerchanged = callback; + } + /** + * Gets the left trigger value + */ + get leftTrigger() { + return this._leftTrigger; + } + /** + * Sets the left trigger value + */ + set leftTrigger(newValue) { + if (this._onlefttriggerchanged && this._leftTrigger !== newValue) { + this._onlefttriggerchanged(newValue); + } + this._leftTrigger = newValue; + } + /** + * Gets the right trigger value + */ + get rightTrigger() { + return this._rightTrigger; + } + /** + * Sets the right trigger value + */ + set rightTrigger(newValue) { + if (this._onrighttriggerchanged && this._rightTrigger !== newValue) { + this._onrighttriggerchanged(newValue); + } + this._rightTrigger = newValue; + } + /** + * Defines the callback to call when a button is pressed + * @param callback defines the callback to use + */ + onbuttondown(callback) { + this._onbuttondown = callback; + } + /** + * Defines the callback to call when a button is released + * @param callback defines the callback to use + */ + onbuttonup(callback) { + this._onbuttonup = callback; + } + /** + * Defines the callback to call when a pad is pressed + * @param callback defines the callback to use + */ + ondpaddown(callback) { + this._ondpaddown = callback; + } + /** + * Defines the callback to call when a pad is released + * @param callback defines the callback to use + */ + ondpadup(callback) { + this._ondpadup = callback; + } + _setButtonValue(newValue, currentValue, buttonType) { + if (newValue !== currentValue) { + if (newValue === 1) { + if (this._onbuttondown) { + this._onbuttondown(buttonType); + } + this.onButtonDownObservable.notifyObservers(buttonType); + } + if (newValue === 0) { + if (this._onbuttonup) { + this._onbuttonup(buttonType); + } + this.onButtonUpObservable.notifyObservers(buttonType); + } + } + return newValue; + } + _setDPadValue(newValue, currentValue, buttonType) { + if (newValue !== currentValue) { + if (newValue === 1) { + if (this._ondpaddown) { + this._ondpaddown(buttonType); + } + this.onPadDownObservable.notifyObservers(buttonType); + } + if (newValue === 0) { + if (this._ondpadup) { + this._ondpadup(buttonType); + } + this.onPadUpObservable.notifyObservers(buttonType); + } + } + return newValue; + } + /** + * Gets the value of the `Cross` button + */ + get buttonCross() { + return this._buttonCross; + } + /** + * Sets the value of the `Cross` button + */ + set buttonCross(value) { + this._buttonCross = this._setButtonValue(value, this._buttonCross, 0 /* DualShockButton.Cross */); + } + /** + * Gets the value of the `Circle` button + */ + get buttonCircle() { + return this._buttonCircle; + } + /** + * Sets the value of the `Circle` button + */ + set buttonCircle(value) { + this._buttonCircle = this._setButtonValue(value, this._buttonCircle, 1 /* DualShockButton.Circle */); + } + /** + * Gets the value of the `Square` button + */ + get buttonSquare() { + return this._buttonSquare; + } + /** + * Sets the value of the `Square` button + */ + set buttonSquare(value) { + this._buttonSquare = this._setButtonValue(value, this._buttonSquare, 2 /* DualShockButton.Square */); + } + /** + * Gets the value of the `Triangle` button + */ + get buttonTriangle() { + return this._buttonTriangle; + } + /** + * Sets the value of the `Triangle` button + */ + set buttonTriangle(value) { + this._buttonTriangle = this._setButtonValue(value, this._buttonTriangle, 3 /* DualShockButton.Triangle */); + } + /** + * Gets the value of the `Options` button + */ + get buttonOptions() { + return this._buttonOptions; + } + /** + * Sets the value of the `Options` button + */ + set buttonOptions(value) { + this._buttonOptions = this._setButtonValue(value, this._buttonOptions, 9 /* DualShockButton.Options */); + } + /** + * Gets the value of the `Share` button + */ + get buttonShare() { + return this._buttonShare; + } + /** + * Sets the value of the `Share` button + */ + set buttonShare(value) { + this._buttonShare = this._setButtonValue(value, this._buttonShare, 8 /* DualShockButton.Share */); + } + /** + * Gets the value of the `L1` button + */ + get buttonL1() { + return this._buttonL1; + } + /** + * Sets the value of the `L1` button + */ + set buttonL1(value) { + this._buttonL1 = this._setButtonValue(value, this._buttonL1, 4 /* DualShockButton.L1 */); + } + /** + * Gets the value of the `R1` button + */ + get buttonR1() { + return this._buttonR1; + } + /** + * Sets the value of the `R1` button + */ + set buttonR1(value) { + this._buttonR1 = this._setButtonValue(value, this._buttonR1, 5 /* DualShockButton.R1 */); + } + /** + * Gets the value of the Left joystick + */ + get buttonLeftStick() { + return this._buttonLeftStick; + } + /** + * Sets the value of the Left joystick + */ + set buttonLeftStick(value) { + this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 10 /* DualShockButton.LeftStick */); + } + /** + * Gets the value of the Right joystick + */ + get buttonRightStick() { + return this._buttonRightStick; + } + /** + * Sets the value of the Right joystick + */ + set buttonRightStick(value) { + this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 11 /* DualShockButton.RightStick */); + } + /** + * Gets the value of D-pad up + */ + get dPadUp() { + return this._dPadUp; + } + /** + * Sets the value of D-pad up + */ + set dPadUp(value) { + this._dPadUp = this._setDPadValue(value, this._dPadUp, 12 /* DualShockDpad.Up */); + } + /** + * Gets the value of D-pad down + */ + get dPadDown() { + return this._dPadDown; + } + /** + * Sets the value of D-pad down + */ + set dPadDown(value) { + this._dPadDown = this._setDPadValue(value, this._dPadDown, 13 /* DualShockDpad.Down */); + } + /** + * Gets the value of D-pad left + */ + get dPadLeft() { + return this._dPadLeft; + } + /** + * Sets the value of D-pad left + */ + set dPadLeft(value) { + this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 14 /* DualShockDpad.Left */); + } + /** + * Gets the value of D-pad right + */ + get dPadRight() { + return this._dPadRight; + } + /** + * Sets the value of D-pad right + */ + set dPadRight(value) { + this._dPadRight = this._setDPadValue(value, this._dPadRight, 15 /* DualShockDpad.Right */); + } + /** + * Force the gamepad to synchronize with device values + */ + update() { + super.update(); + this.buttonCross = this.browserGamepad.buttons[0].value; + this.buttonCircle = this.browserGamepad.buttons[1].value; + this.buttonSquare = this.browserGamepad.buttons[2].value; + this.buttonTriangle = this.browserGamepad.buttons[3].value; + this.buttonL1 = this.browserGamepad.buttons[4].value; + this.buttonR1 = this.browserGamepad.buttons[5].value; + this.leftTrigger = this.browserGamepad.buttons[6].value; + this.rightTrigger = this.browserGamepad.buttons[7].value; + this.buttonShare = this.browserGamepad.buttons[8].value; + this.buttonOptions = this.browserGamepad.buttons[9].value; + this.buttonLeftStick = this.browserGamepad.buttons[10].value; + this.buttonRightStick = this.browserGamepad.buttons[11].value; + this.dPadUp = this.browserGamepad.buttons[12].value; + this.dPadDown = this.browserGamepad.buttons[13].value; + this.dPadLeft = this.browserGamepad.buttons[14].value; + this.dPadRight = this.browserGamepad.buttons[15].value; + } + /** + * Disposes the gamepad + */ + dispose() { + super.dispose(); + this.onButtonDownObservable.clear(); + this.onButtonUpObservable.clear(); + this.onPadDownObservable.clear(); + this.onPadUpObservable.clear(); + } +} + +/** + * Manager for handling gamepads + */ +class GamepadManager { + /** + * Initializes the gamepad manager + * @param _scene BabylonJS scene + */ + constructor(_scene) { + this._scene = _scene; + this._babylonGamepads = []; + this._oneGamepadConnected = false; + /** @internal */ + this._isMonitoring = false; + /** + * observable to be triggered when the gamepad controller has been disconnected + */ + this.onGamepadDisconnectedObservable = new Observable(); + if (!IsWindowObjectExist()) { + this._gamepadEventSupported = false; + } + else { + this._gamepadEventSupported = "GamepadEvent" in window; + this._gamepadSupport = navigator && navigator.getGamepads; + } + this.onGamepadConnectedObservable = new Observable((observer) => { + // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected + for (const i in this._babylonGamepads) { + const gamepad = this._babylonGamepads[i]; + if (gamepad && gamepad._isConnected) { + this.onGamepadConnectedObservable.notifyObserver(observer, gamepad); + } + } + }); + this._onGamepadConnectedEvent = (evt) => { + const gamepad = evt.gamepad; + if (gamepad.index in this._babylonGamepads) { + if (this._babylonGamepads[gamepad.index].isConnected) { + return; + } + } + let newGamepad; + if (this._babylonGamepads[gamepad.index]) { + newGamepad = this._babylonGamepads[gamepad.index]; + newGamepad.browserGamepad = gamepad; + newGamepad._isConnected = true; + } + else { + newGamepad = this._addNewGamepad(gamepad); + } + this.onGamepadConnectedObservable.notifyObservers(newGamepad); + this._startMonitoringGamepads(); + }; + this._onGamepadDisconnectedEvent = (evt) => { + const gamepad = evt.gamepad; + // Remove the gamepad from the list of gamepads to monitor. + for (const i in this._babylonGamepads) { + if (this._babylonGamepads[i].index === gamepad.index) { + const disconnectedGamepad = this._babylonGamepads[i]; + disconnectedGamepad._isConnected = false; + this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad); + disconnectedGamepad.dispose && disconnectedGamepad.dispose(); + break; + } + } + }; + if (this._gamepadSupport) { + //first add already-connected gamepads + this._updateGamepadObjects(); + if (this._babylonGamepads.length) { + this._startMonitoringGamepads(); + } + // Checking if the gamepad connected event is supported (like in Firefox) + if (this._gamepadEventSupported) { + const hostWindow = this._scene ? this._scene.getEngine().getHostWindow() : window; + if (hostWindow) { + hostWindow.addEventListener("gamepadconnected", this._onGamepadConnectedEvent, false); + hostWindow.addEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent, false); + } + } + else { + this._startMonitoringGamepads(); + } + } + } + /** + * The gamepads in the game pad manager + */ + get gamepads() { + return this._babylonGamepads; + } + /** + * Get the gamepad controllers based on type + * @param type The type of gamepad controller + * @returns Nullable gamepad + */ + getGamepadByType(type = Gamepad.XBOX) { + for (const gamepad of this._babylonGamepads) { + if (gamepad && gamepad.type === type) { + return gamepad; + } + } + return null; + } + /** + * Disposes the gamepad manager + */ + dispose() { + if (this._gamepadEventSupported) { + if (this._onGamepadConnectedEvent) { + window.removeEventListener("gamepadconnected", this._onGamepadConnectedEvent); + } + if (this._onGamepadDisconnectedEvent) { + window.removeEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent); + } + this._onGamepadConnectedEvent = null; + this._onGamepadDisconnectedEvent = null; + } + this._babylonGamepads.forEach((gamepad) => { + gamepad.dispose(); + }); + this.onGamepadConnectedObservable.clear(); + this.onGamepadDisconnectedObservable.clear(); + this._oneGamepadConnected = false; + this._stopMonitoringGamepads(); + this._babylonGamepads = []; + } + _addNewGamepad(gamepad) { + if (!this._oneGamepadConnected) { + this._oneGamepadConnected = true; + } + let newGamepad; + const dualShock = gamepad.id.search("054c") !== -1 && gamepad.id.search("0ce6") === -1; + const xboxOne = gamepad.id.search("Xbox One") !== -1; + if (xboxOne || + gamepad.id.search("Xbox 360") !== -1 || + gamepad.id.search("xinput") !== -1 || + (gamepad.id.search("045e") !== -1 && gamepad.id.search("Surface Dock") === -1)) { + // make sure the Surface Dock Extender is not detected as an xbox controller + newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne); + } + else if (dualShock) { + newGamepad = new DualShockPad(gamepad.id, gamepad.index, gamepad); + } + else { + newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad); + } + this._babylonGamepads[newGamepad.index] = newGamepad; + return newGamepad; + } + _startMonitoringGamepads() { + if (!this._isMonitoring) { + this._isMonitoring = true; + //back-comp + this._checkGamepadsStatus(); + } + } + _stopMonitoringGamepads() { + this._isMonitoring = false; + } + /** @internal */ + _checkGamepadsStatus() { + // Hack to be compatible Chrome + this._updateGamepadObjects(); + for (const i in this._babylonGamepads) { + const gamepad = this._babylonGamepads[i]; + if (!gamepad || !gamepad.isConnected) { + continue; + } + try { + gamepad.update(); + } + catch { + if (this._loggedErrors.indexOf(gamepad.index) === -1) { + Tools.Warn(`Error updating gamepad ${gamepad.id}`); + this._loggedErrors.push(gamepad.index); + } + } + } + if (this._isMonitoring) { + AbstractEngine.QueueNewFrame(() => { + this._checkGamepadsStatus(); + }); + } + } + // This function is called only on Chrome, which does not properly support + // connection/disconnection events and forces you to recopy again the gamepad object + _updateGamepadObjects() { + const gamepads = navigator.getGamepads ? navigator.getGamepads() : []; + for (let i = 0; i < gamepads.length; i++) { + const gamepad = gamepads[i]; + if (gamepad) { + if (!this._babylonGamepads[gamepad.index]) { + const newGamepad = this._addNewGamepad(gamepad); + this.onGamepadConnectedObservable.notifyObservers(newGamepad); + } + else { + // Forced to copy again this object for Chrome for unknown reason + this._babylonGamepads[i].browserGamepad = gamepad; + if (!this._babylonGamepads[i].isConnected) { + this._babylonGamepads[i]._isConnected = true; + this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]); + } + } + } + } + } +} + +Object.defineProperty(Scene.prototype, "gamepadManager", { + get: function () { + if (!this._gamepadManager) { + this._gamepadManager = new GamepadManager(this); + let component = this._getComponent(SceneComponentConstants.NAME_GAMEPAD); + if (!component) { + component = new GamepadSystemSceneComponent(this); + this._addComponent(component); + } + } + return this._gamepadManager; + }, + enumerable: true, + configurable: true, +}); +/** + * Adds a gamepad to the free camera inputs manager + * @returns the FreeCameraInputsManager + */ +FreeCameraInputsManager.prototype.addGamepad = function () { + this.add(new FreeCameraGamepadInput()); + return this; +}; +/** + * Adds a gamepad to the arc rotate camera inputs manager + * @returns the camera inputs manager + */ +ArcRotateCameraInputsManager.prototype.addGamepad = function () { + this.add(new ArcRotateCameraGamepadInput()); + return this; +}; +/** + * Defines the gamepad scene component responsible to manage gamepads in a given scene + */ +class GamepadSystemSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpfull to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_GAMEPAD; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + // Nothing to do for gamepads + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do for gamepads + } + /** + * Disposes the component and the associated resources + */ + dispose() { + const gamepadManager = this.scene._gamepadManager; + if (gamepadManager) { + gamepadManager.dispose(); + this.scene._gamepadManager = null; + } + } +} + +Node$2.AddNodeConstructor("FreeCamera", (name, scene) => { + // Forcing to use the Universal camera + return () => new UniversalCamera(name, Vector3.Zero(), scene); +}); +/** + * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera, + * which still works and will still be found in many Playgrounds. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera + */ +class UniversalCamera extends TouchCamera { + /** + * Defines the gamepad rotation sensibility. + * This is the threshold from when rotation starts to be accounted for to prevent jittering. + */ + get gamepadAngularSensibility() { + const gamepad = this.inputs.attached["gamepad"]; + if (gamepad) { + return gamepad.gamepadAngularSensibility; + } + return 0; + } + set gamepadAngularSensibility(value) { + const gamepad = this.inputs.attached["gamepad"]; + if (gamepad) { + gamepad.gamepadAngularSensibility = value; + } + } + /** + * Defines the gamepad move sensibility. + * This is the threshold from when moving starts to be accounted for to prevent jittering. + */ + get gamepadMoveSensibility() { + const gamepad = this.inputs.attached["gamepad"]; + if (gamepad) { + return gamepad.gamepadMoveSensibility; + } + return 0; + } + set gamepadMoveSensibility(value) { + const gamepad = this.inputs.attached["gamepad"]; + if (gamepad) { + gamepad.gamepadMoveSensibility = value; + } + } + /** + * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera, + * which still works and will still be found in many Playgrounds. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera + * @param name Define the name of the camera in the scene + * @param position Define the start position of the camera in the scene + * @param scene Define the scene the camera belongs to + */ + constructor(name, position, scene) { + super(name, position, scene); + this.inputs.addGamepad(); + } + /** + * Gets the current object class name. + * @returns the class name + */ + getClassName() { + return "UniversalCamera"; + } +} +Camera._CreateDefaultParsedCamera = (name, scene) => { + return new UniversalCamera(name, Vector3.Zero(), scene); +}; + +Node$2.AddNodeConstructor("GamepadCamera", (name, scene) => { + return () => new GamepadCamera(name, Vector3.Zero(), scene); +}); +/** + * This represents a FPS type of camera. This is only here for back compat purpose. + * Please use the UniversalCamera instead as both are identical. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera + */ +class GamepadCamera extends UniversalCamera { + /** + * Instantiates a new Gamepad Camera + * This represents a FPS type of camera. This is only here for back compat purpose. + * Please use the UniversalCamera instead as both are identical. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera + * @param name Define the name of the camera in the scene + * @param position Define the start position of the camera in the scene + * @param scene Define the scene the camera belongs to + */ + constructor(name, position, scene) { + super(name, position, scene); + } + /** + * Gets the current object class name. + * @returns the class name + */ + getClassName() { + return "GamepadCamera"; + } +} + +/** + * Postprocess used to generate anaglyphic rendering + */ +class ThinAnaglyphPostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => anaglyph_fragment)); + } + else { + list.push(Promise.resolve().then(() => anaglyph_fragment$1)); + } + } + /** + * Constructs a new anaglyph post process + * @param name Name of the effect + * @param engine Engine to use to render the effect. If not provided, the last created engine will be used + * @param options Options to configure the effect + */ + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinAnaglyphPostProcess.FragmentUrl, + samplers: ThinAnaglyphPostProcess.Samplers, + }); + } +} +/** + * The fragment shader url + */ +ThinAnaglyphPostProcess.FragmentUrl = "anaglyph"; +/** + * The list of samplers used by the effect + */ +ThinAnaglyphPostProcess.Samplers = ["leftSampler"]; + +/** + * Postprocess used to generate anaglyphic rendering + */ +class AnaglyphPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "AnaglyphPostProcess" string + */ + getClassName() { + return "AnaglyphPostProcess"; + } + /** + * Creates a new AnaglyphPostProcess + * @param name defines postprocess name + * @param options defines creation options or target ratio scale + * @param rigCameras defines cameras using this postprocess + * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default) + * @param engine defines hosting engine + * @param reusable defines if the postprocess will be reused multiple times per frame + */ + constructor(name, options, rigCameras, samplingMode, engine, reusable) { + const localOptions = { + samplers: ThinAnaglyphPostProcess.Samplers, + size: typeof options === "number" ? options : undefined, + camera: rigCameras[1], + samplingMode, + engine, + reusable, + ...options, + }; + super(name, ThinAnaglyphPostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinAnaglyphPostProcess(name, engine, localOptions) : undefined, + ...localOptions, + }); + this._passedProcess = rigCameras[0]._rigPostProcess; + this.onApplyObservable.add((effect) => { + effect.setTextureFromPostProcess("leftSampler", this._passedProcess); + }); + } +} +RegisterClass("BABYLON.AnaglyphPostProcess", AnaglyphPostProcess); + +/** + * @internal + */ +function setStereoscopicAnaglyphRigMode(camera) { + camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + "_passthru", 1.0, camera._rigCameras[0]); + camera._rigCameras[1]._rigPostProcess = new AnaglyphPostProcess(camera.name + "_anaglyph", 1.0, camera._rigCameras); +} + +Node$2.AddNodeConstructor("AnaglyphArcRotateCamera", (name, scene, options) => { + return () => new AnaglyphArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), options.interaxial_distance, scene); +}); +/** + * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras + */ +class AnaglyphArcRotateCamera extends ArcRotateCamera { + /** + * Creates a new AnaglyphArcRotateCamera + * @param name defines camera name + * @param alpha defines alpha angle (in radians) + * @param beta defines beta angle (in radians) + * @param radius defines radius + * @param target defines camera target + * @param interaxialDistance defines distance between each color axis + * @param scene defines the hosting scene + */ + constructor(name, alpha, beta, radius, target, interaxialDistance, scene) { + super(name, alpha, beta, radius, target, scene); + this._setRigMode = () => setStereoscopicAnaglyphRigMode(this); + this.interaxialDistance = interaxialDistance; + this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); + } + /** + * Gets camera class name + * @returns AnaglyphArcRotateCamera + */ + getClassName() { + return "AnaglyphArcRotateCamera"; + } +} + +Node$2.AddNodeConstructor("AnaglyphFreeCamera", (name, scene, options) => { + return () => new AnaglyphFreeCamera(name, Vector3.Zero(), options.interaxial_distance, scene); +}); +/** + * Camera used to simulate anaglyphic rendering (based on FreeCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras + */ +class AnaglyphFreeCamera extends FreeCamera { + /** + * Creates a new AnaglyphFreeCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param scene defines the hosting scene + */ + constructor(name, position, interaxialDistance, scene) { + super(name, position, scene); + this._setRigMode = () => setStereoscopicAnaglyphRigMode(this); + this.interaxialDistance = interaxialDistance; + this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); + } + /** + * Gets camera class name + * @returns AnaglyphFreeCamera + */ + getClassName() { + return "AnaglyphFreeCamera"; + } +} + +Node$2.AddNodeConstructor("AnaglyphGamepadCamera", (name, scene, options) => { + return () => new AnaglyphGamepadCamera(name, Vector3.Zero(), options.interaxial_distance, scene); +}); +/** + * Camera used to simulate anaglyphic rendering (based on GamepadCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras + */ +class AnaglyphGamepadCamera extends GamepadCamera { + /** + * Creates a new AnaglyphGamepadCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param scene defines the hosting scene + */ + constructor(name, position, interaxialDistance, scene) { + super(name, position, scene); + this._setRigMode = () => setStereoscopicAnaglyphRigMode(this); + this.interaxialDistance = interaxialDistance; + this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); + } + /** + * Gets camera class name + * @returns AnaglyphGamepadCamera + */ + getClassName() { + return "AnaglyphGamepadCamera"; + } +} + +Node$2.AddNodeConstructor("AnaglyphUniversalCamera", (name, scene, options) => { + return () => new AnaglyphUniversalCamera(name, Vector3.Zero(), options.interaxial_distance, scene); +}); +/** + * Camera used to simulate anaglyphic rendering (based on UniversalCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras + */ +class AnaglyphUniversalCamera extends UniversalCamera { + /** + * Creates a new AnaglyphUniversalCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param scene defines the hosting scene + */ + constructor(name, position, interaxialDistance, scene) { + super(name, position, scene); + this._setRigMode = () => setStereoscopicAnaglyphRigMode(this); + this.interaxialDistance = interaxialDistance; + this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); + } + /** + * Gets camera class name + * @returns AnaglyphUniversalCamera + */ + getClassName() { + return "AnaglyphUniversalCamera"; + } +} + +// Do not edit. +const name$7Y = "stereoscopicInterlacePixelShader"; +const shader$7X = `const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; +#ifdef IS_STEREOSCOPIC_HORIZ +useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); +#else +#ifdef IS_STEREOSCOPIC_INTERLACED +float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); +#else +useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); +#endif +#endif +if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} +gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7Y]) { + ShaderStore.ShadersStore[name$7Y] = shader$7X; +} + +/** + * StereoscopicInterlacePostProcessI used to render stereo views from a rigged camera with support for alternate line interlacing + */ +class StereoscopicInterlacePostProcessI extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "StereoscopicInterlacePostProcessI" string + */ + getClassName() { + return "StereoscopicInterlacePostProcessI"; + } + /** + * Initializes a StereoscopicInterlacePostProcessI + * @param name The name of the effect. + * @param rigCameras The rig cameras to be applied to the post process + * @param isStereoscopicHoriz If the rendered results are horizontal or vertical + * @param isStereoscopicInterlaced If the rendered results are alternate line interlaced + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + */ + constructor(name, rigCameras, isStereoscopicHoriz, isStereoscopicInterlaced, samplingMode, engine, reusable) { + super(name, "stereoscopicInterlace", ["stepSize"], ["camASampler"], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicInterlaced ? "#define IS_STEREOSCOPIC_INTERLACED 1" : isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined); + this._passedProcess = rigCameras[0]._rigPostProcess; + this._stepSize = new Vector2(1 / this.width, 1 / this.height); + this.onSizeChangedObservable.add(() => { + this._stepSize = new Vector2(1 / this.width, 1 / this.height); + }); + this.onApplyObservable.add((effect) => { + effect.setTextureFromPostProcess("camASampler", this._passedProcess); + effect.setFloat2("stepSize", this._stepSize.x, this._stepSize.y); + }); + } +} + +/** + * @internal + */ +function setStereoscopicRigMode(camera) { + const isStereoscopicHoriz = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; + const isCrossEye = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; + const isInterlaced = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_INTERLACED; + // Use post-processors for interlacing + if (isInterlaced) { + camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + "_passthru", 1.0, camera._rigCameras[0]); + camera._rigCameras[1]._rigPostProcess = new StereoscopicInterlacePostProcessI(camera.name + "_stereoInterlace", camera._rigCameras, false, true); + } + // Otherwise, create appropriate viewports + else { + camera._rigCameras[isCrossEye ? 1 : 0].viewport = new Viewport(0, 0, isStereoscopicHoriz ? 0.5 : 1.0, isStereoscopicHoriz ? 1.0 : 0.5); + camera._rigCameras[isCrossEye ? 0 : 1].viewport = new Viewport(isStereoscopicHoriz ? 0.5 : 0, isStereoscopicHoriz ? 0 : 0.5, isStereoscopicHoriz ? 0.5 : 1.0, isStereoscopicHoriz ? 1.0 : 0.5); + } +} + +Node$2.AddNodeConstructor("StereoscopicArcRotateCamera", (name, scene, options) => { + return () => new StereoscopicArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); +}); +/** + * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras + */ +class StereoscopicArcRotateCamera extends ArcRotateCamera { + /** + * Creates a new StereoscopicArcRotateCamera + * @param name defines camera name + * @param alpha defines alpha angle (in radians) + * @param beta defines beta angle (in radians) + * @param radius defines radius + * @param target defines camera target + * @param interaxialDistance defines distance between each color axis + * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under + * @param scene defines the hosting scene + */ + constructor(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) { + super(name, alpha, beta, radius, target, scene); + this._setRigMode = () => setStereoscopicRigMode(this); + this.interaxialDistance = interaxialDistance; + this.isStereoscopicSideBySide = isStereoscopicSideBySide; + this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { + interaxialDistance: interaxialDistance, + }); + } + /** + * Gets camera class name + * @returns StereoscopicArcRotateCamera + */ + getClassName() { + return "StereoscopicArcRotateCamera"; + } +} + +Node$2.AddNodeConstructor("StereoscopicFreeCamera", (name, scene, options) => { + return () => new StereoscopicFreeCamera(name, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); +}); +/** + * Camera used to simulate stereoscopic rendering (based on FreeCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras + */ +class StereoscopicFreeCamera extends FreeCamera { + /** + * Creates a new StereoscopicFreeCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under + * @param scene defines the hosting scene + */ + constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { + super(name, position, scene); + this._setRigMode = () => setStereoscopicRigMode(this); + this.interaxialDistance = interaxialDistance; + this.isStereoscopicSideBySide = isStereoscopicSideBySide; + this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { + interaxialDistance: interaxialDistance, + }); + } + /** + * Gets camera class name + * @returns StereoscopicFreeCamera + */ + getClassName() { + return "StereoscopicFreeCamera"; + } +} + +Node$2.AddNodeConstructor("StereoscopicGamepadCamera", (name, scene, options) => { + return () => new StereoscopicGamepadCamera(name, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); +}); +/** + * Camera used to simulate stereoscopic rendering (based on GamepadCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras + */ +class StereoscopicGamepadCamera extends GamepadCamera { + /** + * Creates a new StereoscopicGamepadCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under + * @param scene defines the hosting scene + */ + constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { + super(name, position, scene); + this._setRigMode = () => setStereoscopicRigMode(this); + this.interaxialDistance = interaxialDistance; + this.isStereoscopicSideBySide = isStereoscopicSideBySide; + this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { + interaxialDistance: interaxialDistance, + }); + } + /** + * Gets camera class name + * @returns StereoscopicGamepadCamera + */ + getClassName() { + return "StereoscopicGamepadCamera"; + } +} + +Node$2.AddNodeConstructor("StereoscopicFreeCamera", (name, scene, options) => { + return () => new StereoscopicUniversalCamera(name, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); +}); +/** + * Camera used to simulate stereoscopic rendering (based on UniversalCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras + */ +class StereoscopicUniversalCamera extends UniversalCamera { + /** + * Creates a new StereoscopicUniversalCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under + * @param scene defines the hosting scene + */ + constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { + super(name, position, scene); + this._setRigMode = () => setStereoscopicRigMode(this); + this.interaxialDistance = interaxialDistance; + this.isStereoscopicSideBySide = isStereoscopicSideBySide; + this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { + interaxialDistance: interaxialDistance, + }); + } + /** + * Gets camera class name + * @returns StereoscopicUniversalCamera + */ + getClassName() { + return "StereoscopicUniversalCamera"; + } +} + +Node$2.AddNodeConstructor("VirtualJoysticksCamera", (name, scene) => { + return () => new VirtualJoysticksCamera(name, Vector3.Zero(), scene); +}); +/** + * This represents a free type of camera. It can be useful in First Person Shooter game for instance. + * It is identical to the Free Camera and simply adds by default a virtual joystick. + * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#virtual-joysticks-camera + */ +class VirtualJoysticksCamera extends FreeCamera { + /** + * Instantiates a VirtualJoysticksCamera. It can be useful in First Person Shooter game for instance. + * It is identical to the Free Camera and simply adds by default a virtual joystick. + * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#virtual-joysticks-camera + * @param name Define the name of the camera in the scene + * @param position Define the start position of the camera in the scene + * @param scene Define the scene the camera belongs to + */ + constructor(name, position, scene) { + super(name, position, scene); + this.inputs.addVirtualJoystick(); + } + /** + * Gets the current object class name. + * @returns the class name + */ + getClassName() { + return "VirtualJoysticksCamera"; + } +} + +/** + * This represents all the required metrics to create a VR camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#device-orientation-camera + */ +class VRCameraMetrics { + constructor() { + /** + * Define if the current vr camera should compensate the distortion of the lens or not. + */ + this.compensateDistortion = true; + /** + * Defines if multiview should be enabled when rendering (Default: false) + */ + this.multiviewEnabled = false; + } + /** + * Gets the rendering aspect ratio based on the provided resolutions. + */ + get aspectRatio() { + return this.hResolution / (2 * this.vResolution); + } + /** + * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes. + */ + get aspectRatioFov() { + return 2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)); + } + /** + * @internal + */ + get leftHMatrix() { + const meters = this.hScreenSize / 4 - this.lensSeparationDistance / 2; + const h = (4 * meters) / this.hScreenSize; + return Matrix.Translation(h, 0, 0); + } + /** + * @internal + */ + get rightHMatrix() { + const meters = this.hScreenSize / 4 - this.lensSeparationDistance / 2; + const h = (4 * meters) / this.hScreenSize; + return Matrix.Translation(-h, 0, 0); + } + /** + * @internal + */ + get leftPreViewMatrix() { + return Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0); + } + /** + * @internal + */ + get rightPreViewMatrix() { + return Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0); + } + /** + * Get the default VRMetrics based on the most generic setup. + * @returns the default vr metrics + */ + static GetDefault() { + const result = new VRCameraMetrics(); + result.hResolution = 1280; + result.vResolution = 800; + result.hScreenSize = 0.149759993; + result.vScreenSize = 0.0935999975; + result.vScreenCenter = 0.0467999987; + result.eyeToScreenDistance = 0.0410000011; + result.lensSeparationDistance = 0.063500002; + result.interpupillaryDistance = 0.064000003; + result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0]; + result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0]; + result.postProcessScaleFactor = 1.714605507808412; + result.lensCenterOffset = 0.151976421; + return result; + } +} + +/** + * VRDistortionCorrectionPostProcess used for mobile VR + */ +class VRDistortionCorrectionPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "VRDistortionCorrectionPostProcess" string + */ + getClassName() { + return "VRDistortionCorrectionPostProcess"; + } + /** + * Initializes the VRDistortionCorrectionPostProcess + * @param name The name of the effect. + * @param camera The camera to apply the render pass to. + * @param isRightEye If this is for the right eye distortion + * @param vrMetrics All the required metrics for the VR camera + */ + constructor(name, camera, isRightEye, vrMetrics) { + super(name, "vrDistortionCorrection", ["LensCenter", "Scale", "ScaleIn", "HmdWarpParam"], null, vrMetrics.postProcessScaleFactor, camera, Texture.BILINEAR_SAMPLINGMODE); + this._isRightEye = isRightEye; + this._distortionFactors = vrMetrics.distortionK; + this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor; + this._lensCenterOffset = vrMetrics.lensCenterOffset; + this.adaptScaleToCurrentViewport = true; + this.onSizeChangedObservable.add(() => { + this._scaleIn = new Vector2(2, 2 / this.aspectRatio); + this._scaleFactor = new Vector2(0.5 * (1 / this._postProcessScaleFactor), 0.5 * (1 / this._postProcessScaleFactor) * this.aspectRatio); + this._lensCenter = new Vector2(this._isRightEye ? 0.5 - this._lensCenterOffset * 0.5 : 0.5 + this._lensCenterOffset * 0.5, 0.5); + }); + this.onApplyObservable.add((effect) => { + effect.setFloat2("LensCenter", this._lensCenter.x, this._lensCenter.y); + effect.setFloat2("Scale", this._scaleFactor.x, this._scaleFactor.y); + effect.setFloat2("ScaleIn", this._scaleIn.x, this._scaleIn.y); + effect.setFloat4("HmdWarpParam", this._distortionFactors[0], this._distortionFactors[1], this._distortionFactors[2], this._distortionFactors[3]); + }); + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => vrDistortionCorrection_fragment)); + } + else { + list.push(Promise.resolve().then(() => vrDistortionCorrection_fragment$1)); + } + super._gatherImports(useWebGPU, list); + } +} + +// Do not edit. +const name$7X = "vrMultiviewToSingleviewPixelShader"; +const shader$7W = `precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7X]) { + ShaderStore.ShadersStore[name$7X] = shader$7W; +} + +/** + * Renders to multiple views with a single draw call + * Only for WebGL backends + * @see https://www.khronos.org/registry/webgl/extensions/OVR_multiview2/ + */ +class MultiviewRenderTarget extends RenderTargetTexture { + set samples(value) { + // We override this setter because multisampling is handled by framebufferTextureMultisampleMultiviewOVR + this._samples = value; + } + get samples() { + return this._samples; + } + /** + * Creates a multiview render target + * @param scene scene used with the render target + * @param size the size of the render target (used for each view) + */ + constructor(scene, size = 512) { + super("multiview rtt", size, scene, false, true, 0, false, undefined, false, false, true, undefined, true); + this._renderTarget = this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight()); + this._texture = this._renderTarget.texture; + this._texture.isMultiview = true; + this._texture.format = 5; + this.samples = this._getEngine().getCaps().maxSamples || this.samples; + this._texture.samples = this._samples; + } + /** + * @internal + */ + _bindFrameBuffer() { + if (!this._renderTarget) { + return; + } + this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget); + } + /** + * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1) + * @returns the view count + */ + getViewCount() { + return 2; + } +} + +Engine.prototype.createMultiviewRenderTargetTexture = function (width, height, colorTexture, depthStencilTexture) { + const gl = this._gl; + if (!this.getCaps().multiview) { + // eslint-disable-next-line no-throw-literal + throw "Multiview is not supported"; + } + const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, { width, height }); + rtWrapper._framebuffer = gl.createFramebuffer(); + const internalTexture = new InternalTexture(this, 0 /* InternalTextureSource.Unknown */, true); + internalTexture.width = width; + internalTexture.height = height; + internalTexture.isMultiview = true; + if (!colorTexture) { + colorTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D_ARRAY, colorTexture); + gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, width, height, 2); + } + rtWrapper._colorTextureArray = colorTexture; + if (!depthStencilTexture) { + depthStencilTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D_ARRAY, depthStencilTexture); + gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.DEPTH24_STENCIL8, width, height, 2); + } + rtWrapper._depthStencilTextureArray = depthStencilTexture; + internalTexture.isReady = true; + rtWrapper.setTextures(internalTexture); + rtWrapper._depthStencilTexture = internalTexture; + return rtWrapper; +}; +Engine.prototype.bindMultiviewFramebuffer = function (_multiviewTexture) { + const multiviewTexture = _multiviewTexture; + const gl = this._gl; + const ext = this.getCaps().oculusMultiview || this.getCaps().multiview; + this.bindFramebuffer(multiviewTexture, undefined, undefined, undefined, true); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, multiviewTexture._framebuffer); + if (multiviewTexture._colorTextureArray && multiviewTexture._depthStencilTextureArray) { + if (this.getCaps().oculusMultiview) { + ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, multiviewTexture.samples, 0, 2); + ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, multiviewTexture.samples, 0, 2); + } + else { + ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, 0, 2); + ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, 0, 2); + } + } + else { + // eslint-disable-next-line no-throw-literal + throw "Invalid multiview frame buffer"; + } +}; +Engine.prototype.bindSpaceWarpFramebuffer = function (_spaceWarpTexture) { + const spaceWarpTexture = _spaceWarpTexture; + const gl = this._gl; + const ext = this.getCaps().oculusMultiview || this.getCaps().multiview; + this.bindFramebuffer(spaceWarpTexture, undefined, undefined, undefined, true); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, spaceWarpTexture._framebuffer); + if (spaceWarpTexture._colorTextureArray && spaceWarpTexture._depthStencilTextureArray) { + ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, spaceWarpTexture._colorTextureArray, 0, 0, 2); + ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_ATTACHMENT, spaceWarpTexture._depthStencilTextureArray, 0, 0, 2); + } + else { + throw new Error("Invalid Space Warp framebuffer"); + } +}; +Camera.prototype._useMultiviewToSingleView = false; +Camera.prototype._multiviewTexture = null; +Camera.prototype._resizeOrCreateMultiviewTexture = function (width, height) { + if (!this._multiviewTexture) { + this._multiviewTexture = new MultiviewRenderTarget(this.getScene(), { width: width, height: height }); + } + else if (this._multiviewTexture.getRenderWidth() != width || this._multiviewTexture.getRenderHeight() != height) { + this._multiviewTexture.dispose(); + this._multiviewTexture = new MultiviewRenderTarget(this.getScene(), { width: width, height: height }); + } +}; +function createMultiviewUbo(engine, name) { + const ubo = new UniformBuffer(engine, undefined, true, name); + ubo.addUniform("viewProjection", 16); + ubo.addUniform("viewProjectionR", 16); + ubo.addUniform("view", 16); + ubo.addUniform("projection", 16); + ubo.addUniform("vEyePosition", 4); + return ubo; +} +const currentCreateSceneUniformBuffer = Scene.prototype.createSceneUniformBuffer; +Scene.prototype._transformMatrixR = Matrix.Zero(); +Scene.prototype._multiviewSceneUbo = null; +Scene.prototype._createMultiviewUbo = function () { + this._multiviewSceneUbo = createMultiviewUbo(this.getEngine(), "scene_multiview"); +}; +Scene.prototype.createSceneUniformBuffer = function (name) { + if (this._multiviewSceneUbo) { + return createMultiviewUbo(this.getEngine(), name); + } + return currentCreateSceneUniformBuffer.bind(this)(name); +}; +Scene.prototype._updateMultiviewUbo = function (viewR, projectionR) { + if (viewR && projectionR) { + viewR.multiplyToRef(projectionR, this._transformMatrixR); + } + if (viewR && projectionR) { + viewR.multiplyToRef(projectionR, TmpVectors.Matrix[0]); + Frustum.GetRightPlaneToRef(TmpVectors.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane + } + if (this._multiviewSceneUbo) { + this._multiviewSceneUbo.updateMatrix("viewProjection", this.getTransformMatrix()); + this._multiviewSceneUbo.updateMatrix("viewProjectionR", this._transformMatrixR); + this._multiviewSceneUbo.updateMatrix("view", this._viewMatrix); + this._multiviewSceneUbo.updateMatrix("projection", this._projectionMatrix); + } +}; +Scene.prototype._renderMultiviewToSingleView = function (camera) { + // Multiview is only able to be displayed directly for API's such as webXR + // This displays a multiview image by rendering to the multiview image and then + // copying the result into the sub cameras instead of rendering them and proceeding as normal from there + // Render to a multiview texture + camera._resizeOrCreateMultiviewTexture(camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.width > 0 ? camera._rigPostProcess.width : this.getEngine().getRenderWidth(true), camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.height > 0 ? camera._rigPostProcess.height : this.getEngine().getRenderHeight(true)); + if (!this._multiviewSceneUbo) { + this._createMultiviewUbo(); + } + camera.outputRenderTarget = camera._multiviewTexture; + this._renderForCamera(camera); + camera.outputRenderTarget = null; + // Consume the multiview texture through a shader for each eye + for (let index = 0; index < camera._rigCameras.length; index++) { + const engine = this.getEngine(); + this._activeCamera = camera._rigCameras[index]; + engine.setViewport(this._activeCamera.viewport); + if (this.postProcessManager) { + this.postProcessManager._prepareFrame(); + this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate); + } + } +}; + +/** + * VRMultiviewToSingleview used to convert multiview texture arrays to standard textures for scenarios such as webVR + * This will not be used for webXR as it supports displaying texture arrays directly + */ +class VRMultiviewToSingleviewPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "VRMultiviewToSingleviewPostProcess" string + */ + getClassName() { + return "VRMultiviewToSingleviewPostProcess"; + } + /** + * Initializes a VRMultiviewToSingleview + * @param name name of the post process + * @param camera camera to be applied to + * @param scaleFactor scaling factor to the size of the output texture + */ + constructor(name, camera, scaleFactor) { + super(name, "vrMultiviewToSingleview", ["imageIndex"], ["multiviewSampler"], scaleFactor, camera, Texture.BILINEAR_SAMPLINGMODE); + const cam = camera ?? this.getCamera(); + this.onSizeChangedObservable.add(() => { }); + this.onApplyObservable.add((effect) => { + if (cam._scene.activeCamera && cam._scene.activeCamera.isLeftCamera) { + effect.setInt("imageIndex", 0); + } + else { + effect.setInt("imageIndex", 1); + } + effect.setTexture("multiviewSampler", cam._multiviewTexture); + }); + } +} + +/** + * @internal + */ +function setVRRigMode(camera, rigParams) { + const metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault(); + camera._rigCameras[0]._cameraRigParams.vrMetrics = metrics; + camera._rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1.0); + camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new Matrix(); + camera._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix; + camera._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix; + camera._rigCameras[0].getProjectionMatrix = camera._rigCameras[0]._getVRProjectionMatrix; + camera._rigCameras[1]._cameraRigParams.vrMetrics = metrics; + camera._rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0); + camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new Matrix(); + camera._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix; + camera._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix; + camera._rigCameras[1].getProjectionMatrix = camera._rigCameras[1]._getVRProjectionMatrix; + // For multiview camera + // First multiview will be rendered to camera._multiviewTexture + // Then this postprocess will run on each eye to copy the right texture to each eye + if (metrics.multiviewEnabled) { + if (!camera.getScene().getEngine().getCaps().multiview) { + Logger.Warn("Multiview is not supported, falling back to standard rendering"); + metrics.multiviewEnabled = false; + } + else { + camera._useMultiviewToSingleView = true; + camera._rigPostProcess = new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview", camera, metrics.postProcessScaleFactor); + } + } + if (metrics.compensateDistortion) { + camera._rigCameras[0]._rigPostProcess = new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", camera._rigCameras[0], false, metrics); + camera._rigCameras[1]._rigPostProcess = new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", camera._rigCameras[1], true, metrics); + } +} + +Node$2.AddNodeConstructor("VRDeviceOrientationArcRotateCamera", (name, scene) => { + return () => new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), scene); +}); +/** + * Camera used to simulate VR rendering (based on ArcRotateCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras + */ +class VRDeviceOrientationArcRotateCamera extends ArcRotateCamera { + /** + * Creates a new VRDeviceOrientationArcRotateCamera + * @param name defines camera name + * @param alpha defines the camera rotation along the longitudinal axis + * @param beta defines the camera rotation along the latitudinal axis + * @param radius defines the camera distance from its target + * @param target defines the camera target + * @param scene defines the scene the camera belongs to + * @param compensateDistortion defines if the camera needs to compensate the lens distortion + * @param vrCameraMetrics defines the vr metrics associated to the camera + */ + constructor(name, alpha, beta, radius, target, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) { + super(name, alpha, beta, radius, target, scene); + this._setRigMode = (rigParams) => setVRRigMode(this, rigParams); + vrCameraMetrics.compensateDistortion = compensateDistortion; + this.setCameraRigMode(Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); + this.inputs.addVRDeviceOrientation(); + } + /** + * Gets camera class name + * @returns VRDeviceOrientationArcRotateCamera + */ + getClassName() { + return "VRDeviceOrientationArcRotateCamera"; + } +} + +Node$2.AddNodeConstructor("VRDeviceOrientationFreeCamera", (name, scene) => { + return () => new VRDeviceOrientationFreeCamera(name, Vector3.Zero(), scene); +}); +/** + * Camera used to simulate VR rendering (based on FreeCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras + */ +class VRDeviceOrientationFreeCamera extends DeviceOrientationCamera { + /** + * Creates a new VRDeviceOrientationFreeCamera + * @param name defines camera name + * @param position defines the start position of the camera + * @param scene defines the scene the camera belongs to + * @param compensateDistortion defines if the camera needs to compensate the lens distortion + * @param vrCameraMetrics defines the vr metrics associated to the camera + */ + constructor(name, position, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) { + super(name, position, scene); + this._setRigMode = (rigParams) => setVRRigMode(this, rigParams); + vrCameraMetrics.compensateDistortion = compensateDistortion; + this.setCameraRigMode(Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); + } + /** + * Gets camera class name + * @returns VRDeviceOrientationFreeCamera + */ + getClassName() { + return "VRDeviceOrientationFreeCamera"; + } +} + +Node$2.AddNodeConstructor("VRDeviceOrientationGamepadCamera", (name, scene) => { + return () => new VRDeviceOrientationGamepadCamera(name, Vector3.Zero(), scene); +}); +/** + * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera) + * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras + */ +class VRDeviceOrientationGamepadCamera extends VRDeviceOrientationFreeCamera { + /** + * Creates a new VRDeviceOrientationGamepadCamera + * @param name defines camera name + * @param position defines the start position of the camera + * @param scene defines the scene the camera belongs to + * @param compensateDistortion defines if the camera needs to compensate the lens distortion + * @param vrCameraMetrics defines the vr metrics associated to the camera + */ + constructor(name, position, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) { + super(name, position, scene, compensateDistortion, vrCameraMetrics); + this._setRigMode = (rigParams) => setVRRigMode(this, rigParams); + this.inputs.addGamepad(); + } + /** + * Gets camera class name + * @returns VRDeviceOrientationGamepadCamera + */ + getClassName() { + return "VRDeviceOrientationGamepadCamera"; + } +} + +ThinEngine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) { + const texture = new InternalTexture(this, 4 /* InternalTextureSource.Dynamic */); + texture.baseWidth = width; + texture.baseHeight = height; + if (generateMipMaps) { + width = this.needPOTTextures ? GetExponentOfTwo(width, this._caps.maxTextureSize) : width; + height = this.needPOTTextures ? GetExponentOfTwo(height, this._caps.maxTextureSize) : height; + } + // this.resetTextureCache(); + texture.width = width; + texture.height = height; + texture.isReady = false; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + this.updateTextureSamplingMode(samplingMode, texture); + this._internalTexturesCache.push(texture); + return texture; +}; +ThinEngine.prototype.updateDynamicTexture = function (texture, source, invertY, premulAlpha = false, format, forceBindTexture = false, +// eslint-disable-next-line @typescript-eslint/no-unused-vars +allowGPUOptimization = false) { + if (!texture) { + return; + } + const gl = this._gl; + const target = gl.TEXTURE_2D; + const wasPreviouslyBound = this._bindTextureDirectly(target, texture, true, forceBindTexture); + this._unpackFlipY(invertY === undefined ? texture.invertY : invertY); + if (premulAlpha) { + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); + } + const textureType = this._getWebGLTextureType(texture.type); + const glformat = this._getInternalFormat(format ? format : texture.format); + const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, glformat); + gl.texImage2D(target, 0, internalFormat, glformat, textureType, source); + if (texture.generateMipMaps) { + gl.generateMipmap(target); + } + if (!wasPreviouslyBound) { + this._bindTextureDirectly(target, null); + } + if (premulAlpha) { + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); + } + if (format) { + texture.format = format; + } + texture._dynamicTextureSource = source; + texture._premulAlpha = premulAlpha; + texture.invertY = invertY || false; + texture.isReady = true; +}; + +/** + * A class extending Texture allowing drawing on a texture + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/dynamicTexture + */ +class DynamicTexture extends Texture { + /** @internal */ + constructor(name, canvasOrSize, sceneOrOptions, generateMipMaps = false, samplingMode = 3, format = 5, invertY) { + const isScene = !sceneOrOptions || sceneOrOptions._isScene; + const scene = isScene ? sceneOrOptions : sceneOrOptions?.scene; + const noMipmap = isScene ? !generateMipMaps : sceneOrOptions; + super(null, scene, noMipmap, invertY, samplingMode, undefined, undefined, undefined, undefined, format); + this.name = name; + this.wrapU = Texture.CLAMP_ADDRESSMODE; + this.wrapV = Texture.CLAMP_ADDRESSMODE; + this._generateMipMaps = generateMipMaps; + const engine = this._getEngine(); + if (!engine) { + return; + } + if (canvasOrSize.getContext) { + this._canvas = canvasOrSize; + this._ownCanvas = false; + this._texture = engine.createDynamicTexture(this._canvas.width, this._canvas.height, generateMipMaps, samplingMode); + } + else { + this._canvas = engine.createCanvas(1, 1); + this._ownCanvas = true; + const optionsAsSize = canvasOrSize; + if (optionsAsSize.width || optionsAsSize.width === 0) { + this._texture = engine.createDynamicTexture(optionsAsSize.width, optionsAsSize.height, generateMipMaps, samplingMode); + } + else { + this._texture = engine.createDynamicTexture(canvasOrSize, canvasOrSize, generateMipMaps, samplingMode); + } + } + const textureSize = this.getSize(); + if (this._canvas.width !== textureSize.width) { + this._canvas.width = textureSize.width; + } + if (this._canvas.height !== textureSize.height) { + this._canvas.height = textureSize.height; + } + this._context = this._canvas.getContext("2d"); + } + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "DynamicTexture" + */ + getClassName() { + return "DynamicTexture"; + } + /** + * Gets the current state of canRescale + */ + get canRescale() { + return true; + } + _recreate(textureSize) { + this._canvas.width = textureSize.width; + this._canvas.height = textureSize.height; + this.releaseInternalTexture(); + this._texture = this._getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this.samplingMode); + } + /** + * Scales the texture + * @param ratio the scale factor to apply to both width and height + */ + scale(ratio) { + const textureSize = this.getSize(); + textureSize.width *= ratio; + textureSize.height *= ratio; + this._recreate(textureSize); + } + /** + * Resizes the texture + * @param width the new width + * @param height the new height + */ + scaleTo(width, height) { + const textureSize = this.getSize(); + textureSize.width = width; + textureSize.height = height; + this._recreate(textureSize); + } + /** + * Gets the context of the canvas used by the texture + * @returns the canvas context of the dynamic texture + */ + getContext() { + return this._context; + } + /** + * Clears the texture + * @param clearColor Defines the clear color to use + */ + clear(clearColor) { + const size = this.getSize(); + if (clearColor) { + this._context.fillStyle = clearColor; + } + this._context.clearRect(0, 0, size.width, size.height); + } + /** + * Updates the texture + * @param invertY defines the direction for the Y axis (default is true - y increases downwards) + * @param premulAlpha defines if alpha is stored as premultiplied (default is false) + * @param allowGPUOptimization true to allow some specific GPU optimizations (subject to engine feature "allowGPUOptimizationsForGUI" being true) + */ + update(invertY, premulAlpha = false, allowGPUOptimization = false) { + this._getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined, undefined, allowGPUOptimization); + } + /** + * Draws text onto the texture + * @param text defines the text to be drawn + * @param x defines the placement of the text from the left + * @param y defines the placement of the text from the top when invertY is true and from the bottom when false + * @param font defines the font to be used with font-style, font-size, font-name + * @param color defines the color used for the text + * @param fillColor defines the color for the canvas, use null to not overwrite canvas (this bleands with the background to replace, use the clear function) + * @param invertY defines the direction for the Y axis (default is true - y increases downwards) + * @param update defines whether texture is immediately update (default is true) + */ + drawText(text, x, y, font, color, fillColor, invertY, update = true) { + const size = this.getSize(); + if (fillColor) { + this._context.fillStyle = fillColor; + this._context.fillRect(0, 0, size.width, size.height); + } + this._context.font = font; + if (x === null || x === undefined) { + const textSize = this._context.measureText(text); + x = (size.width - textSize.width) / 2; + } + if (y === null || y === undefined) { + const fontSize = parseInt(font.replace(/\D/g, "")); + y = size.height / 2 + fontSize / 3.65; + } + this._context.fillStyle = color || ""; + this._context.fillText(text, x, y); + if (update) { + this.update(invertY); + } + } + /** + * Disposes the dynamic texture. + */ + dispose() { + super.dispose(); + if (this._ownCanvas) { + this._canvas?.remove?.(); + } + this._canvas = null; + this._context = null; + } + /** + * Clones the texture + * @returns the clone of the texture. + */ + clone() { + const scene = this.getScene(); + if (!scene) { + return this; + } + const textureSize = this.getSize(); + const newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps); + // Base texture + newTexture.hasAlpha = this.hasAlpha; + newTexture.level = this.level; + // Dynamic Texture + newTexture.wrapU = this.wrapU; + newTexture.wrapV = this.wrapV; + return newTexture; + } + /** + * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized + * @returns a serialized dynamic texture object + */ + serialize() { + const scene = this.getScene(); + if (scene && !scene.isReady()) { + Logger.Warn("The scene must be ready before serializing the dynamic texture"); + } + const serializationObject = super.serialize(); + if (DynamicTexture._IsCanvasElement(this._canvas)) { + serializationObject.base64String = this._canvas.toDataURL(); + } + serializationObject.invertY = this._invertY; + serializationObject.samplingMode = this.samplingMode; + return serializationObject; + } + static _IsCanvasElement(canvas) { + return canvas.toDataURL !== undefined; + } + /** @internal */ + _rebuild() { + this.update(); + } +} + +/** + * Wrapper over subclasses of XRLayer. + * @internal + */ +class WebXRLayerWrapper { + /** + * Check if fixed foveation is supported on this device + */ + get isFixedFoveationSupported() { + return this.layerType == "XRWebGLLayer" && typeof this.layer.fixedFoveation == "number"; + } + /** + * Get the fixed foveation currently set, as specified by the webxr specs + * If this returns null, then fixed foveation is not supported + */ + get fixedFoveation() { + if (this.isFixedFoveationSupported) { + return this.layer.fixedFoveation; + } + return null; + } + /** + * Set the fixed foveation to the specified value, as specified by the webxr specs + * This value will be normalized to be between 0 and 1, 1 being max foveation, 0 being no foveation + */ + set fixedFoveation(value) { + if (this.isFixedFoveationSupported) { + const val = Math.max(0, Math.min(1, value || 0)); + this.layer.fixedFoveation = val; + } + } + /** + * Create a render target provider for the wrapped layer. + * @param xrSessionManager The XR Session Manager + * @returns A new render target texture provider for the wrapped layer. + */ + createRenderTargetTextureProvider(xrSessionManager) { + this._rttWrapper = this._createRenderTargetTextureProvider(xrSessionManager); + return this._rttWrapper; + } + dispose() { + if (this._rttWrapper) { + this._rttWrapper.dispose(); + this._rttWrapper = null; + } + } + constructor( + /** The width of the layer's framebuffer. */ + getWidth, + /** The height of the layer's framebuffer. */ + getHeight, + /** The XR layer that this WebXRLayerWrapper wraps. */ + layer, + /** The type of XR layer that is being wrapped. */ + layerType, + /** Create a render target provider for the wrapped layer. */ + _createRenderTargetTextureProvider) { + this.getWidth = getWidth; + this.getHeight = getHeight; + this.layer = layer; + this.layerType = layerType; + this._createRenderTargetTextureProvider = _createRenderTargetTextureProvider; + this._rttWrapper = null; + } +} + +/** + * Provides render target textures and other important rendering information for a given XRLayer. + * @internal + */ +class WebXRLayerRenderTargetTextureProvider { + constructor(_scene, layerWrapper) { + this._scene = _scene; + this.layerWrapper = layerWrapper; + this._renderTargetTextures = new Array(); + this._engine = _scene.getEngine(); + } + _createInternalTexture(textureSize, texture) { + const internalTexture = new InternalTexture(this._engine, 0 /* InternalTextureSource.Unknown */, true); + internalTexture.width = textureSize.width; + internalTexture.height = textureSize.height; + internalTexture._hardwareTexture = new WebGLHardwareTexture(texture, this._engine._gl); + internalTexture.isReady = true; + return internalTexture; + } + _createRenderTargetTexture(width, height, framebuffer, colorTexture, depthStencilTexture, multiview) { + if (!this._engine) { + throw new Error("Engine is disposed"); + } + const textureSize = { width, height }; + // Create render target texture from the internal texture + const renderTargetTexture = multiview ? new MultiviewRenderTarget(this._scene, textureSize) : new RenderTargetTexture("XR renderTargetTexture", textureSize, this._scene); + const renderTargetWrapper = renderTargetTexture.renderTarget; + renderTargetWrapper._samples = renderTargetTexture.samples; + // Set the framebuffer, make sure it works in all scenarios - emulator, no layers and layers + if (framebuffer || !colorTexture) { + renderTargetWrapper._framebuffer = framebuffer; + } + // Create internal texture + if (colorTexture) { + if (multiview) { + renderTargetWrapper._colorTextureArray = colorTexture; + } + else { + const internalTexture = this._createInternalTexture(textureSize, colorTexture); + renderTargetWrapper.setTexture(internalTexture, 0); + renderTargetTexture._texture = internalTexture; + } + } + if (depthStencilTexture) { + if (multiview) { + renderTargetWrapper._depthStencilTextureArray = depthStencilTexture; + } + else { + renderTargetWrapper._depthStencilTexture = this._createInternalTexture(textureSize, depthStencilTexture); + } + } + renderTargetTexture.disableRescaling(); + this._renderTargetTextures.push(renderTargetTexture); + return renderTargetTexture; + } + _destroyRenderTargetTexture(renderTargetTexture) { + this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(renderTargetTexture), 1); + renderTargetTexture.dispose(); + } + getFramebufferDimensions() { + return this._framebufferDimensions; + } + dispose() { + this._renderTargetTextures.forEach((rtt) => rtt.dispose()); + this._renderTargetTextures.length = 0; + } +} + +/** + * Wraps xr webgl layers. + * @internal + */ +class WebXRWebGLLayerWrapper extends WebXRLayerWrapper { + /** + * @param layer is the layer to be wrapped. + * @returns a new WebXRLayerWrapper wrapping the provided XRWebGLLayer. + */ + constructor(layer) { + super(() => layer.framebufferWidth, () => layer.framebufferHeight, layer, "XRWebGLLayer", (sessionManager) => new WebXRWebGLLayerRenderTargetTextureProvider(sessionManager.scene, this)); + this.layer = layer; + } +} +/** + * Provides render target textures and other important rendering information for a given XRWebGLLayer. + * @internal + */ +class WebXRWebGLLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider { + constructor(scene, layerWrapper) { + super(scene, layerWrapper); + this.layerWrapper = layerWrapper; + this._layer = layerWrapper.layer; + this._framebufferDimensions = { + framebufferWidth: this._layer.framebufferWidth, + framebufferHeight: this._layer.framebufferHeight, + }; + } + trySetViewportForView(viewport, view) { + const xrViewport = this._layer.getViewport(view); + if (!xrViewport) { + return false; + } + const framebufferWidth = this._framebufferDimensions.framebufferWidth; + const framebufferHeight = this._framebufferDimensions.framebufferHeight; + viewport.x = xrViewport.x / framebufferWidth; + viewport.y = xrViewport.y / framebufferHeight; + viewport.width = xrViewport.width / framebufferWidth; + viewport.height = xrViewport.height / framebufferHeight; + return true; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getRenderTargetTextureForEye(eye) { + const layerWidth = this._layer.framebufferWidth; + const layerHeight = this._layer.framebufferHeight; + const framebuffer = this._layer.framebuffer; + if (!this._rtt || + layerWidth !== this._framebufferDimensions.framebufferWidth || + layerHeight !== this._framebufferDimensions.framebufferHeight || + framebuffer !== this._framebuffer) { + this._rtt = this._createRenderTargetTexture(layerWidth, layerHeight, framebuffer); + this._framebufferDimensions.framebufferWidth = layerWidth; + this._framebufferDimensions.framebufferHeight = layerHeight; + this._framebuffer = framebuffer; + } + return this._rtt; + } + getRenderTargetTextureForView(view) { + return this.getRenderTargetTextureForEye(view.eye); + } +} + +/** + * Configuration object for WebXR output canvas + */ +class WebXRManagedOutputCanvasOptions { + /** + * Get the default values of the configuration object + * @param engine defines the engine to use (can be null) + * @returns default values of this configuration object + */ + static GetDefaults(engine) { + const defaults = new WebXRManagedOutputCanvasOptions(); + defaults.canvasOptions = { + antialias: true, + depth: true, + stencil: engine ? engine.isStencilEnable : true, + alpha: true, + framebufferScaleFactor: 1, + }; + defaults.newCanvasCssStyle = "position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;"; + return defaults; + } +} +/** + * Creates a canvas that is added/removed from the webpage when entering/exiting XR + */ +class WebXRManagedOutputCanvas { + /** + * Initializes the canvas to be added/removed upon entering/exiting xr + * @param _xrSessionManager The XR Session manager + * @param _options optional configuration for this canvas output. defaults will be used if not provided + */ + constructor(_xrSessionManager, _options = WebXRManagedOutputCanvasOptions.GetDefaults()) { + this._options = _options; + this._canvas = null; + this._engine = null; + /** + * xr layer for the canvas + */ + this.xrLayer = null; + this._xrLayerWrapper = null; + /** + * Observers registered here will be triggered when the xr layer was initialized + */ + this.onXRLayerInitObservable = new Observable(); + this._engine = _xrSessionManager.scene.getEngine(); + this._engine.onDisposeObservable.addOnce(() => { + this._engine = null; + }); + if (!_options.canvasElement) { + const canvas = document.createElement("canvas"); + canvas.style.cssText = this._options.newCanvasCssStyle || "position:absolute; bottom:0px;right:0px;"; + this._setManagedOutputCanvas(canvas); + } + else { + this._setManagedOutputCanvas(_options.canvasElement); + } + _xrSessionManager.onXRSessionInit.add(() => { + this._addCanvas(); + }); + _xrSessionManager.onXRSessionEnded.add(() => { + this._removeCanvas(); + }); + this._makeCanvasCompatibleAsync(); + } + /** + * Disposes of the object + */ + dispose() { + this._removeCanvas(); + this._setManagedOutputCanvas(null); + this.onXRLayerInitObservable.clear(); + } + _makeCanvasCompatibleAsync() { + this._canvasCompatiblePromise = new Promise((resolve, reject) => { + // stay safe - make sure the context has the function + try { + if (this.canvasContext && this.canvasContext.makeXRCompatible) { + this.canvasContext.makeXRCompatible().then(() => { + resolve(); + }, () => { + // fail silently + Tools.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly."); + resolve(); + }); + } + else { + resolve(); + } + } + catch (e) { + // if this fails - the exception will be caught and the promise will be rejected + reject(e); + } + }); + } + /** + * Initializes a XRWebGLLayer to be used as the session's baseLayer. + * @param xrSession xr session + * @returns a promise that will resolve once the XR Layer has been created + */ + async initializeXRLayerAsync(xrSession) { + const createLayer = () => { + this.xrLayer = new XRWebGLLayer(xrSession, this.canvasContext, this._options.canvasOptions); + this._xrLayerWrapper = new WebXRWebGLLayerWrapper(this.xrLayer); + this.onXRLayerInitObservable.notifyObservers(this.xrLayer); + return this.xrLayer; + }; + return this._canvasCompatiblePromise + .then( + // catch any error and continue. When using the emulator is throws this error for no apparent reason. + () => { }, () => { }) + .then(() => { + return createLayer(); + }); + } + _addCanvas() { + if (this._canvas && this._engine && this._canvas !== this._engine.getRenderingCanvas()) { + document.body.appendChild(this._canvas); + } + if (this.xrLayer) { + this._setCanvasSize(true); + } + else { + this.onXRLayerInitObservable.addOnce(() => { + this._setCanvasSize(true); + }); + } + } + _removeCanvas() { + if (this._canvas && this._engine && document.body.contains(this._canvas) && this._canvas !== this._engine.getRenderingCanvas()) { + document.body.removeChild(this._canvas); + } + this._setCanvasSize(false); + } + _setCanvasSize(init = true, xrLayer = this._xrLayerWrapper) { + if (!this._canvas || !this._engine) { + return; + } + if (init) { + if (xrLayer) { + if (this._canvas !== this._engine.getRenderingCanvas()) { + this._canvas.style.width = xrLayer.getWidth() + "px"; + this._canvas.style.height = xrLayer.getHeight() + "px"; + } + else { + this._engine.setSize(xrLayer.getWidth(), xrLayer.getHeight()); + } + } + } + else { + if (this._originalCanvasSize) { + if (this._canvas !== this._engine.getRenderingCanvas()) { + this._canvas.style.width = this._originalCanvasSize.width + "px"; + this._canvas.style.height = this._originalCanvasSize.height + "px"; + } + else { + this._engine.setSize(this._originalCanvasSize.width, this._originalCanvasSize.height); + } + } + } + } + _setManagedOutputCanvas(canvas) { + this._removeCanvas(); + if (!canvas) { + this._canvas = null; + this.canvasContext = null; + } + else { + this._originalCanvasSize = { + width: canvas.offsetWidth, + height: canvas.offsetHeight, + }; + this._canvas = canvas; + this.canvasContext = this._canvas.getContext("webgl2"); + if (!this.canvasContext) { + this.canvasContext = this._canvas.getContext("webgl"); + } + } + } +} + +/** + * Wraps XRWebGLLayer's created by Babylon Native. + * @internal + */ +class NativeXRLayerWrapper extends WebXRLayerWrapper { + constructor(layer) { + super(() => layer.framebufferWidth, () => layer.framebufferHeight, layer, "XRWebGLLayer", (sessionManager) => new NativeXRLayerRenderTargetTextureProvider(sessionManager, this)); + this.layer = layer; + } +} +/** + * Provides render target textures for layers created by Babylon Native. + * @internal + */ +class NativeXRLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider { + constructor(sessionManager, layerWrapper) { + super(sessionManager.scene, layerWrapper); + this.layerWrapper = layerWrapper; + this._nativeRTTProvider = navigator.xr.getNativeRenderTargetProvider(sessionManager.session, this._createRenderTargetTexture.bind(this), this._destroyRenderTargetTexture.bind(this)); + this._nativeLayer = layerWrapper.layer; + } + trySetViewportForView(viewport) { + viewport.x = 0; + viewport.y = 0; + viewport.width = 1; + viewport.height = 1; + return true; + } + getRenderTargetTextureForEye(eye) { + // TODO (rgerd): Update the contract on the BabylonNative side to call this "getRenderTargetTextureForEye" + return this._nativeRTTProvider.getRenderTargetForEye(eye); + } + getRenderTargetTextureForView(view) { + return this._nativeRTTProvider.getRenderTargetForEye(view.eye); + } + getFramebufferDimensions() { + return { + framebufferWidth: this._nativeLayer.framebufferWidth, + framebufferHeight: this._nativeLayer.framebufferHeight, + }; + } +} +/** + * Creates the xr layer that will be used as the xr session's base layer. + * @internal + */ +class NativeXRRenderTarget { + constructor(_xrSessionManager) { + this._nativeRenderTarget = navigator.xr.getWebXRRenderTarget(_xrSessionManager.scene.getEngine()); + } + async initializeXRLayerAsync(xrSession) { + await this._nativeRenderTarget.initializeXRLayerAsync(xrSession); + this.xrLayer = this._nativeRenderTarget.xrLayer; + return this.xrLayer; + } + dispose() { + /* empty */ + } +} + +/** + * Manages an XRSession to work with Babylon's engine + * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRSessionManagers + */ +class WebXRSessionManager { + /** + * Scale factor to apply to all XR-related elements (camera, controllers) + */ + get worldScalingFactor() { + return this._worldScalingFactor; + } + set worldScalingFactor(value) { + const oldValue = this._worldScalingFactor; + this._worldScalingFactor = value; + this.onWorldScaleFactorChangedObservable.notifyObservers({ + previousScaleFactor: oldValue, + newScaleFactor: value, + }); + } + /** + * Constructs a WebXRSessionManager, this must be initialized within a user action before usage + * @param scene The scene which the session should be created for + */ + constructor( + /** The scene which the session should be created for */ + scene) { + this.scene = scene; + /** WebXR timestamp updated every frame */ + this.currentTimestamp = -1; + /** + * Used just in case of a failure to initialize an immersive session. + * The viewer reference space is compensated using this height, creating a kind of "viewer-floor" reference space + */ + this.defaultHeightCompensation = 1.7; + /** + * Fires every time a new xrFrame arrives which can be used to update the camera + */ + this.onXRFrameObservable = new Observable(); + /** + * Fires when the reference space changed + */ + this.onXRReferenceSpaceChanged = new Observable(); + /** + * Fires when the xr session is ended either by the device or manually done + */ + this.onXRSessionEnded = new Observable(); + /** + * Fires when the xr session is initialized: right after requestSession was called and returned with a successful result + */ + this.onXRSessionInit = new Observable(); + /** + * Fires when the xr reference space has been initialized + */ + this.onXRReferenceSpaceInitialized = new Observable(); + /** + * Fires when the session manager is rendering the first frame + */ + this.onXRReady = new Observable(); + /** + * Are we currently in the XR loop? + */ + this.inXRFrameLoop = false; + /** + * Are we in an XR session? + */ + this.inXRSession = false; + this._worldScalingFactor = 1; + /** + * Observable raised when the world scale has changed + */ + this.onWorldScaleFactorChangedObservable = new Observable(undefined, true); + this._engine = scene.getEngine(); + this._onEngineDisposedObserver = this._engine.onDisposeObservable.addOnce(() => { + this._engine = null; + }); + scene.onDisposeObservable.addOnce(() => { + this.dispose(); + }); + } + /** + * The current reference space used in this session. This reference space can constantly change! + * It is mainly used to offset the camera's position. + */ + get referenceSpace() { + return this._referenceSpace; + } + /** + * Set a new reference space and triggers the observable + */ + set referenceSpace(newReferenceSpace) { + this._referenceSpace = newReferenceSpace; + this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace); + } + /** + * The mode for the managed XR session + */ + get sessionMode() { + return this._sessionMode; + } + /** + * Disposes of the session manager + * This should be called explicitly by the dev, if required. + */ + dispose() { + // disposing without leaving XR? Exit XR first + if (this.inXRSession) { + this.exitXRAsync(); + } + this.onXRReady.clear(); + this.onXRFrameObservable.clear(); + this.onXRSessionEnded.clear(); + this.onXRReferenceSpaceChanged.clear(); + this.onXRSessionInit.clear(); + this.onWorldScaleFactorChangedObservable.clear(); + this._engine?.onDisposeObservable.remove(this._onEngineDisposedObserver); + this._engine = null; + } + /** + * Stops the xrSession and restores the render loop + * @returns Promise which resolves after it exits XR + */ + async exitXRAsync() { + if (this.session && this.inXRSession) { + this.inXRSession = false; + try { + return await this.session.end(); + } + catch { + Logger.Warn("Could not end XR session."); + } + } + return Promise.resolve(); + } + /** + * Attempts to set the framebuffer-size-normalized viewport to be rendered this frame for this view. + * In the event of a failure, the supplied viewport is not updated. + * @param viewport the viewport to which the view will be rendered + * @param view the view for which to set the viewport + * @returns whether the operation was successful + */ + trySetViewportForView(viewport, view) { + return this._baseLayerRTTProvider?.trySetViewportForView(viewport, view) || false; + } + /** + * Gets the correct render target texture to be rendered this frame for this eye + * @param eye the eye for which to get the render target + * @returns the render target for the specified eye or null if not available + */ + getRenderTargetTextureForEye(eye) { + return this._baseLayerRTTProvider?.getRenderTargetTextureForEye(eye) || null; + } + /** + * Gets the correct render target texture to be rendered this frame for this view + * @param view the view for which to get the render target + * @returns the render target for the specified view or null if not available + */ + getRenderTargetTextureForView(view) { + return this._baseLayerRTTProvider?.getRenderTargetTextureForView(view) || null; + } + /** + * Creates a WebXRRenderTarget object for the XR session + * @param options optional options to provide when creating a new render target + * @returns a WebXR render target to which the session can render + */ + getWebXRRenderTarget(options) { + const engine = this.scene.getEngine(); + if (this._xrNavigator.xr.native) { + return new NativeXRRenderTarget(this); + } + else { + options = options || WebXRManagedOutputCanvasOptions.GetDefaults(engine); + options.canvasElement = options.canvasElement || engine.getRenderingCanvas() || undefined; + return new WebXRManagedOutputCanvas(this, options); + } + } + /** + * Initializes the manager + * After initialization enterXR can be called to start an XR session + * @returns Promise which resolves after it is initialized + */ + initializeAsync() { + // Check if the browser supports webXR + this._xrNavigator = navigator; + if (!this._xrNavigator.xr) { + return Promise.reject("WebXR not available"); + } + return Promise.resolve(); + } + /** + * Initializes an xr session + * @param xrSessionMode mode to initialize + * @param xrSessionInit defines optional and required values to pass to the session builder + * @returns a promise which will resolve once the session has been initialized + */ + initializeSessionAsync(xrSessionMode = "immersive-vr", xrSessionInit = {}) { + return this._xrNavigator.xr.requestSession(xrSessionMode, xrSessionInit).then((session) => { + this.session = session; + this._sessionMode = xrSessionMode; + this.inXRSession = true; + this.onXRSessionInit.notifyObservers(session); + // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone) + this.session.addEventListener("end", () => { + this.inXRSession = false; + // Notify frame observers + this.onXRSessionEnded.notifyObservers(null); + if (this._engine) { + // make sure dimensions object is restored + this._engine.framebufferDimensionsObject = null; + // Restore frame buffer to avoid clear on xr framebuffer after session end + this._engine.restoreDefaultFramebuffer(); + // Need to restart render loop as after the session is ended the last request for new frame will never call callback + this._engine.customAnimationFrameRequester = null; + this._engine._renderLoop(); + } + // Dispose render target textures. + // Only dispose on native because we can't destroy opaque textures on browser. + if (this.isNative) { + this._baseLayerRTTProvider?.dispose(); + } + this._baseLayerRTTProvider = null; + this._baseLayerWrapper = null; + }, { once: true }); + return this.session; + }); + } + /** + * Checks if a session would be supported for the creation options specified + * @param sessionMode session mode to check if supported eg. immersive-vr + * @returns A Promise that resolves to true if supported and false if not + */ + isSessionSupportedAsync(sessionMode) { + return WebXRSessionManager.IsSessionSupportedAsync(sessionMode); + } + /** + * Resets the reference space to the one started the session + */ + resetReferenceSpace() { + this.referenceSpace = this.baseReferenceSpace; + } + /** + * Starts rendering to the xr layer + */ + runXRRenderLoop() { + if (!this.inXRSession || !this._engine) { + return; + } + // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information + this._engine.customAnimationFrameRequester = { + requestAnimationFrame: (callback) => this.session.requestAnimationFrame(callback), + renderFunction: (timestamp, xrFrame) => { + if (!this.inXRSession || !this._engine) { + return; + } + // Store the XR frame and timestamp in the session manager + this.currentFrame = xrFrame; + this.currentTimestamp = timestamp; + if (xrFrame) { + this.inXRFrameLoop = true; + const framebufferDimensionsObject = this._baseLayerRTTProvider?.getFramebufferDimensions() || null; + // equality can be tested as it should be the same object + if (this._engine.framebufferDimensionsObject !== framebufferDimensionsObject) { + this._engine.framebufferDimensionsObject = framebufferDimensionsObject; + } + this.onXRFrameObservable.notifyObservers(xrFrame); + this._engine._renderLoop(); + this._engine.framebufferDimensionsObject = null; + this.inXRFrameLoop = false; + } + }, + }; + this._engine.framebufferDimensionsObject = this._baseLayerRTTProvider?.getFramebufferDimensions() || null; + this.onXRFrameObservable.addOnce(() => { + this.onXRReady.notifyObservers(this); + }); + // Stop window's animation frame and trigger sessions animation frame + if (typeof window !== "undefined" && window.cancelAnimationFrame) { + window.cancelAnimationFrame(this._engine._frameHandler); + } + this._engine._renderLoop(); + } + /** + * Sets the reference space on the xr session + * @param referenceSpaceType space to set + * @returns a promise that will resolve once the reference space has been set + */ + setReferenceSpaceTypeAsync(referenceSpaceType = "local-floor") { + return this.session + .requestReferenceSpace(referenceSpaceType) + .then((referenceSpace) => { + return referenceSpace; + }, (rejectionReason) => { + Logger.Error("XR.requestReferenceSpace failed for the following reason: "); + Logger.Error(rejectionReason); + Logger.Log('Defaulting to universally-supported "viewer" reference space type.'); + return this.session.requestReferenceSpace("viewer").then((referenceSpace) => { + const heightCompensation = new XRRigidTransform({ x: 0, y: -this.defaultHeightCompensation, z: 0 }); + return referenceSpace.getOffsetReferenceSpace(heightCompensation); + }, (rejectionReason) => { + Logger.Error(rejectionReason); + // eslint-disable-next-line no-throw-literal + throw 'XR initialization failed: required "viewer" reference space type not supported.'; + }); + }) + .then((referenceSpace) => { + // create viewer reference space before setting the first reference space + return this.session.requestReferenceSpace("viewer").then((viewerReferenceSpace) => { + this.viewerReferenceSpace = viewerReferenceSpace; + return referenceSpace; + }); + }) + .then((referenceSpace) => { + // initialize the base and offset (currently the same) + this.referenceSpace = this.baseReferenceSpace = referenceSpace; + this.onXRReferenceSpaceInitialized.notifyObservers(referenceSpace); + return this.referenceSpace; + }); + } + /** + * Updates the render state of the session. + * Note that this is deprecated in favor of WebXRSessionManager.updateRenderState(). + * @param state state to set + * @returns a promise that resolves once the render state has been updated + * @deprecated Use updateRenderState() instead. + */ + updateRenderStateAsync(state) { + return Promise.resolve(this.session.updateRenderState(state)); + } + /** + * @internal + */ + _setBaseLayerWrapper(baseLayerWrapper) { + if (this.isNative) { + this._baseLayerRTTProvider?.dispose(); + } + this._baseLayerWrapper = baseLayerWrapper; + this._baseLayerRTTProvider = this._baseLayerWrapper?.createRenderTargetTextureProvider(this) || null; + } + /** + * @internal + */ + _getBaseLayerWrapper() { + return this._baseLayerWrapper; + } + /** + * Updates the render state of the session + * @param state state to set + */ + updateRenderState(state) { + if (state.baseLayer) { + this._setBaseLayerWrapper(this.isNative ? new NativeXRLayerWrapper(state.baseLayer) : new WebXRWebGLLayerWrapper(state.baseLayer)); + } + this.session.updateRenderState(state); + } + /** + * Returns a promise that resolves with a boolean indicating if the provided session mode is supported by this browser + * @param sessionMode defines the session to test + * @returns a promise with boolean as final value + */ + static IsSessionSupportedAsync(sessionMode) { + if (!navigator.xr) { + return Promise.resolve(false); + } + // When the specs are final, remove supportsSession! + const functionToUse = navigator.xr.isSessionSupported || navigator.xr.supportsSession; + if (!functionToUse) { + return Promise.resolve(false); + } + else { + return functionToUse + .call(navigator.xr, sessionMode) + .then((result) => { + const returnValue = typeof result === "undefined" ? true : result; + return Promise.resolve(returnValue); + }) + .catch((e) => { + Logger.Warn(e); + return Promise.resolve(false); + }); + } + } + /** + * Returns true if Babylon.js is using the BabylonNative backend, otherwise false + */ + get isNative() { + return this._xrNavigator.xr.native ?? false; + } + /** + * The current frame rate as reported by the device + */ + get currentFrameRate() { + return this.session?.frameRate; + } + /** + * A list of supported frame rates (only available in-session! + */ + get supportedFrameRates() { + return this.session?.supportedFrameRates; + } + /** + * Set the framerate of the session. + * @param rate the new framerate. This value needs to be in the supportedFrameRates array + * @returns a promise that resolves once the framerate has been set + */ + updateTargetFrameRate(rate) { + return this.session.updateTargetFrameRate(rate); + } + /** + * Run a callback in the xr render loop + * @param callback the callback to call when in XR Frame + * @param ignoreIfNotInSession if no session is currently running, run it first thing on the next session + */ + runInXRFrame(callback, ignoreIfNotInSession = true) { + if (this.inXRFrameLoop) { + callback(); + } + else if (this.inXRSession || !ignoreIfNotInSession) { + this.onXRFrameObservable.addOnce(callback); + } + } + /** + * Check if fixed foveation is supported on this device + */ + get isFixedFoveationSupported() { + return this._baseLayerWrapper?.isFixedFoveationSupported || false; + } + /** + * Get the fixed foveation currently set, as specified by the webxr specs + * If this returns null, then fixed foveation is not supported + */ + get fixedFoveation() { + return this._baseLayerWrapper?.fixedFoveation || null; + } + /** + * Set the fixed foveation to the specified value, as specified by the webxr specs + * This value will be normalized to be between 0 and 1, 1 being max foveation, 0 being no foveation + */ + set fixedFoveation(value) { + const val = Math.max(0, Math.min(1, value || 0)); + if (this._baseLayerWrapper) { + this._baseLayerWrapper.fixedFoveation = val; + } + } + /** + * Get the features enabled on the current session + * This is only available in-session! + * @see https://www.w3.org/TR/webxr/#dom-xrsession-enabledfeatures + */ + get enabledFeatures() { + return this.session?.enabledFeatures ?? null; + } +} + +Mesh._GroundMeshParser = (parsedMesh, scene) => { + return GroundMesh.Parse(parsedMesh, scene); +}; +/** + * Mesh representing the ground + */ +class GroundMesh extends Mesh { + constructor(name, scene) { + super(name, scene); + /** If octree should be generated */ + this.generateOctree = false; + } + /** + * "GroundMesh" + * @returns "GroundMesh" + */ + getClassName() { + return "GroundMesh"; + } + /** + * The minimum of x and y subdivisions + */ + get subdivisions() { + return Math.min(this._subdivisionsX, this._subdivisionsY); + } + /** + * X subdivisions + */ + get subdivisionsX() { + return this._subdivisionsX; + } + /** + * Y subdivisions + */ + get subdivisionsY() { + return this._subdivisionsY; + } + /** + * This function will divide the mesh into submeshes and update an octree to help to select the right submeshes + * for rendering, picking and collision computations. Please note that you must have a decent number of submeshes + * to get performance improvements when using an octree. + * @param chunksCount the number of submeshes the mesh will be divided into + * @param octreeBlocksSize the maximum size of the octree blocks (Default: 32) + */ + optimize(chunksCount, octreeBlocksSize = 32) { + this._subdivisionsX = chunksCount; + this._subdivisionsY = chunksCount; + this.subdivide(chunksCount); + // Call the octree system optimization if it is defined. + const thisAsAny = this; + if (thisAsAny.createOrUpdateSubmeshesOctree) { + thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize); + } + } + /** + * Returns a height (y) value in the World system : + * the ground altitude at the coordinates (x, z) expressed in the World system. + * @param x x coordinate + * @param z z coordinate + * @returns the ground y position if (x, z) are outside the ground surface. + */ + getHeightAtCoordinates(x, z) { + const world = this.getWorldMatrix(); + const invMat = TmpVectors.Matrix[5]; + world.invertToRef(invMat); + const tmpVect = TmpVectors.Vector3[8]; + Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space + x = tmpVect.x; + z = tmpVect.z; + if (x < this._minX || x >= this._maxX || z <= this._minZ || z > this._maxZ) { + return this.position.y; + } + if (!this._heightQuads || this._heightQuads.length == 0) { + this._initHeightQuads(); + this._computeHeightQuads(); + } + const facet = this._getFacetAt(x, z); + const y = -(facet.x * x + facet.z * z + facet.w) / facet.y; + // return y in the World system + Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect); + return tmpVect.y; + } + /** + * Returns a normalized vector (Vector3) orthogonal to the ground + * at the ground coordinates (x, z) expressed in the World system. + * @param x x coordinate + * @param z z coordinate + * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface. + */ + getNormalAtCoordinates(x, z) { + const normal = new Vector3(0.0, 1.0, 0.0); + this.getNormalAtCoordinatesToRef(x, z, normal); + return normal; + } + /** + * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground + * at the ground coordinates (x, z) expressed in the World system. + * Doesn't update the reference Vector3 if (x, z) are outside the ground surface. + * @param x x coordinate + * @param z z coordinate + * @param ref vector to store the result + * @returns the GroundMesh. + */ + getNormalAtCoordinatesToRef(x, z, ref) { + const world = this.getWorldMatrix(); + const tmpMat = TmpVectors.Matrix[5]; + world.invertToRef(tmpMat); + const tmpVect = TmpVectors.Vector3[8]; + Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space + x = tmpVect.x; + z = tmpVect.z; + if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) { + return this; + } + if (!this._heightQuads || this._heightQuads.length == 0) { + this._initHeightQuads(); + this._computeHeightQuads(); + } + const facet = this._getFacetAt(x, z); + Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref); + return this; + } + /** + * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates() + * if the ground has been updated. + * This can be used in the render loop. + * @returns the GroundMesh. + */ + updateCoordinateHeights() { + if (!this._heightQuads || this._heightQuads.length == 0) { + this._initHeightQuads(); + } + this._computeHeightQuads(); + return this; + } + // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates + _getFacetAt(x, z) { + // retrieve col and row from x, z coordinates in the ground local system + const col = Math.floor(((x + this._maxX) * this._subdivisionsX) / this._width); + const row = Math.floor((-(z + this._maxZ) * this._subdivisionsY) / this._height + this._subdivisionsY); + const quad = this._heightQuads[row * this._subdivisionsX + col]; + let facet; + if (z < quad.slope.x * x + quad.slope.y) { + facet = quad.facet1; + } + else { + facet = quad.facet2; + } + return facet; + } + // Creates and populates the heightMap array with "facet" elements : + // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets + // slope : Vector2(c, h) = 2D diagonal line equation setting apart two triangular facets in a quad : z = cx + h + // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0 + // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 + // Returns the GroundMesh. + _initHeightQuads() { + const subdivisionsX = this._subdivisionsX; + const subdivisionsY = this._subdivisionsY; + this._heightQuads = new Array(); + for (let row = 0; row < subdivisionsY; row++) { + for (let col = 0; col < subdivisionsX; col++) { + const quad = { slope: Vector2.Zero(), facet1: new Vector4(0.0, 0.0, 0.0, 0.0), facet2: new Vector4(0.0, 0.0, 0.0, 0.0) }; + this._heightQuads[row * subdivisionsX + col] = quad; + } + } + return this; + } + // Compute each quad element values and update the heightMap array : + // slope : Vector2(c, h) = 2D diagonal line equation setting apart two triangular facets in a quad : z = cx + h + // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0 + // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 + // Returns the GroundMesh. + _computeHeightQuads() { + const positions = this.getVerticesData(VertexBuffer.PositionKind); + if (!positions) { + return this; + } + const v1 = TmpVectors.Vector3[3]; + const v2 = TmpVectors.Vector3[2]; + const v3 = TmpVectors.Vector3[1]; + const v4 = TmpVectors.Vector3[0]; + const v1v2 = TmpVectors.Vector3[4]; + const v1v3 = TmpVectors.Vector3[5]; + const v1v4 = TmpVectors.Vector3[6]; + const norm1 = TmpVectors.Vector3[7]; + const norm2 = TmpVectors.Vector3[8]; + let i = 0; + let j = 0; + let k = 0; + let cd = 0; // 2D slope coefficient : z = cd * x + h + let h = 0; + let d1 = 0; // facet plane equation : ax + by + cz + d = 0 + let d2 = 0; + const subdivisionsX = this._subdivisionsX; + const subdivisionsY = this._subdivisionsY; + for (let row = 0; row < subdivisionsY; row++) { + for (let col = 0; col < subdivisionsX; col++) { + i = col * 3; + j = row * (subdivisionsX + 1) * 3; + k = (row + 1) * (subdivisionsX + 1) * 3; + v1.x = positions[j + i]; + v1.y = positions[j + i + 1]; + v1.z = positions[j + i + 2]; + v2.x = positions[j + i + 3]; + v2.y = positions[j + i + 4]; + v2.z = positions[j + i + 5]; + v3.x = positions[k + i]; + v3.y = positions[k + i + 1]; + v3.z = positions[k + i + 2]; + v4.x = positions[k + i + 3]; + v4.y = positions[k + i + 4]; + v4.z = positions[k + i + 5]; + // 2D slope V1V4 + cd = (v4.z - v1.z) / (v4.x - v1.x); + h = v1.z - cd * v1.x; // v1 belongs to the slope + // facet equations : + // we compute each facet normal vector + // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0 + // we compute the value d by applying the equation to v1 which belongs to the plane + // then we store the facet equation in a Vector4 + v2.subtractToRef(v1, v1v2); + v3.subtractToRef(v1, v1v3); + v4.subtractToRef(v1, v1v4); + Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class + Vector3.CrossToRef(v1v2, v1v4, norm2); + norm1.normalize(); + norm2.normalize(); + d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z); + d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z); + const quad = this._heightQuads[row * subdivisionsX + col]; + quad.slope.copyFromFloats(cd, h); + quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1); + quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2); + } + } + return this; + } + /** + * Serializes this ground mesh + * @param serializationObject object to write serialization to + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.subdivisionsX = this._subdivisionsX; + serializationObject.subdivisionsY = this._subdivisionsY; + serializationObject.minX = this._minX; + serializationObject.maxX = this._maxX; + serializationObject.minZ = this._minZ; + serializationObject.maxZ = this._maxZ; + serializationObject.width = this._width; + serializationObject.height = this._height; + } + /** + * Parses a serialized ground mesh + * @param parsedMesh the serialized mesh + * @param scene the scene to create the ground mesh in + * @returns the created ground mesh + */ + static Parse(parsedMesh, scene) { + const result = new GroundMesh(parsedMesh.name, scene); + result._subdivisionsX = parsedMesh.subdivisionsX || 1; + result._subdivisionsY = parsedMesh.subdivisionsY || 1; + result._minX = parsedMesh.minX; + result._maxX = parsedMesh.maxX; + result._minZ = parsedMesh.minZ; + result._maxZ = parsedMesh.maxZ; + result._width = parsedMesh.width; + result._height = parsedMesh.height; + return result; + } +} + +/** + * Creates the VertexData for a Ground + * @param options an object used to set the following optional parameters for the Ground, required but can be empty + * @param options.width the width (x direction) of the ground, optional, default 1 + * @param options.height the height (z direction) of the ground, optional, default 1 + * @param options.subdivisions the number of subdivisions per side, optional, default 1 + * @param options.subdivisionsX the number of subdivisions in the x direction, overrides options.subdivisions, optional, default undefined + * @param options.subdivisionsY the number of subdivisions in the y direction, overrides options.subdivisions, optional, default undefined + * @returns the VertexData of the Ground + */ +function CreateGroundVertexData(options) { + const indices = []; + const positions = []; + const normals = []; + const uvs = []; + let row, col; + const width = options.width || options.size || 1; + const height = options.height || options.size || 1; + const subdivisionsX = (options.subdivisionsX || options.subdivisions || 1) | 0; + const subdivisionsY = (options.subdivisionsY || options.subdivisions || 1) | 0; + for (row = 0; row <= subdivisionsY; row++) { + for (col = 0; col <= subdivisionsX; col++) { + const position = new Vector3((col * width) / subdivisionsX - width / 2.0, 0, ((subdivisionsY - row) * height) / subdivisionsY - height / 2.0); + const normal = new Vector3(0, 1.0, 0); + positions.push(position.x, position.y, position.z); + normals.push(normal.x, normal.y, normal.z); + uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY); + } + } + for (row = 0; row < subdivisionsY; row++) { + for (col = 0; col < subdivisionsX; col++) { + indices.push(col + 1 + (row + 1) * (subdivisionsX + 1)); + indices.push(col + 1 + row * (subdivisionsX + 1)); + indices.push(col + row * (subdivisionsX + 1)); + indices.push(col + (row + 1) * (subdivisionsX + 1)); + indices.push(col + 1 + (row + 1) * (subdivisionsX + 1)); + indices.push(col + row * (subdivisionsX + 1)); + } + } + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + return vertexData; +} +/** + * Creates the VertexData for a TiledGround by subdividing the ground into tiles + * @param options an object used to set the following optional parameters for the Ground + * @param options.xmin ground minimum X coordinate, default -1 + * @param options.zmin ground minimum Z coordinate, default -1 + * @param options.xmax ground maximum X coordinate, default 1 + * @param options.zmax ground maximum Z coordinate, default 1 + * @param options.subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6} + * @param options.subdivisions.w positive integer, default 6 + * @param options.subdivisions.h positive integer, default 6 + * @param options.precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2} + * @param options.precision.w positive integer, default 2 + * @param options.precision.h positive integer, default 2 + * @returns the VertexData of the TiledGround + */ +function CreateTiledGroundVertexData(options) { + const xmin = options.xmin !== undefined && options.xmin !== null ? options.xmin : -1; + const zmin = options.zmin !== undefined && options.zmin !== null ? options.zmin : -1; + const xmax = options.xmax !== undefined && options.xmax !== null ? options.xmax : 1.0; + const zmax = options.zmax !== undefined && options.zmax !== null ? options.zmax : 1.0; + const subdivisions = options.subdivisions || { w: 1, h: 1 }; + const precision = options.precision || { w: 1, h: 1 }; + const indices = []; + const positions = []; + const normals = []; + const uvs = []; + let row, col, tileRow, tileCol; + subdivisions.h = subdivisions.h < 1 ? 1 : subdivisions.h; + subdivisions.w = subdivisions.w < 1 ? 1 : subdivisions.w; + precision.w = precision.w < 1 ? 1 : precision.w; + precision.h = precision.h < 1 ? 1 : precision.h; + const tileSize = { + w: (xmax - xmin) / subdivisions.w, + h: (zmax - zmin) / subdivisions.h, + }; + function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) { + // Indices + const base = positions.length / 3; + const rowLength = precision.w + 1; + for (row = 0; row < precision.h; row++) { + for (col = 0; col < precision.w; col++) { + const square = [base + col + row * rowLength, base + (col + 1) + row * rowLength, base + (col + 1) + (row + 1) * rowLength, base + col + (row + 1) * rowLength]; + indices.push(square[1]); + indices.push(square[2]); + indices.push(square[3]); + indices.push(square[0]); + indices.push(square[1]); + indices.push(square[3]); + } + } + // Position, normals and uvs + const position = Vector3.Zero(); + const normal = new Vector3(0, 1.0, 0); + for (row = 0; row <= precision.h; row++) { + position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin; + for (col = 0; col <= precision.w; col++) { + position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin; + position.y = 0; + positions.push(position.x, position.y, position.z); + normals.push(normal.x, normal.y, normal.z); + uvs.push(col / precision.w, row / precision.h); + } + } + } + for (tileRow = 0; tileRow < subdivisions.h; tileRow++) { + for (tileCol = 0; tileCol < subdivisions.w; tileCol++) { + applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h); + } + } + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + return vertexData; +} +/** + * Creates the VertexData of the Ground designed from a heightmap + * @param options an object used to set the following parameters for the Ground, required and provided by CreateGroundFromHeightMap + * @param options.width the width (x direction) of the ground + * @param options.height the height (z direction) of the ground + * @param options.subdivisions the number of subdivisions per side + * @param options.minHeight the minimum altitude on the ground, optional, default 0 + * @param options.maxHeight the maximum altitude on the ground, optional default 1 + * @param options.colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11) + * @param options.buffer the array holding the image color data + * @param options.bufferWidth the width of image + * @param options.bufferHeight the height of image + * @param options.alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible) + * @param options.heightBuffer a array of floats where the height data can be saved, if its length is greater than zero. + * @returns the VertexData of the Ground designed from a heightmap + */ +function CreateGroundFromHeightMapVertexData(options) { + const indices = []; + const positions = []; + const normals = []; + const uvs = []; + let row, col; + const filter = options.colorFilter || new Color3(0.3, 0.59, 0.11); + const alphaFilter = options.alphaFilter || 0.0; + let invert = false; + if (options.minHeight > options.maxHeight) { + invert = true; + const temp = options.maxHeight; + options.maxHeight = options.minHeight; + options.minHeight = temp; + } + // Vertices + for (row = 0; row <= options.subdivisions; row++) { + for (col = 0; col <= options.subdivisions; col++) { + const position = new Vector3((col * options.width) / options.subdivisions - options.width / 2.0, 0, ((options.subdivisions - row) * options.height) / options.subdivisions - options.height / 2.0); + // Compute height + const heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0; + const heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0; + const pos = (heightMapX + heightMapY * options.bufferWidth) * 4; + let r = options.buffer[pos] / 255.0; + let g = options.buffer[pos + 1] / 255.0; + let b = options.buffer[pos + 2] / 255.0; + const a = options.buffer[pos + 3] / 255.0; + if (invert) { + r = 1.0 - r; + g = 1.0 - g; + b = 1.0 - b; + } + const gradient = r * filter.r + g * filter.g + b * filter.b; + // If our alpha channel is not within our filter then we will assign a 'special' height + // Then when building the indices, we will ignore any vertex that is using the special height + if (a >= alphaFilter) { + position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient; + } + else { + position.y = options.minHeight - Epsilon; // We can't have a height below minHeight, normally. + } + if (options.heightBuffer) { + // set the height buffer information in row major order. + options.heightBuffer[row * (options.subdivisions + 1) + col] = position.y; + } + // Add vertex + positions.push(position.x, position.y, position.z); + normals.push(0, 0, 0); + uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions); + } + } + // Indices + for (row = 0; row < options.subdivisions; row++) { + for (col = 0; col < options.subdivisions; col++) { + // Calculate Indices + const idx1 = col + 1 + (row + 1) * (options.subdivisions + 1); + const idx2 = col + 1 + row * (options.subdivisions + 1); + const idx3 = col + row * (options.subdivisions + 1); + const idx4 = col + (row + 1) * (options.subdivisions + 1); + // Check that all indices are visible (based on our special height) + // Only display the vertex if all Indices are visible + // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height + const isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight; + const isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight; + const isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight; + if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) { + indices.push(idx1); + indices.push(idx2); + indices.push(idx3); + } + const isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight; + if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) { + indices.push(idx4); + indices.push(idx1); + indices.push(idx3); + } + } + } + // Normals + VertexData.ComputeNormals(positions, indices, normals); + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + return vertexData; +} +/** + * Creates a ground mesh + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param options.width set the width size (float, default 1) + * @param options.height set the height size (float, default 1) + * @param options.subdivisions sets the number of subdivision per side (default 1) + * @param options.subdivisionsX sets the number of subdivision on the X axis (overrides subdivisions) + * @param options.subdivisionsY sets the number of subdivision on the Y axis (overrides subdivisions) + * @param options.updatable defines if the mesh must be flagged as updatable (default false) + * @param scene defines the hosting scene + * @returns the ground mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#ground + */ +function CreateGround(name, options = {}, scene) { + const ground = new GroundMesh(name, scene); + ground._setReady(false); + ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1; + ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1; + ground._width = options.width || 1; + ground._height = options.height || 1; + ground._maxX = ground._width / 2; + ground._maxZ = ground._height / 2; + ground._minX = -ground._maxX; + ground._minZ = -ground._maxZ; + const vertexData = CreateGroundVertexData(options); + vertexData.applyToMesh(ground, options.updatable); + ground._setReady(true); + return ground; +} +/** + * Creates a tiled ground mesh + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param options.xmin ground minimum X coordinate (float, default -1) + * @param options.zmin ground minimum Z coordinate (float, default -1) + * @param options.xmax ground maximum X coordinate (float, default 1) + * @param options.zmax ground maximum Z coordinate (float, default 1) + * @param options.subdivisions a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile + * @param options.subdivisions.w positive integer, default 6 + * @param options.subdivisions.h positive integer, default 6 + * @param options.precision a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile + * @param options.precision.w positive integer, default 2 + * @param options.precision.h positive integer, default 2 + * @param options.updatable boolean, default false, true if the mesh must be flagged as updatable + * @param scene defines the hosting scene + * @returns the tiled ground mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#tiled-ground + */ +function CreateTiledGround(name, options, scene = null) { + const tiledGround = new Mesh(name, scene); + const vertexData = CreateTiledGroundVertexData(options); + vertexData.applyToMesh(tiledGround, options.updatable); + return tiledGround; +} +/** + * Creates a ground mesh from a height map. The height map download can take some frames, + * so the mesh is not immediately ready. To wait for the mesh to be completely built, + * you should use the `onReady` callback option. + * @param name defines the name of the mesh + * @param url sets the URL of the height map image resource. + * @param options defines the options used to create the mesh + * @param options.width sets the ground width size (positive float, default 10) + * @param options.height sets the ground height size (positive float, default 10) + * @param options.subdivisions sets the number of subdivision per side (positive integer, default 1) + * @param options.minHeight is the minimum altitude on the ground (float, default 0) + * @param options.maxHeight is the maximum altitude on the ground (float, default 1) + * @param options.colorFilter is the filter to apply to the image pixel colors to compute the height (optional Color3, default (0.3, 0.59, 0.11) ) + * @param options.alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible) + * @param options.updatable defines if the mesh must be flagged as updatable + * @param options.onReady is a javascript callback function that will be called once the mesh is just built (the height map download can last some time) + * @param options.onError is a javascript callback function that will be called if there is an error + * @param options.passHeightBufferInCallback a boolean that indicates if the calculated height data will be passed in the onReady callback. Useful if you need the height data for physics, for example. + * @param scene defines the hosting scene + * @returns the ground mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/height_map + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#ground-from-a-height-map + */ +function CreateGroundFromHeightMap(name, url, options = {}, scene = null) { + const width = options.width || 10.0; + const height = options.height || 10.0; + const subdivisions = options.subdivisions || 1 | 0; + const minHeight = options.minHeight || 0.0; + const maxHeight = options.maxHeight || 1.0; + const filter = options.colorFilter || new Color3(0.3, 0.59, 0.11); + const alphaFilter = options.alphaFilter || 0.0; + const updatable = options.updatable; + const onReady = options.onReady; + scene = scene || EngineStore.LastCreatedScene; + const ground = new GroundMesh(name, scene); + ground._subdivisionsX = subdivisions; + ground._subdivisionsY = subdivisions; + ground._width = width; + ground._height = height; + ground._maxX = ground._width / 2.0; + ground._maxZ = ground._height / 2.0; + ground._minX = -ground._maxX; + ground._minZ = -ground._maxZ; + ground._setReady(false); + let heightBuffer; + if (options.passHeightBufferInCallback) { + heightBuffer = new Float32Array((subdivisions + 1) * (subdivisions + 1)); + } + const onBufferLoaded = (buffer, bufferWidth, bufferHeight) => { + const vertexData = CreateGroundFromHeightMapVertexData({ + width: width, + height: height, + subdivisions: subdivisions, + minHeight: minHeight, + maxHeight: maxHeight, + colorFilter: filter, + buffer: buffer, + bufferWidth: bufferWidth, + bufferHeight: bufferHeight, + alphaFilter: alphaFilter, + heightBuffer, + }); + vertexData.applyToMesh(ground, updatable); + //execute ready callback, if set + if (onReady) { + onReady(ground, heightBuffer); + } + ground._setReady(true); + }; + if (typeof url === "string") { + const onload = (img) => { + const bufferWidth = img.width; + const bufferHeight = img.height; + if (scene.isDisposed) { + return; + } + const buffer = scene?.getEngine().resizeImageBitmap(img, bufferWidth, bufferHeight); + onBufferLoaded(buffer, bufferWidth, bufferHeight); + }; + Tools.LoadImage(url, onload, options.onError ? options.onError : () => { }, scene.offlineProvider); + } + else { + onBufferLoaded(url.data, url.width, url.height); + } + return ground; +} +VertexData.CreateGround = CreateGroundVertexData; +VertexData.CreateTiledGround = CreateTiledGroundVertexData; +VertexData.CreateGroundFromHeightMap = CreateGroundFromHeightMapVertexData; +Mesh.CreateGround = (name, width, height, subdivisions, scene, updatable) => { + const options = { + width, + height, + subdivisions, + updatable, + }; + return CreateGround(name, options, scene); +}; +Mesh.CreateTiledGround = (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) => { + const options = { + xmin, + zmin, + xmax, + zmax, + subdivisions, + precision, + updatable, + }; + return CreateTiledGround(name, options, scene); +}; +Mesh.CreateGroundFromHeightMap = (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) => { + const options = { + width, + height, + subdivisions, + minHeight, + maxHeight, + updatable, + onReady, + alphaFilter, + }; + return CreateGroundFromHeightMap(name, url, options, scene); +}; + +/** + * Creates the VertexData for a torus + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * diameter the diameter of the torus, optional default 1 + * * thickness the diameter of the tube forming the torus, optional default 0.5 + * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @param options.diameter + * @param options.thickness + * @param options.tessellation + * @param options.sideOrientation + * @param options.frontUVs + * @param options.backUVs + * @returns the VertexData of the torus + */ +function CreateTorusVertexData(options) { + const indices = []; + const positions = []; + const normals = []; + const uvs = []; + const diameter = options.diameter || 1; + const thickness = options.thickness || 0.5; + const tessellation = (options.tessellation || 16) | 0; + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + const stride = tessellation + 1; + for (let i = 0; i <= tessellation; i++) { + const u = i / tessellation; + const outerAngle = (i * Math.PI * 2.0) / tessellation - Math.PI / 2.0; + const transform = Matrix.Translation(diameter / 2.0, 0, 0).multiply(Matrix.RotationY(outerAngle)); + for (let j = 0; j <= tessellation; j++) { + const v = 1 - j / tessellation; + const innerAngle = (j * Math.PI * 2.0) / tessellation + Math.PI; + const dx = Math.cos(innerAngle); + const dy = Math.sin(innerAngle); + // Create a vertex. + let normal = new Vector3(dx, dy, 0); + let position = normal.scale(thickness / 2); + const textureCoordinate = new Vector2(u, v); + position = Vector3.TransformCoordinates(position, transform); + normal = Vector3.TransformNormal(normal, transform); + positions.push(position.x, position.y, position.z); + normals.push(normal.x, normal.y, normal.z); + uvs.push(textureCoordinate.x, textureCoordinate.y); + // And create indices for two triangles. + const nextI = (i + 1) % stride; + const nextJ = (j + 1) % stride; + indices.push(i * stride + j); + indices.push(i * stride + nextJ); + indices.push(nextI * stride + j); + indices.push(i * stride + nextJ); + indices.push(nextI * stride + nextJ); + indices.push(nextI * stride + j); + } + } + // Sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + return vertexData; +} +/** + * Creates a torus mesh + * * The parameter `diameter` sets the diameter size (float) of the torus (default 1) + * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5) + * * The parameter `tessellation` sets the number of torus sides (positive integer, default 16) + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param options.diameter + * @param options.thickness + * @param options.tessellation + * @param options.updatable + * @param options.sideOrientation + * @param options.frontUVs + * @param options.backUVs + * @param scene defines the hosting scene + * @returns the torus mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#torus + */ +function CreateTorus(name, options = {}, scene) { + const torus = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + torus._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreateTorusVertexData(options); + vertexData.applyToMesh(torus, options.updatable); + return torus; +} +VertexData.CreateTorus = CreateTorusVertexData; +Mesh.CreateTorus = (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) => { + const options = { + diameter, + thickness, + tessellation, + sideOrientation, + updatable, + }; + return CreateTorus(name, options, scene); +}; + +class VRExperienceHelperGazer { + constructor(scene, gazeTrackerToClone = null) { + this.scene = scene; + /** @internal */ + this._pointerDownOnMeshAsked = false; + /** @internal */ + this._isActionableMesh = false; + /** @internal */ + this._teleportationRequestInitiated = false; + /** @internal */ + this._teleportationBackRequestInitiated = false; + /** @internal */ + this._rotationRightAsked = false; + /** @internal */ + this._rotationLeftAsked = false; + /** @internal */ + this._dpadPressed = true; + /** @internal */ + this._activePointer = false; + this._id = VRExperienceHelperGazer._IdCounter++; + // Gaze tracker + if (!gazeTrackerToClone) { + this._gazeTracker = CreateTorus("gazeTracker", { + diameter: 0.0035, + thickness: 0.0025, + tessellation: 20, + updatable: false, + }, scene); + this._gazeTracker.bakeCurrentTransformIntoVertices(); + this._gazeTracker.isPickable = false; + this._gazeTracker.isVisible = false; + const targetMat = new StandardMaterial("targetMat", scene); + targetMat.specularColor = Color3.Black(); + targetMat.emissiveColor = new Color3(0.7, 0.7, 0.7); + targetMat.backFaceCulling = false; + this._gazeTracker.material = targetMat; + } + else { + this._gazeTracker = gazeTrackerToClone.clone("gazeTracker"); + } + } + /** + * @internal + */ + _getForwardRay(length) { + return new Ray(Vector3.Zero(), new Vector3(0, 0, length)); + } + /** @internal */ + _selectionPointerDown() { + this._pointerDownOnMeshAsked = true; + if (this._currentHit) { + this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id }); + } + } + /** @internal */ + _selectionPointerUp() { + if (this._currentHit) { + this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id }); + } + this._pointerDownOnMeshAsked = false; + } + /** @internal */ + _activatePointer() { + this._activePointer = true; + } + /** @internal */ + _deactivatePointer() { + this._activePointer = false; + } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _updatePointerDistance(distance = 100) { } + dispose() { + this._interactionsEnabled = false; + this._teleportationEnabled = false; + if (this._gazeTracker) { + this._gazeTracker.dispose(); + } + } +} +VRExperienceHelperGazer._IdCounter = 0; +class VRExperienceHelperCameraGazer extends VRExperienceHelperGazer { + constructor(_getCamera, scene) { + super(scene); + this._getCamera = _getCamera; + } + _getForwardRay(length) { + const camera = this._getCamera(); + if (camera) { + return camera.getForwardRay(length); + } + else { + return new Ray(Vector3.Zero(), Vector3.Forward()); + } + } +} +/** + * Helps to quickly add VR support to an existing scene. + * See https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRHelper + * @deprecated Use WebXR instead! + */ +class VRExperienceHelper { + /** Return this.onEnteringVRObservable + * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly + */ + get onEnteringVR() { + return this.onEnteringVRObservable; + } + /** Return this.onExitingVRObservable + * Note: This one is for backward compatibility. Please use onExitingVRObservable directly + */ + get onExitingVR() { + return this.onExitingVRObservable; + } + /** + * The mesh used to display where the user is going to teleport. + */ + get teleportationTarget() { + return this._teleportationTarget; + } + /** + * Sets the mesh to be used to display where the user is going to teleport. + */ + set teleportationTarget(value) { + if (value) { + value.name = "teleportationTarget"; + this._isDefaultTeleportationTarget = false; + this._teleportationTarget = value; + } + } + /** + * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller + * when set bakeCurrentTransformIntoVertices will be called on the mesh. + * See https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms + */ + get gazeTrackerMesh() { + return this._cameraGazer._gazeTracker; + } + set gazeTrackerMesh(value) { + if (value) { + // Dispose of existing meshes + if (this._cameraGazer._gazeTracker) { + this._cameraGazer._gazeTracker.dispose(); + } + // Set and create gaze trackers on head and controllers + this._cameraGazer._gazeTracker = value; + this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(); + this._cameraGazer._gazeTracker.isPickable = false; + this._cameraGazer._gazeTracker.isVisible = false; + this._cameraGazer._gazeTracker.name = "gazeTracker"; + } + } + /** + * If the ray of the gaze should be displayed. + */ + get displayGaze() { + return this._displayGaze; + } + /** + * Sets if the ray of the gaze should be displayed. + */ + set displayGaze(value) { + this._displayGaze = value; + if (!value) { + this._cameraGazer._gazeTracker.isVisible = false; + } + } + /** + * If the ray of the LaserPointer should be displayed. + */ + get displayLaserPointer() { + return this._displayLaserPointer; + } + /** + * Sets if the ray of the LaserPointer should be displayed. + */ + set displayLaserPointer(value) { + this._displayLaserPointer = value; + } + /** + * The deviceOrientationCamera used as the camera when not in VR. + */ + get deviceOrientationCamera() { + return this._deviceOrientationCamera; + } + /** + * Based on the current WebVR support, returns the current VR camera used. + */ + get currentVRCamera() { + return this._scene.activeCamera; + } + /** + * The deviceOrientationCamera that is used as a fallback when vr device is not connected. + */ + get vrDeviceOrientationCamera() { + return this._vrDeviceOrientationCamera; + } + /** + * The html button that is used to trigger entering into VR. + */ + get vrButton() { + return this._btnVR; + } + get _teleportationRequestInitiated() { + return this._cameraGazer._teleportationRequestInitiated; + } + /** + * Instantiates a VRExperienceHelper. + * Helps to quickly add VR support to an existing scene. + * @param scene The scene the VRExperienceHelper belongs to. + * @param webVROptions Options to modify the vr experience helper's behavior. + */ + constructor(scene, + /** [Empty object] Options to modify the vr experience helper's behavior. */ + webVROptions = {}) { + this.webVROptions = webVROptions; + // Are we presenting in the fullscreen fallback? + this._fullscreenVRpresenting = false; + /** + * Gets or sets a boolean indicating that gaze can be enabled even if pointer lock is not engage (useful on iOS where fullscreen mode and pointer lock are not supported) + */ + this.enableGazeEvenWhenNoPointerLock = false; + /** + * Gets or sets a boolean indicating that the VREXperienceHelper will exit VR if double tap is detected + */ + this.exitVROnDoubleTap = true; + /** + * Observable raised right before entering VR. + */ + this.onEnteringVRObservable = new Observable(); + /** + * Observable raised when entering VR has completed. + */ + this.onAfterEnteringVRObservable = new Observable(); + /** + * Observable raised when exiting VR. + */ + this.onExitingVRObservable = new Observable(); + this._useCustomVRButton = false; + this._teleportActive = false; + this._floorMeshesCollection = []; + this._teleportationMode = VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME; + this._teleportationTime = 122; + this._teleportationSpeed = 20; + this._rotationAllowed = true; + this._teleportBackwardsVector = new Vector3(0, -1, -1); + this._isDefaultTeleportationTarget = true; + this._teleportationFillColor = "#444444"; + this._teleportationBorderColor = "#FFFFFF"; + this._rotationAngle = 0; + this._haloCenter = new Vector3(0, 0, 0); + this._padSensibilityUp = 0.65; + this._padSensibilityDown = 0.35; + this._pickedLaserColor = new Color3(0.2, 0.2, 1); + this._pickedGazeColor = new Color3(0, 0, 1); + /** + * Observable raised when a new mesh is selected based on meshSelectionPredicate + */ + this.onNewMeshSelected = new Observable(); + /** + * Observable raised when a new mesh is picked based on meshSelectionPredicate + */ + this.onNewMeshPicked = new Observable(); + /** + * Observable raised before camera teleportation + */ + this.onBeforeCameraTeleport = new Observable(); + /** + * Observable raised after camera teleportation + */ + this.onAfterCameraTeleport = new Observable(); + /** + * Observable raised when current selected mesh gets unselected + */ + this.onSelectedMeshUnselected = new Observable(); + /** + * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept. + */ + this.teleportationEnabled = true; + this._teleportationInitialized = false; + this._interactionsEnabled = false; + this._displayGaze = true; + this._displayLaserPointer = true; + /** + * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes + */ + this.updateGazeTrackerScale = true; + /** + * If the gaze trackers color should be updated when selecting meshes + */ + this.updateGazeTrackerColor = true; + /** + * If the controller laser color should be updated when selecting meshes + */ + this.updateControllerLaserColor = true; + /** + * Defines whether or not Pointer lock should be requested when switching to + * full screen. + */ + this.requestPointerLockOnFullScreen = true; + /** + * Was the XR test done already. If this is true AND this.xr exists, xr is initialized. + * If this is true and no this.xr, xr exists but is not supported, using WebVR. + */ + this.xrTestDone = false; + this._onResize = () => { + this._moveButtonToBottomRight(); + }; + this._onFullscreenChange = () => { + this._fullscreenVRpresenting = !!document.fullscreenElement; + if (!this._fullscreenVRpresenting && this._inputElement) { + this.exitVR(); + if (!this._useCustomVRButton && this._btnVR) { + this._btnVR.style.top = this._inputElement.offsetTop + this._inputElement.offsetHeight - 70 + "px"; + this._btnVR.style.left = this._inputElement.offsetLeft + this._inputElement.offsetWidth - 100 + "px"; + // make sure the button is visible after setting its position + this._updateButtonVisibility(); + } + } + }; + this._cachedAngularSensibility = { angularSensibilityX: null, angularSensibilityY: null, angularSensibility: null }; + this._beforeRender = () => { + if (this._scene.getEngine().isPointerLock || this.enableGazeEvenWhenNoPointerLock) ; + else { + this._cameraGazer._gazeTracker.isVisible = false; + } + }; + this._onNewGamepadConnected = (gamepad) => { + if (gamepad.type !== Gamepad.POSE_ENABLED) { + if (gamepad.leftStick) { + gamepad.onleftstickchanged((stickValues) => { + if (this._teleportationInitialized && this.teleportationEnabled) { + // Listening to classic/xbox gamepad only if no VR controller is active + this._checkTeleportWithRay(stickValues, this._cameraGazer); + this._checkTeleportBackwards(stickValues, this._cameraGazer); + } + }); + } + if (gamepad.rightStick) { + gamepad.onrightstickchanged((stickValues) => { + if (this._teleportationInitialized) { + this._checkRotate(stickValues, this._cameraGazer); + } + }); + } + if (gamepad.type === Gamepad.XBOX) { + gamepad.onbuttondown((buttonPressed) => { + if (this._interactionsEnabled && buttonPressed === 0 /* Xbox360Button.A */) { + this._cameraGazer._selectionPointerDown(); + } + }); + gamepad.onbuttonup((buttonPressed) => { + if (this._interactionsEnabled && buttonPressed === 0 /* Xbox360Button.A */) { + this._cameraGazer._selectionPointerUp(); + } + }); + } + } + }; + this._workingVector = Vector3.Zero(); + this._workingQuaternion = Quaternion.Identity(); + this._workingMatrix = Matrix.Identity(); + Logger.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"); + this._scene = scene; + this._inputElement = scene.getEngine().getInputElement(); + // check for VR support: + const vrSupported = "getVRDisplays" in navigator; + // no VR support? force XR but only when it is not set because web vr can work without the getVRDisplays + if (!vrSupported && webVROptions.useXR === undefined) { + webVROptions.useXR = true; + } + // Parse options + if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) { + webVROptions.createFallbackVRDeviceOrientationFreeCamera = true; + } + if (webVROptions.createDeviceOrientationCamera === undefined) { + webVROptions.createDeviceOrientationCamera = true; + } + if (webVROptions.laserToggle === undefined) { + webVROptions.laserToggle = true; + } + this._hasEnteredVR = false; + // Set position + if (this._scene.activeCamera) { + this._position = this._scene.activeCamera.position.clone(); + } + else { + this._position = new Vector3(0, this._defaultHeight, 0); + } + // Set non-vr camera + if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) { + this._deviceOrientationCamera = new DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene); + // Copy data from existing camera + if (this._scene.activeCamera) { + this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ; + this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ; + // Set rotation from previous camera + if (this._scene.activeCamera instanceof TargetCamera && this._scene.activeCamera.rotation) { + const targetCamera = this._scene.activeCamera; + if (targetCamera.rotationQuaternion) { + this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion); + } + else { + this._deviceOrientationCamera.rotationQuaternion.copyFrom(Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z)); + } + this._deviceOrientationCamera.rotation = targetCamera.rotation.clone(); + } + } + this._scene.activeCamera = this._deviceOrientationCamera; + if (this._inputElement) { + this._scene.activeCamera.attachControl(); + } + } + else { + this._existingCamera = this._scene.activeCamera; + } + if (this.webVROptions.useXR && navigator.xr) { + // force-check XR session support + WebXRSessionManager.IsSessionSupportedAsync("immersive-vr").then((supported) => { + if (supported) { + Logger.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"); + // it is possible to use XR, let's do it! + scene + .createDefaultXRExperienceAsync({ + floorMeshes: webVROptions.floorMeshes || [], + }) + .then((xr) => { + this.xr = xr; + // connect observables + this.xrTestDone = true; + this._cameraGazer = new VRExperienceHelperCameraGazer(() => { + return this.xr.baseExperience.camera; + }, scene); + this.xr.baseExperience.onStateChangedObservable.add((state) => { + // support for entering / exiting + switch (state) { + case 0 /* WebXRState.ENTERING_XR */: + this.onEnteringVRObservable.notifyObservers(this); + if (!this._interactionsEnabled) { + this.xr.pointerSelection.detach(); + } + this.xr.pointerSelection.displayLaserPointer = this._displayLaserPointer; + break; + case 1 /* WebXRState.EXITING_XR */: + this.onExitingVRObservable.notifyObservers(this); + // resize to update width and height when exiting vr exits fullscreen + this._scene.getEngine().resize(); + break; + case 2 /* WebXRState.IN_XR */: + this._hasEnteredVR = true; + break; + case 3 /* WebXRState.NOT_IN_XR */: + this._hasEnteredVR = false; + break; + } + }); + }); + } + else { + // XR not supported (thou exists), continue WebVR init + this._completeVRInit(scene, webVROptions); + } + }); + } + else { + // no XR, continue init synchronous + this._completeVRInit(scene, webVROptions); + } + } + _completeVRInit(scene, webVROptions) { + this.xrTestDone = true; + // Create VR cameras + if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) { + this._vrDeviceOrientationCamera = new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene, true, webVROptions.vrDeviceOrientationCameraMetrics); + this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE; + } + this._cameraGazer = new VRExperienceHelperCameraGazer(() => { + return this.currentVRCamera; + }, scene); + // Create default button + if (!this._useCustomVRButton) { + this._btnVR = document.createElement("BUTTON"); + this._btnVR.className = "babylonVRicon"; + this._btnVR.id = "babylonVRiconbtn"; + this._btnVR.title = "Click to switch to VR"; + const url = !window.SVGSVGElement + ? "https://cdn.babylonjs.com/Assets/vrButton.png" + : "data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A"; + let css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(" + + url + + "); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }"; + css += ".babylonVRicon.vrdisplaypresenting { display: none; }"; + // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR) + // css += ".babylonVRicon.vrdisplaysupported { }"; + // css += ".babylonVRicon.vrdisplayready { }"; + // css += ".babylonVRicon.vrdisplayrequesting { }"; + const style = document.createElement("style"); + style.appendChild(document.createTextNode(css)); + document.getElementsByTagName("head")[0].appendChild(style); + this._moveButtonToBottomRight(); + } + // VR button click event + if (this._btnVR) { + this._btnVR.addEventListener("click", () => { + if (!this.isInVRMode) { + this.enterVR(); + } + }); + } + // Window events + const hostWindow = this._scene.getEngine().getHostWindow(); + if (!hostWindow) { + return; + } + hostWindow.addEventListener("resize", this._onResize); + document.addEventListener("fullscreenchange", this._onFullscreenChange, false); + // Display vr button when headset is connected + if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) { + this._displayVRButton(); + } + // Exiting VR mode using 'ESC' key on desktop + this._onKeyDown = (event) => { + if (event.keyCode === 27 && this.isInVRMode) { + this.exitVR(); + } + }; + document.addEventListener("keydown", this._onKeyDown); + // Exiting VR mode double tapping the touch screen + this._scene.onPrePointerObservable.add(() => { + if (this._hasEnteredVR && this.exitVROnDoubleTap) { + this.exitVR(); + if (this._fullscreenVRpresenting) { + this._scene.getEngine().exitFullscreen(); + } + } + }, PointerEventTypes.POINTERDOUBLETAP, false); + scene.onDisposeObservable.add(() => { + this.dispose(); + }); + this._updateButtonVisibility(); + //create easing functions + this._circleEase = new CircleEase(); + this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT); + this._teleportationEasing = this._circleEase; + // Allow clicking in the vrDeviceOrientationCamera + scene.onPointerObservable.add((e) => { + if (this._interactionsEnabled) { + if (scene.activeCamera === this.vrDeviceOrientationCamera && e.event.pointerType === "mouse") { + if (e.type === PointerEventTypes.POINTERDOWN) { + this._cameraGazer._selectionPointerDown(); + } + else if (e.type === PointerEventTypes.POINTERUP) { + this._cameraGazer._selectionPointerUp(); + } + } + } + }); + if (this.webVROptions.floorMeshes) { + this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes }); + } + } + /** + * Gets a value indicating if we are currently in VR mode. + */ + get isInVRMode() { + return (this.xr && this.webVROptions.useXR && this.xr.baseExperience.state === 2 /* WebXRState.IN_XR */) || this._fullscreenVRpresenting; + } + _moveButtonToBottomRight() { + if (this._inputElement && !this._useCustomVRButton && this._btnVR) { + const rect = this._inputElement.getBoundingClientRect(); + this._btnVR.style.top = rect.top + rect.height - 70 + "px"; + this._btnVR.style.left = rect.left + rect.width - 100 + "px"; + } + } + _displayVRButton() { + if (!this._useCustomVRButton && !this._btnVRDisplayed && this._btnVR) { + document.body.appendChild(this._btnVR); + this._btnVRDisplayed = true; + } + } + _updateButtonVisibility() { + if (!this._btnVR || this._useCustomVRButton) { + return; + } + this._btnVR.className = "babylonVRicon"; + if (this.isInVRMode) { + this._btnVR.className += " vrdisplaypresenting"; + } + } + /** + * Attempt to enter VR. If a headset is connected and ready, will request present on that. + * Otherwise, will use the fullscreen API. + */ + enterVR() { + if (this.xr) { + this.xr.baseExperience.enterXRAsync("immersive-vr", "local-floor", this.xr.renderTarget); + return; + } + if (this.onEnteringVRObservable) { + try { + this.onEnteringVRObservable.notifyObservers(this); + } + catch (err) { + Logger.Warn("Error in your custom logic onEnteringVR: " + err); + } + } + if (this._scene.activeCamera) { + this._position = this._scene.activeCamera.position.clone(); + if (this.vrDeviceOrientationCamera) { + this.vrDeviceOrientationCamera.rotation = Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(); + this.vrDeviceOrientationCamera.angularSensibility = 2000; + } + // make sure that we return to the last active camera + this._existingCamera = this._scene.activeCamera; + // Remove and cache angular sensability to avoid camera rotation when in VR + if (this._existingCamera.angularSensibilityX) { + this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX; + this._existingCamera.angularSensibilityX = Number.MAX_VALUE; + } + if (this._existingCamera.angularSensibilityY) { + this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY; + this._existingCamera.angularSensibilityY = Number.MAX_VALUE; + } + if (this._existingCamera.angularSensibility) { + this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility; + this._existingCamera.angularSensibility = Number.MAX_VALUE; + } + } + // If WebVR is supported and a headset is connected + if (this._vrDeviceOrientationCamera) { + this._vrDeviceOrientationCamera.position = this._position; + if (this._scene.activeCamera) { + this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ; + } + this._scene.activeCamera = this._vrDeviceOrientationCamera; + this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen); + this._updateButtonVisibility(); + this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(() => { + this.onAfterEnteringVRObservable.notifyObservers({ success: true }); + }); + } + if (this._scene.activeCamera && this._inputElement) { + this._scene.activeCamera.attachControl(); + } + if (this._interactionsEnabled) { + this._scene.registerBeforeRender(this._beforeRender); + } + this._hasEnteredVR = true; + } + /** + * Attempt to exit VR, or fullscreen. + */ + exitVR() { + if (this.xr) { + this.xr.baseExperience.exitXRAsync(); + return; + } + if (this._hasEnteredVR) { + if (this.onExitingVRObservable) { + try { + this.onExitingVRObservable.notifyObservers(this); + } + catch (err) { + Logger.Warn("Error in your custom logic onExitingVR: " + err); + } + } + if (this._scene.activeCamera) { + this._position = this._scene.activeCamera.position.clone(); + } + if (this.vrDeviceOrientationCamera) { + this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE; + } + if (this._deviceOrientationCamera) { + this._deviceOrientationCamera.position = this._position; + this._scene.activeCamera = this._deviceOrientationCamera; + // Restore angular sensibility + if (this._cachedAngularSensibility.angularSensibilityX) { + this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX; + this._cachedAngularSensibility.angularSensibilityX = null; + } + if (this._cachedAngularSensibility.angularSensibilityY) { + this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY; + this._cachedAngularSensibility.angularSensibilityY = null; + } + if (this._cachedAngularSensibility.angularSensibility) { + this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility; + this._cachedAngularSensibility.angularSensibility = null; + } + } + else if (this._existingCamera) { + this._existingCamera.position = this._position; + this._scene.activeCamera = this._existingCamera; + if (this._inputElement) { + this._scene.activeCamera.attachControl(); + } + // Restore angular sensibility + if (this._cachedAngularSensibility.angularSensibilityX) { + this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX; + this._cachedAngularSensibility.angularSensibilityX = null; + } + if (this._cachedAngularSensibility.angularSensibilityY) { + this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY; + this._cachedAngularSensibility.angularSensibilityY = null; + } + if (this._cachedAngularSensibility.angularSensibility) { + this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility; + this._cachedAngularSensibility.angularSensibility = null; + } + } + this._updateButtonVisibility(); + if (this._interactionsEnabled) { + this._scene.unregisterBeforeRender(this._beforeRender); + this._cameraGazer._gazeTracker.isVisible = false; + } + // resize to update width and height when exiting vr exits fullscreen + this._scene.getEngine().resize(); + this._hasEnteredVR = false; + } + } + /** + * The position of the vr experience helper. + */ + get position() { + return this._position; + } + /** + * Sets the position of the vr experience helper. + */ + set position(value) { + this._position = value; + if (this._scene.activeCamera) { + this._scene.activeCamera.position = value; + } + } + /** + * Enables controllers and user interactions such as selecting and object or clicking on an object. + */ + enableInteractions() { + if (!this._interactionsEnabled) { + // in XR it is enabled by default, but just to make sure, re-attach + if (this.xr) { + if (this.xr.baseExperience.state === 2 /* WebXRState.IN_XR */) { + this.xr.pointerSelection.attach(); + } + return; + } + this.raySelectionPredicate = (mesh) => { + return mesh.isVisible && (mesh.isPickable || mesh.name === this._floorMeshName); + }; + this.meshSelectionPredicate = () => { + return true; + }; + this._raySelectionPredicate = (mesh) => { + if (this._isTeleportationFloor(mesh) || + (mesh.name.indexOf("gazeTracker") === -1 && mesh.name.indexOf("teleportationTarget") === -1 && mesh.name.indexOf("torusTeleportation") === -1)) { + return this.raySelectionPredicate(mesh); + } + return false; + }; + this._interactionsEnabled = true; + } + } + _isTeleportationFloor(mesh) { + for (let i = 0; i < this._floorMeshesCollection.length; i++) { + if (this._floorMeshesCollection[i].id === mesh.id) { + return true; + } + } + if (this._floorMeshName && mesh.name === this._floorMeshName) { + return true; + } + return false; + } + /** + * Adds a floor mesh to be used for teleportation. + * @param floorMesh the mesh to be used for teleportation. + */ + addFloorMesh(floorMesh) { + if (!this._floorMeshesCollection) { + return; + } + if (this._floorMeshesCollection.indexOf(floorMesh) > -1) { + return; + } + this._floorMeshesCollection.push(floorMesh); + } + /** + * Removes a floor mesh from being used for teleportation. + * @param floorMesh the mesh to be removed. + */ + removeFloorMesh(floorMesh) { + if (!this._floorMeshesCollection) { + return; + } + const meshIndex = this._floorMeshesCollection.indexOf(floorMesh); + if (meshIndex !== -1) { + this._floorMeshesCollection.splice(meshIndex, 1); + } + } + /** + * Enables interactions and teleportation using the VR controllers and gaze. + * @param vrTeleportationOptions options to modify teleportation behavior. + */ + enableTeleportation(vrTeleportationOptions = {}) { + if (!this._teleportationInitialized) { + this.enableInteractions(); + if (this.webVROptions.useXR && (vrTeleportationOptions.floorMeshes || vrTeleportationOptions.floorMeshName)) { + const floorMeshes = vrTeleportationOptions.floorMeshes || []; + if (!floorMeshes.length) { + const floorMesh = this._scene.getMeshByName(vrTeleportationOptions.floorMeshName); + if (floorMesh) { + floorMeshes.push(floorMesh); + } + } + if (this.xr) { + floorMeshes.forEach((mesh) => { + this.xr.teleportation.addFloorMesh(mesh); + }); + if (!this.xr.teleportation.attached) { + this.xr.teleportation.attach(); + } + return; + } + else if (!this.xrTestDone) { + const waitForXr = () => { + if (this.xrTestDone) { + this._scene.unregisterBeforeRender(waitForXr); + if (this.xr) { + if (!this.xr.teleportation.attached) { + this.xr.teleportation.attach(); + } + } + else { + this.enableTeleportation(vrTeleportationOptions); + } + } + }; + this._scene.registerBeforeRender(waitForXr); + return; + } + } + if (vrTeleportationOptions.floorMeshName) { + this._floorMeshName = vrTeleportationOptions.floorMeshName; + } + if (vrTeleportationOptions.floorMeshes) { + this._floorMeshesCollection = vrTeleportationOptions.floorMeshes; + } + if (vrTeleportationOptions.teleportationMode) { + this._teleportationMode = vrTeleportationOptions.teleportationMode; + } + if (vrTeleportationOptions.teleportationTime && vrTeleportationOptions.teleportationTime > 0) { + this._teleportationTime = vrTeleportationOptions.teleportationTime; + } + if (vrTeleportationOptions.teleportationSpeed && vrTeleportationOptions.teleportationSpeed > 0) { + this._teleportationSpeed = vrTeleportationOptions.teleportationSpeed; + } + if (vrTeleportationOptions.easingFunction !== undefined) { + this._teleportationEasing = vrTeleportationOptions.easingFunction; + } + // Creates an image processing post process for the vignette not relying + // on the main scene configuration for image processing to reduce setup and spaces + // (gamma/linear) conflicts. + const imageProcessingConfiguration = new ImageProcessingConfiguration(); + imageProcessingConfiguration.vignetteColor = new Color4(0, 0, 0, 0); + imageProcessingConfiguration.vignetteEnabled = true; + this._teleportationInitialized = true; + if (this._isDefaultTeleportationTarget) { + this._createTeleportationCircles(); + } + } + } + _checkTeleportWithRay(stateObject, gazer) { + // Dont teleport if another gaze already requested teleportation + if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) { + return; + } + if (!gazer._teleportationRequestInitiated) { + if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) { + gazer._activatePointer(); + gazer._teleportationRequestInitiated = true; + } + } + else { + // Listening to the proper controller values changes to confirm teleportation + if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) { + if (this._teleportActive) { + this.teleportCamera(this._haloCenter); + } + gazer._teleportationRequestInitiated = false; + } + } + } + _checkRotate(stateObject, gazer) { + // Only rotate when user is not currently selecting a teleportation location + if (gazer._teleportationRequestInitiated) { + return; + } + if (!gazer._rotationLeftAsked) { + if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) { + gazer._rotationLeftAsked = true; + if (this._rotationAllowed) { + this._rotateCamera(false); + } + } + } + else { + if (stateObject.x > -this._padSensibilityDown) { + gazer._rotationLeftAsked = false; + } + } + if (!gazer._rotationRightAsked) { + if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) { + gazer._rotationRightAsked = true; + if (this._rotationAllowed) { + this._rotateCamera(true); + } + } + } + else { + if (stateObject.x < this._padSensibilityDown) { + gazer._rotationRightAsked = false; + } + } + } + _checkTeleportBackwards(stateObject, gazer) { + // Only teleport backwards when user is not currently selecting a teleportation location + if (gazer._teleportationRequestInitiated) { + return; + } + // Teleport backwards + if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) { + if (!gazer._teleportationBackRequestInitiated) { + if (!this.currentVRCamera) { + return; + } + // Get rotation and position of the current camera + const rotation = Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()); + const position = this.currentVRCamera.position; + // Get matrix with only the y rotation of the device rotation + rotation.toEulerAnglesToRef(this._workingVector); + this._workingVector.z = 0; + this._workingVector.x = 0; + Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion); + this._workingQuaternion.toRotationMatrix(this._workingMatrix); + // Rotate backwards ray by device rotation to cast at the ground behind the user + Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector); + // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff + const ray = new Ray(position, this._workingVector); + const hit = this._scene.pickWithRay(ray, this._raySelectionPredicate); + if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) { + this.teleportCamera(hit.pickedPoint); + } + gazer._teleportationBackRequestInitiated = true; + } + } + else { + gazer._teleportationBackRequestInitiated = false; + } + } + _createTeleportationCircles() { + this._teleportationTarget = CreateGround("teleportationTarget", { width: 2, height: 2, subdivisions: 2 }, this._scene); + this._teleportationTarget.isPickable = false; + const length = 512; + const dynamicTexture = new DynamicTexture("DynamicTexture", length, this._scene, true); + dynamicTexture.hasAlpha = true; + const context = dynamicTexture.getContext(); + const centerX = length / 2; + const centerY = length / 2; + const radius = 200; + context.beginPath(); + context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); + context.fillStyle = this._teleportationFillColor; + context.fill(); + context.lineWidth = 10; + context.strokeStyle = this._teleportationBorderColor; + context.stroke(); + context.closePath(); + dynamicTexture.update(); + const teleportationCircleMaterial = new StandardMaterial("TextPlaneMaterial", this._scene); + teleportationCircleMaterial.diffuseTexture = dynamicTexture; + this._teleportationTarget.material = teleportationCircleMaterial; + const torus = CreateTorus("torusTeleportation", { + diameter: 0.75, + thickness: 0.1, + tessellation: 25, + updatable: false, + }, this._scene); + torus.isPickable = false; + torus.parent = this._teleportationTarget; + const animationInnerCircle = new Animation("animationInnerCircle", "position.y", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE); + const keys = []; + keys.push({ + frame: 0, + value: 0, + }); + keys.push({ + frame: 30, + value: 0.4, + }); + keys.push({ + frame: 60, + value: 0, + }); + animationInnerCircle.setKeys(keys); + const easingFunction = new SineEase(); + easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT); + animationInnerCircle.setEasingFunction(easingFunction); + torus.animations = []; + torus.animations.push(animationInnerCircle); + this._scene.beginAnimation(torus, 0, 60, true); + this._hideTeleportationTarget(); + } + _hideTeleportationTarget() { + this._teleportActive = false; + if (this._teleportationInitialized) { + this._teleportationTarget.isVisible = false; + if (this._isDefaultTeleportationTarget) { + this._teleportationTarget.getChildren()[0].isVisible = false; + } + } + } + _rotateCamera(right) { + if (!(this.currentVRCamera instanceof FreeCamera)) { + return; + } + if (right) { + this._rotationAngle++; + } + else { + this._rotationAngle--; + } + this.currentVRCamera.animations = []; + const target = Quaternion.FromRotationMatrix(Matrix.RotationY((Math.PI / 4) * this._rotationAngle)); + const animationRotation = new Animation("animationRotation", "rotationQuaternion", 90, Animation.ANIMATIONTYPE_QUATERNION, Animation.ANIMATIONLOOPMODE_CONSTANT); + const animationRotationKeys = []; + animationRotationKeys.push({ + frame: 0, + value: this.currentVRCamera.rotationQuaternion, + }); + animationRotationKeys.push({ + frame: 6, + value: target, + }); + animationRotation.setKeys(animationRotationKeys); + animationRotation.setEasingFunction(this._circleEase); + this.currentVRCamera.animations.push(animationRotation); + this._postProcessMove.animations = []; + const animationPP = new Animation("animationPP", "vignetteWeight", 90, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT); + const vignetteWeightKeys = []; + vignetteWeightKeys.push({ + frame: 0, + value: 0, + }); + vignetteWeightKeys.push({ + frame: 3, + value: 4, + }); + vignetteWeightKeys.push({ + frame: 6, + value: 0, + }); + animationPP.setKeys(vignetteWeightKeys); + animationPP.setEasingFunction(this._circleEase); + this._postProcessMove.animations.push(animationPP); + const animationPP2 = new Animation("animationPP2", "vignetteStretch", 90, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT); + const vignetteStretchKeys = []; + vignetteStretchKeys.push({ + frame: 0, + value: 0, + }); + vignetteStretchKeys.push({ + frame: 3, + value: 10, + }); + vignetteStretchKeys.push({ + frame: 6, + value: 0, + }); + animationPP2.setKeys(vignetteStretchKeys); + animationPP2.setEasingFunction(this._circleEase); + this._postProcessMove.animations.push(animationPP2); + this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0; + this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0; + this._postProcessMove.samples = 4; + this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1); + } + /** + * Teleports the users feet to the desired location + * @param location The location where the user's feet should be placed + */ + teleportCamera(location) { + if (!(this.currentVRCamera instanceof FreeCamera)) { + return; + } + // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the + // offset of the headset from the anchor. + this._workingVector.copyFrom(location); + // Add height to account for user's height offset + if (this.isInVRMode) ; + else { + this._workingVector.y += this._defaultHeight; + } + this.onBeforeCameraTeleport.notifyObservers(this._workingVector); + // Animations FPS + const FPS = 90; + let speedRatio, lastFrame; + if (this._teleportationMode == VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED) { + lastFrame = FPS; + const dist = Vector3.Distance(this.currentVRCamera.position, this._workingVector); + speedRatio = this._teleportationSpeed / dist; + } + else { + // teleportationMode is TELEPORTATIONMODE_CONSTANTTIME + lastFrame = Math.round((this._teleportationTime * FPS) / 1000); + speedRatio = 1; + } + // Create animation from the camera's position to the new location + this.currentVRCamera.animations = []; + const animationCameraTeleportation = new Animation("animationCameraTeleportation", "position", FPS, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT); + const animationCameraTeleportationKeys = [ + { + frame: 0, + value: this.currentVRCamera.position, + }, + { + frame: lastFrame, + value: this._workingVector, + }, + ]; + animationCameraTeleportation.setKeys(animationCameraTeleportationKeys); + animationCameraTeleportation.setEasingFunction(this._teleportationEasing); + this.currentVRCamera.animations.push(animationCameraTeleportation); + this._postProcessMove.animations = []; + // Calculate the mid frame for vignette animations + const midFrame = Math.round(lastFrame / 2); + const animationPP = new Animation("animationPP", "vignetteWeight", FPS, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT); + const vignetteWeightKeys = []; + vignetteWeightKeys.push({ + frame: 0, + value: 0, + }); + vignetteWeightKeys.push({ + frame: midFrame, + value: 8, + }); + vignetteWeightKeys.push({ + frame: lastFrame, + value: 0, + }); + animationPP.setKeys(vignetteWeightKeys); + this._postProcessMove.animations.push(animationPP); + const animationPP2 = new Animation("animationPP2", "vignetteStretch", FPS, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT); + const vignetteStretchKeys = []; + vignetteStretchKeys.push({ + frame: 0, + value: 0, + }); + vignetteStretchKeys.push({ + frame: midFrame, + value: 10, + }); + vignetteStretchKeys.push({ + frame: lastFrame, + value: 0, + }); + animationPP2.setKeys(vignetteStretchKeys); + this._postProcessMove.animations.push(animationPP2); + this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0; + this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0; + this._scene.beginAnimation(this.currentVRCamera, 0, lastFrame, false, speedRatio, () => { + this.onAfterCameraTeleport.notifyObservers(this._workingVector); + }); + this._hideTeleportationTarget(); + } + /** + * Permanently set new colors for the laser pointer + * @param color the new laser color + * @param pickedColor the new laser color when picked mesh detected + */ + setLaserColor(color, pickedColor = this._pickedLaserColor) { + this._pickedLaserColor = pickedColor; + } + /** + * Set lighting enabled / disabled on the laser pointer of both controllers + * @param _enabled should the lighting be enabled on the laser pointer + */ + setLaserLightingState(_enabled = true) { + // no-op + } + /** + * Permanently set new colors for the gaze pointer + * @param color the new gaze color + * @param pickedColor the new gaze color when picked mesh detected + */ + setGazeColor(color, pickedColor = this._pickedGazeColor) { + this._pickedGazeColor = pickedColor; + } + /** + * Sets the color of the laser ray from the vr controllers. + * @param _color new color for the ray. + */ + changeLaserColor(_color) { + if (!this.updateControllerLaserColor) { + return; + } + } + /** + * Sets the color of the ray from the vr headsets gaze. + * @param color new color for the ray. + */ + changeGazeColor(color) { + if (!this.updateGazeTrackerColor) { + return; + } + if (!this._cameraGazer._gazeTracker.material) { + return; + } + this._cameraGazer._gazeTracker.material.emissiveColor = color; + } + /** + * Exits VR and disposes of the vr experience helper + */ + dispose() { + if (this.isInVRMode) { + this.exitVR(); + } + if (this._postProcessMove) { + this._postProcessMove.dispose(); + } + if (this._vrDeviceOrientationCamera) { + this._vrDeviceOrientationCamera.dispose(); + } + if (!this._useCustomVRButton && this._btnVR && this._btnVR.parentNode) { + document.body.removeChild(this._btnVR); + } + if (this._deviceOrientationCamera && this._scene.activeCamera != this._deviceOrientationCamera) { + this._deviceOrientationCamera.dispose(); + } + if (this._cameraGazer) { + this._cameraGazer.dispose(); + } + if (this._teleportationTarget) { + this._teleportationTarget.dispose(); + } + if (this.xr) { + this.xr.dispose(); + } + this._floorMeshesCollection.length = 0; + document.removeEventListener("keydown", this._onKeyDown); + window.removeEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChangeBind); + window.removeEventListener("resize", this._onResize); + document.removeEventListener("fullscreenchange", this._onFullscreenChange); + this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected); + this._scene.unregisterBeforeRender(this._beforeRender); + } + /** + * Gets the name of the VRExperienceHelper class + * @returns "VRExperienceHelper" + */ + getClassName() { + return "VRExperienceHelper"; + } +} +/** + * Time Constant Teleportation Mode + */ +VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME = 0; +/** + * Speed Constant Teleportation Mode + */ +VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED = 1; + +const intersectBoxAASphere = (boxMin, boxMax, sphereCenter, sphereRadius) => { + if (boxMin.x > sphereCenter.x + sphereRadius) { + return false; + } + if (sphereCenter.x - sphereRadius > boxMax.x) { + return false; + } + if (boxMin.y > sphereCenter.y + sphereRadius) { + return false; + } + if (sphereCenter.y - sphereRadius > boxMax.y) { + return false; + } + if (boxMin.z > sphereCenter.z + sphereRadius) { + return false; + } + if (sphereCenter.z - sphereRadius > boxMax.z) { + return false; + } + return true; +}; +const getLowestRoot = (function () { + const result = { root: 0, found: false }; + return function (a, b, c, maxR) { + result.root = 0; + result.found = false; + const determinant = b * b - 4.0 * a * c; + if (determinant < 0) { + return result; + } + const sqrtD = Math.sqrt(determinant); + let r1 = (-b - sqrtD) / (2.0 * a); + let r2 = (-b + sqrtD) / (2.0 * a); + if (r1 > r2) { + const temp = r2; + r2 = r1; + r1 = temp; + } + if (r1 > 0 && r1 < maxR) { + result.root = r1; + result.found = true; + return result; + } + if (r2 > 0 && r2 < maxR) { + result.root = r2; + result.found = true; + return result; + } + return result; + }; +})(); +/** @internal */ +class Collider { + constructor() { + // Implementation of the "Improved Collision detection and Response" algorithm proposed by Kasper Fauerby + // https://www.peroxide.dk/papers/collision/collision.pdf + this._collisionPoint = Vector3.Zero(); + this._planeIntersectionPoint = Vector3.Zero(); + this._tempVector = Vector3.Zero(); + this._tempVector2 = Vector3.Zero(); + this._tempVector3 = Vector3.Zero(); + this._tempVector4 = Vector3.Zero(); + this._edge = Vector3.Zero(); + this._baseToVertex = Vector3.Zero(); + this._destinationPoint = Vector3.Zero(); + this._slidePlaneNormal = Vector3.Zero(); + this._displacementVector = Vector3.Zero(); + /** @internal */ + this._radius = Vector3.One(); + /** @internal */ + this._retry = 0; + /** @internal */ + this._basePointWorld = Vector3.Zero(); + this._velocityWorld = Vector3.Zero(); + this._normalizedVelocity = Vector3.Zero(); + this._collisionMask = -1; + } + get collisionMask() { + return this._collisionMask; + } + set collisionMask(mask) { + this._collisionMask = !isNaN(mask) ? mask : -1; + } + /** + * Gets the plane normal used to compute the sliding response (in local space) + */ + get slidePlaneNormal() { + return this._slidePlaneNormal; + } + // Methods + /** + * @internal + */ + _initialize(source, dir, e) { + this._velocity = dir; + this._velocitySquaredLength = this._velocity.lengthSquared(); + const len = Math.sqrt(this._velocitySquaredLength); + if (len === 0 || len === 1.0) { + this._normalizedVelocity.copyFromFloats(dir._x, dir._y, dir._z); + } + else { + dir.scaleToRef(1.0 / len, this._normalizedVelocity); + } + this._basePoint = source; + source.multiplyToRef(this._radius, this._basePointWorld); + dir.multiplyToRef(this._radius, this._velocityWorld); + this._velocityWorldLength = this._velocityWorld.length(); + this._epsilon = e; + this.collisionFound = false; + } + /** + * @internal + */ + _checkPointInTriangle(point, pa, pb, pc, n) { + pa.subtractToRef(point, this._tempVector); + pb.subtractToRef(point, this._tempVector2); + Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4); + let d = Vector3.Dot(this._tempVector4, n); + if (d < 0) { + return false; + } + pc.subtractToRef(point, this._tempVector3); + Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4); + d = Vector3.Dot(this._tempVector4, n); + if (d < 0) { + return false; + } + Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4); + d = Vector3.Dot(this._tempVector4, n); + return d >= 0; + } + /** + * @internal + */ + _canDoCollision(sphereCenter, sphereRadius, vecMin, vecMax) { + const distance = Vector3.Distance(this._basePointWorld, sphereCenter); + const max = Math.max(this._radius.x, this._radius.y, this._radius.z); + if (distance > this._velocityWorldLength + max + sphereRadius) { + return false; + } + if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) { + return false; + } + return true; + } + /** + * @internal + */ + _testTriangle(faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh) { + let t0; + let embeddedInPlane = false; + //defensive programming, actually not needed. + if (!trianglePlaneArray) { + trianglePlaneArray = []; + } + if (!trianglePlaneArray[faceIndex]) { + trianglePlaneArray[faceIndex] = new Plane(0, 0, 0, 0); + trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3); + } + const trianglePlane = trianglePlaneArray[faceIndex]; + if (!hasMaterial && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) { + return; + } + const signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint); + const normalDotVelocity = Vector3.Dot(trianglePlane.normal, this._velocity); + // if DoubleSidedCheck is false(default), a double sided face will be consided 2 times. + // if true, it discard the faces having normal not facing velocity + if (Collider.DoubleSidedCheck && normalDotVelocity > 0.0001) { + return; + } + if (normalDotVelocity == 0) { + if (Math.abs(signedDistToTrianglePlane) >= 1.0) { + return; + } + embeddedInPlane = true; + t0 = 0; + } + else { + t0 = (-1 - signedDistToTrianglePlane) / normalDotVelocity; + let t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity; + if (t0 > t1) { + const temp = t1; + t1 = t0; + t0 = temp; + } + if (t0 > 1.0 || t1 < 0.0) { + return; + } + if (t0 < 0) { + t0 = 0; + } + if (t0 > 1.0) { + t0 = 1.0; + } + } + this._collisionPoint.copyFromFloats(0, 0, 0); + let found = false; + let t = 1.0; + if (!embeddedInPlane) { + this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint); + this._velocity.scaleToRef(t0, this._tempVector); + this._planeIntersectionPoint.addInPlace(this._tempVector); + if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) { + found = true; + t = t0; + this._collisionPoint.copyFrom(this._planeIntersectionPoint); + } + } + if (!found) { + let a = this._velocitySquaredLength; + this._basePoint.subtractToRef(p1, this._tempVector); + let b = 2.0 * Vector3.Dot(this._velocity, this._tempVector); + let c = this._tempVector.lengthSquared() - 1.0; + let lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + t = lowestRoot.root; + found = true; + this._collisionPoint.copyFrom(p1); + } + this._basePoint.subtractToRef(p2, this._tempVector); + b = 2.0 * Vector3.Dot(this._velocity, this._tempVector); + c = this._tempVector.lengthSquared() - 1.0; + lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + t = lowestRoot.root; + found = true; + this._collisionPoint.copyFrom(p2); + } + this._basePoint.subtractToRef(p3, this._tempVector); + b = 2.0 * Vector3.Dot(this._velocity, this._tempVector); + c = this._tempVector.lengthSquared() - 1.0; + lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + t = lowestRoot.root; + found = true; + this._collisionPoint.copyFrom(p3); + } + p2.subtractToRef(p1, this._edge); + p1.subtractToRef(this._basePoint, this._baseToVertex); + let edgeSquaredLength = this._edge.lengthSquared(); + let edgeDotVelocity = Vector3.Dot(this._edge, this._velocity); + let edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex); + a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity; + b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex); + c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; + lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; + if (f >= 0.0 && f <= 1.0) { + t = lowestRoot.root; + found = true; + this._edge.scaleInPlace(f); + p1.addToRef(this._edge, this._collisionPoint); + } + } + p3.subtractToRef(p2, this._edge); + p2.subtractToRef(this._basePoint, this._baseToVertex); + edgeSquaredLength = this._edge.lengthSquared(); + edgeDotVelocity = Vector3.Dot(this._edge, this._velocity); + edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex); + a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity; + b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex); + c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; + lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; + if (f >= 0.0 && f <= 1.0) { + t = lowestRoot.root; + found = true; + this._edge.scaleInPlace(f); + p2.addToRef(this._edge, this._collisionPoint); + } + } + p1.subtractToRef(p3, this._edge); + p3.subtractToRef(this._basePoint, this._baseToVertex); + edgeSquaredLength = this._edge.lengthSquared(); + edgeDotVelocity = Vector3.Dot(this._edge, this._velocity); + edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex); + a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity; + b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex); + c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; + lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; + if (f >= 0.0 && f <= 1.0) { + t = lowestRoot.root; + found = true; + this._edge.scaleInPlace(f); + p3.addToRef(this._edge, this._collisionPoint); + } + } + } + if (found) { + const distToCollisionSquared = t * t * this._velocitySquaredLength; + if (!this.collisionFound || distToCollisionSquared < this._nearestDistanceSquared) { + // if collisionResponse is false, collision is not found but the collidedMesh is set anyway. + // onCollide observable are triggered if collideMesh is set + // this allow trigger volumes to be created. + if (hostMesh.collisionResponse) { + if (!this.intersectionPoint) { + this.intersectionPoint = this._collisionPoint.clone(); + } + else { + this.intersectionPoint.copyFrom(this._collisionPoint); + } + this._nearestDistanceSquared = distToCollisionSquared; + this._nearestDistance = Math.sqrt(distToCollisionSquared); + this.collisionFound = true; + } + this.collidedMesh = hostMesh; + } + } + } + /** + * @internal + */ + _collide(trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial, hostMesh, invertTriangles, triangleStrip = false) { + if (triangleStrip) { + if (!indices || indices.length === 0) { + for (let i = 0; i < pts.length - 2; i += 1) { + const p1 = pts[i]; + const p2 = pts[i + 1]; + const p3 = pts[i + 2]; + // stay defensive and don't check against undefined positions. + if (!p1 || !p2 || !p3) { + continue; + } + // Handles strip faces one on two is reversed + if ((invertTriangles ? 1 : 0) ^ i % 2) { + this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh); + } + else { + this._testTriangle(i, trianglePlaneArray, p2, p1, p3, hasMaterial, hostMesh); + } + } + } + else { + for (let i = indexStart; i < indexEnd - 2; i += 1) { + const indexA = indices[i]; + const indexB = indices[i + 1]; + const indexC = indices[i + 2]; + if (indexC === 0xffffffff) { + i += 2; + continue; + } + const p1 = pts[indexA]; + const p2 = pts[indexB]; + const p3 = pts[indexC]; + // stay defensive and don't check against undefined positions. + if (!p1 || !p2 || !p3) { + continue; + } + // Handles strip faces one on two is reversed + if ((invertTriangles ? 1 : 0) ^ i % 2) { + this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh); + } + else { + this._testTriangle(i, trianglePlaneArray, p2, p1, p3, hasMaterial, hostMesh); + } + } + } + } + else if (!indices || indices.length === 0) { + for (let i = 0; i < pts.length; i += 3) { + const p1 = pts[i]; + const p2 = pts[i + 1]; + const p3 = pts[i + 2]; + if (invertTriangles) { + this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh); + } + else { + this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh); + } + } + } + else { + for (let i = indexStart; i < indexEnd; i += 3) { + const p1 = pts[indices[i] - decal]; + const p2 = pts[indices[i + 1] - decal]; + const p3 = pts[indices[i + 2] - decal]; + if (invertTriangles) { + this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh); + } + else { + this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh); + } + } + } + } + /** + * @internal + */ + _getResponse(pos, vel) { + pos.addToRef(vel, this._destinationPoint); + vel.scaleInPlace(this._nearestDistance / vel.length()); + this._basePoint.addToRef(vel, pos); + pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal); + this._slidePlaneNormal.normalize(); + this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector); + pos.addInPlace(this._displacementVector); + this.intersectionPoint.addInPlace(this._displacementVector); + this._slidePlaneNormal.scaleInPlace(Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint)); + this._destinationPoint.subtractInPlace(this._slidePlaneNormal); + this._destinationPoint.subtractToRef(this.intersectionPoint, vel); + } +} +/** + * If true, it check for double sided faces and only returns 1 collision instead of 2 + */ +Collider.DoubleSidedCheck = false; + +/** @internal */ +class DefaultCollisionCoordinator { + constructor() { + this._scaledPosition = Vector3.Zero(); + this._scaledVelocity = Vector3.Zero(); + this._finalPosition = Vector3.Zero(); + } + getNewPosition(position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) { + position.divideToRef(collider._radius, this._scaledPosition); + displacement.divideToRef(collider._radius, this._scaledVelocity); + collider.collidedMesh = null; + collider._retry = 0; + collider._initialVelocity = this._scaledVelocity; + collider._initialPosition = this._scaledPosition; + this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh); + this._finalPosition.multiplyInPlace(collider._radius); + //run the callback + onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh); + } + createCollider() { + return new Collider(); + } + init(scene) { + this._scene = scene; + } + _collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh = null) { + const closeDistance = AbstractEngine.CollisionsEpsilon * 10.0; + if (collider._retry >= maximumRetry) { + finalPosition.copyFrom(position); + return; + } + // Check if this is a mesh else camera or -1 + const collisionMask = excludedMesh ? excludedMesh.collisionMask : collider.collisionMask; + collider._initialize(position, velocity, closeDistance); + // Check if collision detection should happen against specified list of meshes or, + // if not specified, against all meshes in the scene + const meshes = (excludedMesh && excludedMesh.surroundingMeshes) || this._scene.meshes; + for (let index = 0; index < meshes.length; index++) { + const mesh = meshes[index]; + if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && (collisionMask & mesh.collisionGroup) !== 0) { + mesh._checkCollision(collider); + } + } + if (!collider.collisionFound) { + position.addToRef(velocity, finalPosition); + return; + } + if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) { + collider._getResponse(position, velocity); + } + if (velocity.length() <= closeDistance) { + finalPosition.copyFrom(position); + return; + } + collider._retry++; + this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh); + } +} +Scene.CollisionCoordinatorFactory = () => { + return new DefaultCollisionCoordinator(); +}; + +// Do not edit. +const name$7W = "pickingPixelShader"; +const shader$7V = `#if defined(INSTANCES) +varying vec4 vMeshID; +#else +uniform vec4 meshID; +#endif +void main(void) { +#if defined(INSTANCES) +gl_FragColor=vMeshID; +#else +gl_FragColor=meshID; +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7W]) { + ShaderStore.ShadersStore[name$7W] = shader$7V; +} + +// Do not edit. +const name$7V = "pickingVertexShader"; +const shader$7U = `attribute vec3 position; +#if defined(INSTANCES) +attribute vec4 instanceMeshID; +#endif +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +uniform mat4 viewProjection; +#if defined(INSTANCES) +varying vec4 vMeshID; +#endif +void main(void) { +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos; +#if defined(INSTANCES) +vMeshID=instanceMeshID; +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7V]) { + ShaderStore.ShadersStore[name$7V] = shader$7U; +} + +// Do not edit. +const name$7U = "pickingPixelShader"; +const shader$7T = `#if defined(INSTANCES) +varying vMeshID: vec4f; +#else +uniform meshID: vec4f; +#endif +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#if defined(INSTANCES) +fragmentOutputs.color=input.vMeshID; +#else +fragmentOutputs.color=uniforms.meshID; +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7U]) { + ShaderStore.ShadersStoreWGSL[name$7U] = shader$7T; +} + +// Do not edit. +const name$7T = "bonesDeclaration"; +const shader$7S = `#if NUM_BONE_INFLUENCERS>0 +attribute matricesIndices : vec4;attribute matricesWeights : vec4; +#if NUM_BONE_INFLUENCERS>4 +attribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4; +#endif +#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#ifdef BONETEXTURE +var boneSampler : texture_2d;uniform boneTextureWidth : f32; +#else +uniform mBones : array; +#ifdef BONES_VELOCITY_ENABLED +uniform mPreviousBones : array; +#endif +#endif +#ifdef BONETEXTURE +fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4 +{let offset=i32(index) *4; +let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);} +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7T]) { + ShaderStore.IncludesShadersStoreWGSL[name$7T] = shader$7S; +} +/** @internal */ +const bonesDeclarationWGSL = { name: name$7T, shader: shader$7S }; + +const bonesDeclaration = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bonesDeclarationWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7S = "bakedVertexAnimationDeclaration"; +const shader$7R = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d; +#ifdef INSTANCES +attribute bakedVertexAnimationSettingsInstanced : vec4; +#endif +fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4 +{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7S]) { + ShaderStore.IncludesShadersStoreWGSL[name$7S] = shader$7R; +} + +// Do not edit. +const name$7R = "morphTargetsVertexGlobalDeclaration"; +const shader$7Q = `#ifdef MORPHTARGETS +uniform morphTargetInfluences : array; +#ifdef MORPHTARGETS_TEXTURE +uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3 +{ +let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} +fn readVector4FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec4 +{ +let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0);} +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7R]) { + ShaderStore.IncludesShadersStoreWGSL[name$7R] = shader$7Q; +} +/** @internal */ +const morphTargetsVertexGlobalDeclarationWGSL = { name: name$7R, shader: shader$7Q }; + +const morphTargetsVertexGlobalDeclaration = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + morphTargetsVertexGlobalDeclarationWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7Q = "morphTargetsVertexDeclaration"; +const shader$7P = `#ifdef MORPHTARGETS +#ifndef MORPHTARGETS_TEXTURE +#ifdef MORPHTARGETS_POSITION +attribute position{X} : vec3; +#endif +#ifdef MORPHTARGETS_NORMAL +attribute normal{X} : vec3; +#endif +#ifdef MORPHTARGETS_TANGENT +attribute tangent{X} : vec3; +#endif +#ifdef MORPHTARGETS_UV +attribute uv_{X} : vec2; +#endif +#ifdef MORPHTARGETS_UV2 +attribute uv2_{X} : vec2; +#endif +#elif {X}==0 +uniform morphTargetCount: i32; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7Q]) { + ShaderStore.IncludesShadersStoreWGSL[name$7Q] = shader$7P; +} +/** @internal */ +const morphTargetsVertexDeclarationWGSL = { name: name$7Q, shader: shader$7P }; + +const morphTargetsVertexDeclaration = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + morphTargetsVertexDeclarationWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7P = "instancesDeclaration"; +const shader$7O = `#ifdef INSTANCES +attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; +#ifdef INSTANCESCOLOR +attribute instanceColor : vec4; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform world : mat4x4; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) +attribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4; +#ifdef THIN_INSTANCES +uniform previousWorld : mat4x4; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform world : mat4x4; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) +uniform previousWorld : mat4x4; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7P]) { + ShaderStore.IncludesShadersStoreWGSL[name$7P] = shader$7O; +} + +// Do not edit. +const name$7O = "morphTargetsVertexGlobal"; +const shader$7N = `#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +var vertexID : f32; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7O]) { + ShaderStore.IncludesShadersStoreWGSL[name$7O] = shader$7N; +} +/** @internal */ +const morphTargetsVertexGlobalWGSL = { name: name$7O, shader: shader$7N }; + +const morphTargetsVertexGlobal = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + morphTargetsVertexGlobalWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7N = "morphTargetsVertex"; +const shader$7M = `#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +#if {X}==0 +for (var i=0; i=uniforms.morphTargetCount) {break;} +vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x; +#ifdef MORPHTARGETS_POSITION +positionUpdated=positionUpdated+(readVector3FromRawSampler(i,vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[i]; +#endif +#ifdef MORPHTARGETTEXTURE_HASPOSITIONS +vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_NORMAL +normalUpdated=normalUpdated+(readVector3FromRawSampler(i,vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[i]; +#endif +#ifdef MORPHTARGETTEXTURE_HASNORMALS +vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[i]; +#endif +#ifdef MORPHTARGETTEXTURE_HASUVS +vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated=vec4f(tangentUpdated.xyz+(readVector3FromRawSampler(i,vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[i],tangentUpdated.a); +#endif +#ifdef MORPHTARGETTEXTURE_HASTANGENTS +vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_UV2 +uv2Updated=uv2Updated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv2)*uniforms.morphTargetInfluences[i]; +#endif +#ifdef MORPHTARGETS_COLOR +colorUpdated=colorUpdated+(readVector4FromRawSampler(i,vertexID)-vertexInputs.color)*uniforms.morphTargetInfluences[i]; +#endif +} +#endif +#else +#ifdef MORPHTARGETS_POSITION +positionUpdated=positionUpdated+(vertexInputs.position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_NORMAL +normalUpdated=normalUpdated+(vertexInputs.normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated=vec4f(tangentUpdated.xyz+(vertexInputs.tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}],tangentUpdated.a); +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(vertexInputs.uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV2 +uv2Updated=uv2Updated+(vertexInputs.uv2_{X}-vertexInputs.uv2)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_COLOR +colorUpdated=colorUpdated+(vertexInputs.color{X}-vertexInputs.color)*uniforms.morphTargetInfluences[{X}]; +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7N]) { + ShaderStore.IncludesShadersStoreWGSL[name$7N] = shader$7M; +} +/** @internal */ +const morphTargetsVertexWGSL = { name: name$7N, shader: shader$7M }; + +const morphTargetsVertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + morphTargetsVertexWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7M = "instancesVertex"; +const shader$7L = `#ifdef INSTANCES +var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) +var finalPreviousWorld=mat4x4( +vertexInputs.previousWorld0,vertexInputs.previousWorld1, +vertexInputs.previousWorld2,vertexInputs.previousWorld3); +#endif +#ifdef THIN_INSTANCES +#if !defined(WORLD_UBO) +finalWorld=uniforms.world*finalWorld; +#else +finalWorld=mesh.world*finalWorld; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) +finalPreviousWorld=uniforms.previousWorld*finalPreviousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +var finalWorld=uniforms.world; +#else +var finalWorld=mesh.world; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) +var finalPreviousWorld=uniforms.previousWorld; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7M]) { + ShaderStore.IncludesShadersStoreWGSL[name$7M] = shader$7L; +} + +// Do not edit. +const name$7L = "bonesVertex"; +const shader$7K = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#if NUM_BONE_INFLUENCERS>0 +var influence : mat4x4; +#ifdef BONETEXTURE +influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; +#endif +#else +influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7L]) { + ShaderStore.IncludesShadersStoreWGSL[name$7L] = shader$7K; +} +/** @internal */ +const bonesVertexWGSL = { name: name$7L, shader: shader$7K }; + +const bonesVertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bonesVertexWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7K = "bakedVertexAnimation"; +const shader$7J = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +{ +#ifdef INSTANCES +let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; +#else +let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; +#endif +let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; +#endif +finalWorld=finalWorld*VATInfluence;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7K]) { + ShaderStore.IncludesShadersStoreWGSL[name$7K] = shader$7J; +} + +// Do not edit. +const name$7J = "pickingVertexShader"; +const shader$7I = `attribute position: vec3f; +#if defined(INSTANCES) +attribute instanceMeshID: vec4f; +#endif +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +uniform viewProjection: mat4x4f; +#if defined(INSTANCES) +varying vMeshID: vec4f; +#endif +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +var worldPos: vec4f=finalWorld*vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos; +#if defined(INSTANCES) +vertexOutputs.vMeshID=input.instanceMeshID; +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7J]) { + ShaderStore.ShadersStoreWGSL[name$7J] = shader$7I; +} + +/** + * Effect wrapping a compute shader and let execute (dispatch) the shader + */ +class ComputeEffect { + /** + * Creates a compute effect that can be used to execute a compute shader + * @param baseName Name of the effect + * @param options Set of all options to create the effect + * @param engine The engine the effect is created for + * @param key Effect Key identifying uniquely compiled shader variants + */ + constructor(baseName, options, engine, key = "") { + /** + * String container all the define statements that should be set on the shader. + */ + this.defines = ""; + /** + * Callback that will be called when the shader is compiled. + */ + this.onCompiled = null; + /** + * Callback that will be called if an error occurs during shader compilation. + */ + this.onError = null; + /** + * Unique ID of the effect. + */ + this.uniqueId = 0; + /** + * Observable that will be called when the shader is compiled. + * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised. + */ + this.onCompileObservable = new Observable(); + /** + * Observable that will be called if an error occurs during shader compilation. + */ + this.onErrorObservable = new Observable(); + /** + * Observable that will be called when effect is bound. + */ + this.onBindObservable = new Observable(); + /** + * @internal + * Specifies if the effect was previously ready + */ + this._wasPreviouslyReady = false; + this._isReady = false; + this._compilationError = ""; + /** @internal */ + this._key = ""; + this._computeSourceCodeOverride = ""; + /** @internal */ + this._pipelineContext = null; + /** @internal */ + this._computeSourceCode = ""; + this._rawComputeSourceCode = ""; + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + this.name = baseName; + this._key = key; + this._engine = engine; + this.uniqueId = ComputeEffect._UniqueIdSeed++; + this.defines = options.defines ?? ""; + this.onError = options.onError; + this.onCompiled = options.onCompiled; + this._entryPoint = options.entryPoint ?? "main"; + this._shaderStore = ShaderStore.GetShadersStore(this._shaderLanguage); + this._shaderRepository = ShaderStore.GetShadersRepository(this._shaderLanguage); + this._includeShaderStore = ShaderStore.GetIncludesShadersStore(this._shaderLanguage); + let computeSource; + const hostDocument = IsWindowObjectExist() ? this._engine.getHostDocument() : null; + if (typeof baseName === "string") { + computeSource = baseName; + } + else if (baseName.computeSource) { + computeSource = "source:" + baseName.computeSource; + } + else if (baseName.computeElement) { + computeSource = hostDocument?.getElementById(baseName.computeElement) || baseName.computeElement; + } + else { + computeSource = baseName.compute || baseName; + } + const processorOptions = { + defines: this.defines.split("\n"), + indexParameters: undefined, + isFragment: false, + shouldUseHighPrecisionShader: false, + processor: null, + supportsUniformBuffers: this._engine.supportsUniformBuffers, + shadersRepository: this._shaderRepository, + includesShadersStore: this._includeShaderStore, + version: (this._engine.version * 100).toString(), + platformName: this._engine.shaderPlatformName, + processingContext: null, + isNDCHalfZRange: this._engine.isNDCHalfZRange, + useReverseDepthBuffer: this._engine.useReverseDepthBuffer, + processCodeAfterIncludes: (shaderType, code, defines) => { + if (!defines) { + return code; + } + // We need to convert #define key value to a const + for (const define of defines) { + const keyValue = define.replace("#define", "").replace(";", "").trim(); + const split = keyValue.split(" "); + if (split.length === 2) { + const key = split[0]; + const value = split[1]; + if (!isNaN(parseInt(value)) || !isNaN(parseFloat(value))) { + code = `const ${key} = ${value};\n` + code; + } + } + } + return code; + }, + }; + this._loadShader(computeSource, "Compute", "", (computeCode) => { + Initialize(processorOptions); + PreProcess(computeCode, processorOptions, (migratedComputeCode) => { + this._rawComputeSourceCode = computeCode; + if (options.processFinalCode) { + migratedComputeCode = options.processFinalCode(migratedComputeCode); + } + const finalShaders = Finalize(migratedComputeCode, "", processorOptions); + this._useFinalCode(finalShaders.vertexCode, baseName); + }, this._engine); + }); + } + _useFinalCode(migratedCommputeCode, baseName) { + if (baseName) { + const compute = baseName.computeElement || baseName.compute || baseName.spectorName || baseName; + this._computeSourceCode = "//#define SHADER_NAME compute:" + compute + "\n" + migratedCommputeCode; + } + else { + this._computeSourceCode = migratedCommputeCode; + } + this._prepareEffect(); + } + /** + * Unique key for this effect + */ + get key() { + return this._key; + } + /** + * If the effect has been compiled and prepared. + * @returns if the effect is compiled and prepared. + */ + isReady() { + try { + return this._isReadyInternal(); + } + catch { + return false; + } + } + _isReadyInternal() { + if (this._isReady) { + return true; + } + if (this._pipelineContext) { + return this._pipelineContext.isReady; + } + return false; + } + /** + * The engine the effect was initialized with. + * @returns the engine. + */ + getEngine() { + return this._engine; + } + /** + * The pipeline context for this effect + * @returns the associated pipeline context + */ + getPipelineContext() { + return this._pipelineContext; + } + /** + * The error from the last compilation. + * @returns the error string. + */ + getCompilationError() { + return this._compilationError; + } + /** + * Adds a callback to the onCompiled observable and call the callback immediately if already ready. + * @param func The callback to be used. + */ + executeWhenCompiled(func) { + if (this.isReady()) { + func(this); + return; + } + this.onCompileObservable.add((effect) => { + func(effect); + }); + if (!this._pipelineContext || this._pipelineContext.isAsync) { + this._checkIsReady(null); + } + } + _checkIsReady(previousPipelineContext) { + _retryWithInterval(() => this._isReadyInternal(), () => { + // no-op, all work is done in _isReadyInternal + }, (e) => { + this._processCompilationErrors(e, previousPipelineContext); + }, undefined, undefined, false); + } + _loadShader(shader, key, optionalKey, callback) { + if (typeof HTMLElement !== "undefined") { + // DOM element ? + if (shader instanceof HTMLElement) { + const shaderCode = GetDOMTextContent(shader); + callback(shaderCode); + return; + } + } + // Direct source ? + if (shader.substring(0, 7) === "source:") { + callback(shader.substring(7)); + return; + } + // Base64 encoded ? + if (shader.substring(0, 7) === "base64:") { + const shaderBinary = window.atob(shader.substring(7)); + callback(shaderBinary); + return; + } + // Is in local store ? + if (this._shaderStore[shader + key + "Shader"]) { + callback(this._shaderStore[shader + key + "Shader"]); + return; + } + if (optionalKey && this._shaderStore[shader + optionalKey + "Shader"]) { + callback(this._shaderStore[shader + optionalKey + "Shader"]); + return; + } + let shaderUrl; + if (shader[0] === "." || shader[0] === "/" || shader.indexOf("http") > -1) { + shaderUrl = shader; + } + else { + shaderUrl = this._shaderRepository + shader; + } + this._engine._loadFile(shaderUrl + "." + key.toLowerCase() + ".fx", callback); + } + /** + * Gets the compute shader source code of this effect + */ + get computeSourceCode() { + return this._computeSourceCodeOverride ? this._computeSourceCodeOverride : (this._pipelineContext?._getComputeShaderCode() ?? this._computeSourceCode); + } + /** + * Gets the compute shader source code before it has been processed by the preprocessor + */ + get rawComputeSourceCode() { + return this._rawComputeSourceCode; + } + /** + * Prepares the effect + * @internal + */ + _prepareEffect() { + const defines = this.defines; + const previousPipelineContext = this._pipelineContext; + this._isReady = false; + try { + const engine = this._engine; + this._pipelineContext = engine.createComputePipelineContext(); + this._pipelineContext._name = this._key; + engine._prepareComputePipelineContext(this._pipelineContext, this._computeSourceCodeOverride ? this._computeSourceCodeOverride : this._computeSourceCode, this._rawComputeSourceCode, this._computeSourceCodeOverride ? null : defines, this._entryPoint); + engine._executeWhenComputeStateIsCompiled(this._pipelineContext, (messages) => { + if (messages && messages.numErrors > 0) { + this._processCompilationErrors(messages, previousPipelineContext); + return; + } + this._compilationError = ""; + this._isReady = true; + if (this.onCompiled) { + this.onCompiled(this); + } + this.onCompileObservable.notifyObservers(this); + this.onCompileObservable.clear(); + if (previousPipelineContext) { + this.getEngine()._deleteComputePipelineContext(previousPipelineContext); + } + }); + if (this._pipelineContext.isAsync) { + this._checkIsReady(previousPipelineContext); + } + } + catch (e) { + this._processCompilationErrors(e, previousPipelineContext); + } + } + _processCompilationErrors(e, previousPipelineContext = null) { + this._compilationError = ""; + Logger.Error("Unable to compile compute effect:"); + if (this.defines) { + Logger.Error("Defines:\n" + this.defines); + } + if (ComputeEffect.LogShaderCodeOnCompilationError) { + const code = this._pipelineContext?._getComputeShaderCode(); + if (code) { + Logger.Error("Compute code:"); + Logger.Error(code); + } + } + if (typeof e === "string") { + this._compilationError = e; + Logger.Error("Error: " + this._compilationError); + } + else { + for (const message of e.messages) { + let msg = ""; + if (message.line !== undefined) { + msg += "Line " + message.line + ", "; + } + if (message.offset !== undefined) { + msg += "Offset " + message.offset + ", "; + } + if (message.length !== undefined) { + msg += "Length " + message.length + ", "; + } + msg += message.type + ": " + message.text; + if (this._compilationError) { + this._compilationError += "\n"; + } + this._compilationError += msg; + Logger.Error(msg); + } + } + if (previousPipelineContext) { + this._pipelineContext = previousPipelineContext; + this._isReady = true; + } + if (this.onError) { + this.onError(this, this._compilationError); + } + this.onErrorObservable.notifyObservers(this); + } + /** + * Release all associated resources. + **/ + dispose() { + if (this._pipelineContext) { + this._pipelineContext.dispose(); + } + this._engine._releaseComputeEffect(this); + } + /** + * This function will add a new compute shader to the shader store + * @param name the name of the shader + * @param computeShader compute shader content + */ + static RegisterShader(name, computeShader) { + ShaderStore.GetShadersStore(1 /* ShaderLanguage.WGSL */)[`${name}ComputeShader`] = computeShader; + } +} +ComputeEffect._UniqueIdSeed = 0; +/** + * Enable logging of the shader code when a compilation error occurs + */ +ComputeEffect.LogShaderCodeOnCompilationError = true; + +/** + * Class used to define a WebGPU performance counter + */ +class WebGPUPerfCounter { + constructor() { + this._gpuTimeInFrameId = -1; + /** + * The GPU time in nanoseconds spent in the last frame + */ + this.counter = new PerfCounter(); + } + /** + * @internal + */ + _addDuration(currentFrameId, duration) { + if (currentFrameId < this._gpuTimeInFrameId) { + return; + } + if (this._gpuTimeInFrameId !== currentFrameId) { + this.counter._fetchResult(); + this.counter.fetchNewFrame(); + this.counter.addCount(duration, false); + this._gpuTimeInFrameId = currentFrameId; + } + else { + this.counter.addCount(duration, false); + } + } +} + +/** + * The ComputeShader object lets you execute a compute shader on your GPU (if supported by the engine) + */ +class ComputeShader { + /** + * The options used to create the shader + */ + get options() { + return this._options; + } + /** + * The shaderPath used to create the shader + */ + get shaderPath() { + return this._shaderPath; + } + /** + * Instantiates a new compute shader. + * @param name Defines the name of the compute shader in the scene + * @param engine Defines the engine the compute shader belongs to + * @param shaderPath Defines the route to the shader code in one of three ways: + * * object: \{ compute: "custom" \}, used with ShaderStore.ShadersStoreWGSL["customComputeShader"] + * * object: \{ computeElement: "HTMLElementId" \}, used with shader code in script tags + * * object: \{ computeSource: "compute shader code string" \}, where the string contains the shader code + * * string: try first to find the code in ShaderStore.ShadersStoreWGSL[shaderPath + "ComputeShader"]. If not, assumes it is a file with name shaderPath.compute.fx in index.html folder. + * @param options Define the options used to create the shader + */ + constructor(name, engine, shaderPath, options = {}) { + this._bindings = {}; + this._samplers = {}; + this._contextIsDirty = false; + /** + * When set to true, dispatch won't call isReady anymore and won't check if the underlying GPU resources should be (re)created because of a change in the inputs (texture, uniform buffer, etc.) + * If you know that your inputs did not change since last time dispatch was called and that isReady() returns true, set this flag to true to improve performance + */ + this.fastMode = false; + /** + * Callback triggered when the shader is compiled + */ + this.onCompiled = null; + /** + * Callback triggered when an error occurs + */ + this.onError = null; + this.name = name; + this._engine = engine; + this.uniqueId = UniqueIdGenerator.UniqueId; + if (engine.enableGPUTimingMeasurements) { + this.gpuTimeInFrame = new WebGPUPerfCounter(); + } + if (!this._engine.getCaps().supportComputeShaders) { + Logger.Error("This engine does not support compute shaders!"); + return; + } + if (!options.bindingsMapping) { + Logger.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!"); + return; + } + this._context = engine.createComputeContext(); + this._shaderPath = shaderPath; + this._options = { + bindingsMapping: {}, + defines: [], + ...options, + }; + } + /** + * Gets the current class name of the material e.g. "ComputeShader" + * Mainly use in serialization. + * @returns the class name + */ + getClassName() { + return "ComputeShader"; + } + /** + * Binds a texture to the shader + * @param name Binding name of the texture + * @param texture Texture to bind + * @param bindSampler Bind the sampler corresponding to the texture (default: true). The sampler will be bound just before the binding index of the texture + */ + setTexture(name, texture, bindSampler = true) { + const current = this._bindings[name]; + this._bindings[name] = { + type: bindSampler ? 0 /* ComputeBindingType.Texture */ : 4 /* ComputeBindingType.TextureWithoutSampler */, + object: texture, + indexInGroupEntries: current?.indexInGroupEntries, + }; + this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture || current.type !== this._bindings[name].type); + } + /** + * Binds a storage texture to the shader + * @param name Binding name of the texture + * @param texture Texture to bind + */ + setStorageTexture(name, texture) { + const current = this._bindings[name]; + this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture); + this._bindings[name] = { + type: 1 /* ComputeBindingType.StorageTexture */, + object: texture, + indexInGroupEntries: current?.indexInGroupEntries, + }; + } + /** + * Binds an external texture to the shader + * @param name Binding name of the texture + * @param texture Texture to bind + */ + setExternalTexture(name, texture) { + const current = this._bindings[name]; + this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture); + this._bindings[name] = { + type: 6 /* ComputeBindingType.ExternalTexture */, + object: texture, + indexInGroupEntries: current?.indexInGroupEntries, + }; + } + /** + * Binds a video texture to the shader (by binding the external texture attached to this video) + * @param name Binding name of the texture + * @param texture Texture to bind + * @returns true if the video texture was successfully bound, else false. false will be returned if the current engine does not support external textures + */ + setVideoTexture(name, texture) { + if (texture.externalTexture) { + this.setExternalTexture(name, texture.externalTexture); + return true; + } + return false; + } + /** + * Binds a uniform buffer to the shader + * @param name Binding name of the buffer + * @param buffer Buffer to bind + */ + setUniformBuffer(name, buffer) { + const current = this._bindings[name]; + this._contextIsDirty || (this._contextIsDirty = !current || current.object !== buffer); + this._bindings[name] = { + type: ComputeShader._BufferIsDataBuffer(buffer) ? 7 /* ComputeBindingType.DataBuffer */ : 2 /* ComputeBindingType.UniformBuffer */, + object: buffer, + indexInGroupEntries: current?.indexInGroupEntries, + }; + } + /** + * Binds a storage buffer to the shader + * @param name Binding name of the buffer + * @param buffer Buffer to bind + */ + setStorageBuffer(name, buffer) { + const current = this._bindings[name]; + this._contextIsDirty || (this._contextIsDirty = !current || current.object !== buffer); + this._bindings[name] = { + type: ComputeShader._BufferIsDataBuffer(buffer) ? 7 /* ComputeBindingType.DataBuffer */ : 3 /* ComputeBindingType.StorageBuffer */, + object: buffer, + indexInGroupEntries: current?.indexInGroupEntries, + }; + } + /** + * Binds a texture sampler to the shader + * @param name Binding name of the sampler + * @param sampler Sampler to bind + */ + setTextureSampler(name, sampler) { + const current = this._bindings[name]; + this._contextIsDirty || (this._contextIsDirty = !current || !sampler.compareSampler(current.object)); + this._bindings[name] = { + type: 5 /* ComputeBindingType.Sampler */, + object: sampler, + indexInGroupEntries: current?.indexInGroupEntries, + }; + } + /** + * Specifies that the compute shader is ready to be executed (the compute effect and all the resources are ready) + * @returns true if the compute shader is ready to be executed + */ + isReady() { + let effect = this._effect; + for (const key in this._bindings) { + const binding = this._bindings[key], type = binding.type, object = binding.object; + switch (type) { + case 0 /* ComputeBindingType.Texture */: + case 4 /* ComputeBindingType.TextureWithoutSampler */: + case 1 /* ComputeBindingType.StorageTexture */: { + const texture = object; + if (!texture.isReady()) { + return false; + } + break; + } + case 6 /* ComputeBindingType.ExternalTexture */: { + const texture = object; + if (!texture.isReady()) { + return false; + } + break; + } + } + } + const defines = []; + const shaderName = this._shaderPath; + if (this._options.defines) { + for (let index = 0; index < this._options.defines.length; index++) { + defines.push(this._options.defines[index]); + } + } + const join = defines.join("\n"); + if (this._cachedDefines !== join) { + this._cachedDefines = join; + effect = this._engine.createComputeEffect(shaderName, { + defines: join, + entryPoint: this._options.entryPoint, + onCompiled: this.onCompiled, + onError: this.onError, + }); + this._effect = effect; + } + if (!effect.isReady()) { + return false; + } + return true; + } + /** + * Dispatches (executes) the compute shader + * @param x Number of workgroups to execute on the X dimension + * @param y Number of workgroups to execute on the Y dimension (default: 1) + * @param z Number of workgroups to execute on the Z dimension (default: 1) + * @returns True if the dispatch could be done, else false (meaning either the compute effect or at least one of the bound resources was not ready) + */ + dispatch(x, y, z) { + if (!this.fastMode && !this._checkContext()) { + return false; + } + this._engine.computeDispatch(this._effect, this._context, this._bindings, x, y, z, this._options.bindingsMapping, this.gpuTimeInFrame); + return true; + } + /** + * Dispatches (executes) the compute shader. + * @param buffer Buffer containing the number of workgroups to execute on the X, Y and Z dimensions + * @param offset Offset in the buffer where the workgroup counts are stored (default: 0) + * @returns True if the dispatch could be done, else false (meaning either the compute effect or at least one of the bound resources was not ready) + */ + dispatchIndirect(buffer, offset = 0) { + if (!this.fastMode && !this._checkContext()) { + return false; + } + const dataBuffer = ComputeShader._BufferIsDataBuffer(buffer) ? buffer : buffer.getBuffer(); + this._engine.computeDispatchIndirect(this._effect, this._context, this._bindings, dataBuffer, offset, this._options.bindingsMapping, this.gpuTimeInFrame); + return true; + } + _checkContext() { + if (!this.isReady()) { + return false; + } + // If the sampling parameters of a texture bound to the shader have changed, we must clear the compute context so that it is recreated with the updated values + // Also, if the actual (gpu) buffer used by a uniform buffer has changed, we must clear the compute context so that it is recreated with the updated value + for (const key in this._bindings) { + const binding = this._bindings[key]; + if (!this._options.bindingsMapping[key]) { + throw new Error("ComputeShader ('" + this.name + "'): No binding mapping has been provided for the property '" + key + "'"); + } + switch (binding.type) { + case 0 /* ComputeBindingType.Texture */: { + const sampler = this._samplers[key]; + const texture = binding.object; + if (!sampler || !texture._texture || !sampler.compareSampler(texture._texture)) { + this._samplers[key] = new TextureSampler().setParameters(texture.wrapU, texture.wrapV, texture.wrapR, texture.anisotropicFilteringLevel, texture._texture.samplingMode, texture._texture?._comparisonFunction); + this._contextIsDirty = true; + } + break; + } + case 6 /* ComputeBindingType.ExternalTexture */: { + // we must recreate the bind groups each time if there's an external texture, because device.importExternalTexture must be called each frame + this._contextIsDirty = true; + break; + } + case 2 /* ComputeBindingType.UniformBuffer */: { + const ubo = binding.object; + if (ubo.getBuffer() !== binding.buffer) { + binding.buffer = ubo.getBuffer(); + this._contextIsDirty = true; + } + break; + } + } + } + if (this._contextIsDirty) { + this._contextIsDirty = false; + this._context.clear(); + } + return true; + } + /** + * Waits for the compute shader to be ready and executes it + * @param x Number of workgroups to execute on the X dimension + * @param y Number of workgroups to execute on the Y dimension (default: 1) + * @param z Number of workgroups to execute on the Z dimension (default: 1) + * @param delay Delay between the retries while the shader is not ready (in milliseconds - 10 by default) + * @returns A promise that is resolved once the shader has been sent to the GPU. Note that it does not mean that the shader execution itself is finished! + */ + dispatchWhenReady(x, y, z, delay = 10) { + return new Promise((resolve) => { + _retryWithInterval(() => this.dispatch(x, y, z), resolve, undefined, delay); + }); + } + /** + * Serializes this compute shader in a JSON representation + * @returns the serialized compute shader object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.options = this._options; + serializationObject.shaderPath = this._shaderPath; + serializationObject.bindings = {}; + serializationObject.textures = {}; + for (const key in this._bindings) { + const binding = this._bindings[key]; + const object = binding.object; + switch (binding.type) { + case 0 /* ComputeBindingType.Texture */: + case 4 /* ComputeBindingType.TextureWithoutSampler */: + case 1 /* ComputeBindingType.StorageTexture */: { + const serializedData = object.serialize(); + if (serializedData) { + serializationObject.textures[key] = serializedData; + serializationObject.bindings[key] = { + type: binding.type, + }; + } + break; + } + } + } + return serializationObject; + } + /** + * Creates a compute shader from parsed compute shader data + * @param source defines the JSON representation of the compute shader + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a new compute shader + */ + static Parse(source, scene, rootUrl) { + const compute = SerializationHelper.Parse(() => new ComputeShader(source.name, scene.getEngine(), source.shaderPath, source.options), source, scene, rootUrl); + for (const key in source.textures) { + const binding = source.bindings[key]; + const texture = Texture.Parse(source.textures[key], scene, rootUrl); + if (binding.type === 0 /* ComputeBindingType.Texture */) { + compute.setTexture(key, texture); + } + else if (binding.type === 4 /* ComputeBindingType.TextureWithoutSampler */) { + compute.setTexture(key, texture, false); + } + else { + compute.setStorageTexture(key, texture); + } + } + return compute; + } + static _BufferIsDataBuffer(buffer) { + return buffer.underlyingResource !== undefined; + } +} +__decorate([ + serialize() +], ComputeShader.prototype, "name", void 0); +__decorate([ + serialize() +], ComputeShader.prototype, "fastMode", void 0); +RegisterClass("BABYLON.ComputeShader", ComputeShader); + +// Do not edit. +const name$7I = "gpuTransformVertexShader"; +const shader$7H = `attribute vec3 position; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +out vec3 outPosition;const mat4 identity=mat4( +vec4(1.0,0.0,0.0,0.0), +vec4(0.0,1.0,0.0,0.0), +vec4(0.0,0.0,1.0,0.0), +vec4(0.0,0.0,0.0,1.0) +);void main(void) {vec3 positionUpdated=position; +#include +#include[0..maxSimultaneousMorphTargets] +mat4 finalWorld=identity; +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);outPosition=worldPos.xyz;}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7I]) { + ShaderStore.ShadersStore[name$7I] = shader$7H; +} + +// Do not edit. +const name$7H = "gpuTransformPixelShader"; +const shader$7G = `#version 300 es +void main() {discard;} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7H]) { + ShaderStore.ShadersStore[name$7H] = shader$7G; +} + +// Do not edit. +const name$7G = "boundingInfoComputeShader"; +const shader$7F = `struct Results {minX : atomic, +minY : atomic, +minZ : atomic, +maxX : atomic, +maxY : atomic, +maxZ : atomic, +dummy1 : i32, +dummy2 : i32,};fn floatToBits(value: f32)->i32 {return bitcast(value);} +fn bitsToFloat(value: i32)->f32 {return bitcast(value);} +fn atomicMinFloat(atomicVar: ptr,read_write>,value: f32) {let intValue=floatToBits(value);loop {let oldIntValue=atomicLoad(atomicVar);let oldValue=bitsToFloat(oldIntValue);if (value>=oldValue) {break;} +if (atomicCompareExchangeWeak(atomicVar,oldIntValue,intValue).old_value==oldIntValue) {break;}}} +fn atomicMaxFloat(atomicVar: ptr,read_write>,value: f32) {let intValue=floatToBits(value);loop {let oldIntValue=atomicLoad(atomicVar);let oldValue=bitsToFloat(oldIntValue);if (value<=oldValue) {break;} +if (atomicCompareExchangeWeak(atomicVar,oldIntValue,intValue).old_value==oldIntValue) {break;}}} +fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4 +{let offset=i32(index) *4; +let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);} +const identity=mat4x4f( +vec4f(1.0,0.0,0.0,0.0), +vec4f(0.0,1.0,0.0,0.0), +vec4f(0.0,0.0,1.0,0.0), +vec4f(0.0,0.0,0.0,1.0) +);struct Settings {morphTargetTextureInfo: vec3f, +morphTargetCount: i32, +indexResult : u32,};@group(0) @binding(0) var positionBuffer : array;@group(0) @binding(1) var resultBuffer : array;@group(0) @binding(7) var settings : Settings; +#if NUM_BONE_INFLUENCERS>0 +@group(0) @binding(2) var boneSampler : texture_2d;@group(0) @binding(3) var indexBuffer : array;@group(0) @binding(4) var weightBuffer : array; +#if NUM_BONE_INFLUENCERS>4 +@group(0) @binding(5) var indexExtraBuffer : array;@group(0) @binding(6) var weightExtraBuffer : array; +#endif +#endif +#ifdef MORPHTARGETS +@group(0) @binding(8) var morphTargets : texture_2d_array;@group(0) @binding(9) var morphTargetInfluences : array;@group(0) @binding(10) var morphTargetTextureIndices : array; +#endif +#ifdef MORPHTARGETS +fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : u32)->vec3f +{ +let vertexID=f32(vertexIndex)*settings.morphTargetTextureInfo.x;let y=floor(vertexID/settings.morphTargetTextureInfo.y);let x=vertexID-y*settings.morphTargetTextureInfo.y;let textureUV=vec2(i32(x),i32(y));return textureLoad(morphTargets,textureUV,i32(morphTargetTextureIndices[targetIndex]),0).xyz;} +fn readVector4FromRawSampler(targetIndex : i32,vertexIndex : u32)->vec4f +{ +let vertexID=f32(vertexIndex)*settings.morphTargetTextureInfo.x;let y=floor(vertexID/settings.morphTargetTextureInfo.y);let x=vertexID-y*settings.morphTargetTextureInfo.y;let textureUV=vec2(i32(x),i32(y));return textureLoad(morphTargets,textureUV,i32(morphTargetTextureIndices[targetIndex]),0);} +#endif +@compute @workgroup_size(256,1,1) +fn main(@builtin(global_invocation_id) global_id : vec3) {let index=global_id.x;if (index>=arrayLength(&positionBuffer)/3) {return;} +let position=vec3f(positionBuffer[index*3],positionBuffer[index*3+1],positionBuffer[index*3+2]);var finalWorld=identity;var positionUpdated=position; +#if NUM_BONE_INFLUENCERS>0 +var influence : mat4x4;let matricesIndices=indexBuffer[index];let matricesWeights=weightBuffer[index];influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +let matricesIndicesExtra=indexExtraBuffer[index];let matricesWeightsExtra=weightExtraBuffer[index];influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.x)*matricesWeightsExtra.x; +#if NUM_BONE_INFLUENCERS>5 +influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.y)*matricesWeightsExtra.y; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.z)*matricesWeightsExtra.z; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.w)*matricesWeightsExtra.w; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#ifdef MORPHTARGETS +for (var i=0; i=settings.morphTargetCount) {break;} +positionUpdated=positionUpdated+(readVector3FromRawSampler(i,index)-position)*morphTargetInfluences[i];} +#endif +var worldPos=finalWorld*vec4f(positionUpdated.x,positionUpdated.y,positionUpdated.z,1.0);atomicMinFloat(&resultBuffer[settings.indexResult].minX,worldPos.x);atomicMinFloat(&resultBuffer[settings.indexResult].minY,worldPos.y);atomicMinFloat(&resultBuffer[settings.indexResult].minZ,worldPos.z);atomicMaxFloat(&resultBuffer[settings.indexResult].maxX,worldPos.x);atomicMaxFloat(&resultBuffer[settings.indexResult].maxY,worldPos.y);atomicMaxFloat(&resultBuffer[settings.indexResult].maxZ,worldPos.z);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7G]) { + ShaderStore.ShadersStoreWGSL[name$7G] = shader$7F; +} + +/** + * Class used to store a cell in an octree + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees + */ +class OctreeBlock { + /** + * Creates a new block + * @param minPoint defines the minimum vector (in world space) of the block's bounding box + * @param maxPoint defines the maximum vector (in world space) of the block's bounding box + * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks) + * @param depth defines the current depth of this block in the octree + * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored) + * @param creationFunc defines a callback to call when an element is added to the block + */ + constructor(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) { + /** + * Gets the content of the current block + */ + this.entries = []; + this._boundingVectors = new Array(); + this._capacity = capacity; + this._depth = depth; + this._maxDepth = maxDepth; + this._creationFunc = creationFunc; + this._minPoint = minPoint; + this._maxPoint = maxPoint; + this._boundingVectors.push(minPoint.clone()); + this._boundingVectors.push(maxPoint.clone()); + this._boundingVectors.push(minPoint.clone()); + this._boundingVectors[2].x = maxPoint.x; + this._boundingVectors.push(minPoint.clone()); + this._boundingVectors[3].y = maxPoint.y; + this._boundingVectors.push(minPoint.clone()); + this._boundingVectors[4].z = maxPoint.z; + this._boundingVectors.push(maxPoint.clone()); + this._boundingVectors[5].z = minPoint.z; + this._boundingVectors.push(maxPoint.clone()); + this._boundingVectors[6].x = minPoint.x; + this._boundingVectors.push(maxPoint.clone()); + this._boundingVectors[7].y = minPoint.y; + } + // Property + /** + * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks) + */ + get capacity() { + return this._capacity; + } + /** + * Gets the minimum vector (in world space) of the block's bounding box + */ + get minPoint() { + return this._minPoint; + } + /** + * Gets the maximum vector (in world space) of the block's bounding box + */ + get maxPoint() { + return this._maxPoint; + } + // Methods + /** + * Add a new element to this block + * @param entry defines the element to add + */ + addEntry(entry) { + if (this.blocks) { + for (let index = 0; index < this.blocks.length; index++) { + const block = this.blocks[index]; + block.addEntry(entry); + } + return; + } + this._creationFunc(entry, this); + if (this.entries.length > this.capacity && this._depth < this._maxDepth) { + this.createInnerBlocks(); + } + } + /** + * Remove an element from this block + * @param entry defines the element to remove + */ + removeEntry(entry) { + if (this.blocks) { + for (let index = 0; index < this.blocks.length; index++) { + const block = this.blocks[index]; + block.removeEntry(entry); + } + return; + } + const entryIndex = this.entries.indexOf(entry); + if (entryIndex > -1) { + this.entries.splice(entryIndex, 1); + } + } + /** + * Add an array of elements to this block + * @param entries defines the array of elements to add + */ + addEntries(entries) { + for (let index = 0; index < entries.length; index++) { + const mesh = entries[index]; + this.addEntry(mesh); + } + } + /** + * Test if the current block intersects the frustum planes and if yes, then add its content to the selection array + * @param frustumPlanes defines the frustum planes to test + * @param selection defines the array to store current content if selection is positive + * @param allowDuplicate defines if the selection array can contains duplicated entries + */ + select(frustumPlanes, selection, allowDuplicate) { + if (BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) { + if (this.blocks) { + for (let index = 0; index < this.blocks.length; index++) { + const block = this.blocks[index]; + block.select(frustumPlanes, selection, allowDuplicate); + } + return; + } + if (allowDuplicate) { + selection.concat(this.entries); + } + else { + selection.concatWithNoDuplicate(this.entries); + } + } + } + /** + * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array + * @param sphereCenter defines the bounding sphere center + * @param sphereRadius defines the bounding sphere radius + * @param selection defines the array to store current content if selection is positive + * @param allowDuplicate defines if the selection array can contains duplicated entries + */ + intersects(sphereCenter, sphereRadius, selection, allowDuplicate) { + if (BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) { + if (this.blocks) { + for (let index = 0; index < this.blocks.length; index++) { + const block = this.blocks[index]; + block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate); + } + return; + } + if (allowDuplicate) { + selection.concat(this.entries); + } + else { + selection.concatWithNoDuplicate(this.entries); + } + } + } + /** + * Test if the current block intersect with the given ray and if yes, then add its content to the selection array + * @param ray defines the ray to test with + * @param selection defines the array to store current content if selection is positive + */ + intersectsRay(ray, selection) { + if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) { + if (this.blocks) { + for (let index = 0; index < this.blocks.length; index++) { + const block = this.blocks[index]; + block.intersectsRay(ray, selection); + } + return; + } + selection.concatWithNoDuplicate(this.entries); + } + } + /** + * Subdivide the content into child blocks (this block will then be empty) + */ + createInnerBlocks() { + OctreeBlock._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc); + this.entries.splice(0); + } + /** + * @internal + */ + static _CreateBlocks(worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) { + target.blocks = new Array(); + const blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); + // Segmenting space + for (let x = 0; x < 2; x++) { + for (let y = 0; y < 2; y++) { + for (let z = 0; z < 2; z++) { + const localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z)); + const localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1)); + const block = new OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc); + block.addEntries(entries); + target.blocks.push(block); + } + } + } + } +} + +/** + * Octrees are a really powerful data structure that can quickly select entities based on space coordinates. + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees + */ +class Octree { + /** + * Creates a octree + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees + * @param creationFunc function to be used to instantiate the octree + * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64) + * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) + */ + constructor(creationFunc, maxBlockCapacity, + /** [2] Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */ + maxDepth = 2) { + this.maxDepth = maxDepth; + /** + * Content stored in the octree + */ + this.dynamicContent = []; + this._maxBlockCapacity = maxBlockCapacity || 64; + this._selectionContent = new SmartArrayNoDuplicate(1024); + this._creationFunc = creationFunc; + } + // Methods + /** + * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters + * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); + * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); + * @param entries meshes to be added to the octree blocks + */ + update(worldMin, worldMax, entries) { + OctreeBlock._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc); + } + /** + * Adds a mesh to the octree + * @param entry Mesh to add to the octree + */ + addMesh(entry) { + for (let index = 0; index < this.blocks.length; index++) { + const block = this.blocks[index]; + block.addEntry(entry); + } + } + /** + * Remove an element from the octree + * @param entry defines the element to remove + */ + removeMesh(entry) { + for (let index = 0; index < this.blocks.length; index++) { + const block = this.blocks[index]; + block.removeEntry(entry); + } + } + /** + * Selects an array of meshes within the frustum + * @param frustumPlanes The frustum planes to use which will select all meshes within it + * @param allowDuplicate If duplicate objects are allowed in the resulting object array + * @returns array of meshes within the frustum + */ + select(frustumPlanes, allowDuplicate) { + this._selectionContent.reset(); + for (let index = 0; index < this.blocks.length; index++) { + const block = this.blocks[index]; + block.select(frustumPlanes, this._selectionContent, allowDuplicate); + } + if (allowDuplicate) { + this._selectionContent.concat(this.dynamicContent); + } + else { + this._selectionContent.concatWithNoDuplicate(this.dynamicContent); + } + return this._selectionContent; + } + /** + * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array + * @param sphereCenter defines the bounding sphere center + * @param sphereRadius defines the bounding sphere radius + * @param allowDuplicate defines if the selection array can contains duplicated entries + * @returns an array of objects that intersect the sphere + */ + intersects(sphereCenter, sphereRadius, allowDuplicate) { + this._selectionContent.reset(); + for (let index = 0; index < this.blocks.length; index++) { + const block = this.blocks[index]; + block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate); + } + if (allowDuplicate) { + this._selectionContent.concat(this.dynamicContent); + } + else { + this._selectionContent.concatWithNoDuplicate(this.dynamicContent); + } + return this._selectionContent; + } + /** + * Test if the octree intersect with the given ray and if yes, then add its content to resulting array + * @param ray defines the ray to test with + * @returns array of intersected objects + */ + intersectsRay(ray) { + this._selectionContent.reset(); + for (let index = 0; index < this.blocks.length; index++) { + const block = this.blocks[index]; + block.intersectsRay(ray, this._selectionContent); + } + this._selectionContent.concatWithNoDuplicate(this.dynamicContent); + return this._selectionContent; + } +} +/** + * Adds a mesh into the octree block if it intersects the block + * @param entry defines the mesh to try to add to the block + * @param block defines the block where the mesh should be added + */ +Octree.CreationFuncForMeshes = (entry, block) => { + const boundingInfo = entry.getBoundingInfo(); + if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) { + block.entries.push(entry); + } +}; +/** + * Adds a submesh into the octree block if it intersects the block + * @param entry defines the submesh to try to add to the block + * @param block defines the block where the submesh should be added + */ +Octree.CreationFuncForSubMeshes = (entry, block) => { + const boundingInfo = entry.getBoundingInfo(); + if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) { + block.entries.push(entry); + } +}; + +Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity = 64, maxDepth = 2) { + let component = this._getComponent(SceneComponentConstants.NAME_OCTREE); + if (!component) { + component = new OctreeSceneComponent(this); + this._addComponent(component); + } + if (!this._selectionOctree) { + this._selectionOctree = new Octree(Octree.CreationFuncForMeshes, maxCapacity, maxDepth); + } + const worldExtends = this.getWorldExtends(); + // Update octree + this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes); + return this._selectionOctree; +}; +Object.defineProperty(Scene.prototype, "selectionOctree", { + get: function () { + return this._selectionOctree; + }, + enumerable: true, + configurable: true, +}); +/** + * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations. + * Please note that you must have a decent number of submeshes to get performance improvements when using an octree + * @param maxCapacity defines the maximum size of each block (64 by default) + * @param maxDepth defines the maximum depth to use (no more than 2 levels by default) + * @returns the new octree + * @see https://www.babylonjs-playground.com/#NA4OQ#12 + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees + */ +AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity = 64, maxDepth = 2) { + const scene = this.getScene(); + let component = scene._getComponent(SceneComponentConstants.NAME_OCTREE); + if (!component) { + component = new OctreeSceneComponent(scene); + scene._addComponent(component); + } + if (!this._submeshesOctree) { + this._submeshesOctree = new Octree(Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth); + } + this.computeWorldMatrix(true); + const boundingInfo = this.getBoundingInfo(); + // Update octree + const bbox = boundingInfo.boundingBox; + this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes); + return this._submeshesOctree; +}; +/** + * Defines the octree scene component responsible to manage any octrees + * in a given scene. + */ +class OctreeSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name help to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_OCTREE; + /** + * Indicates if the meshes have been checked to make sure they are isEnabled() + */ + this.checksIsEnabled = true; + this._tempRay = new Ray(Vector3.Zero(), new Vector3(1, 1, 1)); + scene = scene || EngineStore.LastCreatedScene; + if (!scene) { + return; + } + this.scene = scene; + this.scene.getActiveMeshCandidates = () => this.getActiveMeshCandidates(); + this.scene.getActiveSubMeshCandidates = (mesh) => this.getActiveSubMeshCandidates(mesh); + this.scene.getCollidingSubMeshCandidates = (mesh, collider) => this.getCollidingSubMeshCandidates(mesh, collider); + this.scene.getIntersectingSubMeshCandidates = (mesh, localRay) => this.getIntersectingSubMeshCandidates(mesh, localRay); + } + /** + * Registers the component in a given scene + */ + register() { + this.scene.onMeshRemovedObservable.add((mesh) => { + const sceneOctree = this.scene.selectionOctree; + if (sceneOctree !== undefined && sceneOctree !== null) { + const index = sceneOctree.dynamicContent.indexOf(mesh); + if (index !== -1) { + sceneOctree.dynamicContent.splice(index, 1); + } + } + }); + this.scene.onMeshImportedObservable.add((mesh) => { + const sceneOctree = this.scene.selectionOctree; + if (sceneOctree !== undefined && sceneOctree !== null) { + sceneOctree.addMesh(mesh); + } + }); + } + /** + * Return the list of active meshes + * @returns the list of active meshes + */ + getActiveMeshCandidates() { + return this.scene._selectionOctree?.select(this.scene.frustumPlanes) || this.scene._getDefaultMeshCandidates(); + } + /** + * Return the list of active sub meshes + * @param mesh The mesh to get the candidates sub meshes from + * @returns the list of active sub meshes + */ + getActiveSubMeshCandidates(mesh) { + if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) { + const intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes); + return intersections; + } + return this.scene._getDefaultSubMeshCandidates(mesh); + } + /** + * Return the list of sub meshes intersecting with a given local ray + * @param mesh defines the mesh to find the submesh for + * @param localRay defines the ray in local space + * @returns the list of intersecting sub meshes + */ + getIntersectingSubMeshCandidates(mesh, localRay) { + if (mesh._submeshesOctree && mesh.useOctreeForPicking) { + Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay); + const intersections = mesh._submeshesOctree.intersectsRay(this._tempRay); + return intersections; + } + return this.scene._getDefaultSubMeshCandidates(mesh); + } + /** + * Return the list of sub meshes colliding with a collider + * @param mesh defines the mesh to find the submesh for + * @param collider defines the collider to evaluate the collision against + * @returns the list of colliding sub meshes + */ + getCollidingSubMeshCandidates(mesh, collider) { + if (mesh._submeshesOctree && mesh.useOctreeForCollisions) { + const radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z); + const intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius); + return intersections; + } + return this.scene._getDefaultSubMeshCandidates(mesh); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do here. + } + /** + * Disposes the component and the associated resources. + */ + dispose() { + // Nothing to do here. + } +} + +/** + * Creates the VertexData for a cylinder, cone or prism + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * height sets the height (y direction) of the cylinder, optional, default 2 + * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter + * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter + * * diameter sets the diameter of the top and bottom of the cone, optional default 1 + * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 + * * subdivisions` the number of rings along the cylinder height, optional, default 1 + * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1 + * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * * hasRings when true makes each subdivision independently treated as a face for faceUV and faceColors, optional, default false + * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the cylinder, cone or prism + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function CreateCylinderVertexData(options) { + const height = options.height || 2; + let diameterTop = options.diameterTop === 0 ? 0 : options.diameterTop || options.diameter || 1; + let diameterBottom = options.diameterBottom === 0 ? 0 : options.diameterBottom || options.diameter || 1; + diameterTop = diameterTop || 0.00001; // Prevent broken normals + diameterBottom = diameterBottom || 0.00001; // Prevent broken normals + const tessellation = (options.tessellation || 24) | 0; + const subdivisions = (options.subdivisions || 1) | 0; + const hasRings = options.hasRings ? true : false; + const enclose = options.enclose ? true : false; + const cap = options.cap === 0 ? 0 : options.cap || Mesh.CAP_ALL; + const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0; + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + const faceUV = options.faceUV || new Array(3); + const faceColors = options.faceColors; + // default face colors and UV if undefined + const quadNb = arc !== 1 && enclose ? 2 : 0; + const ringNb = hasRings ? subdivisions : 1; + const surfaceNb = 2 + (1 + quadNb) * ringNb; + let f; + for (f = 0; f < surfaceNb; f++) { + if (faceColors && faceColors[f] === undefined) { + faceColors[f] = new Color4(1, 1, 1, 1); + } + } + for (f = 0; f < surfaceNb; f++) { + if (faceUV && faceUV[f] === undefined) { + faceUV[f] = new Vector4(0, 0, 1, 1); + } + } + const indices = []; + const positions = []; + const normals = []; + const uvs = []; + const colors = []; + const angleStep = (Math.PI * 2 * arc) / tessellation; + let angle; + let h; + let radius; + const tan = (diameterBottom - diameterTop) / 2 / height; + const ringVertex = Vector3.Zero(); + const ringNormal = Vector3.Zero(); + const ringFirstVertex = Vector3.Zero(); + const ringFirstNormal = Vector3.Zero(); + const quadNormal = Vector3.Zero(); + const Y = Axis.Y; + // positions, normals, uvs + let i; + let j; + let r; + let ringIdx = 1; + let s = 1; // surface index + let cs = 0; + let v = 0; + for (i = 0; i <= subdivisions; i++) { + h = i / subdivisions; + radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2; + ringIdx = hasRings && i !== 0 && i !== subdivisions ? 2 : 1; + for (r = 0; r < ringIdx; r++) { + if (hasRings) { + s += r; + } + if (enclose) { + s += 2 * r; + } + for (j = 0; j <= tessellation; j++) { + angle = j * angleStep; + // position + ringVertex.x = Math.cos(-angle) * radius; + ringVertex.y = -height / 2 + h * height; + ringVertex.z = Math.sin(-angle) * radius; + // normal + if (diameterTop === 0 && i === subdivisions) { + // if no top cap, reuse former normals + ringNormal.x = normals[normals.length - (tessellation + 1) * 3]; + ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1]; + ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2]; + } + else { + ringNormal.x = ringVertex.x; + ringNormal.z = ringVertex.z; + ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan; + ringNormal.normalize(); + } + // keep first ring vertex values for enclose + if (j === 0) { + ringFirstVertex.copyFrom(ringVertex); + ringFirstNormal.copyFrom(ringNormal); + } + positions.push(ringVertex.x, ringVertex.y, ringVertex.z); + normals.push(ringNormal.x, ringNormal.y, ringNormal.z); + if (hasRings) { + v = cs !== s ? faceUV[s].y : faceUV[s].w; + } + else { + v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h; + } + uvs.push(faceUV[s].x + ((faceUV[s].z - faceUV[s].x) * j) / tessellation, v); + if (faceColors) { + colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a); + } + } + // if enclose, add four vertices and their dedicated normals + if (arc !== 1 && enclose) { + positions.push(ringVertex.x, ringVertex.y, ringVertex.z); + positions.push(0, ringVertex.y, 0); + positions.push(0, ringVertex.y, 0); + positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z); + Vector3.CrossToRef(Y, ringNormal, quadNormal); + quadNormal.normalize(); + normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z); + Vector3.CrossToRef(ringFirstNormal, Y, quadNormal); + quadNormal.normalize(); + normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z); + if (hasRings) { + v = cs !== s ? faceUV[s + 1].y : faceUV[s + 1].w; + } + else { + v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h; + } + uvs.push(faceUV[s + 1].x, v); + uvs.push(faceUV[s + 1].z, v); + if (hasRings) { + v = cs !== s ? faceUV[s + 2].y : faceUV[s + 2].w; + } + else { + v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h; + } + uvs.push(faceUV[s + 2].x, v); + uvs.push(faceUV[s + 2].z, v); + if (faceColors) { + colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a); + colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a); + colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a); + colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a); + } + } + if (cs !== s) { + cs = s; + } + } + } + // indices + const e = arc !== 1 && enclose ? tessellation + 4 : tessellation; // correction of number of iteration if enclose + i = 0; + for (s = 0; s < subdivisions; s++) { + let i0 = 0; + let i1 = 0; + let i2 = 0; + let i3 = 0; + for (j = 0; j < tessellation; j++) { + i0 = i * (e + 1) + j; + i1 = (i + 1) * (e + 1) + j; + i2 = i * (e + 1) + (j + 1); + i3 = (i + 1) * (e + 1) + (j + 1); + indices.push(i0, i1, i2); + indices.push(i3, i2, i1); + } + if (arc !== 1 && enclose) { + // if enclose, add two quads + indices.push(i0 + 2, i1 + 2, i2 + 2); + indices.push(i3 + 2, i2 + 2, i1 + 2); + indices.push(i0 + 4, i1 + 4, i2 + 4); + indices.push(i3 + 4, i2 + 4, i1 + 4); + } + i = hasRings ? i + 2 : i + 1; + } + // Caps + const createCylinderCap = (isTop) => { + const radius = isTop ? diameterTop / 2 : diameterBottom / 2; + if (radius === 0) { + return; + } + // Cap positions, normals & uvs + let angle; + let circleVector; + let i; + const u = isTop ? faceUV[surfaceNb - 1] : faceUV[0]; + let c = null; + if (faceColors) { + c = isTop ? faceColors[surfaceNb - 1] : faceColors[0]; + } + // cap center + const vbase = positions.length / 3; + const offset = isTop ? height / 2 : -height / 2; + const center = new Vector3(0, offset, 0); + positions.push(center.x, center.y, center.z); + normals.push(0, isTop ? 1 : -1, 0); + const v = u.y + (u.w - u.y) * 0.5; + uvs.push(u.x + (u.z - u.x) * 0.5, v); + if (c) { + colors.push(c.r, c.g, c.b, c.a); + } + const textureScale = new Vector2(0.5, 0.5); + for (i = 0; i <= tessellation; i++) { + angle = (Math.PI * 2 * i * arc) / tessellation; + const cos = Math.cos(-angle); + const sin = Math.sin(-angle); + circleVector = new Vector3(cos * radius, offset, sin * radius); + const textureCoordinate = new Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5); + positions.push(circleVector.x, circleVector.y, circleVector.z); + normals.push(0, isTop ? 1 : -1, 0); + const v = u.y + (u.w - u.y) * textureCoordinate.y; + uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, v); + if (c) { + colors.push(c.r, c.g, c.b, c.a); + } + } + // Cap indices + for (i = 0; i < tessellation; i++) { + if (!isTop) { + indices.push(vbase); + indices.push(vbase + (i + 1)); + indices.push(vbase + (i + 2)); + } + else { + indices.push(vbase); + indices.push(vbase + (i + 2)); + indices.push(vbase + (i + 1)); + } + } + }; + // add caps to geometry based on cap parameter + if (cap === Mesh.CAP_START || cap === Mesh.CAP_ALL) { + createCylinderCap(false); + } + if (cap === Mesh.CAP_END || cap === Mesh.CAP_ALL) { + createCylinderCap(true); + } + // Sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + if (faceColors) { + vertexData.colors = colors; + } + return vertexData; +} +/** + * Creates a cylinder or a cone mesh + * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). + * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). + * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. + * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. + * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). + * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces. + * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis. + * * The parameter `cap` sets the way the cylinder is capped. Possible values : BABYLON.Mesh.NO_CAP, BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL (default). + * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder. + * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements). + * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3 + * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7 + * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17 + * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface. + * * If `enclose` is false, a ring surface is one element. + * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces. + * * Example how to set colors and textures on a sliced cylinder : https://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379 + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the cylinder mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#cylinder-or-cone + */ +function CreateCylinder(name, options = {}, scene) { + const cylinder = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + cylinder._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreateCylinderVertexData(options); + vertexData.applyToMesh(cylinder, options.updatable); + return cylinder; +} +VertexData.CreateCylinder = CreateCylinderVertexData; +Mesh.CreateCylinder = (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) => { + if (scene === undefined || !(scene instanceof Scene)) { + if (scene !== undefined) { + sideOrientation = updatable || Mesh.DEFAULTSIDE; + updatable = scene; + } + scene = subdivisions; + subdivisions = 1; + } + const options = { + height, + diameterTop, + diameterBottom, + tessellation, + subdivisions, + sideOrientation, + updatable, + }; + return CreateCylinder(name, options, scene); +}; + +/** + * Renders a layer on top of an existing scene + */ +class UtilityLayerRenderer { + /** + * Gets the camera that is used to render the utility layer (when not set, this will be the last active camera) + * @param getRigParentIfPossible if the current active camera is a rig camera, should its parent camera be returned + * @returns the camera that is used when rendering the utility layer + */ + getRenderCamera(getRigParentIfPossible) { + if (this._renderCamera) { + return this._renderCamera; + } + else { + let activeCam; + if (this.originalScene.activeCameras && this.originalScene.activeCameras.length > 1) { + activeCam = this.originalScene.activeCameras[this.originalScene.activeCameras.length - 1]; + } + else { + activeCam = this.originalScene.activeCamera; + } + if (getRigParentIfPossible && activeCam && activeCam.isRigCamera) { + return activeCam.rigParent; + } + return activeCam; + } + } + /** + * Sets the camera that should be used when rendering the utility layer (If set to null the last active camera will be used) + * @param cam the camera that should be used when rendering the utility layer + */ + setRenderCamera(cam) { + this._renderCamera = cam; + } + /** + * @internal + * Light which used by gizmos to get light shading + */ + _getSharedGizmoLight() { + if (!this._sharedGizmoLight) { + this._sharedGizmoLight = new HemisphericLight("shared gizmo light", new Vector3(0, 1, 0), this.utilityLayerScene); + this._sharedGizmoLight.intensity = 2; + this._sharedGizmoLight.groundColor = Color3.Gray(); + } + return this._sharedGizmoLight; + } + /** + * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it) + */ + static get DefaultUtilityLayer() { + if (UtilityLayerRenderer._DefaultUtilityLayer == null) { + return UtilityLayerRenderer._CreateDefaultUtilityLayerFromScene(EngineStore.LastCreatedScene); + } + return UtilityLayerRenderer._DefaultUtilityLayer; + } + /** + * Creates an utility layer, and set it as a default utility layer + * @param scene associated scene + * @internal + */ + static _CreateDefaultUtilityLayerFromScene(scene) { + UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(scene); + UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(() => { + UtilityLayerRenderer._DefaultUtilityLayer = null; + }); + return UtilityLayerRenderer._DefaultUtilityLayer; + } + /** + * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it) + */ + static get DefaultKeepDepthUtilityLayer() { + if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) { + UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(EngineStore.LastCreatedScene); + UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false; + UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(() => { + UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null; + }); + } + return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer; + } + /** + * Instantiates a UtilityLayerRenderer + * @param originalScene the original scene that will be rendered on top of + * @param handleEvents boolean indicating if the utility layer should handle events + * @param manualRender boolean indicating if the utility layer should render manually. + */ + constructor( + /** the original scene that will be rendered on top of */ + originalScene, handleEvents = true, manualRender = false) { + this.originalScene = originalScene; + this.handleEvents = handleEvents; + this._pointerCaptures = {}; + this._lastPointerEvents = {}; + this._sharedGizmoLight = null; + this._renderCamera = null; + /** + * If the picking should be done on the utility layer prior to the actual scene (Default: true) + */ + this.pickUtilitySceneFirst = true; + /** + * If the utility layer should automatically be rendered on top of existing scene + */ + this.shouldRender = true; + /** + * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene + */ + this.onlyCheckPointerDownEvents = true; + /** + * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default) + */ + this.processAllEvents = false; + /** + * Set to false to disable picking + */ + this.pickingEnabled = true; + /** + * Observable raised when the pointer moves from the utility layer scene to the main scene + */ + this.onPointerOutObservable = new Observable(); + // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app + this.utilityLayerScene = new Scene(originalScene.getEngine(), { virtual: true }); + this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem; + this.utilityLayerScene._allowPostProcessClearColor = false; + // Deactivate post processes + this.utilityLayerScene.postProcessesEnabled = false; + // Detach controls on utility scene, events will be fired by logic below to handle picking priority + this.utilityLayerScene.detachControl(); + if (handleEvents) { + this._originalPointerObserver = originalScene.onPrePointerObservable.add((prePointerInfo) => { + if (!this.utilityLayerScene.activeCamera) { + return; + } + if (!this.pickingEnabled) { + return; + } + if (!this.processAllEvents) { + if (prePointerInfo.type !== PointerEventTypes.POINTERMOVE && + prePointerInfo.type !== PointerEventTypes.POINTERUP && + prePointerInfo.type !== PointerEventTypes.POINTERDOWN && + prePointerInfo.type !== PointerEventTypes.POINTERDOUBLETAP) { + return; + } + } + this.utilityLayerScene.pointerX = originalScene.pointerX; + this.utilityLayerScene.pointerY = originalScene.pointerY; + const pointerEvent = prePointerInfo.event; + if (originalScene.isPointerCaptured(pointerEvent.pointerId)) { + this._pointerCaptures[pointerEvent.pointerId] = false; + return; + } + const getNearPickDataForScene = (scene) => { + let scenePick = null; + if (prePointerInfo.nearInteractionPickingInfo) { + if (prePointerInfo.nearInteractionPickingInfo.pickedMesh.getScene() == scene) { + scenePick = prePointerInfo.nearInteractionPickingInfo; + } + else { + scenePick = new PickingInfo(); + } + } + else if (scene !== this.utilityLayerScene && prePointerInfo.originalPickingInfo) { + scenePick = prePointerInfo.originalPickingInfo; + } + else { + let previousActiveCamera = null; + // If a camera is set for rendering with this layer + // it will also be used for the ray computation + // To preserve back compat and because scene.pick always use activeCamera + // it's substituted temporarily and a new scenePick is forced. + // otherwise, the ray with previously active camera is always used. + // It's set back to previous activeCamera after operation. + if (this._renderCamera) { + previousActiveCamera = scene._activeCamera; + scene._activeCamera = this._renderCamera; + prePointerInfo.ray = null; + } + scenePick = prePointerInfo.ray ? scene.pickWithRay(prePointerInfo.ray) : scene.pick(originalScene.pointerX, originalScene.pointerY); + if (previousActiveCamera) { + scene._activeCamera = previousActiveCamera; + } + } + return scenePick; + }; + const utilityScenePick = getNearPickDataForScene(this.utilityLayerScene); + if (!prePointerInfo.ray && utilityScenePick) { + prePointerInfo.ray = utilityScenePick.ray; + } + if (prePointerInfo.originalPickingInfo?.aimTransform && utilityScenePick) { + utilityScenePick.aimTransform = prePointerInfo.originalPickingInfo.aimTransform; + utilityScenePick.gripTransform = prePointerInfo.originalPickingInfo.gripTransform; + } + // always fire the prepointer observable + this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo); + // allow every non pointer down event to flow to the utility layer + if (this.onlyCheckPointerDownEvents && prePointerInfo.type != PointerEventTypes.POINTERDOWN) { + if (!prePointerInfo.skipOnPointerObservable) { + this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick), prePointerInfo.type); + } + if (prePointerInfo.type === PointerEventTypes.POINTERUP && this._pointerCaptures[pointerEvent.pointerId]) { + this._pointerCaptures[pointerEvent.pointerId] = false; + } + return; + } + if (this.utilityLayerScene.autoClearDepthAndStencil || this.pickUtilitySceneFirst) { + // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene + if (utilityScenePick && utilityScenePick.hit) { + if (!prePointerInfo.skipOnPointerObservable) { + this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick), prePointerInfo.type); + } + prePointerInfo.skipOnPointerObservable = true; + } + } + else { + const originalScenePick = getNearPickDataForScene(originalScene); + const pointerEvent = prePointerInfo.event; + // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray + if (originalScenePick && utilityScenePick) { + // No pick in utility scene + if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) { + if (this.mainSceneTrackerPredicate && this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) { + // We touched an utility mesh present in the main scene + this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent); + prePointerInfo.skipOnPointerObservable = true; + } + else if (prePointerInfo.type === PointerEventTypes.POINTERDOWN) { + this._pointerCaptures[pointerEvent.pointerId] = true; + this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent); + } + else if (prePointerInfo.type === PointerEventTypes.POINTERMOVE || prePointerInfo.type === PointerEventTypes.POINTERUP) { + if (this._lastPointerEvents[pointerEvent.pointerId]) { + // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete + this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId); + delete this._lastPointerEvents[pointerEvent.pointerId]; + } + this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent); + } + } + else if (!this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) { + // We pick something in utility scene or the pick in utility is closer than the one in main scene + this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent); + // If a previous utility layer set this, do not unset this + if (!prePointerInfo.skipOnPointerObservable) { + prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0; + } + } + else if (!this._pointerCaptures[pointerEvent.pointerId] && utilityScenePick.distance >= originalScenePick.distance) { + // We have a pick in both scenes but main is closer than utility + // We touched an utility mesh present in the main scene + if (this.mainSceneTrackerPredicate && this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) { + this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent); + prePointerInfo.skipOnPointerObservable = true; + } + else { + if (prePointerInfo.type === PointerEventTypes.POINTERMOVE || prePointerInfo.type === PointerEventTypes.POINTERUP) { + if (this._lastPointerEvents[pointerEvent.pointerId]) { + // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete + this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId); + delete this._lastPointerEvents[pointerEvent.pointerId]; + } + } + this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent); + } + } + if (prePointerInfo.type === PointerEventTypes.POINTERUP && this._pointerCaptures[pointerEvent.pointerId]) { + this._pointerCaptures[pointerEvent.pointerId] = false; + } + } + } + }); + // As a newly added utility layer will be rendered over the screen last, it's pointer events should be processed first + if (this._originalPointerObserver) { + originalScene.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver); + } + } + // Render directly on top of existing scene without clearing + this.utilityLayerScene.autoClear = false; + if (!manualRender) { + this._afterRenderObserver = this.originalScene.onAfterRenderCameraObservable.add((camera) => { + // Only render when the render camera finishes rendering + if (this.shouldRender && camera == this.getRenderCamera()) { + this.render(); + } + }); + } + this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(() => { + this.dispose(); + }); + this._updateCamera(); + } + _notifyObservers(prePointerInfo, pickInfo, pointerEvent) { + if (!prePointerInfo.skipOnPointerObservable) { + this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo), prePointerInfo.type); + this._lastPointerEvents[pointerEvent.pointerId] = true; + } + } + /** + * Renders the utility layers scene on top of the original scene + */ + render() { + this._updateCamera(); + if (this.utilityLayerScene.activeCamera) { + // Set the camera's scene to utility layers scene + const oldScene = this.utilityLayerScene.activeCamera.getScene(); + const camera = this.utilityLayerScene.activeCamera; + camera._scene = this.utilityLayerScene; + if (camera.leftCamera) { + camera.leftCamera._scene = this.utilityLayerScene; + } + if (camera.rightCamera) { + camera.rightCamera._scene = this.utilityLayerScene; + } + this.utilityLayerScene.render(false); + // Reset camera's scene back to original + camera._scene = oldScene; + if (camera.leftCamera) { + camera.leftCamera._scene = oldScene; + } + if (camera.rightCamera) { + camera.rightCamera._scene = oldScene; + } + } + } + /** + * Disposes of the renderer + */ + dispose() { + this.onPointerOutObservable.clear(); + if (this._afterRenderObserver) { + this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver); + } + if (this._sceneDisposeObserver) { + this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver); + } + if (this._originalPointerObserver) { + this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver); + } + this.utilityLayerScene.dispose(); + } + _updateCamera() { + this.utilityLayerScene.cameraToUseForPointers = this.getRenderCamera(); + this.utilityLayerScene.activeCamera = this.getRenderCamera(); + } +} +/** @internal */ +UtilityLayerRenderer._DefaultUtilityLayer = null; +/** @internal */ +UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null; + +/** + * Anchor options where the Gizmo can be positioned in relation to its anchored node + */ +var GizmoAnchorPoint; +(function (GizmoAnchorPoint) { + /** The origin of the attached node */ + GizmoAnchorPoint[GizmoAnchorPoint["Origin"] = 0] = "Origin"; + /** The pivot point of the attached node*/ + GizmoAnchorPoint[GizmoAnchorPoint["Pivot"] = 1] = "Pivot"; +})(GizmoAnchorPoint || (GizmoAnchorPoint = {})); +/** + * Coordinates mode: Local or World. Defines how axis is aligned: either on world axis or transform local axis + */ +var GizmoCoordinatesMode; +(function (GizmoCoordinatesMode) { + GizmoCoordinatesMode[GizmoCoordinatesMode["World"] = 0] = "World"; + GizmoCoordinatesMode[GizmoCoordinatesMode["Local"] = 1] = "Local"; +})(GizmoCoordinatesMode || (GizmoCoordinatesMode = {})); + +Object.defineProperty(Scene.prototype, "debugLayer", { + get: function () { + if (!this._debugLayer) { + this._debugLayer = new DebugLayer(this); + } + return this._debugLayer; + }, + enumerable: true, + configurable: true, +}); +/** + * Enum of inspector action tab + */ +var DebugLayerTab; +(function (DebugLayerTab) { + /** + * Properties tag (default) + */ + DebugLayerTab[DebugLayerTab["Properties"] = 0] = "Properties"; + /** + * Debug tab + */ + DebugLayerTab[DebugLayerTab["Debug"] = 1] = "Debug"; + /** + * Statistics tab + */ + DebugLayerTab[DebugLayerTab["Statistics"] = 2] = "Statistics"; + /** + * Tools tab + */ + DebugLayerTab[DebugLayerTab["Tools"] = 3] = "Tools"; + /** + * Settings tab + */ + DebugLayerTab[DebugLayerTab["Settings"] = 4] = "Settings"; +})(DebugLayerTab || (DebugLayerTab = {})); +/** + * The debug layer (aka Inspector) is the go to tool in order to better understand + * what is happening in your scene + * @see https://doc.babylonjs.com/toolsAndResources/inspector + */ +class DebugLayer { + /** + * Observable triggered when a property is changed through the inspector. + */ + get onPropertyChangedObservable() { + if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) { + return this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable; + } + if (!this._onPropertyChangedObservable) { + this._onPropertyChangedObservable = new Observable(); + } + return this._onPropertyChangedObservable; + } + /** + * Observable triggered when the selection is changed through the inspector. + */ + get onSelectionChangedObservable() { + if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) { + return this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable; + } + if (!this._onSelectionChangedObservable) { + this._onSelectionChangedObservable = new Observable(); + } + return this._onSelectionChangedObservable; + } + /** + * Instantiates a new debug layer. + * The debug layer (aka Inspector) is the go to tool in order to better understand + * what is happening in your scene + * @see https://doc.babylonjs.com/toolsAndResources/inspector + * @param scene Defines the scene to inspect + */ + constructor(scene) { + // eslint-disable-next-line @typescript-eslint/naming-convention + this.BJSINSPECTOR = this._getGlobalInspector(); + this._scene = scene || EngineStore.LastCreatedScene; + if (!this._scene) { + return; + } + this._scene.onDisposeObservable.add(() => { + // Debug layer + if (this._scene._debugLayer) { + this._scene._debugLayer.hide(); + } + }); + } + /** + * Creates the inspector window. + * @param config + */ + _createInspector(config) { + if (this.isVisible()) { + return; + } + if (this._onPropertyChangedObservable) { + for (const observer of this._onPropertyChangedObservable.observers) { + this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(observer); + } + this._onPropertyChangedObservable.clear(); + this._onPropertyChangedObservable = undefined; + } + if (this._onSelectionChangedObservable) { + for (const observer of this._onSelectionChangedObservable.observers) { + this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(observer); + } + this._onSelectionChangedObservable.clear(); + this._onSelectionChangedObservable = undefined; + } + const userOptions = { + ...DebugLayer.Config, + ...config, + }; + this.BJSINSPECTOR = this.BJSINSPECTOR || this._getGlobalInspector(); + this.BJSINSPECTOR.Inspector.Show(this._scene, userOptions); + } + /** + * Select a specific entity in the scene explorer and highlight a specific block in that entity property grid + * @param entity defines the entity to select + * @param lineContainerTitles defines the specific blocks to highlight (could be a string or an array of strings) + */ + select(entity, lineContainerTitles) { + if (this.BJSINSPECTOR) { + if (lineContainerTitles) { + if (Object.prototype.toString.call(lineContainerTitles) == "[object String]") { + this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(lineContainerTitles); + } + else { + this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(lineContainerTitles); + } + } + this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(entity); + } + } + /** + * Get the inspector from bundle or global + * @returns the inspector instance if found otherwise, null + */ + _getGlobalInspector() { + // UMD Global name detection from Webpack Bundle UMD Name. + if (typeof INSPECTOR !== "undefined") { + return INSPECTOR; + } + // In case of module let s check the global emitted from the Inspector entry point. + if (typeof BABYLON !== "undefined" && typeof BABYLON.Inspector !== "undefined") { + return BABYLON; + } + return undefined; + } + /** + * Get if the inspector is visible or not. + * @returns true if visible otherwise, false + */ + isVisible() { + return this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector.IsVisible; + } + /** + * Hide the inspector and close its window. + */ + hide() { + if (this.BJSINSPECTOR) { + this.BJSINSPECTOR.Inspector.Hide(); + } + } + /** + * Get the number of opened panes in the inspector + */ + get openedPanes() { + if (this.BJSINSPECTOR) { + return this.BJSINSPECTOR.Inspector._OpenedPane; + } + return 0; + } + /** + * Update the scene in the inspector + */ + setAsActiveScene() { + if (this.BJSINSPECTOR) { + this.BJSINSPECTOR.Inspector._SetNewScene(this._scene); + } + } + popupSceneExplorer() { + if (this.BJSINSPECTOR) { + this.BJSINSPECTOR.Inspector.PopupSceneExplorer(); + } + } + popupInspector() { + if (this.BJSINSPECTOR) { + this.BJSINSPECTOR.Inspector.PopupInspector(); + } + } + popupEmbed() { + if (this.BJSINSPECTOR) { + this.BJSINSPECTOR.Inspector.PopupEmbed(); + } + } + /** + * Launch the debugLayer. + * @param config Define the configuration of the inspector + * @returns a promise fulfilled when the debug layer is visible + */ + show(config) { + return new Promise((resolve) => { + if (typeof this.BJSINSPECTOR == "undefined") { + const inspectorUrl = config && config.inspectorURL ? config.inspectorURL : DebugLayer.InspectorURL; + // Load inspector and add it to the DOM + Tools.LoadBabylonScript(inspectorUrl, () => { + this._createInspector(config); + resolve(this); + }); + } + else { + // Otherwise creates the inspector + this._createInspector(config); + resolve(this); + } + }); + } +} +/** + * Define the url to get the inspector script from. + * By default it uses the babylonjs CDN. + * @ignoreNaming + */ +DebugLayer.InspectorURL = `${Tools._DefaultCdnUrl}/v${AbstractEngine.Version}/inspector/babylon.inspector.bundle.js`; +/** + * The default configuration of the inspector + */ +DebugLayer.Config = { + overlay: false, + showExplorer: true, + showInspector: true, + embedMode: false, + handleResize: true, + enablePopup: true, +}; + +/** + * Creates the VertexData for a box + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * size sets the width, height and depth of the box to the value of size, optional default 1 + * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size + * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size + * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size + * * faceUV an array of 6 Vector4 elements used to set different images to each box side + * * faceColors an array of 6 Color3 elements used to set different colors to each box side + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box + */ +function CreateBoxVertexData(options) { + const nbFaces = 6; + let indices = [0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23]; + const normals = [ + 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 1, 0, 0, + 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, + ]; + const uvs = []; + let positions = []; + const width = options.width || options.size || 1; + const height = options.height || options.size || 1; + const depth = options.depth || options.size || 1; + const wrap = options.wrap || false; + let topBaseAt = options.topBaseAt === void 0 ? 1 : options.topBaseAt; + let bottomBaseAt = options.bottomBaseAt === void 0 ? 0 : options.bottomBaseAt; + topBaseAt = (topBaseAt + 4) % 4; // places values as 0 to 3 + bottomBaseAt = (bottomBaseAt + 4) % 4; // places values as 0 to 3 + const topOrder = [2, 0, 3, 1]; + const bottomOrder = [2, 0, 1, 3]; + let topIndex = topOrder[topBaseAt]; + let bottomIndex = bottomOrder[bottomBaseAt]; + let basePositions = [ + 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, + 1, 1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, + ]; + if (wrap) { + indices = [2, 3, 0, 2, 0, 1, 4, 5, 6, 4, 6, 7, 9, 10, 11, 9, 11, 8, 12, 14, 15, 12, 13, 14]; + basePositions = [ + -1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1, + ]; + let topFaceBase = [ + [1, 1, 1], + [-1, 1, 1], + [-1, 1, -1], + [1, 1, -1], + ]; + let bottomFaceBase = [ + [-1, -1, 1], + [1, -1, 1], + [1, -1, -1], + [-1, -1, -1], + ]; + const topFaceOrder = [17, 18, 19, 16]; + const bottomFaceOrder = [22, 23, 20, 21]; + while (topIndex > 0) { + topFaceBase.unshift(topFaceBase.pop()); + topFaceOrder.unshift(topFaceOrder.pop()); + topIndex--; + } + while (bottomIndex > 0) { + bottomFaceBase.unshift(bottomFaceBase.pop()); + bottomFaceOrder.unshift(bottomFaceOrder.pop()); + bottomIndex--; + } + topFaceBase = topFaceBase.flat(); + bottomFaceBase = bottomFaceBase.flat(); + basePositions = basePositions.concat(topFaceBase).concat(bottomFaceBase); + indices.push(topFaceOrder[0], topFaceOrder[2], topFaceOrder[3], topFaceOrder[0], topFaceOrder[1], topFaceOrder[2]); + indices.push(bottomFaceOrder[0], bottomFaceOrder[2], bottomFaceOrder[3], bottomFaceOrder[0], bottomFaceOrder[1], bottomFaceOrder[2]); + } + const scaleArray = [width / 2, height / 2, depth / 2]; + positions = basePositions.reduce((accumulator, currentValue, currentIndex) => accumulator.concat(currentValue * scaleArray[currentIndex % 3]), []); + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + const faceUV = options.faceUV || new Array(6); + const faceColors = options.faceColors; + const colors = []; + // default face colors and UV if undefined + for (let f = 0; f < 6; f++) { + if (faceUV[f] === undefined) { + faceUV[f] = new Vector4(0, 0, 1, 1); + } + if (faceColors && faceColors[f] === undefined) { + faceColors[f] = new Color4(1, 1, 1, 1); + } + } + // Create each face in turn. + for (let index = 0; index < nbFaces; index++) { + uvs.push(faceUV[index].z, faceUV[index].w); + uvs.push(faceUV[index].x, faceUV[index].w); + uvs.push(faceUV[index].x, faceUV[index].y); + uvs.push(faceUV[index].z, faceUV[index].y); + if (faceColors) { + for (let c = 0; c < 4; c++) { + colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a); + } + } + } + // sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + if (faceColors) { + const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors; + vertexData.colors = totalColors; + } + return vertexData; +} +/** + * Creates the VertexData for a segmented box + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * size sets the width, height and depth of the box to the value of size, optional default 1 + * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size + * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size + * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size + * * segments sets the number of segments on the all axis (1 by default) + * * widthSegments sets the number of segments on the x axis (1 by default) + * * heightSegments sets the number of segments on the y axis (1 by default) + * * depthSegments sets the number of segments on the z axis (1 by default) + * @returns the VertexData of the box + */ +function CreateSegmentedBoxVertexData(options) { + const width = options.width || options.size || 1; + const height = options.height || options.size || 1; + const depth = options.depth || options.size || 1; + const widthSegments = (options.widthSegments || options.segments || 1) | 0; + const heightSegments = (options.heightSegments || options.segments || 1) | 0; + const depthSegments = (options.depthSegments || options.segments || 1) | 0; + const rotationMatrix = new Matrix(); + const translationMatrix = new Matrix(); + const transformMatrix = new Matrix(); + const bottomPlane = CreateGroundVertexData({ width: width, height: depth, subdivisionsX: widthSegments, subdivisionsY: depthSegments }); + Matrix.TranslationToRef(0, -height / 2, 0, translationMatrix); + Matrix.RotationZToRef(Math.PI, rotationMatrix); + rotationMatrix.multiplyToRef(translationMatrix, transformMatrix); + bottomPlane.transform(transformMatrix); + const topPlane = CreateGroundVertexData({ width: width, height: depth, subdivisionsX: widthSegments, subdivisionsY: depthSegments }); + Matrix.TranslationToRef(0, height / 2, 0, transformMatrix); + topPlane.transform(transformMatrix); + const negXPlane = CreateGroundVertexData({ width: height, height: depth, subdivisionsX: heightSegments, subdivisionsY: depthSegments }); + Matrix.TranslationToRef(-width / 2, 0, 0, translationMatrix); + Matrix.RotationZToRef(Math.PI / 2, rotationMatrix); + rotationMatrix.multiplyToRef(translationMatrix, transformMatrix); + negXPlane.transform(transformMatrix); + const posXPlane = CreateGroundVertexData({ width: height, height: depth, subdivisionsX: heightSegments, subdivisionsY: depthSegments }); + Matrix.TranslationToRef(width / 2, 0, 0, translationMatrix); + Matrix.RotationZToRef(-Math.PI / 2, rotationMatrix); + rotationMatrix.multiplyToRef(translationMatrix, transformMatrix); + posXPlane.transform(transformMatrix); + const negZPlane = CreateGroundVertexData({ width: width, height: height, subdivisionsX: widthSegments, subdivisionsY: heightSegments }); + Matrix.TranslationToRef(0, 0, -depth / 2, translationMatrix); + Matrix.RotationXToRef(-Math.PI / 2, rotationMatrix); + rotationMatrix.multiplyToRef(translationMatrix, transformMatrix); + negZPlane.transform(transformMatrix); + const posZPlane = CreateGroundVertexData({ width: width, height: height, subdivisionsX: widthSegments, subdivisionsY: heightSegments }); + Matrix.TranslationToRef(0, 0, depth / 2, translationMatrix); + Matrix.RotationXToRef(Math.PI / 2, rotationMatrix); + rotationMatrix.multiplyToRef(translationMatrix, transformMatrix); + posZPlane.transform(transformMatrix); + // Result + bottomPlane.merge([topPlane, posXPlane, negXPlane, negZPlane, posZPlane], true); + return bottomPlane; +} +/** + * Creates a box mesh + * * The parameter `size` sets the size (float) of each box side (default 1) + * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`) + * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements) + * * Please read this tutorial : https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#box + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the box mesh + */ +function CreateBox(name, options = {}, scene = null) { + const box = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + box._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreateBoxVertexData(options); + vertexData.applyToMesh(box, options.updatable); + return box; +} +// Side effects +VertexData.CreateBox = CreateBoxVertexData; +Mesh.CreateBox = (name, size, scene = null, updatable, sideOrientation) => { + const options = { + size, + sideOrientation, + updatable, + }; + return CreateBox(name, options, scene); +}; + +/** + * Creates the VertexData for an ellipsoid, defaults to a sphere + * @param options an object used to set the following optional parameters for the box, required but can be empty + * * segments sets the number of horizontal strips optional, default 32 + * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1 + * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter + * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter + * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter + * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1 + * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the ellipsoid + */ +function CreateSphereVertexData(options) { + const segments = (options.segments || 32) | 0; + const diameterX = options.diameterX || options.diameter || 1; + const diameterY = options.diameterY || options.diameter || 1; + const diameterZ = options.diameterZ || options.diameter || 1; + const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0; + const slice = options.slice && options.slice <= 0 ? 1.0 : options.slice || 1.0; + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + const dedupTopBottomIndices = !!options.dedupTopBottomIndices; + const radius = new Vector3(diameterX / 2, diameterY / 2, diameterZ / 2); + const totalZRotationSteps = 2 + segments; + const totalYRotationSteps = 2 * totalZRotationSteps; + const indices = []; + const positions = []; + const normals = []; + const uvs = []; + for (let zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) { + const normalizedZ = zRotationStep / totalZRotationSteps; + const angleZ = normalizedZ * Math.PI * slice; + for (let yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) { + const normalizedY = yRotationStep / totalYRotationSteps; + const angleY = normalizedY * Math.PI * 2 * arc; + const rotationZ = Matrix.RotationZ(-angleZ); + const rotationY = Matrix.RotationY(angleY); + const afterRotZ = Vector3.TransformCoordinates(Vector3.Up(), rotationZ); + const complete = Vector3.TransformCoordinates(afterRotZ, rotationY); + const vertex = complete.multiply(radius); + const normal = complete.divide(radius).normalize(); + positions.push(vertex.x, vertex.y, vertex.z); + normals.push(normal.x, normal.y, normal.z); + uvs.push(normalizedY, normalizedZ); + } + if (zRotationStep > 0) { + const verticesCount = positions.length / 3; + for (let firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); firstIndex + totalYRotationSteps + 2 < verticesCount; firstIndex++) { + if (dedupTopBottomIndices) { + if (zRotationStep > 1) { + indices.push(firstIndex); + indices.push(firstIndex + 1); + indices.push(firstIndex + totalYRotationSteps + 1); + } + if (zRotationStep < totalZRotationSteps || slice < 1.0) { + indices.push(firstIndex + totalYRotationSteps + 1); + indices.push(firstIndex + 1); + indices.push(firstIndex + totalYRotationSteps + 2); + } + } + else { + indices.push(firstIndex); + indices.push(firstIndex + 1); + indices.push(firstIndex + totalYRotationSteps + 1); + indices.push(firstIndex + totalYRotationSteps + 1); + indices.push(firstIndex + 1); + indices.push(firstIndex + totalYRotationSteps + 2); + } + } + } + } + // Sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + return vertexData; +} +/** + * Creates a sphere mesh + * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1) + * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value of `diameter`) + * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32) + * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio + * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude) + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the sphere mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#sphere + */ +function CreateSphere(name, options = {}, scene = null) { + const sphere = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + sphere._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreateSphereVertexData(options); + vertexData.applyToMesh(sphere, options.updatable); + return sphere; +} +VertexData.CreateSphere = CreateSphereVertexData; +Mesh.CreateSphere = (name, segments, diameter, scene, updatable, sideOrientation) => { + const options = { + segments: segments, + diameterX: diameter, + diameterY: diameter, + diameterZ: diameter, + sideOrientation: sideOrientation, + updatable: updatable, + }; + return CreateSphere(name, options, scene); +}; + +/** + * This is a holder class for the physics joint created by the physics plugin + * It holds a set of functions to control the underlying joint + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine + */ +class PhysicsJoint { + /** + * Initializes the physics joint + * @param type The type of the physics joint + * @param jointData The data for the physics joint + */ + constructor( + /** + * The type of the physics joint + */ + type, + /** + * The data for the physics joint + */ + jointData) { + this.type = type; + this.jointData = jointData; + jointData.nativeParams = jointData.nativeParams || {}; + } + /** + * Gets the physics joint + */ + get physicsJoint() { + return this._physicsJoint; + } + /** + * Sets the physics joint + */ + set physicsJoint(newJoint) { + this._physicsJoint = newJoint; + } + /** + * Sets the physics plugin + */ + set physicsPlugin(physicsPlugin) { + this._physicsPlugin = physicsPlugin; + } + /** + * Execute a function that is physics-plugin specific. + * @param {Function} func the function that will be executed. + * It accepts two parameters: the physics world and the physics joint + */ + executeNativeFunction(func) { + func(this._physicsPlugin.world, this._physicsJoint); + } +} +//TODO check if the native joints are the same +//Joint Types +/** + * Distance-Joint type + */ +PhysicsJoint.DistanceJoint = 0; +/** + * Hinge-Joint type + */ +PhysicsJoint.HingeJoint = 1; +/** + * Ball-and-Socket joint type + */ +PhysicsJoint.BallAndSocketJoint = 2; +/** + * Wheel-Joint type + */ +PhysicsJoint.WheelJoint = 3; +/** + * Slider-Joint type + */ +PhysicsJoint.SliderJoint = 4; +//OIMO +/** + * Prismatic-Joint type + */ +PhysicsJoint.PrismaticJoint = 5; +// +/** + * Universal-Joint type + * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions) + */ +PhysicsJoint.UniversalJoint = 6; +/** + * Hinge-Joint 2 type + */ +PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint; +//Cannon +/** + * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters + */ +PhysicsJoint.PointToPointJoint = 8; +//Cannon only at the moment +/** + * Spring-Joint type + */ +PhysicsJoint.SpringJoint = 9; +/** + * Lock-Joint type + */ +PhysicsJoint.LockJoint = 10; + +Mesh._PhysicsImpostorParser = function (scene, physicObject, jsonObject) { + return new PhysicsImpostor(physicObject, jsonObject.physicsImpostor, { + mass: jsonObject.physicsMass, + friction: jsonObject.physicsFriction, + restitution: jsonObject.physicsRestitution, + }, scene); +}; +/** + * Represents a physics imposter + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine + */ +class PhysicsImpostor { + /** + * Specifies if the physics imposter is disposed + */ + get isDisposed() { + return this._isDisposed; + } + /** + * Gets the mass of the physics imposter + */ + get mass() { + return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0; + } + set mass(value) { + this.setMass(value); + } + /** + * Gets the coefficient of friction + */ + get friction() { + return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0; + } + /** + * Sets the coefficient of friction + */ + set friction(value) { + if (!this._physicsEngine) { + return; + } + this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value); + } + /** + * Gets the coefficient of restitution + */ + get restitution() { + return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0; + } + /** + * Sets the coefficient of restitution + */ + set restitution(value) { + if (!this._physicsEngine) { + return; + } + this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value); + } + /** + * Gets the pressure of a soft body; only supported by the AmmoJSPlugin + */ + get pressure() { + if (!this._physicsEngine) { + return 0; + } + const plugin = this._physicsEngine.getPhysicsPlugin(); + if (!plugin.setBodyPressure) { + return 0; + } + return plugin.getBodyPressure(this); + } + /** + * Sets the pressure of a soft body; only supported by the AmmoJSPlugin + */ + set pressure(value) { + if (!this._physicsEngine) { + return; + } + const plugin = this._physicsEngine.getPhysicsPlugin(); + if (!plugin.setBodyPressure) { + return; + } + plugin.setBodyPressure(this, value); + } + /** + * Gets the stiffness of a soft body; only supported by the AmmoJSPlugin + */ + get stiffness() { + if (!this._physicsEngine) { + return 0; + } + const plugin = this._physicsEngine.getPhysicsPlugin(); + if (!plugin.getBodyStiffness) { + return 0; + } + return plugin.getBodyStiffness(this); + } + /** + * Sets the stiffness of a soft body; only supported by the AmmoJSPlugin + */ + set stiffness(value) { + if (!this._physicsEngine) { + return; + } + const plugin = this._physicsEngine.getPhysicsPlugin(); + if (!plugin.setBodyStiffness) { + return; + } + plugin.setBodyStiffness(this, value); + } + /** + * Gets the velocityIterations of a soft body; only supported by the AmmoJSPlugin + */ + get velocityIterations() { + if (!this._physicsEngine) { + return 0; + } + const plugin = this._physicsEngine.getPhysicsPlugin(); + if (!plugin.getBodyVelocityIterations) { + return 0; + } + return plugin.getBodyVelocityIterations(this); + } + /** + * Sets the velocityIterations of a soft body; only supported by the AmmoJSPlugin + */ + set velocityIterations(value) { + if (!this._physicsEngine) { + return; + } + const plugin = this._physicsEngine.getPhysicsPlugin(); + if (!plugin.setBodyVelocityIterations) { + return; + } + plugin.setBodyVelocityIterations(this, value); + } + /** + * Gets the positionIterations of a soft body; only supported by the AmmoJSPlugin + */ + get positionIterations() { + if (!this._physicsEngine) { + return 0; + } + const plugin = this._physicsEngine.getPhysicsPlugin(); + if (!plugin.getBodyPositionIterations) { + return 0; + } + return plugin.getBodyPositionIterations(this); + } + /** + * Sets the positionIterations of a soft body; only supported by the AmmoJSPlugin + */ + set positionIterations(value) { + if (!this._physicsEngine) { + return; + } + const plugin = this._physicsEngine.getPhysicsPlugin(); + if (!plugin.setBodyPositionIterations) { + return; + } + plugin.setBodyPositionIterations(this, value); + } + /** + * Initializes the physics imposter + * @param object The physics-enabled object used as the physics imposter + * @param type The type of the physics imposter. Types are available as static members of this class. + * @param _options The options for the physics imposter + * @param _scene The Babylon scene + */ + constructor( + /** + * The physics-enabled object used as the physics imposter + */ + object, + /** + * The type of the physics imposter + */ + type, _options = { mass: 0 }, _scene) { + this.object = object; + this.type = type; + this._options = _options; + this._scene = _scene; + /** @internal */ + this._pluginData = {}; + this._bodyUpdateRequired = false; + this._onBeforePhysicsStepCallbacks = new Array(); + this._onAfterPhysicsStepCallbacks = new Array(); + /** @internal */ + this._onPhysicsCollideCallbacks = []; + this._deltaPosition = Vector3.Zero(); + this._isDisposed = false; + /** + * @internal + */ + this.soft = false; + /** + * @internal + */ + this.segments = 0; + //temp variables for parent rotation calculations + //private _mats: Array = [new Matrix(), new Matrix()]; + this._tmpQuat = new Quaternion(); + this._tmpQuat2 = new Quaternion(); + /** + * this function is executed by the physics engine. + */ + this.beforeStep = () => { + if (!this._physicsEngine) { + return; + } + this.object.translate(this._deltaPosition, -1); + this._deltaRotationConjugated && + this.object.rotationQuaternion && + this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated, this.object.rotationQuaternion); + this.object.computeWorldMatrix(false); + if (this.object.parent && this.object.rotationQuaternion) { + this.getParentsRotation(); + this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this._tmpQuat); + } + else { + this._tmpQuat.copyFrom(this.object.rotationQuaternion || new Quaternion()); + } + if (!this._options.disableBidirectionalTransformation) { + this.object.rotationQuaternion && + this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this, /*bInfo.boundingBox.centerWorld*/ this.object.getAbsolutePosition(), this._tmpQuat); + } + this._onBeforePhysicsStepCallbacks.forEach((func) => { + func(this); + }); + }; + /** + * this function is executed by the physics engine + */ + this.afterStep = () => { + if (!this._physicsEngine) { + return; + } + this._onAfterPhysicsStepCallbacks.forEach((func) => { + func(this); + }); + this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this); + // object has now its world rotation. needs to be converted to local. + if (this.object.parent && this.object.rotationQuaternion) { + this.getParentsRotation(); + this._tmpQuat.conjugateInPlace(); + this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this.object.rotationQuaternion); + } + // take the position set and make it the absolute position of this object. + this.object.setAbsolutePosition(this.object.position); + if (this._deltaRotation) { + this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotation, this.object.rotationQuaternion); + this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation, PhysicsImpostor._TmpVecs[0]); + this.object.translate(PhysicsImpostor._TmpVecs[0], 1); + } + else { + this.object.translate(this._deltaPosition, 1); + } + this.object.computeWorldMatrix(true); + }; + /** + * Legacy collision detection event support + */ + this.onCollideEvent = null; + /** + * define an onCollide function to call when this impostor collides against a different body + * @param e collide event data + */ + this.onCollide = (e) => { + if (!this._onPhysicsCollideCallbacks.length && !this.onCollideEvent) { + return; + } + if (!this._physicsEngine) { + return; + } + const otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body); + if (otherImpostor) { + // Legacy collision detection event support + if (this.onCollideEvent) { + this.onCollideEvent(this, otherImpostor); + } + this._onPhysicsCollideCallbacks + .filter((obj) => { + return obj.otherImpostors.indexOf(otherImpostor) !== -1; + }) + .forEach((obj) => { + obj.callback(this, otherImpostor, e.point, e.distance, e.impulse, e.normal); + }); + } + }; + //sanity check! + if (!this.object) { + Logger.Error("No object was provided. A physics object is obligatory"); + return; + } + if (this.object.parent && _options.mass !== 0) { + Logger.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."); + } + // Legacy support for old syntax. + if (!this._scene && object.getScene) { + this._scene = object.getScene(); + } + if (!this._scene) { + return; + } + if (this.type > 100) { + this.soft = true; + } + this._physicsEngine = this._scene.getPhysicsEngine(); + if (!this._physicsEngine) { + Logger.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."); + } + else { + //set the object's quaternion, if not set + if (!this.object.rotationQuaternion) { + if (this.object.rotation) { + this.object.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z); + } + else { + this.object.rotationQuaternion = new Quaternion(); + } + } + //default options params + this._options.mass = _options.mass === void 0 ? 0 : _options.mass; + this._options.friction = _options.friction === void 0 ? 0.2 : _options.friction; + this._options.restitution = _options.restitution === void 0 ? 0.2 : _options.restitution; + if (this.soft) { + //softbody mass must be above 0; + this._options.mass = this._options.mass > 0 ? this._options.mass : 1; + this._options.pressure = _options.pressure === void 0 ? 200 : _options.pressure; + this._options.stiffness = _options.stiffness === void 0 ? 1 : _options.stiffness; + this._options.velocityIterations = _options.velocityIterations === void 0 ? 20 : _options.velocityIterations; + this._options.positionIterations = _options.positionIterations === void 0 ? 20 : _options.positionIterations; + this._options.fixedPoints = _options.fixedPoints === void 0 ? 0 : _options.fixedPoints; + this._options.margin = _options.margin === void 0 ? 0 : _options.margin; + this._options.damping = _options.damping === void 0 ? 0 : _options.damping; + this._options.path = _options.path === void 0 ? null : _options.path; + this._options.shape = _options.shape === void 0 ? null : _options.shape; + } + this._joints = []; + //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that. + if (!this.object.parent || this._options.ignoreParent) { + this._init(); + } + else if (this.object.parent.physicsImpostor) { + Logger.Warn("You must affect impostors to children before affecting impostor to parent."); + } + } + } + /** + * This function will completely initialize this impostor. + * It will create a new body - but only if this mesh has no parent. + * If it has, this impostor will not be used other than to define the impostor + * of the child mesh. + * @internal + */ + _init() { + if (!this._physicsEngine) { + return; + } + this._physicsEngine.removeImpostor(this); + this.physicsBody = null; + this._parent = this._parent || this._getPhysicsParent(); + if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) { + this._physicsEngine.addImpostor(this); + } + } + _getPhysicsParent() { + if (this.object.parent instanceof AbstractMesh) { + const parentMesh = this.object.parent; + return parentMesh.physicsImpostor; + } + return null; + } + /** + * Should a new body be generated. + * @returns boolean specifying if body initialization is required + */ + isBodyInitRequired() { + return this._bodyUpdateRequired || (!this._physicsBody && (!this._parent || !!this._options.ignoreParent)); + } + /** + * Sets the updated scaling + */ + setScalingUpdated() { + this.forceUpdate(); + } + /** + * Force a regeneration of this or the parent's impostor's body. + * Use with caution - This will remove all previously-instantiated joints. + */ + forceUpdate() { + this._init(); + if (this.parent && !this._options.ignoreParent) { + this.parent.forceUpdate(); + } + } + /*public get mesh(): AbstractMesh { + return this._mesh; + }*/ + /** + * Gets the body that holds this impostor. Either its own, or its parent. + */ + get physicsBody() { + return this._parent && !this._options.ignoreParent ? this._parent.physicsBody : this._physicsBody; + } + /** + * Get the parent of the physics imposter + * @returns Physics imposter or null + */ + get parent() { + return !this._options.ignoreParent && this._parent ? this._parent : null; + } + /** + * Sets the parent of the physics imposter + */ + set parent(value) { + this._parent = value; + } + /** + * Set the physics body. Used mainly by the physics engine/plugin + */ + set physicsBody(physicsBody) { + if (this._physicsBody && this._physicsEngine) { + this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this); + } + this._physicsBody = physicsBody; + this.resetUpdateFlags(); + } + /** + * Resets the update flags + */ + resetUpdateFlags() { + this._bodyUpdateRequired = false; + } + /** + * Gets the object extents + * @returns the object extents + */ + getObjectExtents() { + if (this.object.getBoundingInfo) { + const q = this.object.rotationQuaternion; + const scaling = this.object.scaling.clone(); + //reset rotation + this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION; + //calculate the world matrix with no rotation + const worldMatrix = this.object.computeWorldMatrix && this.object.computeWorldMatrix(true); + if (worldMatrix) { + worldMatrix.decompose(scaling, undefined, undefined); + } + const boundingInfo = this.object.getBoundingInfo(); + // get the global scaling of the object + const size = boundingInfo.boundingBox.extendSize.scale(2).multiplyInPlace(scaling); + size.x = Math.abs(size.x); + size.y = Math.abs(size.y); + size.z = Math.abs(size.z); + //bring back the rotation + this.object.rotationQuaternion = q; + //calculate the world matrix with the new rotation + this.object.computeWorldMatrix && this.object.computeWorldMatrix(true); + return size; + } + else { + return PhysicsImpostor.DEFAULT_OBJECT_SIZE; + } + } + /** + * Gets the object center + * @returns The object center + */ + getObjectCenter() { + if (this.object.getBoundingInfo) { + const boundingInfo = this.object.getBoundingInfo(); + return boundingInfo.boundingBox.centerWorld; + } + else { + return this.object.position; + } + } + /** + * Get a specific parameter from the options parameters + * @param paramName The object parameter name + * @returns The object parameter + */ + getParam(paramName) { + return this._options[paramName]; + } + /** + * Sets a specific parameter in the options given to the physics plugin + * @param paramName The parameter name + * @param value The value of the parameter + */ + setParam(paramName, value) { + this._options[paramName] = value; + this._bodyUpdateRequired = true; + } + /** + * Specifically change the body's mass. Won't recreate the physics body object + * @param mass The mass of the physics imposter + */ + setMass(mass) { + if (this.getParam("mass") !== mass) { + this.setParam("mass", mass); + } + if (this._physicsEngine) { + this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass); + } + } + /** + * Gets the linear velocity + * @returns linear velocity or null + */ + getLinearVelocity() { + return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : Vector3.Zero(); + } + /** + * Sets the linear velocity + * @param velocity linear velocity or null + */ + setLinearVelocity(velocity) { + if (this._physicsEngine) { + this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity); + } + } + /** + * Gets the angular velocity + * @returns angular velocity or null + */ + getAngularVelocity() { + return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : Vector3.Zero(); + } + /** + * Sets the angular velocity + * @param velocity The velocity or null + */ + setAngularVelocity(velocity) { + if (this._physicsEngine) { + this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity); + } + } + /** + * Execute a function with the physics plugin native code + * Provide a function the will have two variables - the world object and the physics body object + * @param func The function to execute with the physics plugin native code + */ + executeNativeFunction(func) { + if (this._physicsEngine) { + func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody); + } + } + /** + * Register a function that will be executed before the physics world is stepping forward + * @param func The function to execute before the physics world is stepped forward + */ + registerBeforePhysicsStep(func) { + this._onBeforePhysicsStepCallbacks.push(func); + } + /** + * Unregister a function that will be executed before the physics world is stepping forward + * @param func The function to execute before the physics world is stepped forward + */ + unregisterBeforePhysicsStep(func) { + const index = this._onBeforePhysicsStepCallbacks.indexOf(func); + if (index > -1) { + this._onBeforePhysicsStepCallbacks.splice(index, 1); + } + else { + Logger.Warn("Function to remove was not found"); + } + } + /** + * Register a function that will be executed after the physics step + * @param func The function to execute after physics step + */ + registerAfterPhysicsStep(func) { + this._onAfterPhysicsStepCallbacks.push(func); + } + /** + * Unregisters a function that will be executed after the physics step + * @param func The function to execute after physics step + */ + unregisterAfterPhysicsStep(func) { + const index = this._onAfterPhysicsStepCallbacks.indexOf(func); + if (index > -1) { + this._onAfterPhysicsStepCallbacks.splice(index, 1); + } + else { + Logger.Warn("Function to remove was not found"); + } + } + /** + * register a function that will be executed when this impostor collides against a different body + * @param collideAgainst Physics imposter, or array of physics imposters to collide against + * @param func Callback that is executed on collision + */ + registerOnPhysicsCollide(collideAgainst, func) { + const collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst]; + this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList }); + } + /** + * Unregisters the physics imposter's collision callback + * @param collideAgainst The physics object to collide against + * @param func Callback to execute on collision + */ + unregisterOnPhysicsCollide(collideAgainst, func) { + const collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst]; + let index = -1; + const found = this._onPhysicsCollideCallbacks.some((cbDef, idx) => { + if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) { + // chcek the arrays match + const sameList = cbDef.otherImpostors.every((impostor) => { + return collidedAgainstList.indexOf(impostor) > -1; + }); + if (sameList) { + index = idx; + } + return sameList; + } + return false; + }); + if (found) { + this._onPhysicsCollideCallbacks.splice(index, 1); + } + else { + Logger.Warn("Function to remove was not found"); + } + } + /** + * Get the parent rotation + * @returns The parent rotation + */ + getParentsRotation() { + let parent = this.object.parent; + this._tmpQuat.copyFromFloats(0, 0, 0, 1); + while (parent) { + if (parent.rotationQuaternion) { + this._tmpQuat2.copyFrom(parent.rotationQuaternion); + } + else { + Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2); + } + this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat); + parent = parent.parent; + } + return this._tmpQuat; + } + /** + * Apply a force + * @param force The force to apply + * @param contactPoint The contact point for the force + * @returns The physics imposter + */ + applyForce(force, contactPoint) { + if (this._physicsEngine) { + this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint); + } + return this; + } + /** + * Apply an impulse + * @param force The impulse force + * @param contactPoint The contact point for the impulse force + * @returns The physics imposter + */ + applyImpulse(force, contactPoint) { + if (this._physicsEngine) { + this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint); + } + return this; + } + /** + * A help function to create a joint + * @param otherImpostor A physics imposter used to create a joint + * @param jointType The type of joint + * @param jointData The data for the joint + * @returns The physics imposter + */ + createJoint(otherImpostor, jointType, jointData) { + const joint = new PhysicsJoint(jointType, jointData); + this.addJoint(otherImpostor, joint); + return this; + } + /** + * Add a joint to this impostor with a different impostor + * @param otherImpostor A physics imposter used to add a joint + * @param joint The joint to add + * @returns The physics imposter + */ + addJoint(otherImpostor, joint) { + this._joints.push({ + otherImpostor: otherImpostor, + joint: joint, + }); + if (this._physicsEngine) { + this._physicsEngine.addJoint(this, otherImpostor, joint); + } + return this; + } + /** + * Add an anchor to a cloth impostor + * @param otherImpostor rigid impostor to anchor to + * @param width ratio across width from 0 to 1 + * @param height ratio up height from 0 to 1 + * @param influence the elasticity between cloth impostor and anchor from 0, very stretchy to 1, little stretch + * @param noCollisionBetweenLinkedBodies when true collisions between cloth impostor and anchor are ignored; default false + * @returns impostor the soft imposter + */ + addAnchor(otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies) { + if (!this._physicsEngine) { + return this; + } + const plugin = this._physicsEngine.getPhysicsPlugin(); + if (!plugin.appendAnchor) { + return this; + } + if (this._physicsEngine) { + plugin.appendAnchor(this, otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies); + } + return this; + } + /** + * Add a hook to a rope impostor + * @param otherImpostor rigid impostor to anchor to + * @param length ratio across rope from 0 to 1 + * @param influence the elasticity between rope impostor and anchor from 0, very stretchy to 1, little stretch + * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false + * @returns impostor the rope imposter + */ + addHook(otherImpostor, length, influence, noCollisionBetweenLinkedBodies) { + if (!this._physicsEngine) { + return this; + } + const plugin = this._physicsEngine.getPhysicsPlugin(); + if (!plugin.appendAnchor) { + return this; + } + if (this._physicsEngine) { + plugin.appendHook(this, otherImpostor, length, influence, noCollisionBetweenLinkedBodies); + } + return this; + } + /** + * Will keep this body still, in a sleep mode. + * @returns the physics imposter + */ + sleep() { + if (this._physicsEngine) { + this._physicsEngine.getPhysicsPlugin().sleepBody(this); + } + return this; + } + /** + * Wake the body up. + * @returns The physics imposter + */ + wakeUp() { + if (this._physicsEngine) { + this._physicsEngine.getPhysicsPlugin().wakeUpBody(this); + } + return this; + } + /** + * Clones the physics imposter + * @param newObject The physics imposter clones to this physics-enabled object + * @returns A nullable physics imposter + */ + clone(newObject) { + if (!newObject) { + return null; + } + return new PhysicsImpostor(newObject, this.type, this._options, this._scene); + } + /** + * Disposes the physics imposter + */ + dispose( /*disposeChildren: boolean = true*/) { + //no dispose if no physics engine is available. + if (!this._physicsEngine) { + return; + } + this._joints.forEach((j) => { + if (this._physicsEngine) { + this._physicsEngine.removeJoint(this, j.otherImpostor, j.joint); + } + }); + //dispose the physics body + this._physicsEngine.removeImpostor(this); + if (this.parent) { + this.parent.forceUpdate(); + } + this._isDisposed = true; + } + /** + * Sets the delta position + * @param position The delta position amount + */ + setDeltaPosition(position) { + this._deltaPosition.copyFrom(position); + } + /** + * Sets the delta rotation + * @param rotation The delta rotation amount + */ + setDeltaRotation(rotation) { + if (!this._deltaRotation) { + this._deltaRotation = new Quaternion(); + } + this._deltaRotation.copyFrom(rotation); + this._deltaRotationConjugated = this._deltaRotation.conjugate(); + } + /** + * Gets the box size of the physics imposter and stores the result in the input parameter + * @param result Stores the box size + * @returns The physics imposter + */ + getBoxSizeToRef(result) { + if (this._physicsEngine) { + this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result); + } + return this; + } + /** + * Gets the radius of the physics imposter + * @returns Radius of the physics imposter + */ + getRadius() { + return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0; + } + /** + * Sync a bone with this impostor + * @param bone The bone to sync to the impostor. + * @param boneMesh The mesh that the bone is influencing. + * @param jointPivot The pivot of the joint / bone in local space. + * @param distToJoint Optional distance from the impostor to the joint. + * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. + */ + syncBoneWithImpostor(bone, boneMesh, jointPivot, distToJoint, adjustRotation) { + const tempVec = PhysicsImpostor._TmpVecs[0]; + const mesh = this.object; + if (mesh.rotationQuaternion) { + if (adjustRotation) { + const tempQuat = PhysicsImpostor._TmpQuat; + mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat); + bone.setRotationQuaternion(tempQuat, 1 /* Space.WORLD */, boneMesh); + } + else { + bone.setRotationQuaternion(mesh.rotationQuaternion, 1 /* Space.WORLD */, boneMesh); + } + } + tempVec.x = 0; + tempVec.y = 0; + tempVec.z = 0; + if (jointPivot) { + tempVec.x = jointPivot.x; + tempVec.y = jointPivot.y; + tempVec.z = jointPivot.z; + bone.getDirectionToRef(tempVec, boneMesh, tempVec); + if (distToJoint === undefined || distToJoint === null) { + distToJoint = jointPivot.length(); + } + tempVec.x *= distToJoint; + tempVec.y *= distToJoint; + tempVec.z *= distToJoint; + } + if (bone.getParent()) { + tempVec.addInPlace(mesh.getAbsolutePosition()); + bone.setAbsolutePosition(tempVec, boneMesh); + } + else { + boneMesh.setAbsolutePosition(mesh.getAbsolutePosition()); + boneMesh.position.x -= tempVec.x; + boneMesh.position.y -= tempVec.y; + boneMesh.position.z -= tempVec.z; + } + } + /** + * Sync impostor to a bone + * @param bone The bone that the impostor will be synced to. + * @param boneMesh The mesh that the bone is influencing. + * @param jointPivot The pivot of the joint / bone in local space. + * @param distToJoint Optional distance from the impostor to the joint. + * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. + * @param boneAxis Optional vector3 axis the bone is aligned with + */ + syncImpostorWithBone(bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) { + const mesh = this.object; + if (mesh.rotationQuaternion) { + if (adjustRotation) { + const tempQuat = PhysicsImpostor._TmpQuat; + bone.getRotationQuaternionToRef(1 /* Space.WORLD */, boneMesh, tempQuat); + tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion); + } + else { + bone.getRotationQuaternionToRef(1 /* Space.WORLD */, boneMesh, mesh.rotationQuaternion); + } + } + const pos = PhysicsImpostor._TmpVecs[0]; + const boneDir = PhysicsImpostor._TmpVecs[1]; + if (!boneAxis) { + boneAxis = PhysicsImpostor._TmpVecs[2]; + boneAxis.x = 0; + boneAxis.y = 1; + boneAxis.z = 0; + } + bone.getDirectionToRef(boneAxis, boneMesh, boneDir); + bone.getAbsolutePositionToRef(boneMesh, pos); + if ((distToJoint === undefined || distToJoint === null) && jointPivot) { + distToJoint = jointPivot.length(); + } + if (distToJoint !== undefined && distToJoint !== null) { + pos.x += boneDir.x * distToJoint; + pos.y += boneDir.y * distToJoint; + pos.z += boneDir.z * distToJoint; + } + mesh.setAbsolutePosition(pos); + } +} +/** + * The default object size of the imposter + */ +PhysicsImpostor.DEFAULT_OBJECT_SIZE = new Vector3(1, 1, 1); +/** + * The identity quaternion of the imposter + */ +PhysicsImpostor.IDENTITY_QUATERNION = Quaternion.Identity(); +PhysicsImpostor._TmpVecs = BuildArray(3, Vector3.Zero); +PhysicsImpostor._TmpQuat = Quaternion.Identity(); +//Impostor types +/** + * No-Imposter type + */ +PhysicsImpostor.NoImpostor = 0; +/** + * Sphere-Imposter type + */ +PhysicsImpostor.SphereImpostor = 1; +/** + * Box-Imposter type + */ +PhysicsImpostor.BoxImpostor = 2; +/** + * Plane-Imposter type + */ +PhysicsImpostor.PlaneImpostor = 3; +/** + * Mesh-imposter type (Only available to objects with vertices data) + */ +PhysicsImpostor.MeshImpostor = 4; +/** + * Capsule-Impostor type (Ammo.js plugin only) + */ +PhysicsImpostor.CapsuleImpostor = 6; +/** + * Cylinder-Imposter type + */ +PhysicsImpostor.CylinderImpostor = 7; +/** + * Particle-Imposter type + */ +PhysicsImpostor.ParticleImpostor = 8; +/** + * Heightmap-Imposter type + */ +PhysicsImpostor.HeightmapImpostor = 9; +/** + * ConvexHull-Impostor type (Ammo.js plugin only) + */ +PhysicsImpostor.ConvexHullImpostor = 10; +/** + * Custom-Imposter type (Ammo.js plugin only) + */ +PhysicsImpostor.CustomImpostor = 100; +/** + * Rope-Imposter type + */ +PhysicsImpostor.RopeImpostor = 101; +/** + * Cloth-Imposter type + */ +PhysicsImpostor.ClothImpostor = 102; +/** + * Softbody-Imposter type + */ +PhysicsImpostor.SoftbodyImpostor = 103; + +/** + * Scripts based off of https://github.com/maximeq/three-js-capsule-geometry/blob/master/src/CapsuleBufferGeometry.js + * @param options the constructors options used to shape the mesh. + * @returns the capsule VertexData + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/capsule + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function CreateCapsuleVertexData(options = { + subdivisions: 2, + tessellation: 16, + height: 1, + radius: 0.25, + capSubdivisions: 6, +}) { + const subdivisions = Math.max(options.subdivisions ? options.subdivisions : 2, 1) | 0; + const tessellation = Math.max(options.tessellation ? options.tessellation : 16, 3) | 0; + const height = Math.max(options.height ? options.height : 1, 0); + const radius = Math.max(options.radius ? options.radius : 0.25, 0); + const capDetail = Math.max(options.capSubdivisions ? options.capSubdivisions : 6, 1) | 0; + const radialSegments = tessellation; + const heightSegments = subdivisions; + const radiusTop = Math.max(options.radiusTop ? options.radiusTop : radius, 0); + const radiusBottom = Math.max(options.radiusBottom ? options.radiusBottom : radius, 0); + const heightMinusCaps = height - (radiusTop + radiusBottom); + const thetaStart = 0.0; + const thetaLength = 2.0 * Math.PI; + const capsTopSegments = Math.max(options.topCapSubdivisions ? options.topCapSubdivisions : capDetail, 1); + const capsBottomSegments = Math.max(options.bottomCapSubdivisions ? options.bottomCapSubdivisions : capDetail, 1); + const alpha = Math.acos((radiusBottom - radiusTop) / height); + let indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let index = 0; + const indexArray = [], halfHeight = heightMinusCaps * 0.5; + const pi2 = Math.PI * 0.5; + let x, y; + const normal = Vector3.Zero(); + const vertex = Vector3.Zero(); + const cosAlpha = Math.cos(alpha); + const sinAlpha = Math.sin(alpha); + const coneLength = new Vector2(radiusTop * sinAlpha, halfHeight + radiusTop * cosAlpha) + .subtract(new Vector2(radiusBottom * sinAlpha, -halfHeight + radiusBottom * cosAlpha)) + .length(); + // Total length for v texture coord + const vl = radiusTop * alpha + coneLength + radiusBottom * (pi2 - alpha); + let v = 0; + for (y = 0; y <= capsTopSegments; y++) { + const indexRow = []; + const a = pi2 - alpha * (y / capsTopSegments); + v += (radiusTop * alpha) / capsTopSegments; + const cosA = Math.cos(a); + const sinA = Math.sin(a); + // calculate the radius of the current row + const _radius = cosA * radiusTop; + for (x = 0; x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + // vertex + vertex.x = _radius * sinTheta; + vertex.y = halfHeight + sinA * radiusTop; + vertex.z = _radius * cosTheta; + vertices.push(vertex.x, vertex.y, vertex.z); + // normal + normal.set(cosA * sinTheta, sinA, cosA * cosTheta); + normals.push(normal.x, normal.y, normal.z); + // uv + uvs.push(u, 1 - v / vl); + // save index of vertex in respective row + indexRow.push(index); + // increase index + index++; + } + // now save vertices of the row in our index array + indexArray.push(indexRow); + } + const coneHeight = height - radiusTop - radiusBottom + cosAlpha * radiusTop - cosAlpha * radiusBottom; + const slope = (sinAlpha * (radiusBottom - radiusTop)) / coneHeight; + for (y = 1; y <= heightSegments; y++) { + const indexRow = []; + v += coneLength / heightSegments; + // calculate the radius of the current row + const _radius = sinAlpha * ((y * (radiusBottom - radiusTop)) / heightSegments + radiusTop); + for (x = 0; x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + // vertex + vertex.x = _radius * sinTheta; + vertex.y = halfHeight + cosAlpha * radiusTop - (y * coneHeight) / heightSegments; + vertex.z = _radius * cosTheta; + vertices.push(vertex.x, vertex.y, vertex.z); + // normal + normal.set(sinTheta, slope, cosTheta).normalize(); + normals.push(normal.x, normal.y, normal.z); + // uv + uvs.push(u, 1 - v / vl); + // save index of vertex in respective row + indexRow.push(index); + // increase index + index++; + } + // now save vertices of the row in our index array + indexArray.push(indexRow); + } + for (y = 1; y <= capsBottomSegments; y++) { + const indexRow = []; + const a = pi2 - alpha - (Math.PI - alpha) * (y / capsBottomSegments); + v += (radiusBottom * alpha) / capsBottomSegments; + const cosA = Math.cos(a); + const sinA = Math.sin(a); + // calculate the radius of the current row + const _radius = cosA * radiusBottom; + for (x = 0; x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + // vertex + vertex.x = _radius * sinTheta; + vertex.y = -halfHeight + sinA * radiusBottom; + vertex.z = _radius * cosTheta; + vertices.push(vertex.x, vertex.y, vertex.z); + // normal + normal.set(cosA * sinTheta, sinA, cosA * cosTheta); + normals.push(normal.x, normal.y, normal.z); + // uv + uvs.push(u, 1 - v / vl); + // save index of vertex in respective row + indexRow.push(index); + // increase index + index++; + } + // now save vertices of the row in our index array + indexArray.push(indexRow); + } + // generate indices + for (x = 0; x < radialSegments; x++) { + for (y = 0; y < capsTopSegments + heightSegments + capsBottomSegments; y++) { + // we use the index array to access the correct indices + const i1 = indexArray[y][x]; + const i2 = indexArray[y + 1][x]; + const i3 = indexArray[y + 1][x + 1]; + const i4 = indexArray[y][x + 1]; + // face one + indices.push(i1); + indices.push(i2); + indices.push(i4); + // face two + indices.push(i2); + indices.push(i3); + indices.push(i4); + } + } + indices = indices.reverse(); + if (options.orientation && !options.orientation.equals(Vector3.Up())) { + const m = new Matrix(); + options.orientation + .clone() + .scale(Math.PI * 0.5) + .cross(Vector3.Up()) + .toQuaternion() + .toRotationMatrix(m); + const v = Vector3.Zero(); + for (let i = 0; i < vertices.length; i += 3) { + v.set(vertices[i], vertices[i + 1], vertices[i + 2]); + Vector3.TransformCoordinatesToRef(v.clone(), m, v); + vertices[i] = v.x; + vertices[i + 1] = v.y; + vertices[i + 2] = v.z; + } + } + const vDat = new VertexData(); + vDat.positions = vertices; + vDat.normals = normals; + vDat.uvs = uvs; + vDat.indices = indices; + return vDat; +} +/** + * Creates a capsule or a pill mesh + * @param name defines the name of the mesh + * @param options The constructors options. + * @param scene The scene the mesh is scoped to. + * @returns Capsule Mesh + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function CreateCapsule(name, options = { + orientation: Vector3.Up(), + subdivisions: 2, + tessellation: 16, + height: 1, + radius: 0.25, + capSubdivisions: 6, + updatable: false, +}, scene = null) { + const capsule = new Mesh(name, scene); + const vertexData = CreateCapsuleVertexData(options); + vertexData.applyToMesh(capsule, options.updatable); + return capsule; +} +/** + * Creates a capsule or a pill mesh + * @param name defines the name of the mesh. + * @param options the constructors options used to shape the mesh. + * @param scene defines the scene the mesh is scoped to. + * @returns the capsule mesh + * @see https://doc.babylonjs.com/how_to/capsule_shape + */ +Mesh.CreateCapsule = (name, options, scene) => { + return CreateCapsule(name, options, scene); +}; +VertexData.CreateCapsule = CreateCapsuleVertexData; + +/** + * Creates the VertexData for a Ribbon + * @param options an object used to set the following optional parameters for the ribbon, required but can be empty + * * pathArray array of paths, each of which an array of successive Vector3 + * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false + * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false + * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false + * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional + * * colors a linear array, of length 4 * number of vertices, of custom color values, optional + * @returns the VertexData of the ribbon + */ +function CreateRibbonVertexData(options) { + let pathArray = options.pathArray; + const closeArray = options.closeArray || false; + const closePath = options.closePath || false; + const invertUV = options.invertUV || false; + const defaultOffset = Math.floor(pathArray[0].length / 2); + let offset = options.offset || defaultOffset; + offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + const customUV = options.uvs; + const customColors = options.colors; + const positions = []; + const indices = []; + const normals = []; + const uvs = []; + const us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id + const vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutive paths from pathArray + const uTotalDistance = []; // uTotalDistance[p] : total distance of path p + const vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray + let minlg; // minimal length among all paths from pathArray + const lg = []; // array of path lengths : nb of vertex per path + const idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number + let p; // path iterator + let i; // point iterator + let j; // point iterator + // if single path in pathArray + if (pathArray.length < 2) { + const ar1 = []; + const ar2 = []; + for (i = 0; i < pathArray[0].length - offset; i++) { + ar1.push(pathArray[0][i]); + ar2.push(pathArray[0][i + offset]); + } + pathArray = [ar1, ar2]; + } + // positions and horizontal distances (u) + let idc = 0; + const closePathCorr = closePath ? 1 : 0; // the final index will be +1 if closePath + const closeArrayCorr = closeArray ? 1 : 0; + let path; + let l; + minlg = pathArray[0].length; + let vectlg; + let dist; + for (p = 0; p < pathArray.length + closeArrayCorr; p++) { + uTotalDistance[p] = 0; + us[p] = [0]; + path = p === pathArray.length ? pathArray[0] : pathArray[p]; + l = path.length; + minlg = minlg < l ? minlg : l; + j = 0; + while (j < l) { + positions.push(path[j].x, path[j].y, path[j].z); + if (j > 0) { + vectlg = path[j].subtract(path[j - 1]).length(); + dist = vectlg + uTotalDistance[p]; + us[p].push(dist); + uTotalDistance[p] = dist; + } + j++; + } + if (closePath) { + // an extra hidden vertex is added in the "positions" array + j--; + positions.push(path[0].x, path[0].y, path[0].z); + vectlg = path[j].subtract(path[0]).length(); + dist = vectlg + uTotalDistance[p]; + us[p].push(dist); + uTotalDistance[p] = dist; + } + lg[p] = l + closePathCorr; + idx[p] = idc; + idc += l + closePathCorr; + } + // vertical distances (v) + let path1; + let path2; + let vertex1 = null; + let vertex2 = null; + for (i = 0; i < minlg + closePathCorr; i++) { + vTotalDistance[i] = 0; + vs[i] = [0]; + for (p = 0; p < pathArray.length - 1 + closeArrayCorr; p++) { + path1 = pathArray[p]; + path2 = p === pathArray.length - 1 ? pathArray[0] : pathArray[p + 1]; + if (i === minlg) { + // closePath + vertex1 = path1[0]; + vertex2 = path2[0]; + } + else { + vertex1 = path1[i]; + vertex2 = path2[i]; + } + vectlg = vertex2.subtract(vertex1).length(); + dist = vectlg + vTotalDistance[i]; + vs[i].push(dist); + vTotalDistance[i] = dist; + } + } + // uvs + let u; + let v; + if (customUV) { + for (p = 0; p < customUV.length; p++) { + uvs.push(customUV[p].x, customUV[p].y); + } + } + else { + for (p = 0; p < pathArray.length + closeArrayCorr; p++) { + for (i = 0; i < minlg + closePathCorr; i++) { + u = uTotalDistance[p] != 0.0 ? us[p][i] / uTotalDistance[p] : 0.0; + v = vTotalDistance[i] != 0.0 ? vs[i][p] / vTotalDistance[i] : 0.0; + if (invertUV) { + uvs.push(v, u); + } + else { + uvs.push(u, v); + } + } + } + } + // indices + p = 0; // path index + let pi = 0; // positions array index + let l1 = lg[p] - 1; // path1 length + let l2 = lg[p + 1] - 1; // path2 length + let min = l1 < l2 ? l1 : l2; // current path stop index + let shft = idx[1] - idx[0]; // shift + const path1nb = lg.length - 1; // number of path1 to iterate on + while (pi <= min && p < path1nb) { + // stay under min and don't go over next to last path + // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise + indices.push(pi, pi + shft, pi + 1); + indices.push(pi + shft + 1, pi + 1, pi + shft); + pi += 1; + if (pi === min) { + // if end of one of two consecutive paths reached, go to next existing path + p++; + shft = idx[p + 1] - idx[p]; + l1 = lg[p] - 1; + l2 = lg[p + 1] - 1; + pi = idx[p]; + min = l1 < l2 ? l1 + pi : l2 + pi; + } + } + // normals + VertexData.ComputeNormals(positions, indices, normals); + if (closePath) { + // update both the first and last vertex normals to their average value + let indexFirst = 0; + let indexLast = 0; + for (p = 0; p < pathArray.length; p++) { + indexFirst = idx[p] * 3; + if (p + 1 < pathArray.length) { + indexLast = (idx[p + 1] - 1) * 3; + } + else { + indexLast = normals.length - 3; + } + normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5; + normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5; + normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5; + const l = Math.sqrt(normals[indexFirst] * normals[indexFirst] + normals[indexFirst + 1] * normals[indexFirst + 1] + normals[indexFirst + 2] * normals[indexFirst + 2]); + normals[indexFirst] /= l; + normals[indexFirst + 1] /= l; + normals[indexFirst + 2] /= l; + normals[indexLast] = normals[indexFirst]; + normals[indexLast + 1] = normals[indexFirst + 1]; + normals[indexLast + 2] = normals[indexFirst + 2]; + } + } + if (closeArray) { + let indexFirst = idx[0] * 3; + let indexLast = idx[pathArray.length] * 3; + for (i = 0; i < minlg + closePathCorr; i++) { + normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5; + normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5; + normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5; + const l = Math.sqrt(normals[indexFirst] * normals[indexFirst] + normals[indexFirst + 1] * normals[indexFirst + 1] + normals[indexFirst + 2] * normals[indexFirst + 2]); + normals[indexFirst] /= l; + normals[indexFirst + 1] /= l; + normals[indexFirst + 2] /= l; + normals[indexLast] = normals[indexFirst]; + normals[indexLast + 1] = normals[indexFirst + 1]; + normals[indexLast + 2] = normals[indexFirst + 2]; + indexFirst += 3; + indexLast += 3; + } + } + // sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + // Colors + let colors = null; + if (customColors) { + colors = new Float32Array(customColors.length * 4); + for (let c = 0; c < customColors.length; c++) { + colors[c * 4] = customColors[c].r; + colors[c * 4 + 1] = customColors[c].g; + colors[c * 4 + 2] = customColors[c].b; + colors[c * 4 + 3] = customColors[c].a; + } + } + // Result + const vertexData = new VertexData(); + const positions32 = new Float32Array(positions); + const normals32 = new Float32Array(normals); + const uvs32 = new Float32Array(uvs); + vertexData.indices = indices; + vertexData.positions = positions32; + vertexData.normals = normals32; + vertexData.uvs = uvs32; + if (colors) { + vertexData.set(colors, VertexBuffer.ColorKind); + } + if (closePath) { + vertexData._idx = idx; + } + return vertexData; +} +/** + * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters + * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry + * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array + * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array + * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path + * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11 + * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#ribbon + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones + * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values + * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry + * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the ribbon mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/ribbon_extra + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param + */ +function CreateRibbon(name, options, scene = null) { + const pathArray = options.pathArray; + const closeArray = options.closeArray; + const closePath = options.closePath; + const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + const instance = options.instance; + const updatable = options.updatable; + if (instance) { + // existing ribbon instance update + // positionFunction : ribbon case + // only pathArray and sideOrientation parameters are taken into account for positions update + const minimum = TmpVectors.Vector3[0].setAll(Number.MAX_VALUE); + const maximum = TmpVectors.Vector3[1].setAll(-Number.MAX_VALUE); + const positionFunction = (positions) => { + let minlg = pathArray[0].length; + const mesh = instance; + let i = 0; + const ns = mesh._originalBuilderSideOrientation === Mesh.DOUBLESIDE ? 2 : 1; + for (let si = 1; si <= ns; ++si) { + for (let p = 0; p < pathArray.length; ++p) { + const path = pathArray[p]; + const l = path.length; + minlg = minlg < l ? minlg : l; + for (let j = 0; j < minlg; ++j) { + const pathPoint = path[j]; + positions[i] = pathPoint.x; + positions[i + 1] = pathPoint.y; + positions[i + 2] = pathPoint.z; + minimum.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z); + maximum.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z); + i += 3; + } + if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) { + const pathPoint = path[0]; + positions[i] = pathPoint.x; + positions[i + 1] = pathPoint.y; + positions[i + 2] = pathPoint.z; + i += 3; + } + } + } + }; + const positions = instance.getVerticesData(VertexBuffer.PositionKind); + positionFunction(positions); + if (instance.hasBoundingInfo) { + instance.getBoundingInfo().reConstruct(minimum, maximum, instance._worldMatrix); + } + else { + instance.buildBoundingInfo(minimum, maximum, instance._worldMatrix); + } + instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false); + if (options.colors) { + const colors = instance.getVerticesData(VertexBuffer.ColorKind); + for (let c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) { + const color = options.colors[c]; + colors[colorIndex] = color.r; + colors[colorIndex + 1] = color.g; + colors[colorIndex + 2] = color.b; + colors[colorIndex + 3] = color.a; + } + instance.updateVerticesData(VertexBuffer.ColorKind, colors, false, false); + } + if (options.uvs) { + const uvs = instance.getVerticesData(VertexBuffer.UVKind); + for (let i = 0; i < options.uvs.length; i++) { + uvs[i * 2] = options.uvs[i].x; + uvs[i * 2 + 1] = options.uvs[i].y; + } + instance.updateVerticesData(VertexBuffer.UVKind, uvs, false, false); + } + if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) { + const indices = instance.getIndices(); + const normals = instance.getVerticesData(VertexBuffer.NormalKind); + const params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null; + VertexData.ComputeNormals(positions, indices, normals, params); + if (instance._creationDataStorage && instance._creationDataStorage.closePath) { + let indexFirst = 0; + let indexLast = 0; + for (let p = 0; p < pathArray.length; p++) { + indexFirst = instance._creationDataStorage.idx[p] * 3; + if (p + 1 < pathArray.length) { + indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3; + } + else { + indexLast = normals.length - 3; + } + normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5; + normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5; + normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5; + normals[indexLast] = normals[indexFirst]; + normals[indexLast + 1] = normals[indexFirst + 1]; + normals[indexLast + 2] = normals[indexFirst + 2]; + } + } + if (!instance.areNormalsFrozen) { + instance.updateVerticesData(VertexBuffer.NormalKind, normals, false, false); + } + } + return instance; + } + else { + // new ribbon creation + const ribbon = new Mesh(name, scene); + ribbon._originalBuilderSideOrientation = sideOrientation; + ribbon._creationDataStorage = new _CreationDataStorage(); + const vertexData = CreateRibbonVertexData(options); + if (closePath) { + ribbon._creationDataStorage.idx = vertexData._idx; + } + ribbon._creationDataStorage.closePath = closePath; + ribbon._creationDataStorage.closeArray = closeArray; + vertexData.applyToMesh(ribbon, updatable); + return ribbon; + } +} +VertexData.CreateRibbon = CreateRibbonVertexData; +Mesh.CreateRibbon = (name, pathArray, closeArray = false, closePath, offset, scene, updatable = false, sideOrientation, instance) => { + return CreateRibbon(name, { + pathArray: pathArray, + closeArray: closeArray, + closePath: closePath, + offset: offset, + updatable: updatable, + sideOrientation: sideOrientation, + instance: instance, + }, scene); +}; + +/** + * Creates the VertexData of the Disc or regular Polygon + * @param options an object used to set the following optional parameters for the disc, required but can be empty + * * radius the radius of the disc, optional default 0.5 + * * tessellation the number of polygon sides, optional, default 64 + * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the box + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function CreateDiscVertexData(options) { + const positions = []; + const indices = []; + const normals = []; + const uvs = []; + const radius = options.radius || 0.5; + const tessellation = options.tessellation || 64; + const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0; + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + // positions and uvs + positions.push(0, 0, 0); // disc center first + uvs.push(0.5, 0.5); + const theta = Math.PI * 2 * arc; + const step = arc === 1 ? theta / tessellation : theta / (tessellation - 1); + let a = 0; + for (let t = 0; t < tessellation; t++) { + const x = Math.cos(a); + const y = Math.sin(a); + const u = (x + 1) / 2; + const v = (1 - y) / 2; + positions.push(radius * x, radius * y, 0); + uvs.push(u, v); + a += step; + } + if (arc === 1) { + positions.push(positions[3], positions[4], positions[5]); // close the circle + uvs.push(uvs[2], uvs[3]); + } + //indices + const vertexNb = positions.length / 3; + for (let i = 1; i < vertexNb - 1; i++) { + indices.push(i + 1, 0, i); + } + // result + VertexData.ComputeNormals(positions, indices, normals); + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + return vertexData; +} +/** + * Creates a plane polygonal mesh. By default, this is a disc + * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5) + * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc + * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the plane polygonal mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#disc-or-regular-polygon + */ +function CreateDisc(name, options = {}, scene = null) { + const disc = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + disc._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreateDiscVertexData(options); + vertexData.applyToMesh(disc, options.updatable); + return disc; +} +VertexData.CreateDisc = CreateDiscVertexData; +Mesh.CreateDisc = (name, radius, tessellation, scene = null, updatable, sideOrientation) => { + const options = { + radius, + tessellation, + sideOrientation, + updatable, + }; + return CreateDisc(name, options, scene); +}; + +/** + * Creates the VertexData for a tiled plane + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_plane + * @param options an object used to set the following optional parameters for the tiled plane, required but can be empty + * * pattern a limited pattern arrangement depending on the number + * * size of the box + * * width of the box, overwrites size + * * height of the box, overwrites size + * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1 + * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size + * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * alignHorizontal places whole tiles aligned to the center, left or right of a row + * * alignVertical places whole tiles aligned to the center, left or right of a column + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * @param options.pattern + * @param options.tileSize + * @param options.tileWidth + * @param options.tileHeight + * @param options.size + * @param options.width + * @param options.height + * @param options.alignHorizontal + * @param options.alignVertical + * @param options.sideOrientation + * @param options.frontUVs + * @param options.backUVs + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the tiled plane + */ +function CreateTiledPlaneVertexData(options) { + const flipTile = options.pattern || Mesh.NO_FLIP; + const tileWidth = options.tileWidth || options.tileSize || 1; + const tileHeight = options.tileHeight || options.tileSize || 1; + const alignH = options.alignHorizontal || 0; + const alignV = options.alignVertical || 0; + const width = options.width || options.size || 1; + const tilesX = Math.floor(width / tileWidth); + let offsetX = width - tilesX * tileWidth; + const height = options.height || options.size || 1; + const tilesY = Math.floor(height / tileHeight); + let offsetY = height - tilesY * tileHeight; + const halfWidth = (tileWidth * tilesX) / 2; + const halfHeight = (tileHeight * tilesY) / 2; + let adjustX = 0; + let adjustY = 0; + let startX = 0; + let startY = 0; + let endX = 0; + let endY = 0; + //Part Tiles + if (offsetX > 0 || offsetY > 0) { + startX = -halfWidth; + startY = -halfHeight; + endX = halfWidth; + endY = halfHeight; + switch (alignH) { + case Mesh.CENTER: + offsetX /= 2; + startX -= offsetX; + endX += offsetX; + break; + case Mesh.LEFT: + endX += offsetX; + adjustX = -offsetX / 2; + break; + case Mesh.RIGHT: + startX -= offsetX; + adjustX = offsetX / 2; + break; + } + switch (alignV) { + case Mesh.CENTER: + offsetY /= 2; + startY -= offsetY; + endY += offsetY; + break; + case Mesh.BOTTOM: + endY += offsetY; + adjustY = -offsetY / 2; + break; + case Mesh.TOP: + startY -= offsetY; + adjustY = offsetY / 2; + break; + } + } + const positions = []; + const normals = []; + const uvBase = []; + uvBase[0] = [0, 0, 1, 0, 1, 1, 0, 1]; + uvBase[1] = [0, 0, 1, 0, 1, 1, 0, 1]; + if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) { + uvBase[1] = [1, 1, 0, 1, 0, 0, 1, 0]; + } + if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) { + uvBase[1] = [1, 0, 0, 0, 0, 1, 1, 1]; + } + if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvBase[1] = [0, 1, 1, 1, 1, 0, 0, 0]; + } + let uvs = []; + const colors = []; + const indices = []; + let index = 0; + for (let y = 0; y < tilesY; y++) { + for (let x = 0; x < tilesX; x++) { + positions.push(-halfWidth + x * tileWidth + adjustX, -halfHeight + y * tileHeight + adjustY, 0); + positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, -halfHeight + y * tileHeight + adjustY, 0); + positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); + positions.push(-halfWidth + x * tileWidth + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); + indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); + if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) { + uvs = uvs.concat(uvBase[((x % 2) + (y % 2)) % 2]); + } + else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvs = uvs.concat(uvBase[y % 2]); + } + else { + uvs = uvs.concat(uvBase[0]); + } + colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); + normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + index += 4; + } + } + //Part Tiles + if (offsetX > 0 || offsetY > 0) { + const partialBottomRow = offsetY > 0 && (alignV === Mesh.CENTER || alignV === Mesh.TOP); + const partialTopRow = offsetY > 0 && (alignV === Mesh.CENTER || alignV === Mesh.BOTTOM); + const partialLeftCol = offsetX > 0 && (alignH === Mesh.CENTER || alignH === Mesh.RIGHT); + const partialRightCol = offsetX > 0 && (alignH === Mesh.CENTER || alignH === Mesh.LEFT); + let uvPart = []; + let a, b, c, d; + //corners + if (partialBottomRow && partialLeftCol) { + //bottom left corner + positions.push(startX + adjustX, startY + adjustY, 0); + positions.push(-halfWidth + adjustX, startY + adjustY, 0); + positions.push(-halfWidth + adjustX, startY + offsetY + adjustY, 0); + positions.push(startX + adjustX, startY + offsetY + adjustY, 0); + indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); + index += 4; + a = 1 - offsetX / tileWidth; + b = 1 - offsetY / tileHeight; + c = 1; + d = 1; + uvPart = [a, b, c, b, c, d, a, d]; + if (flipTile === Mesh.ROTATE_ROW) { + uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; + } + if (flipTile === Mesh.FLIP_ROW) { + uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; + } + if (flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; + } + uvs = uvs.concat(uvPart); + colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); + normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + } + if (partialBottomRow && partialRightCol) { + //bottom right corner + positions.push(halfWidth + adjustX, startY + adjustY, 0); + positions.push(endX + adjustX, startY + adjustY, 0); + positions.push(endX + adjustX, startY + offsetY + adjustY, 0); + positions.push(halfWidth + adjustX, startY + offsetY + adjustY, 0); + indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); + index += 4; + a = 0; + b = 1 - offsetY / tileHeight; + c = offsetX / tileWidth; + d = 1; + uvPart = [a, b, c, b, c, d, a, d]; + if (flipTile === Mesh.ROTATE_ROW || (flipTile === Mesh.ROTATE_TILE && tilesX % 2 === 0)) { + uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; + } + if (flipTile === Mesh.FLIP_ROW || (flipTile === Mesh.FLIP_TILE && tilesX % 2 === 0)) { + uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; + } + if (flipTile === Mesh.FLIP_N_ROTATE_ROW || (flipTile === Mesh.FLIP_N_ROTATE_TILE && tilesX % 2 === 0)) { + uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; + } + uvs = uvs.concat(uvPart); + colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); + normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + } + if (partialTopRow && partialLeftCol) { + //top left corner + positions.push(startX + adjustX, halfHeight + adjustY, 0); + positions.push(-halfWidth + adjustX, halfHeight + adjustY, 0); + positions.push(-halfWidth + adjustX, endY + adjustY, 0); + positions.push(startX + adjustX, endY + adjustY, 0); + indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); + index += 4; + a = 1 - offsetX / tileWidth; + b = 0; + c = 1; + d = offsetY / tileHeight; + uvPart = [a, b, c, b, c, d, a, d]; + if ((flipTile === Mesh.ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.ROTATE_TILE && tilesY % 1 === 0)) { + uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; + } + if ((flipTile === Mesh.FLIP_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_TILE && tilesY % 2 === 0)) { + uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; + } + if ((flipTile === Mesh.FLIP_N_ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_N_ROTATE_TILE && tilesY % 2 === 0)) { + uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; + } + uvs = uvs.concat(uvPart); + colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); + normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + } + if (partialTopRow && partialRightCol) { + //top right corner + positions.push(halfWidth + adjustX, halfHeight + adjustY, 0); + positions.push(endX + adjustX, halfHeight + adjustY, 0); + positions.push(endX + adjustX, endY + adjustY, 0); + positions.push(halfWidth + adjustX, endY + adjustY, 0); + indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); + index += 4; + a = 0; + b = 0; + c = offsetX / tileWidth; + d = offsetY / tileHeight; + uvPart = [a, b, c, b, c, d, a, d]; + if ((flipTile === Mesh.ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.ROTATE_TILE && (tilesY + tilesX) % 2 === 1)) { + uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; + } + if ((flipTile === Mesh.FLIP_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_TILE && (tilesY + tilesX) % 2 === 1)) { + uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; + } + if ((flipTile === Mesh.FLIP_N_ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_N_ROTATE_TILE && (tilesY + tilesX) % 2 === 1)) { + uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; + } + uvs = uvs.concat(uvPart); + colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); + normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + } + //part rows + if (partialBottomRow) { + const uvBaseBR = []; + a = 0; + b = 1 - offsetY / tileHeight; + c = 1; + d = 1; + uvBaseBR[0] = [a, b, c, b, c, d, a, d]; + uvBaseBR[1] = [a, b, c, b, c, d, a, d]; + if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) { + uvBaseBR[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; + } + if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) { + uvBaseBR[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; + } + if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvBaseBR[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; + } + for (let x = 0; x < tilesX; x++) { + positions.push(-halfWidth + x * tileWidth + adjustX, startY + adjustY, 0); + positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, startY + adjustY, 0); + positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, startY + offsetY + adjustY, 0); + positions.push(-halfWidth + x * tileWidth + adjustX, startY + offsetY + adjustY, 0); + indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); + index += 4; + if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) { + uvs = uvs.concat(uvBaseBR[(x + 1) % 2]); + } + else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvs = uvs.concat(uvBaseBR[1]); + } + else { + uvs = uvs.concat(uvBaseBR[0]); + } + colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); + normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + } + } + if (partialTopRow) { + const uvBaseTR = []; + a = 0; + b = 0; + c = 1; + d = offsetY / tileHeight; + uvBaseTR[0] = [a, b, c, b, c, d, a, d]; + uvBaseTR[1] = [a, b, c, b, c, d, a, d]; + if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) { + uvBaseTR[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; + } + if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) { + uvBaseTR[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; + } + if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvBaseTR[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; + } + for (let x = 0; x < tilesX; x++) { + positions.push(-halfWidth + x * tileWidth + adjustX, endY - offsetY + adjustY, 0); + positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, endY - offsetY + adjustY, 0); + positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, endY + adjustY, 0); + positions.push(-halfWidth + x * tileWidth + adjustX, endY + adjustY, 0); + indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); + index += 4; + if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) { + uvs = uvs.concat(uvBaseTR[(x + tilesY) % 2]); + } + else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvs = uvs.concat(uvBaseTR[tilesY % 2]); + } + else { + uvs = uvs.concat(uvBaseTR[0]); + } + colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); + normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + } + } + if (partialLeftCol) { + const uvBaseLC = []; + a = 1 - offsetX / tileWidth; + b = 0; + c = 1; + d = 1; + uvBaseLC[0] = [a, b, c, b, c, d, a, d]; + uvBaseLC[1] = [a, b, c, b, c, d, a, d]; + if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) { + uvBaseLC[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; + } + if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) { + uvBaseLC[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; + } + if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvBaseLC[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; + } + for (let y = 0; y < tilesY; y++) { + positions.push(startX + adjustX, -halfHeight + y * tileHeight + adjustY, 0); + positions.push(startX + offsetX + adjustX, -halfHeight + y * tileHeight + adjustY, 0); + positions.push(startX + offsetX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); + positions.push(startX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); + indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); + index += 4; + if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) { + uvs = uvs.concat(uvBaseLC[(y + 1) % 2]); + } + else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvs = uvs.concat(uvBaseLC[y % 2]); + } + else { + uvs = uvs.concat(uvBaseLC[0]); + } + colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); + normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + } + } + if (partialRightCol) { + const uvBaseRC = []; + a = 0; + b = 0; + c = offsetX / tileHeight; + d = 1; + uvBaseRC[0] = [a, b, c, b, c, d, a, d]; + uvBaseRC[1] = [a, b, c, b, c, d, a, d]; + if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) { + uvBaseRC[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; + } + if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) { + uvBaseRC[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; + } + if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvBaseRC[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; + } + for (let y = 0; y < tilesY; y++) { + positions.push(endX - offsetX + adjustX, -halfHeight + y * tileHeight + adjustY, 0); + positions.push(endX + adjustX, -halfHeight + y * tileHeight + adjustY, 0); + positions.push(endX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); + positions.push(endX - offsetX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); + indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); + index += 4; + if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) { + uvs = uvs.concat(uvBaseRC[(y + tilesX) % 2]); + } + else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) { + uvs = uvs.concat(uvBaseRC[y % 2]); + } + else { + uvs = uvs.concat(uvBaseRC[0]); + } + colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); + normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + } + } + } + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + // sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors; + vertexData.colors = totalColors; + return vertexData; +} +/** + * Creates a tiled plane mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_plane + * @param name defines the name of the mesh + * @param options an object used to set the following optional parameters for the tiled plane, required but can be empty + * * pattern a limited pattern arrangement depending on the number + * * size of the box + * * width of the box, overwrites size + * * height of the box, overwrites size + * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1 + * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size + * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * alignHorizontal places whole tiles aligned to the center, left or right of a row + * * alignVertical places whole tiles aligned to the center, left or right of a column + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @param options.pattern + * @param options.tileSize + * @param options.tileWidth + * @param options.tileHeight + * @param options.size + * @param options.width + * @param options.height + * @param options.alignHorizontal + * @param options.alignVertical + * @param options.sideOrientation + * @param options.frontUVs + * @param options.backUVs + * @param options.updatable + * @param scene defines the hosting scene + * @returns the box mesh + */ +function CreateTiledPlane(name, options, scene = null) { + const plane = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + plane._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreateTiledPlaneVertexData(options); + vertexData.applyToMesh(plane, options.updatable); + return plane; +} +VertexData.CreateTiledPlane = CreateTiledPlaneVertexData; + +/** + * Creates the VertexData for a tiled box + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_box + * @param options an object used to set the following optional parameters for the tiled box, required but can be empty + * * pattern sets the rotation or reflection pattern for the tiles, + * * size of the box + * * width of the box, overwrites size + * * height of the box, overwrites size + * * depth of the box, overwrites size + * * tileSize sets the size of a tile + * * tileWidth sets the tile width and overwrites tileSize + * * tileHeight sets the tile width and overwrites tileSize + * * faceUV an array of 6 Vector4 elements used to set different images to each box side + * * faceColors an array of 6 Color3 elements used to set different colors to each box side + * * alignHorizontal places whole tiles aligned to the center, left or right of a row + * * alignVertical places whole tiles aligned to the center, left or right of a column + * @param options.pattern + * @param options.size + * @param options.width + * @param options.height + * @param options.depth + * @param options.tileSize + * @param options.tileWidth + * @param options.tileHeight + * @param options.faceUV + * @param options.faceColors + * @param options.alignHorizontal + * @param options.alignVertical + * @param options.sideOrientation + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * @returns the VertexData of the TiledBox + */ +function CreateTiledBoxVertexData(options) { + const nbFaces = 6; + const faceUV = options.faceUV || new Array(6); + const faceColors = options.faceColors; + const flipTile = options.pattern || Mesh.NO_FLIP; + const width = options.width || options.size || 1; + const height = options.height || options.size || 1; + const depth = options.depth || options.size || 1; + const tileWidth = options.tileWidth || options.tileSize || 1; + const tileHeight = options.tileHeight || options.tileSize || 1; + const alignH = options.alignHorizontal || 0; + const alignV = options.alignVertical || 0; + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + // default face colors and UV if undefined + for (let f = 0; f < nbFaces; f++) { + if (faceUV[f] === undefined) { + faceUV[f] = new Vector4(0, 0, 1, 1); + } + if (faceColors && faceColors[f] === undefined) { + faceColors[f] = new Color4(1, 1, 1, 1); + } + } + const halfWidth = width / 2; + const halfHeight = height / 2; + const halfDepth = depth / 2; + const faceVertexData = []; + for (let f = 0; f < 2; f++) { + //front and back + faceVertexData[f] = CreateTiledPlaneVertexData({ + pattern: flipTile, + tileWidth: tileWidth, + tileHeight: tileHeight, + width: width, + height: height, + alignVertical: alignV, + alignHorizontal: alignH, + sideOrientation: sideOrientation, + }); + } + for (let f = 2; f < 4; f++) { + //sides + faceVertexData[f] = CreateTiledPlaneVertexData({ + pattern: flipTile, + tileWidth: tileWidth, + tileHeight: tileHeight, + width: depth, + height: height, + alignVertical: alignV, + alignHorizontal: alignH, + sideOrientation: sideOrientation, + }); + } + let baseAlignV = alignV; + if (alignV === Mesh.BOTTOM) { + baseAlignV = Mesh.TOP; + } + else if (alignV === Mesh.TOP) { + baseAlignV = Mesh.BOTTOM; + } + for (let f = 4; f < 6; f++) { + //top and bottom + faceVertexData[f] = CreateTiledPlaneVertexData({ + pattern: flipTile, + tileWidth: tileWidth, + tileHeight: tileHeight, + width: width, + height: depth, + alignVertical: baseAlignV, + alignHorizontal: alignH, + sideOrientation: sideOrientation, + }); + } + let positions = []; + let normals = []; + let uvs = []; + let indices = []; + const colors = []; + const facePositions = []; + const faceNormals = []; + const newFaceUV = []; + let lu = 0; + let li = 0; + for (let f = 0; f < nbFaces; f++) { + const len = faceVertexData[f].positions.length; + facePositions[f] = []; + faceNormals[f] = []; + for (let p = 0; p < len / 3; p++) { + facePositions[f].push(new Vector3(faceVertexData[f].positions[3 * p], faceVertexData[f].positions[3 * p + 1], faceVertexData[f].positions[3 * p + 2])); + faceNormals[f].push(new Vector3(faceVertexData[f].normals[3 * p], faceVertexData[f].normals[3 * p + 1], faceVertexData[f].normals[3 * p + 2])); + } + // uvs + lu = faceVertexData[f].uvs.length; + newFaceUV[f] = []; + for (let i = 0; i < lu; i += 2) { + newFaceUV[f][i] = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * faceVertexData[f].uvs[i]; + newFaceUV[f][i + 1] = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * faceVertexData[f].uvs[i + 1]; + } + uvs = uvs.concat(newFaceUV[f]); + indices = indices.concat(faceVertexData[f].indices.map((x) => x + li)); + li += facePositions[f].length; + if (faceColors) { + for (let c = 0; c < 4; c++) { + colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a); + } + } + } + const vec0 = new Vector3(0, 0, halfDepth); + const mtrx0 = Matrix.RotationY(Math.PI); + positions = facePositions[0] + .map((entry) => Vector3.TransformNormal(entry, mtrx0).add(vec0)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); + normals = faceNormals[0] + .map((entry) => Vector3.TransformNormal(entry, mtrx0)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); + positions = positions.concat(facePositions[1] + .map((entry) => entry.subtract(vec0)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); + normals = normals.concat(faceNormals[1].map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); + const vec2 = new Vector3(halfWidth, 0, 0); + const mtrx2 = Matrix.RotationY(-Math.PI / 2); + positions = positions.concat(facePositions[2] + .map((entry) => Vector3.TransformNormal(entry, mtrx2).add(vec2)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); + normals = normals.concat(faceNormals[2] + .map((entry) => Vector3.TransformNormal(entry, mtrx2)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); + const mtrx3 = Matrix.RotationY(Math.PI / 2); + positions = positions.concat(facePositions[3] + .map((entry) => Vector3.TransformNormal(entry, mtrx3).subtract(vec2)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); + normals = normals.concat(faceNormals[3] + .map((entry) => Vector3.TransformNormal(entry, mtrx3)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); + const vec4 = new Vector3(0, halfHeight, 0); + const mtrx4 = Matrix.RotationX(Math.PI / 2); + positions = positions.concat(facePositions[4] + .map((entry) => Vector3.TransformNormal(entry, mtrx4).add(vec4)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); + normals = normals.concat(faceNormals[4] + .map((entry) => Vector3.TransformNormal(entry, mtrx4)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); + const mtrx5 = Matrix.RotationX(-Math.PI / 2); + positions = positions.concat(facePositions[5] + .map((entry) => Vector3.TransformNormal(entry, mtrx5).subtract(vec4)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); + normals = normals.concat(faceNormals[5] + .map((entry) => Vector3.TransformNormal(entry, mtrx5)) + .map((entry) => [entry.x, entry.y, entry.z]) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); + // sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs); + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + if (faceColors) { + const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors; + vertexData.colors = totalColors; + } + return vertexData; +} +/** + * Creates a tiled box mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_box + * @param name defines the name of the mesh + * @param options an object used to set the following optional parameters for the tiled box, required but can be empty + * * pattern sets the rotation or reflection pattern for the tiles, + * * size of the box + * * width of the box, overwrites size + * * height of the box, overwrites size + * * depth of the box, overwrites size + * * tileSize sets the size of a tile + * * tileWidth sets the tile width and overwrites tileSize + * * tileHeight sets the tile width and overwrites tileSize + * * faceUV an array of 6 Vector4 elements used to set different images to each box side + * * faceColors an array of 6 Color3 elements used to set different colors to each box side + * * alignHorizontal places whole tiles aligned to the center, left or right of a row + * * alignVertical places whole tiles aligned to the center, left or right of a column + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * @param options.pattern + * @param options.width + * @param options.height + * @param options.depth + * @param options.tileSize + * @param options.tileWidth + * @param options.tileHeight + * @param options.alignHorizontal + * @param options.alignVertical + * @param options.faceUV + * @param options.faceColors + * @param options.sideOrientation + * @param options.updatable + * @param scene defines the hosting scene + * @returns the box mesh + */ +function CreateTiledBox(name, options, scene = null) { + const box = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + box._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreateTiledBoxVertexData(options); + vertexData.applyToMesh(box, options.updatable); + return box; +} +VertexData.CreateTiledBox = CreateTiledBoxVertexData; + +// based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473 +/** + * Creates the VertexData for a TorusKnot + * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty + * * radius the radius of the torus knot, optional, default 2 + * * tube the thickness of the tube, optional, default 0.5 + * * radialSegments the number of sides on each tube segments, optional, default 32 + * * tubularSegments the number of tubes to decompose the knot into, optional, default 32 + * * p the number of windings around the z axis, optional, default 2 + * * q the number of windings around the x axis, optional, default 3 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @param options.radius + * @param options.tube + * @param options.radialSegments + * @param options.tubularSegments + * @param options.p + * @param options.q + * @param options.sideOrientation + * @param options.frontUVs + * @param options.backUVs + * @returns the VertexData of the Torus Knot + */ +function CreateTorusKnotVertexData(options) { + const indices = []; + const positions = []; + const normals = []; + const uvs = []; + const radius = options.radius || 2; + const tube = options.tube || 0.5; + const radialSegments = options.radialSegments || 32; + const tubularSegments = options.tubularSegments || 32; + const p = options.p || 2; + const q = options.q || 3; + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + // Helper + const getPos = (angle) => { + const cu = Math.cos(angle); + const su = Math.sin(angle); + const quOverP = (q / p) * angle; + const cs = Math.cos(quOverP); + const tx = radius * (2 + cs) * 0.5 * cu; + const ty = radius * (2 + cs) * su * 0.5; + const tz = radius * Math.sin(quOverP) * 0.5; + return new Vector3(tx, ty, tz); + }; + // Vertices + let i; + let j; + for (i = 0; i <= radialSegments; i++) { + const modI = i % radialSegments; + const u = (modI / radialSegments) * 2 * p * Math.PI; + const p1 = getPos(u); + const p2 = getPos(u + 0.01); + const tang = p2.subtract(p1); + let n = p2.add(p1); + const bitan = Vector3.Cross(tang, n); + n = Vector3.Cross(bitan, tang); + bitan.normalize(); + n.normalize(); + for (j = 0; j < tubularSegments; j++) { + const modJ = j % tubularSegments; + const v = (modJ / tubularSegments) * 2 * Math.PI; + const cx = -tube * Math.cos(v); + const cy = tube * Math.sin(v); + positions.push(p1.x + cx * n.x + cy * bitan.x); + positions.push(p1.y + cx * n.y + cy * bitan.y); + positions.push(p1.z + cx * n.z + cy * bitan.z); + uvs.push(i / radialSegments); + uvs.push(j / tubularSegments); + } + } + for (i = 0; i < radialSegments; i++) { + for (j = 0; j < tubularSegments; j++) { + const jNext = (j + 1) % tubularSegments; + const a = i * tubularSegments + j; + const b = (i + 1) * tubularSegments + j; + const c = (i + 1) * tubularSegments + jNext; + const d = i * tubularSegments + jNext; + indices.push(d); + indices.push(b); + indices.push(a); + indices.push(d); + indices.push(c); + indices.push(b); + } + } + // Normals + VertexData.ComputeNormals(positions, indices, normals); + // Sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + return vertexData; +} +/** + * Creates a torus knot mesh + * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2) + * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32) + * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32) + * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3) + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param options.radius + * @param options.tube + * @param options.radialSegments + * @param options.tubularSegments + * @param options.p + * @param options.q + * @param options.updatable + * @param options.sideOrientation + * @param options.frontUVs + * @param options.backUVs + * @param scene defines the hosting scene + * @returns the torus knot mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#torus-knot + */ +function CreateTorusKnot(name, options = {}, scene) { + const torusKnot = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + torusKnot._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreateTorusKnotVertexData(options); + vertexData.applyToMesh(torusKnot, options.updatable); + return torusKnot; +} +VertexData.CreateTorusKnot = CreateTorusKnotVertexData; +Mesh.CreateTorusKnot = (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) => { + const options = { + radius, + tube, + radialSegments, + tubularSegments, + p, + q, + sideOrientation, + updatable, + }; + return CreateTorusKnot(name, options, scene); +}; + +Mesh._LinesMeshParser = (parsedMesh, scene) => { + return LinesMesh.Parse(parsedMesh, scene); +}; +/** + * Line mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param + */ +class LinesMesh extends Mesh { + _isShaderMaterial(shader) { + return shader.getClassName() === "ShaderMaterial"; + } + /** + * Creates a new LinesMesh + * @param name defines the name + * @param scene defines the hosting scene + * @param parent defines the parent mesh if any + * @param source defines the optional source LinesMesh used to clone data from + * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False. + * When false, achieved by calling a clone(), also passing False. + * This will make creation of children, recursive. + * @param useVertexColor defines if this LinesMesh supports vertex color + * @param useVertexAlpha defines if this LinesMesh supports vertex alpha + * @param material material to use to draw the line. If not provided, will create a new one + */ + constructor(name, scene = null, parent = null, source = null, doNotCloneChildren, + /** + * If vertex color should be applied to the mesh + */ + useVertexColor, + /** + * If vertex alpha should be applied to the mesh + */ + useVertexAlpha, material) { + super(name, scene, parent, source, doNotCloneChildren); + this.useVertexColor = useVertexColor; + this.useVertexAlpha = useVertexAlpha; + /** + * Color of the line (Default: White) + */ + this.color = new Color3(1, 1, 1); + /** + * Alpha of the line (Default: 1) + */ + this.alpha = 1; + /** Shader language used by the material */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + if (source) { + this.color = source.color.clone(); + this.alpha = source.alpha; + this.useVertexColor = source.useVertexColor; + this.useVertexAlpha = source.useVertexAlpha; + } + this.intersectionThreshold = 0.1; + const defines = []; + const options = { + attributes: [VertexBuffer.PositionKind], + uniforms: ["world", "viewProjection"], + needAlphaBlending: true, + defines: defines, + useClipPlane: null, + shaderLanguage: 0 /* ShaderLanguage.GLSL */, + }; + if (!this.useVertexAlpha) { + options.needAlphaBlending = false; + } + else { + options.defines.push("#define VERTEXALPHA"); + } + if (!this.useVertexColor) { + options.uniforms.push("color"); + this._color4 = new Color4(); + } + else { + options.defines.push("#define VERTEXCOLOR"); + options.attributes.push(VertexBuffer.ColorKind); + } + if (material) { + this.material = material; + } + else { + const engine = this.getScene().getEngine(); + if (engine.isWebGPU && !LinesMesh.ForceGLSL) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + } + options.shaderLanguage = this._shaderLanguage; + options.extraInitializationsAsync = async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => color_vertex), Promise.resolve().then(() => color_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => color_vertex$1), Promise.resolve().then(() => color_fragment$1)]); + } + }; + this.material = new ShaderMaterial("colorShader", this.getScene(), "color", options, false); + this.material.doNotSerialize = true; + } + } + isReady() { + if (!this._lineMaterial.isReady(this, !!this._userInstancedBuffersStorage || this.hasThinInstances)) { + return false; + } + return super.isReady(); + } + /** + * @returns the string "LineMesh" + */ + getClassName() { + return "LinesMesh"; + } + /** + * @internal + */ + get material() { + return this._lineMaterial; + } + /** + * @internal + */ + set material(value) { + this._lineMaterial = value; + this._lineMaterial.fillMode = Material.LineListDrawMode; + } + /** + * @internal + */ + get checkCollisions() { + return false; + } + set checkCollisions(value) { + // Just ignore it + } + /** + * @internal + */ + _bind(_subMesh, colorEffect) { + if (!this._geometry) { + return this; + } + // VBOs + const indexToBind = this.isUnIndexed ? null : this._geometry.getIndexBuffer(); + if (!this._userInstancedBuffersStorage || this.hasThinInstances) { + this._geometry._bind(colorEffect, indexToBind); + } + else { + this._geometry._bind(colorEffect, indexToBind, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects); + } + // Color + if (!this.useVertexColor && this._isShaderMaterial(this._lineMaterial)) { + const { r, g, b } = this.color; + this._color4.set(r, g, b, this.alpha); + this._lineMaterial.setColor4("color", this._color4); + } + return this; + } + /** + * @internal + */ + _draw(subMesh, fillMode, instancesCount) { + if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { + return this; + } + const engine = this.getScene().getEngine(); + // Draw order + if (this._unIndexed) { + engine.drawArraysType(Material.LineListDrawMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount); + } + else { + engine.drawElementsType(Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount); + } + return this; + } + /** + * Disposes of the line mesh + * @param doNotRecurse If children should be disposed + * @param disposeMaterialAndTextures This parameter is not used by the LineMesh class + * @param doNotDisposeMaterial If the material should not be disposed (default: false, meaning the material is disposed) + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + dispose(doNotRecurse, disposeMaterialAndTextures = false, doNotDisposeMaterial) { + if (!doNotDisposeMaterial) { + this._lineMaterial.dispose(false, false, true); + } + super.dispose(doNotRecurse); + } + /** + * Returns a new LineMesh object cloned from the current one. + * @param name defines the cloned mesh name + * @param newParent defines the new mesh parent + * @param doNotCloneChildren if set to true, none of the mesh children are cloned (false by default) + * @returns the new mesh + */ + clone(name, newParent = null, doNotCloneChildren) { + return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren); + } + /** + * Creates a new InstancedLinesMesh object from the mesh model. + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances + * @param name defines the name of the new instance + * @returns a new InstancedLinesMesh + */ + createInstance(name) { + const instance = new InstancedLinesMesh(name, this); + if (this.instancedBuffers) { + instance.instancedBuffers = {}; + for (const key in this.instancedBuffers) { + instance.instancedBuffers[key] = this.instancedBuffers[key]; + } + } + return instance; + } + /** + * Serializes this ground mesh + * @param serializationObject object to write serialization to + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.color = this.color.asArray(); + serializationObject.alpha = this.alpha; + } + /** + * Parses a serialized ground mesh + * @param parsedMesh the serialized mesh + * @param scene the scene to create the ground mesh in + * @returns the created ground mesh + */ + static Parse(parsedMesh, scene) { + const result = new LinesMesh(parsedMesh.name, scene); + result.color = Color3.FromArray(parsedMesh.color); + result.alpha = parsedMesh.alpha; + return result; + } +} +/** + * Force all the LineMeshes to compile their default color material to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +LinesMesh.ForceGLSL = false; +/** + * Creates an instance based on a source LinesMesh + */ +class InstancedLinesMesh extends InstancedMesh { + constructor(name, source) { + super(name, source); + this.intersectionThreshold = source.intersectionThreshold; + } + /** + * @returns the string "InstancedLinesMesh". + */ + getClassName() { + return "InstancedLinesMesh"; + } +} + +/* eslint-disable @typescript-eslint/naming-convention */ +/** + * Creates the VertexData of the LineSystem + * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty + * - lines an array of lines, each line being an array of successive Vector3 + * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point + * @returns the VertexData of the LineSystem + */ +function CreateLineSystemVertexData(options) { + const indices = []; + const positions = []; + const lines = options.lines; + const colors = options.colors; + const vertexColors = []; + let idx = 0; + for (let l = 0; l < lines.length; l++) { + const points = lines[l]; + for (let index = 0; index < points.length; index++) { + const { x, y, z } = points[index]; + positions.push(x, y, z); + if (colors) { + const color = colors[l]; + const { r, g, b, a } = color[index]; + vertexColors.push(r, g, b, a); + } + if (index > 0) { + indices.push(idx - 1); + indices.push(idx); + } + idx++; + } + } + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + if (colors) { + vertexData.colors = vertexColors; + } + return vertexData; +} +/** + * Create the VertexData for a DashedLines + * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty + * - points an array successive Vector3 + * - dashSize the size of the dashes relative to the dash number, optional, default 3 + * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1 + * - dashNb the intended total number of dashes, optional, default 200 + * @returns the VertexData for the DashedLines + */ +function CreateDashedLinesVertexData(options) { + const dashSize = options.dashSize || 3; + const gapSize = options.gapSize || 1; + const dashNb = options.dashNb || 200; + const points = options.points; + const positions = []; + const indices = []; + const curvect = Vector3.Zero(); + let lg = 0; + let nb = 0; + let shft = 0; + let dashshft = 0; + let curshft = 0; + let idx = 0; + let i = 0; + for (i = 0; i < points.length - 1; i++) { + points[i + 1].subtractToRef(points[i], curvect); + lg += curvect.length(); + } + shft = lg / dashNb; + dashshft = (dashSize * shft) / (dashSize + gapSize); + for (i = 0; i < points.length - 1; i++) { + points[i + 1].subtractToRef(points[i], curvect); + nb = Math.floor(curvect.length() / shft); + curvect.normalize(); + for (let j = 0; j < nb; j++) { + curshft = shft * j; + positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z); + positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z); + indices.push(idx, idx + 1); + idx += 2; + } + } + // Result + const vertexData = new VertexData(); + vertexData.positions = positions; + vertexData.indices = indices; + return vertexData; +} +/** + * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh + * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter + * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function + * * The parameter `lines` is an array of lines, each line being an array of successive Vector3 + * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter + * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point + * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster) + * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created + * * Updating a simple Line mesh, you just need to update every line in the `lines` array : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#lines-and-dashedlines + * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#line-system + * @param name defines the name of the new line system + * @param options defines the options used to create the line system + * @param scene defines the hosting scene + * @returns a new line system mesh + */ +function CreateLineSystem(name, options, scene = null) { + const instance = options.instance; + const lines = options.lines; + const colors = options.colors; + if (instance) { + // lines update + const positions = instance.getVerticesData(VertexBuffer.PositionKind); + let vertexColor; + let lineColors; + if (colors) { + vertexColor = instance.getVerticesData(VertexBuffer.ColorKind); + } + let i = 0; + let c = 0; + for (let l = 0; l < lines.length; l++) { + const points = lines[l]; + for (let p = 0; p < points.length; p++) { + positions[i] = points[p].x; + positions[i + 1] = points[p].y; + positions[i + 2] = points[p].z; + if (colors && vertexColor) { + lineColors = colors[l]; + vertexColor[c] = lineColors[p].r; + vertexColor[c + 1] = lineColors[p].g; + vertexColor[c + 2] = lineColors[p].b; + vertexColor[c + 3] = lineColors[p].a; + c += 4; + } + i += 3; + } + } + instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false); + if (colors && vertexColor) { + instance.updateVerticesData(VertexBuffer.ColorKind, vertexColor, false, false); + } + instance.refreshBoundingInfo(); + return instance; + } + // line system creation + const useVertexColor = colors ? true : false; + const lineSystem = new LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha, options.material); + const vertexData = CreateLineSystemVertexData(options); + vertexData.applyToMesh(lineSystem, options.updatable); + return lineSystem; +} +/** + * Creates a line mesh + * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter + * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function + * * The parameter `points` is an array successive Vector3 + * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#lines-and-dashedlines + * * The optional parameter `colors` is an array of successive Color4, one per line point + * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster) + * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created + * * When updating an instance, remember that only point positions can change, not the number of points + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#lines + * @param name defines the name of the new line system + * @param options defines the options used to create the line system + * @param scene defines the hosting scene + * @returns a new line mesh + */ +function CreateLines(name, options, scene = null) { + const colors = options.colors ? [options.colors] : null; + const lines = CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha, material: options.material }, scene); + return lines; +} +/** + * Creates a dashed line mesh + * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter + * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function + * * The parameter `points` is an array successive Vector3 + * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200) + * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3) + * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1) + * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#lines-and-dashedlines + * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster) + * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created + * * When updating an instance, remember that only point positions can change, not the number of points + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the dashed line mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#dashed-lines + */ +function CreateDashedLines(name, options, scene = null) { + const points = options.points; + const instance = options.instance; + const gapSize = options.gapSize || 1; + const dashSize = options.dashSize || 3; + if (instance) { + // dashed lines update + const positionFunction = (positions) => { + const curvect = Vector3.Zero(); + const nbSeg = positions.length / 6; + let lg = 0; + let nb = 0; + let shft = 0; + let dashshft = 0; + let curshft = 0; + let p = 0; + let i = 0; + let j = 0; + for (i = 0; i < points.length - 1; i++) { + points[i + 1].subtractToRef(points[i], curvect); + lg += curvect.length(); + } + shft = lg / nbSeg; + const dashSize = instance._creationDataStorage.dashSize; + const gapSize = instance._creationDataStorage.gapSize; + dashshft = (dashSize * shft) / (dashSize + gapSize); + for (i = 0; i < points.length - 1; i++) { + points[i + 1].subtractToRef(points[i], curvect); + nb = Math.floor(curvect.length() / shft); + curvect.normalize(); + j = 0; + while (j < nb && p < positions.length) { + curshft = shft * j; + positions[p] = points[i].x + curshft * curvect.x; + positions[p + 1] = points[i].y + curshft * curvect.y; + positions[p + 2] = points[i].z + curshft * curvect.z; + positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x; + positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y; + positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z; + p += 6; + j++; + } + } + while (p < positions.length) { + positions[p] = points[i].x; + positions[p + 1] = points[i].y; + positions[p + 2] = points[i].z; + p += 3; + } + }; + if (options.dashNb || options.dashSize || options.gapSize || options.useVertexAlpha || options.material) { + Logger.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."); + } + instance.updateMeshPositions(positionFunction, false); + return instance; + } + // dashed lines creation + const dashedLines = new LinesMesh(name, scene, null, undefined, undefined, undefined, options.useVertexAlpha, options.material); + const vertexData = CreateDashedLinesVertexData(options); + vertexData.applyToMesh(dashedLines, options.updatable); + dashedLines._creationDataStorage = new _CreationDataStorage(); + dashedLines._creationDataStorage.dashSize = dashSize; + dashedLines._creationDataStorage.gapSize = gapSize; + return dashedLines; +} +VertexData.CreateLineSystem = CreateLineSystemVertexData; +VertexData.CreateDashedLines = CreateDashedLinesVertexData; +Mesh.CreateLines = (name, points, scene = null, updatable = false, instance = null) => { + const options = { + points, + updatable, + instance, + }; + return CreateLines(name, options, scene); +}; +Mesh.CreateDashedLines = (name, points, dashSize, gapSize, dashNb, scene = null, updatable, instance) => { + const options = { + points, + dashSize, + gapSize, + dashNb, + updatable, + instance, + }; + return CreateDashedLines(name, options, scene); +}; + +/** + * Vector2 wth index property + */ +class IndexedVector2 extends Vector2 { + constructor(original, + /** Index of the vector2 */ + index) { + super(original.x, original.y); + this.index = index; + } +} +/** + * Defines points to create a polygon + */ +class PolygonPoints { + constructor() { + this.elements = []; + } + add(originalPoints) { + const result = []; + originalPoints.forEach((point) => { + const newPoint = new IndexedVector2(point, this.elements.length); + result.push(newPoint); + this.elements.push(newPoint); + }); + return result; + } + computeBounds() { + const lmin = new Vector2(this.elements[0].x, this.elements[0].y); + const lmax = new Vector2(this.elements[0].x, this.elements[0].y); + this.elements.forEach((point) => { + // x + if (point.x < lmin.x) { + lmin.x = point.x; + } + else if (point.x > lmax.x) { + lmax.x = point.x; + } + // y + if (point.y < lmin.y) { + lmin.y = point.y; + } + else if (point.y > lmax.y) { + lmax.y = point.y; + } + }); + return { + min: lmin, + max: lmax, + width: lmax.x - lmin.x, + height: lmax.y - lmin.y, + }; + } +} +/** + * Builds a polygon + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/polyMeshBuilder + */ +class PolygonMeshBuilder { + _addToepoint(points) { + for (const p of points) { + this._epoints.push(p.x, p.y); + } + } + /** + * Creates a PolygonMeshBuilder + * @param name name of the builder + * @param contours Path of the polygon + * @param scene scene to add to when creating the mesh + * @param earcutInjection can be used to inject your own earcut reference + */ + constructor(name, contours, scene, earcutInjection = earcut) { + this._points = new PolygonPoints(); + this._outlinepoints = new PolygonPoints(); + this._holes = new Array(); + this._epoints = new Array(); + this._eholes = new Array(); + this.bjsEarcut = earcutInjection; + this._name = name; + this._scene = scene || EngineStore.LastCreatedScene; + let points; + if (contours instanceof Path2) { + points = contours.getPoints(); + } + else { + points = contours; + } + this._addToepoint(points); + this._points.add(points); + this._outlinepoints.add(points); + if (typeof this.bjsEarcut === "undefined") { + Logger.Warn("Earcut was not found, the polygon will not be built."); + } + } + /** + * Adds a hole within the polygon + * @param hole Array of points defining the hole + * @returns this + */ + addHole(hole) { + this._points.add(hole); + const holepoints = new PolygonPoints(); + holepoints.add(hole); + this._holes.push(holepoints); + this._eholes.push(this._epoints.length / 2); + this._addToepoint(hole); + return this; + } + /** + * Creates the polygon + * @param updatable If the mesh should be updatable + * @param depth The depth of the mesh created + * @param smoothingThreshold Dot product threshold for smoothed normals + * @returns the created mesh + */ + build(updatable = false, depth = 0, smoothingThreshold = 2) { + const result = new Mesh(this._name, this._scene); + const vertexData = this.buildVertexData(depth, smoothingThreshold); + result.setVerticesData(VertexBuffer.PositionKind, vertexData.positions, updatable); + result.setVerticesData(VertexBuffer.NormalKind, vertexData.normals, updatable); + result.setVerticesData(VertexBuffer.UVKind, vertexData.uvs, updatable); + result.setIndices(vertexData.indices); + return result; + } + /** + * Creates the polygon + * @param depth The depth of the mesh created + * @param smoothingThreshold Dot product threshold for smoothed normals + * @returns the created VertexData + */ + buildVertexData(depth = 0, smoothingThreshold = 2) { + const result = new VertexData(); + const normals = []; + const positions = []; + const uvs = []; + const bounds = this._points.computeBounds(); + this._points.elements.forEach((p) => { + normals.push(0, 1.0, 0); + positions.push(p.x, 0, p.y); + uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height); + }); + const indices = []; + const res = this.bjsEarcut(this._epoints, this._eholes, 2); + for (let i = 0; i < res.length; i++) { + indices.push(res[i]); + } + if (depth > 0) { + const positionscount = positions.length / 3; //get the current pointcount + this._points.elements.forEach((p) => { + //add the elements at the depth + normals.push(0, -1, 0); + positions.push(p.x, -depth, p.y); + uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height); + }); + const totalCount = indices.length; + for (let i = 0; i < totalCount; i += 3) { + const i0 = indices[i + 0]; + const i1 = indices[i + 1]; + const i2 = indices[i + 2]; + indices.push(i2 + positionscount); + indices.push(i1 + positionscount); + indices.push(i0 + positionscount); + } + //Add the sides + this._addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false, smoothingThreshold); + this._holes.forEach((hole) => { + this._addSide(positions, normals, uvs, indices, bounds, hole, depth, true, smoothingThreshold); + }); + } + result.indices = indices; + result.positions = positions; + result.normals = normals; + result.uvs = uvs; + return result; + } + /** + * Adds a side to the polygon + * @param positions points that make the polygon + * @param normals normals of the polygon + * @param uvs uvs of the polygon + * @param indices indices of the polygon + * @param bounds bounds of the polygon + * @param points points of the polygon + * @param depth depth of the polygon + * @param flip flip of the polygon + * @param smoothingThreshold + */ + _addSide(positions, normals, uvs, indices, bounds, points, depth, flip, smoothingThreshold) { + let startIndex = positions.length / 3; + let ulength = 0; + for (let i = 0; i < points.elements.length; i++) { + const p = points.elements[i]; + const p1 = points.elements[(i + 1) % points.elements.length]; + positions.push(p.x, 0, p.y); + positions.push(p.x, -depth, p.y); + positions.push(p1.x, 0, p1.y); + positions.push(p1.x, -depth, p1.y); + const p0 = points.elements[(i + points.elements.length - 1) % points.elements.length]; + const p2 = points.elements[(i + 2) % points.elements.length]; + let vc = new Vector3(-(p1.y - p.y), 0, p1.x - p.x); + let vp = new Vector3(-(p.y - p0.y), 0, p.x - p0.x); + let vn = new Vector3(-(p2.y - p1.y), 0, p2.x - p1.x); + if (!flip) { + vc = vc.scale(-1); + vp = vp.scale(-1); + vn = vn.scale(-1); + } + const vc_norm = vc.normalizeToNew(); + let vp_norm = vp.normalizeToNew(); + let vn_norm = vn.normalizeToNew(); + const dotp = Vector3.Dot(vp_norm, vc_norm); + if (dotp > smoothingThreshold) { + if (dotp < Epsilon - 1) { + vp_norm = new Vector3(p.x, 0, p.y).subtract(new Vector3(p1.x, 0, p1.y)).normalize(); + } + else { + // cheap average weighed by side length + vp_norm = vp.add(vc).normalize(); + } + } + else { + vp_norm = vc_norm; + } + const dotn = Vector3.Dot(vn, vc); + if (dotn > smoothingThreshold) { + if (dotn < Epsilon - 1) { + // back to back + vn_norm = new Vector3(p1.x, 0, p1.y).subtract(new Vector3(p.x, 0, p.y)).normalize(); + } + else { + // cheap average weighed by side length + vn_norm = vn.add(vc).normalize(); + } + } + else { + vn_norm = vc_norm; + } + uvs.push(ulength / bounds.width, 0); + uvs.push(ulength / bounds.width, 1); + ulength += vc.length(); + uvs.push(ulength / bounds.width, 0); + uvs.push(ulength / bounds.width, 1); + normals.push(vp_norm.x, vp_norm.y, vp_norm.z); + normals.push(vp_norm.x, vp_norm.y, vp_norm.z); + normals.push(vn_norm.x, vn_norm.y, vn_norm.z); + normals.push(vn_norm.x, vn_norm.y, vn_norm.z); + if (!flip) { + indices.push(startIndex); + indices.push(startIndex + 1); + indices.push(startIndex + 2); + indices.push(startIndex + 1); + indices.push(startIndex + 3); + indices.push(startIndex + 2); + } + else { + indices.push(startIndex); + indices.push(startIndex + 2); + indices.push(startIndex + 1); + indices.push(startIndex + 1); + indices.push(startIndex + 2); + indices.push(startIndex + 3); + } + startIndex += 4; + } + } +} + +/** + * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build() + * All parameters are provided by CreatePolygon as needed + * @param polygon a mesh built from polygonTriangulation.build() + * @param sideOrientation takes the values Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @param wrp a boolean, default false, when true and fUVs used texture is wrapped around all sides, when false texture is applied side + * @returns the VertexData of the Polygon + */ +function CreatePolygonVertexData(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrp) { + const faceUV = fUV || new Array(3); + const faceColors = fColors; + const colors = []; + const wrap = wrp || false; + // default face colors and UV if undefined + for (let f = 0; f < 3; f++) { + if (faceUV[f] === undefined) { + faceUV[f] = new Vector4(0, 0, 1, 1); + } + if (faceColors && faceColors[f] === undefined) { + faceColors[f] = new Color4(1, 1, 1, 1); + } + } + const positions = polygon.getVerticesData(VertexBuffer.PositionKind); + const normals = polygon.getVerticesData(VertexBuffer.NormalKind); + const uvs = polygon.getVerticesData(VertexBuffer.UVKind); + const indices = polygon.getIndices(); + const startIndex = positions.length / 9; + let disp = 0; + let distX = 0; + let distZ = 0; + let dist = 0; + let totalLen = 0; + const cumulate = [0]; + if (wrap) { + for (let idx = startIndex; idx < positions.length / 3; idx += 4) { + distX = positions[3 * (idx + 2)] - positions[3 * idx]; + distZ = positions[3 * (idx + 2) + 2] - positions[3 * idx + 2]; + dist = Math.sqrt(distX * distX + distZ * distZ); + totalLen += dist; + cumulate.push(totalLen); + } + } + // set face colours and textures + let idx = 0; + let face = 0; + for (let index = 0; index < normals.length; index += 3) { + //Edge Face no. 1 + if (Math.abs(normals[index + 1]) < 0.001) { + face = 1; + } + //Top Face no. 0 + if (Math.abs(normals[index + 1] - 1) < 0.001) { + face = 0; + } + //Bottom Face no. 2 + if (Math.abs(normals[index + 1] + 1) < 0.001) { + face = 2; + } + idx = index / 3; + if (face === 1) { + disp = idx - startIndex; + if (disp % 4 < 1.5) { + if (wrap) { + uvs[2 * idx] = faceUV[face].x + ((faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4)]) / totalLen; + } + else { + uvs[2 * idx] = faceUV[face].x; + } + } + else { + if (wrap) { + uvs[2 * idx] = faceUV[face].x + ((faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4) + 1]) / totalLen; + } + else { + uvs[2 * idx] = faceUV[face].z; + } + } + if (disp % 2 === 0) { + uvs[2 * idx + 1] = faceUV[face].w; + } + else { + uvs[2 * idx + 1] = faceUV[face].y; + } + } + else { + uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z; + uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w; + } + if (faceColors) { + colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a); + } + } + // sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs); + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + if (faceColors) { + const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors; + vertexData.colors = totalColors; + } + return vertexData; +} +/** + * Creates a polygon mesh + * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh + * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors + * * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4) + * * Remember you can only change the shape positions, not their number when updating a polygon + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @param earcutInjection can be used to inject your own earcut reference + * @returns the polygon mesh + */ +function CreatePolygon(name, options, scene = null, earcutInjection = earcut) { + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + const shape = options.shape; + const holes = options.holes || []; + const depth = options.depth || 0; + const smoothingThreshold = options.smoothingThreshold || 2; + const contours = []; + let hole = []; + for (let i = 0; i < shape.length; i++) { + contours[i] = new Vector2(shape[i].x, shape[i].z); + } + const epsilon = 0.00000001; + if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) { + contours.pop(); + } + const polygonTriangulation = new PolygonMeshBuilder(name, contours, scene || EngineStore.LastCreatedScene, earcutInjection); + for (let hNb = 0; hNb < holes.length; hNb++) { + hole = []; + for (let hPoint = 0; hPoint < holes[hNb].length; hPoint++) { + hole.push(new Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z)); + } + polygonTriangulation.addHole(hole); + } + //updatability is set during applyToMesh; setting to true in triangulation build produces errors + const polygon = polygonTriangulation.build(false, depth, smoothingThreshold); + polygon._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreatePolygonVertexData(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs, options.wrap); + vertexData.applyToMesh(polygon, options.updatable); + return polygon; +} +/** + * Creates an extruded polygon mesh, with depth in the Y direction. + * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements) + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @param earcutInjection can be used to inject your own earcut reference + * @returns the polygon mesh + */ +function ExtrudePolygon(name, options, scene = null, earcutInjection = earcut) { + return CreatePolygon(name, options, scene, earcutInjection); +} +VertexData.CreatePolygon = CreatePolygonVertexData; +Mesh.CreatePolygon = (name, shape, scene, holes, updatable, sideOrientation, earcutInjection = earcut) => { + const options = { + shape: shape, + holes: holes, + updatable: updatable, + sideOrientation: sideOrientation, + }; + return CreatePolygon(name, options, scene, earcutInjection); +}; +Mesh.ExtrudePolygon = (name, shape, depth, scene, holes, updatable, sideOrientation, earcutInjection = earcut) => { + const options = { + shape: shape, + holes: holes, + depth: depth, + updatable: updatable, + sideOrientation: sideOrientation, + }; + return ExtrudePolygon(name, options, scene, earcutInjection); +}; + +/** + * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. + * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. + * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. + * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. + * * The parameter `scale` (float, default 1) is the value to scale the shape. + * * The parameter `closeShape` (boolean, default false) closes the shape when true, since v5.0.0. + * * The parameter `closePath` (boolean, default false) closes the path when true and no caps, since v5.0.0. + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#extruded-shape + * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. + * * The optional parameter `firstNormal` (Vector3) defines the direction of the first normal of the supplied path. Consider using this for any path that is straight, and particular for paths in the xy plane. + * * The optional `adjustFrame` (boolean, default false) will cause the internally generated Path3D tangents, normals, and binormals to be adjusted so that a) they are always well-defined, and b) they do not reverse from one path point to the next. This prevents the extruded shape from being flipped and/or rotated with resulting mesh self-intersections. This is primarily useful for straight paths that can reverse direction. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the extruded shape mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes + */ +function ExtrudeShape(name, options, scene = null) { + const path = options.path; + const shape = options.shape; + const scale = options.scale || 1; + const rotation = options.rotation || 0; + const cap = options.cap === 0 ? 0 : options.cap || Mesh.NO_CAP; + const updatable = options.updatable; + const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + const instance = options.instance || null; + const invertUV = options.invertUV || false; + const closeShape = options.closeShape || false; + const closePath = options.closePath || false; + const capFunction = options.capFunction || null; + return _ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, closePath, closeShape, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null, options.firstNormal || null, options.adjustFrame ? true : false, capFunction); +} +/** + * Creates an custom extruded shape mesh. + * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. + * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. + * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. + * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the beginning of the path + * * It must returns a float value that will be the rotation in radians applied to the shape on each path point. + * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the beginning of the path + * * It must returns a float value that will be the scale value applied to the shape on each path point + * * The parameter `closeShape` (boolean, default false) closes the shape when true, since v5.0.0. + * * The parameter `closePath` (boolean, default false) closes the path when true and no caps, since v5.0.0. + * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray` - depreciated in favor of closeShape + * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray` - depreciated in favor of closePath + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#extruded-shape + * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * * The optional parameter `firstNormal` (Vector3) defines the direction of the first normal of the supplied path. It should be supplied when the path is in the xy plane, and particularly if these sections are straight, because the underlying Path3D object will pick a normal in the xy plane that causes the extrusion to be collapsed into the plane. This should be used for any path that is straight. + * * The optional `adjustFrame` (boolean, default false) will cause the internally generated Path3D tangents, normals, and binormals to be adjusted so that a) they are always well-defined, and b) they do not reverse from one path point to the next. This prevents the extruded shape from being flipped and/or rotated with resulting mesh self-intersections. This is primarily useful for straight paths that can reverse direction. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the custom extruded shape mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#custom-extruded-shapes + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes + */ +function ExtrudeShapeCustom(name, options, scene = null) { + const path = options.path; + const shape = options.shape; + const scaleFunction = options.scaleFunction || + (() => { + return 1; + }); + const rotationFunction = options.rotationFunction || + (() => { + return 0; + }); + const ribbonCloseArray = options.closePath || options.ribbonCloseArray || false; + const ribbonClosePath = options.closeShape || options.ribbonClosePath || false; + const cap = options.cap === 0 ? 0 : options.cap || Mesh.NO_CAP; + const updatable = options.updatable; + const firstNormal = options.firstNormal || null; + const adjustFrame = options.adjustFrame || false; + const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + const instance = options.instance; + const invertUV = options.invertUV || false; + const capFunction = options.capFunction || null; + return _ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null, firstNormal, adjustFrame, capFunction || null); +} +function _ExtrudeShapeGeneric(name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs, firstNormal, adjustFrame, capFunction) { + // extrusion geometry + const extrusionPathArray = (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom, adjustFrame) => { + const tangents = path3D.getTangents(); + const normals = path3D.getNormals(); + const binormals = path3D.getBinormals(); + const distances = path3D.getDistances(); + if (adjustFrame) { + /* fix tangents,normals, binormals */ + for (let i = 0; i < tangents.length; i++) { + if (tangents[i].x == 0 && tangents[i].y == 0 && tangents[i].z == 0) { + tangents[i].copyFrom(tangents[i - 1]); + } + if (normals[i].x == 0 && normals[i].y == 0 && normals[i].z == 0) { + normals[i].copyFrom(normals[i - 1]); + } + if (binormals[i].x == 0 && binormals[i].y == 0 && binormals[i].z == 0) { + binormals[i].copyFrom(binormals[i - 1]); + } + if (i > 0) { + let v = tangents[i - 1]; + if (Vector3.Dot(v, tangents[i]) < 0) { + tangents[i].scaleInPlace(-1); + } + v = normals[i - 1]; + if (Vector3.Dot(v, normals[i]) < 0) { + normals[i].scaleInPlace(-1); + } + v = binormals[i - 1]; + if (Vector3.Dot(v, binormals[i]) < 0) { + binormals[i].scaleInPlace(-1); + } + } + } + } + let angle = 0; + const returnScale = () => { + return scale !== null ? scale : 1; + }; + const returnRotation = () => { + return rotation !== null ? rotation : 0; + }; + const rotate = custom && rotateFunction ? rotateFunction : returnRotation; + const scl = custom && scaleFunction ? scaleFunction : returnScale; + let index = cap === Mesh.NO_CAP || cap === Mesh.CAP_END ? 0 : 2; + const rotationMatrix = TmpVectors.Matrix[0]; + for (let i = 0; i < curve.length; i++) { + const shapePath = []; + const angleStep = rotate(i, distances[i]); + const scaleRatio = scl(i, distances[i]); + Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix); + for (let p = 0; p < shape.length; p++) { + const planed = tangents[i].scale(shape[p].z).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)); + const rotated = Vector3.Zero(); + Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated); + rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]); + shapePath[p] = rotated; + } + shapePaths[index] = shapePath; + angle += angleStep; + index++; + } + // cap + const defaultCapPath = (shapePath) => { + const pointCap = Array(); + const barycenter = Vector3.Zero(); + let i; + for (i = 0; i < shapePath.length; i++) { + barycenter.addInPlace(shapePath[i]); + } + barycenter.scaleInPlace(1.0 / shapePath.length); + for (i = 0; i < shapePath.length; i++) { + pointCap.push(barycenter); + } + return pointCap; + }; + const capPath = capFunction || defaultCapPath; + switch (cap) { + case Mesh.NO_CAP: + break; + case Mesh.CAP_START: + shapePaths[0] = capPath(shapePaths[2]); + shapePaths[1] = shapePaths[2]; + break; + case Mesh.CAP_END: + shapePaths[index] = shapePaths[index - 1]; + shapePaths[index + 1] = capPath(shapePaths[index - 1]); + break; + case Mesh.CAP_ALL: + shapePaths[0] = capPath(shapePaths[2]); + shapePaths[1] = shapePaths[2]; + shapePaths[index] = shapePaths[index - 1]; + shapePaths[index + 1] = capPath(shapePaths[index - 1]); + break; + } + return shapePaths; + }; + let path3D; + let pathArray; + if (instance) { + // instance update + const storage = instance._creationDataStorage; + path3D = firstNormal ? storage.path3D.update(curve, firstNormal) : storage.path3D.update(curve); + pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom, adjustFrame); + instance = CreateRibbon("", { pathArray, closeArray: false, closePath: false, offset: 0, updatable: false, sideOrientation: 0, instance }, scene || undefined); + return instance; + } + // extruded shape creation + path3D = firstNormal ? new Path3D(curve, firstNormal) : new Path3D(curve); + const newShapePaths = new Array(); + cap = cap < 0 || cap > 3 ? 0 : cap; + pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom, adjustFrame); + const extrudedGeneric = CreateRibbon(name, { + pathArray: pathArray, + closeArray: rbCA, + closePath: rbCP, + updatable: updtbl, + sideOrientation: side, + invertUV: invertUV, + frontUVs: frontUVs || undefined, + backUVs: backUVs || undefined, + }, scene); + extrudedGeneric._creationDataStorage.pathArray = pathArray; + extrudedGeneric._creationDataStorage.path3D = path3D; + extrudedGeneric._creationDataStorage.cap = cap; + return extrudedGeneric; +} +Mesh.ExtrudeShape = (name, shape, path, scale, rotation, cap, scene = null, updatable, sideOrientation, instance) => { + const options = { + shape: shape, + path: path, + scale: scale, + rotation: rotation, + cap: cap === 0 ? 0 : cap || Mesh.NO_CAP, + sideOrientation: sideOrientation, + instance: instance, + updatable: updatable, + }; + return ExtrudeShape(name, options, scene); +}; +Mesh.ExtrudeShapeCustom = (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) => { + const options = { + shape: shape, + path: path, + scaleFunction: scaleFunction, + rotationFunction: rotationFunction, + ribbonCloseArray: ribbonCloseArray, + ribbonClosePath: ribbonClosePath, + cap: cap === 0 ? 0 : cap || Mesh.NO_CAP, + sideOrientation: sideOrientation, + instance: instance, + updatable: updatable, + }; + return ExtrudeShapeCustom(name, options, scene); +}; + +/** + * Creates lathe mesh. + * The lathe is a shape with a symmetry axis : a 2D model shape is rotated around this axis to design the lathe + * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero + * * The parameter `radius` (positive float, default 1) is the radius value of the lathe + * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe + * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides + * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape + * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc" + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the lathe mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#lathe + */ +function CreateLathe(name, options, scene = null) { + const arc = options.arc ? (options.arc <= 0 || options.arc > 1 ? 1.0 : options.arc) : 1.0; + const closed = options.closed === undefined ? true : options.closed; + const shape = options.shape; + const radius = options.radius || 1; + const tessellation = options.tessellation || 64; + const clip = options.clip || 0; + const updatable = options.updatable; + const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + const cap = options.cap || Mesh.NO_CAP; + const pi2 = Math.PI * 2; + const paths = []; + const invertUV = options.invertUV || false; + let i = 0; + let p = 0; + const step = (pi2 / tessellation) * arc; + let rotated; + let path; + for (i = 0; i <= tessellation - clip; i++) { + path = []; + if (cap == Mesh.CAP_START || cap == Mesh.CAP_ALL) { + path.push(new Vector3(0, shape[0].y, 0)); + path.push(new Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius)); + } + for (p = 0; p < shape.length; p++) { + rotated = new Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius); + path.push(rotated); + } + if (cap == Mesh.CAP_END || cap == Mesh.CAP_ALL) { + path.push(new Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius)); + path.push(new Vector3(0, shape[shape.length - 1].y, 0)); + } + paths.push(path); + } + // lathe ribbon + const lathe = CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene); + return lathe; +} +Mesh.CreateLathe = (name, shape, radius, tessellation, scene, updatable, sideOrientation) => { + const options = { + shape: shape, + radius: radius, + tessellation: tessellation, + sideOrientation: sideOrientation, + updatable: updatable, + }; + return CreateLathe(name, options, scene); +}; + +/** + * Creates a tube mesh. + * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters + * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube + * * The parameter `radius` (positive float, default 1) sets the tube radius size + * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface + * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overrides the parameter `radius` + * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float) + * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc + * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL + * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter. The `path`Array HAS to have the SAME number of points as the previous one: https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#tube + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. The NUMBER of points CAN'T CHANGE, only their positions. + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param options.path + * @param options.radius + * @param options.tessellation + * @param options.radiusFunction + * @param options.cap + * @param options.arc + * @param options.updatable + * @param options.sideOrientation + * @param options.frontUVs + * @param options.backUVs + * @param options.instance + * @param options.invertUV + * @param scene defines the hosting scene + * @returns the tube mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#tube + */ +function CreateTube(name, options, scene = null) { + const path = options.path; + let instance = options.instance; + let radius = 1.0; + if (options.radius !== undefined) { + radius = options.radius; + } + else if (instance) { + radius = instance._creationDataStorage.radius; + } + const tessellation = options.tessellation || 64 | 0; + const radiusFunction = options.radiusFunction || null; + let cap = options.cap || Mesh.NO_CAP; + const invertUV = options.invertUV || false; + const updatable = options.updatable; + const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0; + // tube geometry + const tubePathArray = (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) => { + const tangents = path3D.getTangents(); + const normals = path3D.getNormals(); + const distances = path3D.getDistances(); + const pi2 = Math.PI * 2; + const step = (pi2 / tessellation) * arc; + const returnRadius = () => radius; + const radiusFunctionFinal = radiusFunction || returnRadius; + let circlePath; + let rad; + let normal; + let rotated; + const rotationMatrix = TmpVectors.Matrix[0]; + let index = cap === Mesh.NO_CAP || cap === Mesh.CAP_END ? 0 : 2; + for (let i = 0; i < path.length; i++) { + rad = radiusFunctionFinal(i, distances[i]); // current radius + circlePath = Array(); // current circle array + normal = normals[i]; // current normal + for (let t = 0; t < tessellation; t++) { + Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix); + rotated = circlePath[t] ? circlePath[t] : Vector3.Zero(); + Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated); + rotated.scaleInPlace(rad).addInPlace(path[i]); + circlePath[t] = rotated; + } + circlePaths[index] = circlePath; + index++; + } + // cap + const capPath = (nbPoints, pathIndex) => { + const pointCap = Array(); + for (let i = 0; i < nbPoints; i++) { + pointCap.push(path[pathIndex]); + } + return pointCap; + }; + switch (cap) { + case Mesh.NO_CAP: + break; + case Mesh.CAP_START: + circlePaths[0] = capPath(tessellation, 0); + circlePaths[1] = circlePaths[2].slice(0); + break; + case Mesh.CAP_END: + circlePaths[index] = circlePaths[index - 1].slice(0); + circlePaths[index + 1] = capPath(tessellation, path.length - 1); + break; + case Mesh.CAP_ALL: + circlePaths[0] = capPath(tessellation, 0); + circlePaths[1] = circlePaths[2].slice(0); + circlePaths[index] = circlePaths[index - 1].slice(0); + circlePaths[index + 1] = capPath(tessellation, path.length - 1); + break; + } + return circlePaths; + }; + let path3D; + let pathArray; + if (instance) { + // tube update + const storage = instance._creationDataStorage; + const arc = options.arc || storage.arc; + path3D = storage.path3D.update(path); + pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc); + instance = CreateRibbon("", { pathArray: pathArray, instance: instance }); + // Update mode, no need to recreate the storage. + storage.path3D = path3D; + storage.pathArray = pathArray; + storage.arc = arc; + storage.radius = radius; + return instance; + } + // tube creation + path3D = new Path3D(path); + const newPathArray = new Array(); + cap = cap < 0 || cap > 3 ? 0 : cap; + pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc); + const tube = CreateRibbon(name, { + pathArray: pathArray, + closePath: true, + closeArray: false, + updatable: updatable, + sideOrientation: sideOrientation, + invertUV: invertUV, + frontUVs: options.frontUVs, + backUVs: options.backUVs, + }, scene); + tube._creationDataStorage.pathArray = pathArray; + tube._creationDataStorage.path3D = path3D; + tube._creationDataStorage.tessellation = tessellation; + tube._creationDataStorage.cap = cap; + tube._creationDataStorage.arc = options.arc; + tube._creationDataStorage.radius = radius; + return tube; +} +Mesh.CreateTube = (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) => { + const options = { + path: path, + radius: radius, + tessellation: tessellation, + radiusFunction: radiusFunction, + arc: 1, + cap: cap, + updatable: updatable, + sideOrientation: sideOrientation, + instance: instance, + }; + return CreateTube(name, options, scene); +}; + +// inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html +/** + * Creates the VertexData for a Polyhedron + * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty + * * type provided types are: + * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) + * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20) + * * size the size of the IcoSphere, optional default 1 + * * sizeX allows stretching in the x direction, optional, default size + * * sizeY allows stretching in the y direction, optional, default size + * * sizeZ allows stretching in the z direction, optional, default size + * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor + * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * * flat when true creates a flat shaded mesh, optional, default true + * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the Polyhedron + */ +function CreatePolyhedronVertexData(options) { + // provided polyhedron types : + // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) + // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20) + const polyhedra = []; + polyhedra[0] = { + vertex: [ + [0, 0, 1.732051], + [1.632993, 0, -0.5773503], + [-0.8164966, 1.414214, -0.5773503], + [-0.8164966, -1.414214, -0.5773503], + ], + face: [ + [0, 1, 2], + [0, 2, 3], + [0, 3, 1], + [1, 3, 2], + ], + }; + polyhedra[1] = { + vertex: [ + [0, 0, 1.414214], + [1.414214, 0, 0], + [0, 1.414214, 0], + [-1.414214, 0, 0], + [0, -1.414214, 0], + [0, 0, -1.414214], + ], + face: [ + [0, 1, 2], + [0, 2, 3], + [0, 3, 4], + [0, 4, 1], + [1, 4, 5], + [1, 5, 2], + [2, 5, 3], + [3, 5, 4], + ], + }; + polyhedra[2] = { + vertex: [ + [0, 0, 1.070466], + [0.7136442, 0, 0.7978784], + [-0.3568221, 0.618034, 0.7978784], + [-0.3568221, -0.618034, 0.7978784], + [0.7978784, 0.618034, 0.3568221], + [0.7978784, -0.618034, 0.3568221], + [-0.9341724, 0.381966, 0.3568221], + [0.1362939, 1, 0.3568221], + [0.1362939, -1, 0.3568221], + [-0.9341724, -0.381966, 0.3568221], + [0.9341724, 0.381966, -0.3568221], + [0.9341724, -0.381966, -0.3568221], + [-0.7978784, 0.618034, -0.3568221], + [-0.1362939, 1, -0.3568221], + [-0.1362939, -1, -0.3568221], + [-0.7978784, -0.618034, -0.3568221], + [0.3568221, 0.618034, -0.7978784], + [0.3568221, -0.618034, -0.7978784], + [-0.7136442, 0, -0.7978784], + [0, 0, -1.070466], + ], + face: [ + [0, 1, 4, 7, 2], + [0, 2, 6, 9, 3], + [0, 3, 8, 5, 1], + [1, 5, 11, 10, 4], + [2, 7, 13, 12, 6], + [3, 9, 15, 14, 8], + [4, 10, 16, 13, 7], + [5, 8, 14, 17, 11], + [6, 12, 18, 15, 9], + [10, 11, 17, 19, 16], + [12, 13, 16, 19, 18], + [14, 15, 18, 19, 17], + ], + }; + polyhedra[3] = { + vertex: [ + [0, 0, 1.175571], + [1.051462, 0, 0.5257311], + [0.3249197, 1, 0.5257311], + [-0.8506508, 0.618034, 0.5257311], + [-0.8506508, -0.618034, 0.5257311], + [0.3249197, -1, 0.5257311], + [0.8506508, 0.618034, -0.5257311], + [0.8506508, -0.618034, -0.5257311], + [-0.3249197, 1, -0.5257311], + [-1.051462, 0, -0.5257311], + [-0.3249197, -1, -0.5257311], + [0, 0, -1.175571], + ], + face: [ + [0, 1, 2], + [0, 2, 3], + [0, 3, 4], + [0, 4, 5], + [0, 5, 1], + [1, 5, 7], + [1, 7, 6], + [1, 6, 2], + [2, 6, 8], + [2, 8, 3], + [3, 8, 9], + [3, 9, 4], + [4, 9, 10], + [4, 10, 5], + [5, 10, 7], + [6, 7, 11], + [6, 11, 8], + [7, 10, 11], + [8, 11, 9], + [9, 11, 10], + ], + }; + polyhedra[4] = { + vertex: [ + [0, 0, 1.070722], + [0.7148135, 0, 0.7971752], + [-0.104682, 0.7071068, 0.7971752], + [-0.6841528, 0.2071068, 0.7971752], + [-0.104682, -0.7071068, 0.7971752], + [0.6101315, 0.7071068, 0.5236279], + [1.04156, 0.2071068, 0.1367736], + [0.6101315, -0.7071068, 0.5236279], + [-0.3574067, 1, 0.1367736], + [-0.7888348, -0.5, 0.5236279], + [-0.9368776, 0.5, 0.1367736], + [-0.3574067, -1, 0.1367736], + [0.3574067, 1, -0.1367736], + [0.9368776, -0.5, -0.1367736], + [0.7888348, 0.5, -0.5236279], + [0.3574067, -1, -0.1367736], + [-0.6101315, 0.7071068, -0.5236279], + [-1.04156, -0.2071068, -0.1367736], + [-0.6101315, -0.7071068, -0.5236279], + [0.104682, 0.7071068, -0.7971752], + [0.6841528, -0.2071068, -0.7971752], + [0.104682, -0.7071068, -0.7971752], + [-0.7148135, 0, -0.7971752], + [0, 0, -1.070722], + ], + face: [ + [0, 2, 3], + [1, 6, 5], + [4, 9, 11], + [7, 15, 13], + [8, 16, 10], + [12, 14, 19], + [17, 22, 18], + [20, 21, 23], + [0, 1, 5, 2], + [0, 3, 9, 4], + [0, 4, 7, 1], + [1, 7, 13, 6], + [2, 5, 12, 8], + [2, 8, 10, 3], + [3, 10, 17, 9], + [4, 11, 15, 7], + [5, 6, 14, 12], + [6, 13, 20, 14], + [8, 12, 19, 16], + [9, 17, 18, 11], + [10, 16, 22, 17], + [11, 18, 21, 15], + [13, 15, 21, 20], + [14, 20, 23, 19], + [16, 19, 23, 22], + [18, 22, 23, 21], + ], + }; + polyhedra[5] = { + vertex: [ + [0, 0, 1.322876], + [1.309307, 0, 0.1889822], + [-0.9819805, 0.8660254, 0.1889822], + [0.1636634, -1.299038, 0.1889822], + [0.3273268, 0.8660254, -0.9449112], + [-0.8183171, -0.4330127, -0.9449112], + ], + face: [ + [0, 3, 1], + [2, 4, 5], + [0, 1, 4, 2], + [0, 2, 5, 3], + [1, 3, 5, 4], + ], + }; + polyhedra[6] = { + vertex: [ + [0, 0, 1.159953], + [1.013464, 0, 0.5642542], + [-0.3501431, 0.9510565, 0.5642542], + [-0.7715208, -0.6571639, 0.5642542], + [0.6633206, 0.9510565, -0.03144481], + [0.8682979, -0.6571639, -0.3996071], + [-1.121664, 0.2938926, -0.03144481], + [-0.2348831, -1.063314, -0.3996071], + [0.5181548, 0.2938926, -0.9953061], + [-0.5850262, -0.112257, -0.9953061], + ], + face: [ + [0, 1, 4, 2], + [0, 2, 6, 3], + [1, 5, 8, 4], + [3, 6, 9, 7], + [5, 7, 9, 8], + [0, 3, 7, 5, 1], + [2, 4, 8, 9, 6], + ], + }; + polyhedra[7] = { + vertex: [ + [0, 0, 1.118034], + [0.8944272, 0, 0.6708204], + [-0.2236068, 0.8660254, 0.6708204], + [-0.7826238, -0.4330127, 0.6708204], + [0.6708204, 0.8660254, 0.2236068], + [1.006231, -0.4330127, -0.2236068], + [-1.006231, 0.4330127, 0.2236068], + [-0.6708204, -0.8660254, -0.2236068], + [0.7826238, 0.4330127, -0.6708204], + [0.2236068, -0.8660254, -0.6708204], + [-0.8944272, 0, -0.6708204], + [0, 0, -1.118034], + ], + face: [ + [0, 1, 4, 2], + [0, 2, 6, 3], + [1, 5, 8, 4], + [3, 6, 10, 7], + [5, 9, 11, 8], + [7, 10, 11, 9], + [0, 3, 7, 9, 5, 1], + [2, 4, 8, 11, 10, 6], + ], + }; + polyhedra[8] = { + vertex: [ + [-0.729665, 0.670121, 0.319155], + [-0.655235, -0.29213, -0.754096], + [-0.093922, -0.607123, 0.537818], + [0.702196, 0.595691, 0.485187], + [0.776626, -0.36656, -0.588064], + ], + face: [ + [1, 4, 2], + [0, 1, 2], + [3, 0, 2], + [4, 3, 2], + [4, 1, 0, 3], + ], + }; + polyhedra[9] = { + vertex: [ + [-0.868849, -0.100041, 0.61257], + [-0.329458, 0.976099, 0.28078], + [-0.26629, -0.013796, -0.477654], + [-0.13392, -1.034115, 0.229829], + [0.738834, 0.707117, -0.307018], + [0.859683, -0.535264, -0.338508], + ], + face: [ + [3, 0, 2], + [5, 3, 2], + [4, 5, 2], + [1, 4, 2], + [0, 1, 2], + [0, 3, 5, 4, 1], + ], + }; + polyhedra[10] = { + vertex: [ + [-0.610389, 0.243975, 0.531213], + [-0.187812, -0.48795, -0.664016], + [-0.187812, 0.9759, -0.664016], + [0.187812, -0.9759, 0.664016], + [0.798201, 0.243975, 0.132803], + ], + face: [ + [1, 3, 0], + [3, 4, 0], + [3, 1, 4], + [0, 2, 1], + [0, 4, 2], + [2, 4, 1], + ], + }; + polyhedra[11] = { + vertex: [ + [-1.028778, 0.392027, -0.048786], + [-0.640503, -0.646161, 0.621837], + [-0.125162, -0.395663, -0.540059], + [0.004683, 0.888447, -0.651988], + [0.125161, 0.395663, 0.540059], + [0.632925, -0.791376, 0.433102], + [1.031672, 0.157063, -0.354165], + ], + face: [ + [3, 2, 0], + [2, 1, 0], + [2, 5, 1], + [0, 4, 3], + [0, 1, 4], + [4, 1, 5], + [2, 3, 6], + [3, 4, 6], + [5, 2, 6], + [4, 5, 6], + ], + }; + polyhedra[12] = { + vertex: [ + [-0.669867, 0.334933, -0.529576], + [-0.669867, 0.334933, 0.529577], + [-0.4043, 1.212901, 0], + [-0.334933, -0.669867, -0.529576], + [-0.334933, -0.669867, 0.529577], + [0.334933, 0.669867, -0.529576], + [0.334933, 0.669867, 0.529577], + [0.4043, -1.212901, 0], + [0.669867, -0.334933, -0.529576], + [0.669867, -0.334933, 0.529577], + ], + face: [ + [8, 9, 7], + [6, 5, 2], + [3, 8, 7], + [5, 0, 2], + [4, 3, 7], + [0, 1, 2], + [9, 4, 7], + [1, 6, 2], + [9, 8, 5, 6], + [8, 3, 0, 5], + [3, 4, 1, 0], + [4, 9, 6, 1], + ], + }; + polyhedra[13] = { + vertex: [ + [-0.931836, 0.219976, -0.264632], + [-0.636706, 0.318353, 0.692816], + [-0.613483, -0.735083, -0.264632], + [-0.326545, 0.979634, 0], + [-0.318353, -0.636706, 0.692816], + [-0.159176, 0.477529, -0.856368], + [0.159176, -0.477529, -0.856368], + [0.318353, 0.636706, 0.692816], + [0.326545, -0.979634, 0], + [0.613482, 0.735082, -0.264632], + [0.636706, -0.318353, 0.692816], + [0.931835, -0.219977, -0.264632], + ], + face: [ + [11, 10, 8], + [7, 9, 3], + [6, 11, 8], + [9, 5, 3], + [2, 6, 8], + [5, 0, 3], + [4, 2, 8], + [0, 1, 3], + [10, 4, 8], + [1, 7, 3], + [10, 11, 9, 7], + [11, 6, 5, 9], + [6, 2, 0, 5], + [2, 4, 1, 0], + [4, 10, 7, 1], + ], + }; + polyhedra[14] = { + vertex: [ + [-0.93465, 0.300459, -0.271185], + [-0.838689, -0.260219, -0.516017], + [-0.711319, 0.717591, 0.128359], + [-0.710334, -0.156922, 0.080946], + [-0.599799, 0.556003, -0.725148], + [-0.503838, -4675e-6, -0.969981], + [-0.487004, 0.26021, 0.48049], + [-0.460089, -0.750282, -0.512622], + [-0.376468, 0.973135, -0.325605], + [-0.331735, -0.646985, 0.084342], + [-0.254001, 0.831847, 0.530001], + [-0.125239, -0.494738, -0.966586], + [0.029622, 0.027949, 0.730817], + [0.056536, -0.982543, -0.262295], + [0.08085, 1.087391, 0.076037], + [0.125583, -0.532729, 0.485984], + [0.262625, 0.599586, 0.780328], + [0.391387, -0.726999, -0.716259], + [0.513854, -0.868287, 0.139347], + [0.597475, 0.85513, 0.326364], + [0.641224, 0.109523, 0.783723], + [0.737185, -0.451155, 0.538891], + [0.848705, -0.612742, -0.314616], + [0.976075, 0.365067, 0.32976], + [1.072036, -0.19561, 0.084927], + ], + face: [ + [15, 18, 21], + [12, 20, 16], + [6, 10, 2], + [3, 0, 1], + [9, 7, 13], + [2, 8, 4, 0], + [0, 4, 5, 1], + [1, 5, 11, 7], + [7, 11, 17, 13], + [13, 17, 22, 18], + [18, 22, 24, 21], + [21, 24, 23, 20], + [20, 23, 19, 16], + [16, 19, 14, 10], + [10, 14, 8, 2], + [15, 9, 13, 18], + [12, 15, 21, 20], + [6, 12, 16, 10], + [3, 6, 2, 0], + [9, 3, 1, 7], + [9, 15, 12, 6, 3], + [22, 17, 11, 5, 4, 8, 14, 19, 23, 24], + ], + }; + const type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0; + const size = options.size; + const sizeX = options.sizeX || size || 1; + const sizeY = options.sizeY || size || 1; + const sizeZ = options.sizeZ || size || 1; + const data = options.custom || polyhedra[type]; + const nbfaces = data.face.length; + const faceUV = options.faceUV || new Array(nbfaces); + const faceColors = options.faceColors; + const flat = options.flat === undefined ? true : options.flat; + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + const positions = []; + const indices = []; + const normals = []; + const uvs = []; + const colors = []; + let index = 0; + let faceIdx = 0; // face cursor in the array "indexes" + const indexes = []; + let i = 0; + let f = 0; + let u, v, ang, x, y, tmp; + // default face colors and UV if undefined + if (flat) { + for (f = 0; f < nbfaces; f++) { + if (faceColors && faceColors[f] === undefined) { + faceColors[f] = new Color4(1, 1, 1, 1); + } + if (faceUV && faceUV[f] === undefined) { + faceUV[f] = new Vector4(0, 0, 1, 1); + } + } + } + if (!flat) { + for (i = 0; i < data.vertex.length; i++) { + positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ); + uvs.push(0, 0); + } + for (f = 0; f < nbfaces; f++) { + for (i = 0; i < data.face[f].length - 2; i++) { + indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]); + } + } + } + else { + for (f = 0; f < nbfaces; f++) { + const fl = data.face[f].length; // number of vertices of the current face + ang = (2 * Math.PI) / fl; + x = 0.5 * Math.tan(ang / 2); + y = 0.5; + // positions, uvs, colors + for (i = 0; i < fl; i++) { + // positions + positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ); + indexes.push(index); + index++; + // uvs + u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x); + v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5); + uvs.push(u, v); + tmp = x * Math.cos(ang) - y * Math.sin(ang); + y = x * Math.sin(ang) + y * Math.cos(ang); + x = tmp; + // colors + if (faceColors) { + colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a); + } + } + // indices from indexes + for (i = 0; i < fl - 2; i++) { + indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]); + } + faceIdx += fl; + } + } + VertexData.ComputeNormals(positions, indices, normals); + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + const vertexData = new VertexData(); + vertexData.positions = positions; + vertexData.indices = indices; + vertexData.normals = normals; + vertexData.uvs = uvs; + if (faceColors && flat) { + vertexData.colors = colors; + } + return vertexData; +} +/** + * Creates a polyhedron mesh + * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type + * * The parameter `size` (positive float, default 1) sets the polygon size + * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value) + * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overrides the parameter `type` + * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron + * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`) + * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace + * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the polyhedron mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra + */ +function CreatePolyhedron(name, options = {}, scene = null) { + const polyhedron = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + polyhedron._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreatePolyhedronVertexData(options); + vertexData.applyToMesh(polyhedron, options.updatable); + return polyhedron; +} +VertexData.CreatePolyhedron = CreatePolyhedronVertexData; +Mesh.CreatePolyhedron = (name, options, scene) => { + return CreatePolyhedron(name, options, scene); +}; + +/** + * Creates the VertexData of the IcoSphere + * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty + * * radius the radius of the IcoSphere, optional default 1 + * * radiusX allows stretching in the x direction, optional, default radius + * * radiusY allows stretching in the y direction, optional, default radius + * * radiusZ allows stretching in the z direction, optional, default radius + * * flat when true creates a flat shaded mesh, optional, default true + * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @returns the VertexData of the IcoSphere + */ +function CreateIcoSphereVertexData(options) { + const sideOrientation = options.sideOrientation || VertexData.DEFAULTSIDE; + const radius = options.radius || 1; + const flat = options.flat === undefined ? true : options.flat; + const subdivisions = (options.subdivisions || 4) | 0; + const radiusX = options.radiusX || radius; + const radiusY = options.radiusY || radius; + const radiusZ = options.radiusZ || radius; + const t = (1 + Math.sqrt(5)) / 2; + // 12 vertex x,y,z + const icoVertices = [ + -1, + t, + -0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + 0, // v0-3 + 0, + -1, + -t, + 0, + 1, + -t, + 0, + -1, + t, + 0, + 1, + t, // v4-7 + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + 0, + -1, // v8-11 + ]; + // index of 3 vertex makes a face of icopshere + const ico_indices = [ + 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23, 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8, 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9, 4, 21, 5, 13, 17, + 23, 6, 13, 22, 19, 6, 18, 9, 8, 1, + ]; + // vertex for uv have aliased position, not for UV + const vertices_unalias_id = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + // vertex alias + 0, // 12: 0 + 12 + 2, // 13: 2 + 11 + 3, // 14: 3 + 11 + 3, // 15: 3 + 12 + 3, // 16: 3 + 13 + 4, // 17: 4 + 13 + 7, // 18: 7 + 11 + 8, // 19: 8 + 11 + 9, // 20: 9 + 11 + 9, // 21: 9 + 12 + 10, // 22: A + 12 + 11, // 23: B + 12 + ]; + // uv as integer step (not pixels !) + const ico_vertexuv = [ + 5, + 1, + 3, + 1, + 6, + 4, + 0, + 0, // v0-3 + 5, + 3, + 4, + 2, + 2, + 2, + 4, + 0, // v4-7 + 2, + 0, + 1, + 1, + 6, + 0, + 6, + 2, // v8-11 + // vertex alias (for same vertex on different faces) + 0, + 4, // 12: 0 + 12 + 3, + 3, // 13: 2 + 11 + 4, + 4, // 14: 3 + 11 + 3, + 1, // 15: 3 + 12 + 4, + 2, // 16: 3 + 13 + 4, + 4, // 17: 4 + 13 + 0, + 2, // 18: 7 + 11 + 1, + 1, // 19: 8 + 11 + 2, + 2, // 20: 9 + 11 + 3, + 3, // 21: 9 + 12 + 1, + 3, // 22: A + 12 + 2, + 4, // 23: B + 12 + ]; + // Vertices[0, 1, ...9, A, B] : position on UV plane + // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B) + // First island of uv mapping + // v = 4h 3+ 2 + // v = 3h 9+ 4 + // v = 2h 9+ 5 B + // v = 1h 9 1 0 + // v = 0h 3 8 7 A + // u = 0 1 2 3 4 5 6 *a + // Second island of uv mapping + // v = 4h 0+ B+ 4+ + // v = 3h A+ 2+ + // v = 2h 7+ 6 3+ + // v = 1h 8+ 3+ + // v = 0h + // u = 0 1 2 3 4 5 6 *a + // Face layout on texture UV mapping + // ============ + // \ 4 /\ 16 / ====== + // \ / \ / /\ 11 / + // \/ 7 \/ / \ / + // ======= / 10 \/ + // /\ 17 /\ ======= + // / \ / \ \ 15 /\ + // / 8 \/ 12 \ \ / \ + // ============ \/ 6 \ + // \ 18 /\ ============ + // \ / \ \ 5 /\ 0 / + // \/ 13 \ \ / \ / + // ======= \/ 1 \/ + // ============= + // /\ 19 /\ 2 /\ + // / \ / \ / \ + // / 14 \/ 9 \/ 3 \ + // =================== + // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97 + const ustep = 138 / 1024; + const vstep = 239 / 1024; + const uoffset = 60 / 1024; + const voffset = 26 / 1024; + // Second island should have margin, not to touch the first island + // avoid any borderline artefact in pixel rounding + const island_u_offset = -40 / 1024; + const island_v_offset = 20 / 1024; + // face is either island 0 or 1 : + // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18] + const island = [ + 0, + 0, + 0, + 0, + 1, // 0 - 4 + 0, + 0, + 1, + 1, + 0, // 5 - 9 + 0, + 0, + 1, + 1, + 0, // 10 - 14 + 0, + 1, + 1, + 1, + 0, // 15 - 19 + ]; + const indices = []; + const positions = []; + const normals = []; + const uvs = []; + let current_indice = 0; + // prepare array of 3 vector (empty) (to be worked in place, shared for each face) + const face_vertex_pos = new Array(3); + const face_vertex_uv = new Array(3); + let v012; + for (v012 = 0; v012 < 3; v012++) { + face_vertex_pos[v012] = Vector3.Zero(); + face_vertex_uv[v012] = Vector2.Zero(); + } + // create all with normals + for (let face = 0; face < 20; face++) { + // 3 vertex per face + for (v012 = 0; v012 < 3; v012++) { + // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias) + const v_id = ico_indices[3 * face + v012]; + // vertex have 3D position (x,y,z) + face_vertex_pos[v012].copyFromFloats(icoVertices[3 * vertices_unalias_id[v_id]], icoVertices[3 * vertices_unalias_id[v_id] + 1], icoVertices[3 * vertices_unalias_id[v_id] + 2]); + // Normalize to get normal + face_vertex_pos[v012].normalize(); + // uv Coordinates from vertex ID + face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset); + } + // Subdivide the face (interpolate pos, norm, uv) + // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere) + // - norm is linear interpolation of vertex corner normal + // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? ) + // - uv is linear interpolation + // + // Topology is as below for sub-divide by 2 + // vertex shown as v0,v1,v2 + // interp index is i1 to progress in range [v0,v1[ + // interp index is i2 to progress in range [v0,v2[ + // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1) + // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1) + // + // + // i2 v2 + // ^ ^ + // / / \ + // / / \ + // / / \ + // / / (0,1) \ + // / #---------\ + // / / \ (0,0)'/ \ + // / / \ / \ + // / / \ / \ + // / / (0,0) \ / (1,0) \ + // / #---------#---------\ + // v0 v1 + // + // --------------------> i1 + // + // interp of (i1,i2): + // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S) + // along i1 : lerp(x0,x1, i1/(S-i2)) + // + // centroid of triangle is needed to get help normal computation + // (c1,c2) are used for centroid location + const interp_vertex = (i1, i2, c1, c2) => { + // vertex is interpolated from + // - face_vertex_pos[0..2] + // - face_vertex_uv[0..2] + const pos_x0 = Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions); + const pos_x1 = Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions); + const pos_interp = subdivisions === i2 ? face_vertex_pos[2] : Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2)); + pos_interp.normalize(); + let vertex_normal; + if (flat) { + // in flat mode, recalculate normal as face centroid normal + const centroid_x0 = Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions); + const centroid_x1 = Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions); + vertex_normal = Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2)); + } + else { + // in smooth mode, recalculate normal from each single vertex position + vertex_normal = new Vector3(pos_interp.x, pos_interp.y, pos_interp.z); + } + // Vertex normal need correction due to X,Y,Z radius scaling + vertex_normal.x /= radiusX; + vertex_normal.y /= radiusY; + vertex_normal.z /= radiusZ; + vertex_normal.normalize(); + const uv_x0 = Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions); + const uv_x1 = Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions); + const uv_interp = subdivisions === i2 ? face_vertex_uv[2] : Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2)); + positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ); + normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z); + uvs.push(uv_interp.x, uv_interp.y); + // push each vertex has member of a face + // Same vertex can belong to multiple face, it is pushed multiple time (duplicate vertex are present) + indices.push(current_indice); + current_indice++; + }; + for (let i2 = 0; i2 < subdivisions; i2++) { + for (let i1 = 0; i1 + i2 < subdivisions; i1++) { + // face : (i1,i2) for /\ : + // interp for : (i1,i2),(i1+1,i2),(i1,i2+1) + interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3); + interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3); + interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3); + if (i1 + i2 + 1 < subdivisions) { + // face : (i1,i2)' for \/ : + // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1) + interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3); + interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3); + interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3); + } + } + } + } + // Sides + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); + // Result + const vertexData = new VertexData(); + vertexData.indices = indices; + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.uvs = uvs; + return vertexData; +} +/** + * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided + * * The parameter `radius` sets the radius size (float) of the icosphere (default 1) + * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value of `radius`) + * * The parameter `subdivisions` sets the number of subdivisions (positive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size + * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface + * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE + * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation + * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the icosahedron mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra#icosphere + */ +function CreateIcoSphere(name, options = {}, scene = null) { + const sphere = new Mesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + sphere._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreateIcoSphereVertexData(options); + vertexData.applyToMesh(sphere, options.updatable); + return sphere; +} +VertexData.CreateIcoSphere = CreateIcoSphereVertexData; +Mesh.CreateIcoSphere = (name, options, scene) => { + return CreateIcoSphere(name, options, scene); +}; + +const xpAxis = new Vector3(1, 0, 0); +const xnAxis = new Vector3(-1, 0, 0); +const ypAxis = new Vector3(0, 1, 0); +const ynAxis = new Vector3(0, -1, 0); +const zpAxis = new Vector3(0, 0, 1); +const znAxis = new Vector3(0, 0, -1); +/** @internal */ +class DecalVertex { + constructor(position = Vector3.Zero(), normal = Vector3.Up(), uv = Vector2.Zero(), vertexIdx = 0, vertexIdxForBones = 0, localPositionOverride = null, localNormalOverride = null, matrixIndicesOverride = null, matrixWeightsOverride = null) { + this.position = position; + this.normal = normal; + this.uv = uv; + this.vertexIdx = vertexIdx; + this.vertexIdxForBones = vertexIdxForBones; + this.localPositionOverride = localPositionOverride; + this.localNormalOverride = localNormalOverride; + this.matrixIndicesOverride = matrixIndicesOverride; + this.matrixWeightsOverride = matrixWeightsOverride; + } + clone() { + return new DecalVertex(this.position.clone(), this.normal.clone(), this.uv.clone(), this.vertexIdx, this.vertexIdxForBones, this.localPositionOverride?.slice(), this.localNormalOverride?.slice(), this.matrixIndicesOverride?.slice(), this.matrixWeightsOverride?.slice()); + } +} +/** + * Creates a decal mesh. + * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal + * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates + * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates + * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling + * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal + * * The parameter `captureUVS` defines if we need to capture the uvs or compute them + * * The parameter `cullBackFaces` defines if the back faces should be removed from the decal mesh + * * The parameter `localMode` defines that the computations should be done with the local mesh coordinates instead of the world space coordinates. + * * Use this mode if you want the decal to be parented to the sourceMesh and move/rotate with it. + * Note: Meshes with morph targets are not supported! + * @param name defines the name of the mesh + * @param sourceMesh defines the mesh where the decal must be applied + * @param options defines the options used to create the mesh + * @returns the decal mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/decals + */ +function CreateDecal(name, sourceMesh, options) { + const hasSkeleton = !!sourceMesh.skeleton; + const useLocalComputation = options.localMode || hasSkeleton; + const indices = sourceMesh.getIndices(); + const positions = hasSkeleton ? sourceMesh.getPositionData(true, true) : sourceMesh.getVerticesData(VertexBuffer.PositionKind); + const normals = hasSkeleton ? sourceMesh.getNormalsData(true, true) : sourceMesh.getVerticesData(VertexBuffer.NormalKind); + const localPositions = useLocalComputation ? (hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.PositionKind) : positions) : null; + const localNormals = useLocalComputation ? (hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.NormalKind) : normals) : null; + const uvs = sourceMesh.getVerticesData(VertexBuffer.UVKind); + const matIndices = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesIndicesKind) : null; + const matWeights = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesWeightsKind) : null; + const matIndicesExtra = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null; + const matWeightsExtra = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null; + const position = options.position || Vector3.Zero(); + let normal = options.normal || Vector3.Up(); + const size = options.size || Vector3.One(); + const angle = options.angle || 0; + // Getting correct rotation + if (!normal) { + const target = new Vector3(0, 0, 1); + const camera = sourceMesh.getScene().activeCamera; + const cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix()); + normal = camera.globalPosition.subtract(cameraWorldTarget); + } + const yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2; + const len = Math.sqrt(normal.x * normal.x + normal.z * normal.z); + const pitch = Math.atan2(normal.y, len); + const vertexData = new VertexData(); + vertexData.indices = []; + vertexData.positions = []; + vertexData.normals = []; + vertexData.uvs = []; + vertexData.matricesIndices = hasSkeleton ? [] : null; + vertexData.matricesWeights = hasSkeleton ? [] : null; + vertexData.matricesIndicesExtra = matIndicesExtra ? [] : null; + vertexData.matricesWeightsExtra = matWeightsExtra ? [] : null; + let currentVertexDataIndex = 0; + const extractDecalVector3 = (indexId, transformMatrix) => { + const result = new DecalVertex(); + if (!indices || !positions || !normals) { + return result; + } + const vertexId = indices[indexId]; + result.vertexIdx = vertexId * 3; + result.vertexIdxForBones = vertexId * 4; + // Send vector to decal local world + result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]); + Vector3.TransformCoordinatesToRef(result.position, transformMatrix, result.position); + // Get normal + result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]); + Vector3.TransformNormalToRef(result.normal, transformMatrix, result.normal); + if (options.captureUVS && uvs) { + const v = uvs[vertexId * 2 + 1]; + result.uv = new Vector2(uvs[vertexId * 2], v); + } + return result; + }; + const emptyArray = [0, 0, 0, 0]; + // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js + const clip = (vertices, axis) => { + if (vertices.length === 0) { + return vertices; + } + const clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis)); + const indexOf = (arr, val, start, num) => { + for (let i = 0; i < num; ++i) { + if (arr[start + i] === val) { + return start + i; + } + } + return -1; + }; + const clipVertices = (v0, v1) => { + const clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize); + let indices = emptyArray; + let weights = emptyArray; + if (matIndices && matWeights) { + const mat0Index = v0.matrixIndicesOverride ? 0 : v0.vertexIdxForBones; + const v0Indices = v0.matrixIndicesOverride ?? matIndices; + const v0Weights = v0.matrixWeightsOverride ?? matWeights; + const mat1Index = v1.matrixIndicesOverride ? 0 : v1.vertexIdxForBones; + const v1Indices = v1.matrixIndicesOverride ?? matIndices; + const v1Weights = v1.matrixWeightsOverride ?? matWeights; + indices = [0, 0, 0, 0]; + weights = [0, 0, 0, 0]; + let index = 0; + for (let i = 0; i < 4; ++i) { + if (v0Weights[mat0Index + i] > 0) { + const idx = indexOf(v1Indices, v0Indices[mat0Index + i], mat1Index, 4); + indices[index] = v0Indices[mat0Index + i]; + weights[index] = Lerp(v0Weights[mat0Index + i], idx >= 0 ? v1Weights[idx] : 0, clipFactor); + index++; + } + } + for (let i = 0; i < 4 && index < 4; ++i) { + const ind = v1Indices[mat1Index + i]; + if (indexOf(v0Indices, ind, mat0Index, 4) !== -1) + continue; + indices[index] = ind; + weights[index] = Lerp(0, v1Weights[mat1Index + i], clipFactor); + index++; + } + const sumw = weights[0] + weights[1] + weights[2] + weights[3]; + weights[0] /= sumw; + weights[1] /= sumw; + weights[2] /= sumw; + weights[3] /= sumw; + } + const v0LocalPositionX = v0.localPositionOverride ? v0.localPositionOverride[0] : (localPositions?.[v0.vertexIdx] ?? 0); + const v0LocalPositionY = v0.localPositionOverride ? v0.localPositionOverride[1] : (localPositions?.[v0.vertexIdx + 1] ?? 0); + const v0LocalPositionZ = v0.localPositionOverride ? v0.localPositionOverride[2] : (localPositions?.[v0.vertexIdx + 2] ?? 0); + const v1LocalPositionX = v1.localPositionOverride ? v1.localPositionOverride[0] : (localPositions?.[v1.vertexIdx] ?? 0); + const v1LocalPositionY = v1.localPositionOverride ? v1.localPositionOverride[1] : (localPositions?.[v1.vertexIdx + 1] ?? 0); + const v1LocalPositionZ = v1.localPositionOverride ? v1.localPositionOverride[2] : (localPositions?.[v1.vertexIdx + 2] ?? 0); + const v0LocalNormalX = v0.localNormalOverride ? v0.localNormalOverride[0] : (localNormals?.[v0.vertexIdx] ?? 0); + const v0LocalNormalY = v0.localNormalOverride ? v0.localNormalOverride[1] : (localNormals?.[v0.vertexIdx + 1] ?? 0); + const v0LocalNormalZ = v0.localNormalOverride ? v0.localNormalOverride[2] : (localNormals?.[v0.vertexIdx + 2] ?? 0); + const v1LocalNormalX = v1.localNormalOverride ? v1.localNormalOverride[0] : (localNormals?.[v1.vertexIdx] ?? 0); + const v1LocalNormalY = v1.localNormalOverride ? v1.localNormalOverride[1] : (localNormals?.[v1.vertexIdx + 1] ?? 0); + const v1LocalNormalZ = v1.localNormalOverride ? v1.localNormalOverride[2] : (localNormals?.[v1.vertexIdx + 2] ?? 0); + const interpNormalX = v0LocalNormalX + (v1LocalNormalX - v0LocalNormalX) * clipFactor; + const interpNormalY = v0LocalNormalY + (v1LocalNormalY - v0LocalNormalY) * clipFactor; + const interpNormalZ = v0LocalNormalZ + (v1LocalNormalZ - v0LocalNormalZ) * clipFactor; + const norm = Math.sqrt(interpNormalX * interpNormalX + interpNormalY * interpNormalY + interpNormalZ * interpNormalZ); + return new DecalVertex(Vector3.Lerp(v0.position, v1.position, clipFactor), Vector3.Lerp(v0.normal, v1.normal, clipFactor).normalize(), Vector2.Lerp(v0.uv, v1.uv, clipFactor), -1, -1, localPositions + ? [ + v0LocalPositionX + (v1LocalPositionX - v0LocalPositionX) * clipFactor, + v0LocalPositionY + (v1LocalPositionY - v0LocalPositionY) * clipFactor, + v0LocalPositionZ + (v1LocalPositionZ - v0LocalPositionZ) * clipFactor, + ] + : null, localNormals ? [interpNormalX / norm, interpNormalY / norm, interpNormalZ / norm] : null, indices, weights); + }; + let clipResult = null; + if (vertices.length > 3) { + clipResult = []; + } + for (let index = 0; index < vertices.length; index += 3) { + let total = 0; + let nV1 = null; + let nV2 = null; + let nV3 = null; + let nV4 = null; + const d1 = Vector3.Dot(vertices[index].position, axis) - clipSize; + const d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize; + const d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize; + const v1Out = d1 > 0; + const v2Out = d2 > 0; + const v3Out = d3 > 0; + total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0); + switch (total) { + case 0: + if (vertices.length > 3) { + clipResult.push(vertices[index]); + clipResult.push(vertices[index + 1]); + clipResult.push(vertices[index + 2]); + } + else { + clipResult = vertices; + } + break; + case 1: + clipResult = clipResult ?? new Array(); + if (v1Out) { + nV1 = vertices[index + 1]; + nV2 = vertices[index + 2]; + nV3 = clipVertices(vertices[index], nV1); + nV4 = clipVertices(vertices[index], nV2); + } + if (v2Out) { + nV1 = vertices[index]; + nV2 = vertices[index + 2]; + nV3 = clipVertices(vertices[index + 1], nV1); + nV4 = clipVertices(vertices[index + 1], nV2); + clipResult.push(nV3); + clipResult.push(nV2.clone()); + clipResult.push(nV1.clone()); + clipResult.push(nV2.clone()); + clipResult.push(nV3.clone()); + clipResult.push(nV4); + break; + } + if (v3Out) { + nV1 = vertices[index]; + nV2 = vertices[index + 1]; + nV3 = clipVertices(vertices[index + 2], nV1); + nV4 = clipVertices(vertices[index + 2], nV2); + } + if (nV1 && nV2 && nV3 && nV4) { + clipResult.push(nV1.clone()); + clipResult.push(nV2.clone()); + clipResult.push(nV3); + clipResult.push(nV4); + clipResult.push(nV3.clone()); + clipResult.push(nV2.clone()); + } + break; + case 2: + clipResult = clipResult ?? new Array(); + if (!v1Out) { + nV1 = vertices[index].clone(); + nV2 = clipVertices(nV1, vertices[index + 1]); + nV3 = clipVertices(nV1, vertices[index + 2]); + clipResult.push(nV1); + clipResult.push(nV2); + clipResult.push(nV3); + } + if (!v2Out) { + nV1 = vertices[index + 1].clone(); + nV2 = clipVertices(nV1, vertices[index + 2]); + nV3 = clipVertices(nV1, vertices[index]); + clipResult.push(nV1); + clipResult.push(nV2); + clipResult.push(nV3); + } + if (!v3Out) { + nV1 = vertices[index + 2].clone(); + nV2 = clipVertices(nV1, vertices[index]); + nV3 = clipVertices(nV1, vertices[index + 1]); + clipResult.push(nV1); + clipResult.push(nV2); + clipResult.push(nV3); + } + break; + } + } + return clipResult; + }; + const sourceMeshAsMesh = sourceMesh instanceof Mesh ? sourceMesh : null; + const matrixData = sourceMeshAsMesh?._thinInstanceDataStorage.matrixData; + const numMatrices = sourceMeshAsMesh?.thinInstanceCount || 1; + const thinInstanceMatrix = TmpVectors.Matrix[0]; + thinInstanceMatrix.copyFrom(Matrix.IdentityReadOnly); + for (let m = 0; m < numMatrices; ++m) { + if (sourceMeshAsMesh?.hasThinInstances && matrixData) { + const ofst = m * 16; + thinInstanceMatrix.setRowFromFloats(0, matrixData[ofst + 0], matrixData[ofst + 1], matrixData[ofst + 2], matrixData[ofst + 3]); + thinInstanceMatrix.setRowFromFloats(1, matrixData[ofst + 4], matrixData[ofst + 5], matrixData[ofst + 6], matrixData[ofst + 7]); + thinInstanceMatrix.setRowFromFloats(2, matrixData[ofst + 8], matrixData[ofst + 9], matrixData[ofst + 10], matrixData[ofst + 11]); + thinInstanceMatrix.setRowFromFloats(3, matrixData[ofst + 12], matrixData[ofst + 13], matrixData[ofst + 14], matrixData[ofst + 15]); + } + // Matrix + const decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z)); + const inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix); + const meshWorldMatrix = sourceMesh.getWorldMatrix(); + const transformMatrix = thinInstanceMatrix.multiply(meshWorldMatrix).multiply(inverseDecalWorldMatrix); + const oneFaceVertices = new Array(3); + for (let index = 0; index < indices.length; index += 3) { + let faceVertices = oneFaceVertices; + faceVertices[0] = extractDecalVector3(index, transformMatrix); + faceVertices[1] = extractDecalVector3(index + 1, transformMatrix); + faceVertices[2] = extractDecalVector3(index + 2, transformMatrix); + if (options.cullBackFaces) { + // If all the normals of the vertices of the face are pointing away from the view direction we discard the face. + // As computations are done in the decal coordinate space, the viewDirection is (0,0,1), so when dot(vertexNormal, -viewDirection) <= 0 the vertex is culled + if (-faceVertices[0].normal.z <= 0 && -faceVertices[1].normal.z <= 0 && -faceVertices[2].normal.z <= 0) { + continue; + } + } + // Clip + faceVertices = clip(faceVertices, xpAxis); + if (!faceVertices) + continue; + faceVertices = clip(faceVertices, xnAxis); + if (!faceVertices) + continue; + faceVertices = clip(faceVertices, ypAxis); + if (!faceVertices) + continue; + faceVertices = clip(faceVertices, ynAxis); + if (!faceVertices) + continue; + faceVertices = clip(faceVertices, zpAxis); + if (!faceVertices) + continue; + faceVertices = clip(faceVertices, znAxis); + if (!faceVertices) + continue; + // Add UVs and get back to world + for (let vIndex = 0; vIndex < faceVertices.length; vIndex++) { + const vertex = faceVertices[vIndex]; + //TODO check for Int32Array | Uint32Array | Uint16Array + vertexData.indices.push(currentVertexDataIndex); + if (useLocalComputation) { + if (vertex.localPositionOverride) { + vertexData.positions[currentVertexDataIndex * 3] = vertex.localPositionOverride[0]; + vertexData.positions[currentVertexDataIndex * 3 + 1] = vertex.localPositionOverride[1]; + vertexData.positions[currentVertexDataIndex * 3 + 2] = vertex.localPositionOverride[2]; + } + else if (localPositions) { + vertexData.positions[currentVertexDataIndex * 3] = localPositions[vertex.vertexIdx]; + vertexData.positions[currentVertexDataIndex * 3 + 1] = localPositions[vertex.vertexIdx + 1]; + vertexData.positions[currentVertexDataIndex * 3 + 2] = localPositions[vertex.vertexIdx + 2]; + } + if (vertex.localNormalOverride) { + vertexData.normals[currentVertexDataIndex * 3] = vertex.localNormalOverride[0]; + vertexData.normals[currentVertexDataIndex * 3 + 1] = vertex.localNormalOverride[1]; + vertexData.normals[currentVertexDataIndex * 3 + 2] = vertex.localNormalOverride[2]; + } + else if (localNormals) { + vertexData.normals[currentVertexDataIndex * 3] = localNormals[vertex.vertexIdx]; + vertexData.normals[currentVertexDataIndex * 3 + 1] = localNormals[vertex.vertexIdx + 1]; + vertexData.normals[currentVertexDataIndex * 3 + 2] = localNormals[vertex.vertexIdx + 2]; + } + } + else { + vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3); + vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3); + } + if (vertexData.matricesIndices && vertexData.matricesWeights) { + if (vertex.matrixIndicesOverride) { + vertexData.matricesIndices[currentVertexDataIndex * 4] = vertex.matrixIndicesOverride[0]; + vertexData.matricesIndices[currentVertexDataIndex * 4 + 1] = vertex.matrixIndicesOverride[1]; + vertexData.matricesIndices[currentVertexDataIndex * 4 + 2] = vertex.matrixIndicesOverride[2]; + vertexData.matricesIndices[currentVertexDataIndex * 4 + 3] = vertex.matrixIndicesOverride[3]; + } + else { + if (matIndices) { + vertexData.matricesIndices[currentVertexDataIndex * 4] = matIndices[vertex.vertexIdxForBones]; + vertexData.matricesIndices[currentVertexDataIndex * 4 + 1] = matIndices[vertex.vertexIdxForBones + 1]; + vertexData.matricesIndices[currentVertexDataIndex * 4 + 2] = matIndices[vertex.vertexIdxForBones + 2]; + vertexData.matricesIndices[currentVertexDataIndex * 4 + 3] = matIndices[vertex.vertexIdxForBones + 3]; + } + if (matIndicesExtra && vertexData.matricesIndicesExtra) { + vertexData.matricesIndicesExtra[currentVertexDataIndex * 4] = matIndicesExtra[vertex.vertexIdxForBones]; + vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 1] = matIndicesExtra[vertex.vertexIdxForBones + 1]; + vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 2] = matIndicesExtra[vertex.vertexIdxForBones + 2]; + vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 3] = matIndicesExtra[vertex.vertexIdxForBones + 3]; + } + } + if (vertex.matrixWeightsOverride) { + vertexData.matricesWeights[currentVertexDataIndex * 4] = vertex.matrixWeightsOverride[0]; + vertexData.matricesWeights[currentVertexDataIndex * 4 + 1] = vertex.matrixWeightsOverride[1]; + vertexData.matricesWeights[currentVertexDataIndex * 4 + 2] = vertex.matrixWeightsOverride[2]; + vertexData.matricesWeights[currentVertexDataIndex * 4 + 3] = vertex.matrixWeightsOverride[3]; + } + else { + if (matWeights) { + vertexData.matricesWeights[currentVertexDataIndex * 4] = matWeights[vertex.vertexIdxForBones]; + vertexData.matricesWeights[currentVertexDataIndex * 4 + 1] = matWeights[vertex.vertexIdxForBones + 1]; + vertexData.matricesWeights[currentVertexDataIndex * 4 + 2] = matWeights[vertex.vertexIdxForBones + 2]; + vertexData.matricesWeights[currentVertexDataIndex * 4 + 3] = matWeights[vertex.vertexIdxForBones + 3]; + } + if (matWeightsExtra && vertexData.matricesWeightsExtra) { + vertexData.matricesWeightsExtra[currentVertexDataIndex * 4] = matWeightsExtra[vertex.vertexIdxForBones]; + vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 1] = matWeightsExtra[vertex.vertexIdxForBones + 1]; + vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 2] = matWeightsExtra[vertex.vertexIdxForBones + 2]; + vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 3] = matWeightsExtra[vertex.vertexIdxForBones + 3]; + } + } + } + if (!options.captureUVS) { + vertexData.uvs.push(0.5 + vertex.position.x / size.x); + const v = 0.5 + vertex.position.y / size.y; + vertexData.uvs.push(v); + } + else { + vertex.uv.toArray(vertexData.uvs, currentVertexDataIndex * 2); + } + currentVertexDataIndex++; + } + } + } + // Avoid the "Setting vertex data kind 'XXX' with an empty array" warning when calling vertexData.applyToMesh + if (vertexData.indices.length === 0) + vertexData.indices = null; + if (vertexData.positions.length === 0) + vertexData.positions = null; + if (vertexData.normals.length === 0) + vertexData.normals = null; + if (vertexData.uvs.length === 0) + vertexData.uvs = null; + if (vertexData.matricesIndices?.length === 0) + vertexData.matricesIndices = null; + if (vertexData.matricesWeights?.length === 0) + vertexData.matricesWeights = null; + if (vertexData.matricesIndicesExtra?.length === 0) + vertexData.matricesIndicesExtra = null; + if (vertexData.matricesWeightsExtra?.length === 0) + vertexData.matricesWeightsExtra = null; + // Return mesh + const decal = new Mesh(name, sourceMesh.getScene()); + vertexData.applyToMesh(decal); + if (useLocalComputation) { + decal.skeleton = sourceMesh.skeleton; + decal.parent = sourceMesh; + } + else { + decal.position = position.clone(); + decal.rotation = new Vector3(pitch, yaw, angle); + } + decal.computeWorldMatrix(true); + decal.refreshBoundingInfo(true, true); + return decal; +} +Mesh.CreateDecal = (name, sourceMesh, position, normal, size, angle) => { + const options = { + position, + normal, + size, + angle, + }; + return CreateDecal(name, sourceMesh, options); +}; + +/** + * Class representing an isovector a vector containing 2 INTEGER coordinates + * x axis is horizontal + * y axis is 60 deg counter clockwise from positive y axis + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _IsoVector { + /** + * Creates a new isovector from the given x and y coordinates + * @param x defines the first coordinate, must be an integer + * @param y defines the second coordinate, must be an integer + */ + constructor( + /** [0] defines the first coordinate */ + x = 0, + /** [0] defines the second coordinate */ + y = 0) { + this.x = x; + this.y = y; + if (x !== Math.floor(x)) { + x = Math.floor(x); + Logger.Warn("x is not an integer, floor(x) used"); + } + if (y !== Math.floor(y)) { + y = Math.floor(y); + Logger.Warn("y is not an integer, floor(y) used"); + } + } + // Operators + /** + * Gets a new IsoVector copied from the IsoVector + * @returns a new IsoVector + */ + clone() { + return new _IsoVector(this.x, this.y); + } + /** + * Rotates one IsoVector 60 degrees counter clockwise about another + * Please note that this is an in place operation + * @param other an IsoVector a center of rotation + * @returns the rotated IsoVector + */ + rotate60About(other) { + //other IsoVector + const x = this.x; + this.x = other.x + other.y - this.y; + this.y = x + this.y - other.x; + return this; + } + /** + * Rotates one IsoVector 60 degrees clockwise about another + * Please note that this is an in place operation + * @param other an IsoVector as center of rotation + * @returns the rotated IsoVector + */ + rotateNeg60About(other) { + const x = this.x; + this.x = x + this.y - other.y; + this.y = other.x + other.y - x; + return this; + } + /** + * For an equilateral triangle OAB with O at isovector (0, 0) and A at isovector (m, n) + * Rotates one IsoVector 120 degrees counter clockwise about the center of the triangle + * Please note that this is an in place operation + * @param m integer a measure a Primary triangle of order (m, n) m > n + * @param n >= 0 integer a measure for a Primary triangle of order (m, n) + * @returns the rotated IsoVector + */ + rotate120(m, n) { + //m, n integers + if (m !== Math.floor(m)) { + m = Math.floor(m); + Logger.Warn("m not an integer only floor(m) used"); + } + if (n !== Math.floor(n)) { + n = Math.floor(n); + Logger.Warn("n not an integer only floor(n) used"); + } + const x = this.x; + this.x = m - x - this.y; + this.y = n + x; + return this; + } + /** + * For an equilateral triangle OAB with O at isovector (0, 0) and A at isovector (m, n) + * Rotates one IsoVector 120 degrees clockwise about the center of the triangle + * Please note that this is an in place operation + * @param m integer a measure a Primary triangle of order (m, n) m > n + * @param n >= 0 integer a measure for a Primary triangle of order (m, n) + * @returns the rotated IsoVector + */ + rotateNeg120(m, n) { + //m, n integers + if (m !== Math.floor(m)) { + m = Math.floor(m); + Logger.Warn("m is not an integer, floor(m) used"); + } + if (n !== Math.floor(n)) { + n = Math.floor(n); + Logger.Warn("n is not an integer, floor(n) used"); + } + const x = this.x; + this.x = this.y - n; + this.y = m + n - x - this.y; + return this; + } + /** + * Transforms an IsoVector to one in Cartesian 3D space based on an isovector + * @param origin an IsoVector + * @param isoGridSize + * @returns Point as a Vector3 + */ + toCartesianOrigin(origin, isoGridSize) { + const point = Vector3.Zero(); + point.x = origin.x + 2 * this.x * isoGridSize + this.y * isoGridSize; + point.y = origin.y + Math.sqrt(3) * this.y * isoGridSize; + return point; + } + // Statics + /** + * Gets a new IsoVector(0, 0) + * @returns a new IsoVector + */ + static Zero() { + return new _IsoVector(0, 0); + } +} + +/** + * Class representing data for one face OAB of an equilateral icosahedron + * When O is the isovector (0, 0), A is isovector (m, n) + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _PrimaryIsoTriangle { + constructor() { + this.cartesian = []; + this.vertices = []; + this.max = []; + this.min = []; + this.closestTo = []; + this.innerFacets = []; + this.isoVecsABOB = []; + this.isoVecsOBOA = []; + this.isoVecsBAOA = []; + this.vertexTypes = []; + // eslint-disable-next-line @typescript-eslint/naming-convention + this.IDATA = new PolyhedronData("icosahedron", "Regular", [ + [0, PHI, -1], + [-PHI, 1, 0], + [-1, 0, -PHI], + [1, 0, -PHI], + [PHI, 1, 0], + [0, PHI, 1], + [-1, 0, PHI], + [-PHI, -1, 0], + [0, -PHI, -1], + [PHI, -1, 0], + [1, 0, PHI], + [0, -PHI, 1], + ], [ + [0, 2, 1], + [0, 3, 2], + [0, 4, 3], + [0, 5, 4], + [0, 1, 5], + [7, 6, 1], + [8, 7, 2], + [9, 8, 3], + [10, 9, 4], + [6, 10, 5], + [2, 7, 1], + [3, 8, 2], + [4, 9, 3], + [5, 10, 4], + [1, 6, 5], + [11, 6, 7], + [11, 7, 8], + [11, 8, 9], + [11, 9, 10], + [11, 10, 6], + ]); + } + /** + * Creates the PrimaryIsoTriangle Triangle OAB + * @param m an integer + * @param n an integer + */ + //operators + setIndices() { + let indexCount = 12; // 12 vertices already assigned + const vecToidx = {}; //maps iso-vectors to indexCount; + const m = this.m; + const n = this.n; + let g = m; // hcf of m, n when n != 0 + let m1 = 1; + let n1 = 0; + if (n !== 0) { + g = HighestCommonFactor(m, n); + } + m1 = m / g; + n1 = n / g; + let fr; //face to the right of current face + let rot; //rotation about which vertex for fr + let O; + let A; + let B; + const oVec = _IsoVector.Zero(); + const aVec = new _IsoVector(m, n); + const bVec = new _IsoVector(-n, m + n); + const oaVec = _IsoVector.Zero(); + const abVec = _IsoVector.Zero(); + const obVec = _IsoVector.Zero(); + let verts = []; + let idx; + let idxR; + let isoId; + let isoIdR; + const closestTo = []; + const vDist = this.vertByDist; + const matchIdx = (f, fr, isoId, isoIdR) => { + idx = f + "|" + isoId; + idxR = fr + "|" + isoIdR; + if (!(idx in vecToidx || idxR in vecToidx)) { + vecToidx[idx] = indexCount; + vecToidx[idxR] = indexCount; + indexCount++; + } + else if (idx in vecToidx && !(idxR in vecToidx)) { + vecToidx[idxR] = vecToidx[idx]; + } + else if (idxR in vecToidx && !(idx in vecToidx)) { + vecToidx[idx] = vecToidx[idxR]; + } + if (vDist[isoId][0] > 2) { + closestTo[vecToidx[idx]] = [-vDist[isoId][0], vDist[isoId][1], vecToidx[idx]]; + } + else { + closestTo[vecToidx[idx]] = [verts[vDist[isoId][0]], vDist[isoId][1], vecToidx[idx]]; + } + }; + this.IDATA.edgematch = [ + [1, "B"], + [2, "B"], + [3, "B"], + [4, "B"], + [0, "B"], + [10, "O", 14, "A"], + [11, "O", 10, "A"], + [12, "O", 11, "A"], + [13, "O", 12, "A"], + [14, "O", 13, "A"], + [0, "O"], + [1, "O"], + [2, "O"], + [3, "O"], + [4, "O"], + [19, "B", 5, "A"], + [15, "B", 6, "A"], + [16, "B", 7, "A"], + [17, "B", 8, "A"], + [18, "B", 9, "A"], + ]; + /***edges AB to OB***** rotation about B*/ + for (let f = 0; f < 20; f++) { + //f current face + verts = this.IDATA.face[f]; + O = verts[2]; + A = verts[1]; + B = verts[0]; + isoId = oVec.x + "|" + oVec.y; + idx = f + "|" + isoId; + if (!(idx in vecToidx)) { + vecToidx[idx] = O; + closestTo[O] = [verts[vDist[isoId][0]], vDist[isoId][1]]; + } + isoId = aVec.x + "|" + aVec.y; + idx = f + "|" + isoId; + if (!(idx in vecToidx)) { + vecToidx[idx] = A; + closestTo[A] = [verts[vDist[isoId][0]], vDist[isoId][1]]; + } + isoId = bVec.x + "|" + bVec.y; + idx = f + "|" + isoId; + if (!(idx in vecToidx)) { + vecToidx[idx] = B; + closestTo[B] = [verts[vDist[isoId][0]], vDist[isoId][1]]; + } + //for edge vertices + fr = this.IDATA.edgematch[f][0]; + rot = this.IDATA.edgematch[f][1]; + if (rot === "B") { + for (let i = 1; i < g; i++) { + abVec.x = m - i * (m1 + n1); + abVec.y = n + i * m1; + obVec.x = -i * n1; + obVec.y = i * (m1 + n1); + isoId = abVec.x + "|" + abVec.y; + isoIdR = obVec.x + "|" + obVec.y; + matchIdx(f, fr, isoId, isoIdR); + } + } + if (rot === "O") { + for (let i = 1; i < g; i++) { + obVec.x = -i * n1; + obVec.y = i * (m1 + n1); + oaVec.x = i * m1; + oaVec.y = i * n1; + isoId = obVec.x + "|" + obVec.y; + isoIdR = oaVec.x + "|" + oaVec.y; + matchIdx(f, fr, isoId, isoIdR); + } + } + fr = this.IDATA.edgematch[f][2]; + rot = this.IDATA.edgematch[f][3]; + if (rot && rot === "A") { + for (let i = 1; i < g; i++) { + oaVec.x = i * m1; + oaVec.y = i * n1; + abVec.x = m - (g - i) * (m1 + n1); //reversed for BA + abVec.y = n + (g - i) * m1; //reversed for BA + isoId = oaVec.x + "|" + oaVec.y; + isoIdR = abVec.x + "|" + abVec.y; + matchIdx(f, fr, isoId, isoIdR); + } + } + for (let i = 0; i < this.vertices.length; i++) { + isoId = this.vertices[i].x + "|" + this.vertices[i].y; + idx = f + "|" + isoId; + if (!(idx in vecToidx)) { + vecToidx[idx] = indexCount++; + if (vDist[isoId][0] > 2) { + closestTo[vecToidx[idx]] = [-vDist[isoId][0], vDist[isoId][1], vecToidx[idx]]; + } + else { + closestTo[vecToidx[idx]] = [verts[vDist[isoId][0]], vDist[isoId][1], vecToidx[idx]]; + } + } + } + } + this.closestTo = closestTo; + this.vecToidx = vecToidx; + } + calcCoeffs() { + const m = this.m; + const n = this.n; + const thirdR3 = Math.sqrt(3) / 3; + const LSQD = m * m + n * n + m * n; + this.coau = (m + n) / LSQD; + this.cobu = -n / LSQD; + this.coav = (-thirdR3 * (m - n)) / LSQD; + this.cobv = (thirdR3 * (2 * m + n)) / LSQD; + } + createInnerFacets() { + const m = this.m; + const n = this.n; + for (let y = 0; y < n + m + 1; y++) { + for (let x = this.min[y]; x < this.max[y] + 1; x++) { + if (x < this.max[y] && x < this.max[y + 1] + 1) { + this.innerFacets.push(["|" + x + "|" + y, "|" + x + "|" + (y + 1), "|" + (x + 1) + "|" + y]); + } + if (y > 0 && x < this.max[y - 1] && x + 1 < this.max[y] + 1) { + this.innerFacets.push(["|" + x + "|" + y, "|" + (x + 1) + "|" + y, "|" + (x + 1) + "|" + (y - 1)]); + } + } + } + } + edgeVecsABOB() { + const m = this.m; + const n = this.n; + const B = new _IsoVector(-n, m + n); + for (let y = 1; y < m + n; y++) { + const point = new _IsoVector(this.min[y], y); + const prev = new _IsoVector(this.min[y - 1], y - 1); + const next = new _IsoVector(this.min[y + 1], y + 1); + const pointR = point.clone(); + const prevR = prev.clone(); + const nextR = next.clone(); + pointR.rotate60About(B); + prevR.rotate60About(B); + nextR.rotate60About(B); + const maxPoint = new _IsoVector(this.max[pointR.y], pointR.y); + const maxPrev = new _IsoVector(this.max[pointR.y - 1], pointR.y - 1); + const maxLeftPrev = new _IsoVector(this.max[pointR.y - 1] - 1, pointR.y - 1); + if (pointR.x !== maxPoint.x || pointR.y !== maxPoint.y) { + if (pointR.x !== maxPrev.x) { + // type2 + //up + this.vertexTypes.push([1, 0, 0]); + this.isoVecsABOB.push([point, maxPrev, maxLeftPrev]); + //down + this.vertexTypes.push([1, 0, 0]); + this.isoVecsABOB.push([point, maxLeftPrev, maxPoint]); + } + else if (pointR.y === nextR.y) { + // type1 + //up + this.vertexTypes.push([1, 1, 0]); + this.isoVecsABOB.push([point, prev, maxPrev]); + //down + this.vertexTypes.push([1, 0, 1]); + this.isoVecsABOB.push([point, maxPrev, next]); + } + else { + // type 0 + //up + this.vertexTypes.push([1, 1, 0]); + this.isoVecsABOB.push([point, prev, maxPrev]); + //down + this.vertexTypes.push([1, 0, 0]); + this.isoVecsABOB.push([point, maxPrev, maxPoint]); + } + } + } + } + mapABOBtoOBOA() { + const point = new _IsoVector(0, 0); + for (let i = 0; i < this.isoVecsABOB.length; i++) { + const temp = []; + for (let j = 0; j < 3; j++) { + point.x = this.isoVecsABOB[i][j].x; + point.y = this.isoVecsABOB[i][j].y; + if (this.vertexTypes[i][j] === 0) { + point.rotateNeg120(this.m, this.n); + } + temp.push(point.clone()); + } + this.isoVecsOBOA.push(temp); + } + } + mapABOBtoBAOA() { + const point = new _IsoVector(0, 0); + for (let i = 0; i < this.isoVecsABOB.length; i++) { + const temp = []; + for (let j = 0; j < 3; j++) { + point.x = this.isoVecsABOB[i][j].x; + point.y = this.isoVecsABOB[i][j].y; + if (this.vertexTypes[i][j] === 1) { + point.rotate120(this.m, this.n); + } + temp.push(point.clone()); + } + this.isoVecsBAOA.push(temp); + } + } + // eslint-disable-next-line @typescript-eslint/naming-convention + MapToFace(faceNb, geodesicData) { + const F = this.IDATA.face[faceNb]; + const oidx = F[2]; + const aidx = F[1]; + const bidx = F[0]; + const O = Vector3.FromArray(this.IDATA.vertex[oidx]); + const A = Vector3.FromArray(this.IDATA.vertex[aidx]); + const B = Vector3.FromArray(this.IDATA.vertex[bidx]); + const OA = A.subtract(O); + const OB = B.subtract(O); + const x = OA.scale(this.coau).add(OB.scale(this.cobu)); + const y = OA.scale(this.coav).add(OB.scale(this.cobv)); + let idx; + let tempVec = TmpVectors.Vector3[0]; + for (let i = 0; i < this.cartesian.length; i++) { + tempVec = x.scale(this.cartesian[i].x).add(y.scale(this.cartesian[i].y)).add(O); + [tempVec.x, tempVec.y, tempVec.z]; + idx = faceNb + "|" + this.vertices[i].x + "|" + this.vertices[i].y; + geodesicData.vertex[this.vecToidx[idx]] = [tempVec.x, tempVec.y, tempVec.z]; + } + } + //statics + /**Creates a primary triangle + * @internal + */ + build(m, n) { + const vertices = []; + const O = _IsoVector.Zero(); + const A = new _IsoVector(m, n); + const B = new _IsoVector(-n, m + n); + vertices.push(O, A, B); + //max internal isoceles triangle vertices + for (let y = n; y < m + 1; y++) { + for (let x = 0; x < m + 1 - y; x++) { + vertices.push(new _IsoVector(x, y)); + } + } + //shared vertices along edges when needed + if (n > 0) { + const g = HighestCommonFactor(m, n); + const m1 = m / g; + const n1 = n / g; + for (let i = 1; i < g; i++) { + vertices.push(new _IsoVector(i * m1, i * n1)); //OA + vertices.push(new _IsoVector(-i * n1, i * (m1 + n1))); //OB + vertices.push(new _IsoVector(m - i * (m1 + n1), n + i * m1)); // AB + } + //lower rows vertices and their rotations + const ratio = m / n; + for (let y = 1; y < n; y++) { + for (let x = 0; x < y * ratio; x++) { + vertices.push(new _IsoVector(x, y)); + vertices.push(new _IsoVector(x, y).rotate120(m, n)); + vertices.push(new _IsoVector(x, y).rotateNeg120(m, n)); + } + } + } + //order vertices by x and then y + vertices.sort((a, b) => { + return a.x - b.x; + }); + vertices.sort((a, b) => { + return a.y - b.y; + }); + const min = new Array(m + n + 1); + const max = new Array(m + n + 1); + for (let i = 0; i < min.length; i++) { + min[i] = Infinity; + max[i] = -Infinity; + } + let y = 0; + let x = 0; + const len = vertices.length; + for (let i = 0; i < len; i++) { + x = vertices[i].x; + y = vertices[i].y; + min[y] = Math.min(x, min[y]); + max[y] = Math.max(x, max[y]); + } + //calculates the distance of a vertex from a given primary vertex + const distFrom = (vert, primVert) => { + const v = vert.clone(); + if (primVert === "A") { + v.rotateNeg120(m, n); + } + if (primVert === "B") { + v.rotate120(m, n); + } + if (v.x < 0) { + return v.y; + } + return v.x + v.y; + }; + const cartesian = []; + const distFromO = []; + const distFromA = []; + const distFromB = []; + const vertByDist = {}; + const vertData = []; + let closest = -1; + let dist = -1; + for (let i = 0; i < len; i++) { + cartesian[i] = vertices[i].toCartesianOrigin(new _IsoVector(0, 0), 0.5); + distFromO[i] = distFrom(vertices[i], "O"); + distFromA[i] = distFrom(vertices[i], "A"); + distFromB[i] = distFrom(vertices[i], "B"); + if (distFromO[i] === distFromA[i] && distFromA[i] === distFromB[i]) { + closest = 3; + dist = distFromO[i]; + } + else if (distFromO[i] === distFromA[i]) { + closest = 4; + dist = distFromO[i]; + } + else if (distFromA[i] === distFromB[i]) { + closest = 5; + dist = distFromA[i]; + } + else if (distFromB[i] === distFromO[i]) { + closest = 6; + dist = distFromO[i]; + } + if (distFromO[i] < distFromA[i] && distFromO[i] < distFromB[i]) { + closest = 2; + dist = distFromO[i]; + } + if (distFromA[i] < distFromO[i] && distFromA[i] < distFromB[i]) { + closest = 1; + dist = distFromA[i]; + } + if (distFromB[i] < distFromA[i] && distFromB[i] < distFromO[i]) { + closest = 0; + dist = distFromB[i]; + } + vertData.push([closest, dist, vertices[i].x, vertices[i].y]); + } + vertData.sort((a, b) => { + return a[2] - b[2]; + }); + vertData.sort((a, b) => { + return a[3] - b[3]; + }); + vertData.sort((a, b) => { + return a[1] - b[1]; + }); + vertData.sort((a, b) => { + return a[0] - b[0]; + }); + for (let v = 0; v < vertData.length; v++) { + vertByDist[vertData[v][2] + "|" + vertData[v][3]] = [vertData[v][0], vertData[v][1], v]; + } + this.m = m; + this.n = n; + this.vertices = vertices; + this.vertByDist = vertByDist; + this.cartesian = cartesian; + this.min = min; + this.max = max; + return this; + } +} +/** Builds Polyhedron Data + * @internal + */ +class PolyhedronData { + constructor( + /** + * The name of the polyhedron + */ + name, + /** + * The category of the polyhedron + */ + category, + /** + * vertex data + */ + vertex, + /** + * face data + */ + face) { + this.name = name; + this.category = category; + this.vertex = vertex; + this.face = face; + } +} +/** + * This class Extends the PolyhedronData Class to provide measures for a Geodesic Polyhedron + */ +class GeodesicData extends PolyhedronData { + /** + * @internal + */ + innerToData(face, primTri) { + for (let i = 0; i < primTri.innerFacets.length; i++) { + this.face.push(primTri.innerFacets[i].map((el) => primTri.vecToidx[face + el])); + } + } + /** + * @internal + */ + mapABOBtoDATA(faceNb, primTri) { + const fr = primTri.IDATA.edgematch[faceNb][0]; + for (let i = 0; i < primTri.isoVecsABOB.length; i++) { + const temp = []; + for (let j = 0; j < 3; j++) { + if (primTri.vertexTypes[i][j] === 0) { + temp.push(faceNb + "|" + primTri.isoVecsABOB[i][j].x + "|" + primTri.isoVecsABOB[i][j].y); + } + else { + temp.push(fr + "|" + primTri.isoVecsABOB[i][j].x + "|" + primTri.isoVecsABOB[i][j].y); + } + } + this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]); + } + } + /** + * @internal + */ + mapOBOAtoDATA(faceNb, primTri) { + const fr = primTri.IDATA.edgematch[faceNb][0]; + for (let i = 0; i < primTri.isoVecsOBOA.length; i++) { + const temp = []; + for (let j = 0; j < 3; j++) { + if (primTri.vertexTypes[i][j] === 1) { + temp.push(faceNb + "|" + primTri.isoVecsOBOA[i][j].x + "|" + primTri.isoVecsOBOA[i][j].y); + } + else { + temp.push(fr + "|" + primTri.isoVecsOBOA[i][j].x + "|" + primTri.isoVecsOBOA[i][j].y); + } + } + this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]); + } + } + /** + * @internal + */ + mapBAOAtoDATA(faceNb, primTri) { + const fr = primTri.IDATA.edgematch[faceNb][2]; + for (let i = 0; i < primTri.isoVecsBAOA.length; i++) { + const temp = []; + for (let j = 0; j < 3; j++) { + if (primTri.vertexTypes[i][j] === 1) { + temp.push(faceNb + "|" + primTri.isoVecsBAOA[i][j].x + "|" + primTri.isoVecsBAOA[i][j].y); + } + else { + temp.push(fr + "|" + primTri.isoVecsBAOA[i][j].x + "|" + primTri.isoVecsBAOA[i][j].y); + } + } + this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]); + } + } + /** + * @internal + */ + orderData(primTri) { + const nearTo = []; + for (let i = 0; i < 13; i++) { + nearTo[i] = []; + } + const close = primTri.closestTo; + for (let i = 0; i < close.length; i++) { + if (close[i][0] > -1) { + if (close[i][1] > 0) { + nearTo[close[i][0]].push([i, close[i][1]]); + } + } + else { + nearTo[12].push([i, close[i][0]]); + } + } + const near = []; + for (let i = 0; i < 12; i++) { + near[i] = i; + } + let nearIndex = 12; + for (let i = 0; i < 12; i++) { + nearTo[i].sort((a, b) => { + return a[1] - b[1]; + }); + for (let j = 0; j < nearTo[i].length; j++) { + near[nearTo[i][j][0]] = nearIndex++; + } + } + for (let j = 0; j < nearTo[12].length; j++) { + near[nearTo[12][j][0]] = nearIndex++; + } + for (let i = 0; i < this.vertex.length; i++) { + this.vertex[i].push(near[i]); + } + this.vertex.sort((a, b) => { + return a[3] - b[3]; + }); + for (let i = 0; i < this.vertex.length; i++) { + this.vertex[i].pop(); + } + for (let i = 0; i < this.face.length; i++) { + for (let j = 0; j < this.face[i].length; j++) { + this.face[i][j] = near[this.face[i][j]]; + } + } + this.sharedNodes = nearTo[12].length; + this.poleNodes = this.vertex.length - this.sharedNodes; + } + /** + * @internal + */ + setOrder(m, faces) { + const adjVerts = []; + const dualFaces = []; + let face = faces.pop(); + dualFaces.push(face); + let index = this.face[face].indexOf(m); + index = (index + 2) % 3; + let v = this.face[face][index]; + adjVerts.push(v); + let f = 0; + while (faces.length > 0) { + face = faces[f]; + if (this.face[face].indexOf(v) > -1) { + // v is a vertex of face f + index = (this.face[face].indexOf(v) + 1) % 3; + v = this.face[face][index]; + adjVerts.push(v); + dualFaces.push(face); + faces.splice(f, 1); + f = 0; + } + else { + f++; + } + } + this.adjacentFaces.push(adjVerts); + return dualFaces; + } + /** + * @internal + */ + toGoldbergPolyhedronData() { + const goldbergPolyhedronData = new PolyhedronData("GeoDual", "Goldberg", [], []); + goldbergPolyhedronData.name = "GD dual"; + const verticesNb = this.vertex.length; + const map = new Array(verticesNb); + for (let v = 0; v < verticesNb; v++) { + map[v] = []; + } + for (let f = 0; f < this.face.length; f++) { + for (let i = 0; i < 3; i++) { + map[this.face[f][i]].push(f); + } + } + let cx = 0; + let cy = 0; + let cz = 0; + let face = []; + let vertex = []; + this.adjacentFaces = []; + for (let m = 0; m < map.length; m++) { + goldbergPolyhedronData.face[m] = this.setOrder(m, map[m].concat([])); + map[m].forEach((el) => { + cx = 0; + cy = 0; + cz = 0; + face = this.face[el]; + for (let i = 0; i < 3; i++) { + vertex = this.vertex[face[i]]; + cx += vertex[0]; + cy += vertex[1]; + cz += vertex[2]; + } + goldbergPolyhedronData.vertex[el] = [cx / 3, cy / 3, cz / 3]; + }); + } + return goldbergPolyhedronData; + } + //statics + /**Builds the data for a Geodesic Polyhedron from a primary triangle + * @param primTri the primary triangle + * @internal + */ + static BuildGeodesicData(primTri) { + const geodesicData = new GeodesicData("Geodesic-m-n", "Geodesic", [ + [0, PHI, -1], + [-PHI, 1, 0], + [-1, 0, -PHI], + [1, 0, -PHI], + [PHI, 1, 0], + [0, PHI, 1], + [-1, 0, PHI], + [-PHI, -1, 0], + [0, -PHI, -1], + [PHI, -1, 0], + [1, 0, PHI], + [0, -PHI, 1], + ], []); + primTri.setIndices(); + primTri.calcCoeffs(); + primTri.createInnerFacets(); + primTri.edgeVecsABOB(); + primTri.mapABOBtoOBOA(); + primTri.mapABOBtoBAOA(); + for (let f = 0; f < primTri.IDATA.face.length; f++) { + primTri.MapToFace(f, geodesicData); + geodesicData.innerToData(f, primTri); + if (primTri.IDATA.edgematch[f][1] === "B") { + geodesicData.mapABOBtoDATA(f, primTri); + } + if (primTri.IDATA.edgematch[f][1] === "O") { + geodesicData.mapOBOAtoDATA(f, primTri); + } + if (primTri.IDATA.edgematch[f][3] === "A") { + geodesicData.mapBAOAtoDATA(f, primTri); + } + } + geodesicData.orderData(primTri); + const radius = 1; + geodesicData.vertex = geodesicData.vertex.map(function (el) { + const a = el[0]; + const b = el[1]; + const c = el[2]; + const d = Math.sqrt(a * a + b * b + c * c); + el[0] *= radius / d; + el[1] *= radius / d; + el[2] *= radius / d; + return el; + }); + return geodesicData; + } +} + +/** + * Creates the Mesh for a Geodesic Polyhedron + * @see https://en.wikipedia.org/wiki/Geodesic_polyhedron + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra/geodesic_poly + * @param name defines the name of the mesh + * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty + * * m number of horizontal steps along an isogrid + * * n number of angled steps along an isogrid + * * size the size of the Geodesic, optional default 1 + * * sizeX allows stretching in the x direction, optional, default size + * * sizeY allows stretching in the y direction, optional, default size + * * sizeZ allows stretching in the z direction, optional, default size + * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively + * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively + * * flat when true creates a flat shaded mesh, optional, default true + * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 + * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE + * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) + * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) + * @param scene defines the hosting scene + * @returns Geodesic mesh + */ +function CreateGeodesic(name, options, scene = null) { + let m = options.m || 1; + if (m !== Math.floor(m)) { + m = Math.floor(m); + Logger.Warn("m not an integer only floor(m) used"); + } + let n = options.n || 0; + if (n !== Math.floor(n)) { + n = Math.floor(n); + Logger.Warn("n not an integer only floor(n) used"); + } + if (n > m) { + const temp = n; + n = m; + m = temp; + Logger.Warn("n > m therefore m and n swapped"); + } + const primTri = new _PrimaryIsoTriangle(); + primTri.build(m, n); + const geodesicData = GeodesicData.BuildGeodesicData(primTri); + const geoOptions = { + custom: geodesicData, + size: options.size, + sizeX: options.sizeX, + sizeY: options.sizeY, + sizeZ: options.sizeZ, + faceUV: options.faceUV, + faceColors: options.faceColors, + flat: options.flat, + updatable: options.updatable, + sideOrientation: options.sideOrientation, + frontUVs: options.frontUVs, + backUVs: options.backUVs, + }; + const geodesic = CreatePolyhedron(name, geoOptions, scene); + return geodesic; +} + +Mesh._GoldbergMeshParser = (parsedMesh, scene) => { + return GoldbergMesh.Parse(parsedMesh, scene); +}; +/** + * Mesh for a Goldberg Polyhedron which is made from 12 pentagonal and the rest hexagonal faces + * @see https://en.wikipedia.org/wiki/Goldberg_polyhedron + */ +class GoldbergMesh extends Mesh { + constructor() { + super(...arguments); + /** + * Defines the specific Goldberg data used in this mesh construction. + */ + this.goldbergData = { + faceColors: [], + faceCenters: [], + faceZaxis: [], + faceXaxis: [], + faceYaxis: [], + nbSharedFaces: 0, + nbUnsharedFaces: 0, + nbFaces: 0, + nbFacesAtPole: 0, + adjacentFaces: [], + }; + } + /** + * Gets the related Goldberg face from pole infos + * @param poleOrShared Defines the pole index or the shared face index if the fromPole parameter is passed in + * @param fromPole Defines an optional pole index to find the related info from + * @returns the goldberg face number + */ + relatedGoldbergFace(poleOrShared, fromPole) { + if (fromPole === void 0) { + if (poleOrShared > this.goldbergData.nbUnsharedFaces - 1) { + Logger.Warn("Maximum number of unshared faces used"); + poleOrShared = this.goldbergData.nbUnsharedFaces - 1; + } + return this.goldbergData.nbUnsharedFaces + poleOrShared; + } + if (poleOrShared > 11) { + Logger.Warn("Last pole used"); + poleOrShared = 11; + } + if (fromPole > this.goldbergData.nbFacesAtPole - 1) { + Logger.Warn("Maximum number of faces at a pole used"); + fromPole = this.goldbergData.nbFacesAtPole - 1; + } + return 12 + poleOrShared * this.goldbergData.nbFacesAtPole + fromPole; + } + _changeGoldbergFaceColors(colorRange) { + for (let i = 0; i < colorRange.length; i++) { + const min = colorRange[i][0]; + const max = colorRange[i][1]; + const col = colorRange[i][2]; + for (let f = min; f < max + 1; f++) { + this.goldbergData.faceColors[f] = col; + } + } + const newCols = []; + for (let f = 0; f < 12; f++) { + for (let i = 0; i < 5; i++) { + newCols.push(this.goldbergData.faceColors[f].r, this.goldbergData.faceColors[f].g, this.goldbergData.faceColors[f].b, this.goldbergData.faceColors[f].a); + } + } + for (let f = 12; f < this.goldbergData.faceColors.length; f++) { + for (let i = 0; i < 6; i++) { + newCols.push(this.goldbergData.faceColors[f].r, this.goldbergData.faceColors[f].g, this.goldbergData.faceColors[f].b, this.goldbergData.faceColors[f].a); + } + } + return newCols; + } + /** + * Set new goldberg face colors + * @param colorRange the new color to apply to the mesh + */ + setGoldbergFaceColors(colorRange) { + const newCols = this._changeGoldbergFaceColors(colorRange); + this.setVerticesData(VertexBuffer.ColorKind, newCols); + } + /** + * Updates new goldberg face colors + * @param colorRange the new color to apply to the mesh + */ + updateGoldbergFaceColors(colorRange) { + const newCols = this._changeGoldbergFaceColors(colorRange); + this.updateVerticesData(VertexBuffer.ColorKind, newCols); + } + _changeGoldbergFaceUVs(uvRange) { + const uvs = this.getVerticesData(VertexBuffer.UVKind); + for (let i = 0; i < uvRange.length; i++) { + const min = uvRange[i][0]; + const max = uvRange[i][1]; + const center = uvRange[i][2]; + const radius = uvRange[i][3]; + const angle = uvRange[i][4]; + const points5 = []; + const points6 = []; + let u; + let v; + for (let p = 0; p < 5; p++) { + u = center.x + radius * Math.cos(angle + (p * Math.PI) / 2.5); + v = center.y + radius * Math.sin(angle + (p * Math.PI) / 2.5); + if (u < 0) { + u = 0; + } + if (u > 1) { + u = 1; + } + points5.push(u, v); + } + for (let p = 0; p < 6; p++) { + u = center.x + radius * Math.cos(angle + (p * Math.PI) / 3); + v = center.y + radius * Math.sin(angle + (p * Math.PI) / 3); + if (u < 0) { + u = 0; + } + if (u > 1) { + u = 1; + } + points6.push(u, v); + } + for (let f = min; f < Math.min(12, max + 1); f++) { + for (let p = 0; p < 5; p++) { + uvs[10 * f + 2 * p] = points5[2 * p]; + uvs[10 * f + 2 * p + 1] = points5[2 * p + 1]; + } + } + for (let f = Math.max(12, min); f < max + 1; f++) { + for (let p = 0; p < 6; p++) { + //120 + 12 * (f - 12) = 12 * f - 24 + uvs[12 * f - 24 + 2 * p] = points6[2 * p]; + uvs[12 * f - 23 + 2 * p] = points6[2 * p + 1]; + } + } + } + return uvs; + } + /** + * set new goldberg face UVs + * @param uvRange the new UVs to apply to the mesh + */ + setGoldbergFaceUVs(uvRange) { + const newUVs = this._changeGoldbergFaceUVs(uvRange); + this.setVerticesData(VertexBuffer.UVKind, newUVs); + } + /** + * Updates new goldberg face UVs + * @param uvRange the new UVs to apply to the mesh + */ + updateGoldbergFaceUVs(uvRange) { + const newUVs = this._changeGoldbergFaceUVs(uvRange); + this.updateVerticesData(VertexBuffer.UVKind, newUVs); + } + /** + * Places a mesh on a particular face of the goldberg polygon + * @param mesh Defines the mesh to position + * @param face Defines the face to position onto + * @param position Defines the position relative to the face we are positioning the mesh onto + */ + placeOnGoldbergFaceAt(mesh, face, position) { + const orientation = Vector3.RotationFromAxis(this.goldbergData.faceXaxis[face], this.goldbergData.faceYaxis[face], this.goldbergData.faceZaxis[face]); + mesh.rotation = orientation; + mesh.position = this.goldbergData.faceCenters[face] + .add(this.goldbergData.faceXaxis[face].scale(position.x)) + .add(this.goldbergData.faceYaxis[face].scale(position.y)) + .add(this.goldbergData.faceZaxis[face].scale(position.z)); + } + /** + * Serialize current mesh + * @param serializationObject defines the object which will receive the serialization data + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.type = "GoldbergMesh"; + const goldbergData = {}; + goldbergData.adjacentFaces = this.goldbergData.adjacentFaces; + goldbergData.nbSharedFaces = this.goldbergData.nbSharedFaces; + goldbergData.nbUnsharedFaces = this.goldbergData.nbUnsharedFaces; + goldbergData.nbFaces = this.goldbergData.nbFaces; + goldbergData.nbFacesAtPole = this.goldbergData.nbFacesAtPole; + if (this.goldbergData.faceColors) { + goldbergData.faceColors = []; + for (const color of this.goldbergData.faceColors) { + goldbergData.faceColors.push(color.asArray()); + } + } + if (this.goldbergData.faceCenters) { + goldbergData.faceCenters = []; + for (const vector of this.goldbergData.faceCenters) { + goldbergData.faceCenters.push(vector.asArray()); + } + } + if (this.goldbergData.faceZaxis) { + goldbergData.faceZaxis = []; + for (const vector of this.goldbergData.faceZaxis) { + goldbergData.faceZaxis.push(vector.asArray()); + } + } + if (this.goldbergData.faceYaxis) { + goldbergData.faceYaxis = []; + for (const vector of this.goldbergData.faceYaxis) { + goldbergData.faceYaxis.push(vector.asArray()); + } + } + if (this.goldbergData.faceXaxis) { + goldbergData.faceXaxis = []; + for (const vector of this.goldbergData.faceXaxis) { + goldbergData.faceXaxis.push(vector.asArray()); + } + } + serializationObject.goldbergData = goldbergData; + } + /** + * Parses a serialized goldberg mesh + * @param parsedMesh the serialized mesh + * @param scene the scene to create the goldberg mesh in + * @returns the created goldberg mesh + */ + static Parse(parsedMesh, scene) { + const goldbergData = parsedMesh.goldbergData; + goldbergData.faceColors = goldbergData.faceColors.map((el) => Color4.FromArray(el)); + goldbergData.faceCenters = goldbergData.faceCenters.map((el) => Vector3.FromArray(el)); + goldbergData.faceZaxis = goldbergData.faceZaxis.map((el) => Vector3.FromArray(el)); + goldbergData.faceXaxis = goldbergData.faceXaxis.map((el) => Vector3.FromArray(el)); + goldbergData.faceYaxis = goldbergData.faceYaxis.map((el) => Vector3.FromArray(el)); + const goldberg = new GoldbergMesh(parsedMesh.name, scene); + goldberg.goldbergData = goldbergData; + return goldberg; + } +} + +/** + * Creates the Mesh for a Goldberg Polyhedron + * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty + * @param goldbergData polyhedronData defining the Goldberg polyhedron + * @returns GoldbergSphere mesh + */ +function CreateGoldbergVertexData(options, goldbergData) { + const size = options.size; + const sizeX = options.sizeX || size || 1; + const sizeY = options.sizeY || size || 1; + const sizeZ = options.sizeZ || size || 1; + const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; + const positions = []; + const indices = []; + const normals = []; + const uvs = []; + let minX = Infinity; + let maxX = -Infinity; + let minY = Infinity; + let maxY = -Infinity; + for (let v = 0; v < goldbergData.vertex.length; v++) { + minX = Math.min(minX, goldbergData.vertex[v][0] * sizeX); + maxX = Math.max(maxX, goldbergData.vertex[v][0] * sizeX); + minY = Math.min(minY, goldbergData.vertex[v][1] * sizeY); + maxY = Math.max(maxY, goldbergData.vertex[v][1] * sizeY); + } + let index = 0; + for (let f = 0; f < goldbergData.face.length; f++) { + const verts = goldbergData.face[f]; + const a = Vector3.FromArray(goldbergData.vertex[verts[0]]); + const b = Vector3.FromArray(goldbergData.vertex[verts[2]]); + const c = Vector3.FromArray(goldbergData.vertex[verts[1]]); + const ba = b.subtract(a); + const ca = c.subtract(a); + const norm = Vector3.Cross(ca, ba).normalize(); + for (let v = 0; v < verts.length; v++) { + normals.push(norm.x, norm.y, norm.z); + const pdata = goldbergData.vertex[verts[v]]; + positions.push(pdata[0] * sizeX, pdata[1] * sizeY, pdata[2] * sizeZ); + const vCoord = (pdata[1] * sizeY - minY) / (maxY - minY); + uvs.push((pdata[0] * sizeX - minX) / (maxX - minX), vCoord); + } + for (let v = 0; v < verts.length - 2; v++) { + indices.push(index, index + v + 2, index + v + 1); + } + index += verts.length; + } + VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs); + const vertexData = new VertexData(); + vertexData.positions = positions; + vertexData.indices = indices; + vertexData.normals = normals; + vertexData.uvs = uvs; + return vertexData; +} +/** + * Creates the Mesh for a Goldberg Polyhedron which is made from 12 pentagonal and the rest hexagonal faces + * @see https://en.wikipedia.org/wiki/Goldberg_polyhedron + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra/goldberg_poly + * @param name defines the name of the mesh + * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty + * @param scene defines the hosting scene + * @returns Goldberg mesh + */ +function CreateGoldberg(name, options, scene = null) { + const size = options.size; + const sizeX = options.sizeX || size || 1; + const sizeY = options.sizeY || size || 1; + const sizeZ = options.sizeZ || size || 1; + let m = options.m || 1; + if (m !== Math.floor(m)) { + m = Math.floor(m); + Logger.Warn("m not an integer only floor(m) used"); + } + let n = options.n || 0; + if (n !== Math.floor(n)) { + n = Math.floor(n); + Logger.Warn("n not an integer only floor(n) used"); + } + if (n > m) { + const temp = n; + n = m; + m = temp; + Logger.Warn("n > m therefore m and n swapped"); + } + const primTri = new _PrimaryIsoTriangle(); + primTri.build(m, n); + const geodesicData = GeodesicData.BuildGeodesicData(primTri); + const goldbergData = geodesicData.toGoldbergPolyhedronData(); + const goldberg = new GoldbergMesh(name, scene); + options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); + goldberg._originalBuilderSideOrientation = options.sideOrientation; + const vertexData = CreateGoldbergVertexData(options, goldbergData); + vertexData.applyToMesh(goldberg, options.updatable); + goldberg.goldbergData.nbSharedFaces = geodesicData.sharedNodes; + goldberg.goldbergData.nbUnsharedFaces = geodesicData.poleNodes; + goldberg.goldbergData.adjacentFaces = geodesicData.adjacentFaces; + goldberg.goldbergData.nbFaces = goldberg.goldbergData.nbSharedFaces + goldberg.goldbergData.nbUnsharedFaces; + goldberg.goldbergData.nbFacesAtPole = (goldberg.goldbergData.nbUnsharedFaces - 12) / 12; + for (let f = 0; f < geodesicData.vertex.length; f++) { + goldberg.goldbergData.faceCenters.push(Vector3.FromArray(geodesicData.vertex[f])); + goldberg.goldbergData.faceCenters[f].x *= sizeX; + goldberg.goldbergData.faceCenters[f].y *= sizeY; + goldberg.goldbergData.faceCenters[f].z *= sizeZ; + goldberg.goldbergData.faceColors.push(new Color4(1, 1, 1, 1)); + } + for (let f = 0; f < goldbergData.face.length; f++) { + const verts = goldbergData.face[f]; + const a = Vector3.FromArray(goldbergData.vertex[verts[0]]); + const b = Vector3.FromArray(goldbergData.vertex[verts[2]]); + const c = Vector3.FromArray(goldbergData.vertex[verts[1]]); + const ba = b.subtract(a); + const ca = c.subtract(a); + const norm = Vector3.Cross(ca, ba).normalize(); + const z = Vector3.Cross(ca, norm).normalize(); + goldberg.goldbergData.faceXaxis.push(ca.normalize()); + goldberg.goldbergData.faceYaxis.push(norm); + goldberg.goldbergData.faceZaxis.push(z); + } + return goldberg; +} + +// Shape functions +class ShapePath { + /** Create the ShapePath used to support glyphs + * @param resolution defines the resolution used to determine the number of points per curve (default is 4) + */ + constructor(resolution) { + this._paths = []; + this._tempPaths = []; + this._holes = []; + this._resolution = resolution; + } + /** Move the virtual cursor to a coordinate + * @param x defines the x coordinate + * @param y defines the y coordinate + */ + moveTo(x, y) { + this._currentPath = new Path2(x, y); + this._tempPaths.push(this._currentPath); + } + /** Draw a line from the virtual cursor to a given coordinate + * @param x defines the x coordinate + * @param y defines the y coordinate + */ + lineTo(x, y) { + this._currentPath.addLineTo(x, y); + } + /** Create a quadratic curve from the virtual cursor to a given coordinate + * @param cpx defines the x coordinate of the control point + * @param cpy defines the y coordinate of the control point + * @param x defines the x coordinate of the end point + * @param y defines the y coordinate of the end point + */ + quadraticCurveTo(cpx, cpy, x, y) { + this._currentPath.addQuadraticCurveTo(cpx, cpy, x, y, this._resolution); + } + /** + * Create a bezier curve from the virtual cursor to a given coordinate + * @param cpx1 defines the x coordinate of the first control point + * @param cpy1 defines the y coordinate of the first control point + * @param cpx2 defines the x coordinate of the second control point + * @param cpy2 defines the y coordinate of the second control point + * @param x defines the x coordinate of the end point + * @param y defines the y coordinate of the end point + */ + bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y) { + this._currentPath.addBezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y, this._resolution); + } + /** Extract holes based on CW / CCW */ + extractHoles() { + for (const path of this._tempPaths) { + if (path.area() > 0) { + this._holes.push(path); + } + else { + this._paths.push(path); + } + } + if (!this._paths.length && this._holes.length) { + const temp = this._holes; + this._holes = this._paths; + this._paths = temp; + } + this._tempPaths.length = 0; + } + /** Gets the list of paths */ + get paths() { + return this._paths; + } + /** Gets the list of holes */ + get holes() { + return this._holes; + } +} +// Utility functions +function CreateShapePath(char, scale, offsetX, offsetY, resolution, fontData) { + const glyph = fontData.glyphs[char] || fontData.glyphs["?"]; + if (!glyph) { + // return if there is no glyph data + return null; + } + const shapePath = new ShapePath(resolution); + if (glyph.o) { + const outline = glyph.o.split(" "); + for (let i = 0, l = outline.length; i < l;) { + const action = outline[i++]; + switch (action) { + case "m": { + // moveTo + const x = parseInt(outline[i++]) * scale + offsetX; + const y = parseInt(outline[i++]) * scale + offsetY; + shapePath.moveTo(x, y); + break; + } + case "l": { + // lineTo + const x = parseInt(outline[i++]) * scale + offsetX; + const y = parseInt(outline[i++]) * scale + offsetY; + shapePath.lineTo(x, y); + break; + } + case "q": { + // quadraticCurveTo + const cpx = parseInt(outline[i++]) * scale + offsetX; + const cpy = parseInt(outline[i++]) * scale + offsetY; + const cpx1 = parseInt(outline[i++]) * scale + offsetX; + const cpy1 = parseInt(outline[i++]) * scale + offsetY; + shapePath.quadraticCurveTo(cpx1, cpy1, cpx, cpy); + break; + } + case "b": { + // bezierCurveTo + const cpx = parseInt(outline[i++]) * scale + offsetX; + const cpy = parseInt(outline[i++]) * scale + offsetY; + const cpx1 = parseInt(outline[i++]) * scale + offsetX; + const cpy1 = parseInt(outline[i++]) * scale + offsetY; + const cpx2 = parseInt(outline[i++]) * scale + offsetX; + const cpy2 = parseInt(outline[i++]) * scale + offsetY; + shapePath.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy); + break; + } + } + } + } + // Extract holes (based on clockwise data) + shapePath.extractHoles(); + return { offsetX: glyph.ha * scale, shapePath: shapePath }; +} +/** + * Creates shape paths from a text and font + * @param text the text + * @param size size of the font + * @param resolution resolution of the font + * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/) + * @returns array of ShapePath objects + */ +function CreateTextShapePaths(text, size, resolution, fontData) { + const chars = Array.from(text); + const scale = size / fontData.resolution; + const line_height = (fontData.boundingBox.yMax - fontData.boundingBox.yMin + fontData.underlineThickness) * scale; + const shapePaths = []; + let offsetX = 0, offsetY = 0; + for (let i = 0; i < chars.length; i++) { + const char = chars[i]; + if (char === "\n") { + offsetX = 0; + offsetY -= line_height; + } + else { + const ret = CreateShapePath(char, scale, offsetX, offsetY, resolution, fontData); + if (ret) { + offsetX += ret.offsetX; + shapePaths.push(ret.shapePath); + } + } + } + return shapePaths; +} +/** + * Create a text mesh + * @param name defines the name of the mesh + * @param text defines the text to use to build the mesh + * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/) + * @param options defines options used to create the mesh + * @param scene defines the hosting scene + * @param earcutInjection can be used to inject your own earcut reference + * @returns a new Mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/text + */ +function CreateText(name, text, fontData, options = { + size: 50, + resolution: 8, + depth: 1.0, +}, scene = null, earcutInjection = earcut) { + // First we need to generate the paths + const shapePaths = CreateTextShapePaths(text, options.size || 50, options.resolution || 8, fontData); + // And extrude them + const meshes = []; + let letterIndex = 0; + for (const shapePath of shapePaths) { + if (!shapePath.paths.length) { + continue; + } + const holes = shapePath.holes.slice(); // Copy it as we will update the copy + for (const path of shapePath.paths) { + const holeVectors = []; + const shapeVectors = []; + const points = path.getPoints(); + for (const point of points) { + shapeVectors.push(new Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane + } + // Holes + const localHolesCopy = holes.slice(); + for (const hole of localHolesCopy) { + const points = hole.getPoints(); + let found = false; + for (const point of points) { + if (path.isPointInside(point)) { + found = true; + break; + } + } + if (!found) { + continue; + } + const holePoints = []; + for (const point of points) { + holePoints.push(new Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane + } + holeVectors.push(holePoints); + // Remove the hole as it was already used + holes.splice(holes.indexOf(hole), 1); + } + // There is at least a hole but it was unaffected + if (!holeVectors.length && holes.length) { + for (const hole of holes) { + const points = hole.getPoints(); + const holePoints = []; + for (const point of points) { + holePoints.push(new Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane + } + holeVectors.push(holePoints); + } + } + // Extrusion! + const mesh = ExtrudePolygon(name, { + shape: shapeVectors, + holes: holeVectors.length ? holeVectors : undefined, + depth: options.depth || 1.0, + faceUV: options.faceUV || options.perLetterFaceUV?.(letterIndex), + faceColors: options.faceColors || options.perLetterFaceColors?.(letterIndex), + sideOrientation: Mesh._GetDefaultSideOrientation(options.sideOrientation || Mesh.DOUBLESIDE), + }, scene, earcutInjection); + meshes.push(mesh); + letterIndex++; + } + } + // Then we can merge everyone into one single mesh + const newMesh = Mesh.MergeMeshes(meshes, true, true); + if (newMesh) { + // Move pivot to desired center / bottom / center position + const bbox = newMesh.getBoundingInfo().boundingBox; + newMesh.position.x += -(bbox.minimumWorld.x + bbox.maximumWorld.x) / 2; // Mid X + newMesh.position.y += -(bbox.minimumWorld.y + bbox.maximumWorld.y) / 2; // Mid Z as it will rotate + newMesh.position.z += -(bbox.minimumWorld.z + bbox.maximumWorld.z) / 2 + bbox.extendSize.z; // Bottom Y as it will rotate + newMesh.name = name; + // Rotate 90° Up + const pivot = new TransformNode("pivot", scene); + pivot.rotation.x = -Math.PI / 2; + newMesh.parent = pivot; + newMesh.bakeCurrentTransformIntoVertices(); + // Remove the pivot + newMesh.parent = null; + pivot.dispose(); + } + return newMesh; +} + +/* eslint-disable @typescript-eslint/naming-convention */ +/** + * Class containing static functions to help procedurally build meshes + */ +const MeshBuilder = { + CreateBox, + CreateTiledBox, + CreateSphere, + CreateDisc, + CreateIcoSphere, + CreateRibbon, + CreateCylinder, + CreateTorus, + CreateTorusKnot, + CreateLineSystem, + CreateLines, + CreateDashedLines, + ExtrudeShape, + ExtrudeShapeCustom, + CreateLathe, + CreateTiledPlane, + CreatePlane, + CreateGround, + CreateTiledGround, + CreateGroundFromHeightMap, + CreatePolygon, + ExtrudePolygon, + CreateTube, + CreatePolyhedron, + CreateGeodesic, + CreateGoldberg, + CreateDecal, + CreateCapsule, + CreateText, +}; + +AbstractEngine.prototype.getGPUFrameTimeCounter = function () { + if (!this._gpuFrameTime) { + this._gpuFrameTime = new PerfCounter(); + } + return this._gpuFrameTime; +}; +AbstractEngine.prototype.captureGPUFrameTime = function (value) { + // Do nothing. Must be implemented by child classes +}; + +/** @internal */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _OcclusionDataStorage { + constructor() { + /** @internal */ + this.occlusionInternalRetryCounter = 0; + /** @internal */ + this.isOcclusionQueryInProgress = false; + /** @internal */ + this.isOccluded = false; + /** @internal */ + this.occlusionRetryCount = -1; + /** @internal */ + this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE; + /** @internal */ + this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE; + /** @internal */ + this.forceRenderingWhenOccluded = false; + } +} +AbstractEngine.prototype.createQuery = function () { + return null; +}; +AbstractEngine.prototype.deleteQuery = function (query) { + // Do nothing. Must be implemented by child classes + return this; +}; +AbstractEngine.prototype.isQueryResultAvailable = function (query) { + // Do nothing. Must be implemented by child classes + return false; +}; +AbstractEngine.prototype.getQueryResult = function (query) { + // Do nothing. Must be implemented by child classes + return 0; +}; +AbstractEngine.prototype.beginOcclusionQuery = function (algorithmType, query) { + // Do nothing. Must be implemented by child classes + return false; +}; +AbstractEngine.prototype.endOcclusionQuery = function (algorithmType) { + // Do nothing. Must be implemented by child classes + return this; +}; +Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", { + get: function () { + return this._occlusionDataStorage.isOcclusionQueryInProgress; + }, + set: function (value) { + this._occlusionDataStorage.isOcclusionQueryInProgress = value; + }, + enumerable: false, + configurable: true, +}); +Object.defineProperty(AbstractMesh.prototype, "_occlusionDataStorage", { + get: function () { + if (!this.__occlusionDataStorage) { + this.__occlusionDataStorage = new _OcclusionDataStorage(); + } + return this.__occlusionDataStorage; + }, + enumerable: false, + configurable: true, +}); +Object.defineProperty(AbstractMesh.prototype, "isOccluded", { + get: function () { + return this._occlusionDataStorage.isOccluded; + }, + set: function (value) { + this._occlusionDataStorage.isOccluded = value; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(AbstractMesh.prototype, "occlusionQueryAlgorithmType", { + get: function () { + return this._occlusionDataStorage.occlusionQueryAlgorithmType; + }, + set: function (value) { + this._occlusionDataStorage.occlusionQueryAlgorithmType = value; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(AbstractMesh.prototype, "occlusionType", { + get: function () { + return this._occlusionDataStorage.occlusionType; + }, + set: function (value) { + this._occlusionDataStorage.occlusionType = value; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(AbstractMesh.prototype, "occlusionRetryCount", { + get: function () { + return this._occlusionDataStorage.occlusionRetryCount; + }, + set: function (value) { + this._occlusionDataStorage.occlusionRetryCount = value; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(AbstractMesh.prototype, "forceRenderingWhenOccluded", { + get: function () { + return this._occlusionDataStorage.forceRenderingWhenOccluded; + }, + set: function (value) { + this._occlusionDataStorage.forceRenderingWhenOccluded = value; + }, + enumerable: true, + configurable: true, +}); +// We also need to update AbstractMesh as there is a portion of the code there +AbstractMesh.prototype._checkOcclusionQuery = function () { + const dataStorage = this._occlusionDataStorage; + if (dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) { + dataStorage.isOccluded = false; + return false; + } + const engine = this.getEngine(); + if (!engine.getCaps().supportOcclusionQuery) { + dataStorage.isOccluded = false; + return false; + } + if (!engine.isQueryResultAvailable) { + // Occlusion query where not referenced + dataStorage.isOccluded = false; + return false; + } + if (this.isOcclusionQueryInProgress && this._occlusionQuery !== null && this._occlusionQuery !== undefined) { + const isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery); + if (isOcclusionQueryAvailable) { + const occlusionQueryResult = engine.getQueryResult(this._occlusionQuery); + dataStorage.isOcclusionQueryInProgress = false; + dataStorage.occlusionInternalRetryCounter = 0; + dataStorage.isOccluded = occlusionQueryResult > 0 ? false : true; + } + else { + dataStorage.occlusionInternalRetryCounter++; + if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) { + dataStorage.isOcclusionQueryInProgress = false; + dataStorage.occlusionInternalRetryCounter = 0; + // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop) + // if strict continue the last state of the object. + dataStorage.isOccluded = dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded; + } + else { + return dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded; + } + } + } + const scene = this.getScene(); + if (scene.getBoundingBoxRenderer) { + const occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer(); + if (this._occlusionQuery === null) { + this._occlusionQuery = engine.createQuery(); + } + if (this._occlusionQuery && engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery)) { + occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this); + engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType); + this._occlusionDataStorage.isOcclusionQueryInProgress = true; + } + } + return dataStorage.isOccluded; +}; + +const _onBeforeViewRenderObservable = new Observable(); +const _onAfterViewRenderObservable = new Observable(); +Object.defineProperty(AbstractEngine.prototype, "onBeforeViewRenderObservable", { + get: function () { + return _onBeforeViewRenderObservable; + }, +}); +Object.defineProperty(AbstractEngine.prototype, "onAfterViewRenderObservable", { + get: function () { + return _onAfterViewRenderObservable; + }, +}); +Object.defineProperty(AbstractEngine.prototype, "inputElement", { + get: function () { + return this._inputElement; + }, + set: function (value) { + if (this._inputElement !== value) { + this._inputElement = value; + this._onEngineViewChanged?.(); + } + }, +}); +AbstractEngine.prototype.getInputElement = function () { + return this.inputElement || this.getRenderingCanvas(); +}; +AbstractEngine.prototype.registerView = function (canvas, camera, clearBeforeCopy) { + if (!this.views) { + this.views = []; + } + for (const view of this.views) { + if (view.target === canvas) { + return view; + } + } + const masterCanvas = this.getRenderingCanvas(); + if (masterCanvas) { + canvas.width = masterCanvas.width; + canvas.height = masterCanvas.height; + } + const newView = { target: canvas, camera, clearBeforeCopy, enabled: true, id: (Math.random() * 100000).toFixed() }; + this.views.push(newView); + if (camera && !Array.isArray(camera)) { + camera.onDisposeObservable.add(() => { + this.unRegisterView(canvas); + }); + } + return newView; +}; +AbstractEngine.prototype.unRegisterView = function (canvas) { + if (!this.views || this.views.length === 0) { + return this; + } + for (const view of this.views) { + if (view.target === canvas) { + const index = this.views.indexOf(view); + if (index !== -1) { + this.views.splice(index, 1); + } + break; + } + } + return this; +}; +AbstractEngine.prototype._renderViewStep = function (view) { + const canvas = view.target; + const context = canvas.getContext("2d"); + if (!context) { + return true; + } + const parent = this.getRenderingCanvas(); + _onBeforeViewRenderObservable.notifyObservers(view); + const camera = view.camera; + let previewCamera = null; + let previewCameras = null; + let scene = null; + if (camera) { + scene = Array.isArray(camera) ? camera[0].getScene() : camera.getScene(); + previewCamera = scene.activeCamera; + previewCameras = scene.activeCameras; + if (Array.isArray(camera)) { + scene.activeCameras = camera; + } + else { + scene.activeCamera = camera; + scene.activeCameras = null; + } + } + this.activeView = view; + if (view.customResize) { + view.customResize(canvas); + } + else { + // Set sizes + const width = Math.floor(canvas.clientWidth / this._hardwareScalingLevel); + const height = Math.floor(canvas.clientHeight / this._hardwareScalingLevel); + const dimsChanged = width !== canvas.width || parent.width !== canvas.width || height !== canvas.height || parent.height !== canvas.height; + if (canvas.clientWidth && canvas.clientHeight && dimsChanged) { + canvas.width = width; + canvas.height = height; + this.setSize(width, height); + } + } + if (!parent.width || !parent.height) { + return false; + } + // Render the frame + this._renderFrame(); + this.flushFramebuffer(); + // Copy to target + if (view.clearBeforeCopy) { + context.clearRect(0, 0, parent.width, parent.height); + } + context.drawImage(parent, 0, 0); + // Restore + if (scene) { + scene.activeCameras = previewCameras; + scene.activeCamera = previewCamera; + } + _onAfterViewRenderObservable.notifyObservers(view); + return true; +}; +AbstractEngine.prototype._renderViews = function () { + if (!this.views || this.views.length === 0) { + return false; + } + const parent = this.getRenderingCanvas(); + if (!parent) { + return false; + } + let inputElementView; + for (const view of this.views) { + if (!view.enabled) { + continue; + } + const canvas = view.target; + // Always render the view correspondent to the inputElement for last + if (canvas === this.inputElement) { + inputElementView = view; + continue; + } + if (!this._renderViewStep(view)) { + return false; + } + } + if (inputElementView) { + if (!this._renderViewStep(inputElementView)) { + return false; + } + } + this.activeView = null; + return true; +}; + +/* eslint-disable @typescript-eslint/no-unused-vars */ +AbstractEngine.prototype._debugPushGroup = function (groupName, targetObject) { }; +AbstractEngine.prototype._debugPopGroup = function (targetObject) { }; +AbstractEngine.prototype._debugInsertMarker = function (text, targetObject) { }; +AbstractEngine.prototype._debugFlushPendingCommands = function () { }; + +/** + * @internal + **/ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _TimeToken { + constructor() { + this._timeElapsedQueryEnded = false; + } +} + +ThinEngine.prototype.createQuery = function () { + const query = this._gl.createQuery(); + if (!query) { + throw new Error("Unable to create Occlusion Query"); + } + return query; +}; +ThinEngine.prototype.deleteQuery = function (query) { + this._gl.deleteQuery(query); + return this; +}; +ThinEngine.prototype.isQueryResultAvailable = function (query) { + return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE); +}; +ThinEngine.prototype.getQueryResult = function (query) { + return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT); +}; +ThinEngine.prototype.beginOcclusionQuery = function (algorithmType, query) { + const glAlgorithm = this._getGlAlgorithmType(algorithmType); + this._gl.beginQuery(glAlgorithm, query); + return true; +}; +ThinEngine.prototype.endOcclusionQuery = function (algorithmType) { + const glAlgorithm = this._getGlAlgorithmType(algorithmType); + this._gl.endQuery(glAlgorithm); + return this; +}; +ThinEngine.prototype._createTimeQuery = function () { + const timerQuery = this.getCaps().timerQuery; + if (timerQuery.createQueryEXT) { + return timerQuery.createQueryEXT(); + } + return this.createQuery(); +}; +ThinEngine.prototype._deleteTimeQuery = function (query) { + const timerQuery = this.getCaps().timerQuery; + if (timerQuery.deleteQueryEXT) { + timerQuery.deleteQueryEXT(query); + return; + } + this.deleteQuery(query); +}; +ThinEngine.prototype._getTimeQueryResult = function (query) { + const timerQuery = this.getCaps().timerQuery; + if (timerQuery.getQueryObjectEXT) { + return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT); + } + return this.getQueryResult(query); +}; +ThinEngine.prototype._getTimeQueryAvailability = function (query) { + const timerQuery = this.getCaps().timerQuery; + if (timerQuery.getQueryObjectEXT) { + return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT); + } + return this.isQueryResultAvailable(query); +}; +ThinEngine.prototype.startTimeQuery = function () { + const caps = this.getCaps(); + const timerQuery = caps.timerQuery; + if (!timerQuery) { + return null; + } + const token = new _TimeToken(); + this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT); + if (caps.canUseTimestampForTimerQuery) { + token._startTimeQuery = this._createTimeQuery(); + if (token._startTimeQuery) { + timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT); + } + } + else { + if (this._currentNonTimestampToken) { + return this._currentNonTimestampToken; + } + token._timeElapsedQuery = this._createTimeQuery(); + if (token._timeElapsedQuery) { + if (timerQuery.beginQueryEXT) { + timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery); + } + else { + this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery); + } + } + this._currentNonTimestampToken = token; + } + return token; +}; +ThinEngine.prototype.endTimeQuery = function (token) { + const caps = this.getCaps(); + const timerQuery = caps.timerQuery; + if (!timerQuery || !token) { + return -1; + } + if (caps.canUseTimestampForTimerQuery) { + if (!token._startTimeQuery) { + return -1; + } + if (!token._endTimeQuery) { + token._endTimeQuery = this._createTimeQuery(); + if (token._endTimeQuery) { + timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT); + } + } + } + else if (!token._timeElapsedQueryEnded) { + if (!token._timeElapsedQuery) { + return -1; + } + if (timerQuery.endQueryEXT) { + timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT); + } + else { + this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT); + this._currentNonTimestampToken = null; + } + token._timeElapsedQueryEnded = true; + } + const disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT); + let available = false; + if (token._endTimeQuery) { + available = this._getTimeQueryAvailability(token._endTimeQuery); + } + else if (token._timeElapsedQuery) { + available = this._getTimeQueryAvailability(token._timeElapsedQuery); + } + if (available && !disjoint) { + let result = 0; + if (caps.canUseTimestampForTimerQuery) { + if (!token._startTimeQuery || !token._endTimeQuery) { + return -1; + } + const timeStart = this._getTimeQueryResult(token._startTimeQuery); + const timeEnd = this._getTimeQueryResult(token._endTimeQuery); + result = timeEnd - timeStart; + this._deleteTimeQuery(token._startTimeQuery); + this._deleteTimeQuery(token._endTimeQuery); + token._startTimeQuery = null; + token._endTimeQuery = null; + } + else { + if (!token._timeElapsedQuery) { + return -1; + } + result = this._getTimeQueryResult(token._timeElapsedQuery); + this._deleteTimeQuery(token._timeElapsedQuery); + token._timeElapsedQuery = null; + token._timeElapsedQueryEnded = false; + } + return result; + } + return -1; +}; +ThinEngine.prototype.captureGPUFrameTime = function (value) { + if (value === this._captureGPUFrameTime) { + return; + } + this._captureGPUFrameTime = value; + if (value) { + const gpuFrameTime = this.getGPUFrameTimeCounter(); + this._onBeginFrameObserver = this.onBeginFrameObservable.add(() => { + if (!this._gpuFrameTimeToken) { + this._gpuFrameTimeToken = this.startTimeQuery(); + } + }); + this._onEndFrameObserver = this.onEndFrameObservable.add(() => { + if (!this._gpuFrameTimeToken) { + return; + } + const time = this.endTimeQuery(this._gpuFrameTimeToken); + if (time > -1) { + this._gpuFrameTimeToken = null; + gpuFrameTime.fetchNewFrame(); + gpuFrameTime.addCount(time, true); + } + }); + } + else { + this.onBeginFrameObservable.remove(this._onBeginFrameObserver); + this._onBeginFrameObserver = null; + this.onEndFrameObservable.remove(this._onEndFrameObserver); + this._onEndFrameObserver = null; + } +}; +ThinEngine.prototype._getGlAlgorithmType = function (algorithmType) { + return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED; +}; + +Engine.prototype.createTransformFeedback = function () { + const transformFeedback = this._gl.createTransformFeedback(); + if (!transformFeedback) { + throw new Error("Unable to create Transform Feedback"); + } + return transformFeedback; +}; +Engine.prototype.deleteTransformFeedback = function (value) { + this._gl.deleteTransformFeedback(value); +}; +Engine.prototype.bindTransformFeedback = function (value) { + this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value); +}; +Engine.prototype.beginTransformFeedback = function (usePoints = true) { + this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES); +}; +Engine.prototype.endTransformFeedback = function () { + this._gl.endTransformFeedback(); +}; +Engine.prototype.setTranformFeedbackVaryings = function (program, value) { + this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS); +}; +Engine.prototype.bindTransformFeedbackBuffer = function (value) { + this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value ? value.underlyingResource : null); +}; +Engine.prototype.readTransformFeedbackBuffer = function (target) { + this._gl.getBufferSubData(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, target); +}; + +ThinEngine.prototype.updateVideoTexture = function (texture, video, invertY) { + if (!texture || texture._isDisabled) { + return; + } + const glformat = this._getInternalFormat(texture.format); + const internalFormat = this._getRGBABufferInternalSizedFormat(0, texture.format); + const wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); + this._unpackFlipY(!invertY); // Video are upside down by default + try { + // Testing video texture support + if (this._videoTextureSupported === undefined) { + // clear old errors just in case. + this._gl.getError(); + this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, video); + if (this._gl.getError() !== 0) { + this._videoTextureSupported = false; + } + else { + this._videoTextureSupported = true; + } + } + // Copy video through the current working canvas if video texture is not supported + if (!this._videoTextureSupported) { + if (!texture._workingCanvas) { + texture._workingCanvas = this.createCanvas(texture.width, texture.height); + const context = texture._workingCanvas.getContext("2d"); + if (!context) { + throw new Error("Unable to get 2d context"); + } + texture._workingContext = context; + texture._workingCanvas.width = texture.width; + texture._workingCanvas.height = texture.height; + } + texture._workingContext.clearRect(0, 0, texture.width, texture.height); + texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height); + this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, texture._workingCanvas); + } + else { + this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, video); + } + if (texture.generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_2D); + } + if (!wasPreviouslyBound) { + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + } + // this.resetTextureCache(); + texture.isReady = true; + } + catch (ex) { + // Something unexpected + // Let's disable the texture + texture._isDisabled = true; + } +}; + +ThinEngine.prototype.restoreSingleAttachment = function () { + const gl = this._gl; + this.bindAttachments([gl.BACK]); +}; +ThinEngine.prototype.restoreSingleAttachmentForRenderTarget = function () { + const gl = this._gl; + this.bindAttachments([gl.COLOR_ATTACHMENT0]); +}; +ThinEngine.prototype.buildTextureLayout = function (textureStatus) { + const gl = this._gl; + const result = []; + for (let i = 0; i < textureStatus.length; i++) { + if (textureStatus[i]) { + result.push(gl["COLOR_ATTACHMENT" + i]); + } + else { + result.push(gl.NONE); + } + } + return result; +}; +ThinEngine.prototype.bindAttachments = function (attachments) { + const gl = this._gl; + gl.drawBuffers(attachments); +}; +ThinEngine.prototype.unBindMultiColorAttachmentFramebuffer = function (rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) { + this._currentRenderTarget = null; + if (!rtWrapper.disableAutomaticMSAAResolve) { + this.resolveMultiFramebuffer(rtWrapper); + } + if (!disableGenerateMipMaps) { + this.generateMipMapsMultiFramebuffer(rtWrapper); + } + if (onBeforeUnbind) { + if (rtWrapper._MSAAFramebuffer) { + // Bind the correct framebuffer + this._bindUnboundFramebuffer(rtWrapper._framebuffer); + } + onBeforeUnbind(); + } + this._bindUnboundFramebuffer(null); +}; +ThinEngine.prototype.createMultipleRenderTarget = function (size, options, initializeBuffers = true) { + let generateMipMaps = false; + let generateDepthBuffer = true; + let generateStencilBuffer = false; + let generateDepthTexture = false; + let depthTextureFormat = undefined; + let textureCount = 1; + let samples = 1; + const defaultType = 0; + const defaultSamplingMode = 3; + const defaultUseSRGBBuffer = false; + const defaultFormat = 5; + const defaultTarget = 3553; + let types = []; + let samplingModes = []; + let useSRGBBuffers = []; + let formats = []; + let targets = []; + let faceIndex = []; + let layerIndex = []; + let layers = []; + let labels = []; + let dontCreateTextures = false; + const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size); + if (options !== undefined) { + generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps; + generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; + generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer; + generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture; + textureCount = options.textureCount ?? 1; + samples = options.samples ?? samples; + types = options.types || types; + samplingModes = options.samplingModes || samplingModes; + useSRGBBuffers = options.useSRGBBuffers || useSRGBBuffers; + formats = options.formats || formats; + targets = options.targetTypes || targets; + faceIndex = options.faceIndex || faceIndex; + layerIndex = options.layerIndex || layerIndex; + layers = options.layerCounts || layers; + labels = options.labels || labels; + dontCreateTextures = options.dontCreateTextures ?? false; + if (this.webGLVersion > 1 && + (options.depthTextureFormat === 13 || + options.depthTextureFormat === 17 || + options.depthTextureFormat === 16 || + options.depthTextureFormat === 14 || + options.depthTextureFormat === 18)) { + depthTextureFormat = options.depthTextureFormat; + } + } + if (depthTextureFormat === undefined) { + depthTextureFormat = generateStencilBuffer ? 13 : 14; + } + const gl = this._gl; + // Create the framebuffer + const currentFramebuffer = this._currentFramebuffer; + const framebuffer = gl.createFramebuffer(); + this._bindUnboundFramebuffer(framebuffer); + const width = size.width ?? size; + const height = size.height ?? size; + const textures = []; + const attachments = []; + const useStencilTexture = this.webGLVersion > 1 && + (depthTextureFormat === 13 || + depthTextureFormat === 17 || + depthTextureFormat === 18); + rtWrapper.label = options?.label ?? "MultiRenderTargetWrapper"; + rtWrapper._framebuffer = framebuffer; + rtWrapper._generateDepthBuffer = generateDepthTexture || generateDepthBuffer; + rtWrapper._generateStencilBuffer = generateDepthTexture ? useStencilTexture : generateStencilBuffer; + rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, width, height, 1, depthTextureFormat); + rtWrapper._attachments = attachments; + for (let i = 0; i < textureCount; i++) { + let samplingMode = samplingModes[i] || defaultSamplingMode; + let type = types[i] || defaultType; + let useSRGBBuffer = useSRGBBuffers[i] || defaultUseSRGBBuffer; + const format = formats[i] || defaultFormat; + const target = targets[i] || defaultTarget; + const layerCount = layers[i] ?? 1; + if (type === 1 && !this._caps.textureFloatLinearFiltering) { + // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE + samplingMode = 1; + } + else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { + // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE + samplingMode = 1; + } + const filters = this._getSamplingParameters(samplingMode, generateMipMaps); + if (type === 1 && !this._caps.textureFloat) { + type = 0; + Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"); + } + useSRGBBuffer = useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU); + const isWebGL2 = this.webGLVersion > 1; + const attachment = gl[isWebGL2 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; + attachments.push(attachment); + if (target === -1 || dontCreateTextures) { + continue; + } + const texture = new InternalTexture(this, 6 /* InternalTextureSource.MultiRenderTarget */); + textures[i] = texture; + gl.activeTexture(gl["TEXTURE" + i]); + gl.bindTexture(target, texture._hardwareTexture.underlyingResource); + gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filters.mag); + gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filters.min); + gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + const internalSizedFormat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer); + const internalFormat = this._getInternalFormat(format); + const webGLTextureType = this._getWebGLTextureType(type); + if (isWebGL2 && (target === 35866 || target === 32879)) { + if (target === 35866) { + texture.is2DArray = true; + } + else { + texture.is3D = true; + } + texture.baseDepth = texture.depth = layerCount; + gl.texImage3D(target, 0, internalSizedFormat, width, height, layerCount, 0, internalFormat, webGLTextureType, null); + } + else if (target === 34067) { + // We have to generate all faces to complete the framebuffer + for (let i = 0; i < 6; i++) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null); + } + texture.isCube = true; + } + else { + gl.texImage2D(gl.TEXTURE_2D, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null); + } + if (generateMipMaps) { + gl.generateMipmap(target); + } + // Unbind + this._bindTextureDirectly(target, null); + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.isReady = true; + texture.samples = 1; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.type = type; + texture._useSRGBBuffer = useSRGBBuffer; + texture.format = format; + texture.label = labels[i] ?? rtWrapper.label + "-Texture" + i; + this._internalTexturesCache.push(texture); + } + if (generateDepthTexture && this._caps.depthTextureExtension && !dontCreateTextures) { + // Depth texture + const depthTexture = new InternalTexture(this, 14 /* InternalTextureSource.Depth */); + let depthTextureType = 5; + let glDepthTextureInternalFormat = gl.DEPTH_COMPONENT16; + let glDepthTextureFormat = gl.DEPTH_COMPONENT; + let glDepthTextureType = gl.UNSIGNED_SHORT; + let glDepthTextureAttachment = gl.DEPTH_ATTACHMENT; + if (this.webGLVersion < 2) { + glDepthTextureInternalFormat = gl.DEPTH_COMPONENT; + } + else { + if (depthTextureFormat === 14) { + depthTextureType = 1; + glDepthTextureType = gl.FLOAT; + glDepthTextureInternalFormat = gl.DEPTH_COMPONENT32F; + } + else if (depthTextureFormat === 18) { + depthTextureType = 0; + glDepthTextureType = gl.FLOAT_32_UNSIGNED_INT_24_8_REV; + glDepthTextureInternalFormat = gl.DEPTH32F_STENCIL8; + glDepthTextureFormat = gl.DEPTH_STENCIL; + glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT; + } + else if (depthTextureFormat === 16) { + depthTextureType = 0; + glDepthTextureType = gl.UNSIGNED_INT; + glDepthTextureInternalFormat = gl.DEPTH_COMPONENT24; + glDepthTextureAttachment = gl.DEPTH_ATTACHMENT; + } + else if (depthTextureFormat === 13 || depthTextureFormat === 17) { + depthTextureType = 12; + glDepthTextureType = gl.UNSIGNED_INT_24_8; + glDepthTextureInternalFormat = gl.DEPTH24_STENCIL8; + glDepthTextureFormat = gl.DEPTH_STENCIL; + glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT; + } + } + this._bindTextureDirectly(gl.TEXTURE_2D, depthTexture, true); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, glDepthTextureInternalFormat, width, height, 0, glDepthTextureFormat, glDepthTextureType, null); + gl.framebufferTexture2D(gl.FRAMEBUFFER, glDepthTextureAttachment, gl.TEXTURE_2D, depthTexture._hardwareTexture.underlyingResource, 0); + this._bindTextureDirectly(gl.TEXTURE_2D, null); + rtWrapper._depthStencilTexture = depthTexture; + rtWrapper._depthStencilTextureWithStencil = useStencilTexture; + depthTexture.baseWidth = width; + depthTexture.baseHeight = height; + depthTexture.width = width; + depthTexture.height = height; + depthTexture.isReady = true; + depthTexture.samples = 1; + depthTexture.generateMipMaps = generateMipMaps; + depthTexture.samplingMode = 1; + depthTexture.format = depthTextureFormat; + depthTexture.type = depthTextureType; + depthTexture.label = rtWrapper.label + "-DepthStencil"; + textures[textureCount] = depthTexture; + this._internalTexturesCache.push(depthTexture); + } + rtWrapper.setTextures(textures); + if (initializeBuffers) { + gl.drawBuffers(attachments); + } + this._bindUnboundFramebuffer(currentFramebuffer); + rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex); + this.resetTextureCache(); + if (!dontCreateTextures) { + this.updateMultipleRenderTargetTextureSampleCount(rtWrapper, samples, initializeBuffers); + } + else if (samples > 1) { + const framebuffer = gl.createFramebuffer(); + if (!framebuffer) { + throw new Error("Unable to create multi sampled framebuffer"); + } + rtWrapper._samples = samples; + rtWrapper._MSAAFramebuffer = framebuffer; + if (textureCount > 0 && initializeBuffers) { + this._bindUnboundFramebuffer(framebuffer); + gl.drawBuffers(attachments); + this._bindUnboundFramebuffer(currentFramebuffer); + } + } + return rtWrapper; +}; +ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function (rtWrapper, samples, initializeBuffers = true) { + if (this.webGLVersion < 2 || !rtWrapper) { + return 1; + } + if (rtWrapper.samples === samples) { + return samples; + } + const gl = this._gl; + samples = Math.min(samples, this.getCaps().maxMSAASamples); + // Dispose previous render buffers + if (rtWrapper._depthStencilBuffer) { + gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer); + rtWrapper._depthStencilBuffer = null; + } + if (rtWrapper._MSAAFramebuffer) { + gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer); + rtWrapper._MSAAFramebuffer = null; + } + const count = rtWrapper._attachments.length; // We do it this way instead of rtWrapper.textures.length to avoid taking into account the depth/stencil texture, in case it has been created + for (let i = 0; i < count; i++) { + const texture = rtWrapper.textures[i]; + const hardwareTexture = texture._hardwareTexture; + hardwareTexture?.releaseMSAARenderBuffers(); + } + if (samples > 1 && typeof gl.renderbufferStorageMultisample === "function") { + const framebuffer = gl.createFramebuffer(); + if (!framebuffer) { + throw new Error("Unable to create multi sampled framebuffer"); + } + rtWrapper._MSAAFramebuffer = framebuffer; + this._bindUnboundFramebuffer(framebuffer); + const attachments = []; + for (let i = 0; i < count; i++) { + const texture = rtWrapper.textures[i]; + const hardwareTexture = texture._hardwareTexture; + const attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; + const colorRenderbuffer = this._createRenderBuffer(texture.width, texture.height, samples, -1 /* not used */, this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer), attachment); + if (!colorRenderbuffer) { + throw new Error("Unable to create multi sampled framebuffer"); + } + hardwareTexture.addMSAARenderBuffer(colorRenderbuffer); + texture.samples = samples; + attachments.push(attachment); + } + if (initializeBuffers) { + gl.drawBuffers(attachments); + } + } + else { + this._bindUnboundFramebuffer(rtWrapper._framebuffer); + } + const depthFormat = rtWrapper._depthStencilTexture ? rtWrapper._depthStencilTexture.format : undefined; + rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.width, rtWrapper.height, samples, depthFormat); + this._bindUnboundFramebuffer(null); + rtWrapper._samples = samples; + return samples; +}; +ThinEngine.prototype.generateMipMapsMultiFramebuffer = function (texture) { + const rtWrapper = texture; + const gl = this._gl; + if (!rtWrapper.isMulti) { + return; + } + for (let i = 0; i < rtWrapper._attachments.length; i++) { + const texture = rtWrapper.textures[i]; + if (texture?.generateMipMaps && !texture?.isCube && !texture?.is3D) { + this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); + gl.generateMipmap(gl.TEXTURE_2D); + this._bindTextureDirectly(gl.TEXTURE_2D, null); + } + } +}; +ThinEngine.prototype.resolveMultiFramebuffer = function (texture) { + const rtWrapper = texture; + const gl = this._gl; + if (!rtWrapper._MSAAFramebuffer || !rtWrapper.isMulti) { + return; + } + let bufferBits = rtWrapper.resolveMSAAColors ? gl.COLOR_BUFFER_BIT : 0; + bufferBits |= rtWrapper._generateDepthBuffer && rtWrapper.resolveMSAADepth ? gl.DEPTH_BUFFER_BIT : 0; + bufferBits |= rtWrapper._generateStencilBuffer && rtWrapper.resolveMSAAStencil ? gl.STENCIL_BUFFER_BIT : 0; + const attachments = rtWrapper._attachments; + const count = attachments.length; + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, rtWrapper._MSAAFramebuffer); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, rtWrapper._framebuffer); + for (let i = 0; i < count; i++) { + const texture = rtWrapper.textures[i]; + for (let j = 0; j < count; j++) { + attachments[j] = gl.NONE; + } + attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; + gl.readBuffer(attachments[i]); + gl.drawBuffers(attachments); + gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, bufferBits, gl.NEAREST); + } + for (let i = 0; i < count; i++) { + attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; + } + gl.drawBuffers(attachments); + gl.bindFramebuffer(this._gl.FRAMEBUFFER, rtWrapper._MSAAFramebuffer); +}; + +/** @internal */ +var ComputeBindingType; +(function (ComputeBindingType) { + ComputeBindingType[ComputeBindingType["Texture"] = 0] = "Texture"; + ComputeBindingType[ComputeBindingType["StorageTexture"] = 1] = "StorageTexture"; + ComputeBindingType[ComputeBindingType["UniformBuffer"] = 2] = "UniformBuffer"; + ComputeBindingType[ComputeBindingType["StorageBuffer"] = 3] = "StorageBuffer"; + ComputeBindingType[ComputeBindingType["TextureWithoutSampler"] = 4] = "TextureWithoutSampler"; + ComputeBindingType[ComputeBindingType["Sampler"] = 5] = "Sampler"; + ComputeBindingType[ComputeBindingType["ExternalTexture"] = 6] = "ExternalTexture"; + ComputeBindingType[ComputeBindingType["DataBuffer"] = 7] = "DataBuffer"; +})(ComputeBindingType || (ComputeBindingType = {})); +ThinEngine.prototype.createComputeEffect = function (baseName, options) { + throw new Error("createComputeEffect: This engine does not support compute shaders!"); +}; +ThinEngine.prototype.createComputePipelineContext = function () { + throw new Error("createComputePipelineContext: This engine does not support compute shaders!"); +}; +ThinEngine.prototype.createComputeContext = function () { + return undefined; +}; +ThinEngine.prototype.computeDispatch = function (effect, context, bindings, x, y, z, bindingsMapping) { + throw new Error("computeDispatch: This engine does not support compute shaders!"); +}; +ThinEngine.prototype.computeDispatchIndirect = function (effect, context, bindings, buffer, offset, bindingsMapping) { + throw new Error("computeDispatchIndirect: This engine does not support compute shaders!"); +}; +ThinEngine.prototype.areAllComputeEffectsReady = function () { + return true; +}; +ThinEngine.prototype.releaseComputeEffects = function () { }; +ThinEngine.prototype._prepareComputePipelineContext = function (pipelineContext, computeSourceCode, rawComputeSourceCode, defines, entryPoint) { }; +ThinEngine.prototype._rebuildComputeEffects = function () { }; +AbstractEngine.prototype._executeWhenComputeStateIsCompiled = function (pipelineContext, action) { + action(null); +}; +ThinEngine.prototype._releaseComputeEffect = function (effect) { }; +ThinEngine.prototype._deleteComputePipelineContext = function (pipelineContext) { }; + +function transformTextureUrl(url) { + const excludeFn = (entry) => { + const strRegExPattern = "\\b" + entry + "\\b"; + return url && (url === entry || url.match(new RegExp(strRegExPattern, "g"))); + }; + if (this._excludedCompressedTextures && this._excludedCompressedTextures.some(excludeFn)) { + return url; + } + const lastDot = url.lastIndexOf("."); + const lastQuestionMark = url.lastIndexOf("?"); + const querystring = lastQuestionMark > -1 ? url.substring(lastQuestionMark, url.length) : ""; + return (lastDot > -1 ? url.substring(0, lastDot) : url) + this._textureFormatInUse + querystring; +} +Object.defineProperty(Engine.prototype, "texturesSupported", { + get: function () { + // Intelligently add supported compressed formats in order to check for. + // Check for ASTC support first as it is most powerful and to be very cross platform. + // Next PVRTC & DXT, which are probably superior to ETC1/2. + // Likely no hardware which supports both PVR & DXT, so order matters little. + // ETC2 is newer and handles ETC1 (no alpha capability), so check for first. + const texturesSupported = []; + if (this._caps.astc) { + texturesSupported.push("-astc.ktx"); + } + if (this._caps.s3tc) { + texturesSupported.push("-dxt.ktx"); + } + if (this._caps.pvrtc) { + texturesSupported.push("-pvrtc.ktx"); + } + if (this._caps.etc2) { + texturesSupported.push("-etc2.ktx"); + } + if (this._caps.etc1) { + texturesSupported.push("-etc1.ktx"); + } + return texturesSupported; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(Engine.prototype, "textureFormatInUse", { + get: function () { + return this._textureFormatInUse || null; + }, + enumerable: true, + configurable: true, +}); +Engine.prototype.setCompressedTextureExclusions = function (skippedFiles) { + this._excludedCompressedTextures = skippedFiles; +}; +Engine.prototype.setTextureFormatToUse = function (formatsAvailable) { + const texturesSupported = this.texturesSupported; + for (let i = 0, len1 = texturesSupported.length; i < len1; i++) { + for (let j = 0, len2 = formatsAvailable.length; j < len2; j++) { + if (texturesSupported[i] === formatsAvailable[j].toLowerCase()) { + this._transformTextureUrl = transformTextureUrl.bind(this); + return (this._textureFormatInUse = texturesSupported[i]); + } + } + } + // actively set format to nothing, to allow this to be called more than once + // and possibly fail the 2nd time + this._textureFormatInUse = ""; + this._transformTextureUrl = null; + return null; +}; + +/** @internal */ +class NativeDataStream { + constructor() { + const buffer = new ArrayBuffer(NativeDataStream.DEFAULT_BUFFER_SIZE); + this._uint32s = new Uint32Array(buffer); + this._int32s = new Int32Array(buffer); + this._float32s = new Float32Array(buffer); + this._length = NativeDataStream.DEFAULT_BUFFER_SIZE / 4; + this._position = 0; + this._nativeDataStream = new _native.NativeDataStream(() => { + this._flush(); + }); + } + /** + * Writes a uint32 to the stream + * @param value the value to write + */ + writeUint32(value) { + this._flushIfNecessary(1); + this._uint32s[this._position++] = value; + } + /** + * Writes an int32 to the stream + * @param value the value to write + */ + writeInt32(value) { + this._flushIfNecessary(1); + this._int32s[this._position++] = value; + } + /** + * Writes a float32 to the stream + * @param value the value to write + */ + writeFloat32(value) { + this._flushIfNecessary(1); + this._float32s[this._position++] = value; + } + /** + * Writes a uint32 array to the stream + * @param values the values to write + */ + writeUint32Array(values) { + this._flushIfNecessary(1 + values.length); + this._uint32s[this._position++] = values.length; + this._uint32s.set(values, this._position); + this._position += values.length; + } + /** + * Writes an int32 array to the stream + * @param values the values to write + */ + writeInt32Array(values) { + this._flushIfNecessary(1 + values.length); + this._uint32s[this._position++] = values.length; + this._int32s.set(values, this._position); + this._position += values.length; + } + /** + * Writes a float32 array to the stream + * @param values the values to write + */ + writeFloat32Array(values) { + this._flushIfNecessary(1 + values.length); + this._uint32s[this._position++] = values.length; + this._float32s.set(values, this._position); + this._position += values.length; + } + /** + * Writes native data to the stream + * @param handle the handle to the native data + */ + writeNativeData(handle) { + this._flushIfNecessary(handle.length); + this._uint32s.set(handle, this._position); + this._position += handle.length; + } + /** + * Writes a boolean to the stream + * @param value the value to write + */ + writeBoolean(value) { + this.writeUint32(value ? 1 : 0); + } + _flushIfNecessary(required) { + if (this._position + required > this._length) { + this._flush(); + } + } + _flush() { + this._nativeDataStream.writeBuffer(this._uint32s.buffer, this._position); + this._position = 0; + } +} +// Must be multiple of 4! +// eslint-disable-next-line @typescript-eslint/naming-convention +NativeDataStream.DEFAULT_BUFFER_SIZE = 65536; + +/** + * Extracts the characters between two markers (for eg, between "(" and ")"). The function handles nested markers as well as markers inside strings (delimited by ", ' or `) and comments + * @param markerOpen opening marker + * @param markerClose closing marker + * @param block code block to parse + * @param startIndex starting index in block where the extraction must start. The character at block[startIndex] should be the markerOpen character! + * @returns index of the last character for the extraction (or -1 if the string is invalid - no matching closing marker found). The string to extract (without the markers) is the string between startIndex + 1 and the returned value (exclusive) + */ +function ExtractBetweenMarkers(markerOpen, markerClose, block, startIndex) { + let currPos = startIndex, openMarkers = 0, waitForChar = ""; + while (currPos < block.length) { + const currChar = block.charAt(currPos); + if (!waitForChar) { + switch (currChar) { + case markerOpen: + openMarkers++; + break; + case markerClose: + openMarkers--; + break; + case '"': + case "'": + case "`": + waitForChar = currChar; + break; + case "/": + if (currPos + 1 < block.length) { + const nextChar = block.charAt(currPos + 1); + if (nextChar === "/") { + waitForChar = "\n"; + } + else if (nextChar === "*") { + waitForChar = "*/"; + } + } + break; + } + } + else { + if (currChar === waitForChar) { + if (waitForChar === '"' || waitForChar === "'") { + block.charAt(currPos - 1) !== "\\" && (waitForChar = ""); + } + else { + waitForChar = ""; + } + } + else if (waitForChar === "*/" && currChar === "*" && currPos + 1 < block.length) { + block.charAt(currPos + 1) === "/" && (waitForChar = ""); + if (waitForChar === "") { + currPos++; + } + } + } + currPos++; + if (openMarkers === 0) { + break; + } + } + return openMarkers === 0 ? currPos - 1 : -1; +} +/** + * Parses a string and skip whitespaces + * @param s string to parse + * @param index index where to start parsing + * @returns the index after all whitespaces have been skipped + */ +function SkipWhitespaces(s, index) { + while (index < s.length) { + const c = s[index]; + if (c !== " " && c !== "\n" && c !== "\r" && c !== "\t" && c !== "\u000a" && c !== "\u00a0") { + break; + } + index++; + } + return index; +} +/** + * Checks if a character is an identifier character (meaning, if it is 0-9, A-Z, a-z or _) + * @param c character to check + * @returns true if the character is an identifier character + */ +function IsIdentifierChar(c) { + const v = c.charCodeAt(0); + return ((v >= 48 && v <= 57) || // 0-9 + (v >= 65 && v <= 90) || // A-Z + (v >= 97 && v <= 122) || // a-z + v == 95); // _ +} +/** + * Removes the comments of a code block + * @param block code block to parse + * @returns block with the comments removed + */ +function RemoveComments(block) { + let currPos = 0, waitForChar = "", inComments = false; + const s = []; + while (currPos < block.length) { + const currChar = block.charAt(currPos); + if (!waitForChar) { + switch (currChar) { + case '"': + case "'": + case "`": + waitForChar = currChar; + break; + case "/": + if (currPos + 1 < block.length) { + const nextChar = block.charAt(currPos + 1); + if (nextChar === "/") { + waitForChar = "\n"; + inComments = true; + } + else if (nextChar === "*") { + waitForChar = "*/"; + inComments = true; + } + } + break; + } + if (!inComments) { + s.push(currChar); + } + } + else { + if (currChar === waitForChar) { + if (waitForChar === '"' || waitForChar === "'") { + block.charAt(currPos - 1) !== "\\" && (waitForChar = ""); + s.push(currChar); + } + else { + waitForChar = ""; + inComments = false; + } + } + else if (waitForChar === "*/" && currChar === "*" && currPos + 1 < block.length) { + block.charAt(currPos + 1) === "/" && (waitForChar = ""); + if (waitForChar === "") { + inComments = false; + currPos++; + } + } + else { + if (!inComments) { + s.push(currChar); + } + } + } + currPos++; + } + return s.join(""); +} +/** + * Finds the first occurrence of a character in a string going backward + * @param s the string to parse + * @param index starting index in the string + * @param c the character to find + * @param c2 an optional second character to find + * @returns the index of the character if found, else -1 + */ +function FindBackward(s, index, c, c2) { + while (index >= 0 && s.charAt(index) !== c && (s.charAt(index) !== c2)) { + index--; + } + return index; +} +/** + * Escapes a string so that it is usable as a regular expression + * @param s string to escape + * @returns escaped string + */ +function EscapeRegExp(s) { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +/** + * Injects code at the beginning and/or end of a function. + * The function is identified by "mainFuncDecl". The starting code is injected just after the first "\{" found after the mainFuncDecl. + * The ending code is injected just before the last "\}" of the whole block of code (so, it is assumed that the function is the last of the block of code). + * @param code code to inject into + * @param mainFuncDecl Function declaration to find in the code (for eg: "void main") + * @param startingCode The code to inject at the beginning of the function + * @param endingCode The code to inject at the end of the function + * @returns The code with the injected code + */ +function InjectStartingAndEndingCode(code, mainFuncDecl, startingCode, endingCode) { + let idx = code.indexOf(mainFuncDecl); + if (idx < 0) { + return code; + } + if (startingCode) { + // eslint-disable-next-line no-empty + while (idx++ < code.length && code.charAt(idx) != "{") { } + if (idx < code.length) { + const part1 = code.substring(0, idx + 1); + const part2 = code.substring(idx + 1); + code = part1 + startingCode + part2; + } + } + if (endingCode) { + const lastClosingCurly = code.lastIndexOf("}"); + code = code.substring(0, lastClosingCurly); + code += endingCode + "\n}"; + } + return code; +} + +/** + * Class used to inline functions in shader code + */ +class ShaderCodeInliner { + /** Gets the code after the inlining process */ + get code() { + return this._sourceCode; + } + /** + * Initializes the inliner + * @param sourceCode shader code source to inline + * @param numMaxIterations maximum number of iterations (used to detect recursive calls) + */ + constructor(sourceCode, numMaxIterations = 20) { + /** Gets or sets the debug mode */ + this.debug = false; + this._sourceCode = sourceCode; + this._numMaxIterations = numMaxIterations; + this._functionDescr = []; + this.inlineToken = "#define inline"; + } + /** + * Start the processing of the shader code + */ + processCode() { + if (this.debug) { + Logger.Log(`Start inlining process (code size=${this._sourceCode.length})...`); + } + this._collectFunctions(); + this._processInlining(this._numMaxIterations); + if (this.debug) { + Logger.Log("End of inlining process."); + } + } + _collectFunctions() { + let startIndex = 0; + while (startIndex < this._sourceCode.length) { + // locate the function to inline and extract its name + const inlineTokenIndex = this._sourceCode.indexOf(this.inlineToken, startIndex); + if (inlineTokenIndex < 0) { + break; + } + const funcParamsStartIndex = this._sourceCode.indexOf("(", inlineTokenIndex + this.inlineToken.length); + if (funcParamsStartIndex < 0) { + if (this.debug) { + Logger.Warn(`Could not find the opening parenthesis after the token. startIndex=${startIndex}`); + } + startIndex = inlineTokenIndex + this.inlineToken.length; + continue; + } + const funcNameMatch = ShaderCodeInliner._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex)); + if (!funcNameMatch) { + if (this.debug) { + Logger.Warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex)}`); + } + startIndex = inlineTokenIndex + this.inlineToken.length; + continue; + } + const [funcType, funcName] = [funcNameMatch[3], funcNameMatch[4]]; + // extract the parameters of the function as a whole string (without the leading / trailing parenthesis) + const funcParamsEndIndex = ExtractBetweenMarkers("(", ")", this._sourceCode, funcParamsStartIndex); + if (funcParamsEndIndex < 0) { + if (this.debug) { + Logger.Warn(`Could not extract the parameters the function '${funcName}' (type=${funcType}). funcParamsStartIndex=${funcParamsStartIndex}`); + } + startIndex = inlineTokenIndex + this.inlineToken.length; + continue; + } + const funcParams = this._sourceCode.substring(funcParamsStartIndex + 1, funcParamsEndIndex); + // extract the body of the function (with the curly brackets) + const funcBodyStartIndex = SkipWhitespaces(this._sourceCode, funcParamsEndIndex + 1); + if (funcBodyStartIndex === this._sourceCode.length) { + if (this.debug) { + Logger.Warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcParamsEndIndex=${funcParamsEndIndex}`); + } + startIndex = inlineTokenIndex + this.inlineToken.length; + continue; + } + const funcBodyEndIndex = ExtractBetweenMarkers("{", "}", this._sourceCode, funcBodyStartIndex); + if (funcBodyEndIndex < 0) { + if (this.debug) { + Logger.Warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcBodyStartIndex=${funcBodyStartIndex}`); + } + startIndex = inlineTokenIndex + this.inlineToken.length; + continue; + } + const funcBody = this._sourceCode.substring(funcBodyStartIndex, funcBodyEndIndex + 1); + // process the parameters: extract each names + const params = RemoveComments(funcParams).split(","); + const paramNames = []; + for (let p = 0; p < params.length; ++p) { + const param = params[p].trim(); + const idx = param.lastIndexOf(" "); + if (idx >= 0) { + paramNames.push(param.substring(idx + 1)); + } + } + if (funcType !== "void") { + // for functions that return a value, we will replace "return" by "tempvarname = ", tempvarname being a unique generated name + paramNames.push("return"); + } + // collect the function + this._functionDescr.push({ + name: funcName, + type: funcType, + parameters: paramNames, + body: funcBody, + callIndex: 0, + }); + startIndex = funcBodyEndIndex + 1; + // remove the function from the source code + const partBefore = inlineTokenIndex > 0 ? this._sourceCode.substring(0, inlineTokenIndex) : ""; + const partAfter = funcBodyEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(funcBodyEndIndex + 1) : ""; + this._sourceCode = partBefore + partAfter; + startIndex -= funcBodyEndIndex + 1 - inlineTokenIndex; + } + if (this.debug) { + Logger.Log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=${this._functionDescr}`); + } + } + _processInlining(numMaxIterations = 20) { + while (numMaxIterations-- >= 0) { + if (!this._replaceFunctionCallsByCode()) { + break; + } + } + if (this.debug) { + Logger.Log(`numMaxIterations is ${numMaxIterations} after inlining process`); + } + return numMaxIterations >= 0; + } + _replaceFunctionCallsByCode() { + let doAgain = false; + for (const func of this._functionDescr) { + const { name, type, parameters, body } = func; + let startIndex = 0; + while (startIndex < this._sourceCode.length) { + // Look for the function name in the source code + const functionCallIndex = this._sourceCode.indexOf(name, startIndex); + if (functionCallIndex < 0) { + break; + } + // Make sure "name" is not part of a bigger string + if (functionCallIndex === 0 || IsIdentifierChar(this._sourceCode.charAt(functionCallIndex - 1))) { + startIndex = functionCallIndex + name.length; + continue; + } + // Find the opening parenthesis + const callParamsStartIndex = SkipWhitespaces(this._sourceCode, functionCallIndex + name.length); + if (callParamsStartIndex === this._sourceCode.length || this._sourceCode.charAt(callParamsStartIndex) !== "(") { + startIndex = functionCallIndex + name.length; + continue; + } + // extract the parameters of the function call as a whole string (without the leading / trailing parenthesis) + const callParamsEndIndex = ExtractBetweenMarkers("(", ")", this._sourceCode, callParamsStartIndex); + if (callParamsEndIndex < 0) { + if (this.debug) { + Logger.Warn(`Could not extract the parameters of the function call. Function '${name}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}`); + } + startIndex = functionCallIndex + name.length; + continue; + } + const callParams = this._sourceCode.substring(callParamsStartIndex + 1, callParamsEndIndex); + // process the parameter call: extract each names + // this function split the parameter list used in the function call at ',' boundaries by taking care of potential parenthesis like in: + // myfunc(a, vec2(1., 0.), 4.) + const splitParameterCall = (s) => { + const parameters = []; + let curIdx = 0, startParamIdx = 0; + while (curIdx < s.length) { + if (s.charAt(curIdx) === "(") { + const idx2 = ExtractBetweenMarkers("(", ")", s, curIdx); + if (idx2 < 0) { + return null; + } + curIdx = idx2; + } + else if (s.charAt(curIdx) === ",") { + parameters.push(s.substring(startParamIdx, curIdx)); + startParamIdx = curIdx + 1; + } + curIdx++; + } + if (startParamIdx < curIdx) { + parameters.push(s.substring(startParamIdx, curIdx)); + } + return parameters; + }; + const params = splitParameterCall(RemoveComments(callParams)); + if (params === null) { + if (this.debug) { + Logger.Warn(`Invalid function call: can't extract the parameters of the function call. Function '${name}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}, callParams=` + + callParams); + } + startIndex = functionCallIndex + name.length; + continue; + } + const paramNames = []; + for (let p = 0; p < params.length; ++p) { + const param = params[p].trim(); + paramNames.push(param); + } + const retParamName = type !== "void" ? name + "_" + func.callIndex++ : null; + if (retParamName) { + paramNames.push(retParamName + " ="); + } + if (paramNames.length !== parameters.length) { + if (this.debug) { + Logger.Warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${name}' (type=${type}). function parameters=${parameters}, call parameters=${paramNames}`); + } + startIndex = functionCallIndex + name.length; + continue; + } + startIndex = callParamsEndIndex + 1; + // replace the function call by the body function + const funcBody = this._replaceNames(body, parameters, paramNames); + let partBefore = functionCallIndex > 0 ? this._sourceCode.substring(0, functionCallIndex) : ""; + const partAfter = callParamsEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(callParamsEndIndex + 1) : ""; + if (retParamName) { + // case where the function returns a value. We generate: + // FUNCTYPE retParamName; + // {function body} + // and replace the function call by retParamName + const injectDeclarationIndex = FindBackward(this._sourceCode, functionCallIndex - 1, "\n", "{"); + partBefore = this._sourceCode.substring(0, injectDeclarationIndex + 1); + const partBetween = this._sourceCode.substring(injectDeclarationIndex + 1, functionCallIndex); + this._sourceCode = partBefore + type + " " + retParamName + ";\n" + funcBody + "\n" + partBetween + retParamName + partAfter; + if (this.debug) { + Logger.Log(`Replace function call by code. Function '${name}' (type=${type}). injectDeclarationIndex=${injectDeclarationIndex}, call parameters=${paramNames}`); + } + } + else { + // simple case where the return value of the function is "void" + this._sourceCode = partBefore + funcBody + partAfter; + startIndex += funcBody.length - (callParamsEndIndex + 1 - functionCallIndex); + if (this.debug) { + Logger.Log(`Replace function call by code. Function '${name}' (type=${type}). functionCallIndex=${functionCallIndex}, call parameters=${paramNames}`); + } + } + doAgain = true; + } + } + return doAgain; + } + _replaceNames(code, sources, destinations) { + for (let i = 0; i < sources.length; ++i) { + const source = new RegExp(EscapeRegExp(sources[i]), "g"), sourceLen = sources[i].length, destination = destinations[i]; + code = code.replace(source, (match, ...args) => { + const offset = args[0]; + // Make sure "source" is not part of a bigger identifier (for eg, if source=view and we matched it with viewDirection) + if (IsIdentifierChar(code.charAt(offset - 1)) || IsIdentifierChar(code.charAt(offset + sourceLen))) { + return sources[i]; + } + return destination; + }); + } + return code; + } +} +ShaderCodeInliner._RegexpFindFunctionNameAndType = /((\s+?)(\w+)\s+(\w+)\s*?)$/; + +const varyingRegex = /(flat\s)?\s*varying\s*.*/; +/** @internal */ +class NativeShaderProcessor { + constructor() { + this.shaderLanguage = 0 /* ShaderLanguage.GLSL */; + } + initializeShaders(processingContext) { + this._nativeProcessingContext = processingContext; + if (this._nativeProcessingContext) { + this._nativeProcessingContext.remappedAttributeNames = {}; + this._nativeProcessingContext.injectInVertexMain = ""; + } + } + attributeProcessor(attribute) { + if (!this._nativeProcessingContext) { + return attribute.replace("attribute", "in"); + } + const attribRegex = /\s*(?:attribute|in)\s+(\S+)\s+(\S+)\s*;/gm; + const match = attribRegex.exec(attribute); + if (match !== null) { + const attributeType = match[1]; + const name = match[2]; + const numComponents = this._nativeProcessingContext.vertexBufferKindToNumberOfComponents[name]; + if (numComponents !== undefined) { + // Special case for an int/ivecX vertex buffer that is used as a float/vecX attribute in the shader. + const newType = numComponents < 0 ? (numComponents === -1 ? "int" : "ivec" + -numComponents) : numComponents === 1 ? "uint" : "uvec" + numComponents; + const newName = `_int_${name}_`; + attribute = attribute.replace(match[0], `in ${newType} ${newName}; ${attributeType} ${name};`); + this._nativeProcessingContext.injectInVertexMain += `${name} = ${attributeType}(${newName});\n`; + this._nativeProcessingContext.remappedAttributeNames[name] = newName; + } + else { + attribute = attribute.replace(match[0], `in ${attributeType} ${name};`); + } + } + return attribute; + } + varyingCheck(varying, _isFragment) { + return varyingRegex.test(varying); + } + varyingProcessor(varying, isFragment) { + return varying.replace("varying", isFragment ? "in" : "out"); + } + postProcessor(code, defines, isFragment) { + const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1; + // Remove extensions + const regex = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g; + code = code.replace(regex, ""); + // Replace instructions + code = code.replace(/texture2D\s*\(/g, "texture("); + if (isFragment) { + const hasOutput = code.search(/layout *\(location *= *0\) *out/g) !== -1; + code = code.replace(/texture2DLodEXT\s*\(/g, "textureLod("); + code = code.replace(/textureCubeLodEXT\s*\(/g, "textureLod("); + code = code.replace(/textureCube\s*\(/g, "texture("); + code = code.replace(/gl_FragDepthEXT/g, "gl_FragDepth"); + code = code.replace(/gl_FragColor/g, "glFragColor"); + code = code.replace(/gl_FragData/g, "glFragData"); + code = code.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension || hasOutput ? "" : "layout(location = 0) out vec4 glFragColor;\n") + "void main("); + } + else { + if (this._nativeProcessingContext?.injectInVertexMain) { + code = InjectStartingAndEndingCode(code, "void main", this._nativeProcessingContext.injectInVertexMain); + } + const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1; + if (hasMultiviewExtension) { + return "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n" + code; + } + } + return code; + } +} + +class NativePipelineContext { + get isReady() { + if (this.compilationError) { + const message = this.compilationError.message; + throw new Error("SHADER ERROR" + (typeof message === "string" ? "\n" + message : "")); + } + return this.isCompiled; + } + _getVertexShaderCode() { + return null; + } + _getFragmentShaderCode() { + return null; + } + constructor(engine, isAsync, shaderProcessingContext) { + this.isCompiled = false; + this.vertexBufferKindToType = {}; + this._valueCache = {}; + this._engine = engine; + this.isAsync = isAsync; + this.shaderProcessingContext = shaderProcessingContext; + } + _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) { + const engine = this._engine; + if (engine.supportsUniformBuffers) { + for (const name in uniformBuffersNames) { + effect.bindUniformBlock(name, uniformBuffersNames[name]); + } + } + const effectAvailableUniforms = this._engine.getUniforms(this, uniformsNames); + effectAvailableUniforms.forEach((uniform, index) => { + uniforms[uniformsNames[index]] = uniform; + }); + this._uniforms = uniforms; + let index; + for (index = 0; index < samplerList.length; index++) { + const sampler = effect.getUniform(samplerList[index]); + if (sampler == null) { + samplerList.splice(index, 1); + index--; + } + } + samplerList.forEach((name, index) => { + samplers[name] = index; + }); + attributes.push(...engine.getAttributes(this, attributesNames)); + } + setEngine(engine) { + this._engine = engine; + } + /** + * Release all associated resources. + **/ + dispose() { + this._uniforms = {}; + } + /** + * @internal + */ + _cacheMatrix(uniformName, matrix) { + const cache = this._valueCache[uniformName]; + const flag = matrix.updateFlag; + if (cache !== undefined && cache === flag) { + return false; + } + this._valueCache[uniformName] = flag; + return true; + } + /** + * @internal + */ + _cacheFloat2(uniformName, x, y) { + let cache = this._valueCache[uniformName]; + if (!cache) { + cache = [x, y]; + this._valueCache[uniformName] = cache; + return true; + } + let changed = false; + if (cache[0] !== x) { + cache[0] = x; + changed = true; + } + if (cache[1] !== y) { + cache[1] = y; + changed = true; + } + return changed; + } + /** + * @internal + */ + _cacheFloat3(uniformName, x, y, z) { + let cache = this._valueCache[uniformName]; + if (!cache) { + cache = [x, y, z]; + this._valueCache[uniformName] = cache; + return true; + } + let changed = false; + if (cache[0] !== x) { + cache[0] = x; + changed = true; + } + if (cache[1] !== y) { + cache[1] = y; + changed = true; + } + if (cache[2] !== z) { + cache[2] = z; + changed = true; + } + return changed; + } + /** + * @internal + */ + _cacheFloat4(uniformName, x, y, z, w) { + let cache = this._valueCache[uniformName]; + if (!cache) { + cache = [x, y, z, w]; + this._valueCache[uniformName] = cache; + return true; + } + let changed = false; + if (cache[0] !== x) { + cache[0] = x; + changed = true; + } + if (cache[1] !== y) { + cache[1] = y; + changed = true; + } + if (cache[2] !== z) { + cache[2] = z; + changed = true; + } + if (cache[3] !== w) { + cache[3] = w; + changed = true; + } + return changed; + } + /** + * Sets an integer value on a uniform variable. + * @param uniformName Name of the variable. + * @param value Value to be set. + */ + setInt(uniformName, value) { + const cache = this._valueCache[uniformName]; + if (cache !== undefined && cache === value) { + return; + } + if (this._engine.setInt(this._uniforms[uniformName], value)) { + this._valueCache[uniformName] = value; + } + } + /** + * Sets a int2 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int2. + * @param y Second int in int2. + */ + setInt2(uniformName, x, y) { + if (this._cacheFloat2(uniformName, x, y)) { + if (!this._engine.setInt2(this._uniforms[uniformName], x, y)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a int3 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int3. + * @param y Second int in int3. + * @param z Third int in int3. + */ + setInt3(uniformName, x, y, z) { + if (this._cacheFloat3(uniformName, x, y, z)) { + if (!this._engine.setInt3(this._uniforms[uniformName], x, y, z)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a int4 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int4. + * @param y Second int in int4. + * @param z Third int in int4. + * @param w Fourth int in int4. + */ + setInt4(uniformName, x, y, z, w) { + if (this._cacheFloat4(uniformName, x, y, z, w)) { + if (!this._engine.setInt4(this._uniforms[uniformName], x, y, z, w)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets an int array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setIntArray(this._uniforms[uniformName], array); + } + /** + * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray2(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setIntArray2(this._uniforms[uniformName], array); + } + /** + * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray3(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setIntArray3(this._uniforms[uniformName], array); + } + /** + * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray4(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setIntArray4(this._uniforms[uniformName], array); + } + /** + * Sets an unsigned integer value on a uniform variable. + * @param uniformName Name of the variable. + * @param value Value to be set. + */ + setUInt(uniformName, value) { + const cache = this._valueCache[uniformName]; + if (cache !== undefined && cache === value) { + return; + } + if (this._engine.setUInt(this._uniforms[uniformName], value)) { + this._valueCache[uniformName] = value; + } + } + /** + * Sets a unsigned int2 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint2. + * @param y Second unsigned int in uint2. + */ + setUInt2(uniformName, x, y) { + if (this._cacheFloat2(uniformName, x, y)) { + if (!this._engine.setUInt2(this._uniforms[uniformName], x, y)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a unsigned int3 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint3. + * @param y Second unsigned int in uint3. + * @param z Third unsigned int in uint3. + */ + setUInt3(uniformName, x, y, z) { + if (this._cacheFloat3(uniformName, x, y, z)) { + if (!this._engine.setUInt3(this._uniforms[uniformName], x, y, z)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a unsigned int4 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint4. + * @param y Second unsigned int in uint4. + * @param z Third unsigned int in uint4. + * @param w Fourth unsigned int in uint4. + */ + setUInt4(uniformName, x, y, z, w) { + if (this._cacheFloat4(uniformName, x, y, z, w)) { + if (!this._engine.setUInt4(this._uniforms[uniformName], x, y, z, w)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets an unsigned int array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setUIntArray(this._uniforms[uniformName], array); + } + /** + * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray2(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setUIntArray2(this._uniforms[uniformName], array); + } + /** + * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray3(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setUIntArray3(this._uniforms[uniformName], array); + } + /** + * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray4(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setUIntArray4(this._uniforms[uniformName], array); + } + /** + * Sets an float array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setFloatArray(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setFloatArray(this._uniforms[uniformName], array); + } + /** + * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setFloatArray2(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setFloatArray2(this._uniforms[uniformName], array); + } + /** + * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setFloatArray3(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setFloatArray3(this._uniforms[uniformName], array); + } + /** + * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setFloatArray4(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setFloatArray4(this._uniforms[uniformName], array); + } + /** + * Sets an array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setArray(this._uniforms[uniformName], array); + } + /** + * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray2(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setArray2(this._uniforms[uniformName], array); + } + /** + * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray3(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setArray3(this._uniforms[uniformName], array); + } + /** + * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray4(uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setArray4(this._uniforms[uniformName], array); + } + /** + * Sets matrices on a uniform variable. + * @param uniformName Name of the variable. + * @param matrices matrices to be set. + */ + setMatrices(uniformName, matrices) { + if (!matrices) { + return; + } + this._valueCache[uniformName] = null; + this._engine.setMatrices(this._uniforms[uniformName], matrices); + } + /** + * Sets matrix on a uniform variable. + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + */ + setMatrix(uniformName, matrix) { + if (this._cacheMatrix(uniformName, matrix)) { + if (!this._engine.setMatrices(this._uniforms[uniformName], matrix.asArray())) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix) + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + */ + setMatrix3x3(uniformName, matrix) { + this._valueCache[uniformName] = null; + this._engine.setMatrix3x3(this._uniforms[uniformName], matrix); + } + /** + * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix) + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + */ + setMatrix2x2(uniformName, matrix) { + this._valueCache[uniformName] = null; + this._engine.setMatrix2x2(this._uniforms[uniformName], matrix); + } + /** + * Sets a float on a uniform variable. + * @param uniformName Name of the variable. + * @param value value to be set. + */ + setFloat(uniformName, value) { + const cache = this._valueCache[uniformName]; + if (cache !== undefined && cache === value) { + return; + } + if (this._engine.setFloat(this._uniforms[uniformName], value)) { + this._valueCache[uniformName] = value; + } + } + /** + * Sets a boolean on a uniform variable. + * @param uniformName Name of the variable. + * @param bool value to be set. + */ + setBool(uniformName, bool) { + const cache = this._valueCache[uniformName]; + if (cache !== undefined && cache === bool) { + return; + } + if (this._engine.setInt(this._uniforms[uniformName], bool ? 1 : 0)) { + this._valueCache[uniformName] = bool ? 1 : 0; + } + } + /** + * Sets a Vector2 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector2 vector2 to be set. + */ + setVector2(uniformName, vector2) { + if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) { + if (!this._engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a float2 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float2. + * @param y Second float in float2. + */ + setFloat2(uniformName, x, y) { + if (this._cacheFloat2(uniformName, x, y)) { + if (!this._engine.setFloat2(this._uniforms[uniformName], x, y)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Vector3 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector3 Value to be set. + */ + setVector3(uniformName, vector3) { + if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) { + if (!this._engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a float3 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float3. + * @param y Second float in float3. + * @param z Third float in float3. + */ + setFloat3(uniformName, x, y, z) { + if (this._cacheFloat3(uniformName, x, y, z)) { + if (!this._engine.setFloat3(this._uniforms[uniformName], x, y, z)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Vector4 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector4 Value to be set. + */ + setVector4(uniformName, vector4) { + if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) { + if (!this._engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Quaternion on a uniform variable. + * @param uniformName Name of the variable. + * @param quaternion Value to be set. + */ + setQuaternion(uniformName, quaternion) { + if (this._cacheFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w)) { + if (!this._engine.setFloat4(this._uniforms[uniformName], quaternion.x, quaternion.y, quaternion.z, quaternion.w)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a float4 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float4. + * @param y Second float in float4. + * @param z Third float in float4. + * @param w Fourth float in float4. + */ + setFloat4(uniformName, x, y, z, w) { + if (this._cacheFloat4(uniformName, x, y, z, w)) { + if (!this._engine.setFloat4(this._uniforms[uniformName], x, y, z, w)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Color3 on a uniform variable. + * @param uniformName Name of the variable. + * @param color3 Value to be set. + */ + setColor3(uniformName, color3) { + if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) { + if (!this._engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Color4 on a uniform variable. + * @param uniformName Name of the variable. + * @param color3 Value to be set. + * @param alpha Alpha value to be set. + */ + setColor4(uniformName, color3, alpha) { + if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) { + if (!this._engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha)) { + this._valueCache[uniformName] = null; + } + } + } + /** + * Sets a Color4 on a uniform variable + * @param uniformName defines the name of the variable + * @param color4 defines the value to be set + */ + setDirectColor4(uniformName, color4) { + if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) { + if (!this._engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a)) { + this._valueCache[uniformName] = null; + } + } + } +} + +class NativeRenderTargetWrapper extends RenderTargetWrapper { + get _framebuffer() { + return this.__framebuffer; + } + set _framebuffer(framebuffer) { + if (this.__framebuffer) { + this._engine._releaseFramebufferObjects(this.__framebuffer); + } + this.__framebuffer = framebuffer; + } + get _framebufferDepthStencil() { + return this.__framebufferDepthStencil; + } + set _framebufferDepthStencil(framebufferDepthStencil) { + if (this.__framebufferDepthStencil) { + this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil); + } + this.__framebufferDepthStencil = framebufferDepthStencil; + } + constructor(isMulti, isCube, size, engine) { + super(isMulti, isCube, size, engine); + // eslint-disable-next-line @typescript-eslint/naming-convention + this.__framebuffer = null; + // eslint-disable-next-line @typescript-eslint/naming-convention + this.__framebufferDepthStencil = null; + this._engine = engine; + } + dispose(disposeOnlyFramebuffers = false) { + this._framebuffer = null; + this._framebufferDepthStencil = null; + super.dispose(disposeOnlyFramebuffers); + } +} + +/** @internal */ +class NativeHardwareTexture { + get underlyingResource() { + return this._nativeTexture; + } + constructor(existingTexture, engine) { + this._engine = engine; + this.set(existingTexture); + } + setUsage() { } + set(hardwareTexture) { + this._nativeTexture = hardwareTexture; + } + reset() { + this._nativeTexture = null; + } + release() { + if (this._nativeTexture) { + this._engine.deleteTexture(this._nativeTexture); + } + this.reset(); + } +} + +function getNativeTextureFormat(format, type) { + switch (format) { + // Depth (type is ignored) + case 15: + return _native.Engine.TEXTURE_FORMAT_D16; + case 16: + return _native.Engine.TEXTURE_FORMAT_D24; + case 13: + return _native.Engine.TEXTURE_FORMAT_D24S8; + case 14: + return _native.Engine.TEXTURE_FORMAT_D32F; + // Compressed (type is ignored) + case 36492: + return _native.Engine.TEXTURE_FORMAT_BC7; + case 36494: + return _native.Engine.TEXTURE_FORMAT_BC6H; + case 33779: + return _native.Engine.TEXTURE_FORMAT_BC3; + case 33778: + return _native.Engine.TEXTURE_FORMAT_BC2; + case 33777: + return _native.Engine.TEXTURE_FORMAT_BC1; + case 33776: + return _native.Engine.TEXTURE_FORMAT_BC1; + case 37808: + return _native.Engine.TEXTURE_FORMAT_ASTC4x4; + case 36196: + return _native.Engine.TEXTURE_FORMAT_ETC1; + case 37492: + return _native.Engine.TEXTURE_FORMAT_ETC2; + case 37496: + return _native.Engine.TEXTURE_FORMAT_ETC2A; + case 4: { + switch (type) { + case 0: + return _native.Engine.TEXTURE_FORMAT_RGB8; + case 3: + return _native.Engine.TEXTURE_FORMAT_RGB8S; + case 6: + return _native.Engine.TEXTURE_FORMAT_RGB8I; + case 7: + return _native.Engine.TEXTURE_FORMAT_RGB8U; + } + break; + } + case 5: { + switch (type) { + case 0: + return _native.Engine.TEXTURE_FORMAT_RGBA8; + case 1: + return _native.Engine.TEXTURE_FORMAT_RGBA32F; + case 2: + return _native.Engine.TEXTURE_FORMAT_RGBA16F; + case 3: + return _native.Engine.TEXTURE_FORMAT_RGBA8S; + case 4: + return _native.Engine.TEXTURE_FORMAT_RGBA16I; + case 5: + return _native.Engine.TEXTURE_FORMAT_RGBA16U; + case 6: + return _native.Engine.TEXTURE_FORMAT_RGBA32I; + case 7: + return _native.Engine.TEXTURE_FORMAT_RGBA32U; + } + break; + } + case 6: { + switch (type) { + case 0: + return _native.Engine.TEXTURE_FORMAT_R8; + case 1: + return _native.Engine.TEXTURE_FORMAT_R32F; + case 2: + return _native.Engine.TEXTURE_FORMAT_R16F; + case 3: + return _native.Engine.TEXTURE_FORMAT_R8S; + case 4: + return _native.Engine.TEXTURE_FORMAT_R16S; + case 5: + return _native.Engine.TEXTURE_FORMAT_R16U; + case 6: + return _native.Engine.TEXTURE_FORMAT_R32I; + case 7: + return _native.Engine.TEXTURE_FORMAT_R32U; + } + break; + } + case 7: { + switch (type) { + case 0: + return _native.Engine.TEXTURE_FORMAT_RG8; + case 1: + return _native.Engine.TEXTURE_FORMAT_RG32F; + case 2: + return _native.Engine.TEXTURE_FORMAT_RG16F; + case 3: + return _native.Engine.TEXTURE_FORMAT_RG8S; + case 4: + return _native.Engine.TEXTURE_FORMAT_RG16S; + case 5: + return _native.Engine.TEXTURE_FORMAT_RG16U; + case 6: + return _native.Engine.TEXTURE_FORMAT_RG32I; + case 7: + return _native.Engine.TEXTURE_FORMAT_RG32U; + } + break; + } + case 12: { + switch (type) { + case 0: + return _native.Engine.TEXTURE_FORMAT_BGRA8; + } + break; + } + } + throw new RuntimeError(`Unsupported texture format or type: format ${format}, type ${type}.`, ErrorCodes.UnsupportedTextureError); +} +function getNativeSamplingMode(samplingMode) { + switch (samplingMode) { + case 1: + return _native.Engine.TEXTURE_NEAREST_NEAREST; + case 2: + return _native.Engine.TEXTURE_LINEAR_LINEAR; + case 3: + return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; + case 4: + return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST; + case 5: + return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST; + case 6: + return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR; + case 7: + return _native.Engine.TEXTURE_NEAREST_LINEAR; + case 8: + return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; + case 9: + return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST; + case 10: + return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR; + case 11: + return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; + case 12: + return _native.Engine.TEXTURE_LINEAR_NEAREST; + default: + throw new Error(`Unsupported sampling mode: ${samplingMode}.`); + } +} +function getNativeAddressMode(wrapMode) { + switch (wrapMode) { + case 1: + return _native.Engine.ADDRESS_MODE_WRAP; + case 0: + return _native.Engine.ADDRESS_MODE_CLAMP; + case 2: + return _native.Engine.ADDRESS_MODE_MIRROR; + default: + throw new Error("Unexpected wrap mode: " + wrapMode + "."); + } +} +function getNativeStencilFunc(func) { + switch (func) { + case 513: + return _native.Engine.STENCIL_TEST_LESS; + case 515: + return _native.Engine.STENCIL_TEST_LEQUAL; + case 514: + return _native.Engine.STENCIL_TEST_EQUAL; + case 518: + return _native.Engine.STENCIL_TEST_GEQUAL; + case 516: + return _native.Engine.STENCIL_TEST_GREATER; + case 517: + return _native.Engine.STENCIL_TEST_NOTEQUAL; + case 512: + return _native.Engine.STENCIL_TEST_NEVER; + case 519: + return _native.Engine.STENCIL_TEST_ALWAYS; + default: + throw new Error(`Unsupported stencil func mode: ${func}.`); + } +} +function getNativeStencilOpFail(opFail) { + switch (opFail) { + case 7680: + return _native.Engine.STENCIL_OP_FAIL_S_KEEP; + case 0: + return _native.Engine.STENCIL_OP_FAIL_S_ZERO; + case 7681: + return _native.Engine.STENCIL_OP_FAIL_S_REPLACE; + case 7682: + return _native.Engine.STENCIL_OP_FAIL_S_INCR; + case 7683: + return _native.Engine.STENCIL_OP_FAIL_S_DECR; + case 5386: + return _native.Engine.STENCIL_OP_FAIL_S_INVERT; + case 34055: + return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT; + case 34056: + return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT; + default: + throw new Error(`Unsupported stencil OpFail mode: ${opFail}.`); + } +} +function getNativeStencilDepthFail(depthFail) { + switch (depthFail) { + case 7680: + return _native.Engine.STENCIL_OP_FAIL_Z_KEEP; + case 0: + return _native.Engine.STENCIL_OP_FAIL_Z_ZERO; + case 7681: + return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE; + case 7682: + return _native.Engine.STENCIL_OP_FAIL_Z_INCR; + case 7683: + return _native.Engine.STENCIL_OP_FAIL_Z_DECR; + case 5386: + return _native.Engine.STENCIL_OP_FAIL_Z_INVERT; + case 34055: + return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT; + case 34056: + return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT; + default: + throw new Error(`Unsupported stencil depthFail mode: ${depthFail}.`); + } +} +function getNativeStencilDepthPass(opPass) { + switch (opPass) { + case 7680: + return _native.Engine.STENCIL_OP_PASS_Z_KEEP; + case 0: + return _native.Engine.STENCIL_OP_PASS_Z_ZERO; + case 7681: + return _native.Engine.STENCIL_OP_PASS_Z_REPLACE; + case 7682: + return _native.Engine.STENCIL_OP_PASS_Z_INCR; + case 7683: + return _native.Engine.STENCIL_OP_PASS_Z_DECR; + case 5386: + return _native.Engine.STENCIL_OP_PASS_Z_INVERT; + case 34055: + return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT; + case 34056: + return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT; + default: + throw new Error(`Unsupported stencil opPass mode: ${opPass}.`); + } +} +function getNativeAlphaMode(mode) { + switch (mode) { + case 0: + return _native.Engine.ALPHA_DISABLE; + case 1: + return _native.Engine.ALPHA_ADD; + case 2: + return _native.Engine.ALPHA_COMBINE; + case 3: + return _native.Engine.ALPHA_SUBTRACT; + case 4: + return _native.Engine.ALPHA_MULTIPLY; + case 5: + return _native.Engine.ALPHA_MAXIMIZED; + case 6: + return _native.Engine.ALPHA_ONEONE; + case 7: + return _native.Engine.ALPHA_PREMULTIPLIED; + case 8: + return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF; + case 9: + return _native.Engine.ALPHA_INTERPOLATE; + case 10: + return _native.Engine.ALPHA_SCREENMODE; + default: + throw new Error(`Unsupported alpha mode: ${mode}.`); + } +} +function getNativeAttribType(type) { + switch (type) { + case VertexBuffer.BYTE: + return _native.Engine.ATTRIB_TYPE_INT8; + case VertexBuffer.UNSIGNED_BYTE: + return _native.Engine.ATTRIB_TYPE_UINT8; + case VertexBuffer.SHORT: + return _native.Engine.ATTRIB_TYPE_INT16; + case VertexBuffer.UNSIGNED_SHORT: + return _native.Engine.ATTRIB_TYPE_UINT16; + case VertexBuffer.FLOAT: + return _native.Engine.ATTRIB_TYPE_FLOAT; + default: + throw new Error(`Unsupported attribute type: ${type}.`); + } +} + +const vertexBufferKindForNonFloatProcessing = { + [VertexBuffer.PositionKind]: true, + [VertexBuffer.NormalKind]: true, + [VertexBuffer.TangentKind]: true, + [VertexBuffer.UVKind]: true, + [VertexBuffer.UV2Kind]: true, + [VertexBuffer.UV3Kind]: true, + [VertexBuffer.UV4Kind]: true, + [VertexBuffer.UV5Kind]: true, + [VertexBuffer.UV6Kind]: true, + [VertexBuffer.ColorKind]: true, + [VertexBuffer.ColorInstanceKind]: true, + [VertexBuffer.MatricesIndicesKind]: true, + [VertexBuffer.MatricesWeightsKind]: true, + [VertexBuffer.MatricesIndicesExtraKind]: true, + [VertexBuffer.MatricesWeightsExtraKind]: true, +}; +/** + * Indicates if the type is a signed or unsigned type + * @param type Type to check + * @returns True if it is a signed type + */ +function isSignedType(type) { + switch (type) { + case VertexBuffer.BYTE: + case VertexBuffer.SHORT: + case VertexBuffer.INT: + case VertexBuffer.FLOAT: + return true; + case VertexBuffer.UNSIGNED_BYTE: + case VertexBuffer.UNSIGNED_SHORT: + case VertexBuffer.UNSIGNED_INT: + return false; + default: + throw new Error(`Invalid type '${type}'`); + } +} +/** + * Checks whether some vertex buffers that should be of type float are of a different type (int, byte...). + * If so, trigger a shader recompilation to give the shader processor the opportunity to update the code accordingly. + * @param vertexBuffers List of vertex buffers to check + * @param effect The effect (shaders) that should be recompiled if needed + */ +function checkNonFloatVertexBuffers(vertexBuffers, effect) { + const engine = effect.getEngine(); + const pipelineContext = effect._pipelineContext; + if (!pipelineContext?.vertexBufferKindToType) { + return; + } + let shaderProcessingContext = null; + for (const kind in vertexBuffers) { + const currentVertexBuffer = vertexBuffers[kind]; + if (!currentVertexBuffer || !vertexBufferKindForNonFloatProcessing[kind]) { + continue; + } + const currentVertexBufferType = currentVertexBuffer.normalized ? VertexBuffer.FLOAT : currentVertexBuffer.type; + const vertexBufferType = pipelineContext.vertexBufferKindToType[kind]; + if ((currentVertexBufferType !== VertexBuffer.FLOAT && vertexBufferType === undefined) || + (vertexBufferType !== undefined && vertexBufferType !== currentVertexBufferType)) { + if (!shaderProcessingContext) { + shaderProcessingContext = engine._getShaderProcessingContext(effect.shaderLanguage, false); + } + pipelineContext.vertexBufferKindToType[kind] = currentVertexBufferType; + if (currentVertexBufferType !== VertexBuffer.FLOAT) { + shaderProcessingContext.vertexBufferKindToNumberOfComponents[kind] = VertexBuffer.DeduceStride(kind); + if (isSignedType(currentVertexBufferType)) { + shaderProcessingContext.vertexBufferKindToNumberOfComponents[kind] *= -1; + } + } + } + } + if (shaderProcessingContext) { + // We temporarily disable parallel compilation of shaders because we want new shaders to be compiled after the _processShaderCode call, so that they are in effect for the rest of the frame. + // There is no additional call to async so the _processShaderCodeAsync will execute synchronously. + const parallelShaderCompile = engine._caps.parallelShaderCompile; + engine._caps.parallelShaderCompile = undefined; + effect._processShaderCodeAsync(null, engine._features._checkNonFloatVertexBuffersDontRecreatePipelineContext, shaderProcessingContext); + engine._caps.parallelShaderCompile = parallelShaderCompile; + } +} + +/** + * @internal + */ +class NativeShaderProcessingContext { + constructor() { + this.vertexBufferKindToNumberOfComponents = {}; + this.remappedAttributeNames = {}; + this.injectInVertexMain = ""; + } +} + +const onNativeObjectInitialized = new Observable(); +if (typeof self !== "undefined" && !Object.prototype.hasOwnProperty.call(self, "_native")) { + let __native; + Object.defineProperty(self, "_native", { + get: () => __native, + set: (value) => { + __native = value; + if (__native) { + onNativeObjectInitialized.notifyObservers(__native); + } + }, + }); +} +/** + * Returns _native only after it has been defined by BabylonNative. + * @internal + */ +function AcquireNativeObjectAsync() { + return new Promise((resolve) => { + if (typeof _native === "undefined") { + onNativeObjectInitialized.addOnce((nativeObject) => resolve(nativeObject)); + } + else { + resolve(_native); + } + }); +} +/** + * Registers a constructor on the _native object. See NativeXRFrame for an example. + * @internal + */ +async function RegisterNativeTypeAsync(typeName, constructor) { + (await AcquireNativeObjectAsync())[typeName] = constructor; +} +/** + * Container for accessors for natively-stored mesh data buffers. + */ +class NativeDataBuffer extends DataBuffer { +} +/** @internal */ +class CommandBufferEncoder { + constructor(_engine) { + this._engine = _engine; + this._pending = new Array(); + this._isCommandBufferScopeActive = false; + this._commandStream = NativeEngine._createNativeDataStream(); + this._engine.setCommandDataStream(this._commandStream); + } + beginCommandScope() { + if (this._isCommandBufferScopeActive) { + throw new Error("Command scope already active."); + } + this._isCommandBufferScopeActive = true; + } + endCommandScope() { + if (!this._isCommandBufferScopeActive) { + throw new Error("Command scope is not active."); + } + this._isCommandBufferScopeActive = false; + this._submit(); + } + startEncodingCommand(command) { + this._commandStream.writeNativeData(command); + } + encodeCommandArgAsUInt32(commandArg) { + this._commandStream.writeUint32(commandArg); + } + encodeCommandArgAsUInt32s(commandArg) { + this._commandStream.writeUint32Array(commandArg); + } + encodeCommandArgAsInt32(commandArg) { + this._commandStream.writeInt32(commandArg); + } + encodeCommandArgAsInt32s(commandArg) { + this._commandStream.writeInt32Array(commandArg); + } + encodeCommandArgAsFloat32(commandArg) { + this._commandStream.writeFloat32(commandArg); + } + encodeCommandArgAsFloat32s(commandArg) { + this._commandStream.writeFloat32Array(commandArg); + } + encodeCommandArgAsNativeData(commandArg) { + this._commandStream.writeNativeData(commandArg); + this._pending.push(commandArg); + } + finishEncodingCommand() { + if (!this._isCommandBufferScopeActive) { + this._submit(); + } + } + _submit() { + this._engine.submitCommands(); + this._pending.length = 0; + } +} +const remappedAttributesNames = []; +/** @internal */ +class NativeEngine extends Engine { + setHardwareScalingLevel(level) { + super.setHardwareScalingLevel(level); + this._engine.setHardwareScalingLevel(level); + } + constructor(options = {}) { + super(null, false, undefined, options.adaptToDeviceRatio); + this._engine = new _native.Engine({ + version: Engine.Version, + nonFloatVertexBuffers: true, + }); + this._camera = _native.Camera ? new _native.Camera() : null; + this._commandBufferEncoder = new CommandBufferEncoder(this._engine); + this._frameStats = { gpuTimeNs: Number.NaN }; + this._boundBuffersVertexArray = null; + this._currentDepthTest = _native.Engine.DEPTH_TEST_LEQUAL; + this._stencilTest = false; + this._stencilMask = 255; + this._stencilFunc = 519; + this._stencilFuncRef = 0; + this._stencilFuncMask = 255; + this._stencilOpStencilFail = 7680; + this._stencilOpDepthFail = 7680; + this._stencilOpStencilDepthPass = 7681; + this._zOffset = 0; + this._zOffsetUnits = 0; + this._depthWrite = true; + // warning for non supported fill mode has already been displayed + this._fillModeWarningDisplayed = false; + if (_native.Engine.PROTOCOL_VERSION !== NativeEngine.PROTOCOL_VERSION) { + throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${NativeEngine.PROTOCOL_VERSION} (JS)`); + } + if (this._engine.setDeviceLostCallback) { + this._engine.setDeviceLostCallback(() => { + this.onContextLostObservable.notifyObservers(this); + this._contextWasLost = true; + this._restoreEngineAfterContextLost(); + }); + } + this._webGLVersion = 2; + this.disableUniformBuffers = true; + this._shaderPlatformName = "NATIVE"; + // TODO: Initialize this more correctly based on the hardware capabilities. + // Init caps + this._caps = { + maxTexturesImageUnits: 16, + maxVertexTextureImageUnits: 16, + maxCombinedTexturesImageUnits: 32, + maxTextureSize: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE, + maxCubemapTextureSize: 512, + maxRenderTextureSize: 512, + maxVertexAttribs: 16, + maxVaryingVectors: 16, + maxDrawBuffers: 8, + maxFragmentUniformVectors: 16, + maxVertexUniformVectors: 16, + standardDerivatives: true, + astc: null, + pvrtc: null, + etc1: null, + etc2: null, + bptc: null, + maxAnisotropy: 16, // TODO: Retrieve this smartly. Currently set to D3D11 maximum allowable value. + uintIndices: true, + fragmentDepthSupported: false, + highPrecisionShaderSupported: true, + colorBufferFloat: false, + supportFloatTexturesResolve: false, + rg11b10ufColorRenderable: false, + textureFloat: true, + textureFloatLinearFiltering: true, + textureFloatRender: true, + textureHalfFloat: true, + textureHalfFloatLinearFiltering: true, + textureHalfFloatRender: true, + textureLOD: true, + texelFetch: false, + drawBuffersExtension: false, + depthTextureExtension: false, + vertexArrayObject: true, + instancedArrays: true, + supportOcclusionQuery: false, + canUseTimestampForTimerQuery: false, + blendMinMax: false, + maxMSAASamples: 16, + canUseGLInstanceID: true, + canUseGLVertexID: true, + supportComputeShaders: false, + supportSRGBBuffers: true, + supportTransformFeedbacks: false, + textureMaxLevel: false, + texture2DArrayMaxLayerCount: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS, + disableMorphTargetTexture: false, + parallelShaderCompile: { COMPLETION_STATUS_KHR: 0 }, + textureNorm16: false, + }; + this._features = { + forceBitmapOverHTMLImageElement: true, + supportRenderAndCopyToLodForFloatTextures: false, + supportDepthStencilTexture: false, + supportShadowSamplers: false, + uniformBufferHardCheckMatrix: false, + allowTexturePrefiltering: false, + trackUbosInFrame: false, + checkUbosContentBeforeUpload: false, + supportCSM: false, + basisNeedsPOT: false, + support3DTextures: false, + needTypeSuffixInShaderConstants: false, + supportMSAA: true, + supportSSAO2: false, + supportIBLShadows: false, + supportExtendedTextureFormats: false, + supportSwitchCaseInShader: false, + supportSyncTextureRead: false, + needsInvertingBitmap: true, + useUBOBindingCache: true, + needShaderCodeInlining: true, + needToAlwaysBindUniformBuffers: false, + supportRenderPasses: true, + supportSpriteInstancing: false, + forceVertexBufferStrideAndOffsetMultiple4Bytes: true, + _checkNonFloatVertexBuffersDontRecreatePipelineContext: false, + _collectUbosUpdatedInFrame: false, + }; + Tools.Log("Babylon Native (v" + Engine.Version + ") launched"); + Tools.LoadScript = function (scriptUrl, onSuccess, onError, scriptId) { + Tools.LoadFile(scriptUrl, (data) => { + Function(data).apply(null); + if (onSuccess) { + onSuccess(); + } + }, undefined, undefined, false, (request, exception) => { + if (onError) { + onError("LoadScript Error", exception); + } + }); + }; + // Wrappers + if (typeof URL === "undefined") { + window.URL = { + createObjectURL: function () { }, + revokeObjectURL: function () { }, + }; + } + if (typeof Blob === "undefined") { + window.Blob = function (v) { + return v; + }; + } + // polyfill for Chakra + if (!Array.prototype.flat) { + Object.defineProperty(Array.prototype, "flat", { + configurable: true, + value: function flat() { + const depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]); + return depth + ? Array.prototype.reduce.call(this, function (acc, cur) { + if (Array.isArray(cur)) { + acc.push.apply(acc, flat.call(cur, depth - 1)); + } + else { + acc.push(cur); + } + return acc; + }, []) + : Array.prototype.slice.call(this); + }, + writable: true, + }); + } + // Currently we do not fully configure the ThinEngine on construction of NativeEngine. + // Setup resolution scaling based on display settings. + const devicePixelRatio = window ? window.devicePixelRatio || 1.0 : 1.0; + this._hardwareScalingLevel = options.adaptToDeviceRatio ? 1.0 / devicePixelRatio : 1.0; + this._engine.setHardwareScalingLevel(this._hardwareScalingLevel); + this._lastDevicePixelRatio = devicePixelRatio; + this.resize(); + const currentDepthFunction = this.getDepthFunction(); + if (currentDepthFunction) { + this.setDepthFunction(currentDepthFunction); + } + // Shader processor + this._shaderProcessor = new NativeShaderProcessor(); + this.onNewSceneAddedObservable.add((scene) => { + const originalRender = scene.render; + scene.render = (...args) => { + this._commandBufferEncoder.beginCommandScope(); + originalRender.apply(scene, args); + this._commandBufferEncoder.endCommandScope(); + }; + }); + } + dispose() { + super.dispose(); + if (this._boundBuffersVertexArray) { + this._deleteVertexArray(this._boundBuffersVertexArray); + } + this._engine.dispose(); + } + /** @internal */ + static _createNativeDataStream() { + return new NativeDataStream(); + } + /** + * Can be used to override the current requestAnimationFrame requester. + * @internal + */ + _queueNewFrame(bindedRenderFunction, requester) { + // Use the provided requestAnimationFrame, unless the requester is the window. In that case, we will default to the Babylon Native version of requestAnimationFrame. + if (requester.requestAnimationFrame && requester !== window) { + requester.requestAnimationFrame(bindedRenderFunction); + } + else { + this._engine.requestAnimationFrame(bindedRenderFunction); + } + return 0; + } + _restoreEngineAfterContextLost() { + this._clearEmptyResources(); + const depthTest = this._depthCullingState.depthTest; // backup those values because the call to initEngine / wipeCaches will reset them + const depthFunc = this._depthCullingState.depthFunc; + const depthMask = this._depthCullingState.depthMask; + const stencilTest = this._stencilState.stencilTest; + this._rebuildGraphicsResources(); + this._depthCullingState.depthTest = depthTest; + this._depthCullingState.depthFunc = depthFunc; + this._depthCullingState.depthMask = depthMask; + this._stencilState.stencilTest = stencilTest; + this._flagContextRestored(); + } + /** + * Override default engine behavior. + * @param framebuffer + */ + _bindUnboundFramebuffer(framebuffer) { + if (this._currentFramebuffer !== framebuffer) { + if (this._currentFramebuffer) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER); + this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer); + this._commandBufferEncoder.finishEncodingCommand(); + } + if (framebuffer) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER); + this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer); + this._commandBufferEncoder.finishEncodingCommand(); + } + this._currentFramebuffer = framebuffer; + } + } + /** + * Gets host document + * @returns the host document object + */ + getHostDocument() { + return null; + } + clear(color, backBuffer, depth, stencil = false) { + if (this.useReverseDepthBuffer) { + throw new Error("reverse depth buffer is not currently implemented"); + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR); + this._commandBufferEncoder.encodeCommandArgAsUInt32(backBuffer && color ? 1 : 0); + this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.r : 0); + this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.g : 0); + this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.b : 0); + this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.a : 1); + this._commandBufferEncoder.encodeCommandArgAsUInt32(depth ? 1 : 0); + this._commandBufferEncoder.encodeCommandArgAsFloat32(1); + this._commandBufferEncoder.encodeCommandArgAsUInt32(stencil ? 1 : 0); + this._commandBufferEncoder.encodeCommandArgAsUInt32(0); + this._commandBufferEncoder.finishEncodingCommand(); + } + createIndexBuffer(indices, updateable, _label) { + const data = this._normalizeIndexData(indices); + const buffer = new NativeDataBuffer(); + buffer.references = 1; + buffer.is32Bits = data.BYTES_PER_ELEMENT === 4; + if (data.byteLength) { + buffer.nativeIndexBuffer = this._engine.createIndexBuffer(data.buffer, data.byteOffset, data.byteLength, buffer.is32Bits, updateable ?? false); + } + return buffer; + } + createVertexBuffer(vertices, updateable, _label) { + const data = ArrayBuffer.isView(vertices) ? vertices : new Float32Array(vertices); + const buffer = new NativeDataBuffer(); + buffer.references = 1; + if (data.byteLength) { + buffer.nativeVertexBuffer = this._engine.createVertexBuffer(data.buffer, data.byteOffset, data.byteLength, updateable ?? false); + } + return buffer; + } + _recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { + if (!effect._checkedNonFloatVertexBuffers) { + checkNonFloatVertexBuffers(vertexBuffers, effect); + effect._checkedNonFloatVertexBuffers = true; + } + if (indexBuffer) { + this._engine.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer); + } + const attributes = effect.getAttributesNames(); + for (let index = 0; index < attributes.length; index++) { + const location = effect.getAttributeLocation(index); + if (location >= 0) { + const kind = attributes[index]; + let vertexBuffer = null; + if (overrideVertexBuffers) { + vertexBuffer = overrideVertexBuffers[kind]; + } + if (!vertexBuffer) { + vertexBuffer = vertexBuffers[kind]; + } + if (vertexBuffer) { + const buffer = vertexBuffer.effectiveBuffer; + if (buffer && buffer.nativeVertexBuffer) { + this._engine.recordVertexBuffer(vertexArray, buffer.nativeVertexBuffer, location, vertexBuffer.effectiveByteOffset, vertexBuffer.effectiveByteStride, vertexBuffer.getSize(), getNativeAttribType(vertexBuffer.type), vertexBuffer.normalized, vertexBuffer.getInstanceDivisor()); + } + } + } + } + } + bindBuffers(vertexBuffers, indexBuffer, effect) { + if (this._boundBuffersVertexArray) { + this._deleteVertexArray(this._boundBuffersVertexArray); + } + this._boundBuffersVertexArray = this._engine.createVertexArray(); + this._recordVertexArrayObject(this._boundBuffersVertexArray, vertexBuffers, indexBuffer, effect); + this.bindVertexArrayObject(this._boundBuffersVertexArray); + } + recordVertexArrayObject(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { + const vertexArray = this._engine.createVertexArray(); + this._recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers); + return vertexArray; + } + _deleteVertexArray(vertexArray) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY); + this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray); + this._commandBufferEncoder.finishEncodingCommand(); + } + bindVertexArrayObject(vertexArray) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY); + this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray); + this._commandBufferEncoder.finishEncodingCommand(); + } + releaseVertexArrayObject(vertexArray) { + this._deleteVertexArray(vertexArray); + } + getAttributes(pipelineContext, attributesNames) { + const nativePipelineContext = pipelineContext; + const nativeShaderProcessingContext = nativePipelineContext.shaderProcessingContext; + remappedAttributesNames.length = 0; + for (let index = 0; index < attributesNames.length; index++) { + const origAttributeName = attributesNames[index]; + const attributeName = nativeShaderProcessingContext.remappedAttributeNames[origAttributeName] ?? origAttributeName; + remappedAttributesNames[index] = attributeName; + } + return this._engine.getAttributes(nativePipelineContext.program, remappedAttributesNames); + } + /** + * Triangle Fan and Line Loop are not supported by modern rendering API + * @param fillMode defines the primitive to use + * @returns true if supported + */ + _checkSupportedFillMode(fillMode) { + if (fillMode == 5 || fillMode == 8) { + if (!this._fillModeWarningDisplayed) { + Logger.Warn("Line Loop and Triangle Fan are not supported fill modes with Babylon Native. Elements with these fill mode will not be visible."); + this._fillModeWarningDisplayed = true; + } + return false; + } + return true; + } + /** + * Draw a list of indexed primitives + * @param fillMode defines the primitive to use + * @param indexStart defines the starting index + * @param indexCount defines the number of index to draw + * @param instancesCount defines the number of instances to draw (if instantiation is enabled) + */ + drawElementsType(fillMode, indexStart, indexCount, instancesCount) { + if (!this._checkSupportedFillMode(fillMode)) { + return; + } + // Apply states + this._drawCalls.addCount(1, false); + if (instancesCount && _native.Engine.COMMAND_DRAWINDEXEDINSTANCED) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED); + this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode); + this._commandBufferEncoder.encodeCommandArgAsUInt32(indexStart); + this._commandBufferEncoder.encodeCommandArgAsUInt32(indexCount); + this._commandBufferEncoder.encodeCommandArgAsUInt32(instancesCount); + } + else { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED); + this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode); + this._commandBufferEncoder.encodeCommandArgAsUInt32(indexStart); + this._commandBufferEncoder.encodeCommandArgAsUInt32(indexCount); + } + this._commandBufferEncoder.finishEncodingCommand(); + // } + } + /** + * Draw a list of unindexed primitives + * @param fillMode defines the primitive to use + * @param verticesStart defines the index of first vertex to draw + * @param verticesCount defines the count of vertices to draw + * @param instancesCount defines the number of instances to draw (if instantiation is enabled) + */ + drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) { + if (!this._checkSupportedFillMode(fillMode)) { + return; + } + // Apply states + this._drawCalls.addCount(1, false); + if (instancesCount && _native.Engine.COMMAND_DRAWINSTANCED) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED); + this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode); + this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesStart); + this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesCount); + this._commandBufferEncoder.encodeCommandArgAsUInt32(instancesCount); + } + else { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW); + this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode); + this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesStart); + this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesCount); + } + this._commandBufferEncoder.finishEncodingCommand(); + // } + } + createPipelineContext(shaderProcessingContext) { + const isAsync = !!(this._caps.parallelShaderCompile && this._engine.createProgramAsync); + return new NativePipelineContext(this, isAsync, shaderProcessingContext); + } + createMaterialContext() { + return undefined; + } + createDrawContext() { + return undefined; + } + /** + * @internal + */ + _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, _rawVertexSourceCode, _rawFragmentSourceCode, _rebuildRebind, defines, _transformFeedbackVaryings, _key, onReady) { + if (createAsRaw) { + this.createRawShaderProgram(); + } + else { + this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines); + } + onReady(); + } + /** + * @internal + */ + _getShaderProcessingContext(_shaderLanguage) { + return new NativeShaderProcessingContext(); + } + /** + * @internal + */ + _executeWhenRenderingStateIsCompiled(pipelineContext, action) { + const nativePipelineContext = pipelineContext; + if (nativePipelineContext.isAsync) { + if (nativePipelineContext.onCompiled) { + const oldHandler = nativePipelineContext.onCompiled; + nativePipelineContext.onCompiled = () => { + oldHandler(); + action(); + }; + } + else { + nativePipelineContext.onCompiled = action; + } + } + else { + action(); + } + } + createRawShaderProgram() { + throw new Error("Not Supported"); + } + createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines) { + const nativePipelineContext = pipelineContext; + this.onBeforeShaderCompilationObservable.notifyObservers(this); + const vertexInliner = new ShaderCodeInliner(vertexCode); + vertexInliner.processCode(); + vertexCode = vertexInliner.code; + const fragmentInliner = new ShaderCodeInliner(fragmentCode); + fragmentInliner.processCode(); + fragmentCode = fragmentInliner.code; + vertexCode = ThinEngine._ConcatenateShader(vertexCode, defines); + fragmentCode = ThinEngine._ConcatenateShader(fragmentCode, defines); + const onSuccess = () => { + nativePipelineContext.isCompiled = true; + nativePipelineContext.onCompiled?.(); + this.onAfterShaderCompilationObservable.notifyObservers(this); + }; + if (pipelineContext.isAsync) { + nativePipelineContext.program = this._engine.createProgramAsync(vertexCode, fragmentCode, onSuccess, (error) => { + nativePipelineContext.compilationError = error; + }); + } + else { + try { + nativePipelineContext.program = this._engine.createProgram(vertexCode, fragmentCode); + onSuccess(); + } + catch (e) { + const message = e?.message; + throw new Error("SHADER ERROR" + (typeof message === "string" ? "\n" + message : "")); + } + } + return nativePipelineContext.program; + } + /** + * Inline functions in shader code that are marked to be inlined + * @param code code to inline + * @returns inlined code + */ + inlineShaderCode(code) { + const sci = new ShaderCodeInliner(code); + sci.debug = false; + sci.processCode(); + return sci.code; + } + _setProgram(program) { + if (this._currentProgram !== program) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM); + this._commandBufferEncoder.encodeCommandArgAsNativeData(program); + this._commandBufferEncoder.finishEncodingCommand(); + this._currentProgram = program; + } + } + _deletePipelineContext(pipelineContext) { + const nativePipelineContext = pipelineContext; + if (nativePipelineContext && nativePipelineContext.program) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM); + this._commandBufferEncoder.encodeCommandArgAsNativeData(nativePipelineContext.program); + this._commandBufferEncoder.finishEncodingCommand(); + } + } + getUniforms(pipelineContext, uniformsNames) { + const nativePipelineContext = pipelineContext; + return this._engine.getUniforms(nativePipelineContext.program, uniformsNames); + } + bindUniformBlock(pipelineContext, blockName, index) { + // TODO + throw new Error("Not Implemented"); + } + bindSamplers(effect) { + const nativePipelineContext = effect.getPipelineContext(); + this._setProgram(nativePipelineContext.program); + // TODO: share this with engine? + const samplers = effect.getSamplers(); + for (let index = 0; index < samplers.length; index++) { + const uniform = effect.getUniform(samplers[index]); + if (uniform) { + this._boundUniforms[index] = uniform; + } + } + this._currentEffect = null; + } + getRenderWidth(useScreen = false) { + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.width; + } + return this._engine.getRenderWidth(); + } + getRenderHeight(useScreen = false) { + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.height; + } + return this._engine.getRenderHeight(); + } + setViewport(viewport, requiredWidth, requiredHeight) { + this._cachedViewport = viewport; + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT); + this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.x); + this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.y); + this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.width); + this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.height); + this._commandBufferEncoder.finishEncodingCommand(); + } + enableScissor(x, y, width, height) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR); + this._commandBufferEncoder.encodeCommandArgAsFloat32(x); + this._commandBufferEncoder.encodeCommandArgAsFloat32(y); + this._commandBufferEncoder.encodeCommandArgAsFloat32(width); + this._commandBufferEncoder.encodeCommandArgAsFloat32(height); + this._commandBufferEncoder.finishEncodingCommand(); + } + disableScissor() { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR); + this._commandBufferEncoder.encodeCommandArgAsFloat32(0); + this._commandBufferEncoder.encodeCommandArgAsFloat32(0); + this._commandBufferEncoder.encodeCommandArgAsFloat32(0); + this._commandBufferEncoder.encodeCommandArgAsFloat32(0); + this._commandBufferEncoder.finishEncodingCommand(); + } + setStateCullFaceType(_cullBackFaces, _force) { + throw new Error("setStateCullFaceType: Not Implemented"); + } + setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) { + this._zOffset = zOffset; + this._zOffsetUnits = zOffsetUnits; + if (this._zOffset !== 0) { + Tools.Warn("zOffset is not supported in Native engine."); + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE); + this._commandBufferEncoder.encodeCommandArgAsUInt32(culling ? 1 : 0); + this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffset); + this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffsetUnits); + this._commandBufferEncoder.encodeCommandArgAsUInt32((this.cullBackFaces ?? cullBackFaces ?? true) ? 1 : 0); + this._commandBufferEncoder.encodeCommandArgAsUInt32(reverseSide ? 1 : 0); + this._commandBufferEncoder.finishEncodingCommand(); + } + /** + * Gets the client rect of native canvas. Needed for InputManager. + * @returns a client rectangle + */ + getInputElementClientRect() { + const rect = { + bottom: this.getRenderHeight(), + height: this.getRenderHeight(), + left: 0, + right: this.getRenderWidth(), + top: 0, + width: this.getRenderWidth(), + x: 0, + y: 0, + toJSON: () => { }, + }; + return rect; + } + /** + * Set the z offset Factor to apply to current rendering + * @param value defines the offset to apply + */ + setZOffset(value) { + if (value !== this._zOffset) { + this._zOffset = value; + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET); + this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value); + this._commandBufferEncoder.finishEncodingCommand(); + } + } + /** + * Gets the current value of the zOffset Factor + * @returns the current zOffset Factor state + */ + getZOffset() { + return this._zOffset; + } + /** + * Set the z offset Units to apply to current rendering + * @param value defines the offset to apply + */ + setZOffsetUnits(value) { + if (value !== this._zOffsetUnits) { + this._zOffsetUnits = value; + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS); + this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value); + this._commandBufferEncoder.finishEncodingCommand(); + } + } + /** + * Gets the current value of the zOffset Units + * @returns the current zOffset Units state + */ + getZOffsetUnits() { + return this._zOffsetUnits; + } + /** + * Enable or disable depth buffering + * @param enable defines the state to set + */ + setDepthBuffer(enable) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST); + this._commandBufferEncoder.encodeCommandArgAsUInt32(enable ? this._currentDepthTest : _native.Engine.DEPTH_TEST_ALWAYS); + this._commandBufferEncoder.finishEncodingCommand(); + } + /** + * Gets a boolean indicating if depth writing is enabled + * @returns the current depth writing state + */ + getDepthWrite() { + return this._depthWrite; + } + getDepthFunction() { + switch (this._currentDepthTest) { + case _native.Engine.DEPTH_TEST_NEVER: + return 512; + case _native.Engine.DEPTH_TEST_ALWAYS: + return 519; + case _native.Engine.DEPTH_TEST_GREATER: + return 516; + case _native.Engine.DEPTH_TEST_GEQUAL: + return 518; + case _native.Engine.DEPTH_TEST_NOTEQUAL: + return 517; + case _native.Engine.DEPTH_TEST_EQUAL: + return 514; + case _native.Engine.DEPTH_TEST_LESS: + return 513; + case _native.Engine.DEPTH_TEST_LEQUAL: + return 515; + } + return null; + } + setDepthFunction(depthFunc) { + let nativeDepthFunc = 0; + switch (depthFunc) { + case 512: + nativeDepthFunc = _native.Engine.DEPTH_TEST_NEVER; + break; + case 519: + nativeDepthFunc = _native.Engine.DEPTH_TEST_ALWAYS; + break; + case 516: + nativeDepthFunc = _native.Engine.DEPTH_TEST_GREATER; + break; + case 518: + nativeDepthFunc = _native.Engine.DEPTH_TEST_GEQUAL; + break; + case 517: + nativeDepthFunc = _native.Engine.DEPTH_TEST_NOTEQUAL; + break; + case 514: + nativeDepthFunc = _native.Engine.DEPTH_TEST_EQUAL; + break; + case 513: + nativeDepthFunc = _native.Engine.DEPTH_TEST_LESS; + break; + case 515: + nativeDepthFunc = _native.Engine.DEPTH_TEST_LEQUAL; + break; + } + this._currentDepthTest = nativeDepthFunc; + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST); + this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest); + this._commandBufferEncoder.finishEncodingCommand(); + } + /** + * Enable or disable depth writing + * @param enable defines the state to set + */ + setDepthWrite(enable) { + this._depthWrite = enable; + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE); + this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable)); + this._commandBufferEncoder.finishEncodingCommand(); + } + /** + * Enable or disable color writing + * @param enable defines the state to set + */ + setColorWrite(enable) { + this._colorWrite = enable; + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE); + this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable)); + this._commandBufferEncoder.finishEncodingCommand(); + } + /** + * Gets a boolean indicating if color writing is enabled + * @returns the current color writing state + */ + getColorWrite() { + return this._colorWrite; + } + applyStencil() { + this._setStencil(this._stencilMask, getNativeStencilOpFail(this._stencilOpStencilFail), getNativeStencilDepthFail(this._stencilOpDepthFail), getNativeStencilDepthPass(this._stencilOpStencilDepthPass), getNativeStencilFunc(this._stencilFunc), this._stencilFuncRef); + } + _setStencil(mask, stencilOpFail, depthOpFail, depthOpPass, func, ref) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL); + this._commandBufferEncoder.encodeCommandArgAsUInt32(mask); + this._commandBufferEncoder.encodeCommandArgAsUInt32(stencilOpFail); + this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpFail); + this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpPass); + this._commandBufferEncoder.encodeCommandArgAsUInt32(func); + this._commandBufferEncoder.encodeCommandArgAsUInt32(ref); + this._commandBufferEncoder.finishEncodingCommand(); + } + /** + * Enable or disable the stencil buffer + * @param enable defines if the stencil buffer must be enabled or disabled + */ + setStencilBuffer(enable) { + this._stencilTest = enable; + if (enable) { + this.applyStencil(); + } + else { + this._setStencil(255, _native.Engine.STENCIL_OP_FAIL_S_KEEP, _native.Engine.STENCIL_OP_FAIL_Z_KEEP, _native.Engine.STENCIL_OP_PASS_Z_KEEP, _native.Engine.STENCIL_TEST_ALWAYS, 0); + } + } + /** + * Gets a boolean indicating if stencil buffer is enabled + * @returns the current stencil buffer state + */ + getStencilBuffer() { + return this._stencilTest; + } + /** + * Gets the current stencil operation when stencil passes + * @returns a number defining stencil operation to use when stencil passes + */ + getStencilOperationPass() { + return this._stencilOpStencilDepthPass; + } + /** + * Sets the stencil operation to use when stencil passes + * @param operation defines the stencil operation to use when stencil passes + */ + setStencilOperationPass(operation) { + this._stencilOpStencilDepthPass = operation; + this.applyStencil(); + } + /** + * Sets the current stencil mask + * @param mask defines the new stencil mask to use + */ + setStencilMask(mask) { + this._stencilMask = mask; + this.applyStencil(); + } + /** + * Sets the current stencil function + * @param stencilFunc defines the new stencil function to use + */ + setStencilFunction(stencilFunc) { + this._stencilFunc = stencilFunc; + this.applyStencil(); + } + /** + * Sets the current stencil reference + * @param reference defines the new stencil reference to use + */ + setStencilFunctionReference(reference) { + this._stencilFuncRef = reference; + this.applyStencil(); + } + /** + * Sets the current stencil mask + * @param mask defines the new stencil mask to use + */ + setStencilFunctionMask(mask) { + this._stencilFuncMask = mask; + } + /** + * Sets the stencil operation to use when stencil fails + * @param operation defines the stencil operation to use when stencil fails + */ + setStencilOperationFail(operation) { + this._stencilOpStencilFail = operation; + this.applyStencil(); + } + /** + * Sets the stencil operation to use when depth fails + * @param operation defines the stencil operation to use when depth fails + */ + setStencilOperationDepthFail(operation) { + this._stencilOpDepthFail = operation; + this.applyStencil(); + } + /** + * Gets the current stencil mask + * @returns a number defining the new stencil mask to use + */ + getStencilMask() { + return this._stencilMask; + } + /** + * Gets the current stencil function + * @returns a number defining the stencil function to use + */ + getStencilFunction() { + return this._stencilFunc; + } + /** + * Gets the current stencil reference value + * @returns a number defining the stencil reference value to use + */ + getStencilFunctionReference() { + return this._stencilFuncRef; + } + /** + * Gets the current stencil mask + * @returns a number defining the stencil mask to use + */ + getStencilFunctionMask() { + return this._stencilFuncMask; + } + /** + * Gets the current stencil operation when stencil fails + * @returns a number defining stencil operation to use when stencil fails + */ + getStencilOperationFail() { + return this._stencilOpStencilFail; + } + /** + * Gets the current stencil operation when depth fails + * @returns a number defining stencil operation to use when depth fails + */ + getStencilOperationDepthFail() { + return this._stencilOpDepthFail; + } + /** + * Sets alpha constants used by some alpha blending modes + * @param r defines the red component + * @param g defines the green component + * @param b defines the blue component + * @param a defines the alpha component + */ + setAlphaConstants(r, g, b, a) { + throw new Error("Setting alpha blend constant color not yet implemented."); + } + /** + * Sets the current alpha mode + * @param mode defines the mode to use (one of the BABYLON.undefined) + * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default) + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering + */ + setAlphaMode(mode, noDepthWriteChange = false) { + if (this._alphaMode === mode) { + return; + } + const nativeMode = getNativeAlphaMode(mode); + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE); + this._commandBufferEncoder.encodeCommandArgAsUInt32(nativeMode); + this._commandBufferEncoder.finishEncodingCommand(); + if (!noDepthWriteChange) { + this.setDepthWrite(mode === 0); + } + this._alphaMode = mode; + } + setInt(uniform, int) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsInt32(int); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setIntArray(uniform, array) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsInt32s(array); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setIntArray2(uniform, array) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsInt32s(array); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setIntArray3(uniform, array) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsInt32s(array); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setIntArray4(uniform, array) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsInt32s(array); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setFloatArray(uniform, array) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32s(array); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setFloatArray2(uniform, array) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32s(array); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setFloatArray3(uniform, array) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32s(array); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setFloatArray4(uniform, array) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32s(array); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setArray(uniform, array) { + if (!uniform) { + return false; + } + return this.setFloatArray(uniform, new Float32Array(array)); + } + setArray2(uniform, array) { + if (!uniform) { + return false; + } + return this.setFloatArray2(uniform, new Float32Array(array)); + } + setArray3(uniform, array) { + if (!uniform) { + return false; + } + return this.setFloatArray3(uniform, new Float32Array(array)); + } + setArray4(uniform, array) { + if (!uniform) { + return false; + } + return this.setFloatArray4(uniform, new Float32Array(array)); + } + setMatrices(uniform, matrices) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrices); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setMatrix3x3(uniform, matrix) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setMatrix2x2(uniform, matrix) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setFloat(uniform, value) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32(value); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setFloat2(uniform, x, y) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32(x); + this._commandBufferEncoder.encodeCommandArgAsFloat32(y); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setFloat3(uniform, x, y, z) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32(x); + this._commandBufferEncoder.encodeCommandArgAsFloat32(y); + this._commandBufferEncoder.encodeCommandArgAsFloat32(z); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setFloat4(uniform, x, y, z, w) { + if (!uniform) { + return false; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsFloat32(x); + this._commandBufferEncoder.encodeCommandArgAsFloat32(y); + this._commandBufferEncoder.encodeCommandArgAsFloat32(z); + this._commandBufferEncoder.encodeCommandArgAsFloat32(w); + this._commandBufferEncoder.finishEncodingCommand(); + return true; + } + setColor3(uniform, color3) { + if (!uniform) { + return false; + } + this.setFloat3(uniform, color3.r, color3.g, color3.b); + return true; + } + setColor4(uniform, color3, alpha) { + if (!uniform) { + return false; + } + this.setFloat4(uniform, color3.r, color3.g, color3.b, alpha); + return true; + } + wipeCaches(bruteForce) { + if (this.preventCacheWipeBetweenFrames) { + return; + } + this.resetTextureCache(); + this._currentEffect = null; + if (bruteForce) { + this._currentProgram = null; + this._stencilStateComposer.reset(); + this._depthCullingState.reset(); + this._alphaState.reset(); + } + this._cachedVertexBuffers = null; + this._cachedIndexBuffer = null; + this._cachedEffectForVertexBuffers = null; + } + _createTexture() { + return this._engine.createTexture(); + } + _deleteTexture(texture) { + if (texture) { + this._engine.deleteTexture(texture.underlyingResource); + } + } + /** + * Update the content of a dynamic texture + * @param texture defines the texture to update + * @param canvas defines the canvas containing the source + * @param invertY defines if data must be stored with Y axis inverted + * @param premulAlpha defines if alpha is stored as premultiplied + * @param format defines the format of the data + */ + updateDynamicTexture(texture, canvas, invertY, premulAlpha = false, format) { + if (premulAlpha === void 0) { + premulAlpha = false; + } + if (!!texture && !!texture._hardwareTexture) { + const source = canvas.getCanvasTexture(); + const destination = texture._hardwareTexture.underlyingResource; + this._engine.copyTexture(destination, source); + texture.isReady = true; + } + } + createDynamicTexture(width, height, generateMipMaps, samplingMode) { + // it's not possible to create 0x0 texture sized. Many bgfx methods assume texture size is at least 1x1(best case). + // Worst case is getting a crash/assert. + width = Math.max(width, 1); + height = Math.max(height, 1); + return this.createRawTexture(new Uint8Array(width * height * 4), width, height, 5, false, false, samplingMode); + } + createVideoElement(constraints) { + // create native object depending on stream. Only NativeCamera is supported for now. + if (this._camera) { + return this._camera.createVideo(constraints); + } + return null; + } + updateVideoTexture(texture, video, invertY) { + if (texture && texture._hardwareTexture && this._camera) { + const webGLTexture = texture._hardwareTexture.underlyingResource; + this._camera.updateVideoTexture(webGLTexture, video, invertY); + } + } + createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) { + const texture = new InternalTexture(this, 3 /* InternalTextureSource.Raw */); + texture.format = format; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.invertY = invertY; + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = texture.baseWidth; + texture.height = texture.baseHeight; + texture._compression = compression; + texture.type = type; + texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps); + this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer); + if (texture._hardwareTexture) { + const webGLTexture = texture._hardwareTexture.underlyingResource; + const filter = getNativeSamplingMode(samplingMode); + this._setTextureSampling(webGLTexture, filter); + } + this._internalTexturesCache.push(texture); + return texture; + } + createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) { + const texture = new InternalTexture(this, 11 /* InternalTextureSource.Raw2DArray */); + texture.baseWidth = width; + texture.baseHeight = height; + texture.baseDepth = depth; + texture.width = width; + texture.height = height; + texture.depth = depth; + texture.format = format; + texture.type = textureType; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.is2DArray = true; + if (texture._hardwareTexture) { + const nativeTexture = texture._hardwareTexture.underlyingResource; + this._engine.loadRawTexture2DArray(nativeTexture, data, width, height, depth, getNativeTextureFormat(format, textureType), generateMipMaps, invertY); + const filter = getNativeSamplingMode(samplingMode); + this._setTextureSampling(nativeTexture, filter); + } + texture.isReady = true; + this._internalTexturesCache.push(texture); + return texture; + } + updateRawTexture(texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) { + if (!texture) { + return; + } + if (bufferView && texture._hardwareTexture) { + const underlyingResource = texture._hardwareTexture.underlyingResource; + this._engine.loadRawTexture(underlyingResource, bufferView, texture.width, texture.height, getNativeTextureFormat(format, type), texture.generateMipMaps, texture.invertY); + } + texture.isReady = true; + } + // TODO: Refactor to share more logic with babylon.engine.ts version. + /** + * Usually called from Texture.ts. + * Passed information to create a NativeTexture + * @param url defines a value which contains one of the following: + * * A conventional http URL, e.g. 'http://...' or 'file://...' + * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...' + * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg' + * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file + * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx) + * @param scene needed for loading to the correct scene + * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE) + * @param onLoad optional callback to be called upon successful completion + * @param onError optional callback to be called upon failure + * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob + * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities + * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures + * @param forcedExtension defines the extension to use to pick the right loader + * @param mimeType defines an optional mime type + * @param loaderOptions options to be passed to the loader + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). + * @returns a InternalTexture for assignment back into BABYLON.Texture + */ + createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer = false) { + url = url || ""; + const fromData = url.substring(0, 5) === "data:"; + //const fromBlob = url.substring(0, 5) === "blob:"; + const isBase64 = fromData && url.indexOf(";base64,") !== -1; + const texture = fallback ? fallback : new InternalTexture(this, 1 /* InternalTextureSource.Url */); + const originalUrl = url; + if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) { + url = this._transformTextureUrl(url); + } + // establish the file extension, if possible + const lastDot = url.lastIndexOf("."); + const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : ""; + // some formats are already supported by bimg, no need to try to load them with JS + // leaving TextureLoader extension check for future use + let loaderPromise = null; + if (extension.endsWith(".basis") || extension.endsWith(".ktx") || extension.endsWith(".ktx2") || mimeType === "image/ktx" || mimeType === "image/ktx2") { + loaderPromise = _GetCompatibleTextureLoader(extension); + } + if (scene) { + scene.addPendingData(texture); + } + texture.url = url; + texture.generateMipMaps = !noMipmap; + texture.samplingMode = samplingMode; + texture.invertY = invertY; + texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, noMipmap); + if (!this.doNotHandleContextLost) { + // Keep a link to the buffer only if we plan to handle context lost + texture._buffer = buffer; + } + let onLoadObserver = null; + if (onLoad && !fallback) { + onLoadObserver = texture.onLoadedObservable.add(onLoad); + } + if (!fallback) { + this._internalTexturesCache.push(texture); + } + const onInternalError = (message, exception) => { + if (scene) { + scene.removePendingData(texture); + } + if (url === originalUrl) { + if (onLoadObserver) { + texture.onLoadedObservable.remove(onLoadObserver); + } + if (EngineStore.UseFallbackTexture) { + this.createTexture(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture); + } + if (onError) { + onError((message || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""), exception); + } + } + else { + // fall back to the original url if the transformed url fails to load + Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`); + this.createTexture(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, buffer, texture, format, forcedExtension, mimeType, loaderOptions); + } + }; + // processing for non-image formats + if (loaderPromise) { + throw new Error("Loading textures from IInternalTextureLoader not yet implemented."); + } + else { + const onload = (data) => { + if (!texture._hardwareTexture) { + if (scene) { + scene.removePendingData(texture); + } + return; + } + const underlyingResource = texture._hardwareTexture.underlyingResource; + this._engine.loadTexture(underlyingResource, data, !noMipmap, invertY, texture._useSRGBBuffer, () => { + texture.baseWidth = this._engine.getTextureWidth(underlyingResource); + texture.baseHeight = this._engine.getTextureHeight(underlyingResource); + texture.width = texture.baseWidth; + texture.height = texture.baseHeight; + texture.isReady = true; + const filter = getNativeSamplingMode(samplingMode); + this._setTextureSampling(underlyingResource, filter); + if (scene) { + scene.removePendingData(texture); + } + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + }, () => { + throw new Error("Could not load a native texture."); + }); + }; + if (fromData && buffer) { + if (buffer instanceof ArrayBuffer) { + onload(new Uint8Array(buffer)); + } + else if (ArrayBuffer.isView(buffer)) { + onload(buffer); + } + else if (typeof buffer === "string") { + onload(new Uint8Array(Tools.DecodeBase64(buffer))); + } + else { + throw new Error("Unsupported buffer type"); + } + } + else { + if (isBase64) { + onload(new Uint8Array(Tools.DecodeBase64(url))); + } + else { + this._loadFile(url, (data) => onload(new Uint8Array(data)), undefined, undefined, true, (request, exception) => { + onInternalError("Unable to load " + (request ? request.responseURL : url, exception)); + }); + } + } + } + return texture; + } + /** + * Wraps an external native texture in a Babylon texture. + * @param texture defines the external texture + * @param hasMipMaps defines whether the external texture has mip maps + * @param samplingMode defines the sampling mode for the external texture (default: 3) + * @returns the babylon internal texture + */ + wrapNativeTexture(texture, hasMipMaps = false, samplingMode = 3) { + const hardwareTexture = new NativeHardwareTexture(texture, this._engine); + const internalTexture = new InternalTexture(this, 0 /* InternalTextureSource.Unknown */, true); + internalTexture._hardwareTexture = hardwareTexture; + internalTexture.baseWidth = this._engine.getTextureWidth(texture); + internalTexture.baseHeight = this._engine.getTextureHeight(texture); + internalTexture.width = internalTexture.baseWidth; + internalTexture.height = internalTexture.baseHeight; + internalTexture.isReady = true; + internalTexture.useMipMaps = hasMipMaps; + this.updateTextureSamplingMode(samplingMode, internalTexture); + return internalTexture; + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Wraps an external web gl texture in a Babylon texture. + * @returns the babylon internal texture + */ + wrapWebGLTexture() { + throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead."); + } + _createDepthStencilTexture(size, options, rtWrapper) { + // TODO: handle other options? + const generateStencil = options.generateStencil || false; + const samples = options.samples || 1; + const nativeRTWrapper = rtWrapper; + const texture = new InternalTexture(this, 12 /* InternalTextureSource.DepthStencil */); + const width = size.width ?? size; + const height = size.height ?? size; + const framebuffer = this._engine.createFrameBuffer(texture._hardwareTexture.underlyingResource, width, height, generateStencil, true, samples); + nativeRTWrapper._framebufferDepthStencil = framebuffer; + return texture; + } + /** + * @internal + */ + _releaseFramebufferObjects(framebuffer) { + if (framebuffer) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER); + this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer); + this._commandBufferEncoder.finishEncodingCommand(); + } + } + /** + * @internal Engine abstraction for loading and creating an image bitmap from a given source string. + * @param imageSource source to load the image from. + * @param options An object that sets options for the image's extraction. + * @returns ImageBitmap + */ + _createImageBitmapFromSource(imageSource, options) { + const promise = new Promise((resolve, reject) => { + const image = this.createCanvasImage(); + image.onload = () => { + try { + const imageBitmap = this._engine.createImageBitmap(image); + resolve(imageBitmap); + } + catch (error) { + reject(`Error loading image ${image.src} with exception: ${error}`); + } + }; + image.onerror = (error) => { + reject(`Error loading image ${image.src} with exception: ${error}`); + }; + image.src = imageSource; + }); + return promise; + } + /** + * Engine abstraction for createImageBitmap + * @param image source for image + * @param options An object that sets options for the image's extraction. + * @returns ImageBitmap + */ + createImageBitmap(image, options) { + return new Promise((resolve, reject) => { + if (Array.isArray(image)) { + const arr = image; + if (arr.length) { + const image = this._engine.createImageBitmap(arr[0]); + if (image) { + resolve(image); + return; + } + } + } + reject(`Unsupported data for createImageBitmap.`); + }); + } + /** + * Resize an image and returns the image data as an uint8array + * @param image image to resize + * @param bufferWidth destination buffer width + * @param bufferHeight destination buffer height + * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size + */ + resizeImageBitmap(image, bufferWidth, bufferHeight) { + return this._engine.resizeImageBitmap(image, bufferWidth, bufferHeight); + } + /** + * Creates a cube texture + * @param rootUrl defines the url where the files to load is located + * @param scene defines the current scene + * @param files defines the list of files to load (1 per face) + * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default) + * @param onLoad defines an optional callback raised when the texture is loaded + * @param onError defines an optional callback raised if there is an issue to load the texture + * @param format defines the format of the data + * @param forcedExtension defines the extension to use to pick the right loader + * @param createPolynomials if a polynomial sphere should be created for the cube texture + * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness + * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness + * @param fallback defines texture to use while falling back when (compressed) texture file not found. + * @param loaderOptions options to be passed to the loader + * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). + * @param buffer defines the data buffer to load instead of loading the rootUrl + * @returns the cube texture as an InternalTexture + */ + createCubeTexture(rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false, buffer = null) { + const texture = fallback ? fallback : new InternalTexture(this, 7 /* InternalTextureSource.Cube */); + texture.isCube = true; + texture.url = rootUrl; + texture.generateMipMaps = !noMipmap; + texture._lodGenerationScale = lodScale; + texture._lodGenerationOffset = lodOffset; + texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !!noMipmap); + if (!this._doNotHandleContextLost) { + texture._extension = forcedExtension; + texture._files = files; + texture._buffer = buffer; + } + const lastDot = rootUrl.lastIndexOf("."); + const extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : ""; + // TODO: use texture loader to load env files? + if (extension === ".env") { + const onloaddata = (data) => { + const info = GetEnvInfo(data); + texture.width = info.width; + texture.height = info.width; + UploadEnvSpherical(texture, info); + const specularInfo = info.specular; + if (!specularInfo) { + throw new Error(`Nothing else parsed so far`); + } + texture._lodGenerationScale = specularInfo.lodGenerationScale; + const imageData = CreateRadianceImageDataArrayBufferViews(data, info); + texture.format = 5; + texture.type = 0; + texture.generateMipMaps = true; + texture.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, texture); + texture._isRGBD = true; + texture.invertY = true; + this._engine.loadCubeTextureWithMips(texture._hardwareTexture.underlyingResource, imageData, false, texture._useSRGBBuffer, () => { + texture.isReady = true; + if (onLoad) { + onLoad(); + } + }, () => { + throw new Error("Could not load a native cube texture."); + }); + }; + if (buffer) { + onloaddata(buffer); + } + else if (files && files.length === 6) { + throw new Error(`Multi-file loading not allowed on env files.`); + } + else { + const onInternalError = (request, exception) => { + if (onError && request) { + onError(request.status + " " + request.statusText, exception); + } + }; + this._loadFile(rootUrl, (data) => { + onloaddata(new Uint8Array(data, 0, data.byteLength)); + }, undefined, undefined, true, onInternalError); + } + } + else { + if (!files || files.length !== 6) { + throw new Error("Cannot load cubemap because 6 files were not defined"); + } + // Reorder from [+X, +Y, +Z, -X, -Y, -Z] to [+X, -X, +Y, -Y, +Z, -Z]. + const reorderedFiles = [files[0], files[3], files[1], files[4], files[2], files[5]]; + Promise.all(reorderedFiles.map((file) => this._loadFileAsync(file, undefined, true).then((data) => new Uint8Array(data, 0, data.byteLength)))) + .then((data) => { + return new Promise((resolve, reject) => { + this._engine.loadCubeTexture(texture._hardwareTexture.underlyingResource, data, !noMipmap, true, texture._useSRGBBuffer, resolve, reject); + }); + }) + .then(() => { + texture.isReady = true; + if (onLoad) { + onLoad(); + } + }, (error) => { + if (onError) { + onError(`Failed to load cubemap: ${error.message}`, error); + } + }); + } + this._internalTexturesCache.push(texture); + return texture; + } + /** @internal */ + _createHardwareTexture() { + return new NativeHardwareTexture(this._createTexture(), this._engine); + } + /** @internal */ + _createHardwareRenderTargetWrapper(isMulti, isCube, size) { + const rtWrapper = new NativeRenderTargetWrapper(isMulti, isCube, size, this); + this._renderTargetWrapperCache.push(rtWrapper); + return rtWrapper; + } + /** @internal */ + _createInternalTexture(size, options, _delayGPUTextureCreation = true, source = 0 /* InternalTextureSource.Unknown */) { + let generateMipMaps = false; + let type = 0; + let samplingMode = 3; + let format = 5; + let useSRGBBuffer = false; + let samples = 1; + let label; + if (options !== undefined && typeof options === "object") { + generateMipMaps = !!options.generateMipMaps; + type = options.type === undefined ? 0 : options.type; + samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode; + format = options.format === undefined ? 5 : options.format; + useSRGBBuffer = options.useSRGBBuffer === undefined ? false : options.useSRGBBuffer; + samples = options.samples ?? 1; + label = options.label; + } + else { + generateMipMaps = !!options; + } + useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps); + if (type === 1 && !this._caps.textureFloatLinearFiltering) { + // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE + samplingMode = 1; + } + else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { + // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE + samplingMode = 1; + } + if (type === 1 && !this._caps.textureFloat) { + type = 0; + Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"); + } + const texture = new InternalTexture(this, source); + const width = size.width ?? size; + const height = size.height ?? size; + const layers = size.layers || 0; + if (layers !== 0) { + throw new Error("Texture layers are not supported in Babylon Native"); + } + const nativeTexture = texture._hardwareTexture.underlyingResource; + const nativeTextureFormat = getNativeTextureFormat(format, type); + // REVIEW: We are always setting the renderTarget flag as we don't know whether the texture will be used as a render target. + this._engine.initializeTexture(nativeTexture, width, height, generateMipMaps, nativeTextureFormat, true, useSRGBBuffer, samples); + this._setTextureSampling(nativeTexture, getNativeSamplingMode(samplingMode)); + texture._useSRGBBuffer = useSRGBBuffer; + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.depth = layers; + texture.isReady = true; + texture.samples = samples; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.type = type; + texture.format = format; + texture.label = label; + this._internalTexturesCache.push(texture); + return texture; + } + createRenderTargetTexture(size, options) { + const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size); + let generateDepthBuffer = true; + let generateStencilBuffer = false; + let noColorAttachment = false; + let colorAttachment = undefined; + let samples = 1; + if (options !== undefined && typeof options === "object") { + generateDepthBuffer = options.generateDepthBuffer ?? true; + generateStencilBuffer = !!options.generateStencilBuffer; + noColorAttachment = !!options.noColorAttachment; + colorAttachment = options.colorAttachment; + samples = options.samples ?? 1; + } + const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, 5 /* InternalTextureSource.RenderTarget */)); + const width = size.width ?? size; + const height = size.height ?? size; + const framebuffer = this._engine.createFrameBuffer(texture ? texture._hardwareTexture.underlyingResource : null, width, height, generateStencilBuffer, generateDepthBuffer, samples); + rtWrapper._framebuffer = framebuffer; + rtWrapper._generateDepthBuffer = generateDepthBuffer; + rtWrapper._generateStencilBuffer = generateStencilBuffer; + rtWrapper._samples = samples; + rtWrapper.setTextures(texture); + return rtWrapper; + } + updateRenderTargetTextureSampleCount(rtWrapper, samples) { + Logger.Warn("Updating render target sample count is not currently supported"); + return rtWrapper.samples; + } + updateTextureSamplingMode(samplingMode, texture) { + if (texture._hardwareTexture) { + const filter = getNativeSamplingMode(samplingMode); + this._setTextureSampling(texture._hardwareTexture.underlyingResource, filter); + } + texture.samplingMode = samplingMode; + } + bindFramebuffer(texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) { + const nativeRTWrapper = texture; + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + this._currentRenderTarget = texture; + if (faceIndex) { + throw new Error("Cuboid frame buffers are not yet supported in NativeEngine."); + } + if (requiredWidth || requiredHeight) { + throw new Error("Required width/height for frame buffers not yet supported in NativeEngine."); + } + if (nativeRTWrapper._framebufferDepthStencil) { + this._bindUnboundFramebuffer(nativeRTWrapper._framebufferDepthStencil); + } + else { + this._bindUnboundFramebuffer(nativeRTWrapper._framebuffer); + } + } + unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) { + // NOTE: Disabling mipmap generation is not yet supported in NativeEngine. + this._currentRenderTarget = null; + if (onBeforeUnbind) { + onBeforeUnbind(); + } + this._bindUnboundFramebuffer(null); + } + createDynamicVertexBuffer(data) { + return this.createVertexBuffer(data, true); + } + updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) { + const buffer = indexBuffer; + const data = this._normalizeIndexData(indices); + buffer.is32Bits = data.BYTES_PER_ELEMENT === 4; + this._engine.updateDynamicIndexBuffer(buffer.nativeIndexBuffer, data.buffer, data.byteOffset, data.byteLength, offset); + } + updateDynamicVertexBuffer(vertexBuffer, data, byteOffset = 0, byteLength) { + const buffer = vertexBuffer; + const dataView = data instanceof Array ? new Float32Array(data) : data instanceof ArrayBuffer ? new Uint8Array(data) : data; + const byteView = new Uint8Array(dataView.buffer, dataView.byteOffset, byteLength ?? dataView.byteLength); + this._engine.updateDynamicVertexBuffer(buffer.nativeVertexBuffer, byteView.buffer, byteView.byteOffset, byteView.byteLength, byteOffset); + } + // TODO: Refactor to share more logic with base Engine implementation. + /** + * @internal + */ + _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false) { + const uniform = this._boundUniforms[channel]; + if (!uniform) { + return false; + } + // Not ready? + if (!texture) { + if (this._boundTexturesCache[channel] != null) { + this._activeChannel = channel; + this._boundTexturesCache[channel] = null; + this._unsetNativeTexture(uniform); + } + return false; + } + // Video + if (texture.video) { + this._activeChannel = channel; + texture.update(); + } + else if (texture.delayLoadState === 4) { + // Delay loading + texture.delayLoad(); + return false; + } + let internalTexture; + if (depthStencilTexture) { + internalTexture = texture.depthStencilTexture; + } + else if (texture.isReady()) { + internalTexture = texture.getInternalTexture(); + } + else if (texture.isCube) { + internalTexture = this.emptyCubeTexture; + } + else if (texture.is3D) { + internalTexture = this.emptyTexture3D; + } + else if (texture.is2DArray) { + internalTexture = this.emptyTexture2DArray; + } + else { + internalTexture = this.emptyTexture; + } + this._activeChannel = channel; + if (!internalTexture || !internalTexture._hardwareTexture) { + return false; + } + this._setTextureWrapMode(internalTexture._hardwareTexture.underlyingResource, getNativeAddressMode(texture.wrapU), getNativeAddressMode(texture.wrapV), getNativeAddressMode(texture.wrapR)); + this._updateAnisotropicLevel(texture); + this._setNativeTexture(uniform, internalTexture._hardwareTexture.underlyingResource); + return true; + } + // filter is a NativeFilter.XXXX value. + _setTextureSampling(texture, filter) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING); + this._commandBufferEncoder.encodeCommandArgAsNativeData(texture); + this._commandBufferEncoder.encodeCommandArgAsUInt32(filter); + this._commandBufferEncoder.finishEncodingCommand(); + } + // addressModes are NativeAddressMode.XXXX values. + _setTextureWrapMode(texture, addressModeU, addressModeV, addressModeW) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE); + this._commandBufferEncoder.encodeCommandArgAsNativeData(texture); + this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeU); + this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeV); + this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeW); + this._commandBufferEncoder.finishEncodingCommand(); + } + _setNativeTexture(uniform, texture) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.encodeCommandArgAsNativeData(texture); + this._commandBufferEncoder.finishEncodingCommand(); + } + _unsetNativeTexture(uniform) { + if (!_native.Engine.COMMAND_UNSETTEXTURE) { + return; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNSETTEXTURE); + this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); + this._commandBufferEncoder.finishEncodingCommand(); + } + // TODO: Share more of this logic with the base implementation. + // TODO: Rename to match naming in base implementation once refactoring allows different parameters. + _updateAnisotropicLevel(texture) { + const internalTexture = texture.getInternalTexture(); + const value = texture.anisotropicFilteringLevel; + if (!internalTexture || !internalTexture._hardwareTexture) { + return; + } + if (internalTexture._cachedAnisotropicFilteringLevel !== value) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL); + this._commandBufferEncoder.encodeCommandArgAsNativeData(internalTexture._hardwareTexture.underlyingResource); + this._commandBufferEncoder.encodeCommandArgAsUInt32(value); + this._commandBufferEncoder.finishEncodingCommand(); + internalTexture._cachedAnisotropicFilteringLevel = value; + } + } + /** + * @internal + */ + _bindTexture(channel, texture) { + const uniform = this._boundUniforms[channel]; + if (!uniform) { + return; + } + if (texture && texture._hardwareTexture) { + const underlyingResource = texture._hardwareTexture.underlyingResource; + this._setNativeTexture(uniform, underlyingResource); + } + else { + this._unsetNativeTexture(uniform); + } + } + /** + * Unbind all textures + */ + unbindAllTextures() { + if (!_native.Engine.COMMAND_DISCARDALLTEXTURES) { + return; + } + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DISCARDALLTEXTURES); + this._commandBufferEncoder.finishEncodingCommand(); + } + _deleteBuffer(buffer) { + if (buffer.nativeIndexBuffer) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER); + this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer.nativeIndexBuffer); + this._commandBufferEncoder.finishEncodingCommand(); + delete buffer.nativeIndexBuffer; + } + if (buffer.nativeVertexBuffer) { + this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER); + this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer.nativeVertexBuffer); + this._commandBufferEncoder.finishEncodingCommand(); + delete buffer.nativeVertexBuffer; + } + } + /** + * Create a canvas + * @param width width + * @param height height + * @returns ICanvas interface + */ + createCanvas(width, height) { + if (!_native.Canvas) { + throw new Error("Native Canvas plugin not available."); + } + const canvas = new _native.Canvas(); + canvas.width = width; + canvas.height = height; + return canvas; + } + /** + * Create an image to use with canvas + * @returns IImage interface + */ + createCanvasImage() { + if (!_native.Canvas) { + throw new Error("Native Canvas plugin not available."); + } + const image = new _native.Image(); + return image; + } + /** + * Create a 2D path to use with canvas + * @returns IPath2D interface + * @param d SVG path string + */ + createCanvasPath2D(d) { + if (!_native.Canvas) { + throw new Error("Native Canvas plugin not available."); + } + const path2d = new _native.Path2D(d); + return path2d; + } + /** + * Update a portion of an internal texture + * @param texture defines the texture to update + * @param imageData defines the data to store into the texture + * @param xOffset defines the x coordinates of the update rectangle + * @param yOffset defines the y coordinates of the update rectangle + * @param width defines the width of the update rectangle + * @param height defines the height of the update rectangle + * @param faceIndex defines the face index if texture is a cube (0 by default) + * @param lod defines the lod level to update (0 by default) + * @param generateMipMaps defines whether to generate mipmaps or not + */ + updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) { + throw new Error("updateTextureData not implemented."); + } + /** + * @internal + */ + _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) { + throw new Error("_uploadCompressedDataToTextureDirectly not implemented."); + } + /** + * @internal + */ + _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0) { + throw new Error("_uploadDataToTextureDirectly not implemented."); + } + /** + * @internal + */ + _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) { + throw new Error("_uploadArrayBufferViewToTexture not implemented."); + } + /** + * @internal + */ + _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) { + throw new Error("_uploadArrayBufferViewToTexture not implemented."); + } + getFontOffset(font) { + // TODO + const result = { ascent: 0, height: 0, descent: 0 }; + return result; + } + /** + * No equivalent for native. Do nothing. + */ + flushFramebuffer() { } + _readTexturePixels(texture, width, height, faceIndex, level, buffer, _flushRenderer, _noDataConversion, x, y) { + if (faceIndex !== undefined && faceIndex !== -1) { + throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${faceIndex}.`); + } + return this._engine + .readTexture(texture._hardwareTexture?.underlyingResource, level ?? 0, x ?? 0, y ?? 0, width, height, buffer?.buffer ?? null, buffer?.byteOffset ?? 0, buffer?.byteLength ?? 0) + .then((rawBuffer) => { + if (!buffer) { + buffer = new Uint8Array(rawBuffer); + } + return buffer; + }); + } + startTimeQuery() { + if (!this._gpuFrameTimeToken) { + this._gpuFrameTimeToken = new _TimeToken(); + } + // Always return the same time token. For native, we don't need a start marker, we just query for native frame stats. + return this._gpuFrameTimeToken; + } + endTimeQuery(token) { + this._engine.populateFrameStats?.(this._frameStats); + return this._frameStats.gpuTimeNs; + } +} +// This must match the protocol version in NativeEngine.cpp +NativeEngine.PROTOCOL_VERSION = 8; + +NativeEngine._createNativeDataStream = function () { + if (_native.NativeDataStream.VALIDATION_ENABLED) { + return new ValidatedNativeDataStream(); + } + else { + return new NativeDataStream(); + } +}; +/** + * Validated Native Data Stream + */ +class ValidatedNativeDataStream extends NativeDataStream { + constructor() { + super(); + } + writeUint32(value) { + super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32); + super.writeUint32(value); + } + writeInt32(value) { + super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32); + super.writeInt32(value); + } + writeFloat32(value) { + super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32); + super.writeFloat32(value); + } + writeUint32Array(values) { + super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY); + super.writeUint32Array(values); + } + writeInt32Array(values) { + super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY); + super.writeInt32Array(values); + } + writeFloat32Array(values) { + super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY); + super.writeFloat32Array(values); + } + writeNativeData(handle) { + super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA); + super.writeNativeData(handle); + } + writeBoolean(value) { + super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN); + super.writeBoolean(value); + } +} + +/** @internal */ +class WebGPUTextureHelper { + static ComputeNumMipmapLevels(width, height) { + return ILog2(Math.max(width, height)) + 1; + } + static GetTextureTypeFromFormat(format) { + switch (format) { + // One Component = 8 bits unsigned + case "r8unorm" /* WebGPUConstants.TextureFormat.R8Unorm */: + case "r8uint" /* WebGPUConstants.TextureFormat.R8Uint */: + case "rg8unorm" /* WebGPUConstants.TextureFormat.RG8Unorm */: + case "rg8uint" /* WebGPUConstants.TextureFormat.RG8Uint */: + case "rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */: + case "rgba8unorm-srgb" /* WebGPUConstants.TextureFormat.RGBA8UnormSRGB */: + case "rgba8uint" /* WebGPUConstants.TextureFormat.RGBA8Uint */: + case "bgra8unorm" /* WebGPUConstants.TextureFormat.BGRA8Unorm */: + case "bgra8unorm-srgb" /* WebGPUConstants.TextureFormat.BGRA8UnormSRGB */: + case "rgb10a2uint" /* WebGPUConstants.TextureFormat.RGB10A2UINT */: // composite format - let's say it's byte... + case "rgb10a2unorm" /* WebGPUConstants.TextureFormat.RGB10A2Unorm */: // composite format - let's say it's byte... + case "rgb9e5ufloat" /* WebGPUConstants.TextureFormat.RGB9E5UFloat */: // composite format - let's say it's byte... + case "rg11b10ufloat" /* WebGPUConstants.TextureFormat.RG11B10UFloat */: // composite format - let's say it's byte... + case "bc7-rgba-unorm" /* WebGPUConstants.TextureFormat.BC7RGBAUnorm */: + case "bc7-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB */: + case "bc6h-rgb-ufloat" /* WebGPUConstants.TextureFormat.BC6HRGBUFloat */: + case "bc5-rg-unorm" /* WebGPUConstants.TextureFormat.BC5RGUnorm */: + case "bc3-rgba-unorm" /* WebGPUConstants.TextureFormat.BC3RGBAUnorm */: + case "bc3-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB */: + case "bc2-rgba-unorm" /* WebGPUConstants.TextureFormat.BC2RGBAUnorm */: + case "bc2-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB */: + case "bc4-r-unorm" /* WebGPUConstants.TextureFormat.BC4RUnorm */: + case "bc1-rgba-unorm" /* WebGPUConstants.TextureFormat.BC1RGBAUnorm */: + case "bc1-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB */: + case "etc2-rgb8unorm" /* WebGPUConstants.TextureFormat.ETC2RGB8Unorm */: + case "etc2-rgb8unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB */: + case "etc2-rgb8a1unorm" /* WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm */: + case "etc2-rgb8a1unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB */: + case "etc2-rgba8unorm" /* WebGPUConstants.TextureFormat.ETC2RGBA8Unorm */: + case "etc2-rgba8unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB */: + case "eac-r11unorm" /* WebGPUConstants.TextureFormat.EACR11Unorm */: + case "eac-rg11unorm" /* WebGPUConstants.TextureFormat.EACRG11Unorm */: + case "astc-4x4-unorm" /* WebGPUConstants.TextureFormat.ASTC4x4Unorm */: + case "astc-4x4-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB */: + case "astc-5x4-unorm" /* WebGPUConstants.TextureFormat.ASTC5x4Unorm */: + case "astc-5x4-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB */: + case "astc-5x5-unorm" /* WebGPUConstants.TextureFormat.ASTC5x5Unorm */: + case "astc-5x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB */: + case "astc-6x5-unorm" /* WebGPUConstants.TextureFormat.ASTC6x5Unorm */: + case "astc-6x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB */: + case "astc-6x6-unorm" /* WebGPUConstants.TextureFormat.ASTC6x6Unorm */: + case "astc-6x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB */: + case "astc-8x5-unorm" /* WebGPUConstants.TextureFormat.ASTC8x5Unorm */: + case "astc-8x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB */: + case "astc-8x6-unorm" /* WebGPUConstants.TextureFormat.ASTC8x6Unorm */: + case "astc-8x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB */: + case "astc-8x8-unorm" /* WebGPUConstants.TextureFormat.ASTC8x8Unorm */: + case "astc-8x8-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB */: + case "astc-10x5-unorm" /* WebGPUConstants.TextureFormat.ASTC10x5Unorm */: + case "astc-10x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB */: + case "astc-10x6-unorm" /* WebGPUConstants.TextureFormat.ASTC10x6Unorm */: + case "astc-10x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB */: + case "astc-10x8-unorm" /* WebGPUConstants.TextureFormat.ASTC10x8Unorm */: + case "astc-10x8-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB */: + case "astc-10x10-unorm" /* WebGPUConstants.TextureFormat.ASTC10x10Unorm */: + case "astc-10x10-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB */: + case "astc-12x10-unorm" /* WebGPUConstants.TextureFormat.ASTC12x10Unorm */: + case "astc-12x10-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB */: + case "astc-12x12-unorm" /* WebGPUConstants.TextureFormat.ASTC12x12Unorm */: + case "astc-12x12-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB */: + case "stencil8" /* WebGPUConstants.TextureFormat.Stencil8 */: + return 0; + // One Component = 8 bits signed + case "r8snorm" /* WebGPUConstants.TextureFormat.R8Snorm */: + case "r8sint" /* WebGPUConstants.TextureFormat.R8Sint */: + case "rg8snorm" /* WebGPUConstants.TextureFormat.RG8Snorm */: + case "rg8sint" /* WebGPUConstants.TextureFormat.RG8Sint */: + case "rgba8snorm" /* WebGPUConstants.TextureFormat.RGBA8Snorm */: + case "rgba8sint" /* WebGPUConstants.TextureFormat.RGBA8Sint */: + case "bc6h-rgb-float" /* WebGPUConstants.TextureFormat.BC6HRGBFloat */: + case "bc5-rg-snorm" /* WebGPUConstants.TextureFormat.BC5RGSnorm */: + case "bc4-r-snorm" /* WebGPUConstants.TextureFormat.BC4RSnorm */: + case "eac-r11snorm" /* WebGPUConstants.TextureFormat.EACR11Snorm */: + case "eac-rg11snorm" /* WebGPUConstants.TextureFormat.EACRG11Snorm */: + return 3; + // One component = 16 bits unsigned + case "r16uint" /* WebGPUConstants.TextureFormat.R16Uint */: + case "r16unorm" /* WebGPUConstants.TextureFormat.R16Unorm */: + case "rg16unorm" /* WebGPUConstants.TextureFormat.RG16Unorm */: + case "rgba16unorm" /* WebGPUConstants.TextureFormat.RGBA16Unorm */: + case "rg16uint" /* WebGPUConstants.TextureFormat.RG16Uint */: + case "rgba16uint" /* WebGPUConstants.TextureFormat.RGBA16Uint */: + case "depth16unorm" /* WebGPUConstants.TextureFormat.Depth16Unorm */: + return 5; + // One component = 16 bits signed + case "r16sint" /* WebGPUConstants.TextureFormat.R16Sint */: + case "r16snorm" /* WebGPUConstants.TextureFormat.R16Snorm */: + case "rg16snorm" /* WebGPUConstants.TextureFormat.RG16Snorm */: + case "rgba16snorm" /* WebGPUConstants.TextureFormat.RGBA16Snorm */: + case "rg16sint" /* WebGPUConstants.TextureFormat.RG16Sint */: + case "rgba16sint" /* WebGPUConstants.TextureFormat.RGBA16Sint */: + return 4; + case "r16float" /* WebGPUConstants.TextureFormat.R16Float */: + case "rg16float" /* WebGPUConstants.TextureFormat.RG16Float */: + case "rgba16float" /* WebGPUConstants.TextureFormat.RGBA16Float */: + return 2; + // One component = 32 bits unsigned + case "r32uint" /* WebGPUConstants.TextureFormat.R32Uint */: + case "rg32uint" /* WebGPUConstants.TextureFormat.RG32Uint */: + case "rgba32uint" /* WebGPUConstants.TextureFormat.RGBA32Uint */: + return 7; + // One component = 32 bits signed + case "r32sint" /* WebGPUConstants.TextureFormat.R32Sint */: + case "rg32sint" /* WebGPUConstants.TextureFormat.RG32Sint */: + case "rgba32sint" /* WebGPUConstants.TextureFormat.RGBA32Sint */: + return 7; + case "r32float" /* WebGPUConstants.TextureFormat.R32Float */: + case "rg32float" /* WebGPUConstants.TextureFormat.RG32Float */: + case "rgba32float" /* WebGPUConstants.TextureFormat.RGBA32Float */: + case "depth32float" /* WebGPUConstants.TextureFormat.Depth32Float */: + case "depth32float-stencil8" /* WebGPUConstants.TextureFormat.Depth32FloatStencil8 */: + case "depth24plus" /* WebGPUConstants.TextureFormat.Depth24Plus */: + case "depth24plus-stencil8" /* WebGPUConstants.TextureFormat.Depth24PlusStencil8 */: + return 1; + } + return 0; + } + static GetBlockInformationFromFormat(format) { + switch (format) { + // 8 bits formats + case "r8unorm" /* WebGPUConstants.TextureFormat.R8Unorm */: + case "r8snorm" /* WebGPUConstants.TextureFormat.R8Snorm */: + case "r8uint" /* WebGPUConstants.TextureFormat.R8Uint */: + case "r8sint" /* WebGPUConstants.TextureFormat.R8Sint */: + return { width: 1, height: 1, length: 1 }; + // 16 bits formats + case "r16uint" /* WebGPUConstants.TextureFormat.R16Uint */: + case "r16sint" /* WebGPUConstants.TextureFormat.R16Sint */: + case "r16unorm" /* WebGPUConstants.TextureFormat.R16Unorm */: + case "rg16unorm" /* WebGPUConstants.TextureFormat.RG16Unorm */: + case "rgba16unorm" /* WebGPUConstants.TextureFormat.RGBA16Unorm */: + case "r16snorm" /* WebGPUConstants.TextureFormat.R16Snorm */: + case "rg16snorm" /* WebGPUConstants.TextureFormat.RG16Snorm */: + case "rgba16snorm" /* WebGPUConstants.TextureFormat.RGBA16Snorm */: + case "r16float" /* WebGPUConstants.TextureFormat.R16Float */: + case "rg8unorm" /* WebGPUConstants.TextureFormat.RG8Unorm */: + case "rg8snorm" /* WebGPUConstants.TextureFormat.RG8Snorm */: + case "rg8uint" /* WebGPUConstants.TextureFormat.RG8Uint */: + case "rg8sint" /* WebGPUConstants.TextureFormat.RG8Sint */: + return { width: 1, height: 1, length: 2 }; + // 32 bits formats + case "r32uint" /* WebGPUConstants.TextureFormat.R32Uint */: + case "r32sint" /* WebGPUConstants.TextureFormat.R32Sint */: + case "r32float" /* WebGPUConstants.TextureFormat.R32Float */: + case "rg16uint" /* WebGPUConstants.TextureFormat.RG16Uint */: + case "rg16sint" /* WebGPUConstants.TextureFormat.RG16Sint */: + case "rg16float" /* WebGPUConstants.TextureFormat.RG16Float */: + case "rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */: + case "rgba8unorm-srgb" /* WebGPUConstants.TextureFormat.RGBA8UnormSRGB */: + case "rgba8snorm" /* WebGPUConstants.TextureFormat.RGBA8Snorm */: + case "rgba8uint" /* WebGPUConstants.TextureFormat.RGBA8Uint */: + case "rgba8sint" /* WebGPUConstants.TextureFormat.RGBA8Sint */: + case "bgra8unorm" /* WebGPUConstants.TextureFormat.BGRA8Unorm */: + case "bgra8unorm-srgb" /* WebGPUConstants.TextureFormat.BGRA8UnormSRGB */: + case "rgb9e5ufloat" /* WebGPUConstants.TextureFormat.RGB9E5UFloat */: + case "rgb10a2uint" /* WebGPUConstants.TextureFormat.RGB10A2UINT */: + case "rgb10a2unorm" /* WebGPUConstants.TextureFormat.RGB10A2Unorm */: + case "rg11b10ufloat" /* WebGPUConstants.TextureFormat.RG11B10UFloat */: + return { width: 1, height: 1, length: 4 }; + // 64 bits formats + case "rg32uint" /* WebGPUConstants.TextureFormat.RG32Uint */: + case "rg32sint" /* WebGPUConstants.TextureFormat.RG32Sint */: + case "rg32float" /* WebGPUConstants.TextureFormat.RG32Float */: + case "rgba16uint" /* WebGPUConstants.TextureFormat.RGBA16Uint */: + case "rgba16sint" /* WebGPUConstants.TextureFormat.RGBA16Sint */: + case "rgba16float" /* WebGPUConstants.TextureFormat.RGBA16Float */: + return { width: 1, height: 1, length: 8 }; + // 128 bits formats + case "rgba32uint" /* WebGPUConstants.TextureFormat.RGBA32Uint */: + case "rgba32sint" /* WebGPUConstants.TextureFormat.RGBA32Sint */: + case "rgba32float" /* WebGPUConstants.TextureFormat.RGBA32Float */: + return { width: 1, height: 1, length: 16 }; + // Depth and stencil formats + case "stencil8" /* WebGPUConstants.TextureFormat.Stencil8 */: + // eslint-disable-next-line no-throw-literal + throw "No fixed size for Stencil8 format!"; + case "depth16unorm" /* WebGPUConstants.TextureFormat.Depth16Unorm */: + return { width: 1, height: 1, length: 2 }; + case "depth24plus" /* WebGPUConstants.TextureFormat.Depth24Plus */: + // eslint-disable-next-line no-throw-literal + throw "No fixed size for Depth24Plus format!"; + case "depth24plus-stencil8" /* WebGPUConstants.TextureFormat.Depth24PlusStencil8 */: + // eslint-disable-next-line no-throw-literal + throw "No fixed size for Depth24PlusStencil8 format!"; + case "depth32float" /* WebGPUConstants.TextureFormat.Depth32Float */: + return { width: 1, height: 1, length: 4 }; + case "depth32float-stencil8" /* WebGPUConstants.TextureFormat.Depth32FloatStencil8 */: + return { width: 1, height: 1, length: 5 }; + // BC compressed formats usable if "texture-compression-bc" is both + // supported by the device/user agent and enabled in requestDevice. + case "bc7-rgba-unorm" /* WebGPUConstants.TextureFormat.BC7RGBAUnorm */: + case "bc7-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB */: + case "bc6h-rgb-ufloat" /* WebGPUConstants.TextureFormat.BC6HRGBUFloat */: + case "bc6h-rgb-float" /* WebGPUConstants.TextureFormat.BC6HRGBFloat */: + case "bc5-rg-unorm" /* WebGPUConstants.TextureFormat.BC5RGUnorm */: + case "bc5-rg-snorm" /* WebGPUConstants.TextureFormat.BC5RGSnorm */: + case "bc3-rgba-unorm" /* WebGPUConstants.TextureFormat.BC3RGBAUnorm */: + case "bc3-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB */: + case "bc2-rgba-unorm" /* WebGPUConstants.TextureFormat.BC2RGBAUnorm */: + case "bc2-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB */: + return { width: 4, height: 4, length: 16 }; + case "bc4-r-unorm" /* WebGPUConstants.TextureFormat.BC4RUnorm */: + case "bc4-r-snorm" /* WebGPUConstants.TextureFormat.BC4RSnorm */: + case "bc1-rgba-unorm" /* WebGPUConstants.TextureFormat.BC1RGBAUnorm */: + case "bc1-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB */: + return { width: 4, height: 4, length: 8 }; + // ETC2 compressed formats usable if "texture-compression-etc2" is both + // supported by the device/user agent and enabled in requestDevice. + case "etc2-rgb8unorm" /* WebGPUConstants.TextureFormat.ETC2RGB8Unorm */: + case "etc2-rgb8unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB */: + case "etc2-rgb8a1unorm" /* WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm */: + case "etc2-rgb8a1unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB */: + case "eac-r11unorm" /* WebGPUConstants.TextureFormat.EACR11Unorm */: + case "eac-r11snorm" /* WebGPUConstants.TextureFormat.EACR11Snorm */: + return { width: 4, height: 4, length: 8 }; + case "etc2-rgba8unorm" /* WebGPUConstants.TextureFormat.ETC2RGBA8Unorm */: + case "etc2-rgba8unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB */: + case "eac-rg11unorm" /* WebGPUConstants.TextureFormat.EACRG11Unorm */: + case "eac-rg11snorm" /* WebGPUConstants.TextureFormat.EACRG11Snorm */: + return { width: 4, height: 4, length: 16 }; + // ASTC compressed formats usable if "texture-compression-astc" is both + // supported by the device/user agent and enabled in requestDevice. + case "astc-4x4-unorm" /* WebGPUConstants.TextureFormat.ASTC4x4Unorm */: + case "astc-4x4-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB */: + return { width: 4, height: 4, length: 16 }; + case "astc-5x4-unorm" /* WebGPUConstants.TextureFormat.ASTC5x4Unorm */: + case "astc-5x4-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB */: + return { width: 5, height: 4, length: 16 }; + case "astc-5x5-unorm" /* WebGPUConstants.TextureFormat.ASTC5x5Unorm */: + case "astc-5x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB */: + return { width: 5, height: 5, length: 16 }; + case "astc-6x5-unorm" /* WebGPUConstants.TextureFormat.ASTC6x5Unorm */: + case "astc-6x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB */: + return { width: 6, height: 5, length: 16 }; + case "astc-6x6-unorm" /* WebGPUConstants.TextureFormat.ASTC6x6Unorm */: + case "astc-6x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB */: + return { width: 6, height: 6, length: 16 }; + case "astc-8x5-unorm" /* WebGPUConstants.TextureFormat.ASTC8x5Unorm */: + case "astc-8x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB */: + return { width: 8, height: 5, length: 16 }; + case "astc-8x6-unorm" /* WebGPUConstants.TextureFormat.ASTC8x6Unorm */: + case "astc-8x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB */: + return { width: 8, height: 6, length: 16 }; + case "astc-8x8-unorm" /* WebGPUConstants.TextureFormat.ASTC8x8Unorm */: + case "astc-8x8-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB */: + return { width: 8, height: 8, length: 16 }; + case "astc-10x5-unorm" /* WebGPUConstants.TextureFormat.ASTC10x5Unorm */: + case "astc-10x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB */: + return { width: 10, height: 5, length: 16 }; + case "astc-10x6-unorm" /* WebGPUConstants.TextureFormat.ASTC10x6Unorm */: + case "astc-10x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB */: + return { width: 10, height: 6, length: 16 }; + case "astc-10x8-unorm" /* WebGPUConstants.TextureFormat.ASTC10x8Unorm */: + case "astc-10x8-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB */: + return { width: 10, height: 8, length: 16 }; + case "astc-10x10-unorm" /* WebGPUConstants.TextureFormat.ASTC10x10Unorm */: + case "astc-10x10-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB */: + return { width: 10, height: 10, length: 16 }; + case "astc-12x10-unorm" /* WebGPUConstants.TextureFormat.ASTC12x10Unorm */: + case "astc-12x10-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB */: + return { width: 12, height: 10, length: 16 }; + case "astc-12x12-unorm" /* WebGPUConstants.TextureFormat.ASTC12x12Unorm */: + case "astc-12x12-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB */: + return { width: 12, height: 12, length: 16 }; + } + return { width: 1, height: 1, length: 4 }; + } + static IsHardwareTexture(texture) { + return !!texture.release; + } + static IsInternalTexture(texture) { + return !!texture.dispose; + } + static IsImageBitmap(imageBitmap) { + return imageBitmap.close !== undefined; + } + static IsImageBitmapArray(imageBitmap) { + return Array.isArray(imageBitmap) && imageBitmap[0].close !== undefined; + } + static IsCompressedFormat(format) { + switch (format) { + case "bc7-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB */: + case "bc7-rgba-unorm" /* WebGPUConstants.TextureFormat.BC7RGBAUnorm */: + case "bc6h-rgb-float" /* WebGPUConstants.TextureFormat.BC6HRGBFloat */: + case "bc6h-rgb-ufloat" /* WebGPUConstants.TextureFormat.BC6HRGBUFloat */: + case "bc5-rg-snorm" /* WebGPUConstants.TextureFormat.BC5RGSnorm */: + case "bc5-rg-unorm" /* WebGPUConstants.TextureFormat.BC5RGUnorm */: + case "bc4-r-snorm" /* WebGPUConstants.TextureFormat.BC4RSnorm */: + case "bc4-r-unorm" /* WebGPUConstants.TextureFormat.BC4RUnorm */: + case "bc3-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB */: + case "bc3-rgba-unorm" /* WebGPUConstants.TextureFormat.BC3RGBAUnorm */: + case "bc2-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB */: + case "bc2-rgba-unorm" /* WebGPUConstants.TextureFormat.BC2RGBAUnorm */: + case "bc1-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB */: + case "bc1-rgba-unorm" /* WebGPUConstants.TextureFormat.BC1RGBAUnorm */: + case "etc2-rgb8unorm" /* WebGPUConstants.TextureFormat.ETC2RGB8Unorm */: + case "etc2-rgb8unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB */: + case "etc2-rgb8a1unorm" /* WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm */: + case "etc2-rgb8a1unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB */: + case "etc2-rgba8unorm" /* WebGPUConstants.TextureFormat.ETC2RGBA8Unorm */: + case "etc2-rgba8unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB */: + case "eac-r11unorm" /* WebGPUConstants.TextureFormat.EACR11Unorm */: + case "eac-r11snorm" /* WebGPUConstants.TextureFormat.EACR11Snorm */: + case "eac-rg11unorm" /* WebGPUConstants.TextureFormat.EACRG11Unorm */: + case "eac-rg11snorm" /* WebGPUConstants.TextureFormat.EACRG11Snorm */: + case "astc-4x4-unorm" /* WebGPUConstants.TextureFormat.ASTC4x4Unorm */: + case "astc-4x4-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB */: + case "astc-5x4-unorm" /* WebGPUConstants.TextureFormat.ASTC5x4Unorm */: + case "astc-5x4-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB */: + case "astc-5x5-unorm" /* WebGPUConstants.TextureFormat.ASTC5x5Unorm */: + case "astc-5x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB */: + case "astc-6x5-unorm" /* WebGPUConstants.TextureFormat.ASTC6x5Unorm */: + case "astc-6x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB */: + case "astc-6x6-unorm" /* WebGPUConstants.TextureFormat.ASTC6x6Unorm */: + case "astc-6x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB */: + case "astc-8x5-unorm" /* WebGPUConstants.TextureFormat.ASTC8x5Unorm */: + case "astc-8x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB */: + case "astc-8x6-unorm" /* WebGPUConstants.TextureFormat.ASTC8x6Unorm */: + case "astc-8x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB */: + case "astc-8x8-unorm" /* WebGPUConstants.TextureFormat.ASTC8x8Unorm */: + case "astc-8x8-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB */: + case "astc-10x5-unorm" /* WebGPUConstants.TextureFormat.ASTC10x5Unorm */: + case "astc-10x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB */: + case "astc-10x6-unorm" /* WebGPUConstants.TextureFormat.ASTC10x6Unorm */: + case "astc-10x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB */: + case "astc-10x8-unorm" /* WebGPUConstants.TextureFormat.ASTC10x8Unorm */: + case "astc-10x8-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB */: + case "astc-10x10-unorm" /* WebGPUConstants.TextureFormat.ASTC10x10Unorm */: + case "astc-10x10-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB */: + case "astc-12x10-unorm" /* WebGPUConstants.TextureFormat.ASTC12x10Unorm */: + case "astc-12x10-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB */: + case "astc-12x12-unorm" /* WebGPUConstants.TextureFormat.ASTC12x12Unorm */: + case "astc-12x12-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB */: + return true; + } + return false; + } + static GetWebGPUTextureFormat(type, format, useSRGBBuffer = false) { + switch (format) { + case 15: + return "depth16unorm" /* WebGPUConstants.TextureFormat.Depth16Unorm */; + case 16: + return "depth24plus" /* WebGPUConstants.TextureFormat.Depth24Plus */; + case 13: + return "depth24plus-stencil8" /* WebGPUConstants.TextureFormat.Depth24PlusStencil8 */; + case 14: + return "depth32float" /* WebGPUConstants.TextureFormat.Depth32Float */; + case 18: + return "depth32float-stencil8" /* WebGPUConstants.TextureFormat.Depth32FloatStencil8 */; + case 19: + return "stencil8" /* WebGPUConstants.TextureFormat.Stencil8 */; + case 36492: + return useSRGBBuffer ? "bc7-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB */ : "bc7-rgba-unorm" /* WebGPUConstants.TextureFormat.BC7RGBAUnorm */; + case 36495: + return "bc6h-rgb-ufloat" /* WebGPUConstants.TextureFormat.BC6HRGBUFloat */; + case 36494: + return "bc6h-rgb-float" /* WebGPUConstants.TextureFormat.BC6HRGBFloat */; + case 33779: + return useSRGBBuffer ? "bc3-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB */ : "bc3-rgba-unorm" /* WebGPUConstants.TextureFormat.BC3RGBAUnorm */; + case 33778: + return useSRGBBuffer ? "bc2-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB */ : "bc2-rgba-unorm" /* WebGPUConstants.TextureFormat.BC2RGBAUnorm */; + case 33777: + case 33776: + return useSRGBBuffer ? "bc1-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB */ : "bc1-rgba-unorm" /* WebGPUConstants.TextureFormat.BC1RGBAUnorm */; + case 37808: + return useSRGBBuffer ? "astc-4x4-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB */ : "astc-4x4-unorm" /* WebGPUConstants.TextureFormat.ASTC4x4Unorm */; + case 36196: + case 37492: + return useSRGBBuffer ? "etc2-rgb8unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB */ : "etc2-rgb8unorm" /* WebGPUConstants.TextureFormat.ETC2RGB8Unorm */; + case 37496: + return useSRGBBuffer ? "etc2-rgba8unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB */ : "etc2-rgba8unorm" /* WebGPUConstants.TextureFormat.ETC2RGBA8Unorm */; + } + switch (type) { + case 3: + switch (format) { + case 6: + return "r8snorm" /* WebGPUConstants.TextureFormat.R8Snorm */; + case 7: + return "rg8snorm" /* WebGPUConstants.TextureFormat.RG8Snorm */; + case 4: + // eslint-disable-next-line no-throw-literal + throw "RGB format not supported in WebGPU"; + case 8: + return "r8sint" /* WebGPUConstants.TextureFormat.R8Sint */; + case 9: + return "rg8sint" /* WebGPUConstants.TextureFormat.RG8Sint */; + case 10: + // eslint-disable-next-line no-throw-literal + throw "RGB_INTEGER format not supported in WebGPU"; + case 11: + return "rgba8sint" /* WebGPUConstants.TextureFormat.RGBA8Sint */; + default: + return "rgba8snorm" /* WebGPUConstants.TextureFormat.RGBA8Snorm */; + } + case 0: + switch (format) { + case 6: + return "r8unorm" /* WebGPUConstants.TextureFormat.R8Unorm */; + case 7: + return "rg8unorm" /* WebGPUConstants.TextureFormat.RG8Unorm */; + case 4: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_RGB format not supported in WebGPU"; + case 5: + return useSRGBBuffer ? "rgba8unorm-srgb" /* WebGPUConstants.TextureFormat.RGBA8UnormSRGB */ : "rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */; + case 12: + return useSRGBBuffer ? "bgra8unorm-srgb" /* WebGPUConstants.TextureFormat.BGRA8UnormSRGB */ : "bgra8unorm" /* WebGPUConstants.TextureFormat.BGRA8Unorm */; + case 8: + return "r8uint" /* WebGPUConstants.TextureFormat.R8Uint */; + case 9: + return "rg8uint" /* WebGPUConstants.TextureFormat.RG8Uint */; + case 10: + // eslint-disable-next-line no-throw-literal + throw "RGB_INTEGER format not supported in WebGPU"; + case 11: + return "rgba8uint" /* WebGPUConstants.TextureFormat.RGBA8Uint */; + case 0: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_ALPHA format not supported in WebGPU"; + case 1: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_LUMINANCE format not supported in WebGPU"; + case 2: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU"; + default: + return "rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */; + } + case 4: + switch (format) { + case 8: + return "r16sint" /* WebGPUConstants.TextureFormat.R16Sint */; + case 9: + return "rg16sint" /* WebGPUConstants.TextureFormat.RG16Sint */; + case 10: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU"; + case 11: + return "rgba16sint" /* WebGPUConstants.TextureFormat.RGBA16Sint */; + default: + return "rgba16sint" /* WebGPUConstants.TextureFormat.RGBA16Sint */; + } + case 5: + switch (format) { + case 8: + return "r16uint" /* WebGPUConstants.TextureFormat.R16Uint */; + case 9: + return "rg16uint" /* WebGPUConstants.TextureFormat.RG16Uint */; + case 10: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU"; + case 11: + return "rgba16uint" /* WebGPUConstants.TextureFormat.RGBA16Uint */; + default: + return "rgba16uint" /* WebGPUConstants.TextureFormat.RGBA16Uint */; + } + case 6: + switch (format) { + case 8: + return "r32sint" /* WebGPUConstants.TextureFormat.R32Sint */; + case 9: + return "rg32sint" /* WebGPUConstants.TextureFormat.RG32Sint */; + case 10: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU"; + case 11: + return "rgba32sint" /* WebGPUConstants.TextureFormat.RGBA32Sint */; + default: + return "rgba32sint" /* WebGPUConstants.TextureFormat.RGBA32Sint */; + } + case 7: // Refers to UNSIGNED_INT + switch (format) { + case 8: + return "r32uint" /* WebGPUConstants.TextureFormat.R32Uint */; + case 9: + return "rg32uint" /* WebGPUConstants.TextureFormat.RG32Uint */; + case 10: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU"; + case 11: + return "rgba32uint" /* WebGPUConstants.TextureFormat.RGBA32Uint */; + default: + return "rgba32uint" /* WebGPUConstants.TextureFormat.RGBA32Uint */; + } + case 1: + switch (format) { + case 6: + return "r32float" /* WebGPUConstants.TextureFormat.R32Float */; // By default. Other possibility is R16Float. + case 7: + return "rg32float" /* WebGPUConstants.TextureFormat.RG32Float */; // By default. Other possibility is RG16Float. + case 4: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_RGB format not supported in WebGPU"; + case 5: + return "rgba32float" /* WebGPUConstants.TextureFormat.RGBA32Float */; // By default. Other possibility is RGBA16Float. + default: + return "rgba32float" /* WebGPUConstants.TextureFormat.RGBA32Float */; + } + case 2: + switch (format) { + case 6: + return "r16float" /* WebGPUConstants.TextureFormat.R16Float */; + case 7: + return "rg16float" /* WebGPUConstants.TextureFormat.RG16Float */; + case 4: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_RGB format not supported in WebGPU"; + case 5: + return "rgba16float" /* WebGPUConstants.TextureFormat.RGBA16Float */; + default: + return "rgba16float" /* WebGPUConstants.TextureFormat.RGBA16Float */; + } + case 10: + // eslint-disable-next-line no-throw-literal + throw "TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU"; + case 13: + switch (format) { + case 5: + return "rg11b10ufloat" /* WebGPUConstants.TextureFormat.RG11B10UFloat */; + case 11: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"; + default: + return "rg11b10ufloat" /* WebGPUConstants.TextureFormat.RG11B10UFloat */; + } + case 14: + switch (format) { + case 5: + return "rgb9e5ufloat" /* WebGPUConstants.TextureFormat.RGB9E5UFloat */; + case 11: + // eslint-disable-next-line no-throw-literal + throw "TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"; + default: + return "rgb9e5ufloat" /* WebGPUConstants.TextureFormat.RGB9E5UFloat */; + } + case 8: + // eslint-disable-next-line no-throw-literal + throw "TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU"; + case 9: + // eslint-disable-next-line no-throw-literal + throw "TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU"; + case 11: + switch (format) { + case 5: + return "rgb10a2unorm" /* WebGPUConstants.TextureFormat.RGB10A2Unorm */; + case 11: + return "rgb10a2uint" /* WebGPUConstants.TextureFormat.RGB10A2UINT */; + default: + return "rgb10a2unorm" /* WebGPUConstants.TextureFormat.RGB10A2Unorm */; + } + } + return useSRGBBuffer ? "rgba8unorm-srgb" /* WebGPUConstants.TextureFormat.RGBA8UnormSRGB */ : "rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */; + } + static GetNumChannelsFromWebGPUTextureFormat(format) { + switch (format) { + case "r8unorm" /* WebGPUConstants.TextureFormat.R8Unorm */: + case "r8snorm" /* WebGPUConstants.TextureFormat.R8Snorm */: + case "r8uint" /* WebGPUConstants.TextureFormat.R8Uint */: + case "r8sint" /* WebGPUConstants.TextureFormat.R8Sint */: + case "bc4-r-unorm" /* WebGPUConstants.TextureFormat.BC4RUnorm */: + case "bc4-r-snorm" /* WebGPUConstants.TextureFormat.BC4RSnorm */: + case "r16uint" /* WebGPUConstants.TextureFormat.R16Uint */: + case "r16sint" /* WebGPUConstants.TextureFormat.R16Sint */: + case "depth16unorm" /* WebGPUConstants.TextureFormat.Depth16Unorm */: + case "r16float" /* WebGPUConstants.TextureFormat.R16Float */: + case "r16unorm" /* WebGPUConstants.TextureFormat.R16Unorm */: + case "r16snorm" /* WebGPUConstants.TextureFormat.R16Snorm */: + case "r32uint" /* WebGPUConstants.TextureFormat.R32Uint */: + case "r32sint" /* WebGPUConstants.TextureFormat.R32Sint */: + case "r32float" /* WebGPUConstants.TextureFormat.R32Float */: + case "depth32float" /* WebGPUConstants.TextureFormat.Depth32Float */: + case "stencil8" /* WebGPUConstants.TextureFormat.Stencil8 */: + case "depth24plus" /* WebGPUConstants.TextureFormat.Depth24Plus */: + case "eac-r11unorm" /* WebGPUConstants.TextureFormat.EACR11Unorm */: + case "eac-r11snorm" /* WebGPUConstants.TextureFormat.EACR11Snorm */: + return 1; + case "rg8unorm" /* WebGPUConstants.TextureFormat.RG8Unorm */: + case "rg8snorm" /* WebGPUConstants.TextureFormat.RG8Snorm */: + case "rg8uint" /* WebGPUConstants.TextureFormat.RG8Uint */: + case "rg8sint" /* WebGPUConstants.TextureFormat.RG8Sint */: + case "depth32float-stencil8" /* WebGPUConstants.TextureFormat.Depth32FloatStencil8 */: + case "bc5-rg-unorm" /* WebGPUConstants.TextureFormat.BC5RGUnorm */: + case "bc5-rg-snorm" /* WebGPUConstants.TextureFormat.BC5RGSnorm */: + case "rg16uint" /* WebGPUConstants.TextureFormat.RG16Uint */: + case "rg16sint" /* WebGPUConstants.TextureFormat.RG16Sint */: + case "rg16float" /* WebGPUConstants.TextureFormat.RG16Float */: + case "rg16unorm" /* WebGPUConstants.TextureFormat.RG16Unorm */: + case "rg16snorm" /* WebGPUConstants.TextureFormat.RG16Snorm */: + case "rg32uint" /* WebGPUConstants.TextureFormat.RG32Uint */: + case "rg32sint" /* WebGPUConstants.TextureFormat.RG32Sint */: + case "rg32float" /* WebGPUConstants.TextureFormat.RG32Float */: + case "depth24plus-stencil8" /* WebGPUConstants.TextureFormat.Depth24PlusStencil8 */: + case "eac-rg11unorm" /* WebGPUConstants.TextureFormat.EACRG11Unorm */: + case "eac-rg11snorm" /* WebGPUConstants.TextureFormat.EACRG11Snorm */: + return 2; + case "rgb9e5ufloat" /* WebGPUConstants.TextureFormat.RGB9E5UFloat */: + case "rg11b10ufloat" /* WebGPUConstants.TextureFormat.RG11B10UFloat */: + case "bc6h-rgb-ufloat" /* WebGPUConstants.TextureFormat.BC6HRGBUFloat */: + case "bc6h-rgb-float" /* WebGPUConstants.TextureFormat.BC6HRGBFloat */: + case "etc2-rgb8unorm" /* WebGPUConstants.TextureFormat.ETC2RGB8Unorm */: + case "etc2-rgb8unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB */: + return 3; + case "rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */: + case "rgba8unorm-srgb" /* WebGPUConstants.TextureFormat.RGBA8UnormSRGB */: + case "rgba8snorm" /* WebGPUConstants.TextureFormat.RGBA8Snorm */: + case "rgba8uint" /* WebGPUConstants.TextureFormat.RGBA8Uint */: + case "rgba8sint" /* WebGPUConstants.TextureFormat.RGBA8Sint */: + case "bgra8unorm" /* WebGPUConstants.TextureFormat.BGRA8Unorm */: + case "bgra8unorm-srgb" /* WebGPUConstants.TextureFormat.BGRA8UnormSRGB */: + case "rgba16unorm" /* WebGPUConstants.TextureFormat.RGBA16Unorm */: + case "rgba16snorm" /* WebGPUConstants.TextureFormat.RGBA16Snorm */: + case "rgb10a2uint" /* WebGPUConstants.TextureFormat.RGB10A2UINT */: + case "rgb10a2unorm" /* WebGPUConstants.TextureFormat.RGB10A2Unorm */: + case "bc7-rgba-unorm" /* WebGPUConstants.TextureFormat.BC7RGBAUnorm */: + case "bc7-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB */: + case "bc3-rgba-unorm" /* WebGPUConstants.TextureFormat.BC3RGBAUnorm */: + case "bc3-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB */: + case "bc2-rgba-unorm" /* WebGPUConstants.TextureFormat.BC2RGBAUnorm */: + case "bc2-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB */: + case "bc1-rgba-unorm" /* WebGPUConstants.TextureFormat.BC1RGBAUnorm */: + case "bc1-rgba-unorm-srgb" /* WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB */: + case "rgba16uint" /* WebGPUConstants.TextureFormat.RGBA16Uint */: + case "rgba16sint" /* WebGPUConstants.TextureFormat.RGBA16Sint */: + case "rgba16float" /* WebGPUConstants.TextureFormat.RGBA16Float */: + case "rgba32uint" /* WebGPUConstants.TextureFormat.RGBA32Uint */: + case "rgba32sint" /* WebGPUConstants.TextureFormat.RGBA32Sint */: + case "rgba32float" /* WebGPUConstants.TextureFormat.RGBA32Float */: + case "etc2-rgb8a1unorm" /* WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm */: + case "etc2-rgb8a1unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB */: + case "etc2-rgba8unorm" /* WebGPUConstants.TextureFormat.ETC2RGBA8Unorm */: + case "etc2-rgba8unorm-srgb" /* WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB */: + case "astc-4x4-unorm" /* WebGPUConstants.TextureFormat.ASTC4x4Unorm */: + case "astc-4x4-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB */: + case "astc-5x4-unorm" /* WebGPUConstants.TextureFormat.ASTC5x4Unorm */: + case "astc-5x4-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB */: + case "astc-5x5-unorm" /* WebGPUConstants.TextureFormat.ASTC5x5Unorm */: + case "astc-5x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB */: + case "astc-6x5-unorm" /* WebGPUConstants.TextureFormat.ASTC6x5Unorm */: + case "astc-6x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB */: + case "astc-6x6-unorm" /* WebGPUConstants.TextureFormat.ASTC6x6Unorm */: + case "astc-6x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB */: + case "astc-8x5-unorm" /* WebGPUConstants.TextureFormat.ASTC8x5Unorm */: + case "astc-8x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB */: + case "astc-8x6-unorm" /* WebGPUConstants.TextureFormat.ASTC8x6Unorm */: + case "astc-8x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB */: + case "astc-8x8-unorm" /* WebGPUConstants.TextureFormat.ASTC8x8Unorm */: + case "astc-8x8-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB */: + case "astc-10x5-unorm" /* WebGPUConstants.TextureFormat.ASTC10x5Unorm */: + case "astc-10x5-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB */: + case "astc-10x6-unorm" /* WebGPUConstants.TextureFormat.ASTC10x6Unorm */: + case "astc-10x6-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB */: + case "astc-10x8-unorm" /* WebGPUConstants.TextureFormat.ASTC10x8Unorm */: + case "astc-10x8-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB */: + case "astc-10x10-unorm" /* WebGPUConstants.TextureFormat.ASTC10x10Unorm */: + case "astc-10x10-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB */: + case "astc-12x10-unorm" /* WebGPUConstants.TextureFormat.ASTC12x10Unorm */: + case "astc-12x10-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB */: + case "astc-12x12-unorm" /* WebGPUConstants.TextureFormat.ASTC12x12Unorm */: + case "astc-12x12-unorm-srgb" /* WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB */: + return 4; + } + // eslint-disable-next-line no-throw-literal + throw `Unknown format ${format}!`; + } + static HasStencilAspect(format) { + switch (format) { + case "stencil8" /* WebGPUConstants.TextureFormat.Stencil8 */: + case "depth32float-stencil8" /* WebGPUConstants.TextureFormat.Depth32FloatStencil8 */: + case "depth24plus-stencil8" /* WebGPUConstants.TextureFormat.Depth24PlusStencil8 */: + return true; + } + return false; + } + static HasDepthAndStencilAspects(format) { + switch (format) { + case "depth32float-stencil8" /* WebGPUConstants.TextureFormat.Depth32FloatStencil8 */: + case "depth24plus-stencil8" /* WebGPUConstants.TextureFormat.Depth24PlusStencil8 */: + return true; + } + return false; + } + static GetDepthFormatOnly(format) { + switch (format) { + case "depth16unorm" /* WebGPUConstants.TextureFormat.Depth16Unorm */: + return "depth16unorm" /* WebGPUConstants.TextureFormat.Depth16Unorm */; + case "depth24plus" /* WebGPUConstants.TextureFormat.Depth24Plus */: + return "depth24plus" /* WebGPUConstants.TextureFormat.Depth24Plus */; + case "depth24plus-stencil8" /* WebGPUConstants.TextureFormat.Depth24PlusStencil8 */: + return "depth24plus" /* WebGPUConstants.TextureFormat.Depth24Plus */; + case "depth32float" /* WebGPUConstants.TextureFormat.Depth32Float */: + return "depth32float" /* WebGPUConstants.TextureFormat.Depth32Float */; + case "depth32float-stencil8" /* WebGPUConstants.TextureFormat.Depth32FloatStencil8 */: + return "depth32float" /* WebGPUConstants.TextureFormat.Depth32Float */; + } + return format; + } + static GetSample(sampleCount) { + // WebGPU only supports 1 or 4 + return sampleCount > 1 ? 4 : 1; + } +} + +/** + * The base engine class for WebGPU + */ +class ThinWebGPUEngine extends AbstractEngine { + constructor() { + super(...arguments); + // TODO WEBGPU remove those variables when code stabilized + /** @internal */ + this.dbgShowShaderCode = false; + /** @internal */ + this.dbgSanityChecks = true; + /** @internal */ + this.dbgVerboseLogsNumFrames = 10; + /** @internal */ + this.dbgLogIfNotDrawWrapper = true; + /** @internal */ + this.dbgShowEmptyEnableEffectCalls = true; + /** @internal */ + this.dbgVerboseLogsForFirstFrames = false; + /** @internal */ + this._currentRenderPass = null; + this._snapshotRenderingMode = 0; + /** @internal */ + this._timestampIndex = 0; + /** @internal */ + this._debugStackRenderPass = []; + } + /** + * Enables or disables GPU timing measurements. + * Note that this is only supported if the "timestamp-query" extension is enabled in the options. + */ + get enableGPUTimingMeasurements() { + return this._timestampQuery.enable; + } + set enableGPUTimingMeasurements(enable) { + if (this._timestampQuery.enable === enable) { + return; + } + this.gpuTimeInFrameForMainPass = enable ? new WebGPUPerfCounter() : undefined; + this._timestampQuery.enable = enable; + } + _currentPassIsMainPass() { + return this._currentRenderTarget === null; + } + /** @internal */ + _endCurrentRenderPass() { + if (!this._currentRenderPass) { + return 0; + } + if (this._debugStackRenderPass.length !== 0) { + for (let i = 0; i < this._debugStackRenderPass.length; ++i) { + this._currentRenderPass.popDebugGroup(); + } + } + const currentPassIndex = this._currentPassIsMainPass() ? 2 : 1; + if (!this._snapshotRendering.endRenderPass(this._currentRenderPass) && !this.compatibilityMode) { + this._bundleList.run(this._currentRenderPass); + this._bundleList.reset(); + } + this._currentRenderPass.end(); + this._timestampQuery.endPass(this._timestampIndex, (this._currentRenderTarget && this._currentRenderTarget.gpuTimeInFrame + ? this._currentRenderTarget.gpuTimeInFrame + : this.gpuTimeInFrameForMainPass)); + this._timestampIndex += 2; + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log("frame #" + + this._count + + " - " + + (currentPassIndex === 2 ? "main" : "render target") + + " end pass" + + (currentPassIndex === 1 ? " - internalTexture.uniqueId=" + this._currentRenderTarget?.texture?.uniqueId : "")); + } + } + this._debugPopGroup?.(0); + this._currentRenderPass = null; + return currentPassIndex; + } + /** + * @internal + */ + _generateMipmaps(texture, commandEncoder) { + commandEncoder = commandEncoder ?? this._renderEncoder; + const gpuHardwareTexture = texture._hardwareTexture; + if (!gpuHardwareTexture) { + return; + } + if (commandEncoder === this._renderEncoder) { + // We must close the current pass (if any) because we are going to use the render encoder to generate the mipmaps (so, we are going to create a new render pass) + this._endCurrentRenderPass(); + } + const format = texture._hardwareTexture.format; + const mipmapCount = WebGPUTextureHelper.ComputeNumMipmapLevels(texture.width, texture.height); + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log("frame #" + + this._count + + " - generate mipmaps - width=" + + texture.width + + ", height=" + + texture.height + + ", isCube=" + + texture.isCube + + ", command encoder=" + + (commandEncoder === this._renderEncoder ? "render" : "copy")); + } + } + if (texture.isCube) { + this._textureHelper.generateCubeMipmaps(gpuHardwareTexture, format, mipmapCount, commandEncoder); + } + else { + this._textureHelper.generateMipmaps(gpuHardwareTexture, format, mipmapCount, 0, texture.is3D, commandEncoder); + } + } +} + +ThinWebGPUEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange = false) { + if (this._alphaMode === mode && ((mode === 0 && !this._alphaState.alphaBlend) || (mode !== 0 && this._alphaState.alphaBlend))) { + if (!noDepthWriteChange) { + // Make sure we still have the correct depth mask according to the alpha mode (a transparent material could have forced writting to the depth buffer, for instance) + const depthMask = mode === 0; + if (this.depthCullingState.depthMask !== depthMask) { + this.setDepthWrite(depthMask); + this._cacheRenderPipeline.setDepthWriteEnabled(depthMask); + } + } + return; + } + switch (mode) { + case 0: + this._alphaState.alphaBlend = false; + break; + case 7: + this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 1); + this._alphaState.alphaBlend = true; + break; + case 8: + this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771); + this._alphaState.alphaBlend = true; + break; + case 2: + this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 1); + this._alphaState.alphaBlend = true; + break; + case 6: + this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1); + this._alphaState.alphaBlend = true; + break; + case 1: + this._alphaState.setAlphaBlendFunctionParameters(770, 1, 0, 1); + this._alphaState.alphaBlend = true; + break; + case 3: + this._alphaState.setAlphaBlendFunctionParameters(0, 769, 1, 1); + this._alphaState.alphaBlend = true; + break; + case 4: + this._alphaState.setAlphaBlendFunctionParameters(774, 0, 1, 1); + this._alphaState.alphaBlend = true; + break; + case 5: + this._alphaState.setAlphaBlendFunctionParameters(770, 769, 1, 1); + this._alphaState.alphaBlend = true; + break; + case 9: + this._alphaState.setAlphaBlendFunctionParameters(32769, 32770, 32771, 32772); + this._alphaState.alphaBlend = true; + break; + case 10: + this._alphaState.setAlphaBlendFunctionParameters(1, 769, 1, 771); + this._alphaState.alphaBlend = true; + break; + case 11: + this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 1); + this._alphaState.alphaBlend = true; + break; + case 12: + this._alphaState.setAlphaBlendFunctionParameters(772, 1, 0, 0); + this._alphaState.alphaBlend = true; + break; + case 13: + this._alphaState.setAlphaBlendFunctionParameters(775, 769, 773, 771); + this._alphaState.alphaBlend = true; + break; + case 14: + this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771); + this._alphaState.alphaBlend = true; + break; + case 15: + this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 0); + this._alphaState.alphaBlend = true; + break; + case 16: + this._alphaState.setAlphaBlendFunctionParameters(775, 769, 0, 1); + this._alphaState.alphaBlend = true; + break; + case 17: + // Same as ALPHA_COMBINE but accumulates (1 - alpha) values in the alpha channel for a later readout in order independant transparency + this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 771); + this._alphaState.alphaBlend = true; + break; + } + if (!noDepthWriteChange) { + this.setDepthWrite(mode === 0); + this._cacheRenderPipeline.setDepthWriteEnabled(mode === 0); + } + this._alphaMode = mode; + this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend); + this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters); +}; +ThinWebGPUEngine.prototype.setAlphaEquation = function (equation) { + AbstractEngine.prototype.setAlphaEquation.call(this, equation); + this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters); +}; + +/** @internal */ +// eslint-disable-next-line import/export +var PowerPreference; +(function (PowerPreference) { + PowerPreference["LowPower"] = "low-power"; + PowerPreference["HighPerformance"] = "high-performance"; +})(PowerPreference || (PowerPreference = {})); +/** @internal */ +var FeatureName; +(function (FeatureName) { + FeatureName["DepthClipControl"] = "depth-clip-control"; + FeatureName["Depth32FloatStencil8"] = "depth32float-stencil8"; + FeatureName["TextureCompressionBC"] = "texture-compression-bc"; + FeatureName["TextureCompressionBCSliced3D"] = "texture-compression-bc-sliced-3d"; + FeatureName["TextureCompressionETC2"] = "texture-compression-etc2"; + FeatureName["TextureCompressionASTC"] = "texture-compression-astc"; + FeatureName["TextureCompressionASTCSliced3D"] = "texture-compression-astc-sliced-3d"; + FeatureName["TimestampQuery"] = "timestamp-query"; + FeatureName["IndirectFirstInstance"] = "indirect-first-instance"; + FeatureName["ShaderF16"] = "shader-f16"; + FeatureName["RG11B10UFloatRenderable"] = "rg11b10ufloat-renderable"; + FeatureName["BGRA8UnormStorage"] = "bgra8unorm-storage"; + FeatureName["Float32Filterable"] = "float32-filterable"; + FeatureName["Float32Blendable"] = "float32-blendable"; + FeatureName["ClipDistances"] = "clip-distances"; + FeatureName["DualSourceBlending"] = "dual-source-blending"; +})(FeatureName || (FeatureName = {})); +/** @internal */ +var BufferMapState; +(function (BufferMapState) { + BufferMapState["Unmapped"] = "unmapped"; + BufferMapState["Pending"] = "pending"; + BufferMapState["Mapped"] = "mapped"; +})(BufferMapState || (BufferMapState = {})); +/** @internal */ +var BufferUsage; +(function (BufferUsage) { + BufferUsage[BufferUsage["MapRead"] = 1] = "MapRead"; + BufferUsage[BufferUsage["MapWrite"] = 2] = "MapWrite"; + BufferUsage[BufferUsage["CopySrc"] = 4] = "CopySrc"; + BufferUsage[BufferUsage["CopyDst"] = 8] = "CopyDst"; + BufferUsage[BufferUsage["Index"] = 16] = "Index"; + BufferUsage[BufferUsage["Vertex"] = 32] = "Vertex"; + BufferUsage[BufferUsage["Uniform"] = 64] = "Uniform"; + BufferUsage[BufferUsage["Storage"] = 128] = "Storage"; + BufferUsage[BufferUsage["Indirect"] = 256] = "Indirect"; + BufferUsage[BufferUsage["QueryResolve"] = 512] = "QueryResolve"; +})(BufferUsage || (BufferUsage = {})); +/** @internal */ +var MapMode; +(function (MapMode) { + MapMode[MapMode["Read"] = 1] = "Read"; + MapMode[MapMode["Write"] = 2] = "Write"; +})(MapMode || (MapMode = {})); +/** @internal */ +var TextureDimension; +(function (TextureDimension) { + TextureDimension["E1d"] = "1d"; + TextureDimension["E2d"] = "2d"; + TextureDimension["E3d"] = "3d"; +})(TextureDimension || (TextureDimension = {})); +/** @internal */ +var TextureUsage; +(function (TextureUsage) { + TextureUsage[TextureUsage["CopySrc"] = 1] = "CopySrc"; + TextureUsage[TextureUsage["CopyDst"] = 2] = "CopyDst"; + TextureUsage[TextureUsage["TextureBinding"] = 4] = "TextureBinding"; + TextureUsage[TextureUsage["StorageBinding"] = 8] = "StorageBinding"; + TextureUsage[TextureUsage["RenderAttachment"] = 16] = "RenderAttachment"; +})(TextureUsage || (TextureUsage = {})); +/** @internal */ +var TextureViewDimension; +(function (TextureViewDimension) { + TextureViewDimension["E1d"] = "1d"; + TextureViewDimension["E2d"] = "2d"; + TextureViewDimension["E2dArray"] = "2d-array"; + TextureViewDimension["Cube"] = "cube"; + TextureViewDimension["CubeArray"] = "cube-array"; + TextureViewDimension["E3d"] = "3d"; +})(TextureViewDimension || (TextureViewDimension = {})); +/** @internal */ +var TextureAspect; +(function (TextureAspect) { + TextureAspect["All"] = "all"; + TextureAspect["StencilOnly"] = "stencil-only"; + TextureAspect["DepthOnly"] = "depth-only"; +})(TextureAspect || (TextureAspect = {})); +/** + * Comments taken from https://github.com/gfx-rs/wgpu/blob/master/wgpu-types/src/lib.rs + * @internal + */ +var TextureFormat; +(function (TextureFormat) { + // 8-bit formats + TextureFormat["R8Unorm"] = "r8unorm"; + TextureFormat["R8Snorm"] = "r8snorm"; + TextureFormat["R8Uint"] = "r8uint"; + TextureFormat["R8Sint"] = "r8sint"; + // 16-bit formats + TextureFormat["R16Uint"] = "r16uint"; + TextureFormat["R16Sint"] = "r16sint"; + TextureFormat["R16Float"] = "r16float"; + TextureFormat["RG8Unorm"] = "rg8unorm"; + TextureFormat["RG8Snorm"] = "rg8snorm"; + TextureFormat["RG8Uint"] = "rg8uint"; + TextureFormat["RG8Sint"] = "rg8sint"; + TextureFormat["R16Unorm"] = "r16unorm"; + TextureFormat["R16Snorm"] = "r16snorm"; + TextureFormat["RG16Unorm"] = "rg16unorm"; + TextureFormat["RG16Snorm"] = "rg16snorm"; + TextureFormat["RGBA16Unorm"] = "rgba16unorm"; + TextureFormat["RGBA16Snorm"] = "rgba16snorm"; + // 32-bit formats + TextureFormat["R32Uint"] = "r32uint"; + TextureFormat["R32Sint"] = "r32sint"; + TextureFormat["R32Float"] = "r32float"; + TextureFormat["RG16Uint"] = "rg16uint"; + TextureFormat["RG16Sint"] = "rg16sint"; + TextureFormat["RG16Float"] = "rg16float"; + TextureFormat["RGBA8Unorm"] = "rgba8unorm"; + TextureFormat["RGBA8UnormSRGB"] = "rgba8unorm-srgb"; + TextureFormat["RGBA8Snorm"] = "rgba8snorm"; + TextureFormat["RGBA8Uint"] = "rgba8uint"; + TextureFormat["RGBA8Sint"] = "rgba8sint"; + TextureFormat["BGRA8Unorm"] = "bgra8unorm"; + TextureFormat["BGRA8UnormSRGB"] = "bgra8unorm-srgb"; + // Packed 32-bit formats + TextureFormat["RGB9E5UFloat"] = "rgb9e5ufloat"; + TextureFormat["RGB10A2UINT"] = "rgb10a2uint"; + TextureFormat["RGB10A2Unorm"] = "rgb10a2unorm"; + TextureFormat["RG11B10UFloat"] = "rg11b10ufloat"; + // 64-bit formats + TextureFormat["RG32Uint"] = "rg32uint"; + TextureFormat["RG32Sint"] = "rg32sint"; + TextureFormat["RG32Float"] = "rg32float"; + TextureFormat["RGBA16Uint"] = "rgba16uint"; + TextureFormat["RGBA16Sint"] = "rgba16sint"; + TextureFormat["RGBA16Float"] = "rgba16float"; + // 128-bit formats + TextureFormat["RGBA32Uint"] = "rgba32uint"; + TextureFormat["RGBA32Sint"] = "rgba32sint"; + TextureFormat["RGBA32Float"] = "rgba32float"; + // Depth and stencil formats + TextureFormat["Stencil8"] = "stencil8"; + TextureFormat["Depth16Unorm"] = "depth16unorm"; + TextureFormat["Depth24Plus"] = "depth24plus"; + TextureFormat["Depth24PlusStencil8"] = "depth24plus-stencil8"; + TextureFormat["Depth32Float"] = "depth32float"; + // BC compressed formats usable if "texture-compression-bc" is both + // supported by the device/user agent and enabled in requestDevice. + TextureFormat["BC1RGBAUnorm"] = "bc1-rgba-unorm"; + TextureFormat["BC1RGBAUnormSRGB"] = "bc1-rgba-unorm-srgb"; + TextureFormat["BC2RGBAUnorm"] = "bc2-rgba-unorm"; + TextureFormat["BC2RGBAUnormSRGB"] = "bc2-rgba-unorm-srgb"; + TextureFormat["BC3RGBAUnorm"] = "bc3-rgba-unorm"; + TextureFormat["BC3RGBAUnormSRGB"] = "bc3-rgba-unorm-srgb"; + TextureFormat["BC4RUnorm"] = "bc4-r-unorm"; + TextureFormat["BC4RSnorm"] = "bc4-r-snorm"; + TextureFormat["BC5RGUnorm"] = "bc5-rg-unorm"; + TextureFormat["BC5RGSnorm"] = "bc5-rg-snorm"; + TextureFormat["BC6HRGBUFloat"] = "bc6h-rgb-ufloat"; + TextureFormat["BC6HRGBFloat"] = "bc6h-rgb-float"; + TextureFormat["BC7RGBAUnorm"] = "bc7-rgba-unorm"; + TextureFormat["BC7RGBAUnormSRGB"] = "bc7-rgba-unorm-srgb"; + // ETC2 compressed formats usable if "texture-compression-etc2" is both + // supported by the device/user agent and enabled in requestDevice. + TextureFormat["ETC2RGB8Unorm"] = "etc2-rgb8unorm"; + TextureFormat["ETC2RGB8UnormSRGB"] = "etc2-rgb8unorm-srgb"; + TextureFormat["ETC2RGB8A1Unorm"] = "etc2-rgb8a1unorm"; + TextureFormat["ETC2RGB8A1UnormSRGB"] = "etc2-rgb8a1unorm-srgb"; + TextureFormat["ETC2RGBA8Unorm"] = "etc2-rgba8unorm"; + TextureFormat["ETC2RGBA8UnormSRGB"] = "etc2-rgba8unorm-srgb"; + TextureFormat["EACR11Unorm"] = "eac-r11unorm"; + TextureFormat["EACR11Snorm"] = "eac-r11snorm"; + TextureFormat["EACRG11Unorm"] = "eac-rg11unorm"; + TextureFormat["EACRG11Snorm"] = "eac-rg11snorm"; + // ASTC compressed formats usable if "texture-compression-astc" is both + // supported by the device/user agent and enabled in requestDevice. + TextureFormat["ASTC4x4Unorm"] = "astc-4x4-unorm"; + TextureFormat["ASTC4x4UnormSRGB"] = "astc-4x4-unorm-srgb"; + TextureFormat["ASTC5x4Unorm"] = "astc-5x4-unorm"; + TextureFormat["ASTC5x4UnormSRGB"] = "astc-5x4-unorm-srgb"; + TextureFormat["ASTC5x5Unorm"] = "astc-5x5-unorm"; + TextureFormat["ASTC5x5UnormSRGB"] = "astc-5x5-unorm-srgb"; + TextureFormat["ASTC6x5Unorm"] = "astc-6x5-unorm"; + TextureFormat["ASTC6x5UnormSRGB"] = "astc-6x5-unorm-srgb"; + TextureFormat["ASTC6x6Unorm"] = "astc-6x6-unorm"; + TextureFormat["ASTC6x6UnormSRGB"] = "astc-6x6-unorm-srgb"; + TextureFormat["ASTC8x5Unorm"] = "astc-8x5-unorm"; + TextureFormat["ASTC8x5UnormSRGB"] = "astc-8x5-unorm-srgb"; + TextureFormat["ASTC8x6Unorm"] = "astc-8x6-unorm"; + TextureFormat["ASTC8x6UnormSRGB"] = "astc-8x6-unorm-srgb"; + TextureFormat["ASTC8x8Unorm"] = "astc-8x8-unorm"; + TextureFormat["ASTC8x8UnormSRGB"] = "astc-8x8-unorm-srgb"; + TextureFormat["ASTC10x5Unorm"] = "astc-10x5-unorm"; + TextureFormat["ASTC10x5UnormSRGB"] = "astc-10x5-unorm-srgb"; + TextureFormat["ASTC10x6Unorm"] = "astc-10x6-unorm"; + TextureFormat["ASTC10x6UnormSRGB"] = "astc-10x6-unorm-srgb"; + TextureFormat["ASTC10x8Unorm"] = "astc-10x8-unorm"; + TextureFormat["ASTC10x8UnormSRGB"] = "astc-10x8-unorm-srgb"; + TextureFormat["ASTC10x10Unorm"] = "astc-10x10-unorm"; + TextureFormat["ASTC10x10UnormSRGB"] = "astc-10x10-unorm-srgb"; + TextureFormat["ASTC12x10Unorm"] = "astc-12x10-unorm"; + TextureFormat["ASTC12x10UnormSRGB"] = "astc-12x10-unorm-srgb"; + TextureFormat["ASTC12x12Unorm"] = "astc-12x12-unorm"; + TextureFormat["ASTC12x12UnormSRGB"] = "astc-12x12-unorm-srgb"; + // "depth32float-stencil8" feature + TextureFormat["Depth32FloatStencil8"] = "depth32float-stencil8"; +})(TextureFormat || (TextureFormat = {})); +/** @internal */ +var AddressMode; +(function (AddressMode) { + AddressMode["ClampToEdge"] = "clamp-to-edge"; + AddressMode["Repeat"] = "repeat"; + AddressMode["MirrorRepeat"] = "mirror-repeat"; +})(AddressMode || (AddressMode = {})); +/** @internal */ +var FilterMode; +(function (FilterMode) { + FilterMode["Nearest"] = "nearest"; + FilterMode["Linear"] = "linear"; +})(FilterMode || (FilterMode = {})); +/** @internal */ +var MipmapFilterMode; +(function (MipmapFilterMode) { + MipmapFilterMode["Nearest"] = "nearest"; + MipmapFilterMode["Linear"] = "linear"; +})(MipmapFilterMode || (MipmapFilterMode = {})); +/** @internal */ +var CompareFunction; +(function (CompareFunction) { + CompareFunction["Never"] = "never"; + CompareFunction["Less"] = "less"; + CompareFunction["Equal"] = "equal"; + CompareFunction["LessEqual"] = "less-equal"; + CompareFunction["Greater"] = "greater"; + CompareFunction["NotEqual"] = "not-equal"; + CompareFunction["GreaterEqual"] = "greater-equal"; + CompareFunction["Always"] = "always"; +})(CompareFunction || (CompareFunction = {})); +/** @internal */ +var ShaderStage; +(function (ShaderStage) { + ShaderStage[ShaderStage["Vertex"] = 1] = "Vertex"; + ShaderStage[ShaderStage["Fragment"] = 2] = "Fragment"; + ShaderStage[ShaderStage["Compute"] = 4] = "Compute"; +})(ShaderStage || (ShaderStage = {})); +/** @internal */ +var BufferBindingType; +(function (BufferBindingType) { + BufferBindingType["Uniform"] = "uniform"; + BufferBindingType["Storage"] = "storage"; + BufferBindingType["ReadOnlyStorage"] = "read-only-storage"; +})(BufferBindingType || (BufferBindingType = {})); +/** @internal */ +var SamplerBindingType; +(function (SamplerBindingType) { + SamplerBindingType["Filtering"] = "filtering"; + SamplerBindingType["NonFiltering"] = "non-filtering"; + SamplerBindingType["Comparison"] = "comparison"; +})(SamplerBindingType || (SamplerBindingType = {})); +/** @internal */ +var TextureSampleType; +(function (TextureSampleType) { + TextureSampleType["Float"] = "float"; + TextureSampleType["UnfilterableFloat"] = "unfilterable-float"; + TextureSampleType["Depth"] = "depth"; + TextureSampleType["Sint"] = "sint"; + TextureSampleType["Uint"] = "uint"; +})(TextureSampleType || (TextureSampleType = {})); +/** @internal */ +var StorageTextureAccess; +(function (StorageTextureAccess) { + StorageTextureAccess["WriteOnly"] = "write-only"; + StorageTextureAccess["ReadOnly"] = "read-only"; + StorageTextureAccess["ReadWrite"] = "read-write"; +})(StorageTextureAccess || (StorageTextureAccess = {})); +/** @internal */ +var CompilationMessageType; +(function (CompilationMessageType) { + CompilationMessageType["Error"] = "error"; + CompilationMessageType["Warning"] = "warning"; + CompilationMessageType["Info"] = "info"; +})(CompilationMessageType || (CompilationMessageType = {})); +/** @internal */ +var PipelineErrorReason; +(function (PipelineErrorReason) { + PipelineErrorReason["Validation"] = "validation"; + PipelineErrorReason["Internal"] = "internal"; +})(PipelineErrorReason || (PipelineErrorReason = {})); +/** @internal */ +var AutoLayoutMode; +(function (AutoLayoutMode) { + AutoLayoutMode["Auto"] = "auto"; +})(AutoLayoutMode || (AutoLayoutMode = {})); +/** @internal */ +var PrimitiveTopology; +(function (PrimitiveTopology) { + PrimitiveTopology["PointList"] = "point-list"; + PrimitiveTopology["LineList"] = "line-list"; + PrimitiveTopology["LineStrip"] = "line-strip"; + PrimitiveTopology["TriangleList"] = "triangle-list"; + PrimitiveTopology["TriangleStrip"] = "triangle-strip"; +})(PrimitiveTopology || (PrimitiveTopology = {})); +/** @internal */ +var FrontFace; +(function (FrontFace) { + FrontFace["CCW"] = "ccw"; + FrontFace["CW"] = "cw"; +})(FrontFace || (FrontFace = {})); +/** @internal */ +var CullMode; +(function (CullMode) { + CullMode["None"] = "none"; + CullMode["Front"] = "front"; + CullMode["Back"] = "back"; +})(CullMode || (CullMode = {})); +/** @internal */ +var ColorWrite; +(function (ColorWrite) { + ColorWrite[ColorWrite["Red"] = 1] = "Red"; + ColorWrite[ColorWrite["Green"] = 2] = "Green"; + ColorWrite[ColorWrite["Blue"] = 4] = "Blue"; + ColorWrite[ColorWrite["Alpha"] = 8] = "Alpha"; + ColorWrite[ColorWrite["All"] = 15] = "All"; +})(ColorWrite || (ColorWrite = {})); +/** @internal */ +var BlendFactor; +(function (BlendFactor) { + BlendFactor["Zero"] = "zero"; + BlendFactor["One"] = "one"; + BlendFactor["Src"] = "src"; + BlendFactor["OneMinusSrc"] = "one-minus-src"; + BlendFactor["SrcAlpha"] = "src-alpha"; + BlendFactor["OneMinusSrcAlpha"] = "one-minus-src-alpha"; + BlendFactor["Dst"] = "dst"; + BlendFactor["OneMinusDst"] = "one-minus-dst"; + BlendFactor["DstAlpha"] = "dst-alpha"; + BlendFactor["OneMinusDstAlpha"] = "one-minus-dst-alpha"; + BlendFactor["SrcAlphaSaturated"] = "src-alpha-saturated"; + BlendFactor["Constant"] = "constant"; + BlendFactor["OneMinusConstant"] = "one-minus-constant"; + BlendFactor["Src1"] = "src1"; + BlendFactor["OneMinusSrc1"] = "one-minus-src1"; + BlendFactor["Src1Alpha"] = "src1-alpha"; + BlendFactor["OneMinusSrc1Alpha"] = "one-minus-src1-alpha"; +})(BlendFactor || (BlendFactor = {})); +/** @internal */ +var BlendOperation; +(function (BlendOperation) { + BlendOperation["Add"] = "add"; + BlendOperation["Subtract"] = "subtract"; + BlendOperation["ReverseSubtract"] = "reverse-subtract"; + BlendOperation["Min"] = "min"; + BlendOperation["Max"] = "max"; +})(BlendOperation || (BlendOperation = {})); +/** @internal */ +var StencilOperation; +(function (StencilOperation) { + StencilOperation["Keep"] = "keep"; + StencilOperation["Zero"] = "zero"; + StencilOperation["Replace"] = "replace"; + StencilOperation["Invert"] = "invert"; + StencilOperation["IncrementClamp"] = "increment-clamp"; + StencilOperation["DecrementClamp"] = "decrement-clamp"; + StencilOperation["IncrementWrap"] = "increment-wrap"; + StencilOperation["DecrementWrap"] = "decrement-wrap"; +})(StencilOperation || (StencilOperation = {})); +/** @internal */ +var IndexFormat; +(function (IndexFormat) { + IndexFormat["Uint16"] = "uint16"; + IndexFormat["Uint32"] = "uint32"; +})(IndexFormat || (IndexFormat = {})); +/** @internal */ +var VertexFormat; +(function (VertexFormat) { + VertexFormat["Uint8x2"] = "uint8x2"; + VertexFormat["Uint8x4"] = "uint8x4"; + VertexFormat["Sint8x2"] = "sint8x2"; + VertexFormat["Sint8x4"] = "sint8x4"; + VertexFormat["Unorm8x2"] = "unorm8x2"; + VertexFormat["Unorm8x4"] = "unorm8x4"; + VertexFormat["Snorm8x2"] = "snorm8x2"; + VertexFormat["Snorm8x4"] = "snorm8x4"; + VertexFormat["Uint16x2"] = "uint16x2"; + VertexFormat["Uint16x4"] = "uint16x4"; + VertexFormat["Sint16x2"] = "sint16x2"; + VertexFormat["Sint16x4"] = "sint16x4"; + VertexFormat["Unorm16x2"] = "unorm16x2"; + VertexFormat["Unorm16x4"] = "unorm16x4"; + VertexFormat["Snorm16x2"] = "snorm16x2"; + VertexFormat["Snorm16x4"] = "snorm16x4"; + VertexFormat["Float16x2"] = "float16x2"; + VertexFormat["Float16x4"] = "float16x4"; + VertexFormat["Float32"] = "float32"; + VertexFormat["Float32x2"] = "float32x2"; + VertexFormat["Float32x3"] = "float32x3"; + VertexFormat["Float32x4"] = "float32x4"; + VertexFormat["Uint32"] = "uint32"; + VertexFormat["Uint32x2"] = "uint32x2"; + VertexFormat["Uint32x3"] = "uint32x3"; + VertexFormat["Uint32x4"] = "uint32x4"; + VertexFormat["Sint32"] = "sint32"; + VertexFormat["Sint32x2"] = "sint32x2"; + VertexFormat["Sint32x3"] = "sint32x3"; + VertexFormat["Sint32x4"] = "sint32x4"; + VertexFormat["UNORM10x10x10x2"] = "unorm10-10-10-2"; +})(VertexFormat || (VertexFormat = {})); +/** @internal */ +var VertexStepMode; +(function (VertexStepMode) { + VertexStepMode["Vertex"] = "vertex"; + VertexStepMode["Instance"] = "instance"; +})(VertexStepMode || (VertexStepMode = {})); +/** @internal */ +var ComputePassTimestampLocation; +(function (ComputePassTimestampLocation) { + ComputePassTimestampLocation["Beginning"] = "beginning"; + ComputePassTimestampLocation["End"] = "end"; +})(ComputePassTimestampLocation || (ComputePassTimestampLocation = {})); +/** @internal */ +var RenderPassTimestampLocation; +(function (RenderPassTimestampLocation) { + RenderPassTimestampLocation["Beginning"] = "beginning"; + RenderPassTimestampLocation["End"] = "end"; +})(RenderPassTimestampLocation || (RenderPassTimestampLocation = {})); +/** @internal */ +var LoadOp; +(function (LoadOp) { + LoadOp["Load"] = "load"; + LoadOp["Clear"] = "clear"; +})(LoadOp || (LoadOp = {})); +/** @internal */ +var StoreOp; +(function (StoreOp) { + StoreOp["Store"] = "store"; + StoreOp["Discard"] = "discard"; +})(StoreOp || (StoreOp = {})); +/** @internal */ +var QueryType; +(function (QueryType) { + QueryType["Occlusion"] = "occlusion"; + QueryType["Timestamp"] = "timestamp"; +})(QueryType || (QueryType = {})); +/** @internal */ +var CanvasAlphaMode; +(function (CanvasAlphaMode) { + CanvasAlphaMode["Opaque"] = "opaque"; + CanvasAlphaMode["Premultiplied"] = "premultiplied"; +})(CanvasAlphaMode || (CanvasAlphaMode = {})); +/** @internal */ +var CanvasToneMappingMode; +(function (CanvasToneMappingMode) { + CanvasToneMappingMode["Standard"] = "standard"; + CanvasToneMappingMode["Extended"] = "extended"; +})(CanvasToneMappingMode || (CanvasToneMappingMode = {})); +/** @internal */ +var DeviceLostReason; +(function (DeviceLostReason) { + DeviceLostReason["Unknown"] = "unknown"; + DeviceLostReason["Destroyed"] = "destroyed"; +})(DeviceLostReason || (DeviceLostReason = {})); +/** @internal */ +var ErrorFilter; +(function (ErrorFilter) { + ErrorFilter["Validation"] = "validation"; + ErrorFilter["OutOfMemory"] = "out-of-memory"; + ErrorFilter["Internal"] = "internal"; +})(ErrorFilter || (ErrorFilter = {})); + +/** @internal */ +class WebGPUShaderProcessor { + constructor() { + this.shaderLanguage = 0 /* ShaderLanguage.GLSL */; + } + _addUniformToLeftOverUBO(name, uniformType, preProcessors) { + let length = 0; + [name, uniformType, length] = this._getArraySize(name, uniformType, preProcessors); + for (let i = 0; i < this._webgpuProcessingContext.leftOverUniforms.length; i++) { + if (this._webgpuProcessingContext.leftOverUniforms[i].name === name) { + return; + } + } + this._webgpuProcessingContext.leftOverUniforms.push({ + name, + type: uniformType, + length, + }); + } + _buildLeftOverUBO() { + if (!this._webgpuProcessingContext.leftOverUniforms.length) { + return ""; + } + const name = WebGPUShaderProcessor.LeftOvertUBOName; + let availableUBO = this._webgpuProcessingContext.availableBuffers[name]; + if (!availableUBO) { + availableUBO = { + binding: this._webgpuProcessingContext.getNextFreeUBOBinding(), + }; + this._webgpuProcessingContext.availableBuffers[name] = availableUBO; + this._addBufferBindingDescription(name, availableUBO, "uniform" /* WebGPUConstants.BufferBindingType.Uniform */, true); + this._addBufferBindingDescription(name, availableUBO, "uniform" /* WebGPUConstants.BufferBindingType.Uniform */, false); + } + return this._generateLeftOverUBOCode(name, availableUBO); + } + _collectBindingNames() { + // collect all the binding names for faster processing in WebGPUCacheBindGroup + for (let i = 0; i < this._webgpuProcessingContext.bindGroupLayoutEntries.length; i++) { + const setDefinition = this._webgpuProcessingContext.bindGroupLayoutEntries[i]; + if (setDefinition === undefined) { + this._webgpuProcessingContext.bindGroupLayoutEntries[i] = []; + continue; + } + for (let j = 0; j < setDefinition.length; j++) { + const entry = this._webgpuProcessingContext.bindGroupLayoutEntries[i][j]; + const name = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].name; + const nameInArrayOfTexture = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].nameInArrayOfTexture; + if (entry) { + if (entry.texture || entry.externalTexture || entry.storageTexture) { + this._webgpuProcessingContext.textureNames.push(nameInArrayOfTexture); + } + else if (entry.sampler) { + this._webgpuProcessingContext.samplerNames.push(name); + } + else if (entry.buffer) { + this._webgpuProcessingContext.bufferNames.push(name); + } + } + } + } + } + _preCreateBindGroupEntries() { + const bindGroupEntries = this._webgpuProcessingContext.bindGroupEntries; + for (let i = 0; i < this._webgpuProcessingContext.bindGroupLayoutEntries.length; i++) { + const setDefinition = this._webgpuProcessingContext.bindGroupLayoutEntries[i]; + const entries = []; + for (let j = 0; j < setDefinition.length; j++) { + const entry = this._webgpuProcessingContext.bindGroupLayoutEntries[i][j]; + if (entry.sampler || entry.texture || entry.storageTexture || entry.externalTexture) { + entries.push({ + binding: entry.binding, + resource: undefined, + }); + } + else if (entry.buffer) { + entries.push({ + binding: entry.binding, + resource: { + buffer: undefined, + offset: 0, + size: 0, + }, + }); + } + } + bindGroupEntries[i] = entries; + } + } + _addTextureBindingDescription(name, textureInfo, textureIndex, dimension, format, isVertex) { + // eslint-disable-next-line prefer-const + let { groupIndex, bindingIndex } = textureInfo.textures[textureIndex]; + if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) { + this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = []; + this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = []; + } + if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) { + let len; + if (dimension === null) { + len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({ + binding: bindingIndex, + visibility: 0, + externalTexture: {}, + }); + } + else if (format) { + len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({ + binding: bindingIndex, + visibility: 0, + storageTexture: { + access: "write-only" /* WebGPUConstants.StorageTextureAccess.WriteOnly */, + format, + viewDimension: dimension, + }, + }); + } + else { + len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({ + binding: bindingIndex, + visibility: 0, + texture: { + sampleType: textureInfo.sampleType, + viewDimension: dimension, + multisampled: false, + }, + }); + } + const textureName = textureInfo.isTextureArray ? name + textureIndex : name; + this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1, nameInArrayOfTexture: textureName }; + } + bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index; + if (isVertex) { + this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 1 /* WebGPUConstants.ShaderStage.Vertex */; + } + else { + this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 2 /* WebGPUConstants.ShaderStage.Fragment */; + } + } + _addSamplerBindingDescription(name, samplerInfo, isVertex) { + // eslint-disable-next-line prefer-const + let { groupIndex, bindingIndex } = samplerInfo.binding; + if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) { + this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = []; + this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = []; + } + if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) { + const len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({ + binding: bindingIndex, + visibility: 0, + sampler: { + type: samplerInfo.type, + }, + }); + this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1 }; + } + bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index; + if (isVertex) { + this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 1 /* WebGPUConstants.ShaderStage.Vertex */; + } + else { + this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 2 /* WebGPUConstants.ShaderStage.Fragment */; + } + } + _addBufferBindingDescription(name, uniformBufferInfo, bufferType, isVertex) { + // eslint-disable-next-line prefer-const + let { groupIndex, bindingIndex } = uniformBufferInfo.binding; + if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) { + this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = []; + this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = []; + } + if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) { + const len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({ + binding: bindingIndex, + visibility: 0, + buffer: { + type: bufferType, + }, + }); + this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1 }; + } + bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index; + if (isVertex) { + this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 1 /* WebGPUConstants.ShaderStage.Vertex */; + } + else { + this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 2 /* WebGPUConstants.ShaderStage.Fragment */; + } + } +} +WebGPUShaderProcessor.LeftOvertUBOName = "LeftOver"; +WebGPUShaderProcessor.InternalsUBOName = "Internals"; +WebGPUShaderProcessor.UniformSizes = { + // GLSL types + bool: 1, + int: 1, + float: 1, + vec2: 2, + ivec2: 2, + uvec2: 2, + vec3: 3, + ivec3: 3, + uvec3: 3, + vec4: 4, + ivec4: 4, + uvec4: 4, + mat2: 4, + mat3: 12, + mat4: 16, + // WGSL types + i32: 1, + u32: 1, + f32: 1, + mat2x2: 4, + mat3x3: 12, + mat4x4: 16, + mat2x2f: 4, + mat3x3f: 12, + mat4x4f: 16, + vec2i: 2, + vec3i: 3, + vec4i: 4, + vec2u: 2, + vec3u: 3, + vec4u: 4, + vec2f: 2, + vec3f: 3, + vec4f: 4, + vec2h: 1, + vec3h: 2, + vec4h: 2, +}; +// eslint-disable-next-line @typescript-eslint/naming-convention +WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType = { + sampler2D: "sampler2D", + sampler2DArray: "sampler2DArray", + sampler2DShadow: "sampler2DShadow", + sampler2DArrayShadow: "sampler2DArrayShadow", + samplerCube: "samplerCube", + sampler3D: "sampler3D", +}; +// eslint-disable-next-line @typescript-eslint/naming-convention +WebGPUShaderProcessor._TextureTypeByWebGLSamplerType = { + sampler2D: "texture2D", + sampler2DArray: "texture2DArray", + sampler2DShadow: "texture2D", + sampler2DArrayShadow: "texture2DArray", + samplerCube: "textureCube", + samplerCubeArray: "textureCubeArray", + sampler3D: "texture3D", +}; +// eslint-disable-next-line @typescript-eslint/naming-convention +WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType = { + textureCube: "cube" /* WebGPUConstants.TextureViewDimension.Cube */, + textureCubeArray: "cube-array" /* WebGPUConstants.TextureViewDimension.CubeArray */, + texture2D: "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + texture2DArray: "2d-array" /* WebGPUConstants.TextureViewDimension.E2dArray */, + texture3D: "3d" /* WebGPUConstants.TextureViewDimension.E3d */, +}; +// if the webgl sampler type is not listed in this array, "sampler" is taken by default +// eslint-disable-next-line @typescript-eslint/naming-convention +WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType = { + sampler2DShadow: "samplerShadow", + sampler2DArrayShadow: "samplerShadow", +}; +// eslint-disable-next-line @typescript-eslint/naming-convention +WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType = { + samplerShadow: true, + samplerArrayShadow: true, + sampler: false, +}; + +/** @internal */ +class WebGPUPipelineContext { + get isAsync() { + return false; + } + get isReady() { + if (this.stages) { + return true; + } + return false; + } + constructor(shaderProcessingContext, engine) { + // The field is indexed by textureState. See @WebGPUMaterialContext.textureState for more information. + this.bindGroupLayouts = {}; + this._name = "unnamed"; + this.shaderProcessingContext = shaderProcessingContext; + this._leftOverUniformsByName = {}; + this.engine = engine; + this.vertexBufferKindToType = {}; + } + _handlesSpectorRebuildCallback() { + // Nothing to do yet for spector. + } + _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) { + const engine = this.engine; + if (engine._doNotHandleContextLost) { + effect._fragmentSourceCode = ""; + effect._vertexSourceCode = ""; + } + const foundSamplers = this.shaderProcessingContext.availableTextures; + let index; + for (index = 0; index < samplerList.length; index++) { + const name = samplerList[index]; + const sampler = foundSamplers[samplerList[index]]; + if (sampler == null || sampler == undefined) { + samplerList.splice(index, 1); + index--; + } + else { + samplers[name] = index; + } + } + for (const attr of engine.getAttributes(this, attributesNames)) { + attributes.push(attr); + } + // Build the uniform layout for the left over uniforms. + this.buildUniformLayout(); + const attributeNamesFromEffect = []; + const attributeLocationsFromEffect = []; + for (index = 0; index < attributesNames.length; index++) { + const location = attributes[index]; + if (location >= 0) { + attributeNamesFromEffect.push(attributesNames[index]); + attributeLocationsFromEffect.push(location); + } + } + this.shaderProcessingContext.attributeNamesFromEffect = attributeNamesFromEffect; + this.shaderProcessingContext.attributeLocationsFromEffect = attributeLocationsFromEffect; + } + /** @internal */ + /** + * Build the uniform buffer used in the material. + */ + buildUniformLayout() { + if (!this.shaderProcessingContext.leftOverUniforms.length) { + return; + } + this.uniformBuffer?.dispose(); + this.uniformBuffer = new UniformBuffer(this.engine, undefined, undefined, "leftOver-" + this._name); + for (const leftOverUniform of this.shaderProcessingContext.leftOverUniforms) { + const type = leftOverUniform.type.replace(/^(.*?)(<.*>)?$/, "$1"); + const size = WebGPUShaderProcessor.UniformSizes[type]; + this.uniformBuffer.addUniform(leftOverUniform.name, size, leftOverUniform.length); + this._leftOverUniformsByName[leftOverUniform.name] = leftOverUniform.type; + } + this.uniformBuffer.create(); + } + setEngine(engine) { + this.engine = engine; + } + /** + * Release all associated resources. + **/ + dispose() { + if (this.uniformBuffer) { + this.uniformBuffer.dispose(); + } + } + /** + * Sets an integer value on a uniform variable. + * @param uniformName Name of the variable. + * @param value Value to be set. + */ + setInt(uniformName, value) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateInt(uniformName, value); + } + /** + * Sets an int2 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int2. + * @param y Second int in int2. + */ + setInt2(uniformName, x, y) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateInt2(uniformName, x, y); + } + /** + * Sets an int3 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int3. + * @param y Second int in int3. + * @param z Third int in int3. + */ + setInt3(uniformName, x, y, z) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateInt3(uniformName, x, y, z); + } + /** + * Sets an int4 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First int in int4. + * @param y Second int in int4. + * @param z Third int in int4. + * @param w Fourth int in int4. + */ + setInt4(uniformName, x, y, z, w) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateInt4(uniformName, x, y, z, w); + } + /** + * Sets an int array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray(uniformName, array) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateIntArray(uniformName, array); + } + /** + * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray2(uniformName, array) { + this.setIntArray(uniformName, array); + } + /** + * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray3(uniformName, array) { + this.setIntArray(uniformName, array); + } + /** + * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setIntArray4(uniformName, array) { + this.setIntArray(uniformName, array); + } + /** + * Sets an unsigned integer value on a uniform variable. + * @param uniformName Name of the variable. + * @param value Value to be set. + */ + setUInt(uniformName, value) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateUInt(uniformName, value); + } + /** + * Sets an unsigned int2 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint2. + * @param y Second unsigned int in uint2. + */ + setUInt2(uniformName, x, y) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateUInt2(uniformName, x, y); + } + /** + * Sets an unsigned int3 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint3. + * @param y Second unsigned int in uint3. + * @param z Third unsigned int in uint3. + */ + setUInt3(uniformName, x, y, z) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateUInt3(uniformName, x, y, z); + } + /** + * Sets an unsigned int4 value on a uniform variable. + * @param uniformName Name of the variable. + * @param x First unsigned int in uint4. + * @param y Second unsigned int in uint4. + * @param z Third unsigned int in uint4. + * @param w Fourth unsigned int in uint4. + */ + setUInt4(uniformName, x, y, z, w) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateUInt4(uniformName, x, y, z, w); + } + /** + * Sets an unsigned int array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray(uniformName, array) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateUIntArray(uniformName, array); + } + /** + * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray2(uniformName, array) { + this.setUIntArray(uniformName, array); + } + /** + * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray3(uniformName, array) { + this.setUIntArray(uniformName, array); + } + /** + * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setUIntArray4(uniformName, array) { + this.setUIntArray(uniformName, array); + } + /** + * Sets an array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray(uniformName, array) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateArray(uniformName, array); + } + /** + * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray2(uniformName, array) { + this.setArray(uniformName, array); + } + /** + * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray3(uniformName, array) { + this.setArray(uniformName, array); + } + /** + * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + */ + setArray4(uniformName, array) { + this.setArray(uniformName, array); + } + /** + * Sets matrices on a uniform variable. + * @param uniformName Name of the variable. + * @param matrices matrices to be set. + */ + setMatrices(uniformName, matrices) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateMatrices(uniformName, matrices); + } + /** + * Sets matrix on a uniform variable. + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + */ + setMatrix(uniformName, matrix) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateMatrix(uniformName, matrix); + } + /** + * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix) + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + */ + setMatrix3x3(uniformName, matrix) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateMatrix3x3(uniformName, matrix); + } + /** + * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix) + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + */ + setMatrix2x2(uniformName, matrix) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateMatrix2x2(uniformName, matrix); + } + /** + * Sets a float on a uniform variable. + * @param uniformName Name of the variable. + * @param value value to be set. + */ + setFloat(uniformName, value) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateFloat(uniformName, value); + } + /** + * Sets a Vector2 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector2 vector2 to be set. + */ + setVector2(uniformName, vector2) { + this.setFloat2(uniformName, vector2.x, vector2.y); + } + /** + * Sets a float2 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float2. + * @param y Second float in float2. + */ + setFloat2(uniformName, x, y) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateFloat2(uniformName, x, y); + } + /** + * Sets a Vector3 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector3 Value to be set. + */ + setVector3(uniformName, vector3) { + this.setFloat3(uniformName, vector3.x, vector3.y, vector3.z); + } + /** + * Sets a float3 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float3. + * @param y Second float in float3. + * @param z Third float in float3. + */ + setFloat3(uniformName, x, y, z) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateFloat3(uniformName, x, y, z); + } + /** + * Sets a Vector4 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector4 Value to be set. + */ + setVector4(uniformName, vector4) { + this.setFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w); + } + /** + * Sets a Quaternion on a uniform variable. + * @param uniformName Name of the variable. + * @param quaternion Value to be set. + */ + setQuaternion(uniformName, quaternion) { + this.setFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w); + } + /** + * Sets a float4 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float4. + * @param y Second float in float4. + * @param z Third float in float4. + * @param w Fourth float in float4. + */ + setFloat4(uniformName, x, y, z, w) { + if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { + return; + } + this.uniformBuffer.updateFloat4(uniformName, x, y, z, w); + } + /** + * Sets a Color3 on a uniform variable. + * @param uniformName Name of the variable. + * @param color3 Value to be set. + */ + setColor3(uniformName, color3) { + this.setFloat3(uniformName, color3.r, color3.g, color3.b); + } + /** + * Sets a Color4 on a uniform variable. + * @param uniformName Name of the variable. + * @param color3 Value to be set. + * @param alpha Alpha value to be set. + */ + setColor4(uniformName, color3, alpha) { + this.setFloat4(uniformName, color3.r, color3.g, color3.b, alpha); + } + /** + * Sets a Color4 on a uniform variable + * @param uniformName defines the name of the variable + * @param color4 defines the value to be set + */ + setDirectColor4(uniformName, color4) { + this.setFloat4(uniformName, color4.r, color4.g, color4.b, color4.a); + } + _getVertexShaderCode() { + return this.sources?.vertex; + } + _getFragmentShaderCode() { + return this.sources?.fragment; + } +} + +const _maxGroups = 4; +const _maxBindingsPerGroup = 1 << 16; +// all types not listed are assumed to consume 1 location +const _typeToLocationSize = { + // GLSL types + mat2: 2, + mat3: 3, + mat4: 4, + // WGSL types + mat2x2: 2, + mat3x3: 3, + mat4x4: 4, +}; +/** + * @internal + */ +class WebGPUShaderProcessingContext { + static get KnownUBOs() { + return WebGPUShaderProcessingContext._SimplifiedKnownBindings ? WebGPUShaderProcessingContext._SimplifiedKnownUBOs : WebGPUShaderProcessingContext._KnownUBOs; + } + constructor(shaderLanguage, pureMode = false) { + this.vertexBufferKindToNumberOfComponents = {}; + this.shaderLanguage = shaderLanguage; + this._attributeNextLocation = 0; + this._varyingNextLocation = 0; + this.freeGroupIndex = 0; + this.freeBindingIndex = 0; + this.availableVaryings = {}; + this.availableAttributes = {}; + this.availableBuffers = {}; + this.availableTextures = {}; + this.availableSamplers = {}; + this.orderedAttributes = []; + this.bindGroupLayoutEntries = []; + this.bindGroupLayoutEntryInfo = []; + this.bindGroupEntries = []; + this.bufferNames = []; + this.textureNames = []; + this.samplerNames = []; + this.leftOverUniforms = []; + if (!pureMode) { + this._findStartingGroupBinding(); + } + } + _findStartingGroupBinding() { + const knownUBOs = WebGPUShaderProcessingContext.KnownUBOs; + const groups = []; + for (const name in knownUBOs) { + const binding = knownUBOs[name].binding; + if (binding.groupIndex === -1) { + continue; + } + if (groups[binding.groupIndex] === undefined) { + groups[binding.groupIndex] = binding.bindingIndex; + } + else { + groups[binding.groupIndex] = Math.max(groups[binding.groupIndex], binding.bindingIndex); + } + } + this.freeGroupIndex = groups.length - 1; + if (this.freeGroupIndex === 0) { + this.freeGroupIndex++; + this.freeBindingIndex = 0; + } + else { + this.freeBindingIndex = groups[groups.length - 1] + 1; + } + } + getAttributeNextLocation(dataType, arrayLength = 0) { + const index = this._attributeNextLocation; + this._attributeNextLocation += (_typeToLocationSize[dataType] ?? 1) * (arrayLength || 1); + return index; + } + getVaryingNextLocation(dataType, arrayLength = 0) { + const index = this._varyingNextLocation; + this._varyingNextLocation += (_typeToLocationSize[dataType] ?? 1) * (arrayLength || 1); + return index; + } + getNextFreeUBOBinding() { + return this._getNextFreeBinding(1); + } + _getNextFreeBinding(bindingCount) { + if (this.freeBindingIndex > _maxBindingsPerGroup - bindingCount) { + this.freeGroupIndex++; + this.freeBindingIndex = 0; + } + if (this.freeGroupIndex === _maxGroups) { + // eslint-disable-next-line no-throw-literal + throw "Too many textures or UBOs have been declared and it is not supported in WebGPU."; + } + const returnValue = { + groupIndex: this.freeGroupIndex, + bindingIndex: this.freeBindingIndex, + }; + this.freeBindingIndex += bindingCount; + return returnValue; + } +} +/** @internal */ +WebGPUShaderProcessingContext._SimplifiedKnownBindings = true; // if true, use only group=0,binding=0 as a known group/binding for the Scene ubo and use group=1,binding=X for all other bindings +// if false, see _KnownUBOs for the known groups/bindings used +WebGPUShaderProcessingContext._SimplifiedKnownUBOs = { + Scene: { binding: { groupIndex: 0, bindingIndex: 0 } }, + Light0: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light1: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light2: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light3: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light4: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light5: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light6: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light7: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light8: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light9: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light10: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light11: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light12: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light13: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light14: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light15: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light16: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light17: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light18: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light19: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light20: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light21: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light22: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light23: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light24: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light25: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light26: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light27: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light28: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light29: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light30: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Light31: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Material: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Mesh: { binding: { groupIndex: -1, bindingIndex: -1 } }, + Internals: { binding: { groupIndex: -1, bindingIndex: -1 } }, +}; +WebGPUShaderProcessingContext._KnownUBOs = { + Scene: { binding: { groupIndex: 0, bindingIndex: 0 } }, + Light0: { binding: { groupIndex: 1, bindingIndex: 0 } }, + Light1: { binding: { groupIndex: 1, bindingIndex: 1 } }, + Light2: { binding: { groupIndex: 1, bindingIndex: 2 } }, + Light3: { binding: { groupIndex: 1, bindingIndex: 3 } }, + Light4: { binding: { groupIndex: 1, bindingIndex: 4 } }, + Light5: { binding: { groupIndex: 1, bindingIndex: 5 } }, + Light6: { binding: { groupIndex: 1, bindingIndex: 6 } }, + Light7: { binding: { groupIndex: 1, bindingIndex: 7 } }, + Light8: { binding: { groupIndex: 1, bindingIndex: 8 } }, + Light9: { binding: { groupIndex: 1, bindingIndex: 9 } }, + Light10: { binding: { groupIndex: 1, bindingIndex: 10 } }, + Light11: { binding: { groupIndex: 1, bindingIndex: 11 } }, + Light12: { binding: { groupIndex: 1, bindingIndex: 12 } }, + Light13: { binding: { groupIndex: 1, bindingIndex: 13 } }, + Light14: { binding: { groupIndex: 1, bindingIndex: 14 } }, + Light15: { binding: { groupIndex: 1, bindingIndex: 15 } }, + Light16: { binding: { groupIndex: 1, bindingIndex: 16 } }, + Light17: { binding: { groupIndex: 1, bindingIndex: 17 } }, + Light18: { binding: { groupIndex: 1, bindingIndex: 18 } }, + Light19: { binding: { groupIndex: 1, bindingIndex: 19 } }, + Light20: { binding: { groupIndex: 1, bindingIndex: 20 } }, + Light21: { binding: { groupIndex: 1, bindingIndex: 21 } }, + Light22: { binding: { groupIndex: 1, bindingIndex: 22 } }, + Light23: { binding: { groupIndex: 1, bindingIndex: 23 } }, + Light24: { binding: { groupIndex: 1, bindingIndex: 24 } }, + Light25: { binding: { groupIndex: 1, bindingIndex: 25 } }, + Light26: { binding: { groupIndex: 1, bindingIndex: 26 } }, + Light27: { binding: { groupIndex: 1, bindingIndex: 27 } }, + Light28: { binding: { groupIndex: 1, bindingIndex: 28 } }, + Light29: { binding: { groupIndex: 1, bindingIndex: 29 } }, + Light30: { binding: { groupIndex: 1, bindingIndex: 30 } }, + Light31: { binding: { groupIndex: 1, bindingIndex: 31 } }, + Material: { binding: { groupIndex: 2, bindingIndex: 0 } }, + Mesh: { binding: { groupIndex: 2, bindingIndex: 1 } }, + Internals: { binding: { groupIndex: 2, bindingIndex: 2 } }, +}; + +/** @internal */ +class WebGPUShaderProcessorGLSL extends WebGPUShaderProcessor { + constructor() { + super(...arguments); + this._missingVaryings = []; + this._textureArrayProcessing = []; + this._vertexIsGLES3 = false; + this._fragmentIsGLES3 = false; + this.shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this.parseGLES3 = true; + } + _getArraySize(name, type, preProcessors) { + let length = 0; + const startArray = name.indexOf("["); + const endArray = name.indexOf("]"); + if (startArray > 0 && endArray > 0) { + const lengthInString = name.substring(startArray + 1, endArray); + length = +lengthInString; + if (isNaN(length)) { + length = +preProcessors[lengthInString.trim()]; + } + name = name.substring(0, startArray); + } + return [name, type, length]; + } + initializeShaders(processingContext) { + this._webgpuProcessingContext = processingContext; + this._missingVaryings.length = 0; + this._textureArrayProcessing.length = 0; + this.attributeKeywordName = undefined; + this.varyingVertexKeywordName = undefined; + this.varyingFragmentKeywordName = undefined; + } + preProcessShaderCode(code, isFragment) { + const ubDeclaration = `// Internals UBO\nuniform ${WebGPUShaderProcessor.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`; + const alreadyInjected = code.indexOf("// Internals UBO") !== -1; + if (isFragment) { + this._fragmentIsGLES3 = code.indexOf("#version 3") !== -1; + if (this._fragmentIsGLES3) { + this.varyingFragmentKeywordName = "in"; + } + return alreadyInjected ? code : ubDeclaration + "##INJECTCODE##\n" + code; + } + this._vertexIsGLES3 = code.indexOf("#version 3") !== -1; + if (this._vertexIsGLES3) { + this.attributeKeywordName = "in"; + this.varyingVertexKeywordName = "out"; + } + return alreadyInjected ? code : ubDeclaration + code; + } + varyingCheck(varying, isFragment) { + const outRegex = /(flat\s)?\s*\bout\b/; + const inRegex = /(flat\s)?\s*\bin\b/; + const varyingRegex = /(flat\s)?\s*\bvarying\b/; + const regex = isFragment && this._fragmentIsGLES3 ? inRegex : !isFragment && this._vertexIsGLES3 ? outRegex : varyingRegex; + return regex.test(varying); + } + varyingProcessor(varying, isFragment, preProcessors) { + this._preProcessors = preProcessors; + const outRegex = /\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm; + const inRegex = /\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm; + const varyingRegex = /\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm; + const regex = isFragment && this._fragmentIsGLES3 ? inRegex : !isFragment && this._vertexIsGLES3 ? outRegex : varyingRegex; + const match = regex.exec(varying); + if (match !== null) { + const interpolationQualifier = match[1] ?? ""; + const varyingType = match[2]; + const name = match[3]; + let location; + if (isFragment) { + location = this._webgpuProcessingContext.availableVaryings[name]; + this._missingVaryings[location] = ""; + if (location === undefined) { + Logger.Warn(`Invalid fragment shader: The varying named "${name}" is not declared in the vertex shader! This declaration will be ignored.`); + } + } + else { + location = this._webgpuProcessingContext.getVaryingNextLocation(varyingType, this._getArraySize(name, varyingType, preProcessors)[2]); + this._webgpuProcessingContext.availableVaryings[name] = location; + this._missingVaryings[location] = `layout(location = ${location}) ${interpolationQualifier} in ${varyingType} ${name};`; + } + varying = varying.replace(match[0], location === undefined ? "" : `layout(location = ${location}) ${interpolationQualifier} ${isFragment ? "in" : "out"} ${varyingType} ${name};`); + } + return varying; + } + attributeProcessor(attribute, preProcessors) { + this._preProcessors = preProcessors; + const inRegex = /\s*in\s+(\S+)\s+(\S+)\s*;/gm; + const attribRegex = /\s*attribute\s+(\S+)\s+(\S+)\s*;/gm; + const regex = this._vertexIsGLES3 ? inRegex : attribRegex; + const match = regex.exec(attribute); + if (match !== null) { + const attributeType = match[1]; + const name = match[2]; + const location = this._webgpuProcessingContext.getAttributeNextLocation(attributeType, this._getArraySize(name, attributeType, preProcessors)[2]); + this._webgpuProcessingContext.availableAttributes[name] = location; + this._webgpuProcessingContext.orderedAttributes[location] = name; + const numComponents = this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[name]; + if (numComponents !== undefined) { + // Special case for an int/ivecX vertex buffer that is used as a float/vecX attribute in the shader. + const newType = numComponents < 0 ? (numComponents === -1 ? "int" : "ivec" + -numComponents) : numComponents === 1 ? "uint" : "uvec" + numComponents; + const newName = `_int_${name}_`; + attribute = attribute.replace(match[0], `layout(location = ${location}) in ${newType} ${newName}; ${attributeType} ${name} = ${attributeType}(${newName});`); + } + else { + attribute = attribute.replace(match[0], `layout(location = ${location}) in ${attributeType} ${name};`); + } + } + return attribute; + } + uniformProcessor(uniform, isFragment, preProcessors) { + this._preProcessors = preProcessors; + const uniformRegex = /\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm; + const match = uniformRegex.exec(uniform); + if (match !== null) { + let uniformType = match[1]; + let name = match[2]; + if (uniformType.indexOf("sampler") === 0 || uniformType.indexOf("sampler") === 1) { + let arraySize = 0; // 0 means the texture is not declared as an array + [name, uniformType, arraySize] = this._getArraySize(name, uniformType, preProcessors); + let textureInfo = this._webgpuProcessingContext.availableTextures[name]; + if (!textureInfo) { + textureInfo = { + autoBindSampler: true, + isTextureArray: arraySize > 0, + isStorageTexture: false, + textures: [], + sampleType: "float" /* WebGPUConstants.TextureSampleType.Float */, + }; + for (let i = 0; i < (arraySize || 1); ++i) { + textureInfo.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding()); + } + } + const samplerType = WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[uniformType] ?? "sampler"; + const isComparisonSampler = !!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[samplerType]; + const samplerBindingType = isComparisonSampler ? "comparison" /* WebGPUConstants.SamplerBindingType.Comparison */ : "filtering" /* WebGPUConstants.SamplerBindingType.Filtering */; + const samplerName = name + `Sampler`; + let samplerInfo = this._webgpuProcessingContext.availableSamplers[samplerName]; + if (!samplerInfo) { + samplerInfo = { + binding: this._webgpuProcessingContext.getNextFreeUBOBinding(), + type: samplerBindingType, + }; + } + const componentType = uniformType.charAt(0) === "u" ? "u" : uniformType.charAt(0) === "i" ? "i" : ""; + if (componentType) { + uniformType = uniformType.substring(1); + } + const sampleType = isComparisonSampler + ? "depth" /* WebGPUConstants.TextureSampleType.Depth */ + : componentType === "u" + ? "uint" /* WebGPUConstants.TextureSampleType.Uint */ + : componentType === "i" + ? "sint" /* WebGPUConstants.TextureSampleType.Sint */ + : "float" /* WebGPUConstants.TextureSampleType.Float */; + textureInfo.sampleType = sampleType; + const isTextureArray = arraySize > 0; + const samplerGroupIndex = samplerInfo.binding.groupIndex; + const samplerBindingIndex = samplerInfo.binding.bindingIndex; + const samplerFunction = WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[uniformType]; + const textureType = WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[uniformType]; + const textureDimension = WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[textureType]; + // Manage textures and samplers. + if (!isTextureArray) { + arraySize = 1; + uniform = `layout(set = ${samplerGroupIndex}, binding = ${samplerBindingIndex}) uniform ${samplerType} ${samplerName}; + layout(set = ${textureInfo.textures[0].groupIndex}, binding = ${textureInfo.textures[0].bindingIndex}) uniform ${componentType}${textureType} ${name}Texture; + #define ${name} ${componentType}${samplerFunction}(${name}Texture, ${samplerName})`; + } + else { + const layouts = []; + layouts.push(`layout(set = ${samplerGroupIndex}, binding = ${samplerBindingIndex}) uniform ${componentType}${samplerType} ${samplerName};`); + uniform = `\n`; + for (let i = 0; i < arraySize; ++i) { + const textureSetIndex = textureInfo.textures[i].groupIndex; + const textureBindingIndex = textureInfo.textures[i].bindingIndex; + layouts.push(`layout(set = ${textureSetIndex}, binding = ${textureBindingIndex}) uniform ${textureType} ${name}Texture${i};`); + uniform += `${i > 0 ? "\n" : ""}#define ${name}${i} ${componentType}${samplerFunction}(${name}Texture${i}, ${samplerName})`; + } + uniform = layouts.join("\n") + uniform; + this._textureArrayProcessing.push(name); + } + this._webgpuProcessingContext.availableTextures[name] = textureInfo; + this._webgpuProcessingContext.availableSamplers[samplerName] = samplerInfo; + this._addSamplerBindingDescription(samplerName, samplerInfo, !isFragment); + for (let i = 0; i < arraySize; ++i) { + this._addTextureBindingDescription(name, textureInfo, i, textureDimension, null, !isFragment); + } + } + else { + this._addUniformToLeftOverUBO(name, uniformType, preProcessors); + uniform = ""; + } + } + return uniform; + } + uniformBufferProcessor(uniformBuffer, isFragment) { + const uboRegex = /uniform\s+(\w+)/gm; + const match = uboRegex.exec(uniformBuffer); + if (match !== null) { + const name = match[1]; + let uniformBufferInfo = this._webgpuProcessingContext.availableBuffers[name]; + if (!uniformBufferInfo) { + const knownUBO = WebGPUShaderProcessingContext.KnownUBOs[name]; + let binding; + if (knownUBO && knownUBO.binding.groupIndex !== -1) { + binding = knownUBO.binding; + } + else { + binding = this._webgpuProcessingContext.getNextFreeUBOBinding(); + } + uniformBufferInfo = { binding }; + this._webgpuProcessingContext.availableBuffers[name] = uniformBufferInfo; + } + this._addBufferBindingDescription(name, uniformBufferInfo, "uniform" /* WebGPUConstants.BufferBindingType.Uniform */, !isFragment); + uniformBuffer = uniformBuffer.replace("uniform", `layout(set = ${uniformBufferInfo.binding.groupIndex}, binding = ${uniformBufferInfo.binding.bindingIndex}) uniform`); + } + return uniformBuffer; + } + postProcessor(code, defines, isFragment, _processingContext, _parameters) { + const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1; + // Remove extensions + const regex = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g; + code = code.replace(regex, ""); + // Replace instructions + code = code.replace(/texture2D\s*\(/g, "texture("); + if (isFragment) { + const hasFragCoord = code.indexOf("gl_FragCoord") >= 0; + const fragCoordCode = ` + glFragCoord_ = gl_FragCoord; + if (yFactor_ == 1.) { + glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; + } + `; + const injectCode = hasFragCoord ? "vec4 glFragCoord_;\n" : ""; + const hasOutput = code.search(/layout *\(location *= *0\) *out/g) !== -1; + code = code.replace(/texture2DLodEXT\s*\(/g, "textureLod("); + code = code.replace(/textureCubeLodEXT\s*\(/g, "textureLod("); + code = code.replace(/textureCube\s*\(/g, "texture("); + code = code.replace(/gl_FragDepthEXT/g, "gl_FragDepth"); + code = code.replace(/gl_FragColor/g, "glFragColor"); + code = code.replace(/gl_FragData/g, "glFragData"); + code = code.replace(/gl_FragCoord/g, "glFragCoord_"); + if (!this._fragmentIsGLES3) { + code = code.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension || hasOutput ? "" : "layout(location = 0) out vec4 glFragColor;\n") + "void main("); + } + else { + const match = /^\s*out\s+\S+\s+\S+\s*;/gm.exec(code); + if (match !== null) { + code = code.substring(0, match.index) + "layout(location = 0) " + code.substring(match.index); + } + } + code = code.replace(/dFdy/g, "(-yFactor_)*dFdy"); // will also handle dFdyCoarse and dFdyFine + code = code.replace("##INJECTCODE##", injectCode); + if (hasFragCoord) { + code = InjectStartingAndEndingCode(code, "void main", fragCoordCode); + } + } + else { + code = code.replace(/gl_InstanceID/g, "gl_InstanceIndex"); + code = code.replace(/gl_VertexID/g, "gl_VertexIndex"); + const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1; + if (hasMultiviewExtension) { + return "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n" + code; + } + } + // Flip Y + convert z range from [-1,1] to [0,1] + if (!isFragment) { + const lastClosingCurly = code.lastIndexOf("}"); + code = code.substring(0, lastClosingCurly); + code += "gl_Position.y *= yFactor_;\n"; + // isNDCHalfZRange is always true in WebGPU + code += "}"; + } + return code; + } + _applyTextureArrayProcessing(code, name) { + // Replaces the occurrences of name[XX] by nameXX + const regex = new RegExp(name + "\\s*\\[(.+)?\\]", "gm"); + let match = regex.exec(code); + while (match !== null) { + const index = match[1]; + let iindex = +index; + if (this._preProcessors && isNaN(iindex)) { + iindex = +this._preProcessors[index.trim()]; + } + code = code.replace(match[0], name + iindex); + match = regex.exec(code); + } + return code; + } + _generateLeftOverUBOCode(name, uniformBufferDescription) { + let ubo = `layout(set = ${uniformBufferDescription.binding.groupIndex}, binding = ${uniformBufferDescription.binding.bindingIndex}) uniform ${name} {\n `; + for (const leftOverUniform of this._webgpuProcessingContext.leftOverUniforms) { + if (leftOverUniform.length > 0) { + ubo += ` ${leftOverUniform.type} ${leftOverUniform.name}[${leftOverUniform.length}];\n`; + } + else { + ubo += ` ${leftOverUniform.type} ${leftOverUniform.name};\n`; + } + } + ubo += "};\n\n"; + return ubo; + } + finalizeShaders(vertexCode, fragmentCode) { + // make replacements for texture names in the texture array case + for (let i = 0; i < this._textureArrayProcessing.length; ++i) { + const name = this._textureArrayProcessing[i]; + vertexCode = this._applyTextureArrayProcessing(vertexCode, name); + fragmentCode = this._applyTextureArrayProcessing(fragmentCode, name); + } + // inject the missing varying in the fragment shader + for (let i = 0; i < this._missingVaryings.length; ++i) { + const decl = this._missingVaryings[i]; + if (decl && decl.length > 0) { + fragmentCode = decl + "\n" + fragmentCode; + } + } + // Builds the leftover UBOs. + const leftOverUBO = this._buildLeftOverUBO(); + vertexCode = leftOverUBO + vertexCode; + fragmentCode = leftOverUBO + fragmentCode; + this._collectBindingNames(); + this._preCreateBindGroupEntries(); + this._preProcessors = null; + this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents = {}; + return { vertexCode, fragmentCode }; + } +} + +// Do not edit. +const name$7F = "helperFunctions"; +const shader$7E = `const PI: f32=3.1415926535897932384626433832795;const TWO_PI: f32=6.283185307179586;const HALF_PI: f32=1.5707963267948966;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const RECIPROCAL_PI4: f32=0.07957747154594767;const HALF_MIN: f32=5.96046448e-08; +const LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3f=vec3f(0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;fn square(x: f32)->f32 {return x*x;} +fn saturate(x: f32)->f32 {return clamp(x,0.0,1.0);} +fn saturateVec3(x: vec3f)->vec3f {return clamp(x,vec3f(),vec3f(1.0));} +fn saturateEps(x: f32)->f32 {return clamp(x,Epsilon,1.0);} +fn maxEps(x: f32)->f32 {return max(x,Epsilon);} +fn maxEpsVec3(x: vec3f)->vec3f {return max(x,vec3f(Epsilon));} +fn absEps(x: f32)->f32 {return abs(x)+Epsilon;} +fn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3f=inMatrix[0];let i1: vec3f=inMatrix[1];let i2: vec3f=inMatrix[2];let outMatrix:mat3x3f=mat3x3f( +vec3(i0.x,i1.x,i2.x), +vec3(i0.y,i1.y,i2.y), +vec3(i0.z,i1.z,i2.z) +);return outMatrix;} +fn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det, +b11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det, +b21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);} +#if USE_EXACT_SRGB_CONVERSIONS +fn toLinearSpaceExact(color: vec3f)->vec3f +{let nearZeroSection: vec3f=0.0773993808*color;let remainingSection: vec3f=pow(0.947867299*(color+vec3f(0.055)),vec3f(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3f(0.04045)));} +fn toGammaSpaceExact(color: vec3f)->vec3f +{let nearZeroSection: vec3f=12.92*color;let remainingSection: vec3f=1.055*pow(color,vec3f(0.41666))-vec3f(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3f(0.0031308)));} +#endif +fn toLinearSpace(color: f32)->f32 +{ +#if USE_EXACT_SRGB_CONVERSIONS +var nearZeroSection=0.0773993808*color;var remainingSection=pow(0.947867299*(color+0.055),2.4);return select(remainingSection,nearZeroSection,color<=0.04045); +#else +return pow(color,LinearEncodePowerApprox); +#endif +} +fn toLinearSpaceVec3(color: vec3f)->vec3f +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toLinearSpaceExact(color); +#else +return pow(color,vec3f(LinearEncodePowerApprox)); +#endif +} +fn toLinearSpaceVec4(color: vec4)->vec4 +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4f(toLinearSpaceExact(color.rgb),color.a); +#else +return vec4f(pow(color.rgb,vec3f(LinearEncodePowerApprox)),color.a); +#endif +} +fn toGammaSpace(color: vec4)->vec4 +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toGammaSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3f(GammaEncodePowerApprox)),color.a); +#endif +} +fn toGammaSpaceVec3(color: vec3f)->vec3f +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toGammaSpaceExact(color); +#else +return pow(color,vec3f(GammaEncodePowerApprox)); +#endif +} +fn squareVec3(value: vec3f)->vec3f +{return value*value;} +fn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;} +fn getLuminance(color: vec3f)->f32 +{return saturate(dot(color,LuminanceEncodeApprox));} +fn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} +fn dither(seed: vec2,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;} +const rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3f)->vec4 {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3f =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4(saturateVec3(rgb),D);} +fn fromRGBD(rgbd: vec4)->vec3f {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;} +fn parallaxCorrectNormal(vertexPos: vec3f,origVec: vec3f,cubeSize: vec3f,cubePos: vec3f)->vec3f {let invOrigVec: vec3f=vec3f(1.)/origVec;let halfSize: vec3f=cubeSize*0.5;let intersecAtMaxPlane: vec3f=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3f=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3f=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3f=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} +fn equirectangularToCubemapDirection(uv : vec2f)->vec3f {var longitude : f32=uv.x*TWO_PI-PI;var latitude : f32=HALF_PI-uv.y*PI;var direction : vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;} +fn sqrtClamped(value: f32)->f32 {return sqrt(max(value,0.));} +fn avg(value: vec3f)->f32 {return dot(value,vec3f(0.333333333));} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7F]) { + ShaderStore.IncludesShadersStoreWGSL[name$7F] = shader$7E; +} +/** @internal */ +const helperFunctionsWGSL = { name: name$7F, shader: shader$7E }; + +const helperFunctions$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + helperFunctionsWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7E = "fresnelFunction"; +const shader$7D = `#ifdef FRESNEL +fn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32 +{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7E]) { + ShaderStore.IncludesShadersStoreWGSL[name$7E] = shader$7D; +} + +// Do not edit. +const name$7D = "meshUboDeclaration"; +const shader$7C = `struct Mesh {world : mat4x4, +visibility : f32,};var mesh : Mesh; +#define WORLD_UBO +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7D]) { + ShaderStore.IncludesShadersStoreWGSL[name$7D] = shader$7C; +} + +// Do not edit. +const name$7C = "sceneUboDeclaration"; +const shader$7B = `struct Scene {viewProjection : mat4x4, +#ifdef MULTIVIEW +viewProjectionR : mat4x4, +#endif +view : mat4x4, +projection : mat4x4, +vEyePosition : vec4,}; +#define SCENE_UBO +var scene : Scene; +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7C]) { + ShaderStore.IncludesShadersStoreWGSL[name$7C] = shader$7B; +} + +// Do not edit. +const name$7B = "decalFragment"; +const shader$7A = `#ifdef DECAL +var decalTempColor=decalColor.rgb;var decalTempAlpha=decalColor.a; +#ifdef GAMMADECAL +decalTempColor=toLinearSpaceVec3(decalColor.rgb); +#endif +#ifdef DECAL_SMOOTHALPHA +decalTempAlpha=decalColor.a*decalColor.a; +#endif +surfaceAlbedo=mix(surfaceAlbedo.rgb,decalTempColor,decalTempAlpha); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7B]) { + ShaderStore.IncludesShadersStoreWGSL[name$7B] = shader$7A; +} + +const builtInName_frag_depth = "fragmentOutputs.fragDepth"; +const leftOverVarName = "uniforms"; +const internalsVarName = "internals"; +const gpuTextureViewDimensionByWebGPUTextureFunction = { + texture_1d: "1d" /* WebGPUConstants.TextureViewDimension.E1d */, + texture_2d: "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + texture_2d_array: "2d-array" /* WebGPUConstants.TextureViewDimension.E2dArray */, + texture_3d: "3d" /* WebGPUConstants.TextureViewDimension.E3d */, + texture_cube: "cube" /* WebGPUConstants.TextureViewDimension.Cube */, + texture_cube_array: "cube-array" /* WebGPUConstants.TextureViewDimension.CubeArray */, + texture_multisampled_2d: "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + texture_depth_2d: "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + texture_depth_2d_array: "2d-array" /* WebGPUConstants.TextureViewDimension.E2dArray */, + texture_depth_cube: "cube" /* WebGPUConstants.TextureViewDimension.Cube */, + texture_depth_cube_array: "cube-array" /* WebGPUConstants.TextureViewDimension.CubeArray */, + texture_depth_multisampled_2d: "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + texture_storage_1d: "1d" /* WebGPUConstants.TextureViewDimension.E1d */, + texture_storage_2d: "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + texture_storage_2d_array: "2d-array" /* WebGPUConstants.TextureViewDimension.E2dArray */, + texture_storage_3d: "3d" /* WebGPUConstants.TextureViewDimension.E3d */, + texture_external: null, +}; +/** @internal */ +class WebGPUShaderProcessorWGSL extends WebGPUShaderProcessor { + constructor() { + super(...arguments); + this.shaderLanguage = 1 /* ShaderLanguage.WGSL */; + this.uniformRegexp = /uniform\s+(\w+)\s*:\s*(.+)\s*;/; + this.textureRegexp = /var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/; + this.noPrecision = true; + this.pureMode = false; + } + preProcessor(code, defines, preProcessors, isFragment, processingContext) { + // Convert defines into const + for (const key in preProcessors) { + if (key === "__VERSION__") { + continue; + } + const value = preProcessors[key]; + if (!isNaN(parseInt(value)) || !isNaN(parseFloat(value))) { + code = `const ${key} = ${value};\n` + code; + } + } + return code; + } + _getArraySize(name, uniformType, preProcessors) { + let length = 0; + const endArray = uniformType.lastIndexOf(">"); + if (uniformType.indexOf("array") >= 0 && endArray > 0) { + let startArray = endArray; + while (startArray > 0 && uniformType.charAt(startArray) !== " " && uniformType.charAt(startArray) !== ",") { + startArray--; + } + const lengthInString = uniformType.substring(startArray + 1, endArray); + length = +lengthInString; + if (isNaN(length)) { + length = +preProcessors[lengthInString.trim()]; + } + while (startArray > 0 && (uniformType.charAt(startArray) === " " || uniformType.charAt(startArray) === ",")) { + startArray--; + } + uniformType = uniformType.substring(uniformType.indexOf("<") + 1, startArray + 1); + } + return [name, uniformType, length]; + } + initializeShaders(processingContext) { + this._webgpuProcessingContext = processingContext; + this._attributesInputWGSL = []; + this._attributesWGSL = []; + this._attributesConversionCodeWGSL = []; + this._hasNonFloatAttribute = false; + this._varyingsWGSL = []; + this._varyingNamesWGSL = []; + this._stridedUniformArrays = []; + } + preProcessShaderCode(code) { + // Same check as in webgpuShaderProcessorsGLSL to avoid same ubDelcaration to be injected twice. + const ubDeclaration = this.pureMode + ? "" + : `struct ${WebGPUShaderProcessor.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar ${internalsVarName} : ${WebGPUShaderProcessor.InternalsUBOName};\n`; + const alreadyInjected = code.indexOf(ubDeclaration) !== -1; + return alreadyInjected ? code : ubDeclaration + RemoveComments(code); + } + varyingCheck(varying) { + const regex = /(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/; + return regex.test(varying); + } + varyingProcessor(varying, isFragment, preProcessors) { + const varyingRegex = /\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm; + const match = varyingRegex.exec(varying); + if (match !== null) { + const interpolationType = match[1] ?? "perspective"; + const interpolationSampling = match[2] ?? "center"; + const varyingType = match[4]; + const name = match[3]; + const interpolation = interpolationType === "flat" ? `@interpolate(${interpolationType})` : `@interpolate(${interpolationType}, ${interpolationSampling})`; + let location; + if (isFragment) { + location = this._webgpuProcessingContext.availableVaryings[name]; + if (location === undefined) { + Logger.Warn(`Invalid fragment shader: The varying named "${name}" is not declared in the vertex shader! This declaration will be ignored.`); + } + } + else { + location = this._webgpuProcessingContext.getVaryingNextLocation(varyingType, this._getArraySize(name, varyingType, preProcessors)[2]); + this._webgpuProcessingContext.availableVaryings[name] = location; + this._varyingsWGSL.push(` @location(${location}) ${interpolation} ${name} : ${varyingType},`); + this._varyingNamesWGSL.push(name); + } + varying = ""; + } + return varying; + } + attributeProcessor(attribute, preProcessors) { + const attribRegex = /\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm; + const match = attribRegex.exec(attribute); + if (match !== null) { + const attributeType = match[2]; + const name = match[1]; + const location = this._webgpuProcessingContext.getAttributeNextLocation(attributeType, this._getArraySize(name, attributeType, preProcessors)[2]); + this._webgpuProcessingContext.availableAttributes[name] = location; + this._webgpuProcessingContext.orderedAttributes[location] = name; + const numComponents = this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[name]; + if (numComponents !== undefined) { + // Special case for an int/ivecX vertex buffer that is used as a float/vecX attribute in the shader. + const newType = numComponents < 0 ? (numComponents === -1 ? "i32" : "vec" + -numComponents + "") : numComponents === 1 ? "u32" : "vec" + numComponents + ""; + const newName = `_int_${name}_`; + this._attributesInputWGSL.push(`@location(${location}) ${newName} : ${newType},`); + this._attributesWGSL.push(`${name} : ${attributeType},`); + this._attributesConversionCodeWGSL.push(`vertexInputs.${name} = ${attributeType}(vertexInputs_.${newName});`); + this._hasNonFloatAttribute = true; + } + else { + this._attributesInputWGSL.push(`@location(${location}) ${name} : ${attributeType},`); + this._attributesWGSL.push(`${name} : ${attributeType},`); + this._attributesConversionCodeWGSL.push(`vertexInputs.${name} = vertexInputs_.${name};`); + } + attribute = ""; + } + return attribute; + } + uniformProcessor(uniform, isFragment, preProcessors) { + const match = this.uniformRegexp.exec(uniform); + if (match !== null) { + const uniformType = match[2]; + const name = match[1]; + this._addUniformToLeftOverUBO(name, uniformType, preProcessors); + uniform = ""; + } + return uniform; + } + textureProcessor(texture, isFragment, preProcessors) { + const match = this.textureRegexp.exec(texture); + if (match !== null) { + const name = match[1]; // name of the variable + const type = match[2]; // texture_2d or array, 5> for eg + const isArrayOfTexture = !!match[3]; + const textureFunc = match[4]; // texture_2d, texture_depth_2d, etc + const isStorageTexture = textureFunc.indexOf("storage") > 0; + const componentType = match[6]; // f32 or i32 or u32 or undefined + const storageTextureFormat = isStorageTexture ? componentType.substring(0, componentType.indexOf(",")).trim() : null; + let arraySize = isArrayOfTexture ? this._getArraySize(name, type, preProcessors)[2] : 0; + let textureInfo = this._webgpuProcessingContext.availableTextures[name]; + if (!textureInfo) { + textureInfo = { + isTextureArray: arraySize > 0, + isStorageTexture, + textures: [], + sampleType: "float" /* WebGPUConstants.TextureSampleType.Float */, + }; + arraySize = arraySize || 1; + for (let i = 0; i < arraySize; ++i) { + textureInfo.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding()); + } + } + else { + arraySize = textureInfo.textures.length; + } + this._webgpuProcessingContext.availableTextures[name] = textureInfo; + const isDepthTexture = textureFunc.indexOf("depth") > 0; + const textureDimension = gpuTextureViewDimensionByWebGPUTextureFunction[textureFunc]; + const sampleType = isDepthTexture + ? "depth" /* WebGPUConstants.TextureSampleType.Depth */ + : componentType === "u32" + ? "uint" /* WebGPUConstants.TextureSampleType.Uint */ + : componentType === "i32" + ? "sint" /* WebGPUConstants.TextureSampleType.Sint */ + : "float" /* WebGPUConstants.TextureSampleType.Float */; + textureInfo.sampleType = sampleType; + if (textureDimension === undefined) { + // eslint-disable-next-line no-throw-literal + throw `Can't get the texture dimension corresponding to the texture function "${textureFunc}"!`; + } + for (let i = 0; i < arraySize; ++i) { + const { groupIndex, bindingIndex } = textureInfo.textures[i]; + if (i === 0) { + texture = `@group(${groupIndex}) @binding(${bindingIndex}) ${texture}`; + } + this._addTextureBindingDescription(name, textureInfo, i, textureDimension, storageTextureFormat, !isFragment); + } + } + return texture; + } + // We need to process defines which are directly in the files themselves + postProcessor(code) { + const definePattern = /#define (.+?) (.+?)$/gm; + let match; + while ((match = definePattern.exec(code)) !== null) { + code = code.replace(new RegExp(match[1], "g"), match[2]); + } + return code; + } + finalizeShaders(vertexCode, fragmentCode) { + const fragCoordCode = fragmentCode.indexOf("fragmentInputs.position") >= 0 && !this.pureMode + ? ` + if (internals.yFactor_ == 1.) { + fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; + } + ` + : ""; + // Add the group/binding info to the sampler declaration (var xxx: sampler|sampler_comparison) + vertexCode = this._processSamplers(vertexCode, true); + fragmentCode = this._processSamplers(fragmentCode, false); + // Add the group/binding info to the uniform/storage buffer declarations (var XXX:YYY or var XXX:YYY) + vertexCode = this._processCustomBuffers(vertexCode, true); + fragmentCode = this._processCustomBuffers(fragmentCode, false); + // Builds the leftover UBOs. + const leftOverUBO = this._buildLeftOverUBO(); + vertexCode = leftOverUBO + vertexCode; + fragmentCode = leftOverUBO + fragmentCode; + // Vertex code + vertexCode = vertexCode.replace(/#define (\w+)\s+(\d+\.?\d*)/g, "const $1 = $2;"); + vertexCode = vertexCode.replace(/#define /g, "//#define "); + vertexCode = this._processStridedUniformArrays(vertexCode); + let vertexInputs = "struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n"; + if (this._attributesInputWGSL.length > 0) { + vertexInputs += this._attributesInputWGSL.join("\n"); + } + vertexInputs += "\n};\nvar vertexInputs" + (this._hasNonFloatAttribute ? "_" : "") + " : VertexInputs;\n"; + if (this._hasNonFloatAttribute) { + vertexInputs += "struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n"; + vertexInputs += this._attributesWGSL.join("\n"); + vertexInputs += "\n};\nvar vertexInputs : VertexInputs_;\n"; + } + let vertexOutputs = "struct FragmentInputs {\n @builtin(position) position : vec4,\n"; + if (this._varyingsWGSL.length > 0) { + vertexOutputs += this._varyingsWGSL.join("\n"); + } + vertexOutputs += "\n};\nvar vertexOutputs : FragmentInputs;\n"; + vertexCode = vertexInputs + vertexOutputs + vertexCode; + let vertexMainStartingCode = `\n vertexInputs${this._hasNonFloatAttribute ? "_" : ""} = input;\n`; + if (this._hasNonFloatAttribute) { + vertexMainStartingCode += "vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n"; + vertexMainStartingCode += this._attributesConversionCodeWGSL.join("\n"); + vertexMainStartingCode += "\n"; + } + const vertexMainEndingCode = this.pureMode + ? ` return vertexOutputs;` + : ` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;`; + let needDiagnosticOff = vertexCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) !== -1; + vertexCode = + (needDiagnosticOff ? "diagnostic(off, derivative_uniformity);\n" : "") + + "diagnostic(off, chromium.unreachable_code);\n" + + InjectStartingAndEndingCode(vertexCode, "fn main", vertexMainStartingCode, vertexMainEndingCode); + // fragment code + fragmentCode = fragmentCode.replace(/#define (\w+)\s+(\d+\.?\d*)/g, "const $1 = $2;"); + fragmentCode = fragmentCode.replace(/#define /g, "//#define "); + fragmentCode = this._processStridedUniformArrays(fragmentCode); + if (!this.pureMode) { + fragmentCode = fragmentCode.replace(/dpdy/g, "(-internals.yFactor_)*dpdy"); // will also handle dpdyCoarse and dpdyFine + } + let fragmentInputs = "struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n"; + if (this._varyingsWGSL.length > 0) { + fragmentInputs += this._varyingsWGSL.join("\n"); + } + fragmentInputs += "\n};\nvar fragmentInputs : FragmentInputs;\n"; + let fragmentOutputs = "struct FragmentOutputs {\n"; + // Adding fragData output locations + const regexRoot = "fragmentOutputs\\.fragData"; + let match = fragmentCode.match(new RegExp(regexRoot + "0", "g")); + let indexLocation = 0; + if (match) { + fragmentOutputs += ` @location(${indexLocation}) fragData0 : vec4,\n`; + indexLocation++; + for (let index = 1; index < 8; index++) { + match = fragmentCode.match(new RegExp(regexRoot + index, "g")); + if (match) { + fragmentOutputs += ` @location(${indexLocation}) fragData${indexLocation} : vec4,\n`; + indexLocation++; + } + } + if (fragmentCode.indexOf("MRT_AND_COLOR") !== -1) { + fragmentOutputs += ` @location(${indexLocation}) color : vec4,\n`; + indexLocation++; + } + } + // Adding fragData output locations + const regex = /oitDepthSampler/; + match = fragmentCode.match(regex); + if (match) { + fragmentOutputs += ` @location(${indexLocation++}) depth : vec2,\n`; + fragmentOutputs += ` @location(${indexLocation++}) frontColor : vec4,\n`; + fragmentOutputs += ` @location(${indexLocation++}) backColor : vec4,\n`; + } + if (indexLocation === 0) { + fragmentOutputs += " @location(0) color : vec4,\n"; + indexLocation++; + } + // FragDepth + let hasFragDepth = false; + let idx = 0; + while (!hasFragDepth) { + idx = fragmentCode.indexOf(builtInName_frag_depth, idx); + if (idx < 0) { + break; + } + const saveIndex = idx; + hasFragDepth = true; + while (idx > 1 && fragmentCode.charAt(idx) !== "\n") { + if (fragmentCode.charAt(idx) === "/" && fragmentCode.charAt(idx - 1) === "/") { + hasFragDepth = false; + break; + } + idx--; + } + idx = saveIndex + builtInName_frag_depth.length; + } + if (hasFragDepth) { + fragmentOutputs += " @builtin(frag_depth) fragDepth: f32,\n"; + } + fragmentOutputs += "};\nvar fragmentOutputs : FragmentOutputs;\n"; + fragmentCode = fragmentInputs + fragmentOutputs + fragmentCode; + const fragmentStartingCode = " fragmentInputs = input;\n " + fragCoordCode; + const fragmentEndingCode = " return fragmentOutputs;"; + needDiagnosticOff = fragmentCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) !== -1; + fragmentCode = + (needDiagnosticOff ? "diagnostic(off, derivative_uniformity);\n" : "") + + "diagnostic(off, chromium.unreachable_code);\n" + + InjectStartingAndEndingCode(fragmentCode, "fn main", fragmentStartingCode, fragmentEndingCode); + this._collectBindingNames(); + this._preCreateBindGroupEntries(); + this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents = {}; + return { vertexCode, fragmentCode }; + } + _generateLeftOverUBOCode(name, uniformBufferDescription) { + let stridedArrays = ""; + let ubo = `struct ${name} {\n`; + for (const leftOverUniform of this._webgpuProcessingContext.leftOverUniforms) { + const type = leftOverUniform.type.replace(/^(.*?)(<.*>)?$/, "$1"); + const size = WebGPUShaderProcessor.UniformSizes[type]; + if (leftOverUniform.length > 0) { + if (size <= 2) { + const stridedArrayType = `${name}_${this._stridedUniformArrays.length}_strided_arr`; + stridedArrays += `struct ${stridedArrayType} { + @size(16) + el: ${type}, + }`; + this._stridedUniformArrays.push(leftOverUniform.name); + ubo += ` @align(16) ${leftOverUniform.name} : array<${stridedArrayType}, ${leftOverUniform.length}>,\n`; + } + else { + ubo += ` ${leftOverUniform.name} : array<${leftOverUniform.type}, ${leftOverUniform.length}>,\n`; + } + } + else { + ubo += ` ${leftOverUniform.name} : ${leftOverUniform.type},\n`; + } + } + ubo += "};\n"; + ubo = `${stridedArrays}\n${ubo}`; + ubo += `@group(${uniformBufferDescription.binding.groupIndex}) @binding(${uniformBufferDescription.binding.bindingIndex}) var ${leftOverVarName} : ${name};\n`; + return ubo; + } + _processSamplers(code, isVertex) { + const samplerRegexp = /var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm; + // eslint-disable-next-line no-constant-condition + while (true) { + const match = samplerRegexp.exec(code); + if (match === null) { + break; + } + const name = match[1]; // name of the variable + const samplerType = match[2]; // sampler or sampler_comparison + const suffixLessLength = name.length - `Sampler`.length; + const textureName = name.lastIndexOf(`Sampler`) === suffixLessLength ? name.substring(0, suffixLessLength) : null; + const samplerBindingType = samplerType === "sampler_comparison" ? "comparison" /* WebGPUConstants.SamplerBindingType.Comparison */ : "filtering" /* WebGPUConstants.SamplerBindingType.Filtering */; + if (textureName) { + const textureInfo = this._webgpuProcessingContext.availableTextures[textureName]; + if (textureInfo) { + textureInfo.autoBindSampler = true; + } + } + let samplerInfo = this._webgpuProcessingContext.availableSamplers[name]; + if (!samplerInfo) { + samplerInfo = { + binding: this._webgpuProcessingContext.getNextFreeUBOBinding(), + type: samplerBindingType, + }; + this._webgpuProcessingContext.availableSamplers[name] = samplerInfo; + } + this._addSamplerBindingDescription(name, samplerInfo, isVertex); + const part1 = code.substring(0, match.index); + const insertPart = `@group(${samplerInfo.binding.groupIndex}) @binding(${samplerInfo.binding.bindingIndex}) `; + const part2 = code.substring(match.index); + code = part1 + insertPart + part2; + samplerRegexp.lastIndex += insertPart.length; + } + return code; + } + _processCustomBuffers(code, isVertex) { + const instantiateBufferRegexp = /var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm; + // eslint-disable-next-line no-constant-condition + while (true) { + const match = instantiateBufferRegexp.exec(code); + if (match === null) { + break; + } + const type = match[1]; + const decoration = match[3]; + let name = match[4]; + const structName = match[5]; + let bufferInfo = this._webgpuProcessingContext.availableBuffers[name]; + if (!bufferInfo) { + const knownUBO = type === "uniform" ? WebGPUShaderProcessingContext.KnownUBOs[structName] : null; + let binding; + if (knownUBO) { + name = structName; + binding = knownUBO.binding; + if (binding.groupIndex === -1) { + binding = this._webgpuProcessingContext.availableBuffers[name]?.binding; + if (!binding) { + binding = this._webgpuProcessingContext.getNextFreeUBOBinding(); + } + } + } + else { + binding = this._webgpuProcessingContext.getNextFreeUBOBinding(); + } + bufferInfo = { binding }; + this._webgpuProcessingContext.availableBuffers[name] = bufferInfo; + } + this._addBufferBindingDescription(name, this._webgpuProcessingContext.availableBuffers[name], decoration === "read_write" + ? "storage" /* WebGPUConstants.BufferBindingType.Storage */ + : type === "storage" + ? "read-only-storage" /* WebGPUConstants.BufferBindingType.ReadOnlyStorage */ + : "uniform" /* WebGPUConstants.BufferBindingType.Uniform */, isVertex); + const groupIndex = bufferInfo.binding.groupIndex; + const bindingIndex = bufferInfo.binding.bindingIndex; + const part1 = code.substring(0, match.index); + const insertPart = `@group(${groupIndex}) @binding(${bindingIndex}) `; + const part2 = code.substring(match.index); + code = part1 + insertPart + part2; + instantiateBufferRegexp.lastIndex += insertPart.length; + } + return code; + } + _processStridedUniformArrays(code) { + for (const uniformArrayName of this._stridedUniformArrays) { + code = code.replace(new RegExp(`${uniformArrayName}\\s*\\[(.*?)\\]`, "g"), `${uniformArrayName}[$1].el`); + } + return code; + } +} + +/** @internal */ +class WebGPUHardwareTexture { + get underlyingResource() { + return this._webgpuTexture; + } + getMSAATexture(index) { + return this._webgpuMSAATexture?.[index] ?? null; + } + setMSAATexture(texture, index) { + if (!this._webgpuMSAATexture) { + this._webgpuMSAATexture = []; + } + this._webgpuMSAATexture[index] = texture; + } + releaseMSAATexture(index) { + if (this._webgpuMSAATexture) { + if (index !== undefined) { + this._engine._textureHelper.releaseTexture(this._webgpuMSAATexture[index]); + delete this._webgpuMSAATexture[index]; + } + else { + for (const texture of this._webgpuMSAATexture) { + this._engine._textureHelper.releaseTexture(texture); + } + this._webgpuMSAATexture = null; + } + } + } + constructor(_engine, existingTexture = null) { + this._engine = _engine; + /** @internal */ + this._originalFormatIsRGB = false; + this.format = "rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */; + this.textureUsages = 0; + this.textureAdditionalUsages = 0; + this._webgpuTexture = existingTexture; + this._webgpuMSAATexture = null; + this.view = null; + this.viewForWriting = null; + } + set(hardwareTexture) { + this._webgpuTexture = hardwareTexture; + } + setUsage(_textureSource, generateMipMaps, is2DArray, isCube, is3D, width, height, depth) { + let viewDimension = "2d" /* WebGPUConstants.TextureViewDimension.E2d */; + let arrayLayerCount = 1; + if (isCube) { + viewDimension = is2DArray ? "cube-array" /* WebGPUConstants.TextureViewDimension.CubeArray */ : "cube" /* WebGPUConstants.TextureViewDimension.Cube */; + arrayLayerCount = 6 * (depth || 1); + } + else if (is3D) { + viewDimension = "3d" /* WebGPUConstants.TextureViewDimension.E3d */; + arrayLayerCount = 1; + } + else if (is2DArray) { + viewDimension = "2d-array" /* WebGPUConstants.TextureViewDimension.E2dArray */; + arrayLayerCount = depth; + } + const format = WebGPUTextureHelper.GetDepthFormatOnly(this.format); + const aspect = WebGPUTextureHelper.HasDepthAndStencilAspects(this.format) ? "depth-only" /* WebGPUConstants.TextureAspect.DepthOnly */ : "all" /* WebGPUConstants.TextureAspect.All */; + this.createView({ + label: `TextureView${is3D ? "3D" : isCube ? "Cube" : "2D"}${is2DArray ? "_Array" + arrayLayerCount : ""}_${width}x${height}_${generateMipMaps ? "wmips" : "womips"}_${this.format}_${viewDimension}`, + format, + dimension: viewDimension, + mipLevelCount: generateMipMaps ? ILog2(Math.max(width, height)) + 1 : 1, + baseArrayLayer: 0, + baseMipLevel: 0, + arrayLayerCount, + aspect, + }); + } + createView(descriptor, createViewForWriting = false) { + this.view = this._webgpuTexture.createView(descriptor); + if (createViewForWriting && descriptor) { + const saveNumMipMaps = descriptor.mipLevelCount; + descriptor.mipLevelCount = 1; + this.viewForWriting = this._webgpuTexture.createView(descriptor); + descriptor.mipLevelCount = saveNumMipMaps; + } + } + reset() { + this._webgpuTexture = null; + this._webgpuMSAATexture = null; + this.view = null; + this.viewForWriting = null; + } + release() { + this._webgpuTexture?.destroy(); + this.releaseMSAATexture(); + this._copyInvertYTempTexture?.destroy(); + this.reset(); + } +} + +/* eslint-disable @typescript-eslint/naming-convention */ +/* eslint-disable babylonjs/available */ +/* eslint-disable jsdoc/require-jsdoc */ +// License for the mipmap generation code: +// +// Copyright 2020 Brandon Jones +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// TODO WEBGPU improve mipmap generation by using compute shaders +const mipmapVertexSource = ` + const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f)); + const tex = array, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f)); + + varying vTex: vec2f; + + @vertex + fn main(input : VertexInputs) -> FragmentInputs { + vertexOutputs.vTex = tex[input.vertexIndex]; + vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0); + } + `; +const mipmapFragmentSource = ` + var imgSampler: sampler; + var img: texture_2d; + + varying vTex: vec2f; + + @fragment + fn main(input: FragmentInputs) -> FragmentOutputs { + fragmentOutputs.color = textureSample(img, imgSampler, input.vTex); + } + `; +const invertYPreMultiplyAlphaVertexSource = ` + const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f)); + const tex = array, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f)); + + var img: texture_2d; + + #ifdef INVERTY + varying vTextureSize: vec2f; + #endif + + @vertex + fn main(input : VertexInputs) -> FragmentInputs { + #ifdef INVERTY + vertexOutputs.vTextureSize = vec2f(textureDimensions(img, 0)); + #endif + vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0); + } + `; +const invertYPreMultiplyAlphaFragmentSource = ` + var img: texture_2d; + + #ifdef INVERTY + varying vTextureSize: vec2f; + #endif + + @fragment + fn main(input: FragmentInputs) -> FragmentOutputs { + #ifdef INVERTY + var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(input.vTextureSize.y - input.position.y)), 0); + #else + var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color = vec4f(color.rgb * color.a, color.a); + #endif + fragmentOutputs.color = color; + } + `; +const invertYPreMultiplyAlphaWithOfstVertexSource = invertYPreMultiplyAlphaVertexSource; +const invertYPreMultiplyAlphaWithOfstFragmentSource = ` + var img: texture_2d; + uniform ofstX: f32; + uniform ofstY: f32; + uniform width: f32; + uniform height: f32; + + #ifdef INVERTY + varying vTextureSize: vec2f; + #endif + + @fragment + fn main(input: FragmentInputs) -> FragmentOutputs { + if (input.position.x < uniforms.ofstX || input.position.x >= uniforms.ofstX + uniforms.width) { + discard; + } + if (input.position.y < uniforms.ofstY || input.position.y >= uniforms.ofstY + uniforms.height) { + discard; + } + #ifdef INVERTY + var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(uniforms.ofstY + uniforms.height - (input.position.y - uniforms.ofstY))), 0); + #else + var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color = vec4f(color.rgb * color.a, color.a); + #endif + fragmentOutputs.color = color; + } + `; +const clearVertexSource = ` + const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f)); + + @vertex + fn main(input : VertexInputs) -> FragmentInputs { + vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0); + } + `; +const clearFragmentSource = ` + uniform color: vec4f; + + + @fragment + fn main(input: FragmentInputs) -> FragmentOutputs { + fragmentOutputs.color = uniforms.color; + } + `; +const copyVideoToTextureVertexSource = ` + struct VertexOutput { + @builtin(position) Position : vec4, + @location(0) fragUV : vec2 + } + + @vertex + fn main( + @builtin(vertex_index) VertexIndex : u32 + ) -> VertexOutput { + var pos = array, 4>( + vec2(-1.0, 1.0), + vec2( 1.0, 1.0), + vec2(-1.0, -1.0), + vec2( 1.0, -1.0) + ); + var tex = array, 4>( + vec2(0.0, 0.0), + vec2(1.0, 0.0), + vec2(0.0, 1.0), + vec2(1.0, 1.0) + ); + + var output: VertexOutput; + + output.Position = vec4(pos[VertexIndex], 0.0, 1.0); + output.fragUV = tex[VertexIndex]; + + return output; + } + `; +const copyVideoToTextureFragmentSource = ` + @group(0) @binding(0) var videoSampler: sampler; + @group(0) @binding(1) var videoTexture: texture_external; + + @fragment + fn main( + @location(0) fragUV: vec2 + ) -> @location(0) vec4 { + return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); + } + `; +const copyVideoToTextureInvertYFragmentSource = ` + @group(0) @binding(0) var videoSampler: sampler; + @group(0) @binding(1) var videoTexture: texture_external; + + @fragment + fn main( + @location(0) fragUV: vec2 + ) -> @location(0) vec4 { + return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y)); + } + `; +var PipelineType; +(function (PipelineType) { + PipelineType[PipelineType["MipMap"] = 0] = "MipMap"; + PipelineType[PipelineType["InvertYPremultiplyAlpha"] = 1] = "InvertYPremultiplyAlpha"; + PipelineType[PipelineType["Clear"] = 2] = "Clear"; + PipelineType[PipelineType["InvertYPremultiplyAlphaWithOfst"] = 3] = "InvertYPremultiplyAlphaWithOfst"; +})(PipelineType || (PipelineType = {})); +var VideoPipelineType; +(function (VideoPipelineType) { + VideoPipelineType[VideoPipelineType["DontInvertY"] = 0] = "DontInvertY"; + VideoPipelineType[VideoPipelineType["InvertY"] = 1] = "InvertY"; +})(VideoPipelineType || (VideoPipelineType = {})); +const shadersForPipelineType = [ + { vertex: mipmapVertexSource, fragment: mipmapFragmentSource }, + { vertex: invertYPreMultiplyAlphaVertexSource, fragment: invertYPreMultiplyAlphaFragmentSource }, + { vertex: clearVertexSource, fragment: clearFragmentSource }, + { vertex: invertYPreMultiplyAlphaWithOfstVertexSource, fragment: invertYPreMultiplyAlphaWithOfstFragmentSource }, +]; +/** + * Map a (renderable) texture format (GPUTextureFormat) to an index for fast lookup (in caches for eg) + * The number of entries should not go over 64! Else, the code in WebGPUCacheRenderPipeline.setMRT should be updated + */ +const renderableTextureFormatToIndex = { + "": 0, + r8unorm: 1, + r8uint: 2, + r8sint: 3, + r16uint: 4, + r16sint: 5, + r16float: 6, + rg8unorm: 7, + rg8uint: 8, + rg8sint: 9, + r32uint: 10, + r32sint: 11, + r32float: 12, + rg16uint: 13, + rg16sint: 14, + rg16float: 15, + rgba8unorm: 16, + "rgba8unorm-srgb": 17, + rgba8uint: 18, + rgba8sint: 19, + bgra8unorm: 20, + "bgra8unorm-srgb": 21, + rgb10a2uint: 22, + rgb10a2unorm: 23, + /* rg11b10ufloat: this entry is dynamically added if the "RG11B10UFloatRenderable" extension is supported */ + rg32uint: 24, + rg32sint: 25, + rg32float: 26, + rgba16uint: 27, + rgba16sint: 28, + rgba16float: 29, + rgba32uint: 30, + rgba32sint: 31, + rgba32float: 32, + stencil8: 33, + depth16unorm: 34, + depth24plus: 35, + "depth24plus-stencil8": 36, + depth32float: 37, + "depth32float-stencil8": 38, + r16unorm: 39, + rg16unorm: 40, + rgba16unorm: 41, + r16snorm: 42, + rg16snorm: 43, + rgba16snorm: 44, +}; +/** @internal */ +class WebGPUTextureManager { + //------------------------------------------------------------------------------ + // Initialization / Helpers + //------------------------------------------------------------------------------ + constructor(engine, device, bufferManager, enabledExtensions) { + this._pipelines = {}; + this._compiledShaders = []; + this._videoPipelines = {}; + this._videoCompiledShaders = []; + this._deferredReleaseTextures = []; + this._engine = engine; + this._device = device; + this._bufferManager = bufferManager; + if (enabledExtensions.indexOf("rg11b10ufloat-renderable" /* WebGPUConstants.FeatureName.RG11B10UFloatRenderable */) !== -1) { + const keys = Object.keys(renderableTextureFormatToIndex); + renderableTextureFormatToIndex["rg11b10ufloat" /* WebGPUConstants.TextureFormat.RG11B10UFloat */] = renderableTextureFormatToIndex[keys[keys.length - 1]] + 1; + } + this._mipmapSampler = device.createSampler({ minFilter: "linear" /* WebGPUConstants.FilterMode.Linear */ }); + this._videoSampler = device.createSampler({ minFilter: "linear" /* WebGPUConstants.FilterMode.Linear */ }); + this._ubCopyWithOfst = this._bufferManager.createBuffer(4 * 4, BufferUsage.Uniform | BufferUsage.CopyDst, "UBCopyWithOffset").underlyingResource; + this._getPipeline("rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */); + this._getVideoPipeline("rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */); + } + _getPipeline(format, type = PipelineType.MipMap, params) { + const index = type === PipelineType.MipMap + ? 1 << 0 + : type === PipelineType.InvertYPremultiplyAlpha + ? ((params.invertY ? 1 : 0) << 1) + ((params.premultiplyAlpha ? 1 : 0) << 2) + : type === PipelineType.Clear + ? 1 << 3 + : type === PipelineType.InvertYPremultiplyAlphaWithOfst + ? ((params.invertY ? 1 : 0) << 4) + ((params.premultiplyAlpha ? 1 : 0) << 5) + : 0; + if (!this._pipelines[format]) { + this._pipelines[format] = []; + } + let pipelineAndBGL = this._pipelines[format][index]; + if (!pipelineAndBGL) { + let defines = ""; + if (type === PipelineType.InvertYPremultiplyAlpha || type === PipelineType.InvertYPremultiplyAlphaWithOfst) { + if (params.invertY) { + defines += "#define INVERTY\n"; + } + if (params.premultiplyAlpha) { + defines += "#define PREMULTIPLYALPHA\n"; + } + } + let modules = this._compiledShaders[index]; + if (!modules) { + let vertexCode = shadersForPipelineType[type].vertex; + let fragmentCode = shadersForPipelineType[type].fragment; + const processorOptions = { + defines: defines.split("\n"), + indexParameters: null, + isFragment: false, + shouldUseHighPrecisionShader: true, + processor: this._engine._getShaderProcessor(1 /* ShaderLanguage.WGSL */), + supportsUniformBuffers: true, + shadersRepository: "", + includesShadersStore: {}, + version: (this._engine.version * 100).toString(), + platformName: this._engine.shaderPlatformName, + processingContext: this._engine._getShaderProcessingContext(1 /* ShaderLanguage.WGSL */, true), + isNDCHalfZRange: this._engine.isNDCHalfZRange, + useReverseDepthBuffer: this._engine.useReverseDepthBuffer, + }; + Initialize(processorOptions); + // Disable special additions not needed here + processorOptions.processor.pureMode = true; + Process(vertexCode, processorOptions, (migratedVertexCode) => { + vertexCode = migratedVertexCode; + }, this._engine); + processorOptions.isFragment = true; + Process(fragmentCode, processorOptions, (migratedFragmentCode) => { + fragmentCode = migratedFragmentCode; + }, this._engine); + const final = Finalize(vertexCode, fragmentCode, processorOptions); + // Restore + processorOptions.processor.pureMode = false; + const vertexModule = this._device.createShaderModule({ + label: `BabylonWebGPUDevice${this._engine.uniqueId}_InternalVertexShader_${index}`, + code: final.vertexCode, + }); + const fragmentModule = this._device.createShaderModule({ + label: `BabylonWebGPUDevice${this._engine.uniqueId}_InternalFragmentShader_${index}`, + code: final.fragmentCode, + }); + modules = this._compiledShaders[index] = [vertexModule, fragmentModule]; + } + const pipeline = this._device.createRenderPipeline({ + label: `BabylonWebGPUDevice${this._engine.uniqueId}_InternalPipeline_${format}_${index}`, + layout: "auto" /* WebGPUConstants.AutoLayoutMode.Auto */, + vertex: { + module: modules[0], + entryPoint: "main", + }, + fragment: { + module: modules[1], + entryPoint: "main", + targets: [ + { + format, + }, + ], + }, + primitive: { + topology: "triangle-strip" /* WebGPUConstants.PrimitiveTopology.TriangleStrip */, + stripIndexFormat: "uint16" /* WebGPUConstants.IndexFormat.Uint16 */, + }, + }); + pipelineAndBGL = this._pipelines[format][index] = [pipeline, pipeline.getBindGroupLayout(0)]; + } + return pipelineAndBGL; + } + _getVideoPipeline(format, type = VideoPipelineType.DontInvertY) { + const index = type === VideoPipelineType.InvertY ? 1 << 0 : 0; + if (!this._videoPipelines[format]) { + this._videoPipelines[format] = []; + } + let pipelineAndBGL = this._videoPipelines[format][index]; + if (!pipelineAndBGL) { + let modules = this._videoCompiledShaders[index]; + if (!modules) { + const vertexModule = this._device.createShaderModule({ + code: copyVideoToTextureVertexSource, + label: `BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_VertexShader`, + }); + const fragmentModule = this._device.createShaderModule({ + code: index === 0 ? copyVideoToTextureFragmentSource : copyVideoToTextureInvertYFragmentSource, + label: `BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_FragmentShader_${index === 0 ? "DontInvertY" : "InvertY"}`, + }); + modules = this._videoCompiledShaders[index] = [vertexModule, fragmentModule]; + } + const pipeline = this._device.createRenderPipeline({ + label: `BabylonWebGPUDevice${this._engine.uniqueId}_InternalVideoPipeline_${format}_${index === 0 ? "DontInvertY" : "InvertY"}`, + layout: "auto" /* WebGPUConstants.AutoLayoutMode.Auto */, + vertex: { + module: modules[0], + entryPoint: "main", + }, + fragment: { + module: modules[1], + entryPoint: "main", + targets: [ + { + format, + }, + ], + }, + primitive: { + topology: "triangle-strip" /* WebGPUConstants.PrimitiveTopology.TriangleStrip */, + stripIndexFormat: "uint16" /* WebGPUConstants.IndexFormat.Uint16 */, + }, + }); + pipelineAndBGL = this._videoPipelines[format][index] = [pipeline, pipeline.getBindGroupLayout(0)]; + } + return pipelineAndBGL; + } + setCommandEncoder(encoder) { + this._commandEncoderForCreation = encoder; + } + copyVideoToTexture(video, texture, format, invertY = false, commandEncoder) { + const useOwnCommandEncoder = commandEncoder === undefined; + const [pipeline, bindGroupLayout] = this._getVideoPipeline(format, invertY ? VideoPipelineType.InvertY : VideoPipelineType.DontInvertY); + if (useOwnCommandEncoder) { + commandEncoder = this._device.createCommandEncoder({}); + } + commandEncoder.pushDebugGroup?.(`copy video to texture - invertY=${invertY}`); + const webgpuHardwareTexture = texture._hardwareTexture; + const renderPassDescriptor = { + label: `BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${format}_${invertY ? "InvertY" : "DontInvertY"}${texture.label ? "_" + texture.label : ""}`, + colorAttachments: [ + { + view: webgpuHardwareTexture.underlyingResource.createView({ + format, + dimension: "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + mipLevelCount: 1, + baseArrayLayer: 0, + baseMipLevel: 0, + arrayLayerCount: 1, + aspect: "all" /* WebGPUConstants.TextureAspect.All */, + }), + loadOp: "load" /* WebGPUConstants.LoadOp.Load */, + storeOp: "store" /* WebGPUConstants.StoreOp.Store */, + }, + ], + }; + const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); + const descriptor = { + layout: bindGroupLayout, + entries: [ + { + binding: 0, + resource: this._videoSampler, + }, + { + binding: 1, + resource: this._device.importExternalTexture({ + source: video.underlyingResource, + }), + }, + ], + }; + const bindGroup = this._device.createBindGroup(descriptor); + passEncoder.setPipeline(pipeline); + passEncoder.setBindGroup(0, bindGroup); + passEncoder.draw(4, 1, 0, 0); + passEncoder.end(); + commandEncoder.popDebugGroup?.(); + if (useOwnCommandEncoder) { + this._device.queue.submit([commandEncoder.finish()]); + commandEncoder = null; + } + } + invertYPreMultiplyAlpha(gpuOrHdwTexture, width, height, format, invertY = false, premultiplyAlpha = false, faceIndex = 0, mipLevel = 0, layers = 1, ofstX = 0, ofstY = 0, rectWidth = 0, rectHeight = 0, commandEncoder, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + allowGPUOptimization) { + const useRect = rectWidth !== 0; + const useOwnCommandEncoder = commandEncoder === undefined; + const [pipeline, bindGroupLayout] = this._getPipeline(format, useRect ? PipelineType.InvertYPremultiplyAlphaWithOfst : PipelineType.InvertYPremultiplyAlpha, { + invertY, + premultiplyAlpha, + }); + faceIndex = Math.max(faceIndex, 0); + if (useOwnCommandEncoder) { + commandEncoder = this._device.createCommandEncoder({}); + } + commandEncoder.pushDebugGroup?.(`internal process texture - invertY=${invertY} premultiplyAlpha=${premultiplyAlpha}`); + let gpuTexture; + if (WebGPUTextureHelper.IsHardwareTexture(gpuOrHdwTexture)) { + gpuTexture = gpuOrHdwTexture.underlyingResource; + if (!(invertY && !premultiplyAlpha && layers === 1 && faceIndex === 0)) { + // we optimize only for the most likely case (invertY=true, premultiplyAlpha=false, layers=1, faceIndex=0) to avoid dealing with big caches + gpuOrHdwTexture = undefined; + } + } + else { + gpuTexture = gpuOrHdwTexture; + gpuOrHdwTexture = undefined; + } + if (!gpuTexture) { + return; + } + if (useRect) { + this._bufferManager.setRawData(this._ubCopyWithOfst, 0, new Float32Array([ofstX, ofstY, rectWidth, rectHeight]), 0, 4 * 4); + } + const webgpuHardwareTexture = gpuOrHdwTexture; + const outputTexture = webgpuHardwareTexture?._copyInvertYTempTexture ?? + this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, format, 1, commandEncoder, 1 /* WebGPUConstants.TextureUsage.CopySrc */ | 16 /* WebGPUConstants.TextureUsage.RenderAttachment */ | 4 /* WebGPUConstants.TextureUsage.TextureBinding */, undefined, "TempTextureForCopyWithInvertY"); + const renderPassDescriptor = webgpuHardwareTexture?._copyInvertYRenderPassDescr ?? { + label: `BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${format}_${invertY ? "InvertY" : "DontInvertY"}_${premultiplyAlpha ? "PremultiplyAlpha" : "DontPremultiplyAlpha"}`, + colorAttachments: [ + { + view: outputTexture.createView({ + format, + dimension: "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + baseMipLevel: 0, + mipLevelCount: 1, + arrayLayerCount: 1, + baseArrayLayer: 0, + }), + loadOp: "load" /* WebGPUConstants.LoadOp.Load */, + storeOp: "store" /* WebGPUConstants.StoreOp.Store */, + }, + ], + }; + const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); + let bindGroup = useRect ? webgpuHardwareTexture?._copyInvertYBindGroupWithOfst : webgpuHardwareTexture?._copyInvertYBindGroup; + if (!bindGroup) { + const descriptor = { + layout: bindGroupLayout, + entries: [ + { + binding: 0, + resource: gpuTexture.createView({ + format, + dimension: "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + baseMipLevel: mipLevel, + mipLevelCount: 1, + arrayLayerCount: layers, + baseArrayLayer: faceIndex, + }), + }, + ], + }; + if (useRect) { + descriptor.entries.push({ + binding: 1, + resource: { + buffer: this._ubCopyWithOfst, + }, + }); + } + bindGroup = this._device.createBindGroup(descriptor); + } + passEncoder.setPipeline(pipeline); + passEncoder.setBindGroup(0, bindGroup); + passEncoder.draw(4, 1, 0, 0); + passEncoder.end(); + commandEncoder.copyTextureToTexture({ + texture: outputTexture, + }, { + texture: gpuTexture, + mipLevel, + origin: { + x: 0, + y: 0, + z: faceIndex, + }, + }, { + width: rectWidth || width, + height: rectHeight || height, + depthOrArrayLayers: 1, + }); + if (webgpuHardwareTexture) { + webgpuHardwareTexture._copyInvertYTempTexture = outputTexture; + webgpuHardwareTexture._copyInvertYRenderPassDescr = renderPassDescriptor; + if (useRect) { + webgpuHardwareTexture._copyInvertYBindGroupWithOfst = bindGroup; + } + else { + webgpuHardwareTexture._copyInvertYBindGroup = bindGroup; + } + } + else { + this._deferredReleaseTextures.push([outputTexture, null]); + } + commandEncoder.popDebugGroup?.(); + if (useOwnCommandEncoder) { + this._device.queue.submit([commandEncoder.finish()]); + commandEncoder = null; + } + } + //------------------------------------------------------------------------------ + // Creation + //------------------------------------------------------------------------------ + createTexture(imageBitmap, hasMipmaps = false, generateMipmaps = false, invertY = false, premultiplyAlpha = false, is3D = false, format = "rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */, sampleCount = 1, commandEncoder, usage = -1, additionalUsages = 0, label) { + sampleCount = WebGPUTextureHelper.GetSample(sampleCount); + const layerCount = imageBitmap.layers || 1; + const textureSize = { + width: imageBitmap.width, + height: imageBitmap.height, + depthOrArrayLayers: layerCount, + }; + const renderAttachmentFlag = renderableTextureFormatToIndex[format] ? 16 /* WebGPUConstants.TextureUsage.RenderAttachment */ : 0; + const isCompressedFormat = WebGPUTextureHelper.IsCompressedFormat(format); + const mipLevelCount = hasMipmaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(imageBitmap.width, imageBitmap.height) : 1; + const usages = usage >= 0 ? usage : 1 /* WebGPUConstants.TextureUsage.CopySrc */ | 2 /* WebGPUConstants.TextureUsage.CopyDst */ | 4 /* WebGPUConstants.TextureUsage.TextureBinding */; + additionalUsages |= hasMipmaps && !isCompressedFormat ? 1 /* WebGPUConstants.TextureUsage.CopySrc */ | renderAttachmentFlag : 0; + if (!isCompressedFormat && !is3D) { + // we don't know in advance if the texture will be updated with copyExternalImageToTexture (which requires to have those flags), so we need to force the flags all the times + additionalUsages |= renderAttachmentFlag | 2 /* WebGPUConstants.TextureUsage.CopyDst */; + } + const gpuTexture = this._device.createTexture({ + label: `BabylonWebGPUDevice${this._engine.uniqueId}_Texture${is3D ? "3D" : "2D"}_${label ? label + "_" : ""}${textureSize.width}x${textureSize.height}x${textureSize.depthOrArrayLayers}_${hasMipmaps ? "wmips" : "womips"}_${format}_samples${sampleCount}`, + size: textureSize, + dimension: is3D ? "3d" /* WebGPUConstants.TextureDimension.E3d */ : "2d" /* WebGPUConstants.TextureDimension.E2d */, + format, + usage: usages | additionalUsages, + sampleCount, + mipLevelCount, + }); + if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) { + this.updateTexture(imageBitmap, gpuTexture, imageBitmap.width, imageBitmap.height, layerCount, format, 0, 0, invertY, premultiplyAlpha, 0, 0); + if (hasMipmaps && generateMipmaps) { + this.generateMipmaps(gpuTexture, format, mipLevelCount, 0, is3D, commandEncoder); + } + } + return gpuTexture; + } + createCubeTexture(imageBitmaps, hasMipmaps = false, generateMipmaps = false, invertY = false, premultiplyAlpha = false, format = "rgba8unorm" /* WebGPUConstants.TextureFormat.RGBA8Unorm */, sampleCount = 1, commandEncoder, usage = -1, additionalUsages = 0, label) { + sampleCount = WebGPUTextureHelper.GetSample(sampleCount); + const width = WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps) ? imageBitmaps[0].width : imageBitmaps.width; + const height = WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps) ? imageBitmaps[0].height : imageBitmaps.height; + const renderAttachmentFlag = renderableTextureFormatToIndex[format] ? 16 /* WebGPUConstants.TextureUsage.RenderAttachment */ : 0; + const isCompressedFormat = WebGPUTextureHelper.IsCompressedFormat(format); + const mipLevelCount = hasMipmaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(width, height) : 1; + const usages = usage >= 0 ? usage : 1 /* WebGPUConstants.TextureUsage.CopySrc */ | 2 /* WebGPUConstants.TextureUsage.CopyDst */ | 4 /* WebGPUConstants.TextureUsage.TextureBinding */; + additionalUsages |= hasMipmaps && !isCompressedFormat ? 1 /* WebGPUConstants.TextureUsage.CopySrc */ | renderAttachmentFlag : 0; + if (!isCompressedFormat) { + // we don't know in advance if the texture will be updated with copyExternalImageToTexture (which requires to have those flags), so we need to force the flags all the times + additionalUsages |= renderAttachmentFlag | 2 /* WebGPUConstants.TextureUsage.CopyDst */; + } + const gpuTexture = this._device.createTexture({ + label: `BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${label ? label + "_" : ""}${width}x${height}x6_${hasMipmaps ? "wmips" : "womips"}_${format}_samples${sampleCount}`, + size: { + width, + height, + depthOrArrayLayers: 6, + }, + dimension: "2d" /* WebGPUConstants.TextureDimension.E2d */, + format, + usage: usages | additionalUsages, + sampleCount, + mipLevelCount, + }); + if (WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps)) { + this.updateCubeTextures(imageBitmaps, gpuTexture, width, height, format, invertY, premultiplyAlpha, 0, 0); + if (hasMipmaps && generateMipmaps) { + this.generateCubeMipmaps(gpuTexture, format, mipLevelCount, commandEncoder); + } + } + return gpuTexture; + } + generateCubeMipmaps(gpuTexture, format, mipLevelCount, commandEncoder) { + const useOwnCommandEncoder = commandEncoder === undefined; + if (useOwnCommandEncoder) { + commandEncoder = this._device.createCommandEncoder({}); + } + commandEncoder.pushDebugGroup?.(`create cube mipmaps - ${mipLevelCount} levels`); + for (let f = 0; f < 6; ++f) { + this.generateMipmaps(gpuTexture, format, mipLevelCount, f, false, commandEncoder); + } + commandEncoder.popDebugGroup?.(); + if (useOwnCommandEncoder) { + this._device.queue.submit([commandEncoder.finish()]); + commandEncoder = null; + } + } + generateMipmaps(gpuOrHdwTexture, format, mipLevelCount, faceIndex = 0, is3D = false, commandEncoder) { + const useOwnCommandEncoder = commandEncoder === undefined; + const [pipeline, bindGroupLayout] = this._getPipeline(format); + faceIndex = Math.max(faceIndex, 0); + if (useOwnCommandEncoder) { + commandEncoder = this._device.createCommandEncoder({}); + } + commandEncoder.pushDebugGroup?.(`create mipmaps for face #${faceIndex} - ${mipLevelCount} levels`); + let gpuTexture; + if (WebGPUTextureHelper.IsHardwareTexture(gpuOrHdwTexture)) { + gpuTexture = gpuOrHdwTexture.underlyingResource; + gpuOrHdwTexture._mipmapGenRenderPassDescr = gpuOrHdwTexture._mipmapGenRenderPassDescr || []; + gpuOrHdwTexture._mipmapGenBindGroup = gpuOrHdwTexture._mipmapGenBindGroup || []; + } + else { + gpuTexture = gpuOrHdwTexture; + gpuOrHdwTexture = undefined; + } + if (!gpuTexture) { + return; + } + const webgpuHardwareTexture = gpuOrHdwTexture; + for (let i = 1; i < mipLevelCount; ++i) { + const renderPassDescriptor = webgpuHardwareTexture?._mipmapGenRenderPassDescr[faceIndex]?.[i - 1] ?? { + label: `BabylonWebGPUDevice${this._engine.uniqueId}_generateMipmaps_${format}_faceIndex${faceIndex}_level${i}`, + colorAttachments: [ + { + view: gpuTexture.createView({ + format, + dimension: is3D ? "3d" /* WebGPUConstants.TextureViewDimension.E3d */ : "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + baseMipLevel: i, + mipLevelCount: 1, + arrayLayerCount: 1, + baseArrayLayer: faceIndex, + }), + loadOp: "load" /* WebGPUConstants.LoadOp.Load */, + storeOp: "store" /* WebGPUConstants.StoreOp.Store */, + }, + ], + }; + if (webgpuHardwareTexture) { + webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex] = webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex] || []; + webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex][i - 1] = renderPassDescriptor; + } + const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); + const bindGroup = webgpuHardwareTexture?._mipmapGenBindGroup[faceIndex]?.[i - 1] ?? + this._device.createBindGroup({ + layout: bindGroupLayout, + entries: [ + { + binding: 0, + resource: gpuTexture.createView({ + format, + dimension: is3D ? "3d" /* WebGPUConstants.TextureViewDimension.E3d */ : "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + baseMipLevel: i - 1, + mipLevelCount: 1, + arrayLayerCount: 1, + baseArrayLayer: faceIndex, + }), + }, + { + binding: 1, + resource: this._mipmapSampler, + }, + ], + }); + if (webgpuHardwareTexture) { + webgpuHardwareTexture._mipmapGenBindGroup[faceIndex] = webgpuHardwareTexture._mipmapGenBindGroup[faceIndex] || []; + webgpuHardwareTexture._mipmapGenBindGroup[faceIndex][i - 1] = bindGroup; + } + passEncoder.setPipeline(pipeline); + passEncoder.setBindGroup(0, bindGroup); + passEncoder.draw(4, 1, 0, 0); + passEncoder.end(); + } + commandEncoder.popDebugGroup?.(); + if (useOwnCommandEncoder) { + this._device.queue.submit([commandEncoder.finish()]); + commandEncoder = null; + } + } + createGPUTextureForInternalTexture(texture, width, height, depth, creationFlags, dontCreateMSAATexture) { + if (!texture._hardwareTexture) { + texture._hardwareTexture = new WebGPUHardwareTexture(this._engine); + } + if (width === undefined) { + width = texture.width; + } + if (height === undefined) { + height = texture.height; + } + if (depth === undefined) { + depth = texture.depth; + } + const gpuTextureWrapper = texture._hardwareTexture; + const isStorageTexture = ((creationFlags ?? 0) & 1) !== 0; + gpuTextureWrapper.format = WebGPUTextureHelper.GetWebGPUTextureFormat(texture.type, texture.format, texture._useSRGBBuffer); + gpuTextureWrapper.textureUsages = + texture._source === 5 /* InternalTextureSource.RenderTarget */ || texture.source === 6 /* InternalTextureSource.MultiRenderTarget */ + ? 4 /* WebGPUConstants.TextureUsage.TextureBinding */ | 1 /* WebGPUConstants.TextureUsage.CopySrc */ | 16 /* WebGPUConstants.TextureUsage.RenderAttachment */ + : texture._source === 12 /* InternalTextureSource.DepthStencil */ + ? 4 /* WebGPUConstants.TextureUsage.TextureBinding */ | 16 /* WebGPUConstants.TextureUsage.RenderAttachment */ + : -1; + gpuTextureWrapper.textureAdditionalUsages = isStorageTexture ? 8 /* WebGPUConstants.TextureUsage.StorageBinding */ : 0; + const hasMipMaps = texture.generateMipMaps; + const layerCount = depth || 1; + let mipmapCount; + if (texture._maxLodLevel !== null) { + mipmapCount = texture._maxLodLevel; + } + else { + mipmapCount = hasMipMaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(width, height) : 1; + } + if (texture.isCube) { + const gpuTexture = this.createCubeTexture({ width, height }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, gpuTextureWrapper.format, 1, this._commandEncoderForCreation, gpuTextureWrapper.textureUsages, gpuTextureWrapper.textureAdditionalUsages, texture.label); + gpuTextureWrapper.set(gpuTexture); + const arrayLayerCount = texture.is3D ? 1 : layerCount; + const format = WebGPUTextureHelper.GetDepthFormatOnly(gpuTextureWrapper.format); + const aspect = WebGPUTextureHelper.HasDepthAndStencilAspects(gpuTextureWrapper.format) ? "depth-only" /* WebGPUConstants.TextureAspect.DepthOnly */ : "all" /* WebGPUConstants.TextureAspect.All */; + const dimension = texture.is2DArray ? "cube-array" /* WebGPUConstants.TextureViewDimension.CubeArray */ : "cube" /* WebGPUConstants.TextureViewDimension.Cube */; + gpuTextureWrapper.createView({ + label: `BabylonWebGPUDevice${this._engine.uniqueId}_TextureViewCube${texture.is2DArray ? "_Array" + arrayLayerCount : ""}_${width}x${height}_${hasMipMaps ? "wmips" : "womips"}_${format}_${dimension}_${aspect}_${texture.label ?? "noname"}`, + format, + dimension, + mipLevelCount: mipmapCount, + baseArrayLayer: 0, + baseMipLevel: 0, + arrayLayerCount: 6, + aspect, + }, isStorageTexture); + } + else { + const gpuTexture = this.createTexture({ width, height, layers: layerCount }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, texture.is3D, gpuTextureWrapper.format, 1, this._commandEncoderForCreation, gpuTextureWrapper.textureUsages, gpuTextureWrapper.textureAdditionalUsages, texture.label); + gpuTextureWrapper.set(gpuTexture); + const arrayLayerCount = texture.is3D ? 1 : layerCount; + const format = WebGPUTextureHelper.GetDepthFormatOnly(gpuTextureWrapper.format); + const aspect = WebGPUTextureHelper.HasDepthAndStencilAspects(gpuTextureWrapper.format) ? "depth-only" /* WebGPUConstants.TextureAspect.DepthOnly */ : "all" /* WebGPUConstants.TextureAspect.All */; + const dimension = texture.is2DArray + ? "2d-array" /* WebGPUConstants.TextureViewDimension.E2dArray */ + : texture.is3D + ? "3d" /* WebGPUConstants.TextureDimension.E3d */ + : "2d" /* WebGPUConstants.TextureViewDimension.E2d */; + gpuTextureWrapper.createView({ + label: `BabylonWebGPUDevice${this._engine.uniqueId}_TextureView${texture.is3D ? "3D" : "2D"}${texture.is2DArray ? "_Array" + arrayLayerCount : ""}_${width}x${height}${texture.is3D ? "x" + layerCount : ""}_${hasMipMaps ? "wmips" : "womips"}_${format}_${dimension}_${aspect}_${texture.label ?? "noname"}`, + format, + dimension, + mipLevelCount: mipmapCount, + baseArrayLayer: 0, + baseMipLevel: 0, + arrayLayerCount, + aspect, + }, isStorageTexture); + } + texture.width = texture.baseWidth = width; + texture.height = texture.baseHeight = height; + texture.depth = texture.baseDepth = depth; + if (!dontCreateMSAATexture) { + this.createMSAATexture(texture, texture.samples); + } + return gpuTextureWrapper; + } + createMSAATexture(texture, samples, releaseExisting = true, index = 0) { + const gpuTextureWrapper = texture._hardwareTexture; + if (releaseExisting) { + gpuTextureWrapper?.releaseMSAATexture(); + } + if (!gpuTextureWrapper || (samples ?? 1) <= 1) { + return; + } + const width = texture.width; + const height = texture.height; + const gpuMSAATexture = this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, gpuTextureWrapper.format, samples, this._commandEncoderForCreation, 16 /* WebGPUConstants.TextureUsage.RenderAttachment */, 0, texture.label ? "MSAA_" + texture.label : "MSAA"); + gpuTextureWrapper.setMSAATexture(gpuMSAATexture, index); + } + //------------------------------------------------------------------------------ + // Update + //------------------------------------------------------------------------------ + updateCubeTextures(imageBitmaps, gpuTexture, width, height, format, invertY = false, premultiplyAlpha = false, offsetX = 0, offsetY = 0) { + const faces = [0, 3, 1, 4, 2, 5]; + for (let f = 0; f < faces.length; ++f) { + const imageBitmap = imageBitmaps[faces[f]]; + this.updateTexture(imageBitmap, gpuTexture, width, height, 1, format, f, 0, invertY, premultiplyAlpha, offsetX, offsetY); + } + } + // TODO WEBGPU handle data source not being in the same format than the destination texture? + updateTexture(imageBitmap, texture, width, height, layers, format, faceIndex = 0, mipLevel = 0, invertY = false, premultiplyAlpha = false, offsetX = 0, offsetY = 0, allowGPUOptimization) { + const gpuTexture = WebGPUTextureHelper.IsInternalTexture(texture) ? texture._hardwareTexture.underlyingResource : texture; + const blockInformation = WebGPUTextureHelper.GetBlockInformationFromFormat(format); + const gpuOrHdwTexture = WebGPUTextureHelper.IsInternalTexture(texture) ? texture._hardwareTexture : texture; + const textureCopyView = { + texture: gpuTexture, + origin: { + x: offsetX, + y: offsetY, + z: Math.max(faceIndex, 0), + }, + mipLevel: mipLevel, + premultipliedAlpha: premultiplyAlpha, + }; + const textureExtent = { + width: Math.ceil(width / blockInformation.width) * blockInformation.width, + height: Math.ceil(height / blockInformation.height) * blockInformation.height, + depthOrArrayLayers: layers || 1, + }; + if (imageBitmap.byteLength !== undefined) { + imageBitmap = imageBitmap; + const bytesPerRow = Math.ceil(width / blockInformation.width) * blockInformation.length; + const aligned = Math.ceil(bytesPerRow / 256) * 256 === bytesPerRow; + if (aligned) { + const commandEncoder = this._device.createCommandEncoder({}); + const buffer = this._bufferManager.createRawBuffer(imageBitmap.byteLength, BufferUsage.MapWrite | BufferUsage.CopySrc, true, "TempBufferForUpdateTexture" + (gpuTexture ? "_" + gpuTexture.label : "")); + const arrayBuffer = buffer.getMappedRange(); + new Uint8Array(arrayBuffer).set(imageBitmap); + buffer.unmap(); + commandEncoder.copyBufferToTexture({ + buffer: buffer, + offset: 0, + bytesPerRow, + rowsPerImage: height, + }, textureCopyView, textureExtent); + this._device.queue.submit([commandEncoder.finish()]); + this._bufferManager.releaseBuffer(buffer); + } + else { + this._device.queue.writeTexture(textureCopyView, imageBitmap, { + offset: 0, + bytesPerRow, + rowsPerImage: height, + }, textureExtent); + } + if (invertY || premultiplyAlpha) { + if (WebGPUTextureHelper.IsInternalTexture(texture)) { + const dontUseRect = offsetX === 0 && offsetY === 0 && width === texture.width && height === texture.height; + this.invertYPreMultiplyAlpha(gpuOrHdwTexture, texture.width, texture.height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, offsetX, offsetY, dontUseRect ? 0 : width, dontUseRect ? 0 : height, undefined, allowGPUOptimization); + } + else { + // we should never take this code path + // eslint-disable-next-line no-throw-literal + throw "updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!"; + } + } + } + else { + imageBitmap = imageBitmap; + this._device.queue.copyExternalImageToTexture({ source: imageBitmap, flipY: invertY }, textureCopyView, textureExtent); + } + } + readPixels(texture, x, y, width, height, format, faceIndex = 0, mipLevel = 0, buffer = null, noDataConversion = false) { + const blockInformation = WebGPUTextureHelper.GetBlockInformationFromFormat(format); + const bytesPerRow = Math.ceil(width / blockInformation.width) * blockInformation.length; + const bytesPerRowAligned = Math.ceil(bytesPerRow / 256) * 256; + const size = bytesPerRowAligned * height; + const gpuBuffer = this._bufferManager.createRawBuffer(size, BufferUsage.MapRead | BufferUsage.CopyDst, undefined, "TempBufferForReadPixels" + (texture.label ? "_" + texture.label : "")); + const commandEncoder = this._device.createCommandEncoder({}); + commandEncoder.copyTextureToBuffer({ + texture, + mipLevel, + origin: { + x, + y, + z: Math.max(faceIndex, 0), + }, + }, { + buffer: gpuBuffer, + offset: 0, + bytesPerRow: bytesPerRowAligned, + }, { + width, + height, + depthOrArrayLayers: 1, + }); + this._device.queue.submit([commandEncoder.finish()]); + return this._bufferManager.readDataFromBuffer(gpuBuffer, size, width, height, bytesPerRow, bytesPerRowAligned, WebGPUTextureHelper.GetTextureTypeFromFormat(format), 0, buffer, true, noDataConversion); + } + //------------------------------------------------------------------------------ + // Dispose + //------------------------------------------------------------------------------ + releaseTexture(texture) { + if (WebGPUTextureHelper.IsInternalTexture(texture)) { + const hardwareTexture = texture._hardwareTexture; + const irradianceTexture = texture._irradianceTexture; + // We can't destroy the objects just now because they could be used in the current frame - we delay the destroying after the end of the frame + this._deferredReleaseTextures.push([hardwareTexture, irradianceTexture]); + } + else { + this._deferredReleaseTextures.push([texture, null]); + } + } + destroyDeferredTextures() { + for (let i = 0; i < this._deferredReleaseTextures.length; ++i) { + const [hardwareTexture, irradianceTexture] = this._deferredReleaseTextures[i]; + if (hardwareTexture) { + if (WebGPUTextureHelper.IsHardwareTexture(hardwareTexture)) { + hardwareTexture.release(); + } + else { + hardwareTexture.destroy(); + } + } + irradianceTexture?.dispose(); + } + this._deferredReleaseTextures.length = 0; + } +} + +/** @internal */ +class WebGPUDataBuffer extends DataBuffer { + set buffer(buffer) { + this._buffer = buffer; + } + constructor(resource, capacity = 0) { + super(); + // Used to make sure the buffer is not recreated twice after a context loss/restoration + this.engineId = -1; + this.capacity = capacity; + if (resource) { + this._buffer = resource; + } + } + get underlyingResource() { + return this._buffer; + } +} + +/** @internal */ +class WebGPUBufferManager { + static _IsGPUBuffer(buffer) { + return buffer.underlyingResource === undefined; + } + static _FlagsToString(flags, suffix = "") { + let result = suffix; + for (let i = 0; i <= 9; ++i) { + if (flags & (1 << i)) { + if (result) { + result += "_"; + } + result += BufferUsage[1 << i]; + } + } + return result; + } + constructor(engine, device) { + this._deferredReleaseBuffers = []; + this._engine = engine; + this._device = device; + } + createRawBuffer(viewOrSize, flags, mappedAtCreation = false, label) { + const alignedLength = viewOrSize.byteLength !== undefined ? (viewOrSize.byteLength + 3) & -4 : (viewOrSize + 3) & -4; // 4 bytes alignments (because of the upload which requires this) + const verticesBufferDescriptor = { + label: "BabylonWebGPUDevice" + this._engine.uniqueId + "_" + WebGPUBufferManager._FlagsToString(flags, label ?? "Buffer") + "_size" + alignedLength, + mappedAtCreation, + size: alignedLength, + usage: flags, + }; + return this._device.createBuffer(verticesBufferDescriptor); + } + createBuffer(viewOrSize, flags, label) { + const isView = viewOrSize.byteLength !== undefined; + const dataBuffer = new WebGPUDataBuffer(); + const labelId = "DataBufferUniqueId=" + dataBuffer.uniqueId; + dataBuffer.buffer = this.createRawBuffer(viewOrSize, flags, undefined, label ? labelId + "-" + label : labelId); + dataBuffer.references = 1; + dataBuffer.capacity = isView ? viewOrSize.byteLength : viewOrSize; + dataBuffer.engineId = this._engine.uniqueId; + if (isView) { + this.setSubData(dataBuffer, 0, viewOrSize); + } + return dataBuffer; + } + // This calls GPUBuffer.writeBuffer() with no alignment corrections + // dstByteOffset and byteLength must both be aligned to 4 bytes and bytes moved must be within src and dst arrays + setRawData(buffer, dstByteOffset, src, srcByteOffset, byteLength) { + srcByteOffset += src.byteOffset; + this._device.queue.writeBuffer(buffer, dstByteOffset, src.buffer, srcByteOffset, byteLength); + } + // This calls GPUBuffer.writeBuffer() with alignment corrections (dstByteOffset and byteLength will be aligned to 4 byte boundaries) + // If alignment is needed, src must be a full copy of dataBuffer, or at least should be large enough to cope with the additional bytes copied because of alignment! + setSubData(dataBuffer, dstByteOffset, src, srcByteOffset = 0, byteLength = 0) { + const buffer = dataBuffer.underlyingResource; + byteLength = byteLength || src.byteLength - srcByteOffset; + // Make sure the dst offset is aligned to 4 bytes + const startPre = dstByteOffset & 3; + srcByteOffset -= startPre; + dstByteOffset -= startPre; + // Make sure the byte length is aligned to 4 bytes + const originalByteLength = byteLength; + byteLength = (byteLength + startPre + 3) & -4; + // Check if the backing buffer of src is large enough to cope with the additional bytes copied because of alignment + const backingBufferSize = src.buffer.byteLength - src.byteOffset; + if (backingBufferSize < byteLength) { + // Not enough place in the backing buffer for the aligned copy. + // Creates a new buffer and copy the source data to it. + // The buffer will have byteLength - originalByteLength zeros at the end. + const tmpBuffer = new Uint8Array(byteLength); + tmpBuffer.set(new Uint8Array(src.buffer, src.byteOffset + srcByteOffset, originalByteLength)); + src = tmpBuffer; + srcByteOffset = 0; + } + this.setRawData(buffer, dstByteOffset, src, srcByteOffset, byteLength); + } + _getHalfFloatAsFloatRGBAArrayBuffer(dataLength, arrayBuffer, destArray) { + if (!destArray) { + destArray = new Float32Array(dataLength); + } + const srcData = new Uint16Array(arrayBuffer); + while (dataLength--) { + destArray[dataLength] = FromHalfFloat(srcData[dataLength]); + } + return destArray; + } + readDataFromBuffer(gpuBuffer, size, width, height, bytesPerRow, bytesPerRowAligned, type = 0, offset = 0, buffer = null, destroyBuffer = true, noDataConversion = false) { + const floatFormat = type === 1 ? 2 : type === 2 ? 1 : 0; + const engineId = this._engine.uniqueId; + return new Promise((resolve, reject) => { + gpuBuffer.mapAsync(1 /* WebGPUConstants.MapMode.Read */, offset, size).then(() => { + const copyArrayBuffer = gpuBuffer.getMappedRange(offset, size); + let data = buffer; + if (noDataConversion) { + if (data === null) { + data = allocateAndCopyTypedBuffer(type, size, true, copyArrayBuffer); + } + else { + data = allocateAndCopyTypedBuffer(type, data.buffer, undefined, copyArrayBuffer); + } + } + else { + if (data === null) { + switch (floatFormat) { + case 0: // byte format + data = new Uint8Array(size); + data.set(new Uint8Array(copyArrayBuffer)); + break; + case 1: // half float + // TODO WEBGPU use computer shaders (or render pass) to make the conversion? + data = this._getHalfFloatAsFloatRGBAArrayBuffer(size / 2, copyArrayBuffer); + break; + case 2: // float + data = new Float32Array(size / 4); + data.set(new Float32Array(copyArrayBuffer)); + break; + } + } + else { + switch (floatFormat) { + case 0: // byte format + data = new Uint8Array(data.buffer); + data.set(new Uint8Array(copyArrayBuffer)); + break; + case 1: // half float + // TODO WEBGPU use computer shaders (or render pass) to make the conversion? + data = this._getHalfFloatAsFloatRGBAArrayBuffer(size / 2, copyArrayBuffer, buffer); + break; + case 2: // float + data = new Float32Array(data.buffer); + data.set(new Float32Array(copyArrayBuffer)); + break; + } + } + } + if (bytesPerRow !== bytesPerRowAligned) { + // TODO WEBGPU use computer shaders (or render pass) to build the final buffer data? + if (floatFormat === 1 && !noDataConversion) { + // half float have been converted to float above + bytesPerRow *= 2; + bytesPerRowAligned *= 2; + } + const data2 = new Uint8Array(data.buffer); + let offset = bytesPerRow, offset2 = 0; + for (let y = 1; y < height; ++y) { + offset2 = y * bytesPerRowAligned; + for (let x = 0; x < bytesPerRow; ++x) { + data2[offset++] = data2[offset2++]; + } + } + if (floatFormat !== 0 && !noDataConversion) { + data = new Float32Array(data2.buffer, 0, offset / 4); + } + else { + data = new Uint8Array(data2.buffer, 0, offset); + } + } + gpuBuffer.unmap(); + if (destroyBuffer) { + this.releaseBuffer(gpuBuffer); + } + resolve(data); + }, (reason) => { + if (this._engine.isDisposed || this._engine.uniqueId !== engineId) { + // The engine was disposed while waiting for the promise, or a context loss/restoration has occurred: don't reject + resolve(new Uint8Array()); + } + else { + reject(reason); + } + }); + }); + } + releaseBuffer(buffer) { + if (WebGPUBufferManager._IsGPUBuffer(buffer)) { + this._deferredReleaseBuffers.push(buffer); + return true; + } + buffer.references--; + if (buffer.references === 0) { + this._deferredReleaseBuffers.push(buffer.underlyingResource); + return true; + } + return false; + } + destroyDeferredBuffers() { + for (let i = 0; i < this._deferredReleaseBuffers.length; ++i) { + this._deferredReleaseBuffers[i].destroy(); + } + this._deferredReleaseBuffers.length = 0; + } +} + +const filterToBits = [ + 0 | (0 << 1) | (0 << 2), // not used + 0 | (0 << 1) | (0 << 2), // TEXTURE_NEAREST_SAMPLINGMODE / TEXTURE_NEAREST_NEAREST + 1 | (1 << 1) | (0 << 2), // TEXTURE_BILINEAR_SAMPLINGMODE / TEXTURE_LINEAR_LINEAR + 1 | (1 << 1) | (1 << 2), // TEXTURE_TRILINEAR_SAMPLINGMODE / TEXTURE_LINEAR_LINEAR_MIPLINEAR + 0 | (0 << 1) | (0 << 2), // TEXTURE_NEAREST_NEAREST_MIPNEAREST + 0 | (1 << 1) | (0 << 2), // TEXTURE_NEAREST_LINEAR_MIPNEAREST + 0 | (1 << 1) | (1 << 2), // TEXTURE_NEAREST_LINEAR_MIPLINEAR + 0 | (1 << 1) | (0 << 2), // TEXTURE_NEAREST_LINEAR + 0 | (0 << 1) | (1 << 2), // TEXTURE_NEAREST_NEAREST_MIPLINEAR + 1 | (0 << 1) | (0 << 2), // TEXTURE_LINEAR_NEAREST_MIPNEAREST + 1 | (0 << 1) | (1 << 2), // TEXTURE_LINEAR_NEAREST_MIPLINEAR + 1 | (1 << 1) | (0 << 2), // TEXTURE_LINEAR_LINEAR_MIPNEAREST + 1 | (0 << 1) | (0 << 2), // TEXTURE_LINEAR_NEAREST +]; +// subtract 0x01FF from the comparison function value before indexing this array! +const comparisonFunctionToBits = [ + (0 << 3) | (0 << 4) | (0 << 5) | (0 << 6), // undefined + (0 << 3) | (0 << 4) | (0 << 5) | (1 << 6), // NEVER + (0 << 3) | (0 << 4) | (1 << 5) | (0 << 6), // LESS + (0 << 3) | (0 << 4) | (1 << 5) | (1 << 6), // EQUAL + (0 << 3) | (1 << 4) | (0 << 5) | (0 << 6), // LEQUAL + (0 << 3) | (1 << 4) | (0 << 5) | (1 << 6), // GREATER + (0 << 3) | (1 << 4) | (1 << 5) | (0 << 6), // NOTEQUAL + (0 << 3) | (1 << 4) | (1 << 5) | (1 << 6), // GEQUAL + (1 << 3) | (0 << 4) | (0 << 5) | (0 << 6), // ALWAYS +]; +const filterNoMipToBits = [ + 0 << 7, // not used + 1 << 7, // TEXTURE_NEAREST_SAMPLINGMODE / TEXTURE_NEAREST_NEAREST + 1 << 7, // TEXTURE_BILINEAR_SAMPLINGMODE / TEXTURE_LINEAR_LINEAR + 0 << 7, // TEXTURE_TRILINEAR_SAMPLINGMODE / TEXTURE_LINEAR_LINEAR_MIPLINEAR + 0 << 7, // TEXTURE_NEAREST_NEAREST_MIPNEAREST + 0 << 7, // TEXTURE_NEAREST_LINEAR_MIPNEAREST + 0 << 7, // TEXTURE_NEAREST_LINEAR_MIPLINEAR + 1 << 7, // TEXTURE_NEAREST_LINEAR + 0 << 7, // TEXTURE_NEAREST_NEAREST_MIPLINEAR + 0 << 7, // TEXTURE_LINEAR_NEAREST_MIPNEAREST + 0 << 7, // TEXTURE_LINEAR_NEAREST_MIPLINEAR + 0 << 7, // TEXTURE_LINEAR_LINEAR_MIPNEAREST + 1 << 7, // TEXTURE_LINEAR_NEAREST +]; +/** @internal */ +class WebGPUCacheSampler { + constructor(device) { + this._samplers = {}; + this._device = device; + this.disabled = false; + } + static GetSamplerHashCode(sampler) { + // The WebGPU spec currently only allows values 1 and 4 for anisotropy + const anisotropy = sampler._cachedAnisotropicFilteringLevel ? sampler._cachedAnisotropicFilteringLevel : 1; + const code = filterToBits[sampler.samplingMode] + + comparisonFunctionToBits[(sampler._comparisonFunction || 0x0202) - 0x0200 + 1] + + filterNoMipToBits[sampler.samplingMode] + // handle the lodMinClamp = lodMaxClamp = 0 case when no filter used for mip mapping + ((sampler._cachedWrapU ?? 1) << 8) + + ((sampler._cachedWrapV ?? 1) << 10) + + ((sampler._cachedWrapR ?? 1) << 12) + + ((sampler.useMipMaps ? 1 : 0) << 14) + // need to factor this in because _getSamplerFilterDescriptor depends on samplingMode AND useMipMaps! + (anisotropy << 15); + return code; + } + static _GetSamplerFilterDescriptor(sampler, anisotropy) { + let magFilter, minFilter, mipmapFilter, lodMinClamp, lodMaxClamp; + const useMipMaps = sampler.useMipMaps; + switch (sampler.samplingMode) { + case 11: + magFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + minFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + if (!useMipMaps) { + lodMinClamp = lodMaxClamp = 0; + } + break; + case 3: + case 3: + magFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + minFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + if (!useMipMaps) { + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + lodMinClamp = lodMaxClamp = 0; + } + else { + mipmapFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + } + break; + case 8: + magFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + minFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + if (!useMipMaps) { + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + lodMinClamp = lodMaxClamp = 0; + } + else { + mipmapFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + } + break; + case 4: + magFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + minFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + if (!useMipMaps) { + lodMinClamp = lodMaxClamp = 0; + } + break; + case 5: + magFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + minFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + if (!useMipMaps) { + lodMinClamp = lodMaxClamp = 0; + } + break; + case 6: + magFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + minFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + if (!useMipMaps) { + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + lodMinClamp = lodMaxClamp = 0; + } + else { + mipmapFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + } + break; + case 7: + magFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + minFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + lodMinClamp = lodMaxClamp = 0; + break; + case 1: + case 1: + magFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + minFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + lodMinClamp = lodMaxClamp = 0; + break; + case 9: + magFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + minFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + if (!useMipMaps) { + lodMinClamp = lodMaxClamp = 0; + } + break; + case 10: + magFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + minFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + if (!useMipMaps) { + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + lodMinClamp = lodMaxClamp = 0; + } + else { + mipmapFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + } + break; + case 2: + case 2: + magFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + minFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + // In WebGL, if sampling mode is TEXTURE_BILINEAR_SAMPLINGMODE and anisotropy is greater than 1, anisotropy is enabled for the sampler + if (anisotropy > 1) { + mipmapFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + } + else { + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + lodMinClamp = lodMaxClamp = 0; + } + break; + case 12: + magFilter = "linear" /* WebGPUConstants.FilterMode.Linear */; + minFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + lodMinClamp = lodMaxClamp = 0; + break; + default: + magFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + minFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + mipmapFilter = "nearest" /* WebGPUConstants.FilterMode.Nearest */; + lodMinClamp = lodMaxClamp = 0; + break; + } + if (anisotropy > 1 && (lodMinClamp !== 0 || lodMaxClamp !== 0)) { + return { + magFilter: "linear" /* WebGPUConstants.FilterMode.Linear */, + minFilter: "linear" /* WebGPUConstants.FilterMode.Linear */, + mipmapFilter: "linear" /* WebGPUConstants.FilterMode.Linear */, + anisotropyEnabled: true, + }; + } + return { + magFilter, + minFilter, + mipmapFilter, + lodMinClamp, + lodMaxClamp, + }; + } + static _GetWrappingMode(mode) { + switch (mode) { + case 1: + return "repeat" /* WebGPUConstants.AddressMode.Repeat */; + case 0: + return "clamp-to-edge" /* WebGPUConstants.AddressMode.ClampToEdge */; + case 2: + return "mirror-repeat" /* WebGPUConstants.AddressMode.MirrorRepeat */; + } + return "repeat" /* WebGPUConstants.AddressMode.Repeat */; + } + static _GetSamplerWrappingDescriptor(sampler) { + return { + addressModeU: this._GetWrappingMode(sampler._cachedWrapU), + addressModeV: this._GetWrappingMode(sampler._cachedWrapV), + addressModeW: this._GetWrappingMode(sampler._cachedWrapR), + }; + } + static _GetSamplerDescriptor(sampler, label) { + // The check with 2 is to be iso with the WebGL implementation + let anisotropy = (sampler.useMipMaps || sampler.samplingMode === 2) && sampler._cachedAnisotropicFilteringLevel + ? sampler._cachedAnisotropicFilteringLevel + : 1; + // To be iso with the WebGL implementation + if (sampler.samplingMode !== 11 && + sampler.samplingMode !== 3 && + sampler.samplingMode !== 2) { + anisotropy = 1; + } + const filterDescriptor = this._GetSamplerFilterDescriptor(sampler, anisotropy); + return { + label, + ...filterDescriptor, + ...this._GetSamplerWrappingDescriptor(sampler), + compare: sampler._comparisonFunction ? WebGPUCacheSampler.GetCompareFunction(sampler._comparisonFunction) : undefined, + maxAnisotropy: filterDescriptor.anisotropyEnabled ? anisotropy : 1, + }; + } + static GetCompareFunction(compareFunction) { + switch (compareFunction) { + case 519: + return "always" /* WebGPUConstants.CompareFunction.Always */; + case 514: + return "equal" /* WebGPUConstants.CompareFunction.Equal */; + case 516: + return "greater" /* WebGPUConstants.CompareFunction.Greater */; + case 518: + return "greater-equal" /* WebGPUConstants.CompareFunction.GreaterEqual */; + case 513: + return "less" /* WebGPUConstants.CompareFunction.Less */; + case 515: + return "less-equal" /* WebGPUConstants.CompareFunction.LessEqual */; + case 512: + return "never" /* WebGPUConstants.CompareFunction.Never */; + case 517: + return "not-equal" /* WebGPUConstants.CompareFunction.NotEqual */; + default: + return "less" /* WebGPUConstants.CompareFunction.Less */; + } + } + getSampler(sampler, bypassCache = false, hash = 0, label) { + if (this.disabled) { + return this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(sampler, label)); + } + if (bypassCache) { + hash = 0; + } + else if (hash === 0) { + hash = WebGPUCacheSampler.GetSamplerHashCode(sampler); + } + let gpuSampler = bypassCache ? undefined : this._samplers[hash]; + if (!gpuSampler) { + gpuSampler = this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(sampler, label)); + if (!bypassCache) { + this._samplers[hash] = gpuSampler; + } + } + return gpuSampler; + } +} + +/* eslint-disable @typescript-eslint/naming-convention */ +/* eslint-disable babylonjs/available */ +/* eslint-disable jsdoc/require-jsdoc */ + +var StatePosition; +(function (StatePosition) { + StatePosition[StatePosition["StencilReadMask"] = 0] = "StencilReadMask"; + StatePosition[StatePosition["StencilWriteMask"] = 1] = "StencilWriteMask"; + //DepthBiasClamp = 1, // not used, so remove it to improve perf + StatePosition[StatePosition["DepthBias"] = 2] = "DepthBias"; + StatePosition[StatePosition["DepthBiasSlopeScale"] = 3] = "DepthBiasSlopeScale"; + StatePosition[StatePosition["DepthStencilState"] = 4] = "DepthStencilState"; + StatePosition[StatePosition["MRTAttachments1"] = 5] = "MRTAttachments1"; + StatePosition[StatePosition["MRTAttachments2"] = 6] = "MRTAttachments2"; + StatePosition[StatePosition["RasterizationState"] = 7] = "RasterizationState"; + StatePosition[StatePosition["ColorStates"] = 8] = "ColorStates"; + StatePosition[StatePosition["ShaderStage"] = 9] = "ShaderStage"; + StatePosition[StatePosition["TextureStage"] = 10] = "TextureStage"; + StatePosition[StatePosition["VertexState"] = 11] = "VertexState"; + StatePosition[StatePosition["NumStates"] = 12] = "NumStates"; +})(StatePosition || (StatePosition = {})); +const alphaBlendFactorToIndex = { + 0: 1, // Zero + 1: 2, // One + 0x0300: 3, // SrcColor + 0x0301: 4, // OneMinusSrcColor + 0x0302: 5, // SrcAlpha + 0x0303: 6, // OneMinusSrcAlpha + 0x0304: 7, // DstAlpha + 0x0305: 8, // OneMinusDstAlpha + 0x0306: 9, // DstColor + 0x0307: 10, // OneMinusDstColor + 0x0308: 11, // SrcAlphaSaturated + 0x8001: 12, // BlendColor + 0x8002: 13, // OneMinusBlendColor + 0x8003: 12, // BlendColor (alpha) + 0x8004: 13, // OneMinusBlendColor (alpha) +}; +const stencilOpToIndex = { + 0x0000: 0, // ZERO + 0x1e00: 1, // KEEP + 0x1e01: 2, // REPLACE + 0x1e02: 3, // INCR + 0x1e03: 4, // DECR + 0x150a: 5, // INVERT + 0x8507: 6, // INCR_WRAP + 0x8508: 7, // DECR_WRAP +}; +/** @internal */ +class WebGPUCacheRenderPipeline { + constructor(device, emptyVertexBuffer) { + this.mrtTextureCount = 0; + this._device = device; + this._useTextureStage = true; // we force usage because we must handle depth textures with "float" filtering, which can't be fixed by a caps (like "textureFloatLinearFiltering" can for float textures) + this._states = new Array(30); // pre-allocate enough room so that no new allocation will take place afterwards + this._statesLength = 0; + this._stateDirtyLowestIndex = 0; + this._emptyVertexBuffer = emptyVertexBuffer; + this._mrtFormats = []; + this._parameter = { token: undefined, pipeline: null }; + this.disabled = false; + this.vertexBuffers = []; + this._kMaxVertexBufferStride = device.limits.maxVertexBufferArrayStride || 2048; + this.reset(); + } + reset() { + this._isDirty = true; + this.vertexBuffers.length = 0; + this.setAlphaToCoverage(false); + this.resetDepthCullingState(); + this.setClampDepth(false); + this.setDepthBias(0); + //this.setDepthBiasClamp(0); + this._webgpuColorFormat = ["bgra8unorm" /* WebGPUConstants.TextureFormat.BGRA8Unorm */]; + this.setColorFormat("bgra8unorm" /* WebGPUConstants.TextureFormat.BGRA8Unorm */); + this.setMRT([]); + this.setAlphaBlendEnabled(false); + this.setAlphaBlendFactors([null, null, null, null], [null, null]); + this.setWriteMask(0xf); + this.setDepthStencilFormat("depth24plus-stencil8" /* WebGPUConstants.TextureFormat.Depth24PlusStencil8 */); + this.setStencilEnabled(false); + this.resetStencilState(); + this.setBuffers(null, null, null); + this._setTextureState(0); + } + get colorFormats() { + return this._mrtAttachments1 > 0 ? this._mrtFormats : this._webgpuColorFormat; + } + getRenderPipeline(fillMode, effect, sampleCount, textureState = 0) { + sampleCount = WebGPUTextureHelper.GetSample(sampleCount); + if (this.disabled) { + const topology = WebGPUCacheRenderPipeline._GetTopology(fillMode); + this._setVertexState(effect); // to fill this.vertexBuffers with correct data + this._setTextureState(textureState); + this._parameter.pipeline = this._createRenderPipeline(effect, topology, sampleCount); + WebGPUCacheRenderPipeline.NumCacheMiss++; + WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++; + return this._parameter.pipeline; + } + this._setShaderStage(effect.uniqueId); + this._setRasterizationState(fillMode, sampleCount); + this._setColorStates(); + this._setDepthStencilState(); + this._setVertexState(effect); + this._setTextureState(textureState); + this.lastStateDirtyLowestIndex = this._stateDirtyLowestIndex; + if (!this._isDirty && this._parameter.pipeline) { + this._stateDirtyLowestIndex = this._statesLength; + WebGPUCacheRenderPipeline.NumCacheHitWithoutHash++; + return this._parameter.pipeline; + } + this._getRenderPipeline(this._parameter); + this._isDirty = false; + this._stateDirtyLowestIndex = this._statesLength; + if (this._parameter.pipeline) { + WebGPUCacheRenderPipeline.NumCacheHitWithHash++; + return this._parameter.pipeline; + } + const topology = WebGPUCacheRenderPipeline._GetTopology(fillMode); + this._parameter.pipeline = this._createRenderPipeline(effect, topology, sampleCount); + this._setRenderPipeline(this._parameter); + WebGPUCacheRenderPipeline.NumCacheMiss++; + WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++; + return this._parameter.pipeline; + } + endFrame() { + WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame = WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame; + WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame = 0; + } + setAlphaToCoverage(enabled) { + this._alphaToCoverageEnabled = enabled; + } + setFrontFace(frontFace) { + this._frontFace = frontFace; + } + setCullEnabled(enabled) { + this._cullEnabled = enabled; + } + setCullFace(cullFace) { + this._cullFace = cullFace; + } + setClampDepth(clampDepth) { + this._clampDepth = clampDepth; + } + resetDepthCullingState() { + this.setDepthCullingState(false, 2, 1, 0, 0, true, true, 519); + } + setDepthCullingState(cullEnabled, frontFace, cullFace, zOffset, zOffsetUnits, depthTestEnabled, depthWriteEnabled, depthCompare) { + this._depthWriteEnabled = depthWriteEnabled; + this._depthTestEnabled = depthTestEnabled; + this._depthCompare = (depthCompare ?? 519) - 0x0200; + this._cullFace = cullFace; + this._cullEnabled = cullEnabled; + this._frontFace = frontFace; + this.setDepthBiasSlopeScale(zOffset); + this.setDepthBias(zOffsetUnits); + } + setDepthBias(depthBias) { + if (this._depthBias !== depthBias) { + this._depthBias = depthBias; + this._states[StatePosition.DepthBias] = depthBias; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBias); + } + } + /*public setDepthBiasClamp(depthBiasClamp: number): void { + if (this._depthBiasClamp !== depthBiasClamp) { + this._depthBiasClamp = depthBiasClamp; + this._states[StatePosition.DepthBiasClamp] = depthBiasClamp.toString(); + this._isDirty = true; + } + }*/ + setDepthBiasSlopeScale(depthBiasSlopeScale) { + if (this._depthBiasSlopeScale !== depthBiasSlopeScale) { + this._depthBiasSlopeScale = depthBiasSlopeScale; + this._states[StatePosition.DepthBiasSlopeScale] = depthBiasSlopeScale; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBiasSlopeScale); + } + } + setColorFormat(format) { + this._webgpuColorFormat[0] = format; + this._colorFormat = renderableTextureFormatToIndex[format ?? ""]; + } + setMRTAttachments(attachments) { + this.mrtAttachments = attachments; + let mask = 0; + for (let i = 0; i < attachments.length; ++i) { + if (attachments[i] !== 0) { + mask += 1 << i; + } + } + if (this._mrtEnabledMask !== mask) { + this._mrtEnabledMask = mask; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1); + } + } + setMRT(textureArray, textureCount) { + textureCount = textureCount ?? textureArray.length; + if (textureCount > 10) { + // If we want more than 10 attachments we need to change this method (and the StatePosition enum) but 10 seems plenty: note that WebGPU only supports 8 at the time (2021/12/13)! + // As we need ~39 different values we are using 6 bits to encode a texture format, meaning we can encode 5 texture formats in 32 bits + // We are using 2x32 bit values to handle 10 textures + // eslint-disable-next-line no-throw-literal + throw "Can't handle more than 10 attachments for a MRT in cache render pipeline!"; + } + this.mrtTextureArray = textureArray; + this.mrtTextureCount = textureCount; + this._mrtEnabledMask = 0xffff; // all textures are enabled at start (meaning we can write to them). Calls to setMRTAttachments may disable some + const bits = [0, 0]; + let indexBits = 0, mask = 0, numRT = 0; + for (let i = 0; i < textureCount; ++i) { + const texture = textureArray[i]; + const gpuWrapper = texture?._hardwareTexture; + this._mrtFormats[numRT] = gpuWrapper?.format ?? this._webgpuColorFormat[0]; + bits[indexBits] += renderableTextureFormatToIndex[this._mrtFormats[numRT] ?? ""] << mask; + mask += 6; + numRT++; + if (mask >= 32) { + mask = 0; + indexBits++; + } + } + this._mrtFormats.length = numRT; + if (this._mrtAttachments1 !== bits[0] || this._mrtAttachments2 !== bits[1]) { + this._mrtAttachments1 = bits[0]; + this._mrtAttachments2 = bits[1]; + this._states[StatePosition.MRTAttachments1] = bits[0]; + this._states[StatePosition.MRTAttachments2] = bits[1]; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1); + } + } + setAlphaBlendEnabled(enabled) { + this._alphaBlendEnabled = enabled; + } + setAlphaBlendFactors(factors, operations) { + this._alphaBlendFuncParams = factors; + this._alphaBlendEqParams = operations; + } + setWriteMask(mask) { + this._writeMask = mask; + } + setDepthStencilFormat(format) { + this._webgpuDepthStencilFormat = format; + this._depthStencilFormat = format === undefined ? 0 : renderableTextureFormatToIndex[format]; + } + setDepthTestEnabled(enabled) { + this._depthTestEnabled = enabled; + } + setDepthWriteEnabled(enabled) { + this._depthWriteEnabled = enabled; + } + setDepthCompare(func) { + this._depthCompare = (func ?? 519) - 0x0200; + } + setStencilEnabled(enabled) { + this._stencilEnabled = enabled; + } + setStencilCompare(func) { + this._stencilFrontCompare = (func ?? 519) - 0x0200; + } + setStencilDepthFailOp(op) { + this._stencilFrontDepthFailOp = op === null ? 1 /* KEEP */ : stencilOpToIndex[op]; + } + setStencilPassOp(op) { + this._stencilFrontPassOp = op === null ? 2 /* REPLACE */ : stencilOpToIndex[op]; + } + setStencilFailOp(op) { + this._stencilFrontFailOp = op === null ? 1 /* KEEP */ : stencilOpToIndex[op]; + } + setStencilReadMask(mask) { + if (this._stencilReadMask !== mask) { + this._stencilReadMask = mask; + this._states[StatePosition.StencilReadMask] = mask; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilReadMask); + } + } + setStencilWriteMask(mask) { + if (this._stencilWriteMask !== mask) { + this._stencilWriteMask = mask; + this._states[StatePosition.StencilWriteMask] = mask; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilWriteMask); + } + } + resetStencilState() { + this.setStencilState(false, 519, 7680, 7681, 7680, 0xff, 0xff); + } + setStencilState(stencilEnabled, compare, depthFailOp, passOp, failOp, readMask, writeMask) { + this._stencilEnabled = stencilEnabled; + this._stencilFrontCompare = (compare ?? 519) - 0x0200; + this._stencilFrontDepthFailOp = depthFailOp === null ? 1 /* KEEP */ : stencilOpToIndex[depthFailOp]; + this._stencilFrontPassOp = passOp === null ? 2 /* REPLACE */ : stencilOpToIndex[passOp]; + this._stencilFrontFailOp = failOp === null ? 1 /* KEEP */ : stencilOpToIndex[failOp]; + this.setStencilReadMask(readMask); + this.setStencilWriteMask(writeMask); + } + setBuffers(vertexBuffers, indexBuffer, overrideVertexBuffers) { + this._vertexBuffers = vertexBuffers; + this._overrideVertexBuffers = overrideVertexBuffers; + this._indexBuffer = indexBuffer; + } + static _GetTopology(fillMode) { + switch (fillMode) { + // Triangle views + case 0: + return "triangle-list" /* WebGPUConstants.PrimitiveTopology.TriangleList */; + case 2: + return "point-list" /* WebGPUConstants.PrimitiveTopology.PointList */; + case 1: + return "line-list" /* WebGPUConstants.PrimitiveTopology.LineList */; + // Draw modes + case 3: + return "point-list" /* WebGPUConstants.PrimitiveTopology.PointList */; + case 4: + return "line-list" /* WebGPUConstants.PrimitiveTopology.LineList */; + case 5: + // return this._gl.LINE_LOOP; + // TODO WEBGPU. Line Loop Mode Fallback at buffer load time. + // eslint-disable-next-line no-throw-literal + throw "LineLoop is an unsupported fillmode in WebGPU"; + case 6: + return "line-strip" /* WebGPUConstants.PrimitiveTopology.LineStrip */; + case 7: + return "triangle-strip" /* WebGPUConstants.PrimitiveTopology.TriangleStrip */; + case 8: + // return this._gl.TRIANGLE_FAN; + // TODO WEBGPU. Triangle Fan Mode Fallback at buffer load time. + // eslint-disable-next-line no-throw-literal + throw "TriangleFan is an unsupported fillmode in WebGPU"; + default: + return "triangle-list" /* WebGPUConstants.PrimitiveTopology.TriangleList */; + } + } + static _GetAphaBlendOperation(operation) { + switch (operation) { + case 32774: + return "add" /* WebGPUConstants.BlendOperation.Add */; + case 32778: + return "subtract" /* WebGPUConstants.BlendOperation.Subtract */; + case 32779: + return "reverse-subtract" /* WebGPUConstants.BlendOperation.ReverseSubtract */; + case 32775: + return "min" /* WebGPUConstants.BlendOperation.Min */; + case 32776: + return "max" /* WebGPUConstants.BlendOperation.Max */; + default: + return "add" /* WebGPUConstants.BlendOperation.Add */; + } + } + static _GetAphaBlendFactor(factor) { + switch (factor) { + case 0: + return "zero" /* WebGPUConstants.BlendFactor.Zero */; + case 1: + return "one" /* WebGPUConstants.BlendFactor.One */; + case 768: + return "src" /* WebGPUConstants.BlendFactor.Src */; + case 769: + return "one-minus-src" /* WebGPUConstants.BlendFactor.OneMinusSrc */; + case 770: + return "src-alpha" /* WebGPUConstants.BlendFactor.SrcAlpha */; + case 771: + return "one-minus-src-alpha" /* WebGPUConstants.BlendFactor.OneMinusSrcAlpha */; + case 772: + return "dst-alpha" /* WebGPUConstants.BlendFactor.DstAlpha */; + case 773: + return "one-minus-dst-alpha" /* WebGPUConstants.BlendFactor.OneMinusDstAlpha */; + case 774: + return "dst" /* WebGPUConstants.BlendFactor.Dst */; + case 775: + return "one-minus-dst" /* WebGPUConstants.BlendFactor.OneMinusDst */; + case 776: + return "src-alpha-saturated" /* WebGPUConstants.BlendFactor.SrcAlphaSaturated */; + case 32769: + return "constant" /* WebGPUConstants.BlendFactor.Constant */; + case 32770: + return "one-minus-constant" /* WebGPUConstants.BlendFactor.OneMinusConstant */; + case 32771: + return "constant" /* WebGPUConstants.BlendFactor.Constant */; + case 32772: + return "one-minus-constant" /* WebGPUConstants.BlendFactor.OneMinusConstant */; + case 35065: + return "src1" /* WebGPUConstants.BlendFactor.Src1 */; + case 35066: + return "one-minus-src1" /* WebGPUConstants.BlendFactor.OneMinusSrc1 */; + case 34185: + return "src1-alpha" /* WebGPUConstants.BlendFactor.Src1Alpha */; + case 35067: + return "one-minus-src1-alpha" /* WebGPUConstants.BlendFactor.OneMinusSrc1Alpha */; + default: + return "one" /* WebGPUConstants.BlendFactor.One */; + } + } + static _GetCompareFunction(compareFunction) { + switch (compareFunction) { + case 0: // NEVER + return "never" /* WebGPUConstants.CompareFunction.Never */; + case 1: // LESS + return "less" /* WebGPUConstants.CompareFunction.Less */; + case 2: // EQUAL + return "equal" /* WebGPUConstants.CompareFunction.Equal */; + case 3: // LEQUAL + return "less-equal" /* WebGPUConstants.CompareFunction.LessEqual */; + case 4: // GREATER + return "greater" /* WebGPUConstants.CompareFunction.Greater */; + case 5: // NOTEQUAL + return "not-equal" /* WebGPUConstants.CompareFunction.NotEqual */; + case 6: // GEQUAL + return "greater-equal" /* WebGPUConstants.CompareFunction.GreaterEqual */; + case 7: // ALWAYS + return "always" /* WebGPUConstants.CompareFunction.Always */; + } + return "never" /* WebGPUConstants.CompareFunction.Never */; + } + static _GetStencilOpFunction(operation) { + switch (operation) { + case 0: + return "zero" /* WebGPUConstants.StencilOperation.Zero */; + case 1: + return "keep" /* WebGPUConstants.StencilOperation.Keep */; + case 2: + return "replace" /* WebGPUConstants.StencilOperation.Replace */; + case 3: + return "increment-clamp" /* WebGPUConstants.StencilOperation.IncrementClamp */; + case 4: + return "decrement-clamp" /* WebGPUConstants.StencilOperation.DecrementClamp */; + case 5: + return "invert" /* WebGPUConstants.StencilOperation.Invert */; + case 6: + return "increment-wrap" /* WebGPUConstants.StencilOperation.IncrementWrap */; + case 7: + return "decrement-wrap" /* WebGPUConstants.StencilOperation.DecrementWrap */; + } + return "keep" /* WebGPUConstants.StencilOperation.Keep */; + } + static _GetVertexInputDescriptorFormat(vertexBuffer) { + const type = vertexBuffer.type; + const normalized = vertexBuffer.normalized; + const size = vertexBuffer.getSize(); + switch (type) { + case VertexBuffer.BYTE: + switch (size) { + case 1: + case 2: + return normalized ? "snorm8x2" /* WebGPUConstants.VertexFormat.Snorm8x2 */ : "sint8x2" /* WebGPUConstants.VertexFormat.Sint8x2 */; + case 3: + case 4: + return normalized ? "snorm8x4" /* WebGPUConstants.VertexFormat.Snorm8x4 */ : "sint8x4" /* WebGPUConstants.VertexFormat.Sint8x4 */; + } + break; + case VertexBuffer.UNSIGNED_BYTE: + switch (size) { + case 1: + case 2: + return normalized ? "unorm8x2" /* WebGPUConstants.VertexFormat.Unorm8x2 */ : "uint8x2" /* WebGPUConstants.VertexFormat.Uint8x2 */; + case 3: + case 4: + return normalized ? "unorm8x4" /* WebGPUConstants.VertexFormat.Unorm8x4 */ : "uint8x4" /* WebGPUConstants.VertexFormat.Uint8x4 */; + } + break; + case VertexBuffer.SHORT: + switch (size) { + case 1: + case 2: + return normalized ? "snorm16x2" /* WebGPUConstants.VertexFormat.Snorm16x2 */ : "sint16x2" /* WebGPUConstants.VertexFormat.Sint16x2 */; + case 3: + case 4: + return normalized ? "snorm16x4" /* WebGPUConstants.VertexFormat.Snorm16x4 */ : "sint16x4" /* WebGPUConstants.VertexFormat.Sint16x4 */; + } + break; + case VertexBuffer.UNSIGNED_SHORT: + switch (size) { + case 1: + case 2: + return normalized ? "unorm16x2" /* WebGPUConstants.VertexFormat.Unorm16x2 */ : "uint16x2" /* WebGPUConstants.VertexFormat.Uint16x2 */; + case 3: + case 4: + return normalized ? "unorm16x4" /* WebGPUConstants.VertexFormat.Unorm16x4 */ : "uint16x4" /* WebGPUConstants.VertexFormat.Uint16x4 */; + } + break; + case VertexBuffer.INT: + switch (size) { + case 1: + return "sint32" /* WebGPUConstants.VertexFormat.Sint32 */; + case 2: + return "sint32x2" /* WebGPUConstants.VertexFormat.Sint32x2 */; + case 3: + return "sint32x3" /* WebGPUConstants.VertexFormat.Sint32x3 */; + case 4: + return "sint32x4" /* WebGPUConstants.VertexFormat.Sint32x4 */; + } + break; + case VertexBuffer.UNSIGNED_INT: + switch (size) { + case 1: + return "uint32" /* WebGPUConstants.VertexFormat.Uint32 */; + case 2: + return "uint32x2" /* WebGPUConstants.VertexFormat.Uint32x2 */; + case 3: + return "uint32x3" /* WebGPUConstants.VertexFormat.Uint32x3 */; + case 4: + return "uint32x4" /* WebGPUConstants.VertexFormat.Uint32x4 */; + } + break; + case VertexBuffer.FLOAT: + switch (size) { + case 1: + return "float32" /* WebGPUConstants.VertexFormat.Float32 */; + case 2: + return "float32x2" /* WebGPUConstants.VertexFormat.Float32x2 */; + case 3: + return "float32x3" /* WebGPUConstants.VertexFormat.Float32x3 */; + case 4: + return "float32x4" /* WebGPUConstants.VertexFormat.Float32x4 */; + } + break; + } + throw new Error(`Invalid Format '${vertexBuffer.getKind()}' - type=${type}, normalized=${normalized}, size=${size}`); + } + _getAphaBlendState() { + if (!this._alphaBlendEnabled) { + return null; + } + return { + srcFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[2]), + dstFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[3]), + operation: WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[1]), + }; + } + _getColorBlendState() { + if (!this._alphaBlendEnabled) { + return null; + } + return { + srcFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[0]), + dstFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[1]), + operation: WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[0]), + }; + } + _setShaderStage(id) { + if (this._shaderId !== id) { + this._shaderId = id; + this._states[StatePosition.ShaderStage] = id; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ShaderStage); + } + } + _setRasterizationState(topology, sampleCount) { + const frontFace = this._frontFace; + const cullMode = this._cullEnabled ? this._cullFace : 0; + const clampDepth = this._clampDepth ? 1 : 0; + const alphaToCoverage = this._alphaToCoverageEnabled ? 1 : 0; + const rasterizationState = frontFace - 1 + (cullMode << 1) + (clampDepth << 3) + (alphaToCoverage << 4) + (topology << 5) + (sampleCount << 8); + if (this._rasterizationState !== rasterizationState) { + this._rasterizationState = rasterizationState; + this._states[StatePosition.RasterizationState] = this._rasterizationState; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.RasterizationState); + } + } + _setColorStates() { + let colorStates = ((this._writeMask ? 1 : 0) << 22) + (this._colorFormat << 23) + ((this._depthWriteEnabled ? 1 : 0) << 29); // this state has been moved from depthStencilState here because alpha and depth are related (generally when alpha is on, depth write is off and the other way around) + if (this._alphaBlendEnabled) { + colorStates += + ((this._alphaBlendFuncParams[0] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[0]]) << 0) + + ((this._alphaBlendFuncParams[1] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[1]]) << 4) + + ((this._alphaBlendFuncParams[2] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[2]]) << 8) + + ((this._alphaBlendFuncParams[3] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[3]]) << 12) + + ((this._alphaBlendEqParams[0] === null ? 1 : this._alphaBlendEqParams[0] - 0x8005) << 16) + + ((this._alphaBlendEqParams[1] === null ? 1 : this._alphaBlendEqParams[1] - 0x8005) << 19); + } + if (colorStates !== this._colorStates) { + this._colorStates = colorStates; + this._states[StatePosition.ColorStates] = this._colorStates; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ColorStates); + } + } + _setDepthStencilState() { + const stencilState = !this._stencilEnabled + ? 7 /* ALWAYS */ + (1 /* KEEP */ << 3) + (1 /* KEEP */ << 6) + (1 /* KEEP */ << 9) + : this._stencilFrontCompare + (this._stencilFrontDepthFailOp << 3) + (this._stencilFrontPassOp << 6) + (this._stencilFrontFailOp << 9); + const depthStencilState = this._depthStencilFormat + ((this._depthTestEnabled ? this._depthCompare : 7) /* ALWAYS */ << 6) + (stencilState << 10); // stencil front - stencil back is the same + if (this._depthStencilState !== depthStencilState) { + this._depthStencilState = depthStencilState; + this._states[StatePosition.DepthStencilState] = this._depthStencilState; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthStencilState); + } + } + _setVertexState(effect) { + const currStateLen = this._statesLength; + let newNumStates = StatePosition.VertexState; + const webgpuPipelineContext = effect._pipelineContext; + const attributes = webgpuPipelineContext.shaderProcessingContext.attributeNamesFromEffect; + const locations = webgpuPipelineContext.shaderProcessingContext.attributeLocationsFromEffect; + let currentGPUBuffer; + let numVertexBuffers = 0; + for (let index = 0; index < attributes.length; index++) { + const location = locations[index]; + let vertexBuffer = (this._overrideVertexBuffers && this._overrideVertexBuffers[attributes[index]]) ?? this._vertexBuffers[attributes[index]]; + if (!vertexBuffer) { + // In WebGL it's valid to not bind a vertex buffer to an attribute, but it's not valid in WebGPU + // So we must bind a dummy buffer when we are not given one for a specific attribute + vertexBuffer = this._emptyVertexBuffer; + if (WebGPUCacheRenderPipeline.LogErrorIfNoVertexBuffer) { + Logger.Error(`No vertex buffer is provided for the "${attributes[index]}" attribute. A default empty vertex buffer will be used, but this may generate errors in some browsers.`); + } + } + const buffer = vertexBuffer.effectiveBuffer?.underlyingResource; + // We optimize usage of GPUVertexBufferLayout: we will create a single GPUVertexBufferLayout for all the attributes which follow each other and which use the same GPU buffer + // However, there are some constraints in the attribute.offset value range, so we must check for them before being able to reuse the same GPUVertexBufferLayout + // See _getVertexInputDescriptor() below + if (vertexBuffer._validOffsetRange === undefined) { + const offset = vertexBuffer.effectiveByteOffset; + const formatSize = vertexBuffer.getSize(true); + const byteStride = vertexBuffer.effectiveByteStride; + vertexBuffer._validOffsetRange = + (offset + formatSize <= this._kMaxVertexBufferStride && byteStride === 0) || (byteStride !== 0 && offset + formatSize <= byteStride); + } + if (!(currentGPUBuffer && currentGPUBuffer === buffer && vertexBuffer._validOffsetRange)) { + // we can't combine the previous vertexBuffer with the current one + this.vertexBuffers[numVertexBuffers++] = vertexBuffer; + currentGPUBuffer = vertexBuffer._validOffsetRange ? buffer : null; + } + const vid = vertexBuffer.hashCode + (location << 7); + this._isDirty = this._isDirty || this._states[newNumStates] !== vid; + this._states[newNumStates++] = vid; + } + this.vertexBuffers.length = numVertexBuffers; + this._statesLength = newNumStates; + this._isDirty = this._isDirty || newNumStates !== currStateLen; + if (this._isDirty) { + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.VertexState); + } + } + _setTextureState(textureState) { + if (this._textureState !== textureState) { + this._textureState = textureState; + this._states[StatePosition.TextureStage] = this._textureState; + this._isDirty = true; + this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.TextureStage); + } + } + _createPipelineLayout(webgpuPipelineContext) { + if (this._useTextureStage) { + return this._createPipelineLayoutWithTextureStage(webgpuPipelineContext); + } + const bindGroupLayouts = []; + const bindGroupLayoutEntries = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries; + for (let i = 0; i < bindGroupLayoutEntries.length; i++) { + const setDefinition = bindGroupLayoutEntries[i]; + bindGroupLayouts[i] = this._device.createBindGroupLayout({ + entries: setDefinition, + }); + } + webgpuPipelineContext.bindGroupLayouts[0] = bindGroupLayouts; + return this._device.createPipelineLayout({ bindGroupLayouts }); + } + _createPipelineLayoutWithTextureStage(webgpuPipelineContext) { + const shaderProcessingContext = webgpuPipelineContext.shaderProcessingContext; + const bindGroupLayoutEntries = shaderProcessingContext.bindGroupLayoutEntries; + let bitVal = 1; + for (let i = 0; i < bindGroupLayoutEntries.length; i++) { + const setDefinition = bindGroupLayoutEntries[i]; + for (let j = 0; j < setDefinition.length; j++) { + const entry = bindGroupLayoutEntries[i][j]; + if (entry.texture) { + const name = shaderProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].name; + const textureInfo = shaderProcessingContext.availableTextures[name]; + const samplerInfo = textureInfo.autoBindSampler ? shaderProcessingContext.availableSamplers[name + `Sampler`] : null; + let sampleType = textureInfo.sampleType; + let samplerType = samplerInfo?.type ?? "filtering" /* WebGPUConstants.SamplerBindingType.Filtering */; + if (this._textureState & bitVal && sampleType !== "depth" /* WebGPUConstants.TextureSampleType.Depth */) { + // The texture is a 32 bits float texture but the system does not support linear filtering for them OR the texture is a depth texture with "float" filtering: + // we set the sampler to "non-filtering" and the texture sample type to "unfilterable-float" + if (textureInfo.autoBindSampler) { + samplerType = "non-filtering" /* WebGPUConstants.SamplerBindingType.NonFiltering */; + } + sampleType = "unfilterable-float" /* WebGPUConstants.TextureSampleType.UnfilterableFloat */; + } + entry.texture.sampleType = sampleType; + if (samplerInfo) { + const binding = shaderProcessingContext.bindGroupLayoutEntryInfo[samplerInfo.binding.groupIndex][samplerInfo.binding.bindingIndex].index; + bindGroupLayoutEntries[samplerInfo.binding.groupIndex][binding].sampler.type = samplerType; + } + bitVal = bitVal << 1; + } + } + } + const bindGroupLayouts = []; + for (let i = 0; i < bindGroupLayoutEntries.length; ++i) { + bindGroupLayouts[i] = this._device.createBindGroupLayout({ + entries: bindGroupLayoutEntries[i], + }); + } + webgpuPipelineContext.bindGroupLayouts[this._textureState] = bindGroupLayouts; + return this._device.createPipelineLayout({ bindGroupLayouts }); + } + _getVertexInputDescriptor(effect) { + const descriptors = []; + const webgpuPipelineContext = effect._pipelineContext; + const attributes = webgpuPipelineContext.shaderProcessingContext.attributeNamesFromEffect; + const locations = webgpuPipelineContext.shaderProcessingContext.attributeLocationsFromEffect; + let currentGPUBuffer; + let currentGPUAttributes; + for (let index = 0; index < attributes.length; index++) { + const location = locations[index]; + let vertexBuffer = (this._overrideVertexBuffers && this._overrideVertexBuffers[attributes[index]]) ?? this._vertexBuffers[attributes[index]]; + if (!vertexBuffer) { + // In WebGL it's valid to not bind a vertex buffer to an attribute, but it's not valid in WebGPU + // So we must bind a dummy buffer when we are not given one for a specific attribute + vertexBuffer = this._emptyVertexBuffer; + } + let buffer = vertexBuffer.effectiveBuffer?.underlyingResource; + // We reuse the same GPUVertexBufferLayout for all attributes that use the same underlying GPU buffer (and for attributes that follow each other in the attributes array) + let offset = vertexBuffer.effectiveByteOffset; + const invalidOffsetRange = !vertexBuffer._validOffsetRange; + if (!(currentGPUBuffer && currentGPUAttributes && currentGPUBuffer === buffer) || invalidOffsetRange) { + const vertexBufferDescriptor = { + arrayStride: vertexBuffer.effectiveByteStride, + stepMode: vertexBuffer.getIsInstanced() ? "instance" /* WebGPUConstants.VertexStepMode.Instance */ : "vertex" /* WebGPUConstants.VertexStepMode.Vertex */, + attributes: [], + }; + descriptors.push(vertexBufferDescriptor); + currentGPUAttributes = vertexBufferDescriptor.attributes; + if (invalidOffsetRange) { + offset = 0; // the offset will be set directly in the setVertexBuffer call + buffer = null; // buffer can't be reused + } + } + currentGPUAttributes.push({ + shaderLocation: location, + offset, + format: WebGPUCacheRenderPipeline._GetVertexInputDescriptorFormat(vertexBuffer), + }); + currentGPUBuffer = buffer; + } + return descriptors; + } + _createRenderPipeline(effect, topology, sampleCount) { + const webgpuPipelineContext = effect._pipelineContext; + const inputStateDescriptor = this._getVertexInputDescriptor(effect); + const pipelineLayout = this._createPipelineLayout(webgpuPipelineContext); + const colorStates = []; + const alphaBlend = this._getAphaBlendState(); + const colorBlend = this._getColorBlendState(); + if (this._vertexBuffers) { + checkNonFloatVertexBuffers(this._vertexBuffers, effect); + } + if (this._mrtAttachments1 > 0) { + for (let i = 0; i < this._mrtFormats.length; ++i) { + const format = this._mrtFormats[i]; + if (format) { + const descr = { + format, + writeMask: (this._mrtEnabledMask & (1 << i)) !== 0 ? this._writeMask : 0, + }; + if (alphaBlend && colorBlend) { + descr.blend = { + alpha: alphaBlend, + color: colorBlend, + }; + } + colorStates.push(descr); + } + else { + colorStates.push(null); + } + } + } + else { + if (this._webgpuColorFormat[0]) { + const descr = { + format: this._webgpuColorFormat[0], + writeMask: this._writeMask, + }; + if (alphaBlend && colorBlend) { + descr.blend = { + alpha: alphaBlend, + color: colorBlend, + }; + } + colorStates.push(descr); + } + else { + colorStates.push(null); + } + } + const stencilFrontBack = { + compare: WebGPUCacheRenderPipeline._GetCompareFunction(this._stencilEnabled ? this._stencilFrontCompare : 7 /* ALWAYS */), + depthFailOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontDepthFailOp : 1 /* KEEP */), + failOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontFailOp : 1 /* KEEP */), + passOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontPassOp : 1 /* KEEP */), + }; + const topologyIsTriangle = topology === "triangle-list" /* WebGPUConstants.PrimitiveTopology.TriangleList */ || topology === "triangle-strip" /* WebGPUConstants.PrimitiveTopology.TriangleStrip */; + let stripIndexFormat = undefined; + if (topology === "line-strip" /* WebGPUConstants.PrimitiveTopology.LineStrip */ || topology === "triangle-strip" /* WebGPUConstants.PrimitiveTopology.TriangleStrip */) { + stripIndexFormat = !this._indexBuffer || this._indexBuffer.is32Bits ? "uint32" /* WebGPUConstants.IndexFormat.Uint32 */ : "uint16" /* WebGPUConstants.IndexFormat.Uint16 */; + } + const depthStencilFormatHasStencil = this._webgpuDepthStencilFormat ? WebGPUTextureHelper.HasStencilAspect(this._webgpuDepthStencilFormat) : false; + return this._device.createRenderPipeline({ + label: `RenderPipeline_${colorStates[0]?.format ?? "nooutput"}_${this._webgpuDepthStencilFormat ?? "nodepth"}_samples${sampleCount}_textureState${this._textureState}`, + layout: pipelineLayout, + vertex: { + module: webgpuPipelineContext.stages.vertexStage.module, + entryPoint: webgpuPipelineContext.stages.vertexStage.entryPoint, + buffers: inputStateDescriptor, + }, + primitive: { + topology, + stripIndexFormat, + frontFace: this._frontFace === 1 ? "ccw" /* WebGPUConstants.FrontFace.CCW */ : "cw" /* WebGPUConstants.FrontFace.CW */, + cullMode: !this._cullEnabled ? "none" /* WebGPUConstants.CullMode.None */ : this._cullFace === 2 ? "front" /* WebGPUConstants.CullMode.Front */ : "back" /* WebGPUConstants.CullMode.Back */, + }, + fragment: !webgpuPipelineContext.stages.fragmentStage + ? undefined + : { + module: webgpuPipelineContext.stages.fragmentStage.module, + entryPoint: webgpuPipelineContext.stages.fragmentStage.entryPoint, + targets: colorStates, + }, + multisample: { + count: sampleCount, + /*mask, + alphaToCoverageEnabled,*/ + }, + depthStencil: this._webgpuDepthStencilFormat === undefined + ? undefined + : { + depthWriteEnabled: this._depthWriteEnabled, + depthCompare: this._depthTestEnabled ? WebGPUCacheRenderPipeline._GetCompareFunction(this._depthCompare) : "always" /* WebGPUConstants.CompareFunction.Always */, + format: this._webgpuDepthStencilFormat, + stencilFront: this._stencilEnabled && depthStencilFormatHasStencil ? stencilFrontBack : undefined, + stencilBack: this._stencilEnabled && depthStencilFormatHasStencil ? stencilFrontBack : undefined, + stencilReadMask: this._stencilEnabled && depthStencilFormatHasStencil ? this._stencilReadMask : undefined, + stencilWriteMask: this._stencilEnabled && depthStencilFormatHasStencil ? this._stencilWriteMask : undefined, + depthBias: this._depthBias, + depthBiasClamp: topologyIsTriangle ? this._depthBiasClamp : 0, + depthBiasSlopeScale: topologyIsTriangle ? this._depthBiasSlopeScale : 0, + }, + }); + } +} +WebGPUCacheRenderPipeline.LogErrorIfNoVertexBuffer = false; +WebGPUCacheRenderPipeline.NumCacheHitWithoutHash = 0; +WebGPUCacheRenderPipeline.NumCacheHitWithHash = 0; +WebGPUCacheRenderPipeline.NumCacheMiss = 0; +WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame = 0; +WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame = 0; + +/** @internal */ +class NodeState { + constructor() { + this.values = {}; + } + count() { + let countNode = 0, countPipeline = this.pipeline ? 1 : 0; + for (const value in this.values) { + const node = this.values[value]; + const [childCountNodes, childCoundPipeline] = node.count(); + countNode += childCountNodes; + countPipeline += childCoundPipeline; + countNode++; + } + return [countNode, countPipeline]; + } +} +/** @internal */ +class WebGPUCacheRenderPipelineTree extends WebGPUCacheRenderPipeline { + static GetNodeCounts() { + const counts = WebGPUCacheRenderPipelineTree._Cache.count(); + return { nodeCount: counts[0], pipelineCount: counts[1] }; + } + static _GetPipelines(node, pipelines, curPath, curPathLen) { + if (node.pipeline) { + const path = curPath.slice(); + path.length = curPathLen; + pipelines.push(path); + } + for (const value in node.values) { + const nnode = node.values[value]; + curPath[curPathLen] = parseInt(value); + WebGPUCacheRenderPipelineTree._GetPipelines(nnode, pipelines, curPath, curPathLen + 1); + } + } + static GetPipelines() { + const pipelines = []; + WebGPUCacheRenderPipelineTree._GetPipelines(WebGPUCacheRenderPipelineTree._Cache, pipelines, [], 0); + return pipelines; + } + static ResetCache() { + WebGPUCacheRenderPipelineTree._Cache = new NodeState(); + } + reset() { + this._nodeStack = []; + this._nodeStack[0] = WebGPUCacheRenderPipelineTree._Cache; + super.reset(); + } + _getRenderPipeline(param) { + let node = this._nodeStack[this._stateDirtyLowestIndex]; + for (let i = this._stateDirtyLowestIndex; i < this._statesLength; ++i) { + let nn = node.values[this._states[i]]; + if (!nn) { + nn = new NodeState(); + node.values[this._states[i]] = nn; + } + node = nn; + this._nodeStack[i + 1] = node; + } + param.token = node; + param.pipeline = node.pipeline; + } + _setRenderPipeline(param) { + param.token.pipeline = param.pipeline; + } +} +WebGPUCacheRenderPipelineTree._Cache = new NodeState(); + +/** + * @internal + **/ +class WebGPUStencilStateComposer extends StencilStateComposer { + constructor(cache) { + super(false); + this._cache = cache; + this.reset(); + } + get func() { + return this._func; + } + set func(value) { + if (this._func === value) { + return; + } + this._func = value; + this._cache.setStencilCompare(value); + } + get funcMask() { + return this._funcMask; + } + set funcMask(value) { + if (this._funcMask === value) { + return; + } + this._funcMask = value; + this._cache.setStencilReadMask(value); + } + get opStencilFail() { + return this._opStencilFail; + } + set opStencilFail(value) { + if (this._opStencilFail === value) { + return; + } + this._opStencilFail = value; + this._cache.setStencilFailOp(value); + } + get opDepthFail() { + return this._opDepthFail; + } + set opDepthFail(value) { + if (this._opDepthFail === value) { + return; + } + this._opDepthFail = value; + this._cache.setStencilDepthFailOp(value); + } + get opStencilDepthPass() { + return this._opStencilDepthPass; + } + set opStencilDepthPass(value) { + if (this._opStencilDepthPass === value) { + return; + } + this._opStencilDepthPass = value; + this._cache.setStencilPassOp(value); + } + get mask() { + return this._mask; + } + set mask(value) { + if (this._mask === value) { + return; + } + this._mask = value; + this._cache.setStencilWriteMask(value); + } + get enabled() { + return this._enabled; + } + set enabled(value) { + if (this._enabled === value) { + return; + } + this._enabled = value; + this._cache.setStencilEnabled(value); + } + reset() { + super.reset(); + this._cache.resetStencilState(); + } + apply() { + const stencilMaterialEnabled = this.stencilMaterial?.enabled; + this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled; + if (!this.enabled) { + return; + } + this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func; + this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef; + this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask; + this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail; + this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail; + this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass; + this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask; + } +} + +/** + * @internal + **/ +class WebGPUDepthCullingState extends DepthCullingState { + /** + * Initializes the state. + * @param cache + */ + constructor(cache) { + super(false); + this._cache = cache; + this.reset(); + } + get zOffset() { + return this._zOffset; + } + set zOffset(value) { + if (this._zOffset === value) { + return; + } + this._zOffset = value; + this._isZOffsetDirty = true; + this._cache.setDepthBiasSlopeScale(value); + } + get zOffsetUnits() { + return this._zOffsetUnits; + } + set zOffsetUnits(value) { + if (this._zOffsetUnits === value) { + return; + } + this._zOffsetUnits = value; + this._isZOffsetDirty = true; + this._cache.setDepthBias(value); + } + get cullFace() { + return this._cullFace; + } + set cullFace(value) { + if (this._cullFace === value) { + return; + } + this._cullFace = value; + this._isCullFaceDirty = true; + this._cache.setCullFace(value ?? 1); + } + get cull() { + return this._cull; + } + set cull(value) { + if (this._cull === value) { + return; + } + this._cull = value; + this._isCullDirty = true; + this._cache.setCullEnabled(!!value); + } + get depthFunc() { + return this._depthFunc; + } + set depthFunc(value) { + if (this._depthFunc === value) { + return; + } + this._depthFunc = value; + this._isDepthFuncDirty = true; + this._cache.setDepthCompare(value); + } + get depthMask() { + return this._depthMask; + } + set depthMask(value) { + if (this._depthMask === value) { + return; + } + this._depthMask = value; + this._isDepthMaskDirty = true; + this._cache.setDepthWriteEnabled(value); + } + get depthTest() { + return this._depthTest; + } + set depthTest(value) { + if (this._depthTest === value) { + return; + } + this._depthTest = value; + this._isDepthTestDirty = true; + this._cache.setDepthTestEnabled(value); + } + get frontFace() { + return this._frontFace; + } + set frontFace(value) { + if (this._frontFace === value) { + return; + } + this._frontFace = value; + this._isFrontFaceDirty = true; + this._cache.setFrontFace(value ?? 2); + } + reset() { + super.reset(); + this._cache.resetDepthCullingState(); + } + apply() { + // nothing to do + } +} + +/** + * Class used to store an external texture (like GPUExternalTexture in WebGPU) + */ +class ExternalTexture { + /** + * Checks if a texture is an external or internal texture + * @param texture the external or internal texture + * @returns true if the texture is an external texture, else false + */ + static IsExternalTexture(texture) { + return texture.underlyingResource !== undefined; + } + /** + * Get the class name of the texture. + * @returns "ExternalTexture" + */ + getClassName() { + return "ExternalTexture"; + } + /** + * Gets the underlying texture object + */ + get underlyingResource() { + return this._video; + } + /** + * Constructs the texture + * @param video The video the texture should be wrapped around + */ + constructor(video) { + /** + * Gets a boolean indicating if the texture uses mipmaps + */ + this.useMipMaps = false; + /** + * The type of the underlying texture is implementation dependent, so return "UNDEFINED" for the type + */ + this.type = 16; + /** + * The format of the underlying texture is implementation dependent, so return "UNDEFINED" for the format + */ + this.format = 4294967295; + this._video = video; + this.uniqueId = InternalTexture._Counter++; + } + /** + * Get if the texture is ready to be used (downloaded, converted, mip mapped...). + * @returns true if fully ready + */ + isReady() { + return this._video.readyState >= this._video.HAVE_CURRENT_DATA; + } + /** + * Dispose the texture and release its associated resources. + */ + dispose() { } +} + +/* eslint-disable babylonjs/available */ +/* eslint-disable jsdoc/require-jsdoc */ +/** @internal */ +class WebGPUMaterialContext { + get forceBindGroupCreation() { + // If there is at least one external texture to bind, we must recreate the bind groups each time + // because we need to retrieve a new texture each frame (by calling device.importExternalTexture) + return this._numExternalTextures > 0; + } + get hasFloatOrDepthTextures() { + return this._numFloatOrDepthTextures > 0; + } + constructor() { + this.uniqueId = WebGPUMaterialContext._Counter++; + this.updateId = 0; + this.textureState = 0; + this.reset(); + } + reset() { + this.samplers = {}; + this.textures = {}; + this.isDirty = true; + this._numFloatOrDepthTextures = 0; + this._numExternalTextures = 0; + } + setSampler(name, sampler) { + let samplerCache = this.samplers[name]; + let currentHashCode = -1; + if (!samplerCache) { + this.samplers[name] = samplerCache = { sampler, hashCode: 0 }; + } + else { + currentHashCode = samplerCache.hashCode; + } + samplerCache.sampler = sampler; + samplerCache.hashCode = sampler ? WebGPUCacheSampler.GetSamplerHashCode(sampler) : 0; + const isDirty = currentHashCode !== samplerCache.hashCode; + if (isDirty) { + this.updateId++; + } + this.isDirty || (this.isDirty = isDirty); + } + setTexture(name, texture) { + let textureCache = this.textures[name]; + let currentTextureId = -1; + if (!textureCache) { + this.textures[name] = textureCache = { texture, isFloatOrDepthTexture: false, isExternalTexture: false }; + } + else { + currentTextureId = textureCache.texture?.uniqueId ?? -1; + } + if (textureCache.isExternalTexture) { + this._numExternalTextures--; + } + if (textureCache.isFloatOrDepthTexture) { + this._numFloatOrDepthTextures--; + } + if (texture) { + textureCache.isFloatOrDepthTexture = + texture.type === 1 || + (texture.format >= 13 && texture.format <= 18); + textureCache.isExternalTexture = ExternalTexture.IsExternalTexture(texture); + if (textureCache.isFloatOrDepthTexture) { + this._numFloatOrDepthTextures++; + } + if (textureCache.isExternalTexture) { + this._numExternalTextures++; + } + } + else { + textureCache.isFloatOrDepthTexture = false; + textureCache.isExternalTexture = false; + } + textureCache.texture = texture; + const isDirty = currentTextureId !== (texture?.uniqueId ?? -1); + if (isDirty) { + this.updateId++; + } + this.isDirty || (this.isDirty = isDirty); + } +} +WebGPUMaterialContext._Counter = 0; + +/** @internal */ +class WebGPUDrawContext { + isDirty(materialContextUpdateId) { + return this._isDirty || this._materialContextUpdateId !== materialContextUpdateId; + } + resetIsDirty(materialContextUpdateId) { + this._isDirty = false; + this._materialContextUpdateId = materialContextUpdateId; + } + get useInstancing() { + return this._useInstancing; + } + set useInstancing(use) { + if (this._useInstancing === use) { + return; + } + if (!use) { + if (this.indirectDrawBuffer) { + this._bufferManager.releaseBuffer(this.indirectDrawBuffer); + } + this.indirectDrawBuffer = undefined; + this._indirectDrawData = undefined; + } + else { + this.indirectDrawBuffer = this._bufferManager.createRawBuffer(20, BufferUsage.CopyDst | BufferUsage.Indirect | BufferUsage.Storage, undefined, "IndirectDrawBuffer"); + this._indirectDrawData = new Uint32Array(5); + this._indirectDrawData[3] = 0; + this._indirectDrawData[4] = 0; + } + this._useInstancing = use; + this._currentInstanceCount = -1; + } + constructor(bufferManager) { + this._bufferManager = bufferManager; + this.uniqueId = WebGPUDrawContext._Counter++; + this._useInstancing = false; + this._currentInstanceCount = 0; + this.reset(); + } + reset() { + this.buffers = {}; + this._isDirty = true; + this._materialContextUpdateId = 0; + this.fastBundle = undefined; + this.bindGroups = undefined; + } + setBuffer(name, buffer) { + this._isDirty || (this._isDirty = buffer?.uniqueId !== this.buffers[name]?.uniqueId); + this.buffers[name] = buffer; + } + setIndirectData(indexOrVertexCount, instanceCount, firstIndexOrVertex) { + if (instanceCount === this._currentInstanceCount || !this.indirectDrawBuffer || !this._indirectDrawData) { + // The current buffer is already up to date so do nothing + // Note that we only check for instanceCount and not indexOrVertexCount nor firstIndexOrVertex because those values + // are supposed to not change during the lifetime of a draw context + return; + } + this._currentInstanceCount = instanceCount; + this._indirectDrawData[0] = indexOrVertexCount; + this._indirectDrawData[1] = instanceCount; + this._indirectDrawData[2] = firstIndexOrVertex; + this._bufferManager.setRawData(this.indirectDrawBuffer, 0, this._indirectDrawData, 0, 20); + } + dispose() { + if (this.indirectDrawBuffer) { + this._bufferManager.releaseBuffer(this.indirectDrawBuffer); + this.indirectDrawBuffer = undefined; + this._indirectDrawData = undefined; + } + this.fastBundle = undefined; + this.bindGroups = undefined; + this.buffers = undefined; + } +} +WebGPUDrawContext._Counter = 0; + +/* eslint-disable babylonjs/available */ +/* eslint-disable jsdoc/require-jsdoc */ +/** + * Sampler hash codes are 19 bits long, so using a start value of 2^20 for buffer ids will ensure we can't have any collision with the sampler hash codes + */ +const bufferIdStart = 1 << 20; +/** + * textureIdStart is added to texture ids to ensure we can't have any collision with the buffer ids / sampler hash codes. + * 2^35 for textureIdStart means we can have: + * - 2^(35-20) = 2^15 = 32768 possible buffer ids + * - 2^(53-35) = 2^18 = 524288 possible texture ids + */ +const textureIdStart = 2 ** 35; +class WebGPUBindGroupCacheNode { + constructor() { + this.values = {}; + } +} +/** @internal */ +class WebGPUCacheBindGroups { + static get Statistics() { + return { + totalCreated: WebGPUCacheBindGroups.NumBindGroupsCreatedTotal, + lastFrameCreated: WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame, + lookupLastFrame: WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame, + noLookupLastFrame: WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame, + }; + } + static ResetCache() { + WebGPUCacheBindGroups._Cache = new WebGPUBindGroupCacheNode(); + WebGPUCacheBindGroups.NumBindGroupsCreatedTotal = 0; + WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = 0; + WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = 0; + WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = 0; + WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0; + WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0; + WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0; + } + constructor(device, cacheSampler, engine) { + this.disabled = false; + this._device = device; + this._cacheSampler = cacheSampler; + this._engine = engine; + } + endFrame() { + WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame; + WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame; + WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame; + WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0; + WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0; + WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0; + } + /** + * Cache is currently based on the uniform/storage buffers, samplers and textures used by the binding groups. + * Note that all uniform buffers have an offset of 0 in Babylon and we don't have a use case where we would have the same buffer used with different capacity values: + * that means we don't need to factor in the offset/size of the buffer in the cache, only the id + * @param webgpuPipelineContext + * @param drawContext + * @param materialContext + * @returns a bind group array + */ + getBindGroups(webgpuPipelineContext, drawContext, materialContext) { + let bindGroups = undefined; + let node = WebGPUCacheBindGroups._Cache; + const cacheIsDisabled = this.disabled || materialContext.forceBindGroupCreation; + if (!cacheIsDisabled) { + if (!drawContext.isDirty(materialContext.updateId) && !materialContext.isDirty) { + WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame++; + return drawContext.bindGroups; + } + for (const bufferName of webgpuPipelineContext.shaderProcessingContext.bufferNames) { + const uboId = (drawContext.buffers[bufferName]?.uniqueId ?? 0) + bufferIdStart; + let nextNode = node.values[uboId]; + if (!nextNode) { + nextNode = new WebGPUBindGroupCacheNode(); + node.values[uboId] = nextNode; + } + node = nextNode; + } + for (const samplerName of webgpuPipelineContext.shaderProcessingContext.samplerNames) { + const samplerHashCode = materialContext.samplers[samplerName]?.hashCode ?? 0; + let nextNode = node.values[samplerHashCode]; + if (!nextNode) { + nextNode = new WebGPUBindGroupCacheNode(); + node.values[samplerHashCode] = nextNode; + } + node = nextNode; + } + for (const textureName of webgpuPipelineContext.shaderProcessingContext.textureNames) { + const textureId = (materialContext.textures[textureName]?.texture?.uniqueId ?? 0) + textureIdStart; + let nextNode = node.values[textureId]; + if (!nextNode) { + nextNode = new WebGPUBindGroupCacheNode(); + node.values[textureId] = nextNode; + } + node = nextNode; + } + bindGroups = node.bindGroups; + } + drawContext.resetIsDirty(materialContext.updateId); + materialContext.isDirty = false; + if (bindGroups) { + drawContext.bindGroups = bindGroups; + WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame++; + return bindGroups; + } + bindGroups = []; + drawContext.bindGroups = bindGroups; + if (!cacheIsDisabled) { + node.bindGroups = bindGroups; + } + WebGPUCacheBindGroups.NumBindGroupsCreatedTotal++; + WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame++; + const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts[materialContext.textureState]; + for (let i = 0; i < webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries.length; i++) { + const setDefinition = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries[i]; + const entries = webgpuPipelineContext.shaderProcessingContext.bindGroupEntries[i]; + for (let j = 0; j < setDefinition.length; j++) { + const entry = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries[i][j]; + const entryInfo = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding]; + const name = entryInfo.nameInArrayOfTexture ?? entryInfo.name; + if (entry.sampler) { + const bindingInfo = materialContext.samplers[name]; + if (bindingInfo) { + const sampler = bindingInfo.sampler; + if (!sampler) { + if (this._engine.dbgSanityChecks) { + Logger.Error(`Trying to bind a null sampler! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === "texture" ? "" : value))}, materialContext.uniqueId=${materialContext.uniqueId}`, 50); + } + continue; + } + entries[j].resource = this._cacheSampler.getSampler(sampler, false, bindingInfo.hashCode, sampler.label); + } + else { + Logger.Error(`Sampler "${name}" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === "texture" || key === "sampler" ? "" : value)}`, 50); + } + } + else if (entry.texture || entry.storageTexture) { + const bindingInfo = materialContext.textures[name]; + if (bindingInfo) { + if (this._engine.dbgSanityChecks && bindingInfo.texture === null) { + Logger.Error(`Trying to bind a null texture! entry=${JSON.stringify(entry)}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => key === "texture" ? "" : value)}, materialContext.uniqueId=${materialContext.uniqueId}`, 50); + continue; + } + const hardwareTexture = bindingInfo.texture._hardwareTexture; + if (this._engine.dbgSanityChecks && + (!hardwareTexture || (entry.texture && !hardwareTexture.view) || (entry.storageTexture && !hardwareTexture.viewForWriting))) { + Logger.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === "texture" ? "" : value))}, isReady=${bindingInfo.texture?.isReady}, materialContext.uniqueId=${materialContext.uniqueId}`, 50); + continue; + } + entries[j].resource = entry.storageTexture ? hardwareTexture.viewForWriting : hardwareTexture.view; + } + else { + Logger.Error(`Texture "${name}" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === "texture" || key === "sampler" ? "" : value)}`, 50); + } + } + else if (entry.externalTexture) { + const bindingInfo = materialContext.textures[name]; + if (bindingInfo) { + if (this._engine.dbgSanityChecks && bindingInfo.texture === null) { + Logger.Error(`Trying to bind a null external texture! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === "texture" ? "" : value))}, materialContext.uniqueId=${materialContext.uniqueId}`, 50); + continue; + } + const externalTexture = bindingInfo.texture.underlyingResource; + if (this._engine.dbgSanityChecks && !externalTexture) { + Logger.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === "texture" ? "" : value))}, isReady=${bindingInfo.texture?.isReady}, materialContext.uniqueId=${materialContext.uniqueId}`, 50); + continue; + } + entries[j].resource = this._device.importExternalTexture({ source: externalTexture }); + } + else { + Logger.Error(`Texture "${name}" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === "texture" || key === "sampler" ? "" : value)}`, 50); + } + } + else if (entry.buffer) { + const dataBuffer = drawContext.buffers[name]; + if (dataBuffer) { + const webgpuBuffer = dataBuffer.underlyingResource; + entries[j].resource.buffer = webgpuBuffer; + entries[j].resource.size = dataBuffer.capacity; + } + else { + Logger.Error(`Can't find buffer "${name}". entry=${JSON.stringify(entry)}, buffers=${JSON.stringify(drawContext.buffers)}, drawContext.uniqueId=${drawContext.uniqueId}`, 50); + } + } + } + const groupLayout = bindGroupLayouts[i]; + bindGroups[i] = this._device.createBindGroup({ + layout: groupLayout, + entries, + }); + } + return bindGroups; + } +} +WebGPUCacheBindGroups.NumBindGroupsCreatedTotal = 0; +WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = 0; +WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = 0; +WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = 0; +WebGPUCacheBindGroups._Cache = new WebGPUBindGroupCacheNode(); +WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0; +WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0; +WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0; + +// Do not edit. +const name$7A = "clearQuadVertexShader"; +const shader$7z = `uniform depthValue: f32;const pos=array( +vec2f(-1.0,1.0), +vec2f(1.0,1.0), +vec2f(-1.0,-1.0), +vec2f(1.0,-1.0) +); +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0); +#define CUSTOM_VERTEX_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7A]) { + ShaderStore.ShadersStoreWGSL[name$7A] = shader$7z; +} + +// Do not edit. +const name$7z = "clearQuadPixelShader"; +const shader$7y = `uniform color: vec4f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7z]) { + ShaderStore.ShadersStoreWGSL[name$7z] = shader$7y; +} + +/** @internal */ +class WebGPUClearQuad { + setDepthStencilFormat(format) { + this._depthTextureFormat = format; + this._cacheRenderPipeline.setDepthStencilFormat(format); + } + setColorFormat(format) { + this._cacheRenderPipeline.setColorFormat(format); + } + setMRTAttachments(attachments, textureArray, textureCount) { + this._cacheRenderPipeline.setMRT(textureArray, textureCount); + this._cacheRenderPipeline.setMRTAttachments(attachments); + } + constructor(device, engine, emptyVertexBuffer) { + this._bindGroups = {}; + this._bundleCache = {}; + this._keyTemp = []; + this._device = device; + this._engine = engine; + this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, emptyVertexBuffer); + this._cacheRenderPipeline.setDepthTestEnabled(false); + this._cacheRenderPipeline.setStencilReadMask(0xff); + this._effect = engine.createEffect("clearQuad", [], ["color", "depthValue"], undefined, undefined, undefined, undefined, undefined, undefined, 1 /* ShaderLanguage.WGSL */); + } + clear(renderPass, clearColor, clearDepth, clearStencil, sampleCount = 1) { + let renderPass2; + let bundle = null; + let bundleKey; + const isRTTPass = !!this._engine._currentRenderTarget; + if (renderPass) { + renderPass2 = renderPass; + } + else { + let idx = 0; + this._keyTemp.length = 0; + for (let i = 0; i < this._cacheRenderPipeline.colorFormats.length; ++i) { + this._keyTemp[idx++] = renderableTextureFormatToIndex[this._cacheRenderPipeline.colorFormats[i] ?? ""]; + } + const depthStencilFormatIndex = renderableTextureFormatToIndex[this._depthTextureFormat ?? 0]; + this._keyTemp[idx] = + (clearColor ? clearColor.r + clearColor.g * 256 + clearColor.b * 256 * 256 + clearColor.a * 256 * 256 * 256 : 0) + + (clearDepth ? 2 ** 32 : 0) + + (clearStencil ? 2 ** 33 : 0) + + (this._engine.useReverseDepthBuffer ? 2 ** 34 : 0) + + (isRTTPass ? 2 ** 35 : 0) + + (sampleCount > 1 ? 2 ** 36 : 0) + + depthStencilFormatIndex * 2 ** 37; + bundleKey = this._keyTemp.join("_"); + bundle = this._bundleCache[bundleKey]; + if (bundle) { + return bundle; + } + renderPass2 = this._device.createRenderBundleEncoder({ + label: "clearQuadRenderBundle", + colorFormats: this._cacheRenderPipeline.colorFormats, + depthStencilFormat: this._depthTextureFormat, + sampleCount: WebGPUTextureHelper.GetSample(sampleCount), + }); + } + this._cacheRenderPipeline.setDepthWriteEnabled(!!clearDepth); + this._cacheRenderPipeline.setStencilEnabled(!!clearStencil && !!this._depthTextureFormat && WebGPUTextureHelper.HasStencilAspect(this._depthTextureFormat)); + this._cacheRenderPipeline.setStencilWriteMask(clearStencil ? 0xff : 0); + this._cacheRenderPipeline.setStencilCompare(clearStencil ? 519 : 512); + this._cacheRenderPipeline.setStencilPassOp(clearStencil ? 7681 : 7680); + this._cacheRenderPipeline.setWriteMask(clearColor ? 0xf : 0); + const pipeline = this._cacheRenderPipeline.getRenderPipeline(7, this._effect, sampleCount); + const webgpuPipelineContext = this._effect._pipelineContext; + if (clearColor) { + this._effect.setDirectColor4("color", clearColor); + } + this._effect.setFloat("depthValue", this._engine.useReverseDepthBuffer ? this._engine._clearReverseDepthValue : this._engine._clearDepthValue); + webgpuPipelineContext.uniformBuffer.update(); + const bufferInternals = isRTTPass ? this._engine._ubInvertY : this._engine._ubDontInvertY; + const bufferLeftOver = webgpuPipelineContext.uniformBuffer.getBuffer(); + const key = bufferLeftOver.uniqueId + "-" + bufferInternals.uniqueId; + let bindGroups = this._bindGroups[key]; + if (!bindGroups) { + const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts[0]; + bindGroups = this._bindGroups[key] = []; + bindGroups.push(this._device.createBindGroup({ + label: `clearQuadBindGroup0-${key}`, + layout: bindGroupLayouts[0], + entries: [], + })); + if (!WebGPUShaderProcessingContext._SimplifiedKnownBindings) { + bindGroups.push(this._device.createBindGroup({ + label: `clearQuadBindGroup1-${key}`, + layout: bindGroupLayouts[1], + entries: [], + })); + } + bindGroups.push(this._device.createBindGroup({ + label: `clearQuadBindGroup${WebGPUShaderProcessingContext._SimplifiedKnownBindings ? 1 : 2}-${key}`, + layout: bindGroupLayouts[WebGPUShaderProcessingContext._SimplifiedKnownBindings ? 1 : 2], + entries: [ + { + binding: 0, + resource: { + buffer: bufferInternals.underlyingResource, + size: bufferInternals.capacity, + }, + }, + { + binding: 1, + resource: { + buffer: bufferLeftOver.underlyingResource, + size: bufferLeftOver.capacity, + }, + }, + ], + })); + } + renderPass2.setPipeline(pipeline); + for (let i = 0; i < bindGroups.length; ++i) { + renderPass2.setBindGroup(i, bindGroups[i]); + } + renderPass2.draw(4, 1, 0, 0); + if (!renderPass) { + bundle = renderPass2.finish(); + this._bundleCache[bundleKey] = bundle; + } + return bundle; + } +} + +/** @internal */ +class WebGPURenderItemViewport { + constructor(x, y, w, h) { + this.x = Math.floor(x); + this.y = Math.floor(y); + this.w = Math.floor(w); + this.h = Math.floor(h); + } + run(renderPass) { + renderPass.setViewport(this.x, this.y, this.w, this.h, 0, 1); + } + clone() { + return new WebGPURenderItemViewport(this.x, this.y, this.w, this.h); + } +} +/** @internal */ +class WebGPURenderItemScissor { + constructor(x, y, w, h) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + } + run(renderPass) { + renderPass.setScissorRect(this.x, this.y, this.w, this.h); + } + clone() { + return new WebGPURenderItemScissor(this.x, this.y, this.w, this.h); + } +} +/** @internal */ +class WebGPURenderItemStencilRef { + constructor(ref) { + this.ref = ref; + } + run(renderPass) { + renderPass.setStencilReference(this.ref); + } + clone() { + return new WebGPURenderItemStencilRef(this.ref); + } +} +/** @internal */ +class WebGPURenderItemBlendColor { + constructor(color) { + this.color = color; + } + run(renderPass) { + renderPass.setBlendConstant(this.color); + } + clone() { + return new WebGPURenderItemBlendColor(this.color); + } +} +/** @internal */ +class WebGPURenderItemBeginOcclusionQuery { + constructor(query) { + this.query = query; + } + run(renderPass) { + renderPass.beginOcclusionQuery(this.query); + } + clone() { + return new WebGPURenderItemBeginOcclusionQuery(this.query); + } +} +/** @internal */ +class WebGPURenderItemEndOcclusionQuery { + constructor() { } + run(renderPass) { + renderPass.endOcclusionQuery(); + } + clone() { + return new WebGPURenderItemEndOcclusionQuery(); + } +} +class WebGPURenderItemBundles { + constructor() { + this.bundles = []; + } + run(renderPass) { + renderPass.executeBundles(this.bundles); + } + clone() { + const cloned = new WebGPURenderItemBundles(); + cloned.bundles = this.bundles; + return cloned; + } +} +/** @internal */ +class WebGPUBundleList { + constructor(device) { + this.numDrawCalls = 0; + this._device = device; + this._list = new Array(10); + this._listLength = 0; + } + addBundle(bundle) { + if (!this._currentItemIsBundle) { + const item = new WebGPURenderItemBundles(); + this._list[this._listLength++] = item; + this._currentBundleList = item.bundles; + this._currentItemIsBundle = true; + } + if (bundle) { + this._currentBundleList.push(bundle); + } + } + _finishBundle() { + if (this._currentItemIsBundle && this._bundleEncoder) { + this._currentBundleList.push(this._bundleEncoder.finish()); + this._bundleEncoder = undefined; + this._currentItemIsBundle = false; + } + } + addItem(item) { + this._finishBundle(); + this._list[this._listLength++] = item; + this._currentItemIsBundle = false; + } + getBundleEncoder(colorFormats, depthStencilFormat, sampleCount) { + if (!this._currentItemIsBundle) { + this.addBundle(); + this._bundleEncoder = this._device.createRenderBundleEncoder({ + colorFormats, + depthStencilFormat, + sampleCount: WebGPUTextureHelper.GetSample(sampleCount), + }); + } + return this._bundleEncoder; + } + close() { + this._finishBundle(); + } + run(renderPass) { + this.close(); + for (let i = 0; i < this._listLength; ++i) { + this._list[i].run(renderPass); + } + } + reset() { + this._listLength = 0; + this._currentItemIsBundle = false; + this.numDrawCalls = 0; + } + clone() { + this.close(); + const cloned = new WebGPUBundleList(this._device); + cloned._list = new Array(this._listLength); + cloned._listLength = this._listLength; + cloned.numDrawCalls = this.numDrawCalls; + for (let i = 0; i < this._listLength; ++i) { + cloned._list[i] = this._list[i].clone(); + } + return cloned; + } +} + +/** @internal */ +class WebGPUQuerySet { + get querySet() { + return this._querySet; + } + constructor(engine, count, type, device, bufferManager, canUseMultipleBuffers = true, label) { + this._dstBuffers = []; + this._engine = engine; + this._device = device; + this._bufferManager = bufferManager; + this._count = count; + this._canUseMultipleBuffers = canUseMultipleBuffers; + this._querySet = device.createQuerySet({ + label: label ?? "QuerySet", + type, + count, + }); + this._queryBuffer = bufferManager.createRawBuffer(8 * count, BufferUsage.QueryResolve | BufferUsage.CopySrc, undefined, "QueryBuffer"); + if (!canUseMultipleBuffers) { + this._dstBuffers.push(this._bufferManager.createRawBuffer(8 * this._count, BufferUsage.MapRead | BufferUsage.CopyDst, undefined, "QueryBufferNoMultipleBuffers")); + } + } + _getBuffer(firstQuery, queryCount) { + if (!this._canUseMultipleBuffers && this._dstBuffers.length === 0) { + return null; + } + const encoderResult = this._device.createCommandEncoder(); + let buffer; + if (this._dstBuffers.length === 0) { + buffer = this._bufferManager.createRawBuffer(8 * this._count, BufferUsage.MapRead | BufferUsage.CopyDst, undefined, "QueryBufferAdditionalBuffer"); + } + else { + buffer = this._dstBuffers[this._dstBuffers.length - 1]; + this._dstBuffers.length--; + } + encoderResult.resolveQuerySet(this._querySet, firstQuery, queryCount, this._queryBuffer, 0); + encoderResult.copyBufferToBuffer(this._queryBuffer, 0, buffer, 0, 8 * queryCount); + this._device.queue.submit([encoderResult.finish()]); + return buffer; + } + async readValues(firstQuery = 0, queryCount = 1) { + const buffer = this._getBuffer(firstQuery, queryCount); + if (buffer === null) { + return null; + } + const engineId = this._engine.uniqueId; + return buffer.mapAsync(1 /* WebGPUConstants.MapMode.Read */).then(() => { + const arrayBuf = new BigUint64Array(buffer.getMappedRange()).slice(); + buffer.unmap(); + this._dstBuffers[this._dstBuffers.length] = buffer; + return arrayBuf; + }, (err) => { + if (this._engine.isDisposed || this._engine.uniqueId !== engineId) { + // Engine disposed or context loss/restoration + return null; + } + throw err; + }); + } + async readValue(firstQuery = 0) { + const buffer = this._getBuffer(firstQuery, 1); + if (buffer === null) { + return null; + } + const engineId = this._engine.uniqueId; + return buffer.mapAsync(1 /* WebGPUConstants.MapMode.Read */).then(() => { + const arrayBuf = new BigUint64Array(buffer.getMappedRange()); + const value = Number(arrayBuf[0]); + buffer.unmap(); + this._dstBuffers[this._dstBuffers.length] = buffer; + return value; + }, (err) => { + if (this._engine.isDisposed || this._engine.uniqueId !== engineId) { + // Engine disposed or context loss/restoration + return 0; + } + throw err; + }); + } + async readTwoValuesAndSubtract(firstQuery = 0) { + const buffer = this._getBuffer(firstQuery, 2); + if (buffer === null) { + return null; + } + const engineId = this._engine.uniqueId; + return buffer.mapAsync(1 /* WebGPUConstants.MapMode.Read */).then(() => { + const arrayBuf = new BigUint64Array(buffer.getMappedRange()); + const value = Number(arrayBuf[1] - arrayBuf[0]); + buffer.unmap(); + this._dstBuffers[this._dstBuffers.length] = buffer; + return value; + }, (err) => { + if (this._engine.isDisposed || this._engine.uniqueId !== engineId) { + // Engine disposed or context loss/restoration + return 0; + } + throw err; + }); + } + dispose() { + this._querySet.destroy(); + this._bufferManager.releaseBuffer(this._queryBuffer); + for (let i = 0; i < this._dstBuffers.length; ++i) { + this._bufferManager.releaseBuffer(this._dstBuffers[i]); + } + } +} + +/** @internal */ +class WebGPUTimestampQuery { + get gpuFrameTimeCounter() { + return this._gpuFrameTimeCounter; + } + constructor(engine, device, bufferManager) { + this._enabled = false; + this._gpuFrameTimeCounter = new PerfCounter(); + this._measureDurationState = 0; + this._engine = engine; + this._device = device; + this._bufferManager = bufferManager; + } + get enable() { + return this._enabled; + } + set enable(value) { + if (this._enabled === value) { + return; + } + this._enabled = value; + this._measureDurationState = 0; + if (value) { + try { + this._measureDuration = new WebGPUDurationMeasure(this._engine, this._device, this._bufferManager, 2000, "QuerySet_TimestampQuery"); + } + catch (e) { + this._enabled = false; + Logger.Error("Could not create a WebGPUDurationMeasure!\nError: " + e.message + "\nMake sure timestamp query is supported and enabled in your browser."); + return; + } + } + else { + this._measureDuration.dispose(); + } + } + startFrame(commandEncoder) { + if (this._enabled && this._measureDurationState === 0) { + this._measureDuration.start(commandEncoder); + this._measureDurationState = 1; + } + } + endFrame(commandEncoder) { + if (this._measureDurationState === 1) { + this._measureDurationState = 2; + this._measureDuration.stop(commandEncoder).then((duration) => { + if (duration !== null && duration >= 0) { + this._gpuFrameTimeCounter.fetchNewFrame(); + this._gpuFrameTimeCounter.addCount(duration, true); + } + this._measureDurationState = 0; + }); + } + } + startPass(descriptor, index) { + if (this._enabled) { + this._measureDuration.startPass(descriptor, index); + } + else { + descriptor.timestampWrites = undefined; + } + } + endPass(index, gpuPerfCounter) { + if (!this._enabled || !gpuPerfCounter) { + return; + } + const currentFrameId = this._engine.frameId; + this._measureDuration.stopPass(index).then((duration_) => { + gpuPerfCounter._addDuration(currentFrameId, duration_ !== null && duration_ > 0 ? duration_ : 0); + }); + } + dispose() { + this._measureDuration?.dispose(); + } +} +/** @internal */ +class WebGPUDurationMeasure { + constructor(engine, device, bufferManager, count = 2, querySetLabel) { + this._count = count; + this._querySet = new WebGPUQuerySet(engine, count, "timestamp" /* WebGPUConstants.QueryType.Timestamp */, device, bufferManager, true, querySetLabel); + } + start(encoder) { + encoder.writeTimestamp?.(this._querySet.querySet, 0); + } + async stop(encoder) { + encoder.writeTimestamp?.(this._querySet.querySet, 1); + return encoder.writeTimestamp ? this._querySet.readTwoValuesAndSubtract(0) : 0; + } + startPass(descriptor, index) { + if (index + 3 > this._count) { + throw new Error("WebGPUDurationMeasure: index out of range (" + index + ")"); + } + descriptor.timestampWrites = { + querySet: this._querySet.querySet, + beginningOfPassWriteIndex: index + 2, + endOfPassWriteIndex: index + 3, + }; + } + async stopPass(index) { + return this._querySet.readTwoValuesAndSubtract(index + 2); + } + dispose() { + this._querySet.dispose(); + } +} + +/** @internal */ +class WebGPUOcclusionQuery { + get querySet() { + return this._querySet.querySet; + } + get hasQueries() { + return this._currentTotalIndices !== this._availableIndices.length; + } + canBeginQuery(index) { + if (this._frameQuerySetIsDirty === this._engine.frameId || this._queryFrameId[index] === this._engine.frameId) { + return false; + } + const canBegin = this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet !== undefined; + if (canBegin) { + this._queryFrameId[index] = this._engine.frameId; + } + return canBegin; + } + constructor(engine, device, bufferManager, startCount = 50, incrementCount = 100) { + this._availableIndices = []; + this._frameQuerySetIsDirty = -1; + this._queryFrameId = []; + this._engine = engine; + this._device = device; + this._bufferManager = bufferManager; + this._frameLastBuffer = -1; + this._currentTotalIndices = 0; + this._countIncrement = incrementCount; + this._allocateNewIndices(startCount); + } + createQuery() { + if (this._availableIndices.length === 0) { + this._allocateNewIndices(); + } + const index = this._availableIndices[this._availableIndices.length - 1]; + this._availableIndices.length--; + return index; + } + deleteQuery(index) { + this._availableIndices[this._availableIndices.length] = index; + } + isQueryResultAvailable(index) { + this._retrieveQueryBuffer(); + return !!this._lastBuffer && index < this._lastBuffer.length; + } + getQueryResult(index) { + return Number(this._lastBuffer?.[index] ?? -1); + } + _retrieveQueryBuffer() { + if (this._lastBuffer && this._frameLastBuffer === this._engine.frameId) { + return; + } + if (this._frameLastBuffer !== this._engine.frameId) { + this._frameLastBuffer = this._engine.frameId; + this._querySet.readValues(0, this._currentTotalIndices).then((arrayBuffer) => { + this._lastBuffer = arrayBuffer; + }); + } + } + _allocateNewIndices(numIndices) { + numIndices = numIndices ?? this._countIncrement; + this._delayQuerySetDispose(); + for (let i = 0; i < numIndices; ++i) { + this._availableIndices.push(this._currentTotalIndices + i); + } + this._currentTotalIndices += numIndices; + this._querySet = new WebGPUQuerySet(this._engine, this._currentTotalIndices, "occlusion" /* WebGPUConstants.QueryType.Occlusion */, this._device, this._bufferManager, false, "QuerySet_OcclusionQuery_count_" + this._currentTotalIndices); + this._frameQuerySetIsDirty = this._engine.frameId; + } + _delayQuerySetDispose() { + const querySet = this._querySet; + if (querySet) { + // Wait a bit before disposing of the queryset, in case some queries are still running for it + setTimeout(() => querySet.dispose, 1000); + } + } + dispose() { + this._querySet?.dispose(); + this._availableIndices.length = 0; + } +} + +/** @internal */ +class WebGPUTintWASM { + async initTwgsl(twgslOptions) { + if (WebGPUTintWASM._Twgsl) { + return; + } + twgslOptions = twgslOptions || {}; + twgslOptions = { + ...WebGPUTintWASM._TWgslDefaultOptions, + ...twgslOptions, + }; + if (twgslOptions.twgsl) { + WebGPUTintWASM._Twgsl = twgslOptions.twgsl; + return Promise.resolve(); + } + if (twgslOptions.jsPath && twgslOptions.wasmPath) { + await Tools.LoadBabylonScriptAsync(twgslOptions.jsPath); + } + if (self.twgsl) { + WebGPUTintWASM._Twgsl = await self.twgsl(Tools.GetBabylonScriptURL(twgslOptions.wasmPath)); + return Promise.resolve(); + } + return Promise.reject("twgsl is not available."); + } + convertSpirV2WGSL(code, disableUniformityAnalysis = false) { + const ccode = WebGPUTintWASM._Twgsl.convertSpirV2WGSL(code, WebGPUTintWASM.DisableUniformityAnalysis || disableUniformityAnalysis); + if (WebGPUTintWASM.ShowWGSLShaderCode) { + Logger.Log(ccode); + Logger.Log("***********************************************"); + } + return WebGPUTintWASM.DisableUniformityAnalysis || disableUniformityAnalysis ? "diagnostic(off, derivative_uniformity);\n" + ccode : ccode; + } +} +// Default twgsl options. +WebGPUTintWASM._TWgslDefaultOptions = { + jsPath: `${Tools._DefaultCdnUrl}/twgsl/twgsl.js`, + wasmPath: `${Tools._DefaultCdnUrl}/twgsl/twgsl.wasm`, +}; +WebGPUTintWASM.ShowWGSLShaderCode = false; +WebGPUTintWASM.DisableUniformityAnalysis = false; +WebGPUTintWASM._Twgsl = null; + +/** @internal */ +class WebGPUSnapshotRendering { + constructor(engine, renderingMode, bundleList) { + this._record = false; + this._play = false; + this._playBundleListIndex = 0; + this._allBundleLists = []; + this._enabled = false; + this.showDebugLogs = false; + this._engine = engine; + this._mode = renderingMode; + this._bundleList = bundleList; + } + get enabled() { + return this._enabled; + } + get play() { + return this._play; + } + get record() { + return this._record; + } + set enabled(activate) { + this._log("enabled", `activate=${activate}, mode=${this._mode}`); + this._allBundleLists.length = 0; + this._record = this._enabled = activate; + this._play = false; + if (activate) { + this._modeSaved = this._mode; + this._mode = 0; // need to reset to standard for the recording pass to avoid some code being bypassed + } + } + get mode() { + return this._mode; + } + set mode(mode) { + if (this._record) { + this._modeSaved = mode; + } + else { + this._mode = mode; + } + } + endRenderPass(currentRenderPass) { + if (!this._record && !this._play) { + // Snapshot rendering mode is not enabled + return false; + } + let bundleList = null; + if (this._record) { + bundleList = this._bundleList.clone(); + this._allBundleLists.push(bundleList); + this._bundleList.reset(); + this._log("endRenderPass", `bundleList recorded at position #${this._allBundleLists.length - 1}`); + } + else { + // We are playing the snapshot + if (this._playBundleListIndex >= this._allBundleLists.length) { + this._log("endRenderPass", `empty or out-of-sync bundleList (_allBundleLists.length=${this._allBundleLists.length}, playBundleListIndex=${this._playBundleListIndex})`); + } + else { + this._log("endRenderPass", `run bundleList #${this._playBundleListIndex}`); + bundleList = this._allBundleLists[this._playBundleListIndex++]; + } + } + if (bundleList) { + bundleList.run(currentRenderPass); + if (this._mode === 1) { + this._engine._reportDrawCall(bundleList.numDrawCalls); + } + } + return true; + } + endFrame() { + if (this._record) { + // We stop recording and switch to replay mode for the next frames + this._record = false; + this._play = true; + this._mode = this._modeSaved; + this._log("endFrame", "bundles recorded, switching to play mode"); + } + this._playBundleListIndex = 0; + } + reset() { + this._log("reset", "called"); + if (this._record) { + this._mode = this._modeSaved; + } + this.enabled = false; + this.enabled = true; + } + _log(funcName, message) { + if (this.showDebugLogs) { + Logger.Log(`[Frame: ${this._engine.frameId}] WebGPUSnapshotRendering:${funcName} - ${message}`); + } + } +} + +/** + * Nothing specific to WebGPU in this class, but the spec is not final yet so let's remove it later on + * if it is not needed + * @internal + **/ +class WebGPUExternalTexture extends ExternalTexture { + constructor(video) { + super(video); + } +} + +ThinWebGPUEngine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) { + const texture = new InternalTexture(this, 3 /* InternalTextureSource.Raw */); + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.format = format; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.invertY = invertY; + texture._compression = compression; + texture.type = type; + texture._creationFlags = creationFlags; + texture._useSRGBBuffer = useSRGBBuffer; + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + } + this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, undefined, creationFlags); + this.updateRawTexture(texture, data, format, invertY, compression, type, useSRGBBuffer); + this._internalTexturesCache.push(texture); + return texture; +}; +ThinWebGPUEngine.prototype.updateRawTexture = function (texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) { + if (!texture) { + return; + } + if (!this._doNotHandleContextLost) { + texture._bufferView = bufferView; + texture.invertY = invertY; + texture._compression = compression; + texture._useSRGBBuffer = useSRGBBuffer; + } + if (bufferView) { + const gpuTextureWrapper = texture._hardwareTexture; + const needConversion = format === 4; + if (needConversion) { + bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, type); + } + const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength); + this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0); + if (texture.generateMipMaps) { + this._generateMipmaps(texture, this._uploadEncoder); + } + } + texture.isReady = true; +}; +ThinWebGPUEngine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) { + const texture = new InternalTexture(this, 8 /* InternalTextureSource.CubeRaw */); + if (type === 1 && !this._caps.textureFloatLinearFiltering) { + generateMipMaps = false; + samplingMode = 1; + Logger.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."); + } + else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { + generateMipMaps = false; + samplingMode = 1; + Logger.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."); + } + else if (type === 1 && !this._caps.textureFloatRender) { + generateMipMaps = false; + Logger.Warn("Render to float textures is not supported. Mipmap generation forced to false."); + } + else if (type === 2 && !this._caps.colorBufferFloat) { + generateMipMaps = false; + Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false."); + } + texture.isCube = true; + texture._originalFormat = format; + texture.format = format === 4 ? 5 : format; + texture.type = type; + texture.generateMipMaps = generateMipMaps; + texture.width = size; + texture.height = size; + texture.samplingMode = samplingMode; + if (!this._doNotHandleContextLost) { + texture._bufferViewArray = data; + } + texture.invertY = invertY; + texture._compression = compression; + texture._cachedWrapU = 0; + texture._cachedWrapV = 0; + this._textureHelper.createGPUTextureForInternalTexture(texture); + if (format === 4) { + const gpuTextureWrapper = texture._hardwareTexture; + gpuTextureWrapper._originalFormatIsRGB = true; + } + if (data) { + this.updateRawCubeTexture(texture, data, format, type, invertY, compression); + } + texture.isReady = true; + return texture; +}; +ThinWebGPUEngine.prototype.updateRawCubeTexture = function (texture, bufferView, _format, type, invertY, compression = null) { + texture._bufferViewArray = bufferView; + texture.invertY = invertY; + texture._compression = compression; + const gpuTextureWrapper = texture._hardwareTexture; + const needConversion = gpuTextureWrapper._originalFormatIsRGB; + const faces = [0, 2, 4, 1, 3, 5]; + const data = []; + for (let i = 0; i < bufferView.length; ++i) { + let faceData = bufferView[faces[i]]; + if (needConversion) { + faceData = _convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type); + } + data.push(new Uint8Array(faceData.buffer, faceData.byteOffset, faceData.byteLength)); + } + this._textureHelper.updateCubeTextures(data, gpuTextureWrapper.underlyingResource, texture.width, texture.height, gpuTextureWrapper.format, invertY, false, 0, 0); + if (texture.generateMipMaps) { + this._generateMipmaps(texture, this._uploadEncoder); + } + texture.isReady = true; +}; +ThinWebGPUEngine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) { + const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null); + scene?.addPendingData(texture); + texture.url = url; + texture.isReady = false; + this._internalTexturesCache.push(texture); + const onerror = (request, exception) => { + scene?.removePendingData(texture); + if (onError && request) { + onError(request.status + " " + request.statusText, exception); + } + }; + const internalCallback = (data) => { + const width = texture.width; + const faceDataArrays = callback(data); + if (!faceDataArrays) { + return; + } + if (mipmapGenerator) { + const needConversion = format === 4; + const mipData = mipmapGenerator(faceDataArrays); + const gpuTextureWrapper = texture._hardwareTexture; + const faces = [0, 1, 2, 3, 4, 5]; + for (let level = 0; level < mipData.length; level++) { + const mipSize = width >> level; + const allFaces = []; + for (let faceIndex = 0; faceIndex < 6; faceIndex++) { + let mipFaceData = mipData[level][faces[faceIndex]]; + if (needConversion) { + mipFaceData = _convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type); + } + allFaces.push(new Uint8Array(mipFaceData.buffer, mipFaceData.byteOffset, mipFaceData.byteLength)); + } + this._textureHelper.updateCubeTextures(allFaces, gpuTextureWrapper.underlyingResource, mipSize, mipSize, gpuTextureWrapper.format, invertY, false, 0, 0); + } + } + else { + this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY); + } + texture.isReady = true; + scene?.removePendingData(texture); + if (onLoad) { + onLoad(); + } + }; + this._loadFile(url, (data) => { + internalCallback(data); + }, undefined, scene?.offlineProvider, true, onerror); + return texture; +}; +ThinWebGPUEngine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0, creationFlags = 0) { + const source = 10 /* InternalTextureSource.Raw3D */; + const texture = new InternalTexture(this, source); + texture.baseWidth = width; + texture.baseHeight = height; + texture.baseDepth = depth; + texture.width = width; + texture.height = height; + texture.depth = depth; + texture.format = format; + texture.type = textureType; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.is3D = true; + texture._creationFlags = creationFlags; + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + } + this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, undefined, creationFlags); + this.updateRawTexture3D(texture, data, format, invertY, compression, textureType); + this._internalTexturesCache.push(texture); + return texture; +}; +ThinWebGPUEngine.prototype.updateRawTexture3D = function (texture, bufferView, format, invertY, compression = null, textureType = 0) { + if (!this._doNotHandleContextLost) { + texture._bufferView = bufferView; + texture.format = format; + texture.invertY = invertY; + texture._compression = compression; + } + if (bufferView) { + const gpuTextureWrapper = texture._hardwareTexture; + const needConversion = format === 4; + if (needConversion) { + bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, textureType); + } + const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength); + this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0); + if (texture.generateMipMaps) { + this._generateMipmaps(texture, this._uploadEncoder); + } + } + texture.isReady = true; +}; +ThinWebGPUEngine.prototype.createRawTexture2DArray = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0, creationFlags = 0) { + const source = 11 /* InternalTextureSource.Raw2DArray */; + const texture = new InternalTexture(this, source); + texture.baseWidth = width; + texture.baseHeight = height; + texture.baseDepth = depth; + texture.width = width; + texture.height = height; + texture.depth = depth; + texture.format = format; + texture.type = textureType; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.is2DArray = true; + texture._creationFlags = creationFlags; + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + } + this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth, creationFlags); + this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType); + this._internalTexturesCache.push(texture); + return texture; +}; +ThinWebGPUEngine.prototype.updateRawTexture2DArray = function (texture, bufferView, format, invertY, compression = null, textureType = 0) { + if (!this._doNotHandleContextLost) { + texture._bufferView = bufferView; + texture.format = format; + texture.invertY = invertY; + texture._compression = compression; + } + if (bufferView) { + const gpuTextureWrapper = texture._hardwareTexture; + const needConversion = format === 4; + if (needConversion) { + bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, textureType); + } + const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength); + this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0); + if (texture.generateMipMaps) { + this._generateMipmaps(texture, this._uploadEncoder); + } + } + texture.isReady = true; +}; +/** + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function _convertRGBtoRGBATextureData(rgbData, width, height, textureType) { + // Create new RGBA data container. + let rgbaData; + let val1 = 1; + if (textureType === 1) { + rgbaData = new Float32Array(width * height * 4); + } + else if (textureType === 2) { + rgbaData = new Uint16Array(width * height * 4); + val1 = 15360; // 15360 is the encoding of 1 in half float + } + else if (textureType === 7) { + rgbaData = new Uint32Array(width * height * 4); + } + else { + rgbaData = new Uint8Array(width * height * 4); + } + // Convert each pixel. + for (let x = 0; x < width; x++) { + for (let y = 0; y < height; y++) { + const index = (y * width + x) * 3; + const newIndex = (y * width + x) * 4; + // Map Old Value to new value. + rgbaData[newIndex + 0] = rgbData[index + 0]; + rgbaData[newIndex + 1] = rgbData[index + 1]; + rgbaData[newIndex + 2] = rgbData[index + 2]; + // Add fully opaque alpha channel. + rgbaData[newIndex + 3] = val1; + } + } + return rgbaData; +} + +ThinWebGPUEngine.prototype._readTexturePixels = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) { + const gpuTextureWrapper = texture._hardwareTexture; + if (flushRenderer) { + this.flushFramebuffer(); + } + return this._textureHelper.readPixels(gpuTextureWrapper.underlyingResource, x, y, width, height, gpuTextureWrapper.format, faceIndex, level, buffer, noDataConversion); +}; +ThinWebGPUEngine.prototype._readTexturePixelsSync = function () { + // eslint-disable-next-line no-throw-literal + throw "_readTexturePixelsSync is unsupported in WebGPU!"; +}; + +ThinWebGPUEngine.prototype._createDepthStencilCubeTexture = function (size, options) { + const internalTexture = new InternalTexture(this, options.generateStencil ? 12 /* InternalTextureSource.DepthStencil */ : 14 /* InternalTextureSource.Depth */); + internalTexture.isCube = true; + internalTexture.label = options.label; + const internalOptions = { + bilinearFiltering: false, + comparisonFunction: 0, + samples: 1, + depthTextureFormat: options.generateStencil ? 13 : 14, + ...options, + }; + internalTexture.format = internalOptions.depthTextureFormat; + this._setupDepthStencilTexture(internalTexture, size, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples); + this._textureHelper.createGPUTextureForInternalTexture(internalTexture); + // Now that the hardware texture is created, we can retrieve the GPU format and set the right type to the internal texture + const gpuTextureWrapper = internalTexture._hardwareTexture; + internalTexture.type = WebGPUTextureHelper.GetTextureTypeFromFormat(gpuTextureWrapper.format); + this._internalTexturesCache.push(internalTexture); + return internalTexture; +}; +ThinWebGPUEngine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false, buffer = null) { + return this.createCubeTextureBase(rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, null, (texture, imgs) => { + const imageBitmaps = imgs; // we will always get an ImageBitmap array in WebGPU + const width = imageBitmaps[0].width; + const height = width; + this._setCubeMapTextureParams(texture, !noMipmap); + texture.format = format ?? -1; + const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height); + this._textureHelper.updateCubeTextures(imageBitmaps, gpuTextureWrapper.underlyingResource, width, height, gpuTextureWrapper.format, false, false, 0, 0); + if (!noMipmap) { + this._generateMipmaps(texture, this._uploadEncoder); + } + texture.isReady = true; + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + if (onLoad) { + onLoad(); + } + }, !!useSRGBBuffer, buffer); +}; +ThinWebGPUEngine.prototype._setCubeMapTextureParams = function (texture, loadMipmap, maxLevel) { + texture.samplingMode = loadMipmap ? 3 : 2; + texture._cachedWrapU = 0; + texture._cachedWrapV = 0; + if (maxLevel) { + texture._maxLodLevel = maxLevel; + } +}; +ThinWebGPUEngine.prototype.generateMipMapsForCubemap = function (texture) { + if (texture.generateMipMaps) { + const gpuTexture = texture._hardwareTexture?.underlyingResource; + if (!gpuTexture) { + this._textureHelper.createGPUTextureForInternalTexture(texture); + } + this._generateMipmaps(texture); + } +}; + +/** + * Specialized class used to store a render target of a WebGPU engine + */ +class WebGPURenderTargetWrapper extends RenderTargetWrapper { + /** + * Initializes the render target wrapper + * @param isMulti true if the wrapper is a multi render target + * @param isCube true if the wrapper should render to a cube texture + * @param size size of the render target (width/height/layers) + * @param engine engine used to create the render target + * @param label defines the label to use for the wrapper (for debugging purpose only) + */ + constructor(isMulti, isCube, size, engine, label) { + super(isMulti, isCube, size, engine, label); + if (engine.enableGPUTimingMeasurements) { + this.gpuTimeInFrame = new WebGPUPerfCounter(); + } + } +} + +ThinWebGPUEngine.prototype._createHardwareRenderTargetWrapper = function (isMulti, isCube, size) { + const rtWrapper = new WebGPURenderTargetWrapper(isMulti, isCube, size, this); + this._renderTargetWrapperCache.push(rtWrapper); + return rtWrapper; +}; +ThinWebGPUEngine.prototype.createRenderTargetTexture = function (size, options) { + const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size); + const fullOptions = {}; + if (options !== undefined && typeof options === "object") { + fullOptions.generateMipMaps = options.generateMipMaps; + fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; + fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer; + fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode; + fullOptions.creationFlags = options.creationFlags ?? 0; + fullOptions.noColorAttachment = !!options.noColorAttachment; + fullOptions.colorAttachment = options.colorAttachment; + fullOptions.samples = options.samples; + fullOptions.label = options.label; + fullOptions.format = options.format; + fullOptions.type = options.type; + } + else { + fullOptions.generateMipMaps = options; + fullOptions.generateDepthBuffer = true; + fullOptions.generateStencilBuffer = false; + fullOptions.samplingMode = 3; + fullOptions.creationFlags = 0; + fullOptions.noColorAttachment = false; + } + const texture = fullOptions.colorAttachment || (fullOptions.noColorAttachment ? null : this._createInternalTexture(size, fullOptions, true, 5 /* InternalTextureSource.RenderTarget */)); + rtWrapper.label = fullOptions.label ?? "RenderTargetWrapper"; + rtWrapper._samples = fullOptions.colorAttachment?.samples ?? fullOptions.samples ?? 1; + rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer; + rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false; + rtWrapper.setTextures(texture); + if (rtWrapper._generateDepthBuffer || rtWrapper._generateStencilBuffer) { + rtWrapper.createDepthStencilTexture(0, false, // force false as filtering is not supported for depth textures + rtWrapper._generateStencilBuffer, rtWrapper.samples, fullOptions.generateStencilBuffer ? 13 : 14, fullOptions.label ? fullOptions.label + "-DepthStencil" : undefined); + } + if (texture && !fullOptions.colorAttachment) { + if (options !== undefined && typeof options === "object" && options.createMipMaps && !fullOptions.generateMipMaps) { + texture.generateMipMaps = true; + } + this._textureHelper.createGPUTextureForInternalTexture(texture, undefined, undefined, undefined, fullOptions.creationFlags); + if (options !== undefined && typeof options === "object" && options.createMipMaps && !fullOptions.generateMipMaps) { + texture.generateMipMaps = false; + } + } + return rtWrapper; +}; +ThinWebGPUEngine.prototype._createDepthStencilTexture = function (size, options, wrapper) { + const internalOptions = { + bilinearFiltering: false, + comparisonFunction: 0, + samples: 1, + depthTextureFormat: options.generateStencil ? 13 : 14, + ...options, + }; + const hasStencil = HasStencilAspect(internalOptions.depthTextureFormat); + wrapper._depthStencilTextureWithStencil = hasStencil; + const internalTexture = new InternalTexture(this, hasStencil ? 12 /* InternalTextureSource.DepthStencil */ : 14 /* InternalTextureSource.Depth */); + internalTexture.label = options.label; + internalTexture.format = internalOptions.depthTextureFormat; + internalTexture.type = GetTypeForDepthTexture(internalTexture.format); + this._setupDepthStencilTexture(internalTexture, size, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples); + this._textureHelper.createGPUTextureForInternalTexture(internalTexture); + this._internalTexturesCache.push(internalTexture); + return internalTexture; +}; +ThinWebGPUEngine.prototype._setupDepthStencilTexture = function (internalTexture, size, bilinearFiltering, comparisonFunction, samples = 1) { + const width = size.width ?? size; + const height = size.height ?? size; + const layers = size.layers || 0; + const depth = size.depth || 0; + internalTexture.baseWidth = width; + internalTexture.baseHeight = height; + internalTexture.width = width; + internalTexture.height = height; + internalTexture.is2DArray = layers > 0; + internalTexture.is3D = depth > 0; + internalTexture.depth = layers || depth; + internalTexture.isReady = true; + internalTexture.samples = samples; + internalTexture.generateMipMaps = false; + internalTexture.samplingMode = bilinearFiltering ? 2 : 1; + internalTexture.type = 1; // the right type will be set later + internalTexture._comparisonFunction = comparisonFunction; + internalTexture._cachedWrapU = 0; + internalTexture._cachedWrapV = 0; +}; +ThinWebGPUEngine.prototype.updateRenderTargetTextureSampleCount = function (rtWrapper, samples) { + if (!rtWrapper || !rtWrapper.texture || rtWrapper.samples === samples) { + return samples; + } + samples = Math.min(samples, this.getCaps().maxMSAASamples); + this._textureHelper.createMSAATexture(rtWrapper.texture, samples); + if (rtWrapper._depthStencilTexture) { + this._textureHelper.createMSAATexture(rtWrapper._depthStencilTexture, samples); + rtWrapper._depthStencilTexture.samples = samples; + } + rtWrapper._samples = samples; + rtWrapper.texture.samples = samples; + return samples; +}; + +ThinWebGPUEngine.prototype.setDepthStencilTexture = function (channel, uniform, texture, name) { + if (!texture || !texture.depthStencilTexture) { + this._setTexture(channel, null, undefined, undefined, name); + } + else { + this._setTexture(channel, texture, false, true, name); + } +}; + +ThinWebGPUEngine.prototype.createRenderTargetCubeTexture = function (size, options) { + const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size); + const fullOptions = { + generateMipMaps: true, + generateDepthBuffer: true, + generateStencilBuffer: false, + type: 0, + samplingMode: 3, + format: 5, + samples: 1, + ...options, + }; + fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer; + rtWrapper.label = fullOptions.label ?? "RenderTargetWrapper"; + rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer; + rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer; + const texture = new InternalTexture(this, 5 /* InternalTextureSource.RenderTarget */); + texture.width = size; + texture.height = size; + texture.depth = 0; + texture.isReady = true; + texture.isCube = true; + texture.samples = fullOptions.samples; + texture.generateMipMaps = fullOptions.generateMipMaps; + texture.samplingMode = fullOptions.samplingMode; + texture.type = fullOptions.type; + texture.format = fullOptions.format; + this._internalTexturesCache.push(texture); + rtWrapper.setTextures(texture); + if (rtWrapper._generateDepthBuffer || rtWrapper._generateStencilBuffer) { + rtWrapper.createDepthStencilTexture(0, fullOptions.samplingMode === undefined || + fullOptions.samplingMode === 2 || + fullOptions.samplingMode === 2 || + fullOptions.samplingMode === 3 || + fullOptions.samplingMode === 3 || + fullOptions.samplingMode === 5 || + fullOptions.samplingMode === 6 || + fullOptions.samplingMode === 7 || + fullOptions.samplingMode === 11, rtWrapper._generateStencilBuffer, rtWrapper.samples); + } + if (options && options.createMipMaps && !fullOptions.generateMipMaps) { + texture.generateMipMaps = true; + } + this._textureHelper.createGPUTextureForInternalTexture(texture); + if (options && options.createMipMaps && !fullOptions.generateMipMaps) { + texture.generateMipMaps = false; + } + return rtWrapper; +}; + +ThinWebGPUEngine.prototype.getGPUFrameTimeCounter = function () { + return this._timestampQuery.gpuFrameTimeCounter; +}; +ThinWebGPUEngine.prototype.captureGPUFrameTime = function (value) { + this._timestampQuery.enable = value && !!this._caps.timerQuery; +}; +ThinWebGPUEngine.prototype.createQuery = function () { + return this._occlusionQuery.createQuery(); +}; +ThinWebGPUEngine.prototype.deleteQuery = function (query) { + this._occlusionQuery.deleteQuery(query); + return this; +}; +ThinWebGPUEngine.prototype.isQueryResultAvailable = function (query) { + return this._occlusionQuery.isQueryResultAvailable(query); +}; +ThinWebGPUEngine.prototype.getQueryResult = function (query) { + return this._occlusionQuery.getQueryResult(query); +}; +ThinWebGPUEngine.prototype.beginOcclusionQuery = function (algorithmType, query) { + if (this.compatibilityMode) { + if (this._occlusionQuery.canBeginQuery(query)) { + this._currentRenderPass?.beginOcclusionQuery(query); + return true; + } + } + else { + this._bundleList.addItem(new WebGPURenderItemBeginOcclusionQuery(query)); + return true; + } + return false; +}; +ThinWebGPUEngine.prototype.endOcclusionQuery = function () { + if (this.compatibilityMode) { + this._currentRenderPass?.endOcclusionQuery(); + } + else { + this._bundleList.addItem(new WebGPURenderItemEndOcclusionQuery()); + } + return this; +}; + +/* eslint-disable babylonjs/available */ +const viewDescriptorSwapChainAntialiasing = { + label: `TextureView_SwapChain_ResolveTarget`, + dimension: "2d" /* WebGPUConstants.TextureDimension.E2d */, + format: undefined, // will be updated with the right value + mipLevelCount: 1, + arrayLayerCount: 1, +}; +const viewDescriptorSwapChain = { + label: `TextureView_SwapChain`, + dimension: "2d" /* WebGPUConstants.TextureDimension.E2d */, + format: undefined, // will be updated with the right value + mipLevelCount: 1, + arrayLayerCount: 1, +}; +const tempColor4 = new Color4(); +/** + * The web GPU engine class provides support for WebGPU version of babylon.js. + * @since 5.0.0 + */ +class WebGPUEngine extends ThinWebGPUEngine { + /** + * Gets or sets the snapshot rendering mode + */ + get snapshotRenderingMode() { + return this._snapshotRendering.mode; + } + set snapshotRenderingMode(mode) { + this._snapshotRendering.mode = mode; + } + /** + * Creates a new snapshot at the next frame using the current snapshotRenderingMode + */ + snapshotRenderingReset() { + this._snapshotRendering.reset(); + } + /** + * Enables or disables the snapshot rendering mode + * Note that the WebGL engine does not support snapshot rendering so setting the value won't have any effect for this engine + */ + get snapshotRendering() { + return this._snapshotRendering.enabled; + } + set snapshotRendering(activate) { + this._snapshotRendering.enabled = activate; + } + /** + * Sets this to true to disable the cache for the samplers. You should do it only for testing purpose! + */ + get disableCacheSamplers() { + return this._cacheSampler ? this._cacheSampler.disabled : false; + } + set disableCacheSamplers(disable) { + if (this._cacheSampler) { + this._cacheSampler.disabled = disable; + } + } + /** + * Sets this to true to disable the cache for the render pipelines. You should do it only for testing purpose! + */ + get disableCacheRenderPipelines() { + return this._cacheRenderPipeline ? this._cacheRenderPipeline.disabled : false; + } + set disableCacheRenderPipelines(disable) { + if (this._cacheRenderPipeline) { + this._cacheRenderPipeline.disabled = disable; + } + } + /** + * Sets this to true to disable the cache for the bind groups. You should do it only for testing purpose! + */ + get disableCacheBindGroups() { + return this._cacheBindGroups ? this._cacheBindGroups.disabled : false; + } + set disableCacheBindGroups(disable) { + if (this._cacheBindGroups) { + this._cacheBindGroups.disabled = disable; + } + } + /** + * Gets a boolean indicating if all created effects are ready + * @returns true if all effects are ready + */ + areAllEffectsReady() { + return true; + } + /** + * Get Font size information + * @param font font name + * @returns an object containing ascent, height and descent + */ + getFontOffset(font) { + return GetFontOffset(font); + } + /** + * Gets a Promise indicating if the engine can be instantiated (ie. if a WebGPU context can be found) + */ + static get IsSupportedAsync() { + return !navigator.gpu + ? Promise.resolve(false) + : navigator.gpu + .requestAdapter() + .then((adapter) => !!adapter, () => false) + .catch(() => false); + } + /** + * Not supported by WebGPU, you should call IsSupportedAsync instead! + */ + static get IsSupported() { + Logger.Warn("You must call IsSupportedAsync for WebGPU!"); + return false; + } + /** + * Gets a boolean indicating that the engine supports uniform buffers + */ + get supportsUniformBuffers() { + return true; + } + /** Gets the supported extensions by the WebGPU adapter */ + get supportedExtensions() { + return this._adapterSupportedExtensions; + } + /** Gets the currently enabled extensions on the WebGPU device */ + get enabledExtensions() { + return this._deviceEnabledExtensions; + } + /** Gets the supported limits by the WebGPU adapter */ + get supportedLimits() { + return this._adapterSupportedLimits; + } + /** Gets the current limits of the WebGPU device */ + get currentLimits() { + return this._deviceLimits; + } + /** + * Returns a string describing the current engine + */ + get description() { + const description = this.name + this.version; + return description; + } + /** + * Returns the version of the engine + */ + get version() { + return 1; + } + /** + * Gets an object containing information about the current engine context + * @returns an object containing the vendor, the renderer and the version of the current engine context + */ + getInfo() { + return { + vendor: this._adapterInfo.vendor || "unknown vendor", + renderer: this._adapterInfo.architecture || "unknown renderer", + version: this._adapterInfo.description || "unknown version", + }; + } + /** + * (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL). + * Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken. + * See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details + */ + get compatibilityMode() { + return this._compatibilityMode; + } + set compatibilityMode(mode) { + this._compatibilityMode = mode; + } + /** @internal */ + get currentSampleCount() { + return this._currentRenderTarget ? this._currentRenderTarget.samples : this._mainPassSampleCount; + } + /** + * Create a new instance of the gpu engine asynchronously + * @param canvas Defines the canvas to use to display the result + * @param options Defines the options passed to the engine to create the GPU context dependencies + * @returns a promise that resolves with the created engine + */ + static CreateAsync(canvas, options = {}) { + const engine = new WebGPUEngine(canvas, options); + return new Promise((resolve) => { + engine.initAsync(options.glslangOptions, options.twgslOptions).then(() => resolve(engine)); + }); + } + /** + * Create a new instance of the gpu engine. + * @param canvas Defines the canvas to use to display the result + * @param options Defines the options passed to the engine to create the GPU context dependencies + */ + constructor(canvas, options = {}) { + super(options.antialias ?? true, options); + /** A unique id to identify this instance */ + this.uniqueId = -1; + // Page Life cycle and constants + this._uploadEncoderDescriptor = { label: "upload" }; + this._renderEncoderDescriptor = { label: "render" }; + /** @internal */ + this._clearDepthValue = 1; + /** @internal */ + this._clearReverseDepthValue = 0; + /** @internal */ + this._clearStencilValue = 0; + this._defaultSampleCount = 4; // Only supported value for now. + this._glslang = null; + this._tintWASM = null; + this._glslangAndTintAreFullyLoaded = false; + this._adapterInfo = { + vendor: "", + architecture: "", + device: "", + description: "", + }; + /** @internal */ + this._compiledComputeEffects = {}; + /** @internal */ + this._counters = { + numEnableEffects: 0, + numEnableDrawWrapper: 0, + numBundleCreationNonCompatMode: 0, + numBundleReuseNonCompatMode: 0, + }; + /** + * Counters from last frame + */ + this.countersLastFrame = { + numEnableEffects: 0, + numEnableDrawWrapper: 0, + numBundleCreationNonCompatMode: 0, + numBundleReuseNonCompatMode: 0, + }; + /** + * Max number of uncaptured error messages to log + */ + this.numMaxUncapturedErrors = 20; + /** + * Gets the list of created scenes + */ + this.scenes = []; + /** @internal */ + this._virtualScenes = new Array(); + this._commandBuffers = [null, null]; + // Frame Buffer Life Cycle (recreated for each render target pass) + this._mainRenderPassWrapper = { + renderPassDescriptor: null, + colorAttachmentViewDescriptor: null, + depthAttachmentViewDescriptor: null, + colorAttachmentGPUTextures: [], + depthTextureFormat: undefined, + }; + this._rttRenderPassWrapper = { + renderPassDescriptor: null, + colorAttachmentViewDescriptor: null, + depthAttachmentViewDescriptor: null, + colorAttachmentGPUTextures: [], + depthTextureFormat: undefined, + }; + /** @internal */ + this._pendingDebugCommands = []; + this._currentOverrideVertexBuffers = null; + this._currentIndexBuffer = null; + this._colorWriteLocal = true; + this._forceEnableEffect = false; + /** + * Indicates if the z range in NDC space is 0..1 (value: true) or -1..1 (value: false) + */ + this.isNDCHalfZRange = true; + /** + * Indicates that the origin of the texture/framebuffer space is the bottom left corner. If false, the origin is top left + */ + this.hasOriginBottomLeft = false; + //------------------------------------------------------------------------------ + // Initialization + //------------------------------------------------------------------------------ + this._workingGlslangAndTintPromise = null; + //------------------------------------------------------------------------------ + // Dynamic WebGPU States + //------------------------------------------------------------------------------ + // index 0 is for main render pass, 1 for RTT render pass + this._viewportsCurrent = { x: 0, y: 0, w: 0, h: 0 }; + this._scissorsCurrent = { x: 0, y: 0, w: 0, h: 0 }; + this._scissorCached = { x: 0, y: 0, z: 0, w: 0 }; + this._stencilRefsCurrent = -1; + this._blendColorsCurrent = [null, null, null, null]; + this._performanceMonitor = new PerformanceMonitor(); + this._name = "WebGPU"; + this._drawCalls = new PerfCounter(); + options.deviceDescriptor = options.deviceDescriptor || {}; + options.enableGPUDebugMarkers = options.enableGPUDebugMarkers ?? false; + Logger.Log(`Babylon.js v${AbstractEngine.Version} - ${this.description} engine`); + if (!navigator.gpu) { + Logger.Error("WebGPU is not supported by your browser."); + return; + } + options.swapChainFormat = options.swapChainFormat || navigator.gpu.getPreferredCanvasFormat(); + this._isWebGPU = true; + this._shaderPlatformName = "WEBGPU"; + this._renderingCanvas = canvas; + this._options = options; + this._mainPassSampleCount = options.antialias ? this._defaultSampleCount : 1; + if (navigator && navigator.userAgent) { + this._setupMobileChecks(); + } + this._sharedInit(this._renderingCanvas); + this._shaderProcessor = new WebGPUShaderProcessorGLSL(); + this._shaderProcessorWGSL = new WebGPUShaderProcessorWGSL(); + } + /** + * Load the glslang and tintWASM libraries and prepare them for use. + * @returns a promise that resolves when the engine is ready to use the glslang and tintWASM + */ + prepareGlslangAndTintAsync() { + if (!this._workingGlslangAndTintPromise) { + this._workingGlslangAndTintPromise = new Promise((resolve) => { + this._initGlslang(this._glslangOptions ?? this._options?.glslangOptions).then((glslang) => { + this._glslang = glslang; + this._tintWASM = new WebGPUTintWASM(); + this._tintWASM.initTwgsl(this._twgslOptions ?? this._options?.twgslOptions).then(() => { + this._glslangAndTintAreFullyLoaded = true; + resolve(); + }); + }); + }); + } + return this._workingGlslangAndTintPromise; + } + /** + * Initializes the WebGPU context and dependencies. + * @param glslangOptions Defines the GLSLang compiler options if necessary + * @param twgslOptions Defines the Twgsl compiler options if necessary + * @returns a promise notifying the readiness of the engine. + */ + initAsync(glslangOptions, twgslOptions) { + this.uniqueId = WebGPUEngine._InstanceId++; + this._glslangOptions = glslangOptions; + this._twgslOptions = twgslOptions; + return navigator + .gpu.requestAdapter(this._options) + .then((adapter) => { + if (!adapter) { + // eslint-disable-next-line no-throw-literal + throw "Could not retrieve a WebGPU adapter (adapter is null)."; + } + else { + this._adapter = adapter; + this._adapterSupportedExtensions = []; + this._adapter.features?.forEach((feature) => this._adapterSupportedExtensions.push(feature)); + this._adapterSupportedLimits = this._adapter.limits; + this._adapterInfo = this._adapter.info; + const deviceDescriptor = this._options.deviceDescriptor ?? {}; + const requiredFeatures = deviceDescriptor?.requiredFeatures ?? (this._options.enableAllFeatures ? this._adapterSupportedExtensions : undefined); + if (requiredFeatures) { + const requestedExtensions = requiredFeatures; + const validExtensions = []; + for (const extension of requestedExtensions) { + if (this._adapterSupportedExtensions.indexOf(extension) !== -1) { + validExtensions.push(extension); + } + } + deviceDescriptor.requiredFeatures = validExtensions; + } + if (this._options.setMaximumLimits && !deviceDescriptor.requiredLimits) { + deviceDescriptor.requiredLimits = {}; + for (const name in this._adapterSupportedLimits) { + if (name === "minSubgroupSize" || name === "maxSubgroupSize") { + // Chrome exposes these limits in "webgpu developer" mode, but these can't be set on the device. + continue; + } + deviceDescriptor.requiredLimits[name] = this._adapterSupportedLimits[name]; + } + } + deviceDescriptor.label = `BabylonWebGPUDevice${this.uniqueId}`; + return this._adapter.requestDevice(deviceDescriptor); + } + }) + .then((device) => { + this._device = device; + this._deviceEnabledExtensions = []; + this._device.features?.forEach((feature) => this._deviceEnabledExtensions.push(feature)); + this._deviceLimits = device.limits; + let numUncapturedErrors = -1; + this._device.addEventListener("uncapturederror", (event) => { + if (++numUncapturedErrors < this.numMaxUncapturedErrors) { + Logger.Warn(`WebGPU uncaptured error (${numUncapturedErrors + 1}): ${event.error} - ${event.error.message}`); + } + else if (numUncapturedErrors++ === this.numMaxUncapturedErrors) { + Logger.Warn(`WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`); + } + }); + if (!this._doNotHandleContextLost) { + this._device.lost?.then((info) => { + if (this._isDisposed) { + return; + } + this._contextWasLost = true; + Logger.Warn("WebGPU context lost. " + info); + this.onContextLostObservable.notifyObservers(this); + this._restoreEngineAfterContextLost(async () => { + const snapshotRenderingMode = this.snapshotRenderingMode; + const snapshotRendering = this.snapshotRendering; + const disableCacheSamplers = this.disableCacheSamplers; + const disableCacheRenderPipelines = this.disableCacheRenderPipelines; + const disableCacheBindGroups = this.disableCacheBindGroups; + const enableGPUTimingMeasurements = this.enableGPUTimingMeasurements; + await this.initAsync(this._glslangOptions ?? this._options?.glslangOptions, this._twgslOptions ?? this._options?.twgslOptions); + this.snapshotRenderingMode = snapshotRenderingMode; + this.snapshotRendering = snapshotRendering; + this.disableCacheSamplers = disableCacheSamplers; + this.disableCacheRenderPipelines = disableCacheRenderPipelines; + this.disableCacheBindGroups = disableCacheBindGroups; + this.enableGPUTimingMeasurements = enableGPUTimingMeasurements; + this._currentRenderPass = null; + }); + }); + } + }) + .then(() => { + this._initializeLimits(); + this._bufferManager = new WebGPUBufferManager(this, this._device); + this._textureHelper = new WebGPUTextureManager(this, this._device, this._bufferManager, this._deviceEnabledExtensions); + this._cacheSampler = new WebGPUCacheSampler(this._device); + this._cacheBindGroups = new WebGPUCacheBindGroups(this._device, this._cacheSampler, this); + this._timestampQuery = new WebGPUTimestampQuery(this, this._device, this._bufferManager); + this._occlusionQuery = this._device.createQuerySet ? new WebGPUOcclusionQuery(this, this._device, this._bufferManager) : undefined; + this._bundleList = new WebGPUBundleList(this._device); + this._snapshotRendering = new WebGPUSnapshotRendering(this, this._snapshotRenderingMode, this._bundleList); + this._ubInvertY = this._bufferManager.createBuffer(new Float32Array([-1, 0]), BufferUsage.Uniform | BufferUsage.CopyDst, "UBInvertY"); + this._ubDontInvertY = this._bufferManager.createBuffer(new Float32Array([1, 0]), BufferUsage.Uniform | BufferUsage.CopyDst, "UBDontInvertY"); + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + Logger.Log(["%c frame #" + this._count + " - begin", "background: #ffff00"]); + } + } + this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor); + this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor); + this._emptyVertexBuffer = new VertexBuffer(this, [0], "", { + stride: 1, + offset: 0, + size: 1, + label: "EmptyVertexBuffer", + }); + this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, this._emptyVertexBuffer); + this._depthCullingState = new WebGPUDepthCullingState(this._cacheRenderPipeline); + this._stencilStateComposer = new WebGPUStencilStateComposer(this._cacheRenderPipeline); + this._stencilStateComposer.stencilGlobal = this._stencilState; + this._depthCullingState.depthTest = true; + this._depthCullingState.depthFunc = 515; + this._depthCullingState.depthMask = true; + this._textureHelper.setCommandEncoder(this._uploadEncoder); + this._clearQuad = new WebGPUClearQuad(this._device, this, this._emptyVertexBuffer); + this._defaultDrawContext = this.createDrawContext(); + this._currentDrawContext = this._defaultDrawContext; + this._defaultMaterialContext = this.createMaterialContext(); + this._currentMaterialContext = this._defaultMaterialContext; + this._initializeContextAndSwapChain(); + this._initializeMainAttachments(); + this.resize(); + }) + .catch((e) => { + Logger.Error("A fatal error occurred during WebGPU creation/initialization."); + throw e; + }); + } + _initGlslang(glslangOptions) { + glslangOptions = glslangOptions || {}; + glslangOptions = { + ...WebGPUEngine._GlslangDefaultOptions, + ...glslangOptions, + }; + if (glslangOptions.glslang) { + return Promise.resolve(glslangOptions.glslang); + } + if (self.glslang) { + return self.glslang(glslangOptions.wasmPath); + } + if (glslangOptions.jsPath && glslangOptions.wasmPath) { + return Tools.LoadBabylonScriptAsync(glslangOptions.jsPath).then(() => { + return self.glslang(Tools.GetBabylonScriptURL(glslangOptions.wasmPath)); + }); + } + return Promise.reject("gslang is not available."); + } + _initializeLimits() { + // Init caps + // TODO WEBGPU Real Capability check once limits will be working. + this._caps = { + maxTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage, + maxVertexTextureImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage, + maxCombinedTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage * 2, + maxTextureSize: this._deviceLimits.maxTextureDimension2D, + maxCubemapTextureSize: this._deviceLimits.maxTextureDimension2D, + maxRenderTextureSize: this._deviceLimits.maxTextureDimension2D, + maxVertexAttribs: this._deviceLimits.maxVertexAttributes, + maxDrawBuffers: 8, + maxVaryingVectors: this._deviceLimits.maxInterStageShaderVariables, + maxFragmentUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4), + maxVertexUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4), + standardDerivatives: true, + astc: (this._deviceEnabledExtensions.indexOf("texture-compression-astc" /* WebGPUConstants.FeatureName.TextureCompressionASTC */) >= 0 ? true : undefined), + s3tc: (this._deviceEnabledExtensions.indexOf("texture-compression-bc" /* WebGPUConstants.FeatureName.TextureCompressionBC */) >= 0 ? true : undefined), + pvrtc: null, + etc1: null, + etc2: (this._deviceEnabledExtensions.indexOf("texture-compression-etc2" /* WebGPUConstants.FeatureName.TextureCompressionETC2 */) >= 0 ? true : undefined), + bptc: this._deviceEnabledExtensions.indexOf("texture-compression-bc" /* WebGPUConstants.FeatureName.TextureCompressionBC */) >= 0 ? true : undefined, + maxAnisotropy: 16, // Most implementations support maxAnisotropy values in range between 1 and 16, inclusive. The used value of maxAnisotropy will be clamped to the maximum value that the platform supports. + uintIndices: true, + fragmentDepthSupported: true, + highPrecisionShaderSupported: true, + colorBufferFloat: true, + supportFloatTexturesResolve: false, // See https://github.com/gpuweb/gpuweb/issues/3844 + rg11b10ufColorRenderable: this._deviceEnabledExtensions.indexOf("rg11b10ufloat-renderable" /* WebGPUConstants.FeatureName.RG11B10UFloatRenderable */) >= 0, + textureFloat: true, + textureFloatLinearFiltering: this._deviceEnabledExtensions.indexOf("float32-filterable" /* WebGPUConstants.FeatureName.Float32Filterable */) >= 0, + textureFloatRender: true, + textureHalfFloat: true, + textureHalfFloatLinearFiltering: true, + textureHalfFloatRender: true, + textureLOD: true, + texelFetch: true, + drawBuffersExtension: true, + depthTextureExtension: true, + vertexArrayObject: false, + instancedArrays: true, + timerQuery: typeof BigUint64Array !== "undefined" && this._deviceEnabledExtensions.indexOf("timestamp-query" /* WebGPUConstants.FeatureName.TimestampQuery */) !== -1 ? true : undefined, + supportOcclusionQuery: typeof BigUint64Array !== "undefined", + canUseTimestampForTimerQuery: true, + multiview: false, + oculusMultiview: false, + parallelShaderCompile: undefined, + blendMinMax: true, + maxMSAASamples: 4, // the spec only supports values of 1 and 4 + canUseGLInstanceID: true, + canUseGLVertexID: true, + supportComputeShaders: true, + supportSRGBBuffers: true, + supportTransformFeedbacks: false, + textureMaxLevel: true, + texture2DArrayMaxLayerCount: this._deviceLimits.maxTextureArrayLayers, + disableMorphTargetTexture: false, + textureNorm16: false, // in the works: https://github.com/gpuweb/gpuweb/issues/3001 + }; + this._features = { + forceBitmapOverHTMLImageElement: true, + supportRenderAndCopyToLodForFloatTextures: true, + supportDepthStencilTexture: true, + supportShadowSamplers: true, + uniformBufferHardCheckMatrix: false, + allowTexturePrefiltering: true, + trackUbosInFrame: true, + checkUbosContentBeforeUpload: true, + supportCSM: true, + basisNeedsPOT: false, + support3DTextures: true, + needTypeSuffixInShaderConstants: true, + supportMSAA: true, + supportSSAO2: true, + supportIBLShadows: true, + supportExtendedTextureFormats: true, + supportSwitchCaseInShader: true, + supportSyncTextureRead: false, + needsInvertingBitmap: false, + useUBOBindingCache: false, + needShaderCodeInlining: true, + needToAlwaysBindUniformBuffers: true, + supportRenderPasses: true, + supportSpriteInstancing: true, + forceVertexBufferStrideAndOffsetMultiple4Bytes: true, + _checkNonFloatVertexBuffersDontRecreatePipelineContext: true, + _collectUbosUpdatedInFrame: false, + }; + } + _initializeContextAndSwapChain() { + if (!this._renderingCanvas) { + // eslint-disable-next-line no-throw-literal + throw "The rendering canvas has not been set!"; + } + this._context = this._renderingCanvas.getContext("webgpu"); + this._configureContext(); + this._colorFormat = this._options.swapChainFormat; + this._mainRenderPassWrapper.colorAttachmentGPUTextures = [new WebGPUHardwareTexture(this)]; + this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format = this._colorFormat; + this._setColorFormat(this._mainRenderPassWrapper); + } + // Set default values as WebGL with depth and stencil attachment for the broadest Compat. + _initializeMainAttachments() { + if (!this._bufferManager) { + return; + } + this.flushFramebuffer(); + this._mainTextureExtends = { + width: this.getRenderWidth(true), + height: this.getRenderHeight(true), + depthOrArrayLayers: 1, + }; + const bufferDataUpdate = new Float32Array([this.getRenderHeight(true)]); + this._bufferManager.setSubData(this._ubInvertY, 4, bufferDataUpdate); + this._bufferManager.setSubData(this._ubDontInvertY, 4, bufferDataUpdate); + let mainColorAttachments; + if (this._options.antialias) { + const mainTextureDescriptor = { + label: `Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`, + size: this._mainTextureExtends, + mipLevelCount: 1, + sampleCount: this._mainPassSampleCount, + dimension: "2d" /* WebGPUConstants.TextureDimension.E2d */, + format: this._options.swapChainFormat, + usage: 16 /* WebGPUConstants.TextureUsage.RenderAttachment */, + }; + if (this._mainTexture) { + this._textureHelper.releaseTexture(this._mainTexture); + } + this._mainTexture = this._device.createTexture(mainTextureDescriptor); + mainColorAttachments = [ + { + view: this._mainTexture.createView({ + label: "TextureView_MainColor_antialiasing", + dimension: "2d" /* WebGPUConstants.TextureDimension.E2d */, + format: this._options.swapChainFormat, + mipLevelCount: 1, + arrayLayerCount: 1, + }), + clearValue: new Color4(0, 0, 0, 1), + loadOp: "clear" /* WebGPUConstants.LoadOp.Clear */, + storeOp: "store" /* WebGPUConstants.StoreOp.Store */, // don't use StoreOp.Discard, else using several cameras with different viewports or using scissors will fail because we call beginRenderPass / endPass several times for the same color attachment! + }, + ]; + } + else { + mainColorAttachments = [ + { + view: undefined, + clearValue: new Color4(0, 0, 0, 1), + loadOp: "clear" /* WebGPUConstants.LoadOp.Clear */, + storeOp: "store" /* WebGPUConstants.StoreOp.Store */, + }, + ]; + } + this._mainRenderPassWrapper.depthTextureFormat = this.isStencilEnable ? "depth24plus-stencil8" /* WebGPUConstants.TextureFormat.Depth24PlusStencil8 */ : "depth32float" /* WebGPUConstants.TextureFormat.Depth32Float */; + this._setDepthTextureFormat(this._mainRenderPassWrapper); + this._setColorFormat(this._mainRenderPassWrapper); + const depthTextureDescriptor = { + label: `Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`, + size: this._mainTextureExtends, + mipLevelCount: 1, + sampleCount: this._mainPassSampleCount, + dimension: "2d" /* WebGPUConstants.TextureDimension.E2d */, + format: this._mainRenderPassWrapper.depthTextureFormat, + usage: 16 /* WebGPUConstants.TextureUsage.RenderAttachment */, + }; + if (this._depthTexture) { + this._textureHelper.releaseTexture(this._depthTexture); + } + this._depthTexture = this._device.createTexture(depthTextureDescriptor); + const mainDepthAttachment = { + view: this._depthTexture.createView({ + label: `TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`, + dimension: "2d" /* WebGPUConstants.TextureDimension.E2d */, + format: this._depthTexture.format, + mipLevelCount: 1, + arrayLayerCount: 1, + }), + depthClearValue: this._clearDepthValue, + depthLoadOp: "clear" /* WebGPUConstants.LoadOp.Clear */, + depthStoreOp: "store" /* WebGPUConstants.StoreOp.Store */, + stencilClearValue: this._clearStencilValue, + stencilLoadOp: !this.isStencilEnable ? undefined : "clear" /* WebGPUConstants.LoadOp.Clear */, + stencilStoreOp: !this.isStencilEnable ? undefined : "store" /* WebGPUConstants.StoreOp.Store */, + }; + this._mainRenderPassWrapper.renderPassDescriptor = { + label: "MainRenderPass", + colorAttachments: mainColorAttachments, + depthStencilAttachment: mainDepthAttachment, + }; + } + /** + * Shared initialization across engines types. + * @param canvas The canvas associated with this instance of the engine. + */ + _sharedInit(canvas) { + super._sharedInit(canvas); + _CommonInit(this, canvas, this._creationOptions); + } + _configureContext() { + this._context.configure({ + device: this._device, + format: this._options.swapChainFormat, + usage: 16 /* WebGPUConstants.TextureUsage.RenderAttachment */ | 1 /* WebGPUConstants.TextureUsage.CopySrc */, + alphaMode: this.premultipliedAlpha ? "premultiplied" /* WebGPUConstants.CanvasAlphaMode.Premultiplied */ : "opaque" /* WebGPUConstants.CanvasAlphaMode.Opaque */, + }); + } + /** + * Resize an image and returns the image data as an uint8array + * @param image image to resize + * @param bufferWidth destination buffer width + * @param bufferHeight destination buffer height + * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size + */ + resizeImageBitmap(image, bufferWidth, bufferHeight) { + return ResizeImageBitmap(this, image, bufferWidth, bufferHeight); + } + /** + * Engine abstraction for loading and creating an image bitmap from a given source string. + * @param imageSource source to load the image from. + * @param options An object that sets options for the image's extraction. + * @returns ImageBitmap + */ + _createImageBitmapFromSource(imageSource, options) { + return CreateImageBitmapFromSource(this, imageSource, options); + } + /** + * Toggle full screen mode + * @param requestPointerLock defines if a pointer lock should be requested from the user + */ + switchFullscreen(requestPointerLock) { + if (this.isFullscreen) { + this.exitFullscreen(); + } + else { + this.enterFullscreen(requestPointerLock); + } + } + /** + * Enters full screen mode + * @param requestPointerLock defines if a pointer lock should be requested from the user + */ + enterFullscreen(requestPointerLock) { + if (!this.isFullscreen) { + this._pointerLockRequested = requestPointerLock; + if (this._renderingCanvas) { + RequestFullscreen(this._renderingCanvas); + } + } + } + /** + * Exits full screen mode + */ + exitFullscreen() { + if (this.isFullscreen) { + ExitFullscreen(); + } + } + /** + * Enters Pointerlock mode + */ + enterPointerlock() { + if (this._renderingCanvas) { + RequestPointerlock(this._renderingCanvas); + } + } + /** + * Exits Pointerlock mode + */ + exitPointerlock() { + ExitPointerlock(); + } + _rebuildBuffers() { + super._rebuildBuffers(); + for (const storageBuffer of this._storageBuffers) { + // The buffer can already be rebuilt by the call to _rebuildGeometries(), which recreates the storage buffers for the ComputeShaderParticleSystem + if (storageBuffer.getBuffer().engineId !== this.uniqueId) { + storageBuffer._rebuild(); + } + } + } + _restoreEngineAfterContextLost(initEngine) { + WebGPUCacheRenderPipelineTree.ResetCache(); + WebGPUCacheBindGroups.ResetCache(); + // Clear the draw wrappers and material contexts + const cleanScenes = (scenes) => { + for (const scene of scenes) { + for (const mesh of scene.meshes) { + const subMeshes = mesh.subMeshes; + if (!subMeshes) { + continue; + } + for (const subMesh of subMeshes) { + subMesh._drawWrappers = []; + } + } + for (const material of scene.materials) { + material._materialContext?.reset(); + } + } + }; + cleanScenes(this.scenes); + cleanScenes(this._virtualScenes); + // The leftOver uniform buffers are removed from the list because they will be recreated when we rebuild the effects + const uboList = []; + for (const uniformBuffer of this._uniformBuffers) { + if (uniformBuffer.name.indexOf("leftOver") < 0) { + uboList.push(uniformBuffer); + } + } + this._uniformBuffers = uboList; + super._restoreEngineAfterContextLost(initEngine); + } + /** + * Force a specific size of the canvas + * @param width defines the new canvas' width + * @param height defines the new canvas' height + * @param forceSetSize true to force setting the sizes of the underlying canvas + * @returns true if the size was changed + */ + setSize(width, height, forceSetSize = false) { + if (!super.setSize(width, height, forceSetSize)) { + return false; + } + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log(["frame #" + this._count + " - setSize -", width, height]); + } + } + this._initializeMainAttachments(); + if (this.snapshotRendering) { + // reset snapshot rendering so that the next frame will record a new list of bundles + this.snapshotRenderingReset(); + } + return true; + } + /** + * @internal + */ + _getShaderProcessor(shaderLanguage) { + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return this._shaderProcessorWGSL; + } + return this._shaderProcessor; + } + /** + * @internal + */ + _getShaderProcessingContext(shaderLanguage, pureMode) { + return new WebGPUShaderProcessingContext(shaderLanguage, pureMode); + } + _getCurrentRenderPass() { + if (this._currentRenderTarget && !this._currentRenderPass) { + // delayed creation of the render target pass, but we now need to create it as we are requested the render pass + this._startRenderTargetRenderPass(this._currentRenderTarget, false, null, false, false); + } + else if (!this._currentRenderPass) { + this._startMainRenderPass(false); + } + return this._currentRenderPass; + } + /** @internal */ + _getCurrentRenderPassWrapper() { + return this._currentRenderTarget ? this._rttRenderPassWrapper : this._mainRenderPassWrapper; + } + //------------------------------------------------------------------------------ + // Static Pipeline WebGPU States + //------------------------------------------------------------------------------ + /** @internal */ + applyStates() { + this._stencilStateComposer.apply(); + this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend); + } + /** + * Force the entire cache to be cleared + * You should not have to use this function unless your engine needs to share the WebGPU context with another engine + * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states) + */ + wipeCaches(bruteForce) { + if (this.preventCacheWipeBetweenFrames && !bruteForce) { + return; + } + //this._currentEffect = null; // can't reset _currentEffect, else some crashes can occur (for eg in ProceduralTexture which calls bindFrameBuffer (which calls wipeCaches) after having called enableEffect and before drawing into the texture) + // _forceEnableEffect = true assumes the role of _currentEffect = null + this._forceEnableEffect = true; + this._currentIndexBuffer = null; + this._currentOverrideVertexBuffers = null; + this._cacheRenderPipeline.setBuffers(null, null, null); + if (bruteForce) { + this._stencilStateComposer.reset(); + this._depthCullingState.reset(); + this._depthCullingState.depthFunc = 515; + this._alphaState.reset(); + this._alphaMode = 1; + this._alphaEquation = 0; + this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters); + this._cacheRenderPipeline.setAlphaBlendEnabled(false); + this.setColorWrite(true); + } + this._cachedVertexBuffers = null; + this._cachedIndexBuffer = null; + this._cachedEffectForVertexBuffers = null; + } + /** + * Enable or disable color writing + * @param enable defines the state to set + */ + setColorWrite(enable) { + this._colorWriteLocal = enable; + this._cacheRenderPipeline.setWriteMask(enable ? 0xf : 0); + } + /** + * Gets a boolean indicating if color writing is enabled + * @returns the current color writing state + */ + getColorWrite() { + return this._colorWriteLocal; + } + _mustUpdateViewport() { + const x = this._viewportCached.x, y = this._viewportCached.y, w = this._viewportCached.z, h = this._viewportCached.w; + const update = this._viewportsCurrent.x !== x || this._viewportsCurrent.y !== y || this._viewportsCurrent.w !== w || this._viewportsCurrent.h !== h; + if (update) { + this._viewportsCurrent.x = this._viewportCached.x; + this._viewportsCurrent.y = this._viewportCached.y; + this._viewportsCurrent.w = this._viewportCached.z; + this._viewportsCurrent.h = this._viewportCached.w; + } + return update; + } + _applyViewport(bundleList) { + const x = Math.floor(this._viewportCached.x); + const w = Math.floor(this._viewportCached.z); + const h = Math.floor(this._viewportCached.w); + let y = Math.floor(this._viewportCached.y); + if (!this._currentRenderTarget) { + y = this.getRenderHeight(true) - y - h; + } + if (bundleList) { + bundleList.addItem(new WebGPURenderItemViewport(x, y, w, h)); + } + else { + this._getCurrentRenderPass().setViewport(x, y, w, h, 0, 1); + } + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log([ + "frame #" + this._count + " - viewport applied - (", + this._viewportCached.x, + this._viewportCached.y, + this._viewportCached.z, + this._viewportCached.w, + ") current pass is main pass=" + this._currentPassIsMainPass(), + ]); + } + } + } + /** + * @internal + */ + _viewport(x, y, width, height) { + this._viewportCached.x = x; + this._viewportCached.y = y; + this._viewportCached.z = width; + this._viewportCached.w = height; + } + _mustUpdateScissor() { + const x = this._scissorCached.x, y = this._scissorCached.y, w = this._scissorCached.z, h = this._scissorCached.w; + const update = this._scissorsCurrent.x !== x || this._scissorsCurrent.y !== y || this._scissorsCurrent.w !== w || this._scissorsCurrent.h !== h; + if (update) { + this._scissorsCurrent.x = this._scissorCached.x; + this._scissorsCurrent.y = this._scissorCached.y; + this._scissorsCurrent.w = this._scissorCached.z; + this._scissorsCurrent.h = this._scissorCached.w; + } + return update; + } + _applyScissor(bundleList) { + const y = this._currentRenderTarget ? this._scissorCached.y : this.getRenderHeight() - this._scissorCached.w - this._scissorCached.y; + if (bundleList) { + bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x, y, this._scissorCached.z, this._scissorCached.w)); + } + else { + this._getCurrentRenderPass().setScissorRect(this._scissorCached.x, y, this._scissorCached.z, this._scissorCached.w); + } + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log([ + "frame #" + this._count + " - scissor applied - (", + this._scissorCached.x, + this._scissorCached.y, + this._scissorCached.z, + this._scissorCached.w, + ") current pass is main pass=" + this._currentPassIsMainPass(), + ]); + } + } + } + _scissorIsActive() { + return this._scissorCached.x !== 0 || this._scissorCached.y !== 0 || this._scissorCached.z !== 0 || this._scissorCached.w !== 0; + } + enableScissor(x, y, width, height) { + this._scissorCached.x = x; + this._scissorCached.y = y; + this._scissorCached.z = width; + this._scissorCached.w = height; + } + disableScissor() { + this._scissorCached.x = this._scissorCached.y = this._scissorCached.z = this._scissorCached.w = 0; + this._scissorsCurrent.x = this._scissorsCurrent.y = this._scissorsCurrent.w = this._scissorsCurrent.h = 0; + } + _mustUpdateStencilRef() { + const update = this._stencilStateComposer.funcRef !== this._stencilRefsCurrent; + if (update) { + this._stencilRefsCurrent = this._stencilStateComposer.funcRef; + } + return update; + } + _applyStencilRef(bundleList) { + if (bundleList) { + bundleList.addItem(new WebGPURenderItemStencilRef(this._stencilStateComposer.funcRef ?? 0)); + } + else { + this._getCurrentRenderPass().setStencilReference(this._stencilStateComposer.funcRef ?? 0); + } + } + _mustUpdateBlendColor() { + const colorBlend = this._alphaState._blendConstants; + const update = colorBlend[0] !== this._blendColorsCurrent[0] || + colorBlend[1] !== this._blendColorsCurrent[1] || + colorBlend[2] !== this._blendColorsCurrent[2] || + colorBlend[3] !== this._blendColorsCurrent[3]; + if (update) { + this._blendColorsCurrent[0] = colorBlend[0]; + this._blendColorsCurrent[1] = colorBlend[1]; + this._blendColorsCurrent[2] = colorBlend[2]; + this._blendColorsCurrent[3] = colorBlend[3]; + } + return update; + } + _applyBlendColor(bundleList) { + if (bundleList) { + bundleList.addItem(new WebGPURenderItemBlendColor(this._alphaState._blendConstants.slice())); + } + else { + this._getCurrentRenderPass().setBlendConstant(this._alphaState._blendConstants); + } + } + _resetRenderPassStates() { + this._viewportsCurrent.x = this._viewportsCurrent.y = this._viewportsCurrent.w = this._viewportsCurrent.h = 0; + this._scissorsCurrent.x = this._scissorsCurrent.y = this._scissorsCurrent.w = this._scissorsCurrent.h = 0; + this._stencilRefsCurrent = -1; + this._blendColorsCurrent[0] = this._blendColorsCurrent[1] = this._blendColorsCurrent[2] = this._blendColorsCurrent[3] = null; + } + /** + * Clear the current render buffer or the current render target (if any is set up) + * @param color defines the color to use + * @param backBuffer defines if the back buffer must be cleared + * @param depth defines if the depth buffer must be cleared + * @param stencil defines if the stencil buffer must be cleared + */ + clear(color, backBuffer, depth, stencil = false) { + // Some PGs are using color3... + if (color && color.a === undefined) { + color.a = 1; + } + const hasScissor = this._scissorIsActive(); + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log(["frame #" + this._count + " - clear - backBuffer=", backBuffer, " depth=", depth, " stencil=", stencil, " scissor is active=", hasScissor]); + } + } + // We need to recreate the render pass so that the new parameters for clear color / depth / stencil are taken into account + if (this._currentRenderTarget) { + if (hasScissor) { + if (!this._currentRenderPass) { + this._startRenderTargetRenderPass(this._currentRenderTarget, false, backBuffer ? color : null, depth, stencil); + } + this._applyScissor(!this.compatibilityMode ? this._bundleList : null); + this._clearFullQuad(backBuffer ? color : null, depth, stencil); + } + else { + if (this._currentRenderPass) { + this._endCurrentRenderPass(); + } + this._startRenderTargetRenderPass(this._currentRenderTarget, true, backBuffer ? color : null, depth, stencil); + } + } + else { + if (!this._currentRenderPass || !hasScissor) { + this._startMainRenderPass(!hasScissor, backBuffer ? color : null, depth, stencil); + } + if (hasScissor) { + this._applyScissor(!this.compatibilityMode ? this._bundleList : null); + this._clearFullQuad(backBuffer ? color : null, depth, stencil); + } + } + } + _clearFullQuad(clearColor, clearDepth, clearStencil) { + const renderPass = !this.compatibilityMode ? null : this._getCurrentRenderPass(); + this._clearQuad.setColorFormat(this._colorFormat); + this._clearQuad.setDepthStencilFormat(this._depthTextureFormat); + this._clearQuad.setMRTAttachments(this._cacheRenderPipeline.mrtAttachments ?? [], this._cacheRenderPipeline.mrtTextureArray ?? [], this._cacheRenderPipeline.mrtTextureCount); + if (!this.compatibilityMode) { + this._bundleList.addItem(new WebGPURenderItemStencilRef(this._clearStencilValue)); + } + else { + renderPass.setStencilReference(this._clearStencilValue); + } + const bundle = this._clearQuad.clear(renderPass, clearColor, clearDepth, clearStencil, this.currentSampleCount); + if (!this.compatibilityMode) { + this._bundleList.addBundle(bundle); + this._applyStencilRef(this._bundleList); + this._reportDrawCall(); + } + else { + this._applyStencilRef(null); + } + } + //------------------------------------------------------------------------------ + // Vertex/Index/Storage Buffers + //------------------------------------------------------------------------------ + /** + * Creates a vertex buffer + * @param data the data or the size for the vertex buffer + * @param _updatable whether the buffer should be created as updatable + * @param label defines the label of the buffer (for debug purpose) + * @returns the new buffer + */ + createVertexBuffer(data, _updatable, label) { + let view; + if (data instanceof Array) { + view = new Float32Array(data); + } + else if (data instanceof ArrayBuffer) { + view = new Uint8Array(data); + } + else { + view = data; + } + const dataBuffer = this._bufferManager.createBuffer(view, BufferUsage.Vertex | BufferUsage.CopyDst, label); + return dataBuffer; + } + /** + * Creates a vertex buffer + * @param data the data for the dynamic vertex buffer + * @param label defines the label of the buffer (for debug purpose) + * @returns the new buffer + */ + createDynamicVertexBuffer(data, label) { + return this.createVertexBuffer(data, undefined, label); + } + /** + * Creates a new index buffer + * @param indices defines the content of the index buffer + * @param _updatable defines if the index buffer must be updatable + * @param label defines the label of the buffer (for debug purpose) + * @returns a new buffer + */ + createIndexBuffer(indices, _updatable, label) { + let is32Bits = true; + let view; + if (indices instanceof Uint32Array || indices instanceof Int32Array) { + view = indices; + } + else if (indices instanceof Uint16Array) { + view = indices; + is32Bits = false; + } + else { + for (let index = 0; index < indices.length; index++) { + if (indices[index] > 65535) { + view = new Uint32Array(indices); + break; + } + } + if (!view) { + view = new Uint16Array(indices); + is32Bits = false; + } + } + const dataBuffer = this._bufferManager.createBuffer(view, BufferUsage.Index | BufferUsage.CopyDst, label); + dataBuffer.is32Bits = is32Bits; + return dataBuffer; + } + /** + * Update a dynamic index buffer + * @param indexBuffer defines the target index buffer + * @param indices defines the data to update + * @param offset defines the offset in the target index buffer where update should start + */ + updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) { + const gpuBuffer = indexBuffer; + let view; + if (indexBuffer.is32Bits) { + view = indices instanceof Uint32Array ? indices : new Uint32Array(indices); + } + else { + view = indices instanceof Uint16Array ? indices : new Uint16Array(indices); + } + this._bufferManager.setSubData(gpuBuffer, offset, view); + } + /** + * Updates a dynamic vertex buffer. + * @param vertexBuffer the vertex buffer to update + * @param data the data used to update the vertex buffer + * @param byteOffset the byte offset of the data + * @param byteLength the byte length of the data + */ + updateDynamicVertexBuffer(vertexBuffer, data, byteOffset, byteLength) { + const dataBuffer = vertexBuffer; + if (byteOffset === undefined) { + byteOffset = 0; + } + let view; + if (byteLength === undefined) { + if (data instanceof Array) { + view = new Float32Array(data); + } + else if (data instanceof ArrayBuffer) { + view = new Uint8Array(data); + } + else { + view = data; + } + byteLength = view.byteLength; + } + else { + if (data instanceof Array) { + view = new Float32Array(data); + } + else if (data instanceof ArrayBuffer) { + view = new Uint8Array(data); + } + else { + view = data; + } + } + this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength); + } + /** + * @internal + */ + _createBuffer(data, creationFlags, label) { + let view; + if (data instanceof Array) { + view = new Float32Array(data); + } + else if (data instanceof ArrayBuffer) { + view = new Uint8Array(data); + } + else { + view = data; + } + let flags = 0; + if (creationFlags & 1) { + flags |= BufferUsage.CopySrc; + } + if (creationFlags & 2) { + flags |= BufferUsage.CopyDst; + } + if (creationFlags & 4) { + flags |= BufferUsage.Uniform; + } + if (creationFlags & 8) { + flags |= BufferUsage.Vertex; + } + if (creationFlags & 16) { + flags |= BufferUsage.Index; + } + if (creationFlags & 32) { + flags |= BufferUsage.Storage; + } + if (creationFlags & 64) { + flags |= BufferUsage.Indirect; + } + return this._bufferManager.createBuffer(view, flags, label); + } + /** + * @internal + */ + bindBuffersDirectly() { + // eslint-disable-next-line no-throw-literal + throw "Not implemented on WebGPU"; + } + /** + * @internal + */ + updateAndBindInstancesBuffer() { + // eslint-disable-next-line no-throw-literal + throw "Not implemented on WebGPU"; + } + /** + * Unbind all instance attributes + */ + unbindInstanceAttributes() { + // Does nothing + } + /** + * Bind a list of vertex buffers with the engine + * @param vertexBuffers defines the list of vertex buffers to bind + * @param indexBuffer defines the index buffer to bind + * @param effect defines the effect associated with the vertex buffers + * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers + */ + bindBuffers(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { + this._currentIndexBuffer = indexBuffer; + this._currentOverrideVertexBuffers = overrideVertexBuffers ?? null; + this._cacheRenderPipeline.setBuffers(vertexBuffers, indexBuffer, this._currentOverrideVertexBuffers); + } + /** + * @internal + */ + _releaseBuffer(buffer) { + return this._bufferManager.releaseBuffer(buffer); + } + //------------------------------------------------------------------------------ + // Uniform Buffers + //------------------------------------------------------------------------------ + /** + * Create an uniform buffer + * @see https://doc.babylonjs.com/setup/support/webGL2#uniform-buffer-objets + * @param elements defines the content of the uniform buffer + * @param label defines a name for the buffer (for debugging purpose) + * @returns the webGL uniform buffer + */ + createUniformBuffer(elements, label) { + let view; + if (elements instanceof Array) { + view = new Float32Array(elements); + } + else { + view = elements; + } + const dataBuffer = this._bufferManager.createBuffer(view, BufferUsage.Uniform | BufferUsage.CopyDst, label); + return dataBuffer; + } + /** + * Create a dynamic uniform buffer (no different from a non dynamic uniform buffer in WebGPU) + * @see https://doc.babylonjs.com/setup/support/webGL2#uniform-buffer-objets + * @param elements defines the content of the uniform buffer + * @param label defines a name for the buffer (for debugging purpose) + * @returns the webGL uniform buffer + */ + createDynamicUniformBuffer(elements, label) { + return this.createUniformBuffer(elements, label); + } + /** + * Update an existing uniform buffer + * @see https://doc.babylonjs.com/setup/support/webGL2#uniform-buffer-objets + * @param uniformBuffer defines the target uniform buffer + * @param elements defines the content to update + * @param offset defines the offset in the uniform buffer where update should start + * @param count defines the size of the data to update + */ + updateUniformBuffer(uniformBuffer, elements, offset, count) { + if (offset === undefined) { + offset = 0; + } + const dataBuffer = uniformBuffer; + let view; + if (count === undefined) { + if (elements instanceof Float32Array) { + view = elements; + } + else { + view = new Float32Array(elements); + } + count = view.byteLength; + } + else { + if (elements instanceof Float32Array) { + view = elements; + } + else { + view = new Float32Array(elements); + } + } + this._bufferManager.setSubData(dataBuffer, offset, view, 0, count); + } + /** + * Bind a buffer to the current draw context + * @param buffer defines the buffer to bind + * @param _location not used in WebGPU + * @param name Name of the uniform variable to bind + */ + bindUniformBufferBase(buffer, _location, name) { + this._currentDrawContext.setBuffer(name, buffer); + } + /** + * Unused in WebGPU + */ + bindUniformBlock() { } + //------------------------------------------------------------------------------ + // Effects + //------------------------------------------------------------------------------ + /** + * Create a new effect (used to store vertex/fragment shaders) + * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx) + * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object + * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use + * @param samplers defines an array of string used to represent textures + * @param defines defines the string containing the defines to use to compile the shaders + * @param fallbacks defines the list of potential fallbacks to use if shader compilation fails + * @param onCompiled defines a function to call when the effect creation is successful + * @param onError defines a function to call when the effect creation has failed + * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights) + * @param shaderLanguage the language the shader is written in (default: GLSL) + * @param extraInitializationsAsync additional async code to run before preparing the effect + * @returns the new Effect + */ + createEffect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters, shaderLanguage = 0 /* ShaderLanguage.GLSL */, extraInitializationsAsync) { + const vertex = typeof baseName === "string" ? baseName : baseName.vertexToken || baseName.vertexSource || baseName.vertexElement || baseName.vertex; + const fragment = typeof baseName === "string" ? baseName : baseName.fragmentToken || baseName.fragmentSource || baseName.fragmentElement || baseName.fragment; + const globalDefines = this._getGlobalDefines(); + const isOptions = attributesNamesOrOptions.attributes !== undefined; + let fullDefines = defines ?? attributesNamesOrOptions.defines ?? ""; + if (globalDefines) { + fullDefines += "\n" + globalDefines; + } + const name = vertex + "+" + fragment + "@" + fullDefines; + if (this._compiledEffects[name]) { + const compiledEffect = this._compiledEffects[name]; + if (onCompiled && compiledEffect.isReady()) { + onCompiled(compiledEffect); + } + compiledEffect._refCount++; + return compiledEffect; + } + const effect = new Effect(baseName, attributesNamesOrOptions, isOptions ? this : uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, attributesNamesOrOptions.shaderLanguage ?? shaderLanguage, attributesNamesOrOptions.extraInitializationsAsync ?? extraInitializationsAsync); + this._compiledEffects[name] = effect; + return effect; + } + _compileRawShaderToSpirV(source, type) { + return this._glslang.compileGLSL(source, type); + } + _compileShaderToSpirV(source, type, defines, shaderVersion) { + return this._compileRawShaderToSpirV(shaderVersion + (defines ? defines + "\n" : "") + source, type); + } + _getWGSLShader(source, type, defines) { + if (defines) { + defines = "//" + defines.split("\n").join("\n//") + "\n"; + } + else { + defines = ""; + } + return defines + source; + } + _createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment) { + if (this._tintWASM && shaderLanguage === 0 /* ShaderLanguage.GLSL */) { + vertexShader = this._tintWASM.convertSpirV2WGSL(vertexShader, disableUniformityAnalysisInVertex); + fragmentShader = this._tintWASM.convertSpirV2WGSL(fragmentShader, disableUniformityAnalysisInFragment); + } + return { + vertexStage: { + module: this._device.createShaderModule({ + label: "vertex", + code: vertexShader, + }), + entryPoint: "main", + }, + fragmentStage: { + module: this._device.createShaderModule({ + label: "fragment", + code: fragmentShader, + }), + entryPoint: "main", + }, + }; + } + _compileRawPipelineStageDescriptor(vertexCode, fragmentCode, shaderLanguage) { + const disableUniformityAnalysisInVertex = vertexCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) >= 0; + const disableUniformityAnalysisInFragment = fragmentCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) >= 0; + const vertexShader = shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? this._compileRawShaderToSpirV(vertexCode, "vertex") : vertexCode; + const fragmentShader = shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? this._compileRawShaderToSpirV(fragmentCode, "fragment") : fragmentCode; + return this._createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment); + } + _compilePipelineStageDescriptor(vertexCode, fragmentCode, defines, shaderLanguage) { + this.onBeforeShaderCompilationObservable.notifyObservers(this); + const disableUniformityAnalysisInVertex = vertexCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) >= 0; + const disableUniformityAnalysisInFragment = fragmentCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) >= 0; + const shaderVersion = "#version 450\n"; + const vertexShader = shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? this._compileShaderToSpirV(vertexCode, "vertex", defines, shaderVersion) : this._getWGSLShader(vertexCode, "vertex", defines); + const fragmentShader = shaderLanguage === 0 /* ShaderLanguage.GLSL */ + ? this._compileShaderToSpirV(fragmentCode, "fragment", defines, shaderVersion) + : this._getWGSLShader(fragmentCode, "fragment", defines); + const program = this._createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment); + this.onAfterShaderCompilationObservable.notifyObservers(this); + return program; + } + /** + * @internal + */ + createRawShaderProgram() { + // eslint-disable-next-line no-throw-literal + throw "Not available on WebGPU"; + } + /** + * @internal + */ + createShaderProgram() { + // eslint-disable-next-line no-throw-literal + throw "Not available on WebGPU"; + } + /** + * Inline functions in shader code that are marked to be inlined + * @param code code to inline + * @returns inlined code + */ + inlineShaderCode(code) { + const sci = new ShaderCodeInliner(code); + sci.debug = false; + sci.processCode(); + return sci.code; + } + /** + * Creates a new pipeline context + * @param shaderProcessingContext defines the shader processing context used during the processing if available + * @returns the new pipeline + */ + createPipelineContext(shaderProcessingContext) { + return new WebGPUPipelineContext(shaderProcessingContext, this); + } + /** + * Creates a new material context + * @returns the new context + */ + createMaterialContext() { + return new WebGPUMaterialContext(); + } + /** + * Creates a new draw context + * @returns the new context + */ + createDrawContext() { + return new WebGPUDrawContext(this._bufferManager); + } + /** + * @internal + */ + async _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, _rebuildRebind, defines, _transformFeedbackVaryings, _key, onReady) { + const webGpuContext = pipelineContext; + const shaderLanguage = webGpuContext.shaderProcessingContext.shaderLanguage; + if (shaderLanguage === 0 /* ShaderLanguage.GLSL */ && !this._glslangAndTintAreFullyLoaded) { + await this.prepareGlslangAndTintAsync(); + } + if (this.dbgShowShaderCode) { + Logger.Log(["defines", defines]); + Logger.Log(vertexSourceCode); + Logger.Log(fragmentSourceCode); + Logger.Log("***********************************************"); + } + webGpuContext.sources = { + fragment: fragmentSourceCode, + vertex: vertexSourceCode, + rawVertex: rawVertexSourceCode, + rawFragment: rawFragmentSourceCode, + }; + if (createAsRaw) { + webGpuContext.stages = this._compileRawPipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, shaderLanguage); + } + else { + webGpuContext.stages = this._compilePipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, defines, shaderLanguage); + } + onReady(); + } + /** + * Gets the list of active attributes for a given WebGPU program + * @param pipelineContext defines the pipeline context to use + * @param attributesNames defines the list of attribute names to get + * @returns an array of indices indicating the offset of each attribute + */ + getAttributes(pipelineContext, attributesNames) { + const results = new Array(attributesNames.length); + const gpuPipelineContext = pipelineContext; + for (let i = 0; i < attributesNames.length; i++) { + const attributeName = attributesNames[i]; + const attributeLocation = gpuPipelineContext.shaderProcessingContext.availableAttributes[attributeName]; + if (attributeLocation === undefined) { + continue; + } + results[i] = attributeLocation; + } + return results; + } + /** + * Activates an effect, making it the current one (ie. the one used for rendering) + * @param effect defines the effect to activate + */ + enableEffect(effect) { + if (!effect) { + return; + } + if (!IsWrapper(effect)) { + this._currentEffect = effect; + this._currentMaterialContext = this._defaultMaterialContext; + this._currentDrawContext = this._defaultDrawContext; + this._counters.numEnableEffects++; + if (this.dbgLogIfNotDrawWrapper) { + Logger.Warn(`enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=${effect.uniqueId}, effect.name=${effect.name}, effect.name.vertex=${typeof effect.name === "string" ? "" : effect.name.vertex}, effect.name.fragment=${typeof effect.name === "string" ? "" : effect.name.fragment}`, 10); + } + } + else if (!effect.effect || + (effect.effect === this._currentEffect && + effect.materialContext === this._currentMaterialContext && + effect.drawContext === this._currentDrawContext && + !this._forceEnableEffect)) { + if (!effect.effect && this.dbgShowEmptyEnableEffectCalls) { + Logger.Log(["drawWrapper=", effect]); + // eslint-disable-next-line no-throw-literal + throw "Invalid call to enableEffect: the effect property is empty!"; + } + return; + } + else { + this._currentEffect = effect.effect; + this._currentMaterialContext = effect.materialContext; + this._currentDrawContext = effect.drawContext; + this._counters.numEnableDrawWrapper++; + if (!this._currentMaterialContext) { + Logger.Log(["drawWrapper=", effect]); + // eslint-disable-next-line no-throw-literal + throw `Invalid call to enableEffect: the materialContext property is empty!`; + } + } + this._stencilStateComposer.stencilMaterial = undefined; + this._forceEnableEffect = false; + if (this._currentEffect.onBind) { + this._currentEffect.onBind(this._currentEffect); + } + if (this._currentEffect._onBindObservable) { + this._currentEffect._onBindObservable.notifyObservers(this._currentEffect); + } + } + /** + * @internal + */ + _releaseEffect(effect) { + if (this._compiledEffects[effect._key]) { + delete this._compiledEffects[effect._key]; + this._deletePipelineContext(effect.getPipelineContext()); + } + } + /** + * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled + */ + releaseEffects() { + for (const name in this._compiledEffects) { + const webGPUPipelineContext = this._compiledEffects[name].getPipelineContext(); + this._deletePipelineContext(webGPUPipelineContext); + } + this._compiledEffects = {}; + this.onReleaseEffectsObservable.notifyObservers(this); + } + _deletePipelineContext(pipelineContext) { + const webgpuPipelineContext = pipelineContext; + if (webgpuPipelineContext) { + resetCachedPipeline(webgpuPipelineContext); + } + } + //------------------------------------------------------------------------------ + // Textures + //------------------------------------------------------------------------------ + /** + * Gets a boolean indicating that only power of 2 textures are supported + * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them + */ + get needPOTTextures() { + return false; + } + /** @internal */ + _createHardwareTexture() { + return new WebGPUHardwareTexture(this); + } + /** + * @internal + */ + _releaseTexture(texture) { + const index = this._internalTexturesCache.indexOf(texture); + if (index !== -1) { + this._internalTexturesCache.splice(index, 1); + } + this._textureHelper.releaseTexture(texture); + } + /** + * @internal + */ + _getRGBABufferInternalSizedFormat() { + return 5; + } + updateTextureComparisonFunction(texture, comparisonFunction) { + texture._comparisonFunction = comparisonFunction; + } + /** + * Creates an internal texture without binding it to a framebuffer + * @internal + * @param size defines the size of the texture + * @param options defines the options used to create the texture + * @param delayGPUTextureCreation true to delay the texture creation the first time it is really needed. false to create it right away + * @param source source type of the texture + * @returns a new internal texture + */ + _createInternalTexture(size, options, delayGPUTextureCreation = true, source = 0 /* InternalTextureSource.Unknown */) { + const fullOptions = {}; + if (options !== undefined && typeof options === "object") { + fullOptions.generateMipMaps = options.generateMipMaps; + fullOptions.createMipMaps = options.createMipMaps; + fullOptions.type = options.type === undefined ? 0 : options.type; + fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode; + fullOptions.format = options.format === undefined ? 5 : options.format; + fullOptions.samples = options.samples ?? 1; + fullOptions.creationFlags = options.creationFlags ?? 0; + fullOptions.useSRGBBuffer = options.useSRGBBuffer ?? false; + fullOptions.label = options.label; + } + else { + fullOptions.generateMipMaps = options; + fullOptions.type = 0; + fullOptions.samplingMode = 3; + fullOptions.format = 5; + fullOptions.samples = 1; + fullOptions.creationFlags = 0; + fullOptions.useSRGBBuffer = false; + } + if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) { + fullOptions.samplingMode = 1; + } + else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) { + fullOptions.samplingMode = 1; + } + if (fullOptions.type === 1 && !this._caps.textureFloat) { + fullOptions.type = 0; + Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"); + } + const texture = new InternalTexture(this, source); + const width = size.width ?? size; + const height = size.height ?? size; + const depth = size.depth ?? 0; + const layers = size.layers ?? 0; + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.depth = depth || layers; + texture.isReady = true; + texture.samples = fullOptions.samples; + texture.generateMipMaps = !!fullOptions.generateMipMaps; + texture.samplingMode = fullOptions.samplingMode; + texture.type = fullOptions.type; + texture.format = fullOptions.format; + texture.is2DArray = layers > 0; + texture.is3D = depth > 0; + texture._cachedWrapU = 0; + texture._cachedWrapV = 0; + texture._useSRGBBuffer = fullOptions.useSRGBBuffer; + texture.label = fullOptions.label; + this._internalTexturesCache.push(texture); + if (!delayGPUTextureCreation) { + const createMipMapsOnly = !fullOptions.generateMipMaps && fullOptions.createMipMaps; + if (createMipMapsOnly) { + // So that the call to createGPUTextureForInternalTexture creates the mipmaps + texture.generateMipMaps = true; + } + this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, layers || 1, fullOptions.creationFlags); + if (createMipMapsOnly) { + // So that we don't automatically generate mipmaps when the render target is unbound + texture.generateMipMaps = false; + } + } + return texture; + } + /** + * Usually called from Texture.ts. + * Passed information to create a hardware texture + * @param url defines a value which contains one of the following: + * * A conventional http URL, e.g. 'http://...' or 'file://...' + * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...' + * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg' + * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file + * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx) + * @param scene needed for loading to the correct scene + * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE) + * @param onLoad optional callback to be called upon successful completion + * @param onError optional callback to be called upon failure + * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob + * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities + * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures + * @param forcedExtension defines the extension to use to pick the right loader + * @param mimeType defines an optional mime type + * @param loaderOptions options to be passed to the loader + * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) + * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). + * @returns a InternalTexture for assignment back into BABYLON.Texture + */ + createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer) { + return this._createTextureBase(url, noMipmap, invertY, scene, samplingMode, onLoad, onError, (texture, extension, scene, img, invertY, noMipmap, isCompressed, processFunction) => { + const imageBitmap = img; // we will never get an HTMLImageElement in WebGPU + texture.baseWidth = imageBitmap.width; + texture.baseHeight = imageBitmap.height; + texture.width = imageBitmap.width; + texture.height = imageBitmap.height; + texture.format = texture.format !== -1 ? texture.format : (format ?? 5); + texture.type = texture.type !== -1 ? texture.type : 0; + texture._creationFlags = creationFlags ?? 0; + processFunction(texture.width, texture.height, imageBitmap, extension, texture, () => { }); + if (!texture._hardwareTexture?.underlyingResource) { + // the texture could have been created before reaching this point so don't recreate it if already existing + const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, imageBitmap.width, imageBitmap.height, undefined, creationFlags); + if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) { + this._textureHelper.updateTexture(imageBitmap, texture, imageBitmap.width, imageBitmap.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0); + if (!noMipmap && !isCompressed) { + this._generateMipmaps(texture, this._uploadEncoder); + } + } + } + else if (!noMipmap && !isCompressed) { + this._generateMipmaps(texture, this._uploadEncoder); + } + if (scene) { + scene.removePendingData(texture); + } + texture.isReady = true; + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + }, () => false, buffer, fallback, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer); + } + /** + * Wraps an external web gpu texture in a Babylon texture. + * @param texture defines the external texture + * @returns the babylon internal texture + */ + wrapWebGPUTexture(texture) { + const hardwareTexture = new WebGPUHardwareTexture(this, texture); + const internalTexture = new InternalTexture(this, 0 /* InternalTextureSource.Unknown */, true); + internalTexture._hardwareTexture = hardwareTexture; + internalTexture.isReady = true; + return internalTexture; + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Wraps an external web gl texture in a Babylon texture. + * @returns the babylon internal texture + */ + wrapWebGLTexture() { + throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead."); + } + /** + * @internal + */ + _getUseSRGBBuffer(useSRGBBuffer, _noMipmap) { + return useSRGBBuffer && this._caps.supportSRGBBuffers; + } + /** + * @internal + */ + _unpackFlipY(_value) { } + /** + * Update the sampling mode of a given texture + * @param samplingMode defines the required sampling mode + * @param texture defines the texture to update + * @param generateMipMaps defines whether to generate mipmaps for the texture + */ + updateTextureSamplingMode(samplingMode, texture, generateMipMaps = false) { + if (generateMipMaps) { + texture.generateMipMaps = true; + this._generateMipmaps(texture); + } + texture.samplingMode = samplingMode; + } + /** + * Update the sampling mode of a given texture + * @param texture defines the texture to update + * @param wrapU defines the texture wrap mode of the u coordinates + * @param wrapV defines the texture wrap mode of the v coordinates + * @param wrapR defines the texture wrap mode of the r coordinates + */ + updateTextureWrappingMode(texture, wrapU, wrapV = null, wrapR = null) { + if (wrapU !== null) { + texture._cachedWrapU = wrapU; + } + if (wrapV !== null) { + texture._cachedWrapV = wrapV; + } + if ((texture.is2DArray || texture.is3D) && wrapR !== null) { + texture._cachedWrapR = wrapR; + } + } + /** + * Update the dimensions of a texture + * @param texture texture to update + * @param width new width of the texture + * @param height new height of the texture + * @param depth new depth of the texture + */ + updateTextureDimensions(texture, width, height, depth = 1) { + if (!texture._hardwareTexture) { + // the gpu texture is not created yet, so when it is it will be created with the right dimensions + return; + } + if (texture.width === width && texture.height === height && texture.depth === depth) { + return; + } + const additionalUsages = texture._hardwareTexture.textureAdditionalUsages; + texture._hardwareTexture.release(); // don't defer the releasing! Else we will release at the end of this frame the gpu texture we are about to create in the next line... + this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth, additionalUsages); + } + /** + * @internal + */ + _setInternalTexture(name, texture, baseName) { + baseName = baseName ?? name; + if (this._currentEffect) { + const webgpuPipelineContext = this._currentEffect._pipelineContext; + const availableTexture = webgpuPipelineContext.shaderProcessingContext.availableTextures[baseName]; + this._currentMaterialContext.setTexture(name, texture); + if (availableTexture && availableTexture.autoBindSampler) { + const samplerName = baseName + `Sampler`; + this._currentMaterialContext.setSampler(samplerName, texture); // we can safely cast to InternalTexture because ExternalTexture always has autoBindSampler = false + } + } + } + /** + * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection) + * @param rootUrl defines the url where the file to load is located + * @param scene defines the current scene + * @param lodScale defines scale to apply to the mip map selection + * @param lodOffset defines offset to apply to the mip map selection + * @param onLoad defines an optional callback raised when the texture is loaded + * @param onError defines an optional callback raised if there is an issue to load the texture + * @param format defines the format of the data + * @param forcedExtension defines the extension to use to pick the right loader + * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture + * @returns the cube texture as an InternalTexture + */ + createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = true) { + const callback = (loadData) => { + if (!loadData) { + if (onLoad) { + onLoad(null); + } + return; + } + const texture = loadData.texture; + if (!createPolynomials) { + texture._sphericalPolynomial = new SphericalPolynomial(); + } + else if (loadData.info.sphericalPolynomial) { + texture._sphericalPolynomial = loadData.info.sphericalPolynomial; + } + texture._source = 9 /* InternalTextureSource.CubePrefiltered */; + if (onLoad) { + onLoad(texture); + } + }; + return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset); + } + /** + * Sets a texture to the according uniform. + * @param channel The texture channel + * @param unused unused parameter + * @param texture The texture to apply + * @param name The name of the uniform in the effect + */ + setTexture(channel, unused, texture, name) { + this._setTexture(channel, texture, false, false, name, name); + } + /** + * Sets an array of texture to the WebGPU context + * @param channel defines the channel where the texture array must be set + * @param unused unused parameter + * @param textures defines the array of textures to bind + * @param name name of the channel + */ + setTextureArray(channel, unused, textures, name) { + for (let index = 0; index < textures.length; index++) { + this._setTexture(-1, textures[index], true, false, name + index.toString(), name); + } + } + /** + * @internal + */ + _setTexture(channel, texture, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + isPartOfTextureArray = false, depthStencilTexture = false, name = "", baseName) { + // name == baseName for a texture that is not part of a texture array + // Else, name is something like 'myTexture0' / 'myTexture1' / ... and baseName is 'myTexture' + // baseName is used to look up the texture in the shaderProcessingContext.availableTextures map + // name is used to look up the texture in the _currentMaterialContext.textures map + baseName = baseName ?? name; + if (this._currentEffect) { + if (!texture) { + this._currentMaterialContext.setTexture(name, null); + return false; + } + // Video + if (texture.video) { + texture.update(); + } + else if (texture.delayLoadState === 4) { + // Delay loading + texture.delayLoad(); + return false; + } + let internalTexture = null; + if (depthStencilTexture) { + internalTexture = texture.depthStencilTexture; + } + else if (texture.isReady()) { + internalTexture = texture.getInternalTexture(); + } + else if (texture.isCube) { + internalTexture = this.emptyCubeTexture; + } + else if (texture.is3D) { + internalTexture = this.emptyTexture3D; + } + else if (texture.is2DArray) { + internalTexture = this.emptyTexture2DArray; + } + else { + internalTexture = this.emptyTexture; + } + if (internalTexture && !internalTexture.isMultiview) { + // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT. + if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) { + internalTexture._cachedCoordinatesMode = texture.coordinatesMode; + const textureWrapMode = texture.coordinatesMode !== 3 && texture.coordinatesMode !== 5 + ? 1 + : 0; + texture.wrapU = textureWrapMode; + texture.wrapV = textureWrapMode; + } + internalTexture._cachedWrapU = texture.wrapU; + internalTexture._cachedWrapV = texture.wrapV; + if (internalTexture.is3D) { + internalTexture._cachedWrapR = texture.wrapR; + } + this._setAnisotropicLevel(0, internalTexture, texture.anisotropicFilteringLevel); + } + this._setInternalTexture(name, internalTexture, baseName); + } + else { + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log(["frame #" + this._count + " - _setTexture called with a null _currentEffect! texture=", texture]); + } + } + } + return true; + } + /** + * @internal + */ + _setAnisotropicLevel(target, internalTexture, anisotropicFilteringLevel) { + if (internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) { + internalTexture._cachedAnisotropicFilteringLevel = Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy); + } + } + /** + * @internal + */ + _bindTexture(channel, texture, name) { + if (channel === undefined) { + return; + } + this._setInternalTexture(name, texture); + } + /** + * Generates the mipmaps for a texture + * @param texture texture to generate the mipmaps for + */ + generateMipmaps(texture) { + this._generateMipmaps(texture); + } + /** + * Update a portion of an internal texture + * @param texture defines the texture to update + * @param imageData defines the data to store into the texture + * @param xOffset defines the x coordinates of the update rectangle + * @param yOffset defines the y coordinates of the update rectangle + * @param width defines the width of the update rectangle + * @param height defines the height of the update rectangle + * @param faceIndex defines the face index if texture is a cube (0 by default) + * @param lod defines the lod level to update (0 by default) + * @param generateMipMaps defines whether to generate mipmaps or not + */ + updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) { + let gpuTextureWrapper = texture._hardwareTexture; + if (!texture._hardwareTexture?.underlyingResource) { + gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture); + } + const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength); + this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, xOffset, yOffset); + if (generateMipMaps) { + this._generateMipmaps(texture); + } + } + /** + * @internal + */ + _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, imageData, faceIndex = 0, lod = 0) { + let gpuTextureWrapper = texture._hardwareTexture; + if (!texture._hardwareTexture?.underlyingResource) { + texture.format = internalFormat; + gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height); + } + const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength); + this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, false, false, 0, 0); + } + /** + * @internal + */ + _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0, babylonInternalFormat, useTextureWidthAndHeight = false) { + const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E); + const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E); + const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0)); + const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0)); + let gpuTextureWrapper = texture._hardwareTexture; + if (!texture._hardwareTexture?.underlyingResource) { + gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height); + } + const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength); + this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0); + } + /** + * @internal + */ + _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) { + this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod); + } + /** + * @internal + */ + _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) { + let gpuTextureWrapper = texture._hardwareTexture; + if (!texture._hardwareTexture?.underlyingResource) { + gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture); + } + if (image instanceof HTMLImageElement) { + // eslint-disable-next-line no-throw-literal + throw "WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!"; + } + const bitmap = image; // in WebGPU we will always get an ImageBitmap, not an HTMLImageElement + const width = Math.ceil(texture.width / (1 << lod)); + const height = Math.ceil(texture.height / (1 << lod)); + this._textureHelper.updateTexture(bitmap, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0); + } + /** + * Reads pixels from the current frame buffer. Please note that this function can be slow + * @param x defines the x coordinate of the rectangle where pixels must be read + * @param y defines the y coordinate of the rectangle where pixels must be read + * @param width defines the width of the rectangle where pixels must be read + * @param height defines the height of the rectangle where pixels must be read + * @param hasAlpha defines whether the output should have alpha or not (defaults to true) + * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels + * @param data defines the data to fill with the read pixels (if not provided, a new one will be created) + * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + readPixels(x, y, width, height, hasAlpha = true, flushRenderer = true, data = null) { + const renderPassWrapper = this._getCurrentRenderPassWrapper(); + const hardwareTexture = renderPassWrapper.colorAttachmentGPUTextures[0]; + if (!hardwareTexture) { + // we are calling readPixels for a render pass with no color texture bound + return Promise.resolve(new Uint8Array(0)); + } + const gpuTexture = hardwareTexture.underlyingResource; + const gpuTextureFormat = hardwareTexture.format; + if (!gpuTexture) { + // we are calling readPixels before startMainRenderPass has been called and no RTT is bound, so swapChainTexture is not setup yet! + return Promise.resolve(new Uint8Array(0)); + } + if (flushRenderer) { + this.flushFramebuffer(); + } + return this._textureHelper.readPixels(gpuTexture, x, y, width, height, gpuTextureFormat, undefined, undefined, data); + } + //------------------------------------------------------------------------------ + // Frame management + //------------------------------------------------------------------------------ + _measureFps() { + this._performanceMonitor.sampleFrame(); + this._fps = this._performanceMonitor.averageFPS; + this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0; + } + /** + * Gets the performance monitor attached to this engine + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation + */ + get performanceMonitor() { + return this._performanceMonitor; + } + /** + * Begin a new frame + */ + beginFrame() { + this._measureFps(); + super.beginFrame(); + } + /** + * End the current frame + */ + endFrame() { + this._endCurrentRenderPass(); + this._snapshotRendering.endFrame(); + this._timestampQuery.endFrame(this._renderEncoder); + this._timestampIndex = 0; + this.flushFramebuffer(); + this._textureHelper.destroyDeferredTextures(); + this._bufferManager.destroyDeferredBuffers(); + if (this._features._collectUbosUpdatedInFrame) { + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + const list = []; + for (const name in UniformBuffer._UpdatedUbosInFrame) { + list.push(name + ":" + UniformBuffer._UpdatedUbosInFrame[name]); + } + Logger.Log(["frame #" + this._count + " - updated ubos -", list.join(", ")]); + } + } + UniformBuffer._UpdatedUbosInFrame = {}; + } + this.countersLastFrame.numEnableEffects = this._counters.numEnableEffects; + this.countersLastFrame.numEnableDrawWrapper = this._counters.numEnableDrawWrapper; + this.countersLastFrame.numBundleCreationNonCompatMode = this._counters.numBundleCreationNonCompatMode; + this.countersLastFrame.numBundleReuseNonCompatMode = this._counters.numBundleReuseNonCompatMode; + this._counters.numEnableEffects = 0; + this._counters.numEnableDrawWrapper = 0; + this._counters.numBundleCreationNonCompatMode = 0; + this._counters.numBundleReuseNonCompatMode = 0; + this._cacheRenderPipeline.endFrame(); + this._cacheBindGroups.endFrame(); + this._pendingDebugCommands.length = 0; + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log(["%c frame #" + this._count + " - end", "background: #ffff00"]); + } + if (this._count < this.dbgVerboseLogsNumFrames) { + this._count++; + if (this._count !== this.dbgVerboseLogsNumFrames) { + Logger.Log(["%c frame #" + this._count + " - begin", "background: #ffff00"]); + } + } + } + super.endFrame(); + } + /**Gets driver info if available */ + extractDriverInfo() { + return ""; + } + /** + * Force a WebGPU flush (ie. a flush of all waiting commands) + */ + flushFramebuffer() { + // we need to end the current render pass (main or rtt) if any as we are not allowed to submit the command buffers when being in a pass + this._endCurrentRenderPass(); + this._commandBuffers[0] = this._uploadEncoder.finish(); + this._commandBuffers[1] = this._renderEncoder.finish(); + this._device.queue.submit(this._commandBuffers); + this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor); + this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor); + this._timestampQuery.startFrame(this._uploadEncoder); + this._textureHelper.setCommandEncoder(this._uploadEncoder); + this._bundleList.reset(); + } + /** @internal */ + _currentFrameBufferIsDefaultFrameBuffer() { + return this._currentPassIsMainPass(); + } + //------------------------------------------------------------------------------ + // Render Pass + //------------------------------------------------------------------------------ + _startRenderTargetRenderPass(renderTargetWrapper, setClearStates, clearColor, clearDepth, clearStencil) { + this._endCurrentRenderPass(); + const rtWrapper = renderTargetWrapper; + const depthStencilTexture = rtWrapper._depthStencilTexture; + const gpuDepthStencilWrapper = depthStencilTexture?._hardwareTexture; + const gpuDepthStencilTexture = gpuDepthStencilWrapper?.underlyingResource; + const gpuDepthStencilMSAATexture = gpuDepthStencilWrapper?.getMSAATexture(0); + const depthTextureView = gpuDepthStencilTexture?.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor); + const depthMSAATextureView = gpuDepthStencilMSAATexture?.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor); + const depthTextureHasStencil = gpuDepthStencilWrapper ? WebGPUTextureHelper.HasStencilAspect(gpuDepthStencilWrapper.format) : false; + const colorAttachments = []; + if (this.useReverseDepthBuffer) { + this.setDepthFunctionToGreaterOrEqual(); + } + const clearColorForIntegerRT = tempColor4; + if (clearColor) { + clearColorForIntegerRT.r = clearColor.r * 255; + clearColorForIntegerRT.g = clearColor.g * 255; + clearColorForIntegerRT.b = clearColor.b * 255; + clearColorForIntegerRT.a = clearColor.a * 255; + } + const mustClearColor = setClearStates && clearColor; + const mustClearDepth = setClearStates && clearDepth; + const mustClearStencil = setClearStates && clearStencil; + if (rtWrapper._attachments && rtWrapper.isMulti) { + // multi render targets + if (!this._mrtAttachments || this._mrtAttachments.length === 0) { + this._mrtAttachments = rtWrapper._defaultAttachments; + } + for (let i = 0; i < this._mrtAttachments.length; ++i) { + const index = this._mrtAttachments[i]; // if index == 0 it means the texture should not be written to => at render pass creation time, it means we should not clear it + const mrtTexture = rtWrapper.textures[i]; + const gpuMRTWrapper = mrtTexture?._hardwareTexture; + const gpuMRTTexture = gpuMRTWrapper?.underlyingResource; + if (gpuMRTWrapper && gpuMRTTexture) { + const baseArrayLayer = rtWrapper.getBaseArrayLayer(i); + const gpuMSAATexture = gpuMRTWrapper.getMSAATexture(baseArrayLayer); + const viewDescriptor = { + ...this._rttRenderPassWrapper.colorAttachmentViewDescriptor, + dimension: mrtTexture.is3D ? "3d" /* WebGPUConstants.TextureViewDimension.E3d */ : "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + format: gpuMRTWrapper.format, + baseArrayLayer, + }; + const msaaViewDescriptor = { + ...this._rttRenderPassWrapper.colorAttachmentViewDescriptor, + dimension: mrtTexture.is3D ? "3d" /* WebGPUConstants.TextureViewDimension.E3d */ : "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + format: gpuMRTWrapper.format, + baseArrayLayer: 0, + }; + const isRTInteger = mrtTexture.type === 7 || mrtTexture.type === 5; + const colorTextureView = gpuMRTTexture.createView(viewDescriptor); + const colorMSAATextureView = gpuMSAATexture?.createView(msaaViewDescriptor); + colorAttachments.push({ + view: colorMSAATextureView ? colorMSAATextureView : colorTextureView, + resolveTarget: gpuMSAATexture ? colorTextureView : undefined, + depthSlice: mrtTexture.is3D ? (rtWrapper.layerIndices?.[i] ?? 0) : undefined, + clearValue: index !== 0 && mustClearColor ? (isRTInteger ? clearColorForIntegerRT : clearColor) : undefined, + loadOp: index !== 0 && mustClearColor ? "clear" /* WebGPUConstants.LoadOp.Clear */ : "load" /* WebGPUConstants.LoadOp.Load */, + storeOp: "store" /* WebGPUConstants.StoreOp.Store */, + }); + } + } + this._cacheRenderPipeline.setMRT(rtWrapper.textures, this._mrtAttachments.length); + this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments); + } + else { + // single render target + const internalTexture = rtWrapper.texture; + if (internalTexture) { + const gpuWrapper = internalTexture._hardwareTexture; + const gpuTexture = gpuWrapper.underlyingResource; + let depthSlice = undefined; + if (rtWrapper.is3D) { + depthSlice = this._rttRenderPassWrapper.colorAttachmentViewDescriptor.baseArrayLayer; + this._rttRenderPassWrapper.colorAttachmentViewDescriptor.baseArrayLayer = 0; + } + const gpuMSAATexture = gpuWrapper.getMSAATexture(0); + const colorTextureView = gpuTexture.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor); + const colorMSAATextureView = gpuMSAATexture?.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor); + const isRTInteger = internalTexture.type === 7 || internalTexture.type === 5; + colorAttachments.push({ + view: colorMSAATextureView ? colorMSAATextureView : colorTextureView, + resolveTarget: gpuMSAATexture ? colorTextureView : undefined, + depthSlice, + clearValue: mustClearColor ? (isRTInteger ? clearColorForIntegerRT : clearColor) : undefined, + loadOp: mustClearColor ? "clear" /* WebGPUConstants.LoadOp.Clear */ : "load" /* WebGPUConstants.LoadOp.Load */, + storeOp: "store" /* WebGPUConstants.StoreOp.Store */, + }); + } + else { + colorAttachments.push(null); + } + } + this._debugPushGroup?.("render target pass" + (renderTargetWrapper.label ? " (" + renderTargetWrapper.label + ")" : ""), 0); + this._rttRenderPassWrapper.renderPassDescriptor = { + label: (renderTargetWrapper.label ?? "RTT") + " - RenderPass", + colorAttachments, + depthStencilAttachment: depthStencilTexture && gpuDepthStencilTexture + ? { + view: depthMSAATextureView ? depthMSAATextureView : depthTextureView, + depthClearValue: mustClearDepth ? (this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue) : undefined, + depthLoadOp: mustClearDepth ? "clear" /* WebGPUConstants.LoadOp.Clear */ : "load" /* WebGPUConstants.LoadOp.Load */, + depthStoreOp: "store" /* WebGPUConstants.StoreOp.Store */, + stencilClearValue: rtWrapper._depthStencilTextureWithStencil && mustClearStencil ? this._clearStencilValue : undefined, + stencilLoadOp: !depthTextureHasStencil + ? undefined + : rtWrapper._depthStencilTextureWithStencil && mustClearStencil + ? "clear" /* WebGPUConstants.LoadOp.Clear */ + : "load" /* WebGPUConstants.LoadOp.Load */, + stencilStoreOp: !depthTextureHasStencil ? undefined : "store" /* WebGPUConstants.StoreOp.Store */, + } + : undefined, + occlusionQuerySet: this._occlusionQuery?.hasQueries ? this._occlusionQuery.querySet : undefined, + }; + this._timestampQuery.startPass(this._rttRenderPassWrapper.renderPassDescriptor, this._timestampIndex); + this._currentRenderPass = this._renderEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor); + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + const internalTexture = rtWrapper.texture; + Logger.Log([ + "frame #" + + this._count + + " - render target begin pass - rtt name=" + + renderTargetWrapper.label + + ", internalTexture.uniqueId=" + + internalTexture.uniqueId + + ", width=" + + internalTexture.width + + ", height=" + + internalTexture.height + + ", setClearStates=" + + setClearStates, + "renderPassDescriptor=", + this._rttRenderPassWrapper.renderPassDescriptor, + ]); + } + } + this._debugFlushPendingCommands?.(); + this._resetRenderPassStates(); + if (!gpuDepthStencilWrapper || !WebGPUTextureHelper.HasStencilAspect(gpuDepthStencilWrapper.format)) { + this._stencilStateComposer.enabled = false; + } + } + _startMainRenderPass(setClearStates, clearColor, clearDepth, clearStencil) { + this._endCurrentRenderPass(); + if (this.useReverseDepthBuffer) { + this.setDepthFunctionToGreaterOrEqual(); + } + const mustClearColor = setClearStates && clearColor; + const mustClearDepth = setClearStates && clearDepth; + const mustClearStencil = setClearStates && clearStencil; + this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue = mustClearColor ? clearColor : undefined; + this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp = mustClearColor ? "clear" /* WebGPUConstants.LoadOp.Clear */ : "load" /* WebGPUConstants.LoadOp.Load */; + this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue = mustClearDepth + ? this.useReverseDepthBuffer + ? this._clearReverseDepthValue + : this._clearDepthValue + : undefined; + this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp = mustClearDepth ? "clear" /* WebGPUConstants.LoadOp.Clear */ : "load" /* WebGPUConstants.LoadOp.Load */; + this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue = mustClearStencil ? this._clearStencilValue : undefined; + this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp = !this.isStencilEnable + ? undefined + : mustClearStencil + ? "clear" /* WebGPUConstants.LoadOp.Clear */ + : "load" /* WebGPUConstants.LoadOp.Load */; + this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet = this._occlusionQuery?.hasQueries ? this._occlusionQuery.querySet : undefined; + const swapChainTexture = this._context.getCurrentTexture(); + this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(swapChainTexture); + // Resolve in case of MSAA + if (this._options.antialias) { + viewDescriptorSwapChainAntialiasing.format = swapChainTexture.format; + this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget = swapChainTexture.createView(viewDescriptorSwapChainAntialiasing); + } + else { + viewDescriptorSwapChain.format = swapChainTexture.format; + this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view = swapChainTexture.createView(viewDescriptorSwapChain); + } + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log([ + "frame #" + this._count + " - main begin pass - texture width=" + this._mainTextureExtends.width, + " height=" + this._mainTextureExtends.height + ", setClearStates=" + setClearStates, + "renderPassDescriptor=", + this._mainRenderPassWrapper.renderPassDescriptor, + ]); + } + } + this._debugPushGroup?.("main pass", 0); + this._timestampQuery.startPass(this._mainRenderPassWrapper.renderPassDescriptor, this._timestampIndex); + this._currentRenderPass = this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor); + this._setDepthTextureFormat(this._mainRenderPassWrapper); + this._setColorFormat(this._mainRenderPassWrapper); + this._debugFlushPendingCommands?.(); + this._resetRenderPassStates(); + if (!this._isStencilEnable) { + this._stencilStateComposer.enabled = false; + } + } + /** + * Binds the frame buffer to the specified texture. + * @param texture The render target wrapper to render to + * @param faceIndex The face of the texture to render to in case of cube texture + * @param requiredWidth The width of the target to render to + * @param requiredHeight The height of the target to render to + * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true + * @param lodLevel defines the lod level to bind to the frame buffer + * @param layer defines the 2d array index to bind to frame buffer to + */ + bindFramebuffer(texture, faceIndex = 0, requiredWidth, requiredHeight, forceFullscreenViewport, lodLevel = 0, layer = 0) { + const hardwareTexture = texture.texture?._hardwareTexture; + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + else { + this._endCurrentRenderPass(); + } + this._currentRenderTarget = texture; + const depthStencilTexture = this._currentRenderTarget._depthStencilTexture; + this._rttRenderPassWrapper.colorAttachmentGPUTextures[0] = hardwareTexture; + this._rttRenderPassWrapper.depthTextureFormat = depthStencilTexture ? WebGPUTextureHelper.GetWebGPUTextureFormat(-1, depthStencilTexture.format) : undefined; + this._setDepthTextureFormat(this._rttRenderPassWrapper); + this._setColorFormat(this._rttRenderPassWrapper); + this._rttRenderPassWrapper.colorAttachmentViewDescriptor = { + format: this._colorFormat, + dimension: texture.is3D ? "3d" /* WebGPUConstants.TextureViewDimension.E3d */ : "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + mipLevelCount: 1, + baseArrayLayer: texture.isCube ? layer * 6 + faceIndex : layer, + baseMipLevel: lodLevel, + arrayLayerCount: 1, + aspect: "all" /* WebGPUConstants.TextureAspect.All */, + }; + this._rttRenderPassWrapper.depthAttachmentViewDescriptor = { + format: this._depthTextureFormat, + dimension: depthStencilTexture && depthStencilTexture.is3D ? "3d" /* WebGPUConstants.TextureViewDimension.E3d */ : "2d" /* WebGPUConstants.TextureViewDimension.E2d */, + mipLevelCount: 1, + baseArrayLayer: depthStencilTexture ? (depthStencilTexture.isCube ? layer * 6 + faceIndex : layer) : 0, + baseMipLevel: 0, + arrayLayerCount: 1, + aspect: "all" /* WebGPUConstants.TextureAspect.All */, + }; + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log([ + "frame #" + + this._count + + " - bindFramebuffer - rtt name=" + + texture.label + + ", internalTexture.uniqueId=" + + texture.texture?.uniqueId + + ", face=" + + faceIndex + + ", lodLevel=" + + lodLevel + + ", layer=" + + layer, + "colorAttachmentViewDescriptor=", + this._rttRenderPassWrapper.colorAttachmentViewDescriptor, + "depthAttachmentViewDescriptor=", + this._rttRenderPassWrapper.depthAttachmentViewDescriptor, + ]); + } + } + // We don't create the render pass just now, we do a lazy creation of the render pass, hoping the render pass will be created by a call to clear()... + if (this._cachedViewport && !forceFullscreenViewport) { + this.setViewport(this._cachedViewport, requiredWidth, requiredHeight); + } + else { + if (!requiredWidth) { + requiredWidth = texture.width; + if (lodLevel) { + requiredWidth = requiredWidth / Math.pow(2, lodLevel); + } + } + if (!requiredHeight) { + requiredHeight = texture.height; + if (lodLevel) { + requiredHeight = requiredHeight / Math.pow(2, lodLevel); + } + } + this._viewport(0, 0, requiredWidth, requiredHeight); + } + this.wipeCaches(); + } + /** + * Unbind the current render target texture from the WebGPU context + * @param texture defines the render target wrapper to unbind + * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated + * @param onBeforeUnbind defines a function which will be called before the effective unbind + */ + unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) { + const saveCRT = this._currentRenderTarget; + this._currentRenderTarget = null; // to be iso with abstractEngine, this._currentRenderTarget must be null when onBeforeUnbind is called + if (onBeforeUnbind) { + onBeforeUnbind(); + } + this._currentRenderTarget = saveCRT; + this._endCurrentRenderPass(); + if (!disableGenerateMipMaps) { + if (texture.isMulti) { + this.generateMipMapsMultiFramebuffer(texture); + } + else { + this.generateMipMapsFramebuffer(texture); + } + } + this._currentRenderTarget = null; + if (this.dbgVerboseLogsForFirstFrames) { + if (this._count === undefined) { + this._count = 0; + } + if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { + Logger.Log("frame #" + this._count + " - unBindFramebuffer - rtt name=" + texture.label + ", internalTexture.uniqueId=", texture.texture?.uniqueId); + } + } + this._mrtAttachments = []; + this._cacheRenderPipeline.setMRT([]); + this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments); + } + /** + * Generates mipmaps for the texture of the (single) render target + * @param texture The render target containing the texture to generate the mipmaps for + */ + generateMipMapsFramebuffer(texture) { + if (!texture.isMulti && texture.texture?.generateMipMaps && !texture.isCube) { + this._generateMipmaps(texture.texture); + } + } + /** + * Resolves the MSAA texture of the (single) render target into its non-MSAA version. + * Note that if "texture" is not a MSAA render target, no resolve is performed. + * @param _texture The render target texture containing the MSAA texture to resolve + */ + resolveFramebuffer(_texture) { + throw new Error("resolveFramebuffer is not yet implemented in WebGPU!"); + } + /** + * Unbind the current render target and bind the default framebuffer + */ + restoreDefaultFramebuffer() { + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + else if (!this._currentRenderPass) { + this._startMainRenderPass(false); + } + if (this._cachedViewport) { + this.setViewport(this._cachedViewport); + } + this.wipeCaches(); + } + //------------------------------------------------------------------------------ + // Render + //------------------------------------------------------------------------------ + /** + * @internal + */ + _setColorFormat(wrapper) { + const format = wrapper.colorAttachmentGPUTextures[0]?.format ?? null; + this._cacheRenderPipeline.setColorFormat(format); + if (this._colorFormat === format) { + return; + } + this._colorFormat = format; + } + /** + * @internal + */ + _setDepthTextureFormat(wrapper) { + this._cacheRenderPipeline.setDepthStencilFormat(wrapper.depthTextureFormat); + if (this._depthTextureFormat === wrapper.depthTextureFormat) { + return; + } + this._depthTextureFormat = wrapper.depthTextureFormat; + } + setDitheringState() { + // Does not exist in WebGPU + } + setRasterizerState() { + // Does not exist in WebGPU + } + /** + * @internal + */ + _executeWhenRenderingStateIsCompiled(pipelineContext, action) { + // No parallel shader compilation. + // No Async, so direct launch + action(); + } + /** + * @internal + */ + bindSamplers() { } + /** @internal */ + _getUnpackAlignement() { + return 1; + } + /** + * @internal + */ + _bindTextureDirectly() { + return false; + } + setStateCullFaceType(cullBackFaces, force = false) { + const cullFace = (this.cullBackFaces ?? cullBackFaces ?? true) ? 1 : 2; + if (this._depthCullingState.cullFace !== cullFace || force) { + this._depthCullingState.cullFace = cullFace; + } + } + /** + * Set various states to the webGL context + * @param culling defines culling state: true to enable culling, false to disable it + * @param zOffset defines the value to apply to zOffset (0 by default) + * @param force defines if states must be applied even if cache is up to date + * @param reverseSide defines if culling must be reversed (CCW if false, CW if true) + * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled) + * @param stencil stencil states to set + * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default) + */ + setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) { + // Culling + if (this._depthCullingState.cull !== culling || force) { + this._depthCullingState.cull = culling; + } + // Cull face + this.setStateCullFaceType(cullBackFaces, force); + // Z offset + this.setZOffset(zOffset); + this.setZOffsetUnits(zOffsetUnits); + // Front face + const frontFace = reverseSide ? (this._currentRenderTarget ? 1 : 2) : this._currentRenderTarget ? 2 : 1; + if (this._depthCullingState.frontFace !== frontFace || force) { + this._depthCullingState.frontFace = frontFace; + } + this._stencilStateComposer.stencilMaterial = stencil; + } + _applyRenderPassChanges(bundleList) { + const mustUpdateStencilRef = !this._stencilStateComposer.enabled ? false : this._mustUpdateStencilRef(); + const mustUpdateBlendColor = !this._alphaState.alphaBlend ? false : this._mustUpdateBlendColor(); + if (this._mustUpdateViewport()) { + this._applyViewport(bundleList); + } + if (this._mustUpdateScissor()) { + this._applyScissor(bundleList); + } + if (mustUpdateStencilRef) { + this._applyStencilRef(bundleList); + } + if (mustUpdateBlendColor) { + this._applyBlendColor(bundleList); + } + } + _draw(drawType, fillMode, start, count, instancesCount) { + const renderPass = this._getCurrentRenderPass(); + const bundleList = this._bundleList; + this.applyStates(); + const webgpuPipelineContext = this._currentEffect._pipelineContext; + this.bindUniformBufferBase(this._currentRenderTarget ? this._ubInvertY : this._ubDontInvertY, 0, WebGPUShaderProcessor.InternalsUBOName); + if (webgpuPipelineContext.uniformBuffer) { + webgpuPipelineContext.uniformBuffer.update(); + this.bindUniformBufferBase(webgpuPipelineContext.uniformBuffer.getBuffer(), 0, WebGPUShaderProcessor.LeftOvertUBOName); + } + if (this._snapshotRendering.play) { + this._reportDrawCall(); + return; + } + if (!this.compatibilityMode && + (this._currentDrawContext.isDirty(this._currentMaterialContext.updateId) || this._currentMaterialContext.isDirty || this._currentMaterialContext.forceBindGroupCreation)) { + this._currentDrawContext.fastBundle = undefined; + } + const useFastPath = !this.compatibilityMode && this._currentDrawContext.fastBundle; + let renderPass2 = renderPass; + if (useFastPath || this._snapshotRendering.record) { + this._applyRenderPassChanges(bundleList); + if (!this._snapshotRendering.record) { + this._counters.numBundleReuseNonCompatMode++; + if (this._currentDrawContext.indirectDrawBuffer) { + this._currentDrawContext.setIndirectData(count, instancesCount || 1, start); + } + bundleList.addBundle(this._currentDrawContext.fastBundle); + this._reportDrawCall(); + return; + } + renderPass2 = bundleList.getBundleEncoder(this._cacheRenderPipeline.colorFormats, this._depthTextureFormat, this.currentSampleCount); // for snapshot recording mode + bundleList.numDrawCalls++; + } + let textureState = 0; + if (this._currentMaterialContext.hasFloatOrDepthTextures) { + let bitVal = 1; + for (let i = 0; i < webgpuPipelineContext.shaderProcessingContext.textureNames.length; ++i) { + const textureName = webgpuPipelineContext.shaderProcessingContext.textureNames[i]; + const texture = this._currentMaterialContext.textures[textureName]?.texture; + const textureIsDepth = texture && texture.format >= 13 && texture.format <= 18; + if ((texture?.type === 1 && !this._caps.textureFloatLinearFiltering) || textureIsDepth) { + textureState |= bitVal; + } + bitVal = bitVal << 1; + } + } + this._currentMaterialContext.textureState = textureState; + const pipeline = this._cacheRenderPipeline.getRenderPipeline(fillMode, this._currentEffect, this.currentSampleCount, textureState); + const bindGroups = this._cacheBindGroups.getBindGroups(webgpuPipelineContext, this._currentDrawContext, this._currentMaterialContext); + if (!this._snapshotRendering.record) { + this._applyRenderPassChanges(!this.compatibilityMode ? bundleList : null); + if (!this.compatibilityMode) { + this._counters.numBundleCreationNonCompatMode++; + renderPass2 = this._device.createRenderBundleEncoder({ + colorFormats: this._cacheRenderPipeline.colorFormats, + depthStencilFormat: this._depthTextureFormat, + sampleCount: WebGPUTextureHelper.GetSample(this.currentSampleCount), + }); + } + } + // bind pipeline + renderPass2.setPipeline(pipeline); + // bind index/vertex buffers + if (this._currentIndexBuffer) { + renderPass2.setIndexBuffer(this._currentIndexBuffer.underlyingResource, this._currentIndexBuffer.is32Bits ? "uint32" /* WebGPUConstants.IndexFormat.Uint32 */ : "uint16" /* WebGPUConstants.IndexFormat.Uint16 */, 0); + } + const vertexBuffers = this._cacheRenderPipeline.vertexBuffers; + for (let index = 0; index < vertexBuffers.length; index++) { + const vertexBuffer = vertexBuffers[index]; + const buffer = vertexBuffer.effectiveBuffer; + if (buffer) { + renderPass2.setVertexBuffer(index, buffer.underlyingResource, vertexBuffer._validOffsetRange ? 0 : vertexBuffer.byteOffset); + } + } + // bind bind groups + for (let i = 0; i < bindGroups.length; i++) { + renderPass2.setBindGroup(i, bindGroups[i]); + } + // draw + const nonCompatMode = !this.compatibilityMode && !this._snapshotRendering.record; + if (nonCompatMode && this._currentDrawContext.indirectDrawBuffer) { + this._currentDrawContext.setIndirectData(count, instancesCount || 1, start); + if (drawType === 0) { + renderPass2.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer, 0); + } + else { + renderPass2.drawIndirect(this._currentDrawContext.indirectDrawBuffer, 0); + } + } + else if (drawType === 0) { + renderPass2.drawIndexed(count, instancesCount || 1, start, 0, 0); + } + else { + renderPass2.draw(count, instancesCount || 1, start, 0); + } + if (nonCompatMode) { + this._currentDrawContext.fastBundle = renderPass2.finish(); + bundleList.addBundle(this._currentDrawContext.fastBundle); + } + this._reportDrawCall(); + } + /** + * Draw a list of indexed primitives + * @param fillMode defines the primitive to use + * @param indexStart defines the starting index + * @param indexCount defines the number of index to draw + * @param instancesCount defines the number of instances to draw (if instantiation is enabled) + */ + drawElementsType(fillMode, indexStart, indexCount, instancesCount = 1) { + this._draw(0, fillMode, indexStart, indexCount, instancesCount); + } + /** + * Draw a list of unindexed primitives + * @param fillMode defines the primitive to use + * @param verticesStart defines the index of first vertex to draw + * @param verticesCount defines the count of vertices to draw + * @param instancesCount defines the number of instances to draw (if instantiation is enabled) + */ + drawArraysType(fillMode, verticesStart, verticesCount, instancesCount = 1) { + this._currentIndexBuffer = null; + this._draw(1, fillMode, verticesStart, verticesCount, instancesCount); + } + //------------------------------------------------------------------------------ + // Dispose + //------------------------------------------------------------------------------ + /** + * Dispose and release all associated resources + */ + dispose() { + this._isDisposed = true; + this.hideLoadingUI(); + this._timestampQuery.dispose(); + this._mainTexture?.destroy(); + this._depthTexture?.destroy(); + this._textureHelper.destroyDeferredTextures(); + this._bufferManager.destroyDeferredBuffers(); + this._device.destroy(); + _CommonDispose(this, this._renderingCanvas); + super.dispose(); + } + //------------------------------------------------------------------------------ + // Misc + //------------------------------------------------------------------------------ + /** + * Gets the current render width + * @param useScreen defines if screen size must be used (or the current render target if any) + * @returns a number defining the current render width + */ + getRenderWidth(useScreen = false) { + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.width; + } + return this._renderingCanvas?.width ?? 0; + } + /** + * Gets the current render height + * @param useScreen defines if screen size must be used (or the current render target if any) + * @returns a number defining the current render height + */ + getRenderHeight(useScreen = false) { + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.height; + } + return this._renderingCanvas?.height ?? 0; + } + //------------------------------------------------------------------------------ + // Errors + //------------------------------------------------------------------------------ + /** + * Get the current error code of the WebGPU context + * @returns the error code + */ + getError() { + // TODO WEBGPU. from the webgpu errors. + return 0; + } + //------------------------------------------------------------------------------ + // External Textures + //------------------------------------------------------------------------------ + /** + * Creates an external texture + * @param video video element + * @returns the external texture, or null if external textures are not supported by the engine + */ + createExternalTexture(video) { + const texture = new WebGPUExternalTexture(video); + return texture; + } + /** + * Sets an internal texture to the according uniform. + * @param name The name of the uniform in the effect + * @param texture The texture to apply + */ + setExternalTexture(name, texture) { + if (!texture) { + this._currentMaterialContext.setTexture(name, null); + return; + } + this._setInternalTexture(name, texture); + } + //------------------------------------------------------------------------------ + // Samplers + //------------------------------------------------------------------------------ + /** + * Sets a texture sampler to the according uniform. + * @param name The name of the uniform in the effect + * @param sampler The sampler to apply + */ + setTextureSampler(name, sampler) { + this._currentMaterialContext?.setSampler(name, sampler); + } + //------------------------------------------------------------------------------ + // Storage Buffers + //------------------------------------------------------------------------------ + /** + * Creates a storage buffer + * @param data the data for the storage buffer or the size of the buffer + * @param creationFlags flags to use when creating the buffer (see undefined). The BUFFER_CREATIONFLAG_STORAGE flag will be automatically added + * @param label defines the label of the buffer (for debug purpose) + * @returns the new buffer + */ + createStorageBuffer(data, creationFlags, label) { + return this._createBuffer(data, creationFlags | 32, label); + } + /** + * Updates a storage buffer + * @param buffer the storage buffer to update + * @param data the data used to update the storage buffer + * @param byteOffset the byte offset of the data + * @param byteLength the byte length of the data + */ + updateStorageBuffer(buffer, data, byteOffset, byteLength) { + const dataBuffer = buffer; + if (byteOffset === undefined) { + byteOffset = 0; + } + let view; + if (byteLength === undefined) { + if (data instanceof Array) { + view = new Float32Array(data); + } + else if (data instanceof ArrayBuffer) { + view = new Uint8Array(data); + } + else { + view = data; + } + byteLength = view.byteLength; + } + else { + if (data instanceof Array) { + view = new Float32Array(data); + } + else if (data instanceof ArrayBuffer) { + view = new Uint8Array(data); + } + else { + view = data; + } + } + this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength); + } + _readFromGPUBuffer(gpuBuffer, size, buffer, noDelay) { + return new Promise((resolve, reject) => { + const readFromBuffer = () => { + gpuBuffer.mapAsync(1 /* WebGPUConstants.MapMode.Read */, 0, size).then(() => { + const copyArrayBuffer = gpuBuffer.getMappedRange(0, size); + let data = buffer; + if (data === undefined) { + data = new Uint8Array(size); + data.set(new Uint8Array(copyArrayBuffer)); + } + else { + const ctor = data.constructor; // we want to create result data with the same type as buffer (Uint8Array, Float32Array, ...) + data = new ctor(data.buffer); + data.set(new ctor(copyArrayBuffer)); + } + gpuBuffer.unmap(); + this._bufferManager.releaseBuffer(gpuBuffer); + resolve(data); + }, (reason) => { + if (this.isDisposed) { + resolve(new Uint8Array()); + } + else { + reject(reason); + } + }); + }; + if (noDelay) { + this.flushFramebuffer(); + readFromBuffer(); + } + else { + // we are using onEndFrameObservable because we need to map the gpuBuffer AFTER the command buffers + // have been submitted, else we get the error: "Buffer used in a submit while mapped" + this.onEndFrameObservable.addOnce(() => { + readFromBuffer(); + }); + } + }); + } + /** + * Read data from a storage buffer + * @param storageBuffer The storage buffer to read from + * @param offset The offset in the storage buffer to start reading from (default: 0) + * @param size The number of bytes to read from the storage buffer (default: capacity of the buffer) + * @param buffer The buffer to write the data we have read from the storage buffer to (optional) + * @param noDelay If true, a call to flushFramebuffer will be issued so that the data can be read back immediately and not in engine.onEndFrameObservable. This can speed up data retrieval, at the cost of a small perf penalty (default: false). + * @returns If not undefined, returns the (promise) buffer (as provided by the 4th parameter) filled with the data, else it returns a (promise) Uint8Array with the data read from the storage buffer + */ + readFromStorageBuffer(storageBuffer, offset, size, buffer, noDelay) { + size = size || storageBuffer.capacity; + const gpuBuffer = this._bufferManager.createRawBuffer(size, BufferUsage.MapRead | BufferUsage.CopyDst, undefined, "TempReadFromStorageBuffer"); + this._renderEncoder.copyBufferToBuffer(storageBuffer.underlyingResource, offset ?? 0, gpuBuffer, 0, size); + return this._readFromGPUBuffer(gpuBuffer, size, buffer, noDelay); + } + /** + * Read data from multiple storage buffers + * @param storageBuffers The list of storage buffers to read from + * @param offset The offset in the storage buffer to start reading from (default: 0). This is the same offset for all storage buffers! + * @param size The number of bytes to read from each storage buffer (default: capacity of the first buffer) + * @param buffer The buffer to write the data we have read from the storage buffers to (optional). If provided, the buffer should be large enough to hold the data from all storage buffers! + * @param noDelay If true, a call to flushFramebuffer will be issued so that the data can be read back immediately and not in engine.onEndFrameObservable. This can speed up data retrieval, at the cost of a small perf penalty (default: false). + * @returns If not undefined, returns the (promise) buffer (as provided by the 4th parameter) filled with the data, else it returns a (promise) Uint8Array with the data read from the storage buffer + */ + readFromMultipleStorageBuffers(storageBuffers, offset, size, buffer, noDelay) { + size = size || storageBuffers[0].capacity; + const gpuBuffer = this._bufferManager.createRawBuffer(size * storageBuffers.length, BufferUsage.MapRead | BufferUsage.CopyDst, undefined, "TempReadFromMultipleStorageBuffers"); + for (let i = 0; i < storageBuffers.length; i++) { + this._renderEncoder.copyBufferToBuffer(storageBuffers[i].underlyingResource, offset ?? 0, gpuBuffer, i * size, size); + } + return this._readFromGPUBuffer(gpuBuffer, size * storageBuffers.length, buffer, noDelay); + } + /** + * Sets a storage buffer in the shader + * @param name Defines the name of the storage buffer as defined in the shader + * @param buffer Defines the value to give to the uniform + */ + setStorageBuffer(name, buffer) { + this._currentDrawContext?.setBuffer(name, buffer?.getBuffer() ?? null); + } +} +// Default glslang options. +WebGPUEngine._GlslangDefaultOptions = { + jsPath: `${Tools._DefaultCdnUrl}/glslang/glslang.js`, + wasmPath: `${Tools._DefaultCdnUrl}/glslang/glslang.wasm`, +}; +WebGPUEngine._InstanceId = 0; + +/** @internal */ +class WebGPUComputeContext { + getBindGroups(bindings, computePipeline, bindingsMapping) { + if (!bindingsMapping) { + throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!"); + } + if (this._bindGroups.length === 0) { + const bindGroupEntriesExist = this._bindGroupEntries.length > 0; + for (const key in bindings) { + const binding = bindings[key], location = bindingsMapping[key], group = location.group, index = location.binding, type = binding.type, object = binding.object; + let indexInGroupEntries = binding.indexInGroupEntries; + let entries = this._bindGroupEntries[group]; + if (!entries) { + entries = this._bindGroupEntries[group] = []; + } + switch (type) { + case 5 /* ComputeBindingType.Sampler */: { + const sampler = object; + if (indexInGroupEntries !== undefined && bindGroupEntriesExist) { + entries[indexInGroupEntries].resource = this._cacheSampler.getSampler(sampler); + } + else { + binding.indexInGroupEntries = entries.length; + entries.push({ + binding: index, + resource: this._cacheSampler.getSampler(sampler), + }); + } + break; + } + case 0 /* ComputeBindingType.Texture */: + case 4 /* ComputeBindingType.TextureWithoutSampler */: { + const texture = object; + const hardwareTexture = texture._texture._hardwareTexture; + if (indexInGroupEntries !== undefined && bindGroupEntriesExist) { + if (type === 0 /* ComputeBindingType.Texture */) { + entries[indexInGroupEntries++].resource = this._cacheSampler.getSampler(texture._texture); + } + entries[indexInGroupEntries].resource = hardwareTexture.view; + } + else { + binding.indexInGroupEntries = entries.length; + if (type === 0 /* ComputeBindingType.Texture */) { + entries.push({ + binding: index - 1, + resource: this._cacheSampler.getSampler(texture._texture), + }); + } + entries.push({ + binding: index, + resource: hardwareTexture.view, + }); + } + break; + } + case 1 /* ComputeBindingType.StorageTexture */: { + const texture = object; + const hardwareTexture = texture._texture._hardwareTexture; + if ((hardwareTexture.textureAdditionalUsages & 8 /* WebGPUConstants.TextureUsage.StorageBinding */) === 0) { + Logger.Error(`computeDispatch: The texture (name=${texture.name}, uniqueId=${texture.uniqueId}) is not a storage texture!`, 50); + } + if (indexInGroupEntries !== undefined && bindGroupEntriesExist) { + entries[indexInGroupEntries].resource = hardwareTexture.viewForWriting; + } + else { + binding.indexInGroupEntries = entries.length; + entries.push({ + binding: index, + resource: hardwareTexture.viewForWriting, + }); + } + break; + } + case 6 /* ComputeBindingType.ExternalTexture */: { + const texture = object; + const externalTexture = texture.underlyingResource; + if (indexInGroupEntries !== undefined && bindGroupEntriesExist) { + entries[indexInGroupEntries].resource = this._device.importExternalTexture({ source: externalTexture }); + } + else { + binding.indexInGroupEntries = entries.length; + entries.push({ + binding: index, + resource: this._device.importExternalTexture({ source: externalTexture }), + }); + } + break; + } + case 2 /* ComputeBindingType.UniformBuffer */: + case 3 /* ComputeBindingType.StorageBuffer */: + case 7 /* ComputeBindingType.DataBuffer */: { + const dataBuffer = type === 7 /* ComputeBindingType.DataBuffer */ + ? object + : type === 2 /* ComputeBindingType.UniformBuffer */ + ? object.getBuffer() + : object.getBuffer(); + const webgpuBuffer = dataBuffer.underlyingResource; + if (indexInGroupEntries !== undefined && bindGroupEntriesExist) { + entries[indexInGroupEntries].resource.buffer = webgpuBuffer; + entries[indexInGroupEntries].resource.size = dataBuffer.capacity; + } + else { + binding.indexInGroupEntries = entries.length; + entries.push({ + binding: index, + resource: { + buffer: webgpuBuffer, + offset: 0, + size: dataBuffer.capacity, + }, + }); + } + break; + } + } + } + for (let i = 0; i < this._bindGroupEntries.length; ++i) { + const entries = this._bindGroupEntries[i]; + if (!entries) { + this._bindGroups[i] = undefined; + continue; + } + this._bindGroups[i] = this._device.createBindGroup({ + layout: computePipeline.getBindGroupLayout(i), + entries, + }); + } + this._bindGroups.length = this._bindGroupEntries.length; + } + return this._bindGroups; + } + constructor(device, cacheSampler) { + this._device = device; + this._cacheSampler = cacheSampler; + this.uniqueId = WebGPUComputeContext._Counter++; + this._bindGroupEntries = []; + this.clear(); + } + clear() { + this._bindGroups = []; + // Don't reset _bindGroupEntries if they have already been created, they are still ok even if we have to clear _bindGroups (the layout of the compute shader can't change once created) + } +} +WebGPUComputeContext._Counter = 0; + +/** @internal */ +class WebGPUComputePipelineContext { + get isAsync() { + return false; + } + get isReady() { + if (this.isAsync) { + // When async mode is implemented, this should return true if the pipeline is ready + return false; + } + // In synchronous mode, we return false, the readiness being determined by ComputeEffect + return false; + } + constructor(engine) { + this._name = "unnamed"; + this.engine = engine; + } + _getComputeShaderCode() { + return this.sources?.compute; + } + dispose() { } +} + +const computePassDescriptor = {}; +WebGPUEngine.prototype.createComputeContext = function () { + return new WebGPUComputeContext(this._device, this._cacheSampler); +}; +WebGPUEngine.prototype.createComputeEffect = function (baseName, options) { + const compute = typeof baseName === "string" ? baseName : baseName.computeToken || baseName.computeSource || baseName.computeElement || baseName.compute; + const name = compute + "@" + options.defines; + if (this._compiledComputeEffects[name]) { + const compiledEffect = this._compiledComputeEffects[name]; + if (options.onCompiled && compiledEffect.isReady()) { + options.onCompiled(compiledEffect); + } + return compiledEffect; + } + const effect = new ComputeEffect(baseName, options, this, name); + this._compiledComputeEffects[name] = effect; + return effect; +}; +WebGPUEngine.prototype.createComputePipelineContext = function () { + return new WebGPUComputePipelineContext(this); +}; +WebGPUEngine.prototype.areAllComputeEffectsReady = function () { + for (const key in this._compiledComputeEffects) { + const effect = this._compiledComputeEffects[key]; + if (!effect.isReady()) { + return false; + } + } + return true; +}; +WebGPUEngine.prototype.computeDispatch = function (effect, context, bindings, x, y = 1, z = 1, bindingsMapping, gpuPerfCounter) { + this._computeDispatch(effect, context, bindings, x, y, z, undefined, undefined, bindingsMapping, gpuPerfCounter); +}; +WebGPUEngine.prototype.computeDispatchIndirect = function (effect, context, bindings, buffer, offset = 0, bindingsMapping, gpuPerfCounter) { + this._computeDispatch(effect, context, bindings, undefined, undefined, undefined, buffer, offset, bindingsMapping, gpuPerfCounter); +}; +WebGPUEngine.prototype._computeDispatch = function (effect, context, bindings, x, y, z, buffer, offset, bindingsMapping, gpuPerfCounter) { + this._endCurrentRenderPass(); + const contextPipeline = effect._pipelineContext; + const computeContext = context; + if (!contextPipeline.computePipeline) { + contextPipeline.computePipeline = this._device.createComputePipeline({ + layout: "auto" /* WebGPUConstants.AutoLayoutMode.Auto */, + compute: contextPipeline.stage, + }); + } + if (gpuPerfCounter) { + this._timestampQuery.startPass(computePassDescriptor, this._timestampIndex); + } + const computePass = this._renderEncoder.beginComputePass(computePassDescriptor); + computePass.setPipeline(contextPipeline.computePipeline); + const bindGroups = computeContext.getBindGroups(bindings, contextPipeline.computePipeline, bindingsMapping); + for (let i = 0; i < bindGroups.length; ++i) { + const bindGroup = bindGroups[i]; + if (!bindGroup) { + continue; + } + computePass.setBindGroup(i, bindGroup); + } + if (buffer !== undefined) { + computePass.dispatchWorkgroupsIndirect(buffer.underlyingResource, offset); + } + else { + if (x + y + z > 0) { + computePass.dispatchWorkgroups(x, y, z); + } + } + computePass.end(); + if (gpuPerfCounter) { + this._timestampQuery.endPass(this._timestampIndex, gpuPerfCounter); + this._timestampIndex += 2; + } +}; +WebGPUEngine.prototype.releaseComputeEffects = function () { + for (const name in this._compiledComputeEffects) { + const webGPUPipelineContextCompute = this._compiledComputeEffects[name].getPipelineContext(); + this._deleteComputePipelineContext(webGPUPipelineContextCompute); + } + this._compiledComputeEffects = {}; +}; +WebGPUEngine.prototype._prepareComputePipelineContext = function (pipelineContext, computeSourceCode, rawComputeSourceCode, defines, entryPoint) { + const webGpuContext = pipelineContext; + if (this.dbgShowShaderCode) { + Logger.Log(defines); + Logger.Log(computeSourceCode); + } + webGpuContext.sources = { + compute: computeSourceCode, + rawCompute: rawComputeSourceCode, + }; + webGpuContext.stage = this._createComputePipelineStageDescriptor(computeSourceCode, defines, entryPoint); +}; +WebGPUEngine.prototype._releaseComputeEffect = function (effect) { + if (this._compiledComputeEffects[effect._key]) { + delete this._compiledComputeEffects[effect._key]; + this._deleteComputePipelineContext(effect.getPipelineContext()); + } +}; +WebGPUEngine.prototype._rebuildComputeEffects = function () { + for (const key in this._compiledComputeEffects) { + const effect = this._compiledComputeEffects[key]; + effect._pipelineContext = null; + effect._wasPreviouslyReady = false; + effect._prepareEffect(); + } +}; +WebGPUEngine.prototype._executeWhenComputeStateIsCompiled = function (pipelineContext, action) { + pipelineContext.stage.module.getCompilationInfo().then((info) => { + const compilationMessages = { + numErrors: 0, + messages: [], + }; + for (const message of info.messages) { + if (message.type === "error") { + compilationMessages.numErrors++; + } + compilationMessages.messages.push({ + type: message.type, + text: message.message, + line: message.lineNum, + column: message.linePos, + length: message.length, + offset: message.offset, + }); + } + action(compilationMessages); + }); +}; +WebGPUEngine.prototype._deleteComputePipelineContext = function (pipelineContext) { + const webgpuPipelineContext = pipelineContext; + if (webgpuPipelineContext) { + pipelineContext.dispose(); + } +}; +WebGPUEngine.prototype._createComputePipelineStageDescriptor = function (computeShader, defines, entryPoint) { + if (defines) { + defines = "//" + defines.split("\n").join("\n//") + "\n"; + } + else { + defines = ""; + } + return { + module: this._device.createShaderModule({ + code: defines + computeShader, + }), + entryPoint, + }; +}; + +WebGPUEngine.prototype._debugPushGroup = function (groupName, targetObject) { + if (!this._options.enableGPUDebugMarkers) { + return; + } + if (targetObject === 0 || targetObject === 1) { + if (targetObject === 1) { + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + else { + this._endCurrentRenderPass(); + } + } + this._renderEncoder.pushDebugGroup(groupName); + } + else if (this._currentRenderPass) { + this._currentRenderPass.pushDebugGroup(groupName); + this._debugStackRenderPass.push(groupName); + } + else { + this._pendingDebugCommands.push(["push", groupName, targetObject]); + } +}; +WebGPUEngine.prototype._debugPopGroup = function (targetObject) { + if (!this._options.enableGPUDebugMarkers) { + return; + } + if (targetObject === 0 || targetObject === 1) { + if (targetObject === 1) { + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + else { + this._endCurrentRenderPass(); + } + } + this._renderEncoder.popDebugGroup(); + } + else if (this._currentRenderPass) { + this._currentRenderPass.popDebugGroup(); + this._debugStackRenderPass.pop(); + } + else { + this._pendingDebugCommands.push(["pop", null, targetObject]); + } +}; +WebGPUEngine.prototype._debugInsertMarker = function (text, targetObject) { + if (!this._options.enableGPUDebugMarkers) { + return; + } + if (targetObject === 0 || targetObject === 1) { + if (targetObject === 1) { + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + else { + this._endCurrentRenderPass(); + } + } + this._renderEncoder.insertDebugMarker(text); + } + else if (this._currentRenderPass) { + this._currentRenderPass.insertDebugMarker(text); + } + else { + this._pendingDebugCommands.push(["insert", text, targetObject]); + } +}; +WebGPUEngine.prototype._debugFlushPendingCommands = function () { + if (this._debugStackRenderPass.length !== 0) { + const currentDebugStack = this._debugStackRenderPass.slice(); + this._debugStackRenderPass.length = 0; + for (let i = 0; i < currentDebugStack.length; ++i) { + this._debugPushGroup(currentDebugStack[i], 2); + } + } + for (let i = 0; i < this._pendingDebugCommands.length; ++i) { + const [name, param, targetObject] = this._pendingDebugCommands[i]; + switch (name) { + case "push": + this._debugPushGroup(param, targetObject); + break; + case "pop": + this._debugPopGroup(targetObject); + break; + case "insert": + this._debugInsertMarker(param, targetObject); + break; + } + } + this._pendingDebugCommands.length = 0; +}; + +WebGPUEngine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) { + const texture = new InternalTexture(this, 4 /* InternalTextureSource.Dynamic */); + texture.baseWidth = width; + texture.baseHeight = height; + if (generateMipMaps) { + width = this.needPOTTextures ? GetExponentOfTwo(width, this._caps.maxTextureSize) : width; + height = this.needPOTTextures ? GetExponentOfTwo(height, this._caps.maxTextureSize) : height; + } + texture.width = width; + texture.height = height; + texture.isReady = false; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + this.updateTextureSamplingMode(samplingMode, texture); + this._internalTexturesCache.push(texture); + if (width && height) { + this._textureHelper.createGPUTextureForInternalTexture(texture, width, height); + } + return texture; +}; +WebGPUEngine.prototype.updateDynamicTexture = function (texture, source, invertY, premulAlpha = false, format, forceBindTexture, allowGPUOptimization) { + if (!texture) { + return; + } + const width = source.width, height = source.height; + let gpuTextureWrapper = texture._hardwareTexture; + if (!texture._hardwareTexture?.underlyingResource) { + gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height); + } + this._textureHelper.updateTexture(source, texture, width, height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, premulAlpha, 0, 0, allowGPUOptimization); + if (texture.generateMipMaps) { + this._generateMipmaps(texture); + } + texture._dynamicTextureSource = source; + texture._premulAlpha = premulAlpha; + texture.invertY = invertY || false; + texture.isReady = true; +}; + +WebGPUEngine.prototype.unBindMultiColorAttachmentFramebuffer = function (rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) { + if (onBeforeUnbind) { + onBeforeUnbind(); + } + this._endCurrentRenderPass(); + if (!disableGenerateMipMaps) { + this.generateMipMapsMultiFramebuffer(rtWrapper); + } + this._currentRenderTarget = null; + this._mrtAttachments = []; + this._cacheRenderPipeline.setMRT([]); + this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments); +}; +WebGPUEngine.prototype.createMultipleRenderTarget = function (size, options, initializeBuffers) { + let generateMipMaps = false; + let generateDepthBuffer = true; + let generateStencilBuffer = false; + let generateDepthTexture = false; + let depthTextureFormat = 15; + let textureCount = 1; + let samples = 1; + const defaultType = 0; + const defaultSamplingMode = 3; + const defaultUseSRGBBuffer = false; + const defaultFormat = 5; + const defaultTarget = 3553; + let types = []; + let samplingModes = []; + let useSRGBBuffers = []; + let formats = []; + let targets = []; + let faceIndex = []; + let layerIndex = []; + let layers = []; + let labels = []; + let creationFlags = []; + let dontCreateTextures = false; + const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size); + if (options !== undefined) { + generateMipMaps = options.generateMipMaps ?? false; + generateDepthBuffer = options.generateDepthBuffer ?? true; + generateStencilBuffer = options.generateStencilBuffer ?? false; + generateDepthTexture = options.generateDepthTexture ?? false; + textureCount = options.textureCount ?? 1; + depthTextureFormat = options.depthTextureFormat ?? 15; + types = options.types || types; + samplingModes = options.samplingModes || samplingModes; + useSRGBBuffers = options.useSRGBBuffers || useSRGBBuffers; + formats = options.formats || formats; + targets = options.targetTypes || targets; + faceIndex = options.faceIndex || faceIndex; + layerIndex = options.layerIndex || layerIndex; + layers = options.layerCounts || layers; + labels = options.labels || labels; + creationFlags = options.creationFlags || creationFlags; + samples = options.samples ?? samples; + dontCreateTextures = options.dontCreateTextures ?? false; + } + const width = size.width ?? size; + const height = size.height ?? size; + const textures = []; + const attachments = []; + const defaultAttachments = []; + rtWrapper.label = options?.label ?? "MultiRenderTargetWrapper"; + rtWrapper._generateDepthBuffer = generateDepthBuffer; + rtWrapper._generateStencilBuffer = generateStencilBuffer; + rtWrapper._attachments = attachments; + rtWrapper._defaultAttachments = defaultAttachments; + let depthStencilTexture = null; + if ((generateDepthBuffer || generateStencilBuffer || generateDepthTexture) && !dontCreateTextures) { + if (!generateDepthTexture) { + // The caller doesn't want a depth texture, so we are free to use the depth texture format we want. + // So, we will align with what the WebGL engine does + if (generateDepthBuffer && generateStencilBuffer) { + depthTextureFormat = 13; + } + else if (generateDepthBuffer) { + depthTextureFormat = 14; + } + else { + depthTextureFormat = 19; + } + } + depthStencilTexture = rtWrapper.createDepthStencilTexture(0, false, generateStencilBuffer, 1, depthTextureFormat, rtWrapper.label + "-DepthStencil"); + } + const mipmapsCreationOnly = options !== undefined && typeof options === "object" && options.createMipMaps && !generateMipMaps; + for (let i = 0; i < textureCount; i++) { + let samplingMode = samplingModes[i] || defaultSamplingMode; + let type = types[i] || defaultType; + const format = formats[i] || defaultFormat; + const useSRGBBuffer = (useSRGBBuffers[i] || defaultUseSRGBBuffer) && this._caps.supportSRGBBuffers; + const target = targets[i] || defaultTarget; + const layerCount = layers[i] ?? 1; + const creationFlag = creationFlags[i]; + if (type === 1 && !this._caps.textureFloatLinearFiltering) { + // if floating point linear (FLOAT) then force to NEAREST_SAMPLINGMODE + samplingMode = 1; + } + else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { + // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE + samplingMode = 1; + } + if (type === 1 && !this._caps.textureFloat) { + type = 0; + Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"); + } + attachments.push(i + 1); + defaultAttachments.push(initializeBuffers ? i + 1 : i === 0 ? 1 : 0); + if (target === -1 || dontCreateTextures) { + continue; + } + const texture = new InternalTexture(this, 6 /* InternalTextureSource.MultiRenderTarget */); + textures[i] = texture; + switch (target) { + case 34067: + texture.isCube = true; + break; + case 32879: + texture.is3D = true; + texture.baseDepth = texture.depth = layerCount; + break; + case 35866: + texture.is2DArray = true; + texture.baseDepth = texture.depth = layerCount; + break; + } + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.isReady = true; + texture.samples = 1; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.type = type; + texture._cachedWrapU = 0; + texture._cachedWrapV = 0; + texture._useSRGBBuffer = useSRGBBuffer; + texture.format = format; + texture.label = labels[i] ?? rtWrapper.label + "-Texture" + i; + this._internalTexturesCache.push(texture); + if (mipmapsCreationOnly) { + // createGPUTextureForInternalTexture will only create a texture with mipmaps if generateMipMaps is true, as InternalTexture has no createMipMaps property, separate from generateMipMaps. + texture.generateMipMaps = true; + } + this._textureHelper.createGPUTextureForInternalTexture(texture, undefined, undefined, undefined, creationFlag, true); + if (mipmapsCreationOnly) { + texture.generateMipMaps = false; + } + } + if (depthStencilTexture) { + depthStencilTexture.incrementReferences(); + textures[textureCount] = depthStencilTexture; + this._internalTexturesCache.push(depthStencilTexture); + } + rtWrapper.setTextures(textures); + rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex); + if (!dontCreateTextures) { + this.updateMultipleRenderTargetTextureSampleCount(rtWrapper, samples); + } + else { + rtWrapper._samples = samples; + } + return rtWrapper; +}; +WebGPUEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function (rtWrapper, samples) { + if (!rtWrapper || !rtWrapper.textures || rtWrapper.textures.length === 0 || rtWrapper.textures[0].samples === samples) { + return samples; + } + const count = rtWrapper.textures.length; + if (count === 0) { + return 1; + } + samples = Math.min(samples, this.getCaps().maxMSAASamples); + for (let i = 0; i < count; ++i) { + const texture = rtWrapper.textures[i]; + const gpuTextureWrapper = texture._hardwareTexture; + gpuTextureWrapper?.releaseMSAATexture(rtWrapper.getBaseArrayLayer(i)); + } + // Note that rtWrapper.textures can't have null textures, lastTextureIsDepthTexture can't be true if rtWrapper._depthStencilTexture is null + const lastTextureIsDepthTexture = rtWrapper._depthStencilTexture === rtWrapper.textures[count - 1]; + for (let i = 0; i < count; ++i) { + const texture = rtWrapper.textures[i]; + this._textureHelper.createMSAATexture(texture, samples, false, rtWrapper.getBaseArrayLayer(i)); + texture.samples = samples; + } + // Note that the last texture of textures is the depth texture if the depth texture has been generated by the MRT class and so the MSAA texture + // will be recreated for this texture by the loop above: in that case, there's no need to create the MSAA texture for rtWrapper._depthStencilTexture + // because rtWrapper._depthStencilTexture is the same texture than the depth texture + if (rtWrapper._depthStencilTexture && !lastTextureIsDepthTexture) { + this._textureHelper.createMSAATexture(rtWrapper._depthStencilTexture, samples); + rtWrapper._depthStencilTexture.samples = samples; + } + rtWrapper._samples = samples; + return samples; +}; +WebGPUEngine.prototype.generateMipMapsMultiFramebuffer = function (texture) { + const rtWrapper = texture; + if (!rtWrapper.isMulti) { + return; + } + const attachments = rtWrapper._attachments; + const count = attachments.length; + for (let i = 0; i < count; i++) { + const texture = rtWrapper.textures[i]; + if (texture.generateMipMaps && !texture.isCube && !texture.is3D) { + this._generateMipmaps(texture); + } + } +}; +WebGPUEngine.prototype.resolveMultiFramebuffer = function (_texture) { + throw new Error("resolveMultiFramebuffer is not yet implemented in WebGPU!"); +}; +WebGPUEngine.prototype.bindAttachments = function (attachments) { + if (attachments.length === 0 || !this._currentRenderTarget) { + return; + } + this._mrtAttachments = attachments; + if (this._currentRenderPass) { + // the render pass has already been created, we need to call setMRTAttachments to update the state of the attachments + this._cacheRenderPipeline.setMRTAttachments(attachments); + } +}; +WebGPUEngine.prototype.buildTextureLayout = function (textureStatus) { + const result = []; + for (let i = 0; i < textureStatus.length; i++) { + if (textureStatus[i]) { + result.push(i + 1); + } + else { + result.push(0); + } + } + return result; +}; +WebGPUEngine.prototype.restoreSingleAttachment = function () { + // not sure what to do, probably nothing... This function and restoreSingleAttachmentForRenderTarget are not called in Babylon.js so it's hard to know the use case +}; +WebGPUEngine.prototype.restoreSingleAttachmentForRenderTarget = function () { + // not sure what to do, probably nothing... This function and restoreSingleAttachment are not called in Babylon.js so it's hard to know the use case +}; + +function IsExternalTexture(texture) { + return texture && texture.underlyingResource !== undefined ? true : false; +} +WebGPUEngine.prototype.updateVideoTexture = function (texture, video, invertY) { + if (!texture || texture._isDisabled) { + return; + } + if (this._videoTextureSupported === undefined) { + this._videoTextureSupported = true; + } + let gpuTextureWrapper = texture._hardwareTexture; + if (!texture._hardwareTexture?.underlyingResource) { + gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture); + } + if (IsExternalTexture(video)) { + if (video.isReady()) { + try { + this._textureHelper.copyVideoToTexture(video, texture, gpuTextureWrapper.format, !invertY); + if (texture.generateMipMaps) { + this._generateMipmaps(texture); + } + } + catch (e) { + // WebGPU doesn't support video element who are not playing so far + // Ignore this error ensures we can start a video texture in a paused state + } + texture.isReady = true; + } + } + else if (video) { + this.createImageBitmap(video) + .then((bitmap) => { + this._textureHelper.updateTexture(bitmap, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, !invertY, false, 0, 0); + if (texture.generateMipMaps) { + this._generateMipmaps(texture); + } + texture.isReady = true; + }) + .catch(() => { + // Sometimes createImageBitmap(video) fails with "Failed to execute 'createImageBitmap' on 'Window': The provided element's player has no current data." + // Just keep going on + texture.isReady = true; + }); + } +}; + +const pathHasTemplatesRegex = new RegExp(/\/\{(\w+)\}\//g); +/** + * @experimental + * A component that converts a path to an object accessor. + */ +class FlowGraphPathConverterComponent { + constructor(path, ownerBlock) { + this.path = path; + this.ownerBlock = ownerBlock; + /** + * The templated inputs for the provided path. + */ + this.templatedInputs = []; + let match = pathHasTemplatesRegex.exec(path); + const templateSet = new Set(); + while (match) { + const [, matchGroup] = match; + if (templateSet.has(matchGroup)) { + throw new Error("Duplicate template variable detected."); + } + templateSet.add(matchGroup); + this.templatedInputs.push(ownerBlock.registerDataInput(matchGroup, RichTypeFlowGraphInteger, new FlowGraphInteger(0))); + match = pathHasTemplatesRegex.exec(path); + } + } + /** + * Get the accessor for the path. + * @param pathConverter the path converter to use to convert the path to an object accessor. + * @param context the context to use. + * @returns the accessor for the path. + * @throws if the value for a templated input is invalid. + */ + getAccessor(pathConverter, context) { + let finalPath = this.path; + for (const templatedInput of this.templatedInputs) { + const valueToReplace = templatedInput.getValue(context).value; + if (typeof valueToReplace !== "number" || valueToReplace < 0) { + throw new Error("Invalid value for templated input."); + } + finalPath = finalPath.replace(`{${templatedInput.name}}`, valueToReplace.toString()); + } + return pathConverter.convert(finalPath); + } +} + +/** + * Block that logs a message to the console. + */ +class FlowGraphConsoleLogBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor(config) { + super(config); + this.message = this.registerDataInput("message", RichTypeAny); + this.logType = this.registerDataInput("logType", RichTypeAny, "log"); + if (config?.messageTemplate) { + const matches = this._getTemplateMatches(config.messageTemplate); + for (const match of matches) { + this.registerDataInput(match, RichTypeAny); + } + } + } + /** + * @internal + */ + _execute(context) { + const typeValue = this.logType.getValue(context); + const messageValue = this._getMessageValue(context); + if (typeValue === "warn") { + Logger.Warn(messageValue); + } + else if (typeValue === "error") { + Logger.Error(messageValue); + } + else { + Logger.Log(messageValue); + } + // activate the output flow block + this.out._activateSignal(context); + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphConsoleLogBlock" /* FlowGraphBlockNames.ConsoleLog */; + } + _getMessageValue(context) { + if (this.config?.messageTemplate) { + let template = this.config.messageTemplate; + const matches = this._getTemplateMatches(template); + for (const match of matches) { + const value = this.getDataInput(match)?.getValue(context); + if (value !== undefined) { + // replace all + template = template.replace(new RegExp(`\\{${match}\\}`, "g"), value.toString()); + } + } + return template; + } + else { + return this.message.getValue(context); + } + } + _getTemplateMatches(template) { + const regex = /\{([^}]+)\}/g; + const matches = []; + let match; + while ((match = regex.exec(template)) !== null) { + matches.push(match[1]); + } + return matches; + } +} +RegisterClass("FlowGraphConsoleLogBlock" /* FlowGraphBlockNames.ConsoleLog */, FlowGraphConsoleLogBlock); + +const flowGraphConsoleLogBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphConsoleLogBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that evaluates a condition and activates one of two branches. + */ +class FlowGraphBranchBlock extends FlowGraphExecutionBlock { + constructor(config) { + super(config); + this.condition = this.registerDataInput("condition", RichTypeBoolean); + this.onTrue = this._registerSignalOutput("onTrue"); + this.onFalse = this._registerSignalOutput("onFalse"); + } + _execute(context) { + if (this.condition.getValue(context)) { + this.onTrue._activateSignal(context); + } + else { + this.onFalse._activateSignal(context); + } + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphBranchBlock" /* FlowGraphBlockNames.Branch */; + } +} +RegisterClass("FlowGraphBranchBlock" /* FlowGraphBlockNames.Branch */, FlowGraphBranchBlock); + +const flowGraphBranchBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphBranchBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that executes a branch a set number of times. + */ +class FlowGraphDoNBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor( + /** + * [Object] the configuration of the block + */ + config = {}) { + super(config); + this.config = config; + this.config.startIndex = config.startIndex ?? new FlowGraphInteger(0); + this.reset = this._registerSignalInput("reset"); + this.maxExecutions = this.registerDataInput("maxExecutions", RichTypeFlowGraphInteger); + this.executionCount = this.registerDataOutput("executionCount", RichTypeFlowGraphInteger, new FlowGraphInteger(0)); + } + _execute(context, callingSignal) { + if (callingSignal === this.reset) { + this.executionCount.setValue(this.config.startIndex, context); + } + else { + const currentCountValue = this.executionCount.getValue(context); + if (currentCountValue.value < this.maxExecutions.getValue(context).value) { + this.executionCount.setValue(new FlowGraphInteger(currentCountValue.value + 1), context); + this.out._activateSignal(context); + } + } + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphDoNBlock" /* FlowGraphBlockNames.DoN */; + } +} +RegisterClass("FlowGraphDoNBlock" /* FlowGraphBlockNames.DoN */, FlowGraphDoNBlock); + +const flowGraphDoNBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphDoNBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Block that executes an action in a loop. + */ +class FlowGraphForLoopBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor(config) { + super(config); + this.startIndex = this.registerDataInput("startIndex", RichTypeAny, 0); + this.endIndex = this.registerDataInput("endIndex", RichTypeAny); + this.step = this.registerDataInput("step", RichTypeNumber, 1); + this.index = this.registerDataOutput("index", RichTypeFlowGraphInteger, new FlowGraphInteger(getNumericValue(config?.initialIndex ?? 0))); + this.executionFlow = this._registerSignalOutput("executionFlow"); + this.completed = this._registerSignalOutput("completed"); + this._unregisterSignalOutput("out"); + } + /** + * @internal + */ + _execute(context) { + const index = getNumericValue(this.startIndex.getValue(context)); + const step = this.step.getValue(context); + let endIndex = getNumericValue(this.endIndex.getValue(context)); + for (let i = index; i < endIndex; i += step) { + this.index.setValue(new FlowGraphInteger(i), context); + this.executionFlow._activateSignal(context); + endIndex = getNumericValue(this.endIndex.getValue(context)); + if (i > FlowGraphForLoopBlock.MaxLoopIterations) { + break; + } + } + this.completed._activateSignal(context); + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphForLoopBlock" /* FlowGraphBlockNames.ForLoop */; + } +} +/** + * The maximum number of iterations allowed for the loop. + * If the loop exceeds this number, it will stop. This number is configurable to avoid infinite loops. + */ +FlowGraphForLoopBlock.MaxLoopIterations = 1000; +RegisterClass("FlowGraphForLoopBlock" /* FlowGraphBlockNames.ForLoop */, FlowGraphForLoopBlock); + +const flowGraphForLoopBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphForLoopBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that throttles the execution of its output flow. + */ +class FlowGraphThrottleBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor(config) { + super(config); + this.reset = this._registerSignalInput("reset"); + this.duration = this.registerDataInput("duration", RichTypeNumber); + this.lastRemainingTime = this.registerDataOutput("lastRemainingTime", RichTypeNumber, NaN); + } + _execute(context, callingSignal) { + if (callingSignal === this.reset) { + this.lastRemainingTime.setValue(NaN, context); + context._setExecutionVariable(this, "lastRemainingTime", NaN); + context._setExecutionVariable(this, "timestamp", 0); + return; + } + // in seconds + const durationValue = this.duration.getValue(context); + if (durationValue <= 0 || isNaN(durationValue) || !isFinite(durationValue)) { + return this._reportError(context, "Invalid duration in Throttle block"); + } + const lastRemainingTime = context._getExecutionVariable(this, "lastRemainingTime", NaN); + // Using Date.now() to get ms since epoch. not using performance.now() because its precision is not needed here + const currentTime = Date.now(); + if (isNaN(lastRemainingTime)) { + this.lastRemainingTime.setValue(0, context); + context._setExecutionVariable(this, "lastRemainingTime", 0); + context._setExecutionVariable(this, "timestamp", currentTime); + // according to glTF interactivity specs + return this.out._activateSignal(context); + } + else { + const elapsedTime = currentTime - context._getExecutionVariable(this, "timestamp", 0); + // duration is in seconds, so we need to multiply by 1000 + const durationInMs = durationValue * 1000; + if (durationInMs <= elapsedTime) { + this.lastRemainingTime.setValue(0, context); + context._setExecutionVariable(this, "lastRemainingTime", 0); + context._setExecutionVariable(this, "timestamp", currentTime); + return this.out._activateSignal(context); + } + else { + const remainingTime = durationInMs - elapsedTime; + // output is in seconds + this.lastRemainingTime.setValue(remainingTime / 1000, context); + context._setExecutionVariable(this, "lastRemainingTime", remainingTime); + } + } + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphThrottleBlock" /* FlowGraphBlockNames.Throttle */; + } +} +RegisterClass("FlowGraphThrottleBlock" /* FlowGraphBlockNames.Throttle */, FlowGraphThrottleBlock); + +const flowGraphThrottleBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphThrottleBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that has an input flow and routes it to any potential output flows, randomly or sequentially + */ +class FlowGraphMultiGateBlock extends FlowGraphExecutionBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + /** + * Output connections: The output signals. + */ + this.outputSignals = []; + this.reset = this._registerSignalInput("reset"); + this.lastIndex = this.registerDataOutput("lastIndex", RichTypeFlowGraphInteger, new FlowGraphInteger(-1)); + this.setNumberOfOutputSignals(config?.outputSignalCount); + } + _getNextIndex(indexesUsed) { + // find the next index available from the indexes used array + // if all outputs were used, reset the indexes used array if we are in a loop multi gate + if (!indexesUsed.includes(false)) { + if (this.config.isLoop) { + indexesUsed.fill(false); + } + } + if (!this.config.isRandom) { + return indexesUsed.indexOf(false); + } + else { + const unusedIndexes = indexesUsed.map((used, index) => (used ? -1 : index)).filter((index) => index !== -1); + return unusedIndexes.length ? unusedIndexes[Math.floor(Math.random() * unusedIndexes.length)] : -1; + } + } + /** + * Sets the block's output signals. Would usually be passed from the constructor but can be changed afterwards. + * @param numberOutputSignals the number of output flows + */ + setNumberOfOutputSignals(numberOutputSignals = 1) { + // check the size of the outFlow Array, see if it is not larger than needed + while (this.outputSignals.length > numberOutputSignals) { + const flow = this.outputSignals.pop(); + if (flow) { + flow.disconnectFromAll(); + this._unregisterSignalOutput(flow.name); + } + } + while (this.outputSignals.length < numberOutputSignals) { + this.outputSignals.push(this._registerSignalOutput(`out_${this.outputSignals.length}`)); + } + } + _execute(context, callingSignal) { + // set the state(s) of the block + if (!context._hasExecutionVariable(this, "indexesUsed")) { + context._setExecutionVariable(this, "indexesUsed", this.outputSignals.map(() => false)); + } + if (callingSignal === this.reset) { + context._deleteExecutionVariable(this, "indexesUsed"); + this.lastIndex.setValue(new FlowGraphInteger(-1), context); + return; + } + const indexesUsed = context._getExecutionVariable(this, "indexesUsed", []); + const nextIndex = this._getNextIndex(indexesUsed); + if (nextIndex > -1) { + this.lastIndex.setValue(new FlowGraphInteger(nextIndex), context); + indexesUsed[nextIndex] = true; + context._setExecutionVariable(this, "indexesUsed", indexesUsed); + this.outputSignals[nextIndex]._activateSignal(context); + } + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphMultiGateBlock" /* FlowGraphBlockNames.MultiGate */; + } + /** + * Serializes the block. + * @param serializationObject the object to serialize to. + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.config.outputSignalCount = this.config.outputSignalCount; + serializationObject.config.isRandom = this.config.isRandom; + serializationObject.config.loop = this.config.isLoop; + serializationObject.config.startIndex = this.config.startIndex; + } +} +RegisterClass("FlowGraphMultiGateBlock" /* FlowGraphBlockNames.MultiGate */, FlowGraphMultiGateBlock); + +const flowGraphMultiGateBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphMultiGateBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that executes a branch based on a selection. + */ +class FlowGraphSwitchBlock extends FlowGraphExecutionBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + /** + * The default case to execute if no other case is found. + */ + this.default = this._registerSignalOutput("default"); + this._caseToOutputFlow = new Map(); + this.case = this.registerDataInput("case", RichTypeAny); + // iterate the set not using for of + (this.config.cases || []).forEach((caseValue) => { + this._caseToOutputFlow.set(caseValue, this._registerSignalOutput(`out_${caseValue}`)); + }); + } + _execute(context, _callingSignal) { + const selectionValue = this.case.getValue(context); + let outputFlow; + if (isNumeric(selectionValue)) { + outputFlow = this._getOutputFlowForCase(getNumericValue(selectionValue)); + } + else { + outputFlow = this._getOutputFlowForCase(selectionValue); + } + if (outputFlow) { + outputFlow._activateSignal(context); + } + else { + this.default._activateSignal(context); + } + } + /** + * Adds a new case to the switch block. + * @param newCase the new case to add. + */ + addCase(newCase) { + if (this.config.cases.includes(newCase)) { + return; + } + this.config.cases.push(newCase); + this._caseToOutputFlow.set(newCase, this._registerSignalOutput(`out_${newCase}`)); + } + /** + * Removes a case from the switch block. + * @param caseToRemove the case to remove. + */ + removeCase(caseToRemove) { + if (!this.config.cases.includes(caseToRemove)) { + return; + } + const index = this.config.cases.indexOf(caseToRemove); + this.config.cases.splice(index, 1); + this._caseToOutputFlow.delete(caseToRemove); + } + /** + * @internal + */ + _getOutputFlowForCase(caseValue) { + return this._caseToOutputFlow.get(caseValue); + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphSwitchBlock" /* FlowGraphBlockNames.Switch */; + } + /** + * Serialize the block to a JSON representation. + * @param serializationObject the object to serialize to. + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.cases = this.config.cases; + } +} +RegisterClass("FlowGraphSwitchBlock" /* FlowGraphBlockNames.Switch */, FlowGraphSwitchBlock); + +const flowGraphSwitchBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphSwitchBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that waits for all input flows to be activated before activating its output flow. + */ +class FlowGraphWaitAllBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + /** + * An array of input signals + */ + this.inFlows = []; + this._cachedActivationState = []; + this.reset = this._registerSignalInput("reset"); + this.completed = this._registerSignalOutput("completed"); + this.remainingInputs = this.registerDataOutput("remainingInputs", RichTypeNumber, this.config.inputSignalCount || 0); + // The first inFlow is the default input signal all execution blocks have + for (let i = 0; i < this.config.inputSignalCount; i++) { + this.inFlows.push(this._registerSignalInput(`in_${i}`)); + } + // no need for in + this._unregisterSignalInput("in"); + } + _getCurrentActivationState(context) { + const activationState = this._cachedActivationState; + activationState.length = 0; + if (!context._hasExecutionVariable(this, "activationState")) { + for (let i = 0; i < this.config.inputSignalCount; i++) { + activationState.push(false); + } + } + else { + const contextActivationState = context._getExecutionVariable(this, "activationState", []); + for (let i = 0; i < contextActivationState.length; i++) { + activationState.push(contextActivationState[i]); + } + } + return activationState; + } + _execute(context, callingSignal) { + const activationState = this._getCurrentActivationState(context); + if (callingSignal === this.reset) { + for (let i = 0; i < this.config.inputSignalCount; i++) { + activationState[i] = false; + } + } + else { + const index = this.inFlows.indexOf(callingSignal); + if (index >= 0) { + activationState[index] = true; + } + } + this.remainingInputs.setValue(activationState.filter((v) => !v).length, context); + context._setExecutionVariable(this, "activationState", activationState.slice()); + if (!activationState.includes(false)) { + this.completed._activateSignal(context); + for (let i = 0; i < this.config.inputSignalCount; i++) { + activationState[i] = false; + } + } + else { + callingSignal !== this.reset && this.out._activateSignal(context); + } + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphWaitAllBlock" /* FlowGraphBlockNames.WaitAll */; + } + /** + * Serializes this block into a object + * @param serializationObject the object to serialize to + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.config.inputFlows = this.config.inputSignalCount; + } +} +RegisterClass("FlowGraphWaitAllBlock" /* FlowGraphBlockNames.WaitAll */, FlowGraphWaitAllBlock); + +const flowGraphWaitAllBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphWaitAllBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that counts the number of times it has been called. + * Afterwards it activates its out signal. + */ +class FlowGraphCallCounterBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor(config) { + super(config); + this.count = this.registerDataOutput("count", RichTypeNumber); + this.reset = this._registerSignalInput("reset"); + } + _execute(context, callingSignal) { + if (callingSignal === this.reset) { + context._setExecutionVariable(this, "count", 0); + this.count.setValue(0, context); + return; + } + const countValue = context._getExecutionVariable(this, "count", 0) + 1; + context._setExecutionVariable(this, "count", countValue); + this.count.setValue(countValue, context); + this.out._activateSignal(context); + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphCallCounterBlock" /* FlowGraphBlockNames.CallCounter */; + } +} +RegisterClass("FlowGraphCallCounterBlock" /* FlowGraphBlockNames.CallCounter */, FlowGraphCallCounterBlock); + +const flowGraphCounterBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphCallCounterBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that executes a branch while a condition is true. + */ +class FlowGraphWhileLoopBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + this.condition = this.registerDataInput("condition", RichTypeBoolean); + this.executionFlow = this._registerSignalOutput("executionFlow"); + this.completed = this._registerSignalOutput("completed"); + // unregister "out" signal + this._unregisterSignalOutput("out"); + } + _execute(context, _callingSignal) { + let conditionValue = this.condition.getValue(context); + if (this.config?.doWhile && !conditionValue) { + this.executionFlow._activateSignal(context); + } + let i = 0; + while (conditionValue) { + this.executionFlow._activateSignal(context); + ++i; + if (i >= FlowGraphWhileLoopBlock.MaxLoopCount) { + Logger.Warn("FlowGraphWhileLoopBlock: Max loop count reached. Breaking."); + break; + } + conditionValue = this.condition.getValue(context); + } + // out is not triggered - completed is triggered + this.completed._activateSignal(context); + } + getClassName() { + return "FlowGraphWhileLoopBlock" /* FlowGraphBlockNames.WhileLoop */; + } +} +/** + * The maximum number of iterations allowed in a loop. + * This can be set to avoid an infinite loop. + */ +FlowGraphWhileLoopBlock.MaxLoopCount = 1000; +RegisterClass("FlowGraphWhileLoopBlock" /* FlowGraphBlockNames.WhileLoop */, FlowGraphWhileLoopBlock); + +const flowGraphWhileLoopBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphWhileLoopBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This block debounces the execution of a input, i.e. ensures that the input is only executed once every X times + */ +class FlowGraphDebounceBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor(config) { + super(config); + this.count = this.registerDataInput("count", RichTypeNumber); + this.reset = this._registerSignalInput("reset"); + this.currentCount = this.registerDataOutput("currentCount", RichTypeNumber); + } + _execute(context, callingSignal) { + if (callingSignal === this.reset) { + context._setExecutionVariable(this, "debounceCount", 0); + return; + } + const count = this.count.getValue(context); + const currentCount = context._getExecutionVariable(this, "debounceCount", 0); + const newCount = currentCount + 1; + this.currentCount.setValue(newCount, context); + context._setExecutionVariable(this, "debounceCount", newCount); + if (newCount >= count) { + this.out._activateSignal(context); + context._setExecutionVariable(this, "debounceCount", 0); + } + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphDebounceBlock" /* FlowGraphBlockNames.Debounce */; + } +} +RegisterClass("FlowGraphDebounceBlock" /* FlowGraphBlockNames.Debounce */, FlowGraphDebounceBlock); + +const flowGraphDebounceBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphDebounceBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This block flip flops between two outputs. + */ +class FlowGraphFlipFlopBlock extends FlowGraphExecutionBlock { + constructor(config) { + super(config); + this.onOn = this._registerSignalOutput("onOn"); + this.onOff = this._registerSignalOutput("onOff"); + this.value = this.registerDataOutput("value", RichTypeBoolean); + } + _execute(context, _callingSignal) { + let value = context._getExecutionVariable(this, "value", typeof this.config?.startValue === "boolean" ? !this.config.startValue : false); + value = !value; + context._setExecutionVariable(this, "value", value); + this.value.setValue(value, context); + if (value) { + this.onOn._activateSignal(context); + } + else { + this.onOff._activateSignal(context); + } + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphFlipFlopBlock" /* FlowGraphBlockNames.FlipFlop */; + } +} +RegisterClass("FlowGraphFlipFlopBlock" /* FlowGraphBlockNames.FlipFlop */, FlowGraphFlipFlopBlock); + +const flowGraphFlipFlopBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphFlipFlopBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that executes its output flows in sequence. + */ +class FlowGraphSequenceBlock extends FlowGraphExecutionBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + /** + * The output flows. + */ + this.executionSignals = []; + this.setNumberOfOutputSignals(this.config.outputSignalCount); + } + _execute(context) { + for (let i = 0; i < this.executionSignals.length; i++) { + this.executionSignals[i]._activateSignal(context); + } + } + /** + * Sets the block's output flows. Would usually be passed from the constructor but can be changed afterwards. + * @param outputSignalCount the number of output flows + */ + setNumberOfOutputSignals(outputSignalCount = 1) { + // check the size of the outFlow Array, see if it is not larger than needed + while (this.executionSignals.length > outputSignalCount) { + const flow = this.executionSignals.pop(); + if (flow) { + flow.disconnectFromAll(); + this._unregisterSignalOutput(flow.name); + } + } + while (this.executionSignals.length < outputSignalCount) { + this.executionSignals.push(this._registerSignalOutput(`out_${this.executionSignals.length}`)); + } + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphSequenceBlock" /* FlowGraphBlockNames.Sequence */; + } +} +RegisterClass("FlowGraphSequenceBlock" /* FlowGraphBlockNames.Sequence */, FlowGraphSequenceBlock); + +const flowGraphSequenceBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphSequenceBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * The current state of the timer + */ +var TimerState; +(function (TimerState) { + /** + * Timer initialized, not yet started + */ + TimerState[TimerState["INIT"] = 0] = "INIT"; + /** + * Timer started and counting + */ + TimerState[TimerState["STARTED"] = 1] = "STARTED"; + /** + * Timer ended (whether aborted or time reached) + */ + TimerState[TimerState["ENDED"] = 2] = "ENDED"; +})(TimerState || (TimerState = {})); +/** + * A simple version of the timer. Will take options and start the timer immediately after calling it + * + * @param options options with which to initialize this timer + * @returns an observer that can be used to stop the timer + */ +function setAndStartTimer(options) { + let timer = 0; + const startTime = Date.now(); + options.observableParameters = options.observableParameters ?? {}; + const observer = options.contextObservable.add((payload) => { + const now = Date.now(); + timer = now - startTime; + const data = { + startTime, + currentTime: now, + deltaTime: timer, + completeRate: timer / options.timeout, + payload, + }; + options.onTick && options.onTick(data); + if (options.breakCondition && options.breakCondition()) { + options.contextObservable.remove(observer); + options.onAborted && options.onAborted(data); + } + if (timer >= options.timeout) { + options.contextObservable.remove(observer); + options.onEnded && options.onEnded(data); + } + }, options.observableParameters.mask, options.observableParameters.insertFirst, options.observableParameters.scope); + return observer; +} +/** + * An advanced implementation of a timer class + */ +class AdvancedTimer { + /** + * Will construct a new advanced timer based on the options provided. Timer will not start until start() is called. + * @param options construction options for this advanced timer + */ + constructor(options) { + /** + * Will notify each time the timer calculates the remaining time + */ + this.onEachCountObservable = new Observable(); + /** + * Will trigger when the timer was aborted due to the break condition + */ + this.onTimerAbortedObservable = new Observable(); + /** + * Will trigger when the timer ended successfully + */ + this.onTimerEndedObservable = new Observable(); + /** + * Will trigger when the timer state has changed + */ + this.onStateChangedObservable = new Observable(); + this._observer = null; + this._breakOnNextTick = false; + this._tick = (payload) => { + const now = Date.now(); + this._timer = now - this._startTime; + const data = { + startTime: this._startTime, + currentTime: now, + deltaTime: this._timer, + completeRate: this._timer / this._timeToEnd, + payload, + }; + const shouldBreak = this._breakOnNextTick || this._breakCondition(data); + if (shouldBreak || this._timer >= this._timeToEnd) { + this._stop(data, shouldBreak); + } + else { + this.onEachCountObservable.notifyObservers(data); + } + }; + this._setState(0 /* TimerState.INIT */); + this._contextObservable = options.contextObservable; + this._observableParameters = options.observableParameters ?? {}; + this._breakCondition = options.breakCondition ?? (() => false); + this._timeToEnd = options.timeout; + if (options.onEnded) { + this.onTimerEndedObservable.add(options.onEnded); + } + if (options.onTick) { + this.onEachCountObservable.add(options.onTick); + } + if (options.onAborted) { + this.onTimerAbortedObservable.add(options.onAborted); + } + } + /** + * set a breaking condition for this timer. Default is to never break during count + * @param predicate the new break condition. Returns true to break, false otherwise + */ + set breakCondition(predicate) { + this._breakCondition = predicate; + } + /** + * Reset ALL associated observables in this advanced timer + */ + clearObservables() { + this.onEachCountObservable.clear(); + this.onTimerAbortedObservable.clear(); + this.onTimerEndedObservable.clear(); + this.onStateChangedObservable.clear(); + } + /** + * Will start a new iteration of this timer. Only one instance of this timer can run at a time. + * + * @param timeToEnd how much time to measure until timer ended + */ + start(timeToEnd = this._timeToEnd) { + if (this._state === 1 /* TimerState.STARTED */) { + throw new Error("Timer already started. Please stop it before starting again"); + } + this._timeToEnd = timeToEnd; + this._startTime = Date.now(); + this._timer = 0; + this._observer = this._contextObservable.add(this._tick, this._observableParameters.mask, this._observableParameters.insertFirst, this._observableParameters.scope); + this._setState(1 /* TimerState.STARTED */); + } + /** + * Will force a stop on the next tick. + */ + stop() { + if (this._state !== 1 /* TimerState.STARTED */) { + return; + } + this._breakOnNextTick = true; + } + /** + * Dispose this timer, clearing all resources + */ + dispose() { + if (this._observer) { + this._contextObservable.remove(this._observer); + } + this.clearObservables(); + } + _setState(newState) { + this._state = newState; + this.onStateChangedObservable.notifyObservers(this._state); + } + _stop(data, aborted = false) { + this._contextObservable.remove(this._observer); + this._setState(2 /* TimerState.ENDED */); + if (aborted) { + this.onTimerAbortedObservable.notifyObservers(data); + } + else { + this.onTimerEndedObservable.notifyObservers(data); + } + } +} + +/** + * Block that sets a delay in seconds before activating the output signal. + */ +class FlowGraphSetDelayBlock extends FlowGraphAsyncExecutionBlock { + constructor(config) { + super(config); + this.cancel = this._registerSignalInput("cancel"); + this.duration = this.registerDataInput("duration", RichTypeNumber); + this.lastDelayIndex = this.registerDataOutput("lastDelayIndex", RichTypeNumber, -1); + } + _preparePendingTasks(context) { + const duration = this.duration.getValue(context); + if (duration < 0 || isNaN(duration) || !isFinite(duration)) { + return this._reportError(context, "Invalid duration in SetDelay block"); + } + // active delays are global to the context + const activeDelays = context._getGlobalContextVariable("activeDelays", 0); + if (activeDelays >= FlowGraphSetDelayBlock.MaxParallelDelayCount) { + return this._reportError(context, "Max parallel delays reached"); + } + // get the last global delay index + const lastDelayIndex = context._getGlobalContextVariable("lastDelayIndex", -1); + // these are block-specific and not global + const timers = context._getExecutionVariable(this, "pendingDelays", []); + const scene = context.configuration.scene; + const timer = new AdvancedTimer({ + timeout: duration * 1000, // duration is in seconds + contextObservable: scene.onBeforeRenderObservable, + onEnded: () => this._onEnded(timer, context), + }); + timer.start(); + const newIndex = lastDelayIndex + 1; + this.lastDelayIndex.setValue(newIndex, context); + context._setGlobalContextVariable("lastDelayIndex", newIndex); + timers[newIndex] = timer; + context._setExecutionVariable(this, "pendingDelays", timers); + } + _cancelPendingTasks(context) { + const timers = context._getExecutionVariable(this, "pendingDelays", []); + for (const timer of timers) { + timer?.dispose(); + } + context._deleteExecutionVariable(this, "pendingDelays"); + this.lastDelayIndex.setValue(-1, context); + } + _execute(context, callingSignal) { + if (callingSignal === this.cancel) { + this._cancelPendingTasks(context); + return; + } + else { + this._preparePendingTasks(context); + this.out._activateSignal(context); + } + } + getClassName() { + return "FlowGraphSetDelayBlock" /* FlowGraphBlockNames.SetDelay */; + } + _onEnded(timer, context) { + const timers = context._getExecutionVariable(this, "pendingDelays", []); + const index = timers.indexOf(timer); + if (index !== -1) { + timers.splice(index, 1); + } + else { + Logger.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"); + } + context._removePendingBlock(this); + this.done._activateSignal(context); + } +} +/** + * The maximum number of parallel delays that can be set per node. + */ +FlowGraphSetDelayBlock.MaxParallelDelayCount = 100; +RegisterClass("FlowGraphSetDelayBlock" /* FlowGraphBlockNames.SetDelay */, FlowGraphSetDelayBlock); + +const flowGraphSetDelayBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphSetDelayBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This block cancels a delay that was previously scheduled. + */ +class FlowGraphCancelDelayBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor(config) { + super(config); + this.delayIndex = this.registerDataInput("delayIndex", RichTypeNumber); + } + _execute(context, _callingSignal) { + const delayIndex = this.delayIndex.getValue(context); + if (delayIndex <= 0 || isNaN(delayIndex) || !isFinite(delayIndex)) { + return this._reportError(context, "Invalid delay index"); + } + const timers = context._getExecutionVariable(this, "pendingDelays", []); + const timer = timers[delayIndex]; + if (timer) { + timer.dispose(); + // not removing it from the array. Disposing it will clear all of its resources + } + // activate the out output flow + this.out._activateSignal(context); + } + getClassName() { + return "FlowGraphCancelDelayBlock" /* FlowGraphBlockNames.CancelDelay */; + } +} +RegisterClass("FlowGraphCancelDelayBlock" /* FlowGraphBlockNames.CancelDelay */, FlowGraphCancelDelayBlock); + +const flowGraphCancelDelayBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphCancelDelayBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * @experimental + * A block that plays an animation on an animatable object. + */ +class FlowGraphPlayAnimationBlock extends FlowGraphAsyncExecutionBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config, ["animationLoop", "animationEnd", "animationGroupLoop"]); + this.config = config; + this.speed = this.registerDataInput("speed", RichTypeNumber); + this.loop = this.registerDataInput("loop", RichTypeBoolean); + this.from = this.registerDataInput("from", RichTypeNumber, 0); + this.to = this.registerDataInput("to", RichTypeNumber); + this.currentFrame = this.registerDataOutput("currentFrame", RichTypeNumber); + this.currentTime = this.registerDataOutput("currentTime", RichTypeNumber); + this.currentAnimationGroup = this.registerDataOutput("currentAnimationGroup", RichTypeAny); + this.animationGroup = this.registerDataInput("animationGroup", RichTypeAny, config?.animationGroup); + this.animation = this.registerDataInput("animation", RichTypeAny); + this.object = this.registerDataInput("object", RichTypeAny); + } + /** + * @internal + * @param context + */ + _preparePendingTasks(context) { + const ag = this.animationGroup.getValue(context); + const animation = this.animation.getValue(context); + if (!ag && !animation) { + return this._reportError(context, "No animation or animation group provided"); + } + else { + // if an animation group was already created, dispose it and create a new one + const currentAnimationGroup = this.currentAnimationGroup.getValue(context); + if (currentAnimationGroup && currentAnimationGroup !== ag) { + currentAnimationGroup.dispose(); + } + let animationGroupToUse = ag; + // check which animation to use. If no animationGroup was defined and an animation was provided, use the animation + if (animation && !animationGroupToUse) { + const target = this.object.getValue(context); + if (!target) { + return this._reportError(context, "No target object provided"); + } + const animationsArray = Array.isArray(animation) ? animation : [animation]; + const name = animationsArray[0].name; + animationGroupToUse = new AnimationGroup("flowGraphAnimationGroup-" + name + "-" + target.name, context.configuration.scene); + let isInterpolation = false; + const interpolationAnimations = context._getGlobalContextVariable("interpolationAnimations", []); + for (const anim of animationsArray) { + animationGroupToUse.addTargetedAnimation(anim, target); + if (interpolationAnimations.indexOf(anim.uniqueId) !== -1) { + isInterpolation = true; + } + } + if (isInterpolation) { + this._checkInterpolationDuplications(context, animationsArray, target); + } + } + // not accepting 0 + const speed = this.speed.getValue(context) || 1; + const from = this.from.getValue(context) ?? 0; + // not accepting 0 + const to = this.to.getValue(context) || animationGroupToUse.to; + const loop = !isFinite(to) || this.loop.getValue(context); + this.currentAnimationGroup.setValue(animationGroupToUse, context); + const currentlyRunningAnimationGroups = context._getGlobalContextVariable("currentlyRunningAnimationGroups", []); + // check if it already running + if (currentlyRunningAnimationGroups.indexOf(animationGroupToUse.uniqueId) !== -1) { + animationGroupToUse.stop(); + } + try { + animationGroupToUse.start(loop, speed, from, to); + animationGroupToUse.onAnimationGroupEndObservable.add(() => this._onAnimationGroupEnd(context)); + animationGroupToUse.onAnimationEndObservable.add(() => this._eventsSignalOutputs["animationEnd"]._activateSignal(context)); + animationGroupToUse.onAnimationLoopObservable.add(() => this._eventsSignalOutputs["animationLoop"]._activateSignal(context)); + animationGroupToUse.onAnimationGroupLoopObservable.add(() => this._eventsSignalOutputs["animationGroupLoop"]._activateSignal(context)); + currentlyRunningAnimationGroups.push(animationGroupToUse.uniqueId); + context._setGlobalContextVariable("currentlyRunningAnimationGroups", currentlyRunningAnimationGroups); + } + catch (e) { + this._reportError(context, e); + } + } + } + _reportError(context, error) { + super._reportError(context, error); + this.currentFrame.setValue(-1, context); + this.currentTime.setValue(-1, context); + } + /** + * @internal + */ + _executeOnTick(_context) { + const ag = this.currentAnimationGroup.getValue(_context); + if (ag) { + this.currentFrame.setValue(ag.getCurrentFrame(), _context); + this.currentTime.setValue(ag.animatables[0]?.elapsedTime ?? 0, _context); + } + } + _execute(context) { + this._startPendingTasks(context); + } + _onAnimationGroupEnd(context) { + this._removeFromCurrentlyRunning(context, this.currentAnimationGroup.getValue(context)); + this._resetAfterCanceled(context); + this.done._activateSignal(context); + } + /** + * The idea behind this function is to check every running animation group and check if the targeted animations it uses are interpolation animations. + * If they are, we want to see that they don't collide with the current interpolation animations that are starting to play. + * If they do, we want to stop the already-running animation group. + * @internal + */ + _checkInterpolationDuplications(context, animation, target) { + const currentlyRunningAnimationGroups = context._getGlobalContextVariable("currentlyRunningAnimationGroups", []); + for (const uniqueId of currentlyRunningAnimationGroups) { + const ag = context.assetsContext.animationGroups.find((ag) => ag.uniqueId === uniqueId); + if (ag) { + for (const anim of ag.targetedAnimations) { + for (const animToCheck of animation) { + if (anim.animation.targetProperty === animToCheck.targetProperty && anim.target === target) { + this._stopAnimationGroup(context, ag); + } + } + } + } + } + } + _stopAnimationGroup(context, animationGroup) { + // stop, while skipping the on AnimationEndObservable to avoid the "done" signal + animationGroup.stop(true); + animationGroup.dispose(); + this._removeFromCurrentlyRunning(context, animationGroup); + } + _removeFromCurrentlyRunning(context, animationGroup) { + const currentlyRunningAnimationGroups = context._getGlobalContextVariable("currentlyRunningAnimationGroups", []); + const idx = currentlyRunningAnimationGroups.indexOf(animationGroup.uniqueId); + if (idx !== -1) { + currentlyRunningAnimationGroups.splice(idx, 1); + context._setGlobalContextVariable("currentlyRunningAnimationGroups", currentlyRunningAnimationGroups); + } + } + /** + * @internal + * Stop any currently running animations. + */ + _cancelPendingTasks(context) { + const ag = this.currentAnimationGroup.getValue(context); + if (ag) { + this._stopAnimationGroup(context, ag); + } + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */; + } +} +RegisterClass("FlowGraphPlayAnimationBlock" /* FlowGraphBlockNames.PlayAnimation */, FlowGraphPlayAnimationBlock); + +const flowGraphPlayAnimationBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphPlayAnimationBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * @experimental + * Block that stops a running animation + */ +class FlowGraphStopAnimationBlock extends FlowGraphAsyncExecutionBlock { + constructor(config) { + super(config); + this.animationGroup = this.registerDataInput("animationGroup", RichTypeAny); + this.stopAtFrame = this.registerDataInput("stopAtFrame", RichTypeNumber, -1); + } + _preparePendingTasks(context) { + const animationToStopValue = this.animationGroup.getValue(context); + const stopAtFrame = this.stopAtFrame.getValue(context) ?? -1; + // get the context variable + const pendingStopAnimations = context._getGlobalContextVariable("pendingStopAnimations", []); + // add the animation to the list + pendingStopAnimations.push({ uniqueId: animationToStopValue.uniqueId, stopAtFrame }); + // set the global context variable + context._setGlobalContextVariable("pendingStopAnimations", pendingStopAnimations); + } + _cancelPendingTasks(context) { + // remove the animation from the list + const animationToStopValue = this.animationGroup.getValue(context); + const pendingStopAnimations = context._getGlobalContextVariable("pendingStopAnimations", []); + for (let i = 0; i < pendingStopAnimations.length; i++) { + if (pendingStopAnimations[i].uniqueId === animationToStopValue.uniqueId) { + pendingStopAnimations.splice(i, 1); + // set the global context variable + context._setGlobalContextVariable("pendingStopAnimations", pendingStopAnimations); + break; + } + } + } + _execute(context) { + const animationToStopValue = this.animationGroup.getValue(context); + const stopTime = this.stopAtFrame.getValue(context) ?? -1; + // check the values + if (!animationToStopValue) { + Logger.Warn("No animation group provided to stop."); + return this._reportError(context, "No animation group provided to stop."); + } + if (isNaN(stopTime)) { + return this._reportError(context, "Invalid stop time."); + } + if (stopTime > 0) { + this._startPendingTasks(context); + } + else { + this._stopAnimation(animationToStopValue, context); + } + // note that out will not be triggered in case of an error + this.out._activateSignal(context); + } + _executeOnTick(context) { + const animationToStopValue = this.animationGroup.getValue(context); + // check each frame if any animation should be stopped + const pendingStopAnimations = context._getGlobalContextVariable("pendingStopAnimations", []); + for (let i = 0; i < pendingStopAnimations.length; i++) { + // compare the uniqueId to the animation to stop + if (pendingStopAnimations[i].uniqueId === animationToStopValue.uniqueId) { + // check if the current frame is AFTER the stopAtFrame + if (animationToStopValue.getCurrentFrame() >= pendingStopAnimations[i].stopAtFrame) { + // stop the animation + this._stopAnimation(animationToStopValue, context); + // remove the animation from the list + pendingStopAnimations.splice(i, 1); + // set the global context variable + context._setGlobalContextVariable("pendingStopAnimations", pendingStopAnimations); + this.done._activateSignal(context); + context._removePendingBlock(this); + break; + } + } + } + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphStopAnimationBlock" /* FlowGraphBlockNames.StopAnimation */; + } + _stopAnimation(animationGroup, context) { + const currentlyRunning = context._getGlobalContextVariable("currentlyRunningAnimationGroups", []); + const index = currentlyRunning.indexOf(animationGroup.uniqueId); + if (index !== -1) { + animationGroup.stop(); + currentlyRunning.splice(index, 1); + // update the global context variable + context._setGlobalContextVariable("currentlyRunningAnimationGroups", currentlyRunning); + } + } +} +RegisterClass("FlowGraphStopAnimationBlock" /* FlowGraphBlockNames.StopAnimation */, FlowGraphStopAnimationBlock); + +const flowGraphStopAnimationBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphStopAnimationBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * @experimental + * Block that pauses a running animation + */ +class FlowGraphPauseAnimationBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor(config) { + super(config); + this.animationToPause = this.registerDataInput("animationToPause", RichTypeAny); + } + _execute(context) { + const animationToPauseValue = this.animationToPause.getValue(context); + animationToPauseValue.pause(); + this.out._activateSignal(context); + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphPauseAnimationBlock" /* FlowGraphBlockNames.PauseAnimation */; + } +} +RegisterClass("FlowGraphPauseAnimationBlock" /* FlowGraphBlockNames.PauseAnimation */, FlowGraphPauseAnimationBlock); + +const flowGraphPauseAnimationBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphPauseAnimationBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This block is responsible for interpolating between two values. + * The babylon concept used is Animation, and it is the output of this block. + * + * Note that values will be parsed when the in connection is triggered. until then changing the value will not trigger a new interpolation. + * + * Internally this block uses the Animation class. + * + * Note that if the interpolation is already running a signal will be sent to stop the animation group running it. + */ +class FlowGraphInterpolationBlock extends FlowGraphBlock { + constructor(config = {}) { + super(config); + /** + * The keyframes to interpolate between. + * Each keyframe has a duration input and a value input. + */ + this.keyFrames = []; + const type = typeof config?.animationType === "string" + ? getRichTypeByFlowGraphType(config.animationType) + : getRichTypeByAnimationType(config?.animationType ?? 0); + const numberOfKeyFrames = config?.keyFramesCount ?? 1; + const duration = this.registerDataInput(`duration_0`, RichTypeNumber, 0); + const value = this.registerDataInput(`value_0`, type); + this.keyFrames.push({ duration, value }); + for (let i = 1; i < numberOfKeyFrames + 1; i++) { + const duration = this.registerDataInput(`duration_${i}`, RichTypeNumber, i === numberOfKeyFrames ? config.duration : undefined); + const value = this.registerDataInput(`value_${i}`, type); + this.keyFrames.push({ duration, value }); + } + this.initialValue = this.keyFrames[0].value; + this.endValue = this.keyFrames[numberOfKeyFrames].value; + this.easingFunction = this.registerDataInput("easingFunction", RichTypeAny); + this.animation = this.registerDataOutput("animation", RichTypeAny); + this.propertyName = this.registerDataInput("propertyName", RichTypeAny, config?.propertyName); + this.customBuildAnimation = this.registerDataInput("customBuildAnimation", RichTypeAny); + } + _updateOutputs(context) { + const interpolationAnimations = context._getGlobalContextVariable("interpolationAnimations", []); + const propertyName = this.propertyName.getValue(context); + const easingFunction = this.easingFunction.getValue(context); + const animation = this._createAnimation(context, propertyName, easingFunction); + // If an old animation exists, it will be ignored here. + // This is because if the animation is running and they both have the same target, the old will be stopped. + // This doesn't happen here, it happens in the play animation block. + this.animation.setValue(animation, context); + // to make sure no 2 interpolations are running on the same target, we will mark the animation in the context + if (Array.isArray(animation)) { + for (const anim of animation) { + interpolationAnimations.push(anim.uniqueId); + } + } + else { + interpolationAnimations.push(animation.uniqueId); + } + context._setGlobalContextVariable("interpolationAnimations", interpolationAnimations); + } + _createAnimation(context, propertyName, easingFunction) { + const type = this.initialValue.richType; + const keys = []; + // add initial value + const currentValue = this.initialValue.getValue(context) || type.defaultValue; + keys.push({ frame: 0, value: currentValue }); + const numberOfKeyFrames = this.config?.numberOfKeyFrames ?? 1; + for (let i = 1; i < numberOfKeyFrames + 1; i++) { + const duration = this.keyFrames[i].duration?.getValue(context); + let value = this.keyFrames[i].value?.getValue(context); + if (i === numberOfKeyFrames - 1) { + value = value || type.defaultValue; + } + if (duration !== undefined && value) { + // convert duration to frames, based on 60 fps + keys.push({ frame: duration * 60, value }); + } + } + const customBuildAnimation = this.customBuildAnimation.getValue(context); + if (customBuildAnimation) { + return customBuildAnimation()(keys, 60, type.animationType, easingFunction); + } + if (typeof propertyName === "string") { + const animation = Animation.CreateAnimation(propertyName, type.animationType, 60, easingFunction); + animation.setKeys(keys); + return [animation]; + } + else { + const animations = propertyName.map((name) => { + const animation = Animation.CreateAnimation(name, type.animationType, 60, easingFunction); + animation.setKeys(keys); + return animation; + }); + return animations; + } + } + getClassName() { + return "FlowGraphInterpolationBlock" /* FlowGraphBlockNames.ValueInterpolation */; + } +} +RegisterClass("FlowGraphInterpolationBlock" /* FlowGraphBlockNames.ValueInterpolation */, FlowGraphInterpolationBlock); +// #L54P2C + +const flowGraphInterpolationBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphInterpolationBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * The type of the easing function. + */ +var EasingFunctionType; +(function (EasingFunctionType) { + EasingFunctionType[EasingFunctionType["CircleEase"] = 0] = "CircleEase"; + EasingFunctionType[EasingFunctionType["BackEase"] = 1] = "BackEase"; + EasingFunctionType[EasingFunctionType["BounceEase"] = 2] = "BounceEase"; + EasingFunctionType[EasingFunctionType["CubicEase"] = 3] = "CubicEase"; + EasingFunctionType[EasingFunctionType["ElasticEase"] = 4] = "ElasticEase"; + EasingFunctionType[EasingFunctionType["ExponentialEase"] = 5] = "ExponentialEase"; + EasingFunctionType[EasingFunctionType["PowerEase"] = 6] = "PowerEase"; + EasingFunctionType[EasingFunctionType["QuadraticEase"] = 7] = "QuadraticEase"; + EasingFunctionType[EasingFunctionType["QuarticEase"] = 8] = "QuarticEase"; + EasingFunctionType[EasingFunctionType["QuinticEase"] = 9] = "QuinticEase"; + EasingFunctionType[EasingFunctionType["SineEase"] = 10] = "SineEase"; + EasingFunctionType[EasingFunctionType["BezierCurveEase"] = 11] = "BezierCurveEase"; +})(EasingFunctionType || (EasingFunctionType = {})); +/** + * @internal + * Creates an easing function object based on the type and parameters provided. + * This is not tree-shaking friendly, so if you need cubic bezier, use the dedicated bezier block. + * @param type The type of the easing function. + * @param controlPoint1 The first control point for the bezier curve. + * @param controlPoint2 The second control point for the bezier curve. + * @returns The easing function object. + */ +function CreateEasingFunction(type, ...parameters) { + switch (type) { + case 11 /* EasingFunctionType.BezierCurveEase */: + return new BezierCurveEase(...parameters); + case 0 /* EasingFunctionType.CircleEase */: + return new CircleEase(); + case 1 /* EasingFunctionType.BackEase */: + return new BackEase(...parameters); + case 2 /* EasingFunctionType.BounceEase */: + return new BounceEase(...parameters); + case 3 /* EasingFunctionType.CubicEase */: + return new CubicEase(); + case 4 /* EasingFunctionType.ElasticEase */: + return new ElasticEase(...parameters); + case 5 /* EasingFunctionType.ExponentialEase */: + return new ExponentialEase(...parameters); + default: + throw new Error("Easing type not yet implemented"); + } +} +/** + * An easing block that generates an easingFunction object based on the data provided. + */ +class FlowGraphEasingBlock extends FlowGraphBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + /** + * Internal cache of reusable easing functions. + * key is type-mode-properties + */ + this._easingFunctions = {}; + this.type = this.registerDataInput("type", RichTypeAny, 11); + this.mode = this.registerDataInput("mode", RichTypeNumber, 0); + this.parameters = this.registerDataInput("parameters", RichTypeAny, [1, 0, 0, 1]); + this.easingFunction = this.registerDataOutput("easingFunction", RichTypeAny); + } + _updateOutputs(context) { + const type = this.type.getValue(context); + const mode = this.mode.getValue(context); + const parameters = this.parameters.getValue(context); + if (type === undefined || mode === undefined) { + return; + } + const key = `${type}-${mode}-${parameters.join("-")}`; + if (!this._easingFunctions[key]) { + const easing = CreateEasingFunction(type, ...parameters); + easing.setEasingMode(mode); + this._easingFunctions[key] = easing; + } + this.easingFunction.setValue(this._easingFunctions[key], context); + } + getClassName() { + return "FlowGraphEasingBlock" /* FlowGraphBlockNames.Easing */; + } +} +RegisterClass("FlowGraphEasingBlock" /* FlowGraphBlockNames.Easing */, FlowGraphEasingBlock); + +const flowGraphEasingBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + get EasingFunctionType () { return EasingFunctionType; }, + FlowGraphEasingBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * An easing block that generates a BezierCurveEase easingFunction object based on the data provided. + */ +class FlowGraphBezierCurveEasingBlock extends FlowGraphBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + /** + * Internal cache of reusable easing functions. + * key is type-mode-properties + */ + this._easingFunctions = {}; + this.mode = this.registerDataInput("mode", RichTypeNumber, 0); + this.controlPoint1 = this.registerDataInput("controlPoint1", RichTypeVector2); + this.controlPoint2 = this.registerDataInput("controlPoint2", RichTypeVector2); + this.easingFunction = this.registerDataOutput("easingFunction", RichTypeAny); + } + _updateOutputs(context) { + const mode = this.mode.getValue(context); + const controlPoint1 = this.controlPoint1.getValue(context); + const controlPoint2 = this.controlPoint2.getValue(context); + if (mode === undefined) { + return; + } + const key = `${mode}-${controlPoint1.x}-${controlPoint1.y}-${controlPoint2.x}-${controlPoint2.y}`; + if (!this._easingFunctions[key]) { + const easing = new BezierCurveEase(controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y); + easing.setEasingMode(mode); + this._easingFunctions[key] = easing; + } + this.easingFunction.setValue(this._easingFunctions[key], context); + } + getClassName() { + return "FlowGraphBezierCurveEasing" /* FlowGraphBlockNames.BezierCurveEasing */; + } +} +RegisterClass("FlowGraphBezierCurveEasing" /* FlowGraphBlockNames.BezierCurveEasing */, FlowGraphBezierCurveEasingBlock); + +const flowGraphBezierCurveEasingBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphBezierCurveEasingBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Block that returns a value based on a condition. + */ +class FlowGraphConditionalDataBlock extends FlowGraphBlock { + /** + * Creates a new instance of the block + * @param config optional configuration for this block + */ + constructor(config) { + super(config); + this.condition = this.registerDataInput("condition", RichTypeBoolean); + this.onTrue = this.registerDataInput("onTrue", RichTypeAny); + this.onFalse = this.registerDataInput("onFalse", RichTypeAny); + this.output = this.registerDataOutput("output", RichTypeAny); + } + /** + * @internal + */ + _updateOutputs(context) { + // get the value of the condition + const condition = this.condition.getValue(context); + // set the value based on the condition truth-ness. + this.output.setValue(condition ? this.onTrue.getValue(context) : this.onFalse.getValue(context), context); + } + /** + * Gets the class name of this block + * @returns the class name + */ + getClassName() { + return "FlowGraphConditionalBlock" /* FlowGraphBlockNames.Conditional */; + } +} +RegisterClass("FlowGraphConditionalBlock" /* FlowGraphBlockNames.Conditional */, FlowGraphConditionalDataBlock); + +const flowGraphConditionalDataBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphConditionalDataBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that gets the value of a variable. + * Variables are an stored in the context of the flow graph. + */ +class FlowGraphGetVariableBlock extends FlowGraphBlock { + /** + * Construct a FlowGraphGetVariableBlock. + * @param config construction parameters + */ + constructor(config) { + super(config); + this.config = config; + // The output connection has to have the name of the variable. + this.value = this.registerDataOutput("value", RichTypeAny, config.initialValue); + } + /** + * @internal + */ + _updateOutputs(context) { + const variableNameValue = this.config.variable; + if (context.hasVariable(variableNameValue)) { + this.value.setValue(context.getVariable(variableNameValue), context); + } + } + /** + * Serializes this block + * @param serializationObject the object to serialize to + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.config.variable = this.config.variable; + } + getClassName() { + return "FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */; + } +} +RegisterClass("FlowGraphGetVariableBlock" /* FlowGraphBlockNames.GetVariable */, FlowGraphGetVariableBlock); + +const flowGraphGetVariableBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphGetVariableBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This block will set a variable on the context. + */ +class FlowGraphSetVariableBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor(config) { + super(config); + // check if the variable is defined + if (!config.variable && !config.variables) { + throw new Error("FlowGraphSetVariableBlock: variable/variables is not defined"); + } + // check if the variable is an array + if (config.variables && config.variable) { + throw new Error("FlowGraphSetVariableBlock: variable and variables are both defined"); + } + // check if we have either a variable or variables. If we have variables, set the inputs correctly + if (config.variables) { + for (const variable of config.variables) { + this.registerDataInput(variable, RichTypeAny); + } + } + else { + this.registerDataInput("value", RichTypeAny); + } + } + _execute(context, _callingSignal) { + if (this.config?.variables) { + for (const variable of this.config.variables) { + this._saveVariable(context, variable); + } + } + else { + this._saveVariable(context, this.config?.variable, "value"); + } + this.out._activateSignal(context); + } + _saveVariable(context, variableName, inputName) { + // check if there is an animation(group) running on this variable. If there is, stop the animation - a value was force-set. + const currentlyRunningAnimationGroups = context._getGlobalContextVariable("currentlyRunningAnimationGroups", []); + for (const animationUniqueId of currentlyRunningAnimationGroups) { + const animation = context.assetsContext.animationGroups[animationUniqueId]; + // check if there is a target animation that has the target set to be the context + for (const targetAnimation of animation.targetedAnimations) { + if (targetAnimation.target === context) { + // check if the target property is the variable we are setting + if (targetAnimation.target === context) { + // check the variable name + if (targetAnimation.animation.targetProperty === variableName) { + // stop the animation + animation.stop(); + // remove the animation from the currently running animations + const index = currentlyRunningAnimationGroups.indexOf(animationUniqueId); + if (index > -1) { + currentlyRunningAnimationGroups.splice(index, 1); + } + context._setGlobalContextVariable("currentlyRunningAnimationGroups", currentlyRunningAnimationGroups); + break; + } + } + } + } + } + const value = this.getDataInput(inputName || variableName)?.getValue(context); + context.setVariable(variableName, value); + } + getClassName() { + return "FlowGraphSetVariableBlock" /* FlowGraphBlockNames.SetVariable */; + } + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.config.variable = this.config?.variable; + } +} +RegisterClass("FlowGraphSetVariableBlock" /* FlowGraphBlockNames.SetVariable */, FlowGraphSetVariableBlock); + +const flowGraphSetVariableBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphSetVariableBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This blocks transforms a vector from one coordinate system to another. + */ +class FlowGraphTransformCoordinatesSystemBlock extends FlowGraphBlock { + /** + * Creates a new FlowGraphCoordinateTransformBlock + * @param config optional configuration for this block + */ + constructor(config) { + super(config); + this.sourceSystem = this.registerDataInput("sourceSystem", RichTypeAny); + this.destinationSystem = this.registerDataInput("destinationSystem", RichTypeAny); + this.inputCoordinates = this.registerDataInput("inputCoordinates", RichTypeVector3); + this.outputCoordinates = this.registerDataOutput("outputCoordinates", RichTypeVector3); + } + _updateOutputs(_context) { + const sourceSystemValue = this.sourceSystem.getValue(_context); + const destinationSystemValue = this.destinationSystem.getValue(_context); + const inputCoordinatesValue = this.inputCoordinates.getValue(_context); + // takes coordinates from source space to world space + const sourceWorld = sourceSystemValue.getWorldMatrix(); + // takes coordinates from destination space to world space + const destinationWorld = destinationSystemValue.getWorldMatrix(); + const destinationWorldInverse = TmpVectors.Matrix[0].copyFrom(destinationWorld); + // takes coordinates from world space to destination space + destinationWorldInverse.invert(); + const sourceToDestination = TmpVectors.Matrix[1]; + // takes coordinates from source space to world space to destination space + destinationWorldInverse.multiplyToRef(sourceWorld, sourceToDestination); + const outputCoordinatesValue = this.outputCoordinates.getValue(_context); + Vector3.TransformCoordinatesToRef(inputCoordinatesValue, sourceToDestination, outputCoordinatesValue); + } + /** + * Gets the class name of this block + * @returns the class name + */ + getClassName() { + return "FlowGraphTransformCoordinatesSystemBlock" /* FlowGraphBlockNames.TransformCoordinatesSystem */; + } +} +RegisterClass("FlowGraphTransformCoordinatesSystemBlock" /* FlowGraphBlockNames.TransformCoordinatesSystem */, FlowGraphTransformCoordinatesSystemBlock); + +const flowGraphTransformCoordinatesSystemBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphTransformCoordinatesSystemBlock +}, Symbol.toStringTag, { value: 'Module' })); + +const cacheName = "cachedOperationValue"; +const cacheExecIdName = "cachedExecutionId"; +/** + * A block that will cache the result of an operation and deliver it as an output. + */ +class FlowGraphCachedOperationBlock extends FlowGraphBlock { + constructor(outputRichType, config) { + super(config); + this.value = this.registerDataOutput("value", outputRichType); + this.isValid = this.registerDataOutput("isValid", RichTypeBoolean); + } + _updateOutputs(context) { + const cachedExecutionId = context._getExecutionVariable(this, cacheExecIdName, -1); + const cachedValue = context._getExecutionVariable(this, cacheName, null); + if (cachedValue !== undefined && cachedValue !== null && cachedExecutionId === context.executionId) { + this.isValid.setValue(true, context); + this.value.setValue(cachedValue, context); + } + else { + try { + const calculatedValue = this._doOperation(context); + if (calculatedValue === undefined || calculatedValue === null) { + this.isValid.setValue(false, context); + return; + } + context._setExecutionVariable(this, cacheName, calculatedValue); + context._setExecutionVariable(this, cacheExecIdName, context.executionId); + this.value.setValue(calculatedValue, context); + this.isValid.setValue(true, context); + } + catch (e) { + this.isValid.setValue(false, context); + } + } + } +} + +/** + * This block will deliver a property of an asset, based on the property name and an input asset. + * The property name can include dots ("."), which will be interpreted as a path to the property. + * + * For example, with an input of a mesh asset, the property name "position.x" will deliver the x component of the position of the mesh. + * + * Note that it is recommended to input the object on which you are working on (i.e. a material) rather than providing a mesh as object and then getting the material from it. + */ +class FlowGraphGetPropertyBlock extends FlowGraphCachedOperationBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(RichTypeAny, config); + this.config = config; + this.object = this.registerDataInput("object", RichTypeAny, config.object); + this.propertyName = this.registerDataInput("propertyName", RichTypeAny, config.propertyName); + this.customGetFunction = this.registerDataInput("customGetFunction", RichTypeAny); + } + _doOperation(context) { + const getter = this.customGetFunction.getValue(context); + let value; + if (getter) { + value = getter(this.object.getValue(context), this.propertyName.getValue(context), context); + } + else { + const target = this.object.getValue(context); + const propertyName = this.propertyName.getValue(context); + value = target && propertyName ? this._getPropertyValue(target, propertyName) : undefined; + } + return value; + } + _getPropertyValue(target, propertyName) { + const path = propertyName.split("."); + let value = target; + for (const prop of path) { + value = value[prop]; + if (value === undefined) { + return; + } + } + return value; + } + getClassName() { + return "FlowGraphGetPropertyBlock" /* FlowGraphBlockNames.GetProperty */; + } +} +RegisterClass("FlowGraphGetPropertyBlock" /* FlowGraphBlockNames.GetProperty */, FlowGraphGetPropertyBlock); + +const flowGraphGetPropertyBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphGetPropertyBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This block will set a property on a given target asset. + * The property name can include dots ("."), which will be interpreted as a path to the property. + * The target asset is an input and can be changed at any time. + * The value of the property is an input and can be changed at any time. + * + * For example, with an input of a mesh asset, the property name "position.x" will set the x component of the position of the mesh. + * + * Note that it is recommended to input the object on which you are working on (i.e. a material) than providing a mesh and then getting the material from it. + */ +class FlowGraphSetPropertyBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + this.object = this.registerDataInput("object", RichTypeAny, config.target); + this.value = this.registerDataInput("value", RichTypeAny); + this.propertyName = this.registerDataInput("propertyName", RichTypeAny, config.propertyName); + this.customSetFunction = this.registerDataInput("customSetFunction", RichTypeAny); + } + _execute(context, _callingSignal) { + try { + const target = this.object.getValue(context); + const value = this.value.getValue(context); + const setFunction = this.customSetFunction.getValue(context); + if (setFunction) { + setFunction(target, this.propertyName.getValue(context), value, context); + } + else { + this._setPropertyValue(target, this.propertyName.getValue(context), value); + } + } + catch (e) { + this._reportError(context, e); + } + this.out._activateSignal(context); + } + _setPropertyValue(target, propertyName, value) { + const path = propertyName.split("."); + let obj = target; + for (let i = 0; i < path.length - 1; i++) { + const prop = path[i]; + if (obj[prop] === undefined) { + obj[prop] = {}; + } + obj = obj[prop]; + } + obj[path[path.length - 1]] = value; + } + getClassName() { + return "FlowGraphSetPropertyBlock" /* FlowGraphBlockNames.SetProperty */; + } +} +RegisterClass("FlowGraphSetPropertyBlock" /* FlowGraphBlockNames.SetProperty */, FlowGraphSetPropertyBlock); + +const flowGraphSetPropertyBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphSetPropertyBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Block that returns a constant value. + */ +class FlowGraphConstantBlock extends FlowGraphBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + this.output = this.registerDataOutput("output", getRichTypeFromValue(config.value)); + } + _updateOutputs(context) { + this.output.setValue(this.config.value, context); + } + /** + * Gets the class name of this block + * @returns the class name + */ + getClassName() { + return "FlowGraphConstantBlock" /* FlowGraphBlockNames.Constant */; + } + /** + * Serializes this block + * @param serializationObject the object to serialize to + * @param valueSerializeFunction the function to use to serialize the value + */ + serialize(serializationObject = {}, valueSerializeFunction = defaultValueSerializationFunction) { + super.serialize(serializationObject); + valueSerializeFunction("value", this.config.value, serializationObject.config); + } +} +RegisterClass("FlowGraphConstantBlock" /* FlowGraphBlockNames.Constant */, FlowGraphConstantBlock); + +const flowGraphConstantBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphConstantBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that will deliver an asset as an output, based on its type and place in the assets index. + * + * The assets are loaded from the assetsContext defined in the context running this block. The assetsContext is a class extending AbstractClass, + * meaning it can be a Scene, an AssetsContainers, and any other class that extends AbstractClass. + */ +class FlowGraphGetAssetBlock extends FlowGraphBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + this.type = this.registerDataInput("type", RichTypeAny, config.type); + this.value = this.registerDataOutput("value", RichTypeAny); + this.index = this.registerDataInput("index", RichTypeAny, new FlowGraphInteger(getNumericValue(config.index ?? -1))); + } + _updateOutputs(context) { + const type = this.type.getValue(context); + const index = this.index.getValue(context); + // get the asset from the context + const asset = GetFlowGraphAssetWithType(context.assetsContext, type, getNumericValue(index), this.config.useIndexAsUniqueId); + this.value.setValue(asset, context); + } + /** + * Gets the class name of this block + * @returns the class name + */ + getClassName() { + return "FlowGraphGetAssetBlock" /* FlowGraphBlockNames.GetAsset */; + } +} +RegisterClass("FlowGraphGetAssetBlock" /* FlowGraphBlockNames.GetAsset */, FlowGraphGetAssetBlock); + +const flowGraphGetAssetBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphGetAssetBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This block conditionally outputs one of its inputs, based on a condition and a list of cases. + * + * This of it as a passive (data) version of the switch statement in programming languages. + */ +class FlowGraphDataSwitchBlock extends FlowGraphBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + this._inputCases = new Map(); + this.case = this.registerDataInput("case", RichTypeAny, NaN); + this.default = this.registerDataInput("default", RichTypeAny); + this.value = this.registerDataOutput("value", RichTypeAny); + // iterate the set not using for of + (this.config.cases || []).forEach((caseValue) => { + // if treat as integers, make sure not to set it again if it exists + caseValue = getNumericValue(caseValue); + if (this.config.treatCasesAsIntegers) { + caseValue = caseValue | 0; + if (this._inputCases.has(caseValue)) { + return; + } + } + this._inputCases.set(caseValue, this.registerDataInput(`in_${caseValue}`, RichTypeAny)); + }); + } + _updateOutputs(context) { + const selectionValue = this.case.getValue(context); + let outputValue; + if (isNumeric(selectionValue)) { + outputValue = this._getOutputValueForCase(getNumericValue(selectionValue), context); + } + else { + outputValue = this.default.getValue(context); + } + this.value.setValue(outputValue, context); + } + _getOutputValueForCase(caseValue, context) { + return this._inputCases.get(caseValue)?.getValue(context); + } + getClassName() { + return "FlowGraphDataSwitchBlock" /* FlowGraphBlockNames.DataSwitch */; + } +} +RegisterClass("FlowGraphDataSwitchBlock" /* FlowGraphBlockNames.DataSwitch */, FlowGraphDataSwitchBlock); + +const flowGraphDataSwitchBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphDataSwitchBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * The base block for all binary operation blocks. Receives an input of type + * LeftT, one of type RightT, and outputs a value of type ResultT. + */ +class FlowGraphBinaryOperationBlock extends FlowGraphCachedOperationBlock { + constructor(leftRichType, rightRichType, resultRichType, _operation, _className, config) { + super(resultRichType, config); + this._operation = _operation; + this._className = _className; + this.a = this.registerDataInput("a", leftRichType); + this.b = this.registerDataInput("b", rightRichType); + } + /** + * the operation performed by this block + * @param context the graph context + * @returns the result of the operation + */ + _doOperation(context) { + const a = this.a.getValue(context); + const b = this.b.getValue(context); + return this._operation(a, b); + } + /** + * Gets the class name of this block + * @returns the class name + */ + getClassName() { + return this._className; + } +} + +/** + * Block that outputs a value of type ResultT, resulting of an operation with no inputs. + * This block is being extended by some math operations and should not be used directly. + * @internal + */ +class FlowGraphConstantOperationBlock extends FlowGraphCachedOperationBlock { + constructor(richType, _operation, _className, config) { + super(richType, config); + this._operation = _operation; + this._className = _className; + } + /** + * the operation performed by this block + * @param context the graph context + * @returns the result of the operation + */ + _doOperation(context) { + return this._operation(context); + } + /** + * Gets the class name of this block + * @returns the class name + */ + getClassName() { + return this._className; + } +} + +/** + * @internal + * The base block for all unary operation blocks. Receives an input of type InputT, and outputs a value of type ResultT. + */ +class FlowGraphUnaryOperationBlock extends FlowGraphCachedOperationBlock { + constructor(inputRichType, resultRichType, _operation, _className, config) { + super(resultRichType, config); + this._operation = _operation; + this._className = _className; + this.a = this.registerDataInput("a", inputRichType); + } + /** + * the operation performed by this block + * @param context the graph context + * @returns the result of the operation + */ + _doOperation(context) { + return this._operation(this.a.getValue(context)); + } + /** + * Gets the class name of this block + * @returns the class name + */ + getClassName() { + return this._className; + } +} + +/** + * @internal + * The base block for all ternary operation blocks. + */ +class FlowGraphTernaryOperationBlock extends FlowGraphCachedOperationBlock { + constructor(t1Type, t2Type, t3Type, resultRichType, _operation, _className, config) { + super(resultRichType, config); + this._operation = _operation; + this._className = _className; + this.a = this.registerDataInput("a", t1Type); + this.b = this.registerDataInput("b", t2Type); + this.c = this.registerDataInput("c", t3Type); + } + /** + * the operation performed by this block + * @param context the graph context + * @returns the result of the operation + */ + _doOperation(context) { + return this._operation(this.a.getValue(context), this.b.getValue(context), this.c.getValue(context)); + } + /** + * Gets the class name of this block + * @returns the class name + */ + getClassName() { + return this._className; + } +} + +/** + * Polymorphic add block. + */ +class FlowGraphAddBlock extends FlowGraphBinaryOperationBlock { + /** + * Construct a new add block. + * @param config optional configuration + */ + constructor(config) { + super(getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), (a, b) => this._polymorphicAdd(a, b), "FlowGraphAddBlock" /* FlowGraphBlockNames.Add */, config); + } + _polymorphicAdd(a, b) { + const aClassName = _getClassNameOf(a); + const bClassName = _getClassNameOf(b); + if (_areSameVectorClass(aClassName, bClassName) || _areSameMatrixClass(aClassName, bClassName) || _areSameIntegerClass(aClassName, bClassName)) { + // cast to vector3, but any other cast will be fine + return a.add(b); + } + else if (aClassName === "Quaternion" /* FlowGraphTypes.Quaternion */ || bClassName === "Quaternion" /* FlowGraphTypes.Quaternion */) { + // this is a simple add, and should be also supported between Quat and Vector4. Therefore - + return a.add(b); + } + else { + return a + b; + } + } +} +RegisterClass("FlowGraphAddBlock" /* FlowGraphBlockNames.Add */, FlowGraphAddBlock); +/** + * Polymorphic subtract block. + */ +class FlowGraphSubtractBlock extends FlowGraphBinaryOperationBlock { + /** + * Construct a new subtract block. + * @param config optional configuration + */ + constructor(config) { + super(getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), (a, b) => this._polymorphicSubtract(a, b), "FlowGraphSubtractBlock" /* FlowGraphBlockNames.Subtract */, config); + } + _polymorphicSubtract(a, b) { + const aClassName = _getClassNameOf(a); + const bClassName = _getClassNameOf(b); + if (_areSameVectorClass(aClassName, bClassName) || _areSameIntegerClass(aClassName, bClassName) || _areSameMatrixClass(aClassName, bClassName)) { + return a.subtract(b); + } + else if (aClassName === "Quaternion" /* FlowGraphTypes.Quaternion */ || bClassName === "Quaternion" /* FlowGraphTypes.Quaternion */) { + // this is a simple subtract, and should be also supported between Quat and Vector4. Therefore - + return a.subtract(b); + } + else { + return a - b; + } + } +} +RegisterClass("FlowGraphSubtractBlock" /* FlowGraphBlockNames.Subtract */, FlowGraphSubtractBlock); +/** + * Polymorphic multiply block. + * In case of matrix, it is configurable whether the multiplication is done per component. + */ +class FlowGraphMultiplyBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), (a, b) => this._polymorphicMultiply(a, b), "FlowGraphMultiplyBlock" /* FlowGraphBlockNames.Multiply */, config); + } + _polymorphicMultiply(a, b) { + const aClassName = _getClassNameOf(a); + const bClassName = _getClassNameOf(b); + if (_areSameVectorClass(aClassName, bClassName) || _areSameIntegerClass(aClassName, bClassName)) { + return a.multiply(b); + } + else if (aClassName === "Quaternion" /* FlowGraphTypes.Quaternion */ || bClassName === "Quaternion" /* FlowGraphTypes.Quaternion */) { + // this is a simple multiply (per component!), and should be also supported between Quat and Vector4. Therefore - + const aClone = a.clone(); + aClone.x *= b.x; + aClone.y *= b.y; + aClone.z *= b.z; + aClone.w *= b.w; + return aClone; + } + else if (_areSameMatrixClass(aClassName, bClassName)) { + if (this.config?.useMatrixPerComponent) { + // this is the definition of multiplication of glTF interactivity + // get a's m as array, and multiply each component with b's m + const aM = a.m; + for (let i = 0; i < aM.length; i++) { + aM[i] *= b.m[i]; + } + if (aClassName === "Matrix2D" /* FlowGraphTypes.Matrix2D */) { + return new FlowGraphMatrix2D(aM); + } + else if (aClassName === "Matrix3D" /* FlowGraphTypes.Matrix3D */) { + return new FlowGraphMatrix3D(aM); + } + else { + return Matrix.FromArray(aM); + } + } + else { + a = a; + b = b; + return b.multiply(a); + } + } + else { + return a * b; + } + } +} +RegisterClass("FlowGraphMultiplyBlock" /* FlowGraphBlockNames.Multiply */, FlowGraphMultiplyBlock); +/** + * Polymorphic division block. + */ +class FlowGraphDivideBlock extends FlowGraphBinaryOperationBlock { + /** + * Construct a new divide block. + * @param config - Optional configuration + */ + constructor(config) { + super(getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), (a, b) => this._polymorphicDivide(a, b), "FlowGraphDivideBlock" /* FlowGraphBlockNames.Divide */, config); + } + _polymorphicDivide(a, b) { + const aClassName = _getClassNameOf(a); + const bClassName = _getClassNameOf(b); + if (_areSameVectorClass(aClassName, bClassName) || _areSameIntegerClass(aClassName, bClassName)) { + // cast to vector3, but it can be casted to any vector type + return a.divide(b); + } + else if (aClassName === "Quaternion" /* FlowGraphTypes.Quaternion */ || bClassName === "Quaternion" /* FlowGraphTypes.Quaternion */) { + // this is a simple division (per component!), and should be also supported between Quat and Vector4. Therefore - + const aClone = a.clone(); + aClone.x /= b.x; + aClone.y /= b.y; + aClone.z /= b.z; + aClone.w /= b.w; + return aClone; + } + else if (_areSameMatrixClass(aClassName, bClassName)) { + if (this.config?.useMatrixPerComponent) { + // get a's m as array, and divide each component with b's m + const aM = a.m; + for (let i = 0; i < aM.length; i++) { + aM[i] /= b.m[i]; + } + if (aClassName === "Matrix2D" /* FlowGraphTypes.Matrix2D */) { + return new FlowGraphMatrix2D(aM); + } + else if (aClassName === "Matrix3D" /* FlowGraphTypes.Matrix3D */) { + return new FlowGraphMatrix3D(aM); + } + else { + return Matrix.FromArray(aM); + } + } + else { + a = a; + b = b; + return a.divide(b); + } + } + else { + return a / b; + } + } +} +RegisterClass("FlowGraphDivideBlock" /* FlowGraphBlockNames.Divide */, FlowGraphDivideBlock); +/** + * Random number between min and max (defaults to 0 to 1) + * + * This node will cache the result for he same node reference. i.e., a Math.eq that references the SAME random node will always return true. + */ +class FlowGraphRandomBlock extends FlowGraphConstantOperationBlock { + /** + * Construct a new random block. + * @param config optional configuration + */ + constructor(config) { + super(RichTypeNumber, (context) => this._random(context), "FlowGraphRandomBlock" /* FlowGraphBlockNames.Random */, config); + this.min = this.registerDataInput("min", RichTypeNumber, config?.min ?? 0); + this.max = this.registerDataInput("max", RichTypeNumber, config?.max ?? 1); + if (config?.seed) { + this._seed = config.seed; + } + } + _isSeed(seed = this._seed) { + return seed !== undefined; + } + _getRandomValue() { + if (this._isSeed(this._seed)) { + // compute seed-based random number, deterministic randomness! + const x = Math.sin(this._seed++) * 10000; + return x - Math.floor(x); + } + return Math.random(); + } + _random(context) { + const min = this.min.getValue(context); + const max = this.max.getValue(context); + return this._getRandomValue() * (max - min) + min; + } +} +RegisterClass("FlowGraphRandomBlock" /* FlowGraphBlockNames.Random */, FlowGraphRandomBlock); +/** + * E constant. + */ +class FlowGraphEBlock extends FlowGraphConstantOperationBlock { + constructor(config) { + super(RichTypeNumber, () => Math.E, "FlowGraphEBlock" /* FlowGraphBlockNames.E */, config); + } +} +RegisterClass("FlowGraphEBlock" /* FlowGraphBlockNames.E */, FlowGraphEBlock); +/** + * Pi constant. + */ +class FlowGraphPiBlock extends FlowGraphConstantOperationBlock { + constructor(config) { + super(RichTypeNumber, () => Math.PI, "FlowGraphPIBlock" /* FlowGraphBlockNames.PI */, config); + } +} +RegisterClass("FlowGraphPIBlock" /* FlowGraphBlockNames.PI */, FlowGraphPiBlock); +/** + * Positive inf constant. + */ +class FlowGraphInfBlock extends FlowGraphConstantOperationBlock { + constructor(config) { + super(RichTypeNumber, () => Number.POSITIVE_INFINITY, "FlowGraphInfBlock" /* FlowGraphBlockNames.Inf */, config); + } +} +RegisterClass("FlowGraphInfBlock" /* FlowGraphBlockNames.Inf */, FlowGraphInfBlock); +/** + * NaN constant. + */ +class FlowGraphNaNBlock extends FlowGraphConstantOperationBlock { + constructor(config) { + super(RichTypeNumber, () => Number.NaN, "FlowGraphNaNBlock" /* FlowGraphBlockNames.NaN */, config); + } +} +RegisterClass("FlowGraphNaNBlock" /* FlowGraphBlockNames.NaN */, FlowGraphNaNBlock); +function _componentWiseUnaryOperation(a, op) { + const aClassName = _getClassNameOf(a); + switch (aClassName) { + case "FlowGraphInteger": + a = a; + return new FlowGraphInteger(op(a.value)); + case "Vector2" /* FlowGraphTypes.Vector2 */: + a = a; + return new Vector2(op(a.x), op(a.y)); + case "Vector3" /* FlowGraphTypes.Vector3 */: + a = a; + return new Vector3(op(a.x), op(a.y), op(a.z)); + case "Vector4" /* FlowGraphTypes.Vector4 */: + a = a; + return new Vector4(op(a.x), op(a.y), op(a.z), op(a.w)); + case "Quaternion" /* FlowGraphTypes.Quaternion */: + a = a; + return new Quaternion(op(a.x), op(a.y), op(a.z), op(a.w)); + case "Matrix" /* FlowGraphTypes.Matrix */: + a = a; + return Matrix.FromArray(a.m.map(op)); + case "Matrix2D" /* FlowGraphTypes.Matrix2D */: + a = a; + // reason for not using .map is performance + return new FlowGraphMatrix2D(a.m.map(op)); + case "Matrix3D" /* FlowGraphTypes.Matrix3D */: + a = a; + return new FlowGraphMatrix3D(a.m.map(op)); + default: + a = a; + return op(a); + } +} +/** + * Absolute value block. + */ +class FlowGraphAbsBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicAbs(a), "FlowGraphAbsBlock" /* FlowGraphBlockNames.Abs */, config); + } + _polymorphicAbs(a) { + return _componentWiseUnaryOperation(a, Math.abs); + } +} +RegisterClass("FlowGraphAbsBlock" /* FlowGraphBlockNames.Abs */, FlowGraphAbsBlock); +/** + * Sign block. + */ +class FlowGraphSignBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicSign(a), "FlowGraphSignBlock" /* FlowGraphBlockNames.Sign */, config); + } + _polymorphicSign(a) { + return _componentWiseUnaryOperation(a, Math.sign); + } +} +RegisterClass("FlowGraphSignBlock" /* FlowGraphBlockNames.Sign */, FlowGraphSignBlock); +/** + * Truncation block. + */ +class FlowGraphTruncBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicTrunc(a), "FlowGraphTruncBlock" /* FlowGraphBlockNames.Trunc */, config); + } + _polymorphicTrunc(a) { + return _componentWiseUnaryOperation(a, Math.trunc); + } +} +RegisterClass("FlowGraphTruncBlock" /* FlowGraphBlockNames.Trunc */, FlowGraphTruncBlock); +/** + * Floor block. + */ +class FlowGraphFloorBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicFloor(a), "FlowGraphFloorBlock" /* FlowGraphBlockNames.Floor */, config); + } + _polymorphicFloor(a) { + return _componentWiseUnaryOperation(a, Math.floor); + } +} +RegisterClass("FlowGraphFloorBlock" /* FlowGraphBlockNames.Floor */, FlowGraphFloorBlock); +/** + * Ceiling block. + */ +class FlowGraphCeilBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicCeiling(a), "FlowGraphCeilBlock" /* FlowGraphBlockNames.Ceil */, config); + } + _polymorphicCeiling(a) { + return _componentWiseUnaryOperation(a, Math.ceil); + } +} +RegisterClass("FlowGraphCeilBlock" /* FlowGraphBlockNames.Ceil */, FlowGraphCeilBlock); +/** + * Round block. + */ +class FlowGraphRoundBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicRound(a), "FlowGraphRoundBlock" /* FlowGraphBlockNames.Round */, config); + } + _polymorphicRound(a) { + return _componentWiseUnaryOperation(a, (a) => (a < 0 && this.config?.roundHalfAwayFromZero ? -Math.round(-a) : Math.round(a))); + } +} +RegisterClass("FlowGraphRoundBlock" /* FlowGraphBlockNames.Round */, FlowGraphRoundBlock); +/** + * A block that returns the fractional part of a number. + */ +class FlowGraphFractionBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicFraction(a), "FlowGraphFractBlock" /* FlowGraphBlockNames.Fraction */, config); + } + _polymorphicFraction(a) { + return _componentWiseUnaryOperation(a, (a) => a - Math.floor(a)); + } +} +RegisterClass("FlowGraphFractBlock" /* FlowGraphBlockNames.Fraction */, FlowGraphFractionBlock); +/** + * Negation block. + */ +class FlowGraphNegationBlock extends FlowGraphUnaryOperationBlock { + /** + * construct a new negation block. + * @param config optional configuration + */ + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicNeg(a), "FlowGraphNegationBlock" /* FlowGraphBlockNames.Negation */, config); + } + _polymorphicNeg(a) { + return _componentWiseUnaryOperation(a, (a) => -a); + } +} +RegisterClass("FlowGraphNegationBlock" /* FlowGraphBlockNames.Negation */, FlowGraphNegationBlock); +function _componentWiseBinaryOperation(a, b, op) { + const aClassName = _getClassNameOf(a); + switch (aClassName) { + case "FlowGraphInteger": + a = a; + b = b; + return new FlowGraphInteger(op(a.value, b.value)); + case "Vector2" /* FlowGraphTypes.Vector2 */: + a = a; + b = b; + return new Vector2(op(a.x, b.x), op(a.y, b.y)); + case "Vector3" /* FlowGraphTypes.Vector3 */: + a = a; + b = b; + return new Vector3(op(a.x, b.x), op(a.y, b.y), op(a.z, b.z)); + case "Vector4" /* FlowGraphTypes.Vector4 */: + a = a; + b = b; + return new Vector4(op(a.x, b.x), op(a.y, b.y), op(a.z, b.z), op(a.w, b.w)); + case "Quaternion" /* FlowGraphTypes.Quaternion */: + a = a; + b = b; + return new Quaternion(op(a.x, b.x), op(a.y, b.y), op(a.z, b.z), op(a.w, b.w)); + case "Matrix" /* FlowGraphTypes.Matrix */: + a = a; + return Matrix.FromArray(a.m.map((v, i) => op(v, b.m[i]))); + case "Matrix2D" /* FlowGraphTypes.Matrix2D */: + a = a; + return new FlowGraphMatrix2D(a.m.map((v, i) => op(v, b.m[i]))); + case "Matrix3D" /* FlowGraphTypes.Matrix3D */: + a = a; + return new FlowGraphMatrix3D(a.m.map((v, i) => op(v, b.m[i]))); + default: + return op(a, b); + } +} +/** + * Remainder block. + */ +class FlowGraphModuloBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeAny, (a, b) => this._polymorphicRemainder(a, b), "FlowGraphModuloBlock" /* FlowGraphBlockNames.Modulo */, config); + } + _polymorphicRemainder(a, b) { + return _componentWiseBinaryOperation(a, b, (a, b) => a % b); + } +} +RegisterClass("FlowGraphModuloBlock" /* FlowGraphBlockNames.Modulo */, FlowGraphModuloBlock); +/** + * Min block. + */ +class FlowGraphMinBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeAny, (a, b) => this._polymorphicMin(a, b), "FlowGraphMinBlock" /* FlowGraphBlockNames.Min */, config); + } + _polymorphicMin(a, b) { + return _componentWiseBinaryOperation(a, b, Math.min); + } +} +RegisterClass("FlowGraphMinBlock" /* FlowGraphBlockNames.Min */, FlowGraphMinBlock); +/** + * Max block + */ +class FlowGraphMaxBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeAny, (a, b) => this._polymorphicMax(a, b), "FlowGraphMaxBlock" /* FlowGraphBlockNames.Max */, config); + } + _polymorphicMax(a, b) { + return _componentWiseBinaryOperation(a, b, Math.max); + } +} +RegisterClass("FlowGraphMaxBlock" /* FlowGraphBlockNames.Max */, FlowGraphMaxBlock); +function _clamp(a, b, c) { + return Math.min(Math.max(a, Math.min(b, c)), Math.max(b, c)); +} +function _componentWiseTernaryOperation(a, b, c, op) { + const aClassName = _getClassNameOf(a); + switch (aClassName) { + case "FlowGraphInteger": + a = a; + b = b; + c = c; + return new FlowGraphInteger(op(a.value, b.value, c.value)); + case "Vector2" /* FlowGraphTypes.Vector2 */: + a = a; + b = b; + c = c; + return new Vector2(op(a.x, b.x, c.x), op(a.y, b.y, c.y)); + case "Vector3" /* FlowGraphTypes.Vector3 */: + a = a; + b = b; + c = c; + return new Vector3(op(a.x, b.x, c.x), op(a.y, b.y, c.y), op(a.z, b.z, c.z)); + case "Vector4" /* FlowGraphTypes.Vector4 */: + a = a; + b = b; + c = c; + return new Vector4(op(a.x, b.x, c.x), op(a.y, b.y, c.y), op(a.z, b.z, c.z), op(a.w, b.w, c.w)); + case "Quaternion" /* FlowGraphTypes.Quaternion */: + a = a; + b = b; + c = c; + return new Quaternion(op(a.x, b.x, c.x), op(a.y, b.y, c.y), op(a.z, b.z, c.z), op(a.w, b.w, c.w)); + case "Matrix" /* FlowGraphTypes.Matrix */: + return Matrix.FromArray(a.m.map((v, i) => op(v, b.m[i], c.m[i]))); + case "Matrix2D" /* FlowGraphTypes.Matrix2D */: + return new FlowGraphMatrix2D(a.m.map((v, i) => op(v, b.m[i], c.m[i]))); + case "Matrix3D" /* FlowGraphTypes.Matrix3D */: + return new FlowGraphMatrix3D(a.m.map((v, i) => op(v, b.m[i], c.m[i]))); + default: + return op(a, b, c); + } +} +/** + * Clamp block. + */ +class FlowGraphClampBlock extends FlowGraphTernaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeAny, RichTypeAny, (a, b, c) => this._polymorphicClamp(a, b, c), "FlowGraphClampBlock" /* FlowGraphBlockNames.Clamp */, config); + } + _polymorphicClamp(a, b, c) { + return _componentWiseTernaryOperation(a, b, c, _clamp); + } +} +RegisterClass("FlowGraphClampBlock" /* FlowGraphBlockNames.Clamp */, FlowGraphClampBlock); +function _saturate(a) { + return Math.min(Math.max(a, 0), 1); +} +/** + * Saturate block. + */ +class FlowGraphSaturateBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicSaturate(a), "FlowGraphSaturateBlock" /* FlowGraphBlockNames.Saturate */, config); + } + _polymorphicSaturate(a) { + return _componentWiseUnaryOperation(a, _saturate); + } +} +RegisterClass("FlowGraphSaturateBlock" /* FlowGraphBlockNames.Saturate */, FlowGraphSaturateBlock); +function _interpolate(a, b, c) { + return (1 - c) * a + c * b; +} +/** + * Interpolate block. + */ +class FlowGraphMathInterpolationBlock extends FlowGraphTernaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeAny, RichTypeAny, (a, b, c) => this._polymorphicInterpolate(a, b, c), "FlowGraphMathInterpolationBlock" /* FlowGraphBlockNames.MathInterpolation */, config); + } + _polymorphicInterpolate(a, b, c) { + return _componentWiseTernaryOperation(a, b, c, _interpolate); + } +} +RegisterClass("FlowGraphMathInterpolationBlock" /* FlowGraphBlockNames.MathInterpolation */, FlowGraphMathInterpolationBlock); +/** + * Equals block. + */ +class FlowGraphEqualityBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeBoolean, (a, b) => this._polymorphicEq(a, b), "FlowGraphEqualityBlock" /* FlowGraphBlockNames.Equality */, config); + } + _polymorphicEq(a, b) { + const aClassName = _getClassNameOf(a); + const bClassName = _getClassNameOf(b); + if (_areSameVectorClass(aClassName, bClassName) || _areSameMatrixClass(aClassName, bClassName) || _areSameIntegerClass(aClassName, bClassName)) { + return a.equals(b); + } + else { + return a === b; + } + } +} +RegisterClass("FlowGraphEqualityBlock" /* FlowGraphBlockNames.Equality */, FlowGraphEqualityBlock); +function _comparisonOperators(a, b, op) { + if (isNumeric(a) && isNumeric(b)) { + return op(getNumericValue(a), getNumericValue(b)); + } + else { + throw new Error(`Cannot compare ${a} and ${b}`); + } +} +/** + * Less than block. + */ +class FlowGraphLessThanBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeBoolean, (a, b) => this._polymorphicLessThan(a, b), "FlowGraphLessThanBlock" /* FlowGraphBlockNames.LessThan */, config); + } + _polymorphicLessThan(a, b) { + return _comparisonOperators(a, b, (a, b) => a < b); + } +} +RegisterClass("FlowGraphLessThanBlock" /* FlowGraphBlockNames.LessThan */, FlowGraphLessThanBlock); +/** + * Less than or equal block. + */ +class FlowGraphLessThanOrEqualBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeBoolean, (a, b) => this._polymorphicLessThanOrEqual(a, b), "FlowGraphLessThanOrEqualBlock" /* FlowGraphBlockNames.LessThanOrEqual */, config); + } + _polymorphicLessThanOrEqual(a, b) { + return _comparisonOperators(a, b, (a, b) => a <= b); + } +} +RegisterClass("FlowGraphLessThanOrEqualBlock" /* FlowGraphBlockNames.LessThanOrEqual */, FlowGraphLessThanOrEqualBlock); +/** + * Greater than block. + */ +class FlowGraphGreaterThanBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeBoolean, (a, b) => this._polymorphicGreaterThan(a, b), "FlowGraphGreaterThanBlock" /* FlowGraphBlockNames.GreaterThan */, config); + } + _polymorphicGreaterThan(a, b) { + return _comparisonOperators(a, b, (a, b) => a > b); + } +} +RegisterClass("FlowGraphGreaterThanBlock" /* FlowGraphBlockNames.GreaterThan */, FlowGraphGreaterThanBlock); +/** + * Greater than or equal block. + */ +class FlowGraphGreaterThanOrEqualBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeBoolean, (a, b) => this._polymorphicGreaterThanOrEqual(a, b), "FlowGraphGreaterThanOrEqualBlock" /* FlowGraphBlockNames.GreaterThanOrEqual */, config); + } + _polymorphicGreaterThanOrEqual(a, b) { + return _comparisonOperators(a, b, (a, b) => a >= b); + } +} +RegisterClass("FlowGraphGreaterThanOrEqualBlock" /* FlowGraphBlockNames.GreaterThanOrEqual */, FlowGraphGreaterThanOrEqualBlock); +/** + * Is NaN block. + */ +class FlowGraphIsNanBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeBoolean, (a) => this._polymorphicIsNan(a), "FlowGraphIsNaNBlock" /* FlowGraphBlockNames.IsNaN */, config); + } + _polymorphicIsNan(a) { + if (isNumeric(a)) { + return isNaN(getNumericValue(a)); + } + else { + throw new Error(`Cannot get NaN of ${a}`); + } + } +} +RegisterClass("FlowGraphIsNaNBlock" /* FlowGraphBlockNames.IsNaN */, FlowGraphIsNanBlock); +/** + * Is Inf block. + */ +class FlowGraphIsInfinityBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeBoolean, (a) => this._polymorphicIsInf(a), "FlowGraphIsInfBlock" /* FlowGraphBlockNames.IsInfinity */, config); + } + _polymorphicIsInf(a) { + if (isNumeric(a)) { + return !isFinite(getNumericValue(a)); + } + else { + throw new Error(`Cannot get isInf of ${a}`); + } + } +} +RegisterClass("FlowGraphIsInfBlock" /* FlowGraphBlockNames.IsInfinity */, FlowGraphIsInfinityBlock); +/** + * Convert degrees to radians block. + */ +class FlowGraphDegToRadBlock extends FlowGraphUnaryOperationBlock { + /** + * Constructs a new instance of the flow graph math block. + * @param config - Optional configuration for the flow graph block. + */ + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicDegToRad(a), "FlowGraphDegToRadBlock" /* FlowGraphBlockNames.DegToRad */, config); + } + _degToRad(a) { + return (a * Math.PI) / 180; + } + _polymorphicDegToRad(a) { + return _componentWiseUnaryOperation(a, this._degToRad); + } +} +RegisterClass("FlowGraphDegToRadBlock" /* FlowGraphBlockNames.DegToRad */, FlowGraphDegToRadBlock); +/** + * Convert radians to degrees block. + */ +class FlowGraphRadToDegBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicRadToDeg(a), "FlowGraphRadToDegBlock" /* FlowGraphBlockNames.RadToDeg */, config); + } + _radToDeg(a) { + return (a * 180) / Math.PI; + } + _polymorphicRadToDeg(a) { + return _componentWiseUnaryOperation(a, this._radToDeg); + } +} +RegisterClass("FlowGraphRadToDegBlock" /* FlowGraphBlockNames.RadToDeg */, FlowGraphRadToDegBlock); +/** + * Sin block. + */ +class FlowGraphSinBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicSin(a), "FlowGraphSinBlock" /* FlowGraphBlockNames.Sin */, config); + } + _polymorphicSin(a) { + return _componentWiseUnaryOperation(a, Math.sin); + } +} +/** + * Cos block. + */ +class FlowGraphCosBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicCos(a), "FlowGraphCosBlock" /* FlowGraphBlockNames.Cos */, config); + } + _polymorphicCos(a) { + return _componentWiseUnaryOperation(a, Math.cos); + } +} +/** + * Tan block. + */ +class FlowGraphTanBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicTan(a), "FlowGraphTanBlock" /* FlowGraphBlockNames.Tan */, config); + } + _polymorphicTan(a) { + return _componentWiseUnaryOperation(a, Math.tan); + } +} +/** + * Arcsin block. + */ +class FlowGraphAsinBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicAsin(a), "FlowGraphASinBlock" /* FlowGraphBlockNames.Asin */, config); + } + _polymorphicAsin(a) { + return _componentWiseUnaryOperation(a, Math.asin); + } +} +RegisterClass("FlowGraphASinBlock" /* FlowGraphBlockNames.Asin */, FlowGraphAsinBlock); +/** + * Arccos block. + */ +class FlowGraphAcosBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicAcos(a), "FlowGraphACosBlock" /* FlowGraphBlockNames.Acos */, config); + } + _polymorphicAcos(a) { + return _componentWiseUnaryOperation(a, Math.acos); + } +} +RegisterClass("FlowGraphACosBlock" /* FlowGraphBlockNames.Acos */, FlowGraphAcosBlock); +/** + * Arctan block. + */ +class FlowGraphAtanBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicAtan(a), "FlowGraphATanBlock" /* FlowGraphBlockNames.Atan */, config); + } + _polymorphicAtan(a) { + return _componentWiseUnaryOperation(a, Math.atan); + } +} +RegisterClass("FlowGraphATanBlock" /* FlowGraphBlockNames.Atan */, FlowGraphAtanBlock); +/** + * Arctan2 block. + */ +class FlowGraphAtan2Block extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeAny, (a, b) => this._polymorphicAtan2(a, b), "FlowGraphATan2Block" /* FlowGraphBlockNames.Atan2 */, config); + } + _polymorphicAtan2(a, b) { + return _componentWiseBinaryOperation(a, b, Math.atan2); + } +} +RegisterClass("FlowGraphATan2Block" /* FlowGraphBlockNames.Atan2 */, FlowGraphAtan2Block); +/** + * Hyperbolic sin block. + */ +class FlowGraphSinhBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicSinh(a), "FlowGraphSinhBlock" /* FlowGraphBlockNames.Sinh */, config); + } + _polymorphicSinh(a) { + return _componentWiseUnaryOperation(a, Math.sinh); + } +} +RegisterClass("FlowGraphSinhBlock" /* FlowGraphBlockNames.Sinh */, FlowGraphSinhBlock); +/** + * Hyperbolic cos block. + */ +class FlowGraphCoshBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicCosh(a), "FlowGraphCoshBlock" /* FlowGraphBlockNames.Cosh */, config); + } + _polymorphicCosh(a) { + return _componentWiseUnaryOperation(a, Math.cosh); + } +} +RegisterClass("FlowGraphCoshBlock" /* FlowGraphBlockNames.Cosh */, FlowGraphCoshBlock); +/** + * Hyperbolic tan block. + */ +class FlowGraphTanhBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicTanh(a), "FlowGraphTanhBlock" /* FlowGraphBlockNames.Tanh */, config); + } + _polymorphicTanh(a) { + return _componentWiseUnaryOperation(a, Math.tanh); + } +} +RegisterClass("FlowGraphTanhBlock" /* FlowGraphBlockNames.Tanh */, FlowGraphTanhBlock); +/** + * Hyperbolic arcsin block. + */ +class FlowGraphAsinhBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicAsinh(a), "FlowGraphASinhBlock" /* FlowGraphBlockNames.Asinh */, config); + } + _polymorphicAsinh(a) { + return _componentWiseUnaryOperation(a, Math.asinh); + } +} +RegisterClass("FlowGraphASinhBlock" /* FlowGraphBlockNames.Asinh */, FlowGraphAsinhBlock); +/** + * Hyperbolic arccos block. + */ +class FlowGraphAcoshBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicAcosh(a), "FlowGraphACoshBlock" /* FlowGraphBlockNames.Acosh */, config); + } + _polymorphicAcosh(a) { + return _componentWiseUnaryOperation(a, Math.acosh); + } +} +RegisterClass("FlowGraphACoshBlock" /* FlowGraphBlockNames.Acosh */, FlowGraphAcoshBlock); +/** + * Hyperbolic arctan block. + */ +class FlowGraphAtanhBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicAtanh(a), "FlowGraphATanhBlock" /* FlowGraphBlockNames.Atanh */, config); + } + _polymorphicAtanh(a) { + return _componentWiseUnaryOperation(a, Math.atanh); + } +} +RegisterClass("FlowGraphATanhBlock" /* FlowGraphBlockNames.Atanh */, FlowGraphAtanhBlock); +/** + * Exponential block. + */ +class FlowGraphExpBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicExp(a), "FlowGraphExponentialBlock" /* FlowGraphBlockNames.Exponential */, config); + } + _polymorphicExp(a) { + return _componentWiseUnaryOperation(a, Math.exp); + } +} +RegisterClass("FlowGraphExponentialBlock" /* FlowGraphBlockNames.Exponential */, FlowGraphExpBlock); +/** + * Logarithm block. + */ +class FlowGraphLogBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicLog(a), "FlowGraphLogBlock" /* FlowGraphBlockNames.Log */, config); + } + _polymorphicLog(a) { + return _componentWiseUnaryOperation(a, Math.log); + } +} +RegisterClass("FlowGraphLogBlock" /* FlowGraphBlockNames.Log */, FlowGraphLogBlock); +/** + * Base 2 logarithm block. + */ +class FlowGraphLog2Block extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicLog2(a), "FlowGraphLog2Block" /* FlowGraphBlockNames.Log2 */, config); + } + _polymorphicLog2(a) { + return _componentWiseUnaryOperation(a, Math.log2); + } +} +RegisterClass("FlowGraphLog2Block" /* FlowGraphBlockNames.Log2 */, FlowGraphLog2Block); +/** + * Base 10 logarithm block. + */ +class FlowGraphLog10Block extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicLog10(a), "FlowGraphLog10Block" /* FlowGraphBlockNames.Log10 */, config); + } + _polymorphicLog10(a) { + return _componentWiseUnaryOperation(a, Math.log10); + } +} +RegisterClass("FlowGraphLog10Block" /* FlowGraphBlockNames.Log10 */, FlowGraphLog10Block); +/** + * Square root block. + */ +class FlowGraphSquareRootBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicSqrt(a), "FlowGraphSquareRootBlock" /* FlowGraphBlockNames.SquareRoot */, config); + } + _polymorphicSqrt(a) { + return _componentWiseUnaryOperation(a, Math.sqrt); + } +} +RegisterClass("FlowGraphSquareRootBlock" /* FlowGraphBlockNames.SquareRoot */, FlowGraphSquareRootBlock); +/** + * Cube root block. + */ +class FlowGraphCubeRootBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicCubeRoot(a), "FlowGraphCubeRootBlock" /* FlowGraphBlockNames.CubeRoot */, config); + } + _polymorphicCubeRoot(a) { + return _componentWiseUnaryOperation(a, Math.cbrt); + } +} +RegisterClass("FlowGraphCubeRootBlock" /* FlowGraphBlockNames.CubeRoot */, FlowGraphCubeRootBlock); +/** + * Power block. + */ +class FlowGraphPowerBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, RichTypeNumber, (a, b) => this._polymorphicPow(a, b), "FlowGraphPowerBlock" /* FlowGraphBlockNames.Power */, config); + } + _polymorphicPow(a, b) { + return _componentWiseBinaryOperation(a, b, Math.pow); + } +} +RegisterClass("FlowGraphPowerBlock" /* FlowGraphBlockNames.Power */, FlowGraphPowerBlock); +/** + * Bitwise NOT operation + */ +class FlowGraphBitwiseNotBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), (a) => { + if (typeof a === "boolean") { + return !a; + } + else if (typeof a === "number") { + return ~a; + } + return new FlowGraphInteger(~a.value); + }, "FlowGraphBitwiseNotBlock" /* FlowGraphBlockNames.BitwiseNot */, config); + } +} +RegisterClass("FlowGraphBitwiseNotBlock" /* FlowGraphBlockNames.BitwiseNot */, FlowGraphBitwiseNotBlock); +/** + * Bitwise AND operation + */ +class FlowGraphBitwiseAndBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), (a, b) => { + if (typeof a === "boolean" && typeof b === "boolean") { + return a && b; + } + else if (typeof a === "number" && typeof b === "number") { + return a & b; + } + else if (typeof a === "object" && typeof b === "object") { + return new FlowGraphInteger(a.value & b.value); + } + else { + throw new Error(`Cannot perform bitwise AND on ${a} and ${b}`); + } + }, "FlowGraphBitwiseAndBlock" /* FlowGraphBlockNames.BitwiseAnd */, config); + } +} +RegisterClass("FlowGraphBitwiseAndBlock" /* FlowGraphBlockNames.BitwiseAnd */, FlowGraphBitwiseAndBlock); +/** + * Bitwise OR operation + */ +class FlowGraphBitwiseOrBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), (a, b) => { + if (typeof a === "boolean" && typeof b === "boolean") { + return a || b; + } + else if (typeof a === "number" && typeof b === "number") { + return a | b; + } + else if (typeof a === "object" && typeof b === "object") { + return new FlowGraphInteger(a.value | b.value); + } + else { + throw new Error(`Cannot perform bitwise OR on ${a} and ${b}`); + } + }, "FlowGraphBitwiseOrBlock" /* FlowGraphBlockNames.BitwiseOr */, config); + } +} +RegisterClass("FlowGraphBitwiseOrBlock" /* FlowGraphBlockNames.BitwiseOr */, FlowGraphBitwiseOrBlock); +/** + * Bitwise XOR operation + */ +class FlowGraphBitwiseXorBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger" /* FlowGraphTypes.Integer */), (a, b) => { + if (typeof a === "boolean" && typeof b === "boolean") { + return a !== b; + } + else if (typeof a === "number" && typeof b === "number") { + return a ^ b; + } + else if (typeof a === "object" && typeof b === "object") { + return new FlowGraphInteger(a.value ^ b.value); + } + else { + throw new Error(`Cannot perform bitwise XOR on ${a} and ${b}`); + } + }, "FlowGraphBitwiseXorBlock" /* FlowGraphBlockNames.BitwiseXor */, config); + } +} +RegisterClass("FlowGraphBitwiseXorBlock" /* FlowGraphBlockNames.BitwiseXor */, FlowGraphBitwiseXorBlock); +/** + * Bitwise left shift operation + */ +class FlowGraphBitwiseLeftShiftBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, (a, b) => new FlowGraphInteger(a.value << b.value), "FlowGraphBitwiseLeftShiftBlock" /* FlowGraphBlockNames.BitwiseLeftShift */, config); + } +} +RegisterClass("FlowGraphBitwiseLeftShiftBlock" /* FlowGraphBlockNames.BitwiseLeftShift */, FlowGraphBitwiseLeftShiftBlock); +/** + * Bitwise right shift operation + */ +class FlowGraphBitwiseRightShiftBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, (a, b) => new FlowGraphInteger(a.value >> b.value), "FlowGraphBitwiseRightShiftBlock" /* FlowGraphBlockNames.BitwiseRightShift */, config); + } +} +RegisterClass("FlowGraphBitwiseRightShiftBlock" /* FlowGraphBlockNames.BitwiseRightShift */, FlowGraphBitwiseRightShiftBlock); +/** + * Count leading zeros operation + */ +class FlowGraphLeadingZerosBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, (a) => new FlowGraphInteger(Math.clz32(a.value)), "FlowGraphLeadingZerosBlock" /* FlowGraphBlockNames.LeadingZeros */, config); + } +} +RegisterClass("FlowGraphLeadingZerosBlock" /* FlowGraphBlockNames.LeadingZeros */, FlowGraphLeadingZerosBlock); +/** + * Count trailing zeros operation + */ +class FlowGraphTrailingZerosBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, (a) => new FlowGraphInteger(a.value ? 31 - Math.clz32(a.value & -a.value) : 32), "FlowGraphTrailingZerosBlock" /* FlowGraphBlockNames.TrailingZeros */, config); + } +} +RegisterClass("FlowGraphTrailingZerosBlock" /* FlowGraphBlockNames.TrailingZeros */, FlowGraphTrailingZerosBlock); +/** + * Given a number (which is converted to a 32-bit integer), return the + * number of bits set to one on that number. + * @param n the number to run the op on + * @returns the number of bits set to one on that number + */ +function _countOnes(n) { + let result = 0; + while (n) { + // This zeroes out all bits except for the least significant one. + // So if the bit is set, it will be 1, otherwise it will be 0. + result += n & 1; + // This shifts n's bits to the right by one + n >>= 1; + } + return result; +} +/** + * Count one bits operation + */ +class FlowGraphOneBitsCounterBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, (a) => new FlowGraphInteger(_countOnes(a.value)), "FlowGraphOneBitsCounterBlock" /* FlowGraphBlockNames.OneBitsCounter */, config); + } +} +RegisterClass("FlowGraphOneBitsCounterBlock" /* FlowGraphBlockNames.OneBitsCounter */, FlowGraphOneBitsCounterBlock); + +const flowGraphMathBlocks = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphAbsBlock, + FlowGraphAcosBlock, + FlowGraphAcoshBlock, + FlowGraphAddBlock, + FlowGraphAsinBlock, + FlowGraphAsinhBlock, + FlowGraphAtan2Block, + FlowGraphAtanBlock, + FlowGraphAtanhBlock, + FlowGraphBitwiseAndBlock, + FlowGraphBitwiseLeftShiftBlock, + FlowGraphBitwiseNotBlock, + FlowGraphBitwiseOrBlock, + FlowGraphBitwiseRightShiftBlock, + FlowGraphBitwiseXorBlock, + FlowGraphCeilBlock, + FlowGraphClampBlock, + FlowGraphCosBlock, + FlowGraphCoshBlock, + FlowGraphCubeRootBlock, + FlowGraphDegToRadBlock, + FlowGraphDivideBlock, + FlowGraphEBlock, + FlowGraphEqualityBlock, + FlowGraphExpBlock, + FlowGraphFloorBlock, + FlowGraphFractionBlock, + FlowGraphGreaterThanBlock, + FlowGraphGreaterThanOrEqualBlock, + FlowGraphInfBlock, + FlowGraphIsInfinityBlock, + FlowGraphIsNanBlock, + FlowGraphLeadingZerosBlock, + FlowGraphLessThanBlock, + FlowGraphLessThanOrEqualBlock, + FlowGraphLog10Block, + FlowGraphLog2Block, + FlowGraphLogBlock, + FlowGraphMathInterpolationBlock, + FlowGraphMaxBlock, + FlowGraphMinBlock, + FlowGraphModuloBlock, + FlowGraphMultiplyBlock, + FlowGraphNaNBlock, + FlowGraphNegationBlock, + FlowGraphOneBitsCounterBlock, + FlowGraphPiBlock, + FlowGraphPowerBlock, + FlowGraphRadToDegBlock, + FlowGraphRandomBlock, + FlowGraphRoundBlock, + FlowGraphSaturateBlock, + FlowGraphSignBlock, + FlowGraphSinBlock, + FlowGraphSinhBlock, + FlowGraphSquareRootBlock, + FlowGraphSubtractBlock, + FlowGraphTanBlock, + FlowGraphTanhBlock, + FlowGraphTrailingZerosBlock, + FlowGraphTruncBlock +}, Symbol.toStringTag, { value: 'Module' })); + +class FlowGraphMathCombineBlock extends FlowGraphCachedOperationBlock { + /** + * Base class for blocks that combine multiple numeric inputs into a single result. + * Handles registering data inputs and managing cached outputs. + * @param numberOfInputs The number of input values to combine. + * @param type The type of the result. + * @param config The block configuration. + */ + constructor(numberOfInputs, type, config) { + super(type, config); + for (let i = 0; i < numberOfInputs; i++) { + this.registerDataInput(`input_${i}`, RichTypeNumber, 0); + } + } +} +/** + * Abstract class representing a flow graph block that extracts multiple outputs from a single input. + */ +class FlowGraphMathExtractBlock extends FlowGraphBlock { + /** + * Creates an instance of FlowGraphMathExtractBlock. + * + * @param numberOfOutputs - The number of outputs to be extracted from the input. + * @param type - The type of the input data. + * @param config - Optional configuration for the flow graph block. + */ + constructor(numberOfOutputs, type, config) { + super(config); + this.registerDataInput("input", type); + for (let i = 0; i < numberOfOutputs; i++) { + this.registerDataOutput(`output_${i}`, RichTypeNumber, 0); + } + } +} +/** + * Combines two floats into a new Vector2 + */ +class FlowGraphCombineVector2Block extends FlowGraphMathCombineBlock { + constructor(config) { + super(2, RichTypeVector2, config); + } + /** + * @internal + * Combines two floats into a new Vector2 + */ + _doOperation(context) { + if (!context._hasExecutionVariable(this, "cachedVector")) { + context._setExecutionVariable(this, "cachedVector", new Vector2()); + } + const vector = context._getExecutionVariable(this, "cachedVector", null); + vector.set(this.getDataInput("input_0").getValue(context), this.getDataInput("input_1").getValue(context)); + return vector; + } + getClassName() { + return "FlowGraphCombineVector2Block" /* FlowGraphBlockNames.CombineVector2 */; + } +} +RegisterClass("FlowGraphCombineVector2Block" /* FlowGraphBlockNames.CombineVector2 */, FlowGraphCombineVector2Block); +/** + * Combines three floats into a new Vector3 + */ +class FlowGraphCombineVector3Block extends FlowGraphMathCombineBlock { + constructor(config) { + super(3, RichTypeVector3, config); + } + _doOperation(context) { + if (!context._hasExecutionVariable(this, "cachedVector")) { + context._setExecutionVariable(this, "cachedVector", new Vector3()); + } + const vector = context._getExecutionVariable(this, "cachedVector", null); + vector.set(this.getDataInput("input_0").getValue(context), this.getDataInput("input_1").getValue(context), this.getDataInput("input_2").getValue(context)); + return vector; + } + getClassName() { + return "FlowGraphCombineVector3Block" /* FlowGraphBlockNames.CombineVector3 */; + } +} +RegisterClass("FlowGraphCombineVector3Block" /* FlowGraphBlockNames.CombineVector3 */, FlowGraphCombineVector3Block); +/** + * Combines four floats into a new Vector4 + */ +class FlowGraphCombineVector4Block extends FlowGraphMathCombineBlock { + constructor(config) { + super(4, RichTypeVector4, config); + } + _doOperation(context) { + if (!context._hasExecutionVariable(this, "cachedVector")) { + context._setExecutionVariable(this, "cachedVector", new Vector4()); + } + const vector = context._getExecutionVariable(this, "cachedVector", null); + vector.set(this.getDataInput("input_0").getValue(context), this.getDataInput("input_1").getValue(context), this.getDataInput("input_2").getValue(context), this.getDataInput("input_3").getValue(context)); + return vector; + } + getClassName() { + return "FlowGraphCombineVector4Block" /* FlowGraphBlockNames.CombineVector4 */; + } +} +RegisterClass("FlowGraphCombineVector4Block" /* FlowGraphBlockNames.CombineVector4 */, FlowGraphCombineVector4Block); +/** + * Combines 16 floats into a new Matrix + * + * Note that glTF interactivity's combine4x4 uses column-major order, while Babylon.js uses row-major order. + */ +class FlowGraphCombineMatrixBlock extends FlowGraphMathCombineBlock { + constructor(config) { + super(16, RichTypeMatrix, config); + } + _doOperation(context) { + if (!context._hasExecutionVariable(this, "cachedMatrix")) { + context._setExecutionVariable(this, "cachedMatrix", new Matrix()); + } + const matrix = context._getExecutionVariable(this, "cachedMatrix", null); + if (this.config?.inputIsColumnMajor) { + matrix.set(this.getDataInput("input_0").getValue(context), this.getDataInput("input_4").getValue(context), this.getDataInput("input_8").getValue(context), this.getDataInput("input_12").getValue(context), this.getDataInput("input_1").getValue(context), this.getDataInput("input_5").getValue(context), this.getDataInput("input_9").getValue(context), this.getDataInput("input_13").getValue(context), this.getDataInput("input_2").getValue(context), this.getDataInput("input_6").getValue(context), this.getDataInput("input_10").getValue(context), this.getDataInput("input_14").getValue(context), this.getDataInput("input_3").getValue(context), this.getDataInput("input_7").getValue(context), this.getDataInput("input_11").getValue(context), this.getDataInput("input_15").getValue(context)); + } + else { + matrix.set(this.getDataInput("input_0").getValue(context), this.getDataInput("input_1").getValue(context), this.getDataInput("input_2").getValue(context), this.getDataInput("input_3").getValue(context), this.getDataInput("input_4").getValue(context), this.getDataInput("input_5").getValue(context), this.getDataInput("input_6").getValue(context), this.getDataInput("input_7").getValue(context), this.getDataInput("input_8").getValue(context), this.getDataInput("input_9").getValue(context), this.getDataInput("input_10").getValue(context), this.getDataInput("input_11").getValue(context), this.getDataInput("input_12").getValue(context), this.getDataInput("input_13").getValue(context), this.getDataInput("input_14").getValue(context), this.getDataInput("input_15").getValue(context)); + } + return matrix; + } + getClassName() { + return "FlowGraphCombineMatrixBlock" /* FlowGraphBlockNames.CombineMatrix */; + } +} +RegisterClass("FlowGraphCombineMatrixBlock" /* FlowGraphBlockNames.CombineMatrix */, FlowGraphCombineMatrixBlock); +/** + * Combines 4 floats into a new Matrix + */ +class FlowGraphCombineMatrix2DBlock extends FlowGraphMathCombineBlock { + constructor(config) { + super(4, RichTypeMatrix2D, config); + } + _doOperation(context) { + if (!context._hasExecutionVariable(this, "cachedMatrix")) { + context._setExecutionVariable(this, "cachedMatrix", new FlowGraphMatrix2D()); + } + const matrix = context._getExecutionVariable(this, "cachedMatrix", null); + const array = this.config?.inputIsColumnMajor + ? [ + // column to row-major + this.getDataInput("input_0").getValue(context), + this.getDataInput("input_2").getValue(context), + this.getDataInput("input_1").getValue(context), + this.getDataInput("input_3").getValue(context), + ] + : [ + this.getDataInput("input_0").getValue(context), + this.getDataInput("input_1").getValue(context), + this.getDataInput("input_2").getValue(context), + this.getDataInput("input_3").getValue(context), + ]; + matrix.fromArray(array); + return matrix; + } + getClassName() { + return "FlowGraphCombineMatrix2DBlock" /* FlowGraphBlockNames.CombineMatrix2D */; + } +} +RegisterClass("FlowGraphCombineMatrix2DBlock" /* FlowGraphBlockNames.CombineMatrix2D */, FlowGraphCombineMatrix2DBlock); +/** + * Combines 9 floats into a new Matrix3D + */ +class FlowGraphCombineMatrix3DBlock extends FlowGraphMathCombineBlock { + constructor(config) { + super(9, RichTypeMatrix3D, config); + } + _doOperation(context) { + if (!context._hasExecutionVariable(this, "cachedMatrix")) { + context._setExecutionVariable(this, "cachedMatrix", new FlowGraphMatrix3D()); + } + const matrix = context._getExecutionVariable(this, "cachedMatrix", null); + const array = this.config?.inputIsColumnMajor + ? [ + // column to row major + this.getDataInput("input_0").getValue(context), + this.getDataInput("input_3").getValue(context), + this.getDataInput("input_6").getValue(context), + this.getDataInput("input_1").getValue(context), + this.getDataInput("input_4").getValue(context), + this.getDataInput("input_7").getValue(context), + this.getDataInput("input_2").getValue(context), + this.getDataInput("input_5").getValue(context), + this.getDataInput("input_8").getValue(context), + ] + : [ + this.getDataInput("input_0").getValue(context), + this.getDataInput("input_1").getValue(context), + this.getDataInput("input_2").getValue(context), + this.getDataInput("input_3").getValue(context), + this.getDataInput("input_4").getValue(context), + this.getDataInput("input_5").getValue(context), + this.getDataInput("input_6").getValue(context), + this.getDataInput("input_7").getValue(context), + this.getDataInput("input_8").getValue(context), + ]; + matrix.fromArray(array); + return matrix; + } + getClassName() { + return "FlowGraphCombineMatrix3DBlock" /* FlowGraphBlockNames.CombineMatrix3D */; + } +} +RegisterClass("FlowGraphCombineMatrix3DBlock" /* FlowGraphBlockNames.CombineMatrix3D */, FlowGraphCombineMatrix3DBlock); +/** + * Extracts two floats from a Vector2 + */ +class FlowGraphExtractVector2Block extends FlowGraphMathExtractBlock { + constructor(config) { + super(2, RichTypeVector2, config); + } + _updateOutputs(context) { + let input = this.getDataInput("input")?.getValue(context); + if (!input) { + input = Vector2.Zero(); + this.getDataInput("input").setValue(input, context); + } + this.getDataOutput("output_0").setValue(input.x, context); + this.getDataOutput("output_1").setValue(input.y, context); + } + getClassName() { + return "FlowGraphExtractVector2Block" /* FlowGraphBlockNames.ExtractVector2 */; + } +} +RegisterClass("FlowGraphExtractVector2Block" /* FlowGraphBlockNames.ExtractVector2 */, FlowGraphExtractVector2Block); +/** + * Extracts three floats from a Vector3 + */ +class FlowGraphExtractVector3Block extends FlowGraphMathExtractBlock { + constructor(config) { + super(3, RichTypeVector3, config); + } + _updateOutputs(context) { + let input = this.getDataInput("input")?.getValue(context); + if (!input) { + input = Vector3.Zero(); + this.getDataInput("input").setValue(input, context); + } + this.getDataOutput("output_0").setValue(input.x, context); + this.getDataOutput("output_1").setValue(input.y, context); + this.getDataOutput("output_2").setValue(input.z, context); + } + getClassName() { + return "FlowGraphExtractVector3Block" /* FlowGraphBlockNames.ExtractVector3 */; + } +} +RegisterClass("FlowGraphExtractVector3Block" /* FlowGraphBlockNames.ExtractVector3 */, FlowGraphExtractVector3Block); +/** + * Extracts four floats from a Vector4 + */ +class FlowGraphExtractVector4Block extends FlowGraphMathExtractBlock { + constructor(config) { + super(4, RichTypeVector4, config); + } + _updateOutputs(context) { + let input = this.getDataInput("input")?.getValue(context); + if (!input) { + input = Vector4.Zero(); + this.getDataInput("input").setValue(input, context); + } + this.getDataOutput("output_0").setValue(input.x, context); + this.getDataOutput("output_1").setValue(input.y, context); + this.getDataOutput("output_2").setValue(input.z, context); + this.getDataOutput("output_3").setValue(input.w, context); + } + getClassName() { + return "FlowGraphExtractVector4Block" /* FlowGraphBlockNames.ExtractVector4 */; + } +} +RegisterClass("FlowGraphExtractVector4Block" /* FlowGraphBlockNames.ExtractVector4 */, FlowGraphExtractVector4Block); +/** + * Extracts 16 floats from a Matrix + */ +class FlowGraphExtractMatrixBlock extends FlowGraphMathExtractBlock { + constructor(config) { + super(16, RichTypeMatrix, config); + } + _updateOutputs(context) { + let input = this.getDataInput("input")?.getValue(context); + if (!input) { + input = Matrix.Identity(); + this.getDataInput("input").setValue(input, context); + } + for (let i = 0; i < 16; i++) { + this.getDataOutput(`output_${i}`).setValue(input.m[i], context); + } + } + getClassName() { + return "FlowGraphExtractMatrixBlock" /* FlowGraphBlockNames.ExtractMatrix */; + } +} +RegisterClass("FlowGraphExtractMatrixBlock" /* FlowGraphBlockNames.ExtractMatrix */, FlowGraphExtractMatrixBlock); +/** + * Extracts 4 floats from a Matrix2D + */ +class FlowGraphExtractMatrix2DBlock extends FlowGraphMathExtractBlock { + constructor(config) { + super(4, RichTypeMatrix2D, config); + } + _updateOutputs(context) { + let input = this.getDataInput("input")?.getValue(context); + if (!input) { + input = new FlowGraphMatrix2D(); + this.getDataInput("input").setValue(input, context); + } + for (let i = 0; i < 4; i++) { + this.getDataOutput(`output_${i}`).setValue(input.m[i], context); + } + } + getClassName() { + return "FlowGraphExtractMatrix2DBlock" /* FlowGraphBlockNames.ExtractMatrix2D */; + } +} +RegisterClass("FlowGraphExtractMatrix2DBlock" /* FlowGraphBlockNames.ExtractMatrix2D */, FlowGraphExtractMatrix2DBlock); +/** + * Extracts 4 floats from a Matrix2D + */ +class FlowGraphExtractMatrix3DBlock extends FlowGraphMathExtractBlock { + constructor(config) { + super(9, RichTypeMatrix3D, config); + } + _updateOutputs(context) { + let input = this.getDataInput("input")?.getValue(context); + if (!input) { + input = new FlowGraphMatrix3D(); + this.getDataInput("input").setValue(input, context); + } + for (let i = 0; i < 9; i++) { + this.getDataOutput(`output_${i}`).setValue(input.m[i], context); + } + } + getClassName() { + return "FlowGraphExtractMatrix3DBlock" /* FlowGraphBlockNames.ExtractMatrix3D */; + } +} +RegisterClass("FlowGraphExtractMatrix3DBlock" /* FlowGraphBlockNames.ExtractMatrix3D */, FlowGraphExtractMatrix3DBlock); + +const flowGraphMathCombineExtractBlocks = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphCombineMatrix2DBlock, + FlowGraphCombineMatrix3DBlock, + FlowGraphCombineMatrixBlock, + FlowGraphCombineVector2Block, + FlowGraphCombineVector3Block, + FlowGraphCombineVector4Block, + FlowGraphExtractMatrix2DBlock, + FlowGraphExtractMatrix3DBlock, + FlowGraphExtractMatrixBlock, + FlowGraphExtractVector2Block, + FlowGraphExtractVector3Block, + FlowGraphExtractVector4Block +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Transposes a matrix. + */ +class FlowGraphTransposeBlock extends FlowGraphUnaryOperationBlock { + /** + * Creates a new instance of the block. + * @param config the configuration of the block + */ + constructor(config) { + super(getRichTypeByFlowGraphType(config?.matrixType || "Matrix" /* FlowGraphTypes.Matrix */), getRichTypeByFlowGraphType(config?.matrixType || "Matrix" /* FlowGraphTypes.Matrix */), (a) => (a.transpose ? a.transpose() : Matrix.Transpose(a)), "FlowGraphTransposeBlock" /* FlowGraphBlockNames.Transpose */, config); + } +} +RegisterClass("FlowGraphTransposeBlock" /* FlowGraphBlockNames.Transpose */, FlowGraphTransposeBlock); +/** + * Gets the determinant of a matrix. + */ +class FlowGraphDeterminantBlock extends FlowGraphUnaryOperationBlock { + /** + * Creates a new instance of the block. + * @param config the configuration of the block + */ + constructor(config) { + super(getRichTypeByFlowGraphType(config?.matrixType || "Matrix" /* FlowGraphTypes.Matrix */), RichTypeNumber, (a) => a.determinant(), "FlowGraphDeterminantBlock" /* FlowGraphBlockNames.Determinant */, config); + } +} +RegisterClass("FlowGraphDeterminantBlock" /* FlowGraphBlockNames.Determinant */, FlowGraphDeterminantBlock); +/** + * Inverts a matrix. + */ +class FlowGraphInvertMatrixBlock extends FlowGraphUnaryOperationBlock { + /** + * Creates a new instance of the inverse block. + * @param config the configuration of the block + */ + constructor(config) { + super(getRichTypeByFlowGraphType(config?.matrixType || "Matrix" /* FlowGraphTypes.Matrix */), getRichTypeByFlowGraphType(config?.matrixType || "Matrix" /* FlowGraphTypes.Matrix */), (a) => (a.inverse ? a.inverse() : Matrix.Invert(a)), "FlowGraphInvertMatrixBlock" /* FlowGraphBlockNames.InvertMatrix */, config); + } +} +RegisterClass("FlowGraphInvertMatrixBlock" /* FlowGraphBlockNames.InvertMatrix */, FlowGraphInvertMatrixBlock); +/** + * Multiplies two matrices. + */ +class FlowGraphMatrixMultiplicationBlock extends FlowGraphBinaryOperationBlock { + /** + * Creates a new instance of the multiplication block. + * Note - this is similar to the math multiplication if not using matrix per-component multiplication. + * @param config the configuration of the block + */ + constructor(config) { + super(getRichTypeByFlowGraphType(config?.matrixType || "Matrix" /* FlowGraphTypes.Matrix */), getRichTypeByFlowGraphType(config?.matrixType || "Matrix" /* FlowGraphTypes.Matrix */), getRichTypeByFlowGraphType(config?.matrixType || "Matrix" /* FlowGraphTypes.Matrix */), (a, b) => b.multiply(a), "FlowGraphMatrixMultiplicationBlock" /* FlowGraphBlockNames.MatrixMultiplication */, config); + } +} +RegisterClass("FlowGraphMatrixMultiplicationBlock" /* FlowGraphBlockNames.MatrixMultiplication */, FlowGraphMatrixMultiplicationBlock); +/** + * Matrix decompose block + */ +class FlowGraphMatrixDecomposeBlock extends FlowGraphBlock { + constructor(config) { + super(config); + this.input = this.registerDataInput("input", RichTypeMatrix); + this.position = this.registerDataOutput("position", RichTypeVector3); + this.rotationQuaternion = this.registerDataOutput("rotationQuaternion", RichTypeQuaternion); + this.scaling = this.registerDataOutput("scaling", RichTypeVector3); + this.isValid = this.registerDataOutput("isValid", RichTypeBoolean, false); + } + _updateOutputs(context) { + const cachedExecutionId = context._getExecutionVariable(this, "executionId", -1); + const cachedPosition = context._getExecutionVariable(this, "cachedPosition", null); + const cachedRotation = context._getExecutionVariable(this, "cachedRotation", null); + const cachedScaling = context._getExecutionVariable(this, "cachedScaling", null); + if (cachedExecutionId === context.executionId && cachedPosition && cachedRotation && cachedScaling) { + this.position.setValue(cachedPosition, context); + this.rotationQuaternion.setValue(cachedRotation, context); + this.scaling.setValue(cachedScaling, context); + } + else { + const matrix = this.input.getValue(context); + const position = cachedPosition || new Vector3(); + const rotation = cachedRotation || new Quaternion(); + const scaling = cachedScaling || new Vector3(); + // check matrix last column components should be 0,0,0,1 + // round them to 4 decimal places + const m3 = Math.round(matrix.m[3] * 10000) / 10000; + const m7 = Math.round(matrix.m[7] * 10000) / 10000; + const m11 = Math.round(matrix.m[11] * 10000) / 10000; + const m15 = Math.round(matrix.m[15] * 10000) / 10000; + if (m3 !== 0 || m7 !== 0 || m11 !== 0 || m15 !== 1) { + this.isValid.setValue(false, context); + this.position.setValue(Vector3.Zero(), context); + this.rotationQuaternion.setValue(Quaternion.Identity(), context); + this.scaling.setValue(Vector3.One(), context); + return; + } + // make the checks for validity + const valid = matrix.decompose(scaling, rotation, position); + this.isValid.setValue(valid, context); + this.position.setValue(position, context); + this.rotationQuaternion.setValue(rotation, context); + this.scaling.setValue(scaling, context); + context._setExecutionVariable(this, "cachedPosition", position); + context._setExecutionVariable(this, "cachedRotation", rotation); + context._setExecutionVariable(this, "cachedScaling", scaling); + context._setExecutionVariable(this, "executionId", context.executionId); + } + } + getClassName() { + return "FlowGraphMatrixDecompose" /* FlowGraphBlockNames.MatrixDecompose */; + } +} +RegisterClass("FlowGraphMatrixDecompose" /* FlowGraphBlockNames.MatrixDecompose */, FlowGraphMatrixDecomposeBlock); +/** + * Matrix compose block + */ +class FlowGraphMatrixComposeBlock extends FlowGraphBlock { + constructor(config) { + super(config); + this.position = this.registerDataInput("position", RichTypeVector3); + this.rotationQuaternion = this.registerDataInput("rotationQuaternion", RichTypeQuaternion); + this.scaling = this.registerDataInput("scaling", RichTypeVector3); + this.value = this.registerDataOutput("value", RichTypeMatrix); + } + _updateOutputs(context) { + const cachedExecutionId = context._getExecutionVariable(this, "executionId", -1); + const cachedMatrix = context._getExecutionVariable(this, "cachedMatrix", null); + if (cachedExecutionId === context.executionId && cachedMatrix) { + this.value.setValue(cachedMatrix, context); + } + else { + const matrix = Matrix.Compose(this.scaling.getValue(context), this.rotationQuaternion.getValue(context), this.position.getValue(context)); + this.value.setValue(matrix, context); + context._setExecutionVariable(this, "cachedMatrix", matrix); + context._setExecutionVariable(this, "executionId", context.executionId); + } + } + getClassName() { + return "FlowGraphMatrixCompose" /* FlowGraphBlockNames.MatrixCompose */; + } +} +RegisterClass("FlowGraphMatrixCompose" /* FlowGraphBlockNames.MatrixCompose */, FlowGraphMatrixComposeBlock); + +const flowGraphMatrixMathBlocks = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphDeterminantBlock, + FlowGraphInvertMatrixBlock, + FlowGraphMatrixComposeBlock, + FlowGraphMatrixDecomposeBlock, + FlowGraphMatrixMultiplicationBlock, + FlowGraphTransposeBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Vector length block. + */ +class FlowGraphLengthBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicLength(a), "FlowGraphLengthBlock" /* FlowGraphBlockNames.Length */, config); + } + _polymorphicLength(a) { + const aClassName = _getClassNameOf(a); + switch (aClassName) { + case "Vector2" /* FlowGraphTypes.Vector2 */: + case "Vector3" /* FlowGraphTypes.Vector3 */: + case "Vector4" /* FlowGraphTypes.Vector4 */: + case "Quaternion" /* FlowGraphTypes.Quaternion */: + return a.length(); + default: + throw new Error(`Cannot compute length of value ${a}`); + } + } +} +RegisterClass("FlowGraphLengthBlock" /* FlowGraphBlockNames.Length */, FlowGraphLengthBlock); +/** + * Vector normalize block. + */ +class FlowGraphNormalizeBlock extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, (a) => this._polymorphicNormalize(a), "FlowGraphNormalizeBlock" /* FlowGraphBlockNames.Normalize */, config); + } + _polymorphicNormalize(a) { + const aClassName = _getClassNameOf(a); + let normalized; + switch (aClassName) { + case "Vector2" /* FlowGraphTypes.Vector2 */: + case "Vector3" /* FlowGraphTypes.Vector3 */: + case "Vector4" /* FlowGraphTypes.Vector4 */: + case "Quaternion" /* FlowGraphTypes.Quaternion */: + normalized = a.normalizeToNew(); + if (this.config?.nanOnZeroLength) { + const length = a.length(); + if (length === 0) { + normalized.setAll(NaN); + } + } + return normalized; + default: + throw new Error(`Cannot normalize value ${a}`); + } + } +} +RegisterClass("FlowGraphNormalizeBlock" /* FlowGraphBlockNames.Normalize */, FlowGraphNormalizeBlock); +/** + * Dot product block. + */ +class FlowGraphDotBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeAny, RichTypeAny, RichTypeNumber, (a, b) => this._polymorphicDot(a, b), "FlowGraphDotBlock" /* FlowGraphBlockNames.Dot */, config); + } + _polymorphicDot(a, b) { + const className = _getClassNameOf(a); + switch (className) { + case "Vector2" /* FlowGraphTypes.Vector2 */: + case "Vector3" /* FlowGraphTypes.Vector3 */: + case "Vector4" /* FlowGraphTypes.Vector4 */: + case "Quaternion" /* FlowGraphTypes.Quaternion */: + // casting is needed because dot requires both to be the same type + return a.dot(b); + default: + throw new Error(`Cannot get dot product of ${a} and ${b}`); + } + } +} +RegisterClass("FlowGraphDotBlock" /* FlowGraphBlockNames.Dot */, FlowGraphDotBlock); +/** + * Cross product block. + */ +class FlowGraphCrossBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeVector3, RichTypeVector3, RichTypeVector3, (a, b) => Vector3.Cross(a, b), "FlowGraphCrossBlock" /* FlowGraphBlockNames.Cross */, config); + } +} +RegisterClass("FlowGraphCrossBlock" /* FlowGraphBlockNames.Cross */, FlowGraphCrossBlock); +/** + * 2D rotation block. + */ +class FlowGraphRotate2DBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeVector2, RichTypeNumber, RichTypeVector2, (a, b) => Vector2.Transform(a, Matrix.RotationZ(b)), "FlowGraphRotate2DBlock" /* FlowGraphBlockNames.Rotate2D */, config); + } +} +RegisterClass("FlowGraphRotate2DBlock" /* FlowGraphBlockNames.Rotate2D */, FlowGraphRotate2DBlock); +/** + * 3D rotation block. + */ +class FlowGraphRotate3DBlock extends FlowGraphTernaryOperationBlock { + constructor(config) { + super(RichTypeVector3, RichTypeVector3, RichTypeNumber, RichTypeVector3, (a, b, c) => Vector3.TransformCoordinates(a, Matrix.RotationAxis(b, c)), "FlowGraphRotate3DBlock" /* FlowGraphBlockNames.Rotate3D */, config); + } +} +RegisterClass("FlowGraphRotate3DBlock" /* FlowGraphBlockNames.Rotate3D */, FlowGraphRotate3DBlock); +function _transformVector(a, b) { + const className = _getClassNameOf(a); + switch (className) { + case "Vector2" /* FlowGraphTypes.Vector2 */: + return b.transformVector(a); + case "Vector3" /* FlowGraphTypes.Vector3 */: + return b.transformVector(a); + case "Vector4" /* FlowGraphTypes.Vector4 */: + a = a; + // transform the vector 4 with the matrix here. Vector4.TransformCoordinates transforms a 3D coordinate, not Vector4 + return new Vector4(a.x * b.m[0] + a.y * b.m[1] + a.z * b.m[2] + a.w * b.m[3], a.x * b.m[4] + a.y * b.m[5] + a.z * b.m[6] + a.w * b.m[7], a.x * b.m[8] + a.y * b.m[9] + a.z * b.m[10] + a.w * b.m[11], a.x * b.m[12] + a.y * b.m[13] + a.z * b.m[14] + a.w * b.m[15]); + default: + throw new Error(`Cannot transform value ${a}`); + } +} +/** + * Transform a vector3 by a matrix. + */ +class FlowGraphTransformBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + const vectorType = config?.vectorType || "Vector3" /* FlowGraphTypes.Vector3 */; + const matrixType = vectorType === "Vector2" /* FlowGraphTypes.Vector2 */ ? "Matrix2D" /* FlowGraphTypes.Matrix2D */ : vectorType === "Vector3" /* FlowGraphTypes.Vector3 */ ? "Matrix3D" /* FlowGraphTypes.Matrix3D */ : "Matrix" /* FlowGraphTypes.Matrix */; + super(getRichTypeByFlowGraphType(vectorType), getRichTypeByFlowGraphType(matrixType), getRichTypeByFlowGraphType(vectorType), _transformVector, "FlowGraphTransformVectorBlock" /* FlowGraphBlockNames.TransformVector */, config); + } +} +RegisterClass("FlowGraphTransformVectorBlock" /* FlowGraphBlockNames.TransformVector */, FlowGraphTransformBlock); +/** + * Transform a vector3 by a matrix. + */ +class FlowGraphTransformCoordinatesBlock extends FlowGraphBinaryOperationBlock { + constructor(config) { + super(RichTypeVector3, RichTypeMatrix, RichTypeVector3, (a, b) => Vector3.TransformCoordinates(a, b), "FlowGraphTransformCoordinatesBlock" /* FlowGraphBlockNames.TransformCoordinates */, config); + } +} +RegisterClass("FlowGraphTransformCoordinatesBlock" /* FlowGraphBlockNames.TransformCoordinates */, FlowGraphTransformCoordinatesBlock); + +const flowGraphVectorMathBlocks = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphCrossBlock, + FlowGraphDotBlock, + FlowGraphLengthBlock, + FlowGraphNormalizeBlock, + FlowGraphRotate2DBlock, + FlowGraphRotate3DBlock, + FlowGraphTransformBlock, + FlowGraphTransformCoordinatesBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This block will take a JSON pointer and parse it to get the value from the JSON object. + * The output is an object and a property name. + * Optionally, the block can also output the value of the property. This is configurable. + */ +class FlowGraphJsonPointerParserBlock extends FlowGraphCachedOperationBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(RichTypeAny, config); + this.config = config; + this.object = this.registerDataOutput("object", RichTypeAny); + this.propertyName = this.registerDataOutput("propertyName", RichTypeAny); + this.setterFunction = this.registerDataOutput("setFunction", RichTypeAny, this._setPropertyValue.bind(this)); + this.getterFunction = this.registerDataOutput("getFunction", RichTypeAny, this._getPropertyValue.bind(this)); + this.generateAnimationsFunction = this.registerDataOutput("generateAnimationsFunction", RichTypeAny, this._getInterpolationAnimationPropertyInfo.bind(this)); + this.templateComponent = new FlowGraphPathConverterComponent(config.jsonPointer, this); + } + _doOperation(context) { + const accessorContainer = this.templateComponent.getAccessor(this.config.pathConverter, context); + const value = accessorContainer.info.get(accessorContainer.object); + const object = accessorContainer.info.getTarget?.(accessorContainer.object); + const propertyName = accessorContainer.info.getPropertyName?.[0](accessorContainer.object); + if (!object) { + throw new Error("Object is undefined"); + } + else { + this.object.setValue(object, context); + if (propertyName) { + this.propertyName.setValue(propertyName, context); + } + } + return value; + } + _setPropertyValue(_target, _propertyName, value, context) { + const accessorContainer = this.templateComponent.getAccessor(this.config.pathConverter, context); + const type = accessorContainer.info.type; + if (type.startsWith("Color")) { + value = ToColor(value, type); + } + accessorContainer.info.set?.(value, accessorContainer.object); + } + _getPropertyValue(_target, _propertyName, context) { + const accessorContainer = this.templateComponent.getAccessor(this.config.pathConverter, context); + return accessorContainer.info.get(accessorContainer.object); + } + _getInterpolationAnimationPropertyInfo(_target, _propertyName, context) { + const accessorContainer = this.templateComponent.getAccessor(this.config.pathConverter, context); + return (keys, fps, animationType, easingFunction) => { + const animations = []; + // make sure keys are of the right type (in case of float3 color/vector) + const type = accessorContainer.info.type; + if (type.startsWith("Color")) { + keys = keys.map((key) => { + return { + frame: key.frame, + value: ToColor(key.value, type), + }; + }); + } + accessorContainer.info.interpolation?.forEach((info, index) => { + const name = accessorContainer.info.getPropertyName?.[index](accessorContainer.object) || "Animation-interpolation-" + index; + // generate the keys based on interpolation info + let newKeys = keys; + if (animationType !== info.type) { + // convert the keys to the right type + newKeys = keys.map((key) => { + return { + frame: key.frame, + value: info.getValue(undefined, key.value.asArray ? key.value.asArray() : [key.value], 0, 1), + }; + }); + } + const animationData = info.buildAnimations(accessorContainer.object, name, 60, newKeys); + animationData.forEach((animation) => { + if (easingFunction) { + animation.babylonAnimation.setEasingFunction(easingFunction); + } + animations.push(animation.babylonAnimation); + }); + }); + return animations; + }; + } + /** + * Gets the class name of this block + * @returns the class name + */ + getClassName() { + return "FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */; + } +} +function ToColor(value, expectedValue) { + if (value.getClassName().startsWith("Color")) { + return value; + } + if (expectedValue === "Color3") { + return new Color3(value.x, value.y, value.z); + } + else if (expectedValue === "Color4") { + return new Color4(value.x, value.y, value.z, value.w); + } + return value; +} +RegisterClass("FlowGraphJsonPointerParserBlock" /* FlowGraphBlockNames.JsonPointerParser */, FlowGraphJsonPointerParserBlock); + +const flowGraphJsonPointerParserBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphJsonPointerParserBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that converts a boolean to a float. + */ +class FlowGraphBooleanToFloat extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeBoolean, RichTypeNumber, (a) => +a, "FlowGraphBooleanToFloat" /* FlowGraphBlockNames.BooleanToFloat */, config); + } +} +RegisterClass("FlowGraphBooleanToFloat" /* FlowGraphBlockNames.BooleanToFloat */, FlowGraphBooleanToFloat); +/** + * A block that converts a boolean to an integer + */ +class FlowGraphBooleanToInt extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeBoolean, RichTypeFlowGraphInteger, (a) => FlowGraphInteger.FromValue(+a), "FlowGraphBooleanToInt" /* FlowGraphBlockNames.BooleanToInt */, config); + } +} +RegisterClass("FlowGraphBooleanToInt" /* FlowGraphBlockNames.BooleanToInt */, FlowGraphBooleanToInt); +/** + * A block that converts a float to a boolean. + */ +class FlowGraphFloatToBoolean extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeBoolean, (a) => !!a, "FlowGraphFloatToBoolean" /* FlowGraphBlockNames.FloatToBoolean */, config); + } +} +RegisterClass("FlowGraphFloatToBoolean" /* FlowGraphBlockNames.FloatToBoolean */, FlowGraphFloatToBoolean); +/** + * A block that converts an integer to a boolean. + */ +class FlowGraphIntToBoolean extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeFlowGraphInteger, RichTypeBoolean, (a) => !!a.value, "FlowGraphIntToBoolean" /* FlowGraphBlockNames.IntToBoolean */, config); + } +} +RegisterClass("FlowGraphIntToBoolean" /* FlowGraphBlockNames.IntToBoolean */, FlowGraphIntToBoolean); +/** + * A block that converts an integer to a float. + */ +class FlowGraphIntToFloat extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeFlowGraphInteger, RichTypeNumber, (a) => a.value, "FlowGraphIntToFloat" /* FlowGraphBlockNames.IntToFloat */, config); + } +} +RegisterClass("FlowGraphIntToFloat" /* FlowGraphBlockNames.IntToFloat */, FlowGraphIntToFloat); +/** + * A block that converts a float to an integer. + */ +class FlowGraphFloatToInt extends FlowGraphUnaryOperationBlock { + constructor(config) { + super(RichTypeNumber, RichTypeFlowGraphInteger, (a) => { + const roundingMode = config?.roundingMode; + switch (roundingMode) { + case "floor": + return FlowGraphInteger.FromValue(Math.floor(a)); + case "ceil": + return FlowGraphInteger.FromValue(Math.ceil(a)); + case "round": + return FlowGraphInteger.FromValue(Math.round(a)); + default: + return FlowGraphInteger.FromValue(a); + } + }, "FlowGraphFloatToInt" /* FlowGraphBlockNames.FloatToInt */, config); + } +} +RegisterClass("FlowGraphFloatToInt" /* FlowGraphBlockNames.FloatToInt */, FlowGraphFloatToInt); + +const flowGraphTypeToTypeBlocks = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphBooleanToFloat, + FlowGraphBooleanToInt, + FlowGraphFloatToBoolean, + FlowGraphFloatToInt, + FlowGraphIntToBoolean, + FlowGraphIntToFloat +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that outputs elements from the context + */ +class FlowGraphContextBlock extends FlowGraphBlock { + constructor(config) { + super(config); + this.userVariables = this.registerDataOutput("userVariables", RichTypeAny); + this.executionId = this.registerDataOutput("executionId", RichTypeNumber); + } + _updateOutputs(context) { + this.userVariables.setValue(context.userVariables, context); + this.executionId.setValue(context.executionId, context); + } + serialize(serializationObject) { + super.serialize(serializationObject); + } + getClassName() { + return "FlowGraphContextBlock" /* FlowGraphBlockNames.Context */; + } +} +RegisterClass("FlowGraphContextBlock" /* FlowGraphBlockNames.Context */, FlowGraphContextBlock); + +const flowGraphContextBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphContextBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This simple Util block takes an array as input and selects a single element from it. + */ +class FlowGraphArrayIndexBlock extends FlowGraphBlock { + /** + * Construct a FlowGraphArrayIndexBlock. + * @param config construction parameters + */ + constructor(config) { + super(config); + this.config = config; + this.array = this.registerDataInput("array", RichTypeAny); + this.index = this.registerDataInput("index", RichTypeAny, new FlowGraphInteger(-1)); + this.value = this.registerDataOutput("value", RichTypeAny); + } + /** + * @internal + */ + _updateOutputs(context) { + const array = this.array.getValue(context); + const index = getNumericValue(this.index.getValue(context)); + if (array && index >= 0 && index < array.length) { + this.value.setValue(array[index], context); + } + else { + this.value.setValue(null, context); + } + } + /** + * Serializes this block + * @param serializationObject the object to serialize to + */ + serialize(serializationObject) { + super.serialize(serializationObject); + } + getClassName() { + return "FlowGraphArrayIndexBlock" /* FlowGraphBlockNames.ArrayIndex */; + } +} +RegisterClass("FlowGraphArrayIndexBlock" /* FlowGraphBlockNames.ArrayIndex */, FlowGraphArrayIndexBlock); + +const flowGraphArrayIndexBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphArrayIndexBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This block takes in a function that is defined OUTSIDE of the flow graph and executes it. + * The function can be a normal function or an async function. + * The function's arguments will be the value of the input connection as the first variable, and the flow graph context as the second variable. + */ +class FlowGraphCodeExecutionBlock extends FlowGraphBlock { + /** + * Construct a FlowGraphCodeExecutionBlock. + * @param config construction parameters + */ + constructor(config) { + super(config); + this.config = config; + this.executionFunction = this.registerDataInput("function", RichTypeAny); + this.value = this.registerDataInput("value", RichTypeAny); + this.result = this.registerDataOutput("result", RichTypeAny); + } + /** + * @internal + */ + _updateOutputs(context) { + const func = this.executionFunction.getValue(context); + const value = this.value.getValue(context); + if (func) { + this.result.setValue(func(value, context), context); + } + } + getClassName() { + return "FlowGraphCodeExecutionBlock" /* FlowGraphBlockNames.CodeExecution */; + } +} + +const flowGraphCodeExecutionBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphCodeExecutionBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This block takes an object as input and an array and returns the index of the object in the array. + */ +class FlowGraphIndexOfBlock extends FlowGraphBlock { + /** + * Construct a FlowGraphIndexOfBlock. + * @param config construction parameters + */ + constructor(config) { + super(config); + this.config = config; + this.object = this.registerDataInput("object", RichTypeAny); + this.array = this.registerDataInput("array", RichTypeAny); + this.index = this.registerDataOutput("index", RichTypeFlowGraphInteger, new FlowGraphInteger(-1)); + } + /** + * @internal + */ + _updateOutputs(context) { + const object = this.object.getValue(context); + const array = this.array.getValue(context); + if (array) { + this.index.setValue(new FlowGraphInteger(array.indexOf(object)), context); + } + } + /** + * Serializes this block + * @param serializationObject the object to serialize to + */ + serialize(serializationObject) { + super.serialize(serializationObject); + } + getClassName() { + return "FlowGraphIndexOfBlock" /* FlowGraphBlockNames.IndexOf */; + } +} +RegisterClass("FlowGraphIndexOfBlock" /* FlowGraphBlockNames.IndexOf */, FlowGraphIndexOfBlock); + +const flowGraphIndexOfBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphIndexOfBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A flow graph block that takes a function name, an object and an optional context as inputs and calls the function on the object. + */ +class FlowGraphFunctionReferenceBlock extends FlowGraphBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.functionName = this.registerDataInput("functionName", RichTypeString); + this.object = this.registerDataInput("object", RichTypeAny); + this.context = this.registerDataInput("context", RichTypeAny, null); + this.output = this.registerDataOutput("output", RichTypeAny); + } + _updateOutputs(context) { + const functionName = this.functionName.getValue(context); + const object = this.object.getValue(context); + const contextValue = this.context.getValue(context); + if (object && functionName) { + const func = object[functionName]; + if (func && typeof func === "function") { + this.output.setValue(func.bind(contextValue), context); + } + } + } + getClassName() { + return "FlowGraphFunctionReference" /* FlowGraphBlockNames.FunctionReference */; + } +} +RegisterClass("FlowGraphFunctionReference" /* FlowGraphBlockNames.FunctionReference */, FlowGraphFunctionReferenceBlock); + +const flowGraphFunctionReferenceBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphFunctionReferenceBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that activates when a mesh is picked. + */ +class FlowGraphMeshPickEventBlock extends FlowGraphEventBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + /** + * the type of the event this block reacts to + */ + this.type = "MeshPick" /* FlowGraphEventType.MeshPick */; + this.asset = this.registerDataInput("asset", RichTypeAny, config?.targetMesh); + this.pickedPoint = this.registerDataOutput("pickedPoint", RichTypeVector3); + this.pickOrigin = this.registerDataOutput("pickOrigin", RichTypeVector3); + this.pointerId = this.registerDataOutput("pointerId", RichTypeNumber); + this.pickedMesh = this.registerDataOutput("pickedMesh", RichTypeAny); + this.pointerType = this.registerDataInput("pointerType", RichTypeAny, PointerEventTypes.POINTERPICK); + } + _getReferencedMesh(context) { + return this.asset.getValue(context); + } + _executeEvent(context, pickedInfo) { + // get the pointer type + const pointerType = this.pointerType.getValue(context); + if (pointerType !== pickedInfo.type) { + // returning true here to continue the propagation of the pointer event to the rest of the blocks + return true; + } + // check if the mesh is the picked mesh or a descendant + const mesh = this._getReferencedMesh(context); + if (mesh && pickedInfo.pickInfo?.pickedMesh && (pickedInfo.pickInfo?.pickedMesh === mesh || _isADescendantOf(pickedInfo.pickInfo?.pickedMesh, mesh))) { + this.pointerId.setValue(pickedInfo.event.pointerId, context); + this.pickOrigin.setValue(pickedInfo.pickInfo.ray?.origin, context); + this.pickedPoint.setValue(pickedInfo.pickInfo.pickedPoint, context); + this.pickedMesh.setValue(pickedInfo.pickInfo.pickedMesh, context); + this._execute(context); + // stop the propagation if the configuration says so + return !this.config?.stopPropagation; + } + else { + // reset the outputs + this.pointerId.resetToDefaultValue(context); + this.pickOrigin.resetToDefaultValue(context); + this.pickedPoint.resetToDefaultValue(context); + this.pickedMesh.resetToDefaultValue(context); + } + return true; + } + /** + * @internal + */ + _preparePendingTasks(_context) { + // no-op + } + /** + * @internal + */ + _cancelPendingTasks(_context) { + // no-op + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphMeshPickEventBlock" /* FlowGraphBlockNames.MeshPickEvent */; + } +} +RegisterClass("FlowGraphMeshPickEventBlock" /* FlowGraphBlockNames.MeshPickEvent */, FlowGraphMeshPickEventBlock); + +const flowGraphMeshPickEventBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphMeshPickEventBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Block that triggers when a scene is ready. + */ +class FlowGraphSceneReadyEventBlock extends FlowGraphEventBlock { + constructor() { + super(...arguments); + this.initPriority = -1; + this.type = "SceneReady" /* FlowGraphEventType.SceneReady */; + } + _executeEvent(context, _payload) { + this._execute(context); + return true; + } + _preparePendingTasks(context) { + // no-op + } + _cancelPendingTasks(context) { + // no-op + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphSceneReadyEventBlock" /* FlowGraphBlockNames.SceneReadyEvent */; + } +} +RegisterClass("FlowGraphSceneReadyEventBlock" /* FlowGraphBlockNames.SceneReadyEvent */, FlowGraphSceneReadyEventBlock); + +const flowGraphSceneReadyEventBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphSceneReadyEventBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that receives a custom event. + * It saves the event data in the data outputs, based on the provided eventData in the configuration. For example, if the event data is + * `{ x: { type: RichTypeNumber }, y: { type: RichTypeNumber } }`, the block will have two data outputs: x and y. + */ +class FlowGraphReceiveCustomEventBlock extends FlowGraphEventBlock { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + this.initPriority = 1; + // use event data to register data outputs + for (const key in this.config.eventData) { + this.registerDataOutput(key, this.config.eventData[key].type); + } + } + _preparePendingTasks(context) { + const observable = context.configuration.coordinator.getCustomEventObservable(this.config.eventId); + // check if we are not exceeding the max number of events + if (observable && observable.hasObservers() && observable.observers.length > FlowGraphCoordinator.MaxEventsPerType) { + this._reportError(context, `FlowGraphReceiveCustomEventBlock: Too many observers for event ${this.config.eventId}. Max is ${FlowGraphCoordinator.MaxEventsPerType}.`); + return; + } + const eventObserver = observable.add((eventData) => { + Object.keys(eventData).forEach((key) => { + this.getDataOutput(key)?.setValue(eventData[key], context); + }); + this._execute(context); + }); + context._setExecutionVariable(this, "_eventObserver", eventObserver); + } + _cancelPendingTasks(context) { + const observable = context.configuration.coordinator.getCustomEventObservable(this.config.eventId); + if (observable) { + const eventObserver = context._getExecutionVariable(this, "_eventObserver", null); + observable.remove(eventObserver); + } + else { + Tools.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this.config.eventId}`); + } + } + _executeEvent(_context, _payload) { + return true; + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphReceiveCustomEventBlock" /* FlowGraphBlockNames.ReceiveCustomEvent */; + } +} +RegisterClass("FlowGraphReceiveCustomEventBlock" /* FlowGraphBlockNames.ReceiveCustomEvent */, FlowGraphReceiveCustomEventBlock); + +const flowGraphReceiveCustomEventBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphReceiveCustomEventBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A block that sends a custom event. + * To receive this event you need to use the ReceiveCustomEvent block. + * This block has no output, but does have inputs based on the eventData from the configuration. + * @see FlowGraphReceiveCustomEventBlock + */ +class FlowGraphSendCustomEventBlock extends FlowGraphExecutionBlockWithOutSignal { + constructor( + /** + * the configuration of the block + */ + config) { + super(config); + this.config = config; + for (const key in this.config.eventData) { + this.registerDataInput(key, this.config.eventData[key].type, this.config.eventData[key].value); + } + } + _execute(context) { + const eventId = this.config.eventId; + // eventData is a map with the key being the data input's name, and value being the data input's value + const eventData = {}; + this.dataInputs.forEach((port) => { + eventData[port.name] = port.getValue(context); + }); + context.configuration.coordinator.notifyCustomEvent(eventId, eventData); + this.out._activateSignal(context); + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphReceiveCustomEventBlock" /* FlowGraphBlockNames.ReceiveCustomEvent */; + } +} +RegisterClass("FlowGraphReceiveCustomEventBlock" /* FlowGraphBlockNames.ReceiveCustomEvent */, FlowGraphSendCustomEventBlock); + +const flowGraphSendCustomEventBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphSendCustomEventBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Block that triggers on scene tick (before each render). + */ +class FlowGraphSceneTickEventBlock extends FlowGraphEventBlock { + constructor() { + super(); + this.type = "SceneBeforeRender" /* FlowGraphEventType.SceneBeforeRender */; + this.timeSinceStart = this.registerDataOutput("timeSinceStart", RichTypeNumber); + this.deltaTime = this.registerDataOutput("deltaTime", RichTypeNumber); + } + /** + * @internal + */ + _preparePendingTasks(_context) { + // no-op + } + /** + * @internal + */ + _executeEvent(context, payload) { + this.timeSinceStart.setValue(payload.timeSinceStart, context); + this.deltaTime.setValue(payload.deltaTime, context); + this._execute(context); + return true; + } + /** + * @internal + */ + _cancelPendingTasks(_context) { + // no-op + } + /** + * @returns class name of the block. + */ + getClassName() { + return "FlowGraphSceneTickEventBlock" /* FlowGraphBlockNames.SceneTickEvent */; + } +} +RegisterClass("FlowGraphSceneTickEventBlock" /* FlowGraphBlockNames.SceneTickEvent */, FlowGraphSceneTickEventBlock); + +const flowGraphSceneTickEventBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphSceneTickEventBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A pointe out event block. + * This block can be used as an entry pointer to when a pointer is out of a specific target mesh. + */ +class FlowGraphPointerOutEventBlock extends FlowGraphEventBlock { + constructor(config) { + super(config); + this.type = "PointerOut" /* FlowGraphEventType.PointerOut */; + this.pointerId = this.registerDataOutput("pointerId", RichTypeNumber); + this.targetMesh = this.registerDataInput("targetMesh", RichTypeAny, config?.targetMesh); + this.meshOutOfPointer = this.registerDataOutput("meshOutOfPointer", RichTypeAny); + } + _executeEvent(context, payload) { + const mesh = this.targetMesh.getValue(context); + this.meshOutOfPointer.setValue(payload.mesh, context); + this.pointerId.setValue(payload.pointerId, context); + const skipEvent = payload.over && _isADescendantOf(payload.mesh, mesh); + if (!skipEvent && (payload.mesh === mesh || _isADescendantOf(payload.mesh, mesh))) { + this._execute(context); + return !this.config?.stopPropagation; + } + return true; + } + _preparePendingTasks(_context) { + // no-op + } + _cancelPendingTasks(_context) { + // no-op + } + getClassName() { + return "FlowGraphPointerOutEventBlock" /* FlowGraphBlockNames.PointerOutEvent */; + } +} +RegisterClass("FlowGraphPointerOutEventBlock" /* FlowGraphBlockNames.PointerOutEvent */, FlowGraphPointerOutEventBlock); + +const flowGraphPointerOutEventBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphPointerOutEventBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A pointer over event block. + * This block can be used as an entry pointer to when a pointer is over a specific target mesh. + */ +class FlowGraphPointerOverEventBlock extends FlowGraphEventBlock { + constructor(config) { + super(config); + this.type = "PointerOver" /* FlowGraphEventType.PointerOver */; + this.pointerId = this.registerDataOutput("pointerId", RichTypeNumber); + this.targetMesh = this.registerDataInput("targetMesh", RichTypeAny, config?.targetMesh); + this.meshUnderPointer = this.registerDataOutput("meshUnderPointer", RichTypeAny); + } + _executeEvent(context, payload) { + const mesh = this.targetMesh.getValue(context); + this.meshUnderPointer.setValue(payload.mesh, context); + // skip if we moved from a mesh that is under the hierarchy of the target mesh + const skipEvent = payload.out && _isADescendantOf(payload.out, mesh); + this.pointerId.setValue(payload.pointerId, context); + if (!skipEvent && (payload.mesh === mesh || _isADescendantOf(payload.mesh, mesh))) { + this._execute(context); + return !this.config?.stopPropagation; + } + return true; + } + _preparePendingTasks(_context) { + // no-op + } + _cancelPendingTasks(_context) { + // no-op + } + getClassName() { + return "FlowGraphPointerOverEventBlock" /* FlowGraphBlockNames.PointerOverEvent */; + } +} +RegisterClass("FlowGraphPointerOverEventBlock" /* FlowGraphBlockNames.PointerOverEvent */, FlowGraphPointerOverEventBlock); + +const flowGraphPointerOverEventBlock = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + FlowGraphPointerOverEventBlock +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Enum of all block names. + * Note - if you add a new block, you must add it here, and must add it in the block factory! + */ +var FlowGraphBlockNames; +(function (FlowGraphBlockNames) { + FlowGraphBlockNames["PlayAnimation"] = "FlowGraphPlayAnimationBlock"; + FlowGraphBlockNames["StopAnimation"] = "FlowGraphStopAnimationBlock"; + FlowGraphBlockNames["PauseAnimation"] = "FlowGraphPauseAnimationBlock"; + FlowGraphBlockNames["ValueInterpolation"] = "FlowGraphInterpolationBlock"; + FlowGraphBlockNames["SceneReadyEvent"] = "FlowGraphSceneReadyEventBlock"; + FlowGraphBlockNames["SceneTickEvent"] = "FlowGraphSceneTickEventBlock"; + FlowGraphBlockNames["SendCustomEvent"] = "FlowGraphSendCustomEventBlock"; + FlowGraphBlockNames["ReceiveCustomEvent"] = "FlowGraphReceiveCustomEventBlock"; + FlowGraphBlockNames["MeshPickEvent"] = "FlowGraphMeshPickEventBlock"; + FlowGraphBlockNames["PointerEvent"] = "FlowGraphPointerEventBlock"; + FlowGraphBlockNames["PointerDownEvent"] = "FlowGraphPointerDownEventBlock"; + FlowGraphBlockNames["PointerUpEvent"] = "FlowGraphPointerUpEventBlock"; + FlowGraphBlockNames["PointerMoveEvent"] = "FlowGraphPointerMoveEventBlock"; + FlowGraphBlockNames["PointerOverEvent"] = "FlowGraphPointerOverEventBlock"; + FlowGraphBlockNames["PointerOutEvent"] = "FlowGraphPointerOutEventBlock"; + FlowGraphBlockNames["E"] = "FlowGraphEBlock"; + FlowGraphBlockNames["PI"] = "FlowGraphPIBlock"; + FlowGraphBlockNames["Inf"] = "FlowGraphInfBlock"; + FlowGraphBlockNames["NaN"] = "FlowGraphNaNBlock"; + FlowGraphBlockNames["Random"] = "FlowGraphRandomBlock"; + FlowGraphBlockNames["Add"] = "FlowGraphAddBlock"; + FlowGraphBlockNames["Subtract"] = "FlowGraphSubtractBlock"; + FlowGraphBlockNames["Multiply"] = "FlowGraphMultiplyBlock"; + FlowGraphBlockNames["Divide"] = "FlowGraphDivideBlock"; + FlowGraphBlockNames["Abs"] = "FlowGraphAbsBlock"; + FlowGraphBlockNames["Sign"] = "FlowGraphSignBlock"; + FlowGraphBlockNames["Trunc"] = "FlowGraphTruncBlock"; + FlowGraphBlockNames["Floor"] = "FlowGraphFloorBlock"; + FlowGraphBlockNames["Ceil"] = "FlowGraphCeilBlock"; + FlowGraphBlockNames["Round"] = "FlowGraphRoundBlock"; + FlowGraphBlockNames["Fraction"] = "FlowGraphFractBlock"; + FlowGraphBlockNames["Negation"] = "FlowGraphNegationBlock"; + FlowGraphBlockNames["Modulo"] = "FlowGraphModuloBlock"; + FlowGraphBlockNames["Min"] = "FlowGraphMinBlock"; + FlowGraphBlockNames["Max"] = "FlowGraphMaxBlock"; + FlowGraphBlockNames["Clamp"] = "FlowGraphClampBlock"; + FlowGraphBlockNames["Saturate"] = "FlowGraphSaturateBlock"; + FlowGraphBlockNames["MathInterpolation"] = "FlowGraphMathInterpolationBlock"; + FlowGraphBlockNames["Equality"] = "FlowGraphEqualityBlock"; + FlowGraphBlockNames["LessThan"] = "FlowGraphLessThanBlock"; + FlowGraphBlockNames["LessThanOrEqual"] = "FlowGraphLessThanOrEqualBlock"; + FlowGraphBlockNames["GreaterThan"] = "FlowGraphGreaterThanBlock"; + FlowGraphBlockNames["GreaterThanOrEqual"] = "FlowGraphGreaterThanOrEqualBlock"; + FlowGraphBlockNames["IsNaN"] = "FlowGraphIsNaNBlock"; + FlowGraphBlockNames["IsInfinity"] = "FlowGraphIsInfBlock"; + FlowGraphBlockNames["DegToRad"] = "FlowGraphDegToRadBlock"; + FlowGraphBlockNames["RadToDeg"] = "FlowGraphRadToDegBlock"; + FlowGraphBlockNames["Sin"] = "FlowGraphSinBlock"; + FlowGraphBlockNames["Cos"] = "FlowGraphCosBlock"; + FlowGraphBlockNames["Tan"] = "FlowGraphTanBlock"; + FlowGraphBlockNames["Asin"] = "FlowGraphASinBlock"; + FlowGraphBlockNames["Acos"] = "FlowGraphACosBlock"; + FlowGraphBlockNames["Atan"] = "FlowGraphATanBlock"; + FlowGraphBlockNames["Atan2"] = "FlowGraphATan2Block"; + FlowGraphBlockNames["Sinh"] = "FlowGraphSinhBlock"; + FlowGraphBlockNames["Cosh"] = "FlowGraphCoshBlock"; + FlowGraphBlockNames["Tanh"] = "FlowGraphTanhBlock"; + FlowGraphBlockNames["Asinh"] = "FlowGraphASinhBlock"; + FlowGraphBlockNames["Acosh"] = "FlowGraphACoshBlock"; + FlowGraphBlockNames["Atanh"] = "FlowGraphATanhBlock"; + FlowGraphBlockNames["Exponential"] = "FlowGraphExponentialBlock"; + FlowGraphBlockNames["Log"] = "FlowGraphLogBlock"; + FlowGraphBlockNames["Log2"] = "FlowGraphLog2Block"; + FlowGraphBlockNames["Log10"] = "FlowGraphLog10Block"; + FlowGraphBlockNames["SquareRoot"] = "FlowGraphSquareRootBlock"; + FlowGraphBlockNames["CubeRoot"] = "FlowGraphCubeRootBlock"; + FlowGraphBlockNames["Power"] = "FlowGraphPowerBlock"; + FlowGraphBlockNames["Length"] = "FlowGraphLengthBlock"; + FlowGraphBlockNames["Normalize"] = "FlowGraphNormalizeBlock"; + FlowGraphBlockNames["Dot"] = "FlowGraphDotBlock"; + FlowGraphBlockNames["Cross"] = "FlowGraphCrossBlock"; + FlowGraphBlockNames["Rotate2D"] = "FlowGraphRotate2DBlock"; + FlowGraphBlockNames["Rotate3D"] = "FlowGraphRotate3DBlock"; + FlowGraphBlockNames["Transpose"] = "FlowGraphTransposeBlock"; + FlowGraphBlockNames["Determinant"] = "FlowGraphDeterminantBlock"; + FlowGraphBlockNames["InvertMatrix"] = "FlowGraphInvertMatrixBlock"; + FlowGraphBlockNames["MatrixMultiplication"] = "FlowGraphMatrixMultiplicationBlock"; + FlowGraphBlockNames["BitwiseAnd"] = "FlowGraphBitwiseAndBlock"; + FlowGraphBlockNames["BitwiseOr"] = "FlowGraphBitwiseOrBlock"; + FlowGraphBlockNames["BitwiseXor"] = "FlowGraphBitwiseXorBlock"; + FlowGraphBlockNames["BitwiseNot"] = "FlowGraphBitwiseNotBlock"; + FlowGraphBlockNames["BitwiseLeftShift"] = "FlowGraphBitwiseLeftShiftBlock"; + FlowGraphBlockNames["BitwiseRightShift"] = "FlowGraphBitwiseRightShiftBlock"; + FlowGraphBlockNames["LeadingZeros"] = "FlowGraphLeadingZerosBlock"; + FlowGraphBlockNames["TrailingZeros"] = "FlowGraphTrailingZerosBlock"; + FlowGraphBlockNames["OneBitsCounter"] = "FlowGraphOneBitsCounterBlock"; + FlowGraphBlockNames["Branch"] = "FlowGraphBranchBlock"; + FlowGraphBlockNames["SetDelay"] = "FlowGraphSetDelayBlock"; + FlowGraphBlockNames["CancelDelay"] = "FlowGraphCancelDelayBlock"; + FlowGraphBlockNames["CallCounter"] = "FlowGraphCallCounterBlock"; + FlowGraphBlockNames["Debounce"] = "FlowGraphDebounceBlock"; + FlowGraphBlockNames["Throttle"] = "FlowGraphThrottleBlock"; + FlowGraphBlockNames["DoN"] = "FlowGraphDoNBlock"; + FlowGraphBlockNames["FlipFlop"] = "FlowGraphFlipFlopBlock"; + FlowGraphBlockNames["ForLoop"] = "FlowGraphForLoopBlock"; + FlowGraphBlockNames["MultiGate"] = "FlowGraphMultiGateBlock"; + FlowGraphBlockNames["Sequence"] = "FlowGraphSequenceBlock"; + FlowGraphBlockNames["Switch"] = "FlowGraphSwitchBlock"; + FlowGraphBlockNames["WaitAll"] = "FlowGraphWaitAllBlock"; + FlowGraphBlockNames["WhileLoop"] = "FlowGraphWhileLoopBlock"; + FlowGraphBlockNames["ConsoleLog"] = "FlowGraphConsoleLogBlock"; + FlowGraphBlockNames["Conditional"] = "FlowGraphConditionalBlock"; + FlowGraphBlockNames["Constant"] = "FlowGraphConstantBlock"; + FlowGraphBlockNames["TransformCoordinatesSystem"] = "FlowGraphTransformCoordinatesSystemBlock"; + FlowGraphBlockNames["GetAsset"] = "FlowGraphGetAssetBlock"; + FlowGraphBlockNames["GetProperty"] = "FlowGraphGetPropertyBlock"; + FlowGraphBlockNames["SetProperty"] = "FlowGraphSetPropertyBlock"; + FlowGraphBlockNames["GetVariable"] = "FlowGraphGetVariableBlock"; + FlowGraphBlockNames["SetVariable"] = "FlowGraphSetVariableBlock"; + FlowGraphBlockNames["JsonPointerParser"] = "FlowGraphJsonPointerParserBlock"; + FlowGraphBlockNames["CombineVector2"] = "FlowGraphCombineVector2Block"; + FlowGraphBlockNames["CombineVector3"] = "FlowGraphCombineVector3Block"; + FlowGraphBlockNames["CombineVector4"] = "FlowGraphCombineVector4Block"; + FlowGraphBlockNames["CombineMatrix"] = "FlowGraphCombineMatrixBlock"; + FlowGraphBlockNames["CombineMatrix2D"] = "FlowGraphCombineMatrix2DBlock"; + FlowGraphBlockNames["CombineMatrix3D"] = "FlowGraphCombineMatrix3DBlock"; + FlowGraphBlockNames["ExtractVector2"] = "FlowGraphExtractVector2Block"; + FlowGraphBlockNames["ExtractVector3"] = "FlowGraphExtractVector3Block"; + FlowGraphBlockNames["ExtractVector4"] = "FlowGraphExtractVector4Block"; + FlowGraphBlockNames["ExtractMatrix"] = "FlowGraphExtractMatrixBlock"; + FlowGraphBlockNames["ExtractMatrix2D"] = "FlowGraphExtractMatrix2DBlock"; + FlowGraphBlockNames["ExtractMatrix3D"] = "FlowGraphExtractMatrix3DBlock"; + FlowGraphBlockNames["TransformVector"] = "FlowGraphTransformVectorBlock"; + FlowGraphBlockNames["TransformCoordinates"] = "FlowGraphTransformCoordinatesBlock"; + FlowGraphBlockNames["MatrixDecompose"] = "FlowGraphMatrixDecompose"; + FlowGraphBlockNames["MatrixCompose"] = "FlowGraphMatrixCompose"; + FlowGraphBlockNames["BooleanToFloat"] = "FlowGraphBooleanToFloat"; + FlowGraphBlockNames["BooleanToInt"] = "FlowGraphBooleanToInt"; + FlowGraphBlockNames["FloatToBoolean"] = "FlowGraphFloatToBoolean"; + FlowGraphBlockNames["IntToBoolean"] = "FlowGraphIntToBoolean"; + FlowGraphBlockNames["IntToFloat"] = "FlowGraphIntToFloat"; + FlowGraphBlockNames["FloatToInt"] = "FlowGraphFloatToInt"; + FlowGraphBlockNames["Easing"] = "FlowGraphEasingBlock"; + FlowGraphBlockNames["Context"] = "FlowGraphContextBlock"; + FlowGraphBlockNames["ArrayIndex"] = "FlowGraphArrayIndexBlock"; + FlowGraphBlockNames["CodeExecution"] = "FlowGraphCodeExecutionBlock"; + FlowGraphBlockNames["IndexOf"] = "FlowGraphIndexOfBlock"; + FlowGraphBlockNames["FunctionReference"] = "FlowGraphFunctionReference"; + FlowGraphBlockNames["BezierCurveEasing"] = "FlowGraphBezierCurveEasing"; + FlowGraphBlockNames["DataSwitch"] = "FlowGraphDataSwitchBlock"; +})(FlowGraphBlockNames || (FlowGraphBlockNames = {})); + +/** + * Defines the kind of connection point for node render graph nodes + */ +var NodeRenderGraphBlockConnectionPointTypes; +(function (NodeRenderGraphBlockConnectionPointTypes) { + /** General purpose texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["Texture"] = 1] = "Texture"; + /** Back buffer color texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureBackBuffer"] = 2] = "TextureBackBuffer"; + /** Back buffer depth/stencil attachment */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureBackBufferDepthStencilAttachment"] = 4] = "TextureBackBufferDepthStencilAttachment"; + /** Depth/stencil attachment */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureDepthStencilAttachment"] = 8] = "TextureDepthStencilAttachment"; + /** Depth (in view space) geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureViewDepth"] = 16] = "TextureViewDepth"; + /** Normal (in view space) geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureViewNormal"] = 32] = "TextureViewNormal"; + /** Albedo geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureAlbedo"] = 64] = "TextureAlbedo"; + /** Reflectivity geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureReflectivity"] = 128] = "TextureReflectivity"; + /** Position (in world space) geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureWorldPosition"] = 256] = "TextureWorldPosition"; + /** Velocity geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureVelocity"] = 512] = "TextureVelocity"; + /** Irradiance geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureIrradiance"] = 1024] = "TextureIrradiance"; + /** Albedo (sqrt) geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureAlbedoSqrt"] = 2048] = "TextureAlbedoSqrt"; + /** Depth (in screen space) geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureScreenDepth"] = 4096] = "TextureScreenDepth"; + /** Normal (in world space) geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureWorldNormal"] = 8192] = "TextureWorldNormal"; + /** Position (in local space) geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureLocalPosition"] = 16384] = "TextureLocalPosition"; + /** Linear velocity geometry texture */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureLinearVelocity"] = 32768] = "TextureLinearVelocity"; + /** Bit field for all textures but back buffer depth/stencil */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureAllButBackBufferDepthStencil"] = 1048571] = "TextureAllButBackBufferDepthStencil"; + /** Bit field for all textures but back buffer color and depth/stencil */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureAllButBackBuffer"] = 1048569] = "TextureAllButBackBuffer"; + /** Bit field for all textures */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["TextureAll"] = 1048575] = "TextureAll"; + /** Resource container */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["ResourceContainer"] = 1048576] = "ResourceContainer"; + /** Shadow generator */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["ShadowGenerator"] = 2097152] = "ShadowGenerator"; + /** Light */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["ShadowLight"] = 4194304] = "ShadowLight"; + /** Camera */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["Camera"] = 16777216] = "Camera"; + /** List of objects (meshes, particle systems, sprites) */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["ObjectList"] = 33554432] = "ObjectList"; + /** Detect type based on connection */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["AutoDetect"] = 268435456] = "AutoDetect"; + /** Output type that will be defined by input type */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["BasedOnInput"] = 536870912] = "BasedOnInput"; + /** Undefined */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["Undefined"] = 1073741824] = "Undefined"; + /** Custom object */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["Object"] = 2147483648] = "Object"; + /** Bitmask of all types */ + NodeRenderGraphBlockConnectionPointTypes[NodeRenderGraphBlockConnectionPointTypes["All"] = 4294967295] = "All"; +})(NodeRenderGraphBlockConnectionPointTypes || (NodeRenderGraphBlockConnectionPointTypes = {})); +/** + * Enum used to define the compatibility state between two connection points + */ +var NodeRenderGraphConnectionPointCompatibilityStates; +(function (NodeRenderGraphConnectionPointCompatibilityStates) { + /** Points are compatibles */ + NodeRenderGraphConnectionPointCompatibilityStates[NodeRenderGraphConnectionPointCompatibilityStates["Compatible"] = 0] = "Compatible"; + /** Points are incompatible because of their types */ + NodeRenderGraphConnectionPointCompatibilityStates[NodeRenderGraphConnectionPointCompatibilityStates["TypeIncompatible"] = 1] = "TypeIncompatible"; + /** Points are incompatible because they are in the same hierarchy **/ + NodeRenderGraphConnectionPointCompatibilityStates[NodeRenderGraphConnectionPointCompatibilityStates["HierarchyIssue"] = 2] = "HierarchyIssue"; +})(NodeRenderGraphConnectionPointCompatibilityStates || (NodeRenderGraphConnectionPointCompatibilityStates = {})); +/** + * Defines the direction of a connection point + */ +var NodeRenderGraphConnectionPointDirection; +(function (NodeRenderGraphConnectionPointDirection) { + /** Input */ + NodeRenderGraphConnectionPointDirection[NodeRenderGraphConnectionPointDirection["Input"] = 0] = "Input"; + /** Output */ + NodeRenderGraphConnectionPointDirection[NodeRenderGraphConnectionPointDirection["Output"] = 1] = "Output"; +})(NodeRenderGraphConnectionPointDirection || (NodeRenderGraphConnectionPointDirection = {})); + +/** + * Defines a connection point for a block + */ +class NodeRenderGraphConnectionPoint { + /** Gets the direction of the point */ + get direction() { + return this._direction; + } + /** + * Checks if the value is a texture handle + * @param value The value to check + * @returns True if the value is a texture handle + */ + static IsTextureHandle(value) { + return value !== undefined && Number.isFinite(value); + } + /** + * Checks if the value is a shadow generator task + * @param value The value to check + * @returns True if the value is a shadow generator + */ + static IsShadowGenerator(value) { + return value !== undefined && value.mapSize !== undefined; + } + /** + * Checks if the value is a shadow light + * @param value The value to check + * @returns True if the value is a shadow light + */ + static IsShadowLight(value) { + return value !== undefined && value.setShadowProjectionMatrix !== undefined; + } + /** + * Gets or sets the connection point type (default is Undefined) + */ + get type() { + if (this._type === NodeRenderGraphBlockConnectionPointTypes.AutoDetect) { + if (this._ownerBlock.isInput) { + return this._ownerBlock.type; + } + if (this._connectedPoint) { + return this._connectedPoint.type; + } + if (this._linkedConnectionSource) { + if (this._linkedConnectionSource.isConnected) { + return this._linkedConnectionSource.type; + } + if (this._linkedConnectionSource._defaultConnectionPointType) { + return this._linkedConnectionSource._defaultConnectionPointType; + } + } + if (this._defaultConnectionPointType) { + return this._defaultConnectionPointType; + } + } + if (this._type === NodeRenderGraphBlockConnectionPointTypes.BasedOnInput) { + if (this._typeConnectionSource) { + const typeConnectionSource = typeof this._typeConnectionSource === "function" ? this._typeConnectionSource() : this._typeConnectionSource; + if (!typeConnectionSource.isConnected) { + return this._defaultConnectionPointType ?? typeConnectionSource.type; + } + return typeConnectionSource._connectedPoint.type; + } + else if (this._defaultConnectionPointType) { + return this._defaultConnectionPointType; + } + } + return this._type; + } + set type(value) { + this._type = value; + } + /** + * Gets a boolean indicating that the current point is connected to another NodeRenderGraphBlock + */ + get isConnected() { + return this.connectedPoint !== null || this.hasEndpoints; + } + /** Get the other side of the connection (if any) */ + get connectedPoint() { + return this._connectedPoint; + } + /** Get the block that owns this connection point */ + get ownerBlock() { + return this._ownerBlock; + } + /** Get the block connected on the other side of this connection (if any) */ + get sourceBlock() { + if (!this._connectedPoint) { + return null; + } + return this._connectedPoint.ownerBlock; + } + /** Get the block connected on the endpoints of this connection (if any) */ + get connectedBlocks() { + if (this._endpoints.length === 0) { + return []; + } + return this._endpoints.map((e) => e.ownerBlock); + } + /** Gets the list of connected endpoints */ + get endpoints() { + return this._endpoints; + } + /** Gets a boolean indicating if that output point is connected to at least one input */ + get hasEndpoints() { + return this._endpoints && this._endpoints.length > 0; + } + /** Get the inner type (ie AutoDetect for instance instead of the inferred one) */ + get innerType() { + if (this._linkedConnectionSource && !this._isMainLinkSource && this._linkedConnectionSource.isConnected) { + return this.type; + } + return this._type; + } + /** + * Creates a block suitable to be used as an input for this input point. + * If null is returned, a block based on the point type will be created. + * @returns The returned string parameter is the name of the output point of NodeRenderGraphBlock (first parameter of the returned array) that can be connected to the input + */ + createCustomInputBlock() { + return null; + } + /** + * Creates a new connection point + * @param name defines the connection point name + * @param ownerBlock defines the block hosting this connection point + * @param direction defines the direction of the connection point + */ + constructor(name, ownerBlock, direction) { + this._connectedPoint = null; + /** @internal */ + this._acceptedConnectionPointType = null; + this._endpoints = new Array(); + this._type = NodeRenderGraphBlockConnectionPointTypes.Undefined; + /** @internal */ + this._linkedConnectionSource = null; + /** @internal */ + this._isMainLinkSource = false; + /** @internal */ + this._typeConnectionSource = null; + /** @internal */ + this._defaultConnectionPointType = null; + /** Indicates that this connection point needs dual validation before being connected to another point */ + this.needDualDirectionValidation = false; + /** + * Gets or sets the additional types supported by this connection point + */ + this.acceptedConnectionPointTypes = []; + /** + * Gets or sets the additional types excluded by this connection point + */ + this.excludedConnectionPointTypes = []; + /** + * Observable triggered when this point is connected + */ + this.onConnectionObservable = new Observable(); + /** + * Observable triggered when this point is disconnected + */ + this.onDisconnectionObservable = new Observable(); + /** + * Gets or sets a boolean indicating that this connection point is exposed on a frame + */ + this.isExposedOnFrame = false; + /** + * Gets or sets number indicating the position that the port is exposed to on a frame + */ + this.exposedPortPosition = -1; + this._ownerBlock = ownerBlock; + this.name = name; + this._direction = direction; + } + /** + * Gets the current class name e.g. "NodeRenderGraphConnectionPoint" + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphConnectionPoint"; + } + /** + * Gets a boolean indicating if the current point can be connected to another point + * @param connectionPoint defines the other connection point + * @returns a boolean + */ + canConnectTo(connectionPoint) { + return this.checkCompatibilityState(connectionPoint) === 0 /* NodeRenderGraphConnectionPointCompatibilityStates.Compatible */; + } + /** + * Gets a number indicating if the current point can be connected to another point + * @param connectionPoint defines the other connection point + * @returns a number defining the compatibility state + */ + checkCompatibilityState(connectionPoint) { + const ownerBlock = this._ownerBlock; + const otherBlock = connectionPoint.ownerBlock; + if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeRenderGraphBlockConnectionPointTypes.AutoDetect) { + // Accepted types + if (connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) { + return 0 /* NodeRenderGraphConnectionPointCompatibilityStates.Compatible */; + } + else { + return 1 /* NodeRenderGraphConnectionPointCompatibilityStates.TypeIncompatible */; + } + } + // Excluded + if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) { + return 1 /* NodeRenderGraphConnectionPointCompatibilityStates.TypeIncompatible */; + } + // Check hierarchy + let targetBlock = otherBlock; + let sourceBlock = ownerBlock; + if (this.direction === 0 /* NodeRenderGraphConnectionPointDirection.Input */) { + targetBlock = ownerBlock; + sourceBlock = otherBlock; + } + if (targetBlock.isAnAncestorOf(sourceBlock)) { + return 2 /* NodeRenderGraphConnectionPointCompatibilityStates.HierarchyIssue */; + } + return 0 /* NodeRenderGraphConnectionPointCompatibilityStates.Compatible */; + } + /** + * Connect this point to another connection point + * @param connectionPoint defines the other connection point + * @param ignoreConstraints defines if the system will ignore connection type constraints (default is false) + * @returns the current connection point + */ + connectTo(connectionPoint, ignoreConstraints = false) { + if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) { + // eslint-disable-next-line no-throw-literal + throw "Cannot connect these two connectors."; + } + this._endpoints.push(connectionPoint); + connectionPoint._connectedPoint = this; + this.onConnectionObservable.notifyObservers(connectionPoint); + connectionPoint.onConnectionObservable.notifyObservers(this); + return this; + } + /** + * Disconnect this point from one of his endpoint + * @param endpoint defines the other connection point + * @returns the current connection point + */ + disconnectFrom(endpoint) { + const index = this._endpoints.indexOf(endpoint); + if (index === -1) { + return this; + } + this._endpoints.splice(index, 1); + endpoint._connectedPoint = null; + this.onDisconnectionObservable.notifyObservers(endpoint); + endpoint.onDisconnectionObservable.notifyObservers(this); + return this; + } + /** + * Fills the list of excluded connection point types with all types other than those passed in the parameter + * @param mask Types (ORed values of NodeRenderGraphBlockConnectionPointTypes) that are allowed, and thus will not be pushed to the excluded list + */ + addExcludedConnectionPointFromAllowedTypes(mask) { + let bitmask = 0; + let val = 2 ** bitmask; + // Note: don't use 1 << bitmask instead of 2 ** bitmask, as it will cause an infinite loop because 1 << 31 is negative! + while (val < NodeRenderGraphBlockConnectionPointTypes.All) { + if (!(mask & val)) { + this.excludedConnectionPointTypes.push(val); + } + bitmask++; + val = 2 ** bitmask; + } + } + /** + * Adds accepted connection point types + * @param mask Types (ORed values of NodeRenderGraphBlockConnectionPointTypes) that are allowed to connect to this point + */ + addAcceptedConnectionPointTypes(mask) { + let bitmask = 0; + let val = 2 ** bitmask; + // Note: don't use 1 << bitmask instead of 2 ** bitmask, as it will cause an infinite loop because 1 << 31 is negative! + while (val < NodeRenderGraphBlockConnectionPointTypes.All) { + if (mask & val && this.acceptedConnectionPointTypes.indexOf(val) === -1) { + this.acceptedConnectionPointTypes.push(val); + } + bitmask++; + val = 2 ** bitmask; + } + } + /** + * Serializes this point in a JSON representation + * @param isInput defines if the connection point is an input (default is true) + * @returns the serialized point object + */ + serialize(isInput = true) { + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.displayName = this.displayName; + if (isInput && this.connectedPoint) { + serializationObject.inputName = this.name; + serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId; + serializationObject.targetConnectionName = this.connectedPoint.name; + serializationObject.isExposedOnFrame = true; + serializationObject.exposedPortPosition = this.exposedPortPosition; + } + if (this.isExposedOnFrame || this.exposedPortPosition >= 0) { + serializationObject.isExposedOnFrame = true; + serializationObject.exposedPortPosition = this.exposedPortPosition; + } + return serializationObject; + } + /** + * Release resources + */ + dispose() { + this.onConnectionObservable.clear(); + this.onDisconnectionObservable.clear(); + } +} + +/** + * Defines a block that can be used inside a node render graph + */ +class NodeRenderGraphBlock { + /** + * Gets or sets the disable flag of the task associated with this block + */ + get disabled() { + return !!this._frameGraphTask?.disabled; + } + set disabled(value) { + if (this._frameGraphTask) { + this._frameGraphTask.disabled = value; + } + } + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Gets the list of input points + */ + get inputs() { + return this._inputs; + } + /** Gets the list of output points */ + get outputs() { + return this._outputs; + } + /** + * Gets or set the name of the block + */ + get name() { + return this._name; + } + set name(value) { + this._name = value; + } + /** + * Gets a boolean indicating if this block is an input + */ + get isInput() { + return this._isInput; + } + /** + * Gets a boolean indicating if this block is a teleport out + */ + get isTeleportOut() { + return this._isTeleportOut; + } + /** + * Gets a boolean indicating if this block is a teleport in + */ + get isTeleportIn() { + return this._isTeleportIn; + } + /** + * Gets a boolean indicating if this block is a debug block + */ + get isDebug() { + return this._isDebug; + } + /** + * Gets a boolean indicating that this block can only be used once per node render graph + */ + get isUnique() { + return this._isUnique; + } + /** + * Gets the current class name e.g. "NodeRenderGraphBlock" + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphBlock"; + } + _inputRename(name) { + return name; + } + _outputRename(name) { + return name; + } + /** + * Checks if the current block is an ancestor of a given block + * @param block defines the potential descendant block to check + * @returns true if block is a descendant + */ + isAnAncestorOf(block) { + for (const output of this._outputs) { + if (!output.hasEndpoints) { + continue; + } + for (const endpoint of output.endpoints) { + if (endpoint.ownerBlock === block) { + return true; + } + if (endpoint.ownerBlock.isAnAncestorOf(block)) { + return true; + } + } + } + return false; + } + /** + * Checks if the current block is an ancestor of a given type + * @param type defines the potential type to check + * @returns true if block is a descendant + */ + isAnAncestorOfType(type) { + if (this.getClassName() === type) { + return true; + } + for (const output of this._outputs) { + if (!output.hasEndpoints) { + continue; + } + for (const endpoint of output.endpoints) { + if (endpoint.ownerBlock.isAnAncestorOfType(type)) { + return true; + } + } + } + return false; + } + /** + * Get the first descendant using a predicate + * @param predicate defines the predicate to check + * @returns descendant or null if none found + */ + getDescendantOfPredicate(predicate) { + if (predicate(this)) { + return this; + } + for (const output of this._outputs) { + if (!output.hasEndpoints) { + continue; + } + for (const endpoint of output.endpoints) { + const descendant = endpoint.ownerBlock.getDescendantOfPredicate(predicate); + if (descendant) { + return descendant; + } + } + } + return null; + } + /** + * Creates a new NodeRenderGraphBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param _additionalConstructionParameters defines additional parameters to pass to the block constructor + */ + constructor(name, frameGraph, scene, ..._additionalConstructionParameters) { + this._name = ""; + this._isInput = false; + this._isTeleportOut = false; + this._isTeleportIn = false; + this._isDebug = false; + this._isUnique = false; + /** + * Gets an observable raised when the block is built + */ + this.onBuildObservable = new Observable(); + /** @internal */ + this._inputs = new Array(); + /** @internal */ + this._outputs = new Array(); + /** @internal */ + this._codeVariableName = ""; + /** @internal */ + this._additionalConstructionParameters = null; + /** Gets or sets a boolean indicating that this input can be edited from a collapsed frame */ + this.visibleOnFrame = false; + this._name = name; + this._frameGraph = frameGraph; + this._scene = scene; + this._engine = scene.getEngine(); + this.uniqueId = UniqueIdGenerator.UniqueId; + } + /** + * Register a new input. Must be called inside a block constructor + * @param name defines the connection point name + * @param type defines the connection point type + * @param isOptional defines a boolean indicating that this input can be omitted + * @param point an already created connection point. If not provided, create a new one + * @returns the current block + */ + registerInput(name, type, isOptional = false, point) { + point = point ?? new NodeRenderGraphConnectionPoint(name, this, 0 /* NodeRenderGraphConnectionPointDirection.Input */); + point.type = type; + point.isOptional = isOptional; + this._inputs.push(point); + return this; + } + /** + * Register a new output. Must be called inside a block constructor + * @param name defines the connection point name + * @param type defines the connection point type + * @param point an already created connection point. If not provided, create a new one + * @returns the current block + */ + registerOutput(name, type, point) { + point = point ?? new NodeRenderGraphConnectionPoint(name, this, 1 /* NodeRenderGraphConnectionPointDirection.Output */); + point.type = type; + this._outputs.push(point); + return this; + } + _addDependenciesInput(additionalAllowedTypes = 0) { + this.registerInput("dependencies", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + const dependencies = this.getInputByName("dependencies"); + dependencies.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | + NodeRenderGraphBlockConnectionPointTypes.ResourceContainer | + NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator | + additionalAllowedTypes); + return dependencies; + } + _buildBlock(_state) { + // Empty. Must be defined by child nodes + } + _customBuildStep(_state) { + // Must be implemented by children + } + _propagateInputValueToOutput(inputConnectionPoint, outputConnectionPoint) { + if (inputConnectionPoint.connectedPoint) { + outputConnectionPoint.value = inputConnectionPoint.connectedPoint.value; + } + } + /** + * Build the current node and generate the vertex data + * @param state defines the current generation state + * @returns true if already built + */ + build(state) { + if (this._buildId === state.buildId) { + return true; + } + this._buildId = state.buildId; + // Check if "parent" blocks are compiled + for (const input of this._inputs) { + if (!input.connectedPoint) { + if (!input.isOptional) { + // Emit a warning + state._notConnectedNonOptionalInputs.push(input); + } + continue; + } + const block = input.connectedPoint.ownerBlock; + if (block && block !== this) { + block.build(state); + } + } + this._customBuildStep(state); + // Logs + if (state.verbose) { + Logger.Log(`Building ${this.name} [${this.getClassName()}]`); + } + if (this._frameGraphTask) { + this._frameGraphTask.name = this.name; + } + this._buildBlock(state); + if (this._frameGraphTask) { + this._frameGraphTask.dependencies = undefined; + const dependenciesConnectedPoint = this.getInputByName("dependencies")?.connectedPoint; + if (dependenciesConnectedPoint) { + if (dependenciesConnectedPoint.type === NodeRenderGraphBlockConnectionPointTypes.ResourceContainer) { + const container = dependenciesConnectedPoint.ownerBlock; + for (let i = 0; i < container.inputs.length; i++) { + const input = container.inputs[i]; + if (input.connectedPoint && input.connectedPoint.value !== undefined && NodeRenderGraphConnectionPoint.IsTextureHandle(input.connectedPoint.value)) { + this._frameGraphTask.dependencies = this._frameGraphTask.dependencies || new Set(); + this._frameGraphTask.dependencies.add(input.connectedPoint.value); + } + } + } + else if (NodeRenderGraphConnectionPoint.IsTextureHandle(dependenciesConnectedPoint.value)) { + this._frameGraphTask.dependencies = this._frameGraphTask.dependencies || new Set(); + this._frameGraphTask.dependencies.add(dependenciesConnectedPoint.value); + } + } + this._frameGraph.addTask(this._frameGraphTask); + } + this.onBuildObservable.notifyObservers(this); + return false; + } + _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) { + if (looseCoupling) { + this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0]; + } + else { + this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1]; + this._inputs[inputIndex0]._isMainLinkSource = true; + } + this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0]; + } + /** + * Initialize the block and prepare the context for build + */ + initialize() { + // Do nothing + } + /** + * Lets the block try to connect some inputs automatically + */ + autoConfigure() { + // Do nothing + } + /** + * Find an input by its name + * @param name defines the name of the input to look for + * @returns the input or null if not found + */ + getInputByName(name) { + const filter = this._inputs.filter((e) => e.name === name); + if (filter.length) { + return filter[0]; + } + return null; + } + /** + * Find an output by its name + * @param name defines the name of the output to look for + * @returns the output or null if not found + */ + getOutputByName(name) { + const filter = this._outputs.filter((e) => e.name === name); + if (filter.length) { + return filter[0]; + } + return null; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = {}; + serializationObject.customType = "BABYLON." + this.getClassName(); + serializationObject.id = this.uniqueId; + serializationObject.name = this.name; + serializationObject.visibleOnFrame = this.visibleOnFrame; + serializationObject.disabled = this.disabled; + if (this._additionalConstructionParameters) { + serializationObject.additionalConstructionParameters = this._additionalConstructionParameters; + } + serializationObject.inputs = []; + serializationObject.outputs = []; + for (const input of this.inputs) { + serializationObject.inputs.push(input.serialize()); + } + for (const output of this.outputs) { + serializationObject.outputs.push(output.serialize(false)); + } + return serializationObject; + } + /** + * @internal + */ + _deserialize(serializationObject) { + this._name = serializationObject.name; + this.comments = serializationObject.comments; + this.visibleOnFrame = serializationObject.visibleOnFrame; + this.disabled = serializationObject.disabled; + this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject); + } + _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) { + const serializedInputs = serializationObject.inputs; + const serializedOutputs = serializationObject.outputs; + if (serializedInputs) { + serializedInputs.forEach((port) => { + const input = this.inputs.find((i) => i.name === port.name); + if (!input) { + return; + } + if (port.displayName) { + input.displayName = port.displayName; + } + if (port.isExposedOnFrame) { + input.isExposedOnFrame = port.isExposedOnFrame; + input.exposedPortPosition = port.exposedPortPosition; + } + }); + } + if (serializedOutputs) { + serializedOutputs.forEach((port, i) => { + if (port.displayName) { + this.outputs[i].displayName = port.displayName; + } + if (port.isExposedOnFrame) { + this.outputs[i].isExposedOnFrame = port.isExposedOnFrame; + this.outputs[i].exposedPortPosition = port.exposedPortPosition; + } + }); + } + } + _dumpPropertiesCode() { + const variableName = this._codeVariableName; + return `${variableName}.visibleOnFrame = ${this.visibleOnFrame};\n${variableName}.disabled = ${this.disabled};\n`; + } + /** + * @internal + */ + _dumpCodeForOutputConnections(alreadyDumped) { + let codeString = ""; + if (alreadyDumped.indexOf(this) !== -1) { + return codeString; + } + alreadyDumped.push(this); + for (const input of this.inputs) { + if (!input.isConnected) { + continue; + } + const connectedOutput = input.connectedPoint; + const connectedBlock = connectedOutput.ownerBlock; + codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped); + codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});\n`; + } + return codeString; + } + /** + * @internal + */ + _dumpCode(uniqueNames, alreadyDumped) { + alreadyDumped.push(this); + // Get unique name + const nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, ""); + this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`; + if (uniqueNames.indexOf(this._codeVariableName) !== -1) { + let index = 0; + do { + index++; + this._codeVariableName = nameAsVariableName + index; + } while (uniqueNames.indexOf(this._codeVariableName) !== -1); + } + uniqueNames.push(this._codeVariableName); + // Declaration + let codeString = `\n// ${this.getClassName()}\n`; + if (this.comments) { + codeString += `// ${this.comments}\n`; + } + const className = this.getClassName(); + if (className === "RenderGraphInputBlock") { + const block = this; + const blockType = block.type; + codeString += `var ${this._codeVariableName} = new BABYLON.NodeRenderGraphInputBlock("${this.name}", nodeRenderGraph.frameGraph, scene, BABYLON.NodeRenderGraphBlockConnectionPointTypes.${NodeRenderGraphBlockConnectionPointTypes[blockType]});\n`; + } + else { + if (this._additionalConstructionParameters) { + codeString += `var ${this._codeVariableName} = new BABYLON.${className}("${this.name}", nodeRenderGraph.frameGraph, scene, ...${JSON.stringify(this._additionalConstructionParameters)});\n`; + } + else { + codeString += `var ${this._codeVariableName} = new BABYLON.${className}("${this.name}", nodeRenderGraph.frameGraph, scene);\n`; + } + } + // Properties + codeString += this._dumpPropertiesCode() + "\n"; + // Inputs + for (const input of this.inputs) { + if (!input.isConnected) { + continue; + } + const connectedOutput = input.connectedPoint; + const connectedBlock = connectedOutput.ownerBlock; + if (alreadyDumped.indexOf(connectedBlock) === -1) { + codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped); + } + } + // Outputs + for (const output of this.outputs) { + if (!output.hasEndpoints) { + continue; + } + for (const endpoint of output.endpoints) { + const connectedBlock = endpoint.ownerBlock; + if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) { + codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped); + } + } + } + return codeString; + } + /** + * Clone the current block to a new identical block + * @returns a copy of the current block + */ + clone() { + const serializationObject = this.serialize(); + const blockType = GetClass(serializationObject.customType); + if (blockType) { + const additionalConstructionParameters = serializationObject.additionalConstructionParameters; + const block = additionalConstructionParameters + ? new blockType("", this._frameGraph, this._scene, ...additionalConstructionParameters) + : new blockType("", this._frameGraph, this._scene); + block._deserialize(serializationObject); + return block; + } + return null; + } + /** + * Release resources + */ + dispose() { + for (const input of this.inputs) { + input.dispose(); + } + for (const output of this.outputs) { + output.dispose(); + } + this._frameGraphTask?.dispose(); + this._frameGraphTask = undefined; + this.onBuildObservable.clear(); + } +} +__decorate([ + serialize("comment") +], NodeRenderGraphBlock.prototype, "comments", void 0); + +/** + * Represents a texture handle for the backbuffer color texture. + */ +const backbufferColorTextureHandle = 0; +/** + * Represents a texture handle for the backbuffer depth/stencil texture. + */ +const backbufferDepthStencilTextureHandle = 1; + +/** + * @internal + */ +class FrameGraphPass { + constructor(name, _parentTask, _context) { + this.name = name; + this._parentTask = _parentTask; + this._context = _context; + this.disabled = false; + } + setExecuteFunc(func) { + this._executeFunc = func; + } + _execute() { + if (!this.disabled) { + this._executeFunc(this._context); + } + } + _isValid() { + return this._executeFunc !== undefined ? null : "Execute function is not set (call setExecuteFunc to set it)"; + } +} + +/** + * Cull pass used to filter objects that are not visible. + */ +class FrameGraphCullPass extends FrameGraphPass { + /** + * Checks if a pass is a cull pass. + * @param pass The pass to check. + * @returns True if the pass is a cull pass, else false. + */ + static IsCullPass(pass) { + return pass.setObjectList !== undefined; + } + /** + * Gets the object list used by the cull pass. + */ + get objectList() { + return this._objectList; + } + /** + * Sets the object list to use for culling. + * @param objectList The object list to use for culling. + */ + setObjectList(objectList) { + this._objectList = objectList; + } + /** @internal */ + constructor(name, parentTask, context, engine) { + super(name, parentTask, context); + this._engine = engine; + } + /** @internal */ + _isValid() { + const errMsg = super._isValid(); + return errMsg ? errMsg : this._objectList !== undefined ? null : "Object list is not set (call setObjectList to set it)"; + } +} + +/** + * Render pass used to render objects. + */ +class FrameGraphRenderPass extends FrameGraphPass { + /** + * Checks if a pass is a render pass. + * @param pass The pass to check. + * @returns True if the pass is a render pass, else false. + */ + static IsRenderPass(pass) { + return pass.setRenderTarget !== undefined; + } + /** + * Gets the render target(s) used by the render pass. + */ + get renderTarget() { + return this._renderTarget; + } + /** + * Gets the render target depth used by the render pass. + */ + get renderTargetDepth() { + return this._renderTargetDepth; + } + /** @internal */ + constructor(name, parentTask, context, engine) { + super(name, parentTask, context); + this._dependencies = new Set(); + this._engine = engine; + } + /** + * Sets the render target(s) to use for rendering. + * @param renderTargetHandle The render target to use for rendering, or an array of render targets to use for multi render target rendering. + */ + setRenderTarget(renderTargetHandle) { + this._renderTarget = renderTargetHandle; + } + /** + * Sets the render target depth to use for rendering. + * @param renderTargetHandle The render target depth to use for rendering. + */ + setRenderTargetDepth(renderTargetHandle) { + this._renderTargetDepth = renderTargetHandle; + } + /** + * Adds dependencies to the render pass. + * @param dependencies The dependencies to add. + */ + addDependencies(dependencies) { + if (Array.isArray(dependencies)) { + for (const dependency of dependencies) { + this._dependencies.add(dependency); + } + } + else { + this._dependencies.add(dependencies); + } + } + /** + * Collects the dependencies of the render pass. + * @param dependencies The set of dependencies to update. + */ + collectDependencies(dependencies) { + const iterator = this._dependencies.keys(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + dependencies.add(key.value); + } + if (this._renderTarget) { + if (Array.isArray(this._renderTarget)) { + for (const handle of this._renderTarget) { + if (handle !== undefined) { + dependencies.add(handle); + } + } + } + else { + dependencies.add(this._renderTarget); + } + } + if (this._renderTargetDepth) { + dependencies.add(this._renderTargetDepth); + } + } + /** @internal */ + _execute() { + this._frameGraphRenderTarget = this._frameGraphRenderTarget || this._context.createRenderTarget(this.name, this._renderTarget, this._renderTargetDepth); + this._context.bindRenderTarget(this._frameGraphRenderTarget, `frame graph render pass - ${this.name}`); + super._execute(); + this._context._flushDebugMessages(); + } + /** @internal */ + _isValid() { + const errMsg = super._isValid(); + return errMsg + ? errMsg + : this._renderTarget !== undefined || this.renderTargetDepth !== undefined + ? null + : "Render target and render target depth cannot both be undefined."; + } +} + +/** + * Represents a task in a frame graph. + * @experimental + */ +class FrameGraphTask { + /** + * The name of the task. + */ + get name() { + return this._name; + } + set name(value) { + this._name = value; + } + /** + * Whether the task is disabled. + */ + get disabled() { + return this._disabled; + } + set disabled(value) { + this._disabled = value; + } + /** + * Gets the render passes of the task. + */ + get passes() { + return this._passes; + } + /** + * Gets the disabled render passes of the task. + */ + get passesDisabled() { + return this._passesDisabled; + } + /** + * Checks if the task is ready to be executed. + * @returns True if the task is ready to be executed, else false. + */ + isReady() { + return true; + } + /** + * Disposes of the task. + */ + dispose() { + this._reset(); + this.onTexturesAllocatedObservable.clear(); + } + /** + * Constructs a new frame graph task. + * @param name The name of the task. + * @param frameGraph The frame graph this task is associated with. + */ + constructor(name, frameGraph) { + this._passes = []; + this._passesDisabled = []; + this._disabled = false; + /** + * An observable that is triggered after the textures have been allocated. + */ + this.onTexturesAllocatedObservable = new Observable(); + this.name = name; + this._frameGraph = frameGraph; + this._reset(); + } + /** @internal */ + _reset() { + this._passes.length = 0; + this._passesDisabled.length = 0; + } + /** @internal */ + _addPass(pass, disabled) { + if (disabled) { + this._passesDisabled.push(pass); + } + else { + this._passes.push(pass); + } + } + /** @internal */ + _checkTask() { + let outputTexture = null; + let outputDepthTexture = null; + let outputObjectList; + for (const pass of this._passes) { + const errMsg = pass._isValid(); + if (errMsg) { + throw new Error(`Pass "${pass.name}" is not valid. ${errMsg}`); + } + if (FrameGraphRenderPass.IsRenderPass(pass)) { + const handles = Array.isArray(pass.renderTarget) ? pass.renderTarget : [pass.renderTarget]; + outputTexture = []; + for (const handle of handles) { + if (handle !== undefined) { + outputTexture.push(this._frameGraph.textureManager.getTextureFromHandle(handle)); + } + } + outputDepthTexture = pass.renderTargetDepth !== undefined ? this._frameGraph.textureManager.getTextureFromHandle(pass.renderTargetDepth) : null; + } + else if (FrameGraphCullPass.IsCullPass(pass)) { + outputObjectList = pass.objectList; + } + } + let disabledOutputTexture = null; + let disabledOutputTextureHandle = []; + let disabledOutputDepthTexture = null; + let disabledOutputObjectList; + for (const pass of this._passesDisabled) { + const errMsg = pass._isValid(); + if (errMsg) { + throw new Error(`Pass "${pass.name}" is not valid. ${errMsg}`); + } + if (FrameGraphRenderPass.IsRenderPass(pass)) { + const handles = Array.isArray(pass.renderTarget) ? pass.renderTarget : [pass.renderTarget]; + disabledOutputTexture = []; + for (const handle of handles) { + if (handle !== undefined) { + disabledOutputTexture.push(this._frameGraph.textureManager.getTextureFromHandle(handle)); + } + } + disabledOutputTextureHandle = handles; + disabledOutputDepthTexture = pass.renderTargetDepth !== undefined ? this._frameGraph.textureManager.getTextureFromHandle(pass.renderTargetDepth) : null; + } + else if (FrameGraphCullPass.IsCullPass(pass)) { + disabledOutputObjectList = pass.objectList; + } + } + if (this._passesDisabled.length > 0) { + if (!this._checkSameRenderTarget(outputTexture, disabledOutputTexture)) { + let ok = true; + for (const handle of disabledOutputTextureHandle) { + if (handle !== undefined && !this._frameGraph.textureManager.isHistoryTexture(handle)) { + ok = false; + break; + } + } + if (!ok) { + throw new Error(`The output texture of the task "${this.name}" is different when it is enabled or disabled.`); + } + } + if (outputDepthTexture !== disabledOutputDepthTexture) { + throw new Error(`The output depth texture of the task "${this.name}" is different when it is enabled or disabled.`); + } + if (outputObjectList !== disabledOutputObjectList) { + throw new Error(`The output object list of the task "${this.name}" is different when it is enabled or disabled.`); + } + } + } + /** @internal */ + _getPasses() { + return this.disabled && this._passesDisabled.length > 0 ? this._passesDisabled : this._passes; + } + _checkSameRenderTarget(src, dst) { + if (src === null || dst === null) { + return src === dst; + } + if (src.length !== dst.length) { + return false; + } + for (let i = 0; i < src.length; i++) { + if (src[i] !== dst[i]) { + return false; + } + } + return true; + } +} + +/** + * Task which copies a texture to the backbuffer color texture. + */ +class FrameGraphCopyToBackbufferColorTask extends FrameGraphTask { + record() { + if (this.sourceTexture === undefined) { + throw new Error(`FrameGraphCopyToBackbufferColorTask "${this.name}": sourceTexture is required`); + } + const pass = this._frameGraph.addRenderPass(this.name); + pass.addDependencies(this.sourceTexture); + pass.setRenderTarget(backbufferColorTextureHandle); + pass.setExecuteFunc((context) => { + if (!context.isBackbuffer(this.sourceTexture)) { + context.copyTexture(this.sourceTexture); + } + }); + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.setRenderTarget(backbufferColorTextureHandle); + passDisabled.setExecuteFunc((_context) => { }); + } +} + +/** + * Block used to generate the final graph + */ +class NodeRenderGraphOutputBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphOutputBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._isUnique = true; + this.registerInput("texture", NodeRenderGraphBlockConnectionPointTypes.Texture); + this.texture.addAcceptedConnectionPointTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAll); + this._frameGraphTask = new FrameGraphCopyToBackbufferColorTask(name, frameGraph); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphOutputBlock"; + } + /** + * Gets the texture input component + */ + get texture() { + return this._inputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this._frameGraphTask.name = this.name; + const textureConnectedPoint = this.texture.connectedPoint; + if (textureConnectedPoint) { + this._frameGraphTask.sourceTexture = textureConnectedPoint.value; + } + } +} +RegisterClass("BABYLON.NodeRenderGraphOutputBlock", NodeRenderGraphOutputBlock); + +/** + * Conversion modes available when copying a texture into another one + */ +var ConversionMode; +(function (ConversionMode) { + ConversionMode[ConversionMode["None"] = 0] = "None"; + ConversionMode[ConversionMode["ToLinearSpace"] = 1] = "ToLinearSpace"; + ConversionMode[ConversionMode["ToGammaSpace"] = 2] = "ToGammaSpace"; +})(ConversionMode || (ConversionMode = {})); +/** + * Class used for fast copy from one texture to another + */ +class CopyTextureToTexture { + /** + * Gets the shader language + */ + get shaderLanguage() { + return this._shaderLanguage; + } + _textureIsInternal(texture) { + return texture.getInternalTexture === undefined; + } + /** + * Constructs a new instance of the class + * @param engine The engine to use for the copy + * @param isDepthTexture True means that we should write (using gl_FragDepth) into the depth texture attached to the destination (default: false) + */ + constructor(engine, isDepthTexture = false) { + /** Shader language used */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._shadersLoaded = false; + this._engine = engine; + this._isDepthTexture = isDepthTexture; + this._renderer = new EffectRenderer(engine); + this._initShaderSourceAsync(isDepthTexture); + } + async _initShaderSourceAsync(isDepthTexture) { + const engine = this._engine; + if (engine.isWebGPU) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + await Promise.resolve().then(() => copyTextureToTexture_fragment); + } + else { + await Promise.resolve().then(() => copyTextureToTexture_fragment$1); + } + this._shadersLoaded = true; + this._effectWrapper = new EffectWrapper({ + engine: engine, + name: "CopyTextureToTexture", + fragmentShader: "copyTextureToTexture", + useShaderStore: true, + uniformNames: ["conversion"], + samplerNames: ["textureSampler"], + defines: isDepthTexture ? ["#define DEPTH_TEXTURE"] : [], + shaderLanguage: this._shaderLanguage, + }); + this._effectWrapper.onApplyObservable.add(() => { + if (isDepthTexture) { + engine.setState(false); + engine.setDepthBuffer(true); + engine.depthCullingState.depthMask = true; + engine.depthCullingState.depthFunc = 519; + } + else { + engine.depthCullingState.depthMask = false; + // other states are already set by EffectRenderer.applyEffectWrapper + } + if (this._textureIsInternal(this._source)) { + this._effectWrapper.effect._bindTexture("textureSampler", this._source); + } + else { + this._effectWrapper.effect.setTexture("textureSampler", this._source); + } + this._effectWrapper.effect.setFloat("conversion", this._conversion); + }); + } + /** + * Indicates if the effect is ready to be used for the copy + * @returns true if "copy" can be called without delay, else false + */ + isReady() { + return this._shadersLoaded && !!this._effectWrapper?.effect?.isReady(); + } + /** + * Copy one texture into another + * @param source The source texture + * @param destination The destination texture. If null, copy the source to the currently bound framebuffer + * @param conversion The conversion mode that should be applied when copying + * @returns + */ + copy(source, destination = null, conversion = 0 /* ConversionMode.None */) { + if (!this.isReady()) { + return false; + } + this._source = source; + this._conversion = conversion; + const engineDepthFunc = this._engine.getDepthFunction(); + const engineDepthMask = this._engine.getDepthWrite(); // for some reasons, depthWrite is not restored by EffectRenderer.restoreStates + this._renderer.render(this._effectWrapper, destination); + this._engine.setDepthWrite(engineDepthMask); + if (this._isDepthTexture && engineDepthFunc) { + this._engine.setDepthFunction(engineDepthFunc); + } + return true; + } + /** + * Releases all the resources used by the class + */ + dispose() { + this._effectWrapper?.dispose(); + this._renderer.dispose(); + } +} + +/** + * Base class for frame graph context. + */ +class FrameGraphContext { +} + +/** + * Frame graph context used render passes. + * @experimental + */ +class FrameGraphRenderContext extends FrameGraphContext { + static _IsObjectRenderer(value) { + return value.initRender !== undefined; + } + /** @internal */ + constructor(_engine, _textureManager, _scene) { + super(); + this._engine = _engine; + this._textureManager = _textureManager; + this._scene = _scene; + this._debugMessageHasBeenPushed = false; + this._renderTargetIsBound = true; + this._effectRenderer = new EffectRenderer(this._engine); + this._copyTexture = new CopyTextureToTexture(this._engine); + } + /** + * Checks whether a texture handle points to the backbuffer's color or depth texture + * @param handle The handle to check + * @returns True if the handle points to the backbuffer's color or depth texture, otherwise false + */ + isBackbuffer(handle) { + return this._textureManager.isBackbuffer(handle); + } + /** + * Checks whether a texture handle points to the backbuffer's color texture + * @param handle The handle to check + * @returns True if the handle points to the backbuffer's color texture, otherwise false + */ + isBackbufferColor(handle) { + return this._textureManager.isBackbufferColor(handle); + } + /** + * Checks whether a texture handle points to the backbuffer's depth texture + * @param handle The handle to check + * @returns True if the handle points to the backbuffer's depth texture, otherwise false + */ + isBackbufferDepthStencil(handle) { + return this._textureManager.isBackbufferDepthStencil(handle); + } + /** + * Creates a (frame graph) render target wrapper + * Note that renderTargets or renderTargetDepth can be undefined, but not both at the same time! + * @param name Name of the render target wrapper + * @param renderTargets Render target handles (textures) to use + * @param renderTargetDepth Render target depth handle (texture) to use + * @returns The created render target wrapper + */ + createRenderTarget(name, renderTargets, renderTargetDepth) { + return this._textureManager.createRenderTarget(name, renderTargets, renderTargetDepth); + } + /** + * Clears the current render buffer or the current render target (if any is set up) + * @param color Defines the color to use + * @param backBuffer Defines if the back buffer must be cleared + * @param depth Defines if the depth buffer must be cleared + * @param stencil Defines if the stencil buffer must be cleared + */ + clear(color, backBuffer, depth, stencil) { + this._applyRenderTarget(); + this._engine.clear(color, backBuffer, depth, stencil); + } + /** + * Clears the color attachments of the current render target + * @param color Defines the color to use + * @param attachments The attachments to clear + */ + clearColorAttachments(color, attachments) { + this._applyRenderTarget(); + this._engine.bindAttachments(attachments); + this._engine.clear(color, true, false, false); + } + /** + * Binds the attachments to the current render target + * @param attachments The attachments to bind + */ + bindAttachments(attachments) { + this._applyRenderTarget(); + this._engine.bindAttachments(attachments); + } + /** + * Generates mipmaps for the current render target + */ + generateMipMaps() { + if (this._currentRenderTarget?.renderTargetWrapper === undefined) { + return; + } + if (this._renderTargetIsBound && this._engine._currentRenderTarget) { + // we can't generate the mipmaps if the render target is bound + this._flushDebugMessages(); + this._engine.unBindFramebuffer(this._engine._currentRenderTarget); + this._renderTargetIsBound = false; + } + const textures = this._currentRenderTarget.renderTargetWrapper.textures; + if (textures) { + for (const texture of textures) { + this._engine.generateMipmaps(texture); + } + } + } + /** + * Sets the texture sampling mode for a given texture handle + * @param handle Handle of the texture to set the sampling mode for + * @param samplingMode Sampling mode to set + */ + setTextureSamplingMode(handle, samplingMode) { + const internalTexture = this._textureManager.getTextureFromHandle(handle); + if (internalTexture && internalTexture.samplingMode !== samplingMode) { + this._engine.updateTextureSamplingMode(samplingMode, internalTexture); + } + } + /** + * Binds a texture handle to a given effect (resolves the handle to a texture and binds it to the effect) + * @param effect The effect to bind the texture to + * @param name The name of the texture in the effect + * @param handle The handle of the texture to bind + */ + bindTextureHandle(effect, name, handle) { + let texture; + const historyEntry = this._textureManager._historyTextures.get(handle); + if (historyEntry) { + texture = historyEntry.textures[historyEntry.index]; // texture we write to in this frame + if (this._currentRenderTarget !== undefined && + this._currentRenderTarget.renderTargetWrapper !== undefined && + this._currentRenderTarget.renderTargetWrapper.textures.includes(texture)) { + // If the current render target renders to the history write texture, we bind the read texture instead + texture = historyEntry.textures[historyEntry.index ^ 1]; + } + } + else { + texture = this._textureManager._textures.get(handle).texture; + } + effect._bindTexture(name, texture); + } + /** + * Saves the current depth states (depth testing and depth writing) + */ + saveDepthStates() { + this._depthTest = this._engine.getDepthBuffer(); + this._depthWrite = this._engine.getDepthWrite(); + } + /** + * Restores the depth states saved by saveDepthStates + */ + restoreDepthStates() { + this._engine.setDepthBuffer(this._depthTest); + this._engine.setDepthWrite(this._depthWrite); + } + /** + * Sets the depth states for the current render target + * @param depthTest If true, depth testing is enabled + * @param depthWrite If true, depth writing is enabled + */ + setDepthStates(depthTest, depthWrite) { + this._engine.setDepthBuffer(depthTest); + this._engine.setDepthWrite(depthWrite); + } + /** + * Applies a full-screen effect to the current render target + * @param drawWrapper The draw wrapper containing the effect to apply + * @param customBindings The custom bindings to use when applying the effect (optional) + * @returns True if the effect was applied, otherwise false (effect not ready) + */ + applyFullScreenEffect(drawWrapper, customBindings) { + if (!drawWrapper.effect?.isReady()) { + return false; + } + this._applyRenderTarget(); + const engineDepthMask = this._engine.getDepthWrite(); // for some reasons, depthWrite is not restored by EffectRenderer.restoreStates + this._effectRenderer.saveStates(); + this._effectRenderer.setViewport(); + this._engine.enableEffect(drawWrapper); + this._engine.setState(false); + this._engine.setDepthBuffer(false); + this._engine.setDepthWrite(false); + this._effectRenderer.bindBuffers(drawWrapper.effect); + customBindings?.(); + this._effectRenderer.draw(); + this._effectRenderer.restoreStates(); + this._engine.setDepthWrite(engineDepthMask); + this._engine.setAlphaMode(0); + return true; + } + /** + * Copies a texture to the current render target + * @param sourceTexture The source texture to copy from + * @param forceCopyToBackbuffer If true, the copy will be done to the back buffer regardless of the current render target + */ + copyTexture(sourceTexture, forceCopyToBackbuffer = false) { + if (forceCopyToBackbuffer) { + this.bindRenderTarget(); + } + this._applyRenderTarget(); + this._copyTexture.copy(this._textureManager.getTextureFromHandle(sourceTexture)); + } + /** + * Renders a RenderTargetTexture or a layer + * @param object The RenderTargetTexture/Layer to render + * @param viewportWidth The width of the viewport (optional for Layer, but mandatory for ObjectRenderer) + * @param viewportHeight The height of the viewport (optional for Layer, but mandatory for ObjectRenderer) + */ + render(object, viewportWidth, viewportHeight) { + if (FrameGraphRenderContext._IsObjectRenderer(object)) { + if (object.shouldRender()) { + this._scene.incrementRenderId(); + this._scene.resetCachedMaterial(); + this._applyRenderTarget(); + object.prepareRenderList(); + object.initRender(viewportWidth, viewportHeight); + object.render(); + object.finishRender(); + } + } + else { + this._applyRenderTarget(); + object.render(); + } + } + /** + * Binds a render target texture so that upcoming draw calls will render to it + * Note: it is a lazy operation, so the render target will only be bound when needed. This way, it is possible to call + * this method several times with different render targets without incurring the cost of binding if no draw calls are made + * @param renderTarget The handle of the render target texture to bind (default: undefined, meaning "back buffer"). Pass an array for MRT rendering. + * @param debugMessage Optional debug message to display when the render target is bound (visible in PIX, for example) + */ + bindRenderTarget(renderTarget, debugMessage) { + if ((renderTarget?.renderTargetWrapper === undefined && this._currentRenderTarget === undefined) || + (renderTarget && this._currentRenderTarget && renderTarget.equals(this._currentRenderTarget))) { + this._flushDebugMessages(); + if (debugMessage !== undefined) { + this._engine._debugPushGroup?.(debugMessage, 2); + this._debugMessageWhenTargetBound = undefined; + this._debugMessageHasBeenPushed = true; + } + return; + } + this._currentRenderTarget = renderTarget?.renderTargetWrapper === undefined ? undefined : renderTarget; + this._debugMessageWhenTargetBound = debugMessage; + this._renderTargetIsBound = false; + } + /** @internal */ + _flushDebugMessages() { + if (this._debugMessageHasBeenPushed) { + this._engine._debugPopGroup?.(2); + this._debugMessageHasBeenPushed = false; + } + } + /** @internal */ + _applyRenderTarget() { + if (this._renderTargetIsBound) { + return; + } + this._flushDebugMessages(); + const renderTargetWrapper = this._currentRenderTarget?.renderTargetWrapper; + if (renderTargetWrapper === undefined) { + this._engine.restoreDefaultFramebuffer(); + } + else { + if (this._engine._currentRenderTarget) { + this._engine.unBindFramebuffer(this._engine._currentRenderTarget); + } + this._engine.bindFramebuffer(renderTargetWrapper); + } + if (this._debugMessageWhenTargetBound !== undefined) { + this._engine._debugPushGroup?.(this._debugMessageWhenTargetBound, 2); + this._debugMessageWhenTargetBound = undefined; + this._debugMessageHasBeenPushed = true; + } + this._renderTargetIsBound = true; + } + /** @internal */ + _isReady() { + return this._copyTexture.isReady(); + } + /** @internal */ + _dispose() { + this._effectRenderer.dispose(); + this._copyTexture.dispose(); + } +} + +/** + * Check if a TextureSize is an object + * @param size The TextureSize to check + * @returns True if the TextureSize is an object + */ +function textureSizeIsObject(size) { + // eslint-disable-next-line jsdoc/require-jsdoc + return size.width !== undefined; +} +/** + * Get the width/height dimensions from a TextureSize + * @param size The TextureSize to get the dimensions from + * @returns The width and height as an object + */ +function getDimensionsFromTextureSize(size) { + if (textureSizeIsObject(size)) { + return { width: size.width, height: size.height }; + } + return { width: size, height: size }; +} + +/** + * @internal + * @experimental + */ +class FrameGraphRenderTarget { + constructor(name, textureManager, renderTargets, renderTargetDepth) { + this._isBackBuffer = false; + this.name = name; + this._textureManager = textureManager; + this._renderTargets = renderTargets === undefined ? undefined : Array.isArray(renderTargets) ? renderTargets : [renderTargets]; + this._renderTargetDepth = renderTargetDepth; + } + get renderTargetWrapper() { + if (this._isBackBuffer) { + return undefined; + } + if (!this._renderTargetWrapper) { + const engine = this._textureManager.engine; + // _renderTargets and _renderTargetDepth cannot both be undefined + const textureHandle = this._renderTargets === undefined ? this._renderTargetDepth : this._renderTargets[0]; + if (this._textureManager.isBackbuffer(textureHandle)) { + this._isBackBuffer = true; + return undefined; + } + const textureDescription = this._textureManager.getTextureDescription(textureHandle); + const creationOptionsForTexture = { + textureCount: this._renderTargets?.length ?? 0, + generateDepthBuffer: false, + label: this.name, + samples: textureDescription.options.samples ?? 1, + dontCreateTextures: true, + }; + this._renderTargetWrapper = engine.createMultipleRenderTarget(textureDescription.size, creationOptionsForTexture, true); + for (let i = 0; i < creationOptionsForTexture.textureCount; i++) { + const handle = this._renderTargets[i]; + const texture = this._textureManager.getTextureFromHandle(handle); + if (!texture) { + throw new Error(`FrameGraphRenderTarget.renderTargetWrapper: Failed to get texture from handle. handle: ${handle}, name: ${this.name}, index: ${i}, renderTargets: ${this._renderTargets}`); + } + this._renderTargetWrapper.setTexture(texture, i, false); + } + if (this._renderTargetDepth !== undefined) { + this._renderTargetWrapper.setDepthStencilTexture(this._textureManager.getTextureFromHandle(this._renderTargetDepth), false); + } + } + return this._renderTargetWrapper; + } + equals(other) { + const src = this._renderTargets; + const dst = other._renderTargets; + if (src !== undefined && dst !== undefined) { + if (src.length !== dst.length) { + return false; + } + for (let i = 0; i < src.length; i++) { + if (src[i] !== dst[i]) { + return false; + } + } + } + else if ((src === undefined && dst !== undefined) || (src !== undefined && dst === undefined)) { + return false; + } + return this._renderTargetDepth === other._renderTargetDepth; + } +} + +var FrameGraphTextureNamespace; +(function (FrameGraphTextureNamespace) { + FrameGraphTextureNamespace[FrameGraphTextureNamespace["Task"] = 0] = "Task"; + FrameGraphTextureNamespace[FrameGraphTextureNamespace["Graph"] = 1] = "Graph"; + FrameGraphTextureNamespace[FrameGraphTextureNamespace["External"] = 2] = "External"; +})(FrameGraphTextureNamespace || (FrameGraphTextureNamespace = {})); +/** + * Manages the textures used by a frame graph + * @experimental + */ +class FrameGraphTextureManager { + /** + * Constructs a new instance of the texture manager + * @param engine The engine to use + * @param _debugTextures If true, debug textures will be created so that they are visible in the inspector + * @param _scene The scene the manager belongs to + */ + constructor(engine, _debugTextures = false, _scene) { + this.engine = engine; + this._debugTextures = _debugTextures; + this._scene = _scene; + /** @internal */ + this._textures = new Map(); + /** @internal */ + this._historyTextures = new Map(); + /** @internal */ + this._isRecordingTask = false; + /** + * Gets or sets a boolean indicating if debug logs should be shown when applying texture allocation optimization (default: false) + */ + this.showDebugLogsForTextureAllcationOptimization = false; + this._addSystemTextures(); + } + /** + * Checks if a handle is a backbuffer handle (color or depth/stencil) + * @param handle The handle to check + * @returns True if the handle is a backbuffer handle + */ + isBackbuffer(handle) { + if (handle === backbufferColorTextureHandle || handle === backbufferDepthStencilTextureHandle) { + return true; + } + const textureEntry = this._textures.get(handle); + if (!textureEntry) { + return false; + } + return textureEntry.refHandle === backbufferColorTextureHandle || textureEntry.refHandle === backbufferDepthStencilTextureHandle; + } + /** + * Checks if a handle is a backbuffer color handle + * @param handle The handle to check + * @returns True if the handle is a backbuffer color handle + */ + isBackbufferColor(handle) { + if (handle === backbufferColorTextureHandle) { + return true; + } + const textureEntry = this._textures.get(handle); + if (!textureEntry) { + return false; + } + return textureEntry.refHandle === backbufferColorTextureHandle; + } + /** + * Checks if a handle is a backbuffer depth/stencil handle + * @param handle The handle to check + * @returns True if the handle is a backbuffer depth/stencil handle + */ + isBackbufferDepthStencil(handle) { + if (handle === backbufferDepthStencilTextureHandle) { + return true; + } + const textureEntry = this._textures.get(handle); + if (!textureEntry) { + return false; + } + return textureEntry.refHandle === backbufferDepthStencilTextureHandle; + } + /** + * Checks if a handle is a history texture (or points to a history texture, for a dangling handle) + * @param handle The handle to check + * @returns True if the handle is a history texture, otherwise false + */ + isHistoryTexture(handle) { + const entry = this._textures.get(handle); + if (!entry) { + return false; + } + handle = entry.refHandle ?? handle; + return this._historyTextures.has(handle); + } + /** + * Gets the creation options of a texture + * @param handle Handle of the texture + * @returns The creation options of the texture + */ + getTextureCreationOptions(handle) { + const entry = this._textures.get(handle); + const creationOptions = entry.creationOptions; + return { + size: textureSizeIsObject(creationOptions.size) ? { ...creationOptions.size } : creationOptions.size, + sizeIsPercentage: creationOptions.sizeIsPercentage, + options: FrameGraphTextureManager.CloneTextureOptions(creationOptions.options, entry.textureIndex), + isHistoryTexture: creationOptions.isHistoryTexture, + }; + } + /** + * Gets the description of a texture + * @param handle Handle of the texture + * @returns The description of the texture + */ + getTextureDescription(handle) { + const creationOptions = this.getTextureCreationOptions(handle); + const size = !creationOptions.sizeIsPercentage + ? textureSizeIsObject(creationOptions.size) + ? creationOptions.size + : { width: creationOptions.size, height: creationOptions.size } + : this.getAbsoluteDimensions(creationOptions.size); + return { + size, + options: creationOptions.options, + }; + } + /** + * Gets a texture handle or creates a new texture if the handle is not provided. + * If handle is not provided, newTextureName and creationOptions must be provided. + * @param handle If provided, will simply return the handle + * @param newTextureName Name of the new texture to create + * @param creationOptions Options to use when creating the new texture + * @returns The handle to the texture. + */ + getTextureHandleOrCreateTexture(handle, newTextureName, creationOptions) { + if (handle === undefined) { + if (newTextureName === undefined || creationOptions === undefined) { + throw new Error("getTextureHandleOrCreateTexture: Either handle or newTextureName and creationOptions must be provided."); + } + return this.createRenderTargetTexture(newTextureName, creationOptions); + } + return handle; + } + /** + * Gets a texture from a handle. + * Note that if the texture is a history texture, the read texture for the current frame will be returned. + * @param handle The handle of the texture + * @returns The texture or null if not found + */ + getTextureFromHandle(handle) { + const historyEntry = this._historyTextures.get(handle); + if (historyEntry) { + return historyEntry.textures[historyEntry.index ^ 1]; // gets the read texture + } + return this._textures.get(handle).texture; + } + /** + * Imports a texture into the texture manager + * @param name Name of the texture + * @param texture Texture to import + * @param handle Existing handle to use for the texture. If not provided (default), a new handle will be created. + * @returns The handle to the texture + */ + importTexture(name, texture, handle) { + if (handle !== undefined) { + this._freeEntry(handle); + } + const creationOptions = { + size: { width: texture.width, height: texture.height }, + sizeIsPercentage: false, + isHistoryTexture: false, + options: { + createMipMaps: texture.generateMipMaps, + samples: texture.samples, + types: [texture.type], + formats: [texture.format], + useSRGBBuffers: [texture._useSRGBBuffer], + creationFlags: [texture._creationFlags], + labels: texture.label ? [texture.label] : ["imported"], + }, + }; + return this._createHandleForTexture(name, texture, creationOptions, FrameGraphTextureNamespace.External, handle); + } + /** + * Creates a new render target texture + * If multiple textures are described in FrameGraphTextureCreationOptions, the handle of the first texture is returned, handle+1 is the handle of the second texture, etc. + * @param name Name of the texture + * @param creationOptions Options to use when creating the texture + * @param handle Existing handle to use for the texture. If not provided (default), a new handle will be created. + * @returns The handle to the texture + */ + createRenderTargetTexture(name, creationOptions, handle) { + return this._createHandleForTexture(name, null, { + size: textureSizeIsObject(creationOptions.size) ? { ...creationOptions.size } : creationOptions.size, + sizeIsPercentage: creationOptions.sizeIsPercentage, + isHistoryTexture: creationOptions.isHistoryTexture, + options: FrameGraphTextureManager.CloneTextureOptions(creationOptions.options, undefined, true), + }, this._isRecordingTask ? FrameGraphTextureNamespace.Task : FrameGraphTextureNamespace.Graph, handle); + } + /** + * Creates a (frame graph) render target wrapper + * Note that renderTargets or renderTargetDepth can be undefined, but not both at the same time! + * @param name Name of the render target wrapper + * @param renderTargets Render target handles (textures) to use + * @param renderTargetDepth Render target depth handle (texture) to use + * @returns The created render target wrapper + */ + createRenderTarget(name, renderTargets, renderTargetDepth) { + const renderTarget = new FrameGraphRenderTarget(name, this, renderTargets, renderTargetDepth); + const rtw = renderTarget.renderTargetWrapper; + if (rtw !== undefined && renderTargets) { + const handles = Array.isArray(renderTargets) ? renderTargets : [renderTargets]; + for (let i = 0; i < handles.length; i++) { + let handle = handles[i]; + handle = this._textures.get(handle)?.refHandle ?? handle; + const historyEntry = this._historyTextures.get(handle); + if (historyEntry) { + historyEntry.references.push({ renderTargetWrapper: rtw, textureIndex: i }); + rtw.setTexture(historyEntry.textures[historyEntry.index], i, false); + } + } + } + return renderTarget; + } + /** + * Creates a handle which is not associated with any texture. + * Call resolveDanglingHandle to associate the handle with a valid texture handle. + * @returns The dangling handle + */ + createDanglingHandle() { + return FrameGraphTextureManager._Counter++; + } + /** + * Associates a texture with a dangling handle + * @param danglingHandle The dangling handle + * @param handle The handle to associate with the dangling handle (if not provided, a new texture handle will be created, using the newTextureName and creationOptions parameters) + * @param newTextureName The name of the new texture to create (if handle is not provided) + * @param creationOptions The options to use when creating the new texture (if handle is not provided) + */ + resolveDanglingHandle(danglingHandle, handle, newTextureName, creationOptions) { + if (handle === undefined) { + if (newTextureName === undefined || creationOptions === undefined) { + throw new Error("resolveDanglingHandle: Either handle or newTextureName and creationOptions must be provided."); + } + this.createRenderTargetTexture(newTextureName, creationOptions, danglingHandle); + return; + } + const textureEntry = this._textures.get(handle); + if (textureEntry === undefined) { + throw new Error(`resolveDanglingHandle: Handle ${handle} does not exist!`); + } + this._textures.set(danglingHandle, { + texture: textureEntry.texture, + refHandle: handle, + name: textureEntry.name, + creationOptions: { + size: { ...textureEntry.creationOptions.size }, + options: FrameGraphTextureManager.CloneTextureOptions(textureEntry.creationOptions.options), + sizeIsPercentage: textureEntry.creationOptions.sizeIsPercentage, + isHistoryTexture: false, + }, + namespace: textureEntry.namespace, + textureIndex: textureEntry.textureIndex, + }); + } + /** + * Gets the absolute dimensions of a texture. + * @param size The size of the texture. Width and height must be expressed as a percentage of the screen size (100=100%)! + * @param screenWidth The width of the screen (default: the width of the rendering canvas) + * @param screenHeight The height of the screen (default: the height of the rendering canvas) + * @returns The absolute dimensions of the texture + */ + getAbsoluteDimensions(size, screenWidth = this.engine.getRenderWidth(true), screenHeight = this.engine.getRenderHeight(true)) { + const { width, height } = getDimensionsFromTextureSize(size); + return { + width: Math.floor((width * screenWidth) / 100), + height: Math.floor((height * screenHeight) / 100), + }; + } + /** + * Calculates the total byte size of all textures used by the frame graph texture manager (including external textures) + * @param optimizedSize True if the calculation should not factor in aliased textures + * @param outputWidth The output width of the frame graph. Will be used to calculate the size of percentage-based textures + * @param outputHeight The output height of the frame graph. Will be used to calculate the size of percentage-based textures + * @returns The total size of all textures + */ + computeTotalTextureSize(optimizedSize, outputWidth, outputHeight) { + let totalSize = 0; + this._textures.forEach((entry, handle) => { + if (handle === backbufferColorTextureHandle || handle === backbufferDepthStencilTextureHandle || entry.refHandle !== undefined) { + return; + } + if (optimizedSize && entry.aliasHandle !== undefined) { + return; + } + const options = entry.creationOptions; + const textureIndex = entry.textureIndex || 0; + const dimensions = options.sizeIsPercentage ? this.getAbsoluteDimensions(options.size, outputWidth, outputHeight) : getDimensionsFromTextureSize(options.size); + const blockInfo = FrameGraphTextureManager._GetTextureBlockInformation(options.options.types?.[textureIndex] ?? 0, options.options.formats[textureIndex]); + const textureByteSize = Math.ceil(dimensions.width / blockInfo.width) * Math.ceil(dimensions.height / blockInfo.height) * blockInfo.length; + let byteSize = textureByteSize; + if (options.options.createMipMaps) { + byteSize = Math.floor((byteSize * 4) / 3); + } + if ((options.options.samples || 1) > 1) { + // We need an additional texture in the case of MSAA + byteSize += textureByteSize; + } + totalSize += byteSize; + }); + return totalSize; + } + /** @internal */ + _dispose() { + this._releaseTextures(); + } + /** @internal */ + _allocateTextures(tasks) { + if (tasks) { + this._optimizeTextureAllocation(tasks); + } + this._textures.forEach((entry) => { + if (!entry.texture) { + if (entry.refHandle !== undefined) { + // entry is a dangling handle which has been resolved to point to refHandle + // We simply update the texture to point to the refHandle texture + const refEntry = this._textures.get(entry.refHandle); + entry.texture = refEntry.texture; + if (refEntry.refHandle === backbufferColorTextureHandle) { + entry.refHandle = backbufferColorTextureHandle; + } + if (refEntry.refHandle === backbufferDepthStencilTextureHandle) { + entry.refHandle = backbufferDepthStencilTextureHandle; + } + } + else if (entry.namespace !== FrameGraphTextureNamespace.External) { + if (entry.aliasHandle !== undefined) { + const aliasEntry = this._textures.get(entry.aliasHandle); + entry.texture = aliasEntry.texture; + entry.texture.incrementReferences(); + } + else { + const creationOptions = entry.creationOptions; + const size = creationOptions.sizeIsPercentage ? this.getAbsoluteDimensions(creationOptions.size) : creationOptions.size; + const textureIndex = entry.textureIndex || 0; + const internalTextureCreationOptions = { + createMipMaps: creationOptions.options.createMipMaps, + samples: creationOptions.options.samples, + type: creationOptions.options.types?.[textureIndex], + format: creationOptions.options.formats?.[textureIndex], + useSRGBBuffer: creationOptions.options.useSRGBBuffers?.[textureIndex], + creationFlags: creationOptions.options.creationFlags?.[textureIndex], + label: creationOptions.options.labels?.[textureIndex] ?? `${entry.name}${textureIndex > 0 ? "#" + textureIndex : ""}`, + samplingMode: 1, + createMSAATexture: creationOptions.options.samples > 1, + }; + const isDepthTexture = IsDepthTexture(internalTextureCreationOptions.format); + const hasStencil = HasStencilAspect(internalTextureCreationOptions.format); + const source = isDepthTexture && hasStencil + ? 12 /* InternalTextureSource.DepthStencil */ + : isDepthTexture || hasStencil + ? 14 /* InternalTextureSource.Depth */ + : 5 /* InternalTextureSource.RenderTarget */; + const internalTexture = this.engine._createInternalTexture(size, internalTextureCreationOptions, false, source); + if (isDepthTexture) { + internalTexture.type = GetTypeForDepthTexture(internalTexture.format); + } + entry.texture = internalTexture; + } + } + } + if (entry.texture && entry.refHandle === undefined) { + entry.debug?.dispose(); + entry.debug = this._createDebugTexture(entry.name, entry.texture); + } + }); + this._historyTextures.forEach((entry) => { + for (let i = 0; i < entry.handles.length; i++) { + entry.textures[i] = this._textures.get(entry.handles[i]).texture; + } + }); + } + /** @internal */ + _releaseTextures(releaseAll = true) { + this._textures.forEach((entry, handle) => { + if (entry.lifespan) { + entry.lifespan.firstTask = Number.MAX_VALUE; + entry.lifespan.lastTask = 0; + } + entry.aliasHandle = undefined; + if (releaseAll || entry.namespace !== FrameGraphTextureNamespace.External) { + entry.debug?.dispose(); + entry.debug = undefined; + } + if (entry.namespace === FrameGraphTextureNamespace.External) { + return; + } + entry.texture?.dispose(); + entry.texture = null; + if (releaseAll || entry.namespace === FrameGraphTextureNamespace.Task) { + this._textures.delete(handle); + } + }); + this._historyTextures.forEach((entry) => { + for (let i = 0; i < entry.handles.length; i++) { + entry.textures[i] = null; + } + }); + if (releaseAll) { + this._textures.clear(); + this._historyTextures.clear(); + this._addSystemTextures(); + } + } + /** @internal */ + _updateHistoryTextures() { + this._historyTextures.forEach((entry) => { + entry.index = entry.index ^ 1; + const currentTexture = entry.textures[entry.index]; + if (currentTexture) { + for (const { renderTargetWrapper, textureIndex } of entry.references) { + renderTargetWrapper.setTexture(currentTexture, textureIndex, false); + } + } + }); + } + _addSystemTextures() { + const size = { width: this.engine.getRenderWidth(true), height: this.engine.getRenderHeight(true) }; + this._textures.set(backbufferColorTextureHandle, { + name: "backbuffer color", + texture: null, + creationOptions: { + size, + options: { + createMipMaps: false, + samples: this.engine.getCreationOptions().antialias ? 4 : 1, + types: [0], // todo? get from engine + formats: [5], // todo? get from engine + useSRGBBuffers: [false], + creationFlags: [0], + labels: ["backbuffer color"], + }, + sizeIsPercentage: false, + }, + namespace: FrameGraphTextureNamespace.External, + }); + this._textures.set(backbufferDepthStencilTextureHandle, { + name: "backbuffer depth/stencil", + texture: null, + creationOptions: { + size, + options: { + createMipMaps: false, + samples: this.engine.getCreationOptions().antialias ? 4 : 1, + types: [0], // todo? get from engine + formats: [16], // todo? get from engine + useSRGBBuffers: [false], + creationFlags: [0], + labels: ["backbuffer depth/stencil"], + }, + sizeIsPercentage: false, + }, + namespace: FrameGraphTextureNamespace.External, + }); + } + _createDebugTexture(name, texture) { + if (!this._debugTextures) { + return; + } + const textureDebug = new Texture(null, this._scene); + textureDebug.name = name; + textureDebug._texture = texture; + textureDebug._texture.incrementReferences(); + return textureDebug; + } + _freeEntry(handle) { + const entry = this._textures.get(handle); + if (entry) { + entry.debug?.dispose(); + this._textures.delete(handle); + } + } + _createHandleForTexture(name, texture, creationOptions, namespace, handle, textureIndex) { + handle = handle ?? FrameGraphTextureManager._Counter++; + textureIndex = textureIndex || 0; + const textureName = creationOptions.isHistoryTexture ? `${name} ping` : name; + let label = creationOptions.options.labels?.[textureIndex] ?? ""; + if (label === textureName) { + label = ""; + } + const textureEntry = { + texture, + name: `${textureName}${label ? " " + label : ""}`, + creationOptions: { + size: textureSizeIsObject(creationOptions.size) ? creationOptions.size : { width: creationOptions.size, height: creationOptions.size }, + options: creationOptions.options, + sizeIsPercentage: creationOptions.sizeIsPercentage, + isHistoryTexture: creationOptions.isHistoryTexture, + }, + namespace, + textureIndex, + textureDescriptionHash: this._createTextureDescriptionHash(creationOptions), + lifespan: { + firstTask: Number.MAX_VALUE, + lastTask: 0, + }, + }; + this._textures.set(handle, textureEntry); + if (namespace === FrameGraphTextureNamespace.External) { + return handle; + } + if (creationOptions.isHistoryTexture) { + const pongCreationOptions = { + size: { ...textureEntry.creationOptions.size }, + options: { ...textureEntry.creationOptions.options }, + sizeIsPercentage: textureEntry.creationOptions.sizeIsPercentage, + isHistoryTexture: false, + }; + const pongTexture = this._createHandleForTexture(`${name} pong`, null, pongCreationOptions, namespace); + this._historyTextures.set(handle, { textures: [null, null], handles: [handle, pongTexture], index: 0, references: [] }); + return handle; + } + if (creationOptions.options.types && creationOptions.options.types.length > 1 && textureIndex === 0) { + const textureCount = creationOptions.options.types.length; + const creationOptionsForTexture = { + size: textureSizeIsObject(creationOptions.size) ? creationOptions.size : { width: creationOptions.size, height: creationOptions.size }, + options: creationOptions.options, + sizeIsPercentage: creationOptions.sizeIsPercentage, + }; + for (let i = 1; i < textureCount; i++) { + this._createHandleForTexture(textureName, null, creationOptionsForTexture, namespace, handle + i, i); + } + FrameGraphTextureManager._Counter += textureCount - 1; + } + return handle; + } + _createTextureDescriptionHash(options) { + const hash = []; + hash.push(textureSizeIsObject(options.size) ? `${options.size.width}_${options.size.height}` : `${options.size}`); + hash.push(options.sizeIsPercentage ? "%" : "A"); + hash.push(options.options.createMipMaps ? "M" : "N"); + hash.push(options.options.samples ? `${options.options.samples}` : "S1"); + hash.push(options.options.types ? options.options.types.join("_") : `${0}`); + hash.push(options.options.formats ? options.options.formats.join("_") : `${5}`); + hash.push(options.options.useSRGBBuffers ? options.options.useSRGBBuffers.join("_") : "false"); + hash.push(options.options.creationFlags ? options.options.creationFlags.join("_") : "0"); + return hash.join("_"); + } + _optimizeTextureAllocation(tasks) { + this._computeTextureLifespan(tasks); + if (this.showDebugLogsForTextureAllcationOptimization) { + Logger.Log(`================== Optimization of texture allocation ==================`); + } + const cache = new Map(); + const iterator = this._textures.keys(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const textureHandle = key.value; + const textureEntry = this._textures.get(textureHandle); + if (textureEntry.refHandle !== undefined || textureEntry.namespace === FrameGraphTextureNamespace.External || this._historyTextures.has(textureHandle)) { + continue; + } + const textureHash = textureEntry.textureDescriptionHash; + const textureLifespan = textureEntry.lifespan; + const cacheEntries = cache.get(textureHash); + if (cacheEntries) { + let cacheEntryFound = false; + for (const cacheEntry of cacheEntries) { + const [sourceHandle, lifespanArray] = cacheEntry; + let overlapped = false; + for (const lifespan of lifespanArray) { + if (lifespan.firstTask <= textureLifespan.lastTask && lifespan.lastTask >= textureLifespan.firstTask) { + overlapped = true; + break; + } + } + if (!overlapped) { + // No overlap between texture lifespan and all lifespans in the array, this texture can reuse the same entry cache + if (this.showDebugLogsForTextureAllcationOptimization) { + Logger.Log(`Texture ${textureHandle} (${textureEntry.name}) reuses cache entry ${sourceHandle}`); + } + lifespanArray.push(textureLifespan); + textureEntry.aliasHandle = sourceHandle; + cacheEntryFound = true; + break; + } + } + if (!cacheEntryFound) { + cacheEntries.push([textureHandle, [textureLifespan]]); + } + } + else { + cache.set(textureHash, [[textureHandle, [textureLifespan]]]); + } + } + } + // Loop through all task/pass dependencies and compute the lifespan of each texture (that is, the first task/pass that uses it and the last task/pass that uses it) + _computeTextureLifespan(tasks) { + if (this.showDebugLogsForTextureAllcationOptimization) { + Logger.Log(`================== Dump of texture dependencies for all tasks/passes ==================`); + } + for (let t = 0; t < tasks.length; ++t) { + const task = tasks[t]; + if (task.passes.length > 0) { + this._computeTextureLifespanForPasses(task, t, task.passes); + } + if (task.passesDisabled.length > 0) { + this._computeTextureLifespanForPasses(task, t, task.passesDisabled); + } + if (task.dependencies) { + if (this.showDebugLogsForTextureAllcationOptimization) { + Logger.Log(`task#${t} (${task.name}), global dependencies`); + } + this._updateLifespan(t * 100 + 99, task.dependencies); + } + } + if (this.showDebugLogsForTextureAllcationOptimization) { + Logger.Log(`================== Texture lifespans ==================`); + const iterator = this._textures.keys(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const textureHandle = key.value; + const textureEntry = this._textures.get(textureHandle); + if (textureEntry.refHandle !== undefined || textureEntry.namespace === FrameGraphTextureNamespace.External || this._historyTextures.has(textureHandle)) { + continue; + } + Logger.Log(`${textureHandle} (${textureEntry.name}): ${textureEntry.lifespan.firstTask} - ${textureEntry.lifespan.lastTask}`); + } + } + } + _computeTextureLifespanForPasses(task, taskIndex, passes) { + for (let p = 0; p < passes.length; ++p) { + const dependencies = new Set(); + const pass = passes[p]; + if (!FrameGraphRenderPass.IsRenderPass(pass)) { + continue; + } + pass.collectDependencies(dependencies); + if (this.showDebugLogsForTextureAllcationOptimization) { + Logger.Log(`task#${taskIndex} (${task.name}), pass#${p} (${pass.name})`); + } + this._updateLifespan(taskIndex * 100 + p, dependencies); + } + } + _updateLifespan(passOrderNum, dependencies) { + const iterator = dependencies.keys(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const textureHandle = key.value; + let textureEntry = this._textures.get(textureHandle); + if (!textureEntry) { + throw new Error(`FrameGraph._computeTextureLifespan: Texture handle "${textureHandle}" not found in the texture manager.`); + } + let handle = textureHandle; + while (textureEntry.refHandle !== undefined) { + handle = textureEntry.refHandle; + textureEntry = this._textures.get(handle); + if (!textureEntry) { + throw new Error(`FrameGraph._computeTextureLifespan: Texture handle "${handle}" not found in the texture manager (source handle="${textureHandle}").`); + } + } + if (textureEntry.namespace === FrameGraphTextureNamespace.External || this._historyTextures.has(handle)) { + continue; + } + if (this.showDebugLogsForTextureAllcationOptimization) { + Logger.Log(` ${handle} (${textureEntry.name})`); + } + textureEntry.lifespan.firstTask = Math.min(textureEntry.lifespan.firstTask, passOrderNum); + textureEntry.lifespan.lastTask = Math.max(textureEntry.lifespan.lastTask, passOrderNum); + } + } + /** + * Clones a texture options + * @param options The options to clone + * @param textureIndex The index of the texture in the types, formats, etc array of FrameGraphTextureOptions. If not provided, all options are cloned. + * @param preserveLabels True if the labels should be preserved (default: false) + * @returns The cloned options + */ + static CloneTextureOptions(options, textureIndex, preserveLabels) { + return textureIndex !== undefined + ? { + createMipMaps: options.createMipMaps, + samples: options.samples, + types: options.types ? [options.types[textureIndex]] : undefined, + formats: options.formats ? [options.formats[textureIndex]] : undefined, + useSRGBBuffers: options.useSRGBBuffers ? [options.useSRGBBuffers[textureIndex]] : undefined, + creationFlags: options.creationFlags ? [options.creationFlags[textureIndex]] : undefined, + labels: options.labels ? [options.labels[textureIndex]] : undefined, + } + : { + createMipMaps: options.createMipMaps, + samples: options.samples, + types: options.types ? [...options.types] : undefined, + formats: options.formats ? [...options.formats] : undefined, + useSRGBBuffers: options.useSRGBBuffers ? [...options.useSRGBBuffers] : undefined, + creationFlags: options.creationFlags ? [...options.creationFlags] : undefined, + labels: options.labels && preserveLabels ? [...options.labels] : undefined, + }; + } + /** + * Gets the texture block information. + * @param type Type of the texture. + * @param format Format of the texture. + * @returns The texture block information. You can calculate the byte size of the texture by doing: Math.ceil(width / blockInfo.width) * Math.ceil(height / blockInfo.height) * blockInfo.length + */ + static _GetTextureBlockInformation(type, format) { + switch (format) { + case 15: + return { width: 1, height: 1, length: 2 }; + case 16: + return { width: 1, height: 1, length: 3 }; + case 13: + return { width: 1, height: 1, length: 4 }; + case 14: + return { width: 1, height: 1, length: 4 }; + case 18: + return { width: 1, height: 1, length: 5 }; + case 19: + return { width: 1, height: 1, length: 1 }; + case 36492: + return { width: 4, height: 4, length: 16 }; + case 36495: + return { width: 4, height: 4, length: 16 }; + case 36494: + return { width: 4, height: 4, length: 16 }; + case 33779: + return { width: 4, height: 4, length: 16 }; + case 33778: + return { width: 4, height: 4, length: 16 }; + case 33777: + case 33776: + return { width: 4, height: 4, length: 8 }; + case 37808: + return { width: 4, height: 4, length: 16 }; + case 36196: + case 37492: + return { width: 4, height: 4, length: 8 }; + case 37496: + return { width: 4, height: 4, length: 16 }; + } + switch (type) { + case 3: + case 0: + switch (format) { + case 6: + case 8: + case 0: + case 1: + case 2: + return { width: 1, height: 1, length: 1 }; + case 7: + case 9: + return { width: 1, height: 1, length: 2 }; + case 4: + case 10: + return { width: 1, height: 1, length: 3 }; + case 11: + return { width: 1, height: 1, length: 4 }; + default: + return { width: 1, height: 1, length: 4 }; + } + case 4: + case 5: + switch (format) { + case 8: + return { width: 1, height: 1, length: 2 }; + case 9: + return { width: 1, height: 1, length: 4 }; + case 10: + return { width: 1, height: 1, length: 6 }; + case 11: + return { width: 1, height: 1, length: 8 }; + default: + return { width: 1, height: 1, length: 8 }; + } + case 6: + case 7: // Refers to UNSIGNED_INT + switch (format) { + case 8: + return { width: 1, height: 1, length: 4 }; + case 9: + return { width: 1, height: 1, length: 8 }; + case 10: + return { width: 1, height: 1, length: 12 }; + case 11: + return { width: 1, height: 1, length: 16 }; + default: + return { width: 1, height: 1, length: 16 }; + } + case 1: + switch (format) { + case 6: + return { width: 1, height: 1, length: 4 }; + case 7: + return { width: 1, height: 1, length: 8 }; + case 4: + return { width: 1, height: 1, length: 12 }; + case 5: + return { width: 1, height: 1, length: 16 }; + default: + return { width: 1, height: 1, length: 16 }; + } + case 2: + switch (format) { + case 6: + return { width: 1, height: 1, length: 2 }; + case 7: + return { width: 1, height: 1, length: 4 }; + case 4: + return { width: 1, height: 1, length: 6 }; + case 5: + return { width: 1, height: 1, length: 8 }; + default: + return { width: 1, height: 1, length: 8 }; + } + case 10: + return { width: 1, height: 1, length: 2 }; + case 13: + switch (format) { + case 5: + case 11: + return { width: 1, height: 1, length: 4 }; + default: + return { width: 1, height: 1, length: 4 }; + } + case 14: + switch (format) { + case 5: + case 11: + return { width: 1, height: 1, length: 4 }; + default: + return { width: 1, height: 1, length: 4 }; + } + case 8: + return { width: 1, height: 1, length: 2 }; + case 9: + return { width: 1, height: 1, length: 2 }; + case 11: + switch (format) { + case 5: + return { width: 1, height: 1, length: 4 }; + case 11: + return { width: 1, height: 1, length: 4 }; + default: + return { width: 1, height: 1, length: 4 }; + } + } + return { width: 1, height: 1, length: 4 }; + } +} +FrameGraphTextureManager._Counter = 2; // 0 and 1 are reserved for backbuffer textures + +var FrameGraphPassType; +(function (FrameGraphPassType) { + FrameGraphPassType[FrameGraphPassType["Normal"] = 0] = "Normal"; + FrameGraphPassType[FrameGraphPassType["Render"] = 1] = "Render"; + FrameGraphPassType[FrameGraphPassType["Cull"] = 2] = "Cull"; +})(FrameGraphPassType || (FrameGraphPassType = {})); +/** + * Class used to implement a frame graph + * @experimental + */ +class FrameGraph { + /** + * Gets the engine used by the frame graph + */ + get engine() { + return this._engine; + } + /** + * Gets the scene used by the frame graph + */ + get scene() { + return this._scene; + } + /** + * Gets the list of tasks in the frame graph + */ + get tasks() { + return this._tasks; + } + /** + * Gets the node render graph linked to the frame graph (if any) + * @returns the linked node render graph or null if none + */ + getLinkedNodeRenderGraph() { + return this._linkedNodeRenderGraph; + } + /** + * Constructs the frame graph + * @param scene defines the scene the frame graph is associated with + * @param debugTextures defines a boolean indicating that textures created by the frame graph should be visible in the inspector (default is false) + * @param _linkedNodeRenderGraph defines the linked node render graph (if any) + */ + constructor(scene, debugTextures = false, _linkedNodeRenderGraph = null) { + this._linkedNodeRenderGraph = _linkedNodeRenderGraph; + this._tasks = []; + this._currentProcessedTask = null; + this._whenReadyAsyncCancel = null; + /** + * Name of the frame graph + */ + this.name = "Frame Graph"; + /** + * Gets or sets a boolean indicating that texture allocation should be optimized (that is, reuse existing textures when possible to limit GPU memory usage) (default: true) + */ + this.optimizeTextureAllocation = true; + /** + * Observable raised when the node render graph is built + */ + this.onBuildObservable = new Observable(); + this._scene = scene; + this._engine = scene.getEngine(); + this.textureManager = new FrameGraphTextureManager(this._engine, debugTextures, scene); + this._passContext = new FrameGraphContext(); + this._renderContext = new FrameGraphRenderContext(this._engine, this.textureManager, scene); + this._scene.frameGraphs.push(this); + } + /** + * Gets the class name of the frame graph + * @returns the class name + */ + getClassName() { + return "FrameGraph"; + } + /** + * Gets a task by name + * @param name Name of the task to get + * @returns The task or undefined if not found + */ + getTaskByName(name) { + return this._tasks.find((t) => t.name === name); + } + /** + * Adds a task to the frame graph + * @param task Task to add + */ + addTask(task) { + if (this._currentProcessedTask !== null) { + throw new Error(`FrameGraph.addTask: Can't add the task "${task.name}" while another task is currently building (task: ${this._currentProcessedTask.name}).`); + } + this._tasks.push(task); + } + /** + * Adds a pass to a task. This method can only be called during a Task.record execution. + * @param name The name of the pass + * @param whenTaskDisabled If true, the pass will be added to the list of passes to execute when the task is disabled (default is false) + * @returns The render pass created + */ + addPass(name, whenTaskDisabled = false) { + return this._addPass(name, FrameGraphPassType.Normal, whenTaskDisabled); + } + /** + * Adds a render pass to a task. This method can only be called during a Task.record execution. + * @param name The name of the pass + * @param whenTaskDisabled If true, the pass will be added to the list of passes to execute when the task is disabled (default is false) + * @returns The render pass created + */ + addRenderPass(name, whenTaskDisabled = false) { + return this._addPass(name, FrameGraphPassType.Render, whenTaskDisabled); + } + /** + * Adds a cull pass to a task. This method can only be called during a Task.record execution. + * @param name The name of the pass + * @param whenTaskDisabled If true, the pass will be added to the list of passes to execute when the task is disabled (default is false) + * @returns The cull pass created + */ + addCullPass(name, whenTaskDisabled = false) { + return this._addPass(name, FrameGraphPassType.Cull, whenTaskDisabled); + } + _addPass(name, passType, whenTaskDisabled = false) { + if (!this._currentProcessedTask) { + throw new Error("FrameGraph: A pass must be created during a Task.record execution only."); + } + let pass; + switch (passType) { + case FrameGraphPassType.Render: + pass = new FrameGraphRenderPass(name, this._currentProcessedTask, this._renderContext, this._engine); + break; + case FrameGraphPassType.Cull: + pass = new FrameGraphCullPass(name, this._currentProcessedTask, this._passContext, this._engine); + break; + default: + pass = new FrameGraphPass(name, this._currentProcessedTask, this._passContext); + break; + } + this._currentProcessedTask._addPass(pass, whenTaskDisabled); + return pass; + } + /** + * Builds the frame graph. + * This method should be called after all tasks have been added to the frame graph (FrameGraph.addTask) and before the graph is executed (FrameGraph.execute). + */ + build() { + this.textureManager._releaseTextures(false); + try { + for (const task of this._tasks) { + task._reset(); + this._currentProcessedTask = task; + this.textureManager._isRecordingTask = true; + task.record(); + this.textureManager._isRecordingTask = false; + this._currentProcessedTask = null; + } + this.textureManager._allocateTextures(this.optimizeTextureAllocation ? this._tasks : undefined); + for (const task of this._tasks) { + task._checkTask(); + } + for (const task of this._tasks) { + task.onTexturesAllocatedObservable.notifyObservers(this._renderContext); + } + this.onBuildObservable.notifyObservers(this); + } + catch (e) { + this._tasks.length = 0; + this._currentProcessedTask = null; + this.textureManager._isRecordingTask = false; + throw e; + } + } + /** + * Returns a promise that resolves when the frame graph is ready to be executed + * This method must be called after the graph has been built (FrameGraph.build called)! + * @param timeStep Time step in ms between retries (default is 16) + * @param maxTimeout Maximum time in ms to wait for the graph to be ready (default is 30000) + * @returns The promise that resolves when the graph is ready + */ + whenReadyAsync(timeStep = 16, maxTimeout = 30000) { + let firstNotReadyTask = null; + return new Promise((resolve) => { + this._whenReadyAsyncCancel = _retryWithInterval(() => { + let ready = this._renderContext._isReady(); + for (const task of this._tasks) { + const taskIsReady = task.isReady(); + if (!taskIsReady && !firstNotReadyTask) { + firstNotReadyTask = task; + } + ready && (ready = taskIsReady); + } + return ready; + }, () => { + this._whenReadyAsyncCancel = null; + resolve(); + }, (err, isTimeout) => { + this._whenReadyAsyncCancel = null; + if (!isTimeout) { + Logger.Error("FrameGraph: An unexpected error occurred while waiting for the frame graph to be ready."); + if (err) { + Logger.Error(err); + if (err.stack) { + Logger.Error(err.stack); + } + } + } + else { + Logger.Error(`FrameGraph: Timeout while waiting for the frame graph to be ready.${firstNotReadyTask ? ` First task not ready: ${firstNotReadyTask.name}` : ""}`); + if (err) { + Logger.Error(err); + } + } + }, timeStep, maxTimeout); + }); + } + /** + * Executes the frame graph. + */ + execute() { + this._renderContext.bindRenderTarget(); + this.textureManager._updateHistoryTextures(); + for (const task of this._tasks) { + const passes = task._getPasses(); + for (const pass of passes) { + pass._execute(); + } + } + } + /** + * Clears the frame graph (remove the tasks and release the textures). + * The frame graph can be built again after this method is called. + */ + clear() { + this._whenReadyAsyncCancel?.(); + this._whenReadyAsyncCancel = null; + for (const task of this._tasks) { + task._reset(); + } + this._tasks.length = 0; + this.textureManager._releaseTextures(); + this._currentProcessedTask = null; + } + /** + * Disposes the frame graph + */ + dispose() { + this._whenReadyAsyncCancel?.(); + this._whenReadyAsyncCancel = null; + this.clear(); + this.textureManager._dispose(); + this._renderContext._dispose(); + const index = this._scene.frameGraphs.indexOf(this); + if (index !== -1) { + this._scene.frameGraphs.splice(index, 1); + } + } +} + +/** + * Enum defining the type of properties that can be edited in the property pages in the node editor + */ +var PropertyTypeForEdition; +(function (PropertyTypeForEdition) { + /** property is a boolean */ + PropertyTypeForEdition[PropertyTypeForEdition["Boolean"] = 0] = "Boolean"; + /** property is a float */ + PropertyTypeForEdition[PropertyTypeForEdition["Float"] = 1] = "Float"; + /** property is a int */ + PropertyTypeForEdition[PropertyTypeForEdition["Int"] = 2] = "Int"; + /** property is a Vector2 */ + PropertyTypeForEdition[PropertyTypeForEdition["Vector2"] = 3] = "Vector2"; + /** property is a list of values */ + PropertyTypeForEdition[PropertyTypeForEdition["List"] = 4] = "List"; + /** property is a Color4 */ + PropertyTypeForEdition[PropertyTypeForEdition["Color4"] = 5] = "Color4"; + /** property (int) should be edited as a combo box with a list of sampling modes */ + PropertyTypeForEdition[PropertyTypeForEdition["SamplingMode"] = 6] = "SamplingMode"; + /** property (int) should be edited as a combo box with a list of texture formats */ + PropertyTypeForEdition[PropertyTypeForEdition["TextureFormat"] = 7] = "TextureFormat"; + /** property (int) should be edited as a combo box with a list of texture types */ + PropertyTypeForEdition[PropertyTypeForEdition["TextureType"] = 8] = "TextureType"; +})(PropertyTypeForEdition || (PropertyTypeForEdition = {})); +/** + * Decorator that flags a property in a node block as being editable + * @param displayName the display name of the property + * @param propertyType the type of the property + * @param groupName the group name of the property + * @param options the options of the property + * @returns the decorator + */ +function editableInPropertyPage(displayName, propertyType = 0 /* PropertyTypeForEdition.Boolean */, groupName = "PROPERTIES", options) { + return (target, propertyKey) => { + let propStore = target._propStore; + if (!propStore) { + propStore = []; + target._propStore = propStore; + } + propStore.push({ + propertyName: propertyKey, + displayName: displayName, + type: propertyType, + groupName: groupName, + options: options ?? {}, + className: target.getClassName(), + }); + }; +} + +/** + * Block used to expose an input value + */ +class NodeRenderGraphInputBlock extends NodeRenderGraphBlock { + /** + * Gets or sets the connection point type (default is Undefined) + */ + get type() { + return this._type; + } + /** + * Creates a new NodeRenderGraphInputBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param type defines the type of the input (can be set to NodeRenderGraphBlockConnectionPointTypes.Undefined) + */ + constructor(name, frameGraph, scene, type = NodeRenderGraphBlockConnectionPointTypes.Undefined) { + super(name, frameGraph, scene); + this._storedValue = null; + this._type = NodeRenderGraphBlockConnectionPointTypes.Undefined; + /** Gets an observable raised when the value is changed */ + this.onValueChangedObservable = new Observable(); + /** Indicates that the input is externally managed */ + this.isExternal = false; + this._type = type; + this._isInput = true; + this.registerOutput("output", type); + this.setDefaultValue(); + } + /** + * Set the input block to its default value (based on its type) + */ + setDefaultValue() { + switch (this.type) { + case NodeRenderGraphBlockConnectionPointTypes.Texture: + case NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth: + case NodeRenderGraphBlockConnectionPointTypes.TextureScreenDepth: + case NodeRenderGraphBlockConnectionPointTypes.TextureViewNormal: + case NodeRenderGraphBlockConnectionPointTypes.TextureWorldNormal: + case NodeRenderGraphBlockConnectionPointTypes.TextureAlbedo: + case NodeRenderGraphBlockConnectionPointTypes.TextureReflectivity: + case NodeRenderGraphBlockConnectionPointTypes.TextureLocalPosition: + case NodeRenderGraphBlockConnectionPointTypes.TextureWorldPosition: + case NodeRenderGraphBlockConnectionPointTypes.TextureVelocity: + case NodeRenderGraphBlockConnectionPointTypes.TextureLinearVelocity: + case NodeRenderGraphBlockConnectionPointTypes.TextureIrradiance: + case NodeRenderGraphBlockConnectionPointTypes.TextureAlbedoSqrt: { + const options = { + size: { width: 100, height: 100 }, + options: { + createMipMaps: false, + types: [0], + formats: [5], + samples: 1, + useSRGBBuffers: [false], + }, + sizeIsPercentage: true, + }; + this.creationOptions = options; + break; + } + case NodeRenderGraphBlockConnectionPointTypes.TextureDepthStencilAttachment: { + const options = { + size: { width: 100, height: 100 }, + options: { + createMipMaps: false, + types: [0], + formats: [13], + useSRGBBuffers: [false], + labels: [this.name], + samples: 1, + }, + sizeIsPercentage: true, + }; + this.creationOptions = options; + break; + } + case NodeRenderGraphBlockConnectionPointTypes.ObjectList: + this.value = { meshes: [], particleSystems: [] }; + this.isExternal = true; + break; + case NodeRenderGraphBlockConnectionPointTypes.Camera: + this.value = this._scene.cameras[0]; + this.isExternal = true; + break; + default: + this.isExternal = true; + } + } + /** + * Gets or sets the value of that point. + */ + get value() { + return this._storedValue; + } + set value(value) { + this._storedValue = value; + this.output.value = undefined; + this.onValueChangedObservable.notifyObservers(this); + } + /** + * Gets the value as a specific type + * @returns the value as a specific type + */ + getTypedValue() { + return this._storedValue; + } + /** + * Gets the value as an internal texture + * @returns The internal texture stored in value if value is an internal texture, otherwise null + */ + getInternalTextureFromValue() { + if (this._storedValue._swapAndDie) { + return this._storedValue; + } + return null; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphInputBlock"; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Check if the block is a texture of any type + * @returns true if the block is a texture + */ + isAnyTexture() { + return (this.type & NodeRenderGraphBlockConnectionPointTypes.TextureAll) !== 0; + } + /** + * Gets a boolean indicating that the connection point is the back buffer texture + * @returns true if the connection point is the back buffer texture + */ + isBackBuffer() { + return (this.type & NodeRenderGraphBlockConnectionPointTypes.TextureBackBuffer) !== 0; + } + /** + * Gets a boolean indicating that the connection point is a depth/stencil attachment texture + * @returns true if the connection point is a depth/stencil attachment texture + */ + isBackBufferDepthStencilAttachment() { + return (this.type & NodeRenderGraphBlockConnectionPointTypes.TextureBackBufferDepthStencilAttachment) !== 0; + } + /** + * Check if the block is a camera + * @returns true if the block is a camera + */ + isCamera() { + return (this.type & NodeRenderGraphBlockConnectionPointTypes.Camera) !== 0; + } + /** + * Check if the block is an object list + * @returns true if the block is an object list + */ + isObjectList() { + return (this.type & NodeRenderGraphBlockConnectionPointTypes.ObjectList) !== 0; + } + /** + * Check if the block is a shadow light + * @returns true if the block is a shadow light + */ + isShadowLight() { + return (this.type & NodeRenderGraphBlockConnectionPointTypes.ShadowLight) !== 0; + } + _buildBlock(state) { + super._buildBlock(state); + if (this.isExternal) { + if (this.isBackBuffer()) { + this.output.value = backbufferColorTextureHandle; + } + else if (this.isBackBufferDepthStencilAttachment()) { + this.output.value = backbufferDepthStencilTextureHandle; + } + else if (this.isCamera()) { + this.output.value = this.getTypedValue(); + } + else if (this.isObjectList()) { + this.output.value = this.getTypedValue(); + } + else if (this.isShadowLight()) { + this.output.value = this.getTypedValue(); + } + else { + if (this._storedValue === undefined || this._storedValue === null) { + throw new Error(`NodeRenderGraphInputBlock: External input "${this.name}" is not set`); + } + const texture = this.getInternalTextureFromValue(); + if (texture) { + this.output.value = this._frameGraph.textureManager.importTexture(this.name, texture, this.output.value); + } + } + return; + } + if ((this.type & NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer) !== 0) { + const textureCreateOptions = this.creationOptions; + if (!textureCreateOptions) { + throw new Error(`NodeRenderGraphInputBlock: Creation options are missing for texture "${this.name}"`); + } + this.output.value = this._frameGraph.textureManager.createRenderTargetTexture(this.name, textureCreateOptions); + } + } + dispose() { + this._storedValue = null; + this.onValueChangedObservable.clear(); + super.dispose(); + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.isExternal = ${this.isExternal};`); + if (this.isAnyTexture()) { + if (!this.isExternal) { + codes.push(`${this._codeVariableName}.creationOptions = ${JSON.stringify(this.creationOptions)};`); + } + else { + codes.push(`${this._codeVariableName}.value = EXTERNAL_TEXTURE; // TODO: set the external texture`); + } + } + else if (this.isCamera()) { + codes.push(`${this._codeVariableName}.value = EXTERNAL_CAMERA; // TODO: set the external camera`); + } + else if (this.isObjectList()) { + codes.push(`${this._codeVariableName}.value = EXTERNAL_OBJECT_LIST; // TODO: set the external object list`); + } + else if (this.isShadowLight()) { + codes.push(`${this._codeVariableName}.value = EXTERNAL_SHADOW_LIGHT; // TODO: set the external shadow light`); + } + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.type = this.type; + serializationObject.isExternal = this.isExternal; + if (this.creationOptions) { + serializationObject.creationOptions = this.creationOptions; + } + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this._type = serializationObject.type; + this.output.type = this._type; + this.isExternal = serializationObject.isExternal; + if (serializationObject.creationOptions) { + if (serializationObject.creationOptions.options.depthTextureFormat !== undefined) { + // Backward compatibility - remove this code in the future + serializationObject.creationOptions.options.formats = [serializationObject.creationOptions.options.depthTextureFormat]; + } + this.creationOptions = serializationObject.creationOptions; + } + } +} +__decorate([ + editableInPropertyPage("Is external", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphInputBlock.prototype, "isExternal", void 0); +RegisterClass("BABYLON.NodeRenderGraphInputBlock", NodeRenderGraphInputBlock); + +/** + * Task used to clear a texture. + */ +class FrameGraphClearTextureTask extends FrameGraphTask { + /** + * Constructs a new clear task. + * @param name The name of the task. + * @param frameGraph The frame graph the task belongs to. + */ + constructor(name, frameGraph) { + super(name, frameGraph); + /** + * The color to clear the texture with. + */ + this.color = new Color4(0.2, 0.2, 0.3, 1); + /** + * If the color should be cleared. + */ + this.clearColor = true; + /** + * If the color should be converted to linear space (default: false). + */ + this.convertColorToLinearSpace = false; + /** + * If the depth should be cleared. + */ + this.clearDepth = false; + /** + * If the stencil should be cleared. + */ + this.clearStencil = false; + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.outputDepthTexture = this._frameGraph.textureManager.createDanglingHandle(); + } + record() { + if (this.targetTexture === undefined && this.depthTexture === undefined) { + throw new Error(`FrameGraphClearTextureTask ${this.name}: targetTexture and depthTexture can't both be undefined.`); + } + let textureSamples = 0; + let depthSamples = 0; + if (this.targetTexture !== undefined) { + textureSamples = this._frameGraph.textureManager.getTextureDescription(this.targetTexture).options.samples || 1; + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture); + } + if (this.depthTexture !== undefined) { + depthSamples = this._frameGraph.textureManager.getTextureDescription(this.depthTexture).options.samples || 1; + this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture, this.depthTexture); + } + if (textureSamples !== depthSamples && textureSamples !== 0 && depthSamples !== 0) { + throw new Error(`FrameGraphClearTextureTask ${this.name}: the depth texture and the target texture must have the same number of samples.`); + } + const color = TmpColors.Color4[0]; + const pass = this._frameGraph.addRenderPass(this.name); + pass.setRenderTarget(this.targetTexture); + pass.setRenderTargetDepth(this.depthTexture); + pass.setExecuteFunc((context) => { + color.copyFrom(this.color); + if (this.convertColorToLinearSpace) { + color.toLinearSpaceToRef(color); + } + context.clear(color, !!this.clearColor, !!this.clearDepth, !!this.clearStencil); + }); + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.setRenderTarget(this.targetTexture); + passDisabled.setRenderTargetDepth(this.depthTexture); + passDisabled.setExecuteFunc((_context) => { }); + return pass; + } +} + +/** + * Block used to clear a texture + */ +class NodeRenderGraphClearBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphClearBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("depth", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this._addDependenciesInput(); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.registerOutput("outputDepth", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAll); + this.depth.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureDepthStencilAttachment | NodeRenderGraphBlockConnectionPointTypes.TextureBackBufferDepthStencilAttachment); + this.output._typeConnectionSource = this.target; + this.outputDepth._typeConnectionSource = this.depth; + this._frameGraphTask = new FrameGraphClearTextureTask(name, frameGraph); + } + /** Gets or sets the clear color */ + get color() { + return this._frameGraphTask.color; + } + set color(value) { + this._frameGraphTask.color = value; + } + /** Gets or sets a boolean indicating whether the color part of the texture should be cleared. */ + get clearColor() { + return !!this._frameGraphTask.clearColor; + } + set clearColor(value) { + this._frameGraphTask.clearColor = value; + } + /** Gets or sets a boolean indicating whether the color should be converted to linear space. */ + get convertColorToLinearSpace() { + return !!this._frameGraphTask.convertColorToLinearSpace; + } + set convertColorToLinearSpace(value) { + this._frameGraphTask.convertColorToLinearSpace = value; + } + /** Gets or sets a boolean indicating whether the depth part of the texture should be cleared. */ + get clearDepth() { + return !!this._frameGraphTask.clearDepth; + } + set clearDepth(value) { + this._frameGraphTask.clearDepth = value; + } + /** Gets or sets a boolean indicating whether the stencil part of the texture should be cleared. */ + get clearStencil() { + return !!this._frameGraphTask.clearStencil; + } + set clearStencil(value) { + this._frameGraphTask.clearStencil = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphClearBlock"; + } + /** + * Gets the target input component + */ + get target() { + return this._inputs[0]; + } + /** + * Gets the depth texture input component + */ + get depth() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the output depth component + */ + get outputDepth() { + return this._outputs[1]; + } + _buildBlock(state) { + super._buildBlock(state); + this._propagateInputValueToOutput(this.target, this.output); + this._propagateInputValueToOutput(this.depth, this.outputDepth); + this._frameGraphTask.targetTexture = this.target.connectedPoint?.value; + this._frameGraphTask.depthTexture = this.depth.connectedPoint?.value; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.color = new BABYLON.Color4(${this.color.r}, ${this.color.g}, ${this.color.b}, ${this.color.a});`); + codes.push(`${this._codeVariableName}.clearColor = ${this.clearColor};`); + codes.push(`${this._codeVariableName}.convertColorToLinearSpace = ${this.convertColorToLinearSpace};`); + codes.push(`${this._codeVariableName}.clearDepth = ${this.clearDepth};`); + codes.push(`${this._codeVariableName}.clearStencil = ${this.clearStencil};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.color = this.color.asArray(); + serializationObject.clearColor = this.clearColor; + serializationObject.convertColorToLinearSpace = this.convertColorToLinearSpace; + serializationObject.clearDepth = this.clearDepth; + serializationObject.clearStencil = this.clearStencil; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.color = Color4.FromArray(serializationObject.color); + this.clearColor = serializationObject.clearColor; + this.convertColorToLinearSpace = !!serializationObject.convertColorToLinearSpace; + this.clearDepth = serializationObject.clearDepth; + this.clearStencil = serializationObject.clearStencil; + } +} +__decorate([ + editableInPropertyPage("Color", 5 /* PropertyTypeForEdition.Color4 */) +], NodeRenderGraphClearBlock.prototype, "color", null); +__decorate([ + editableInPropertyPage("Clear color", 0 /* PropertyTypeForEdition.Boolean */, undefined, { embedded: true }) +], NodeRenderGraphClearBlock.prototype, "clearColor", null); +__decorate([ + editableInPropertyPage("Convert color to linear space", 0 /* PropertyTypeForEdition.Boolean */) +], NodeRenderGraphClearBlock.prototype, "convertColorToLinearSpace", null); +__decorate([ + editableInPropertyPage("Clear depth", 0 /* PropertyTypeForEdition.Boolean */, undefined, { embedded: true }) +], NodeRenderGraphClearBlock.prototype, "clearDepth", null); +__decorate([ + editableInPropertyPage("Clear stencil", 0 /* PropertyTypeForEdition.Boolean */, undefined, { embedded: true }) +], NodeRenderGraphClearBlock.prototype, "clearStencil", null); +RegisterClass("BABYLON.NodeRenderGraphClearBlock", NodeRenderGraphClearBlock); + +/** + * Task used to generate shadows from a list of objects. + */ +class FrameGraphShadowGeneratorTask extends FrameGraphTask { + /** + * The light to generate shadows from. + */ + get light() { + return this._light; + } + set light(value) { + if (value === this._light) { + return; + } + this._light = value; + this._setupShadowGenerator(); + } + /** + * Gets or sets the camera used to generate the shadow generator. + */ + get camera() { + return this._camera; + } + set camera(camera) { + this._camera = camera; + this._setupShadowGenerator(); + } + /** + * The size of the shadow map. + */ + get mapSize() { + return this._mapSize; + } + set mapSize(value) { + if (value === this._mapSize) { + return; + } + this._mapSize = value; + this._setupShadowGenerator(); + } + /** + * If true, the shadow map will use a 32 bits float texture type (else, 16 bits float is used if supported). + */ + get useFloat32TextureType() { + return this._useFloat32TextureType; + } + set useFloat32TextureType(value) { + if (value === this._useFloat32TextureType) { + return; + } + this._useFloat32TextureType = value; + this._setupShadowGenerator(); + } + /** + * If true, the shadow map will use a red texture format (else, a RGBA format is used). + */ + get useRedTextureFormat() { + return this._useRedTextureFormat; + } + set useRedTextureFormat(value) { + if (value === this._useRedTextureFormat) { + return; + } + this._useRedTextureFormat = value; + this._setupShadowGenerator(); + } + /** + * The bias to apply to the shadow map. + */ + get bias() { + return this._bias; + } + set bias(value) { + if (value === this._bias) { + return; + } + this._bias = value; + if (this._shadowGenerator) { + this._shadowGenerator.bias = value; + } + } + /** + * The normal bias to apply to the shadow map. + */ + get normalBias() { + return this._normalBias; + } + set normalBias(value) { + if (value === this._normalBias) { + return; + } + this._normalBias = value; + if (this._shadowGenerator) { + this._shadowGenerator.normalBias = value; + } + } + /** + * The darkness of the shadows. + */ + get darkness() { + return this._darkness; + } + set darkness(value) { + if (value === this._darkness) { + return; + } + this._darkness = value; + if (this._shadowGenerator) { + this._shadowGenerator.darkness = value; + } + } + /** + * Gets or sets the ability to have transparent shadow + */ + get transparencyShadow() { + return this._transparencyShadow; + } + set transparencyShadow(value) { + if (value === this._transparencyShadow) { + return; + } + this._transparencyShadow = value; + if (this._shadowGenerator) { + this._shadowGenerator.transparencyShadow = value; + } + } + /** + * Enables or disables shadows with varying strength based on the transparency + */ + get enableSoftTransparentShadow() { + return this._enableSoftTransparentShadow; + } + set enableSoftTransparentShadow(value) { + if (value === this._enableSoftTransparentShadow) { + return; + } + this._enableSoftTransparentShadow = value; + if (this._shadowGenerator) { + this._shadowGenerator.enableSoftTransparentShadow = value; + } + } + /** + * If this is true, use the opacity texture's alpha channel for transparent shadows instead of the diffuse one + */ + get useOpacityTextureForTransparentShadow() { + return this._useOpacityTextureForTransparentShadow; + } + set useOpacityTextureForTransparentShadow(value) { + if (value === this._useOpacityTextureForTransparentShadow) { + return; + } + this._useOpacityTextureForTransparentShadow = value; + if (this._shadowGenerator) { + this._shadowGenerator.useOpacityTextureForTransparentShadow = value; + } + } + /** + * The filter to apply to the shadow map. + */ + get filter() { + return this._filter; + } + set filter(value) { + if (value === this._filter) { + return; + } + this._filter = value; + if (this._shadowGenerator) { + this._shadowGenerator.filter = value; + } + } + /** + * The filtering quality to apply to the filter. + */ + get filteringQuality() { + return this._filteringQuality; + } + set filteringQuality(value) { + if (value === this._filteringQuality) { + return; + } + this._filteringQuality = value; + if (this._shadowGenerator) { + this._shadowGenerator.filteringQuality = value; + } + } + _createShadowGenerator() { + this._shadowGenerator = new ShadowGenerator(this._mapSize, this._light, this._useFloat32TextureType, undefined, this._useRedTextureFormat); + } + _setupShadowGenerator() { + this._shadowGenerator?.dispose(); + this._shadowGenerator = undefined; + if (this._light !== undefined) { + this._createShadowGenerator(); + const shadowGenerator = this._shadowGenerator; + if (shadowGenerator === undefined) { + return; + } + shadowGenerator.bias = this._bias; + shadowGenerator.normalBias = this._normalBias; + shadowGenerator.darkness = this._darkness; + shadowGenerator.transparencyShadow = this._transparencyShadow; + shadowGenerator.enableSoftTransparentShadow = this._enableSoftTransparentShadow; + shadowGenerator.useOpacityTextureForTransparentShadow = this._useOpacityTextureForTransparentShadow; + shadowGenerator.filter = this._filter; + shadowGenerator.filteringQuality = this._filteringQuality; + const shadowMap = shadowGenerator.getShadowMap(); + shadowMap._disableEngineStages = true; + shadowMap.cameraForLOD = this._camera; + this.shadowGenerator = shadowGenerator; + } + } + isReady() { + return !!this._shadowGenerator && !!this._shadowGenerator.getShadowMap()?.isReadyForRendering(); + } + /** + * Creates a new shadow generator task. + * @param name The name of the task. + * @param frameGraph The frame graph the task belongs to. + * @param scene The scene to create the shadow generator for. + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph); + this._mapSize = 1024; + this._useFloat32TextureType = false; + this._useRedTextureFormat = true; + this._bias = 0.01; + this._normalBias = 0; + this._darkness = 0; + this._transparencyShadow = false; + this._enableSoftTransparentShadow = false; + this._useOpacityTextureForTransparentShadow = false; + this._filter = ShadowGenerator.FILTER_PCF; + this._filteringQuality = ShadowGenerator.QUALITY_HIGH; + this._engine = scene.getEngine(); + this._scene = scene; + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + } + record() { + if (this.light === undefined || this.objectList === undefined || this.camera === undefined) { + throw new Error(`FrameGraphShadowGeneratorTask ${this.name}: light, objectList and camera are required`); + } + // Make sure the renderList / particleSystemList are set when FrameGraphShadowGeneratorTask.isReady() is called! + const shadowMap = this._shadowGenerator.getShadowMap(); + shadowMap.renderList = this.objectList.meshes; + shadowMap.particleSystemList = this.objectList.particleSystems; + const shadowTextureHandle = this._frameGraph.textureManager.importTexture(`${this.name} shadowmap`, this._shadowGenerator.getShadowMap().getInternalTexture()); + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, shadowTextureHandle); + const pass = this._frameGraph.addPass(this.name); + pass.setExecuteFunc((_context) => { + if (!this.light.isEnabled() || !this.light.shadowEnabled) { + return; + } + const shadowMap = this._shadowGenerator.getShadowMap(); + shadowMap.renderList = this.objectList.meshes; + shadowMap.particleSystemList = this.objectList.particleSystems; + const currentRenderTarget = this._engine._currentRenderTarget; + this._scene.incrementRenderId(); + this._scene.resetCachedMaterial(); + shadowMap.render(); + if (this._engine._currentRenderTarget !== currentRenderTarget) { + if (!currentRenderTarget) { + this._engine.restoreDefaultFramebuffer(); + } + else { + this._engine.bindFramebuffer(currentRenderTarget); + } + } + }); + const passDisabled = this._frameGraph.addPass(this.name + "_disabled", true); + passDisabled.setExecuteFunc((_context) => { }); + } + dispose() { + this._shadowGenerator?.dispose(); + this._shadowGenerator = undefined; + } +} + +/** + * Task used to generate a cascaded shadow map from a list of objects. + */ +class FrameGraphCascadedShadowGeneratorTask extends FrameGraphShadowGeneratorTask { + constructor() { + super(...arguments); + this._numCascades = CascadedShadowGenerator.DEFAULT_CASCADES_COUNT; + this._debug = false; + this._stabilizeCascades = false; + this._lambda = 0.5; + this._cascadeBlendPercentage = 0.1; + this._depthClamp = true; + this._autoCalcDepthBounds = false; + this._shadowMaxZ = 10000; + } + /** + * Checks if a shadow generator task is a cascaded shadow generator task. + * @param task The task to check. + * @returns True if the task is a cascaded shadow generator task, else false. + */ + static IsCascadedShadowGenerator(task) { + return task.numCascades !== undefined; + } + /** + * The number of cascades. + */ + get numCascades() { + return this._numCascades; + } + set numCascades(value) { + if (value === this._numCascades) { + return; + } + this._numCascades = value; + this._setupShadowGenerator(); + } + /** + * Gets or sets a value indicating whether the shadow generator should display the cascades. + */ + get debug() { + return this._debug; + } + set debug(value) { + if (value === this._debug) { + return; + } + this._debug = value; + if (this._shadowGenerator) { + this._shadowGenerator.debug = value; + } + } + /** + * Gets or sets a value indicating whether the shadow generator should stabilize the cascades. + */ + get stabilizeCascades() { + return this._stabilizeCascades; + } + set stabilizeCascades(value) { + if (value === this._stabilizeCascades) { + return; + } + this._stabilizeCascades = value; + if (this._shadowGenerator) { + this._shadowGenerator.stabilizeCascades = value; + } + } + /** + * Gets or sets the lambda parameter of the shadow generator. + */ + get lambda() { + return this._lambda; + } + set lambda(value) { + if (value === this._lambda) { + return; + } + this._lambda = value; + if (this._shadowGenerator) { + this._shadowGenerator.lambda = value; + } + } + /** + * Gets or sets the cascade blend percentage. + */ + get cascadeBlendPercentage() { + return this._cascadeBlendPercentage; + } + set cascadeBlendPercentage(value) { + if (value === this._cascadeBlendPercentage) { + return; + } + this._cascadeBlendPercentage = value; + if (this._shadowGenerator) { + this._shadowGenerator.cascadeBlendPercentage = value; + } + } + /** + * Gets or sets a value indicating whether the shadow generator should use depth clamping. + */ + get depthClamp() { + return this._depthClamp; + } + set depthClamp(value) { + if (value === this._depthClamp) { + return; + } + this._depthClamp = value; + if (this._shadowGenerator) { + this._shadowGenerator.depthClamp = value; + } + } + /** + * Gets or sets a value indicating whether the shadow generator should automatically calculate the depth bounds. + */ + get autoCalcDepthBounds() { + return this._autoCalcDepthBounds; + } + set autoCalcDepthBounds(value) { + if (value === this._autoCalcDepthBounds) { + return; + } + this._autoCalcDepthBounds = value; + if (this._shadowGenerator) { + this._shadowGenerator.autoCalcDepthBounds = value; + } + } + /** + * Gets or sets the maximum shadow Z value. + */ + get shadowMaxZ() { + return this._shadowMaxZ; + } + set shadowMaxZ(value) { + if (value === this._shadowMaxZ) { + return; + } + this._shadowMaxZ = value; + if (this._shadowGenerator) { + this._shadowGenerator.shadowMaxZ = value; + } + } + _createShadowGenerator() { + if (!(this.light instanceof DirectionalLight)) { + throw new Error(`FrameGraphCascadedShadowGeneratorTask ${this.name}: the CSM shadow generator only supports directional lights.`); + } + this._shadowGenerator = new CascadedShadowGenerator(this.mapSize, this.light, this.useFloat32TextureType, this.camera, this.useRedTextureFormat); + this._shadowGenerator.numCascades = this._numCascades; + } + _setupShadowGenerator() { + super._setupShadowGenerator(); + const shadowGenerator = this._shadowGenerator; + if (shadowGenerator === undefined) { + return; + } + shadowGenerator.debug = this._debug; + shadowGenerator.stabilizeCascades = this._stabilizeCascades; + shadowGenerator.lambda = this._lambda; + shadowGenerator.cascadeBlendPercentage = this._cascadeBlendPercentage; + shadowGenerator.depthClamp = this._depthClamp; + shadowGenerator.autoCalcDepthBounds = this._autoCalcDepthBounds; + shadowGenerator.shadowMaxZ = this._shadowMaxZ; + } +} + +/** + * Task used to render objects to a texture. + */ +class FrameGraphObjectRendererTask extends FrameGraphTask { + /** + * Gets or sets the camera used to render the objects. + */ + get camera() { + return this._camera; + } + set camera(camera) { + this._camera = camera; + this._renderer.activeCamera = this.camera; + } + /** + * The object renderer used to render the objects. + */ + get objectRenderer() { + return this._renderer; + } + get name() { + return this._name; + } + set name(value) { + this._name = value; + if (this._renderer) { + this._renderer.name = value; + } + } + /** + * Constructs a new object renderer task. + * @param name The name of the task. + * @param frameGraph The frame graph the task belongs to. + * @param scene The scene the frame graph is associated with. + * @param options The options of the object renderer. + * @param existingObjectRenderer An existing object renderer to use (optional). If provided, the options parameter will be ignored. + */ + constructor(name, frameGraph, scene, options, existingObjectRenderer) { + super(name, frameGraph); + /** + * The shadow generators used to render the objects (optional). + */ + this.shadowGenerators = []; + /** + * If depth testing should be enabled (default is true). + */ + this.depthTest = true; + /** + * If depth writing should be enabled (default is true). + */ + this.depthWrite = true; + /** + * If shadows should be disabled (default is false). + */ + this.disableShadows = false; + /** + * If the rendering should be done in linear space (default is false). + */ + this.renderInLinearSpace = false; + this._onBeforeRenderObservable = null; + this._onAfterRenderObservable = null; + this._externalObjectRenderer = false; + this._scene = scene; + this._externalObjectRenderer = !!existingObjectRenderer; + this._renderer = existingObjectRenderer ?? new ObjectRenderer(name, scene, options); + this.name = name; + if (!this._externalObjectRenderer) { + this._renderer.onBeforeRenderingManagerRenderObservable.add(() => { + if (!this._renderer.options.doNotChangeAspectRatio) { + scene.updateTransformMatrix(true); + } + }); + } + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.outputDepthTexture = this._frameGraph.textureManager.createDanglingHandle(); + } + isReady() { + return this._renderer.isReadyForRendering(this._textureWidth, this._textureHeight); + } + record(skipCreationOfDisabledPasses = false, additionalExecute) { + if (this.targetTexture === undefined || this.objectList === undefined) { + throw new Error(`FrameGraphObjectRendererTask ${this.name}: targetTexture and objectList are required`); + } + // Make sure the renderList / particleSystemList are set when FrameGraphObjectRendererTask.isReady() is called! + this._renderer.renderList = this.objectList.meshes; + this._renderer.particleSystemList = this.objectList.particleSystems; + this._renderer.renderInLinearSpace = this.renderInLinearSpace; + const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.targetTexture); + let depthEnabled = false; + if (this.depthTexture !== undefined) { + if (this.depthTexture === backbufferDepthStencilTextureHandle && this.targetTexture !== backbufferColorTextureHandle) { + throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer color texture is the only color texture allowed when the depth is the back buffer depth/stencil`); + } + if (this.depthTexture !== backbufferDepthStencilTextureHandle && this.targetTexture === backbufferColorTextureHandle) { + throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer depth/stencil texture is the only depth texture allowed when the target is the back buffer color`); + } + const depthTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.depthTexture); + if (depthTextureDescription.options.samples !== outputTextureDescription.options.samples) { + throw new Error(`FrameGraphObjectRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`); + } + depthEnabled = true; + } + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture); + if (this.depthTexture !== undefined) { + this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture, this.depthTexture); + } + this._textureWidth = outputTextureDescription.size.width; + this._textureHeight = outputTextureDescription.size.height; + this._setLightsForShadow(); + const pass = this._frameGraph.addRenderPass(this.name); + pass.setRenderTarget(this.targetTexture); + pass.setRenderTargetDepth(this.depthTexture); + pass.setExecuteFunc((context) => { + this._renderer.renderList = this.objectList.meshes; + this._renderer.particleSystemList = this.objectList.particleSystems; + this._renderer.renderInLinearSpace = this.renderInLinearSpace; + context.setDepthStates(this.depthTest && depthEnabled, this.depthWrite && depthEnabled); + context.render(this._renderer, this._textureWidth, this._textureHeight); + additionalExecute?.(context); + }); + if (!skipCreationOfDisabledPasses) { + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.setRenderTarget(this.targetTexture); + passDisabled.setRenderTargetDepth(this.depthTexture); + passDisabled.setExecuteFunc((_context) => { }); + } + return pass; + } + dispose() { + this._renderer.onBeforeRenderObservable.remove(this._onBeforeRenderObservable); + this._renderer.onAfterRenderObservable.remove(this._onAfterRenderObservable); + if (!this._externalObjectRenderer) { + this._renderer.dispose(); + } + super.dispose(); + } + _setLightsForShadow() { + const lightsForShadow = new Set(); + const shadowEnabled = new Map(); + if (this.shadowGenerators) { + for (const shadowGeneratorTask of this.shadowGenerators) { + const shadowGenerator = shadowGeneratorTask.shadowGenerator; + const light = shadowGenerator.getLight(); + if (light.isEnabled() && light.shadowEnabled) { + lightsForShadow.add(light); + if (FrameGraphCascadedShadowGeneratorTask.IsCascadedShadowGenerator(shadowGeneratorTask)) { + light._shadowGenerators.set(shadowGeneratorTask.camera, shadowGenerator); + } + else { + light._shadowGenerators.set(null, shadowGenerator); + } + } + } + } + this._renderer.onBeforeRenderObservable.remove(this._onBeforeRenderObservable); + this._onBeforeRenderObservable = this._renderer.onBeforeRenderObservable.add(() => { + for (let i = 0; i < this._scene.lights.length; i++) { + const light = this._scene.lights[i]; + shadowEnabled.set(light, light.shadowEnabled); + light.shadowEnabled = !this.disableShadows && lightsForShadow.has(light); + } + }); + this._renderer.onAfterRenderObservable.remove(this._onAfterRenderObservable); + this._onAfterRenderObservable = this._renderer.onAfterRenderObservable.add(() => { + for (let i = 0; i < this._scene.lights.length; i++) { + const light = this._scene.lights[i]; + light.shadowEnabled = shadowEnabled.get(light); + } + }); + } +} + +/** + * Defines a connection point to be used for points with a custom object type + */ +class NodeRenderGraphConnectionPointCustomObject extends NodeRenderGraphConnectionPoint { + /** + * Creates a new connection point + * @param name defines the connection point name + * @param ownerBlock defines the block hosting this connection point + * @param direction defines the direction of the connection point + * @param _blockType + * @param _blockName + */ + constructor(name, ownerBlock, direction, + // @internal + _blockType, _blockName) { + super(name, ownerBlock, direction); + this._blockType = _blockType; + this._blockName = _blockName; + this.needDualDirectionValidation = true; + } + checkCompatibilityState(connectionPoint) { + return connectionPoint instanceof NodeRenderGraphConnectionPointCustomObject && connectionPoint._blockName === this._blockName + ? 0 /* NodeRenderGraphConnectionPointCompatibilityStates.Compatible */ + : 1 /* NodeRenderGraphConnectionPointCompatibilityStates.TypeIncompatible */; + } + createCustomInputBlock() { + return [new this._blockType(this._blockName), this.name]; + } +} + +/** + * @internal + */ +class NodeRenderGraphBaseObjectRendererBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphBaseObjectRendererBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this.registerInput("depth", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera); + this.registerInput("objects", NodeRenderGraphBlockConnectionPointTypes.ObjectList); + this._addDependenciesInput(); + this.registerInput("shadowGenerators", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.registerOutput("outputDepth", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.registerOutput("objectRenderer", NodeRenderGraphBlockConnectionPointTypes.Object, new NodeRenderGraphConnectionPointCustomObject("objectRenderer", this, 1 /* NodeRenderGraphConnectionPointDirection.Output */, NodeRenderGraphBaseObjectRendererBlock, "NodeRenderGraphBaseObjectRendererBlock")); + this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBufferDepthStencil); + this.depth.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureDepthStencilAttachment | NodeRenderGraphBlockConnectionPointTypes.TextureBackBufferDepthStencilAttachment); + this.shadowGenerators.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator | NodeRenderGraphBlockConnectionPointTypes.ResourceContainer); + this.output._typeConnectionSource = this.target; + this.outputDepth._typeConnectionSource = this.depth; + } + /** Indicates if depth testing must be enabled or disabled */ + get depthTest() { + return this._frameGraphTask.depthTest; + } + set depthTest(value) { + this._frameGraphTask.depthTest = value; + } + /** Indicates if depth writing must be enabled or disabled */ + get depthWrite() { + return this._frameGraphTask.depthWrite; + } + set depthWrite(value) { + this._frameGraphTask.depthWrite = value; + } + /** Indicates if shadows must be enabled or disabled */ + get disableShadows() { + return this._frameGraphTask.disableShadows; + } + set disableShadows(value) { + this._frameGraphTask.disableShadows = value; + } + /** If the rendering should be done in linear space */ + get renderInLinearSpace() { + return this._frameGraphTask.renderInLinearSpace; + } + set renderInLinearSpace(value) { + this._frameGraphTask.renderInLinearSpace = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphBaseObjectRendererBlock"; + } + /** + * Gets the target texture input component + */ + get target() { + return this._inputs[0]; + } + /** + * Gets the depth texture input component + */ + get depth() { + return this._inputs[1]; + } + /** + * Gets the camera input component + */ + get camera() { + return this._inputs[2]; + } + /** + * Gets the objects input component + */ + get objects() { + return this._inputs[3]; + } + /** + * Gets the dependencies input component + */ + get dependencies() { + return this._inputs[4]; + } + /** + * Gets the shadowGenerators input component + */ + get shadowGenerators() { + return this._inputs[5]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the output depth component + */ + get outputDepth() { + return this._outputs[1]; + } + /** + * Gets the objectRenderer component + */ + get objectRenderer() { + return this._outputs[2]; + } + _buildBlock(state) { + super._buildBlock(state); + this.output.value = this._frameGraphTask.outputTexture; // the value of the output connection point is the "output" texture of the task + this.outputDepth.value = this._frameGraphTask.outputDepthTexture; // the value of the outputDepth connection point is the "outputDepth" texture of the task + this.objectRenderer.value = this._frameGraphTask; // the value of the objectRenderer connection point is the task itself + this._frameGraphTask.targetTexture = this.target.connectedPoint?.value; + this._frameGraphTask.depthTexture = this.depth.connectedPoint?.value; + this._frameGraphTask.camera = this.camera.connectedPoint?.value; + this._frameGraphTask.objectList = this.objects.connectedPoint?.value; + this._frameGraphTask.shadowGenerators = []; + const shadowGeneratorsConnectedPoint = this.shadowGenerators.connectedPoint; + if (shadowGeneratorsConnectedPoint) { + if (shadowGeneratorsConnectedPoint.type === NodeRenderGraphBlockConnectionPointTypes.ResourceContainer) { + const container = shadowGeneratorsConnectedPoint.ownerBlock; + container.inputs.forEach((input) => { + if (input.connectedPoint && input.connectedPoint.value !== undefined && NodeRenderGraphConnectionPoint.IsShadowGenerator(input.connectedPoint.value)) { + this._frameGraphTask.shadowGenerators.push(input.connectedPoint.value); + } + }); + } + else if (NodeRenderGraphConnectionPoint.IsShadowGenerator(shadowGeneratorsConnectedPoint.value)) { + this._frameGraphTask.shadowGenerators[0] = shadowGeneratorsConnectedPoint.value; + } + } + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.depthTest = ${this.depthTest};`); + codes.push(`${this._codeVariableName}.depthWrite = ${this.depthWrite};`); + codes.push(`${this._codeVariableName}.disableShadows = ${this.disableShadows};`); + codes.push(`${this._codeVariableName}.renderInLinearSpace = ${this.renderInLinearSpace};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.depthTest = this.depthTest; + serializationObject.depthWrite = this.depthWrite; + serializationObject.disableShadows = this.disableShadows; + serializationObject.renderInLinearSpace = this.renderInLinearSpace; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.depthTest = serializationObject.depthTest; + this.depthWrite = serializationObject.depthWrite; + this.disableShadows = serializationObject.disableShadows; + this.renderInLinearSpace = !!serializationObject.renderInLinearSpace; + } +} +__decorate([ + editableInPropertyPage("Depth test", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphBaseObjectRendererBlock.prototype, "depthTest", null); +__decorate([ + editableInPropertyPage("Depth write", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphBaseObjectRendererBlock.prototype, "depthWrite", null); +__decorate([ + editableInPropertyPage("Disable shadows", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphBaseObjectRendererBlock.prototype, "disableShadows", null); +__decorate([ + editableInPropertyPage("Render in linear space", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphBaseObjectRendererBlock.prototype, "renderInLinearSpace", null); + +/** + * Block that render objects to a render target + */ +class NodeRenderGraphObjectRendererBlock extends NodeRenderGraphBaseObjectRendererBlock { + /** + * Create a new NodeRenderGraphObjectRendererBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param doNotChangeAspectRatio True (default) to not change the aspect ratio of the scene in the RTT + */ + constructor(name, frameGraph, scene, doNotChangeAspectRatio = true) { + super(name, frameGraph, scene); + this._additionalConstructionParameters = [doNotChangeAspectRatio]; + this._frameGraphTask = new FrameGraphObjectRendererTask(this.name, frameGraph, scene, { doNotChangeAspectRatio }); + } + /** True (default) to not change the aspect ratio of the scene in the RTT */ + get doNotChangeAspectRatio() { + return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio; + } + set doNotChangeAspectRatio(value) { + const disabled = this._frameGraphTask.disabled; + const depthTest = this.depthTest; + const depthWrite = this.depthWrite; + const disableShadows = this.disableShadows; + const renderInLinearSpace = this.renderInLinearSpace; + this._frameGraphTask.dispose(); + this._frameGraphTask = new FrameGraphObjectRendererTask(this.name, this._frameGraph, this._scene, { doNotChangeAspectRatio: value }); + this._additionalConstructionParameters = [value]; + this.depthTest = depthTest; + this.depthWrite = depthWrite; + this.disableShadows = disableShadows; + this.renderInLinearSpace = renderInLinearSpace; + this._frameGraphTask.disabled = disabled; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphObjectRendererBlock"; + } +} +__decorate([ + editableInPropertyPage("Do not change aspect ratio", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphObjectRendererBlock.prototype, "doNotChangeAspectRatio", null); +RegisterClass("BABYLON.NodeRenderGraphObjectRendererBlock", NodeRenderGraphObjectRendererBlock); + +/** + * Class used to store node based render graph build state + */ +class NodeRenderGraphBuildState { + constructor() { + /** Gets or sets a boolean indicating that verbose mode is on */ + this.verbose = false; + /** + * Gets or sets the list of non connected mandatory inputs + * @internal + */ + this._notConnectedNonOptionalInputs = []; + } + /** + * Emits console errors and exceptions if there is a failing check + * @param errorObservable defines an Observable to send the error message + * @returns true if all checks pass + */ + emitErrors(errorObservable = null) { + let errorMessage = ""; + for (const notConnectedInput of this._notConnectedNonOptionalInputs) { + errorMessage += `input "${notConnectedInput.name}" from block "${notConnectedInput.ownerBlock.name}"[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional.\n`; + } + if (errorMessage) { + if (errorObservable) { + errorObservable.notifyObservers(errorMessage); + } + Logger.Error("Build of node render graph failed:\n" + errorMessage); + return false; + } + return true; + } +} + +/** + * Defines a node render graph + */ +class NodeRenderGraph { + /** @returns the inspector from bundle or global */ + _getGlobalNodeRenderGraphEditor() { + // UMD Global name detection from Webpack Bundle UMD Name. + if (typeof NODERENDERGRAPHEDITOR !== "undefined") { + return NODERENDERGRAPHEDITOR; + } + // In case of module let's check the global emitted from the editor entry point. + if (typeof BABYLON !== "undefined" && typeof BABYLON.NodeRenderGraphEditor !== "undefined") { + return BABYLON; + } + return undefined; + } + /** + * Gets the frame graph used by this node render graph + */ + get frameGraph() { + return this._frameGraph; + } + /** + * Gets the scene used by this node render graph + * @returns the scene used by this node render graph + */ + getScene() { + return this._scene; + } + /** + * Creates a new node render graph + * @param name defines the name of the node render graph + * @param scene defines the scene to use to execute the graph + * @param options defines the options to use when creating the graph + */ + constructor(name, scene, options) { + this._buildId = NodeRenderGraph._BuildIdGenerator++; + // eslint-disable-next-line @typescript-eslint/naming-convention + this.BJSNODERENDERGRAPHEDITOR = this._getGlobalNodeRenderGraphEditor(); + /** + * Gets or sets data used by visual editor + * @see https://nrge.babylonjs.com + */ + this.editorData = null; + /** + * Gets an array of blocks that needs to be serialized even if they are not yet connected + */ + this.attachedBlocks = []; + /** + * Observable raised when the node render graph is built + */ + this.onBuildObservable = new Observable(); + /** + * Observable raised when an error is detected + */ + this.onBuildErrorObservable = new Observable(); + /** Gets or sets the RenderGraphOutputBlock used to gather the final node render graph data */ + this.outputBlock = null; + this._resizeObserver = null; + this.name = name; + this._scene = scene; + this._engine = scene.getEngine(); + options = { + debugTextures: false, + autoConfigure: false, + verbose: false, + rebuildGraphOnEngineResize: true, + autoFillExternalInputs: true, + ...options, + }; + this._options = options; + this._frameGraph = new FrameGraph(this._scene, options.debugTextures, this); + this._frameGraph.name = name; + if (options.rebuildGraphOnEngineResize) { + this._resizeObserver = this._engine.onResizeObservable.add(() => { + this.build(); + }); + } + } + /** + * Gets the current class name ("NodeRenderGraph") + * @returns the class name + */ + getClassName() { + return "NodeRenderGraph"; + } + /** + * Gets a block by its name + * @param name defines the name of the block to retrieve + * @returns the required block or null if not found + */ + getBlockByName(name) { + let result = null; + for (const block of this.attachedBlocks) { + if (block.name === name) { + if (!result) { + result = block; + } + else { + Tools.Warn("More than one block was found with the name `" + name + "`"); + return result; + } + } + } + return result; + } + /** + * Get a block using a predicate + * @param predicate defines the predicate used to find the good candidate + * @returns the required block or null if not found + */ + getBlockByPredicate(predicate) { + for (const block of this.attachedBlocks) { + if (predicate(block)) { + return block; + } + } + return null; + } + /** + * Get all blocks that match a predicate + * @param predicate defines the predicate used to find the good candidate(s) + * @returns the list of blocks found + */ + getBlocksByPredicate(predicate) { + const blocks = []; + for (const block of this.attachedBlocks) { + if (predicate(block)) { + blocks.push(block); + } + } + return blocks; + } + /** + * Gets the list of input blocks attached to this material + * @returns an array of InputBlocks + */ + getInputBlocks() { + const blocks = []; + for (const block of this.attachedBlocks) { + if (block.isInput) { + blocks.push(block); + } + } + return blocks; + } + /** + * Launch the node render graph editor + * @param config Define the configuration of the editor + * @returns a promise fulfilled when the node editor is visible + */ + edit(config) { + return new Promise((resolve) => { + this.BJSNODERENDERGRAPHEDITOR = this.BJSNODERENDERGRAPHEDITOR || this._getGlobalNodeRenderGraphEditor(); + if (typeof this.BJSNODERENDERGRAPHEDITOR == "undefined") { + const editorUrl = config && config.editorURL ? config.editorURL : NodeRenderGraph.EditorURL; + // Load editor and add it to the DOM + Tools.LoadBabylonScript(editorUrl, () => { + this.BJSNODERENDERGRAPHEDITOR = this.BJSNODERENDERGRAPHEDITOR || this._getGlobalNodeRenderGraphEditor(); + this._createNodeEditor(config?.nodeRenderGraphEditorConfig); + resolve(); + }); + } + else { + // Otherwise creates the editor + this._createNodeEditor(config?.nodeRenderGraphEditorConfig); + resolve(); + } + }); + } + /** + * Creates the node editor window. + * @param additionalConfig Additional configuration for the FGE + */ + _createNodeEditor(additionalConfig) { + const nodeEditorConfig = { + nodeRenderGraph: this, + ...additionalConfig, + }; + this.BJSNODERENDERGRAPHEDITOR.NodeRenderGraphEditor.Show(nodeEditorConfig); + } + /** + * Build the final list of blocks that will be executed by the "execute" method + */ + build() { + if (!this.outputBlock) { + throw new Error("You must define the outputBlock property before building the node render graph"); + } + this._initializeBlock(this.outputBlock); + this._frameGraph.clear(); + const state = new NodeRenderGraphBuildState(); + state.buildId = this._buildId; + state.verbose = this._options.verbose; + if (this._options.autoFillExternalInputs) { + this._autoFillExternalInputs(); + } + try { + this.outputBlock.build(state); + this._frameGraph.build(); + } + finally { + this._buildId = NodeRenderGraph._BuildIdGenerator++; + if (state.emitErrors(this.onBuildErrorObservable)) { + this.onBuildObservable.notifyObservers(this); + } + } + } + _autoFillExternalInputs() { + const allInputs = this.getInputBlocks(); + const shadowLights = []; + for (const light of this._scene.lights) { + if (light.setShadowProjectionMatrix !== undefined) { + shadowLights.push(light); + } + } + let cameraIndex = 0; + let lightIndex = 0; + for (const input of allInputs) { + if (!input.isExternal) { + continue; + } + if (!input.isAnAncestorOfType("NodeRenderGraphOutputBlock")) { + continue; + } + if ((input.type & NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer) !== 0) ; + else if (input.isCamera()) { + const camera = this._scene.cameras[cameraIndex++] || this._scene.cameras[0]; + if (!this._scene.cameraToUseForPointers) { + this._scene.cameraToUseForPointers = camera; + } + input.value = camera; + } + else if (input.isObjectList()) { + input.value = { meshes: this._scene.meshes, particleSystems: this._scene.particleSystems }; + } + else if (input.isShadowLight()) { + if (lightIndex < shadowLights.length) { + input.value = shadowLights[lightIndex++]; + lightIndex = lightIndex % shadowLights.length; + } + } + } + } + /** + * Returns a promise that resolves when the node render graph is ready to be executed + * This method must be called after the graph has been built (NodeRenderGraph.build called)! + * @param timeStep Time step in ms between retries (default is 16) + * @param maxTimeout Maximum time in ms to wait for the graph to be ready (default is 30000) + * @returns The promise that resolves when the graph is ready + */ + whenReadyAsync(timeStep = 16, maxTimeout = 30000) { + return this._frameGraph.whenReadyAsync(timeStep, maxTimeout); + } + /** + * Execute the graph (the graph must have been built before!) + */ + execute() { + this._frameGraph.execute(); + } + _initializeBlock(node) { + node.initialize(); + if (this._options.autoConfigure) { + node.autoConfigure(); + } + if (this.attachedBlocks.indexOf(node) === -1) { + this.attachedBlocks.push(node); + } + for (const input of node.inputs) { + const connectedPoint = input.connectedPoint; + if (connectedPoint) { + const block = connectedPoint.ownerBlock; + if (block !== node) { + this._initializeBlock(block); + } + } + } + } + /** + * Clear the current graph + */ + clear() { + this.outputBlock = null; + this.attachedBlocks.length = 0; + } + /** + * Remove a block from the current graph + * @param block defines the block to remove + */ + removeBlock(block) { + const attachedBlockIndex = this.attachedBlocks.indexOf(block); + if (attachedBlockIndex > -1) { + this.attachedBlocks.splice(attachedBlockIndex, 1); + } + if (block === this.outputBlock) { + this.outputBlock = null; + } + } + /** + * Clear the current graph and load a new one from a serialization object + * @param source defines the JSON representation of the graph + * @param merge defines whether or not the source must be merged or replace the current content + */ + parseSerializedObject(source, merge = false) { + if (!merge) { + this.clear(); + } + const map = {}; + // Create blocks + for (const parsedBlock of source.blocks) { + const blockType = GetClass(parsedBlock.customType); + if (blockType) { + const additionalConstructionParameters = parsedBlock.additionalConstructionParameters; + const block = additionalConstructionParameters + ? new blockType("", this._frameGraph, this._scene, ...additionalConstructionParameters) + : new blockType("", this._frameGraph, this._scene); + block._deserialize(parsedBlock); + map[parsedBlock.id] = block; + this.attachedBlocks.push(block); + } + } + // Reconnect teleportation + for (const block of this.attachedBlocks) { + if (block.isTeleportOut) { + const teleportOut = block; + const id = teleportOut._tempEntryPointUniqueId; + if (id) { + const source = map[id]; + if (source) { + source.attachToEndpoint(teleportOut); + } + } + } + } + // Connections - Starts with input blocks only (except if in "merge" mode where we scan all blocks) + for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) { + const parsedBlock = source.blocks[blockIndex]; + const block = map[parsedBlock.id]; + if (!block) { + continue; + } + if (block.inputs.length && parsedBlock.inputs.some((i) => i.targetConnectionName) && !merge) { + continue; + } + this._restoreConnections(block, source, map); + } + // Outputs + if (source.outputNodeId) { + this.outputBlock = map[source.outputNodeId]; + } + // UI related info + if (source.locations || (source.editorData && source.editorData.locations)) { + const locations = source.locations || source.editorData.locations; + for (const location of locations) { + if (map[location.blockId]) { + location.blockId = map[location.blockId].uniqueId; + } + } + if (merge && this.editorData && this.editorData.locations) { + locations.concat(this.editorData.locations); + } + if (source.locations) { + this.editorData = { + locations: locations, + }; + } + else { + this.editorData = source.editorData; + this.editorData.locations = locations; + } + const blockMap = []; + for (const key in map) { + blockMap[key] = map[key].uniqueId; + } + this.editorData.map = blockMap; + } + this.comment = source.comment; + } + _restoreConnections(block, source, map) { + for (const outputPoint of block.outputs) { + for (const candidate of source.blocks) { + const target = map[candidate.id]; + if (!target) { + continue; + } + for (const input of candidate.inputs) { + if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) { + const inputPoint = target.getInputByName(input.inputName); + if (!inputPoint || inputPoint.isConnected) { + continue; + } + outputPoint.connectTo(inputPoint, true); + this._restoreConnections(target, source, map); + continue; + } + } + } + } + } + /** + * Generate a string containing the code declaration required to create an equivalent of this node render graph + * @returns a string + */ + generateCode() { + let alreadyDumped = []; + const blocks = []; + const uniqueNames = ["const", "var", "let"]; + // Gets active blocks + if (this.outputBlock) { + this._gatherBlocks(this.outputBlock, blocks); + } + // Generate + const options = JSON.stringify(this._options); + let codeString = `let nodeRenderGraph = new BABYLON.NodeRenderGraph("${this.name || "render graph"}", scene, ${options});\n`; + for (const node of blocks) { + if (node.isInput && alreadyDumped.indexOf(node) === -1) { + codeString += node._dumpCode(uniqueNames, alreadyDumped) + "\n"; + } + } + if (this.outputBlock) { + // Connections + alreadyDumped = []; + codeString += "// Connections\n"; + codeString += this.outputBlock._dumpCodeForOutputConnections(alreadyDumped); + // Output nodes + codeString += "// Output nodes\n"; + codeString += `nodeRenderGraph.outputBlock = ${this.outputBlock._codeVariableName};\n`; + codeString += `nodeRenderGraph.build();\n`; + } + return codeString; + } + _gatherBlocks(rootNode, list) { + if (list.indexOf(rootNode) !== -1) { + return; + } + list.push(rootNode); + for (const input of rootNode.inputs) { + const connectedPoint = input.connectedPoint; + if (connectedPoint) { + const block = connectedPoint.ownerBlock; + if (block !== rootNode) { + this._gatherBlocks(block, list); + } + } + } + // Teleportation + if (rootNode.isTeleportOut) { + const block = rootNode; + if (block.entryPoint) { + this._gatherBlocks(block.entryPoint, list); + } + } + } + /** + * Clear the current graph and set it to a default state + */ + setToDefault() { + this.clear(); + this.editorData = null; + // Source textures + const colorTexture = new NodeRenderGraphInputBlock("Color Texture", this._frameGraph, this._scene, NodeRenderGraphBlockConnectionPointTypes.Texture); + colorTexture.creationOptions.options.samples = 4; + const depthTexture = new NodeRenderGraphInputBlock("Depth Texture", this._frameGraph, this._scene, NodeRenderGraphBlockConnectionPointTypes.TextureDepthStencilAttachment); + depthTexture.creationOptions.options.samples = 4; + // Clear texture + const clear = new NodeRenderGraphClearBlock("Clear", this._frameGraph, this._scene); + clear.clearDepth = true; + clear.clearStencil = true; + colorTexture.output.connectTo(clear.target); + depthTexture.output.connectTo(clear.depth); + // Render objects + const camera = new NodeRenderGraphInputBlock("Camera", this._frameGraph, this._scene, NodeRenderGraphBlockConnectionPointTypes.Camera); + const objectList = new NodeRenderGraphInputBlock("Object List", this._frameGraph, this._scene, NodeRenderGraphBlockConnectionPointTypes.ObjectList); + const mainRendering = new NodeRenderGraphObjectRendererBlock("Main Rendering", this._frameGraph, this._scene); + camera.output.connectTo(mainRendering.camera); + objectList.output.connectTo(mainRendering.objects); + clear.output.connectTo(mainRendering.target); + clear.outputDepth.connectTo(mainRendering.depth); + // Final output + const output = new NodeRenderGraphOutputBlock("Output", this._frameGraph, this._scene); + mainRendering.output.connectTo(output.texture); + this.outputBlock = output; + } + /** + * Makes a duplicate of the current node render graph. + * @param name defines the name to use for the new node render graph + * @returns the new node render graph + */ + clone(name) { + const serializationObject = this.serialize(); + const clone = SerializationHelper.Clone(() => new NodeRenderGraph(name, this._scene), this); + clone.name = name; + clone.parseSerializedObject(serializationObject); + clone._buildId = this._buildId; + clone.build(); + return clone; + } + /** + * Serializes this node render graph in a JSON representation + * @param selectedBlocks defines the list of blocks to save (if null the whole node render graph will be saved) + * @returns the serialized node render graph object + */ + serialize(selectedBlocks) { + const serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this); + serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy + let blocks = []; + if (selectedBlocks) { + blocks = selectedBlocks; + } + else { + serializationObject.customType = "BABYLON.NodeRenderGraph"; + if (this.outputBlock) { + serializationObject.outputNodeId = this.outputBlock.uniqueId; + } + } + // Blocks + serializationObject.blocks = []; + for (const block of blocks) { + serializationObject.blocks.push(block.serialize()); + } + if (!selectedBlocks) { + for (const block of this.attachedBlocks) { + if (blocks.indexOf(block) !== -1) { + continue; + } + serializationObject.blocks.push(block.serialize()); + } + } + return serializationObject; + } + /** + * Disposes the ressources + */ + dispose() { + for (const block of this.attachedBlocks) { + block.dispose(); + } + this._frameGraph.dispose(); + this._frameGraph = undefined; + this._engine.onResizeObservable.remove(this._resizeObserver); + this._resizeObserver = null; + this.attachedBlocks.length = 0; + this.onBuildObservable.clear(); + this.onBuildErrorObservable.clear(); + } + /** + * Creates a new node render graph set to default basic configuration + * @param name defines the name of the node render graph + * @param scene defines the scene to use + * @param nodeRenderGraphOptions defines options to use when creating the node render graph + * @returns a new NodeRenderGraph + */ + static CreateDefault(name, scene, nodeRenderGraphOptions) { + const renderGraph = new NodeRenderGraph(name, scene, nodeRenderGraphOptions); + renderGraph.setToDefault(); + renderGraph.build(); + return renderGraph; + } + /** + * Creates a node render graph from parsed graph data + * @param source defines the JSON representation of the node render graph + * @param scene defines the scene to use + * @param nodeRenderGraphOptions defines options to use when creating the node render + * @param skipBuild defines whether to skip building the node render graph (default is true) + * @returns a new node render graph + */ + static Parse(source, scene, nodeRenderGraphOptions, skipBuild = true) { + const renderGraph = SerializationHelper.Parse(() => new NodeRenderGraph(source.name, scene, nodeRenderGraphOptions), source, null); + renderGraph.parseSerializedObject(source); + if (!skipBuild) { + renderGraph.build(); + } + return renderGraph; + } + /** + * Creates a node render graph from a snippet saved by the node render graph editor + * @param snippetId defines the snippet to load + * @param scene defines the scene to use + * @param nodeRenderGraphOptions defines options to use when creating the node render graph + * @param nodeRenderGraph defines a node render graph to update (instead of creating a new one) + * @param skipBuild defines whether to skip building the node render graph (default is true) + * @returns a promise that will resolve to the new node render graph + */ + static ParseFromSnippetAsync(snippetId, scene, nodeRenderGraphOptions, nodeRenderGraph, skipBuild = true) { + if (snippetId === "_BLANK") { + return Promise.resolve(NodeRenderGraph.CreateDefault("blank", scene, nodeRenderGraphOptions)); + } + return new Promise((resolve, reject) => { + const request = new WebRequest(); + request.addEventListener("readystatechange", () => { + if (request.readyState == 4) { + if (request.status == 200) { + const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); + const serializationObject = JSON.parse(snippet.nodeRenderGraph); + if (!nodeRenderGraph) { + nodeRenderGraph = SerializationHelper.Parse(() => new NodeRenderGraph(snippetId, scene, nodeRenderGraphOptions), serializationObject, null); + } + nodeRenderGraph.parseSerializedObject(serializationObject); + nodeRenderGraph.snippetId = snippetId; + try { + if (!skipBuild) { + nodeRenderGraph.build(); + } + resolve(nodeRenderGraph); + } + catch (err) { + reject(err); + } + } + else { + reject("Unable to load the snippet " + snippetId); + } + } + }); + request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); + request.send(); + }); + } +} +NodeRenderGraph._BuildIdGenerator = 0; +/** Define the Url to load node editor script */ +NodeRenderGraph.EditorURL = `${Tools._DefaultCdnUrl}/v${Engine.Version}/NodeRenderGraph/babylon.nodeRenderGraph.js`; +/** Define the Url to load snippets */ +NodeRenderGraph.SnippetUrl = `https://snippet.babylonjs.com`; +__decorate([ + serialize() +], NodeRenderGraph.prototype, "name", void 0); +__decorate([ + serialize("comment") +], NodeRenderGraph.prototype, "comment", void 0); + +/** + * Task used to cull objects that are not visible. + */ +class FrameGraphCullObjectsTask extends FrameGraphTask { + /** + * Creates a new cull objects task. + * @param name The name of the task. + * @param frameGraph The frame graph the task belongs to. + * @param scene The scene to cull objects from. + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph); + this._scene = scene; + this.outputObjectList = { + meshes: [], + particleSystems: [], + }; + } + record() { + if (this.objectList === undefined || this.camera === undefined) { + throw new Error(`FrameGraphCullObjectsTask ${this.name}: objectList and camera are required`); + } + const pass = this._frameGraph.addCullPass(this.name); + pass.setObjectList(this.outputObjectList); + pass.setExecuteFunc((_context) => { + this.outputObjectList.meshes = []; + this.camera._updateFrustumPlanes(); + const frustumPlanes = this.camera._frustumPlanes; + const meshes = this.objectList.meshes || this._scene.meshes; + for (let i = 0; i < meshes.length; i++) { + const mesh = meshes[i]; + if (mesh.isBlocked || !mesh.isReady() || !mesh.isEnabled() || mesh.scaling.hasAZeroComponent) { + continue; + } + if (mesh.isVisible && + mesh.visibility > 0 && + (mesh.layerMask & this.camera.layerMask) !== 0 && + (this._scene.skipFrustumClipping || mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(frustumPlanes))) { + this.outputObjectList.meshes.push(mesh); + } + } + }); + const passDisabled = this._frameGraph.addCullPass(this.name + "_disabled", true); + passDisabled.setObjectList(this.outputObjectList); + passDisabled.setExecuteFunc((_context) => { + this.outputObjectList.meshes = this.objectList.meshes; + this.outputObjectList.particleSystems = this.objectList.particleSystems; + }); + } +} + +/** + * Block that culls a list of objects + */ +class NodeRenderGraphCullObjectsBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphCullObjectsBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera); + this.registerInput("objects", NodeRenderGraphBlockConnectionPointTypes.ObjectList); + this._addDependenciesInput(); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.ObjectList); + this._frameGraphTask = new FrameGraphCullObjectsTask(this.name, frameGraph, scene); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphCullObjectsBlock"; + } + /** + * Gets the camera input component + */ + get camera() { + return this._inputs[0]; + } + /** + * Gets the objects input component + */ + get objects() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.output.value = this._frameGraphTask.outputObjectList; + this._frameGraphTask.camera = this.camera.connectedPoint?.value; + this._frameGraphTask.objectList = this.objects.connectedPoint?.value; + } + _dumpPropertiesCode() { + const codes = []; + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + } +} +RegisterClass("BABYLON.NodeRenderGraphCullObjectsBlock", NodeRenderGraphCullObjectsBlock); + +/** + * Block used as a pass through + */ +class NodeRenderGraphElbowBlock extends NodeRenderGraphBlock { + /** + * Creates a new NodeRenderGraphElbowBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("input", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphElbowBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const input = this._inputs[0]; + this._propagateInputValueToOutput(input, output); + } +} +RegisterClass("BABYLON.NodeRenderGraphElbowBlock", NodeRenderGraphElbowBlock); + +/** + * Task used to execute a custom function. + */ +class FrameGraphExecuteTask extends FrameGraphTask { + /** + * Creates a new execute task. + * @param name The name of the task. + * @param frameGraph The frame graph the task belongs to. + */ + constructor(name, frameGraph) { + super(name, frameGraph); + } + record() { + if (!this.func) { + throw new Error("FrameGraphExecuteTask: Execute task must have a function."); + } + const pass = this._frameGraph.addPass(this.name); + pass.setExecuteFunc((context) => { + this.func(context); + }); + const passDisabled = this._frameGraph.addPass(this.name + "_disabled", true); + passDisabled.setExecuteFunc((context) => { + this.funcDisabled?.(context); + }); + return pass; + } +} + +/** + * Block used to execute a custom function in the frame graph + */ +class NodeRenderGraphExecuteBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Creates a new NodeRenderGraphExecuteBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._addDependenciesInput(NodeRenderGraphBlockConnectionPointTypes.Camera | NodeRenderGraphBlockConnectionPointTypes.ShadowLight | NodeRenderGraphBlockConnectionPointTypes.ObjectList); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.ResourceContainer); + this._frameGraphTask = new FrameGraphExecuteTask(name, frameGraph); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphExecuteBlock"; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } +} +RegisterClass("BABYLON.NodeRenderGraphExecuteBlock", NodeRenderGraphExecuteBlock); + +/** + * Block used as a resource (textures, buffers) container + */ +class NodeRenderGraphResourceContainerBlock extends NodeRenderGraphBlock { + /** + * Creates a new NodeRenderGraphResourceContainerBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("resource0", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("resource1", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("resource2", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("resource3", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("resource4", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("resource5", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("resource6", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("resource7", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.ResourceContainer); + this.resource0.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator); + this.resource1.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator); + this.resource2.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator); + this.resource3.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator); + this.resource4.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator); + this.resource5.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator); + this.resource6.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator); + this.resource7.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphResourceContainerBlock"; + } + /** + * Gets the resource0 component + */ + get resource0() { + return this._inputs[0]; + } + /** + * Gets the resource1 component + */ + get resource1() { + return this._inputs[1]; + } + /** + * Gets the resource2 component + */ + get resource2() { + return this._inputs[2]; + } + /** + * Gets the resource3 component + */ + get resource3() { + return this._inputs[3]; + } + /** + * Gets the resource4 component + */ + get resource4() { + return this._inputs[4]; + } + /** + * Gets the resource5 component + */ + get resource5() { + return this._inputs[5]; + } + /** + * Gets the resource6 component + */ + get resource6() { + return this._inputs[6]; + } + /** + * Gets the resource7 component + */ + get resource7() { + return this._inputs[7]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } +} +RegisterClass("BABYLON.NodeRenderGraphResourceContainerBlock", NodeRenderGraphResourceContainerBlock); + +/** + * Special Glow Blur post process only blurring the alpha channel + * It enforces keeping the most luminous color in the color channel. + * @internal + */ +class ThinGlowBlurPostProcess extends EffectWrapper { + constructor(name, engine = null, direction, kernel, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinGlowBlurPostProcess.FragmentUrl, + uniforms: ThinGlowBlurPostProcess.Uniforms, + }); + this.direction = direction; + this.kernel = kernel; + this.textureWidth = 0; + this.textureHeight = 0; + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => glowBlurPostProcess_fragment)); + } + else { + list.push(Promise.resolve().then(() => glowBlurPostProcess_fragment$1)); + } + super._gatherImports(useWebGPU, list); + } + bind() { + super.bind(); + this._drawWrapper.effect.setFloat2("screenSize", this.textureWidth, this.textureHeight); + this._drawWrapper.effect.setVector2("direction", this.direction); + this._drawWrapper.effect.setFloat("blurWidth", this.kernel); + } +} +/** + * The fragment shader url + */ +ThinGlowBlurPostProcess.FragmentUrl = "glowBlurPostProcess"; +/** + * The list of uniforms used by the effect + */ +ThinGlowBlurPostProcess.Uniforms = ["screenSize", "direction", "blurWidth"]; +/** + * @internal + */ +class ThinEffectLayer { + /** + * Gets/sets the camera attached to the layer. + */ + get camera() { + return this._options.camera; + } + set camera(camera) { + this._options.camera = camera; + } + /** + * Gets the rendering group id the layer should render in. + */ + get renderingGroupId() { + return this._options.renderingGroupId; + } + set renderingGroupId(renderingGroupId) { + this._options.renderingGroupId = renderingGroupId; + } + /** + * Gets the object renderer used to render objects in the layer + */ + get objectRenderer() { + return this._objectRenderer; + } + /** + * Gets the shader language used in this material. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Sets a specific material to be used to render a mesh/a list of meshes in the layer + * @param mesh mesh or array of meshes + * @param material material to use by the layer when rendering the mesh(es). If undefined is passed, the specific material created by the layer will be used. + */ + setMaterialForRendering(mesh, material) { + this._objectRenderer.setMaterialForRendering(mesh, material); + if (Array.isArray(mesh)) { + for (let i = 0; i < mesh.length; ++i) { + const currentMesh = mesh[i]; + if (!material) { + delete this._materialForRendering[currentMesh.uniqueId]; + } + else { + this._materialForRendering[currentMesh.uniqueId] = [currentMesh, material]; + } + } + } + else { + if (!material) { + delete this._materialForRendering[mesh.uniqueId]; + } + else { + this._materialForRendering[mesh.uniqueId] = [mesh, material]; + } + } + } + /** + * Gets the intensity of the effect for a specific mesh. + * @param mesh The mesh to get the effect intensity for + * @returns The intensity of the effect for the mesh + */ + getEffectIntensity(mesh) { + return this._effectIntensity[mesh.uniqueId] ?? 1; + } + /** + * Sets the intensity of the effect for a specific mesh. + * @param mesh The mesh to set the effect intensity for + * @param intensity The intensity of the effect for the mesh + */ + setEffectIntensity(mesh, intensity) { + this._effectIntensity[mesh.uniqueId] = intensity; + } + /** + * Instantiates a new effect Layer + * @param name The name of the layer + * @param scene The scene to use the layer in + * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false + * @param dontCheckIfReady Specifies if the layer should disable checking whether all the post processes are ready (default: false). To save performance, this should be set to true and you should call `isReady` manually before rendering to the layer. + * @param _additionalImportShadersAsync Additional shaders to import when the layer is created + */ + constructor(name, scene, forceGLSL = false, dontCheckIfReady = false, _additionalImportShadersAsync) { + this._additionalImportShadersAsync = _additionalImportShadersAsync; + this._vertexBuffers = {}; + this._dontCheckIfReady = false; + /** @internal */ + this._shouldRender = true; + /** @internal */ + this._emissiveTextureAndColor = { texture: null, color: new Color4() }; + /** @internal */ + this._effectIntensity = {}; + /** @internal */ + this._postProcesses = []; + /** + * The clear color of the texture used to generate the glow map. + */ + this.neutralColor = new Color4(); + /** + * Specifies whether the effect layer is enabled or not. + */ + this.isEnabled = true; + /** + * Specifies if the bounding boxes should be rendered normally or if they should undergo the effect of the layer + */ + this.disableBoundingBoxesFromEffectLayer = false; + /** + * An event triggered when the effect layer has been disposed. + */ + this.onDisposeObservable = new Observable(); + /** + * An event triggered when the effect layer is about rendering the main texture with the glowy parts. + */ + this.onBeforeRenderLayerObservable = new Observable(); + /** + * An event triggered when the generated texture is being merged in the scene. + */ + this.onBeforeComposeObservable = new Observable(); + /** + * An event triggered when the mesh is rendered into the effect render target. + */ + this.onBeforeRenderMeshToEffect = new Observable(); + /** + * An event triggered after the mesh has been rendered into the effect render target. + */ + this.onAfterRenderMeshToEffect = new Observable(); + /** + * An event triggered when the generated texture has been merged in the scene. + */ + this.onAfterComposeObservable = new Observable(); + /** + * An event triggered when the layer is being blurred. + */ + this.onBeforeBlurObservable = new Observable(); + /** + * An event triggered when the layer has been blurred. + */ + this.onAfterBlurObservable = new Observable(); + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._materialForRendering = {}; + /** @internal */ + this._shadersLoaded = false; + this.name = name; + this._scene = scene || EngineStore.LastCreatedScene; + this._dontCheckIfReady = dontCheckIfReady; + const engine = this._scene.getEngine(); + if (engine.isWebGPU && !forceGLSL && !ThinEffectLayer.ForceGLSL) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + } + this._engine = this._scene.getEngine(); + this._mergeDrawWrapper = []; + // Generate Buffers + this._generateIndexBuffer(); + this._generateVertexBuffer(); + } + /** + * Get the effect name of the layer. + * @returns The effect name + */ + getEffectName() { + return ""; + } + /** + * Checks for the readiness of the element composing the layer. + * @param _subMesh the mesh to check for + * @param _useInstances specify whether or not to use instances to render the mesh + * @returns true if ready otherwise, false + */ + isReady(_subMesh, _useInstances) { + return true; + } + /** + * Returns whether or not the layer needs stencil enabled during the mesh rendering. + * @returns true if the effect requires stencil during the main canvas render pass. + */ + needStencil() { + return false; + } + /** @internal */ + _createMergeEffect() { + throw new Error("Effect Layer: no merge effect defined"); + } + /** @internal */ + _createTextureAndPostProcesses() { } + /** @internal */ + _internalCompose(_effect, _renderIndex) { } + /** @internal */ + _setEmissiveTextureAndColor(_mesh, _subMesh, _material) { } + /** @internal */ + _numInternalDraws() { + return 1; + } + /** @internal */ + _init(options) { + // Adapt options + this._options = { + mainTextureRatio: 0.5, + mainTextureFixedSize: 0, + mainTextureType: 0, + alphaBlendingMode: 2, + camera: null, + renderingGroupId: -1, + ...options, + }; + this._createObjectRenderer(); + } + _generateIndexBuffer() { + // Indices + const indices = []; + indices.push(0); + indices.push(1); + indices.push(2); + indices.push(0); + indices.push(2); + indices.push(3); + this._indexBuffer = this._engine.createIndexBuffer(indices); + } + _generateVertexBuffer() { + // VBO + const vertices = []; + vertices.push(1, 1); + vertices.push(-1, 1); + vertices.push(-1, -1); + vertices.push(1, -1); + const vertexBuffer = new VertexBuffer(this._engine, vertices, VertexBuffer.PositionKind, false, false, 2); + this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer; + } + _createObjectRenderer() { + this._objectRenderer = new ObjectRenderer(`ObjectRenderer for thin effect layer ${this.name}`, this._scene, { + doNotChangeAspectRatio: true, + }); + this._objectRenderer.activeCamera = this._options.camera; + this._objectRenderer.renderParticles = false; + this._objectRenderer.renderList = null; + // Prevent package size in es6 (getBoundingBoxRenderer might not be present) + const hasBoundingBoxRenderer = !!this._scene.getBoundingBoxRenderer; + let boundingBoxRendererEnabled = false; + if (hasBoundingBoxRenderer) { + this._objectRenderer.onBeforeRenderObservable.add(() => { + boundingBoxRendererEnabled = this._scene.getBoundingBoxRenderer().enabled; + this._scene.getBoundingBoxRenderer().enabled = !this.disableBoundingBoxesFromEffectLayer && boundingBoxRendererEnabled; + }); + this._objectRenderer.onAfterRenderObservable.add(() => { + this._scene.getBoundingBoxRenderer().enabled = boundingBoxRendererEnabled; + }); + } + this._objectRenderer.customIsReadyFunction = (mesh, refreshRate, preWarm) => { + if ((preWarm || refreshRate === 0) && mesh.subMeshes) { + for (let i = 0; i < mesh.subMeshes.length; ++i) { + const subMesh = mesh.subMeshes[i]; + const material = subMesh.getMaterial(); + const renderingMesh = subMesh.getRenderingMesh(); + if (!material) { + continue; + } + const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); + const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances; + this._setEmissiveTextureAndColor(renderingMesh, subMesh, material); + if (!this._isSubMeshReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) { + return false; + } + } + } + return true; + }; + // Custom render function + this._objectRenderer.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { + this.onBeforeRenderLayerObservable.notifyObservers(this); + let index; + const engine = this._scene.getEngine(); + if (depthOnlySubMeshes.length) { + engine.setColorWrite(false); + for (index = 0; index < depthOnlySubMeshes.length; index++) { + this._renderSubMesh(depthOnlySubMeshes.data[index]); + } + engine.setColorWrite(true); + } + for (index = 0; index < opaqueSubMeshes.length; index++) { + this._renderSubMesh(opaqueSubMeshes.data[index]); + } + for (index = 0; index < alphaTestSubMeshes.length; index++) { + this._renderSubMesh(alphaTestSubMeshes.data[index]); + } + const previousAlphaMode = engine.getAlphaMode(); + for (index = 0; index < transparentSubMeshes.length; index++) { + const subMesh = transparentSubMeshes.data[index]; + const material = subMesh.getMaterial(); + if (material && material.needDepthPrePass) { + const engine = material.getScene().getEngine(); + engine.setColorWrite(false); + this._renderSubMesh(subMesh); + engine.setColorWrite(true); + } + this._renderSubMesh(subMesh, true); + } + engine.setAlphaMode(previousAlphaMode); + }; + } + /** @internal */ + _addCustomEffectDefines(_defines) { } + /** @internal */ + _internalIsSubMeshReady(subMesh, useInstances, emissiveTexture) { + const engine = this._scene.getEngine(); + const mesh = subMesh.getMesh(); + const renderingMaterial = mesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine.currentRenderPassId]; + if (renderingMaterial) { + return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances); + } + const material = subMesh.getMaterial(); + if (!material) { + return false; + } + if (this._useMeshMaterial(subMesh.getRenderingMesh())) { + return material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances); + } + const defines = []; + const attribs = [VertexBuffer.PositionKind]; + let uv1 = false; + let uv2 = false; + const color = false; + // Diffuse + if (material) { + const needAlphaTest = material.needAlphaTestingForMesh(mesh); + const diffuseTexture = material.getAlphaTestTexture(); + const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture); + if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) { + defines.push("#define DIFFUSE"); + if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && diffuseTexture.coordinatesIndex === 1) { + defines.push("#define DIFFUSEUV2"); + uv2 = true; + } + else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { + defines.push("#define DIFFUSEUV1"); + uv1 = true; + } + if (needAlphaTest) { + defines.push("#define ALPHATEST"); + defines.push("#define ALPHATESTVALUE 0.4"); + } + if (!diffuseTexture.gammaSpace) { + defines.push("#define DIFFUSE_ISLINEAR"); + } + } + const opacityTexture = material.opacityTexture; + if (opacityTexture) { + defines.push("#define OPACITY"); + if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && opacityTexture.coordinatesIndex === 1) { + defines.push("#define OPACITYUV2"); + uv2 = true; + } + else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { + defines.push("#define OPACITYUV1"); + uv1 = true; + } + } + } + // Emissive + if (emissiveTexture) { + defines.push("#define EMISSIVE"); + if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && emissiveTexture.coordinatesIndex === 1) { + defines.push("#define EMISSIVEUV2"); + uv2 = true; + } + else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { + defines.push("#define EMISSIVEUV1"); + uv1 = true; + } + if (!emissiveTexture.gammaSpace) { + defines.push("#define EMISSIVE_ISLINEAR"); + } + } + // Vertex + if (mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind) && mesh.hasVertexAlpha && material.transparencyMode !== Material.MATERIAL_OPAQUE) { + attribs.push(VertexBuffer.ColorKind); + defines.push("#define VERTEXALPHA"); + } + if (uv1) { + attribs.push(VertexBuffer.UVKind); + defines.push("#define UV1"); + } + if (uv2) { + attribs.push(VertexBuffer.UV2Kind); + defines.push("#define UV2"); + } + // Bones + const fallbacks = new EffectFallbacks(); + if (mesh.useBones && mesh.computeBonesUsingShaders) { + attribs.push(VertexBuffer.MatricesIndicesKind); + attribs.push(VertexBuffer.MatricesWeightsKind); + if (mesh.numBoneInfluencers > 4) { + attribs.push(VertexBuffer.MatricesIndicesExtraKind); + attribs.push(VertexBuffer.MatricesWeightsExtraKind); + } + defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); + const skeleton = mesh.skeleton; + if (skeleton && skeleton.isUsingTextureForMatrices) { + defines.push("#define BONETEXTURE"); + } + else { + defines.push("#define BonesPerMesh " + (skeleton ? skeleton.bones.length + 1 : 0)); + } + if (mesh.numBoneInfluencers > 0) { + fallbacks.addCPUSkinningFallback(0, mesh); + } + } + else { + defines.push("#define NUM_BONE_INFLUENCERS 0"); + } + // Morph targets + const numMorphInfluencers = mesh.morphTargetManager + ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph + false, // useNormalMorph + false, // useTangentMorph + uv1, // useUVMorph + uv2, // useUV2Morph + color // useColorMorph + ) + : 0; + // Instances + if (useInstances) { + defines.push("#define INSTANCES"); + PushAttributesForInstances(attribs); + if (subMesh.getRenderingMesh().hasThinInstances) { + defines.push("#define THIN_INSTANCES"); + } + } + // ClipPlanes + prepareStringDefinesForClipPlanes(material, this._scene, defines); + this._addCustomEffectDefines(defines); + // Get correct effect + const drawWrapper = subMesh._getDrawWrapper(undefined, true); + const cachedDefines = drawWrapper.defines; + const join = defines.join("\n"); + if (cachedDefines !== join) { + const uniforms = [ + "world", + "mBones", + "viewProjection", + "glowColor", + "morphTargetInfluences", + "morphTargetCount", + "boneTextureWidth", + "diffuseMatrix", + "emissiveMatrix", + "opacityMatrix", + "opacityIntensity", + "morphTargetTextureInfo", + "morphTargetTextureIndices", + "glowIntensity", + ]; + addClipPlaneUniforms(uniforms); + drawWrapper.setEffect(this._engine.createEffect("glowMapGeneration", attribs, uniforms, ["diffuseSampler", "emissiveSampler", "opacitySampler", "boneSampler", "morphTargets"], join, fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: numMorphInfluencers }, this._shaderLanguage, this._shadersLoaded + ? undefined + : async () => { + await this._importShadersAsync(); + this._shadersLoaded = true; + }), join); + } + const effectIsReady = drawWrapper.effect.isReady(); + return effectIsReady && (this._dontCheckIfReady || (!this._dontCheckIfReady && this.isLayerReady())); + } + /** @internal */ + _isSubMeshReady(subMesh, useInstances, emissiveTexture) { + return this._internalIsSubMeshReady(subMesh, useInstances, emissiveTexture); + } + async _importShadersAsync() { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => glowMapGeneration_vertex), Promise.resolve().then(() => glowMapGeneration_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => glowMapGeneration_vertex$1), Promise.resolve().then(() => glowMapGeneration_fragment$1)]); + } + this._additionalImportShadersAsync?.(); + } + /** @internal */ + _internalIsLayerReady() { + let isReady = true; + for (let i = 0; i < this._postProcesses.length; i++) { + isReady = this._postProcesses[i].isReady() && isReady; + } + const numDraws = this._numInternalDraws(); + for (let i = 0; i < numDraws; ++i) { + let currentEffect = this._mergeDrawWrapper[i]; + if (!currentEffect) { + currentEffect = this._mergeDrawWrapper[i] = new DrawWrapper(this._engine); + currentEffect.setEffect(this._createMergeEffect()); + } + isReady = currentEffect.effect.isReady() && isReady; + } + return isReady; + } + /** + * Checks if the layer is ready to be used. + * @returns true if the layer is ready to be used + */ + isLayerReady() { + return this._internalIsLayerReady(); + } + /** + * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene. + * @returns true if the rendering was successful + */ + compose() { + if (!this._dontCheckIfReady && !this.isLayerReady()) { + return false; + } + const engine = this._scene.getEngine(); + const numDraws = this._numInternalDraws(); + this.onBeforeComposeObservable.notifyObservers(this); + const previousAlphaMode = engine.getAlphaMode(); + for (let i = 0; i < numDraws; ++i) { + const currentEffect = this._mergeDrawWrapper[i]; + // Render + engine.enableEffect(currentEffect); + engine.setState(false); + // VBOs + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect.effect); + // Go Blend. + engine.setAlphaMode(this._options.alphaBlendingMode); + // Blends the map on the main canvas. + this._internalCompose(currentEffect.effect, i); + } + // Restore Alpha + engine.setAlphaMode(previousAlphaMode); + this.onAfterComposeObservable.notifyObservers(this); + return true; + } + /** @internal */ + _internalHasMesh(mesh) { + if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) { + return true; + } + return false; + } + /** + * Determine if a given mesh will be used in the current effect. + * @param mesh mesh to test + * @returns true if the mesh will be used + */ + hasMesh(mesh) { + return this._internalHasMesh(mesh); + } + /** @internal */ + _internalShouldRender() { + return this.isEnabled && this._shouldRender; + } + /** + * Returns true if the layer contains information to display, otherwise false. + * @returns true if the glow layer should be rendered + */ + shouldRender() { + return this._internalShouldRender(); + } + /** @internal */ + _shouldRenderMesh(_mesh) { + return true; + } + /** @internal */ + _internalCanRenderMesh(mesh, material) { + return !material.needAlphaBlendingForMesh(mesh); + } + /** @internal */ + _canRenderMesh(mesh, material) { + return this._internalCanRenderMesh(mesh, material); + } + _renderSubMesh(subMesh, enableAlphaMode = false) { + if (!this._internalShouldRender()) { + return; + } + const material = subMesh.getMaterial(); + const ownerMesh = subMesh.getMesh(); + const replacementMesh = subMesh.getReplacementMesh(); + const renderingMesh = subMesh.getRenderingMesh(); + const effectiveMesh = subMesh.getEffectiveMesh(); + const scene = this._scene; + const engine = scene.getEngine(); + effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; + if (!material) { + return; + } + // Do not block in blend mode. + if (!this._canRenderMesh(renderingMesh, material)) { + return; + } + // Culling + let sideOrientation = material._getEffectiveOrientation(renderingMesh); + const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant(); + if (mainDeterminant < 0) { + sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation; + } + const reverse = sideOrientation === Material.ClockWiseSideOrientation; + engine.setState(material.backFaceCulling, material.zOffset, undefined, reverse, material.cullBackFaces, undefined, material.zOffsetUnits); + // Managing instances + const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!replacementMesh); + if (batch.mustReturn) { + return; + } + // Early Exit per mesh + if (!this._shouldRenderMesh(renderingMesh)) { + return; + } + const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances; + this._setEmissiveTextureAndColor(renderingMesh, subMesh, material); + this.onBeforeRenderMeshToEffect.notifyObservers(ownerMesh); + if (this._useMeshMaterial(renderingMesh)) { + subMesh.getMaterial()._glowModeEnabled = true; + renderingMesh.render(subMesh, enableAlphaMode, replacementMesh || undefined); + subMesh.getMaterial()._glowModeEnabled = false; + } + else if (this._isSubMeshReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) { + const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine.currentRenderPassId]; + let drawWrapper = subMesh._getDrawWrapper(); + if (!drawWrapper && renderingMaterial) { + drawWrapper = renderingMaterial._getDrawWrapper(); + } + if (!drawWrapper) { + return; + } + const effect = drawWrapper.effect; + engine.enableEffect(drawWrapper); + if (!hardwareInstancedRendering) { + renderingMesh._bind(subMesh, effect, material.fillMode); + } + if (!renderingMaterial) { + effect.setMatrix("viewProjection", scene.getTransformMatrix()); + effect.setMatrix("world", effectiveMesh.getWorldMatrix()); + effect.setFloat4("glowColor", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a); + } + else { + renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh); + } + if (!renderingMaterial) { + const needAlphaTest = material.needAlphaTestingForMesh(effectiveMesh); + const diffuseTexture = material.getAlphaTestTexture(); + const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture); + if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) { + effect.setTexture("diffuseSampler", diffuseTexture); + const textureMatrix = diffuseTexture.getTextureMatrix(); + if (textureMatrix) { + effect.setMatrix("diffuseMatrix", textureMatrix); + } + } + const opacityTexture = material.opacityTexture; + if (opacityTexture) { + effect.setTexture("opacitySampler", opacityTexture); + effect.setFloat("opacityIntensity", opacityTexture.level); + const textureMatrix = opacityTexture.getTextureMatrix(); + if (textureMatrix) { + effect.setMatrix("opacityMatrix", textureMatrix); + } + } + // Glow emissive only + if (this._emissiveTextureAndColor.texture) { + effect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture); + effect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix()); + } + // Bones + if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { + const skeleton = renderingMesh.skeleton; + if (skeleton.isUsingTextureForMatrices) { + const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh); + if (!boneTexture) { + return; + } + effect.setTexture("boneSampler", boneTexture); + effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); + } + else { + effect.setMatrices("mBones", skeleton.getTransformMatrices(renderingMesh)); + } + } + // Morph targets + BindMorphTargetParameters(renderingMesh, effect); + if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { + renderingMesh.morphTargetManager._bind(effect); + } + // Alpha mode + if (enableAlphaMode) { + engine.setAlphaMode(material.alphaMode); + } + // Intensity of effect + effect.setFloat("glowIntensity", this.getEffectIntensity(renderingMesh)); + // Clip planes + bindClipPlane(effect, material, scene); + } + // Draw + renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix("world", world)); + } + else { + // Need to reset refresh rate of the main map + this._objectRenderer.resetRefreshCounter(); + } + this.onAfterRenderMeshToEffect.notifyObservers(ownerMesh); + } + /** @internal */ + _useMeshMaterial(_mesh) { + return false; + } + /** @internal */ + _rebuild() { + const vb = this._vertexBuffers[VertexBuffer.PositionKind]; + if (vb) { + vb._rebuild(); + } + this._generateIndexBuffer(); + } + /** + * Dispose the effect layer and free resources. + */ + dispose() { + const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind]; + if (vertexBuffer) { + vertexBuffer.dispose(); + this._vertexBuffers[VertexBuffer.PositionKind] = null; + } + if (this._indexBuffer) { + this._scene.getEngine()._releaseBuffer(this._indexBuffer); + this._indexBuffer = null; + } + for (const drawWrapper of this._mergeDrawWrapper) { + drawWrapper.dispose(); + } + this._mergeDrawWrapper = []; + this._objectRenderer.dispose(); + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + this.onBeforeRenderLayerObservable.clear(); + this.onBeforeComposeObservable.clear(); + this.onBeforeRenderMeshToEffect.clear(); + this.onAfterRenderMeshToEffect.clear(); + this.onAfterComposeObservable.clear(); + } +} +/** + * Force all the effect layers to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +ThinEffectLayer.ForceGLSL = false; + +/** + * @internal + */ +class ThinGlowLayer extends ThinEffectLayer { + /** + * Gets the ldrMerge option. + */ + get ldrMerge() { + return this._options.ldrMerge; + } + /** + * Sets the kernel size of the blur. + */ + set blurKernelSize(value) { + if (value === this._options.blurKernelSize) { + return; + } + this._options.blurKernelSize = value; + const effectiveKernel = this._getEffectiveBlurKernelSize(); + this._horizontalBlurPostprocess1.kernel = effectiveKernel; + this._verticalBlurPostprocess1.kernel = effectiveKernel; + this._horizontalBlurPostprocess2.kernel = effectiveKernel; + this._verticalBlurPostprocess2.kernel = effectiveKernel; + } + /** + * Gets the kernel size of the blur. + */ + get blurKernelSize() { + return this._options.blurKernelSize; + } + /** + * Sets the glow intensity. + */ + set intensity(value) { + this._intensity = value; + } + /** + * Gets the glow intensity. + */ + get intensity() { + return this._intensity; + } + /** + * Instantiates a new glow Layer and references it to the scene. + * @param name The name of the layer + * @param scene The scene to use the layer in + * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information) + * @param dontCheckIfReady Specifies if the layer should disable checking whether all the post processes are ready (default: false). To save performance, this should be set to true and you should call `isReady` manually before rendering to the layer. + */ + constructor(name, scene, options, dontCheckIfReady = false) { + super(name, scene, false, dontCheckIfReady); + this._intensity = 1.0; + /** @internal */ + this._includedOnlyMeshes = []; + /** @internal */ + this._excludedMeshes = []; + this._meshesUsingTheirOwnMaterials = []; + /** @internal */ + this._renderPassId = 0; + this.neutralColor = new Color4(0, 0, 0, 1); + // Adapt options + this._options = { + mainTextureRatio: 0.5, + mainTextureFixedSize: 0, + mainTextureType: 0, + blurKernelSize: 32, + camera: null, + renderingGroupId: -1, + ldrMerge: false, + alphaBlendingMode: 1, + ...options, + }; + // Initialize the layer + this._init(this._options); + if (dontCheckIfReady) { + // When dontCheckIfReady is true, we are in the new ThinXXX layer mode, so we must call _createTextureAndPostProcesses ourselves (it is called by EffectLayer otherwise) + this._createTextureAndPostProcesses(); + } + } + /** + * Gets the class name of the thin glow layer + * @returns the string with the class name of the glow layer + */ + getClassName() { + return "GlowLayer"; + } + async _importShadersAsync() { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([ + Promise.resolve().then(() => glowMapMerge_fragment), + Promise.resolve().then(() => glowMapMerge_vertex), + Promise.resolve().then(() => glowBlurPostProcess_fragment), + ]); + } + else { + await Promise.all([Promise.resolve().then(() => glowMapMerge_fragment$1), Promise.resolve().then(() => glowMapMerge_vertex$1), Promise.resolve().then(() => glowBlurPostProcess_fragment$1)]); + } + await super._importShadersAsync(); + } + getEffectName() { + return ThinGlowLayer.EffectName; + } + _createMergeEffect() { + let defines = "#define EMISSIVE \n"; + if (this._options.ldrMerge) { + defines += "#define LDR \n"; + } + // Effect + return this._engine.createEffect("glowMapMerge", [VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], defines, undefined, undefined, undefined, undefined, this.shaderLanguage, this._shadersLoaded + ? undefined + : async () => { + await this._importShadersAsync(); + this._shadersLoaded = true; + }); + } + _createTextureAndPostProcesses() { + const effectiveKernel = this._getEffectiveBlurKernelSize(); + this._horizontalBlurPostprocess1 = new ThinBlurPostProcess("GlowLayerHBP1", this._scene.getEngine(), new Vector2(1.0, 0), effectiveKernel); + this._verticalBlurPostprocess1 = new ThinBlurPostProcess("GlowLayerVBP1", this._scene.getEngine(), new Vector2(0, 1.0), effectiveKernel); + this._horizontalBlurPostprocess2 = new ThinBlurPostProcess("GlowLayerHBP2", this._scene.getEngine(), new Vector2(1.0, 0), effectiveKernel); + this._verticalBlurPostprocess2 = new ThinBlurPostProcess("GlowLayerVBP2", this._scene.getEngine(), new Vector2(0, 1.0), effectiveKernel); + this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2]; + } + _getEffectiveBlurKernelSize() { + return this._options.blurKernelSize / 2; + } + isReady(subMesh, useInstances) { + const material = subMesh.getMaterial(); + const mesh = subMesh.getRenderingMesh(); + if (!material || !mesh) { + return false; + } + const emissiveTexture = material.emissiveTexture; + return super._isSubMeshReady(subMesh, useInstances, emissiveTexture); + } + _canRenderMesh(_mesh, _material) { + return true; + } + _internalCompose(effect) { + // Texture + this.bindTexturesForCompose(effect); + effect.setFloat("offset", this._intensity); + // Cache + const engine = this._engine; + const previousStencilBuffer = engine.getStencilBuffer(); + // Draw order + engine.setStencilBuffer(false); + engine.drawElementsType(Material.TriangleFillMode, 0, 6); + // Draw order + engine.setStencilBuffer(previousStencilBuffer); + } + _setEmissiveTextureAndColor(mesh, subMesh, material) { + let textureLevel = 1.0; + if (this.customEmissiveTextureSelector) { + this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material); + } + else { + if (material) { + this._emissiveTextureAndColor.texture = material.emissiveTexture; + if (this._emissiveTextureAndColor.texture) { + textureLevel = this._emissiveTextureAndColor.texture.level; + } + } + else { + this._emissiveTextureAndColor.texture = null; + } + } + if (this.customEmissiveColorSelector) { + this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color); + } + else { + if (material.emissiveColor) { + const emissiveIntensity = material.emissiveIntensity ?? 1; + textureLevel *= emissiveIntensity; + this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, material.alpha); + } + else { + this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a); + } + } + } + _shouldRenderMesh(mesh) { + return this.hasMesh(mesh); + } + _addCustomEffectDefines(defines) { + defines.push("#define GLOW"); + } + /** + * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer. + * @param mesh The mesh to exclude from the glow layer + */ + addExcludedMesh(mesh) { + if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) { + this._excludedMeshes.push(mesh.uniqueId); + } + } + /** + * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer. + * @param mesh The mesh to remove + */ + removeExcludedMesh(mesh) { + const index = this._excludedMeshes.indexOf(mesh.uniqueId); + if (index !== -1) { + this._excludedMeshes.splice(index, 1); + } + } + /** + * Add a mesh in the inclusion list to impact or being impacted by the glow layer. + * @param mesh The mesh to include in the glow layer + */ + addIncludedOnlyMesh(mesh) { + if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) { + this._includedOnlyMeshes.push(mesh.uniqueId); + } + } + /** + * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer. + * @param mesh The mesh to remove + */ + removeIncludedOnlyMesh(mesh) { + const index = this._includedOnlyMeshes.indexOf(mesh.uniqueId); + if (index !== -1) { + this._includedOnlyMeshes.splice(index, 1); + } + } + hasMesh(mesh) { + if (!super.hasMesh(mesh)) { + return false; + } + // Included Mesh + if (this._includedOnlyMeshes.length) { + return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1; + } + // Excluded Mesh + if (this._excludedMeshes.length) { + return this._excludedMeshes.indexOf(mesh.uniqueId) === -1; + } + return true; + } + _useMeshMaterial(mesh) { + // Specific case of material supporting glow directly + if (mesh.material?._supportGlowLayer) { + return true; + } + if (this._meshesUsingTheirOwnMaterials.length == 0) { + return false; + } + return this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId) > -1; + } + /** + * Add a mesh to be rendered through its own material and not with emissive only. + * @param mesh The mesh for which we need to use its material + */ + referenceMeshToUseItsOwnMaterial(mesh) { + mesh.resetDrawCache(this._renderPassId); + this._meshesUsingTheirOwnMaterials.push(mesh.uniqueId); + mesh.onDisposeObservable.add(() => { + this._disposeMesh(mesh); + }); + } + /** + * Remove a mesh from being rendered through its own material and not with emissive only. + * @param mesh The mesh for which we need to not use its material + * @param renderPassId The render pass id used when rendering the mesh + */ + unReferenceMeshFromUsingItsOwnMaterial(mesh, renderPassId) { + let index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId); + while (index >= 0) { + this._meshesUsingTheirOwnMaterials.splice(index, 1); + index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId); + } + mesh.resetDrawCache(renderPassId); + } + /** @internal */ + _disposeMesh(mesh) { + this.removeIncludedOnlyMesh(mesh); + this.removeExcludedMesh(mesh); + } +} +/** + * Effect Name of the layer. + */ +ThinGlowLayer.EffectName = "GlowLayer"; +/** + * The default blur kernel size used for the glow. + */ +ThinGlowLayer.DefaultBlurKernelSize = 32; + +/** + * Task which applies a post process. + */ +class FrameGraphPostProcessTask extends FrameGraphTask { + /** + * The draw wrapper used by the post process + */ + get drawWrapper() { + return this._postProcessDrawWrapper; + } + /** + * Constructs a new post process task. + * @param name Name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param postProcess The post process to apply. + */ + constructor(name, frameGraph, postProcess) { + super(name, frameGraph); + /** + * The sampling mode to use for the source texture. + */ + this.sourceSamplingMode = 2; + this.postProcess = postProcess; + this._postProcessDrawWrapper = this.postProcess.drawWrapper; + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.onTexturesAllocatedObservable.add((context) => { + context.setTextureSamplingMode(this.sourceTexture, this.sourceSamplingMode); + }); + } + isReady() { + return this.postProcess.isReady(); + } + record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) { + if (this.sourceTexture === undefined) { + throw new Error(`FrameGraphPostProcessTask "${this.name}": sourceTexture is required`); + } + const sourceTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture); + sourceTextureCreationOptions.options.samples = 1; + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture, this.name, sourceTextureCreationOptions); + const sourceSize = !sourceTextureCreationOptions.sizeIsPercentage + ? textureSizeIsObject(sourceTextureCreationOptions.size) + ? sourceTextureCreationOptions.size + : { width: sourceTextureCreationOptions.size, height: sourceTextureCreationOptions.size } + : this._frameGraph.textureManager.getAbsoluteDimensions(sourceTextureCreationOptions.size); + this._sourceWidth = sourceSize.width; + this._sourceHeight = sourceSize.height; + const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.outputTexture); + this._outputWidth = outputTextureDescription.size.width; + this._outputHeight = outputTextureDescription.size.height; + const pass = this._frameGraph.addRenderPass(this.name); + pass.addDependencies(this.sourceTexture); + pass.setRenderTarget(this.outputTexture); + pass.setExecuteFunc((context) => { + additionalExecute?.(context); + context.applyFullScreenEffect(this._postProcessDrawWrapper, () => { + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "textureSampler", this.sourceTexture); + additionalBindings?.(context); + this.postProcess.bind(); + }); + }); + if (!skipCreationOfDisabledPasses) { + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.addDependencies(this.sourceTexture); + passDisabled.setRenderTarget(this.outputTexture); + passDisabled.setExecuteFunc((context) => { + context.copyTexture(this.sourceTexture); + }); + } + return pass; + } + dispose() { + this.postProcess.dispose(); + super.dispose(); + } +} + +/** + * Task which applies a blur post process. + */ +class FrameGraphBlurTask extends FrameGraphPostProcessTask { + /** + * Constructs a new blur task. + * @param name Name of the task. + * @param frameGraph Frame graph this task is associated with. + * @param thinPostProcess The thin post process to use for the blur effect. + */ + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinBlurPostProcess(name, frameGraph.engine, new Vector2(1, 0), 10)); + } + record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) { + const pass = super.record(skipCreationOfDisabledPasses, additionalExecute, additionalBindings); + this.postProcess.textureWidth = this._outputWidth; // should be _sourceWidth, but to avoid a breaking change, we use _outputWidth (BlurPostProcess uses _outputTexture to get width/height) + this.postProcess.textureHeight = this._outputHeight; // same as above for height + return pass; + } +} + +class FrameGraphGlowBlurTask extends FrameGraphPostProcessTask { + /** + * Constructs a new glow blur task. + * @param name The name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param thinPostProcess The thin post process to use for the glow blur effect. If not provided, a new one will be created. + */ + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinGlowBlurPostProcess(name, frameGraph.engine, new Vector2(1, 0), 1)); + } + record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) { + const pass = super.record(skipCreationOfDisabledPasses, additionalExecute, additionalBindings); + this.postProcess.textureWidth = this._outputWidth; + this.postProcess.textureHeight = this._outputHeight; + return pass; + } +} +/** + * @internal + */ +class FrameGraphBaseLayerTask extends FrameGraphTask { + /** + * The name of the task. + */ + get name() { + return this._name; + } + set name(name) { + this._name = name; + if (this._blurX) { + for (let i = 0; i < this._blurX.length; i++) { + this._blurX[i].name = `${name} Blur X${i}`; + this._blurY[i].name = `${name} Blur Y${i}`; + } + } + if (this._clearLayerTextures) { + this._clearLayerTextures.name = name + " Clear Layer"; + } + if (this._objectRendererForLayer) { + this._objectRendererForLayer.name = name + " Render to Layer"; + } + } + /** + * Constructs a new layer task. + * @param name Name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param scene The scene to render the layer in. + * @param layer The layer. + * @param numBlurPasses The number of blur passes applied by the layer. + * @param useCustomBlur If true, the layer will use a custom blur post process instead of the default one. + * @param _setRenderTargetDepth If true, the task will set the render target depth. + * @param _notifyBlurObservable If true, the task will notify before and after blurring occurs. + */ + constructor(name, frameGraph, scene, layer, numBlurPasses, useCustomBlur = false, _setRenderTargetDepth = false, _notifyBlurObservable = false) { + super(name, frameGraph); + this._setRenderTargetDepth = _setRenderTargetDepth; + this._notifyBlurObservable = _notifyBlurObservable; + this._blurX = []; + this._blurY = []; + this._onBeforeBlurTask = null; + this._onAfterBlurTask = null; + this._onBeforeObservableObserver = null; + this._onAfterObservableObserver = null; + this._onAfterRenderingGroupObserver = null; + this._scene = scene; + this._engine = scene.getEngine(); + this.layer = layer; + for (let i = 0; i < numBlurPasses; i++) { + if (useCustomBlur) { + this._blurX.push(new FrameGraphGlowBlurTask(`${name} Blur X${i}`, this._frameGraph, this.layer._postProcesses[1 + i * 2 + 0])); + this._blurY.push(new FrameGraphGlowBlurTask(`${name} Blur Y${i}`, this._frameGraph, this.layer._postProcesses[1 + i * 2 + 1])); + } + else { + this._blurX.push(new FrameGraphBlurTask(`${name} Blur X${i}`, this._frameGraph, this.layer._postProcesses[i * 2 + 0])); + this._blurY.push(new FrameGraphBlurTask(`${name} Blur Y${i}`, this._frameGraph, this.layer._postProcesses[i * 2 + 1])); + } + } + this._clearLayerTextures = new FrameGraphClearTextureTask(name + " Clear Layer", frameGraph); + this._clearLayerTextures.clearColor = true; + this._clearLayerTextures.clearDepth = true; + this._objectRendererForLayer = new FrameGraphObjectRendererTask(name + " Render to Layer", frameGraph, scene, undefined, this.layer.objectRenderer); + if (this._notifyBlurObservable) { + this._onBeforeBlurTask = new FrameGraphExecuteTask(name + " On Before Blur", frameGraph); + this._onAfterBlurTask = new FrameGraphExecuteTask(name + " On After Blur", frameGraph); + this._onBeforeBlurTask.func = () => { + if (this.layer.onBeforeBlurObservable.hasObservers()) { + this.layer.onBeforeBlurObservable.notifyObservers(this.layer); + } + }; + this._onAfterBlurTask.func = () => { + if (this.layer.onAfterBlurObservable.hasObservers()) { + this.layer.onAfterBlurObservable.notifyObservers(this.layer); + } + }; + } + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.onTexturesAllocatedObservable.add((context) => { + for (let i = 0; i < this._blurX.length; i++) { + this._blurX[i].onTexturesAllocatedObservable.notifyObservers(context); + this._blurY[i].onTexturesAllocatedObservable.notifyObservers(context); + } + context.setTextureSamplingMode(this._blurY[this._blurY.length - 1].targetTexture, 2); + }); + } + isReady() { + return this._objectRendererForLayer.isReady() && this.layer.isLayerReady(); + } + record() { + if (this.targetTexture === undefined || this.objectRendererTask === undefined) { + throw new Error(`${this.constructor.name} "${this.name}": targetTexture and objectRendererTask are required`); + } + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture); + // Uses the layerTexture or creates a color texture to render the layer to + let textureSize; + let textureCreationOptions; + let colorLayerOutput; + if (this.layerTexture) { + colorLayerOutput = this.layerTexture; + textureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.layerTexture); + textureSize = getDimensionsFromTextureSize(textureCreationOptions.size); + textureCreationOptions.size = textureSize; + } + else { + const targetTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.targetTexture); + const fixedTextureSize = this.layer._options.mainTextureFixedSize ? Math.max(2, this.layer._options.mainTextureFixedSize) : 0; + textureSize = getDimensionsFromTextureSize(targetTextureCreationOptions.size); + textureSize.width = fixedTextureSize || Math.floor(textureSize.width * (this.layer._options.mainTextureRatio || 0.1)) || 1; + textureSize.height = fixedTextureSize || Math.floor(textureSize.height * (this.layer._options.mainTextureRatio || 0.1)) || 1; + textureCreationOptions = { + size: textureSize, + options: { + createMipMaps: false, + types: [this.layer._options.mainTextureType], + formats: [5], + samples: 1, + useSRGBBuffers: [false], + creationFlags: [0], + }, + sizeIsPercentage: this.layer._options.mainTextureFixedSize ? false : targetTextureCreationOptions.sizeIsPercentage, + }; + colorLayerOutput = this._frameGraph.textureManager.createRenderTargetTexture(`${this.name} Color`, textureCreationOptions); + } + // Creates a depth texture, used to render objects to the layer + // We don't reuse the depth texture of the objectRendererTask, as the size of the layer texture will generally be different (smaller). + const textureDepthCreationOptions = { + size: textureSize, + options: FrameGraphTextureManager.CloneTextureOptions(textureCreationOptions.options), + sizeIsPercentage: textureCreationOptions.sizeIsPercentage, + }; + textureDepthCreationOptions.options.formats[0] = 14; + const depthLayerOutput = this._frameGraph.textureManager.createRenderTargetTexture(`${this.name} Depth`, textureDepthCreationOptions); + // Clears the textures + this._clearLayerTextures.targetTexture = colorLayerOutput; + this._clearLayerTextures.depthTexture = depthLayerOutput; + this._clearLayerTextures.color = this.layer.neutralColor; + this._clearLayerTextures.clearDepth = true; + const clearTaskPass = this._clearLayerTextures.record(); + // Renders the objects to the layer texture + this._objectRendererForLayer.targetTexture = this._clearLayerTextures.outputTexture; + this._objectRendererForLayer.depthTexture = this._clearLayerTextures.outputDepthTexture; + this._objectRendererForLayer.camera = this.objectRendererTask.camera; + this._objectRendererForLayer.objectList = this.objectRendererTask.objectList; + this._objectRendererForLayer.disableShadows = true; + const objectRendererForLayerTaskPass = this._objectRendererForLayer.record(); + // Blurs the layer color texture + let blurTextureType = 0; + if (this._engine.getCaps().textureHalfFloatRender) { + blurTextureType = 2; + } + else { + blurTextureType = 0; + } + textureCreationOptions.options.types[0] = blurTextureType; + const blurTextureSizeRatio = this.layer._options.blurTextureSizeRatio !== undefined ? this.layer._options.blurTextureSizeRatio || 0.1 : undefined; + if (blurTextureSizeRatio !== undefined) { + textureSize.width = Math.floor(textureSize.width * blurTextureSizeRatio) || 1; + textureSize.height = Math.floor(textureSize.height * blurTextureSizeRatio) || 1; + } + const onBeforeBlurPass = this._onBeforeBlurTask?.record(); + const blurPasses = []; + for (let i = 0; i < this._blurX.length; i++) { + const blurXTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurX[i].name, textureCreationOptions); + this._blurX[i].sourceTexture = i === 0 ? this._objectRendererForLayer.outputTexture : this._blurY[i - 1].outputTexture; + this._blurX[i].sourceSamplingMode = 2; + this._blurX[i].targetTexture = blurXTextureHandle; + blurPasses.push(this._blurX[i].record(true)); + const blurYTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurY[i].name, textureCreationOptions); + this._blurY[i].sourceTexture = this._blurX[i].outputTexture; + this._blurY[i].sourceSamplingMode = 2; + this._blurY[i].targetTexture = blurYTextureHandle; + blurPasses.push(this._blurY[i].record(true)); + textureSize.width = textureSize.width >> 1; + textureSize.height = textureSize.height >> 1; + } + const onAfterBlurPass = this._onAfterBlurTask?.record(); + // Enables stencil (if stencil is needed) when rendering objects to the main texture + // We also disable the internal passes if the layer should not render + this.objectRendererTask.objectRenderer.onBeforeRenderObservable.remove(this._onBeforeObservableObserver); + this._onBeforeObservableObserver = this.objectRendererTask.objectRenderer.onBeforeRenderObservable.add(() => { + const shouldRender = this.layer.shouldRender(); + clearTaskPass.disabled = !shouldRender; + objectRendererForLayerTaskPass.disabled = !shouldRender; + if (onBeforeBlurPass) { + onBeforeBlurPass.disabled = !shouldRender; + } + for (let i = 0; i < blurPasses.length; i++) { + blurPasses[i].disabled = !shouldRender; + } + if (onAfterBlurPass) { + onAfterBlurPass.disabled = !shouldRender; + } + if (shouldRender && this.layer.needStencil()) { + this._engine.setStencilBuffer(true); + this._engine.setStencilFunctionReference(1); + } + }); + this.objectRendererTask.objectRenderer.onAfterRenderObservable.remove(this._onAfterObservableObserver); + this._onAfterObservableObserver = this.objectRendererTask.objectRenderer.onAfterRenderObservable.add(() => { + if (this.layer.shouldRender() && this.layer.needStencil()) { + this._engine.setStencilBuffer(false); + } + }); + // Composes the layer with the target texture + this.layer.bindTexturesForCompose = undefined; + this._clearAfterRenderingGroupObserver(); + const pass = this._frameGraph.addRenderPass(this.name); + for (let i = 0; i < this._blurY.length; i++) { + pass.addDependencies(this._blurY[i].outputTexture); + } + pass.setRenderTarget(this.outputTexture); + if (this._setRenderTargetDepth) { + pass.setRenderTargetDepth(this.objectRendererTask.depthTexture); + } + pass.setExecuteFunc((context) => { + if (!this.layer.bindTexturesForCompose) { + this.layer.bindTexturesForCompose = (effect) => { + for (let i = 0; i < this._blurY.length; i++) { + context.bindTextureHandle(effect, `textureSampler${i > 0 ? i + 1 : ""}`, this._blurY[i].outputTexture); + } + }; + } + if (this.layer._options.renderingGroupId !== -1) { + if (!this._onAfterRenderingGroupObserver) { + this._onAfterRenderingGroupObserver = this._scene.onAfterRenderingGroupObservable.add((info) => { + if (!this.layer.shouldRender() || + info.renderingGroupId !== this.layer._options.renderingGroupId || + info.renderingManager !== this.objectRendererTask.objectRenderer._renderingManager) { + return; + } + this._objectRendererForLayer.objectList = this.objectRendererTask.objectList; + context.saveDepthStates(); + context.setDepthStates(false, false); + context._applyRenderTarget(); + this.layer.compose(); + context.restoreDepthStates(); + }); + } + } + else { + this._clearAfterRenderingGroupObserver(); + if (this.layer.shouldRender()) { + this._objectRendererForLayer.objectList = this.objectRendererTask.objectList; // in case the object list has changed in objectRendererTask + context.setDepthStates(false, false); + context._applyRenderTarget(); + this.layer.compose(); + } + } + }); + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.setRenderTarget(this.outputTexture); + if (this._setRenderTargetDepth) { + passDisabled.setRenderTargetDepth(this.objectRendererTask.depthTexture); + } + passDisabled.setExecuteFunc((_context) => { }); + } + _clearAfterRenderingGroupObserver() { + this._scene.onAfterRenderingGroupObservable.remove(this._onAfterRenderingGroupObserver); + this._onAfterRenderingGroupObserver = null; + } + dispose() { + this._clearAfterRenderingGroupObserver(); + this._clearLayerTextures.dispose(); + this._objectRendererForLayer.dispose(); + this._onBeforeBlurTask?.dispose(); + this._onAfterBlurTask?.dispose(); + this.layer.dispose(); + for (let i = 0; i < this._blurX.length; i++) { + this._blurX[i].dispose(); + this._blurY[i].dispose(); + } + super.dispose(); + } +} + +/** + * Task which applies a glowing effect to a texture. + */ +class FrameGraphGlowLayerTask extends FrameGraphBaseLayerTask { + /** + * Constructs a new glow layer task. + * @param name Name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param scene The scene to render the glow layer in. + * @param options Options for the glow layer. + */ + constructor(name, frameGraph, scene, options) { + super(name, frameGraph, scene, new ThinGlowLayer(name, scene, options, true), 2); + this.layer._renderPassId = this._objectRendererForLayer.objectRenderer.renderPassId; + } +} + +/** + * Block that implements the glow layer + */ +class NodeRenderGraphGlowLayerBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphGlowLayerBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param ldrMerge Forces the merge step to be done in ldr (clamp values > 1). Default: false + * @param layerTextureRatio multiplication factor applied to the main texture size to compute the size of the layer render target texture (default: 0.5) + * @param layerTextureFixedSize defines the fixed size of the layer render target texture. Takes precedence over layerTextureRatio if provided (default: undefined) + * @param layerTextureType defines the type of the layer texture (default: 0) + */ + constructor(name, frameGraph, scene, ldrMerge = false, layerTextureRatio = 0.5, layerTextureFixedSize, layerTextureType = 0) { + super(name, frameGraph, scene); + this._additionalConstructionParameters = [ldrMerge, layerTextureRatio, layerTextureFixedSize, layerTextureType]; + this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this.registerInput("layer", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("objectRenderer", NodeRenderGraphBlockConnectionPointTypes.Object, true, new NodeRenderGraphConnectionPointCustomObject("objectRenderer", this, 0 /* NodeRenderGraphConnectionPointDirection.Input */, NodeRenderGraphBaseObjectRendererBlock, "NodeRenderGraphBaseObjectRendererBlock")); + this._addDependenciesInput(); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBufferDepthStencil); + this.layer.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer); + this.output._typeConnectionSource = this.target; + this._frameGraphTask = new FrameGraphGlowLayerTask(this.name, this._frameGraph, this._scene, { + ldrMerge, + mainTextureRatio: layerTextureRatio, + mainTextureFixedSize: layerTextureFixedSize, + mainTextureType: layerTextureType, + }); + } + _createTask(ldrMerge, layerTextureRatio, layerTextureFixedSize, layerTextureType) { + const blurKernelSize = this.blurKernelSize; + const intensity = this.intensity; + this._frameGraphTask?.dispose(); + this._frameGraphTask = new FrameGraphGlowLayerTask(this.name, this._frameGraph, this._scene, { + ldrMerge, + mainTextureRatio: layerTextureRatio, + mainTextureFixedSize: layerTextureFixedSize, + mainTextureType: layerTextureType, + }); + this.blurKernelSize = blurKernelSize; + this.intensity = intensity; + this._additionalConstructionParameters = [ldrMerge, layerTextureRatio, layerTextureFixedSize, layerTextureType]; + } + /** Forces the merge step to be done in ldr (clamp values > 1). Default: false */ + get ldrMerge() { + return this._frameGraphTask.layer.ldrMerge; + } + set ldrMerge(value) { + const options = this._frameGraphTask.layer._options; + this._createTask(value, options.mainTextureRatio, options.mainTextureFixedSize, options.mainTextureType); + } + /** Multiplication factor applied to the main texture size to compute the size of the layer render target texture */ + get layerTextureRatio() { + return this._frameGraphTask.layer._options.mainTextureRatio; + } + set layerTextureRatio(value) { + const options = this._frameGraphTask.layer._options; + this._createTask(options.ldrMerge, value, options.mainTextureFixedSize, options.mainTextureType); + } + /** Defines the fixed size of the layer render target texture. Takes precedence over layerTextureRatio if provided */ + get layerTextureFixedSize() { + return this._frameGraphTask.layer._options.mainTextureFixedSize; + } + set layerTextureFixedSize(value) { + const options = this._frameGraphTask.layer._options; + this._createTask(options.ldrMerge, options.mainTextureRatio, value, options.mainTextureType); + } + /** Defines the type of the layer texture */ + get layerTextureType() { + return this._frameGraphTask.layer._options.mainTextureType; + } + set layerTextureType(value) { + const options = this._frameGraphTask.layer._options; + this._createTask(options.ldrMerge, options.mainTextureRatio, options.mainTextureFixedSize, value); + } + /** How big is the kernel of the blur texture */ + get blurKernelSize() { + return this._frameGraphTask.layer.blurKernelSize; + } + set blurKernelSize(value) { + this._frameGraphTask.layer.blurKernelSize = value; + } + /** The intensity of the glow */ + get intensity() { + return this._frameGraphTask.layer.intensity; + } + set intensity(value) { + this._frameGraphTask.layer.intensity = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphGlowLayerBlock"; + } + /** + * Gets the target texture input component + */ + get target() { + return this._inputs[0]; + } + /** + * Gets the layer texture input component + */ + get layer() { + return this._inputs[1]; + } + /** + * Gets the objectRenderer input component + */ + get objectRenderer() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.output.value = this._frameGraphTask.outputTexture; + this._frameGraphTask.targetTexture = this.target.connectedPoint?.value; + this._frameGraphTask.layerTexture = this.layer.connectedPoint?.value; + this._frameGraphTask.objectRendererTask = this.objectRenderer.connectedPoint?.value; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.blurKernelSize = ${this.blurKernelSize};`); + codes.push(`${this._codeVariableName}.intensity = ${this.intensity};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.blurKernelSize = this.blurKernelSize; + serializationObject.intensity = this.intensity; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.blurKernelSize = serializationObject.blurKernelSize; + this.intensity = serializationObject.intensity; + } +} +__decorate([ + editableInPropertyPage("LDR merge", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphGlowLayerBlock.prototype, "ldrMerge", null); +__decorate([ + editableInPropertyPage("Layer texture ratio", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphGlowLayerBlock.prototype, "layerTextureRatio", null); +__decorate([ + editableInPropertyPage("Layer texture fixed size", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphGlowLayerBlock.prototype, "layerTextureFixedSize", null); +__decorate([ + editableInPropertyPage("Layer texture type", 8 /* PropertyTypeForEdition.TextureType */, "PROPERTIES") +], NodeRenderGraphGlowLayerBlock.prototype, "layerTextureType", null); +__decorate([ + editableInPropertyPage("Blur kernel size", 2 /* PropertyTypeForEdition.Int */, "PROPERTIES", { min: 1, max: 256 }) +], NodeRenderGraphGlowLayerBlock.prototype, "blurKernelSize", null); +__decorate([ + editableInPropertyPage("Intensity", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0, max: 5 }) +], NodeRenderGraphGlowLayerBlock.prototype, "intensity", null); +RegisterClass("BABYLON.NodeRenderGraphGlowLayerBlock", NodeRenderGraphGlowLayerBlock); + +/** + * @internal + */ +class ThinHighlightLayer extends ThinEffectLayer { + /** + * Specifies the horizontal size of the blur. + */ + set blurHorizontalSize(value) { + this._horizontalBlurPostprocess.kernel = value; + this._options.blurHorizontalSize = value; + } + /** + * Specifies the vertical size of the blur. + */ + set blurVerticalSize(value) { + this._verticalBlurPostprocess.kernel = value; + this._options.blurVerticalSize = value; + } + /** + * Gets the horizontal size of the blur. + */ + get blurHorizontalSize() { + return this._horizontalBlurPostprocess.kernel; + } + /** + * Gets the vertical size of the blur. + */ + get blurVerticalSize() { + return this._verticalBlurPostprocess.kernel; + } + /** + * Instantiates a new highlight Layer and references it to the scene.. + * @param name The name of the layer + * @param scene The scene to use the layer in + * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information) + * @param dontCheckIfReady Specifies if the layer should disable checking whether all the post processes are ready (default: false). To save performance, this should be set to true and you should call `isReady` manually before rendering to the layer. + */ + constructor(name, scene, options, dontCheckIfReady = false) { + super(name, scene, options !== undefined ? !!options.forceGLSL : false); + /** + * Specifies whether or not the inner glow is ACTIVE in the layer. + */ + this.innerGlow = true; + /** + * Specifies whether or not the outer glow is ACTIVE in the layer. + */ + this.outerGlow = true; + this._instanceGlowingMeshStencilReference = ThinHighlightLayer.GlowingMeshStencilReference++; + /** @internal */ + this._meshes = {}; + /** @internal */ + this._excludedMeshes = {}; + /** @internal */ + this._mainObjectRendererRenderPassId = -1; + this.neutralColor = ThinHighlightLayer.NeutralColor; + // Adapt options + this._options = { + mainTextureRatio: 0.5, + blurTextureSizeRatio: 0.5, + mainTextureFixedSize: 0, + blurHorizontalSize: 1.0, + blurVerticalSize: 1.0, + alphaBlendingMode: 2, + camera: null, + renderingGroupId: -1, + forceGLSL: false, + mainTextureType: 0, + isStroke: false, + ...options, + }; + // Initialize the layer + this._init(this._options); + // Do not render as long as no meshes have been added + this._shouldRender = false; + if (dontCheckIfReady) { + // When dontCheckIfReady is true, we are in the new ThinXXX layer mode, so we must call _createTextureAndPostProcesses ourselves (it is called by EffectLayer otherwise) + this._createTextureAndPostProcesses(); + } + } + /** + * Gets the class name of the effect layer + * @returns the string with the class name of the effect layer + */ + getClassName() { + return "HighlightLayer"; + } + async _importShadersAsync() { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([ + Promise.resolve().then(() => glowMapMerge_fragment), + Promise.resolve().then(() => glowMapMerge_vertex), + Promise.resolve().then(() => glowBlurPostProcess_fragment), + ]); + } + else { + await Promise.all([Promise.resolve().then(() => glowMapMerge_fragment$1), Promise.resolve().then(() => glowMapMerge_vertex$1), Promise.resolve().then(() => glowBlurPostProcess_fragment$1)]); + } + await super._importShadersAsync(); + } + getEffectName() { + return ThinHighlightLayer.EffectName; + } + _numInternalDraws() { + return 2; // we need two rendering, one for the inner glow and the other for the outer glow + } + _createMergeEffect() { + return this._engine.createEffect("glowMapMerge", [VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined, undefined, undefined, undefined, undefined, this._shaderLanguage, this._shadersLoaded + ? undefined + : async () => { + await this._importShadersAsync(); + this._shadersLoaded = true; + }); + } + _createTextureAndPostProcesses() { + if (this._options.alphaBlendingMode === 2) { + this._downSamplePostprocess = new ThinPassPostProcess("HighlightLayerPPP", this._scene.getEngine()); + this._horizontalBlurPostprocess = new ThinGlowBlurPostProcess("HighlightLayerHBP", this._scene.getEngine(), new Vector2(1.0, 0), this._options.blurHorizontalSize); + this._verticalBlurPostprocess = new ThinGlowBlurPostProcess("HighlightLayerVBP", this._scene.getEngine(), new Vector2(0, 1.0), this._options.blurVerticalSize); + this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess]; + } + else { + this._horizontalBlurPostprocess = new ThinBlurPostProcess("HighlightLayerHBP", this._scene.getEngine(), new Vector2(1.0, 0), this._options.blurHorizontalSize / 2); + this._verticalBlurPostprocess = new ThinBlurPostProcess("HighlightLayerVBP", this._scene.getEngine(), new Vector2(0, 1.0), this._options.blurVerticalSize / 2); + this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess]; + } + } + needStencil() { + return true; + } + isReady(subMesh, useInstances) { + const material = subMesh.getMaterial(); + const mesh = subMesh.getRenderingMesh(); + if (!material || !mesh || !this._meshes) { + return false; + } + let emissiveTexture = null; + const highlightLayerMesh = this._meshes[mesh.uniqueId]; + if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) { + emissiveTexture = material.emissiveTexture; + } + return super._isSubMeshReady(subMesh, useInstances, emissiveTexture); + } + _canRenderMesh(_mesh, _material) { + // all meshes can be rendered in the highlight layer, even transparent ones + return true; + } + _internalCompose(effect, renderIndex) { + // Texture + this.bindTexturesForCompose(effect); + // Cache + const engine = this._engine; + engine.cacheStencilState(); + // Stencil operations + engine.setStencilOperationPass(7681); + engine.setStencilOperationFail(7680); + engine.setStencilOperationDepthFail(7680); + // Draw order + engine.setStencilMask(0x00); + engine.setStencilBuffer(true); + engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference); + // 2 passes inner outer + if (this.outerGlow && renderIndex === 0) { + // the outer glow is rendered the first time _internalRender is called, so when renderIndex == 0 (and only if outerGlow is enabled) + effect.setFloat("offset", 0); + engine.setStencilFunction(517); + engine.drawElementsType(Material.TriangleFillMode, 0, 6); + } + if (this.innerGlow && renderIndex === 1) { + // the inner glow is rendered the second time _internalRender is called, so when renderIndex == 1 (and only if innerGlow is enabled) + effect.setFloat("offset", 1); + engine.setStencilFunction(514); + engine.drawElementsType(Material.TriangleFillMode, 0, 6); + } + // Restore Cache + engine.restoreStencilState(); + } + _setEmissiveTextureAndColor(mesh, _subMesh, material) { + const highlightLayerMesh = this._meshes[mesh.uniqueId]; + if (highlightLayerMesh) { + this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0); + } + else { + this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a); + } + if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) { + this._emissiveTextureAndColor.texture = material.emissiveTexture; + this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0); + } + else { + this._emissiveTextureAndColor.texture = null; + } + } + shouldRender() { + return this._meshes && super.shouldRender() ? true : false; + } + _shouldRenderMesh(mesh) { + if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) { + return false; + } + return super.hasMesh(mesh); + } + _addCustomEffectDefines(defines) { + defines.push("#define HIGHLIGHT"); + } + /** + * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer. + * @param mesh The mesh to exclude from the highlight layer + */ + addExcludedMesh(mesh) { + if (!this._excludedMeshes) { + return; + } + const meshExcluded = this._excludedMeshes[mesh.uniqueId]; + if (!meshExcluded) { + const obj = { + mesh: mesh, + beforeBind: null, + afterRender: null, + stencilState: false, + }; + obj.beforeBind = mesh.onBeforeBindObservable.add((mesh) => { + if (this._mainObjectRendererRenderPassId !== -1 && this._mainObjectRendererRenderPassId !== this._engine.currentRenderPassId) { + return; + } + obj.stencilState = mesh.getEngine().getStencilBuffer(); + mesh.getEngine().setStencilBuffer(false); + }); + obj.afterRender = mesh.onAfterRenderObservable.add((mesh) => { + if (this._mainObjectRendererRenderPassId !== -1 && this._mainObjectRendererRenderPassId !== this._engine.currentRenderPassId) { + return; + } + mesh.getEngine().setStencilBuffer(obj.stencilState); + }); + this._excludedMeshes[mesh.uniqueId] = obj; + } + } + /** + * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer. + * @param mesh The mesh to highlight + */ + removeExcludedMesh(mesh) { + if (!this._excludedMeshes) { + return; + } + const meshExcluded = this._excludedMeshes[mesh.uniqueId]; + if (meshExcluded) { + if (meshExcluded.beforeBind) { + mesh.onBeforeBindObservable.remove(meshExcluded.beforeBind); + } + if (meshExcluded.afterRender) { + mesh.onAfterRenderObservable.remove(meshExcluded.afterRender); + } + } + this._excludedMeshes[mesh.uniqueId] = null; + } + hasMesh(mesh) { + if (!this._meshes || !super.hasMesh(mesh)) { + return false; + } + return !!this._meshes[mesh.uniqueId]; + } + /** + * Add a mesh in the highlight layer in order to make it glow with the chosen color. + * @param mesh The mesh to highlight + * @param color The color of the highlight + * @param glowEmissiveOnly Extract the glow from the emissive texture + */ + addMesh(mesh, color, glowEmissiveOnly = false) { + if (!this._meshes) { + return; + } + const meshHighlight = this._meshes[mesh.uniqueId]; + if (meshHighlight) { + meshHighlight.color = color; + } + else { + this._meshes[mesh.uniqueId] = { + mesh: mesh, + color: color, + // Lambda required for capture due to Observable this context + observerHighlight: mesh.onBeforeBindObservable.add((mesh) => { + if (this._mainObjectRendererRenderPassId !== -1 && this._mainObjectRendererRenderPassId !== this._engine.currentRenderPassId) { + return; + } + if (this.isEnabled) { + if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) { + this._defaultStencilReference(mesh); + } + else { + mesh.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference); + } + } + }), + observerDefault: mesh.onAfterRenderObservable.add((mesh) => { + if (this._mainObjectRendererRenderPassId !== -1 && this._mainObjectRendererRenderPassId !== this._engine.currentRenderPassId) { + return; + } + if (this.isEnabled) { + this._defaultStencilReference(mesh); + } + }), + glowEmissiveOnly: glowEmissiveOnly, + }; + mesh.onDisposeObservable.add(() => { + this._disposeMesh(mesh); + }); + } + this._shouldRender = true; + } + /** + * Remove a mesh from the highlight layer in order to make it stop glowing. + * @param mesh The mesh to highlight + */ + removeMesh(mesh) { + if (!this._meshes) { + return; + } + const meshHighlight = this._meshes[mesh.uniqueId]; + if (meshHighlight) { + if (meshHighlight.observerHighlight) { + mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight); + } + if (meshHighlight.observerDefault) { + mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault); + } + delete this._meshes[mesh.uniqueId]; + } + this._shouldRender = false; + for (const meshHighlightToCheck in this._meshes) { + if (this._meshes[meshHighlightToCheck]) { + this._shouldRender = true; + break; + } + } + } + /** + * Remove all the meshes currently referenced in the highlight layer + */ + removeAllMeshes() { + if (!this._meshes) { + return; + } + for (const uniqueId in this._meshes) { + if (Object.prototype.hasOwnProperty.call(this._meshes, uniqueId)) { + const mesh = this._meshes[uniqueId]; + if (mesh) { + this.removeMesh(mesh.mesh); + } + } + } + } + _defaultStencilReference(mesh) { + mesh.getScene().getEngine().setStencilFunctionReference(ThinHighlightLayer.NormalMeshStencilReference); + } + _disposeMesh(mesh) { + this.removeMesh(mesh); + this.removeExcludedMesh(mesh); + } + dispose() { + if (this._meshes) { + // Clean mesh references + for (const id in this._meshes) { + const meshHighlight = this._meshes[id]; + if (meshHighlight && meshHighlight.mesh) { + if (meshHighlight.observerHighlight) { + meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight); + } + if (meshHighlight.observerDefault) { + meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault); + } + } + } + this._meshes = null; + } + if (this._excludedMeshes) { + for (const id in this._excludedMeshes) { + const meshHighlight = this._excludedMeshes[id]; + if (meshHighlight) { + if (meshHighlight.beforeBind) { + meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.beforeBind); + } + if (meshHighlight.afterRender) { + meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender); + } + } + } + this._excludedMeshes = null; + } + super.dispose(); + } +} +/** + * Effect Name of the highlight layer. + */ +ThinHighlightLayer.EffectName = "HighlightLayer"; +/** + * The neutral color used during the preparation of the glow effect. + * This is black by default as the blend operation is a blend operation. + */ +ThinHighlightLayer.NeutralColor = new Color4(0, 0, 0, 0); +/** + * Stencil value used for glowing meshes. + */ +ThinHighlightLayer.GlowingMeshStencilReference = 0x02; +/** + * Stencil value used for the other meshes in the scene. + */ +ThinHighlightLayer.NormalMeshStencilReference = 0x01; + +/** + * Task which applies a highlight effect to a texture. + */ +class FrameGraphHighlightLayerTask extends FrameGraphBaseLayerTask { + /** + * Constructs a new highlight layer task. + * @param name Name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param scene The scene to render the highlight layer in. + * @param options Options for the highlight layer. + */ + constructor(name, frameGraph, scene, options) { + const alphaBlendingMode = options?.alphaBlendingMode ?? 2; + super(name, frameGraph, scene, new ThinHighlightLayer(name, scene, options, true), 1, alphaBlendingMode === 2, true, true); + } + record() { + if (!this.objectRendererTask.depthTexture) { + throw new Error(`FrameGraphHighlightLayerTask "${this.name}": objectRendererTask must have a depthTexture input`); + } + const depthTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.objectRendererTask.depthTexture); + if (!depthTextureCreationOptions.options.formats || !HasStencilAspect(depthTextureCreationOptions.options.formats[0])) { + throw new Error(`FrameGraphHighlightLayerTask "${this.name}": objectRendererTask depthTexture must have a stencil aspect`); + } + super.record(); + this.layer._mainObjectRendererRenderPassId = this.objectRendererTask.objectRenderer.renderPassId; + } +} + +/** + * Block that implements the highlight layer + */ +class NodeRenderGraphHighlightLayerBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphHighlightLayerBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param layerTextureRatio multiplication factor applied to the main texture size to compute the size of the layer render target texture (default: 0.5) + * @param layerTextureFixedSize defines the fixed size of the layer render target texture. Takes precedence over layerTextureRatio if provided (default: undefined) + * @param blurTextureSizeRatio defines the factor to apply to the layer texture size to create the blur textures (default: 0.5) + * @param isStroke should we display highlight as a solid stroke? (default: false) + * @param layerTextureType defines the type of the layer texture (default: 0) + */ + constructor(name, frameGraph, scene, layerTextureRatio = 0.5, layerTextureFixedSize, blurTextureSizeRatio = 0.5, isStroke = false, layerTextureType = 0) { + super(name, frameGraph, scene); + this._additionalConstructionParameters = [layerTextureRatio, layerTextureFixedSize, blurTextureSizeRatio, isStroke, layerTextureType]; + this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this.registerInput("layer", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("objectRenderer", NodeRenderGraphBlockConnectionPointTypes.Object, true, new NodeRenderGraphConnectionPointCustomObject("objectRenderer", this, 0 /* NodeRenderGraphConnectionPointDirection.Input */, NodeRenderGraphBaseObjectRendererBlock, "NodeRenderGraphBaseObjectRendererBlock")); + this._addDependenciesInput(); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBufferDepthStencil); + this.layer.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer); + this.output._typeConnectionSource = this.target; + this._frameGraphTask = new FrameGraphHighlightLayerTask(this.name, this._frameGraph, this._scene, { + mainTextureRatio: layerTextureRatio, + mainTextureFixedSize: layerTextureFixedSize, + blurTextureSizeRatio, + isStroke, + mainTextureType: layerTextureType, + }); + } + _createTask(layerTextureRatio, layerTextureFixedSize, blurTextureSizeRatio, isStroke, layerTextureType) { + const blurHorizontalSize = this.blurHorizontalSize; + const blurVerticalSize = this.blurVerticalSize; + this._frameGraphTask?.dispose(); + this._frameGraphTask = new FrameGraphHighlightLayerTask(this.name, this._frameGraph, this._scene, { + mainTextureRatio: layerTextureRatio, + mainTextureFixedSize: layerTextureFixedSize, + blurTextureSizeRatio, + isStroke, + mainTextureType: layerTextureType, + }); + this.blurHorizontalSize = blurHorizontalSize; + this.blurVerticalSize = blurVerticalSize; + this._additionalConstructionParameters = [layerTextureRatio, layerTextureFixedSize, blurTextureSizeRatio, isStroke, layerTextureType]; + } + /** Multiplication factor applied to the main texture size to compute the size of the layer render target texture */ + get layerTextureRatio() { + return this._frameGraphTask.layer._options.mainTextureRatio; + } + set layerTextureRatio(value) { + const options = this._frameGraphTask.layer._options; + this._createTask(value, options.mainTextureFixedSize, options.blurTextureSizeRatio, options.isStroke, options.mainTextureType); + } + /** Defines the fixed size of the layer render target texture. Takes precedence over layerTextureRatio if provided */ + get layerTextureFixedSize() { + return this._frameGraphTask.layer._options.mainTextureFixedSize; + } + set layerTextureFixedSize(value) { + const options = this._frameGraphTask.layer._options; + this._createTask(options.mainTextureRatio, value, options.blurTextureSizeRatio, options.isStroke, options.mainTextureType); + } + /** Defines the factor to apply to the layer texture size to create the blur textures */ + get blurTextureSizeRatio() { + return this._frameGraphTask.layer._options.blurTextureSizeRatio; + } + set blurTextureSizeRatio(value) { + const options = this._frameGraphTask.layer._options; + this._createTask(options.mainTextureRatio, options.mainTextureFixedSize, value, options.isStroke, options.mainTextureType); + } + /** Should we display highlight as a solid stroke? */ + get isStroke() { + return this._frameGraphTask.layer._options.isStroke; + } + set isStroke(value) { + const options = this._frameGraphTask.layer._options; + this._createTask(options.mainTextureRatio, options.mainTextureFixedSize, options.blurTextureSizeRatio, value, options.mainTextureType); + } + /** Defines the type of the layer texture */ + get layerTextureType() { + return this._frameGraphTask.layer._options.mainTextureType; + } + set layerTextureType(value) { + const options = this._frameGraphTask.layer._options; + this._createTask(options.mainTextureRatio, options.mainTextureFixedSize, options.blurTextureSizeRatio, options.isStroke, value); + } + /** How big is the horizontal kernel of the blur texture */ + get blurHorizontalSize() { + return this._frameGraphTask.layer.blurHorizontalSize; + } + set blurHorizontalSize(value) { + this._frameGraphTask.layer.blurHorizontalSize = value; + } + /** How big is the vertical kernel of the blur texture */ + get blurVerticalSize() { + return this._frameGraphTask.layer.blurVerticalSize; + } + set blurVerticalSize(value) { + this._frameGraphTask.layer.blurVerticalSize = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphHighlightLayerBlock"; + } + /** + * Gets the target texture input component + */ + get target() { + return this._inputs[0]; + } + /** + * Gets the layer input component + */ + get layer() { + return this._inputs[1]; + } + /** + * Gets the objectRenderer input component + */ + get objectRenderer() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.output.value = this._frameGraphTask.outputTexture; + this._frameGraphTask.targetTexture = this.target.connectedPoint?.value; + this._frameGraphTask.layerTexture = this.layer.connectedPoint?.value; + this._frameGraphTask.objectRendererTask = this.objectRenderer.connectedPoint?.value; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.blurHorizontalSize = ${this.blurHorizontalSize};`); + codes.push(`${this._codeVariableName}.blurVerticalSize = ${this.blurVerticalSize};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.blurHorizontalSize = this.blurHorizontalSize; + serializationObject.blurVerticalSize = this.blurVerticalSize; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.blurHorizontalSize = serializationObject.blurHorizontalSize; + this.blurVerticalSize = serializationObject.blurVerticalSize; + } +} +__decorate([ + editableInPropertyPage("Layer texture ratio", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphHighlightLayerBlock.prototype, "layerTextureRatio", null); +__decorate([ + editableInPropertyPage("Layer texture fixed size", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphHighlightLayerBlock.prototype, "layerTextureFixedSize", null); +__decorate([ + editableInPropertyPage("Blur texture size ratio", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphHighlightLayerBlock.prototype, "blurTextureSizeRatio", null); +__decorate([ + editableInPropertyPage("Is stroke", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphHighlightLayerBlock.prototype, "isStroke", null); +__decorate([ + editableInPropertyPage("Layer texture type", 8 /* PropertyTypeForEdition.TextureType */, "PROPERTIES") +], NodeRenderGraphHighlightLayerBlock.prototype, "layerTextureType", null); +__decorate([ + editableInPropertyPage("Blur horizontal size", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0, max: 4 }) +], NodeRenderGraphHighlightLayerBlock.prototype, "blurHorizontalSize", null); +__decorate([ + editableInPropertyPage("Blur vertical size", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0, max: 4 }) +], NodeRenderGraphHighlightLayerBlock.prototype, "blurVerticalSize", null); +RegisterClass("BABYLON.NodeRenderGraphHighlightLayerBlock", NodeRenderGraphHighlightLayerBlock); + +/** + * Task which applies an anaglyph post process. + */ +class FrameGraphAnaglyphTask extends FrameGraphPostProcessTask { + /** + * Constructs a new anaglyph task. + * @param name The name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param thinPostProcess The thin post process to use for the anaglyph effect. If not provided, a new one will be created. + */ + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinAnaglyphPostProcess(name, frameGraph.engine)); + } + record(skipCreationOfDisabledPasses = false) { + if (this.sourceTexture === undefined || this.leftTexture === undefined) { + throw new Error(`FrameGraphAnaglyphTask "${this.name}": sourceTexture and leftTexture are required`); + } + const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => { + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "leftSampler", this.leftTexture); + }); + pass.addDependencies(this.leftTexture); + return pass; + } +} + +/** + * @internal + */ +class NodeRenderGraphBasePostProcessBlock extends NodeRenderGraphBlock { + /** + * Create a new NodeRenderGraphBasePostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("source", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.source.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer); + this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAll); + } + _finalizeInputOutputRegistering() { + this._addDependenciesInput(); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.output._typeConnectionSource = () => { + return this.target.isConnected ? this.target : this.source; + }; + } + /** Sampling mode used to sample from the source texture */ + get sourceSamplingMode() { + return this._frameGraphTask.sourceSamplingMode; + } + set sourceSamplingMode(value) { + this._frameGraphTask.sourceSamplingMode = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphBasePostProcessBlock"; + } + /** + * Gets the source input component + */ + get source() { + return this._inputs[0]; + } + /** + * Gets the target input component + */ + get target() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.output.value = this._frameGraphTask.outputTexture; + this._frameGraphTask.sourceTexture = this.source.connectedPoint?.value; + this._frameGraphTask.targetTexture = this.target.connectedPoint?.value; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.sourceSamplingMode = this.sourceSamplingMode; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.sourceSamplingMode = serializationObject.sourceSamplingMode; + } +} +__decorate([ + editableInPropertyPage("Source sampling mode", 6 /* PropertyTypeForEdition.SamplingMode */, "PROPERTIES") +], NodeRenderGraphBasePostProcessBlock.prototype, "sourceSamplingMode", null); + +/** + * Block that implements the anaglyph post process + */ +class NodeRenderGraphAnaglyphPostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderAnaglyphPostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("leftTexture", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this.leftTexture.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer); + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphAnaglyphTask(this.name, frameGraph, new ThinAnaglyphPostProcess(name, scene.getEngine())); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphAnaglyphPostProcessBlock"; + } + /** + * Gets the left texture input component + */ + get leftTexture() { + return this._inputs[2]; + } + _buildBlock(state) { + super._buildBlock(state); + this._frameGraphTask.leftTexture = this.leftTexture.connectedPoint?.value; + } +} +RegisterClass("BABYLON.NodeRenderGraphAnaglyphPostProcessBlock", NodeRenderGraphAnaglyphPostProcessBlock); + +/** + * Post process used to render in black and white + */ +class ThinBlackAndWhitePostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => blackAndWhite_fragment)); + } + else { + list.push(Promise.resolve().then(() => blackAndWhite_fragment$1)); + } + } + /** + * Constructs a new black and white post process + * @param name Name of the effect + * @param engine Engine to use to render the effect. If not provided, the last created engine will be used + * @param options Options to configure the effect + */ + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinBlackAndWhitePostProcess.FragmentUrl, + uniforms: ThinBlackAndWhitePostProcess.Uniforms, + }); + /** + * Effect intensity (default: 1) + */ + this.degree = 1; + } + bind() { + super.bind(); + this._drawWrapper.effect.setFloat("degree", this.degree); + } +} +/** + * The fragment shader url + */ +ThinBlackAndWhitePostProcess.FragmentUrl = "blackAndWhite"; +/** + * The list of uniforms used by the effect + */ +ThinBlackAndWhitePostProcess.Uniforms = ["degree"]; + +/** + * Task which applies a black and white post process. + */ +class FrameGraphBlackAndWhiteTask extends FrameGraphPostProcessTask { + /** + * Constructs a new black and white task. + * @param name The name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param thinPostProcess The thin post process to use for the black and white effect. If not provided, a new one will be created. + */ + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinBlackAndWhitePostProcess(name, frameGraph.engine)); + } +} + +/** + * Block that implements the black and white post process + */ +class NodeRenderGraphBlackAndWhitePostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new BlackAndWhitePostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphBlackAndWhiteTask(this.name, frameGraph, new ThinBlackAndWhitePostProcess(name, scene.getEngine())); + } + /** Degree of conversion to black and white (default: 1 - full b&w conversion) */ + get degree() { + return this._frameGraphTask.postProcess.degree; + } + set degree(value) { + this._frameGraphTask.postProcess.degree = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphBlackAndWhitePostProcessBlock"; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.degree = ${this.degree};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.degree = this.degree; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.degree = serializationObject.degree; + } +} +__decorate([ + editableInPropertyPage("Degree", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0, max: 1 }) +], NodeRenderGraphBlackAndWhitePostProcessBlock.prototype, "degree", null); +RegisterClass("BABYLON.NodeRenderGraphBlackAndWhitePostProcessBlock", NodeRenderGraphBlackAndWhitePostProcessBlock); + +/** + * @internal + */ +class ThinBloomMergePostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => bloomMerge_fragment)); + } + else { + list.push(Promise.resolve().then(() => bloomMerge_fragment$1)); + } + } + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinBloomMergePostProcess.FragmentUrl, + uniforms: ThinBloomMergePostProcess.Uniforms, + samplers: ThinBloomMergePostProcess.Samplers, + }); + /** Weight of the bloom to be added to the original input. */ + this.weight = 1; + } + bind() { + super.bind(); + this._drawWrapper.effect.setFloat("bloomWeight", this.weight); + } +} +ThinBloomMergePostProcess.FragmentUrl = "bloomMerge"; +ThinBloomMergePostProcess.Uniforms = ["bloomWeight"]; +ThinBloomMergePostProcess.Samplers = ["bloomBlur"]; + +/** + * @internal + */ +class FrameGraphBloomMergeTask extends FrameGraphPostProcessTask { + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinBloomMergePostProcess(name, frameGraph.engine)); + } + record(skipCreationOfDisabledPasses = false) { + if (this.sourceTexture === undefined || this.blurTexture === undefined) { + throw new Error(`FrameGraphBloomMergeTask "${this.name}": sourceTexture and blurTexture are required`); + } + const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => { + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "bloomBlur", this.blurTexture); + }); + pass.addDependencies(this.blurTexture); + return pass; + } +} + +/** + * Post process used to extract highlights. + */ +class ThinExtractHighlightsPostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => extractHighlights_fragment)); + } + else { + list.push(Promise.resolve().then(() => extractHighlights_fragment$1)); + } + } + /** + * Constructs a new extract highlights post process + * @param name Name of the effect + * @param engine Engine to use to render the effect. If not provided, the last created engine will be used + * @param options Options to configure the effect + */ + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinExtractHighlightsPostProcess.FragmentUrl, + uniforms: ThinExtractHighlightsPostProcess.Uniforms, + }); + /** + * The luminance threshold, pixels below this value will be set to black. + */ + this.threshold = 0.9; + /** @internal */ + this._exposure = 1; + } + bind() { + super.bind(); + const effect = this._drawWrapper.effect; + effect.setFloat("threshold", Math.pow(this.threshold, ToGammaSpace)); + effect.setFloat("exposure", this._exposure); + } +} +/** + * The fragment shader url + */ +ThinExtractHighlightsPostProcess.FragmentUrl = "extractHighlights"; +/** + * The list of uniforms used by the effect + */ +ThinExtractHighlightsPostProcess.Uniforms = ["threshold", "exposure"]; + +/** + * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras + */ +class ThinBloomEffect { + /** + * The luminance threshold to find bright areas of the image to bloom. + */ + get threshold() { + return this._downscale.threshold; + } + set threshold(value) { + this._downscale.threshold = value; + } + /** + * The strength of the bloom. + */ + get weight() { + return this._merge.weight; + } + set weight(value) { + this._merge.weight = value; + } + /** + * Specifies the size of the bloom blur kernel, relative to the final output size + */ + get kernel() { + return this._blurX.kernel / this.scale; + } + set kernel(value) { + this._blurX.kernel = value * this.scale; + this._blurY.kernel = value * this.scale; + } + /** + * Creates a new instance of @see ThinBloomEffect + * @param name The name of the bloom render effect + * @param engine The engine which the render effect will be applied. (default: current engine) + * @param scale The ratio of the blur texture to the input texture that should be used to compute the bloom. + * @param blockCompilation If shaders should not be compiled when the effect is created (default: false) + */ + constructor(name, engine, scale, blockCompilation = false) { + this.scale = scale; + this._downscale = new ThinExtractHighlightsPostProcess(name + "_downscale", engine, { blockCompilation }); + this._blurX = new ThinBlurPostProcess(name + "_blurX", engine, new Vector2(1, 0), 10, { blockCompilation }); + this._blurY = new ThinBlurPostProcess(name + "_blurY", engine, new Vector2(0, 1), 10, { blockCompilation }); + this._merge = new ThinBloomMergePostProcess(name + "_merge", engine, { blockCompilation }); + } + /** + * Checks if the effect is ready to be used + * @returns if the effect is ready + */ + isReady() { + return this._downscale.isReady() && this._blurX.isReady() && this._blurY.isReady() && this._merge.isReady(); + } +} + +/** + * Task used to extract highlights from a scene. + */ +class FrameGraphExtractHighlightsTask extends FrameGraphPostProcessTask { + /** + * Constructs a new extract highlights task. + * @param name The name of the task. + * @param frameGraph The frame graph the task belongs to. + * @param thinPostProcess The thin post process to use for the task. If not provided, a new one will be created. + */ + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinExtractHighlightsPostProcess(name, frameGraph.engine)); + } +} + +/** + * Task which applies a bloom render effect. + */ +class FrameGraphBloomTask extends FrameGraphTask { + /** + * The name of the task. + */ + get name() { + return this._name; + } + set name(name) { + this._name = name; + if (this._downscale) { + this._downscale.name = `${name} Downscale`; + } + if (this._blurX) { + this._blurX.name = `${name} Blur X`; + } + if (this._blurY) { + this._blurY.name = `${name} Blur Y`; + } + if (this._merge) { + this._merge.name = `${name} Merge`; + } + } + /** + * Constructs a new bloom task. + * @param name Name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param weight Weight of the bloom effect. + * @param kernel Kernel size of the bloom effect. + * @param threshold Threshold of the bloom effect. + * @param hdr Whether the bloom effect is HDR. + * @param bloomScale The scale of the bloom effect. This value is multiplied by the source texture size to determine the bloom texture size. + */ + constructor(name, frameGraph, weight, kernel, threshold, hdr = false, bloomScale = 0.5) { + super(name, frameGraph); + /** + * The sampling mode to use for the source texture. + */ + this.sourceSamplingMode = 2; + this.hdr = hdr; + this._defaultPipelineTextureType = 0; + if (hdr) { + const caps = frameGraph.engine.getCaps(); + if (caps.textureHalfFloatRender) { + this._defaultPipelineTextureType = 2; + } + else if (caps.textureFloatRender) { + this._defaultPipelineTextureType = 1; + } + } + this.bloom = new ThinBloomEffect(name, frameGraph.engine, bloomScale); + this.bloom.threshold = threshold; + this.bloom.kernel = kernel; + this.bloom.weight = weight; + this._downscale = new FrameGraphExtractHighlightsTask(`${name} Downscale`, this._frameGraph, this.bloom._downscale); + this._blurX = new FrameGraphBlurTask(`${name} Blur X`, this._frameGraph, this.bloom._blurX); + this._blurY = new FrameGraphBlurTask(`${name} Blur Y`, this._frameGraph, this.bloom._blurY); + this._merge = new FrameGraphBloomMergeTask(`${name} Merge`, this._frameGraph, this.bloom._merge); + this.onTexturesAllocatedObservable.add((context) => { + this._downscale.onTexturesAllocatedObservable.notifyObservers(context); + this._blurX.onTexturesAllocatedObservable.notifyObservers(context); + this._blurY.onTexturesAllocatedObservable.notifyObservers(context); + this._merge.onTexturesAllocatedObservable.notifyObservers(context); + }); + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + } + isReady() { + return this.bloom.isReady(); + } + record() { + if (this.sourceTexture === undefined) { + throw new Error("FrameGraphBloomTask: sourceTexture is required"); + } + const sourceTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.sourceTexture); + const textureCreationOptions = { + size: { + width: Math.floor(sourceTextureDescription.size.width * this.bloom.scale) || 1, + height: Math.floor(sourceTextureDescription.size.height * this.bloom.scale) || 1, + }, + options: { + createMipMaps: false, + types: [this._defaultPipelineTextureType], + formats: [5], + samples: 1, + useSRGBBuffers: [false], + labels: [""], + }, + sizeIsPercentage: false, + }; + const downscaleTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._downscale.name, textureCreationOptions); + this._downscale.sourceTexture = this.sourceTexture; + this._downscale.sourceSamplingMode = 2; + this._downscale.targetTexture = downscaleTextureHandle; + this._downscale.record(true); + const blurXTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurX.name, textureCreationOptions); + this._blurX.sourceTexture = downscaleTextureHandle; + this._blurX.sourceSamplingMode = 2; + this._blurX.targetTexture = blurXTextureHandle; + this._blurX.record(true); + const blurYTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurY.name, textureCreationOptions); + this._blurY.sourceTexture = blurXTextureHandle; + this._blurY.sourceSamplingMode = 2; + this._blurY.targetTexture = blurYTextureHandle; + this._blurY.record(true); + const sourceTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture); + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture, this._merge.name, sourceTextureCreationOptions); + this._merge.sourceTexture = this.sourceTexture; + this._merge.sourceSamplingMode = this.sourceSamplingMode; + this._merge.blurTexture = blurYTextureHandle; + this._merge.targetTexture = this.outputTexture; + this._merge.record(true); + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.addDependencies(this.sourceTexture); + passDisabled.setRenderTarget(this.outputTexture); + passDisabled.setExecuteFunc((context) => { + context.copyTexture(this.sourceTexture); + }); + } + dispose() { + this._downscale.dispose(); + this._blurX.dispose(); + this._blurY.dispose(); + this._merge.dispose(); + super.dispose(); + } +} + +/** + * Block that implements the bloom post process + */ +class NodeRenderGraphBloomPostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphBloomPostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param hdr If high dynamic range textures should be used (default: false) + * @param bloomScale The scale of the bloom effect (default: 0.5) + */ + constructor(name, frameGraph, scene, hdr = false, bloomScale = 0.5) { + super(name, frameGraph, scene); + this._additionalConstructionParameters = [hdr, bloomScale]; + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphBloomTask(this.name, frameGraph, 0.75, 64, 0.2, hdr, bloomScale); + } + _createTask(bloomScale, hdr) { + const sourceSamplingMode = this._frameGraphTask.sourceSamplingMode; + const threshold = this._frameGraphTask.bloom.threshold; + const weight = this._frameGraphTask.bloom.weight; + const kernel = this._frameGraphTask.bloom.kernel; + this._frameGraphTask.dispose(); + this._frameGraphTask = new FrameGraphBloomTask(this.name, this._frameGraph, weight, kernel, threshold, hdr, bloomScale); + this._frameGraphTask.sourceSamplingMode = sourceSamplingMode; + this._additionalConstructionParameters = [hdr, bloomScale]; + } + /** The quality of the blur effect */ + get bloomScale() { + return this._frameGraphTask.bloom.scale; + } + set bloomScale(value) { + this._createTask(value, this._frameGraphTask.hdr); + } + /** If high dynamic range textures should be used */ + get hdr() { + return this._frameGraphTask.hdr; + } + set hdr(value) { + this._createTask(this._frameGraphTask.bloom.scale, value); + } + /** The luminance threshold to find bright areas of the image to bloom. */ + get threshold() { + return this._frameGraphTask.bloom.threshold; + } + set threshold(value) { + this._frameGraphTask.bloom.threshold = value; + } + /** The strength of the bloom. */ + get weight() { + return this._frameGraphTask.bloom.weight; + } + set weight(value) { + this._frameGraphTask.bloom.weight = value; + } + /** Specifies the size of the bloom blur kernel, relative to the final output size */ + get kernel() { + return this._frameGraphTask.bloom.kernel; + } + set kernel(value) { + this._frameGraphTask.bloom.kernel = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphBloomPostProcessBlock"; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.threshold = ${this.threshold};`); + codes.push(`${this._codeVariableName}.weight = ${this.weight};`); + codes.push(`${this._codeVariableName}.kernel = ${this.kernel};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.threshold = this.threshold; + serializationObject.weight = this.weight; + serializationObject.kernel = this.kernel; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.threshold = serializationObject.threshold; + this.weight = serializationObject.weight; + this.kernel = serializationObject.kernel; + } +} +__decorate([ + editableInPropertyPage("Bloom scale", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphBloomPostProcessBlock.prototype, "bloomScale", null); +__decorate([ + editableInPropertyPage("HDR", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphBloomPostProcessBlock.prototype, "hdr", null); +__decorate([ + editableInPropertyPage("Threshold", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0, max: 2 }) +], NodeRenderGraphBloomPostProcessBlock.prototype, "threshold", null); +__decorate([ + editableInPropertyPage("Weight", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0, max: 3 }) +], NodeRenderGraphBloomPostProcessBlock.prototype, "weight", null); +__decorate([ + editableInPropertyPage("Kernel", 2 /* PropertyTypeForEdition.Int */, "PROPERTIES", { min: 1, max: 128 }) +], NodeRenderGraphBloomPostProcessBlock.prototype, "kernel", null); +RegisterClass("BABYLON.NodeRenderGraphBloomPostProcessBlock", NodeRenderGraphBloomPostProcessBlock); + +/** + * Block that implements the blur post process + */ +class NodeRenderGraphBlurPostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphBlurPostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphBlurTask(this.name, frameGraph, new ThinBlurPostProcess(name, scene.getEngine(), new Vector2(1, 0), 32)); + } + /** The direction in which to blur the image */ + get direction() { + return this._frameGraphTask.postProcess.direction; + } + set direction(value) { + this._frameGraphTask.postProcess.direction = value; + } + /** Length in pixels of the blur sample region */ + get kernel() { + return this._frameGraphTask.postProcess.kernel; + } + set kernel(value) { + this._frameGraphTask.postProcess.kernel = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphBlurPostProcessBlock"; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.direction = new BABYLON.Vector2(${this.direction.x}, ${this.direction.y});`); + codes.push(`${this._codeVariableName}.kernel = ${this.kernel};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.direction = this.direction.asArray(); + serializationObject.kernel = this.kernel; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.direction.fromArray(serializationObject.direction); + this.kernel = serializationObject.kernel; + } +} +__decorate([ + editableInPropertyPage("Direction", 3 /* PropertyTypeForEdition.Vector2 */, "PROPERTIES") +], NodeRenderGraphBlurPostProcessBlock.prototype, "direction", null); +__decorate([ + editableInPropertyPage("Kernel", 2 /* PropertyTypeForEdition.Int */, "PROPERTIES", { min: 1, max: 256 }) +], NodeRenderGraphBlurPostProcessBlock.prototype, "kernel", null); +RegisterClass("BABYLON.NodeRenderGraphBlurPostProcessBlock", NodeRenderGraphBlurPostProcessBlock); + +/** + * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen + */ +class ThinChromaticAberrationPostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => chromaticAberration_fragment)); + } + else { + list.push(Promise.resolve().then(() => chromaticAberration_fragment$1)); + } + } + /** + * Constructs a new chromatic aberration post process + * @param name Name of the effect + * @param engine Engine to use to render the effect. If not provided, the last created engine will be used + * @param options Options to configure the effect + */ + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinChromaticAberrationPostProcess.FragmentUrl, + uniforms: ThinChromaticAberrationPostProcess.Uniforms, + }); + /** + * The amount of separation of rgb channels (default: 30) + */ + this.aberrationAmount = 30; + /** + * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0) + */ + this.radialIntensity = 0; + /** + * The normalized direction in which the rgb channels should be separated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707)) + */ + this.direction = new Vector2(0.707, 0.707); + /** + * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corner] (default: Vector2(0.5 ,0.5)) + */ + this.centerPosition = new Vector2(0.5, 0.5); + } + bind() { + super.bind(); + const effect = this._drawWrapper.effect; + effect.setFloat("chromatic_aberration", this.aberrationAmount); + effect.setFloat("screen_width", this.screenWidth); + effect.setFloat("screen_height", this.screenHeight); + effect.setFloat("radialIntensity", this.radialIntensity); + effect.setFloat2("direction", this.direction.x, this.direction.y); + effect.setFloat2("centerPosition", this.centerPosition.x, this.centerPosition.y); + } +} +/** + * The fragment shader url + */ +ThinChromaticAberrationPostProcess.FragmentUrl = "chromaticAberration"; +/** + * The list of uniforms used by the effect + */ +ThinChromaticAberrationPostProcess.Uniforms = ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"]; + +/** + * Task which applies a chromatic aberration post process. + */ +class FrameGraphChromaticAberrationTask extends FrameGraphPostProcessTask { + /** + * Constructs a new chromatic aberration task. + * @param name The name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param thinPostProcess The thin post process to use for the chromatic aberration effect. If not provided, a new one will be created. + */ + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinChromaticAberrationPostProcess(name, frameGraph.engine)); + } + record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) { + const pass = super.record(skipCreationOfDisabledPasses, additionalExecute, additionalBindings); + this.postProcess.screenWidth = this._sourceWidth; + this.postProcess.screenHeight = this._sourceHeight; + return pass; + } +} + +/** + * Block that implements the chromatic aberration post process + */ +class NodeRenderGraphChromaticAberrationPostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new chromatic aberration post process block + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphChromaticAberrationTask(this.name, frameGraph, new ThinChromaticAberrationPostProcess(name, scene.getEngine())); + } + /** The amount of separation of rgb channels */ + get aberrationAmount() { + return this._frameGraphTask.postProcess.aberrationAmount; + } + set aberrationAmount(value) { + this._frameGraphTask.postProcess.aberrationAmount = value; + } + /** The amount the effect will increase for pixels closer to the edge of the screen */ + get radialIntensity() { + return this._frameGraphTask.postProcess.radialIntensity; + } + set radialIntensity(value) { + this._frameGraphTask.postProcess.radialIntensity = value; + } + /** The normalized direction in which the rgb channels should be separated. If set to 0,0 radial direction will be used. */ + get direction() { + return this._frameGraphTask.postProcess.direction; + } + set direction(value) { + this._frameGraphTask.postProcess.direction = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphChromaticAberrationPostProcessBlock"; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.aberrationAmount = ${this.aberrationAmount};`); + codes.push(`${this._codeVariableName}.radialIntensity = ${this.radialIntensity};`); + codes.push(`${this._codeVariableName}.direction = new BABYLON.Vector2(${this.direction.x}, ${this.direction.y});`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.aberrationAmount = this.aberrationAmount; + serializationObject.radialIntensity = this.radialIntensity; + serializationObject.direction = this.direction.asArray(); + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.aberrationAmount = serializationObject.aberrationAmount; + this.radialIntensity = serializationObject.radialIntensity; + this.direction = Vector2.FromArray(serializationObject.direction); + } +} +__decorate([ + editableInPropertyPage("Amount", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: -1e3, max: 1000 }) +], NodeRenderGraphChromaticAberrationPostProcessBlock.prototype, "aberrationAmount", null); +__decorate([ + editableInPropertyPage("Radial intensity", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0.1, max: 5 }) +], NodeRenderGraphChromaticAberrationPostProcessBlock.prototype, "radialIntensity", null); +__decorate([ + editableInPropertyPage("Direction", 3 /* PropertyTypeForEdition.Vector2 */, "PROPERTIES") +], NodeRenderGraphChromaticAberrationPostProcessBlock.prototype, "direction", null); +RegisterClass("BABYLON.NodeRenderGraphChromaticAberrationPostProcessBlock", NodeRenderGraphChromaticAberrationPostProcessBlock); + +/** + * Post process used to calculate the circle of confusion (used for depth of field, for example) + */ +class ThinCircleOfConfusionPostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => circleOfConfusion_fragment)); + } + else { + list.push(Promise.resolve().then(() => circleOfConfusion_fragment$1)); + } + } + /** + * Constructs a new circle of confusion post process + * @param name Name of the effect + * @param engine Engine to use to render the effect. If not provided, the last created engine will be used + * @param options Options to configure the effect + */ + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinCircleOfConfusionPostProcess.FragmentUrl, + uniforms: ThinCircleOfConfusionPostProcess.Uniforms, + samplers: ThinCircleOfConfusionPostProcess.Samplers, + defines: options?.depthNotNormalized ? ThinCircleOfConfusionPostProcess.DefinesDepthNotNormalized : undefined, + }); + /** + * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diameter of the resulting aperture can be computed by lensSize/fStop. + */ + this.lensSize = 50; + /** + * F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop. (default: 1.4) + */ + this.fStop = 1.4; + /** + * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000) + */ + this.focusDistance = 2000; + /** + * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50) + */ + this.focalLength = 50; + } + bind() { + super.bind(); + const options = this.options; + const effect = this._drawWrapper.effect; + if (!options.depthNotNormalized) { + effect.setFloat2("cameraMinMaxZ", this.camera.minZ, this.camera.maxZ - this.camera.minZ); + } + // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html + const aperture = this.lensSize / this.fStop; + const cocPrecalculation = (aperture * this.focalLength) / (this.focusDistance - this.focalLength); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader] + effect.setFloat("focusDistance", this.focusDistance); + effect.setFloat("cocPrecalculation", cocPrecalculation); + } +} +/** + * The fragment shader url + */ +ThinCircleOfConfusionPostProcess.FragmentUrl = "circleOfConfusion"; +/** + * The list of uniforms used by the effect + */ +ThinCircleOfConfusionPostProcess.Uniforms = ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"]; +/** + * The list of samplers used by the effect + */ +ThinCircleOfConfusionPostProcess.Samplers = ["depthSampler"]; +/** + * Defines if the depth is normalized or not + */ +ThinCircleOfConfusionPostProcess.DefinesDepthNotNormalized = "#define COC_DEPTH_NOT_NORMALIZED"; + +/** + * Task which applies a circle of confusion post process. + */ +class FrameGraphCircleOfConfusionTask extends FrameGraphPostProcessTask { + /** + * Constructs a new circle of confusion task. + * @param name The name of the task. + * @param frameGraph The frame graph this task belongs to. + * @param thinPostProcess The thin post process to use for the task. If not provided, a new one will be created. + */ + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinCircleOfConfusionPostProcess(name, frameGraph.engine)); + /** + * The sampling mode to use for the depth texture. + */ + this.depthSamplingMode = 2; + this.onTexturesAllocatedObservable.add((context) => { + context.setTextureSamplingMode(this.depthTexture, this.depthSamplingMode); + }); + } + record(skipCreationOfDisabledPasses = false) { + if (this.sourceTexture === undefined || this.depthTexture === undefined || this.camera === undefined) { + throw new Error(`FrameGraphCircleOfConfusionTask "${this.name}": sourceTexture, depthTexture and camera are required`); + } + const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => { + this.postProcess.camera = this.camera; + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "depthSampler", this.depthTexture); + }); + pass.addDependencies(this.depthTexture); + return pass; + } +} + +/** + * Block that implements the circle of confusion post process + */ +class NodeRenderGraphCircleOfConfusionPostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphCircleOfConfusionPostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("geomViewDepth", NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth); + this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera); + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphCircleOfConfusionTask(this.name, frameGraph, new ThinCircleOfConfusionPostProcess(name, scene.getEngine(), { depthNotNormalized: true })); + } + /** Sampling mode used to sample from the depth texture */ + get depthSamplingMode() { + return this._frameGraphTask.depthSamplingMode; + } + set depthSamplingMode(value) { + this._frameGraphTask.depthSamplingMode = value; + } + /** Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. The diameter of the resulting aperture can be computed by lensSize/fStop. */ + get lensSize() { + return this._frameGraphTask.postProcess.lensSize; + } + set lensSize(value) { + this._frameGraphTask.postProcess.lensSize = value; + } + /** F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop */ + get fStop() { + return this._frameGraphTask.postProcess.fStop; + } + set fStop(value) { + this._frameGraphTask.postProcess.fStop = value; + } + /** Distance away from the camera to focus on in scene units/1000 (eg. millimeter) */ + get focusDistance() { + return this._frameGraphTask.postProcess.focusDistance; + } + set focusDistance(value) { + this._frameGraphTask.postProcess.focusDistance = value; + } + /** Focal length of the effect's camera in scene units/1000 (eg. millimeter) */ + get focalLength() { + return this._frameGraphTask.postProcess.focalLength; + } + set focalLength(value) { + this._frameGraphTask.postProcess.focalLength = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphCircleOfConfusionPostProcessBlock"; + } + /** + * Gets the geometry view depth input component + */ + get geomViewDepth() { + return this._inputs[2]; + } + /** + * Gets the camera input component + */ + get camera() { + return this._inputs[3]; + } + _buildBlock(state) { + super._buildBlock(state); + this._frameGraphTask.depthTexture = this.geomViewDepth.connectedPoint?.value; + this._frameGraphTask.camera = this.camera.connectedPoint?.value; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.lensSize = ${this.lensSize};`); + codes.push(`${this._codeVariableName}.fStop = ${this.fStop};`); + codes.push(`${this._codeVariableName}.focusDistance = ${this.focusDistance};`); + codes.push(`${this._codeVariableName}.focalLength = ${this.focalLength};`); + codes.push(`${this._codeVariableName}.depthSamplingMode = ${this.depthSamplingMode};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.lensSize = this.lensSize; + serializationObject.fStop = this.fStop; + serializationObject.focusDistance = this.focusDistance; + serializationObject.focalLength = this.focalLength; + serializationObject.depthSamplingMode = this.depthSamplingMode; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.lensSize = serializationObject.lensSize; + this.fStop = serializationObject.fStop; + this.focusDistance = serializationObject.focusDistance; + this.focalLength = serializationObject.focalLength; + this.depthSamplingMode = serializationObject.depthSamplingMode; + } +} +__decorate([ + editableInPropertyPage("Depth sampling mode", 6 /* PropertyTypeForEdition.SamplingMode */, "PROPERTIES") +], NodeRenderGraphCircleOfConfusionPostProcessBlock.prototype, "depthSamplingMode", null); +__decorate([ + editableInPropertyPage("Lens size", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphCircleOfConfusionPostProcessBlock.prototype, "lensSize", null); +__decorate([ + editableInPropertyPage("F-Stop", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphCircleOfConfusionPostProcessBlock.prototype, "fStop", null); +__decorate([ + editableInPropertyPage("Focus distance", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphCircleOfConfusionPostProcessBlock.prototype, "focusDistance", null); +__decorate([ + editableInPropertyPage("Focal length", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphCircleOfConfusionPostProcessBlock.prototype, "focalLength", null); +RegisterClass("BABYLON.NodeRenderGraphCircleOfConfusionPostProcessBlock", NodeRenderGraphCircleOfConfusionPostProcessBlock); + +/** + * @internal + */ +class ThinDepthOfFieldMergePostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => depthOfFieldMerge_fragment)); + } + else { + list.push(Promise.resolve().then(() => depthOfFieldMerge_fragment$1)); + } + } + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinDepthOfFieldMergePostProcess.FragmentUrl, + samplers: ThinDepthOfFieldMergePostProcess.Samplers, + }); + } +} +ThinDepthOfFieldMergePostProcess.FragmentUrl = "depthOfFieldMerge"; +ThinDepthOfFieldMergePostProcess.Samplers = ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"]; + +/** + * @internal + */ +class FrameGraphDepthOfFieldMergeTask extends FrameGraphPostProcessTask { + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinDepthOfFieldMergePostProcess(name, frameGraph.engine)); + this.blurSteps = []; + this.onTexturesAllocatedObservable.add((context) => { + context.setTextureSamplingMode(this.blurSteps[this.blurSteps.length - 1], 2); + }); + } + record(skipCreationOfDisabledPasses = false) { + if (this.sourceTexture === undefined || this.circleOfConfusionTexture === undefined || this.blurSteps.length === 0) { + throw new Error(`FrameGraphBloomMergeTask "${this.name}": sourceTexture, circleOfConfusionTexture and blurSteps are required`); + } + this.postProcess.updateEffect("#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n"); + const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => { + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "circleOfConfusionSampler", this.circleOfConfusionTexture); + this.blurSteps.forEach((handle, index) => { + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "blurStep" + (this.blurSteps.length - index - 1), handle); + }); + }); + pass.addDependencies(this.circleOfConfusionTexture); + pass.addDependencies(this.blurSteps); + return pass; + } +} + +/** + * @internal + */ +class ThinDepthOfFieldBlurPostProcess extends ThinBlurPostProcess { + constructor(name, engine = null, direction, kernel, options) { + super(name, engine, direction, kernel, { + ...options, + defines: `#define DOF 1\n`, + }); + } +} + +/** + * @internal + */ +class FrameGraphDepthOfFieldBlurTask extends FrameGraphBlurTask { + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinDepthOfFieldBlurPostProcess(name, frameGraph.engine, new Vector2(1, 0), 10)); + this.circleOfConfusionSamplingMode = 2; + this.onTexturesAllocatedObservable.add((context) => { + context.setTextureSamplingMode(this.circleOfConfusionTexture, this.circleOfConfusionSamplingMode); + }); + } + record(skipCreationOfDisabledPasses = false) { + if (this.sourceTexture === undefined || this.circleOfConfusionTexture === undefined) { + throw new Error(`FrameGraphDepthOfFieldBlurTask "${this.name}": sourceTexture and circleOfConfusionTexture are required`); + } + const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => { + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "circleOfConfusionSampler", this.circleOfConfusionTexture); + }); + pass.addDependencies(this.circleOfConfusionTexture); + return pass; + } +} + +/** + * Specifies the level of blur that should be applied when using the depth of field effect + */ +var ThinDepthOfFieldEffectBlurLevel; +(function (ThinDepthOfFieldEffectBlurLevel) { + /** + * Subtle blur + */ + ThinDepthOfFieldEffectBlurLevel[ThinDepthOfFieldEffectBlurLevel["Low"] = 0] = "Low"; + /** + * Medium blur + */ + ThinDepthOfFieldEffectBlurLevel[ThinDepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium"; + /** + * Large blur + */ + ThinDepthOfFieldEffectBlurLevel[ThinDepthOfFieldEffectBlurLevel["High"] = 2] = "High"; +})(ThinDepthOfFieldEffectBlurLevel || (ThinDepthOfFieldEffectBlurLevel = {})); +class ThinDepthOfFieldEffect { + /** + * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter) + */ + set focalLength(value) { + this._circleOfConfusion.focalLength = value; + } + get focalLength() { + return this._circleOfConfusion.focalLength; + } + /** + * F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop. (default: 1.4) + */ + set fStop(value) { + this._circleOfConfusion.fStop = value; + } + get fStop() { + return this._circleOfConfusion.fStop; + } + /** + * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000) + */ + set focusDistance(value) { + this._circleOfConfusion.focusDistance = value; + } + get focusDistance() { + return this._circleOfConfusion.focusDistance; + } + /** + * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diameter of the resulting aperture can be computed by lensSize/fStop. + */ + set lensSize(value) { + this._circleOfConfusion.lensSize = value; + } + get lensSize() { + return this._circleOfConfusion.lensSize; + } + /** + * Creates a new instance of @see ThinDepthOfFieldEffect + * @param name The name of the depth of field render effect + * @param engine The engine which the render effect will be applied. (default: current engine) + * @param blurLevel The quality of the effect. (default: DepthOfFieldEffectBlurLevel.Low) + * @param depthNotNormalized If the (view) depth used in circle of confusion post-process is normalized (0.0 to 1.0 from near to far) or not (0 to camera max distance) (default: false) + * @param blockCompilation If shaders should not be compiled when the effect is created (default: false) + */ + constructor(name, engine, blurLevel = 0 /* ThinDepthOfFieldEffectBlurLevel.Low */, depthNotNormalized = false, blockCompilation = false) { + /** @internal */ + this._depthOfFieldBlurX = []; + /** @internal */ + this._depthOfFieldBlurY = []; + this._circleOfConfusion = new ThinCircleOfConfusionPostProcess(name, engine, { depthNotNormalized, blockCompilation }); + this.blurLevel = blurLevel; + let blurCount = 1; + let kernelSize = 15; + switch (blurLevel) { + case 2 /* ThinDepthOfFieldEffectBlurLevel.High */: { + blurCount = 3; + kernelSize = 51; + break; + } + case 1 /* ThinDepthOfFieldEffectBlurLevel.Medium */: { + blurCount = 2; + kernelSize = 31; + break; + } + default: { + kernelSize = 15; + blurCount = 1; + break; + } + } + const adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1); + let ratio = 1.0; + for (let i = 0; i < blurCount; i++) { + this._depthOfFieldBlurY.push([new ThinBlurPostProcess(name, engine, new Vector2(0, 1), adjustedKernelSize, { blockCompilation }), ratio]); + ratio = 0.75 / Math.pow(2, i); + this._depthOfFieldBlurX.push([new ThinBlurPostProcess(name, engine, new Vector2(1, 0), adjustedKernelSize, { blockCompilation }), ratio]); + } + this._dofMerge = new ThinDepthOfFieldMergePostProcess(name, engine, { blockCompilation }); + } + /** + * Checks if the effect is ready to be used + * @returns if the effect is ready + */ + isReady() { + let isReady = this._circleOfConfusion.isReady() && this._dofMerge.isReady(); + for (let i = 0; i < this._depthOfFieldBlurX.length; i++) { + isReady = isReady && this._depthOfFieldBlurX[i][0].isReady() && this._depthOfFieldBlurY[i][0].isReady(); + } + return isReady; + } +} + +/** + * Task which applies a depth of field effect. + */ +class FrameGraphDepthOfFieldTask extends FrameGraphTask { + /** + * The name of the task. + */ + get name() { + return this._name; + } + set name(name) { + this._name = name; + if (this._circleOfConfusion) { + this._circleOfConfusion.name = `${name} Circle of Confusion`; + } + if (this._blurX) { + for (let i = 0; i < this._blurX.length; i++) { + this._blurX[i].name = `${name} Blur X${i}`; + this._blurY[i].name = `${name} Blur Y${i}`; + } + } + if (this._merge) { + this._merge.name = `${name} Merge`; + } + } + /** + * Constructs a depth of field task. + * @param name The name of the task. + * @param frameGraph The frame graph this task belongs to. + * @param blurLevel The blur level of the depth of field effect (default: ThinDepthOfFieldEffectBlurLevel.Low). + * @param hdr Whether the depth of field effect is HDR. + */ + constructor(name, frameGraph, blurLevel = 0 /* ThinDepthOfFieldEffectBlurLevel.Low */, hdr = false) { + super(name, frameGraph); + /** + * The sampling mode to use for the source texture. + */ + this.sourceSamplingMode = 2; + /** + * The sampling mode to use for the depth texture. + */ + this.depthSamplingMode = 2; + this._blurX = []; + this._blurY = []; + this._engine = frameGraph.engine; + this.hdr = hdr; + this._defaultPipelineTextureType = 0; + if (hdr) { + const caps = frameGraph.engine.getCaps(); + if (caps.textureHalfFloatRender) { + this._defaultPipelineTextureType = 2; + } + else if (caps.textureFloatRender) { + this._defaultPipelineTextureType = 1; + } + } + this.depthOfField = new ThinDepthOfFieldEffect(name, frameGraph.engine, blurLevel, true); + this._circleOfConfusion = new FrameGraphCircleOfConfusionTask(`${name} Circle of Confusion`, this._frameGraph, this.depthOfField._circleOfConfusion); + const blurCount = this.depthOfField._depthOfFieldBlurX.length; + for (let i = 0; i < blurCount; i++) { + this._blurX.push(new FrameGraphDepthOfFieldBlurTask(`${name} Blur X${i}`, this._frameGraph, this.depthOfField._depthOfFieldBlurX[i][0])); + this._blurY.push(new FrameGraphDepthOfFieldBlurTask(`${name} Blur Y${i}`, this._frameGraph, this.depthOfField._depthOfFieldBlurY[i][0])); + } + this._merge = new FrameGraphDepthOfFieldMergeTask(`${name} Merge`, this._frameGraph, this.depthOfField._dofMerge); + this.onTexturesAllocatedObservable.add((context) => { + this._circleOfConfusion.onTexturesAllocatedObservable.notifyObservers(context); + for (let i = 0; i < blurCount; i++) { + this._blurX[i].onTexturesAllocatedObservable.notifyObservers(context); + this._blurY[i].onTexturesAllocatedObservable.notifyObservers(context); + } + this._merge.onTexturesAllocatedObservable.notifyObservers(context); + }); + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + } + isReady() { + return this.depthOfField.isReady(); + } + record() { + if (this.sourceTexture === undefined || this.depthTexture === undefined || this.camera === undefined) { + throw new Error("FrameGraphDepthOfFieldTask: sourceTexture, depthTexture and camera are required"); + } + const sourceTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.sourceTexture); + const textureSize = { + width: sourceTextureDescription.size.width, + height: sourceTextureDescription.size.height, + }; + const circleOfConfusionTextureFormat = this._engine.isWebGPU || this._engine.version > 1 ? 6 : 5; + const textureCreationOptions = { + size: textureSize, + options: { + createMipMaps: false, + types: [this._defaultPipelineTextureType], + formats: [circleOfConfusionTextureFormat], + samples: 1, + useSRGBBuffers: [false], + labels: [""], + }, + sizeIsPercentage: false, + }; + const circleOfConfusionTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._circleOfConfusion.name, textureCreationOptions); + this._circleOfConfusion.sourceTexture = this.sourceTexture; // texture not used by the CoC shader + this._circleOfConfusion.depthTexture = this.depthTexture; + this._circleOfConfusion.depthSamplingMode = this.depthSamplingMode; + this._circleOfConfusion.camera = this.camera; + this._circleOfConfusion.targetTexture = circleOfConfusionTextureHandle; + this._circleOfConfusion.record(true); + textureCreationOptions.options.formats = [5]; + const blurSteps = []; + for (let i = 0; i < this._blurX.length; i++) { + const ratio = this.depthOfField._depthOfFieldBlurX[i][1]; + textureSize.width = Math.floor(sourceTextureDescription.size.width * ratio) || 1; + textureSize.height = Math.floor(sourceTextureDescription.size.height * ratio) || 1; + textureCreationOptions.options.labels[0] = "step " + (i + 1); + const blurYTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurY[i].name, textureCreationOptions); + this._blurY[i].sourceTexture = i === 0 ? this.sourceTexture : this._blurX[i - 1].outputTexture; + this._blurY[i].sourceSamplingMode = 2; + this._blurY[i].circleOfConfusionTexture = circleOfConfusionTextureHandle; + this._blurY[i].targetTexture = blurYTextureHandle; + this._blurY[i].record(true); + const blurXTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurX[i].name, textureCreationOptions); + this._blurX[i].sourceTexture = this._blurY[i].outputTexture; + this._blurX[i].sourceSamplingMode = 2; + this._blurX[i].circleOfConfusionTexture = circleOfConfusionTextureHandle; + this._blurX[i].targetTexture = blurXTextureHandle; + this._blurX[i].record(true); + blurSteps.push(blurXTextureHandle); + } + const sourceTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture); + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture, this._merge.name, sourceTextureCreationOptions); + this._merge.sourceTexture = this.sourceTexture; + this._merge.sourceSamplingMode = this.sourceSamplingMode; + this._merge.circleOfConfusionTexture = circleOfConfusionTextureHandle; + this._merge.blurSteps = blurSteps; + this._merge.targetTexture = this.outputTexture; + this._merge.record(true); + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.addDependencies(this.sourceTexture); + passDisabled.setRenderTarget(this.outputTexture); + passDisabled.setExecuteFunc((context) => { + context.copyTexture(this.sourceTexture); + }); + } + dispose() { + this._circleOfConfusion.dispose(); + for (let i = 0; i < this._blurX.length; i++) { + this._blurX[i].dispose(); + this._blurY[i].dispose(); + } + this._merge.dispose(); + super.dispose(); + } +} + +/** + * Block that implements the depth of field post process + */ +class NodeRenderGraphDepthOfFieldPostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphDepthOfFieldPostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param blurLevel The quality of the depth of field effect (default: ThinDepthOfFieldEffectBlurLevel.Low) + * @param hdr If high dynamic range textures should be used (default: false) + */ + constructor(name, frameGraph, scene, blurLevel = 0 /* ThinDepthOfFieldEffectBlurLevel.Low */, hdr = false) { + super(name, frameGraph, scene); + this._additionalConstructionParameters = [blurLevel, hdr]; + this.registerInput("geomViewDepth", NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth); + this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera); + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphDepthOfFieldTask(this.name, frameGraph, blurLevel, hdr); + } + _createTask(blurLevel, hdr) { + const sourceSamplingMode = this._frameGraphTask.sourceSamplingMode; + const depthSamplingMode = this._frameGraphTask.depthSamplingMode; + const focalLength = this._frameGraphTask.depthOfField.focalLength; + const fStop = this._frameGraphTask.depthOfField.fStop; + const focusDistance = this._frameGraphTask.depthOfField.focusDistance; + const lensSize = this._frameGraphTask.depthOfField.lensSize; + this._frameGraphTask.dispose(); + this._frameGraphTask = new FrameGraphDepthOfFieldTask(this.name, this._frameGraph, blurLevel, hdr); + this._frameGraphTask.sourceSamplingMode = sourceSamplingMode; + this._frameGraphTask.depthSamplingMode = depthSamplingMode; + this._frameGraphTask.depthOfField.focalLength = focalLength; + this._frameGraphTask.depthOfField.fStop = fStop; + this._frameGraphTask.depthOfField.focusDistance = focusDistance; + this._frameGraphTask.depthOfField.lensSize = lensSize; + this._additionalConstructionParameters = [blurLevel, hdr]; + } + /** The quality of the blur effect */ + get blurLevel() { + return this._frameGraphTask.depthOfField.blurLevel; + } + set blurLevel(value) { + this._createTask(value, this._frameGraphTask.hdr); + } + /** If high dynamic range textures should be used */ + get hdr() { + return this._frameGraphTask.hdr; + } + set hdr(value) { + this._createTask(this._frameGraphTask.depthOfField.blurLevel, value); + } + /** Sampling mode used to sample from the depth texture */ + get depthSamplingMode() { + return this._frameGraphTask.depthSamplingMode; + } + set depthSamplingMode(value) { + this._frameGraphTask.depthSamplingMode = value; + } + /** The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter). */ + get focalLength() { + return this._frameGraphTask.depthOfField.focalLength; + } + set focalLength(value) { + this._frameGraphTask.depthOfField.focalLength = value; + } + /** F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop. */ + get fStop() { + return this._frameGraphTask.depthOfField.fStop; + } + set fStop(value) { + this._frameGraphTask.depthOfField.fStop = value; + } + /** Distance away from the camera to focus on in scene units/1000 (eg. millimeter). */ + get focusDistance() { + return this._frameGraphTask.depthOfField.focusDistance; + } + set focusDistance(value) { + this._frameGraphTask.depthOfField.focusDistance = value; + } + /** Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. The diameter of the resulting aperture can be computed by lensSize/fStop. */ + get lensSize() { + return this._frameGraphTask.depthOfField.lensSize; + } + set lensSize(value) { + this._frameGraphTask.depthOfField.lensSize = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphDepthOfFieldPostProcessBlock"; + } + /** + * Gets the geometry view depth input component + */ + get geomViewDepth() { + return this._inputs[2]; + } + /** + * Gets the camera input component + */ + get camera() { + return this._inputs[3]; + } + _buildBlock(state) { + super._buildBlock(state); + this.output.value = this._frameGraphTask.outputTexture; + this._frameGraphTask.depthTexture = this.geomViewDepth.connectedPoint?.value; + this._frameGraphTask.camera = this.camera.connectedPoint?.value; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.lensSize = ${this.lensSize};`); + codes.push(`${this._codeVariableName}.fStop = ${this.fStop};`); + codes.push(`${this._codeVariableName}.focusDistance = ${this.focusDistance};`); + codes.push(`${this._codeVariableName}.focalLength = ${this.focalLength};`); + codes.push(`${this._codeVariableName}.depthSamplingMode = ${this.depthSamplingMode};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.lensSize = this.lensSize; + serializationObject.fStop = this.fStop; + serializationObject.focusDistance = this.focusDistance; + serializationObject.focalLength = this.focalLength; + serializationObject.depthSamplingMode = this.depthSamplingMode; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.lensSize = serializationObject.lensSize; + this.fStop = serializationObject.fStop; + this.focusDistance = serializationObject.focusDistance; + this.focalLength = serializationObject.focalLength; + this.depthSamplingMode = serializationObject.depthSamplingMode; + } +} +__decorate([ + editableInPropertyPage("Blur level", 4 /* PropertyTypeForEdition.List */, "PROPERTIES", { + options: [ + { label: "Low", value: 0 /* ThinDepthOfFieldEffectBlurLevel.Low */ }, + { label: "Medium", value: 1 /* ThinDepthOfFieldEffectBlurLevel.Medium */ }, + { label: "High", value: 2 /* ThinDepthOfFieldEffectBlurLevel.High */ }, + ], + }) +], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "blurLevel", null); +__decorate([ + editableInPropertyPage("HDR", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "hdr", null); +__decorate([ + editableInPropertyPage("Depth sampling mode", 6 /* PropertyTypeForEdition.SamplingMode */, "PROPERTIES") +], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "depthSamplingMode", null); +__decorate([ + editableInPropertyPage("Focal length", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "focalLength", null); +__decorate([ + editableInPropertyPage("F-Stop", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "fStop", null); +__decorate([ + editableInPropertyPage("Focus distance", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "focusDistance", null); +__decorate([ + editableInPropertyPage("Lens size", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES") +], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "lensSize", null); +RegisterClass("BABYLON.NodeRenderGraphDepthOfFieldPostProcessBlock", NodeRenderGraphDepthOfFieldPostProcessBlock); + +/** + * Block that implements the extract highlights post process + */ +class NodeRenderGraphExtractHighlightsPostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new ExtractHighlightsPostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphExtractHighlightsTask(this.name, frameGraph, new ThinExtractHighlightsPostProcess(name, scene.getEngine())); + } + /** The luminance threshold, pixels below this value will be set to black. */ + get threshold() { + return this._frameGraphTask.postProcess.threshold; + } + set threshold(value) { + this._frameGraphTask.postProcess.threshold = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphExtractHighlightsPostProcessBlock"; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.threshold = ${this.threshold};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.threshold = this.threshold; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.threshold = serializationObject.threshold; + } +} +__decorate([ + editableInPropertyPage("Threshold", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0, max: 1 }) +], NodeRenderGraphExtractHighlightsPostProcessBlock.prototype, "threshold", null); +RegisterClass("BABYLON.NodeRenderGraphExtractHighlightsPostProcessBlock", NodeRenderGraphExtractHighlightsPostProcessBlock); + +/** + * Task which applies a pass post process. + */ +class FrameGraphPassTask extends FrameGraphPostProcessTask { + /** + * Constructs a new pass task. + * @param name The name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param thinPostProcess The thin post process to use for the pass effect. If not provided, a new one will be created. + */ + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinPassPostProcess(name, frameGraph.engine)); + } +} +/** + * Task which applies a pass cube post process. + */ +class FrameGraphPassCubeTask extends FrameGraphPostProcessTask { + /** + * Constructs a new pass cube task. + * @param name The name of the task. + * @param frameGraph The frame graph this task is associated with. + * @param thinPostProcess The thin post process to use for the pass cube effect. If not provided, a new one will be created. + */ + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinPassCubePostProcess(name, frameGraph.engine)); + } +} + +/** + * Block that implements the pass post process + */ +class NodeRenderGraphPassPostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphPassPostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphPassTask(this.name, frameGraph, new ThinPassPostProcess(name, scene.getEngine())); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphPassPostProcessBlock"; + } +} +RegisterClass("BABYLON.NodeRenderGraphPassPostProcessBlock", NodeRenderGraphPassPostProcessBlock); +/** + * Block that implements the pass cube post process + */ +class NodeRenderGraphPassCubePostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphPassCubePostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphPassCubeTask(this.name, frameGraph, new ThinPassCubePostProcess(name, scene.getEngine())); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphPassCubePostProcessBlock"; + } +} +RegisterClass("BABYLON.NodeRenderGraphPassCubePostProcessBlock", NodeRenderGraphPassCubePostProcessBlock); + +const trs = Matrix.Compose(new Vector3(0.5, 0.5, 0.5), Quaternion.Identity(), new Vector3(0.5, 0.5, 0.5)); +const trsWebGPU = Matrix.Compose(new Vector3(0.5, 0.5, 1), Quaternion.Identity(), new Vector3(0.5, 0.5, 0)); +/** + * @internal + */ +class ThinSSRPostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => screenSpaceReflection2_fragment)); + } + else { + list.push(Promise.resolve().then(() => screenSpaceReflection2_fragment$1)); + } + } + get reflectivityThreshold() { + return this._reflectivityThreshold; + } + set reflectivityThreshold(threshold) { + if (threshold === this._reflectivityThreshold) { + return; + } + if ((threshold === 0 && this._reflectivityThreshold !== 0) || (threshold !== 0 && this._reflectivityThreshold === 0)) { + this._reflectivityThreshold = threshold; + this._updateEffectDefines(); + } + else { + this._reflectivityThreshold = threshold; + } + } + get useBlur() { + return this._useBlur; + } + set useBlur(blur) { + if (this._useBlur === blur) { + return; + } + this._useBlur = blur; + this._updateEffectDefines(); + } + get enableSmoothReflections() { + return this._enableSmoothReflections; + } + set enableSmoothReflections(enabled) { + if (enabled === this._enableSmoothReflections) { + return; + } + this._enableSmoothReflections = enabled; + this._updateEffectDefines(); + } + get environmentTexture() { + return this._environmentTexture; + } + set environmentTexture(texture) { + this._environmentTexture = texture; + this._updateEffectDefines(); + } + get environmentTextureIsProbe() { + return this._environmentTextureIsProbe; + } + set environmentTextureIsProbe(isProbe) { + this._environmentTextureIsProbe = isProbe; + this._updateEffectDefines(); + } + get attenuateScreenBorders() { + return this._attenuateScreenBorders; + } + set attenuateScreenBorders(attenuate) { + if (this._attenuateScreenBorders === attenuate) { + return; + } + this._attenuateScreenBorders = attenuate; + this._updateEffectDefines(); + } + get attenuateIntersectionDistance() { + return this._attenuateIntersectionDistance; + } + set attenuateIntersectionDistance(attenuate) { + if (this._attenuateIntersectionDistance === attenuate) { + return; + } + this._attenuateIntersectionDistance = attenuate; + this._updateEffectDefines(); + } + get attenuateIntersectionIterations() { + return this._attenuateIntersectionIterations; + } + set attenuateIntersectionIterations(attenuate) { + if (this._attenuateIntersectionIterations === attenuate) { + return; + } + this._attenuateIntersectionIterations = attenuate; + this._updateEffectDefines(); + } + get attenuateFacingCamera() { + return this._attenuateFacingCamera; + } + set attenuateFacingCamera(attenuate) { + if (this._attenuateFacingCamera === attenuate) { + return; + } + this._attenuateFacingCamera = attenuate; + this._updateEffectDefines(); + } + get attenuateBackfaceReflection() { + return this._attenuateBackfaceReflection; + } + set attenuateBackfaceReflection(attenuate) { + if (this._attenuateBackfaceReflection === attenuate) { + return; + } + this._attenuateBackfaceReflection = attenuate; + this._updateEffectDefines(); + } + get clipToFrustum() { + return this._clipToFrustum; + } + set clipToFrustum(clip) { + if (this._clipToFrustum === clip) { + return; + } + this._clipToFrustum = clip; + this._updateEffectDefines(); + } + get useFresnel() { + return this._useFresnel; + } + set useFresnel(fresnel) { + if (this._useFresnel === fresnel) { + return; + } + this._useFresnel = fresnel; + this._updateEffectDefines(); + } + get enableAutomaticThicknessComputation() { + return this._enableAutomaticThicknessComputation; + } + set enableAutomaticThicknessComputation(automatic) { + if (this._enableAutomaticThicknessComputation === automatic) { + return; + } + this._enableAutomaticThicknessComputation = automatic; + this._updateEffectDefines(); + } + get inputTextureColorIsInGammaSpace() { + return this._inputTextureColorIsInGammaSpace; + } + set inputTextureColorIsInGammaSpace(gammaSpace) { + if (this._inputTextureColorIsInGammaSpace === gammaSpace) { + return; + } + this._inputTextureColorIsInGammaSpace = gammaSpace; + this._updateEffectDefines(); + } + get generateOutputInGammaSpace() { + return this._generateOutputInGammaSpace; + } + set generateOutputInGammaSpace(gammaSpace) { + if (this._generateOutputInGammaSpace === gammaSpace) { + return; + } + this._generateOutputInGammaSpace = gammaSpace; + this._updateEffectDefines(); + } + get debug() { + return this._debug; + } + set debug(value) { + if (this._debug === value) { + return; + } + this._debug = value; + this._updateEffectDefines(); + } + get textureWidth() { + return this._textureWidth; + } + set textureWidth(width) { + if (this._textureWidth === width) { + return; + } + this._textureWidth = width; + } + get textureHeight() { + return this._textureHeight; + } + set textureHeight(height) { + if (this._textureHeight === height) { + return; + } + this._textureHeight = height; + } + get useScreenspaceDepth() { + return this._useScreenspaceDepth; + } + set useScreenspaceDepth(value) { + if (this._useScreenspaceDepth === value) { + return; + } + this._useScreenspaceDepth = value; + this._updateEffectDefines(); + } + get normalsAreInWorldSpace() { + return this._normalsAreInWorldSpace; + } + set normalsAreInWorldSpace(value) { + if (this._normalsAreInWorldSpace === value) { + return; + } + this._normalsAreInWorldSpace = value; + this._updateEffectDefines(); + } + get normalsAreUnsigned() { + return this._normalsAreUnsigned; + } + set normalsAreUnsigned(value) { + if (this._normalsAreUnsigned === value) { + return; + } + this._normalsAreUnsigned = value; + this._updateEffectDefines(); + } + constructor(name, scene, options) { + super({ + ...options, + name, + engine: scene.getEngine() || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinSSRPostProcess.FragmentUrl, + uniforms: ThinSSRPostProcess.Uniforms, + samplers: ThinSSRPostProcess.Samplers, + shaderLanguage: scene.getEngine().isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, + }); + this.isSSRSupported = true; + this.maxDistance = 1000.0; + this.step = 1.0; + this.thickness = 0.5; + this.strength = 1; + this.reflectionSpecularFalloffExponent = 1; + this.maxSteps = 1000.0; + this.roughnessFactor = 0.2; + this.selfCollisionNumSkip = 1; + this._reflectivityThreshold = 0.04; + this._useBlur = false; + this._enableSmoothReflections = false; + this._environmentTextureIsProbe = false; + this._attenuateScreenBorders = true; + this._attenuateIntersectionDistance = true; + this._attenuateIntersectionIterations = true; + this._attenuateFacingCamera = false; + this._attenuateBackfaceReflection = false; + this._clipToFrustum = true; + this._useFresnel = false; + this._enableAutomaticThicknessComputation = false; + this._inputTextureColorIsInGammaSpace = true; + this._generateOutputInGammaSpace = true; + this._debug = false; + this._textureWidth = 0; + this._textureHeight = 0; + this.camera = null; + this._useScreenspaceDepth = false; + this._normalsAreInWorldSpace = false; + this._normalsAreUnsigned = false; + this._scene = scene; + this._updateEffectDefines(); + } + bind() { + super.bind(); + const effect = this._drawWrapper.effect; + const camera = this.camera; + if (!camera) { + return; + } + const viewMatrix = camera.getViewMatrix(); + const projectionMatrix = camera.getProjectionMatrix(); + projectionMatrix.invertToRef(TmpVectors.Matrix[0]); + viewMatrix.invertToRef(TmpVectors.Matrix[1]); + effect.setMatrix("projection", projectionMatrix); + effect.setMatrix("view", viewMatrix); + effect.setMatrix("invView", TmpVectors.Matrix[1]); + effect.setMatrix("invProjectionMatrix", TmpVectors.Matrix[0]); + effect.setFloat("thickness", this.thickness); + effect.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent); + effect.setFloat("strength", this.strength); + effect.setFloat("stepSize", this.step); + effect.setFloat("maxSteps", this.maxSteps); + effect.setFloat("roughnessFactor", this.roughnessFactor); + effect.setFloat("nearPlaneZ", camera.minZ); + effect.setFloat("farPlaneZ", camera.maxZ); + effect.setFloat("maxDistance", this.maxDistance); + effect.setFloat("selfCollisionNumSkip", this.selfCollisionNumSkip); + effect.setFloat("reflectivityThreshold", this._reflectivityThreshold); + Matrix.ScalingToRef(this.textureWidth, this.textureHeight, 1, TmpVectors.Matrix[2]); + projectionMatrix.multiplyToRef(this._scene.getEngine().isWebGPU ? trsWebGPU : trs, TmpVectors.Matrix[3]); + TmpVectors.Matrix[3].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[4]); + effect.setMatrix("projectionPixel", TmpVectors.Matrix[4]); + if (this._environmentTexture) { + effect.setTexture("envCubeSampler", this._environmentTexture); + if (this._environmentTexture.boundingBoxSize) { + effect.setVector3("vReflectionPosition", this._environmentTexture.boundingBoxPosition); + effect.setVector3("vReflectionSize", this._environmentTexture.boundingBoxSize); + } + } + } + _updateEffectDefines() { + const defines = []; + if (this.isSSRSupported) { + defines.push("#define SSR_SUPPORTED"); + } + if (this._enableSmoothReflections) { + defines.push("#define SSRAYTRACE_ENABLE_REFINEMENT"); + } + if (this._scene.useRightHandedSystem) { + defines.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"); + } + if (this._useScreenspaceDepth) { + defines.push("#define SSRAYTRACE_SCREENSPACE_DEPTH"); + } + if (this._environmentTexture) { + defines.push("#define SSR_USE_ENVIRONMENT_CUBE"); + if (this._environmentTexture.boundingBoxSize) { + defines.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"); + } + if (this._environmentTexture.gammaSpace) { + defines.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE"); + } + } + if (this._environmentTextureIsProbe) { + defines.push("#define SSR_INVERTCUBICMAP"); + } + if (this._enableAutomaticThicknessComputation) { + defines.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"); + } + if (this._attenuateScreenBorders) { + defines.push("#define SSR_ATTENUATE_SCREEN_BORDERS"); + } + if (this._attenuateIntersectionDistance) { + defines.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"); + } + if (this._attenuateIntersectionIterations) { + defines.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"); + } + if (this._attenuateFacingCamera) { + defines.push("#define SSR_ATTENUATE_FACING_CAMERA"); + } + if (this._attenuateBackfaceReflection) { + defines.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"); + } + if (this._clipToFrustum) { + defines.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"); + } + if (this.useBlur) { + defines.push("#define SSR_USE_BLUR"); + } + if (this._debug) { + defines.push("#define SSRAYTRACE_DEBUG"); + } + if (this._inputTextureColorIsInGammaSpace) { + defines.push("#define SSR_INPUT_IS_GAMMA_SPACE"); + } + if (this._generateOutputInGammaSpace) { + defines.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"); + } + if (this._useFresnel) { + defines.push("#define SSR_BLEND_WITH_FRESNEL"); + } + if (this._reflectivityThreshold === 0) { + defines.push("#define SSR_DISABLE_REFLECTIVITY_TEST"); + } + if (this._normalsAreInWorldSpace) { + defines.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"); + } + if (this._normalsAreUnsigned) { + defines.push("#define SSR_DECODE_NORMAL"); + } + if (this.camera && this.camera.mode === 1) { + defines.push("#define ORTHOGRAPHIC_CAMERA"); + } + this.updateEffect(defines.join("\n")); + } +} +/** + * The fragment shader url + */ +ThinSSRPostProcess.FragmentUrl = "screenSpaceReflection2"; +/** + * The list of uniforms used by the effect + */ +ThinSSRPostProcess.Uniforms = [ + "projection", + "invProjectionMatrix", + "view", + "invView", + "thickness", + "reflectionSpecularFalloffExponent", + "strength", + "stepSize", + "maxSteps", + "roughnessFactor", + "projectionPixel", + "nearPlaneZ", + "farPlaneZ", + "maxDistance", + "selfCollisionNumSkip", + "vReflectionPosition", + "vReflectionSize", + "backSizeFactor", + "reflectivityThreshold", +]; +ThinSSRPostProcess.Samplers = ["textureSampler", "normalSampler", "reflectivitySampler", "depthSampler", "envCubeSampler", "backDepthSampler"]; + +/** + * @internal + */ +class ThinSSRBlurPostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => screenSpaceReflection2Blur_fragment)); + } + else { + list.push(Promise.resolve().then(() => screenSpaceReflection2Blur_fragment$1)); + } + } + constructor(name, engine = null, direction, blurStrength, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinSSRBlurPostProcess.FragmentUrl, + uniforms: ThinSSRBlurPostProcess.Uniforms, + samplers: ThinSSRBlurPostProcess.Samplers, + }); + this.textureWidth = 0; + this.textureHeight = 0; + this.direction = new Vector2(1, 0); + this.blurStrength = 0.03; + if (direction !== undefined) { + this.direction = direction; + } + if (blurStrength !== undefined) { + this.blurStrength = blurStrength; + } + } + bind() { + super.bind(); + this._drawWrapper.effect.setFloat2("texelOffsetScale", (1 / this.textureWidth) * this.direction.x * this.blurStrength, (1 / this.textureHeight) * this.direction.y * this.blurStrength); + } +} +ThinSSRBlurPostProcess.FragmentUrl = "screenSpaceReflection2Blur"; +ThinSSRBlurPostProcess.Uniforms = ["texelOffsetScale"]; +ThinSSRBlurPostProcess.Samplers = ["textureSampler"]; + +/** + * @internal + */ +class ThinSSRBlurCombinerPostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => screenSpaceReflection2BlurCombiner_fragment)); + } + else { + list.push(Promise.resolve().then(() => screenSpaceReflection2BlurCombiner_fragment$1)); + } + } + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinSSRBlurCombinerPostProcess.FragmentUrl, + uniforms: ThinSSRBlurCombinerPostProcess.Uniforms, + samplers: ThinSSRBlurCombinerPostProcess.Samplers, + }); + this.strength = 1; + this.reflectionSpecularFalloffExponent = 1; + this.camera = null; + this._useFresnel = false; + this._useScreenspaceDepth = false; + this._inputTextureColorIsInGammaSpace = true; + this._generateOutputInGammaSpace = true; + this._debug = false; + this._reflectivityThreshold = 0.04; + this._normalsAreInWorldSpace = false; + this._normalsAreUnsigned = false; + this._updateEffectDefines(); + } + get useFresnel() { + return this._useFresnel; + } + set useFresnel(fresnel) { + if (this._useFresnel === fresnel) { + return; + } + this._useFresnel = fresnel; + this._updateEffectDefines(); + } + get useScreenspaceDepth() { + return this._useScreenspaceDepth; + } + set useScreenspaceDepth(value) { + if (this._useScreenspaceDepth === value) { + return; + } + this._useScreenspaceDepth = value; + this._updateEffectDefines(); + } + get inputTextureColorIsInGammaSpace() { + return this._inputTextureColorIsInGammaSpace; + } + set inputTextureColorIsInGammaSpace(gammaSpace) { + if (this._inputTextureColorIsInGammaSpace === gammaSpace) { + return; + } + this._inputTextureColorIsInGammaSpace = gammaSpace; + this._updateEffectDefines(); + } + get generateOutputInGammaSpace() { + return this._generateOutputInGammaSpace; + } + set generateOutputInGammaSpace(gammaSpace) { + if (this._generateOutputInGammaSpace === gammaSpace) { + return; + } + this._generateOutputInGammaSpace = gammaSpace; + this._updateEffectDefines(); + } + get debug() { + return this._debug; + } + set debug(value) { + if (this._debug === value) { + return; + } + this._debug = value; + this._updateEffectDefines(); + } + get reflectivityThreshold() { + return this._reflectivityThreshold; + } + set reflectivityThreshold(threshold) { + if (threshold === this._reflectivityThreshold) { + return; + } + if ((threshold === 0 && this._reflectivityThreshold !== 0) || (threshold !== 0 && this._reflectivityThreshold === 0)) { + this._reflectivityThreshold = threshold; + this._updateEffectDefines(); + } + else { + this._reflectivityThreshold = threshold; + } + } + get normalsAreInWorldSpace() { + return this._normalsAreInWorldSpace; + } + set normalsAreInWorldSpace(value) { + if (this._normalsAreInWorldSpace === value) { + return; + } + this._normalsAreInWorldSpace = value; + this._updateEffectDefines(); + } + get normalsAreUnsigned() { + return this._normalsAreUnsigned; + } + set normalsAreUnsigned(value) { + if (this._normalsAreUnsigned === value) { + return; + } + this._normalsAreUnsigned = value; + this._updateEffectDefines(); + } + bind() { + super.bind(); + const effect = this._drawWrapper.effect; + effect.setFloat("strength", this.strength); + effect.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent); + effect.setFloat("reflectivityThreshold", this.reflectivityThreshold); + if (this.useFresnel && this.camera) { + const projectionMatrix = this.camera.getProjectionMatrix(); + projectionMatrix.invertToRef(TmpVectors.Matrix[0]); + effect.setMatrix("projection", projectionMatrix); + effect.setMatrix("invProjectionMatrix", TmpVectors.Matrix[0]); + effect.setMatrix("view", this.camera.getViewMatrix()); + if (this.useScreenspaceDepth) { + effect.setFloat("nearPlaneZ", this.camera.minZ); + effect.setFloat("farPlaneZ", this.camera.maxZ); + } + } + } + _updateEffectDefines() { + let defines = ""; + if (this._debug) { + defines += "#define SSRAYTRACE_DEBUG\n"; + } + if (this._inputTextureColorIsInGammaSpace) { + defines += "#define SSR_INPUT_IS_GAMMA_SPACE\n"; + } + if (this._generateOutputInGammaSpace) { + defines += "#define SSR_OUTPUT_IS_GAMMA_SPACE\n"; + } + if (this._useFresnel) { + defines += "#define SSR_BLEND_WITH_FRESNEL\n"; + } + if (this._useScreenspaceDepth) { + defines += "#define SSRAYTRACE_SCREENSPACE_DEPTH\n"; + } + if (this._reflectivityThreshold === 0) { + defines += "#define SSR_DISABLE_REFLECTIVITY_TEST\n"; + } + if (this._normalsAreInWorldSpace) { + defines += "#define SSR_NORMAL_IS_IN_WORLDSPACE\n"; + } + if (this._normalsAreUnsigned) { + defines += "#define SSR_DECODE_NORMAL\n"; + } + this.updateEffect(defines); + } +} +ThinSSRBlurCombinerPostProcess.FragmentUrl = "screenSpaceReflection2BlurCombiner"; +ThinSSRBlurCombinerPostProcess.Uniforms = [ + "strength", + "reflectionSpecularFalloffExponent", + "reflectivityThreshold", + "projection", + "invProjectionMatrix", + "nearPlaneZ", + "farPlaneZ", + "view", +]; +ThinSSRBlurCombinerPostProcess.Samplers = ["textureSampler", "depthSampler", "normalSampler", "mainSampler", "reflectivitySampler"]; + +/** + * The SSR rendering pipeline is used to generate a reflection based on a flat mirror model. + */ +class ThinSSRRenderingPipeline { + /** + * Gets or sets a boolean indicating if the SSR rendering pipeline is supported + */ + get isSSRSupported() { + return this._ssrPostProcess.isSSRSupported; + } + set isSSRSupported(supported) { + this._ssrPostProcess.isSSRSupported = supported; + } + /** + * Gets or sets the maxDistance used to define how far we look for reflection during the ray-marching on the reflected ray (default: 1000). + * Note that this value is a view (camera) space distance (not pixels!). + */ + get maxDistance() { + return this._ssrPostProcess.maxDistance; + } + set maxDistance(distance) { + this._ssrPostProcess.maxDistance = distance; + } + /** + * Gets or sets the step size used to iterate until the effect finds the color of the reflection's pixel. Should be an integer \>= 1 as it is the number of pixels we advance at each step (default: 1). + * Use higher values to improve performances (but at the expense of quality). + */ + get step() { + return this._ssrPostProcess.step; + } + set step(step) { + this._ssrPostProcess.step = step; + } + /** + * Gets or sets the thickness value used as tolerance when computing the intersection between the reflected ray and the scene (default: 0.5). + * If setting "enableAutomaticThicknessComputation" to true, you can use lower values for "thickness" (even 0), as the geometry thickness + * is automatically computed thank to the regular depth buffer + the backface depth buffer + */ + get thickness() { + return this._ssrPostProcess.thickness; + } + set thickness(thickness) { + this._ssrPostProcess.thickness = thickness; + } + /** + * Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results (default: 1). + */ + get strength() { + return this._ssrPostProcess.strength; + } + set strength(strength) { + this._ssrPostProcess.strength = strength; + this._ssrBlurCombinerPostProcess.strength = strength; + } + /** + * Gets or sets the falloff exponent used to compute the reflection strength. Higher values lead to fainter reflections (default: 1). + */ + get reflectionSpecularFalloffExponent() { + return this._ssrPostProcess.reflectionSpecularFalloffExponent; + } + set reflectionSpecularFalloffExponent(exponent) { + this._ssrPostProcess.reflectionSpecularFalloffExponent = exponent; + this._ssrBlurCombinerPostProcess.reflectionSpecularFalloffExponent = exponent; + } + /** + * Maximum number of steps during the ray marching process after which we consider an intersection could not be found (default: 1000). + * Should be an integer value. + */ + get maxSteps() { + return this._ssrPostProcess.maxSteps; + } + set maxSteps(steps) { + this._ssrPostProcess.maxSteps = steps; + } + /** + * Gets or sets the factor applied when computing roughness. Default value is 0.2. + * When blurring based on roughness is enabled (meaning blurDispersionStrength \> 0), roughnessFactor is used as a global roughness factor applied on all objects. + * If you want to disable this global roughness set it to 0. + */ + get roughnessFactor() { + return this._ssrPostProcess.roughnessFactor; + } + set roughnessFactor(factor) { + this._ssrPostProcess.roughnessFactor = factor; + } + /** + * Number of steps to skip at start when marching the ray to avoid self collisions (default: 1) + * 1 should normally be a good value, depending on the scene you may need to use a higher value (2 or 3) + */ + get selfCollisionNumSkip() { + return this._ssrPostProcess.selfCollisionNumSkip; + } + set selfCollisionNumSkip(skip) { + this._ssrPostProcess.selfCollisionNumSkip = skip; + } + /** + * Gets or sets the minimum value for one of the reflectivity component of the material to consider it for SSR (default: 0.04). + * If all r/g/b components of the reflectivity is below or equal this value, the pixel will not be considered reflective and SSR won't be applied. + */ + get reflectivityThreshold() { + return this._ssrPostProcess.reflectivityThreshold; + } + set reflectivityThreshold(threshold) { + const currentThreshold = this._ssrPostProcess.reflectivityThreshold; + if (threshold === currentThreshold) { + return; + } + this._ssrPostProcess.reflectivityThreshold = threshold; + this._ssrBlurCombinerPostProcess.reflectivityThreshold = threshold; + } + /** + * Gets or sets the blur dispersion strength. Set this value to 0 to disable blurring (default: 0.03) + * The reflections are blurred based on the roughness of the surface and the distance between the pixel shaded and the reflected pixel: the higher the distance the more blurry the reflection is. + * blurDispersionStrength allows to increase or decrease this effect. + */ + get blurDispersionStrength() { + return this._ssrBlurXPostProcess.blurStrength; + } + set blurDispersionStrength(strength) { + if (strength === this._ssrBlurXPostProcess.blurStrength) { + return; + } + this._ssrPostProcess.useBlur = strength > 0; + this._ssrBlurXPostProcess.blurStrength = strength; + this._ssrBlurYPostProcess.blurStrength = strength; + } + /** + * Gets or sets whether or not smoothing reflections is enabled (default: false) + * Enabling smoothing will require more GPU power. + * Note that this setting has no effect if step = 1: it's only used if step \> 1. + */ + get enableSmoothReflections() { + return this._ssrPostProcess.enableSmoothReflections; + } + set enableSmoothReflections(enabled) { + this._ssrPostProcess.enableSmoothReflections = enabled; + } + /** + * Gets or sets the environment cube texture used to define the reflection when the reflected rays of SSR leave the view space or when the maxDistance/maxSteps is reached. + */ + get environmentTexture() { + return this._ssrPostProcess.environmentTexture; + } + set environmentTexture(texture) { + this._ssrPostProcess.environmentTexture = texture; + } + /** + * Gets or sets the boolean defining if the environment texture is a standard cubemap (false) or a probe (true). Default value is false. + * Note: a probe cube texture is treated differently than an ordinary cube texture because the Y axis is reversed. + */ + get environmentTextureIsProbe() { + return this._ssrPostProcess.environmentTextureIsProbe; + } + set environmentTextureIsProbe(isProbe) { + this._ssrPostProcess.environmentTextureIsProbe = isProbe; + } + /** + * Gets or sets a boolean indicating if the reflections should be attenuated at the screen borders (default: true). + */ + get attenuateScreenBorders() { + return this._ssrPostProcess.attenuateScreenBorders; + } + set attenuateScreenBorders(attenuate) { + this._ssrPostProcess.attenuateScreenBorders = attenuate; + } + /** + * Gets or sets a boolean indicating if the reflections should be attenuated according to the distance of the intersection (default: true). + */ + get attenuateIntersectionDistance() { + return this._ssrPostProcess.attenuateIntersectionDistance; + } + set attenuateIntersectionDistance(attenuate) { + this._ssrPostProcess.attenuateIntersectionDistance = attenuate; + } + /** + * Gets or sets a boolean indicating if the reflections should be attenuated according to the number of iterations performed to find the intersection (default: true). + */ + get attenuateIntersectionIterations() { + return this._ssrPostProcess.attenuateIntersectionIterations; + } + set attenuateIntersectionIterations(attenuate) { + this._ssrPostProcess.attenuateIntersectionIterations = attenuate; + } + /** + * Gets or sets a boolean indicating if the reflections should be attenuated when the reflection ray is facing the camera (the view direction) (default: false). + */ + get attenuateFacingCamera() { + return this._ssrPostProcess.attenuateFacingCamera; + } + set attenuateFacingCamera(attenuate) { + this._ssrPostProcess.attenuateFacingCamera = attenuate; + } + /** + * Gets or sets a boolean indicating if the backface reflections should be attenuated (default: false). + */ + get attenuateBackfaceReflection() { + return this._ssrPostProcess.attenuateBackfaceReflection; + } + set attenuateBackfaceReflection(attenuate) { + this._ssrPostProcess.attenuateBackfaceReflection = attenuate; + } + /** + * Gets or sets a boolean indicating if the ray should be clipped to the frustum (default: true). + * You can try to set this parameter to false to save some performances: it may produce some artefacts in some cases, but generally they won't really be visible + */ + get clipToFrustum() { + return this._ssrPostProcess.clipToFrustum; + } + set clipToFrustum(clip) { + this._ssrPostProcess.clipToFrustum = clip; + } + /** + * Gets or sets a boolean indicating whether the blending between the current color pixel and the reflection color should be done with a Fresnel coefficient (default: false). + * It is more physically accurate to use the Fresnel coefficient (otherwise it uses the reflectivity of the material for blending), but it is also more expensive when you use blur (when blurDispersionStrength \> 0). + */ + get useFresnel() { + return this._ssrPostProcess.useFresnel; + } + set useFresnel(fresnel) { + this._ssrPostProcess.useFresnel = fresnel; + this._ssrBlurCombinerPostProcess.useFresnel = fresnel; + } + /** + * Gets or sets a boolean defining if geometry thickness should be computed automatically (default: false). + * When enabled, a depth renderer is created which will render the back faces of the scene to a depth texture (meaning additional work for the GPU). + * In that mode, the "thickness" property is still used as an offset to compute the ray intersection, but you can typically use a much lower + * value than when enableAutomaticThicknessComputation is false (it's even possible to use a value of 0 when using low values for "step") + * Note that for performance reasons, this option will only apply to the first camera to which the rendering pipeline is attached! + */ + get enableAutomaticThicknessComputation() { + return this._ssrPostProcess.enableAutomaticThicknessComputation; + } + set enableAutomaticThicknessComputation(automatic) { + if (this._ssrPostProcess.enableAutomaticThicknessComputation === automatic) { + return; + } + this._ssrPostProcess.enableAutomaticThicknessComputation = automatic; + } + /** + * Gets or sets a boolean defining if the input color texture is in gamma space (default: true) + * The SSR effect works in linear space, so if the input texture is in gamma space, we must convert the texture to linear space before applying the effect + */ + get inputTextureColorIsInGammaSpace() { + return this._ssrPostProcess.inputTextureColorIsInGammaSpace; + } + set inputTextureColorIsInGammaSpace(gammaSpace) { + if (this._ssrPostProcess.inputTextureColorIsInGammaSpace === gammaSpace) { + return; + } + this._ssrPostProcess.inputTextureColorIsInGammaSpace = gammaSpace; + this._ssrBlurCombinerPostProcess.inputTextureColorIsInGammaSpace = gammaSpace; + } + /** + * Gets or sets a boolean defining if the output color texture generated by the SSR pipeline should be in gamma space (default: true) + * If you have a post-process that comes after the SSR and that post-process needs the input to be in a linear space, you must disable generateOutputInGammaSpace + */ + get generateOutputInGammaSpace() { + return this._ssrPostProcess.generateOutputInGammaSpace; + } + set generateOutputInGammaSpace(gammaSpace) { + if (this._ssrPostProcess.generateOutputInGammaSpace === gammaSpace) { + return; + } + this._ssrPostProcess.generateOutputInGammaSpace = gammaSpace; + this._ssrBlurCombinerPostProcess.generateOutputInGammaSpace = gammaSpace; + } + /** + * Gets or sets a boolean indicating if the effect should be rendered in debug mode (default: false). + * In this mode, colors have this meaning: + * - blue: the ray hit the max distance (we reached maxDistance) + * - red: the ray ran out of steps (we reached maxSteps) + * - yellow: the ray went off screen + * - green: the ray hit a surface. The brightness of the green color is proportional to the distance between the ray origin and the intersection point: A brighter green means more computation than a darker green. + * In the first 3 cases, the final color is calculated by mixing the skybox color with the pixel color (if environmentTexture is defined), otherwise the pixel color is not modified + * You should try to get as few blue/red/yellow pixels as possible, as this means that the ray has gone further than if it had hit a surface. + */ + get debug() { + return this._ssrPostProcess.debug; + } + set debug(value) { + if (this._ssrPostProcess.debug === value) { + return; + } + this._ssrPostProcess.debug = value; + this._ssrBlurCombinerPostProcess.debug = value; + } + /** + * Gets or sets the camera to use to render the reflection + */ + get camera() { + return this._ssrPostProcess.camera; + } + set camera(camera) { + this._ssrPostProcess.camera = camera; + this._ssrBlurCombinerPostProcess.camera = camera; + } + /** + * Gets or sets a boolean indicating if the depth buffer stores screen space depth instead of camera view space depth. + */ + get useScreenspaceDepth() { + return this._ssrPostProcess.useScreenspaceDepth; + } + set useScreenspaceDepth(use) { + this._ssrPostProcess.useScreenspaceDepth = use; + this._ssrBlurCombinerPostProcess.useScreenspaceDepth = use; + } + /** + * Gets or sets a boolean indicating if the normals are in world space (false by default, meaning normals are in camera view space). + */ + get normalsAreInWorldSpace() { + return this._ssrPostProcess.normalsAreInWorldSpace; + } + set normalsAreInWorldSpace(normalsAreInWorldSpace) { + this._ssrPostProcess.normalsAreInWorldSpace = normalsAreInWorldSpace; + this._ssrBlurCombinerPostProcess.normalsAreInWorldSpace = normalsAreInWorldSpace; + } + /** + * Gets or sets a boolean indicating if the normals are encoded as unsigned, that is normalUnsigned = normal*0.5+0.5 (false by default). + */ + get normalsAreUnsigned() { + return this._ssrPostProcess.normalsAreUnsigned; + } + set normalsAreUnsigned(normalsAreUnsigned) { + this._ssrPostProcess.normalsAreUnsigned = normalsAreUnsigned; + this._ssrBlurCombinerPostProcess.normalsAreUnsigned = normalsAreUnsigned; + } + /** + * Checks if all the post processes in the pipeline are ready. + * @returns true if all the post processes in the pipeline are ready + */ + isReady() { + return this._ssrPostProcess.isReady() && this._ssrBlurXPostProcess.isReady() && this._ssrBlurYPostProcess.isReady() && this._ssrBlurCombinerPostProcess.isReady(); + } + /** + * Constructor of the SSR rendering pipeline + * @param name The rendering pipeline name + * @param scene The scene linked to this pipeline + */ + constructor(name, scene) { + /** + * Gets or sets the downsample factor used to reduce the size of the texture used to compute the SSR contribution (default: 0). + * Use 0 to render the SSR contribution at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc. + * Note that it is used only when blurring is enabled (blurDispersionStrength \> 0), because in that mode the SSR contribution is generated in a separate texture. + */ + this.ssrDownsample = 0; + /** + * Gets or sets the downsample factor used to reduce the size of the textures used to blur the reflection effect (default: 0). + * Use 0 to blur at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc. + */ + this.blurDownsample = 0; + this.name = name; + this._scene = scene; + this._ssrPostProcess = new ThinSSRPostProcess(this.name, this._scene); + this._ssrBlurXPostProcess = new ThinSSRBlurPostProcess(this.name + " BlurX", this._scene.getEngine(), new Vector2(1, 0)); + this._ssrBlurYPostProcess = new ThinSSRBlurPostProcess(this.name + " BlurY", this._scene.getEngine(), new Vector2(0, 1)); + this._ssrBlurCombinerPostProcess = new ThinSSRBlurCombinerPostProcess(this.name + " BlurCombiner", this._scene.getEngine()); + this._ssrPostProcess.useBlur = this._ssrBlurXPostProcess.blurStrength > 0; + } + /** + * Disposes of the pipeline + */ + dispose() { + this._ssrPostProcess?.dispose(); + this._ssrBlurXPostProcess?.dispose(); + this._ssrBlurYPostProcess?.dispose(); + this._ssrBlurCombinerPostProcess?.dispose(); + } +} + +/** + * @internal + */ +class FrameGraphSSRTask extends FrameGraphPostProcessTask { + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinSSRPostProcess(name, frameGraph.scene)); + this.onTexturesAllocatedObservable.add((context) => { + context.setTextureSamplingMode(this.normalTexture, 2); + context.setTextureSamplingMode(this.depthTexture, 2); + context.setTextureSamplingMode(this.reflectivityTexture, 2); + if (this.backDepthTexture) { + context.setTextureSamplingMode(this.backDepthTexture, 1); + } + }); + } + record(skipCreationOfDisabledPasses = false) { + if (this.sourceTexture === undefined || + this.normalTexture === undefined || + this.depthTexture === undefined || + this.reflectivityTexture === undefined || + this.camera === undefined) { + throw new Error(`FrameGraphSSRTask "${this.name}": sourceTexture, normalTexture, depthTexture, reflectivityTexture and camera are required`); + } + const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => { + this.postProcess.camera = this.camera; + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "normalSampler", this.normalTexture); + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "depthSampler", this.depthTexture); + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "reflectivitySampler", this.reflectivityTexture); + if (this.backDepthTexture) { + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "backDepthSampler", this.backDepthTexture); + } + if (this.postProcess.enableAutomaticThicknessComputation) { + this._postProcessDrawWrapper.effect.setFloat("backSizeFactor", 1); + } + }); + pass.addDependencies([this.normalTexture, this.depthTexture, this.reflectivityTexture]); + this.postProcess.textureWidth = this._sourceWidth; + this.postProcess.textureHeight = this._sourceHeight; + return pass; + } +} + +/** + * @internal + */ +class FrameGraphSSRBlurTask extends FrameGraphPostProcessTask { + constructor(name, frameGraph, thinPostProcess) { + super(name, frameGraph, thinPostProcess || new ThinSSRBlurPostProcess(name, frameGraph.engine, new Vector2(1, 0), 0.03)); + } + record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) { + const pass = super.record(skipCreationOfDisabledPasses, additionalExecute, additionalBindings); + this.postProcess.textureWidth = this._sourceWidth; + this.postProcess.textureHeight = this._sourceHeight; + return pass; + } +} + +/** + * Task which applies a SSR post process. + */ +class FrameGraphSSRRenderingPipelineTask extends FrameGraphTask { + /** + * The camera used to render the scene. + */ + get camera() { + return this._camera; + } + set camera(camera) { + if (camera === this._camera) { + return; + } + this._camera = camera; + this.ssr.camera = camera; + } + /** + * The name of the task. + */ + get name() { + return this._name; + } + set name(name) { + this._name = name; + if (this._ssr) { + this._ssr.name = `${name} SSR`; + } + if (this._ssrBlurX) { + this._ssrBlurX.name = `${name} SSR Blur X`; + } + if (this._ssrBlurY) { + this._ssrBlurY.name = `${name} SSR Blur Y`; + } + if (this._ssrBlurCombiner) { + this._ssrBlurCombiner.name = `${name} SSR Blur Combiner`; + } + } + /** + * Constructs a SSR rendering pipeline task. + * @param name The name of the task. + * @param frameGraph The frame graph this task belongs to. + * @param textureType The texture type used by the different post processes created by SSR (default: 0) + */ + constructor(name, frameGraph, textureType = 0) { + super(name, frameGraph); + /** + * The sampling mode to use for the source texture. + */ + this.sourceSamplingMode = 2; + this.textureType = textureType; + this.ssr = new ThinSSRRenderingPipeline(name, frameGraph.scene); + this._ssr = new FrameGraphSSRTask(`${name} SSR`, this._frameGraph, this.ssr._ssrPostProcess); + this._ssrBlurX = new FrameGraphSSRBlurTask(`${name} SSR Blur X`, this._frameGraph, this.ssr._ssrBlurXPostProcess); + this._ssrBlurY = new FrameGraphSSRBlurTask(`${name} SSR Blur Y`, this._frameGraph, this.ssr._ssrBlurYPostProcess); + this._ssrBlurCombiner = new FrameGraphPostProcessTask(`${name} SSR Blur Combiner`, this._frameGraph, this.ssr._ssrBlurCombinerPostProcess); + this.onTexturesAllocatedObservable.add((context) => { + this._ssr.onTexturesAllocatedObservable.notifyObservers(context); + // We should not forward the notification if blur is not enabled + if (this.ssr.blurDispersionStrength !== 0) { + this._ssrBlurX.onTexturesAllocatedObservable.notifyObservers(context); + this._ssrBlurY.onTexturesAllocatedObservable.notifyObservers(context); + this._ssrBlurCombiner.onTexturesAllocatedObservable.notifyObservers(context); + } + }); + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + } + isReady() { + return this.ssr.isReady(); + } + record() { + if (this.sourceTexture === undefined || + this.normalTexture === undefined || + this.depthTexture === undefined || + this.reflectivityTexture === undefined || + this.camera === undefined) { + throw new Error(`FrameGraphSSRRenderingPipelineTask "${this.name}": sourceTexture, normalTexture, depthTexture, reflectivityTexture and camera are required`); + } + const sourceTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.sourceTexture); + this._ssr.sourceTexture = this.sourceTexture; + this._ssr.sourceSamplingMode = this.sourceSamplingMode; + this._ssr.camera = this.camera; + this._ssr.normalTexture = this.normalTexture; + this._ssr.depthTexture = this.depthTexture; + this._ssr.backDepthTexture = this.backDepthTexture; + this._ssr.reflectivityTexture = this.reflectivityTexture; + let ssrTextureHandle; + const textureSize = { + width: Math.floor(sourceTextureDescription.size.width / (this.ssr.ssrDownsample + 1)) || 1, + height: Math.floor(sourceTextureDescription.size.height / (this.ssr.ssrDownsample + 1)) || 1, + }; + const textureCreationOptions = { + size: textureSize, + options: { + createMipMaps: false, + types: [this.textureType], + formats: [5], + samples: 1, + useSRGBBuffers: [false], + labels: [""], + }, + sizeIsPercentage: false, + }; + if (this.ssr.blurDispersionStrength > 0 || !this.targetTexture) { + ssrTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._ssr.name, textureCreationOptions); + } + if (this.ssr.blurDispersionStrength === 0) { + this._ssr.targetTexture = this.outputTexture; + if (ssrTextureHandle !== undefined) { + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, ssrTextureHandle); + } + else { + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture); + } + this._ssr.record(true); + } + else { + this._ssr.targetTexture = ssrTextureHandle; + this._ssr.record(true); + textureSize.width = Math.floor(sourceTextureDescription.size.width / (this.ssr.blurDownsample + 1)) || 1; + textureSize.height = Math.floor(sourceTextureDescription.size.height / (this.ssr.blurDownsample + 1)) || 1; + const sourceTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture); + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture, this.name + " Output", sourceTextureCreationOptions); + const blurXTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._ssrBlurX.name, textureCreationOptions); + this._ssrBlurX.sourceTexture = ssrTextureHandle; + this._ssrBlurX.sourceSamplingMode = 2; + this._ssrBlurX.targetTexture = blurXTextureHandle; + this._ssrBlurX.record(true); + const blurYTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._ssrBlurY.name, textureCreationOptions); + this._ssrBlurY.sourceTexture = blurXTextureHandle; + this._ssrBlurY.sourceSamplingMode = 2; + this._ssrBlurY.targetTexture = blurYTextureHandle; + this._ssrBlurY.record(true); + this._ssrBlurCombiner.sourceTexture = this.sourceTexture; + this._ssrBlurCombiner.sourceSamplingMode = this.sourceSamplingMode; + this._ssrBlurCombiner.targetTexture = this.outputTexture; + const combinerPass = this._ssrBlurCombiner.record(true, undefined, (context) => { + context.bindTextureHandle(this._ssrBlurCombiner.drawWrapper.effect, "mainSampler", this.sourceTexture); + context.bindTextureHandle(this._ssrBlurCombiner.drawWrapper.effect, "textureSampler", blurYTextureHandle); + context.bindTextureHandle(this._ssrBlurCombiner.drawWrapper.effect, "reflectivitySampler", this.reflectivityTexture); + if (this.ssr.useFresnel) { + context.bindTextureHandle(this._ssrBlurCombiner.drawWrapper.effect, "normalSampler", this.normalTexture); + context.bindTextureHandle(this._ssrBlurCombiner.drawWrapper.effect, "depthSampler", this.depthTexture); + } + }); + combinerPass.addDependencies(blurYTextureHandle); + } + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.addDependencies(this.sourceTexture); + passDisabled.setRenderTarget(this.outputTexture); + passDisabled.setExecuteFunc((context) => { + context.copyTexture(this.sourceTexture); + }); + } + dispose() { + this._ssr.dispose(); + this._ssrBlurX.dispose(); + this._ssrBlurY.dispose(); + this._ssrBlurCombiner.dispose(); + this.ssr.dispose(); + super.dispose(); + } +} + +/** + * Block that implements the SSR post process + */ +class NodeRenderGraphSSRPostProcessBlock extends NodeRenderGraphBasePostProcessBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphSSRPostProcessBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param textureType The texture type used by the different post processes created by SSR (default: 0) + */ + constructor(name, frameGraph, scene, textureType = 0) { + super(name, frameGraph, scene); + this._additionalConstructionParameters = [textureType]; + this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera); + this.registerInput("geomDepth", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this.registerInput("geomNormal", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this.registerInput("geomReflectivity", NodeRenderGraphBlockConnectionPointTypes.TextureReflectivity); + this.registerInput("geomBackDepth", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.geomNormal.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureWorldNormal | NodeRenderGraphBlockConnectionPointTypes.TextureViewNormal); + this.geomDepth.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureScreenDepth | NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth); + this.geomBackDepth.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureScreenDepth | NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth); + this._finalizeInputOutputRegistering(); + this._frameGraphTask = new FrameGraphSSRRenderingPipelineTask(this.name, frameGraph, textureType); + } + _createTask(textureType) { + const sourceSamplingMode = this.sourceSamplingMode; + const maxDistance = this.maxDistance; + const step = this.step; + const thickness = this.thickness; + const strength = this.strength; + const reflectionSpecularFalloffExponent = this.reflectionSpecularFalloffExponent; + const maxSteps = this.maxSteps; + const roughnessFactor = this.roughnessFactor; + const selfCollisionNumSkip = this.selfCollisionNumSkip; + const reflectivityThreshold = this.reflectivityThreshold; + const ssrDownsample = this.ssrDownsample; + const blurDispersionStrength = this.blurDispersionStrength; + const blurDownsample = this.blurDownsample; + const enableSmoothReflections = this.enableSmoothReflections; + const attenuateScreenBorders = this.attenuateScreenBorders; + const attenuateIntersectionDistance = this.attenuateIntersectionDistance; + const attenuateIntersectionIterations = this.attenuateIntersectionIterations; + const attenuateFacingCamera = this.attenuateFacingCamera; + const attenuateBackfaceReflection = this.attenuateBackfaceReflection; + const clipToFrustum = this.clipToFrustum; + const enableAutomaticThicknessComputation = this.enableAutomaticThicknessComputation; + const useFresnel = this.useFresnel; + const inputTextureColorIsInGammaSpace = this.inputTextureColorIsInGammaSpace; + const generateOutputInGammaSpace = this.generateOutputInGammaSpace; + const debug = this.debug; + this._frameGraphTask.dispose(); + this._frameGraphTask = new FrameGraphSSRRenderingPipelineTask(this.name, this._frameGraph, textureType); + this.sourceSamplingMode = sourceSamplingMode; + this.maxDistance = maxDistance; + this.step = step; + this.thickness = thickness; + this.strength = strength; + this.reflectionSpecularFalloffExponent = reflectionSpecularFalloffExponent; + this.maxSteps = maxSteps; + this.roughnessFactor = roughnessFactor; + this.selfCollisionNumSkip = selfCollisionNumSkip; + this.reflectivityThreshold = reflectivityThreshold; + this.ssrDownsample = ssrDownsample; + this.blurDispersionStrength = blurDispersionStrength; + this.blurDownsample = blurDownsample; + this.enableSmoothReflections = enableSmoothReflections; + this.attenuateScreenBorders = attenuateScreenBorders; + this.attenuateIntersectionDistance = attenuateIntersectionDistance; + this.attenuateIntersectionIterations = attenuateIntersectionIterations; + this.attenuateFacingCamera = attenuateFacingCamera; + this.attenuateBackfaceReflection = attenuateBackfaceReflection; + this.clipToFrustum = clipToFrustum; + this.useFresnel = useFresnel; + this.enableAutomaticThicknessComputation = enableAutomaticThicknessComputation; + this.inputTextureColorIsInGammaSpace = inputTextureColorIsInGammaSpace; + this.generateOutputInGammaSpace = generateOutputInGammaSpace; + this.debug = debug; + this._additionalConstructionParameters = [textureType]; + } + /** The texture type used by the different post processes created by SSR */ + get textureType() { + return this._frameGraphTask.textureType; + } + set textureType(value) { + this._createTask(value); + } + /** Gets or sets a boolean indicating if the effect should be rendered in debug mode */ + get debug() { + return this._frameGraphTask.ssr.debug; + } + set debug(value) { + this._frameGraphTask.ssr.debug = value; + } + /** Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results */ + get strength() { + return this._frameGraphTask.ssr.strength; + } + set strength(value) { + this._frameGraphTask.ssr.strength = value; + } + /** Gets or sets the falloff exponent used to compute the reflection strength. Higher values lead to fainter reflections */ + get reflectionSpecularFalloffExponent() { + return this._frameGraphTask.ssr.reflectionSpecularFalloffExponent; + } + set reflectionSpecularFalloffExponent(value) { + this._frameGraphTask.ssr.reflectionSpecularFalloffExponent = value; + } + /** Gets or sets the minimum value for one of the reflectivity component of the material to consider it for SSR */ + get reflectivityThreshold() { + return this._frameGraphTask.ssr.reflectivityThreshold; + } + set reflectivityThreshold(value) { + this._frameGraphTask.ssr.reflectivityThreshold = value; + } + /** Gets or sets the thickness value used as tolerance when computing the intersection between the reflected ray and the scene */ + get thickness() { + return this._frameGraphTask.ssr.thickness; + } + set thickness(value) { + this._frameGraphTask.ssr.thickness = value; + } + /** Gets or sets the step size used to iterate until the effect finds the color of the reflection's pixel */ + get step() { + return this._frameGraphTask.ssr.step; + } + set step(value) { + this._frameGraphTask.ssr.step = value; + } + /** Gets or sets whether or not smoothing reflections is enabled */ + get enableSmoothReflections() { + return this._frameGraphTask.ssr.enableSmoothReflections; + } + set enableSmoothReflections(value) { + this._frameGraphTask.ssr.enableSmoothReflections = value; + } + /** Maximum number of steps during the ray marching process after which we consider an intersection could not be found */ + get maxSteps() { + return this._frameGraphTask.ssr.maxSteps; + } + set maxSteps(value) { + this._frameGraphTask.ssr.maxSteps = value; + } + /** Gets or sets the max distance used to define how far we look for reflection during the ray-marching on the reflected ray */ + get maxDistance() { + return this._frameGraphTask.ssr.maxDistance; + } + set maxDistance(value) { + this._frameGraphTask.ssr.maxDistance = value; + } + /** Gets or sets the factor applied when computing roughness */ + get roughnessFactor() { + return this._frameGraphTask.ssr.roughnessFactor; + } + set roughnessFactor(value) { + this._frameGraphTask.ssr.roughnessFactor = value; + } + /** Number of steps to skip at start when marching the ray to avoid self collisions */ + get selfCollisionNumSkip() { + return this._frameGraphTask.ssr.selfCollisionNumSkip; + } + set selfCollisionNumSkip(value) { + this._frameGraphTask.ssr.selfCollisionNumSkip = value; + } + /** Gets or sets the downsample factor used to reduce the size of the texture used to compute the SSR contribution */ + get ssrDownsample() { + return this._frameGraphTask.ssr.ssrDownsample; + } + set ssrDownsample(value) { + this._frameGraphTask.ssr.ssrDownsample = value; + } + /** Gets or sets a boolean indicating if the ray should be clipped to the frustum */ + get clipToFrustum() { + return this._frameGraphTask.ssr.clipToFrustum; + } + set clipToFrustum(value) { + this._frameGraphTask.ssr.clipToFrustum = value; + } + /** Gets or sets a boolean defining if geometry thickness should be computed automatically */ + get enableAutomaticThicknessComputation() { + return this._frameGraphTask.ssr.enableAutomaticThicknessComputation; + } + set enableAutomaticThicknessComputation(value) { + this._frameGraphTask.ssr.enableAutomaticThicknessComputation = value; + } + /** Gets or sets a boolean indicating whether the blending between the current color pixel and the reflection color should be done with a Fresnel coefficient */ + get useFresnel() { + return this._frameGraphTask.ssr.useFresnel; + } + set useFresnel(value) { + this._frameGraphTask.ssr.useFresnel = value; + } + /** Gets or sets the blur dispersion strength. Set this value to 0 to disable blurring */ + get blurDispersionStrength() { + return this._frameGraphTask.ssr.blurDispersionStrength; + } + set blurDispersionStrength(value) { + this._frameGraphTask.ssr.blurDispersionStrength = value; + } + /** Gets or sets the downsample factor used to reduce the size of the textures used to blur the reflection effect */ + get blurDownsample() { + return this._frameGraphTask.ssr.blurDownsample; + } + set blurDownsample(value) { + this._frameGraphTask.ssr.blurDownsample = value; + } + /** Gets or sets a boolean indicating if the reflections should be attenuated at the screen borders */ + get attenuateScreenBorders() { + return this._frameGraphTask.ssr.attenuateScreenBorders; + } + set attenuateScreenBorders(value) { + this._frameGraphTask.ssr.attenuateScreenBorders = value; + } + /** Gets or sets a boolean indicating if the reflections should be attenuated according to the distance of the intersection */ + get attenuateIntersectionDistance() { + return this._frameGraphTask.ssr.attenuateIntersectionDistance; + } + set attenuateIntersectionDistance(value) { + this._frameGraphTask.ssr.attenuateIntersectionDistance = value; + } + /** Gets or sets a boolean indicating if the reflections should be attenuated according to the number of iterations performed to find the intersection */ + get attenuateIntersectionIterations() { + return this._frameGraphTask.ssr.attenuateIntersectionIterations; + } + set attenuateIntersectionIterations(value) { + this._frameGraphTask.ssr.attenuateIntersectionIterations = value; + } + /** Gets or sets a boolean indicating if the reflections should be attenuated when the reflection ray is facing the camera (the view direction) */ + get attenuateFacingCamera() { + return this._frameGraphTask.ssr.attenuateFacingCamera; + } + set attenuateFacingCamera(value) { + this._frameGraphTask.ssr.attenuateFacingCamera = value; + } + /** Gets or sets a boolean indicating if the backface reflections should be attenuated */ + get attenuateBackfaceReflection() { + return this._frameGraphTask.ssr.attenuateBackfaceReflection; + } + set attenuateBackfaceReflection(value) { + this._frameGraphTask.ssr.attenuateBackfaceReflection = value; + } + /** Gets or sets a boolean defining if the input color texture is in gamma space */ + get inputTextureColorIsInGammaSpace() { + return this._frameGraphTask.ssr.inputTextureColorIsInGammaSpace; + } + set inputTextureColorIsInGammaSpace(value) { + this._frameGraphTask.ssr.inputTextureColorIsInGammaSpace = value; + } + /** Gets or sets a boolean defining if the output color texture generated by the SSR pipeline should be in gamma space */ + get generateOutputInGammaSpace() { + return this._frameGraphTask.ssr.generateOutputInGammaSpace; + } + set generateOutputInGammaSpace(value) { + this._frameGraphTask.ssr.generateOutputInGammaSpace = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphSSRPostProcessBlock"; + } + /** + * Gets the camera input component + */ + get camera() { + return this._inputs[2]; + } + /** + * Gets the geometry depth input component + */ + get geomDepth() { + return this._inputs[3]; + } + /** + * Gets the geometry normal input component + */ + get geomNormal() { + return this._inputs[4]; + } + /** + * Gets the geometry reflectivity input component + */ + get geomReflectivity() { + return this._inputs[5]; + } + /** + * Gets the geometry back depth input component + */ + get geomBackDepth() { + return this._inputs[6]; + } + _buildBlock(state) { + super._buildBlock(state); + this._frameGraphTask.normalTexture = this.geomNormal.connectedPoint?.value; + this._frameGraphTask.depthTexture = this.geomDepth.connectedPoint?.value; + this._frameGraphTask.reflectivityTexture = this.geomReflectivity.connectedPoint?.value; + this._frameGraphTask.backDepthTexture = this.geomBackDepth.connectedPoint?.value; + this._frameGraphTask.camera = this.camera.connectedPoint?.value; + if (this.enableAutomaticThicknessComputation) { + if (!this._frameGraphTask.backDepthTexture) { + throw new Error(`SSR post process "${this.name}": Automatic thickness computation requires a back depth texture to be connected!`); + } + const geomBackDepthOwnerBlock = this.geomBackDepth.connectedPoint.ownerBlock; + if (geomBackDepthOwnerBlock.getClassName() === "NodeRenderGraphGeometryRendererBlock") { + const geometryBackFaceRendererBlock = geomBackDepthOwnerBlock; + if (!geometryBackFaceRendererBlock.reverseCulling) { + throw new Error(`SSR post process "${this.name}": Automatic thickness computation requires the geometry renderer block for the back depth texture to have reverse culling enabled!`); + } + if (this._frameGraphTask.depthTexture) { + const geomDepthOwnerBlock = this.geomDepth.connectedPoint.ownerBlock; + if (geomDepthOwnerBlock.getClassName() === "NodeRenderGraphGeometryRendererBlock") { + const geomDepthConnectionPointType = this.geomDepth.connectedPoint.type; + const geomBackDepthConnectionPointType = this.geomBackDepth.connectedPoint.type; + if (geomDepthConnectionPointType !== geomBackDepthConnectionPointType) { + throw new Error(`SSR post process "${this.name}": Automatic thickness computation requires that geomDepth and geomBackDepth have the same type (view or screen space depth)!`); + } + } + } + } + } + if (this.geomNormal.connectedPoint) { + if (this.geomNormal.connectedPoint.type === NodeRenderGraphBlockConnectionPointTypes.TextureWorldNormal) { + this._frameGraphTask.ssr.normalsAreInWorldSpace = true; + this._frameGraphTask.ssr.normalsAreUnsigned = true; + } + } + if (this.geomDepth.connectedPoint) { + if (this.geomDepth.connectedPoint.type === NodeRenderGraphBlockConnectionPointTypes.TextureScreenDepth) { + this._frameGraphTask.ssr.useScreenspaceDepth = true; + } + } + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.debug = ${this.debug};`); + codes.push(`${this._codeVariableName}.strength = ${this.strength};`); + codes.push(`${this._codeVariableName}.reflectionSpecularFalloffExponent = ${this.reflectionSpecularFalloffExponent};`); + codes.push(`${this._codeVariableName}.reflectivityThreshold = ${this.reflectivityThreshold};`); + codes.push(`${this._codeVariableName}.thickness = ${this.thickness};`); + codes.push(`${this._codeVariableName}.step = ${this.step};`); + codes.push(`${this._codeVariableName}.enableSmoothReflections = ${this.enableSmoothReflections};`); + codes.push(`${this._codeVariableName}.maxSteps = ${this.maxSteps};`); + codes.push(`${this._codeVariableName}.maxDistance = ${this.maxDistance};`); + codes.push(`${this._codeVariableName}.roughnessFactor = ${this.roughnessFactor};`); + codes.push(`${this._codeVariableName}.selfCollisionNumSkip = ${this.selfCollisionNumSkip};`); + codes.push(`${this._codeVariableName}.ssrDownsample = ${this.ssrDownsample};`); + codes.push(`${this._codeVariableName}.clipToFrustum = ${this.clipToFrustum};`); + codes.push(`${this._codeVariableName}.useFresnel = ${this.useFresnel};`); + codes.push(`${this._codeVariableName}.enableAutomaticThicknessComputation = ${this.enableAutomaticThicknessComputation};`); + codes.push(`${this._codeVariableName}.blurDispersionStrength = ${this.blurDispersionStrength};`); + codes.push(`${this._codeVariableName}.blurDownsample = ${this.blurDownsample};`); + codes.push(`${this._codeVariableName}.attenuateScreenBorders = ${this.attenuateScreenBorders};`); + codes.push(`${this._codeVariableName}.attenuateIntersectionDistance = ${this.attenuateIntersectionDistance};`); + codes.push(`${this._codeVariableName}.attenuateIntersectionIterations = ${this.attenuateIntersectionIterations};`); + codes.push(`${this._codeVariableName}.attenuateFacingCamera = ${this.attenuateFacingCamera};`); + codes.push(`${this._codeVariableName}.attenuateBackfaceReflection = ${this.attenuateBackfaceReflection};`); + codes.push(`${this._codeVariableName}.inputTextureColorIsInGammaSpace = ${this.inputTextureColorIsInGammaSpace};`); + codes.push(`${this._codeVariableName}.generateOutputInGammaSpace = ${this.generateOutputInGammaSpace};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.debug = this.debug; + serializationObject.strength = this.strength; + serializationObject.reflectionSpecularFalloffExponent = this.reflectionSpecularFalloffExponent; + serializationObject.reflectivityThreshold = this.reflectivityThreshold; + serializationObject.thickness = this.thickness; + serializationObject.step = this.step; + serializationObject.enableSmoothReflections = this.enableSmoothReflections; + serializationObject.maxSteps = this.maxSteps; + serializationObject.maxDistance = this.maxDistance; + serializationObject.roughnessFactor = this.roughnessFactor; + serializationObject.selfCollisionNumSkip = this.selfCollisionNumSkip; + serializationObject.ssrDownsample = this.ssrDownsample; + serializationObject.clipToFrustum = this.clipToFrustum; + serializationObject.useFresnel = this.useFresnel; + serializationObject.enableAutomaticThicknessComputation = this.enableAutomaticThicknessComputation; + serializationObject.blurDispersionStrength = this.blurDispersionStrength; + serializationObject.blurDownsample = this.blurDownsample; + serializationObject.attenuateScreenBorders = this.attenuateScreenBorders; + serializationObject.attenuateIntersectionDistance = this.attenuateIntersectionDistance; + serializationObject.attenuateIntersectionIterations = this.attenuateIntersectionIterations; + serializationObject.attenuateFacingCamera = this.attenuateFacingCamera; + serializationObject.attenuateBackfaceReflection = this.attenuateBackfaceReflection; + serializationObject.inputTextureColorIsInGammaSpace = this.inputTextureColorIsInGammaSpace; + serializationObject.generateOutputInGammaSpace = this.generateOutputInGammaSpace; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.debug = serializationObject.debug; + this.strength = serializationObject.strength; + this.reflectionSpecularFalloffExponent = serializationObject.reflectionSpecularFalloffExponent; + this.reflectivityThreshold = serializationObject.reflectivityThreshold; + this.thickness = serializationObject.thickness; + this.step = serializationObject.step; + this.enableSmoothReflections = serializationObject.enableSmoothReflections; + this.maxSteps = serializationObject.maxSteps; + this.maxDistance = serializationObject.maxDistance; + this.roughnessFactor = serializationObject.roughnessFactor; + this.selfCollisionNumSkip = serializationObject.selfCollisionNumSkip; + this.ssrDownsample = serializationObject.ssrDownsample; + this.clipToFrustum = serializationObject.clipToFrustum; + this.useFresnel = serializationObject.useFresnel; + this.enableAutomaticThicknessComputation = serializationObject.enableAutomaticThicknessComputation; + this.blurDispersionStrength = serializationObject.blurDispersionStrength; + this.blurDownsample = serializationObject.blurDownsample; + this.attenuateScreenBorders = serializationObject.attenuateScreenBorders; + this.attenuateIntersectionDistance = serializationObject.attenuateIntersectionDistance; + this.attenuateIntersectionIterations = serializationObject.attenuateIntersectionIterations; + this.attenuateFacingCamera = serializationObject.attenuateFacingCamera; + this.attenuateBackfaceReflection = serializationObject.attenuateBackfaceReflection; + this.inputTextureColorIsInGammaSpace = serializationObject.inputTextureColorIsInGammaSpace; + this.generateOutputInGammaSpace = serializationObject.generateOutputInGammaSpace; + } +} +__decorate([ + editableInPropertyPage("Texture type", 8 /* PropertyTypeForEdition.TextureType */, "SSR") +], NodeRenderGraphSSRPostProcessBlock.prototype, "textureType", null); +__decorate([ + editableInPropertyPage("Debug", 0 /* PropertyTypeForEdition.Boolean */, "SSR") +], NodeRenderGraphSSRPostProcessBlock.prototype, "debug", null); +__decorate([ + editableInPropertyPage("Strength", 1 /* PropertyTypeForEdition.Float */, "SSR", { min: 0, max: 5 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "strength", null); +__decorate([ + editableInPropertyPage("Reflection exponent", 1 /* PropertyTypeForEdition.Float */, "SSR", { min: 0, max: 5 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "reflectionSpecularFalloffExponent", null); +__decorate([ + editableInPropertyPage("Reflectivity threshold", 1 /* PropertyTypeForEdition.Float */, "SSR", { min: 0, max: 1 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "reflectivityThreshold", null); +__decorate([ + editableInPropertyPage("Thickness", 1 /* PropertyTypeForEdition.Float */, "SSR", { min: 0, max: 10 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "thickness", null); +__decorate([ + editableInPropertyPage("Step", 2 /* PropertyTypeForEdition.Int */, "SSR", { min: 1, max: 50 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "step", null); +__decorate([ + editableInPropertyPage("Smooth reflections", 0 /* PropertyTypeForEdition.Boolean */, "SSR") +], NodeRenderGraphSSRPostProcessBlock.prototype, "enableSmoothReflections", null); +__decorate([ + editableInPropertyPage("Max steps", 2 /* PropertyTypeForEdition.Int */, "SSR", { min: 1, max: 3000 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "maxSteps", null); +__decorate([ + editableInPropertyPage("Max distance", 1 /* PropertyTypeForEdition.Float */, "SSR", { min: 1, max: 3000 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "maxDistance", null); +__decorate([ + editableInPropertyPage("Roughness factor", 1 /* PropertyTypeForEdition.Float */, "SSR", { min: 0, max: 1 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "roughnessFactor", null); +__decorate([ + editableInPropertyPage("Self collision skips", 2 /* PropertyTypeForEdition.Int */, "SSR", { min: 1, max: 10 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "selfCollisionNumSkip", null); +__decorate([ + editableInPropertyPage("SSR downsample", 2 /* PropertyTypeForEdition.Int */, "SSR", { min: 0, max: 5 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "ssrDownsample", null); +__decorate([ + editableInPropertyPage("Clip to frustum", 0 /* PropertyTypeForEdition.Boolean */, "SSR") +], NodeRenderGraphSSRPostProcessBlock.prototype, "clipToFrustum", null); +__decorate([ + editableInPropertyPage("Automatic thickness computation", 0 /* PropertyTypeForEdition.Boolean */, "SSR") +], NodeRenderGraphSSRPostProcessBlock.prototype, "enableAutomaticThicknessComputation", null); +__decorate([ + editableInPropertyPage("Use Fresnel", 0 /* PropertyTypeForEdition.Boolean */, "SSR") +], NodeRenderGraphSSRPostProcessBlock.prototype, "useFresnel", null); +__decorate([ + editableInPropertyPage("Strength", 1 /* PropertyTypeForEdition.Float */, "Blur", { min: 0, max: 0.15 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "blurDispersionStrength", null); +__decorate([ + editableInPropertyPage("Blur downsample", 2 /* PropertyTypeForEdition.Int */, "Blur", { min: 0, max: 5 }) +], NodeRenderGraphSSRPostProcessBlock.prototype, "blurDownsample", null); +__decorate([ + editableInPropertyPage("Screen borders", 0 /* PropertyTypeForEdition.Boolean */, "Attenuations") +], NodeRenderGraphSSRPostProcessBlock.prototype, "attenuateScreenBorders", null); +__decorate([ + editableInPropertyPage("Distance", 0 /* PropertyTypeForEdition.Boolean */, "Attenuations") +], NodeRenderGraphSSRPostProcessBlock.prototype, "attenuateIntersectionDistance", null); +__decorate([ + editableInPropertyPage("Step iterations", 0 /* PropertyTypeForEdition.Boolean */, "Attenuations") +], NodeRenderGraphSSRPostProcessBlock.prototype, "attenuateIntersectionIterations", null); +__decorate([ + editableInPropertyPage("Facing camera", 0 /* PropertyTypeForEdition.Boolean */, "Attenuations") +], NodeRenderGraphSSRPostProcessBlock.prototype, "attenuateFacingCamera", null); +__decorate([ + editableInPropertyPage("Backface reflections", 0 /* PropertyTypeForEdition.Boolean */, "Attenuations") +], NodeRenderGraphSSRPostProcessBlock.prototype, "attenuateBackfaceReflection", null); +__decorate([ + editableInPropertyPage("Input is in gamma space", 0 /* PropertyTypeForEdition.Boolean */, "Color space") +], NodeRenderGraphSSRPostProcessBlock.prototype, "inputTextureColorIsInGammaSpace", null); +__decorate([ + editableInPropertyPage("Output to gamma space", 0 /* PropertyTypeForEdition.Boolean */, "Color space") +], NodeRenderGraphSSRPostProcessBlock.prototype, "generateOutputInGammaSpace", null); +RegisterClass("BABYLON.NodeRenderGraphSSRPostProcessBlock", NodeRenderGraphSSRPostProcessBlock); + +/** + * @internal + */ +class NodeRenderGraphBaseShadowGeneratorBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphBaseShadowGeneratorBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("light", NodeRenderGraphBlockConnectionPointTypes.ShadowLight); + this.registerInput("objects", NodeRenderGraphBlockConnectionPointTypes.ObjectList); + this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera); + this._addDependenciesInput(); + this.registerOutput("generator", NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.Texture); + } + /** Sets the size of the shadow texture */ + get mapSize() { + return this._frameGraphTask.mapSize; + } + set mapSize(value) { + this._frameGraphTask.mapSize = value; + } + /** Sets the texture type to float (by default, half float is used if supported) */ + get useFloat32TextureType() { + return this._frameGraphTask.useFloat32TextureType; + } + set useFloat32TextureType(value) { + this._frameGraphTask.useFloat32TextureType = value; + } + /** Sets the texture type to Red */ + get useRedTextureFormat() { + return this._frameGraphTask.useRedTextureFormat; + } + set useRedTextureFormat(value) { + this._frameGraphTask.useRedTextureFormat = value; + } + /** Sets the bias */ + get bias() { + return this._frameGraphTask.bias; + } + set bias(value) { + this._frameGraphTask.bias = value; + } + /** Sets the normal bias */ + get normalBias() { + return this._frameGraphTask.normalBias; + } + set normalBias(value) { + this._frameGraphTask.normalBias = value; + } + /** Sets the darkness of the shadows */ + get darkness() { + return this._frameGraphTask.darkness; + } + set darkness(value) { + this._frameGraphTask.darkness = value; + } + /** Sets the filter method */ + get filter() { + return this._frameGraphTask.filter; + } + set filter(value) { + this._frameGraphTask.filter = value; + } + /** Sets the filter quality (for PCF and PCSS) */ + get filteringQuality() { + return this._frameGraphTask.filteringQuality; + } + set filteringQuality(value) { + this._frameGraphTask.filteringQuality = value; + } + /** Gets or sets the ability to have transparent shadow */ + get transparencyShadow() { + return this._frameGraphTask.transparencyShadow; + } + set transparencyShadow(value) { + this._frameGraphTask.transparencyShadow = value; + } + /** Enables or disables shadows with varying strength based on the transparency */ + get enableSoftTransparentShadow() { + return this._frameGraphTask.enableSoftTransparentShadow; + } + set enableSoftTransparentShadow(value) { + this._frameGraphTask.enableSoftTransparentShadow = value; + } + /** If this is true, use the opacity texture's alpha channel for transparent shadows instead of the diffuse one */ + get useOpacityTextureForTransparentShadow() { + return this._frameGraphTask.useOpacityTextureForTransparentShadow; + } + set useOpacityTextureForTransparentShadow(value) { + this._frameGraphTask.useOpacityTextureForTransparentShadow = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphBaseShadowGeneratorBlock"; + } + /** + * Gets the light input component + */ + get light() { + return this._inputs[0]; + } + /** + * Gets the objects input component + */ + get objects() { + return this._inputs[1]; + } + /** + * Gets the camera input component + */ + get camera() { + return this._inputs[2]; + } + /** + * Gets the shadow generator component + */ + get generator() { + return this._outputs[0]; + } + /** + * Gets the output texture component + */ + get output() { + return this._outputs[1]; + } + _buildBlock(state) { + super._buildBlock(state); + this._frameGraphTask.light = this.light.connectedPoint?.value; + this._frameGraphTask.objectList = this.objects.connectedPoint?.value; + this._frameGraphTask.camera = this.camera.connectedPoint?.value; + // Important: the shadow generator object is created by the task when we set the light, that's why we must set generator.value after setting the light! + this.generator.value = this._frameGraphTask; + this.output.value = this._frameGraphTask.outputTexture; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.mapSize = ${this.mapSize};`); + codes.push(`${this._codeVariableName}.useFloat32TextureType = ${this.useFloat32TextureType};`); + codes.push(`${this._codeVariableName}.useRedTextureFormat = ${this.useRedTextureFormat};`); + codes.push(`${this._codeVariableName}.bias = ${this.bias};`); + codes.push(`${this._codeVariableName}.normalBias = ${this.normalBias};`); + codes.push(`${this._codeVariableName}.darkness = ${this.darkness};`); + codes.push(`${this._codeVariableName}.filter = ${this.filter};`); + codes.push(`${this._codeVariableName}.filteringQuality = ${this.filteringQuality};`); + codes.push(`${this._codeVariableName}.transparencyShadow = ${this.transparencyShadow};`); + codes.push(`${this._codeVariableName}.enableSoftTransparentShadow = ${this.enableSoftTransparentShadow};`); + codes.push(`${this._codeVariableName}.useOpacityTextureForTransparentShadow = ${this.useOpacityTextureForTransparentShadow};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.mapSize = this.mapSize; + serializationObject.useFloat32TextureType = this.useFloat32TextureType; + serializationObject.useRedTextureFormat = this.useRedTextureFormat; + serializationObject.bias = this.bias; + serializationObject.normalBias = this.normalBias; + serializationObject.darkness = this.darkness; + serializationObject.filter = this.filter; + serializationObject.filteringQuality = this.filteringQuality; + serializationObject.transparencyShadow = this.transparencyShadow; + serializationObject.enableSoftTransparentShadow = this.enableSoftTransparentShadow; + serializationObject.useOpacityTextureForTransparentShadow = this.useOpacityTextureForTransparentShadow; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.mapSize = serializationObject.mapSize; + this.useFloat32TextureType = serializationObject.useFloat32TextureType; + this.useRedTextureFormat = serializationObject.useRedTextureFormat; + this.bias = serializationObject.bias; + this.normalBias = serializationObject.normalBias; + this.darkness = serializationObject.darkness; + this.filter = serializationObject.filter; + this.filteringQuality = serializationObject.filteringQuality; + this.transparencyShadow = serializationObject.transparencyShadow; + this.enableSoftTransparentShadow = serializationObject.enableSoftTransparentShadow; + this.useOpacityTextureForTransparentShadow = serializationObject.useOpacityTextureForTransparentShadow; + } +} +__decorate([ + editableInPropertyPage("Map size", 4 /* PropertyTypeForEdition.List */, "PROPERTIES", { + options: [ + { label: "128", value: 128 }, + { label: "256", value: 256 }, + { label: "512", value: 512 }, + { label: "1024", value: 1024 }, + { label: "2048", value: 2048 }, + { label: "4096", value: 4096 }, + { label: "8192", value: 8192 }, + ], + }) +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "mapSize", null); +__decorate([ + editableInPropertyPage("Use 32 bits float texture type", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "useFloat32TextureType", null); +__decorate([ + editableInPropertyPage("Use red texture format", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "useRedTextureFormat", null); +__decorate([ + editableInPropertyPage("Bias", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0, max: 1 }) +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "bias", null); +__decorate([ + editableInPropertyPage("Normal bias", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0, max: 1 }) +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "normalBias", null); +__decorate([ + editableInPropertyPage("Darkness", 1 /* PropertyTypeForEdition.Float */, "PROPERTIES", { min: 0, max: 1 }) +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "darkness", null); +__decorate([ + editableInPropertyPage("Filter", 4 /* PropertyTypeForEdition.List */, "PROPERTIES", { + options: [ + { label: "None", value: ShadowGenerator.FILTER_NONE }, + { label: "Exponential", value: ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP }, + { label: "Poisson Sampling", value: ShadowGenerator.FILTER_POISSONSAMPLING }, + { label: "Blur exponential", value: ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP }, + { label: "Close exponential", value: ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP }, + { label: "Blur close exponential", value: ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP }, + { label: "PCF", value: ShadowGenerator.FILTER_PCF }, + { label: "PCSS", value: ShadowGenerator.FILTER_PCSS }, + ], + }) +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "filter", null); +__decorate([ + editableInPropertyPage("Filter quality", 4 /* PropertyTypeForEdition.List */, "PROPERTIES", { + options: [ + { label: "Low", value: ShadowGenerator.QUALITY_LOW }, + { label: "Medium", value: ShadowGenerator.QUALITY_MEDIUM }, + { label: "High", value: ShadowGenerator.QUALITY_HIGH }, + ], + }) +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "filteringQuality", null); +__decorate([ + editableInPropertyPage("Transparency shadow", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "transparencyShadow", null); +__decorate([ + editableInPropertyPage("Enable soft transparent shadows", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "enableSoftTransparentShadow", null); +__decorate([ + editableInPropertyPage("Use opacity texture for transparent shadows", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "useOpacityTextureForTransparentShadow", null); + +/** + * Block that generates shadows through a shadow generator + */ +class NodeRenderGraphCascadedShadowGeneratorBlock extends NodeRenderGraphBaseShadowGeneratorBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphCascadedShadowGeneratorBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._frameGraphTask = new FrameGraphCascadedShadowGeneratorTask(this.name, frameGraph, scene); + } + /** Sets the number of cascades */ + get numCascades() { + return this._frameGraphTask.numCascades; + } + set numCascades(value) { + this._frameGraphTask.numCascades = value; + } + /** Gets or sets a value indicating whether the shadow generator should display the cascades. */ + get debug() { + return this._frameGraphTask.debug; + } + set debug(value) { + this._frameGraphTask.debug = value; + } + /** Gets or sets a value indicating whether the shadow generator should stabilize the cascades. */ + get stabilizeCascades() { + return this._frameGraphTask.stabilizeCascades; + } + set stabilizeCascades(value) { + this._frameGraphTask.stabilizeCascades = value; + } + /** Gets or sets the lambda parameter of the shadow generator. */ + get lambda() { + return this._frameGraphTask.lambda; + } + set lambda(value) { + this._frameGraphTask.lambda = value; + } + /** Gets or sets the cascade blend percentage. */ + get cascadeBlendPercentage() { + return this._frameGraphTask.cascadeBlendPercentage; + } + set cascadeBlendPercentage(value) { + this._frameGraphTask.cascadeBlendPercentage = value; + } + /** Gets or sets a value indicating whether the shadow generator should use depth clamping. */ + get depthClamp() { + return this._frameGraphTask.depthClamp; + } + set depthClamp(value) { + this._frameGraphTask.depthClamp = value; + } + /** Gets or sets a value indicating whether the shadow generator should automatically calculate the depth bounds. */ + get autoCalcDepthBounds() { + return this._frameGraphTask.autoCalcDepthBounds; + } + set autoCalcDepthBounds(value) { + this._frameGraphTask.autoCalcDepthBounds = value; + } + /** Gets or sets the maximum shadow Z value. */ + get shadowMaxZ() { + return this._frameGraphTask.shadowMaxZ; + } + set shadowMaxZ(value) { + this._frameGraphTask.shadowMaxZ = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphCascadedShadowGeneratorBlock"; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.numCascades = ${this.numCascades};`); + codes.push(`${this._codeVariableName}.debug = ${this.debug};`); + codes.push(`${this._codeVariableName}.stabilizeCascades = ${this.stabilizeCascades};`); + codes.push(`${this._codeVariableName}.lambda = ${this.lambda};`); + codes.push(`${this._codeVariableName}.cascadeBlendPercentage = ${this.cascadeBlendPercentage};`); + codes.push(`${this._codeVariableName}.depthClamp = ${this.depthClamp};`); + codes.push(`${this._codeVariableName}.autoCalcDepthBounds = ${this.autoCalcDepthBounds};`); + codes.push(`${this._codeVariableName}.shadowMaxZ = ${this.shadowMaxZ};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.numCascades = this.numCascades; + serializationObject.debug = this.debug; + serializationObject.stabilizeCascades = this.stabilizeCascades; + serializationObject.lambda = this.lambda; + serializationObject.cascadeBlendPercentage = this.cascadeBlendPercentage; + serializationObject.depthClamp = this.depthClamp; + serializationObject.autoCalcDepthBounds = this.autoCalcDepthBounds; + serializationObject.shadowMaxZ = this.shadowMaxZ; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.numCascades = serializationObject.numCascades; + this.debug = serializationObject.debug; + this.stabilizeCascades = serializationObject.stabilizeCascades; + this.lambda = serializationObject.lambda; + this.cascadeBlendPercentage = serializationObject.cascadeBlendPercentage; + this.depthClamp = serializationObject.depthClamp; + this.autoCalcDepthBounds = serializationObject.autoCalcDepthBounds; + this.shadowMaxZ = serializationObject.shadowMaxZ; + } +} +__decorate([ + editableInPropertyPage("Number of cascades", 4 /* PropertyTypeForEdition.List */, "CSM PROPERTIES", { + options: [ + { label: "2", value: 2 }, + { label: "3", value: 3 }, + { label: "4", value: 4 }, + ], + }) +], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "numCascades", null); +__decorate([ + editableInPropertyPage("Debug mode", 0 /* PropertyTypeForEdition.Boolean */, "CSM PROPERTIES") +], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "debug", null); +__decorate([ + editableInPropertyPage("Stabilize cascades", 0 /* PropertyTypeForEdition.Boolean */, "CSM PROPERTIES") +], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "stabilizeCascades", null); +__decorate([ + editableInPropertyPage("Lambda", 1 /* PropertyTypeForEdition.Float */, "CSM PROPERTIES", { min: 0, max: 1 }) +], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "lambda", null); +__decorate([ + editableInPropertyPage("Cascade blend", 1 /* PropertyTypeForEdition.Float */, "CSM PROPERTIES", { min: 0, max: 1 }) +], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "cascadeBlendPercentage", null); +__decorate([ + editableInPropertyPage("Depth clamp", 0 /* PropertyTypeForEdition.Boolean */, "CSM PROPERTIES") +], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "depthClamp", null); +__decorate([ + editableInPropertyPage("Auto-Calc depth bounds", 0 /* PropertyTypeForEdition.Boolean */, "CSM PROPERTIES") +], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "autoCalcDepthBounds", null); +__decorate([ + editableInPropertyPage("Shadow maxZ", 1 /* PropertyTypeForEdition.Float */, "CSM PROPERTIES") +], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "shadowMaxZ", null); +RegisterClass("BABYLON.NodeRenderGraphCascadedShadowGeneratorBlock", NodeRenderGraphCascadedShadowGeneratorBlock); + +const clearColors = [new Color4(0, 0, 0, 0), new Color4(1, 1, 1, 1), new Color4(1e8, 1e8, 1e8, 1e8)]; +/** + * Task used to render geometry to a set of textures. + */ +class FrameGraphGeometryRendererTask extends FrameGraphTask { + /** + * Gets or sets the camera used for rendering. + */ + get camera() { + return this._camera; + } + set camera(camera) { + this._camera = camera; + this._renderer.activeCamera = this.camera; + } + /** + * Whether to reverse culling (default is false). + */ + get reverseCulling() { + return this._reverseCulling; + } + set reverseCulling(value) { + this._reverseCulling = value; + const configuration = MaterialHelperGeometryRendering.GetConfiguration(this._renderer.renderPassId); + if (configuration) { + configuration.reverseCulling = value; + } + } + /** + * The object renderer used by the geometry renderer task. + */ + get objectRenderer() { + return this._renderer; + } + /** + * Gets or sets the name of the task. + */ + get name() { + return this._name; + } + set name(value) { + this._name = value; + if (this._renderer) { + this._renderer.name = value; + } + } + /** + * Constructs a new geometry renderer task. + * @param name The name of the task. + * @param frameGraph The frame graph the task belongs to. + * @param scene The scene the frame graph is associated with. + * @param options The options of the object renderer. + */ + constructor(name, frameGraph, scene, options) { + super(name, frameGraph); + /** + * Whether depth testing is enabled (default is true). + */ + this.depthTest = true; + /** + * Whether depth writing is enabled (default is true). + */ + this.depthWrite = true; + /** + * The size of the output textures (default is 100% of the back buffer texture size). + */ + this.size = { width: 100, height: 100 }; + /** + * Whether the size is a percentage of the back buffer size (default is true). + */ + this.sizeIsPercentage = true; + /** + * The number of samples to use for the output textures (default is 1). + */ + this.samples = 1; + this._reverseCulling = false; + /** + * Indicates if a mesh shouldn't be rendered when its material has depth write disabled (default is true). + */ + this.dontRenderWhenMaterialDepthWriteIsDisabled = true; + /** + * The list of texture descriptions used by the geometry renderer task. + */ + this.textureDescriptions = []; + this._scene = scene; + this._engine = this._scene.getEngine(); + this._renderer = new ObjectRenderer(name, scene, options); + this._renderer.renderSprites = false; + this._renderer.renderParticles = false; + this._renderer.customIsReadyFunction = (mesh, refreshRate, preWarm) => { + if (this.dontRenderWhenMaterialDepthWriteIsDisabled && mesh.material && mesh.material.disableDepthWrite) { + return !!preWarm; + } + return mesh.isReady(refreshRate === 0); + }; + this._renderer.onBeforeRenderingManagerRenderObservable.add(() => { + if (!this._renderer.options.doNotChangeAspectRatio) { + scene.updateTransformMatrix(true); + } + }); + this.name = name; + this._clearAttachmentsLayout = new Map(); + this._allAttachmentsLayout = []; + this.outputDepthTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.geometryViewDepthTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.geometryScreenDepthTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.geometryViewNormalTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.geometryWorldNormalTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.geometryLocalPositionTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.geometryWorldPositionTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.geometryAlbedoTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.geometryReflectivityTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.geometryVelocityTexture = this._frameGraph.textureManager.createDanglingHandle(); + this.geometryLinearVelocityTexture = this._frameGraph.textureManager.createDanglingHandle(); + } + /** + * Gets the list of excluded meshes from the velocity texture. + */ + get excludedSkinnedMeshFromVelocityTexture() { + return MaterialHelperGeometryRendering.GetConfiguration(this._renderer.renderPassId).excludedSkinnedMesh; + } + isReady() { + return this._renderer.isReadyForRendering(this._textureWidth, this._textureHeight); + } + record() { + if (this.textureDescriptions.length === 0 || this.objectList === undefined) { + throw new Error(`FrameGraphGeometryRendererTask ${this.name}: object list and at least one geometry texture description must be provided`); + } + // Make sure the renderList / particleSystemList are set when FrameGraphGeometryRendererTask.isReady() is called! + this._renderer.renderList = this.objectList.meshes; + this._renderer.particleSystemList = this.objectList.particleSystems; + const outputTextureHandle = this._createMultiRenderTargetTexture(); + const depthEnabled = this._checkDepthTextureCompatibility(); + this._buildClearAttachmentsLayout(); + this._registerForRenderPassId(this._renderer.renderPassId); + const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(outputTextureHandle[0]); + this._textureWidth = outputTextureDescription.size.width; + this._textureHeight = outputTextureDescription.size.height; + // Create pass + MaterialHelperGeometryRendering.MarkAsDirty(this._renderer.renderPassId, this.objectList.meshes || this._scene.meshes); + const pass = this._frameGraph.addRenderPass(this.name); + pass.setRenderTarget(outputTextureHandle); + for (let i = 0; i < this.textureDescriptions.length; i++) { + const description = this.textureDescriptions[i]; + const handle = outputTextureHandle[i]; + const index = MaterialHelperGeometryRendering.GeometryTextureDescriptions.findIndex((f) => f.type === description.type); + const geometryDescription = MaterialHelperGeometryRendering.GeometryTextureDescriptions[index]; + switch (geometryDescription.type) { + case 5: + this._frameGraph.textureManager.resolveDanglingHandle(this.geometryViewDepthTexture, handle); + break; + case 10: + this._frameGraph.textureManager.resolveDanglingHandle(this.geometryScreenDepthTexture, handle); + break; + case 6: + this._frameGraph.textureManager.resolveDanglingHandle(this.geometryViewNormalTexture, handle); + break; + case 8: + this._frameGraph.textureManager.resolveDanglingHandle(this.geometryWorldNormalTexture, handle); + break; + case 9: + this._frameGraph.textureManager.resolveDanglingHandle(this.geometryLocalPositionTexture, handle); + break; + case 1: + this._frameGraph.textureManager.resolveDanglingHandle(this.geometryWorldPositionTexture, handle); + break; + case 12: + this._frameGraph.textureManager.resolveDanglingHandle(this.geometryAlbedoTexture, handle); + break; + case 3: + this._frameGraph.textureManager.resolveDanglingHandle(this.geometryReflectivityTexture, handle); + break; + case 2: + this._frameGraph.textureManager.resolveDanglingHandle(this.geometryVelocityTexture, handle); + break; + case 11: + this._frameGraph.textureManager.resolveDanglingHandle(this.geometryLinearVelocityTexture, handle); + break; + } + } + pass.setRenderTargetDepth(this.depthTexture); + pass.setExecuteFunc((context) => { + this._renderer.renderList = this.objectList.meshes; + this._renderer.particleSystemList = this.objectList.particleSystems; + context.setDepthStates(this.depthTest && depthEnabled, this.depthWrite && depthEnabled); + this._clearAttachmentsLayout.forEach((layout, clearType) => { + context.clearColorAttachments(clearColors[clearType], layout); + }); + context.bindAttachments(this._allAttachmentsLayout); + context.render(this._renderer, this._textureWidth, this._textureHeight); + }); + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.setRenderTarget(outputTextureHandle); + passDisabled.setRenderTargetDepth(this.depthTexture); + passDisabled.setExecuteFunc((_context) => { }); + } + dispose() { + MaterialHelperGeometryRendering.DeleteConfiguration(this._renderer.renderPassId); + this._renderer.dispose(); + super.dispose(); + } + _createMultiRenderTargetTexture() { + const types = []; + const formats = []; + const labels = []; + const useSRGBBuffers = []; + for (let i = 0; i < this.textureDescriptions.length; i++) { + const description = this.textureDescriptions[i]; + const index = MaterialHelperGeometryRendering.GeometryTextureDescriptions.findIndex((f) => f.type === description.type); + if (index === -1) { + throw new Error(`FrameGraphGeometryRendererTask ${this.name}: unknown texture type ${description.type}`); + } + types[i] = description.textureType; + formats[i] = description.textureFormat; + labels[i] = MaterialHelperGeometryRendering.GeometryTextureDescriptions[index].name; + useSRGBBuffers[i] = false; + } + const baseHandle = this._frameGraph.textureManager.createRenderTargetTexture(this.name, { + size: this.size, + sizeIsPercentage: this.sizeIsPercentage, + options: { + createMipMaps: false, + samples: this.samples, + types, + formats, + useSRGBBuffers, + labels, + }, + }); + const handles = []; + for (let i = 0; i < this.textureDescriptions.length; i++) { + handles.push(baseHandle + i); + } + return handles; + } + _checkDepthTextureCompatibility() { + let depthEnabled = false; + if (this.depthTexture !== undefined) { + if (this.depthTexture === backbufferDepthStencilTextureHandle) { + throw new Error(`FrameGraphGeometryRendererTask ${this.name}: the depth/stencil back buffer is not allowed as a depth texture`); + } + const depthTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.depthTexture); + if (depthTextureDescription.options.samples !== this.samples) { + throw new Error(`FrameGraphGeometryRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`); + } + this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture, this.depthTexture); + depthEnabled = true; + } + return depthEnabled; + } + _buildClearAttachmentsLayout() { + const clearAttachmentsLayout = new Map(); + const allAttachmentsLayout = []; + for (let i = 0; i < this.textureDescriptions.length; i++) { + const description = this.textureDescriptions[i]; + const index = MaterialHelperGeometryRendering.GeometryTextureDescriptions.findIndex((f) => f.type === description.type); + const geometryDescription = MaterialHelperGeometryRendering.GeometryTextureDescriptions[index]; + let layout = clearAttachmentsLayout.get(geometryDescription.clearType); + if (layout === undefined) { + layout = []; + clearAttachmentsLayout.set(geometryDescription.clearType, layout); + for (let j = 0; j < i; j++) { + layout[j] = false; + } + } + clearAttachmentsLayout.forEach((layout, clearType) => { + layout.push(clearType === geometryDescription.clearType); + }); + allAttachmentsLayout.push(true); + } + this._clearAttachmentsLayout = new Map(); + clearAttachmentsLayout.forEach((layout, clearType) => { + this._clearAttachmentsLayout.set(clearType, this._engine.buildTextureLayout(layout)); + }); + this._allAttachmentsLayout = this._engine.buildTextureLayout(allAttachmentsLayout); + } + _registerForRenderPassId(renderPassId) { + const configuration = MaterialHelperGeometryRendering.CreateConfiguration(renderPassId); + for (let i = 0; i < this.textureDescriptions.length; i++) { + const description = this.textureDescriptions[i]; + const index = MaterialHelperGeometryRendering.GeometryTextureDescriptions.findIndex((f) => f.type === description.type); + const geometryDescription = MaterialHelperGeometryRendering.GeometryTextureDescriptions[index]; + configuration.defines[geometryDescription.defineIndex] = i; + } + configuration.reverseCulling = this.reverseCulling; + } +} + +/** + * Block that render geometry of objects to a multi render target + */ +class NodeRenderGraphGeometryRendererBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphGeometryRendererBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param doNotChangeAspectRatio True (default) to not change the aspect ratio of the scene in the RTT + */ + constructor(name, frameGraph, scene, doNotChangeAspectRatio = true) { + super(name, frameGraph, scene); + // View depth + this.viewDepthFormat = 6; + this.viewDepthType = 1; + // Screen depth + this.screenDepthFormat = 6; + this.screenDepthType = 1; + // View normal + this.viewNormalFormat = 5; + this.viewNormalType = 2; + // World normal + this.worldNormalFormat = 5; + this.worldNormalType = 0; + // Local position + this.localPositionFormat = 5; + this.localPositionType = 2; + // World Position + this.worldPositionFormat = 5; + this.worldPositionType = 2; + // Albedo + this.albedoFormat = 5; + this.albedoType = 0; + // Reflectivity + this.reflectivityFormat = 5; + this.reflectivityType = 0; + // Velocity + this.velocityFormat = 5; + this.velocityType = 0; + // Linear velocity + this.linearVelocityFormat = 5; + this.linearVelocityType = 0; + this._additionalConstructionParameters = [doNotChangeAspectRatio]; + this.registerInput("depth", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera); + this.registerInput("objects", NodeRenderGraphBlockConnectionPointTypes.ObjectList); + this._addDependenciesInput(); + this.registerOutput("outputDepth", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.registerOutput("geomViewDepth", NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth); + this.registerOutput("geomScreenDepth", NodeRenderGraphBlockConnectionPointTypes.TextureScreenDepth); + this.registerOutput("geomViewNormal", NodeRenderGraphBlockConnectionPointTypes.TextureViewNormal); + this.registerOutput("geomWorldNormal", NodeRenderGraphBlockConnectionPointTypes.TextureWorldNormal); + this.registerOutput("geomLocalPosition", NodeRenderGraphBlockConnectionPointTypes.TextureLocalPosition); + this.registerOutput("geomWorldPosition", NodeRenderGraphBlockConnectionPointTypes.TextureWorldPosition); + this.registerOutput("geomAlbedo", NodeRenderGraphBlockConnectionPointTypes.TextureAlbedo); + this.registerOutput("geomReflectivity", NodeRenderGraphBlockConnectionPointTypes.TextureReflectivity); + this.registerOutput("geomVelocity", NodeRenderGraphBlockConnectionPointTypes.TextureVelocity); + this.registerOutput("geomLinearVelocity", NodeRenderGraphBlockConnectionPointTypes.TextureLinearVelocity); + this.depth.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureDepthStencilAttachment | NodeRenderGraphBlockConnectionPointTypes.TextureBackBufferDepthStencilAttachment); + this.outputDepth._typeConnectionSource = this.depth; + this._frameGraphTask = new FrameGraphGeometryRendererTask(this.name, frameGraph, scene, { doNotChangeAspectRatio }); + } + /** Indicates if depth testing must be enabled or disabled */ + get depthTest() { + return this._frameGraphTask.depthTest; + } + set depthTest(value) { + this._frameGraphTask.depthTest = value; + } + /** Indicates if depth writing must be enabled or disabled */ + get depthWrite() { + return this._frameGraphTask.depthWrite; + } + set depthWrite(value) { + this._frameGraphTask.depthWrite = value; + } + /** True (default) to not change the aspect ratio of the scene in the RTT */ + get doNotChangeAspectRatio() { + return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio; + } + set doNotChangeAspectRatio(value) { + const disabled = this._frameGraphTask.disabled; + const depthTest = this.depthTest; + const depthWrite = this.depthWrite; + const width = this.width; + const height = this.height; + const sizeInPercentage = this.sizeInPercentage; + const samples = this.samples; + const reverseCulling = this.reverseCulling; + const dontRenderWhenMaterialDepthWriteIsDisabled = this.dontRenderWhenMaterialDepthWriteIsDisabled; + this._frameGraphTask.dispose(); + this._frameGraphTask = new FrameGraphGeometryRendererTask(this.name, this._frameGraph, this._scene, { doNotChangeAspectRatio: value }); + this._additionalConstructionParameters = [value]; + this.depthTest = depthTest; + this.depthWrite = depthWrite; + this.width = width; + this.height = height; + this.sizeInPercentage = sizeInPercentage; + this.samples = samples; + this.reverseCulling = reverseCulling; + this.dontRenderWhenMaterialDepthWriteIsDisabled = dontRenderWhenMaterialDepthWriteIsDisabled; + this._frameGraphTask.disabled = disabled; + } + /** Width of the geometry texture */ + get width() { + return this._frameGraphTask.size.width; + } + set width(value) { + this._frameGraphTask.size.width = value; + } + /** Height of the geometry texture */ + get height() { + return this._frameGraphTask.size.height; + } + set height(value) { + this._frameGraphTask.size.height = value; + } + /** Indicates if the geometry texture width and height are percentages or absolute values */ + get sizeInPercentage() { + return this._frameGraphTask.sizeIsPercentage; + } + set sizeInPercentage(value) { + this._frameGraphTask.sizeIsPercentage = value; + } + /** Number of samples of the geometry texture */ + get samples() { + return this._frameGraphTask.samples; + } + set samples(value) { + this._frameGraphTask.samples = value; + } + /** Indicates if culling must be reversed */ + get reverseCulling() { + return this._frameGraphTask.reverseCulling; + } + set reverseCulling(value) { + this._frameGraphTask.reverseCulling = value; + } + /** Indicates if a mesh shouldn't be rendered when its material has depth write disabled */ + get dontRenderWhenMaterialDepthWriteIsDisabled() { + return this._frameGraphTask.dontRenderWhenMaterialDepthWriteIsDisabled; + } + set dontRenderWhenMaterialDepthWriteIsDisabled(value) { + this._frameGraphTask.dontRenderWhenMaterialDepthWriteIsDisabled = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphGeometryRendererBlock"; + } + /** + * Gets the depth texture input component + */ + get depth() { + return this._inputs[0]; + } + /** + * Gets the camera input component + */ + get camera() { + return this._inputs[1]; + } + /** + * Gets the objects input component + */ + get objects() { + return this._inputs[2]; + } + /** + * Gets the output depth component + */ + get outputDepth() { + return this._outputs[0]; + } + /** + * Gets the geometry view depth component + */ + get geomViewDepth() { + return this._outputs[1]; + } + /** + * Gets the geometry screen depth component + */ + get geomScreenDepth() { + return this._outputs[2]; + } + /** + * Gets the geometry view normal component + */ + get geomViewNormal() { + return this._outputs[3]; + } + /** + * Gets the world geometry normal component + */ + get geomWorldNormal() { + return this._outputs[4]; + } + /** + * Gets the geometry local position component + */ + get geomLocalPosition() { + return this._outputs[5]; + } + /** + * Gets the geometry world position component + */ + get geomWorldPosition() { + return this._outputs[6]; + } + /** + * Gets the geometry albedo component + */ + get geomAlbedo() { + return this._outputs[7]; + } + /** + * Gets the geometry reflectivity component + */ + get geomReflectivity() { + return this._outputs[8]; + } + /** + * Gets the geometry velocity component + */ + get geomVelocity() { + return this._outputs[9]; + } + /** + * Gets the geometry linear velocity component + */ + get geomLinearVelocity() { + return this._outputs[10]; + } + _buildBlock(state) { + super._buildBlock(state); + const textureActivation = [ + this.geomViewDepth.isConnected, + this.geomScreenDepth.isConnected, + this.geomViewNormal.isConnected, + this.geomWorldNormal.isConnected, + this.geomLocalPosition.isConnected, + this.geomWorldPosition.isConnected, + this.geomAlbedo.isConnected, + this.geomReflectivity.isConnected, + this.geomVelocity.isConnected, + this.geomLinearVelocity.isConnected, + ]; + if (textureActivation.every((t) => !t)) { + throw new Error("NodeRenderGraphGeometryRendererBlock: At least one output geometry buffer must be connected"); + } + this.outputDepth.value = this._frameGraphTask.outputDepthTexture; + this.geomViewDepth.value = this._frameGraphTask.geometryViewDepthTexture; + this.geomScreenDepth.value = this._frameGraphTask.geometryScreenDepthTexture; + this.geomViewNormal.value = this._frameGraphTask.geometryViewNormalTexture; + this.geomWorldNormal.value = this._frameGraphTask.geometryWorldNormalTexture; + this.geomLocalPosition.value = this._frameGraphTask.geometryLocalPositionTexture; + this.geomWorldPosition.value = this._frameGraphTask.geometryWorldPositionTexture; + this.geomAlbedo.value = this._frameGraphTask.geometryAlbedoTexture; + this.geomReflectivity.value = this._frameGraphTask.geometryReflectivityTexture; + this.geomVelocity.value = this._frameGraphTask.geometryVelocityTexture; + this.geomLinearVelocity.value = this._frameGraphTask.geometryLinearVelocityTexture; + this._frameGraphTask.depthTexture = this.depth.connectedPoint?.value; + this._frameGraphTask.camera = this.camera.connectedPoint?.value; + this._frameGraphTask.objectList = this.objects.connectedPoint?.value; + this._frameGraphTask.textureDescriptions = []; + const textureFormats = [ + this.viewDepthFormat, + this.screenDepthFormat, + this.viewNormalFormat, + this.worldNormalFormat, + this.localPositionFormat, + this.worldPositionFormat, + this.albedoFormat, + this.reflectivityFormat, + this.velocityFormat, + this.linearVelocityFormat, + ]; + const textureTypes = [ + this.viewDepthType, + this.screenDepthType, + this.viewNormalType, + this.worldNormalType, + this.localPositionType, + this.worldPositionType, + this.albedoType, + this.reflectivityType, + this.velocityType, + this.linearVelocityType, + ]; + const bufferTypes = [ + 5, + 10, + 6, + 8, + 9, + 1, + 12, + 3, + 2, + 11, + ]; + for (let i = 0; i < textureActivation.length; i++) { + if (textureActivation[i]) { + this._frameGraphTask.textureDescriptions.push({ + textureFormat: textureFormats[i], + textureType: textureTypes[i], + type: bufferTypes[i], + }); + } + } + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.depthTest = ${this.depthTest};`); + codes.push(`${this._codeVariableName}.depthWrite = ${this.depthWrite};`); + codes.push(`${this._codeVariableName}.samples = ${this.samples};`); + codes.push(`${this._codeVariableName}.reverseCulling = ${this.reverseCulling};`); + codes.push(`${this._codeVariableName}.dontRenderWhenMaterialDepthWriteIsDisabled = ${this.dontRenderWhenMaterialDepthWriteIsDisabled};`); + codes.push(`${this._codeVariableName}.viewDepthFormat = ${this.viewDepthFormat};`); + codes.push(`${this._codeVariableName}.viewDepthType = ${this.viewDepthType};`); + codes.push(`${this._codeVariableName}.screenDepthFormat = ${this.screenDepthFormat};`); + codes.push(`${this._codeVariableName}.screenDepthType = ${this.screenDepthType};`); + codes.push(`${this._codeVariableName}.localPositionFormat = ${this.localPositionFormat};`); + codes.push(`${this._codeVariableName}.localPositionType = ${this.localPositionType};`); + codes.push(`${this._codeVariableName}.worldPositionFormat = ${this.worldPositionFormat};`); + codes.push(`${this._codeVariableName}.worldPositionType = ${this.worldPositionType};`); + codes.push(`${this._codeVariableName}.viewNormalFormat = ${this.viewNormalFormat};`); + codes.push(`${this._codeVariableName}.viewNormalType = ${this.viewNormalType};`); + codes.push(`${this._codeVariableName}.worldNormalFormat = ${this.worldNormalFormat};`); + codes.push(`${this._codeVariableName}.worldNormalType = ${this.worldNormalType};`); + codes.push(`${this._codeVariableName}.albedoFormat = ${this.albedoFormat};`); + codes.push(`${this._codeVariableName}.albedoType = ${this.albedoType};`); + codes.push(`${this._codeVariableName}.reflectivityFormat = ${this.reflectivityFormat};`); + codes.push(`${this._codeVariableName}.reflectivityType = ${this.reflectivityType};`); + codes.push(`${this._codeVariableName}.velocityFormat = ${this.velocityFormat};`); + codes.push(`${this._codeVariableName}.velocityType = ${this.velocityType};`); + codes.push(`${this._codeVariableName}.linearVelocityFormat = ${this.linearVelocityFormat};`); + codes.push(`${this._codeVariableName}.linearVelocityType = ${this.linearVelocityType};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.depthTest = this.depthTest; + serializationObject.depthWrite = this.depthWrite; + serializationObject.samples = this.samples; + serializationObject.reverseCulling = this.reverseCulling; + serializationObject.dontRenderWhenMaterialDepthWriteIsDisabled = this.dontRenderWhenMaterialDepthWriteIsDisabled; + serializationObject.viewDepthFormat = this.viewDepthFormat; + serializationObject.viewDepthType = this.viewDepthType; + serializationObject.screenDepthFormat = this.screenDepthFormat; + serializationObject.screenDepthType = this.screenDepthType; + serializationObject.localPositionFormat = this.localPositionFormat; + serializationObject.localPositionType = this.localPositionType; + serializationObject.worldPositionFormat = this.worldPositionFormat; + serializationObject.worldPositionType = this.worldPositionType; + serializationObject.viewNormalFormat = this.viewNormalFormat; + serializationObject.viewNormalType = this.viewNormalType; + serializationObject.worldNormalFormat = this.worldNormalFormat; + serializationObject.worldNormalType = this.worldNormalType; + serializationObject.albedoFormat = this.albedoFormat; + serializationObject.albedoType = this.albedoType; + serializationObject.reflectivityFormat = this.reflectivityFormat; + serializationObject.reflectivityType = this.reflectivityType; + serializationObject.velocityFormat = this.velocityFormat; + serializationObject.velocityType = this.velocityType; + serializationObject.linearVelocityFormat = this.linearVelocityFormat; + serializationObject.linearVelocityType = this.linearVelocityType; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.depthTest = serializationObject.depthTest; + this.depthWrite = serializationObject.depthWrite; + this.samples = serializationObject.samples; + this.reverseCulling = serializationObject.reverseCulling; + this.dontRenderWhenMaterialDepthWriteIsDisabled = serializationObject.dontRenderWhenMaterialDepthWriteIsDisabled; + this.viewDepthFormat = serializationObject.viewDepthFormat; + this.viewDepthType = serializationObject.viewDepthType; + this.screenDepthFormat = serializationObject.screenDepthFormat; + this.screenDepthType = serializationObject.screenDepthType; + this.localPositionFormat = serializationObject.localPositionFormat; + this.localPositionType = serializationObject.localPositionType; + this.worldPositionFormat = serializationObject.worldPositionFormat; + this.worldPositionType = serializationObject.worldPositionType; + this.viewNormalFormat = serializationObject.viewNormalFormat; + this.viewNormalType = serializationObject.viewNormalType; + this.worldNormalFormat = serializationObject.worldNormalFormat; + this.worldNormalType = serializationObject.worldNormalType; + this.albedoFormat = serializationObject.albedoFormat; + this.albedoType = serializationObject.albedoType; + this.reflectivityFormat = serializationObject.reflectivityFormat; + this.reflectivityType = serializationObject.reflectivityType; + this.velocityFormat = serializationObject.velocityFormat; + this.velocityType = serializationObject.velocityType; + this.linearVelocityFormat = serializationObject.linearVelocityFormat; + this.linearVelocityType = serializationObject.linearVelocityType; + } +} +__decorate([ + editableInPropertyPage("Depth test", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphGeometryRendererBlock.prototype, "depthTest", null); +__decorate([ + editableInPropertyPage("Depth write", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphGeometryRendererBlock.prototype, "depthWrite", null); +__decorate([ + editableInPropertyPage("Do not change aspect ratio", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphGeometryRendererBlock.prototype, "doNotChangeAspectRatio", null); +__decorate([ + editableInPropertyPage("Texture width", 2 /* PropertyTypeForEdition.Int */, "PROPERTIES") +], NodeRenderGraphGeometryRendererBlock.prototype, "width", null); +__decorate([ + editableInPropertyPage("Texture height", 2 /* PropertyTypeForEdition.Int */, "PROPERTIES") +], NodeRenderGraphGeometryRendererBlock.prototype, "height", null); +__decorate([ + editableInPropertyPage("Size is in percentage", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphGeometryRendererBlock.prototype, "sizeInPercentage", null); +__decorate([ + editableInPropertyPage("Samples", 2 /* PropertyTypeForEdition.Int */, "PROPERTIES", { min: 1, max: 8 }) +], NodeRenderGraphGeometryRendererBlock.prototype, "samples", null); +__decorate([ + editableInPropertyPage("Reverse culling", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphGeometryRendererBlock.prototype, "reverseCulling", null); +__decorate([ + editableInPropertyPage("Don't render if material depth write is disabled", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphGeometryRendererBlock.prototype, "dontRenderWhenMaterialDepthWriteIsDisabled", null); +__decorate([ + editableInPropertyPage("View depth format", 7 /* PropertyTypeForEdition.TextureFormat */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "viewDepthFormat", void 0); +__decorate([ + editableInPropertyPage("View depth type", 8 /* PropertyTypeForEdition.TextureType */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "viewDepthType", void 0); +__decorate([ + editableInPropertyPage("Screen depth format", 7 /* PropertyTypeForEdition.TextureFormat */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "screenDepthFormat", void 0); +__decorate([ + editableInPropertyPage("Screen depth type", 8 /* PropertyTypeForEdition.TextureType */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "screenDepthType", void 0); +__decorate([ + editableInPropertyPage("View normal format", 7 /* PropertyTypeForEdition.TextureFormat */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "viewNormalFormat", void 0); +__decorate([ + editableInPropertyPage("View normal type", 8 /* PropertyTypeForEdition.TextureType */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "viewNormalType", void 0); +__decorate([ + editableInPropertyPage("World normal format", 7 /* PropertyTypeForEdition.TextureFormat */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "worldNormalFormat", void 0); +__decorate([ + editableInPropertyPage("World normal type", 8 /* PropertyTypeForEdition.TextureType */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "worldNormalType", void 0); +__decorate([ + editableInPropertyPage("Local position format", 7 /* PropertyTypeForEdition.TextureFormat */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "localPositionFormat", void 0); +__decorate([ + editableInPropertyPage("Local position type", 8 /* PropertyTypeForEdition.TextureType */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "localPositionType", void 0); +__decorate([ + editableInPropertyPage("World position format", 7 /* PropertyTypeForEdition.TextureFormat */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "worldPositionFormat", void 0); +__decorate([ + editableInPropertyPage("World position type", 8 /* PropertyTypeForEdition.TextureType */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "worldPositionType", void 0); +__decorate([ + editableInPropertyPage("Albedo format", 7 /* PropertyTypeForEdition.TextureFormat */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "albedoFormat", void 0); +__decorate([ + editableInPropertyPage("Albedo type", 8 /* PropertyTypeForEdition.TextureType */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "albedoType", void 0); +__decorate([ + editableInPropertyPage("Reflectivity format", 7 /* PropertyTypeForEdition.TextureFormat */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "reflectivityFormat", void 0); +__decorate([ + editableInPropertyPage("Reflectivity type", 8 /* PropertyTypeForEdition.TextureType */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "reflectivityType", void 0); +__decorate([ + editableInPropertyPage("Velocity format", 7 /* PropertyTypeForEdition.TextureFormat */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "velocityFormat", void 0); +__decorate([ + editableInPropertyPage("Velocity type", 8 /* PropertyTypeForEdition.TextureType */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "velocityType", void 0); +__decorate([ + editableInPropertyPage("Linear velocity format", 7 /* PropertyTypeForEdition.TextureFormat */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "linearVelocityFormat", void 0); +__decorate([ + editableInPropertyPage("Linear velocity type", 8 /* PropertyTypeForEdition.TextureType */, "GEOMETRY BUFFERS") +], NodeRenderGraphGeometryRendererBlock.prototype, "linearVelocityType", void 0); +RegisterClass("BABYLON.NodeRenderGraphGeometryRendererBlock", NodeRenderGraphGeometryRendererBlock); + +/** + * Block that generate shadows through a shadow generator + */ +class NodeRenderGraphShadowGeneratorBlock extends NodeRenderGraphBaseShadowGeneratorBlock { + /** + * Create a new NodeRenderGraphShadowGeneratorBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._frameGraphTask = new FrameGraphShadowGeneratorTask(this.name, frameGraph, scene); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphShadowGeneratorBlock"; + } +} +RegisterClass("BABYLON.NodeRenderGraphShadowGeneratorBlock", NodeRenderGraphShadowGeneratorBlock); + +/** + * Class for generating 2D Halton sequences. + * From https://observablehq.com/@jrus/halton + */ +class Halton2DSequence { + /** + * Creates a new Halton2DSequence. + * @param numSamples Number of samples in the sequence. + * @param baseX The base for the x coordinate (default: 2). + * @param baseY The base for the y coordinate (default: 3). + * @param width Factor to scale the x coordinate by (default: 1). The scaling factor is 1/width. + * @param height Factor to scale the y coordinate by (default: 1). The scaling factor is 1/height. + */ + constructor(numSamples, baseX = 2, baseY = 3, width = 1, height = 1) { + this._curIndex = 0; + this._sequence = []; + this._numSamples = 0; + /** + * The x coordinate of the current sample. + */ + this.x = 0; + /** + * The y coordinate of the current sample. + */ + this.y = 0; + this._width = width; + this._height = height; + this._baseX = baseX; + this._baseY = baseY; + this._generateSequence(numSamples); + this.next(); + } + /** + * Regenerates the sequence with a new number of samples. + * @param numSamples Number of samples in the sequence. + */ + regenerate(numSamples) { + this._generateSequence(numSamples); + this.next(); + } + /** + * Sets the dimensions of the sequence. + * @param width Factor to scale the x coordinate by. The scaling factor is 1/width. + * @param height Factor to scale the y coordinate by. The scaling factor is 1/height. + */ + setDimensions(width, height) { + this._width = width; + this._height = height; + } + /** + * Advances to the next sample in the sequence. + */ + next() { + this.x = this._sequence[this._curIndex] / this._width; + this.y = this._sequence[this._curIndex + 1] / this._height; + this._curIndex += 2; + if (this._curIndex >= this._numSamples * 2) { + this._curIndex = 0; + } + } + _generateSequence(numSamples) { + this._sequence = []; + this._curIndex = 0; + this._numSamples = numSamples; + for (let i = 1; i <= numSamples; ++i) { + this._sequence.push(this._halton(i, this._baseX) - 0.5, this._halton(i, this._baseY) - 0.5); + } + } + _halton(index, base) { + let fraction = 1; + let result = 0; + while (index > 0) { + fraction /= base; + result += fraction * (index % base); + index = ~~(index / base); // floor division + } + return result; + } +} + +/** + * Simple implementation of Temporal Anti-Aliasing (TAA). + * This can be used to improve image quality for still pictures (screenshots for e.g.). + */ +class ThinTAAPostProcess extends EffectWrapper { + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => taa_fragment)); + } + else { + list.push(Promise.resolve().then(() => taa_fragment$1)); + } + } + /** + * Number of accumulated samples (default: 8) + */ + set samples(samples) { + if (this._samples === samples) { + return; + } + this._samples = samples; + this._hs.regenerate(samples); + } + get samples() { + return this._samples; + } + /** + * Whether the TAA is disabled + */ + get disabled() { + return this._disabled; + } + set disabled(value) { + if (this._disabled === value) { + return; + } + this._disabled = value; + this._reset(); + } + /** + * The width of the texture in which to render + */ + get textureWidth() { + return this._textureWidth; + } + set textureWidth(width) { + if (this._textureWidth === width) { + return; + } + this._textureWidth = width; + this._reset(); + } + /** + * The height of the texture in which to render + */ + get textureHeight() { + return this._textureHeight; + } + set textureHeight(height) { + if (this._textureHeight === height) { + return; + } + this._textureHeight = height; + this._reset(); + } + /** + * Constructs a new TAA post process + * @param name Name of the effect + * @param engine Engine to use to render the effect. If not provided, the last created engine will be used + * @param options Options to configure the effect + */ + constructor(name, engine = null, options) { + super({ + ...options, + name, + engine: engine || Engine.LastCreatedEngine, + useShaderStore: true, + useAsPostProcess: true, + fragmentShader: ThinTAAPostProcess.FragmentUrl, + uniforms: ThinTAAPostProcess.Uniforms, + samplers: ThinTAAPostProcess.Samplers, + }); + this._samples = 8; + /** + * The factor used to blend the history frame with current frame (default: 0.05) + */ + this.factor = 0.05; + this._disabled = false; + this._textureWidth = 0; + this._textureHeight = 0; + /** + * Disable TAA on camera move (default: true). + * You generally want to keep this enabled, otherwise you will get a ghost effect when the camera moves (but if it's what you want, go for it!) + */ + this.disableOnCameraMove = true; + this._firstUpdate = true; + this._hs = new Halton2DSequence(this.samples); + } + /** @internal */ + _reset() { + this._hs.setDimensions(this._textureWidth / 2, this._textureHeight / 2); + this._hs.next(); + this._firstUpdate = true; + } + updateProjectionMatrix() { + if (this.disabled) { + return; + } + if (this.camera && !this.camera.hasMoved) { + if (this.camera.mode === Camera.PERSPECTIVE_CAMERA) { + const projMat = this.camera.getProjectionMatrix(); + projMat.setRowFromFloats(2, this._hs.x, this._hs.y, projMat.m[10], projMat.m[11]); + } + else { + // We must force the update of the projection matrix so that m[12] and m[13] are recomputed, as we modified them the previous frame + const projMat = this.camera.getProjectionMatrix(true); + projMat.setRowFromFloats(3, this._hs.x + projMat.m[12], this._hs.y + projMat.m[13], projMat.m[14], projMat.m[15]); + } + } + this._hs.next(); + } + bind() { + super.bind(); + if (this.disabled) { + return; + } + const effect = this._drawWrapper.effect; + effect.setFloat("factor", (this.camera?.hasMoved && this.disableOnCameraMove) || this._firstUpdate ? 1 : this.factor); + this._firstUpdate = false; + } +} +/** + * The fragment shader url + */ +ThinTAAPostProcess.FragmentUrl = "taa"; +/** + * The list of uniforms used by the effect + */ +ThinTAAPostProcess.Uniforms = ["factor"]; +/** + * The list of samplers used by the effect + */ +ThinTAAPostProcess.Samplers = ["historySampler"]; + +/** + * Task used to render objects to a texture with Temporal Anti-Aliasing (TAA). + */ +class FrameGraphTAAObjectRendererTask extends FrameGraphObjectRendererTask { + /** + * Constructs a new TAA object renderer task. + * @param name The name of the task + * @param frameGraph The frame graph the task belongs to. + * @param scene The scene the frame graph is associated with. + * @param options The options of the object renderer. + */ + constructor(name, frameGraph, scene, options) { + super(name, frameGraph, scene, options); + this.postProcess = new ThinTAAPostProcess(`${name} post-process`, scene.getEngine()); + this._postProcessDrawWrapper = this.postProcess.drawWrapper; + } + record() { + if (this.targetTexture === undefined || this.objectList === undefined) { + throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: destinationTexture and objectList are required`); + } + if (this.targetTexture === backbufferColorTextureHandle || this.depthTexture === backbufferDepthStencilTextureHandle) { + throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: the back buffer color/depth textures are not allowed. Use regular textures instead.`); + } + // Make sure the renderList / particleSystemList are set when FrameGraphObjectRendererTask.isReady() is called! + this._renderer.renderList = this.objectList.meshes; + this._renderer.particleSystemList = this.objectList.particleSystems; + const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.targetTexture); + let depthEnabled = false; + if (this.depthTexture !== undefined) { + const depthTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.depthTexture); + if (depthTextureDescription.options.samples !== outputTextureDescription.options.samples) { + throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`); + } + depthEnabled = true; + } + this.postProcess.camera = this.camera; + this.postProcess.textureWidth = outputTextureDescription.size.width; + this.postProcess.textureHeight = outputTextureDescription.size.height; + const textureCreationOptions = { + size: outputTextureDescription.size, + options: { + createMipMaps: outputTextureDescription.options.createMipMaps, + types: [2], + formats: [5], + samples: 1, + useSRGBBuffers: [false], + creationFlags: [0], + labels: [""], + }, + sizeIsPercentage: false, + isHistoryTexture: true, + }; + const pingPongHandle = this._frameGraph.textureManager.createRenderTargetTexture(`${this.name} history`, textureCreationOptions); + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, pingPongHandle); + if (this.depthTexture !== undefined) { + this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture, this.depthTexture); + } + this._textureWidth = outputTextureDescription.size.width; + this._textureHeight = outputTextureDescription.size.height; + let pingPongRenderTargetWrapper; + this._setLightsForShadow(); + const pass = this._frameGraph.addRenderPass(this.name); + pass.setRenderTarget(this.targetTexture); + pass.setRenderTargetDepth(this.depthTexture); + pass.setExecuteFunc((context) => { + this._renderer.renderList = this.objectList.meshes; + this._renderer.particleSystemList = this.objectList.particleSystems; + this._renderer.renderInLinearSpace = this.renderInLinearSpace; + this.postProcess.updateProjectionMatrix(); + context.setDepthStates(this.depthTest && depthEnabled, this.depthWrite && depthEnabled); + // We define the active camera and transformation matrices ourselves, otherwise this will be done by calling context.render, in which case + // getProjectionMatrix will be called with a "true" parameter, forcing recalculation of the projection matrix and losing our changes. + if (!this.postProcess.disabled) { + this._scene.activeCamera = this.camera; + this._scene.setTransformMatrix(this.camera.getViewMatrix(), this.camera.getProjectionMatrix()); + } + context.render(this._renderer, this._textureWidth, this._textureHeight); + this._scene.activeCamera = null; + pingPongRenderTargetWrapper = pingPongRenderTargetWrapper || context.createRenderTarget(`${this.name} ping/pong`, pingPongHandle); + context.bindRenderTarget(pingPongRenderTargetWrapper, "frame graph - TAA merge with history texture"); + if (!this.postProcess.disabled) { + context.applyFullScreenEffect(this._postProcessDrawWrapper, () => { + this.postProcess.bind(); + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "textureSampler", this.targetTexture); + context.bindTextureHandle(this._postProcessDrawWrapper.effect, "historySampler", pingPongHandle); + }); + } + else { + context.copyTexture(this.targetTexture); + } + }); + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.setRenderTarget(this.outputTexture); + passDisabled.setRenderTargetDepth(this.depthTexture); + passDisabled.setExecuteFunc((context) => { + context.copyTexture(this.targetTexture); + }); + return pass; + } +} + +/** + * Block that render objects with temporal anti-aliasing to a render target + */ +class NodeRenderGraphTAAObjectRendererBlock extends NodeRenderGraphBaseObjectRendererBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphTAAObjectRendererBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param doNotChangeAspectRatio True (default) to not change the aspect ratio of the scene in the RTT + */ + constructor(name, frameGraph, scene, doNotChangeAspectRatio = true) { + super(name, frameGraph, scene); + this._additionalConstructionParameters = [doNotChangeAspectRatio]; + this._frameGraphTask = new FrameGraphTAAObjectRendererTask(this.name, frameGraph, scene, { doNotChangeAspectRatio }); + } + /** True (default) to not change the aspect ratio of the scene in the RTT */ + get doNotChangeAspectRatio() { + return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio; + } + set doNotChangeAspectRatio(value) { + const disabled = this._frameGraphTask.disabled; + this._frameGraphTask.dispose(); + this._frameGraphTask = new FrameGraphTAAObjectRendererTask(this.name, this._frameGraph, this._scene, { doNotChangeAspectRatio: value }); + this._additionalConstructionParameters = [value]; + this._frameGraphTask.disabled = disabled; + } + /** Number of accumulated samples */ + get samples() { + return this._frameGraphTask.postProcess.samples; + } + set samples(value) { + this._frameGraphTask.postProcess.samples = value; + } + /** The factor used to blend the history frame with current frame */ + get factor() { + return this._frameGraphTask.postProcess.factor; + } + set factor(value) { + this._frameGraphTask.postProcess.factor = value; + } + /** Indicates if depth testing must be enabled or disabled */ + get disableOnCameraMove() { + return this._frameGraphTask.postProcess.disableOnCameraMove; + } + set disableOnCameraMove(value) { + this._frameGraphTask.postProcess.disableOnCameraMove = value; + } + /** Indicates if TAA must be enabled or disabled */ + get disableTAA() { + return this._frameGraphTask.postProcess.disabled; + } + set disableTAA(value) { + this._frameGraphTask.postProcess.disabled = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphTAAObjectRendererBlock"; + } + _dumpPropertiesCode() { + const codes = []; + codes.push(`${this._codeVariableName}.doNotChangeAspectRatio = ${this.doNotChangeAspectRatio};`); + codes.push(`${this._codeVariableName}.samples = ${this.samples};`); + codes.push(`${this._codeVariableName}.factor = ${this.factor};`); + codes.push(`${this._codeVariableName}.disableOnCameraMove = ${this.disableOnCameraMove};`); + codes.push(`${this._codeVariableName}.disableTAA = ${this.disableTAA};`); + return super._dumpPropertiesCode() + codes.join("\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.doNotChangeAspectRatio = this.doNotChangeAspectRatio; + serializationObject.samples = this.samples; + serializationObject.factor = this.factor; + serializationObject.disableOnCameraMove = this.disableOnCameraMove; + serializationObject.disableTAA = this.disableTAA; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.doNotChangeAspectRatio = serializationObject.doNotChangeAspectRatio; + this.samples = serializationObject.samples; + this.factor = serializationObject.factor; + this.disableOnCameraMove = serializationObject.disableOnCameraMove; + this.disableTAA = serializationObject.disableTAA; + } +} +__decorate([ + editableInPropertyPage("Do not change aspect ratio", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphTAAObjectRendererBlock.prototype, "doNotChangeAspectRatio", null); +__decorate([ + editableInPropertyPage("Samples", 2 /* PropertyTypeForEdition.Int */, "TEMPORAL ANTI-ALIASING") +], NodeRenderGraphTAAObjectRendererBlock.prototype, "samples", null); +__decorate([ + editableInPropertyPage("Factor", 1 /* PropertyTypeForEdition.Float */, "TEMPORAL ANTI-ALIASING") +], NodeRenderGraphTAAObjectRendererBlock.prototype, "factor", null); +__decorate([ + editableInPropertyPage("Disable on camera move", 0 /* PropertyTypeForEdition.Boolean */, "TEMPORAL ANTI-ALIASING") +], NodeRenderGraphTAAObjectRendererBlock.prototype, "disableOnCameraMove", null); +__decorate([ + editableInPropertyPage("Disable TAA", 0 /* PropertyTypeForEdition.Boolean */, "TEMPORAL ANTI-ALIASING") +], NodeRenderGraphTAAObjectRendererBlock.prototype, "disableTAA", null); +RegisterClass("BABYLON.NodeRenderGraphTAAObjectRendererBlock", NodeRenderGraphTAAObjectRendererBlock); + +/** + * Task used to render an utility layer. + */ +class FrameGraphUtilityLayerRendererTask extends FrameGraphTask { + /** + * Creates a new utility layer renderer task. + * @param name The name of the task. + * @param frameGraph The frame graph the task belongs to. + * @param scene The scene the task belongs to. + * @param handleEvents If the utility layer should handle events. + */ + constructor(name, frameGraph, scene, handleEvents = true) { + super(name, frameGraph); + this.layer = new UtilityLayerRenderer(scene, handleEvents, true); + this.layer.utilityLayerScene._useCurrentFrameBuffer = true; + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + } + record() { + if (!this.targetTexture || !this.camera) { + throw new Error("FrameGraphUtilityLayerRendererTask: targetTexture and camera are required"); + } + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture); + const pass = this._frameGraph.addRenderPass(this.name); + pass.setRenderTarget(this.outputTexture); + pass.setExecuteFunc((context) => { + this.layer.setRenderCamera(this.camera); + context.render(this.layer); + }); + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.setRenderTarget(this.outputTexture); + passDisabled.setExecuteFunc((_context) => { }); + } + dispose() { + this.layer.dispose(); + super.dispose(); + } +} + +/** + * Block used to render an utility layer in the frame graph + */ +class NodeRenderGraphUtilityLayerRendererBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Creates a new NodeRenderGraphUtilityLayerRendererBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + * @param handleEvents If the utility layer should handle events. + */ + constructor(name, frameGraph, scene, handleEvents = true) { + super(name, frameGraph, scene); + this._additionalConstructionParameters = [handleEvents]; + this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera); + this._addDependenciesInput(); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAll); + this.output._typeConnectionSource = this.target; + this._frameGraphTask = new FrameGraphUtilityLayerRendererTask(name, frameGraph, scene, handleEvents); + } + _createTask(handleEvents) { + const disabled = this._frameGraphTask.disabled; + this._frameGraphTask.dispose(); + this._frameGraphTask = new FrameGraphUtilityLayerRendererTask(this.name, this._frameGraph, this._scene, handleEvents); + this._additionalConstructionParameters = [handleEvents]; + this._frameGraphTask.disabled = disabled; + } + /** If the utility layer should handle events */ + get handleEvents() { + return this._frameGraphTask.layer.handleEvents; + } + set handleEvents(value) { + this._createTask(value); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphUtilityLayerRendererBlock"; + } + /** + * Gets the target input component + */ + get target() { + return this._inputs[0]; + } + /** + * Gets the camera input component + */ + get camera() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.output.value = this._frameGraphTask.outputTexture; + this._frameGraphTask.targetTexture = this.target.connectedPoint?.value; + this._frameGraphTask.camera = this.camera.connectedPoint?.value; + } +} +__decorate([ + editableInPropertyPage("Handle events", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES") +], NodeRenderGraphUtilityLayerRendererBlock.prototype, "handleEvents", null); +RegisterClass("BABYLON.NodeRenderGraphUtilityLayerRendererBlock", NodeRenderGraphUtilityLayerRendererBlock); + +/** + * Defines a block used to teleport a value to an endpoint + */ +class NodeRenderGraphTeleportInBlock extends NodeRenderGraphBlock { + /** Gets the list of attached endpoints */ + get endpoints() { + return this._endpoints; + } + /** + * Create a new NodeRenderGraphTeleportInBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this._endpoints = []; + this._isTeleportIn = true; + this.registerInput("input", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphTeleportInBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + _dumpCode(uniqueNames, alreadyDumped) { + let codeString = super._dumpCode(uniqueNames, alreadyDumped); + for (const endpoint of this.endpoints) { + if (alreadyDumped.indexOf(endpoint) === -1) { + codeString += endpoint._dumpCode(uniqueNames, alreadyDumped); + } + } + return codeString; + } + /** + * Checks if the current block is an ancestor of a given type + * @param type defines the potential type to check + * @returns true if block is a descendant + */ + isAnAncestorOfType(type) { + if (this.getClassName() === type) { + return true; + } + for (const endpoint of this.endpoints) { + if (endpoint.isAnAncestorOfType(type)) { + return true; + } + } + return false; + } + /** + * Checks if the current block is an ancestor of a given block + * @param block defines the potential descendant block to check + * @returns true if block is a descendant + */ + isAnAncestorOf(block) { + for (const endpoint of this.endpoints) { + if (endpoint === block) { + return true; + } + if (endpoint.isAnAncestorOf(block)) { + return true; + } + } + return false; + } + /** + * Get the first descendant using a predicate + * @param predicate defines the predicate to check + * @returns descendant or null if none found + */ + getDescendantOfPredicate(predicate) { + if (predicate(this)) { + return this; + } + for (const endpoint of this.endpoints) { + const descendant = endpoint.getDescendantOfPredicate(predicate); + if (descendant) { + return descendant; + } + } + return null; + } + /** + * Add an enpoint to this block + * @param endpoint define the endpoint to attach to + */ + attachToEndpoint(endpoint) { + endpoint.detach(); + this._endpoints.push(endpoint); + endpoint._entryPoint = this; + endpoint._outputs[0]._typeConnectionSource = this._inputs[0]; + endpoint._tempEntryPointUniqueId = null; + endpoint.name = "> " + this.name; + } + /** + * Remove enpoint from this block + * @param endpoint define the endpoint to remove + */ + detachFromEndpoint(endpoint) { + const index = this._endpoints.indexOf(endpoint); + if (index !== -1) { + this._endpoints.splice(index, 1); + endpoint._outputs[0]._typeConnectionSource = null; + endpoint._entryPoint = null; + } + } + /** + * Release resources + */ + dispose() { + super.dispose(); + for (const endpoint of this._endpoints) { + this.detachFromEndpoint(endpoint); + } + this._endpoints = []; + } +} +RegisterClass("BABYLON.NodeRenderGraphTeleportInBlock", NodeRenderGraphTeleportInBlock); + +/** + * Defines a block used to receive a value from a teleport entry point + */ +class NodeRenderGraphTeleportOutBlock extends NodeRenderGraphBlock { + /** + * Create a new NodeRenderGraphTeleportOutBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + /** @internal */ + this._entryPoint = null; + /** @internal */ + this._tempEntryPointUniqueId = null; + this._isTeleportOut = true; + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + } + /** + * Gets the entry point + */ + get entryPoint() { + return this._entryPoint; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphTeleportOutBlock"; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** Detach from entry point */ + detach() { + if (!this._entryPoint) { + return; + } + this._entryPoint.detachFromEndpoint(this); + } + _buildBlock() { + // Do nothing + // All work done by the emitter + } + _customBuildStep(state) { + if (this.entryPoint) { + this.entryPoint.build(state); + } + } + _dumpCode(uniqueNames, alreadyDumped) { + let codeString = ""; + if (this.entryPoint) { + if (alreadyDumped.indexOf(this.entryPoint) === -1) { + codeString += this.entryPoint._dumpCode(uniqueNames, alreadyDumped); + } + } + return codeString + super._dumpCode(uniqueNames, alreadyDumped); + } + _dumpCodeForOutputConnections(alreadyDumped) { + let codeString = super._dumpCodeForOutputConnections(alreadyDumped); + if (this.entryPoint) { + codeString += this.entryPoint._dumpCodeForOutputConnections(alreadyDumped); + } + return codeString; + } + /** + * Clone the current block to a new identical block + * @returns a copy of the current block + */ + clone() { + const clone = super.clone(); + if (this.entryPoint) { + this.entryPoint.attachToEndpoint(clone); + } + return clone; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + if (this.entryPoint) { + codeString += `${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`; + } + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.entryPoint = this.entryPoint?.uniqueId ?? ""; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this._tempEntryPointUniqueId = serializationObject.entryPoint; + } +} +RegisterClass("BABYLON.NodeRenderGraphTeleportOutBlock", NodeRenderGraphTeleportOutBlock); + +/** + * Task used to copy a texture to another texture. + */ +class FrameGraphCopyToTextureTask extends FrameGraphTask { + /** + * Constructs a new FrameGraphCopyToTextureTask. + * @param name The name of the task. + * @param frameGraph The frame graph the task belongs to. + */ + constructor(name, frameGraph) { + super(name, frameGraph); + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + } + record() { + if (this.sourceTexture === undefined || this.targetTexture === undefined) { + throw new Error(`FrameGraphCopyToTextureTask "${this.name}": sourceTexture and targetTexture are required`); + } + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture); + const pass = this._frameGraph.addRenderPass(this.name); + pass.addDependencies(this.sourceTexture); + pass.setRenderTarget(this.outputTexture); + pass.setExecuteFunc((context) => { + context.copyTexture(this.sourceTexture); + }); + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.setRenderTarget(this.outputTexture); + passDisabled.setExecuteFunc((_context) => { }); + } +} + +/** + * Block used to copy a texture + */ +class NodeRenderGraphCopyTextureBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphCopyTextureBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("source", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this._addDependenciesInput(); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.source.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer); + this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAll); + this.output._typeConnectionSource = this.target; + this._frameGraphTask = new FrameGraphCopyToTextureTask(name, frameGraph); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphCopyTextureBlock"; + } + /** + * Gets the source input component + */ + get source() { + return this._inputs[0]; + } + /** + * Gets the target input component + */ + get target() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.output.value = this._frameGraphTask.outputTexture; // the value of the output connection point is the "output" texture of the task + this._frameGraphTask.sourceTexture = this.source.connectedPoint?.value; + this._frameGraphTask.targetTexture = this.target.connectedPoint?.value; + } +} +RegisterClass("BABYLON.NodeRenderGraphCopyTextureBlock", NodeRenderGraphCopyTextureBlock); + +/** + * Task which generates mipmaps for a texture. + */ +class FrameGraphGenerateMipMapsTask extends FrameGraphTask { + /** + * Constructs a new FrameGraphGenerateMipMapsTask. + * @param name The name of the task. + * @param frameGraph The frame graph the task belongs to. + */ + constructor(name, frameGraph) { + super(name, frameGraph); + this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); + } + record() { + if (this.targetTexture === undefined) { + throw new Error(`FrameGraphGenerateMipMapsTask ${this.name}: targetTexture is required`); + } + this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture); + const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.targetTexture); + if (!outputTextureDescription.options.createMipMaps) { + throw new Error(`FrameGraphGenerateMipMapsTask ${this.name}: targetTexture must have createMipMaps set to true`); + } + const pass = this._frameGraph.addRenderPass(this.name); + pass.setRenderTarget(this.outputTexture); + pass.setExecuteFunc((context) => { + context.generateMipMaps(); + }); + const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); + passDisabled.setRenderTarget(this.outputTexture); + passDisabled.setExecuteFunc((_context) => { }); + } +} + +/** + * Block used to generate mipmaps for a texture + */ +class NodeRenderGraphGenerateMipmapsBlock extends NodeRenderGraphBlock { + /** + * Gets the frame graph task associated with this block + */ + get task() { + return this._frameGraphTask; + } + /** + * Create a new NodeRenderGraphGenerateMipmapsBlock + * @param name defines the block name + * @param frameGraph defines the hosting frame graph + * @param scene defines the hosting scene + */ + constructor(name, frameGraph, scene) { + super(name, frameGraph, scene); + this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect); + this._addDependenciesInput(); + this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput); + this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer); + this.output._typeConnectionSource = this.target; + this._frameGraphTask = new FrameGraphGenerateMipMapsTask(name, frameGraph); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeRenderGraphGenerateMipmapsBlock"; + } + /** + * Gets the target input component + */ + get target() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this._propagateInputValueToOutput(this.target, this.output); + this._frameGraphTask.targetTexture = this.target.connectedPoint?.value; + } +} +RegisterClass("BABYLON.NodeRenderGraphGenerateMipmapsBlock", NodeRenderGraphGenerateMipmapsBlock); + +/** + * Dragging operation in observable + */ +var DragOperation; +(function (DragOperation) { + DragOperation[DragOperation["Rotation"] = 0] = "Rotation"; + DragOperation[DragOperation["Scaling"] = 1] = "Scaling"; +})(DragOperation || (DragOperation = {})); + +/** + * Creates a hemisphere mesh + * @param name defines the name of the mesh + * @param options defines the options used to create the mesh + * @param scene defines the hosting scene + * @returns the hemisphere mesh + */ +function CreateHemisphere(name, options = {}, scene) { + if (!options.diameter) { + options.diameter = 1; + } + if (!options.segments) { + options.segments = 16; + } + const halfSphere = CreateSphere("", { slice: 0.5, diameter: options.diameter, segments: options.segments }, scene); + const disc = CreateDisc("", { radius: options.diameter / 2, tessellation: options.segments * 3 + (4 - options.segments) }, scene); + disc.rotation.x = -Math.PI / 2; + disc.parent = halfSphere; + const merged = Mesh.MergeMeshes([disc, halfSphere], true); + merged.name = name; + return merged; +} +/** + * Creates a hemispheric light + * @param name + * @param segments + * @param diameter + * @param scene + * @returns the mesh + */ +Mesh.CreateHemisphere = (name, segments, diameter, scene) => { + const options = { + segments: segments, + diameter: diameter, + }; + return CreateHemisphere(name, options, scene); +}; + +/** + * Mirror texture can be used to simulate the view from a mirror in a scene. + * It will dynamically be rendered every frame to adapt to the camera point of view. + * You can then easily use it as a reflectionTexture on a flat surface. + * In case the surface is not a plane, please consider relying on reflection probes. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#mirrortexture + */ +class MirrorTexture extends RenderTargetTexture { + /** + * Define the blur ratio used to blur the reflection if needed. + */ + set blurRatio(value) { + if (this._blurRatio === value) { + return; + } + this._blurRatio = value; + this._preparePostProcesses(); + } + get blurRatio() { + return this._blurRatio; + } + /** + * Define the adaptive blur kernel used to blur the reflection if needed. + * This will autocompute the closest best match for the `blurKernel` + */ + set adaptiveBlurKernel(value) { + this._adaptiveBlurKernel = value; + this._autoComputeBlurKernel(); + } + /** + * Define the blur kernel used to blur the reflection if needed. + * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. + */ + set blurKernel(value) { + this.blurKernelX = value; + this.blurKernelY = value; + } + /** + * Define the blur kernel on the X Axis used to blur the reflection if needed. + * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. + */ + set blurKernelX(value) { + if (this._blurKernelX === value) { + return; + } + this._blurKernelX = value; + this._preparePostProcesses(); + } + get blurKernelX() { + return this._blurKernelX; + } + /** + * Define the blur kernel on the Y Axis used to blur the reflection if needed. + * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. + */ + set blurKernelY(value) { + if (this._blurKernelY === value) { + return; + } + this._blurKernelY = value; + this._preparePostProcesses(); + } + get blurKernelY() { + return this._blurKernelY; + } + _autoComputeBlurKernel() { + const engine = this.getScene().getEngine(); + const dw = this.getRenderWidth() / engine.getRenderWidth(); + const dh = this.getRenderHeight() / engine.getRenderHeight(); + this.blurKernelX = this._adaptiveBlurKernel * dw; + this.blurKernelY = this._adaptiveBlurKernel * dh; + } + _onRatioRescale() { + if (this._sizeRatio) { + this.resize(this._initialSizeParameter); + if (!this._adaptiveBlurKernel) { + this._preparePostProcesses(); + } + } + if (this._adaptiveBlurKernel) { + this._autoComputeBlurKernel(); + } + } + _updateGammaSpace() { + const scene = this.getScene(); + if (!scene) { + return; + } + this.gammaSpace = !scene.imageProcessingConfiguration.isEnabled || !scene.imageProcessingConfiguration.applyByPostProcess; + } + /** + * Instantiates a Mirror Texture. + * Mirror texture can be used to simulate the view from a mirror in a scene. + * It will dynamically be rendered every frame to adapt to the camera point of view. + * You can then easily use it as a reflectionTexture on a flat surface. + * In case the surface is not a plane, please consider relying on reflection probes. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#mirrors + * @param name + * @param size + * @param scene + * @param generateMipMaps + * @param type + * @param samplingMode + * @param generateDepthBuffer + */ + constructor(name, size, scene, generateMipMaps, type = 0, samplingMode = Texture.BILINEAR_SAMPLINGMODE, generateDepthBuffer = true) { + super(name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer); + /** + * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector. + * It is possible to directly set the mirrorPlane by directly using a Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#mirrors + */ + this.mirrorPlane = new Plane(0, 1, 0, 1); + this._transformMatrix = Matrix.Zero(); + this._mirrorMatrix = Matrix.Zero(); + this._adaptiveBlurKernel = 0; + this._blurKernelX = 0; + this._blurKernelY = 0; + this._blurRatio = 1.0; + scene = this.getScene(); + if (!scene) { + return this; + } + this.ignoreCameraViewport = true; + this._updateGammaSpace(); + this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(() => { + this._updateGammaSpace(); + }); + const engine = scene.getEngine(); + if (engine.supportsUniformBuffers) { + this._sceneUBO = scene.createSceneUniformBuffer(`Scene for Mirror Texture (name "${name}")`); + } + let saveClipPlane; + this.onBeforeRenderObservable.add(() => { + if (this._sceneUBO) { + this._currentSceneUBO = scene.getSceneUniformBuffer(); + scene.setSceneUniformBuffer(this._sceneUBO); + scene.getSceneUniformBuffer().unbindEffect(); + } + Matrix.ReflectionToRef(this.mirrorPlane, this._mirrorMatrix); + this._mirrorMatrix.multiplyToRef(scene.getViewMatrix(), this._transformMatrix); + scene.setTransformMatrix(this._transformMatrix, scene.getProjectionMatrix()); + saveClipPlane = scene.clipPlane; + scene.clipPlane = this.mirrorPlane; + scene._mirroredCameraPosition = Vector3.TransformCoordinates(scene.activeCamera.globalPosition, this._mirrorMatrix); + }); + this.onAfterRenderObservable.add(() => { + if (this._sceneUBO) { + scene.setSceneUniformBuffer(this._currentSceneUBO); + } + scene.updateTransformMatrix(); + scene._mirroredCameraPosition = null; + scene.clipPlane = saveClipPlane; + }); + } + _preparePostProcesses() { + this.clearPostProcesses(true); + if (this._blurKernelX && this._blurKernelY) { + const engine = this.getScene().getEngine(); + const textureType = engine.getCaps().textureFloatRender && engine.getCaps().textureFloatLinearFiltering ? 1 : 2; + this._blurX = new BlurPostProcess("horizontal blur", new Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType); + this._blurX.autoClear = false; + if (this._blurRatio === 1 && this.samples < 2 && this._texture) { + this._blurX.inputTexture = this._renderTarget; + } + else { + this._blurX.alwaysForcePOT = true; + } + this._blurY = new BlurPostProcess("vertical blur", new Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType); + this._blurY.autoClear = false; + this._blurY.alwaysForcePOT = this._blurRatio !== 1; + this.addPostProcess(this._blurX); + this.addPostProcess(this._blurY); + } + else { + if (this._blurY) { + this.removePostProcess(this._blurY); + this._blurY.dispose(); + this._blurY = null; + } + if (this._blurX) { + this.removePostProcess(this._blurX); + this._blurX.dispose(); + this._blurX = null; + } + } + } + /** + * Clone the mirror texture. + * @returns the cloned texture + */ + clone() { + const scene = this.getScene(); + if (!scene) { + return this; + } + const textureSize = this.getSize(); + const newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer); + // Base texture + newTexture.hasAlpha = this.hasAlpha; + newTexture.level = this.level; + // Mirror Texture + newTexture.mirrorPlane = this.mirrorPlane.clone(); + if (this.renderList) { + newTexture.renderList = this.renderList.slice(0); + } + return newTexture; + } + /** + * Serialize the texture to a JSON representation you could use in Parse later on + * @returns the serialized JSON representation + */ + serialize() { + if (!this.name) { + return null; + } + const serializationObject = super.serialize(); + serializationObject.mirrorPlane = this.mirrorPlane.asArray(); + return serializationObject; + } + /** + * Dispose the texture and release its associated resources. + */ + dispose() { + super.dispose(); + const scene = this.getScene(); + if (scene) { + scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver); + } + this._sceneUBO?.dispose(); + } +} +Texture._CreateMirror = (name, renderTargetSize, scene, generateMipMaps) => { + return new MirrorTexture(name, renderTargetSize, scene, generateMipMaps); +}; + +/** + * Background material defines definition. + * @internal Mainly internal Use + */ +class BackgroundMaterialDefines extends MaterialDefines { + /** + * Constructor of the defines. + */ + constructor() { + super(); + /** + * True if the diffuse texture is in use. + */ + this.DIFFUSE = false; + /** + * The direct UV channel to use. + */ + this.DIFFUSEDIRECTUV = 0; + /** + * True if the diffuse texture is in gamma space. + */ + this.GAMMADIFFUSE = false; + /** + * True if the diffuse texture has opacity in the alpha channel. + */ + this.DIFFUSEHASALPHA = false; + /** + * True if you want the material to fade to transparent at grazing angle. + */ + this.OPACITYFRESNEL = false; + /** + * True if an extra blur needs to be added in the reflection. + */ + this.REFLECTIONBLUR = false; + /** + * True if you want the material to fade to reflection at grazing angle. + */ + this.REFLECTIONFRESNEL = false; + /** + * True if you want the material to falloff as far as you move away from the scene center. + */ + this.REFLECTIONFALLOFF = false; + /** + * False if the current Webgl implementation does not support the texture lod extension. + */ + this.TEXTURELODSUPPORT = false; + /** + * True to ensure the data are premultiplied. + */ + this.PREMULTIPLYALPHA = false; + /** + * True if the texture contains cooked RGB values and not gray scaled multipliers. + */ + this.USERGBCOLOR = false; + /** + * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color + * stays aligned with the desired configuration. + */ + this.USEHIGHLIGHTANDSHADOWCOLORS = false; + /** + * True if only shadows must be rendered + */ + this.BACKMAT_SHADOWONLY = false; + /** + * True to add noise in order to reduce the banding effect. + */ + this.NOISE = false; + /** + * is the reflection texture in BGR color scheme? + * Mainly used to solve a bug in ios10 video tag + */ + this.REFLECTIONBGR = false; + /** + * True if ground projection has been enabled. + */ + this.PROJECTED_GROUND = false; + this.IMAGEPROCESSING = false; + this.VIGNETTE = false; + this.VIGNETTEBLENDMODEMULTIPLY = false; + this.VIGNETTEBLENDMODEOPAQUE = false; + this.TONEMAPPING = 0; + this.CONTRAST = false; + this.COLORCURVES = false; + this.COLORGRADING = false; + this.COLORGRADING3D = false; + this.SAMPLER3DGREENDEPTH = false; + this.SAMPLER3DBGRMAP = false; + this.DITHER = false; + this.IMAGEPROCESSINGPOSTPROCESS = false; + this.SKIPFINALCOLORCLAMP = false; + this.EXPOSURE = false; + this.MULTIVIEW = false; + // Reflection. + this.REFLECTION = false; + this.REFLECTIONMAP_3D = false; + this.REFLECTIONMAP_SPHERICAL = false; + this.REFLECTIONMAP_PLANAR = false; + this.REFLECTIONMAP_CUBIC = false; + this.REFLECTIONMAP_PROJECTION = false; + this.REFLECTIONMAP_SKYBOX = false; + this.REFLECTIONMAP_EXPLICIT = false; + this.REFLECTIONMAP_EQUIRECTANGULAR = false; + this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + this.INVERTCUBICMAP = false; + this.REFLECTIONMAP_OPPOSITEZ = false; + this.LODINREFLECTIONALPHA = false; + this.GAMMAREFLECTION = false; + this.RGBDREFLECTION = false; + this.EQUIRECTANGULAR_RELFECTION_FOV = false; + // Default BJS. + this.MAINUV1 = false; + this.MAINUV2 = false; + this.UV1 = false; + this.UV2 = false; + this.CLIPPLANE = false; + this.CLIPPLANE2 = false; + this.CLIPPLANE3 = false; + this.CLIPPLANE4 = false; + this.CLIPPLANE5 = false; + this.CLIPPLANE6 = false; + this.POINTSIZE = false; + this.FOG = false; + this.NORMAL = false; + this.NUM_BONE_INFLUENCERS = 0; + this.BonesPerMesh = 0; + this.INSTANCES = false; + this.SHADOWFLOAT = false; + this.LOGARITHMICDEPTH = false; + this.NONUNIFORMSCALING = false; + this.ALPHATEST = false; + this.rebuild(); + } +} +/** + * Background material used to create an efficient environment around your scene. + * #157MGZ: simple test + */ +class BackgroundMaterial extends PushMaterial { + /** + * Experimental Internal Use Only. + * + * Key light Color in "perceptual value" meaning the color you would like to see on screen. + * This acts as a helper to set the primary color to a more "human friendly" value. + * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the + * output color as close as possible from the chosen value. + * (This does not account for contrast color grading and color curves as they are considered post effect and not directly + * part of lighting setup.) + */ + get _perceptualColor() { + return this.__perceptualColor; + } + set _perceptualColor(value) { + this.__perceptualColor = value; + this._computePrimaryColorFromPerceptualColor(); + this._markAllSubMeshesAsLightsDirty(); + } + /** + * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors. + * The color opposite to the primary color is used at the level chosen to define what the black area would look. + */ + get primaryColorShadowLevel() { + return this._primaryColorShadowLevel; + } + set primaryColorShadowLevel(value) { + this._primaryColorShadowLevel = value; + this._computePrimaryColors(); + this._markAllSubMeshesAsLightsDirty(); + } + /** + * Defines the level of the highlights (highlight area of the reflection map) in order to help scaling the colors. + * The primary color is used at the level chosen to define what the white area would look. + */ + get primaryColorHighlightLevel() { + return this._primaryColorHighlightLevel; + } + set primaryColorHighlightLevel(value) { + this._primaryColorHighlightLevel = value; + this._computePrimaryColors(); + this._markAllSubMeshesAsLightsDirty(); + } + /** + * Sets the reflection reflectance fresnel values according to the default standard + * empirically know to work well :-) + */ + set reflectionStandardFresnelWeight(value) { + let reflectionWeight = value; + if (reflectionWeight < 0.5) { + reflectionWeight = reflectionWeight * 2.0; + this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight; + this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight; + } + else { + reflectionWeight = reflectionWeight * 2.0 - 1.0; + this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight; + this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight; + } + } + /** + * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". + * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov. + * Recommended to be keep at 1.0 except for special cases. + */ + get fovMultiplier() { + return this._fovMultiplier; + } + set fovMultiplier(value) { + if (isNaN(value)) { + value = 1.0; + } + this._fovMultiplier = Math.max(0.0, Math.min(2.0, value)); + } + /** + * Attaches a new image processing configuration to the PBR Material. + * @param configuration (if null the scene configuration will be use) + */ + _attachImageProcessingConfiguration(configuration) { + if (configuration === this._imageProcessingConfiguration) { + return; + } + // Detaches observer. + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + // Pick the scene configuration if needed. + if (!configuration) { + this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; + } + else { + this._imageProcessingConfiguration = configuration; + } + // Attaches observer. + if (this._imageProcessingConfiguration) { + this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { + this._computePrimaryColorFromPerceptualColor(); + this._markAllSubMeshesAsImageProcessingDirty(); + }); + } + } + /** + * Gets the image processing configuration used either in this material. + */ + get imageProcessingConfiguration() { + return this._imageProcessingConfiguration; + } + /** + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ + set imageProcessingConfiguration(value) { + this._attachImageProcessingConfiguration(value); + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + } + /** + * Gets whether the color curves effect is enabled. + */ + get cameraColorCurvesEnabled() { + return this.imageProcessingConfiguration.colorCurvesEnabled; + } + /** + * Sets whether the color curves effect is enabled. + */ + set cameraColorCurvesEnabled(value) { + this.imageProcessingConfiguration.colorCurvesEnabled = value; + } + /** + * Gets whether the color grading effect is enabled. + */ + get cameraColorGradingEnabled() { + return this.imageProcessingConfiguration.colorGradingEnabled; + } + /** + * Gets whether the color grading effect is enabled. + */ + set cameraColorGradingEnabled(value) { + this.imageProcessingConfiguration.colorGradingEnabled = value; + } + /** + * Gets whether tonemapping is enabled or not. + */ + get cameraToneMappingEnabled() { + return this._imageProcessingConfiguration.toneMappingEnabled; + } + /** + * Sets whether tonemapping is enabled or not + */ + set cameraToneMappingEnabled(value) { + this._imageProcessingConfiguration.toneMappingEnabled = value; + } + /** + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ + get cameraExposure() { + return this._imageProcessingConfiguration.exposure; + } + /** + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ + set cameraExposure(value) { + this._imageProcessingConfiguration.exposure = value; + } + /** + * Gets The camera contrast used on this material. + */ + get cameraContrast() { + return this._imageProcessingConfiguration.contrast; + } + /** + * Sets The camera contrast used on this material. + */ + set cameraContrast(value) { + this._imageProcessingConfiguration.contrast = value; + } + /** + * Gets the Color Grading 2D Lookup Texture. + */ + get cameraColorGradingTexture() { + return this._imageProcessingConfiguration.colorGradingTexture; + } + /** + * Sets the Color Grading 2D Lookup Texture. + */ + set cameraColorGradingTexture(value) { + this.imageProcessingConfiguration.colorGradingTexture = value; + } + /** + * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ + get cameraColorCurves() { + return this.imageProcessingConfiguration.colorCurves; + } + /** + * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ + set cameraColorCurves(value) { + this.imageProcessingConfiguration.colorCurves = value; + } + /** + * Instantiates a Background Material in the given scene + * @param name The friendly name of the material + * @param scene The scene to add the material to + * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false + */ + constructor(name, scene, forceGLSL = false) { + super(name, scene, undefined, forceGLSL); + /** + * Key light Color (multiply against the environment texture) + */ + this.primaryColor = Color3.White(); + this._primaryColorShadowLevel = 0; + this._primaryColorHighlightLevel = 0; + /** + * Reflection Texture used in the material. + * Should be author in a specific way for the best result (refer to the documentation). + */ + this.reflectionTexture = null; + /** + * Reflection Texture level of blur. + * + * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the + * texture twice. + */ + this.reflectionBlur = 0; + /** + * Diffuse Texture used in the material. + * Should be author in a specific way for the best result (refer to the documentation). + */ + this.diffuseTexture = null; + this._shadowLights = null; + /** + * Specify the list of lights casting shadow on the material. + * All scene shadow lights will be included if null. + */ + this.shadowLights = null; + /** + * Helps adjusting the shadow to a softer level if required. + * 0 means black shadows and 1 means no shadows. + */ + this.shadowLevel = 0; + /** + * In case of opacity Fresnel or reflection falloff, this is use as a scene center. + * It is usually zero but might be interesting to modify according to your setup. + */ + this.sceneCenter = Vector3.Zero(); + /** + * This helps specifying that the material is falling off to the sky box at grazing angle. + * This helps ensuring a nice transition when the camera goes under the ground. + */ + this.opacityFresnel = true; + /** + * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle. + * This helps adding a mirror texture on the ground. + */ + this.reflectionFresnel = false; + /** + * This helps specifying the falloff radius off the reflection texture from the sceneCenter. + * This helps adding a nice falloff effect to the reflection if used as a mirror for instance. + */ + this.reflectionFalloffDistance = 0.0; + /** + * This specifies the weight of the reflection against the background in case of reflection Fresnel. + */ + this.reflectionAmount = 1.0; + /** + * This specifies the weight of the reflection at grazing angle. + */ + this.reflectionReflectance0 = 0.05; + /** + * This specifies the weight of the reflection at a perpendicular point of view. + */ + this.reflectionReflectance90 = 0.5; + /** + * Helps to directly use the maps channels instead of their level. + */ + this.useRGBColor = true; + /** + * This helps reducing the banding effect that could occur on the background. + */ + this.enableNoise = false; + this._fovMultiplier = 1.0; + /** + * Enable the FOV adjustment feature controlled by fovMultiplier. + */ + this.useEquirectangularFOV = false; + this._maxSimultaneousLights = 4; + /** + * Number of Simultaneous lights allowed on the material. + */ + this.maxSimultaneousLights = 4; + this._shadowOnly = false; + /** + * Make the material only render shadows + */ + this.shadowOnly = false; + /** + * Keep track of the image processing observer to allow dispose and replace. + */ + this._imageProcessingObserver = null; + /** + * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB. + * Setting this flag to true (not done automatically!) will convert it back to RGB. + */ + this.switchToBGR = false; + this._enableGroundProjection = false; + /** + * Enables the ground projection mode on the material. + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/skybox#ground-projection + */ + this.enableGroundProjection = false; + /** + * Defines the radius of the projected ground if enableGroundProjection is true. + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/skybox#ground-projection + */ + this.projectedGroundRadius = 1000; + /** + * Defines the height of the projected ground if enableGroundProjection is true. + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/skybox#ground-projection + */ + this.projectedGroundHeight = 10; + // Temp values kept as cache in the material. + this._renderTargets = new SmartArray(16); + this._reflectionControls = Vector4.Zero(); + this._white = Color3.White(); + this._primaryShadowColor = Color3.Black(); + this._primaryHighlightColor = Color3.Black(); + this._shadersLoaded = false; + // Setup the default processing configuration to the scene. + this._attachImageProcessingConfiguration(null); + this.getRenderTargetTextures = () => { + this._renderTargets.reset(); + if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) { + this._renderTargets.push(this._diffuseTexture); + } + if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + this._renderTargets.push(this._reflectionTexture); + } + return this._renderTargets; + }; + } + /** + * Gets a boolean indicating that current material needs to register RTT + */ + get hasRenderTargetTextures() { + if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) { + return true; + } + if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + return true; + } + return false; + } + /** + * The entire material has been created in order to prevent overdraw. + * @returns false + */ + needAlphaTesting() { + return true; + } + /** + * The entire material has been created in order to prevent overdraw. + * @returns true if blending is enable + */ + needAlphaBlending() { + return this.alpha < 1 || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._shadowOnly; + } + /** + * Checks whether the material is ready to be rendered for a given mesh. + * @param mesh The mesh to render + * @param subMesh The submesh to check against + * @param useInstances Specify wether or not the material is used with instances + * @returns true if all the dependencies are ready (Textures, Effects...) + */ + isReadyForSubMesh(mesh, subMesh, useInstances = false) { + const drawWrapper = subMesh._drawWrapper; + if (drawWrapper.effect && this.isFrozen) { + if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) { + return true; + } + } + if (!subMesh.materialDefines) { + subMesh.materialDefines = new BackgroundMaterialDefines(); + } + const scene = this.getScene(); + const defines = subMesh.materialDefines; + if (this._isReadyForSubMesh(subMesh)) { + return true; + } + const engine = scene.getEngine(); + // Lights + PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights); + defines._needNormals = true; + // Multiview + PrepareDefinesForMultiview(scene, defines); + // Textures + if (defines._areTexturesDirty) { + defines._needUVs = false; + if (scene.texturesEnabled) { + if (scene.getEngine().getCaps().textureLOD) { + defines.TEXTURELODSUPPORT = true; + } + if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) { + if (!this._diffuseTexture.isReadyOrNotBlocking()) { + return false; + } + PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE"); + defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha; + defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace; + defines.OPACITYFRESNEL = this._opacityFresnel; + } + else { + defines.DIFFUSE = false; + defines.DIFFUSEDIRECTUV = 0; + defines.DIFFUSEHASALPHA = false; + defines.GAMMADIFFUSE = false; + defines.OPACITYFRESNEL = false; + } + const reflectionTexture = this._reflectionTexture; + if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { + if (!reflectionTexture.isReadyOrNotBlocking()) { + return false; + } + defines.REFLECTION = true; + defines.GAMMAREFLECTION = reflectionTexture.gammaSpace; + defines.RGBDREFLECTION = reflectionTexture.isRGBD; + defines.REFLECTIONBLUR = this._reflectionBlur > 0; + defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha; + defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV; + defines.REFLECTIONBGR = this.switchToBGR; + if (reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE) { + defines.INVERTCUBICMAP = true; + } + defines.REFLECTIONMAP_3D = reflectionTexture.isCube; + defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ; + switch (reflectionTexture.coordinatesMode) { + case Texture.EXPLICIT_MODE: + defines.REFLECTIONMAP_EXPLICIT = true; + break; + case Texture.PLANAR_MODE: + defines.REFLECTIONMAP_PLANAR = true; + break; + case Texture.PROJECTION_MODE: + defines.REFLECTIONMAP_PROJECTION = true; + break; + case Texture.SKYBOX_MODE: + defines.REFLECTIONMAP_SKYBOX = true; + break; + case Texture.SPHERICAL_MODE: + defines.REFLECTIONMAP_SPHERICAL = true; + break; + case Texture.EQUIRECTANGULAR_MODE: + defines.REFLECTIONMAP_EQUIRECTANGULAR = true; + break; + case Texture.FIXED_EQUIRECTANGULAR_MODE: + defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true; + break; + case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE: + defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true; + break; + case Texture.CUBIC_MODE: + case Texture.INVCUBIC_MODE: + default: + defines.REFLECTIONMAP_CUBIC = true; + break; + } + if (this.reflectionFresnel) { + defines.REFLECTIONFRESNEL = true; + defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0; + this._reflectionControls.x = this.reflectionAmount; + this._reflectionControls.y = this.reflectionReflectance0; + this._reflectionControls.z = this.reflectionReflectance90; + this._reflectionControls.w = 1 / this.reflectionFalloffDistance; + } + else { + defines.REFLECTIONFRESNEL = false; + defines.REFLECTIONFALLOFF = false; + } + } + else { + defines.REFLECTION = false; + defines.REFLECTIONFRESNEL = false; + defines.REFLECTIONFALLOFF = false; + defines.REFLECTIONBLUR = false; + defines.REFLECTIONMAP_3D = false; + defines.REFLECTIONMAP_SPHERICAL = false; + defines.REFLECTIONMAP_PLANAR = false; + defines.REFLECTIONMAP_CUBIC = false; + defines.REFLECTIONMAP_PROJECTION = false; + defines.REFLECTIONMAP_SKYBOX = false; + defines.REFLECTIONMAP_EXPLICIT = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + defines.INVERTCUBICMAP = false; + defines.REFLECTIONMAP_OPPOSITEZ = false; + defines.LODINREFLECTIONALPHA = false; + defines.GAMMAREFLECTION = false; + defines.RGBDREFLECTION = false; + } + } + defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8; + defines.USERGBCOLOR = this._useRGBColor; + defines.NOISE = this._enableNoise; + } + if (defines._areLightsDirty) { + defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0); + defines.BACKMAT_SHADOWONLY = this._shadowOnly; + } + if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { + if (!this._imageProcessingConfiguration.isReady()) { + return false; + } + this._imageProcessingConfiguration.prepareDefines(defines); + } + if (defines._areMiscDirty) { + if (defines.REFLECTIONMAP_3D && this._enableGroundProjection) { + defines.PROJECTED_GROUND = true; + defines.REFLECTIONMAP_SKYBOX = true; + } + else { + defines.PROJECTED_GROUND = false; + } + } + // Misc. + PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this.needAlphaTestingForMesh(mesh), defines); + // Values that need to be evaluated on every frame + PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances); + // Attribs + if (PrepareDefinesForAttributes(mesh, defines, false, true, false)) { + if (mesh) { + if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) { + mesh.createNormals(true); + Logger.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name); + } + } + } + // Get correct effect + if (defines.isDirty) { + defines.markAsProcessed(); + scene.resetCachedMaterial(); + // Fallbacks + const fallbacks = new EffectFallbacks(); + if (defines.FOG) { + fallbacks.addFallback(0, "FOG"); + } + if (defines.POINTSIZE) { + fallbacks.addFallback(1, "POINTSIZE"); + } + if (defines.MULTIVIEW) { + fallbacks.addFallback(0, "MULTIVIEW"); + } + HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights); + //Attributes + const attribs = [VertexBuffer.PositionKind]; + if (defines.NORMAL) { + attribs.push(VertexBuffer.NormalKind); + } + if (defines.UV1) { + attribs.push(VertexBuffer.UVKind); + } + if (defines.UV2) { + attribs.push(VertexBuffer.UV2Kind); + } + PrepareAttributesForBones(attribs, mesh, defines, fallbacks); + PrepareAttributesForInstances(attribs, defines); + const uniforms = [ + "world", + "view", + "viewProjection", + "vEyePosition", + "vLightsType", + "vFogInfos", + "vFogColor", + "pointSize", + "mBones", + "vPrimaryColor", + "vPrimaryColorShadow", + "vReflectionInfos", + "reflectionMatrix", + "vReflectionMicrosurfaceInfos", + "fFovMultiplier", + "shadowLevel", + "alpha", + "vBackgroundCenter", + "vReflectionControl", + "vDiffuseInfos", + "diffuseMatrix", + "projectedGroundInfos", + "logarithmicDepthConstant", + ]; + addClipPlaneUniforms(uniforms); + const samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"]; + const uniformBuffers = ["Material", "Scene"]; + if (ImageProcessingConfiguration) { + ImageProcessingConfiguration.PrepareUniforms(uniforms, defines); + ImageProcessingConfiguration.PrepareSamplers(samplers, defines); + } + PrepareUniformsAndSamplersList({ + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: defines, + maxSimultaneousLights: this._maxSimultaneousLights, + }); + const join = defines.toString(); + const effect = scene.getEngine().createEffect("background", { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: join, + fallbacks: fallbacks, + onCompiled: this.onCompiled, + onError: this.onError, + indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }, + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: this._shadersLoaded + ? undefined + : async () => { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => background_vertex$1), Promise.resolve().then(() => background_fragment$1)]); + } + else { + await Promise.all([Promise.resolve().then(() => background_vertex), Promise.resolve().then(() => background_fragment)]); + } + this._shadersLoaded = true; + }, + }, engine); + subMesh.setEffect(effect, defines, this._materialContext); + this.buildUniformLayout(); + } + if (!subMesh.effect || !subMesh.effect.isReady()) { + return false; + } + defines._renderId = scene.getRenderId(); + drawWrapper._wasPreviouslyReady = true; + drawWrapper._wasPreviouslyUsingInstances = useInstances; + this._checkScenePerformancePriority(); + return true; + } + /** + * Compute the primary color according to the chosen perceptual color. + */ + _computePrimaryColorFromPerceptualColor() { + if (!this.__perceptualColor) { + return; + } + this._primaryColor.copyFrom(this.__perceptualColor); + // Revert gamma space. + this._primaryColor.toLinearSpaceToRef(this._primaryColor, this.getScene().getEngine().useExactSrgbConversions); + // Revert image processing configuration. + if (this._imageProcessingConfiguration) { + // Revert Exposure. + this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor); + } + this._computePrimaryColors(); + } + /** + * Compute the highlights and shadow colors according to their chosen levels. + */ + _computePrimaryColors() { + if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) { + return; + } + // Find the highlight color based on the configuration. + this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor); + this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor); + // Find the shadow color based on the configuration. + this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor); + this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor); + this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor); + } + /** + * Build the uniform buffer used in the material. + */ + buildUniformLayout() { + // Order is important ! + this._uniformBuffer.addUniform("vPrimaryColor", 4); + this._uniformBuffer.addUniform("vPrimaryColorShadow", 4); + this._uniformBuffer.addUniform("vDiffuseInfos", 2); + this._uniformBuffer.addUniform("vReflectionInfos", 2); + this._uniformBuffer.addUniform("diffuseMatrix", 16); + this._uniformBuffer.addUniform("reflectionMatrix", 16); + this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3); + this._uniformBuffer.addUniform("fFovMultiplier", 1); + this._uniformBuffer.addUniform("pointSize", 1); + this._uniformBuffer.addUniform("shadowLevel", 1); + this._uniformBuffer.addUniform("alpha", 1); + this._uniformBuffer.addUniform("vBackgroundCenter", 3); + this._uniformBuffer.addUniform("vReflectionControl", 4); + this._uniformBuffer.addUniform("projectedGroundInfos", 2); + this._uniformBuffer.create(); + } + /** + * Unbind the material. + */ + unbind() { + if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) { + this._uniformBuffer.setTexture("diffuseSampler", null); + } + if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + this._uniformBuffer.setTexture("reflectionSampler", null); + } + super.unbind(); + } + /** + * Bind only the world matrix to the material. + * @param world The world matrix to bind. + */ + bindOnlyWorldMatrix(world) { + this._activeEffect.setMatrix("world", world); + } + /** + * Bind the material for a dedicated submesh (every used meshes will be considered opaque). + * @param world The world matrix to bind. + * @param mesh the mesh to bind for. + * @param subMesh The submesh to bind for. + */ + bindForSubMesh(world, mesh, subMesh) { + const scene = this.getScene(); + const defines = subMesh.materialDefines; + if (!defines) { + return; + } + const effect = subMesh.effect; + if (!effect) { + return; + } + this._activeEffect = effect; + // Matrices + this.bindOnlyWorldMatrix(world); + // Bones + BindBonesParameters(mesh, this._activeEffect); + const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility); + if (mustRebind) { + this._uniformBuffer.bindToEffect(effect, "Material"); + this.bindViewProjection(effect); + const reflectionTexture = this._reflectionTexture; + if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync || subMesh._drawWrapper._forceRebindOnNextCall) { + // Texture uniforms + if (scene.texturesEnabled) { + if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) { + this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level); + BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse"); + } + if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { + this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix()); + this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur); + this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); + } + } + if (this.shadowLevel > 0) { + this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel); + } + this._uniformBuffer.updateFloat("alpha", this.alpha); + // Point size + if (this.pointsCloud) { + this._uniformBuffer.updateFloat("pointSize", this.pointSize); + } + if (defines.USEHIGHLIGHTANDSHADOWCOLORS) { + this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0); + this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0); + } + else { + this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0); + } + } + this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier); + // Textures + if (scene.texturesEnabled) { + if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) { + this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture); + } + if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { + if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) { + this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture); + } + else if (!defines.REFLECTIONBLUR) { + this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture); + } + else { + this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture); + this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture); + this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture); + } + if (defines.REFLECTIONFRESNEL) { + this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z); + this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w); + } + } + if (defines.PROJECTED_GROUND) { + this._uniformBuffer.updateFloat2("projectedGroundInfos", this.projectedGroundRadius, this.projectedGroundHeight); + } + } + // Clip plane + bindClipPlane(this._activeEffect, this, scene); + scene.bindEyePosition(effect); + } + else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) { + this._uniformBuffer.bindToEffect(effect, "Material"); + this._needToBindSceneUbo = true; + } + if (mustRebind || !this.isFrozen) { + if (scene.lightsEnabled) { + BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights); + } + // View + this.bindView(effect); + // Fog + BindFogParameters(scene, mesh, this._activeEffect, true); + // Log. depth + if (this._useLogarithmicDepth) { + BindLogDepth(defines, effect, scene); + } + // image processing + if (this._imageProcessingConfiguration) { + this._imageProcessingConfiguration.bind(this._activeEffect); + } + } + this._afterBind(mesh, this._activeEffect, subMesh); + this._uniformBuffer.update(); + } + /** + * Checks to see if a texture is used in the material. + * @param texture - Base texture to use. + * @returns - Boolean specifying if a texture is used in the material. + */ + hasTexture(texture) { + if (super.hasTexture(texture)) { + return true; + } + if (this._reflectionTexture === texture) { + return true; + } + if (this._diffuseTexture === texture) { + return true; + } + return false; + } + /** + * Dispose the material. + * @param forceDisposeEffect Force disposal of the associated effect. + * @param forceDisposeTextures Force disposal of the associated textures. + */ + dispose(forceDisposeEffect = false, forceDisposeTextures = false) { + if (forceDisposeTextures) { + if (this.diffuseTexture) { + this.diffuseTexture.dispose(); + } + if (this.reflectionTexture) { + this.reflectionTexture.dispose(); + } + } + this._renderTargets.dispose(); + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + super.dispose(forceDisposeEffect); + } + /** + * Clones the material. + * @param name The cloned name. + * @returns The cloned material. + */ + clone(name) { + return SerializationHelper.Clone(() => new BackgroundMaterial(name, this.getScene()), this); + } + /** + * Serializes the current material to its JSON representation. + * @returns The JSON representation. + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.customType = "BABYLON.BackgroundMaterial"; + return serializationObject; + } + /** + * Gets the class name of the material + * @returns "BackgroundMaterial" + */ + getClassName() { + return "BackgroundMaterial"; + } + /** + * Parse a JSON input to create back a background material. + * @param source The JSON data to parse + * @param scene The scene to create the parsed material in + * @param rootUrl The root url of the assets the material depends upon + * @returns the instantiated BackgroundMaterial. + */ + static Parse(source, scene, rootUrl) { + return SerializationHelper.Parse(() => new BackgroundMaterial(source.name, scene), source, scene, rootUrl); + } +} +/** + * Standard reflectance value at parallel view angle. + */ +BackgroundMaterial.StandardReflectance0 = 0.05; +/** + * Standard reflectance value at grazing angle. + */ +BackgroundMaterial.StandardReflectance90 = 0.5; +__decorate([ + serializeAsColor3() +], BackgroundMaterial.prototype, "_primaryColor", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsLightsDirty") +], BackgroundMaterial.prototype, "primaryColor", void 0); +__decorate([ + serializeAsColor3() +], BackgroundMaterial.prototype, "__perceptualColor", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsLightsDirty") +], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null); +__decorate([ + serializeAsTexture() +], BackgroundMaterial.prototype, "_reflectionTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "reflectionTexture", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_reflectionBlur", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "reflectionBlur", void 0); +__decorate([ + serializeAsTexture() +], BackgroundMaterial.prototype, "_diffuseTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "diffuseTexture", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "shadowLights", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_shadowLevel", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "shadowLevel", void 0); +__decorate([ + serializeAsVector3() +], BackgroundMaterial.prototype, "_sceneCenter", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "sceneCenter", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_opacityFresnel", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "opacityFresnel", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_reflectionFresnel", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "reflectionFresnel", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_reflectionAmount", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "reflectionAmount", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "reflectionReflectance0", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "reflectionReflectance90", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_useRGBColor", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "useRGBColor", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_enableNoise", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "enableNoise", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "_shadowOnly", void 0); +__decorate([ + expandToProperty("_markAllSubMeshesAsLightsDirty") +], BackgroundMaterial.prototype, "shadowOnly", void 0); +__decorate([ + serializeAsImageProcessingConfiguration() +], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsMiscDirty") +], BackgroundMaterial.prototype, "enableGroundProjection", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "projectedGroundRadius", void 0); +__decorate([ + serialize() +], BackgroundMaterial.prototype, "projectedGroundHeight", void 0); +RegisterClass("BABYLON.BackgroundMaterial", BackgroundMaterial); + +/** + * The EnvironmentHelper class can be used to add a fully featured non-expensive background to your scene. + * It includes by default a skybox and a ground relying on the BackgroundMaterial. + * It also helps with the default setup of your ImageProcessingConfiguration. + */ +class EnvironmentHelper { + /** + * Creates the default options for the helper. + * @param scene The scene the environment helper belongs to. + * @returns default options for the helper. + */ + static _GetDefaultOptions(scene) { + return { + createGround: true, + groundSize: 15, + groundTexture: Tools.GetAssetUrl(this._GroundTextureCDNUrl), + groundColor: new Color3(0.2, 0.2, 0.3).toLinearSpace(scene.getEngine().useExactSrgbConversions).scale(3), + groundOpacity: 0.9, + enableGroundShadow: true, + groundShadowLevel: 0.5, + enableGroundMirror: false, + groundMirrorSizeRatio: 0.3, + groundMirrorBlurKernel: 64, + groundMirrorAmount: 1, + groundMirrorFresnelWeight: 1, + groundMirrorFallOffDistance: 0, + groundMirrorTextureType: 0, + groundYBias: 0.00001, + createSkybox: true, + skyboxSize: 20, + skyboxTexture: Tools.GetAssetUrl(this._SkyboxTextureCDNUrl), + skyboxColor: new Color3(0.2, 0.2, 0.3).toLinearSpace(scene.getEngine().useExactSrgbConversions).scale(3), + backgroundYRotation: 0, + sizeAuto: true, + rootPosition: Vector3.Zero(), + setupImageProcessing: true, + environmentTexture: Tools.GetAssetUrl(this._EnvironmentTextureCDNUrl), + cameraExposure: 0.8, + cameraContrast: 1.2, + toneMappingEnabled: true, + }; + } + /** + * Gets the root mesh created by the helper. + */ + get rootMesh() { + return this._rootMesh; + } + /** + * Gets the skybox created by the helper. + */ + get skybox() { + return this._skybox; + } + /** + * Gets the skybox texture created by the helper. + */ + get skyboxTexture() { + return this._skyboxTexture; + } + /** + * Gets the skybox material created by the helper. + */ + get skyboxMaterial() { + return this._skyboxMaterial; + } + /** + * Gets the ground mesh created by the helper. + */ + get ground() { + return this._ground; + } + /** + * Gets the ground texture created by the helper. + */ + get groundTexture() { + return this._groundTexture; + } + /** + * Gets the ground mirror created by the helper. + */ + get groundMirror() { + return this._groundMirror; + } + /** + * Gets the ground mirror render list to helps pushing the meshes + * you wish in the ground reflection. + */ + get groundMirrorRenderList() { + if (this._groundMirror) { + return this._groundMirror.renderList; + } + return null; + } + /** + * Gets the ground material created by the helper. + */ + get groundMaterial() { + return this._groundMaterial; + } + /** + * constructor + * @param options Defines the options we want to customize the helper + * @param scene The scene to add the material to + */ + constructor(options, scene) { + this._errorHandler = (message, exception) => { + this.onErrorObservable.notifyObservers({ message: message, exception: exception }); + }; + this._options = { + ...EnvironmentHelper._GetDefaultOptions(scene), + ...options, + }; + this._scene = scene; + this.onErrorObservable = new Observable(); + this._setupBackground(); + this._setupImageProcessing(); + } + /** + * Updates the environment according to the new options + * @param options options to configure the helper (IEnvironmentHelperOptions) + */ + updateOptions(options) { + const newOptions = { + ...this._options, + ...options, + }; + if (this._ground && !newOptions.createGround) { + this._ground.dispose(); + this._ground = null; + } + if (this._groundMaterial && !newOptions.createGround) { + this._groundMaterial.dispose(); + this._groundMaterial = null; + } + if (this._groundTexture) { + if (this._options.groundTexture != newOptions.groundTexture) { + this._groundTexture.dispose(); + this._groundTexture = null; + } + } + if (this._skybox && !newOptions.createSkybox) { + this._skybox.dispose(); + this._skybox = null; + } + if (this._skyboxMaterial && !newOptions.createSkybox) { + this._skyboxMaterial.dispose(); + this._skyboxMaterial = null; + } + if (this._skyboxTexture) { + if (this._options.skyboxTexture != newOptions.skyboxTexture) { + this._skyboxTexture.dispose(); + this._skyboxTexture = null; + } + } + if (this._groundMirror && !newOptions.enableGroundMirror) { + this._groundMirror.dispose(); + this._groundMirror = null; + } + if (this._scene.environmentTexture) { + if (this._options.environmentTexture != newOptions.environmentTexture) { + this._scene.environmentTexture.dispose(); + } + } + this._options = newOptions; + this._setupBackground(); + this._setupImageProcessing(); + } + /** + * Sets the primary color of all the available elements. + * @param color the main color to affect to the ground and the background + */ + setMainColor(color) { + if (this.groundMaterial) { + this.groundMaterial.primaryColor = color; + } + if (this.skyboxMaterial) { + this.skyboxMaterial.primaryColor = color; + } + if (this.groundMirror) { + this.groundMirror.clearColor = new Color4(color.r, color.g, color.b, 1.0); + } + } + /** + * Setup the image processing according to the specified options. + */ + _setupImageProcessing() { + if (this._options.setupImageProcessing) { + this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast; + this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure; + this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled; + this._setupEnvironmentTexture(); + } + } + /** + * Setup the environment texture according to the specified options. + */ + _setupEnvironmentTexture() { + if (this._scene.environmentTexture) { + return; + } + if (this._options.environmentTexture instanceof BaseTexture) { + this._scene.environmentTexture = this._options.environmentTexture; + return; + } + const environmentTexture = CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene); + this._scene.environmentTexture = environmentTexture; + } + /** + * Setup the background according to the specified options. + */ + _setupBackground() { + if (!this._rootMesh) { + this._rootMesh = new Mesh("BackgroundHelper", this._scene); + } + this._rootMesh.rotation.y = this._options.backgroundYRotation; + const sceneSize = this._getSceneSize(); + if (this._options.createGround) { + this._setupGround(sceneSize); + this._setupGroundMaterial(); + this._setupGroundDiffuseTexture(); + if (this._options.enableGroundMirror) { + this._setupGroundMirrorTexture(sceneSize); + } + this._setupMirrorInGroundMaterial(); + } + if (this._options.createSkybox) { + this._setupSkybox(sceneSize); + this._setupSkyboxMaterial(); + this._setupSkyboxReflectionTexture(); + } + this._rootMesh.position.x = sceneSize.rootPosition.x; + this._rootMesh.position.z = sceneSize.rootPosition.z; + this._rootMesh.position.y = sceneSize.rootPosition.y; + } + /** + * Get the scene sizes according to the setup. + * @returns the different ground and skybox sizes. + */ + _getSceneSize() { + let groundSize = this._options.groundSize; + let skyboxSize = this._options.skyboxSize; + let rootPosition = this._options.rootPosition; + if (!this._scene.meshes || this._scene.meshes.length === 1) { + // 1 only means the root of the helper. + return { groundSize, skyboxSize, rootPosition }; + } + const sceneExtends = this._scene.getWorldExtends((mesh) => { + return mesh !== this._ground && mesh !== this._rootMesh && mesh !== this._skybox; + }); + const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min); + if (this._options.sizeAuto) { + if (this._scene.activeCamera instanceof ArcRotateCamera && this._scene.activeCamera.upperRadiusLimit) { + groundSize = this._scene.activeCamera.upperRadiusLimit * 2; + skyboxSize = groundSize; + } + const sceneDiagonalLenght = sceneDiagonal.length(); + if (sceneDiagonalLenght > groundSize) { + groundSize = sceneDiagonalLenght * 2; + skyboxSize = groundSize; + } + // 10 % bigger. + groundSize *= 1.1; + skyboxSize *= 1.5; + rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5)); + rootPosition.y = sceneExtends.min.y - this._options.groundYBias; + } + return { groundSize, skyboxSize, rootPosition }; + } + /** + * Setup the ground according to the specified options. + * @param sceneSize + */ + _setupGround(sceneSize) { + if (!this._ground || this._ground.isDisposed()) { + this._ground = CreatePlane("BackgroundPlane", { size: sceneSize.groundSize }, this._scene); + this._ground.rotation.x = Math.PI / 2; // Face up by default. + this._ground.isPickable = false; + this._ground.parent = this._rootMesh; + this._ground.onDisposeObservable.add(() => { + this._ground = null; + }); + } + this._ground.receiveShadows = this._options.enableGroundShadow; + } + /** + * Setup the ground material according to the specified options. + */ + _setupGroundMaterial() { + if (!this._groundMaterial) { + this._groundMaterial = new BackgroundMaterial("BackgroundPlaneMaterial", this._scene); + } + this._groundMaterial.alpha = this._options.groundOpacity; + this._groundMaterial.alphaMode = 8; + this._groundMaterial.shadowLevel = this._options.groundShadowLevel; + this._groundMaterial.primaryColor = this._options.groundColor; + this._groundMaterial.useRGBColor = false; + this._groundMaterial.enableNoise = true; + if (this._ground) { + this._ground.material = this._groundMaterial; + } + } + /** + * Setup the ground diffuse texture according to the specified options. + */ + _setupGroundDiffuseTexture() { + if (!this._groundMaterial) { + return; + } + if (this._groundTexture) { + return; + } + if (this._options.groundTexture instanceof BaseTexture) { + this._groundMaterial.diffuseTexture = this._options.groundTexture; + return; + } + this._groundTexture = new Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler); + this._groundTexture.gammaSpace = false; + this._groundTexture.hasAlpha = true; + this._groundMaterial.diffuseTexture = this._groundTexture; + } + /** + * Setup the ground mirror texture according to the specified options. + * @param sceneSize + */ + _setupGroundMirrorTexture(sceneSize) { + const wrapping = Texture.CLAMP_ADDRESSMODE; + if (!this._groundMirror) { + this._groundMirror = new MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, Texture.BILINEAR_SAMPLINGMODE, true); + this._groundMirror.mirrorPlane = new Plane(0, -1, 0, sceneSize.rootPosition.y); + this._groundMirror.anisotropicFilteringLevel = 1; + this._groundMirror.wrapU = wrapping; + this._groundMirror.wrapV = wrapping; + if (this._groundMirror.renderList) { + for (let i = 0; i < this._scene.meshes.length; i++) { + const mesh = this._scene.meshes[i]; + if (mesh !== this._ground && mesh !== this._skybox && mesh !== this._rootMesh) { + this._groundMirror.renderList.push(mesh); + } + } + } + } + const gammaGround = this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions); + this._groundMirror.clearColor = new Color4(gammaGround.r, gammaGround.g, gammaGround.b, 1); + this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel; + } + /** + * Setup the ground to receive the mirror texture. + */ + _setupMirrorInGroundMaterial() { + if (this._groundMaterial) { + this._groundMaterial.reflectionTexture = this._groundMirror; + this._groundMaterial.reflectionFresnel = true; + this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount; + this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight; + this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance; + } + } + /** + * Setup the skybox according to the specified options. + * @param sceneSize + */ + _setupSkybox(sceneSize) { + if (!this._skybox || this._skybox.isDisposed()) { + this._skybox = CreateBox("BackgroundSkybox", { size: sceneSize.skyboxSize, sideOrientation: Mesh.BACKSIDE }, this._scene); + this._skybox.isPickable = false; + this._skybox.onDisposeObservable.add(() => { + this._skybox = null; + }); + } + this._skybox.parent = this._rootMesh; + } + /** + * Setup the skybox material according to the specified options. + */ + _setupSkyboxMaterial() { + if (!this._skybox) { + return; + } + if (!this._skyboxMaterial) { + this._skyboxMaterial = new BackgroundMaterial("BackgroundSkyboxMaterial", this._scene); + } + this._skyboxMaterial.useRGBColor = false; + this._skyboxMaterial.primaryColor = this._options.skyboxColor; + this._skyboxMaterial.enableNoise = true; + this._skybox.material = this._skyboxMaterial; + } + /** + * Setup the skybox reflection texture according to the specified options. + */ + _setupSkyboxReflectionTexture() { + if (!this._skyboxMaterial) { + return; + } + if (this._skyboxTexture) { + return; + } + if (this._options.skyboxTexture instanceof BaseTexture) { + this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture; + return; + } + this._skyboxTexture = new CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler); + this._skyboxTexture.coordinatesMode = Texture.SKYBOX_MODE; + this._skyboxTexture.gammaSpace = false; + this._skyboxMaterial.reflectionTexture = this._skyboxTexture; + } + /** + * Dispose all the elements created by the Helper. + */ + dispose() { + if (this._groundMaterial) { + this._groundMaterial.dispose(true, true); + } + if (this._skyboxMaterial) { + this._skyboxMaterial.dispose(true, true); + } + this._rootMesh.dispose(false); + } +} +/** + * Default ground texture URL. + */ +EnvironmentHelper._GroundTextureCDNUrl = "https://assets.babylonjs.com/core/environments/backgroundGround.png"; +/** + * Default skybox texture URL. + */ +EnvironmentHelper._SkyboxTextureCDNUrl = "https://assets.babylonjs.com/core/environments/backgroundSkybox.dds"; +/** + * Default environment texture URL. + */ +EnvironmentHelper._EnvironmentTextureCDNUrl = "https://assets.babylonjs.com/core/environments/environmentSpecular.env"; + +/** + * Display a 360/180 degree texture on an approximately spherical surface, useful for VR applications or skyboxes. + * As a subclass of TransformNode, this allow parenting to the camera or multiple textures with different locations in the scene. + * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere. + * Potential additions to this helper include zoom and and non-infinite distance rendering effects. + */ +class TextureDome extends TransformNode { + /** + * Gets the texture being displayed on the sphere + */ + get texture() { + return this._texture; + } + /** + * Sets the texture being displayed on the sphere + */ + set texture(newTexture) { + if (this._texture === newTexture) { + return; + } + this._texture = newTexture; + if (this._useDirectMapping) { + this._texture.wrapU = Texture.CLAMP_ADDRESSMODE; + this._texture.wrapV = Texture.CLAMP_ADDRESSMODE; + this._material.diffuseTexture = this._texture; + } + else { + this._texture.coordinatesMode = Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation + this._texture.wrapV = Texture.CLAMP_ADDRESSMODE; + this._material.reflectionTexture = this._texture; + } + this._changeTextureMode(this._textureMode); + } + /** + * Gets the mesh used for the dome. + */ + get mesh() { + return this._mesh; + } + /** + * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". + * Also see the options.resolution property. + */ + get fovMultiplier() { + return this._material.fovMultiplier; + } + set fovMultiplier(value) { + this._material.fovMultiplier = value; + } + /** + * Gets or set the current texture mode for the texture. It can be: + * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360. + * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360. + * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360. + */ + get textureMode() { + return this._textureMode; + } + /** + * Sets the current texture mode for the texture. It can be: + * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360. + * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360. + * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360. + */ + set textureMode(value) { + if (this._textureMode === value) { + return; + } + this._changeTextureMode(value); + } + /** + * Is it a 180 degrees dome (half dome) or 360 texture (full dome) + */ + get halfDome() { + return this._halfDome; + } + /** + * Set the halfDome mode. If set, only the front (180 degrees) will be displayed and the back will be blacked out. + */ + set halfDome(enabled) { + this._halfDome = enabled; + this._halfDomeMask.setEnabled(enabled); + this._changeTextureMode(this._textureMode); + } + /** + * Set the cross-eye mode. If set, images that can be seen when crossing eyes will render correctly + */ + set crossEye(enabled) { + this._crossEye = enabled; + this._changeTextureMode(this._textureMode); + } + /** + * Is it a cross-eye texture? + */ + get crossEye() { + return this._crossEye; + } + /** + * The background material of this dome. + */ + get material() { + return this._material; + } + /** + * Create an instance of this class and pass through the parameters to the relevant classes- Texture, StandardMaterial, and Mesh. + * @param name Element's name, child elements will append suffixes for their own names. + * @param textureUrlOrElement defines the url(s) or the (video) HTML element to use + * @param options An object containing optional or exposed sub element properties + * @param options.resolution + * @param options.clickToPlay + * @param options.autoPlay + * @param options.loop + * @param options.size + * @param options.poster + * @param options.faceForward + * @param options.useDirectMapping + * @param options.halfDomeMode + * @param options.crossEyeMode + * @param options.generateMipMaps + * @param options.mesh + * @param scene + * @param onError + */ + constructor(name, textureUrlOrElement, options, scene, + // eslint-disable-next-line @typescript-eslint/naming-convention + onError = null) { + super(name, scene); + this.onError = onError; + this._halfDome = false; + this._crossEye = false; + this._useDirectMapping = false; + this._textureMode = TextureDome.MODE_MONOSCOPIC; + /** + * Oberserver used in Stereoscopic VR Mode. + */ + this._onBeforeCameraRenderObserver = null; + /** + * Observable raised when an error occurred while loading the texture + */ + this.onLoadErrorObservable = new Observable(); + /** + * Observable raised when the texture finished loading + */ + this.onLoadObservable = new Observable(); + scene = this.getScene(); + // set defaults and manage values + name = name || "textureDome"; + options.resolution = Math.abs(options.resolution) | 0 || 32; + options.clickToPlay = Boolean(options.clickToPlay); + options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay); + options.loop = options.loop === undefined ? true : Boolean(options.loop); + options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000); + if (options.useDirectMapping === undefined) { + this._useDirectMapping = true; + } + else { + this._useDirectMapping = options.useDirectMapping; + } + if (options.faceForward === undefined) { + options.faceForward = true; + } + this._setReady(false); + if (!options.mesh) { + this._mesh = CreateSphere(name + "_mesh", { segments: options.resolution, diameter: options.size, updatable: false, sideOrientation: Mesh.BACKSIDE }, scene); + } + else { + this._mesh = options.mesh; + } + // configure material + const material = (this._material = new BackgroundMaterial(name + "_material", scene)); + material.useEquirectangularFOV = true; + material.fovMultiplier = 1.0; + material.opacityFresnel = false; + const texture = this._initTexture(textureUrlOrElement, scene, options); + this.texture = texture; + // configure mesh + this._mesh.material = material; + this._mesh.parent = this; + // create a (disabled until needed) mask to cover unneeded segments of 180 texture. + this._halfDomeMask = CreateSphere("", { slice: 0.5, diameter: options.size * 0.98, segments: options.resolution * 2, sideOrientation: Mesh.BACKSIDE }, scene); + this._halfDomeMask.rotate(Axis.X, -Math.PI / 2); + // set the parent, so it will always be positioned correctly AND will be disposed when the main sphere is disposed + this._halfDomeMask.parent = this._mesh; + this._halfDome = !!options.halfDomeMode; + // enable or disable according to the settings + this._halfDomeMask.setEnabled(this._halfDome); + this._crossEye = !!options.crossEyeMode; + // create + this._texture.anisotropicFilteringLevel = 1; + this._texture.onLoadObservable.addOnce(() => { + this._setReady(true); + }); + // Initial rotation + if (options.faceForward && scene.activeCamera) { + const camera = scene.activeCamera; + const forward = Vector3.Forward(); + const direction = Vector3.TransformNormal(forward, camera.getViewMatrix()); + direction.normalize(); + this.rotation.y = Math.acos(Vector3.Dot(forward, direction)); + } + this._changeTextureMode(this._textureMode); + } + _changeTextureMode(value) { + this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); + this._textureMode = value; + // Default Setup and Reset. + this._texture.uScale = 1; + this._texture.vScale = 1; + this._texture.uOffset = 0; + this._texture.vOffset = 0; + this._texture.vAng = 0; + switch (value) { + case TextureDome.MODE_MONOSCOPIC: + if (this._halfDome) { + this._texture.uScale = 2; + this._texture.uOffset = -1; + } + break; + case TextureDome.MODE_SIDEBYSIDE: { + // in half-dome mode the uScale should be double of 360 texture + // Use 0.99999 to boost perf by not switching program + this._texture.uScale = this._halfDome ? 0.99999 : 0.5; + const rightOffset = this._halfDome ? 0.0 : 0.5; + const leftOffset = this._halfDome ? -0.5 : 0.0; + this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add((camera) => { + let isRightCamera = camera.isRightCamera; + if (this._crossEye) { + isRightCamera = !isRightCamera; + } + if (isRightCamera) { + this._texture.uOffset = rightOffset; + } + else { + this._texture.uOffset = leftOffset; + } + }); + break; + } + case TextureDome.MODE_TOPBOTTOM: + // in half-dome mode the vScale should be double of 360 texture + // Use 0.99999 to boost perf by not switching program + this._texture.vScale = this._halfDome ? 0.99999 : 0.5; + this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add((camera) => { + let isRightCamera = camera.isRightCamera; + // allow "cross-eye" if left and right were switched in this mode + if (this._crossEye) { + isRightCamera = !isRightCamera; + } + this._texture.vOffset = isRightCamera ? 0.5 : 0.0; + }); + break; + } + } + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse, disposeMaterialAndTextures = false) { + this._texture.dispose(); + this._mesh.dispose(); + this._material.dispose(); + this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); + this.onLoadErrorObservable.clear(); + this.onLoadObservable.clear(); + super.dispose(doNotRecurse, disposeMaterialAndTextures); + } +} +/** + * Define the source as a Monoscopic panoramic 360/180. + */ +TextureDome.MODE_MONOSCOPIC = 0; +/** + * Define the source as a Stereoscopic TopBottom/OverUnder panoramic 360/180. + */ +TextureDome.MODE_TOPBOTTOM = 1; +/** + * Define the source as a Stereoscopic Side by Side panoramic 360/180. + */ +TextureDome.MODE_SIDEBYSIDE = 2; + +/** + * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes. + * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene. + * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere. + * Potential additions to this helper include zoom and and non-infinite distance rendering effects. + */ +class PhotoDome extends TextureDome { + /** + * Gets or sets the texture being displayed on the sphere + */ + get photoTexture() { + return this.texture; + } + /** + * sets the texture being displayed on the sphere + */ + set photoTexture(value) { + this.texture = value; + } + /** + * Gets the current video mode for the video. It can be: + * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360. + * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360. + * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360. + */ + get imageMode() { + return this.textureMode; + } + /** + * Sets the current video mode for the video. It can be: + * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360. + * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360. + * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360. + */ + set imageMode(value) { + this.textureMode = value; + } + _initTexture(urlsOrElement, scene, options) { + return new Texture(urlsOrElement, scene, !options.generateMipMaps, !this._useDirectMapping, undefined, () => { + this.onLoadObservable.notifyObservers(); + }, (message, exception) => { + this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured"); + if (this.onError) { + this.onError(message, exception); + } + }); + } +} +/** + * Define the image as a Monoscopic panoramic 360 image. + */ +PhotoDome.MODE_MONOSCOPIC = TextureDome.MODE_MONOSCOPIC; +/** + * Define the image as a Stereoscopic TopBottom/OverUnder panoramic 360 image. + */ +PhotoDome.MODE_TOPBOTTOM = TextureDome.MODE_TOPBOTTOM; +/** + * Define the image as a Stereoscopic Side by Side panoramic 360 image. + */ +PhotoDome.MODE_SIDEBYSIDE = TextureDome.MODE_SIDEBYSIDE; + +/* eslint-disable @typescript-eslint/naming-convention */ +// Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html +// All values and structures referenced from: +// http://msdn.microsoft.com/en-us/library/bb943991.aspx/ +const DDS_MAGIC = 0x20534444; +const //DDSD_CAPS = 0x1, +//DDSD_HEIGHT = 0x2, +//DDSD_WIDTH = 0x4, +//DDSD_PITCH = 0x8, +//DDSD_PIXELFORMAT = 0x1000, +DDSD_MIPMAPCOUNT = 0x20000; +//DDSD_LINEARSIZE = 0x80000, +//DDSD_DEPTH = 0x800000; +// var DDSCAPS_COMPLEX = 0x8, +// DDSCAPS_MIPMAP = 0x400000, +// DDSCAPS_TEXTURE = 0x1000; +const DDSCAPS2_CUBEMAP = 0x200; +// DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, +// DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, +// DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, +// DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, +// DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, +// DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, +// DDSCAPS2_VOLUME = 0x200000; +const //DDPF_ALPHAPIXELS = 0x1, +//DDPF_ALPHA = 0x2, +DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, +//DDPF_YUV = 0x200, +DDPF_LUMINANCE = 0x20000; +function FourCCToInt32(value) { + return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24); +} +function Int32ToFourCC(value) { + return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff); +} +const FOURCC_DXT1 = FourCCToInt32("DXT1"); +const FOURCC_DXT3 = FourCCToInt32("DXT3"); +const FOURCC_DXT5 = FourCCToInt32("DXT5"); +const FOURCC_DX10 = FourCCToInt32("DX10"); +const FOURCC_D3DFMT_R16G16B16A16F = 113; +const FOURCC_D3DFMT_R32G32B32A32F = 116; +const DXGI_FORMAT_R32G32B32A32_FLOAT = 2; +const DXGI_FORMAT_R16G16B16A16_FLOAT = 10; +const DXGI_FORMAT_B8G8R8X8_UNORM = 88; +const headerLengthInt = 31; // The header length in 32 bit ints +// Offsets into the header array +const off_magic = 0; +const off_size = 1; +const off_flags = 2; +const off_height = 3; +const off_width = 4; +const off_mipmapCount = 7; +const off_pfFlags = 20; +const off_pfFourCC = 21; +const off_RGBbpp = 22; +const off_RMask = 23; +const off_GMask = 24; +const off_BMask = 25; +const off_AMask = 26; +// var off_caps1 = 27; +const off_caps2 = 28; +// var off_caps3 = 29; +// var off_caps4 = 30; +const off_dxgiFormat = 32; +/** + * Class used to provide DDS decompression tools + */ +class DDSTools { + /** + * Gets DDS information from an array buffer + * @param data defines the array buffer view to read data from + * @returns the DDS information + */ + static GetDDSInfo(data) { + const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt); + const extendedHeader = new Int32Array(data.buffer, data.byteOffset, headerLengthInt + 4); + let mipmapCount = 1; + if (header[off_flags] & DDSD_MIPMAPCOUNT) { + mipmapCount = Math.max(1, header[off_mipmapCount]); + } + const fourCC = header[off_pfFourCC]; + const dxgiFormat = fourCC === FOURCC_DX10 ? extendedHeader[off_dxgiFormat] : 0; + let textureType = 0; + switch (fourCC) { + case FOURCC_D3DFMT_R16G16B16A16F: + textureType = 2; + break; + case FOURCC_D3DFMT_R32G32B32A32F: + textureType = 1; + break; + case FOURCC_DX10: + if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) { + textureType = 2; + break; + } + if (dxgiFormat === DXGI_FORMAT_R32G32B32A32_FLOAT) { + textureType = 1; + break; + } + } + return { + width: header[off_width], + height: header[off_height], + mipmapCount: mipmapCount, + isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC, + isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB, + isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE, + isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP, + isCompressed: fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5, + dxgiFormat: dxgiFormat, + textureType: textureType, + }; + } + static _GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { + const destArray = new Float32Array(dataLength); + const srcData = new Uint16Array(arrayBuffer, dataOffset); + let index = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const srcPos = (x + y * width) * 4; + destArray[index] = FromHalfFloat(srcData[srcPos]); + destArray[index + 1] = FromHalfFloat(srcData[srcPos + 1]); + destArray[index + 2] = FromHalfFloat(srcData[srcPos + 2]); + if (DDSTools.StoreLODInAlphaChannel) { + destArray[index + 3] = lod; + } + else { + destArray[index + 3] = FromHalfFloat(srcData[srcPos + 3]); + } + index += 4; + } + } + return destArray; + } + static _GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { + if (DDSTools.StoreLODInAlphaChannel) { + const destArray = new Uint16Array(dataLength); + const srcData = new Uint16Array(arrayBuffer, dataOffset); + let index = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const srcPos = (x + y * width) * 4; + destArray[index] = srcData[srcPos]; + destArray[index + 1] = srcData[srcPos + 1]; + destArray[index + 2] = srcData[srcPos + 2]; + destArray[index + 3] = ToHalfFloat$1(lod); + index += 4; + } + } + return destArray; + } + return new Uint16Array(arrayBuffer, dataOffset, dataLength); + } + static _GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { + if (DDSTools.StoreLODInAlphaChannel) { + const destArray = new Float32Array(dataLength); + const srcData = new Float32Array(arrayBuffer, dataOffset); + let index = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const srcPos = (x + y * width) * 4; + destArray[index] = srcData[srcPos]; + destArray[index + 1] = srcData[srcPos + 1]; + destArray[index + 2] = srcData[srcPos + 2]; + destArray[index + 3] = lod; + index += 4; + } + } + return destArray; + } + return new Float32Array(arrayBuffer, dataOffset, dataLength); + } + static _GetFloatAsHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { + const destArray = new Uint16Array(dataLength); + const srcData = new Float32Array(arrayBuffer, dataOffset); + let index = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + destArray[index] = ToHalfFloat$1(srcData[index]); + destArray[index + 1] = ToHalfFloat$1(srcData[index + 1]); + destArray[index + 2] = ToHalfFloat$1(srcData[index + 2]); + if (DDSTools.StoreLODInAlphaChannel) { + destArray[index + 3] = ToHalfFloat$1(lod); + } + else { + destArray[index + 3] = ToHalfFloat$1(srcData[index + 3]); + } + index += 4; + } + } + return destArray; + } + static _GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { + const destArray = new Uint8Array(dataLength); + const srcData = new Float32Array(arrayBuffer, dataOffset); + let index = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const srcPos = (x + y * width) * 4; + destArray[index] = Clamp(srcData[srcPos]) * 255; + destArray[index + 1] = Clamp(srcData[srcPos + 1]) * 255; + destArray[index + 2] = Clamp(srcData[srcPos + 2]) * 255; + if (DDSTools.StoreLODInAlphaChannel) { + destArray[index + 3] = lod; + } + else { + destArray[index + 3] = Clamp(srcData[srcPos + 3]) * 255; + } + index += 4; + } + } + return destArray; + } + static _GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { + const destArray = new Uint8Array(dataLength); + const srcData = new Uint16Array(arrayBuffer, dataOffset); + let index = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const srcPos = (x + y * width) * 4; + destArray[index] = Clamp(FromHalfFloat(srcData[srcPos])) * 255; + destArray[index + 1] = Clamp(FromHalfFloat(srcData[srcPos + 1])) * 255; + destArray[index + 2] = Clamp(FromHalfFloat(srcData[srcPos + 2])) * 255; + if (DDSTools.StoreLODInAlphaChannel) { + destArray[index + 3] = lod; + } + else { + destArray[index + 3] = Clamp(FromHalfFloat(srcData[srcPos + 3])) * 255; + } + index += 4; + } + } + return destArray; + } + static _GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) { + const byteArray = new Uint8Array(dataLength); + const srcData = new Uint8Array(arrayBuffer, dataOffset); + let index = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const srcPos = (x + y * width) * 4; + byteArray[index] = srcData[srcPos + rOffset]; + byteArray[index + 1] = srcData[srcPos + gOffset]; + byteArray[index + 2] = srcData[srcPos + bOffset]; + byteArray[index + 3] = srcData[srcPos + aOffset]; + index += 4; + } + } + return byteArray; + } + static _ExtractLongWordOrder(value) { + if (value === 0 || value === 255 || value === -16777216) { + return 0; + } + return 1 + DDSTools._ExtractLongWordOrder(value >> 8); + } + static _GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) { + const byteArray = new Uint8Array(dataLength); + const srcData = new Uint8Array(arrayBuffer, dataOffset); + let index = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const srcPos = (x + y * width) * 3; + byteArray[index] = srcData[srcPos + rOffset]; + byteArray[index + 1] = srcData[srcPos + gOffset]; + byteArray[index + 2] = srcData[srcPos + bOffset]; + index += 3; + } + } + return byteArray; + } + static _GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer) { + const byteArray = new Uint8Array(dataLength); + const srcData = new Uint8Array(arrayBuffer, dataOffset); + let index = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const srcPos = x + y * width; + byteArray[index] = srcData[srcPos]; + index++; + } + } + return byteArray; + } + /** + * Uploads DDS Levels to a Babylon Texture + * @internal + */ + static UploadDDSLevels(engine, texture, data, info, loadMipmaps, faces, lodIndex = -1, currentFace, destTypeMustBeFilterable = true) { + let sphericalPolynomialFaces = null; + if (info.sphericalPolynomial) { + sphericalPolynomialFaces = []; + } + const ext = !!engine.getCaps().s3tc; + // TODO WEBGPU Once generateMipMaps is split into generateMipMaps + hasMipMaps in InternalTexture this line can be removed + texture.generateMipMaps = loadMipmaps; + const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt); + let fourCC, width, height, dataLength = 0, dataOffset; + let byteArray, mipmapCount, mip; + let internalCompressedFormat = 0; + let blockBytes = 1; + if (header[off_magic] !== DDS_MAGIC) { + Logger.Error("Invalid magic number in DDS header"); + return; + } + if (!info.isFourCC && !info.isRGB && !info.isLuminance) { + Logger.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code"); + return; + } + if (info.isCompressed && !ext) { + Logger.Error("Compressed textures are not supported on this platform."); + return; + } + let bpp = header[off_RGBbpp]; + dataOffset = header[off_size] + 4; + let computeFormats = false; + if (info.isFourCC) { + fourCC = header[off_pfFourCC]; + switch (fourCC) { + case FOURCC_DXT1: + blockBytes = 8; + internalCompressedFormat = 33777; + break; + case FOURCC_DXT3: + blockBytes = 16; + internalCompressedFormat = 33778; + break; + case FOURCC_DXT5: + blockBytes = 16; + internalCompressedFormat = 33779; + break; + case FOURCC_D3DFMT_R16G16B16A16F: + computeFormats = true; + bpp = 64; + break; + case FOURCC_D3DFMT_R32G32B32A32F: + computeFormats = true; + bpp = 128; + break; + case FOURCC_DX10: { + // There is an additionnal header so dataOffset need to be changed + dataOffset += 5 * 4; // 5 uints + let supported = false; + switch (info.dxgiFormat) { + case DXGI_FORMAT_R16G16B16A16_FLOAT: + computeFormats = true; + bpp = 64; + supported = true; + break; + case DXGI_FORMAT_R32G32B32A32_FLOAT: + computeFormats = true; + bpp = 128; + supported = true; + break; + case DXGI_FORMAT_B8G8R8X8_UNORM: + info.isRGB = true; + info.isFourCC = false; + bpp = 32; + supported = true; + break; + } + if (supported) { + break; + } + } + // eslint-disable-next-line no-fallthrough + default: + Logger.Error(["Unsupported FourCC code:", Int32ToFourCC(fourCC)]); + return; + } + } + const rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]); + const gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]); + const bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]); + const aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]); + if (computeFormats) { + internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType); + } + mipmapCount = 1; + if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) { + mipmapCount = Math.max(1, header[off_mipmapCount]); + } + const startFace = currentFace || 0; + const caps = engine.getCaps(); + for (let face = startFace; face < faces; face++) { + width = header[off_width]; + height = header[off_height]; + for (mip = 0; mip < mipmapCount; ++mip) { + if (lodIndex === -1 || lodIndex === mip) { + // In case of fixed LOD, if the lod has just been uploaded, early exit. + const i = lodIndex === -1 ? mip : 0; + if (!info.isCompressed && info.isFourCC) { + texture.format = 5; + dataLength = width * height * 4; + let floatArray = null; + if (engine._badOS || engine._badDesktopOS || (!caps.textureHalfFloat && !caps.textureFloat)) { + // Required because iOS has many issues with float and half float generation + if (bpp === 128) { + floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i); + if (sphericalPolynomialFaces && i == 0) { + sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i)); + } + } + else if (bpp === 64) { + floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i); + if (sphericalPolynomialFaces && i == 0) { + sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i)); + } + } + texture.type = 0; + } + else { + const floatAvailable = caps.textureFloat && ((destTypeMustBeFilterable && caps.textureFloatLinearFiltering) || !destTypeMustBeFilterable); + const halfFloatAvailable = caps.textureHalfFloat && ((destTypeMustBeFilterable && caps.textureHalfFloatLinearFiltering) || !destTypeMustBeFilterable); + const destType = (bpp === 128 || (bpp === 64 && !halfFloatAvailable)) && floatAvailable + ? 1 + : (bpp === 64 || (bpp === 128 && !floatAvailable)) && halfFloatAvailable + ? 2 + : 0; + let dataGetter; + let dataGetterPolynomial = null; + switch (bpp) { + case 128: { + switch (destType) { + case 1: + dataGetter = DDSTools._GetFloatRGBAArrayBuffer; + dataGetterPolynomial = null; + break; + case 2: + dataGetter = DDSTools._GetFloatAsHalfFloatRGBAArrayBuffer; + dataGetterPolynomial = DDSTools._GetFloatRGBAArrayBuffer; + break; + case 0: + dataGetter = DDSTools._GetFloatAsUIntRGBAArrayBuffer; + dataGetterPolynomial = DDSTools._GetFloatRGBAArrayBuffer; + break; + } + break; + } + default: { + // 64 bpp + switch (destType) { + case 1: + dataGetter = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer; + dataGetterPolynomial = null; + break; + case 2: + dataGetter = DDSTools._GetHalfFloatRGBAArrayBuffer; + dataGetterPolynomial = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer; + break; + case 0: + dataGetter = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer; + dataGetterPolynomial = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer; + break; + } + break; + } + } + texture.type = destType; + floatArray = dataGetter(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i); + if (sphericalPolynomialFaces && i == 0) { + sphericalPolynomialFaces.push(dataGetterPolynomial ? dataGetterPolynomial(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i) : floatArray); + } + } + if (floatArray) { + engine._uploadDataToTextureDirectly(texture, floatArray, face, i); + } + } + else if (info.isRGB) { + texture.type = 0; + if (bpp === 24) { + texture.format = 4; + dataLength = width * height * 3; + byteArray = DDSTools._GetRGBArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset); + engine._uploadDataToTextureDirectly(texture, byteArray, face, i); + } + else { + // 32 + texture.format = 5; + dataLength = width * height * 4; + byteArray = DDSTools._GetRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset, aOffset); + engine._uploadDataToTextureDirectly(texture, byteArray, face, i); + } + } + else if (info.isLuminance) { + const unpackAlignment = engine._getUnpackAlignement(); + const unpaddedRowSize = width; + const paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment; + dataLength = paddedRowSize * (height - 1) + unpaddedRowSize; + byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer); + texture.format = 1; + texture.type = 0; + engine._uploadDataToTextureDirectly(texture, byteArray, face, i); + } + else { + dataLength = (((Math.max(4, width) / 4) * Math.max(4, height)) / 4) * blockBytes; + byteArray = new Uint8Array(data.buffer, data.byteOffset + dataOffset, dataLength); + texture.type = 0; + engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i); + } + } + dataOffset += bpp ? width * height * (bpp / 8) : dataLength; + width *= 0.5; + height *= 0.5; + width = Math.max(1.0, width); + height = Math.max(1.0, height); + } + if (currentFace !== undefined) { + // Loading a single face + break; + } + } + if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) { + info.sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({ + size: header[off_width], + right: sphericalPolynomialFaces[0], + left: sphericalPolynomialFaces[1], + up: sphericalPolynomialFaces[2], + down: sphericalPolynomialFaces[3], + front: sphericalPolynomialFaces[4], + back: sphericalPolynomialFaces[5], + format: 5, + type: 1, + gammaSpace: false, + }); + } + else { + info.sphericalPolynomial = undefined; + } + } +} +/** + * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default) + */ +DDSTools.StoreLODInAlphaChannel = false; + +const dds = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + DDSTools +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Implementation of the DDS Texture Loader. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _DDSTextureLoader { + constructor() { + /** + * Defines whether the loader supports cascade loading the different faces. + */ + this.supportCascades = true; + } + /** + * Uploads the cube texture data to the WebGL texture. It has already been bound. + * @param imgs contains the cube maps + * @param texture defines the BabylonJS internal texture + * @param createPolynomials will be true if polynomials have been requested + * @param onLoad defines the callback to trigger once the texture is ready + */ + loadCubeData(imgs, texture, createPolynomials, onLoad) { + const engine = texture.getEngine(); + let info; + let loadMipmap = false; + let maxLevel = 1000; + if (Array.isArray(imgs)) { + for (let index = 0; index < imgs.length; index++) { + const data = imgs[index]; + info = DDSTools.GetDDSInfo(data); + texture.width = info.width; + texture.height = info.height; + loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps; + engine._unpackFlipY(info.isCompressed); + DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6, -1, index); + if (!info.isFourCC && info.mipmapCount === 1) { + engine.generateMipMapsForCubemap(texture); + } + else { + maxLevel = info.mipmapCount - 1; + } + } + } + else { + const data = imgs; + info = DDSTools.GetDDSInfo(data); + texture.width = info.width; + texture.height = info.height; + if (createPolynomials) { + info.sphericalPolynomial = new SphericalPolynomial(); + } + loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps; + engine._unpackFlipY(info.isCompressed); + DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6); + if (!info.isFourCC && info.mipmapCount === 1) { + // Do not unbind as we still need to set the parameters. + engine.generateMipMapsForCubemap(texture, false); + } + else { + maxLevel = info.mipmapCount - 1; + } + } + engine._setCubeMapTextureParams(texture, loadMipmap, maxLevel); + texture.isReady = true; + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + if (onLoad) { + onLoad({ isDDS: true, width: texture.width, info, data: imgs, texture }); + } + } + /** + * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + */ + loadData(data, texture, callback) { + const info = DDSTools.GetDDSInfo(data); + const loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && Math.max(info.width, info.height) >> (info.mipmapCount - 1) === 1; + callback(info.width, info.height, loadMipmap, info.isFourCC, () => { + DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1); + }); + } +} + +const ddsTextureLoader = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + _DDSTextureLoader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Implementation of the ENV Texture Loader. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _ENVTextureLoader { + constructor() { + /** + * Defines whether the loader supports cascade loading the different faces. + */ + this.supportCascades = false; + } + /** + * Uploads the cube texture data to the WebGL texture. It has already been bound. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param createPolynomials will be true if polynomials have been requested + * @param onLoad defines the callback to trigger once the texture is ready + * @param onError defines the callback to trigger in case of error + */ + loadCubeData(data, texture, createPolynomials, onLoad, onError) { + if (Array.isArray(data)) { + return; + } + const info = GetEnvInfo(data); + if (info) { + texture.width = info.width; + texture.height = info.width; + try { + UploadEnvSpherical(texture, info); + UploadEnvLevelsAsync(texture, data, info).then(() => { + texture.isReady = true; + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + if (onLoad) { + onLoad(); + } + }, (reason) => { + onError?.("Can not upload environment levels", reason); + }); + } + catch (e) { + onError?.("Can not upload environment file", e); + } + } + else if (onError) { + onError("Can not parse the environment file", null); + } + } + /** + * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. + */ + loadData() { + // eslint-disable-next-line no-throw-literal + throw ".env not supported in 2d."; + } +} + +const envTextureLoader = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + _ENVTextureLoader +}, Symbol.toStringTag, { value: 'Module' })); + +/* eslint-disable @typescript-eslint/naming-convention */ +/** + * for description see https://www.khronos.org/opengles/sdk/tools/KTX/ + * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + */ +class KhronosTextureContainer { + /** + * Creates a new KhronosTextureContainer + * @param data contents of the KTX container file + * @param facesExpected should be either 1 or 6, based whether a cube texture or or + */ + constructor( + /** contents of the KTX container file */ + data, facesExpected) { + this.data = data; + /** + * If the container has been made invalid (eg. constructor failed to correctly load array buffer) + */ + this.isInvalid = false; + if (!KhronosTextureContainer.IsValid(data)) { + this.isInvalid = true; + Logger.Error("texture missing KTX identifier"); + return; + } + // load the reset of the header in native 32 bit uint + const dataSize = Uint32Array.BYTES_PER_ELEMENT; + const headerDataView = new DataView(this.data.buffer, this.data.byteOffset + 12, 13 * dataSize); + const endianness = headerDataView.getUint32(0, true); + const littleEndian = endianness === 0x04030201; + this.glType = headerDataView.getUint32(1 * dataSize, littleEndian); // must be 0 for compressed textures + this.glTypeSize = headerDataView.getUint32(2 * dataSize, littleEndian); // must be 1 for compressed textures + this.glFormat = headerDataView.getUint32(3 * dataSize, littleEndian); // must be 0 for compressed textures + this.glInternalFormat = headerDataView.getUint32(4 * dataSize, littleEndian); // the value of arg passed to gl.compressedTexImage2D(,,x,,,,) + this.glBaseInternalFormat = headerDataView.getUint32(5 * dataSize, littleEndian); // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only) + this.pixelWidth = headerDataView.getUint32(6 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,) + this.pixelHeight = headerDataView.getUint32(7 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,) + this.pixelDepth = headerDataView.getUint32(8 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,) + this.numberOfArrayElements = headerDataView.getUint32(9 * dataSize, littleEndian); // used for texture arrays + this.numberOfFaces = headerDataView.getUint32(10 * dataSize, littleEndian); // used for cubemap textures, should either be 1 or 6 + this.numberOfMipmapLevels = headerDataView.getUint32(11 * dataSize, littleEndian); // number of levels; disregard possibility of 0 for compressed textures + this.bytesOfKeyValueData = headerDataView.getUint32(12 * dataSize, littleEndian); // the amount of space after the header for meta-data + // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing. + if (this.glType !== 0) { + Logger.Error("only compressed formats currently supported"); + this.isInvalid = true; + return; + } + else { + // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard. + this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels); + } + if (this.pixelHeight === 0 || this.pixelDepth !== 0) { + Logger.Error("only 2D textures currently supported"); + this.isInvalid = true; + return; + } + if (this.numberOfArrayElements !== 0) { + Logger.Error("texture arrays not currently supported"); + this.isInvalid = true; + return; + } + if (this.numberOfFaces !== facesExpected) { + Logger.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces); + this.isInvalid = true; + return; + } + // we now have a completely validated file, so could use existence of loadType as success + // would need to make this more elaborate & adjust checks above to support more than one load type + this.loadType = KhronosTextureContainer.COMPRESSED_2D; + } + /** + * Uploads KTX content to a Babylon Texture. + * It is assumed that the texture has already been created & is currently bound + * @internal + */ + uploadLevels(texture, loadMipmaps) { + switch (this.loadType) { + case KhronosTextureContainer.COMPRESSED_2D: + this._upload2DCompressedLevels(texture, loadMipmaps); + break; + } + } + _upload2DCompressedLevels(texture, loadMipmaps) { + // initialize width & height for level 1 + let dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData; + let width = this.pixelWidth; + let height = this.pixelHeight; + const mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1; + for (let level = 0; level < mipmapCount; level++) { + const imageSize = new Int32Array(this.data.buffer, this.data.byteOffset + dataOffset, 1)[0]; // size per face, since not supporting array cubemaps + dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above. + for (let face = 0; face < this.numberOfFaces; face++) { + const byteArray = new Uint8Array(this.data.buffer, this.data.byteOffset + dataOffset, imageSize); + const engine = texture.getEngine(); + engine._uploadCompressedDataToTextureDirectly(texture, texture.format, width, height, byteArray, face, level); + dataOffset += imageSize; // add size of the image for the next face/mipmap + dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image + } + width = Math.max(1.0, width * 0.5); + height = Math.max(1.0, height * 0.5); + } + } + /** + * Checks if the given data starts with a KTX file identifier. + * @param data the data to check + * @returns true if the data is a KTX file or false otherwise + */ + static IsValid(data) { + if (data.byteLength >= 12) { + // '«', 'K', 'T', 'X', ' ', '1', '1', '»', '\r', '\n', '\x1A', '\n' + const identifier = new Uint8Array(data.buffer, data.byteOffset, 12); + if (identifier[0] === 0xab && + identifier[1] === 0x4b && + identifier[2] === 0x54 && + identifier[3] === 0x58 && + identifier[4] === 0x20 && + identifier[5] === 0x31 && + identifier[6] === 0x31 && + identifier[7] === 0xbb && + identifier[8] === 0x0d && + identifier[9] === 0x0a && + identifier[10] === 0x1a && + identifier[11] === 0x0a) { + return true; + } + } + return false; + } +} +KhronosTextureContainer.HEADER_LEN = 12 + 13 * 4; // identifier + header elements (not including key value meta-data pairs) +// load types +KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D() +KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D() +KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D() +KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D() + +var SourceTextureFormat; +(function (SourceTextureFormat) { + SourceTextureFormat[SourceTextureFormat["ETC1S"] = 0] = "ETC1S"; + SourceTextureFormat[SourceTextureFormat["UASTC4x4"] = 1] = "UASTC4x4"; +})(SourceTextureFormat || (SourceTextureFormat = {})); +var TranscodeTarget; +(function (TranscodeTarget) { + TranscodeTarget[TranscodeTarget["ASTC_4X4_RGBA"] = 0] = "ASTC_4X4_RGBA"; + TranscodeTarget[TranscodeTarget["BC7_RGBA"] = 1] = "BC7_RGBA"; + TranscodeTarget[TranscodeTarget["BC3_RGBA"] = 2] = "BC3_RGBA"; + TranscodeTarget[TranscodeTarget["BC1_RGB"] = 3] = "BC1_RGB"; + TranscodeTarget[TranscodeTarget["PVRTC1_4_RGBA"] = 4] = "PVRTC1_4_RGBA"; + TranscodeTarget[TranscodeTarget["PVRTC1_4_RGB"] = 5] = "PVRTC1_4_RGB"; + TranscodeTarget[TranscodeTarget["ETC2_RGBA"] = 6] = "ETC2_RGBA"; + TranscodeTarget[TranscodeTarget["ETC1_RGB"] = 7] = "ETC1_RGB"; + TranscodeTarget[TranscodeTarget["RGBA32"] = 8] = "RGBA32"; + TranscodeTarget[TranscodeTarget["R8"] = 9] = "R8"; + TranscodeTarget[TranscodeTarget["RG8"] = 10] = "RG8"; +})(TranscodeTarget || (TranscodeTarget = {})); +var EngineFormat; +(function (EngineFormat) { + EngineFormat[EngineFormat["COMPRESSED_RGBA_BPTC_UNORM_EXT"] = 36492] = "COMPRESSED_RGBA_BPTC_UNORM_EXT"; + EngineFormat[EngineFormat["COMPRESSED_RGBA_ASTC_4X4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4X4_KHR"; + EngineFormat[EngineFormat["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT"; + EngineFormat[EngineFormat["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT"; + EngineFormat[EngineFormat["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; + EngineFormat[EngineFormat["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; + EngineFormat[EngineFormat["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC"; + EngineFormat[EngineFormat["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2"; + EngineFormat[EngineFormat["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL"; + EngineFormat[EngineFormat["RGBA8Format"] = 32856] = "RGBA8Format"; + EngineFormat[EngineFormat["R8Format"] = 33321] = "R8Format"; + EngineFormat[EngineFormat["RG8Format"] = 33323] = "RG8Format"; +})(EngineFormat || (EngineFormat = {})); + +function applyConfig(urls, binariesAndModulesContainer) { + const KTX2DecoderModule = binariesAndModulesContainer?.jsDecoderModule || KTX2DECODER; + if (urls) { + if (urls.wasmUASTCToASTC) { + KTX2DecoderModule.LiteTranscoder_UASTC_ASTC.WasmModuleURL = urls.wasmUASTCToASTC; + } + if (urls.wasmUASTCToBC7) { + KTX2DecoderModule.LiteTranscoder_UASTC_BC7.WasmModuleURL = urls.wasmUASTCToBC7; + } + if (urls.wasmUASTCToRGBA_UNORM) { + KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = urls.wasmUASTCToRGBA_UNORM; + } + if (urls.wasmUASTCToRGBA_SRGB) { + KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = urls.wasmUASTCToRGBA_SRGB; + } + if (urls.wasmUASTCToR8_UNORM) { + KTX2DecoderModule.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL = urls.wasmUASTCToR8_UNORM; + } + if (urls.wasmUASTCToRG8_UNORM) { + KTX2DecoderModule.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL = urls.wasmUASTCToRG8_UNORM; + } + if (urls.jsMSCTranscoder) { + KTX2DecoderModule.MSCTranscoder.JSModuleURL = urls.jsMSCTranscoder; + } + if (urls.wasmMSCTranscoder) { + KTX2DecoderModule.MSCTranscoder.WasmModuleURL = urls.wasmMSCTranscoder; + } + if (urls.wasmZSTDDecoder) { + KTX2DecoderModule.ZSTDDecoder.WasmModuleURL = urls.wasmZSTDDecoder; + } + } + if (binariesAndModulesContainer) { + if (binariesAndModulesContainer.wasmUASTCToASTC) { + KTX2DecoderModule.LiteTranscoder_UASTC_ASTC.WasmBinary = binariesAndModulesContainer.wasmUASTCToASTC; + } + if (binariesAndModulesContainer.wasmUASTCToBC7) { + KTX2DecoderModule.LiteTranscoder_UASTC_BC7.WasmBinary = binariesAndModulesContainer.wasmUASTCToBC7; + } + if (binariesAndModulesContainer.wasmUASTCToRGBA_UNORM) { + KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary = binariesAndModulesContainer.wasmUASTCToRGBA_UNORM; + } + if (binariesAndModulesContainer.wasmUASTCToRGBA_SRGB) { + KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary = binariesAndModulesContainer.wasmUASTCToRGBA_SRGB; + } + if (binariesAndModulesContainer.wasmUASTCToR8_UNORM) { + KTX2DecoderModule.LiteTranscoder_UASTC_R8_UNORM.WasmBinary = binariesAndModulesContainer.wasmUASTCToR8_UNORM; + } + if (binariesAndModulesContainer.wasmUASTCToRG8_UNORM) { + KTX2DecoderModule.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary = binariesAndModulesContainer.wasmUASTCToRG8_UNORM; + } + if (binariesAndModulesContainer.jsMSCTranscoder) { + KTX2DecoderModule.MSCTranscoder.JSModule = binariesAndModulesContainer.jsMSCTranscoder; + } + if (binariesAndModulesContainer.wasmMSCTranscoder) { + KTX2DecoderModule.MSCTranscoder.WasmBinary = binariesAndModulesContainer.wasmMSCTranscoder; + } + if (binariesAndModulesContainer.wasmZSTDDecoder) { + KTX2DecoderModule.ZSTDDecoder.WasmBinary = binariesAndModulesContainer.wasmZSTDDecoder; + } + } +} +function workerFunction$1(KTX2DecoderModule) { + if (typeof KTX2DecoderModule === "undefined" && typeof KTX2DECODER !== "undefined") { + KTX2DecoderModule = KTX2DECODER; + } + let ktx2Decoder; + onmessage = (event) => { + if (!event.data) { + return; + } + switch (event.data.action) { + case "init": { + const urls = event.data.urls; + if (urls) { + if (urls.jsDecoderModule && typeof KTX2DecoderModule === "undefined") { + importScripts(urls.jsDecoderModule); + // assuming global namespace populated by the script (UMD pattern) + KTX2DecoderModule = KTX2DECODER; + } + applyConfig(urls); + } + if (event.data.wasmBinaries) { + applyConfig(undefined, { ...event.data.wasmBinaries, jsDecoderModule: KTX2DecoderModule }); + } + ktx2Decoder = new KTX2DecoderModule.KTX2Decoder(); + postMessage({ action: "init" }); + break; + } + case "setDefaultDecoderOptions": { + KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions = event.data.options; + break; + } + case "decode": + ktx2Decoder + .decode(event.data.data, event.data.caps, event.data.options) + .then((data) => { + const buffers = []; + for (let mip = 0; mip < data.mipmaps.length; ++mip) { + const mipmap = data.mipmaps[mip]; + if (mipmap && mipmap.data) { + buffers.push(mipmap.data.buffer); + } + } + postMessage({ action: "decoded", success: true, decodedData: data }, buffers); + }) + .catch((reason) => { + postMessage({ action: "decoded", success: false, msg: reason }); + }); + break; + } + }; +} +function initializeWebWorker$1(worker, wasmBinaries, urls) { + return new Promise((resolve, reject) => { + const onError = (error) => { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + reject(error); + }; + const onMessage = (message) => { + if (message.data.action === "init") { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + resolve(worker); + } + }; + worker.addEventListener("error", onError); + worker.addEventListener("message", onMessage); + worker.postMessage({ + action: "init", + urls, + wasmBinaries, + }); + }); +} + +/** + * Class that defines the default KTX2 decoder options. + * + * This class is useful for providing options to the KTX2 decoder to control how the source data is transcoded. + */ +class DefaultKTX2DecoderOptions { + constructor() { + this._isDirty = true; + this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = true; + this._ktx2DecoderOptions = {}; + } + /** + * Gets the dirty flag + */ + get isDirty() { + return this._isDirty; + } + /** + * force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and ASTC + BC7 are not available as a compressed transcoded format + */ + get useRGBAIfASTCBC7NotAvailableWhenUASTC() { + return this._useRGBAIfASTCBC7NotAvailableWhenUASTC; + } + set useRGBAIfASTCBC7NotAvailableWhenUASTC(value) { + if (this._useRGBAIfASTCBC7NotAvailableWhenUASTC === value) { + return; + } + this._useRGBAIfASTCBC7NotAvailableWhenUASTC = value; + this._isDirty = true; + } + /** + * force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and only BC1 or BC3 are available as a compressed transcoded format. + * This property is true by default to favor speed over memory, because currently transcoding from UASTC to BC1/3 is slow because the transcoder transcodes + * to uncompressed and then recompresses the texture + */ + get useRGBAIfOnlyBC1BC3AvailableWhenUASTC() { + return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC; + } + set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(value) { + if (this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC === value) { + return; + } + this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = value; + this._isDirty = true; + } + /** + * force to always use (uncompressed) RGBA for transcoded format + */ + get forceRGBA() { + return this._forceRGBA; + } + set forceRGBA(value) { + if (this._forceRGBA === value) { + return; + } + this._forceRGBA = value; + this._isDirty = true; + } + /** + * force to always use (uncompressed) R8 for transcoded format + */ + get forceR8() { + return this._forceR8; + } + set forceR8(value) { + if (this._forceR8 === value) { + return; + } + this._forceR8 = value; + this._isDirty = true; + } + /** + * force to always use (uncompressed) RG8 for transcoded format + */ + get forceRG8() { + return this._forceRG8; + } + set forceRG8(value) { + if (this._forceRG8 === value) { + return; + } + this._forceRG8 = value; + this._isDirty = true; + } + /** + * list of transcoders to bypass when looking for a suitable transcoder. The available transcoders are: + * UniversalTranscoder_UASTC_ASTC + * UniversalTranscoder_UASTC_BC7 + * UniversalTranscoder_UASTC_RGBA_UNORM + * UniversalTranscoder_UASTC_RGBA_SRGB + * UniversalTranscoder_UASTC_R8_UNORM + * UniversalTranscoder_UASTC_RG8_UNORM + * MSCTranscoder + */ + get bypassTranscoders() { + return this._bypassTranscoders; + } + set bypassTranscoders(value) { + if (this._bypassTranscoders === value) { + return; + } + this._bypassTranscoders = value; + this._isDirty = true; + } + /** @internal */ + _getKTX2DecoderOptions() { + if (!this._isDirty) { + return this._ktx2DecoderOptions; + } + this._isDirty = false; + const options = { + useRGBAIfASTCBC7NotAvailableWhenUASTC: this._useRGBAIfASTCBC7NotAvailableWhenUASTC, + forceRGBA: this._forceRGBA, + forceR8: this._forceR8, + forceRG8: this._forceRG8, + bypassTranscoders: this._bypassTranscoders, + }; + if (this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC) { + options.transcodeFormatDecisionTree = { + UASTC: { + transcodeFormat: [TranscodeTarget.BC1_RGB, TranscodeTarget.BC3_RGBA], + yes: { + transcodeFormat: TranscodeTarget.RGBA32, + engineFormat: 32856 /* EngineFormat.RGBA8Format */, + roundToMultiple4: false, + }, + }, + }; + } + this._ktx2DecoderOptions = options; + return options; + } +} +/** + * Class for loading KTX2 files + */ +class KhronosTextureContainer2 { + static GetDefaultNumWorkers() { + if (typeof navigator !== "object" || !navigator.hardwareConcurrency) { + return 1; + } + // Use 50% of the available logical processors but capped at 4. + return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4); + } + static _Initialize(numWorkers) { + if (KhronosTextureContainer2._WorkerPoolPromise || KhronosTextureContainer2._DecoderModulePromise) { + return; + } + const urls = { + jsDecoderModule: Tools.GetBabylonScriptURL(this.URLConfig.jsDecoderModule, true), + wasmUASTCToASTC: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC, true), + wasmUASTCToBC7: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7, true), + wasmUASTCToRGBA_UNORM: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM, true), + wasmUASTCToRGBA_SRGB: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB, true), + wasmUASTCToR8_UNORM: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM, true), + wasmUASTCToRG8_UNORM: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM, true), + jsMSCTranscoder: Tools.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder, true), + wasmMSCTranscoder: Tools.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder, true), + wasmZSTDDecoder: Tools.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder, true), + }; + if (numWorkers && typeof Worker === "function" && typeof URL !== "undefined") { + KhronosTextureContainer2._WorkerPoolPromise = new Promise((resolve) => { + const workerContent = `${applyConfig}(${workerFunction$1})()`; + const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" })); + resolve(new AutoReleaseWorkerPool(numWorkers, () => initializeWebWorker$1(new Worker(workerBlobUrl), undefined, urls))); + }); + } + else { + if (typeof KhronosTextureContainer2._KTX2DecoderModule === "undefined") { + KhronosTextureContainer2._DecoderModulePromise = Tools.LoadBabylonScriptAsync(urls.jsDecoderModule).then(() => { + KhronosTextureContainer2._KTX2DecoderModule = KTX2DECODER; + KhronosTextureContainer2._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread = false; + KhronosTextureContainer2._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread = true; + applyConfig(urls, KhronosTextureContainer2._KTX2DecoderModule); + return new KhronosTextureContainer2._KTX2DecoderModule.KTX2Decoder(); + }); + } + else { + KhronosTextureContainer2._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread = false; + KhronosTextureContainer2._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread = true; + KhronosTextureContainer2._DecoderModulePromise = Promise.resolve(new KhronosTextureContainer2._KTX2DecoderModule.KTX2Decoder()); + } + } + } + /** + * Constructor + * @param engine The engine to use + * @param numWorkersOrOptions The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context. + */ + constructor(engine, numWorkersOrOptions = KhronosTextureContainer2.DefaultNumWorkers) { + this._engine = engine; + const workerPoolOption = (typeof numWorkersOrOptions === "object" && numWorkersOrOptions.workerPool) || KhronosTextureContainer2.WorkerPool; + if (workerPoolOption) { + KhronosTextureContainer2._WorkerPoolPromise = Promise.resolve(workerPoolOption); + } + else { + // set the KTX2 decoder module + if (typeof numWorkersOrOptions === "object") { + KhronosTextureContainer2._KTX2DecoderModule = numWorkersOrOptions?.binariesAndModulesContainer?.jsDecoderModule; + } + else if (typeof KTX2DECODER !== "undefined") { + KhronosTextureContainer2._KTX2DecoderModule = KTX2DECODER; + } + const numberOfWorkers = typeof numWorkersOrOptions === "number" ? numWorkersOrOptions : (numWorkersOrOptions.numWorkers ?? KhronosTextureContainer2.DefaultNumWorkers); + KhronosTextureContainer2._Initialize(numberOfWorkers); + } + } + /** + * @internal + */ + _uploadAsync(data, internalTexture, options) { + const caps = this._engine.getCaps(); + const compressedTexturesCaps = { + astc: !!caps.astc, + bptc: !!caps.bptc, + s3tc: !!caps.s3tc, + pvrtc: !!caps.pvrtc, + etc2: !!caps.etc2, + etc1: !!caps.etc1, + }; + if (KhronosTextureContainer2._WorkerPoolPromise) { + return KhronosTextureContainer2._WorkerPoolPromise.then((workerPool) => { + return new Promise((resolve, reject) => { + workerPool.push((worker, onComplete) => { + const onError = (error) => { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + reject(error); + onComplete(); + }; + const onMessage = (message) => { + if (message.data.action === "decoded") { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + if (!message.data.success) { + reject({ message: message.data.msg }); + } + else { + try { + this._createTexture(message.data.decodedData, internalTexture, options); + resolve(); + } + catch (err) { + reject({ message: err }); + } + } + onComplete(); + } + }; + worker.addEventListener("error", onError); + worker.addEventListener("message", onMessage); + worker.postMessage({ action: "setDefaultDecoderOptions", options: KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions() }); + const dataCopy = new Uint8Array(data.byteLength); + dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); + worker.postMessage({ action: "decode", data: dataCopy, caps: compressedTexturesCaps, options }, [dataCopy.buffer]); + }); + }); + }); + } + else if (KhronosTextureContainer2._DecoderModulePromise) { + return KhronosTextureContainer2._DecoderModulePromise.then((decoder) => { + if (KhronosTextureContainer2.DefaultDecoderOptions.isDirty) { + KhronosTextureContainer2._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions = KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions(); + } + return new Promise((resolve, reject) => { + decoder + .decode(data, caps) + .then((data) => { + this._createTexture(data, internalTexture); + resolve(); + }) + .catch((reason) => { + reject({ message: reason }); + }); + }); + }); + } + throw new Error("KTX2 decoder module is not available"); + } + _createTexture(data, internalTexture, options) { + const oglTexture2D = 3553; // gl.TEXTURE_2D + this._engine._bindTextureDirectly(oglTexture2D, internalTexture); + if (options) { + // return back some information about the decoded data + options.transcodedFormat = data.transcodedFormat; + options.isInGammaSpace = data.isInGammaSpace; + options.hasAlpha = data.hasAlpha; + options.transcoderName = data.transcoderName; + } + let isUncompressedFormat = true; + switch (data.transcodedFormat) { + case 0x8058 /* RGBA8 */: + internalTexture.type = 0; + internalTexture.format = 5; + break; + case 0x8229 /* R8 */: + internalTexture.type = 0; + internalTexture.format = 6; + break; + case 0x822b /* RG8 */: + internalTexture.type = 0; + internalTexture.format = 7; + break; + default: + internalTexture.format = data.transcodedFormat; + isUncompressedFormat = false; + break; + } + internalTexture._gammaSpace = data.isInGammaSpace; + internalTexture.generateMipMaps = data.mipmaps.length > 1; + if (data.errors) { + throw new Error("KTX2 container - could not transcode the data. " + data.errors); + } + for (let t = 0; t < data.mipmaps.length; ++t) { + const mipmap = data.mipmaps[t]; + if (!mipmap || !mipmap.data) { + throw new Error("KTX2 container - could not transcode one of the image"); + } + if (isUncompressedFormat) { + // uncompressed RGBA / R8 / RG8 + internalTexture.width = mipmap.width; // need to set width/height so that the call to _uploadDataToTextureDirectly uses the right dimensions + internalTexture.height = mipmap.height; + this._engine._uploadDataToTextureDirectly(internalTexture, mipmap.data, 0, t, undefined, true); + } + else { + this._engine._uploadCompressedDataToTextureDirectly(internalTexture, data.transcodedFormat, mipmap.width, mipmap.height, mipmap.data, 0, t); + } + } + internalTexture._extension = ".ktx2"; + internalTexture.width = data.mipmaps[0].width; + internalTexture.height = data.mipmaps[0].height; + internalTexture.isReady = true; + this._engine._bindTextureDirectly(oglTexture2D, null); + } + /** + * Checks if the given data starts with a KTX2 file identifier. + * @param data the data to check + * @returns true if the data is a KTX2 file or false otherwise + */ + static IsValid(data) { + if (data.byteLength >= 12) { + // '«', 'K', 'T', 'X', ' ', '2', '0', '»', '\r', '\n', '\x1A', '\n' + const identifier = new Uint8Array(data.buffer, data.byteOffset, 12); + if (identifier[0] === 0xab && + identifier[1] === 0x4b && + identifier[2] === 0x54 && + identifier[3] === 0x58 && + identifier[4] === 0x20 && + identifier[5] === 0x32 && + identifier[6] === 0x30 && + identifier[7] === 0xbb && + identifier[8] === 0x0d && + identifier[9] === 0x0a && + identifier[10] === 0x1a && + identifier[11] === 0x0a) { + return true; + } + } + return false; + } +} +/** + * URLs to use when loading the KTX2 decoder module as well as its dependencies + * If a url is null, the default url is used (pointing to https://preview.babylonjs.com) + * Note that jsDecoderModule can't be null and that the other dependencies will only be loaded if necessary + * Urls you can change: + * URLConfig.jsDecoderModule + * URLConfig.wasmUASTCToASTC + * URLConfig.wasmUASTCToBC7 + * URLConfig.wasmUASTCToRGBA_UNORM + * URLConfig.wasmUASTCToRGBA_SRGB + * URLConfig.wasmUASTCToR8_UNORM + * URLConfig.wasmUASTCToRG8_UNORM + * URLConfig.jsMSCTranscoder + * URLConfig.wasmMSCTranscoder + * URLConfig.wasmZSTDDecoder + * You can see their default values in this PG: https://playground.babylonjs.com/#EIJH8L#29 + */ +KhronosTextureContainer2.URLConfig = { + jsDecoderModule: "https://cdn.babylonjs.com/babylon.ktx2Decoder.js", + wasmUASTCToASTC: null, + wasmUASTCToBC7: null, + wasmUASTCToRGBA_UNORM: null, + wasmUASTCToRGBA_SRGB: null, + wasmUASTCToR8_UNORM: null, + wasmUASTCToRG8_UNORM: null, + jsMSCTranscoder: null, + wasmMSCTranscoder: null, + wasmZSTDDecoder: null, +}; +/** + * Default number of workers used to handle data decoding + */ +KhronosTextureContainer2.DefaultNumWorkers = KhronosTextureContainer2.GetDefaultNumWorkers(); +/** + * Default configuration for the KTX2 decoder. + * The options defined in this way have priority over those passed when creating a KTX2 texture with new Texture(...). + */ +KhronosTextureContainer2.DefaultDecoderOptions = new DefaultKTX2DecoderOptions(); + +function mapSRGBToLinear(format) { + switch (format) { + case 35916: + return 33776; + case 35918: + return 33778; + case 35919: + return 33779; + case 37493: + return 37492; + case 37497: + return 37496; + case 37495: + return 37494; + case 37840: + return 37808; + case 36493: + return 36492; + } + return null; +} +/** + * Implementation of the KTX Texture Loader. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _KTXTextureLoader { + constructor() { + /** + * Defines whether the loader supports cascade loading the different faces. + */ + this.supportCascades = false; + } + /** + * Uploads the cube texture data to the WebGL texture. It has already been bound. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param createPolynomials will be true if polynomials have been requested + * @param onLoad defines the callback to trigger once the texture is ready + */ + loadCubeData(data, texture, createPolynomials, onLoad) { + if (Array.isArray(data)) { + return; + } + // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture + texture._invertVScale = !texture.invertY; + const engine = texture.getEngine(); + const ktx = new KhronosTextureContainer(data, 6); + const loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps; + engine._unpackFlipY(true); + ktx.uploadLevels(texture, texture.generateMipMaps); + texture.width = ktx.pixelWidth; + texture.height = ktx.pixelHeight; + engine._setCubeMapTextureParams(texture, loadMipmap, ktx.numberOfMipmapLevels - 1); + texture.isReady = true; + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + if (onLoad) { + onLoad(); + } + } + /** + * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + * @param options + */ + loadData(data, texture, callback, options) { + if (KhronosTextureContainer.IsValid(data)) { + // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture + texture._invertVScale = !texture.invertY; + const ktx = new KhronosTextureContainer(data, 1); + const mappedFormat = mapSRGBToLinear(ktx.glInternalFormat); + if (mappedFormat) { + texture.format = mappedFormat; + texture._useSRGBBuffer = texture.getEngine()._getUseSRGBBuffer(true, texture.generateMipMaps); + texture._gammaSpace = true; + } + else { + texture.format = ktx.glInternalFormat; + } + callback(ktx.pixelWidth, ktx.pixelHeight, texture.generateMipMaps, true, () => { + ktx.uploadLevels(texture, texture.generateMipMaps); + }, ktx.isInvalid); + } + else if (KhronosTextureContainer2.IsValid(data)) { + const ktx2 = new KhronosTextureContainer2(texture.getEngine()); + ktx2._uploadAsync(data, texture, options).then(() => { + callback(texture.width, texture.height, texture.generateMipMaps, true, () => { }, false); + }, (error) => { + Logger.Warn(`Failed to load KTX2 texture data: ${error.message}`); + callback(0, 0, false, false, () => { }, true); + }); + } + else { + Logger.Error("texture missing KTX identifier"); + callback(0, 0, false, false, () => { }, true); + } + } +} + +const ktxTextureLoader = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + _KTXTextureLoader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * WebXR Camera which holds the views for the xrSession + * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRCamera + */ +class WebXRCamera extends FreeCamera { + /** + * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager + * @param name the name of the camera + * @param scene the scene to add the camera to + * @param _xrSessionManager a constructed xr session manager + */ + constructor(name, scene, _xrSessionManager) { + super(name, Vector3.Zero(), scene); + this._xrSessionManager = _xrSessionManager; + this._firstFrame = false; + this._referenceQuaternion = Quaternion.Identity(); + this._referencedPosition = new Vector3(); + this._trackingState = 0 /* WebXRTrackingState.NOT_TRACKING */; + /** + * This will be triggered after the first XR Frame initialized the camera, + * including the right number of views and their rendering parameters + */ + this.onXRCameraInitializedObservable = new Observable(); + /** + * Observable raised before camera teleportation + * @deprecated use onBeforeCameraTeleport of the teleportation feature instead + */ + this.onBeforeCameraTeleport = new Observable(); + /** + * Observable raised after camera teleportation + * @deprecated use onAfterCameraTeleport of the teleportation feature instead + */ + this.onAfterCameraTeleport = new Observable(); + /** + * Notifies when the camera's tracking state has changed. + * Notice - will also be triggered when tracking has started (at the beginning of the session) + */ + this.onTrackingStateChanged = new Observable(); + /** + * Should position compensation execute on first frame. + * This is used when copying the position from a native (non XR) camera + */ + this.compensateOnFirstFrame = true; + this._rotate180 = new Quaternion(0, 1, 0, 0); + // Initial camera configuration + this.minZ = 0.1; + this.rotationQuaternion = new Quaternion(); + this.cameraRigMode = Camera.RIG_MODE_CUSTOM; + this.updateUpVectorFromRotation = true; + this._updateNumberOfRigCameras(1); + // freeze projection matrix, which will be copied later + this.freezeProjectionMatrix(); + this._deferOnly = true; + this._xrSessionManager.onXRSessionInit.add(() => { + this._referencedPosition.copyFromFloats(0, 0, 0); + this._referenceQuaternion.copyFromFloats(0, 0, 0, 1); + // first frame - camera's y position should be 0 for the correct offset + this._firstFrame = this.compensateOnFirstFrame; + this._xrSessionManager.onWorldScaleFactorChangedObservable.add(() => { + // only run if in session + if (!this._xrSessionManager.currentFrame) { + return; + } + this._updateDepthNearFar(); + }); + }); + // Check transformation changes on each frame. Callback is added to be first so that the transformation will be + // applied to the rest of the elements using the referenceSpace object + this._xrSessionManager.onXRFrameObservable.add(() => { + if (this._firstFrame) { + this._updateFromXRSession(); + } + if (this.onXRCameraInitializedObservable.hasObservers()) { + this.onXRCameraInitializedObservable.notifyObservers(this); + this.onXRCameraInitializedObservable.clear(); + } + if (this._deferredUpdated) { + this.position.copyFrom(this._deferredPositionUpdate); + this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate); + } + this._updateReferenceSpace(); + this._updateFromXRSession(); + }, undefined, true); + } + /** + * Get the current XR tracking state of the camera + */ + get trackingState() { + return this._trackingState; + } + _setTrackingState(newState) { + if (this._trackingState !== newState) { + this._trackingState = newState; + this.onTrackingStateChanged.notifyObservers(newState); + } + } + /** + * Return the user's height, unrelated to the current ground. + * This will be the y position of this camera, when ground level is 0. + * + * Note - this value is multiplied by the worldScalingFactor (if set), so it will be in the same units as the scene. + */ + get realWorldHeight() { + const basePose = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace); + if (basePose && basePose.transform) { + return basePose.transform.position.y * this._xrSessionManager.worldScalingFactor; + } + else { + return 0; + } + } + /** @internal */ + _updateForDualEyeDebugging( /*pupilDistance = 0.01*/) { + // Create initial camera rigs + this._updateNumberOfRigCameras(2); + this.rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1.0); + // this.rigCameras[0].position.x = -pupilDistance / 2; + this.rigCameras[0].outputRenderTarget = null; + this.rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0); + // this.rigCameras[1].position.x = pupilDistance / 2; + this.rigCameras[1].outputRenderTarget = null; + } + /** + * Sets this camera's transformation based on a non-vr camera + * @param otherCamera the non-vr camera to copy the transformation from + * @param resetToBaseReferenceSpace should XR reset to the base reference space + */ + setTransformationFromNonVRCamera(otherCamera = this.getScene().activeCamera, resetToBaseReferenceSpace = true) { + if (!otherCamera || otherCamera === this) { + return; + } + const mat = otherCamera.computeWorldMatrix(); + mat.decompose(undefined, this.rotationQuaternion, this.position); + // set the ground level + this.position.y = 0; + Quaternion.FromEulerAnglesToRef(0, this.rotationQuaternion.toEulerAngles().y, 0, this.rotationQuaternion); + this._firstFrame = true; + if (resetToBaseReferenceSpace) { + this._xrSessionManager.resetReferenceSpace(); + } + } + /** + * Gets the current instance class name ("WebXRCamera"). + * @returns the class name + */ + getClassName() { + return "WebXRCamera"; + } + /** + * Set the target for the camera to look at. + * Note that this only rotates around the Y axis, as opposed to the default behavior of other cameras + * @param target the target to set the camera to look at + */ + setTarget(target) { + // only rotate around the y axis! + const tmpVector = TmpVectors.Vector3[1]; + target.subtractToRef(this.position, tmpVector); + tmpVector.y = 0; + tmpVector.normalize(); + const yRotation = Math.atan2(tmpVector.x, tmpVector.z); + this.rotationQuaternion.toEulerAnglesToRef(tmpVector); + Quaternion.FromEulerAnglesToRef(tmpVector.x, yRotation, tmpVector.z, this.rotationQuaternion); + } + dispose() { + super.dispose(); + this._lastXRViewerPose = undefined; + this.onTrackingStateChanged.clear(); + } + _updateDepthNearFar() { + const far = (this.maxZ || 10000) * this._xrSessionManager.worldScalingFactor; + const xrRenderState = { + // if maxZ is 0 it should be "Infinity", but it doesn't work with the WebXR API. Setting to a large number. + depthFar: far, + depthNear: this.minZ, + }; + this._xrSessionManager.updateRenderState(xrRenderState); + this._cache.minZ = this.minZ; + this._cache.maxZ = far; + } + _updateFromXRSession() { + const pose = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace); + this._lastXRViewerPose = pose || undefined; + if (!pose) { + this._setTrackingState(0 /* WebXRTrackingState.NOT_TRACKING */); + return; + } + // Set the tracking state. if it didn't change it is a no-op + const trackingState = pose.emulatedPosition ? 1 /* WebXRTrackingState.TRACKING_LOST */ : 2 /* WebXRTrackingState.TRACKING */; + this._setTrackingState(trackingState); + // check min/max Z and update if not the same as in cache + if (this.minZ !== this._cache.minZ || this.maxZ !== this._cache.maxZ) { + this._updateDepthNearFar(); + } + if (pose.transform) { + const orientation = pose.transform.orientation; + if (pose.transform.orientation.x === undefined) { + // Babylon native polyfill can return an undefined orientation value + // When not initialized + return; + } + const pos = pose.transform.position; + this._referencedPosition.set(pos.x, pos.y, pos.z).scaleInPlace(this._xrSessionManager.worldScalingFactor); + this._referenceQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w); + if (!this._scene.useRightHandedSystem) { + this._referencedPosition.z *= -1; + this._referenceQuaternion.z *= -1; + this._referenceQuaternion.w *= -1; + } + else { + this._referenceQuaternion.multiplyInPlace(this._rotate180); + } + if (this._firstFrame) { + this._firstFrame = false; + // we have the XR reference, now use this to find the offset to get the camera to be + // in the right position + // set the height to correlate to the current height + this.position.y += this._referencedPosition.y; + // avoid using the head rotation on the first frame. + this._referenceQuaternion.copyFromFloats(0, 0, 0, 1); + } + else { + // update position and rotation as reference + this.rotationQuaternion.copyFrom(this._referenceQuaternion); + this.position.copyFrom(this._referencedPosition); + } + } + // Update camera rigs + if (this.rigCameras.length !== pose.views.length) { + this._updateNumberOfRigCameras(pose.views.length); + } + pose.views.forEach((view, i) => { + const currentRig = this.rigCameras[i]; + // update right and left, where applicable + if (!currentRig.isLeftCamera && !currentRig.isRightCamera) { + if (view.eye === "right") { + currentRig._isRightCamera = true; + } + else if (view.eye === "left") { + currentRig._isLeftCamera = true; + } + } + // add any custom render targets to this camera, if available in the scene + const customRenderTargets = this.getScene().customRenderTargets; + // use a for loop + for (let i = 0; i < customRenderTargets.length; i++) { + const rt = customRenderTargets[i]; + // make sure we don't add the same render target twice + if (currentRig.customRenderTargets.indexOf(rt) === -1) { + currentRig.customRenderTargets.push(rt); + } + } + // Update view/projection matrix + const pos = view.transform.position; + const orientation = view.transform.orientation; + currentRig.parent = this.parent; + currentRig.position.set(pos.x, pos.y, pos.z).scaleInPlace(this._xrSessionManager.worldScalingFactor); + currentRig.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w); + if (!this._scene.useRightHandedSystem) { + currentRig.position.z *= -1; + currentRig.rotationQuaternion.z *= -1; + currentRig.rotationQuaternion.w *= -1; + } + else { + currentRig.rotationQuaternion.multiplyInPlace(this._rotate180); + } + Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, currentRig._projectionMatrix); + if (!this._scene.useRightHandedSystem) { + currentRig._projectionMatrix.toggleProjectionMatrixHandInPlace(); + } + // fov + const fov = Math.atan2(1, view.projectionMatrix[5]) * 2; + currentRig.fov = fov; + // first camera? + if (i === 0) { + this.fov = fov; + this._projectionMatrix.copyFrom(currentRig._projectionMatrix); + } + const renderTargetTexture = this._xrSessionManager.getRenderTargetTextureForView(view); + this._renderingMultiview = renderTargetTexture?._texture?.isMultiview || false; + if (this._renderingMultiview) { + // For multiview, the render target texture is the same per-view (just the slice index is different), + // so we only need to set the output render target once for the rig parent. + if (i == 0) { + this._xrSessionManager.trySetViewportForView(this.viewport, view); + this.outputRenderTarget = renderTargetTexture; + } + } + else { + // Update viewport + this._xrSessionManager.trySetViewportForView(currentRig.viewport, view); + // Set cameras to render to the session's render target + currentRig.outputRenderTarget = renderTargetTexture || this._xrSessionManager.getRenderTargetTextureForView(view); + } + // Replicate parent rig camera behavior + currentRig.layerMask = this.layerMask; + }); + } + _updateNumberOfRigCameras(viewCount = 1) { + while (this.rigCameras.length < viewCount) { + const newCamera = new TargetCamera("XR-RigCamera: " + this.rigCameras.length, Vector3.Zero(), this.getScene()); + newCamera.minZ = 0.1; + newCamera.rotationQuaternion = new Quaternion(); + newCamera.updateUpVectorFromRotation = true; + newCamera.isRigCamera = true; + newCamera.rigParent = this; + // do not compute projection matrix, provided by XR + newCamera.freezeProjectionMatrix(); + this.rigCameras.push(newCamera); + } + while (this.rigCameras.length > viewCount) { + const removedCamera = this.rigCameras.pop(); + if (removedCamera) { + removedCamera.dispose(); + } + } + } + _updateReferenceSpace() { + // were position & rotation updated OUTSIDE of the xr update loop + if (!this.position.equals(this._referencedPosition) || !this.rotationQuaternion.equals(this._referenceQuaternion)) { + const referencedMat = TmpVectors.Matrix[0]; + const poseMat = TmpVectors.Matrix[1]; + const transformMat = TmpVectors.Matrix[2]; + Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly, this._referenceQuaternion, this._referencedPosition, referencedMat); + Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly, this.rotationQuaternion, this.position, poseMat); + referencedMat.invert().multiplyToRef(poseMat, transformMat); + transformMat.invert(); + if (!this._scene.useRightHandedSystem) { + transformMat.toggleModelMatrixHandInPlace(); + } + transformMat.decompose(undefined, this._referenceQuaternion, this._referencedPosition); + const transform = new XRRigidTransform({ + x: this._referencedPosition.x / this._xrSessionManager.worldScalingFactor, + y: this._referencedPosition.y / this._xrSessionManager.worldScalingFactor, + z: this._referencedPosition.z / this._xrSessionManager.worldScalingFactor, + }, { + x: this._referenceQuaternion.x, + y: this._referenceQuaternion.y, + z: this._referenceQuaternion.z, + w: this._referenceQuaternion.w, + }); + this._xrSessionManager.referenceSpace = this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(transform); + } + } +} +WebXRCamera._ScaleReadOnly = Vector3.One(); + +/** + * Base set of functionality needed to create an XR experience (WebXRSessionManager, Camera, StateManagement, etc.) + * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRExperienceHelpers + */ +class WebXRExperienceHelper { + /** + * Creates a WebXRExperienceHelper + * @param _scene The scene the helper should be created in + */ + constructor(_scene) { + this._scene = _scene; + this._nonVRCamera = null; + this._attachedToElement = false; + this._spectatorCamera = null; + this._originalSceneAutoClear = true; + this._supported = false; + this._spectatorMode = false; + this._lastTimestamp = 0; + /** + * Observers registered here will be triggered after the camera's initial transformation is set + * This can be used to set a different ground level or an extra rotation. + * + * Note that ground level is considered to be at 0. The height defined by the XR camera will be added + * to the position set after this observable is done executing. + */ + this.onInitialXRPoseSetObservable = new Observable(); + /** + * Fires when the state of the experience helper has changed + */ + this.onStateChangedObservable = new Observable(); + /** + * The current state of the XR experience (eg. transitioning, in XR or not in XR) + */ + this.state = 3 /* WebXRState.NOT_IN_XR */; + this.sessionManager = new WebXRSessionManager(_scene); + this.camera = new WebXRCamera("webxr", _scene, this.sessionManager); + this.featuresManager = new WebXRFeaturesManager(this.sessionManager); + _scene.onDisposeObservable.addOnce(() => { + this.dispose(); + }); + } + /** + * Creates the experience helper + * @param scene the scene to attach the experience helper to + * @returns a promise for the experience helper + */ + static CreateAsync(scene) { + const helper = new WebXRExperienceHelper(scene); + return helper.sessionManager + .initializeAsync() + .then(() => { + helper._supported = true; + return helper; + }) + .catch((e) => { + helper._setState(3 /* WebXRState.NOT_IN_XR */); + helper.dispose(); + throw e; + }); + } + /** + * Disposes of the experience helper + */ + dispose() { + this.exitXRAsync(); + this.camera.dispose(); + this.onStateChangedObservable.clear(); + this.onInitialXRPoseSetObservable.clear(); + this.sessionManager.dispose(); + this._spectatorCamera?.dispose(); + if (this._nonVRCamera) { + this._scene.activeCamera = this._nonVRCamera; + } + } + /** + * Enters XR mode (This must be done within a user interaction in most browsers eg. button click) + * @param sessionMode options for the XR session + * @param referenceSpaceType frame of reference of the XR session + * @param renderTarget the output canvas that will be used to enter XR mode + * @param sessionCreationOptions optional XRSessionInit object to init the session with + * @returns promise that resolves after xr mode has entered + */ + async enterXRAsync(sessionMode, referenceSpaceType, renderTarget = this.sessionManager.getWebXRRenderTarget(), sessionCreationOptions = {}) { + if (!this._supported) { + // eslint-disable-next-line no-throw-literal + throw "WebXR not supported in this browser or environment"; + } + this._setState(0 /* WebXRState.ENTERING_XR */); + if (referenceSpaceType !== "viewer" && referenceSpaceType !== "local") { + sessionCreationOptions.optionalFeatures = sessionCreationOptions.optionalFeatures || []; + sessionCreationOptions.optionalFeatures.push(referenceSpaceType); + } + sessionCreationOptions = await this.featuresManager._extendXRSessionInitObject(sessionCreationOptions); + // we currently recommend "unbounded" space in AR (#7959) + if (sessionMode === "immersive-ar" && referenceSpaceType !== "unbounded") { + Logger.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode"); + } + // make sure that the session mode is supported + try { + await this.sessionManager.initializeSessionAsync(sessionMode, sessionCreationOptions); + await this.sessionManager.setReferenceSpaceTypeAsync(referenceSpaceType); + const xrRenderState = { + // if maxZ is 0 it should be "Infinity", but it doesn't work with the WebXR API. Setting to a large number. + depthFar: this.camera.maxZ || 10000, + depthNear: this.camera.minZ, + }; + // The layers feature will have already initialized the xr session's layers on session init. + if (!this.featuresManager.getEnabledFeature(WebXRFeatureName.LAYERS)) { + const baseLayer = await renderTarget.initializeXRLayerAsync(this.sessionManager.session); + xrRenderState.baseLayer = baseLayer; + } + this.sessionManager.updateRenderState(xrRenderState); + // run the render loop + this.sessionManager.runXRRenderLoop(); + // Cache pre xr scene settings + this._originalSceneAutoClear = this._scene.autoClear; + this._nonVRCamera = this._scene.activeCamera; + this._attachedToElement = !!this._nonVRCamera?.inputs?.attachedToElement; + this._nonVRCamera?.detachControl(); + this._scene.activeCamera = this.camera; + // do not compensate when AR session is used + if (sessionMode !== "immersive-ar") { + this._nonXRToXRCamera(); + } + else { + // Kept here, TODO - check if needed + this._scene.autoClear = false; + this.camera.compensateOnFirstFrame = false; + // reset the camera's position to the origin + this.camera.position.set(0, 0, 0); + this.camera.rotationQuaternion.set(0, 0, 0, 1); + this.onInitialXRPoseSetObservable.notifyObservers(this.camera); + } + // Vision Pro suspends the audio context when entering XR, so we resume it here if needed. + AbstractEngine.audioEngine?._resumeAudioContextOnStateChange(); + this.sessionManager.onXRSessionEnded.addOnce(() => { + // when using the back button and not the exit button (default on mobile), the session is ending but the EXITING state was not set + if (this.state !== 1 /* WebXRState.EXITING_XR */) { + this._setState(1 /* WebXRState.EXITING_XR */); + } + // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends + this.camera.rigCameras.forEach((c) => { + c.outputRenderTarget = null; + }); + // Restore scene settings + this._scene.autoClear = this._originalSceneAutoClear; + this._scene.activeCamera = this._nonVRCamera; + if (this._attachedToElement && this._nonVRCamera) { + this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault); + } + if (sessionMode !== "immersive-ar" && this.camera.compensateOnFirstFrame) { + if (this._nonVRCamera.setPosition) { + this._nonVRCamera.setPosition(this.camera.position); + } + else { + this._nonVRCamera.position.copyFrom(this.camera.position); + } + } + this._setState(3 /* WebXRState.NOT_IN_XR */); + }); + // Wait until the first frame arrives before setting state to in xr + this.sessionManager.onXRFrameObservable.addOnce(() => { + this._setState(2 /* WebXRState.IN_XR */); + }); + return this.sessionManager; + } + catch (e) { + Logger.Log(e); + Logger.Log(e.message); + this._setState(3 /* WebXRState.NOT_IN_XR */); + throw e; + } + } + /** + * Exits XR mode and returns the scene to its original state + * @returns promise that resolves after xr mode has exited + */ + exitXRAsync() { + // only exit if state is IN_XR + if (this.state !== 2 /* WebXRState.IN_XR */) { + return Promise.resolve(); + } + this._setState(1 /* WebXRState.EXITING_XR */); + return this.sessionManager.exitXRAsync(); + } + /** + * Enable spectator mode for desktop VR experiences. + * When spectator mode is enabled a camera will be attached to the desktop canvas and will + * display the first rig camera's view on the desktop canvas. + * Please note that this will degrade performance, as it requires another camera render. + * It is also not recommended to enable this in devices like the quest, as it brings no benefit there. + * @param options giving WebXRSpectatorModeOption for specutator camera to setup when the spectator mode is enabled. + */ + enableSpectatorMode(options) { + if (!this._spectatorMode) { + this._spectatorMode = true; + this._switchSpectatorMode(options); + } + } + /** + * Disable spectator mode for desktop VR experiences. + */ + disableSpecatatorMode() { + if (this._spectatorMode) { + this._spectatorMode = false; + this._switchSpectatorMode(); + } + } + _switchSpectatorMode(options) { + const fps = options?.fps ? options.fps : 1000.0; + const refreshRate = (1.0 / fps) * 1000.0; + const cameraIndex = options?.preferredCameraIndex ? options?.preferredCameraIndex : 0; + const updateSpectatorCamera = () => { + if (this._spectatorCamera) { + const delta = this.sessionManager.currentTimestamp - this._lastTimestamp; + if (delta >= refreshRate) { + this._lastTimestamp = this.sessionManager.currentTimestamp; + this._spectatorCamera.position.copyFrom(this.camera.rigCameras[cameraIndex].globalPosition); + this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[cameraIndex].absoluteRotation); + } + } + }; + if (this._spectatorMode) { + if (cameraIndex >= this.camera.rigCameras.length) { + throw new Error("the preferred camera index is beyond the length of rig camera array."); + } + const onStateChanged = () => { + if (this.state === 2 /* WebXRState.IN_XR */) { + this._spectatorCamera = new UniversalCamera("webxr-spectator", Vector3.Zero(), this._scene); + this._spectatorCamera.rotationQuaternion = new Quaternion(); + this._scene.activeCameras = [this.camera, this._spectatorCamera]; + this.sessionManager.onXRFrameObservable.add(updateSpectatorCamera); + this._scene.onAfterRenderCameraObservable.add((camera) => { + if (camera === this.camera) { + // reset the dimensions object for correct resizing + this._scene.getEngine().framebufferDimensionsObject = null; + } + }); + } + else if (this.state === 1 /* WebXRState.EXITING_XR */) { + this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera); + this._scene.activeCameras = null; + } + }; + this.onStateChangedObservable.add(onStateChanged); + onStateChanged(); + } + else { + this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera); + this._scene.activeCameras = [this.camera]; + } + } + _nonXRToXRCamera() { + this.camera.setTransformationFromNonVRCamera(this._nonVRCamera); + this.onInitialXRPoseSetObservable.notifyObservers(this.camera); + } + _setState(val) { + if (this.state === val) { + return; + } + this.state = val; + this.onStateChangedObservable.notifyObservers(this.state); + } +} + +/** + * This class represents a single component (for example button or thumbstick) of a motion controller + */ +class WebXRControllerComponent { + /** + * Creates a new component for a motion controller. + * It is created by the motion controller itself + * + * @param id the id of this component + * @param type the type of the component + * @param _buttonIndex index in the buttons array of the gamepad + * @param _axesIndices indices of the values in the axes array of the gamepad + */ + constructor( + /** + * the id of this component + */ + id, + /** + * the type of the component + */ + type, _buttonIndex = -1, _axesIndices = []) { + this.id = id; + this.type = type; + this._buttonIndex = _buttonIndex; + this._axesIndices = _axesIndices; + this._axes = { + x: 0, + y: 0, + }; + this._changes = {}; + this._currentValue = 0; + this._hasChanges = false; + this._pressed = false; + this._touched = false; + /** + * If axes are available for this component (like a touchpad or thumbstick) the observers will be notified when + * the axes data changes + */ + this.onAxisValueChangedObservable = new Observable(); + /** + * Observers registered here will be triggered when the state of a button changes + * State change is either pressed / touched / value + */ + this.onButtonStateChangedObservable = new Observable(); + } + /** + * The current axes data. If this component has no axes it will still return an object { x: 0, y: 0 } + */ + get axes() { + return this._axes; + } + /** + * Get the changes. Elements will be populated only if they changed with their previous and current value + */ + get changes() { + return this._changes; + } + /** + * Return whether or not the component changed the last frame + */ + get hasChanges() { + return this._hasChanges; + } + /** + * is the button currently pressed + */ + get pressed() { + return this._pressed; + } + /** + * is the button currently touched + */ + get touched() { + return this._touched; + } + /** + * Get the current value of this component + */ + get value() { + return this._currentValue; + } + /** + * Dispose this component + */ + dispose() { + this.onAxisValueChangedObservable.clear(); + this.onButtonStateChangedObservable.clear(); + } + /** + * Are there axes correlating to this component + * @returns true is axes data is available + */ + isAxes() { + return this._axesIndices.length !== 0; + } + /** + * Is this component a button (hence - pressable) + * @returns true if can be pressed + */ + isButton() { + return this._buttonIndex !== -1; + } + /** + * update this component using the gamepad object it is in. Called on every frame + * @param nativeController the native gamepad controller object + */ + update(nativeController) { + let buttonUpdated = false; + let axesUpdate = false; + this._hasChanges = false; + this._changes = {}; + if (this.isButton()) { + const button = nativeController.buttons[this._buttonIndex]; + // defensive, in case a profile was forced + if (!button) { + return; + } + if (this._currentValue !== button.value) { + this.changes.value = { + current: button.value, + previous: this._currentValue, + }; + buttonUpdated = true; + this._currentValue = button.value; + } + if (this._touched !== button.touched) { + this.changes.touched = { + current: button.touched, + previous: this._touched, + }; + buttonUpdated = true; + this._touched = button.touched; + } + if (this._pressed !== button.pressed) { + this.changes.pressed = { + current: button.pressed, + previous: this._pressed, + }; + buttonUpdated = true; + this._pressed = button.pressed; + } + } + if (this.isAxes()) { + if (this._axes.x !== nativeController.axes[this._axesIndices[0]]) { + this.changes.axes = { + current: { + x: nativeController.axes[this._axesIndices[0]], + y: this._axes.y, + }, + previous: { + x: this._axes.x, + y: this._axes.y, + }, + }; + this._axes.x = nativeController.axes[this._axesIndices[0]]; + axesUpdate = true; + } + if (this._axes.y !== nativeController.axes[this._axesIndices[1]]) { + if (this.changes.axes) { + this.changes.axes.current.y = nativeController.axes[this._axesIndices[1]]; + } + else { + this.changes.axes = { + current: { + x: this._axes.x, + y: nativeController.axes[this._axesIndices[1]], + }, + previous: { + x: this._axes.x, + y: this._axes.y, + }, + }; + } + this._axes.y = nativeController.axes[this._axesIndices[1]]; + axesUpdate = true; + } + } + if (buttonUpdated) { + this._hasChanges = true; + this.onButtonStateChangedObservable.notifyObservers(this); + } + if (axesUpdate) { + this._hasChanges = true; + this.onAxisValueChangedObservable.notifyObservers(this._axes); + } + } +} +/** + * button component type + */ +WebXRControllerComponent.BUTTON_TYPE = "button"; +/** + * squeeze component type + */ +WebXRControllerComponent.SQUEEZE_TYPE = "squeeze"; +/** + * Thumbstick component type + */ +WebXRControllerComponent.THUMBSTICK_TYPE = "thumbstick"; +/** + * Touchpad component type + */ +WebXRControllerComponent.TOUCHPAD_TYPE = "touchpad"; +/** + * trigger component type + */ +WebXRControllerComponent.TRIGGER_TYPE = "trigger"; + +/** + * An Abstract Motion controller + * This class receives an xrInput and a profile layout and uses those to initialize the components + * Each component has an observable to check for changes in value and state + */ +class WebXRAbstractMotionController { + /** + * constructs a new abstract motion controller + * @param scene the scene to which the model of the controller will be added + * @param layout The profile layout to load + * @param gamepadObject The gamepad object correlating to this controller + * @param handedness handedness (left/right/none) of this controller + * @param _doNotLoadControllerMesh set this flag to ignore the mesh loading + * @param _controllerCache a cache holding controller models already loaded in this session + */ + constructor( + // eslint-disable-next-line @typescript-eslint/naming-convention + scene, + // eslint-disable-next-line @typescript-eslint/naming-convention + layout, + /** + * The gamepad object correlating to this controller + */ + gamepadObject, + /** + * handedness (left/right/none) of this controller + */ + handedness, + /** + * @internal + * [false] + */ + _doNotLoadControllerMesh = false, _controllerCache) { + this.scene = scene; + this.layout = layout; + this.gamepadObject = gamepadObject; + this.handedness = handedness; + this._doNotLoadControllerMesh = _doNotLoadControllerMesh; + this._controllerCache = _controllerCache; + this._initComponent = (id) => { + if (!id) { + return; + } + const componentDef = this.layout.components[id]; + const type = componentDef.type; + const buttonIndex = componentDef.gamepadIndices.button; + // search for axes + const axes = []; + if (componentDef.gamepadIndices.xAxis !== undefined && componentDef.gamepadIndices.yAxis !== undefined) { + axes.push(componentDef.gamepadIndices.xAxis, componentDef.gamepadIndices.yAxis); + } + this.components[id] = new WebXRControllerComponent(id, type, buttonIndex, axes); + }; + this._modelReady = false; + /** + * A map of components (WebXRControllerComponent) in this motion controller + * Components have a ComponentType and can also have both button and axis definitions + */ + this.components = {}; + /** + * Disable the model's animation. Can be set at any time. + */ + this.disableAnimation = false; + /** + * Observers registered here will be triggered when the model of this controller is done loading + */ + this.onModelLoadedObservable = new Observable(); + // initialize the components + if (layout.components) { + Object.keys(layout.components).forEach(this._initComponent); + } + // Model is loaded in WebXRInput + } + /** + * Dispose this controller, the model mesh and all its components + */ + dispose() { + this.getComponentIds().forEach((id) => this.getComponent(id).dispose()); + if (this.rootMesh) { + this.rootMesh.getChildren(undefined, true).forEach((node) => { + node.setEnabled(false); + }); + this.rootMesh.dispose(!!this._controllerCache, !this._controllerCache); + } + this.onModelLoadedObservable.clear(); + } + /** + * Returns all components of specific type + * @param type the type to search for + * @returns an array of components with this type + */ + getAllComponentsOfType(type) { + return this.getComponentIds() + .map((id) => this.components[id]) + .filter((component) => component.type === type); + } + /** + * get a component based an its component id as defined in layout.components + * @param id the id of the component + * @returns the component correlates to the id or undefined if not found + */ + getComponent(id) { + return this.components[id]; + } + /** + * Get the list of components available in this motion controller + * @returns an array of strings correlating to available components + */ + getComponentIds() { + return Object.keys(this.components); + } + /** + * Get the first component of specific type + * @param type type of component to find + * @returns a controller component or null if not found + */ + getComponentOfType(type) { + return this.getAllComponentsOfType(type)[0] || null; + } + /** + * Get the main (Select) component of this controller as defined in the layout + * @returns the main component of this controller + */ + getMainComponent() { + return this.getComponent(this.layout.selectComponentId); + } + /** + * Loads the model correlating to this controller + * When the mesh is loaded, the onModelLoadedObservable will be triggered + * @returns A promise fulfilled with the result of the model loading + */ + async loadModel() { + const useGeneric = !this._getModelLoadingConstraints(); + let loadingParams = this._getGenericFilenameAndPath(); + // Checking if GLB loader is present + if (useGeneric) { + Logger.Warn("Falling back to generic models"); + } + else { + loadingParams = this._getFilenameAndPath(); + } + return new Promise((resolve, reject) => { + const meshesLoaded = (meshes) => { + if (useGeneric) { + this._getGenericParentMesh(meshes); + } + else { + this._setRootMesh(meshes); + } + this._processLoadedModel(meshes); + this._modelReady = true; + this.onModelLoadedObservable.notifyObservers(this); + resolve(true); + }; + if (this._controllerCache) { + // look for it in the cache + const found = this._controllerCache.filter((c) => { + return c.filename === loadingParams.filename && c.path === loadingParams.path; + }); + if (found[0]) { + found[0].meshes.forEach((mesh) => mesh.setEnabled(true)); + meshesLoaded(found[0].meshes); + return; + // found, don't continue to load + } + } + SceneLoader.ImportMesh("", loadingParams.path, loadingParams.filename, this.scene, (meshes) => { + if (this._controllerCache) { + this._controllerCache.push({ + ...loadingParams, + meshes, + }); + } + meshesLoaded(meshes); + }, null, (_scene, message) => { + Logger.Log(message); + Logger.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${loadingParams.path}${loadingParams.filename}`); + reject(message); + }); + }); + } + /** + * Update this model using the current XRFrame + * @param xrFrame the current xr frame to use and update the model + */ + updateFromXRFrame(xrFrame) { + this.getComponentIds().forEach((id) => this.getComponent(id).update(this.gamepadObject)); + this.updateModel(xrFrame); + } + /** + * Backwards compatibility due to a deeply-integrated typo + */ + get handness() { + return this.handedness; + } + /** + * Pulse (vibrate) this controller + * If the controller does not support pulses, this function will fail silently and return Promise directly after called + * Consecutive calls to this function will cancel the last pulse call + * + * @param value the strength of the pulse in 0.0...1.0 range + * @param duration Duration of the pulse in milliseconds + * @param hapticActuatorIndex optional index of actuator (will usually be 0) + * @returns a promise that will send true when the pulse has ended and false if the device doesn't support pulse or an error accrued + */ + pulse(value, duration, hapticActuatorIndex = 0) { + if (this.gamepadObject.hapticActuators && this.gamepadObject.hapticActuators[hapticActuatorIndex]) { + return this.gamepadObject.hapticActuators[hapticActuatorIndex].pulse(value, duration); + } + else { + return Promise.resolve(false); + } + } + // Look through all children recursively. This will return null if no mesh exists with the given name. + _getChildByName(node, name) { + return node.getChildren((n) => n.name === name, false)[0]; + } + // Look through only immediate children. This will return null if no mesh exists with the given name. + _getImmediateChildByName(node, name) { + return node.getChildren((n) => n.name == name, true)[0]; + } + /** + * Moves the axis on the controller mesh based on its current state + * @param axisMap + * @param axisValue the value of the axis which determines the meshes new position + * @internal + */ + _lerpTransform(axisMap, axisValue, fixValueCoordinates) { + if (!axisMap.minMesh || !axisMap.maxMesh || !axisMap.valueMesh) { + return; + } + if (!axisMap.minMesh.rotationQuaternion || !axisMap.maxMesh.rotationQuaternion || !axisMap.valueMesh.rotationQuaternion) { + return; + } + // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1) + const lerpValue = fixValueCoordinates ? axisValue * 0.5 + 0.5 : axisValue; + Quaternion.SlerpToRef(axisMap.minMesh.rotationQuaternion, axisMap.maxMesh.rotationQuaternion, lerpValue, axisMap.valueMesh.rotationQuaternion); + Vector3.LerpToRef(axisMap.minMesh.position, axisMap.maxMesh.position, lerpValue, axisMap.valueMesh.position); + } + /** + * Update the model itself with the current frame data + * @param xrFrame the frame to use for updating the model mesh + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + updateModel(xrFrame) { + if (!this._modelReady) { + return; + } + this._updateModel(xrFrame); + } + _getGenericFilenameAndPath() { + return { + filename: "generic.babylon", + path: "https://controllers.babylonjs.com/generic/", + }; + } + _getGenericParentMesh(meshes) { + this.rootMesh = new Mesh(this.profileId + " " + this.handedness, this.scene); + meshes.forEach((mesh) => { + if (!mesh.parent) { + mesh.isPickable = false; + mesh.setParent(this.rootMesh); + } + }); + this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0); + } +} + +/** + * A generic trigger-only motion controller for WebXR + */ +class WebXRGenericTriggerMotionController extends WebXRAbstractMotionController { + constructor(scene, gamepadObject, handedness) { + super(scene, GenericTriggerLayout[handedness], gamepadObject, handedness); + this.profileId = WebXRGenericTriggerMotionController.ProfileId; + } + _getFilenameAndPath() { + return { + filename: "generic.babylon", + path: "https://controllers.babylonjs.com/generic/", + }; + } + _getModelLoadingConstraints() { + return true; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _processLoadedModel(meshes) { + // nothing to do + } + _setRootMesh(meshes) { + this.rootMesh = new Mesh(this.profileId + " " + this.handedness, this.scene); + meshes.forEach((mesh) => { + mesh.isPickable = false; + if (!mesh.parent) { + mesh.setParent(this.rootMesh); + } + }); + this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0); + } + _updateModel() { + // no-op + } +} +/** + * Static version of the profile id of this controller + */ +WebXRGenericTriggerMotionController.ProfileId = "generic-trigger"; +// https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/generic/generic-trigger-touchpad-thumbstick.json +const GenericTriggerLayout = { + left: { + selectComponentId: "xr-standard-trigger", + components: { + // eslint-disable-next-line @typescript-eslint/naming-convention + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr_standard_trigger", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "generic-trigger-left", + assetPath: "left.glb", + }, + right: { + selectComponentId: "xr-standard-trigger", + components: { + // eslint-disable-next-line @typescript-eslint/naming-convention + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr_standard_trigger", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "generic-trigger-right", + assetPath: "right.glb", + }, + none: { + selectComponentId: "xr-standard-trigger", + components: { + // eslint-disable-next-line @typescript-eslint/naming-convention + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr_standard_trigger", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "generic-trigger-none", + assetPath: "none.glb", + }, +}; + +/** + * A profiled motion controller has its profile loaded from an online repository. + * The class is responsible of loading the model, mapping the keys and enabling model-animations + */ +class WebXRProfiledMotionController extends WebXRAbstractMotionController { + constructor(scene, xrInput, _profile, _repositoryUrl, + // eslint-disable-next-line @typescript-eslint/naming-convention + controllerCache) { + super(scene, _profile.layouts[xrInput.handedness || "none"], xrInput.gamepad, xrInput.handedness, undefined, controllerCache); + this._repositoryUrl = _repositoryUrl; + this.controllerCache = controllerCache; + this._buttonMeshMapping = {}; + this._touchDots = {}; + this.profileId = _profile.profileId; + } + dispose() { + super.dispose(); + if (!this.controllerCache) { + Object.keys(this._touchDots).forEach((visResKey) => { + this._touchDots[visResKey].dispose(); + }); + } + } + _getFilenameAndPath() { + return { + filename: this.layout.assetPath, + path: `${this._repositoryUrl}/profiles/${this.profileId}/`, + }; + } + _getModelLoadingConstraints() { + const glbLoaded = SceneLoader.IsPluginForExtensionAvailable(".glb"); + if (!glbLoaded) { + Logger.Warn("glTF / glb loader was not registered, using generic controller instead"); + } + return glbLoaded; + } + _processLoadedModel(_meshes) { + this.getComponentIds().forEach((type) => { + const componentInLayout = this.layout.components[type]; + this._buttonMeshMapping[type] = { + mainMesh: this._getChildByName(this.rootMesh, componentInLayout.rootNodeName), + states: {}, + }; + Object.keys(componentInLayout.visualResponses).forEach((visualResponseKey) => { + const visResponse = componentInLayout.visualResponses[visualResponseKey]; + if (visResponse.valueNodeProperty === "transform") { + this._buttonMeshMapping[type].states[visualResponseKey] = { + valueMesh: this._getChildByName(this.rootMesh, visResponse.valueNodeName), + minMesh: this._getChildByName(this.rootMesh, visResponse.minNodeName), + maxMesh: this._getChildByName(this.rootMesh, visResponse.maxNodeName), + }; + } + else { + // visibility, usually for touchpads + const nameOfMesh = componentInLayout.type === WebXRControllerComponent.TOUCHPAD_TYPE && componentInLayout.touchPointNodeName + ? componentInLayout.touchPointNodeName + : visResponse.valueNodeName; + this._buttonMeshMapping[type].states[visualResponseKey] = { + valueMesh: this._getChildByName(this.rootMesh, nameOfMesh), + }; + if (componentInLayout.type === WebXRControllerComponent.TOUCHPAD_TYPE && !this._touchDots[visualResponseKey]) { + const dot = CreateSphere(visualResponseKey + "dot", { + diameter: 0.0015, + segments: 8, + }, this.scene); + dot.material = new StandardMaterial(visualResponseKey + "mat", this.scene); + dot.material.diffuseColor = Color3.Red(); + dot.parent = this._buttonMeshMapping[type].states[visualResponseKey].valueMesh || null; + dot.isVisible = false; + this._touchDots[visualResponseKey] = dot; + } + } + }); + }); + } + _setRootMesh(meshes) { + this.rootMesh = new Mesh(this.profileId + "-" + this.handedness, this.scene); + this.rootMesh.isPickable = false; + let rootMesh; + // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh' + for (let i = 0; i < meshes.length; i++) { + const mesh = meshes[i]; + mesh.isPickable = false; + if (!mesh.parent) { + // Handle root node, attach to the new parentMesh + rootMesh = mesh; + } + } + if (rootMesh) { + rootMesh.setParent(this.rootMesh); + } + if (!this.scene.useRightHandedSystem) { + this.rootMesh.rotate(Axis.Y, Math.PI, 1 /* Space.WORLD */); + } + } + _updateModel(_xrFrame) { + if (this.disableAnimation) { + return; + } + this.getComponentIds().forEach((id) => { + const component = this.getComponent(id); + if (!component.hasChanges) { + return; + } + const meshes = this._buttonMeshMapping[id]; + const componentInLayout = this.layout.components[id]; + Object.keys(componentInLayout.visualResponses).forEach((visualResponseKey) => { + const visResponse = componentInLayout.visualResponses[visualResponseKey]; + let value = component.value; + if (visResponse.componentProperty === "xAxis") { + value = component.axes.x; + } + else if (visResponse.componentProperty === "yAxis") { + value = component.axes.y; + } + if (visResponse.valueNodeProperty === "transform") { + this._lerpTransform(meshes.states[visualResponseKey], value, visResponse.componentProperty !== "button"); + } + else { + // visibility + const valueMesh = meshes.states[visualResponseKey].valueMesh; + if (valueMesh) { + valueMesh.isVisible = component.touched || component.pressed; + } + if (this._touchDots[visualResponseKey]) { + this._touchDots[visualResponseKey].isVisible = component.touched || component.pressed; + } + } + }); + }); + } +} + +/** + * The MotionController Manager manages all registered motion controllers and loads the right one when needed. + * + * When this repository is complete: https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/assets + * it should be replaced with auto-loaded controllers. + * + * When using a model try to stay as generic as possible. Eventually there will be no need in any of the controller classes + */ +const controllerCache = []; +/** + * Motion controller manager is managing the different webxr profiles and makes sure the right + * controller is being loaded. + */ +class WebXRMotionControllerManager { + /** + * Clear the cache used for profile loading and reload when requested again + */ + static ClearProfilesCache() { + this._ProfilesList = null; + this._ProfileLoadingPromises = {}; + } + /** + * Register the default fallbacks. + * This function is called automatically when this file is imported. + */ + static DefaultFallbacks() { + this.RegisterFallbacksForProfileId("google-daydream", ["generic-touchpad"]); + this.RegisterFallbacksForProfileId("htc-vive-focus", ["generic-trigger-touchpad"]); + this.RegisterFallbacksForProfileId("htc-vive", ["generic-trigger-squeeze-touchpad"]); + this.RegisterFallbacksForProfileId("magicleap-one", ["generic-trigger-squeeze-touchpad"]); + this.RegisterFallbacksForProfileId("windows-mixed-reality", ["generic-trigger-squeeze-touchpad-thumbstick"]); + this.RegisterFallbacksForProfileId("microsoft-mixed-reality", ["windows-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]); + this.RegisterFallbacksForProfileId("oculus-go", ["generic-trigger-touchpad"]); + this.RegisterFallbacksForProfileId("oculus-touch-v2", ["oculus-touch", "generic-trigger-squeeze-thumbstick"]); + this.RegisterFallbacksForProfileId("oculus-touch", ["generic-trigger-squeeze-thumbstick"]); + this.RegisterFallbacksForProfileId("samsung-gearvr", ["windows-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]); + this.RegisterFallbacksForProfileId("samsung-odyssey", ["generic-touchpad"]); + this.RegisterFallbacksForProfileId("valve-index", ["generic-trigger-squeeze-touchpad-thumbstick"]); + this.RegisterFallbacksForProfileId("generic-hand-select", ["generic-trigger"]); + } + /** + * Find a fallback profile if the profile was not found. There are a few predefined generic profiles. + * @param profileId the profile to which a fallback needs to be found + * @returns an array with corresponding fallback profiles + */ + static FindFallbackWithProfileId(profileId) { + const returnArray = this._Fallbacks[profileId] || []; + returnArray.unshift(profileId); + return returnArray; + } + /** + * When acquiring a new xrInput object (usually by the WebXRInput class), match it with the correct profile. + * The order of search: + * + * 1) Iterate the profiles array of the xr input and try finding a corresponding motion controller + * 2) (If not found) search in the gamepad id and try using it (legacy versions only) + * 3) search for registered fallbacks (should be redundant, nonetheless it makes sense to check) + * 4) return the generic trigger controller if none were found + * + * @param xrInput the xrInput to which a new controller is initialized + * @param scene the scene to which the model will be added + * @param forceProfile force a certain profile for this controller + * @returns A promise that fulfils with the motion controller class for this profile id or the generic standard class if none was found + */ + static GetMotionControllerWithXRInput(xrInput, scene, forceProfile) { + const profileArray = []; + if (forceProfile) { + profileArray.push(forceProfile); + } + profileArray.push(...(xrInput.profiles || [])); + // emulator support + if (profileArray.length && !profileArray[0]) { + // remove the first "undefined" that the emulator is adding + profileArray.pop(); + } + // legacy support - try using the gamepad id + if (xrInput.gamepad && xrInput.gamepad.id) { + switch (xrInput.gamepad.id) { + case xrInput.gamepad.id.match(/oculus touch/gi) ? xrInput.gamepad.id : undefined: + // oculus in gamepad id + profileArray.push("oculus-touch-v2"); + break; + } + } + // make sure microsoft/windows mixed reality works correctly + const windowsMRIdx = profileArray.indexOf("windows-mixed-reality"); + if (windowsMRIdx !== -1) { + profileArray.splice(windowsMRIdx, 0, "microsoft-mixed-reality"); + } + if (!profileArray.length) { + profileArray.push("generic-trigger"); + } + if (this.UseOnlineRepository) { + const firstFunction = this.PrioritizeOnlineRepository ? this._LoadProfileFromRepository : this._LoadProfilesFromAvailableControllers; + const secondFunction = this.PrioritizeOnlineRepository ? this._LoadProfilesFromAvailableControllers : this._LoadProfileFromRepository; + return firstFunction.call(this, profileArray, xrInput, scene).catch(() => { + return secondFunction.call(this, profileArray, xrInput, scene); + }); + } + else { + // use only available functions + return this._LoadProfilesFromAvailableControllers(profileArray, xrInput, scene); + } + } + /** + * Register a new controller based on its profile. This function will be called by the controller classes themselves. + * + * If you are missing a profile, make sure it is imported in your source, otherwise it will not register. + * + * @param type the profile type to register + * @param constructFunction the function to be called when loading this profile + */ + static RegisterController(type, constructFunction) { + this._AvailableControllers[type] = constructFunction; + } + /** + * Register a fallback to a specific profile. + * @param profileId the profileId that will receive the fallbacks + * @param fallbacks A list of fallback profiles + */ + static RegisterFallbacksForProfileId(profileId, fallbacks) { + if (this._Fallbacks[profileId]) { + this._Fallbacks[profileId].push(...fallbacks); + } + else { + this._Fallbacks[profileId] = fallbacks; + } + } + /** + * Will update the list of profiles available in the repository + * @returns a promise that resolves to a map of profiles available online + */ + static UpdateProfilesList() { + this._ProfilesList = Tools.LoadFileAsync(this.BaseRepositoryUrl + "/profiles/profilesList.json", false).then((data) => { + return JSON.parse(data); + }); + return this._ProfilesList; + } + /** + * Clear the controller's cache (usually happens at the end of a session) + */ + static ClearControllerCache() { + controllerCache.forEach((cacheItem) => { + cacheItem.meshes.forEach((mesh) => { + mesh.dispose(false, true); + }); + }); + controllerCache.length = 0; + } + static _LoadProfileFromRepository(profileArray, xrInput, scene) { + return Promise.resolve() + .then(() => { + if (!this._ProfilesList) { + return this.UpdateProfilesList(); + } + else { + return this._ProfilesList; + } + }) + .then((profilesList) => { + // load the right profile + for (let i = 0; i < profileArray.length; ++i) { + // defensive + if (!profileArray[i]) { + continue; + } + if (profilesList[profileArray[i]]) { + return profileArray[i]; + } + } + throw new Error(`neither controller ${profileArray[0]} nor all fallbacks were found in the repository,`); + }) + .then((profileToLoad) => { + // load the profile + if (!this._ProfileLoadingPromises[profileToLoad]) { + this._ProfileLoadingPromises[profileToLoad] = Tools.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${profileToLoad}/profile.json`, false).then((data) => JSON.parse(data)); + } + return this._ProfileLoadingPromises[profileToLoad]; + }) + .then((profile) => { + return new WebXRProfiledMotionController(scene, xrInput, profile, this.BaseRepositoryUrl, this.DisableControllerCache ? undefined : controllerCache); + }); + } + static _LoadProfilesFromAvailableControllers(profileArray, xrInput, scene) { + // check fallbacks + for (let i = 0; i < profileArray.length; ++i) { + // defensive + if (!profileArray[i]) { + continue; + } + const fallbacks = this.FindFallbackWithProfileId(profileArray[i]); + for (let j = 0; j < fallbacks.length; ++j) { + const constructionFunction = this._AvailableControllers[fallbacks[j]]; + if (constructionFunction) { + return Promise.resolve(constructionFunction(xrInput, scene)); + } + } + } + throw new Error(`no controller requested was found in the available controllers list`); + } +} +WebXRMotionControllerManager._AvailableControllers = {}; +WebXRMotionControllerManager._Fallbacks = {}; +// cache for loading +WebXRMotionControllerManager._ProfileLoadingPromises = {}; +/** + * The base URL of the online controller repository. Can be changed at any time. + */ +WebXRMotionControllerManager.BaseRepositoryUrl = "https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist"; +/** + * Which repository gets priority - local or online + */ +WebXRMotionControllerManager.PrioritizeOnlineRepository = true; +/** + * Use the online repository, or use only locally-defined controllers + */ +WebXRMotionControllerManager.UseOnlineRepository = true; +/** + * Disable the controller cache and load the models each time a new WebXRProfileMotionController is loaded. + * Defaults to true. + */ +WebXRMotionControllerManager.DisableControllerCache = true; +// register the generic profile(s) here so we will at least have them +WebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId, (xrInput, scene) => { + return new WebXRGenericTriggerMotionController(scene, xrInput.gamepad, xrInput.handedness); +}); +// register fallbacks +WebXRMotionControllerManager.DefaultFallbacks(); + +let idCount = 0; +/** + * Represents an XR controller + */ +class WebXRInputSource { + /** + * Creates the input source object + * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRInputControllerSupport + * @param _scene the scene which the controller should be associated to + * @param inputSource the underlying input source for the controller + * @param _options options for this controller creation + */ + constructor(_scene, + /** The underlying input source for the controller */ + inputSource, _options = {}) { + this._scene = _scene; + this.inputSource = inputSource; + this._options = _options; + this._tmpVector = new Vector3(); + this._disposed = false; + /** + * Event that fires when the controller is removed/disposed. + * The object provided as event data is this controller, after associated assets were disposed. + * uniqueId is still available. + */ + this.onDisposeObservable = new Observable(); + /** + * Will be triggered when the mesh associated with the motion controller is done loading. + * It is also possible that this will never trigger (!) if no mesh was loaded, or if the developer decides to load a different mesh + * A shortened version of controller -> motion controller -> on mesh loaded. + */ + this.onMeshLoadedObservable = new Observable(); + /** + * Observers registered here will trigger when a motion controller profile was assigned to this xr controller + */ + this.onMotionControllerInitObservable = new Observable(); + this._uniqueId = `controller-${idCount++}-${inputSource.targetRayMode}-${inputSource.handedness}`; + this.pointer = new Mesh(`${this._uniqueId}-pointer`, _scene); + this.pointer.rotationQuaternion = new Quaternion(); + if (this.inputSource.gripSpace) { + this.grip = new Mesh(`${this._uniqueId}-grip`, this._scene); + this.grip.rotationQuaternion = new Quaternion(); + } + this._tmpVector.set(0, 0, this._scene.useRightHandedSystem ? -1 : 1.0); + // for now only load motion controllers if gamepad object available + if (this.inputSource.gamepad && this.inputSource.targetRayMode === "tracked-pointer") { + WebXRMotionControllerManager.GetMotionControllerWithXRInput(inputSource, _scene, this._options.forceControllerProfile).then((motionController) => { + this.motionController = motionController; + this.onMotionControllerInitObservable.notifyObservers(motionController); + // should the model be loaded? + if (!this._options.doNotLoadControllerMesh && !this.motionController._doNotLoadControllerMesh) { + this.motionController.loadModel().then((success) => { + if (success && this.motionController && this.motionController.rootMesh) { + if (this._options.renderingGroupId) { + // anything other than 0? + this.motionController.rootMesh.renderingGroupId = this._options.renderingGroupId; + this.motionController.rootMesh.getChildMeshes(false).forEach((mesh) => (mesh.renderingGroupId = this._options.renderingGroupId)); + } + this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh); + this.motionController.rootMesh.parent = this.grip || this.pointer; + this.motionController.disableAnimation = !!this._options.disableMotionControllerAnimation; + } + // make sure to dispose is the controller is already disposed + if (this._disposed) { + this.motionController?.dispose(); + } + }); + } + }, () => { + Tools.Warn(`Could not find a matching motion controller for the registered input source`); + }); + } + } + /** + * Get this controllers unique id + */ + get uniqueId() { + return this._uniqueId; + } + /** + * Disposes of the object + */ + dispose() { + if (this.grip) { + this.grip.dispose(true); + } + if (this.motionController) { + this.motionController.dispose(); + } + this.pointer.dispose(true); + this.onMotionControllerInitObservable.clear(); + this.onMeshLoadedObservable.clear(); + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + this._disposed = true; + } + /** + * Gets a world space ray coming from the pointer or grip + * @param result the resulting ray + * @param gripIfAvailable use the grip mesh instead of the pointer, if available + */ + getWorldPointerRayToRef(result, gripIfAvailable = false) { + const object = gripIfAvailable && this.grip ? this.grip : this.pointer; + Vector3.TransformNormalToRef(this._tmpVector, object.getWorldMatrix(), result.direction); + result.direction.normalize(); + result.origin.copyFrom(object.absolutePosition); + result.length = 1000; + } + /** + * Updates the controller pose based on the given XRFrame + * @param xrFrame xr frame to update the pose with + * @param referenceSpace reference space to use + * @param xrCamera the xr camera, used for parenting + * @param xrSessionManager the session manager used to get the world reference system + */ + updateFromXRFrame(xrFrame, referenceSpace, xrCamera, xrSessionManager) { + const pose = xrFrame.getPose(this.inputSource.targetRaySpace, referenceSpace); + this._lastXRPose = pose; + // Update the pointer mesh + if (pose) { + const pos = pose.transform.position; + this.pointer.position.set(pos.x, pos.y, pos.z).scaleInPlace(xrSessionManager.worldScalingFactor); + const orientation = pose.transform.orientation; + this.pointer.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w); + if (!this._scene.useRightHandedSystem) { + this.pointer.position.z *= -1; + this.pointer.rotationQuaternion.z *= -1; + this.pointer.rotationQuaternion.w *= -1; + } + this.pointer.parent = xrCamera.parent; + this.pointer.scaling.setAll(xrSessionManager.worldScalingFactor); + } + // Update the grip mesh if it exists + if (this.inputSource.gripSpace && this.grip) { + const pose = xrFrame.getPose(this.inputSource.gripSpace, referenceSpace); + if (pose) { + const pos = pose.transform.position; + const orientation = pose.transform.orientation; + this.grip.position.set(pos.x, pos.y, pos.z).scaleInPlace(xrSessionManager.worldScalingFactor); + this.grip.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w); + if (!this._scene.useRightHandedSystem) { + this.grip.position.z *= -1; + this.grip.rotationQuaternion.z *= -1; + this.grip.rotationQuaternion.w *= -1; + } + } + this.grip.parent = xrCamera.parent; + this.grip.scaling.setAll(xrSessionManager.worldScalingFactor); + } + if (this.motionController) { + // either update buttons only or also position, if in gamepad mode + this.motionController.updateFromXRFrame(xrFrame); + } + } +} + +/** + * XR input used to track XR inputs such as controllers/rays + */ +class WebXRInput { + /** + * Initializes the WebXRInput + * @param xrSessionManager the xr session manager for this session + * @param xrCamera the WebXR camera for this session. Mainly used for teleportation + * @param _options = initialization options for this xr input + */ + constructor( + /** + * the xr session manager for this session + */ + xrSessionManager, + /** + * the WebXR camera for this session. Mainly used for teleportation + */ + xrCamera, _options = {}) { + this.xrSessionManager = xrSessionManager; + this.xrCamera = xrCamera; + this._options = _options; + /** + * XR controllers being tracked + */ + this.controllers = []; + /** + * Event when a controller has been connected/added + */ + this.onControllerAddedObservable = new Observable(); + /** + * Event when a controller has been removed/disconnected + */ + this.onControllerRemovedObservable = new Observable(); + this._onInputSourcesChange = (event) => { + this._addAndRemoveControllers(event.added, event.removed); + }; + // Remove controllers when exiting XR + this._sessionEndedObserver = this.xrSessionManager.onXRSessionEnded.add(() => { + this._addAndRemoveControllers([], this.controllers.map((c) => { + return c.inputSource; + })); + }); + this._sessionInitObserver = this.xrSessionManager.onXRSessionInit.add((session) => { + session.addEventListener("inputsourceschange", this._onInputSourcesChange); + }); + this._frameObserver = this.xrSessionManager.onXRFrameObservable.add((frame) => { + // Update controller pose info + this.controllers.forEach((controller) => { + controller.updateFromXRFrame(frame, this.xrSessionManager.referenceSpace, this.xrCamera, this.xrSessionManager); + }); + }); + if (this._options.customControllersRepositoryURL) { + WebXRMotionControllerManager.BaseRepositoryUrl = this._options.customControllersRepositoryURL; + } + WebXRMotionControllerManager.UseOnlineRepository = !this._options.disableOnlineControllerRepository; + if (WebXRMotionControllerManager.UseOnlineRepository) { + // pre-load the profiles list to load the controllers quicker afterwards + try { + WebXRMotionControllerManager.UpdateProfilesList().catch(() => { + WebXRMotionControllerManager.UseOnlineRepository = false; + }); + } + catch (e) { + WebXRMotionControllerManager.UseOnlineRepository = false; + } + } + } + _addAndRemoveControllers(addInputs, removeInputs) { + // Add controllers if they don't already exist + const sources = this.controllers.map((c) => { + return c.inputSource; + }); + for (const input of addInputs) { + if (sources.indexOf(input) === -1) { + const controller = new WebXRInputSource(this.xrSessionManager.scene, input, { + ...(this._options.controllerOptions || {}), + forceControllerProfile: this._options.forceInputProfile, + doNotLoadControllerMesh: this._options.doNotLoadControllerMeshes, + disableMotionControllerAnimation: this._options.disableControllerAnimation, + }); + this.controllers.push(controller); + this.onControllerAddedObservable.notifyObservers(controller); + } + } + // Remove and dispose of controllers to be disposed + const keepControllers = []; + const removedControllers = []; + this.controllers.forEach((c) => { + if (removeInputs.indexOf(c.inputSource) === -1) { + keepControllers.push(c); + } + else { + removedControllers.push(c); + } + }); + this.controllers = keepControllers; + removedControllers.forEach((c) => { + this.onControllerRemovedObservable.notifyObservers(c); + c.dispose(); + }); + } + /** + * Disposes of the object + */ + dispose() { + this.controllers.forEach((c) => { + c.dispose(); + }); + this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver); + this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver); + this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver); + this.onControllerAddedObservable.clear(); + this.onControllerRemovedObservable.clear(); + // clear the controller cache + WebXRMotionControllerManager.ClearControllerCache(); + } +} + +/** + * This is the base class for all WebXR features. + * Since most features require almost the same resources and callbacks, this class can be used to simplify the development + * Note that since the features manager is using the `IWebXRFeature` you are in no way obligated to use this class + */ +class WebXRAbstractFeature { + /** + * The name of the native xr feature name (like anchor, hit-test, or hand-tracking) + */ + get xrNativeFeatureName() { + return this._xrNativeFeatureName; + } + set xrNativeFeatureName(name) { + // check if feature was initialized while in session but needs to be initialized before the session starts + if (!this._xrSessionManager.isNative && name && this._xrSessionManager.inXRSession && this._xrSessionManager.enabledFeatures?.indexOf(name) === -1) { + Logger.Warn(`The feature ${name} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`); + } + this._xrNativeFeatureName = name; + } + /** + * Construct a new (abstract) WebXR feature + * @param _xrSessionManager the xr session manager for this feature + */ + constructor(_xrSessionManager) { + this._xrSessionManager = _xrSessionManager; + this._attached = false; + this._removeOnDetach = []; + /** + * Is this feature disposed? + */ + this.isDisposed = false; + /** + * Should auto-attach be disabled? + */ + this.disableAutoAttach = false; + this._xrNativeFeatureName = ""; + /** + * Observers registered here will be executed when the feature is attached + */ + this.onFeatureAttachObservable = new Observable(); + /** + * Observers registered here will be executed when the feature is detached + */ + this.onFeatureDetachObservable = new Observable(); + } + /** + * Is this feature attached + */ + get attached() { + return this._attached; + } + /** + * attach this feature + * + * @param force should attachment be forced (even when already attached) + * @returns true if successful, false is failed or already attached + */ + attach(force) { + // do not attach a disposed feature + if (this.isDisposed) { + return false; + } + if (!force) { + if (this.attached) { + return false; + } + } + else { + if (this.attached) { + // detach first, to be sure + this.detach(); + } + } + // if this is a native WebXR feature, check if it is enabled on the session + // For now only check if not using babylon native + // vision OS doesn't support the enabledFeatures array, so just warn instead of failing + if (!this._xrSessionManager.enabledFeatures) { + Logger.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported."); + } + else if (!this._xrSessionManager.isNative && this.xrNativeFeatureName && this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName) === -1) { + return false; + } + this._attached = true; + this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable, (frame) => this._onXRFrame(frame)); + this.onFeatureAttachObservable.notifyObservers(this); + return true; + } + /** + * detach this feature. + * + * @returns true if successful, false if failed or already detached + */ + detach() { + if (!this._attached) { + this.disableAutoAttach = true; + return false; + } + this._attached = false; + this._removeOnDetach.forEach((toRemove) => { + toRemove.observable.remove(toRemove.observer); + }); + this.onFeatureDetachObservable.notifyObservers(this); + return true; + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + this.detach(); + this.isDisposed = true; + this.onFeatureAttachObservable.clear(); + this.onFeatureDetachObservable.clear(); + } + /** + * This function will be executed during before enabling the feature and can be used to not-allow enabling it. + * Note that at this point the session has NOT started, so this is purely checking if the browser supports it + * + * @returns whether or not the feature is compatible in this environment + */ + isCompatible() { + return true; + } + /** + * This is used to register callbacks that will automatically be removed when detach is called. + * @param observable the observable to which the observer will be attached + * @param callback the callback to register + * @param insertFirst should the callback be executed as soon as it is registered + */ + _addNewAttachObserver(observable, callback, insertFirst) { + this._removeOnDetach.push({ + observable, + observer: observable.add(callback, undefined, insertFirst), + }); + } +} + +/** + * A module that will enable pointer selection for motion controllers of XR Input Sources + */ +class WebXRControllerPointerSelection extends WebXRAbstractFeature { + /** + * constructs a new background remover module + * @param _xrSessionManager the session manager for this module + * @param _options read-only options to be used in this module + */ + constructor(_xrSessionManager, _options) { + super(_xrSessionManager); + this._options = _options; + this._attachController = (xrController) => { + if (this._controllers[xrController.uniqueId]) { + // already attached + return; + } + const { laserPointer, selectionMesh } = this._generateNewMeshPair(this._options.forceGripIfAvailable && xrController.grip ? xrController.grip : xrController.pointer); + // get two new meshes + this._controllers[xrController.uniqueId] = { + xrController, + laserPointer, + selectionMesh, + meshUnderPointer: null, + pick: null, + tmpRay: new Ray(new Vector3(), new Vector3()), + disabledByNearInteraction: false, + id: WebXRControllerPointerSelection._IdCounter++, + }; + if (this._attachedController) { + if (!this._options.enablePointerSelectionOnAllControllers && + this._options.preferredHandedness && + xrController.inputSource.handedness === this._options.preferredHandedness) { + this._attachedController = xrController.uniqueId; + } + } + else { + if (!this._options.enablePointerSelectionOnAllControllers) { + this._attachedController = xrController.uniqueId; + } + } + switch (xrController.inputSource.targetRayMode) { + case "tracked-pointer": + return this._attachTrackedPointerRayMode(xrController); + case "gaze": + return this._attachGazeMode(xrController); + case "screen": + case "transient-pointer": + return this._attachScreenRayMode(xrController); + } + }; + this._controllers = {}; + this._tmpVectorForPickCompare = new Vector3(); + /** + * Disable lighting on the laser pointer (so it will always be visible) + */ + this.disablePointerLighting = true; + /** + * Disable lighting on the selection mesh (so it will always be visible) + */ + this.disableSelectionMeshLighting = true; + /** + * Should the laser pointer be displayed + */ + this.displayLaserPointer = true; + /** + * Should the selection mesh be displayed (The ring at the end of the laser pointer) + */ + this.displaySelectionMesh = true; + /** + * This color will be set to the laser pointer when selection is triggered + */ + this.laserPointerPickedColor = new Color3(0.9, 0.9, 0.9); + /** + * Default color of the laser pointer + */ + this.laserPointerDefaultColor = new Color3(0.7, 0.7, 0.7); + /** + * default color of the selection ring + */ + this.selectionMeshDefaultColor = new Color3(0.8, 0.8, 0.8); + /** + * This color will be applied to the selection ring when selection is triggered + */ + this.selectionMeshPickedColor = new Color3(0.3, 0.3, 1.0); + this._identityMatrix = Matrix.Identity(); + this._screenCoordinatesRef = Vector3.Zero(); + this._viewportRef = new Viewport(0, 0, 0, 0); + this._scene = this._xrSessionManager.scene; + // force look and pick mode if using WebXR on safari, assuming it is vision OS + // Only if not explicitly set. If set to false, it will not be forced + if (this._options.lookAndPickMode === undefined && (this._scene.getEngine()._badDesktopOS || this._scene.getEngine()._badOS)) { + this._options.lookAndPickMode = true; + } + // look and pick mode extra state changes + if (this._options.lookAndPickMode) { + this._options.enablePointerSelectionOnAllControllers = true; + this.displayLaserPointer = false; + } + } + /** + * attach this feature + * Will usually be called by the features manager + * + * @returns true if successful. + */ + attach() { + if (!super.attach()) { + return false; + } + this._options.xrInput.controllers.forEach(this._attachController); + this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController, true); + this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => { + // REMOVE the controller + this._detachController(controller.uniqueId); + }, true); + this._scene.constantlyUpdateMeshUnderPointer = true; + if (this._options.gazeCamera) { + const webXRCamera = this._options.gazeCamera; + const { laserPointer, selectionMesh } = this._generateNewMeshPair(webXRCamera); + this._controllers["camera"] = { + webXRCamera, + laserPointer, + selectionMesh, + meshUnderPointer: null, + pick: null, + tmpRay: new Ray(new Vector3(), new Vector3()), + disabledByNearInteraction: false, + id: WebXRControllerPointerSelection._IdCounter++, + }; + this._attachGazeMode(); + } + return true; + } + /** + * detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + if (!super.detach()) { + return false; + } + Object.keys(this._controllers).forEach((controllerId) => { + this._detachController(controllerId); + }); + return true; + } + /** + * Will get the mesh under a specific pointer. + * `scene.meshUnderPointer` will only return one mesh - either left or right. + * @param controllerId the controllerId to check + * @returns The mesh under pointer or null if no mesh is under the pointer + */ + getMeshUnderPointer(controllerId) { + if (this._controllers[controllerId]) { + return this._controllers[controllerId].meshUnderPointer; + } + else { + return null; + } + } + /** + * Get the xr controller that correlates to the pointer id in the pointer event + * + * @param id the pointer id to search for + * @returns the controller that correlates to this id or null if not found + */ + getXRControllerByPointerId(id) { + const keys = Object.keys(this._controllers); + for (let i = 0; i < keys.length; ++i) { + if (this._controllers[keys[i]].id === id) { + return this._controllers[keys[i]].xrController || null; + } + } + return null; + } + /** + * @internal + */ + _getPointerSelectionDisabledByPointerId(id) { + const keys = Object.keys(this._controllers); + for (let i = 0; i < keys.length; ++i) { + if (this._controllers[keys[i]].id === id) { + return this._controllers[keys[i]].disabledByNearInteraction; + } + } + return true; + } + /** + * @internal + */ + _setPointerSelectionDisabledByPointerId(id, state) { + const keys = Object.keys(this._controllers); + for (let i = 0; i < keys.length; ++i) { + if (this._controllers[keys[i]].id === id) { + this._controllers[keys[i]].disabledByNearInteraction = state; + return; + } + } + } + _onXRFrame(_xrFrame) { + Object.keys(this._controllers).forEach((id) => { + // look and pick mode + // only do this for the selected pointer + const controllerData = this._controllers[id]; + if (this._options.lookAndPickMode && controllerData.xrController?.inputSource.targetRayMode !== "transient-pointer") { + return; + } + if ((!this._options.enablePointerSelectionOnAllControllers && id !== this._attachedController) || controllerData.disabledByNearInteraction) { + controllerData.selectionMesh.isVisible = false; + controllerData.laserPointer.isVisible = false; + controllerData.pick = null; + return; + } + controllerData.laserPointer.isVisible = this.displayLaserPointer; + let controllerGlobalPosition; + // Every frame check collisions/input + if (controllerData.xrController) { + controllerGlobalPosition = + this._options.forceGripIfAvailable && controllerData.xrController.grip + ? controllerData.xrController.grip.position + : controllerData.xrController.pointer.position; + controllerData.xrController.getWorldPointerRayToRef(controllerData.tmpRay, this._options.forceGripIfAvailable); + } + else if (controllerData.webXRCamera) { + controllerGlobalPosition = controllerData.webXRCamera.position; + controllerData.webXRCamera.getForwardRayToRef(controllerData.tmpRay); + } + else { + return; + } + if (this._options.maxPointerDistance) { + controllerData.tmpRay.length = this._options.maxPointerDistance; + } + // update pointerX and pointerY of the scene. Only if the flag is set to true! + if (!this._options.disableScenePointerVectorUpdate && controllerGlobalPosition) { + const scene = this._xrSessionManager.scene; + const camera = this._options.xrInput.xrCamera; + if (camera) { + camera.viewport.toGlobalToRef(scene.getEngine().getRenderWidth() / camera.rigCameras.length, scene.getEngine().getRenderHeight(), this._viewportRef); + Vector3.ProjectToRef(controllerGlobalPosition, this._identityMatrix, camera.getTransformationMatrix(), this._viewportRef, this._screenCoordinatesRef); + // stay safe + if (typeof this._screenCoordinatesRef.x === "number" && + typeof this._screenCoordinatesRef.y === "number" && + !isNaN(this._screenCoordinatesRef.x) && + !isNaN(this._screenCoordinatesRef.y) && + this._screenCoordinatesRef.x !== Infinity && + this._screenCoordinatesRef.y !== Infinity) { + scene.pointerX = this._screenCoordinatesRef.x; + scene.pointerY = this._screenCoordinatesRef.y; + controllerData.screenCoordinates = { + x: this._screenCoordinatesRef.x, + y: this._screenCoordinatesRef.y, + }; + } + } + } + let utilityScenePick = null; + if (this._utilityLayerScene) { + utilityScenePick = this._utilityLayerScene.pickWithRay(controllerData.tmpRay, this._utilityLayerScene.pointerMovePredicate || this.raySelectionPredicate); + } + const originalScenePick = this._scene.pickWithRay(controllerData.tmpRay, this._scene.pointerMovePredicate || this.raySelectionPredicate); + if (!utilityScenePick || !utilityScenePick.hit) { + // No hit in utility scene + controllerData.pick = originalScenePick; + } + else if (!originalScenePick || !originalScenePick.hit) { + // No hit in original scene + controllerData.pick = utilityScenePick; + } + else if (utilityScenePick.distance < originalScenePick.distance) { + // Hit is closer in utility scene + controllerData.pick = utilityScenePick; + } + else { + // Hit is closer in original scene + controllerData.pick = originalScenePick; + } + if (controllerData.pick && controllerData.xrController) { + controllerData.pick.aimTransform = controllerData.xrController.pointer; + controllerData.pick.gripTransform = controllerData.xrController.grip || null; + controllerData.pick.originMesh = controllerData.xrController.pointer; + controllerData.tmpRay.length = controllerData.pick.distance; + } + const pick = controllerData.pick; + if (pick && pick.pickedPoint && pick.hit) { + // Update laser state + this._updatePointerDistance(controllerData.laserPointer, pick.distance); + // Update cursor state + controllerData.selectionMesh.position.copyFrom(pick.pickedPoint); + controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance); + controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance); + controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance); + // To avoid z-fighting + const pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), controllerData.tmpRay); + const deltaFighting = 0.001; + controllerData.selectionMesh.position.copyFrom(pick.pickedPoint); + if (pickNormal) { + const axis1 = Vector3.Cross(Axis.Y, pickNormal); + const axis2 = Vector3.Cross(pickNormal, axis1); + Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation); + controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting)); + } + controllerData.selectionMesh.isVisible = this.displaySelectionMesh; + controllerData.meshUnderPointer = pick.pickedMesh; + } + else { + controllerData.selectionMesh.isVisible = false; + this._updatePointerDistance(controllerData.laserPointer, 1); + controllerData.meshUnderPointer = null; + } + }); + } + get _utilityLayerScene() { + return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene; + } + _attachGazeMode(xrController) { + const controllerData = this._controllers[(xrController && xrController.uniqueId) || "camera"]; + // attached when touched, detaches when raised + const timeToSelect = this._options.timeToSelect || 3000; + const sceneToRenderTo = this._options.useUtilityLayer ? this._utilityLayerScene : this._scene; + let oldPick = new PickingInfo(); + const discMesh = CreateTorus("selection", { + diameter: 0.0035 * 15, + thickness: 0.0025 * 6, + tessellation: 20, + }, sceneToRenderTo); + discMesh.isVisible = false; + discMesh.isPickable = false; + discMesh.parent = controllerData.selectionMesh; + let timer = 0; + let downTriggered = false; + const pointerEventInit = { + pointerId: controllerData.id, + pointerType: "xr", + }; + controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => { + if (!controllerData.pick) { + return; + } + this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); + controllerData.laserPointer.material.alpha = 0; + discMesh.isVisible = false; + if (controllerData.pick.hit) { + if (!this._pickingMoved(oldPick, controllerData.pick)) { + if (timer > timeToSelect / 10) { + discMesh.isVisible = true; + } + timer += this._scene.getEngine().getDeltaTime(); + if (timer >= timeToSelect) { + this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); + // this pointerdown event is not setting the controllerData.pointerDownTriggered to avoid a pointerUp event when this feature is detached + downTriggered = true; + // pointer up right after down, if disable on touch out + if (this._options.disablePointerUpOnTouchOut) { + this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); + } + discMesh.isVisible = false; + } + else { + const scaleFactor = 1 - timer / timeToSelect; + discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor); + } + } + else { + if (downTriggered) { + if (!this._options.disablePointerUpOnTouchOut) { + this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); + } + } + downTriggered = false; + timer = 0; + } + } + else { + downTriggered = false; + timer = 0; + } + this._scene.simulatePointerMove(controllerData.pick, pointerEventInit); + oldPick = controllerData.pick; + }); + if (this._options.renderingGroupId !== undefined) { + discMesh.renderingGroupId = this._options.renderingGroupId; + } + if (xrController) { + xrController.onDisposeObservable.addOnce(() => { + if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) { + this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); + controllerData.finalPointerUpTriggered = true; + } + discMesh.dispose(); + }); + } + } + _attachScreenRayMode(xrController) { + const controllerData = this._controllers[xrController.uniqueId]; + let downTriggered = false; + const pointerEventInit = { + pointerId: controllerData.id, + pointerType: "xr", + }; + controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => { + this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); + if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) { + return; + } + if (!downTriggered) { + this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); + controllerData.pointerDownTriggered = true; + downTriggered = true; + if (this._options.disablePointerUpOnTouchOut) { + this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); + } + } + else { + this._scene.simulatePointerMove(controllerData.pick, pointerEventInit); + } + }); + xrController.onDisposeObservable.addOnce(() => { + this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); + this._xrSessionManager.runInXRFrame(() => { + if (controllerData.pick && !controllerData.finalPointerUpTriggered && downTriggered && !this._options.disablePointerUpOnTouchOut) { + this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); + controllerData.finalPointerUpTriggered = true; + } + }); + }); + } + _attachTrackedPointerRayMode(xrController) { + const controllerData = this._controllers[xrController.uniqueId]; + if (this._options.forceGazeMode) { + return this._attachGazeMode(xrController); + } + const pointerEventInit = { + pointerId: controllerData.id, + pointerType: "xr", + }; + controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => { + controllerData.laserPointer.material.disableLighting = this.disablePointerLighting; + controllerData.selectionMesh.material.disableLighting = this.disableSelectionMeshLighting; + if (controllerData.pick) { + this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); + this._scene.simulatePointerMove(controllerData.pick, pointerEventInit); + } + }); + if (xrController.inputSource.gamepad) { + const init = (motionController) => { + if (this._options.overrideButtonId) { + controllerData.selectionComponent = motionController.getComponent(this._options.overrideButtonId); + } + if (!controllerData.selectionComponent) { + controllerData.selectionComponent = motionController.getMainComponent(); + } + controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => { + if (component.changes.pressed) { + const pressed = component.changes.pressed.current; + if (controllerData.pick) { + if (this._options.enablePointerSelectionOnAllControllers || xrController.uniqueId === this._attachedController) { + this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); + if (pressed) { + this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); + controllerData.pointerDownTriggered = true; + controllerData.selectionMesh.material.emissiveColor = this.selectionMeshPickedColor; + controllerData.laserPointer.material.emissiveColor = this.laserPointerPickedColor; + } + else { + this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); + controllerData.selectionMesh.material.emissiveColor = this.selectionMeshDefaultColor; + controllerData.laserPointer.material.emissiveColor = this.laserPointerDefaultColor; + } + } + } + else { + if (pressed && !this._options.enablePointerSelectionOnAllControllers && !this._options.disableSwitchOnClick) { + // force a pointer up if switching controllers + // get the controller that was attached before + const prevController = this._controllers[this._attachedController]; + if (prevController && prevController.pointerDownTriggered && !prevController.finalPointerUpTriggered) { + this._augmentPointerInit(pointerEventInit, prevController.id, prevController.screenCoordinates); + this._scene.simulatePointerUp(new PickingInfo(), { + pointerId: prevController.id, + pointerType: "xr", + }); + prevController.finalPointerUpTriggered = true; + } + this._attachedController = xrController.uniqueId; + } + } + } + }); + }; + if (xrController.motionController) { + init(xrController.motionController); + } + else { + xrController.onMotionControllerInitObservable.add(init); + } + } + else { + // use the select and squeeze events + const selectStartListener = (event) => { + this._xrSessionManager.onXRFrameObservable.addOnce(() => { + this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); + if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) { + this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); + controllerData.pointerDownTriggered = true; + controllerData.selectionMesh.material.emissiveColor = this.selectionMeshPickedColor; + controllerData.laserPointer.material.emissiveColor = this.laserPointerPickedColor; + } + }); + }; + const selectEndListener = (event) => { + this._xrSessionManager.onXRFrameObservable.addOnce(() => { + this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); + if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) { + this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); + controllerData.selectionMesh.material.emissiveColor = this.selectionMeshDefaultColor; + controllerData.laserPointer.material.emissiveColor = this.laserPointerDefaultColor; + } + }); + }; + controllerData.eventListeners = { + selectend: selectEndListener, + selectstart: selectStartListener, + }; + this._xrSessionManager.session.addEventListener("selectstart", selectStartListener); + this._xrSessionManager.session.addEventListener("selectend", selectEndListener); + } + } + _convertNormalToDirectionOfRay(normal, ray) { + if (normal) { + const angle = Math.acos(Vector3.Dot(normal, ray.direction)); + if (angle < Math.PI / 2) { + normal.scaleInPlace(-1); + } + } + return normal; + } + _detachController(xrControllerUniqueId) { + const controllerData = this._controllers[xrControllerUniqueId]; + if (!controllerData) { + return; + } + if (controllerData.selectionComponent) { + if (controllerData.onButtonChangedObserver) { + controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver); + } + } + if (controllerData.onFrameObserver) { + this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver); + } + if (controllerData.eventListeners) { + Object.keys(controllerData.eventListeners).forEach((eventName) => { + const func = controllerData.eventListeners && controllerData.eventListeners[eventName]; + if (func) { + // For future reference - this is an issue in the WebXR typings. + this._xrSessionManager.session.removeEventListener(eventName, func); + } + }); + } + if (!controllerData.finalPointerUpTriggered && controllerData.pointerDownTriggered) { + // Stay safe and fire a pointerup, in case it wasn't already triggered + const pointerEventInit = { + pointerId: controllerData.id, + pointerType: "xr", + }; + this._xrSessionManager.runInXRFrame(() => { + this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); + this._scene.simulatePointerUp(controllerData.pick || new PickingInfo(), pointerEventInit); + controllerData.finalPointerUpTriggered = true; + }); + } + this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(() => { + try { + controllerData.selectionMesh.dispose(); + controllerData.laserPointer.dispose(); + // remove from the map + delete this._controllers[xrControllerUniqueId]; + if (this._attachedController === xrControllerUniqueId) { + // check for other controllers + const keys = Object.keys(this._controllers); + if (keys.length) { + this._attachedController = keys[0]; + } + else { + this._attachedController = ""; + } + } + } + catch (e) { + Tools.Warn("controller already detached."); + } + }); + } + _generateNewMeshPair(meshParent) { + const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene; + const laserPointer = this._options.customLasterPointerMeshGenerator + ? this._options.customLasterPointerMeshGenerator() + : CreateCylinder("laserPointer", { + height: 1, + diameterTop: 0.0002, + diameterBottom: 0.004, + tessellation: 20, + subdivisions: 1, + }, sceneToRenderTo); + laserPointer.parent = meshParent; + const laserPointerMaterial = new StandardMaterial("laserPointerMat", sceneToRenderTo); + laserPointerMaterial.emissiveColor = this.laserPointerDefaultColor; + laserPointerMaterial.alpha = 0.7; + laserPointer.material = laserPointerMaterial; + laserPointer.rotation.x = Math.PI / 2; + this._updatePointerDistance(laserPointer, 1); + laserPointer.isPickable = false; + laserPointer.isVisible = false; + // Create a gaze tracker for the XR controller + const selectionMesh = this._options.customSelectionMeshGenerator + ? this._options.customSelectionMeshGenerator() + : CreateTorus("gazeTracker", { + diameter: 0.0035 * 3, + thickness: 0.0025 * 3, + tessellation: 20, + }, sceneToRenderTo); + selectionMesh.bakeCurrentTransformIntoVertices(); + selectionMesh.isPickable = false; + selectionMesh.isVisible = false; + const targetMat = new StandardMaterial("targetMat", sceneToRenderTo); + targetMat.specularColor = Color3.Black(); + targetMat.emissiveColor = this.selectionMeshDefaultColor; + targetMat.backFaceCulling = false; + selectionMesh.material = targetMat; + if (this._options.renderingGroupId !== undefined) { + laserPointer.renderingGroupId = this._options.renderingGroupId; + selectionMesh.renderingGroupId = this._options.renderingGroupId; + } + return { + laserPointer, + selectionMesh, + }; + } + _pickingMoved(oldPick, newPick) { + if (!oldPick.hit || !newPick.hit) { + return true; + } + if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) { + return true; + } + if (oldPick.pickedMesh !== newPick.pickedMesh) { + return true; + } + oldPick.pickedPoint?.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare); + this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z)); + const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 * newPick.distance; + const length = this._tmpVectorForPickCompare.length(); + if (length > delta) { + return true; + } + return false; + } + _updatePointerDistance(_laserPointer, distance = 100) { + _laserPointer.scaling.y = distance; + // a bit of distance from the controller + if (this._scene.useRightHandedSystem) { + distance *= -1; + } + _laserPointer.position.z = distance / 2 + 0.05; + } + _augmentPointerInit(pointerEventInit, id, screenCoordinates) { + pointerEventInit.pointerId = id; + pointerEventInit.pointerType = "xr"; + if (screenCoordinates) { + pointerEventInit.screenX = screenCoordinates.x; + pointerEventInit.screenY = screenCoordinates.y; + } + } + /** @internal */ + get lasterPointerDefaultColor() { + // here due to a typo + return this.laserPointerDefaultColor; + } +} +WebXRControllerPointerSelection._IdCounter = 200; +/** + * The module's name + */ +WebXRControllerPointerSelection.Name = WebXRFeatureName.POINTER_SELECTION; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRControllerPointerSelection.Version = 1; +//register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => { + return () => new WebXRControllerPointerSelection(xrSessionManager, options); +}, WebXRControllerPointerSelection.Version, true); + +/** + * Defines the kind of connection point for node based material + */ +var NodeMaterialBlockConnectionPointTypes; +(function (NodeMaterialBlockConnectionPointTypes) { + /** Float */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Float"] = 1] = "Float"; + /** Int */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Int"] = 2] = "Int"; + /** Vector2 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector2"] = 4] = "Vector2"; + /** Vector3 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector3"] = 8] = "Vector3"; + /** Vector4 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector4"] = 16] = "Vector4"; + /** Color3 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Color3"] = 32] = "Color3"; + /** Color4 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Color4"] = 64] = "Color4"; + /** Matrix */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Matrix"] = 128] = "Matrix"; + /** Custom object */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Object"] = 256] = "Object"; + /** Detect type based on connection */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["AutoDetect"] = 1024] = "AutoDetect"; + /** Output type that will be defined by input type */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["BasedOnInput"] = 2048] = "BasedOnInput"; + /** Bitmask of all types */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["All"] = 4095] = "All"; +})(NodeMaterialBlockConnectionPointTypes || (NodeMaterialBlockConnectionPointTypes = {})); + +/** + * Enum used to define the target of a block + */ +var NodeMaterialBlockTargets; +(function (NodeMaterialBlockTargets) { + /** Vertex shader */ + NodeMaterialBlockTargets[NodeMaterialBlockTargets["Vertex"] = 1] = "Vertex"; + /** Fragment shader */ + NodeMaterialBlockTargets[NodeMaterialBlockTargets["Fragment"] = 2] = "Fragment"; + /** Neutral */ + NodeMaterialBlockTargets[NodeMaterialBlockTargets["Neutral"] = 4] = "Neutral"; + /** Vertex and Fragment */ + NodeMaterialBlockTargets[NodeMaterialBlockTargets["VertexAndFragment"] = 3] = "VertexAndFragment"; +})(NodeMaterialBlockTargets || (NodeMaterialBlockTargets = {})); + +/** + * Class used to store node based material build state + */ +class NodeMaterialBuildState { + constructor() { + /** Gets or sets a boolean indicating if the current state can emit uniform buffers */ + this.supportUniformBuffers = false; + /** + * Gets the list of emitted attributes + */ + this.attributes = []; + /** + * Gets the list of emitted uniforms + */ + this.uniforms = []; + /** + * Gets the list of emitted constants + */ + this.constants = []; + /** + * Gets the list of emitted samplers + */ + this.samplers = []; + /** + * Gets the list of emitted functions + */ + this.functions = {}; + /** + * Gets the list of emitted extensions + */ + this.extensions = {}; + /** + * Gets the list of emitted prePass outputs - if using the prepass + */ + this.prePassOutput = {}; + /** + * Gets the list of emitted counters + */ + this.counters = {}; + /** @internal */ + this._terminalBlocks = new Set(); + /** @internal */ + this._attributeDeclaration = ""; + /** @internal */ + this._uniformDeclaration = ""; + /** @internal */ + this._constantDeclaration = ""; + /** @internal */ + this._samplerDeclaration = ""; + /** @internal */ + this._varyingTransfer = ""; + /** @internal */ + this._injectAtEnd = ""; + this._repeatableContentAnchorIndex = 0; + /** @internal */ + this._builtCompilationString = ""; + /** + * Gets the emitted compilation strings + */ + this.compilationString = ""; + } + /** + * Gets the current shader language to use + */ + get shaderLanguage() { + return this.sharedData.nodeMaterial.shaderLanguage; + } + /** Gets suffix to add behind type casting */ + get fSuffix() { + return this.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "f" : ""; + } + /** + * Finalize the compilation strings + * @param state defines the current compilation state + */ + finalize(state) { + const emitComments = state.sharedData.emitComments; + const isFragmentMode = this.target === NodeMaterialBlockTargets.Fragment; + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + if (isFragmentMode) { + this.compilationString = `\n${emitComments ? "//Entry point\n" : ""}@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${this.sharedData.varyingInitializationsFragment}${this.compilationString}`; + } + else { + this.compilationString = `\n${emitComments ? "//Entry point\n" : ""}@vertex\nfn main(input: VertexInputs) -> FragmentInputs{\n${this.compilationString}`; + } + } + else { + this.compilationString = `\n${emitComments ? "//Entry point\n" : ""}void main(void) {\n${this.compilationString}`; + } + if (this._constantDeclaration) { + this.compilationString = `\n${emitComments ? "//Constants\n" : ""}${this._constantDeclaration}\n${this.compilationString}`; + } + let functionCode = ""; + for (const functionName in this.functions) { + functionCode += this.functions[functionName] + `\n`; + } + this.compilationString = `\n${functionCode}\n${this.compilationString}`; + if (!isFragmentMode && this._varyingTransfer) { + this.compilationString = `${this.compilationString}\n${this._varyingTransfer}`; + } + if (this._injectAtEnd) { + this.compilationString = `${this.compilationString}\n${this._injectAtEnd}`; + } + this.compilationString = `${this.compilationString}\n}`; + if (this.sharedData.varyingDeclaration) { + this.compilationString = `\n${emitComments ? "//Varyings\n" : ""}${isFragmentMode ? this.sharedData.varyingDeclarationFragment : this.sharedData.varyingDeclaration}\n${this.compilationString}`; + } + if (this._samplerDeclaration) { + this.compilationString = `\n${emitComments ? "//Samplers\n" : ""}${this._samplerDeclaration}\n${this.compilationString}`; + } + if (this._uniformDeclaration) { + this.compilationString = `\n${emitComments ? "//Uniforms\n" : ""}${this._uniformDeclaration}\n${this.compilationString}`; + } + if (this._attributeDeclaration && !isFragmentMode) { + this.compilationString = `\n${emitComments ? "//Attributes\n" : ""}${this._attributeDeclaration}\n${this.compilationString}`; + } + if (this.shaderLanguage !== 1 /* ShaderLanguage.WGSL */) { + this.compilationString = "precision highp float;\n" + this.compilationString; + this.compilationString = "#if defined(WEBGL2) || defined(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n" + this.compilationString; + if (isFragmentMode) { + this.compilationString = + "#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n" + + this.compilationString; + } + for (const extensionName in this.extensions) { + const extension = this.extensions[extensionName]; + this.compilationString = `\n${extension}\n${this.compilationString}`; + } + } + this._builtCompilationString = this.compilationString; + } + /** @internal */ + get _repeatableContentAnchor() { + return `###___ANCHOR${this._repeatableContentAnchorIndex++}___###`; + } + /** + * @internal + */ + _getFreeVariableName(prefix) { + prefix = prefix.replace(/[^a-zA-Z_]+/g, ""); + if (this.sharedData.variableNames[prefix] === undefined) { + this.sharedData.variableNames[prefix] = 0; + // Check reserved words + if (prefix === "output" || prefix === "texture") { + return prefix + this.sharedData.variableNames[prefix]; + } + return prefix; + } + else { + this.sharedData.variableNames[prefix]++; + } + return prefix + this.sharedData.variableNames[prefix]; + } + /** + * @internal + */ + _getFreeDefineName(prefix) { + if (this.sharedData.defineNames[prefix] === undefined) { + this.sharedData.defineNames[prefix] = 0; + } + else { + this.sharedData.defineNames[prefix]++; + } + return prefix + this.sharedData.defineNames[prefix]; + } + /** + * @internal + */ + _excludeVariableName(name) { + this.sharedData.variableNames[name] = 0; + } + /** + * @internal + */ + _emit2DSampler(name, define = "", force = false) { + if (this.samplers.indexOf(name) < 0 || force) { + if (define) { + this._samplerDeclaration += `#if ${define}\n`; + } + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + this._samplerDeclaration += `var ${name + `Sampler`}: sampler;\n`; + this._samplerDeclaration += `var ${name}: texture_2d;\n`; + } + else { + this._samplerDeclaration += `uniform sampler2D ${name};\n`; + } + if (define) { + this._samplerDeclaration += `#endif\n`; + } + if (!force) { + this.samplers.push(name); + } + } + } + /** + * @internal + */ + _emitCubeSampler(name, define = "", force = false) { + if (this.samplers.indexOf(name) < 0 || force) { + if (define) { + this._samplerDeclaration += `#if ${define}\n`; + } + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + this._samplerDeclaration += `var ${name + `Sampler`}: sampler;\n`; + this._samplerDeclaration += `var ${name}: texture_cube;\n`; + } + else { + this._samplerDeclaration += `uniform samplerCube ${name};\n`; + } + if (define) { + this._samplerDeclaration += `#endif\n`; + } + if (!force) { + this.samplers.push(name); + } + } + } + /** + * @internal + */ + _emit2DArraySampler(name) { + if (this.samplers.indexOf(name) < 0) { + this._samplerDeclaration += `uniform sampler2DArray ${name};\n`; + this.samplers.push(name); + } + } + /** + * @internal + */ + _getGLType(type) { + switch (type) { + case NodeMaterialBlockConnectionPointTypes.Float: + return "float"; + case NodeMaterialBlockConnectionPointTypes.Int: + return "int"; + case NodeMaterialBlockConnectionPointTypes.Vector2: + return "vec2"; + case NodeMaterialBlockConnectionPointTypes.Color3: + case NodeMaterialBlockConnectionPointTypes.Vector3: + return "vec3"; + case NodeMaterialBlockConnectionPointTypes.Color4: + case NodeMaterialBlockConnectionPointTypes.Vector4: + return "vec4"; + case NodeMaterialBlockConnectionPointTypes.Matrix: + return "mat4"; + } + return ""; + } + /** + * @internal + */ + _getShaderType(type) { + const isWGSL = this.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + switch (type) { + case NodeMaterialBlockConnectionPointTypes.Float: + return isWGSL ? "f32" : "float"; + case NodeMaterialBlockConnectionPointTypes.Int: + return isWGSL ? "i32" : "int"; + case NodeMaterialBlockConnectionPointTypes.Vector2: + return isWGSL ? "vec2f" : "vec2"; + case NodeMaterialBlockConnectionPointTypes.Color3: + case NodeMaterialBlockConnectionPointTypes.Vector3: + return isWGSL ? "vec3f" : "vec3"; + case NodeMaterialBlockConnectionPointTypes.Color4: + case NodeMaterialBlockConnectionPointTypes.Vector4: + return isWGSL ? "vec4f" : "vec4"; + case NodeMaterialBlockConnectionPointTypes.Matrix: + return isWGSL ? "mat4x4f" : "mat4"; + } + return ""; + } + /** + * @internal + */ + _emitExtension(name, extension, define = "") { + if (this.extensions[name]) { + return; + } + if (define) { + extension = `#if ${define}\n${extension}\n#endif`; + } + this.extensions[name] = extension; + } + /** + * @internal + */ + _emitFunction(name, code, comments) { + if (this.functions[name]) { + return; + } + if (this.sharedData.emitComments) { + code = comments + `\n` + code; + } + this.functions[name] = code; + } + /** + * @internal + */ + _emitCodeFromInclude(includeName, comments, options) { + const store = ShaderStore.GetIncludesShadersStore(this.shaderLanguage); + if (options && options.repeatKey) { + return `#include<${includeName}>${options.substitutionVars ? "(" + options.substitutionVars + ")" : ""}[0..${options.repeatKey}]\n`; + } + let code = store[includeName] + "\n"; + if (this.sharedData.emitComments) { + code = comments + `\n` + code; + } + if (!options) { + return code; + } + if (options.replaceStrings) { + for (let index = 0; index < options.replaceStrings.length; index++) { + const replaceString = options.replaceStrings[index]; + code = code.replace(replaceString.search, replaceString.replace); + } + } + return code; + } + /** + * @internal + */ + _emitFunctionFromInclude(includeName, comments, options, storeKey = "") { + const key = includeName + storeKey; + if (this.functions[key]) { + return; + } + const store = ShaderStore.GetIncludesShadersStore(this.shaderLanguage); + if (!options || (!options.removeAttributes && !options.removeUniforms && !options.removeVaryings && !options.removeIfDef && !options.replaceStrings)) { + if (options && options.repeatKey) { + this.functions[key] = `#include<${includeName}>${options.substitutionVars ? "(" + options.substitutionVars + ")" : ""}[0..${options.repeatKey}]\n`; + } + else { + this.functions[key] = `#include<${includeName}>${options?.substitutionVars ? "(" + options?.substitutionVars + ")" : ""}\n`; + } + if (this.sharedData.emitComments) { + this.functions[key] = comments + `\n` + this.functions[key]; + } + return; + } + this.functions[key] = store[includeName]; + if (this.sharedData.emitComments) { + this.functions[key] = comments + `\n` + this.functions[key]; + } + if (options.removeIfDef) { + this.functions[key] = this.functions[key].replace(/^\s*?#ifdef.+$/gm, ""); + this.functions[key] = this.functions[key].replace(/^\s*?#endif.*$/gm, ""); + this.functions[key] = this.functions[key].replace(/^\s*?#else.*$/gm, ""); + this.functions[key] = this.functions[key].replace(/^\s*?#elif.*$/gm, ""); + } + if (options.removeAttributes) { + this.functions[key] = this.functions[key].replace(/\s*?attribute .+?;/g, "\n"); + } + if (options.removeUniforms) { + this.functions[key] = this.functions[key].replace(/\s*?uniform .*?;/g, "\n"); + } + if (options.removeVaryings) { + this.functions[key] = this.functions[key].replace(/\s*?(varying|in) .+?;/g, "\n"); + } + if (options.replaceStrings) { + for (let index = 0; index < options.replaceStrings.length; index++) { + const replaceString = options.replaceStrings[index]; + this.functions[key] = this.functions[key].replace(replaceString.search, replaceString.replace); + } + } + } + /** + * @internal + */ + _registerTempVariable(name) { + if (this.sharedData.temps.indexOf(name) !== -1) { + return false; + } + this.sharedData.temps.push(name); + return true; + } + /** + * @internal + */ + _emitVaryingFromString(name, type, define = "", notDefine = false) { + if (this.sharedData.varyings.indexOf(name) !== -1) { + return false; + } + this.sharedData.varyings.push(name); + const shaderType = this._getShaderType(type); + const emitCode = (forFragment = false) => { + let code = ""; + if (define) { + if (define.startsWith("defined(")) { + code += `#if ${define}\n`; + } + else { + code += `${notDefine ? "#ifndef" : "#ifdef"} ${define}\n`; + } + } + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + switch (shaderType) { + case "mat4x4f": + // We can't pass a matrix as a varying in WGSL, so we need to split it into 4 vectors + code += `varying ${name}_r0: vec4f;\n`; + code += `varying ${name}_r1: vec4f;\n`; + code += `varying ${name}_r2: vec4f;\n`; + code += `varying ${name}_r3: vec4f;\n`; + if (forFragment) { + code += `var ${name}: mat4x4f;\n`; + this.sharedData.varyingInitializationsFragment += `${name} = mat4x4f(fragmentInputs.${name}_r0, fragmentInputs.${name}_r1, fragmentInputs.${name}_r2, fragmentInputs.${name}_r3);\n`; + } + break; + default: + code += `varying ${name}: ${shaderType};\n`; + break; + } + } + else { + code += `varying ${shaderType} ${name};\n`; + } + if (define) { + code += `#endif\n`; + } + return code; + }; + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + this.sharedData.varyingDeclaration += emitCode(false); + this.sharedData.varyingDeclarationFragment += emitCode(true); + } + else { + const code = emitCode(); + this.sharedData.varyingDeclaration += code; + this.sharedData.varyingDeclarationFragment += code; + } + return true; + } + /** + * @internal + */ + _getVaryingName(name) { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return (this.target !== NodeMaterialBlockTargets.Fragment ? "vertexOutputs." : "fragmentInputs.") + name; + } + return name; + } + /** + * @internal + */ + _emitUniformFromString(name, type, define = "", notDefine = false) { + if (this.uniforms.indexOf(name) !== -1) { + return; + } + this.uniforms.push(name); + if (define) { + if (define.startsWith("defined(")) { + this._uniformDeclaration += `#if ${define}\n`; + } + else { + this._uniformDeclaration += `${notDefine ? "#ifndef" : "#ifdef"} ${define}\n`; + } + } + const shaderType = this._getShaderType(type); + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + this._uniformDeclaration += `uniform ${name}: ${shaderType};\n`; + } + else { + this._uniformDeclaration += `uniform ${shaderType} ${name};\n`; + } + if (define) { + this._uniformDeclaration += `#endif\n`; + } + } + /** + * @internal + */ + _generateTernary(trueStatement, falseStatement, condition) { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return `select(${falseStatement}, ${trueStatement}, ${condition})`; + } + return `(${condition}) ? ${trueStatement} : ${falseStatement}`; + } + /** + * @internal + */ + _emitFloat(value) { + if (value.toString() === value.toFixed(0)) { + return `${value}.0`; + } + return value.toString(); + } + /** + * @internal + */ + _declareOutput(output, isConst) { + return this._declareLocalVar(output.associatedVariableName, output.type, isConst); + } + /** + * @internal + */ + _declareLocalVar(name, type, isConst) { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return `${isConst ? "const" : "var"} ${name}: ${this._getShaderType(type)}`; + } + else { + return `${this._getShaderType(type)} ${name}`; + } + } + /** + * @internal + */ + _samplerCubeFunc() { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return "textureSample"; + } + return "textureCube"; + } + /** + * @internal + */ + _samplerFunc() { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return "textureSample"; + } + return "texture2D"; + } + /** + * @internal + */ + _samplerLODFunc() { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return "textureSampleLevel"; + } + return "texture2DLodEXT"; + } + _toLinearSpace(output) { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + if (output.type === NodeMaterialBlockConnectionPointTypes.Color3 || output.type === NodeMaterialBlockConnectionPointTypes.Vector3) { + return `toLinearSpaceVec3(${output.associatedVariableName})`; + } + return `toLinearSpace(${output.associatedVariableName})`; + } + return `toLinearSpace(${output.associatedVariableName})`; + } + /** + * @internal + */ + _generateTextureSample(uv, samplerName) { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return `${this._samplerFunc()}(${samplerName},${samplerName + `Sampler`}, ${uv})`; + } + return `${this._samplerFunc()}(${samplerName}, ${uv})`; + } + /** + * @internal + */ + _generateTextureSampleLOD(uv, samplerName, lod) { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return `${this._samplerLODFunc()}(${samplerName},${samplerName + `Sampler`}, ${uv}, ${lod})`; + } + return `${this._samplerLODFunc()}(${samplerName}, ${uv}, ${lod})`; + } + /** + * @internal + */ + _generateTextureSampleCube(uv, samplerName) { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return `${this._samplerCubeFunc()}(${samplerName},${samplerName + `Sampler`}, ${uv})`; + } + return `${this._samplerCubeFunc()}(${samplerName}, ${uv})`; + } + /** + * @internal + */ + _generateTextureSampleCubeLOD(uv, samplerName, lod) { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return `${this._samplerCubeFunc()}(${samplerName},${samplerName + `Sampler`}, ${uv}, ${lod})`; + } + return `${this._samplerCubeFunc()}(${samplerName}, ${uv}, ${lod})`; + } + _convertVariableDeclarationToWGSL(type, dest, source) { + return source.replace(new RegExp(`(${type})\\s+(\\w+)`, "g"), `var $2: ${dest}`); + } + _convertVariableConstructorsToWGSL(type, dest, source) { + return source.replace(new RegExp(`(${type})\\(`, "g"), ` ${dest}(`); + } + _convertOutParametersToWGSL(source) { + return source.replace(new RegExp(`out\\s+var\\s+(\\w+)\\s*:\\s*(\\w+)`, "g"), `$1: ptr`); + } + _convertTernaryOperandsToWGSL(source) { + return source.replace(new RegExp(`\\[(.*?)\\?(.*?):(.*)\\]`, "g"), (match, condition, trueCase, falseCase) => `select(${falseCase}, ${trueCase}, ${condition})`); + } + _convertModOperatorsToWGSL(source) { + return source.replace(new RegExp(`mod\\((.+?),\\s*(.+?)\\)`, "g"), (match, left, right) => `((${left})%(${right}))`); + } + _convertConstToWGSL(source) { + return source.replace(new RegExp(`const var`, "g"), `const`); + } + _convertInnerFunctionsToWGSL(source) { + return source.replace(new RegExp(`inversesqrt`, "g"), `inverseSqrt`); + } + _convertFunctionsToWGSL(source) { + const regex = /var\s+(\w+)\s*:\s*(\w+)\((.*)\)/g; + let match; + while ((match = regex.exec(source)) !== null) { + const funcName = match[1]; + const funcType = match[2]; + const params = match[3]; // All parameters as a single string + // Processing the parameters to match 'name: type' format + const formattedParams = params.replace(/var\s/g, ""); + // Constructing the final output string + source = source.replace(match[0], `fn ${funcName}(${formattedParams}) -> ${funcType}`); + } + return source; + } + _babylonSLtoWGSL(code) { + // variable declarations + code = this._convertVariableDeclarationToWGSL("void", "voidnull", code); + code = this._convertVariableDeclarationToWGSL("bool", "bool", code); + code = this._convertVariableDeclarationToWGSL("int", "i32", code); + code = this._convertVariableDeclarationToWGSL("uint", "u32", code); + code = this._convertVariableDeclarationToWGSL("float", "f32", code); + code = this._convertVariableDeclarationToWGSL("vec2", "vec2f", code); + code = this._convertVariableDeclarationToWGSL("vec3", "vec3f", code); + code = this._convertVariableDeclarationToWGSL("vec4", "vec4f", code); + code = this._convertVariableDeclarationToWGSL("mat2", "mat2x2f", code); + code = this._convertVariableDeclarationToWGSL("mat3", "mat3x3f", code); + code = this._convertVariableDeclarationToWGSL("mat4", "mat4x4f", code); + // Type constructors + code = this._convertVariableConstructorsToWGSL("float", "f32", code); + code = this._convertVariableConstructorsToWGSL("vec2", "vec2f", code); + code = this._convertVariableConstructorsToWGSL("vec3", "vec3f", code); + code = this._convertVariableConstructorsToWGSL("vec4", "vec4f", code); + code = this._convertVariableConstructorsToWGSL("mat2", "mat2x2f", code); + code = this._convertVariableConstructorsToWGSL("mat3", "mat3x3f", code); + code = this._convertVariableConstructorsToWGSL("mat4", "mat4x4f", code); + // Ternary operands + code = this._convertTernaryOperandsToWGSL(code); + // Mod operators + code = this._convertModOperatorsToWGSL(code); + // Const + code = this._convertConstToWGSL(code); + // Inner functions + code = this._convertInnerFunctionsToWGSL(code); + // Out paramters + code = this._convertOutParametersToWGSL(code); + code = code.replace(/\[\*\]/g, "*"); + // Functions + code = this._convertFunctionsToWGSL(code); + // Remove voidnull + code = code.replace(/\s->\svoidnull/g, ""); + // Derivatives + code = code.replace(/dFdx/g, "dpdx"); + code = code.replace(/dFdy/g, "dpdy"); + return code; + } + _convertTernaryOperandsToGLSL(source) { + return source.replace(new RegExp(`\\[(.+?)\\?(.+?):(.+)\\]`, "g"), (match, condition, trueCase, falseCase) => `${condition} ? ${trueCase} : ${falseCase}`); + } + _babylonSLtoGLSL(code) { + /** Remove BSL specifics */ + code = code.replace(/\[\*\]/g, ""); + code = this._convertTernaryOperandsToGLSL(code); + return code; + } +} + +/** + * Class used to store shared data between 2 NodeMaterialBuildState + */ +class NodeMaterialBuildStateSharedData { + /** Creates a new shared data */ + constructor() { + /** + * Gets the list of emitted varyings + */ + this.temps = []; + /** + * Gets the list of emitted varyings + */ + this.varyings = []; + /** + * Gets the varying declaration string (for vertex shader) + */ + this.varyingDeclaration = ""; + /** + * Gets the varying declaration string (for fragment shader) + * This is potentially different from varyingDeclaration only in WebGPU + */ + this.varyingDeclarationFragment = ""; + /** + * Gets the varying initialization string (for fragment shader) + * Only used in WebGPU, to reconstruct the varying values from the vertex shader if their types is mat4x4f + */ + this.varyingInitializationsFragment = ""; + /** + * Input blocks + */ + this.inputBlocks = []; + /** + * Input blocks + */ + this.textureBlocks = []; + /** + * Bindable blocks (Blocks that need to set data to the effect) + */ + this.bindableBlocks = []; + /** + * Bindable blocks (Blocks that need to set data to the effect) that will always be called (by bindForSubMesh), contrary to bindableBlocks that won't be called if _mustRebind() returns false + */ + this.forcedBindableBlocks = []; + /** + * List of blocks that can provide a compilation fallback + */ + this.blocksWithFallbacks = []; + /** + * List of blocks that can provide a define update + */ + this.blocksWithDefines = []; + /** + * List of blocks that can provide a repeatable content + */ + this.repeatableContentBlocks = []; + /** + * List of blocks that can provide a dynamic list of uniforms + */ + this.dynamicUniformBlocks = []; + /** + * List of blocks that can block the isReady function for the material + */ + this.blockingBlocks = []; + /** + * Gets the list of animated inputs + */ + this.animatedInputs = []; + /** List of emitted variables */ + this.variableNames = {}; + /** List of emitted defines */ + this.defineNames = {}; + /** + * Gets the compilation hints emitted at compilation time + */ + this.hints = { + needWorldViewMatrix: false, + needWorldViewProjectionMatrix: false, + needAlphaBlending: false, + needAlphaTesting: false, + }; + /** + * List of compilation checks + */ + this.checks = { + emitVertex: false, + emitFragment: false, + notConnectedNonOptionalInputs: new Array(), + }; + /** + * Is vertex program allowed to be empty? + */ + this.allowEmptyVertexProgram = false; + // Exclude usual attributes from free variable names + this.variableNames["position"] = 0; + this.variableNames["normal"] = 0; + this.variableNames["tangent"] = 0; + this.variableNames["uv"] = 0; + this.variableNames["uv2"] = 0; + this.variableNames["uv3"] = 0; + this.variableNames["uv4"] = 0; + this.variableNames["uv5"] = 0; + this.variableNames["uv6"] = 0; + this.variableNames["color"] = 0; + this.variableNames["matricesIndices"] = 0; + this.variableNames["matricesWeights"] = 0; + this.variableNames["matricesIndicesExtra"] = 0; + this.variableNames["matricesWeightsExtra"] = 0; + this.variableNames["diffuseBase"] = 0; + this.variableNames["specularBase"] = 0; + this.variableNames["worldPos"] = 0; + this.variableNames["shadow"] = 0; + this.variableNames["view"] = 0; + // Exclude known varyings + this.variableNames["vTBN"] = 0; + // Exclude defines + this.defineNames["MAINUV0"] = 0; + this.defineNames["MAINUV1"] = 0; + this.defineNames["MAINUV2"] = 0; + this.defineNames["MAINUV3"] = 0; + this.defineNames["MAINUV4"] = 0; + this.defineNames["MAINUV5"] = 0; + this.defineNames["MAINUV6"] = 0; + this.defineNames["MAINUV7"] = 0; + } + /** + * Emits console errors and exceptions if there is a failing check + * @param errorObservable defines an Observable to send the error message + * @returns true if all checks pass + */ + emitErrors(errorObservable = null) { + let errorMessage = ""; + if (!this.checks.emitVertex && !this.allowEmptyVertexProgram) { + errorMessage += "NodeMaterial does not have a vertex output. You need to at least add a block that generates a position value.\n"; + } + if (!this.checks.emitFragment) { + errorMessage += "NodeMaterial does not have a fragment output. You need to at least add a block that generates a color value.\n"; + } + for (const notConnectedInput of this.checks.notConnectedNonOptionalInputs) { + errorMessage += `input ${notConnectedInput.name} from block ${notConnectedInput.ownerBlock.name}[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional.\n`; + } + if (errorMessage) { + if (errorObservable) { + errorObservable.notifyObservers(errorMessage); + } + Logger.Error("Build of NodeMaterial failed:\n" + errorMessage); + return false; + } + return true; + } +} + +/** + * Enum used to define the compatibility state between two connection points + */ +var NodeMaterialConnectionPointCompatibilityStates; +(function (NodeMaterialConnectionPointCompatibilityStates) { + /** Points are compatibles */ + NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["Compatible"] = 0] = "Compatible"; + /** Points are incompatible because of their types */ + NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["TypeIncompatible"] = 1] = "TypeIncompatible"; + /** Points are incompatible because of their targets (vertex vs fragment) */ + NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["TargetIncompatible"] = 2] = "TargetIncompatible"; + /** Points are incompatible because they are in the same hierarchy **/ + NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["HierarchyIssue"] = 3] = "HierarchyIssue"; +})(NodeMaterialConnectionPointCompatibilityStates || (NodeMaterialConnectionPointCompatibilityStates = {})); +/** + * Defines the direction of a connection point + */ +var NodeMaterialConnectionPointDirection; +(function (NodeMaterialConnectionPointDirection) { + /** Input */ + NodeMaterialConnectionPointDirection[NodeMaterialConnectionPointDirection["Input"] = 0] = "Input"; + /** Output */ + NodeMaterialConnectionPointDirection[NodeMaterialConnectionPointDirection["Output"] = 1] = "Output"; +})(NodeMaterialConnectionPointDirection || (NodeMaterialConnectionPointDirection = {})); +/** + * Defines a connection point for a block + */ +class NodeMaterialConnectionPoint { + /** + * Checks if two types are equivalent + * @param type1 type 1 to check + * @param type2 type 2 to check + * @returns true if both types are equivalent, else false + */ + static AreEquivalentTypes(type1, type2) { + switch (type1) { + case NodeMaterialBlockConnectionPointTypes.Vector3: { + if (type2 === NodeMaterialBlockConnectionPointTypes.Color3) { + return true; + } + break; + } + case NodeMaterialBlockConnectionPointTypes.Vector4: { + if (type2 === NodeMaterialBlockConnectionPointTypes.Color4) { + return true; + } + break; + } + case NodeMaterialBlockConnectionPointTypes.Color3: { + if (type2 === NodeMaterialBlockConnectionPointTypes.Vector3) { + return true; + } + break; + } + case NodeMaterialBlockConnectionPointTypes.Color4: { + if (type2 === NodeMaterialBlockConnectionPointTypes.Vector4) { + return true; + } + break; + } + } + return false; + } + get _connectedPoint() { + return this._connectedPointBackingField; + } + set _connectedPoint(value) { + if (this._connectedPointBackingField === value) { + return; + } + this._connectedPointTypeChangedObserver?.remove(); + this._updateTypeDependentState(() => (this._connectedPointBackingField = value)); + if (this._connectedPointBackingField) { + this._connectedPointTypeChangedObserver = this._connectedPointBackingField.onTypeChangedObservable.add(() => { + this._notifyTypeChanged(); + }); + } + } + /** @internal */ + get _typeConnectionSource() { + return this._typeConnectionSourceBackingField; + } + /** @internal */ + set _typeConnectionSource(value) { + if (this._typeConnectionSourceBackingField === value) { + return; + } + this._typeConnectionSourceTypeChangedObserver?.remove(); + this._updateTypeDependentState(() => (this._typeConnectionSourceBackingField = value)); + if (this._typeConnectionSourceBackingField) { + this._typeConnectionSourceTypeChangedObserver = this._typeConnectionSourceBackingField.onTypeChangedObservable.add(() => { + this._notifyTypeChanged(); + }); + } + } + /** @internal */ + get _defaultConnectionPointType() { + return this._defaultConnectionPointTypeBackingField; + } + /** @internal */ + set _defaultConnectionPointType(value) { + this._updateTypeDependentState(() => (this._defaultConnectionPointTypeBackingField = value)); + } + /** @internal */ + get _linkedConnectionSource() { + return this._linkedConnectionSourceBackingField; + } + /** @internal */ + set _linkedConnectionSource(value) { + if (this._linkedConnectionSourceBackingField === value) { + return; + } + this._linkedConnectionSourceTypeChangedObserver?.remove(); + this._updateTypeDependentState(() => (this._linkedConnectionSourceBackingField = value)); + this._isMainLinkSource = false; + if (this._linkedConnectionSourceBackingField) { + this._linkedConnectionSourceTypeChangedObserver = this._linkedConnectionSourceBackingField.onTypeChangedObservable.add(() => { + this._notifyTypeChanged(); + }); + } + } + /** Gets the direction of the point */ + get direction() { + return this._direction; + } + /** + * Gets the declaration variable name in the shader + */ + get declarationVariableName() { + if (this._ownerBlock.isInput) { + return this._ownerBlock.declarationVariableName; + } + if ((!this._enforceAssociatedVariableName || !this._associatedVariableName) && this._connectedPoint) { + return this._connectedPoint.declarationVariableName; + } + return this._associatedVariableName; + } + /** + * Gets or sets the associated variable name in the shader + */ + get associatedVariableName() { + if (this._ownerBlock.isInput) { + return this._ownerBlock.associatedVariableName; + } + if ((!this._enforceAssociatedVariableName || !this._associatedVariableName) && this._connectedPoint) { + return this._connectedPoint.associatedVariableName; + } + return this._associatedVariableName; + } + set associatedVariableName(value) { + this._associatedVariableName = value; + } + /** Get the inner type (ie AutoDetect for instance instead of the inferred one) */ + get innerType() { + if (this._linkedConnectionSource && !this._isMainLinkSource && this._linkedConnectionSource.isConnected) { + return this.type; + } + return this._type; + } + /** + * Gets or sets the connection point type (default is float) + */ + get type() { + if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) { + if (this._ownerBlock.isInput) { + return this._ownerBlock.type; + } + if (this._connectedPoint) { + return this._connectedPoint.type; + } + if (this._linkedConnectionSource) { + if (this._linkedConnectionSource.isConnected) { + if (this._linkedConnectionSource.connectedPoint._redirectedSource && this._linkedConnectionSource.connectedPoint._redirectedSource.isConnected) { + return this._linkedConnectionSource.connectedPoint._redirectedSource.type; + } + return this._linkedConnectionSource.type; + } + if (this._linkedConnectionSource._defaultConnectionPointType) { + return this._linkedConnectionSource._defaultConnectionPointType; + } + } + if (this._defaultConnectionPointType) { + return this._defaultConnectionPointType; + } + } + if (this._type === NodeMaterialBlockConnectionPointTypes.BasedOnInput) { + if (this._typeConnectionSource) { + if (!this._typeConnectionSource.isConnected && this._defaultConnectionPointType) { + return this._defaultConnectionPointType; + } + return this._typeConnectionSource.type; + } + else if (this._defaultConnectionPointType) { + return this._defaultConnectionPointType; + } + } + return this._type; + } + set type(value) { + this._updateTypeDependentState(() => (this._type = value)); + } + /** Gets or sets the target of that connection point */ + get target() { + if (!this._prioritizeVertex || !this._ownerBlock) { + return this._target; + } + if (this._target !== NodeMaterialBlockTargets.VertexAndFragment) { + return this._target; + } + if (this._ownerBlock.target === NodeMaterialBlockTargets.Fragment) { + return NodeMaterialBlockTargets.Fragment; + } + return NodeMaterialBlockTargets.Vertex; + } + set target(value) { + this._target = value; + } + /** + * Gets a boolean indicating that the current point is connected to another NodeMaterialBlock + */ + get isConnected() { + return this.connectedPoint !== null || this.hasEndpoints; + } + /** + * Gets a boolean indicating that the current point is connected to an input block + */ + get isConnectedToInputBlock() { + return this.connectedPoint !== null && this.connectedPoint.ownerBlock.isInput; + } + /** + * Gets a the connected input block (if any) + */ + get connectInputBlock() { + if (!this.isConnectedToInputBlock) { + return null; + } + return this.connectedPoint.ownerBlock; + } + /** Get the other side of the connection (if any) */ + get connectedPoint() { + return this._connectedPoint; + } + /** Get the block that owns this connection point */ + get ownerBlock() { + return this._ownerBlock; + } + /** Get the block connected on the other side of this connection (if any) */ + get sourceBlock() { + if (!this._connectedPoint) { + return null; + } + return this._connectedPoint.ownerBlock; + } + /** Get the block connected on the endpoints of this connection (if any) */ + get connectedBlocks() { + if (this._endpoints.length === 0) { + return []; + } + return this._endpoints.map((e) => e.ownerBlock); + } + /** Gets the list of connected endpoints */ + get endpoints() { + return this._endpoints; + } + /** Gets a boolean indicating if that output point is connected to at least one input */ + get hasEndpoints() { + return this._endpoints && this._endpoints.length > 0; + } + /** Gets a boolean indicating that this connection has a path to the vertex output*/ + get isDirectlyConnectedToVertexOutput() { + if (!this.hasEndpoints) { + return false; + } + for (const endpoint of this._endpoints) { + if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Vertex) { + return true; + } + if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) { + if (endpoint.ownerBlock.outputs.some((o) => o.isDirectlyConnectedToVertexOutput)) { + return true; + } + } + } + return false; + } + /** Gets a boolean indicating that this connection will be used in the vertex shader */ + get isConnectedInVertexShader() { + if (this.target === NodeMaterialBlockTargets.Vertex) { + return true; + } + if (!this.hasEndpoints) { + return false; + } + for (const endpoint of this._endpoints) { + if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Vertex) { + return true; + } + if (endpoint.target === NodeMaterialBlockTargets.Vertex) { + return true; + } + if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) { + if (endpoint.ownerBlock.outputs.some((o) => o.isConnectedInVertexShader)) { + return true; + } + } + } + return false; + } + /** Gets a boolean indicating that this connection will be used in the fragment shader */ + get isConnectedInFragmentShader() { + if (this.target === NodeMaterialBlockTargets.Fragment) { + return true; + } + if (!this.hasEndpoints) { + return false; + } + for (const endpoint of this._endpoints) { + if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { + return true; + } + if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) { + if (endpoint.ownerBlock.isConnectedInFragmentShader()) { + return true; + } + } + } + return false; + } + /** + * Creates a block suitable to be used as an input for this input point. + * If null is returned, a block based on the point type will be created. + * @returns The returned string parameter is the name of the output point of NodeMaterialBlock (first parameter of the returned array) that can be connected to the input + */ + createCustomInputBlock() { + return null; + } + /** + * Creates a new connection point + * @param name defines the connection point name + * @param ownerBlock defines the block hosting this connection point + * @param direction defines the direction of the connection point + */ + constructor(name, ownerBlock, direction) { + /** @internal */ + this._preventBubbleUp = false; + this._connectedPointBackingField = null; + this._endpoints = new Array(); + /** @internal */ + this._redirectedSource = null; + this._typeConnectionSourceBackingField = null; + this._defaultConnectionPointTypeBackingField = null; + /** @internal */ + this._isMainLinkSource = false; + this._linkedConnectionSourceBackingField = null; + /** @internal */ + this._acceptedConnectionPointType = null; + this._type = NodeMaterialBlockConnectionPointTypes.Float; + /** @internal */ + this._enforceAssociatedVariableName = false; + /** @internal */ + this._forPostBuild = false; + /** Indicates that this connection point needs dual validation before being connected to another point */ + this.needDualDirectionValidation = false; + /** + * Gets or sets the additional types supported by this connection point + */ + this.acceptedConnectionPointTypes = []; + /** + * Gets or sets the additional types excluded by this connection point + */ + this.excludedConnectionPointTypes = []; + /** + * Observable triggered when this point is connected + */ + this.onConnectionObservable = new Observable(); + /** + * Observable triggered when this point is disconnected + */ + this.onDisconnectionObservable = new Observable(); + /** + * Observable triggered when the type of the connection point is changed + */ + this.onTypeChangedObservable = new Observable(); + this._isTypeChangeObservableNotifying = false; + /** + * Gets or sets a boolean indicating that this connection point is exposed on a frame + */ + this.isExposedOnFrame = false; + /** + * Gets or sets number indicating the position that the port is exposed to on a frame + */ + this.exposedPortPosition = -1; + /** @internal */ + this._prioritizeVertex = false; + this._target = NodeMaterialBlockTargets.VertexAndFragment; + this._ownerBlock = ownerBlock; + this.name = name; + this._direction = direction; + } + /** + * Gets the current class name e.g. "NodeMaterialConnectionPoint" + * @returns the class name + */ + getClassName() { + return "NodeMaterialConnectionPoint"; + } + /** + * Gets a boolean indicating if the current point can be connected to another point + * @param connectionPoint defines the other connection point + * @returns a boolean + */ + canConnectTo(connectionPoint) { + return this.checkCompatibilityState(connectionPoint) === 0 /* NodeMaterialConnectionPointCompatibilityStates.Compatible */; + } + /** + * Gets a number indicating if the current point can be connected to another point + * @param connectionPoint defines the other connection point + * @returns a number defining the compatibility state + */ + checkCompatibilityState(connectionPoint) { + const ownerBlock = this._ownerBlock; + const otherBlock = connectionPoint.ownerBlock; + if (ownerBlock.target === NodeMaterialBlockTargets.Fragment) { + // Let's check we are not going reverse + if (otherBlock.target === NodeMaterialBlockTargets.Vertex) { + return 2 /* NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible */; + } + for (const output of otherBlock.outputs) { + if (output.ownerBlock.target != NodeMaterialBlockTargets.Neutral && output.isConnectedInVertexShader) { + return 2 /* NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible */; + } + } + } + if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeMaterialBlockConnectionPointTypes.AutoDetect) { + // Equivalents + if (NodeMaterialConnectionPoint.AreEquivalentTypes(this.type, connectionPoint.type)) { + return 0 /* NodeMaterialConnectionPointCompatibilityStates.Compatible */; + } + // Accepted types + if ((connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) || + (connectionPoint._acceptedConnectionPointType && NodeMaterialConnectionPoint.AreEquivalentTypes(connectionPoint._acceptedConnectionPointType.type, this.type))) { + return 0 /* NodeMaterialConnectionPointCompatibilityStates.Compatible */; + } + else { + return 1 /* NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible */; + } + } + // Excluded + if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) { + return 1 /* NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible */; + } + // Check hierarchy + let targetBlock = otherBlock; + let sourceBlock = ownerBlock; + if (this.direction === 0 /* NodeMaterialConnectionPointDirection.Input */) { + targetBlock = ownerBlock; + sourceBlock = otherBlock; + } + if (targetBlock.isAnAncestorOf(sourceBlock)) { + return 3 /* NodeMaterialConnectionPointCompatibilityStates.HierarchyIssue */; + } + return 0 /* NodeMaterialConnectionPointCompatibilityStates.Compatible */; + } + /** + * Connect this point to another connection point + * @param connectionPoint defines the other connection point + * @param ignoreConstraints defines if the system will ignore connection type constraints (default is false) + * @returns the current connection point + */ + connectTo(connectionPoint, ignoreConstraints = false) { + if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) { + // eslint-disable-next-line no-throw-literal + throw "Cannot connect these two connectors."; + } + this._endpoints.push(connectionPoint); + connectionPoint._connectedPoint = this; + this._enforceAssociatedVariableName = false; + this.onConnectionObservable.notifyObservers(connectionPoint); + connectionPoint.onConnectionObservable.notifyObservers(this); + return this; + } + /** + * Disconnect this point from one of his endpoint + * @param endpoint defines the other connection point + * @returns the current connection point + */ + disconnectFrom(endpoint) { + const index = this._endpoints.indexOf(endpoint); + if (index === -1) { + return this; + } + this._endpoints.splice(index, 1); + endpoint._connectedPoint = null; + this._enforceAssociatedVariableName = false; + endpoint._enforceAssociatedVariableName = false; + this.onDisconnectionObservable.notifyObservers(endpoint); + endpoint.onDisconnectionObservable.notifyObservers(this); + return this; + } + /** + * Fill the list of excluded connection point types with all types other than those passed in the parameter + * @param mask Types (ORed values of NodeMaterialBlockConnectionPointTypes) that are allowed, and thus will not be pushed to the excluded list + */ + addExcludedConnectionPointFromAllowedTypes(mask) { + let bitmask = 1; + while (bitmask < NodeMaterialBlockConnectionPointTypes.All) { + if (!(mask & bitmask)) { + this.excludedConnectionPointTypes.push(bitmask); + } + bitmask = bitmask << 1; + } + } + /** + * Serializes this point in a JSON representation + * @param isInput defines if the connection point is an input (default is true) + * @returns the serialized point object + */ + serialize(isInput = true) { + const serializationObject = {}; + serializationObject.name = this.name; + if (this.displayName) { + serializationObject.displayName = this.displayName; + } + if (isInput && this.connectedPoint) { + serializationObject.inputName = this.name; + serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId; + serializationObject.targetConnectionName = this.connectedPoint.name; + serializationObject.isExposedOnFrame = true; + serializationObject.exposedPortPosition = this.exposedPortPosition; + } + if (this.isExposedOnFrame || this.exposedPortPosition >= 0) { + serializationObject.isExposedOnFrame = true; + serializationObject.exposedPortPosition = this.exposedPortPosition; + } + return serializationObject; + } + /** + * Release resources + */ + dispose() { + this.onConnectionObservable.clear(); + this.onDisconnectionObservable.clear(); + this.onTypeChangedObservable.clear(); + this._connectedPoint = null; + this._typeConnectionSource = null; + this._linkedConnectionSource = null; + } + _updateTypeDependentState(update) { + const previousType = this.type; + update(); + if (this.type !== previousType) { + this._notifyTypeChanged(); + } + } + _notifyTypeChanged() { + // Disallow re-entrancy + if (this._isTypeChangeObservableNotifying) { + return; + } + this._isTypeChangeObservableNotifying = true; + this.onTypeChangedObservable.notifyObservers(this.type); + this._isTypeChangeObservableNotifying = false; + } +} + +/** + * Defines a block that can be used inside a node based material + */ +class NodeMaterialBlock { + /** @internal */ + get _isFinalOutputAndActive() { + return this._isFinalOutput; + } + /** @internal */ + get _hasPrecedence() { + return false; + } + /** + * Gets the name of the block + */ + get name() { + return this._name; + } + /** + * Gets a boolean indicating that this block has is code ready to be used + */ + get codeIsReady() { + return this._codeIsReady; + } + /** + * Sets the name of the block. Will check if the name is valid. + */ + set name(newName) { + if (!this.validateBlockName(newName)) { + return; + } + this._name = newName; + } + /** + * Gets a boolean indicating that this block can only be used once per NodeMaterial + */ + get isUnique() { + return this._isUnique; + } + /** + * Gets a boolean indicating that this block is an end block (e.g. it is generating a system value) + */ + get isFinalMerger() { + return this._isFinalMerger; + } + /** + * Gets a boolean indicating that this block is an input (e.g. it sends data to the shader) + */ + get isInput() { + return this._isInput; + } + /** + * Gets a boolean indicating if this block is a teleport out + */ + get isTeleportOut() { + return this._isTeleportOut; + } + /** + * Gets a boolean indicating if this block is a teleport in + */ + get isTeleportIn() { + return this._isTeleportIn; + } + /** + * Gets a boolean indicating if this block is a loop + */ + get isLoop() { + return this._isLoop; + } + /** + * Gets or sets the build Id + */ + get buildId() { + return this._buildId; + } + set buildId(value) { + this._buildId = value; + } + /** + * Gets or sets the target of the block + */ + get target() { + return this._target; + } + set target(value) { + if ((this._target & value) !== 0) { + return; + } + this._target = value; + } + /** + * Gets the list of input points + */ + get inputs() { + return this._inputs; + } + /** Gets the list of output points */ + get outputs() { + return this._outputs; + } + /** + * Find an input by its name + * @param name defines the name of the input to look for + * @returns the input or null if not found + */ + getInputByName(name) { + const filter = this._inputs.filter((e) => e.name === name); + if (filter.length) { + return filter[0]; + } + return null; + } + /** + * Find an output by its name + * @param name defines the name of the output to look for + * @returns the output or null if not found + */ + getOutputByName(name) { + const filter = this._outputs.filter((e) => e.name === name); + if (filter.length) { + return filter[0]; + } + return null; + } + /** + * Creates a new NodeMaterialBlock + * @param name defines the block name + * @param target defines the target of that block (Vertex by default) + * @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false + * @param isFinalOutput defines a boolean indicating that this block is generating a final output and no other block should be generated after + */ + constructor(name, target = NodeMaterialBlockTargets.Vertex, isFinalMerger = false, isFinalOutput = false) { + this._isFinalMerger = false; + this._isInput = false; + this._isLoop = false; + this._isTeleportOut = false; + this._isTeleportIn = false; + this._name = ""; + this._isUnique = false; + this._codeIsReady = true; + /** @internal */ + this._isFinalOutput = false; + /** + * Observable raised when the block code is ready (if the code loading is async) + */ + this.onCodeIsReadyObservable = new Observable(); + /** Gets or sets a boolean indicating that only one input can be connected at a time */ + this.inputsAreExclusive = false; + /** @internal */ + this._codeVariableName = ""; + /** @internal */ + this._inputs = new Array(); + /** @internal */ + this._outputs = new Array(); + /** + * Gets or sets the comments associated with this block + */ + this.comments = ""; + /** Gets or sets a boolean indicating that this input can be edited in the Inspector (false by default) */ + this.visibleInInspector = false; + /** Gets or sets a boolean indicating that this input can be edited from a collapsed frame */ + this.visibleOnFrame = false; + this._target = target; + this._originalTargetIsNeutral = target === NodeMaterialBlockTargets.Neutral; + this._isFinalMerger = isFinalMerger; + this._isFinalOutput = isFinalOutput; + switch (this.getClassName()) { + case "InputBlock": + this._isInput = true; + break; + case "NodeMaterialTeleportOutBlock": + this._isTeleportOut = true; + break; + case "NodeMaterialTeleportInBlock": + this._isTeleportIn = true; + break; + case "LoopBlock": + this._isLoop = true; + break; + } + this._name = name; + this.uniqueId = UniqueIdGenerator.UniqueId; + } + /** @internal */ + _setInitialTarget(target) { + this._target = target; + this._originalTargetIsNeutral = target === NodeMaterialBlockTargets.Neutral; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + initialize(state) { + // Do nothing + } + /** + * Bind data to effect. Will only be called for blocks with isBindable === true + * @param effect defines the effect to bind data to + * @param nodeMaterial defines the hosting NodeMaterial + * @param mesh defines the mesh that will be rendered + * @param subMesh defines the submesh that will be rendered + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + bind(effect, nodeMaterial, mesh, subMesh) { + // Do nothing + } + _writeVariable(currentPoint) { + const connectionPoint = currentPoint.connectedPoint; + if (connectionPoint) { + return `${currentPoint.associatedVariableName}`; + } + return `0.`; + } + _writeFloat(value) { + let stringVersion = value.toString(); + if (stringVersion.indexOf(".") === -1) { + stringVersion += ".0"; + } + return `${stringVersion}`; + } + /** + * Gets the current class name e.g. "NodeMaterialBlock" + * @returns the class name + */ + getClassName() { + return "NodeMaterialBlock"; + } + /** Gets a boolean indicating that this connection will be used in the fragment shader + * @returns true if connected in fragment shader + */ + isConnectedInFragmentShader() { + return this.outputs.some((o) => o.isConnectedInFragmentShader); + } + /** + * Register a new input. Must be called inside a block constructor + * @param name defines the connection point name + * @param type defines the connection point type + * @param isOptional defines a boolean indicating that this input can be omitted + * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default) + * @param point an already created connection point. If not provided, create a new one + * @returns the current block + */ + registerInput(name, type, isOptional = false, target, point) { + point = point ?? new NodeMaterialConnectionPoint(name, this, 0 /* NodeMaterialConnectionPointDirection.Input */); + point.type = type; + point.isOptional = isOptional; + if (target) { + point.target = target; + } + this._inputs.push(point); + return this; + } + /** + * Register a new output. Must be called inside a block constructor + * @param name defines the connection point name + * @param type defines the connection point type + * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default) + * @param point an already created connection point. If not provided, create a new one + * @returns the current block + */ + registerOutput(name, type, target, point) { + point = point ?? new NodeMaterialConnectionPoint(name, this, 1 /* NodeMaterialConnectionPointDirection.Output */); + point.type = type; + if (target) { + point.target = target; + } + this._outputs.push(point); + return this; + } + /** + * Will return the first available input e.g. the first one which is not an uniform or an attribute + * @param forOutput defines an optional connection point to check compatibility with + * @returns the first available input or null + */ + getFirstAvailableInput(forOutput = null) { + for (const input of this._inputs) { + if (!input.connectedPoint) { + if (!forOutput || + forOutput.type === input.type || + input.type === NodeMaterialBlockConnectionPointTypes.AutoDetect || + input.acceptedConnectionPointTypes.indexOf(forOutput.type) !== -1) { + return input; + } + } + } + return null; + } + /** + * Will return the first available output e.g. the first one which is not yet connected and not a varying + * @param forBlock defines an optional block to check compatibility with + * @returns the first available input or null + */ + getFirstAvailableOutput(forBlock = null) { + for (const output of this._outputs) { + if (!forBlock || !forBlock.target || forBlock.target === NodeMaterialBlockTargets.Neutral || (forBlock.target & output.target) !== 0) { + return output; + } + } + return null; + } + /** + * Gets the sibling of the given output + * @param current defines the current output + * @returns the next output in the list or null + */ + getSiblingOutput(current) { + const index = this._outputs.indexOf(current); + if (index === -1 || index >= this._outputs.length) { + return null; + } + return this._outputs[index + 1]; + } + /** + * Checks if the current block is an ancestor of a given block + * @param block defines the potential descendant block to check + * @returns true if block is a descendant + */ + isAnAncestorOf(block) { + for (const output of this._outputs) { + if (!output.hasEndpoints) { + continue; + } + for (const endpoint of output.endpoints) { + if (endpoint.ownerBlock === block) { + return true; + } + if (endpoint.ownerBlock.isAnAncestorOf(block)) { + return true; + } + } + } + return false; + } + /** + * Connect current block with another block + * @param other defines the block to connect with + * @param options define the various options to help pick the right connections + * @param options.input + * @param options.output + * @param options.outputSwizzle + * @returns the current block + */ + connectTo(other, options) { + if (this._outputs.length === 0) { + return; + } + let output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other); + let notFound = true; + while (notFound) { + const input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output); + if (output && input && output.canConnectTo(input)) { + output.connectTo(input); + notFound = false; + } + else if (!output) { + // eslint-disable-next-line no-throw-literal + throw "Unable to find a compatible match"; + } + else { + output = this.getSiblingOutput(output); + } + } + return this; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _buildBlock(state) { + // Empty. Must be defined by child nodes + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _postBuildBlock(state) { + // Empty. Must be defined by child nodes + } + /** + * Add uniforms, samplers and uniform buffers at compilation time + * @param state defines the state to update + * @param nodeMaterial defines the node material requesting the update + * @param defines defines the material defines to update + * @param uniformBuffers defines the list of uniform buffer names + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) { + // Do nothing + } + /** + * Add potential fallbacks if shader compilation fails + * @param mesh defines the mesh to be rendered + * @param fallbacks defines the current prioritized list of fallbacks + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + provideFallbacks(mesh, fallbacks) { + // Do nothing + } + /** + * Initialize defines for shader compilation + * @param mesh defines the mesh to be rendered + * @param nodeMaterial defines the node material requesting the update + * @param defines defines the material defines to update + * @param useInstances specifies that instances should be used + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + initializeDefines(mesh, nodeMaterial, defines, useInstances = false) { } + /** + * Update defines for shader compilation + * @param mesh defines the mesh to be rendered + * @param nodeMaterial defines the node material requesting the update + * @param defines defines the material defines to update + * @param useInstances specifies that instances should be used + * @param subMesh defines which submesh to render + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + prepareDefines(mesh, nodeMaterial, defines, useInstances = false, subMesh) { + // Do nothing + } + /** + * Lets the block try to connect some inputs automatically + * @param material defines the hosting NodeMaterial + * @param additionalFilteringInfo optional additional filtering condition when looking for compatible blocks + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + autoConfigure(material, additionalFilteringInfo = () => true) { + // Do nothing + } + /** + * Function called when a block is declared as repeatable content generator + * @param vertexShaderState defines the current compilation state for the vertex shader + * @param fragmentShaderState defines the current compilation state for the fragment shader + * @param mesh defines the mesh to be rendered + * @param defines defines the material defines to update + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + replaceRepeatableContent(vertexShaderState, fragmentShaderState, mesh, defines) { + // Do nothing + } + /** Gets a boolean indicating that the code of this block will be promoted to vertex shader even if connected to fragment output */ + get willBeGeneratedIntoVertexShaderFromFragmentShader() { + if (this.isInput || this.isFinalMerger) { + return false; + } + if (this._outputs.some((o) => o.isDirectlyConnectedToVertexOutput)) { + return false; + } + if (this.target === NodeMaterialBlockTargets.Vertex) { + return false; + } + if (this.target === NodeMaterialBlockTargets.VertexAndFragment || this.target === NodeMaterialBlockTargets.Neutral) { + if (this._outputs.some((o) => o.isConnectedInVertexShader)) { + return true; + } + } + return false; + } + /** + * Checks if the block is ready + * @param mesh defines the mesh to be rendered + * @param nodeMaterial defines the node material requesting the update + * @param defines defines the material defines to update + * @param useInstances specifies that instances should be used + * @returns true if the block is ready + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + isReady(mesh, nodeMaterial, defines, useInstances = false) { + return true; + } + _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) { + if (looseCoupling) { + this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0]; + } + else { + this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1]; + this._inputs[inputIndex0]._isMainLinkSource = true; + } + this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0]; + } + _processBuild(block, state, input, activeBlocks) { + block.build(state, activeBlocks); + const localBlockIsFragment = state._vertexState != null; + const otherBlockWasGeneratedInVertexShader = block._buildTarget === NodeMaterialBlockTargets.Vertex && block.target !== NodeMaterialBlockTargets.VertexAndFragment; + if (localBlockIsFragment && + ((block.target & block._buildTarget) === 0 || + (block.target & input.target) === 0 || + (this.target !== NodeMaterialBlockTargets.VertexAndFragment && otherBlockWasGeneratedInVertexShader))) { + // context switch! We need a varying + if ((!block.isInput && state.target !== block._buildTarget) || // block was already emitted by vertex shader + (block.isInput && block.isAttribute && !block._noContextSwitch) // block is an attribute + ) { + const connectedPoint = input.connectedPoint; + if (state._vertexState._emitVaryingFromString("v_" + connectedPoint.declarationVariableName, connectedPoint.type)) { + const prefix = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "vertexOutputs." : ""; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ && connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Matrix) { + // We can't pass a matrix as a varying in WGSL, so we need to split it into 4 vectors + state._vertexState.compilationString += `${prefix}${"v_" + connectedPoint.declarationVariableName}_r0 = ${connectedPoint.associatedVariableName}[0];\n`; + state._vertexState.compilationString += `${prefix}${"v_" + connectedPoint.declarationVariableName}_r1 = ${connectedPoint.associatedVariableName}[1];\n`; + state._vertexState.compilationString += `${prefix}${"v_" + connectedPoint.declarationVariableName}_r2 = ${connectedPoint.associatedVariableName}[2];\n`; + state._vertexState.compilationString += `${prefix}${"v_" + connectedPoint.declarationVariableName}_r3 = ${connectedPoint.associatedVariableName}[3];\n`; + } + else { + state._vertexState.compilationString += `${prefix}${"v_" + connectedPoint.declarationVariableName} = ${connectedPoint.associatedVariableName};\n`; + } + } + const prefix = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ && connectedPoint.type !== NodeMaterialBlockConnectionPointTypes.Matrix ? "fragmentInputs." : ""; + input.associatedVariableName = prefix + "v_" + connectedPoint.declarationVariableName; + input._enforceAssociatedVariableName = true; + } + } + } + /** + * Validates the new name for the block node. + * @param newName the new name to be given to the node. + * @returns false if the name is a reserve word, else true. + */ + validateBlockName(newName) { + const reservedNames = [ + "position", + "normal", + "tangent", + "particle_positionw", + "uv", + "uv2", + "uv3", + "uv4", + "uv5", + "uv6", + "position2d", + "particle_uv", + "matricesIndices", + "matricesWeights", + "world0", + "world1", + "world2", + "world3", + "particle_color", + "particle_texturemask", + ]; + for (const reservedName of reservedNames) { + if (newName === reservedName) { + return false; + } + } + return true; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _customBuildStep(state, activeBlocks) { + // Must be implemented by children + } + /** + * Compile the current node and generate the shader code + * @param state defines the current compilation state (uniforms, samplers, current string) + * @param activeBlocks defines the list of active blocks (i.e. blocks to compile) + * @returns true if already built + */ + build(state, activeBlocks) { + if (this._buildId === state.sharedData.buildId) { + return true; + } + if (!this.isInput) { + /** Prepare outputs */ + for (const output of this._outputs) { + if (!output.associatedVariableName) { + output.associatedVariableName = state._getFreeVariableName(output.name); + } + } + } + // Check if "parent" blocks are compiled + for (const input of this._inputs) { + if (!input.connectedPoint) { + if (!input.isOptional) { + // Emit a warning + state.sharedData.checks.notConnectedNonOptionalInputs.push(input); + } + continue; + } + if (this.target !== NodeMaterialBlockTargets.Neutral) { + if ((input.target & this.target) === 0) { + continue; + } + if ((input.target & state.target) === 0) { + continue; + } + } + const block = input.connectedPoint.ownerBlock; + if (block && block !== this) { + this._processBuild(block, state, input, activeBlocks); + } + } + this._customBuildStep(state, activeBlocks); + if (this._buildId === state.sharedData.buildId) { + return true; // Need to check again as inputs can be connected multiple time to this endpoint + } + // Logs + if (state.sharedData.verbose) { + Logger.Log(`${state.target === NodeMaterialBlockTargets.Vertex ? "Vertex shader" : "Fragment shader"}: Building ${this.name} [${this.getClassName()}]`); + } + // Checks final outputs + if (this.isFinalMerger) { + switch (state.target) { + case NodeMaterialBlockTargets.Vertex: + state.sharedData.checks.emitVertex = true; + break; + case NodeMaterialBlockTargets.Fragment: + state.sharedData.checks.emitFragment = true; + break; + } + } + if (!this.isInput && state.sharedData.emitComments) { + state.compilationString += `\n//${this.name}\n`; + } + this._buildBlock(state); + this._buildId = state.sharedData.buildId; + this._buildTarget = state.target; + // Compile connected blocks + for (const output of this._outputs) { + if (output._forPostBuild) { + continue; + } + if ((output.target & state.target) === 0) { + continue; + } + for (const endpoint of output.endpoints) { + const block = endpoint.ownerBlock; + if (block) { + if (((block.target & state.target) !== 0 && activeBlocks.indexOf(block) !== -1) || state._terminalBlocks.has(block)) { + this._processBuild(block, state, endpoint, activeBlocks); + } + } + } + } + this._postBuildBlock(state); + // Compile post build connected blocks + for (const output of this._outputs) { + if (!output._forPostBuild) { + continue; + } + if ((output.target & state.target) === 0) { + continue; + } + for (const endpoint of output.endpoints) { + const block = endpoint.ownerBlock; + if (block && (block.target & state.target) !== 0 && activeBlocks.indexOf(block) !== -1) { + this._processBuild(block, state, endpoint, activeBlocks); + } + } + } + return false; + } + _inputRename(name) { + return name; + } + _outputRename(name) { + return name; + } + _dumpPropertiesCode() { + const variableName = this._codeVariableName; + return `${variableName}.visibleInInspector = ${this.visibleInInspector};\n${variableName}.visibleOnFrame = ${this.visibleOnFrame};\n${variableName}.target = ${this.target};\n`; + } + /** + * @internal + */ + _dumpCode(uniqueNames, alreadyDumped) { + alreadyDumped.push(this); + // Get unique name + const nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, ""); + this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`; + if (uniqueNames.indexOf(this._codeVariableName) !== -1) { + let index = 0; + do { + index++; + this._codeVariableName = nameAsVariableName + index; + } while (uniqueNames.indexOf(this._codeVariableName) !== -1); + } + uniqueNames.push(this._codeVariableName); + // Declaration + let codeString = `\n// ${this.getClassName()}\n`; + if (this.comments) { + codeString += `// ${this.comments}\n`; + } + codeString += `var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`; + // Properties + codeString += this._dumpPropertiesCode(); + // Inputs + for (const input of this.inputs) { + if (!input.isConnected) { + continue; + } + const connectedOutput = input.connectedPoint; + const connectedBlock = connectedOutput.ownerBlock; + if (alreadyDumped.indexOf(connectedBlock) === -1) { + codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped); + } + } + // Outputs + for (const output of this.outputs) { + if (!output.hasEndpoints) { + continue; + } + for (const endpoint of output.endpoints) { + const connectedBlock = endpoint.ownerBlock; + if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) { + codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped); + } + } + } + return codeString; + } + /** + * @internal + */ + _dumpCodeForOutputConnections(alreadyDumped) { + let codeString = ""; + if (alreadyDumped.indexOf(this) !== -1) { + return codeString; + } + alreadyDumped.push(this); + for (const input of this.inputs) { + if (!input.isConnected) { + continue; + } + const connectedOutput = input.connectedPoint; + const connectedBlock = connectedOutput.ownerBlock; + codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped); + codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});\n`; + } + return codeString; + } + /** + * Clone the current block to a new identical block + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a copy of the current block + */ + clone(scene, rootUrl = "") { + const serializationObject = this.serialize(); + const blockType = GetClass(serializationObject.customType); + if (blockType) { + const block = new blockType(); + block._deserialize(serializationObject, scene, rootUrl); + return block; + } + return null; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = {}; + serializationObject.customType = "BABYLON." + this.getClassName(); + serializationObject.id = this.uniqueId; + serializationObject.name = this.name; + serializationObject.comments = this.comments; + serializationObject.visibleInInspector = this.visibleInInspector; + serializationObject.visibleOnFrame = this.visibleOnFrame; + serializationObject.target = this.target; + serializationObject.inputs = []; + serializationObject.outputs = []; + for (const input of this.inputs) { + serializationObject.inputs.push(input.serialize()); + } + for (const output of this.outputs) { + serializationObject.outputs.push(output.serialize(false)); + } + return serializationObject; + } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _deserialize(serializationObject, scene, rootUrl, urlRewriter) { + this.name = serializationObject.name; + this.comments = serializationObject.comments; + this.visibleInInspector = !!serializationObject.visibleInInspector; + this.visibleOnFrame = !!serializationObject.visibleOnFrame; + this._target = serializationObject.target ?? this.target; + this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject); + } + _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) { + const serializedInputs = serializationObject.inputs; + const serializedOutputs = serializationObject.outputs; + if (serializedInputs) { + serializedInputs.forEach((port, i) => { + if (port.displayName) { + this.inputs[i].displayName = port.displayName; + } + if (port.isExposedOnFrame) { + this.inputs[i].isExposedOnFrame = port.isExposedOnFrame; + this.inputs[i].exposedPortPosition = port.exposedPortPosition; + } + }); + } + if (serializedOutputs) { + serializedOutputs.forEach((port, i) => { + if (port.displayName) { + this.outputs[i].displayName = port.displayName; + } + if (port.isExposedOnFrame) { + this.outputs[i].isExposedOnFrame = port.isExposedOnFrame; + this.outputs[i].exposedPortPosition = port.exposedPortPosition; + } + }); + } + } + /** + * Release resources + */ + dispose() { + this.onCodeIsReadyObservable.clear(); + for (const input of this.inputs) { + input.dispose(); + } + for (const output of this.outputs) { + output.dispose(); + } + } +} + +/** + * Block used to transform a vector (2, 3 or 4) with a matrix. It will generate a Vector4 + */ +class TransformBlock extends NodeMaterialBlock { + /** + * Boolean indicating if the transformation is made for a direction vector and not a position vector + * If set to true the complementW value will be set to 0 else it will be set to 1 + */ + get transformAsDirection() { + return this.complementW === 0; + } + set transformAsDirection(value) { + this.complementW = value ? 0 : 1; + } + /** + * Creates a new TransformBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Defines the value to use to complement W value to transform it to a Vector4 + */ + this.complementW = 1; + /** + * Defines the value to use to complement z value to transform it to a Vector4 + */ + this.complementZ = 0; + this.target = NodeMaterialBlockTargets.Vertex; + this.registerInput("vector", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("transform", NodeMaterialBlockConnectionPointTypes.Matrix); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3); + this._inputs[0].onConnectionObservable.add((other) => { + if (other.ownerBlock.isInput) { + const otherAsInput = other.ownerBlock; + if (otherAsInput.name === "normal" || otherAsInput.name === "tangent") { + this.complementW = 0; + } + } + }); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "TransformBlock"; + } + /** + * Gets the vector input + */ + get vector() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the xyz output component + */ + get xyz() { + return this._outputs[1]; + } + /** + * Gets the matrix transform input + */ + get transform() { + return this._inputs[1]; + } + _buildBlock(state) { + super._buildBlock(state); + const vector = this.vector; + const transform = this.transform; + const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4); + const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3); + if (vector.connectedPoint) { + // None uniform scaling case. + if (this.complementW === 0 || this.transformAsDirection) { + const comments = `//${this.name}`; + state._emitFunctionFromInclude("helperFunctions", comments); + state.sharedData.blocksWithDefines.push(this); + const transformName = state._getFreeVariableName(`${transform.associatedVariableName}_NUS`); + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + state.compilationString += `var ${transformName}: mat3x3f = mat3x3f(${transform.associatedVariableName}[0].xyz, ${transform.associatedVariableName}[1].xyz, ${transform.associatedVariableName}[2].xyz);\n`; + } + else { + state.compilationString += `mat3 ${transformName} = mat3(${transform.associatedVariableName});\n`; + } + state.compilationString += `#ifdef NONUNIFORMSCALING\n`; + state.compilationString += `${transformName} = transposeMat3(inverseMat3(${transformName}));\n`; + state.compilationString += `#endif\n`; + switch (vector.connectedPoint.type) { + case NodeMaterialBlockConnectionPointTypes.Vector2: + state.compilationString += + state._declareOutput(this.output) + + ` = ${vec4}(${transformName} * ${vec3}(${vector.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\n`; + break; + case NodeMaterialBlockConnectionPointTypes.Vector3: + case NodeMaterialBlockConnectionPointTypes.Color3: + state.compilationString += + state._declareOutput(this.output) + ` = ${vec4}(${transformName} * ${vector.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`; + break; + default: + state.compilationString += + state._declareOutput(this.output) + ` = ${vec4}(${transformName} * ${vector.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\n`; + break; + } + } + else { + const transformName = transform.associatedVariableName; + switch (vector.connectedPoint.type) { + case NodeMaterialBlockConnectionPointTypes.Vector2: + state.compilationString += + state._declareOutput(this.output) + + ` = ${transformName} * ${vec4}(${vector.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\n`; + break; + case NodeMaterialBlockConnectionPointTypes.Vector3: + case NodeMaterialBlockConnectionPointTypes.Color3: + state.compilationString += + state._declareOutput(this.output) + ` = ${transformName} * ${vec4}(${vector.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`; + break; + default: + state.compilationString += state._declareOutput(this.output) + ` = ${transformName} * ${vector.associatedVariableName};\n`; + break; + } + } + if (this.xyz.hasEndpoints) { + state.compilationString += state._declareOutput(this.xyz) + ` = ${this.output.associatedVariableName}.xyz;\n`; + } + } + return this; + } + /** + * Update defines for shader compilation + * @param mesh defines the mesh to be rendered + * @param nodeMaterial defines the node material requesting the update + * @param defines defines the material defines to update + */ + prepareDefines(mesh, nodeMaterial, defines) { + // Do nothing + if (mesh.nonUniformScaling) { + defines.setValue("NONUNIFORMSCALING", true); + } + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.complementZ = this.complementZ; + serializationObject.complementW = this.complementW; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.complementZ = serializationObject.complementZ !== undefined ? serializationObject.complementZ : 0.0; + this.complementW = serializationObject.complementW !== undefined ? serializationObject.complementW : 1.0; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.complementZ = ${this.complementZ};\n`; + codeString += `${this._codeVariableName}.complementW = ${this.complementW};\n`; + return codeString; + } +} +__decorate([ + editableInPropertyPage("Transform as direction", 0 /* PropertyTypeForEdition.Boolean */, undefined, { embedded: true }) +], TransformBlock.prototype, "transformAsDirection", null); +RegisterClass("BABYLON.TransformBlock", TransformBlock); + +/** + * Block used to output the vertex position + */ +class VertexOutputBlock extends NodeMaterialBlock { + /** + * Creates a new VertexOutputBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Vertex, true); + this.registerInput("vector", NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "VertexOutputBlock"; + } + /** + * Gets the vector input component + */ + get vector() { + return this._inputs[0]; + } + _isLogarithmicDepthEnabled(nodeList, useLogarithmicDepth) { + if (useLogarithmicDepth) { + return true; + } + for (const node of nodeList) { + if (node.useLogarithmicDepth) { + return true; + } + } + return false; + } + _buildBlock(state) { + super._buildBlock(state); + const input = this.vector; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + state.compilationString += `vertexOutputs.position = ${input.associatedVariableName};\n`; + } + else { + state.compilationString += `gl_Position = ${input.associatedVariableName};\n`; + } + // TODOWGSL + if (this._isLogarithmicDepthEnabled(state.sharedData.fragmentOutputNodes, state.sharedData.nodeMaterial.useLogarithmicDepth)) { + state._emitUniformFromString("logarithmicDepthConstant", NodeMaterialBlockConnectionPointTypes.Float); + state._emitVaryingFromString("vFragmentDepth", NodeMaterialBlockConnectionPointTypes.Float); + const fragDepth = isWebGPU ? "vertexOutputs.vFragmentDepth" : "vFragmentDepth"; + const uniformP = isWebGPU ? "uniforms." : ""; + const position = isWebGPU ? "vertexOutputs.position" : "gl_Position"; + state.compilationString += `${fragDepth} = 1.0 + ${position}.w;\n`; + state.compilationString += `${position}.z = log2(max(0.000001, ${fragDepth})) * ${uniformP}logarithmicDepthConstant;\n`; + } + return this; + } +} +RegisterClass("BABYLON.VertexOutputBlock", VertexOutputBlock); + +/** + * Color spaces supported by the fragment output block + */ +var FragmentOutputBlockColorSpace; +(function (FragmentOutputBlockColorSpace) { + /** Unspecified */ + FragmentOutputBlockColorSpace[FragmentOutputBlockColorSpace["NoColorSpace"] = 0] = "NoColorSpace"; + /** Gamma */ + FragmentOutputBlockColorSpace[FragmentOutputBlockColorSpace["Gamma"] = 1] = "Gamma"; + /** Linear */ + FragmentOutputBlockColorSpace[FragmentOutputBlockColorSpace["Linear"] = 2] = "Linear"; +})(FragmentOutputBlockColorSpace || (FragmentOutputBlockColorSpace = {})); +/** + * Block used to output the final color + */ +class FragmentOutputBlock extends NodeMaterialBlock { + /** + * Create a new FragmentOutputBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment, true, true); + /** Gets or sets a boolean indicating if content needs to be converted to gamma space */ + this.convertToGammaSpace = false; + /** Gets or sets a boolean indicating if content needs to be converted to linear space */ + this.convertToLinearSpace = false; + /** Gets or sets a boolean indicating if logarithmic depth should be used */ + this.useLogarithmicDepth = false; + this.registerInput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, true); + this.registerInput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, true); + this.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("glow", NodeMaterialBlockConnectionPointTypes.Color3, true); + this.rgb.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3); + this.rgb.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this.additionalColor.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3); + this.additionalColor.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets or sets the color space used for the block + */ + get colorSpace() { + if (this.convertToGammaSpace) { + return FragmentOutputBlockColorSpace.Gamma; + } + if (this.convertToLinearSpace) { + return FragmentOutputBlockColorSpace.Linear; + } + return FragmentOutputBlockColorSpace.NoColorSpace; + } + set colorSpace(value) { + this.convertToGammaSpace = value === FragmentOutputBlockColorSpace.Gamma; + this.convertToLinearSpace = value === FragmentOutputBlockColorSpace.Linear; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "FragmentOutputBlock"; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("logarithmicDepthConstant"); + state._excludeVariableName("vFragmentDepth"); + } + /** + * Gets the rgba input component + */ + get rgba() { + return this._inputs[0]; + } + /** + * Gets the rgb input component + */ + get rgb() { + return this._inputs[1]; + } + /** + * Gets the a input component + */ + get a() { + return this._inputs[2]; + } + /** + * Gets the additionalColor input component (named glow in the UI for now) + */ + get additionalColor() { + return this._inputs[3]; + } + prepareDefines(mesh, nodeMaterial, defines) { + defines.setValue(this._linearDefineName, this.convertToLinearSpace, true); + defines.setValue(this._gammaDefineName, this.convertToGammaSpace, true); + defines.setValue(this._additionalColorDefineName, this.additionalColor.connectedPoint && nodeMaterial._useAdditionalColor, true); + } + bind(effect, nodeMaterial, mesh) { + if ((this.useLogarithmicDepth || nodeMaterial.useLogarithmicDepth) && mesh) { + BindLogDepth(undefined, effect, mesh.getScene()); + } + } + _buildBlock(state) { + super._buildBlock(state); + const rgba = this.rgba; + const rgb = this.rgb; + const a = this.a; + const additionalColor = this.additionalColor; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + state.sharedData.hints.needAlphaBlending = rgba.isConnected || a.isConnected; + state.sharedData.blocksWithDefines.push(this); + if (this.useLogarithmicDepth || state.sharedData.nodeMaterial.useLogarithmicDepth) { + state._emitUniformFromString("logarithmicDepthConstant", NodeMaterialBlockConnectionPointTypes.Float); + state._emitVaryingFromString("vFragmentDepth", NodeMaterialBlockConnectionPointTypes.Float); + state.sharedData.bindableBlocks.push(this); + } + if (additionalColor.connectedPoint) { + state._excludeVariableName("useAdditionalColor"); + state._emitUniformFromString("useAdditionalColor", NodeMaterialBlockConnectionPointTypes.Float); + this._additionalColorDefineName = state._getFreeDefineName("USEADDITIONALCOLOR"); + } + this._linearDefineName = state._getFreeDefineName("CONVERTTOLINEAR"); + this._gammaDefineName = state._getFreeDefineName("CONVERTTOGAMMA"); + const comments = `//${this.name}`; + state._emitFunctionFromInclude("helperFunctions", comments); + let outputString = "gl_FragColor"; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + state.compilationString += `var fragmentOutputsColor : vec4;\r\n`; + outputString = "fragmentOutputsColor"; + } + const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4); + if (additionalColor.connectedPoint) { + let aValue = "1.0"; + if (a.connectedPoint) { + aValue = a.associatedVariableName; + } + state.compilationString += `#ifdef ${this._additionalColorDefineName}\n`; + if (additionalColor.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float) { + state.compilationString += `${outputString} = ${vec4}(${additionalColor.associatedVariableName}, ${additionalColor.associatedVariableName}, ${additionalColor.associatedVariableName}, ${aValue});\n`; + } + else { + state.compilationString += `${outputString} = ${vec4}(${additionalColor.associatedVariableName}, ${aValue});\n`; + } + state.compilationString += `#else\n`; + } + if (rgba.connectedPoint) { + if (a.isConnected) { + state.compilationString += `${outputString} = ${vec4}(${rgba.associatedVariableName}.rgb, ${a.associatedVariableName});\n`; + } + else { + state.compilationString += `${outputString} = ${rgba.associatedVariableName};\n`; + } + } + else if (rgb.connectedPoint) { + let aValue = "1.0"; + if (a.connectedPoint) { + aValue = a.associatedVariableName; + } + if (rgb.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float) { + state.compilationString += `${outputString} = ${vec4}(${rgb.associatedVariableName}, ${rgb.associatedVariableName}, ${rgb.associatedVariableName}, ${aValue});\n`; + } + else { + state.compilationString += `${outputString} = ${vec4}(${rgb.associatedVariableName}, ${aValue});\n`; + } + } + else { + state.sharedData.checks.notConnectedNonOptionalInputs.push(rgba); + } + if (additionalColor.connectedPoint) { + state.compilationString += `#endif\n`; + } + state.compilationString += `#ifdef ${this._linearDefineName}\n`; + state.compilationString += `${outputString} = toLinearSpace(${outputString});\n`; + state.compilationString += `#endif\n`; + state.compilationString += `#ifdef ${this._gammaDefineName}\n`; + state.compilationString += `${outputString} = toGammaSpace(${outputString});\n`; + state.compilationString += `#endif\n`; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + state.compilationString += `#if !defined(PREPASS)\r\n`; + state.compilationString += `fragmentOutputs.color = fragmentOutputsColor;\r\n`; + state.compilationString += `#endif\r\n`; + } + if (this.useLogarithmicDepth || state.sharedData.nodeMaterial.useLogarithmicDepth) { + const fragDepth = isWebGPU ? "input.vFragmentDepth" : "vFragmentDepth"; + const uniformP = isWebGPU ? "uniforms." : ""; + const output = isWebGPU ? "fragmentOutputs.fragDepth" : "gl_FragDepthEXT"; + state.compilationString += `${output} = log2(${fragDepth}) * ${uniformP}logarithmicDepthConstant * 0.5;\n`; + } + state.compilationString += `#if defined(PREPASS)\r\n`; + state.compilationString += `${isWebGPU ? "fragmentOutputs.fragData0" : "gl_FragData[0]"} = ${outputString};\r\n`; + state.compilationString += `#endif\r\n`; + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`; + codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`; + codeString += `${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.convertToGammaSpace = this.convertToGammaSpace; + serializationObject.convertToLinearSpace = this.convertToLinearSpace; + serializationObject.useLogarithmicDepth = this.useLogarithmicDepth; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.convertToGammaSpace = !!serializationObject.convertToGammaSpace; + this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; + this.useLogarithmicDepth = serializationObject.useLogarithmicDepth ?? false; + } +} +__decorate([ + editableInPropertyPage("Use logarithmic depth", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES", { embedded: true }) +], FragmentOutputBlock.prototype, "useLogarithmicDepth", void 0); +__decorate([ + editableInPropertyPage("Color space", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "No color space", value: FragmentOutputBlockColorSpace.NoColorSpace }, + { label: "Gamma", value: FragmentOutputBlockColorSpace.Gamma }, + { label: "Linear", value: FragmentOutputBlockColorSpace.Linear }, + ], + }) +], FragmentOutputBlock.prototype, "colorSpace", null); +RegisterClass("BABYLON.FragmentOutputBlock", FragmentOutputBlock); + +/** + * Enum used to define system values e.g. values automatically provided by the system + */ +var NodeMaterialSystemValues; +(function (NodeMaterialSystemValues) { + /** World */ + NodeMaterialSystemValues[NodeMaterialSystemValues["World"] = 1] = "World"; + /** View */ + NodeMaterialSystemValues[NodeMaterialSystemValues["View"] = 2] = "View"; + /** Projection */ + NodeMaterialSystemValues[NodeMaterialSystemValues["Projection"] = 3] = "Projection"; + /** ViewProjection */ + NodeMaterialSystemValues[NodeMaterialSystemValues["ViewProjection"] = 4] = "ViewProjection"; + /** WorldView */ + NodeMaterialSystemValues[NodeMaterialSystemValues["WorldView"] = 5] = "WorldView"; + /** WorldViewProjection */ + NodeMaterialSystemValues[NodeMaterialSystemValues["WorldViewProjection"] = 6] = "WorldViewProjection"; + /** CameraPosition */ + NodeMaterialSystemValues[NodeMaterialSystemValues["CameraPosition"] = 7] = "CameraPosition"; + /** Fog Color */ + NodeMaterialSystemValues[NodeMaterialSystemValues["FogColor"] = 8] = "FogColor"; + /** Delta time */ + NodeMaterialSystemValues[NodeMaterialSystemValues["DeltaTime"] = 9] = "DeltaTime"; + /** Camera parameters */ + NodeMaterialSystemValues[NodeMaterialSystemValues["CameraParameters"] = 10] = "CameraParameters"; + /** Material alpha */ + NodeMaterialSystemValues[NodeMaterialSystemValues["MaterialAlpha"] = 11] = "MaterialAlpha"; +})(NodeMaterialSystemValues || (NodeMaterialSystemValues = {})); + +/** + * Enum defining the type of animations supported by InputBlock + */ +var AnimatedInputBlockTypes; +(function (AnimatedInputBlockTypes) { + /** No animation */ + AnimatedInputBlockTypes[AnimatedInputBlockTypes["None"] = 0] = "None"; + /** Time based animation (is incremented by 0.6 each second). Will only work for floats */ + AnimatedInputBlockTypes[AnimatedInputBlockTypes["Time"] = 1] = "Time"; + /** Time elapsed (in seconds) since the engine was initialized. Will only work for floats */ + AnimatedInputBlockTypes[AnimatedInputBlockTypes["RealTime"] = 2] = "RealTime"; + AnimatedInputBlockTypes[AnimatedInputBlockTypes["MouseInfo"] = 3] = "MouseInfo"; +})(AnimatedInputBlockTypes || (AnimatedInputBlockTypes = {})); + +/* eslint-disable @typescript-eslint/naming-convention */ +const remapAttributeName = { + position2d: "position", + particle_uv: "vUV", + particle_color: "vColor", + particle_texturemask: "textureMask", + particle_positionw: "vPositionW", +}; +const attributeInFragmentOnly = { + particle_uv: true, + particle_color: true, + particle_texturemask: true, + particle_positionw: true, +}; +const attributeAsUniform = { + particle_texturemask: true, +}; +const attributeDefine = { + normal: "NORMAL", + tangent: "TANGENT", + uv: "UV1", + uv2: "UV2", + uv3: "UV3", + uv4: "UV4", + uv5: "UV5", + uv6: "UV6", + uv7: "UV7", + uv8: "UV8", +}; +/** + * Block used to expose an input value + */ +class InputBlock extends NodeMaterialBlock { + /** + * Gets or sets the connection point type (default is float) + */ + get type() { + if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) { + if (this.isUniform && this.value != null) { + if (!isNaN(this.value)) { + this._type = NodeMaterialBlockConnectionPointTypes.Float; + return this._type; + } + switch (this.value.getClassName()) { + case "Vector2": + this._type = NodeMaterialBlockConnectionPointTypes.Vector2; + return this._type; + case "Vector3": + this._type = NodeMaterialBlockConnectionPointTypes.Vector3; + return this._type; + case "Vector4": + this._type = NodeMaterialBlockConnectionPointTypes.Vector4; + return this._type; + case "Color3": + this._type = NodeMaterialBlockConnectionPointTypes.Color3; + return this._type; + case "Color4": + this._type = NodeMaterialBlockConnectionPointTypes.Color4; + return this._type; + case "Matrix": + this._type = NodeMaterialBlockConnectionPointTypes.Matrix; + return this._type; + } + } + if (this.isAttribute) { + switch (this.name) { + case "splatIndex": + this._type = NodeMaterialBlockConnectionPointTypes.Float; + return this._type; + case "position": + case "normal": + case "particle_positionw": + case "splatPosition": + this._type = NodeMaterialBlockConnectionPointTypes.Vector3; + return this._type; + case "uv": + case "uv2": + case "uv3": + case "uv4": + case "uv5": + case "uv6": + case "position2d": + case "particle_uv": + case "splatScale": + this._type = NodeMaterialBlockConnectionPointTypes.Vector2; + return this._type; + case "matricesIndices": + case "matricesWeights": + case "matricesIndicesExtra": + case "matricesWeightsExtra": + case "world0": + case "world1": + case "world2": + case "world3": + case "tangent": + this._type = NodeMaterialBlockConnectionPointTypes.Vector4; + return this._type; + case "color": + case "instanceColor": + case "particle_color": + case "particle_texturemask": + case "splatColor": + this._type = NodeMaterialBlockConnectionPointTypes.Color4; + return this._type; + } + } + if (this.isSystemValue) { + switch (this._systemValue) { + case NodeMaterialSystemValues.World: + case NodeMaterialSystemValues.WorldView: + case NodeMaterialSystemValues.WorldViewProjection: + case NodeMaterialSystemValues.View: + case NodeMaterialSystemValues.ViewProjection: + case NodeMaterialSystemValues.Projection: + this._type = NodeMaterialBlockConnectionPointTypes.Matrix; + return this._type; + case NodeMaterialSystemValues.CameraPosition: + this._type = NodeMaterialBlockConnectionPointTypes.Vector3; + return this._type; + case NodeMaterialSystemValues.FogColor: + this._type = NodeMaterialBlockConnectionPointTypes.Color3; + return this._type; + case NodeMaterialSystemValues.DeltaTime: + case NodeMaterialSystemValues.MaterialAlpha: + this._type = NodeMaterialBlockConnectionPointTypes.Float; + return this._type; + case NodeMaterialSystemValues.CameraParameters: + this._type = NodeMaterialBlockConnectionPointTypes.Vector4; + return this._type; + } + } + } + return this._type; + } + /** + * Creates a new InputBlock + * @param name defines the block name + * @param target defines the target of that block (Vertex by default) + * @param type defines the type of the input (can be set to NodeMaterialBlockConnectionPointTypes.AutoDetect) + */ + constructor(name, target = NodeMaterialBlockTargets.Vertex, type = NodeMaterialBlockConnectionPointTypes.AutoDetect) { + super(name, target, false); + this._mode = 3 /* NodeMaterialBlockConnectionPointMode.Undefined */; + this._animationType = AnimatedInputBlockTypes.None; + this._prefix = ""; + /** Gets or set a value used to limit the range of float values */ + this.min = 0; + /** Gets or set a value used to limit the range of float values */ + this.max = 0; + /** Gets or set a value indicating that this input can only get 0 and 1 values */ + this.isBoolean = false; + /** Gets or sets a value used by the Node Material editor to determine how to configure the current value if it is a matrix */ + this.matrixMode = 0; + /** @internal */ + this._systemValue = null; + /** Gets or sets a boolean indicating that the value of this input will not change after a build */ + this.isConstant = false; + /** Gets or sets the group to use to display this block in the Inspector */ + this.groupInInspector = ""; + /** Gets an observable raised when the value is changed */ + this.onValueChangedObservable = new Observable(); + /** Gets or sets a boolean indicating if content needs to be converted to gamma space (for color3/4 only) */ + this.convertToGammaSpace = false; + /** Gets or sets a boolean indicating if content needs to be converted to linear space (for color3/4 only) */ + this.convertToLinearSpace = false; + this._type = type; + this.setDefaultValue(); + this.registerOutput("output", type); + } + /** + * Validates if a name is a reserve word. + * @param newName the new name to be given to the node. + * @returns false if the name is a reserve word, else true. + */ + validateBlockName(newName) { + if (!this.isAttribute) { + return super.validateBlockName(newName); + } + return true; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Set the source of this connection point to a vertex attribute + * @param attributeName defines the attribute name (position, uv, normal, etc...). If not specified it will take the connection point name + * @returns the current connection point + */ + setAsAttribute(attributeName) { + this._mode = 1 /* NodeMaterialBlockConnectionPointMode.Attribute */; + if (attributeName) { + this.name = attributeName; + } + return this; + } + /** + * Set the source of this connection point to a system value + * @param value define the system value to use (world, view, etc...) or null to switch to manual value + * @returns the current connection point + */ + setAsSystemValue(value) { + this.systemValue = value; + return this; + } + /** + * Gets or sets the value of that point. + * Please note that this value will be ignored if valueCallback is defined + */ + get value() { + return this._storedValue; + } + set value(value) { + if (this.type === NodeMaterialBlockConnectionPointTypes.Float) { + if (this.isBoolean) { + value = value ? 1 : 0; + } + else if (this.min !== this.max) { + value = Math.max(this.min, value); + value = Math.min(this.max, value); + } + } + this._storedValue = value; + this._mode = 0 /* NodeMaterialBlockConnectionPointMode.Uniform */; + this.onValueChangedObservable.notifyObservers(this); + } + /** + * Gets or sets a callback used to get the value of that point. + * Please note that setting this value will force the connection point to ignore the value property + */ + get valueCallback() { + return this._valueCallback; + } + set valueCallback(value) { + this._valueCallback = value; + this._mode = 0 /* NodeMaterialBlockConnectionPointMode.Uniform */; + } + /** + * Gets the declaration variable name in the shader + */ + get declarationVariableName() { + return this._associatedVariableName; + } + /** + * Gets or sets the associated variable name in the shader + */ + get associatedVariableName() { + return this._prefix + this._associatedVariableName; + } + set associatedVariableName(value) { + this._associatedVariableName = value; + } + /** Gets or sets the type of animation applied to the input */ + get animationType() { + return this._animationType; + } + set animationType(value) { + this._animationType = value; + } + /** + * Gets a boolean indicating that this connection point not defined yet + */ + get isUndefined() { + return this._mode === 3 /* NodeMaterialBlockConnectionPointMode.Undefined */; + } + /** + * Gets or sets a boolean indicating that this connection point is coming from an uniform. + * In this case the connection point name must be the name of the uniform to use. + * Can only be set on inputs + */ + get isUniform() { + return this._mode === 0 /* NodeMaterialBlockConnectionPointMode.Uniform */; + } + set isUniform(value) { + this._mode = value ? 0 /* NodeMaterialBlockConnectionPointMode.Uniform */ : 3 /* NodeMaterialBlockConnectionPointMode.Undefined */; + this.associatedVariableName = ""; + } + /** + * Gets or sets a boolean indicating that this connection point is coming from an attribute. + * In this case the connection point name must be the name of the attribute to use + * Can only be set on inputs + */ + get isAttribute() { + return this._mode === 1 /* NodeMaterialBlockConnectionPointMode.Attribute */; + } + set isAttribute(value) { + this._mode = value ? 1 /* NodeMaterialBlockConnectionPointMode.Attribute */ : 3 /* NodeMaterialBlockConnectionPointMode.Undefined */; + this.associatedVariableName = ""; + } + /** + * Gets or sets a boolean indicating that this connection point is generating a varying variable. + * Can only be set on exit points + */ + get isVarying() { + return this._mode === 2 /* NodeMaterialBlockConnectionPointMode.Varying */; + } + set isVarying(value) { + this._mode = value ? 2 /* NodeMaterialBlockConnectionPointMode.Varying */ : 3 /* NodeMaterialBlockConnectionPointMode.Undefined */; + this.associatedVariableName = ""; + } + /** + * Gets a boolean indicating that the current connection point is a system value + */ + get isSystemValue() { + return this._systemValue != null; + } + /** + * Gets or sets the current well known value or null if not defined as a system value + */ + get systemValue() { + return this._systemValue; + } + set systemValue(value) { + this._mode = 0 /* NodeMaterialBlockConnectionPointMode.Uniform */; + this.associatedVariableName = ""; + this._systemValue = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "InputBlock"; + } + /** + * Animate the input if animationType !== None + * @param scene defines the rendering scene + */ + animate(scene) { + switch (this._animationType) { + case AnimatedInputBlockTypes.Time: { + if (this.type === NodeMaterialBlockConnectionPointTypes.Float) { + this.value += scene.getAnimationRatio() * 0.01; + } + break; + } + case AnimatedInputBlockTypes.RealTime: { + if (this.type === NodeMaterialBlockConnectionPointTypes.Float) { + this.value = (PrecisionDate.Now - scene.getEngine().startTime) / 1000; + } + break; + } + case AnimatedInputBlockTypes.MouseInfo: { + if (this.type === NodeMaterialBlockConnectionPointTypes.Vector4) { + const event = scene._inputManager._originMouseEvent; + if (event) { + const x = event.offsetX; + const y = event.offsetY; + const z = (event.buttons & 1) != 0 ? 1 : 0; + const w = (event.buttons & 2) != 0 ? 1 : 0; + this.value = new Vector4(x, y, z, w); + } + else { + this.value = new Vector4(0, 0, 0, 0); + } + } + break; + } + } + } + _emitDefine(define) { + if (define[0] === "!") { + return `#ifndef ${define.substring(1)}\n`; + } + return `#ifdef ${define}\n`; + } + initialize() { + this.associatedVariableName = ""; + } + /** + * Set the input block to its default value (based on its type) + */ + setDefaultValue() { + switch (this.type) { + case NodeMaterialBlockConnectionPointTypes.Float: + this.value = 0; + break; + case NodeMaterialBlockConnectionPointTypes.Vector2: + this.value = Vector2.Zero(); + break; + case NodeMaterialBlockConnectionPointTypes.Vector3: + this.value = Vector3.Zero(); + break; + case NodeMaterialBlockConnectionPointTypes.Vector4: + this.value = Vector4.Zero(); + break; + case NodeMaterialBlockConnectionPointTypes.Color3: + this.value = Color3.White(); + break; + case NodeMaterialBlockConnectionPointTypes.Color4: + this.value = new Color4(1, 1, 1, 1); + break; + case NodeMaterialBlockConnectionPointTypes.Matrix: + this.value = Matrix.Identity(); + break; + } + } + _emitConstant(state) { + switch (this.type) { + case NodeMaterialBlockConnectionPointTypes.Float: + return `${state._emitFloat(this.value)}`; + case NodeMaterialBlockConnectionPointTypes.Vector2: + return `vec2(${this.value.x}, ${this.value.y})`; + case NodeMaterialBlockConnectionPointTypes.Vector3: + return `vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`; + case NodeMaterialBlockConnectionPointTypes.Vector4: + return `vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`; + case NodeMaterialBlockConnectionPointTypes.Color3: + TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b); + if (this.convertToGammaSpace) { + TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0], state.sharedData.scene.getEngine().useExactSrgbConversions); + } + if (this.convertToLinearSpace) { + TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0], state.sharedData.scene.getEngine().useExactSrgbConversions); + } + return `vec3(${TmpColors.Color3[0].r}, ${TmpColors.Color3[0].g}, ${TmpColors.Color3[0].b})`; + case NodeMaterialBlockConnectionPointTypes.Color4: + TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a); + if (this.convertToGammaSpace) { + TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0], state.sharedData.scene.getEngine().useExactSrgbConversions); + } + if (this.convertToLinearSpace) { + TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0], state.sharedData.scene.getEngine().useExactSrgbConversions); + } + return `vec4(${TmpColors.Color4[0].r}, ${TmpColors.Color4[0].g}, ${TmpColors.Color4[0].b}, ${TmpColors.Color4[0].a})`; + } + return ""; + } + /** @internal */ + get _noContextSwitch() { + return attributeInFragmentOnly[this.name]; + } + _emit(state, define) { + // Uniforms + if (this.isUniform) { + if (!this._associatedVariableName) { + this._associatedVariableName = state._getFreeVariableName("u_" + this.name); + } + if (this.isConstant) { + if (state.constants.indexOf(this.associatedVariableName) !== -1) { + return; + } + state.constants.push(this.associatedVariableName); + state._constantDeclaration += state._declareOutput(this.output, true) + ` = ${this._emitConstant(state)};\n`; + return; + } + if (state.uniforms.indexOf(this.associatedVariableName) !== -1) { + return; + } + state.uniforms.push(this.associatedVariableName); + if (define) { + state._uniformDeclaration += this._emitDefine(define); + } + const shaderType = state._getShaderType(this.type); + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + state._uniformDeclaration += `uniform ${this._associatedVariableName}: ${shaderType};\n`; + this._prefix = "uniforms."; + } + else { + state._uniformDeclaration += `uniform ${shaderType} ${this.associatedVariableName};\n`; + } + if (define) { + state._uniformDeclaration += `#endif\n`; + } + // well known + const hints = state.sharedData.hints; + if (this._systemValue !== null && this._systemValue !== undefined) { + switch (this._systemValue) { + case NodeMaterialSystemValues.WorldView: + hints.needWorldViewMatrix = true; + break; + case NodeMaterialSystemValues.WorldViewProjection: + hints.needWorldViewProjectionMatrix = true; + break; + } + } + else { + if (this._animationType !== AnimatedInputBlockTypes.None) { + state.sharedData.animatedInputs.push(this); + } + } + return; + } + // Attribute + if (this.isAttribute) { + this.associatedVariableName = remapAttributeName[this.name] ?? this.name; + if (this.target === NodeMaterialBlockTargets.Vertex && state._vertexState) { + // Attribute for fragment need to be carried over by varyings + if (attributeInFragmentOnly[this.name]) { + if (attributeAsUniform[this.name]) { + state._emitUniformFromString(this.declarationVariableName, this.type, define); + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + this._prefix = `vertexInputs.`; + } + } + else { + state._emitVaryingFromString(this.declarationVariableName, this.type, define); + } + } + else { + this._emit(state._vertexState, define); + } + return; + } + const alreadyDeclared = state.attributes.indexOf(this.declarationVariableName) !== -1; + if (!alreadyDeclared) { + state.attributes.push(this.declarationVariableName); + } + if (attributeInFragmentOnly[this.name]) { + if (attributeAsUniform[this.name]) { + if (!alreadyDeclared) { + state._emitUniformFromString(this.declarationVariableName, this.type, define); + } + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + this._prefix = `uniforms.`; + } + } + else { + if (!alreadyDeclared) { + state._emitVaryingFromString(this.declarationVariableName, this.type, define); + } + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + this._prefix = `fragmentInputs.`; + } + } + } + else { + if (define && !alreadyDeclared) { + state._attributeDeclaration += this._emitDefine(define); + } + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + if (!alreadyDeclared) { + const defineName = attributeDefine[this.name]; + if (defineName) { + state._attributeDeclaration += `#ifdef ${defineName}\n`; + state._attributeDeclaration += `attribute ${this.declarationVariableName}: ${state._getShaderType(this.type)};\n`; + state._attributeDeclaration += `#else\n`; + state._attributeDeclaration += `var ${this.declarationVariableName}: ${state._getShaderType(this.type)} = ${state._getShaderType(this.type)}(0.);\n`; + state._attributeDeclaration += `#endif\n`; + } + else { + state._attributeDeclaration += `attribute ${this.declarationVariableName}: ${state._getShaderType(this.type)};\n`; + } + } + this._prefix = `vertexInputs.`; + } + else { + if (!alreadyDeclared) { + const defineName = attributeDefine[this.name]; + if (defineName) { + state._attributeDeclaration += `#ifdef ${defineName}\n`; + state._attributeDeclaration += `attribute ${state._getShaderType(this.type)} ${this.declarationVariableName};\n`; + state._attributeDeclaration += `#else\n`; + state._attributeDeclaration += `${state._getShaderType(this.type)} ${this.declarationVariableName} = ${state._getShaderType(this.type)}(0.);\n`; + state._attributeDeclaration += `#endif\n`; + } + else { + state._attributeDeclaration += `attribute ${state._getShaderType(this.type)} ${this.declarationVariableName};\n`; + } + } + } + if (define && !alreadyDeclared) { + state._attributeDeclaration += `#endif\n`; + } + } + } + } + /** + * @internal + */ + _transmitWorld(effect, world, worldView, worldViewProjection) { + if (!this._systemValue) { + return; + } + const variableName = this._associatedVariableName; + switch (this._systemValue) { + case NodeMaterialSystemValues.World: + effect.setMatrix(variableName, world); + break; + case NodeMaterialSystemValues.WorldView: + effect.setMatrix(variableName, worldView); + break; + case NodeMaterialSystemValues.WorldViewProjection: + effect.setMatrix(variableName, worldViewProjection); + break; + } + } + /** + * @internal + */ + _transmit(effect, scene, material) { + if (this.isAttribute) { + return; + } + const variableName = this._associatedVariableName; + if (this._systemValue) { + switch (this._systemValue) { + case NodeMaterialSystemValues.World: + case NodeMaterialSystemValues.WorldView: + case NodeMaterialSystemValues.WorldViewProjection: + return; + case NodeMaterialSystemValues.View: + effect.setMatrix(variableName, scene.getViewMatrix()); + break; + case NodeMaterialSystemValues.Projection: + effect.setMatrix(variableName, scene.getProjectionMatrix()); + break; + case NodeMaterialSystemValues.ViewProjection: + effect.setMatrix(variableName, scene.getTransformMatrix()); + break; + case NodeMaterialSystemValues.CameraPosition: + scene.bindEyePosition(effect, variableName, true); + break; + case NodeMaterialSystemValues.FogColor: + effect.setColor3(variableName, scene.fogColor); + break; + case NodeMaterialSystemValues.DeltaTime: + effect.setFloat(variableName, scene.deltaTime / 1000.0); + break; + case NodeMaterialSystemValues.CameraParameters: + if (scene.activeCamera) { + effect.setFloat4(variableName, scene.getEngine().hasOriginBottomLeft ? -1 : 1, scene.activeCamera.minZ, scene.activeCamera.maxZ, 1 / scene.activeCamera.maxZ); + } + break; + case NodeMaterialSystemValues.MaterialAlpha: + effect.setFloat(variableName, material.alpha); + break; + } + return; + } + const value = this._valueCallback ? this._valueCallback() : this._storedValue; + if (value === null) { + return; + } + switch (this.type) { + case NodeMaterialBlockConnectionPointTypes.Float: + effect.setFloat(variableName, value); + break; + case NodeMaterialBlockConnectionPointTypes.Int: + effect.setInt(variableName, value); + break; + case NodeMaterialBlockConnectionPointTypes.Color3: + TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b); + if (this.convertToGammaSpace) { + TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0], scene.getEngine().useExactSrgbConversions); + } + if (this.convertToLinearSpace) { + TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0], scene.getEngine().useExactSrgbConversions); + } + effect.setColor3(variableName, TmpColors.Color3[0]); + break; + case NodeMaterialBlockConnectionPointTypes.Color4: + TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a); + if (this.convertToGammaSpace) { + TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0], scene.getEngine().useExactSrgbConversions); + } + if (this.convertToLinearSpace) { + TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0], scene.getEngine().useExactSrgbConversions); + } + effect.setDirectColor4(variableName, TmpColors.Color4[0]); + break; + case NodeMaterialBlockConnectionPointTypes.Vector2: + effect.setVector2(variableName, value); + break; + case NodeMaterialBlockConnectionPointTypes.Vector3: + effect.setVector3(variableName, value); + break; + case NodeMaterialBlockConnectionPointTypes.Vector4: + effect.setVector4(variableName, value); + break; + case NodeMaterialBlockConnectionPointTypes.Matrix: + effect.setMatrix(variableName, value); + break; + } + } + _buildBlock(state) { + super._buildBlock(state); + if (this.isUniform || this.isSystemValue) { + state.sharedData.inputBlocks.push(this); + } + this._emit(state); + } + _dumpPropertiesCode() { + const variableName = this._codeVariableName; + if (this.isAttribute) { + return super._dumpPropertiesCode() + `${variableName}.setAsAttribute("${this.name}");\n`; + } + if (this.isSystemValue) { + return super._dumpPropertiesCode() + `${variableName}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${NodeMaterialSystemValues[this._systemValue]});\n`; + } + if (this.isUniform) { + const codes = []; + let valueString = ""; + switch (this.type) { + case NodeMaterialBlockConnectionPointTypes.Float: + valueString = `${this.value}`; + break; + case NodeMaterialBlockConnectionPointTypes.Vector2: + valueString = `new BABYLON.Vector2(${this.value.x}, ${this.value.y})`; + break; + case NodeMaterialBlockConnectionPointTypes.Vector3: + valueString = `new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`; + break; + case NodeMaterialBlockConnectionPointTypes.Vector4: + valueString = `new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`; + break; + case NodeMaterialBlockConnectionPointTypes.Color3: + valueString = `new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`; + if (this.convertToGammaSpace) { + valueString += ".toGammaSpace()"; + } + if (this.convertToLinearSpace) { + valueString += ".toLinearSpace()"; + } + break; + case NodeMaterialBlockConnectionPointTypes.Color4: + valueString = `new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`; + if (this.convertToGammaSpace) { + valueString += ".toGammaSpace()"; + } + if (this.convertToLinearSpace) { + valueString += ".toLinearSpace()"; + } + break; + case NodeMaterialBlockConnectionPointTypes.Matrix: + valueString = `BABYLON.Matrix.FromArray([${this.value.m}])`; + break; + } + // Common Property "Value" + codes.push(`${variableName}.value = ${valueString}`); + // Float-Value-Specific Properties + if (this.type === NodeMaterialBlockConnectionPointTypes.Float) { + codes.push(`${variableName}.min = ${this.min}`, `${variableName}.max = ${this.max}`, `${variableName}.isBoolean = ${this.isBoolean}`, `${variableName}.matrixMode = ${this.matrixMode}`, `${variableName}.animationType = BABYLON.AnimatedInputBlockTypes.${AnimatedInputBlockTypes[this.animationType]}`); + } + // Common Property "Type" + codes.push(`${variableName}.isConstant = ${this.isConstant}`); + codes.push(""); + return super._dumpPropertiesCode() + codes.join(";\n"); + } + return super._dumpPropertiesCode(); + } + dispose() { + this.onValueChangedObservable.clear(); + super.dispose(); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.type = this.type; + serializationObject.mode = this._mode; + serializationObject.systemValue = this._systemValue; + serializationObject.animationType = this._animationType; + serializationObject.min = this.min; + serializationObject.max = this.max; + serializationObject.isBoolean = this.isBoolean; + serializationObject.matrixMode = this.matrixMode; + serializationObject.isConstant = this.isConstant; + serializationObject.groupInInspector = this.groupInInspector; + serializationObject.convertToGammaSpace = this.convertToGammaSpace; + serializationObject.convertToLinearSpace = this.convertToLinearSpace; + if (this._storedValue != null && this._mode === 0 /* NodeMaterialBlockConnectionPointMode.Uniform */) { + if (this._storedValue.asArray) { + serializationObject.valueType = "BABYLON." + this._storedValue.getClassName(); + serializationObject.value = this._storedValue.asArray(); + } + else { + serializationObject.valueType = "number"; + serializationObject.value = this._storedValue; + } + } + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + this._mode = serializationObject.mode; + super._deserialize(serializationObject, scene, rootUrl); + this._type = serializationObject.type; + this._systemValue = serializationObject.systemValue || serializationObject.wellKnownValue; + this._animationType = serializationObject.animationType; + this.min = serializationObject.min || 0; + this.max = serializationObject.max || 0; + this.isBoolean = !!serializationObject.isBoolean; + this.matrixMode = serializationObject.matrixMode || 0; + this.isConstant = !!serializationObject.isConstant; + this.groupInInspector = serializationObject.groupInInspector || ""; + this.convertToGammaSpace = !!serializationObject.convertToGammaSpace; + this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; + // Tangents back compat + if (serializationObject.name === "tangent" && + serializationObject.mode === 1 /* NodeMaterialBlockConnectionPointMode.Attribute */ && + serializationObject.type === NodeMaterialBlockConnectionPointTypes.Vector3) { + this._type = NodeMaterialBlockConnectionPointTypes.Vector4; + } + if (!serializationObject.valueType) { + return; + } + if (serializationObject.valueType === "number") { + this._storedValue = serializationObject.value; + } + else { + const valueType = GetClass(serializationObject.valueType); + if (valueType) { + this._storedValue = valueType.FromArray(serializationObject.value); + } + } + } +} +RegisterClass("BABYLON.InputBlock", InputBlock); + +/** + * Base block used as input for post process + */ +class CurrentScreenBlock extends NodeMaterialBlock { + /** + * Create a new CurrentScreenBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.VertexAndFragment); + this._samplerName = "textureSampler"; + /** + * Gets or sets a boolean indicating if content needs to be converted to gamma space + */ + this.convertToGammaSpace = false; + /** + * Gets or sets a boolean indicating if content needs to be converted to linear space + */ + this.convertToLinearSpace = false; + this._isUnique = false; + this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment); + this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral); + this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral); + this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + this._inputs[0]._prioritizeVertex = false; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "CurrentScreenBlock"; + } + /** + * Gets the uv input component + */ + get uv() { + return this._inputs[0]; + } + /** + * Gets the rgba output component + */ + get rgba() { + return this._outputs[0]; + } + /** + * Gets the rgb output component + */ + get rgb() { + return this._outputs[1]; + } + /** + * Gets the r output component + */ + get r() { + return this._outputs[2]; + } + /** + * Gets the g output component + */ + get g() { + return this._outputs[3]; + } + /** + * Gets the b output component + */ + get b() { + return this._outputs[4]; + } + /** + * Gets the a output component + */ + get a() { + return this._outputs[5]; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName(this._samplerName); + } + get target() { + if (!this.uv.isConnected) { + return NodeMaterialBlockTargets.VertexAndFragment; + } + if (this.uv.sourceBlock.isInput) { + return NodeMaterialBlockTargets.VertexAndFragment; + } + return NodeMaterialBlockTargets.Fragment; + } + prepareDefines(mesh, nodeMaterial, defines) { + defines.setValue(this._linearDefineName, this.convertToGammaSpace, true); + defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true); + } + isReady() { + if (this.texture && !this.texture.isReadyOrNotBlocking()) { + return false; + } + return true; + } + _injectVertexCode(state) { + const uvInput = this.uv; + if (uvInput.connectedPoint.ownerBlock.isInput) { + const uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock; + if (!uvInputOwnerBlock.isAttribute) { + state._emitUniformFromString(uvInput.associatedVariableName, NodeMaterialBlockConnectionPointTypes.Vector2); + } + } + this._mainUVName = "vMain" + uvInput.associatedVariableName; + state._emitVaryingFromString(this._mainUVName, NodeMaterialBlockConnectionPointTypes.Vector2); + state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\n`; + if (!this._outputs.some((o) => o.isConnectedInVertexShader)) { + return; + } + this._writeTextureRead(state, true); + for (const output of this._outputs) { + if (output.hasEndpoints) { + this._writeOutput(state, output, output.name, true); + } + } + } + _writeTextureRead(state, vertexMode = false) { + const uvInput = this.uv; + if (vertexMode) { + if (state.target === NodeMaterialBlockTargets.Fragment) { + return; + } + const textureReadFunc = state.shaderLanguage === 0 /* ShaderLanguage.GLSL */ + ? `texture2D(${this._samplerName},` + : `textureSampleLevel(${this._samplerName}, ${this._samplerName + `Sampler`},`; + const complement = state.shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? "" : ", 0"; + state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${textureReadFunc} ${uvInput.associatedVariableName}${complement});\n`; + return; + } + const textureReadFunc = state.shaderLanguage === 0 /* ShaderLanguage.GLSL */ + ? `texture2D(${this._samplerName},` + : `textureSample(${this._samplerName}, ${this._samplerName + `Sampler`},`; + if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { + state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${textureReadFunc} ${uvInput.associatedVariableName});\n`; + return; + } + state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${textureReadFunc} ${this._mainUVName});\n`; + } + _writeOutput(state, output, swizzle, vertexMode = false) { + if (vertexMode) { + if (state.target === NodeMaterialBlockTargets.Fragment) { + return; + } + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};\n`; + return; + } + if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};\n`; + return; + } + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};\n`; + state.compilationString += `#ifdef ${this._linearDefineName}\n`; + state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\n`; + state.compilationString += `#endif\n`; + state.compilationString += `#ifdef ${this._gammaDefineName}\n`; + state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\n`; + state.compilationString += `#endif\n`; + } + _buildBlock(state) { + super._buildBlock(state); + this._tempTextureRead = state._getFreeVariableName("tempTextureRead"); + if (state.sharedData.blockingBlocks.indexOf(this) < 0) { + state.sharedData.blockingBlocks.push(this); + } + if (state.sharedData.textureBlocks.indexOf(this) < 0) { + state.sharedData.textureBlocks.push(this); + } + if (state.sharedData.blocksWithDefines.indexOf(this) < 0) { + state.sharedData.blocksWithDefines.push(this); + } + if (state.target !== NodeMaterialBlockTargets.Fragment) { + // Vertex + state._emit2DSampler(this._samplerName); + this._injectVertexCode(state); + return; + } + // Fragment + if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) { + return; + } + state._emit2DSampler(this._samplerName); + this._linearDefineName = state._getFreeDefineName("ISLINEAR"); + this._gammaDefineName = state._getFreeDefineName("ISGAMMA"); + const comments = `//${this.name}`; + state._emitFunctionFromInclude("helperFunctions", comments); + this._writeTextureRead(state); + for (const output of this._outputs) { + if (output.hasEndpoints) { + this._writeOutput(state, output, output.name); + } + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.convertToGammaSpace = this.convertToGammaSpace; + serializationObject.convertToLinearSpace = this.convertToLinearSpace; + if (this.texture && !this.texture.isRenderTarget) { + serializationObject.texture = this.texture.serialize(); + } + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.convertToGammaSpace = serializationObject.convertToGammaSpace; + this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; + if (serializationObject.texture) { + rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; + this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl); + } + } +} +RegisterClass("BABYLON.CurrentScreenBlock", CurrentScreenBlock); + +/** + * Base block used for the particle texture + */ +class ParticleTextureBlock extends NodeMaterialBlock { + /** + * Create a new ParticleTextureBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this._samplerName = "diffuseSampler"; + /** + * Gets or sets a boolean indicating if content needs to be converted to gamma space + */ + this.convertToGammaSpace = false; + /** + * Gets or sets a boolean indicating if content needs to be converted to linear space + */ + this.convertToLinearSpace = false; + this._isUnique = false; + this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment); + this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral); + this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral); + this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ParticleTextureBlock"; + } + /** + * Gets the uv input component + */ + get uv() { + return this._inputs[0]; + } + /** + * Gets the rgba output component + */ + get rgba() { + return this._outputs[0]; + } + /** + * Gets the rgb output component + */ + get rgb() { + return this._outputs[1]; + } + /** + * Gets the r output component + */ + get r() { + return this._outputs[2]; + } + /** + * Gets the g output component + */ + get g() { + return this._outputs[3]; + } + /** + * Gets the b output component + */ + get b() { + return this._outputs[4]; + } + /** + * Gets the a output component + */ + get a() { + return this._outputs[5]; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("diffuseSampler"); + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.uv.isConnected) { + let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "particle_uv" && additionalFilteringInfo(b)); + if (!uvInput) { + uvInput = new InputBlock("uv"); + uvInput.setAsAttribute("particle_uv"); + } + uvInput.output.connectTo(this.uv); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + defines.setValue(this._linearDefineName, this.convertToGammaSpace, true); + defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true); + } + isReady() { + if (this.texture && !this.texture.isReadyOrNotBlocking()) { + return false; + } + return true; + } + _writeOutput(state, output, swizzle) { + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};\n`; + state.compilationString += `#ifdef ${this._linearDefineName}\n`; + state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\n`; + state.compilationString += `#endif\n`; + state.compilationString += `#ifdef ${this._gammaDefineName}\n`; + state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\n`; + state.compilationString += `#endif\n`; + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Vertex) { + return; + } + this._tempTextureRead = state._getFreeVariableName("tempTextureRead"); + state._emit2DSampler(this._samplerName); + state.sharedData.blockingBlocks.push(this); + state.sharedData.textureBlocks.push(this); + state.sharedData.blocksWithDefines.push(this); + this._linearDefineName = state._getFreeDefineName("ISLINEAR"); + this._gammaDefineName = state._getFreeDefineName("ISGAMMA"); + const comments = `//${this.name}`; + state._emitFunctionFromInclude("helperFunctions", comments); + state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${state._generateTextureSample(this.uv.associatedVariableName, this._samplerName)};\n`; + for (const output of this._outputs) { + if (output.hasEndpoints) { + this._writeOutput(state, output, output.name); + } + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.convertToGammaSpace = this.convertToGammaSpace; + serializationObject.convertToLinearSpace = this.convertToLinearSpace; + if (this.texture && !this.texture.isRenderTarget) { + serializationObject.texture = this.texture.serialize(); + } + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.convertToGammaSpace = serializationObject.convertToGammaSpace; + this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; + if (serializationObject.texture) { + rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; + this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl); + } + } +} +RegisterClass("BABYLON.ParticleTextureBlock", ParticleTextureBlock); + +/** + * Block used for the particle ramp gradient section + */ +class ParticleRampGradientBlock extends NodeMaterialBlock { + /** + * Create a new ParticleRampGradientBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this._isUnique = true; + this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment); + this.registerOutput("rampColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ParticleRampGradientBlock"; + } + /** + * Gets the color input component + */ + get color() { + return this._inputs[0]; + } + /** + * Gets the rampColor output component + */ + get rampColor() { + return this._outputs[0]; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("remapRanges"); + state._excludeVariableName("rampSampler"); + state._excludeVariableName("baseColor"); + state._excludeVariableName("alpha"); + state._excludeVariableName("remappedColorIndex"); + state._excludeVariableName("rampColor"); + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Vertex) { + return; + } + state._emit2DSampler("rampSampler", "RAMPGRADIENT"); + state._emitVaryingFromString("remapRanges", NodeMaterialBlockConnectionPointTypes.Vector4, "RAMPGRADIENT"); + const varyingString = state.shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? "" : "fragmentInputs."; + state.compilationString += ` + #ifdef RAMPGRADIENT + ${state._declareLocalVar("baseColor", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this.color.associatedVariableName}; + ${state._declareLocalVar("alpha", NodeMaterialBlockConnectionPointTypes.Float)} = ${this.color.associatedVariableName}.a; + + ${state._declareLocalVar("remappedColorIndex", NodeMaterialBlockConnectionPointTypes.Float)} = clamp((alpha - ${varyingString}remapRanges.x) / ${varyingString}remapRanges.y, 0.0, 1.0); + + ${state._declareLocalVar("rampColor", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${state._generateTextureSample("vec2(1.0 - remappedColorIndex, 0.)", "rampSampler")}; + + // Remapped alpha + ${state._declareOutput(this.rampColor)} = vec4${state.fSuffix}(baseColor.rgb * rampColor.rgb, clamp((alpha * rampColor.a - ${varyingString}remapRanges.z) / ${varyingString}remapRanges.w, 0.0, 1.0)); + #else + ${state._declareOutput(this.rampColor)} = ${this.color.associatedVariableName}; + #endif + `; + return this; + } +} +RegisterClass("BABYLON.ParticleRampGradientBlock", ParticleRampGradientBlock); + +/** + * Block used for the particle blend multiply section + */ +class ParticleBlendMultiplyBlock extends NodeMaterialBlock { + /** + * Create a new ParticleBlendMultiplyBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this._isUnique = true; + this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("alphaTexture", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("alphaColor", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); + this.registerOutput("blendColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ParticleBlendMultiplyBlock"; + } + /** + * Gets the color input component + */ + get color() { + return this._inputs[0]; + } + /** + * Gets the alphaTexture input component + */ + get alphaTexture() { + return this._inputs[1]; + } + /** + * Gets the alphaColor input component + */ + get alphaColor() { + return this._inputs[2]; + } + /** + * Gets the blendColor output component + */ + get blendColor() { + return this._outputs[0]; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("sourceAlpha"); + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Vertex) { + return; + } + state.compilationString += ` + #ifdef BLENDMULTIPLYMODE + ${state._declareOutput(this.blendColor)}; + ${state._declareLocalVar("sourceAlpha", NodeMaterialBlockConnectionPointTypes.Float)} = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; + ${this.blendColor.associatedVariableName} = vec4${state.fSuffix}(${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha), ${this.color.associatedVariableName}.a); + #else + ${state._declareOutput(this.blendColor)} = ${this.color.associatedVariableName}; + #endif + `; + return this; + } +} +RegisterClass("BABYLON.ParticleBlendMultiplyBlock", ParticleBlendMultiplyBlock); + +/** + * Block used to create a Vector2/3/4 out of individual inputs (one for each component) + */ +class VectorMergerBlock extends NodeMaterialBlock { + /** + * Create a new VectorMergerBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Gets or sets the swizzle for x (meaning which component to affect to the output.x) + */ + this.xSwizzle = "x"; + /** + * Gets or sets the swizzle for y (meaning which component to affect to the output.y) + */ + this.ySwizzle = "y"; + /** + * Gets or sets the swizzle for z (meaning which component to affect to the output.z) + */ + this.zSwizzle = "z"; + /** + * Gets or sets the swizzle for w (meaning which component to affect to the output.w) + */ + this.wSwizzle = "w"; + this.registerInput("xyzw ", NodeMaterialBlockConnectionPointTypes.Vector4, true); + this.registerInput("xyz ", NodeMaterialBlockConnectionPointTypes.Vector3, true); + this.registerInput("xy ", NodeMaterialBlockConnectionPointTypes.Vector2, true); + this.registerInput("zw ", NodeMaterialBlockConnectionPointTypes.Vector2, true); + this.registerInput("x", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("y", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("z", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("w", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerOutput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerOutput("zw", NodeMaterialBlockConnectionPointTypes.Vector2); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "VectorMergerBlock"; + } + /** + * Gets the xyzw component (input) + */ + get xyzwIn() { + return this._inputs[0]; + } + /** + * Gets the xyz component (input) + */ + get xyzIn() { + return this._inputs[1]; + } + /** + * Gets the xy component (input) + */ + get xyIn() { + return this._inputs[2]; + } + /** + * Gets the zw component (input) + */ + get zwIn() { + return this._inputs[3]; + } + /** + * Gets the x component (input) + */ + get x() { + return this._inputs[4]; + } + /** + * Gets the y component (input) + */ + get y() { + return this._inputs[5]; + } + /** + * Gets the z component (input) + */ + get z() { + return this._inputs[6]; + } + /** + * Gets the w component (input) + */ + get w() { + return this._inputs[7]; + } + /** + * Gets the xyzw component (output) + */ + get xyzw() { + return this._outputs[0]; + } + /** + * Gets the xyz component (output) + */ + get xyzOut() { + return this._outputs[1]; + } + /** + * Gets the xy component (output) + */ + get xyOut() { + return this._outputs[2]; + } + /** + * Gets the zw component (output) + */ + get zwOut() { + return this._outputs[3]; + } + /** + * Gets the xy component (output) + * @deprecated Please use xyOut instead. + */ + get xy() { + return this.xyOut; + } + /** + * Gets the xyz component (output) + * @deprecated Please use xyzOut instead. + */ + get xyz() { + return this.xyzOut; + } + _inputRename(name) { + if (name === "xyzw ") { + return "xyzwIn"; + } + if (name === "xyz ") { + return "xyzIn"; + } + if (name === "xy ") { + return "xyIn"; + } + if (name === "zw ") { + return "zwIn"; + } + return name; + } + _buildSwizzle(len) { + const swizzle = this.xSwizzle + this.ySwizzle + this.zSwizzle + this.wSwizzle; + return "." + swizzle.substring(0, len); + } + _buildBlock(state) { + super._buildBlock(state); + const xInput = this.x; + const yInput = this.y; + const zInput = this.z; + const wInput = this.w; + const xyInput = this.xyIn; + const zwInput = this.zwIn; + const xyzInput = this.xyzIn; + const xyzwInput = this.xyzwIn; + const v4Output = this._outputs[0]; + const v3Output = this._outputs[1]; + const v2Output = this._outputs[2]; + const v2CompOutput = this._outputs[3]; + const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4); + const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3); + const vec2 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector2); + if (xyzwInput.isConnected) { + if (v4Output.hasEndpoints) { + state.compilationString += state._declareOutput(v4Output) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(4)};\n`; + } + if (v3Output.hasEndpoints) { + state.compilationString += state._declareOutput(v3Output) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(3)};\n`; + } + if (v2Output.hasEndpoints) { + state.compilationString += state._declareOutput(v2Output) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(2)};\n`; + } + } + else if (xyzInput.isConnected) { + if (v4Output.hasEndpoints) { + state.compilationString += + state._declareOutput(v4Output) + + ` = ${vec4}(${xyzInput.associatedVariableName}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(4)};\n`; + } + if (v3Output.hasEndpoints) { + state.compilationString += state._declareOutput(v3Output) + ` = ${xyzInput.associatedVariableName}${this._buildSwizzle(3)};\n`; + } + if (v2Output.hasEndpoints) { + state.compilationString += state._declareOutput(v2Output) + ` = ${xyzInput.associatedVariableName}${this._buildSwizzle(2)};\n`; + } + } + else if (xyInput.isConnected) { + if (v4Output.hasEndpoints) { + if (zwInput.isConnected) { + state.compilationString += + state._declareOutput(v4Output) + ` = ${vec4}(${xyInput.associatedVariableName}, ${zwInput.associatedVariableName})${this._buildSwizzle(4)};\n`; + } + else { + state.compilationString += + state._declareOutput(v4Output) + + ` = ${vec4}(${xyInput.associatedVariableName}, ${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(4)};\n`; + } + } + if (v3Output.hasEndpoints) { + state.compilationString += + state._declareOutput(v3Output) + + ` = ${vec3}(${xyInput.associatedVariableName}, ${zInput.isConnected ? this._writeVariable(zInput) : "0.0"})${this._buildSwizzle(3)};\n`; + } + if (v2Output.hasEndpoints) { + state.compilationString += state._declareOutput(v2Output) + ` = ${xyInput.associatedVariableName}${this._buildSwizzle(2)};\n`; + } + if (v2CompOutput.hasEndpoints) { + if (zwInput.isConnected) { + state.compilationString += state._declareOutput(v2CompOutput) + ` = ${zwInput.associatedVariableName}${this._buildSwizzle(2)};\n`; + } + else { + state.compilationString += + state._declareOutput(v2CompOutput) + + ` = ${vec2}(${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(2)};\n`; + } + } + } + else { + if (v4Output.hasEndpoints) { + if (zwInput.isConnected) { + state.compilationString += + state._declareOutput(v4Output) + + ` = ${vec4}(${xInput.isConnected ? this._writeVariable(xInput) : "0.0"}, ${yInput.isConnected ? this._writeVariable(yInput) : "0.0"}, ${zwInput.associatedVariableName})${this._buildSwizzle(4)};\n`; + } + else { + state.compilationString += + state._declareOutput(v4Output) + + ` = ${vec4}(${xInput.isConnected ? this._writeVariable(xInput) : "0.0"}, ${yInput.isConnected ? this._writeVariable(yInput) : "0.0"}, ${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(4)};\n`; + } + } + if (v3Output.hasEndpoints) { + state.compilationString += + state._declareOutput(v3Output) + + ` = ${vec3}(${xInput.isConnected ? this._writeVariable(xInput) : "0.0"}, ${yInput.isConnected ? this._writeVariable(yInput) : "0.0"}, ${zInput.isConnected ? this._writeVariable(zInput) : "0.0"})${this._buildSwizzle(3)};\n`; + } + if (v2Output.hasEndpoints) { + state.compilationString += + state._declareOutput(v2Output) + + ` = ${vec2}(${xInput.isConnected ? this._writeVariable(xInput) : "0.0"}, ${yInput.isConnected ? this._writeVariable(yInput) : "0.0"})${this._buildSwizzle(2)};\n`; + } + if (v2CompOutput.hasEndpoints) { + if (zwInput.isConnected) { + state.compilationString += state._declareOutput(v2CompOutput) + ` = ${zwInput.associatedVariableName}${this._buildSwizzle(2)};\n`; + } + else { + state.compilationString += + state._declareOutput(v2CompOutput) + + ` = ${vec2}(${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(2)};\n`; + } + } + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.xSwizzle = this.xSwizzle; + serializationObject.ySwizzle = this.ySwizzle; + serializationObject.zSwizzle = this.zSwizzle; + serializationObject.wSwizzle = this.wSwizzle; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.xSwizzle = serializationObject.xSwizzle ?? "x"; + this.ySwizzle = serializationObject.ySwizzle ?? "y"; + this.zSwizzle = serializationObject.zSwizzle ?? "z"; + this.wSwizzle = serializationObject.wSwizzle ?? "w"; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\n`; + codeString += `${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\n`; + codeString += `${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\n`; + codeString += `${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\n`; + return codeString; + } +} +RegisterClass("BABYLON.VectorMergerBlock", VectorMergerBlock); + +/** + * Block used to remap a float from a range to a new one + */ +class RemapBlock extends NodeMaterialBlock { + /** + * Creates a new RemapBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Gets or sets the source range + */ + this.sourceRange = new Vector2(-1, 1); + /** + * Gets or sets the target range + */ + this.targetRange = new Vector2(0, 1); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("sourceMin", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("sourceMax", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("targetMin", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("targetMax", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "RemapBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the source min input component + */ + get sourceMin() { + return this._inputs[1]; + } + /** + * Gets the source max input component + */ + get sourceMax() { + return this._inputs[2]; + } + /** + * Gets the target min input component + */ + get targetMin() { + return this._inputs[3]; + } + /** + * Gets the target max input component + */ + get targetMax() { + return this._inputs[4]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const sourceMin = this.sourceMin.isConnected ? this.sourceMin.associatedVariableName : this._writeFloat(this.sourceRange.x); + const sourceMax = this.sourceMax.isConnected ? this.sourceMax.associatedVariableName : this._writeFloat(this.sourceRange.y); + const targetMin = this.targetMin.isConnected ? this.targetMin.associatedVariableName : this._writeFloat(this.targetRange.x); + const targetMax = this.targetMax.isConnected ? this.targetMax.associatedVariableName : this._writeFloat(this.targetRange.y); + state.compilationString += + state._declareOutput(output) + + ` = ${targetMin} + (${this._inputs[0].associatedVariableName} - ${sourceMin}) * (${targetMax} - ${targetMin}) / (${sourceMax} - ${sourceMin});\n`; + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\n`; + codeString += `${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.sourceRange = this.sourceRange.asArray(); + serializationObject.targetRange = this.targetRange.asArray(); + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.sourceRange = Vector2.FromArray(serializationObject.sourceRange); + this.targetRange = Vector2.FromArray(serializationObject.targetRange); + } +} +__decorate([ + editableInPropertyPage("From", 3 /* PropertyTypeForEdition.Vector2 */) +], RemapBlock.prototype, "sourceRange", void 0); +__decorate([ + editableInPropertyPage("To", 3 /* PropertyTypeForEdition.Vector2 */) +], RemapBlock.prototype, "targetRange", void 0); +RegisterClass("BABYLON.RemapBlock", RemapBlock); + +/** + * Block used to perform a mathematical operation on 2 values + */ +class BaseMathBlock extends NodeMaterialBlock { + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this.output._typeConnectionSource = this.left; + this._linkConnectionTypes(0, 1, true); + this.left.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this.right.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._connectionObservers = [ + this.left.onTypeChangedObservable.add(() => this._updateInputOutputTypes()), + this.right.onTypeChangedObservable.add(() => this._updateInputOutputTypes()), + ]; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _updateInputOutputTypes() { + // First update the output type with the initial assumption that we'll base it on the left input. + this.output._typeConnectionSource = this.left; + if (this.left.isConnected && this.right.isConnected) { + // Both inputs are connected, so we need to determine the output type based on the input types. + if (this.left.type === NodeMaterialBlockConnectionPointTypes.Int || + (this.left.type === NodeMaterialBlockConnectionPointTypes.Float && this.right.type !== NodeMaterialBlockConnectionPointTypes.Int)) { + this.output._typeConnectionSource = this.right; + } + } + else if (this.left.isConnected !== this.right.isConnected) { + // Only one input is connected, so we need to determine the output type based on the connected input. + this.output._typeConnectionSource = this.left.isConnected ? this.left : this.right; + } + // Next update the accepted connection point types for the inputs based on the current input connection state. + if (this.left.isConnected || this.right.isConnected) { + for (const [first, second] of [ + [this.left, this.right], + [this.right, this.left], + ]) { + // Always allow Ints and Floats. + first.acceptedConnectionPointTypes = [NodeMaterialBlockConnectionPointTypes.Int, NodeMaterialBlockConnectionPointTypes.Float]; + if (second.isConnected) { + // The same types as the connected input are always allowed. + first.acceptedConnectionPointTypes.push(second.type); + // If the other input is a scalar, then we also allow Vector/Color/Matrix types. + if (second.type === NodeMaterialBlockConnectionPointTypes.Int || second.type === NodeMaterialBlockConnectionPointTypes.Float) { + first.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockConnectionPointTypes.Matrix); + } + } + } + } + } + /** + * Release resources + */ + dispose() { + super.dispose(); + this._connectionObservers.forEach((observer) => observer.remove()); + this._connectionObservers.length = 0; + } +} + +/** + * Block used to multiply 2 values + */ +class MultiplyBlock extends BaseMathBlock { + /** + * Creates a new MultiplyBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MultiplyBlock"; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\n`; + return this; + } +} +RegisterClass("BABYLON.MultiplyBlock", MultiplyBlock); + +/** + * Enum used to define the material modes + */ +var NodeMaterialModes; +(function (NodeMaterialModes) { + /** Regular material */ + NodeMaterialModes[NodeMaterialModes["Material"] = 0] = "Material"; + /** For post process */ + NodeMaterialModes[NodeMaterialModes["PostProcess"] = 1] = "PostProcess"; + /** For particle system */ + NodeMaterialModes[NodeMaterialModes["Particle"] = 2] = "Particle"; + /** For procedural texture */ + NodeMaterialModes[NodeMaterialModes["ProceduralTexture"] = 3] = "ProceduralTexture"; + /** For gaussian splatting */ + NodeMaterialModes[NodeMaterialModes["GaussianSplatting"] = 4] = "GaussianSplatting"; +})(NodeMaterialModes || (NodeMaterialModes = {})); + +/** + * @internal + */ +class ImageProcessingConfigurationDefines extends MaterialDefines { + constructor() { + super(); + this.IMAGEPROCESSING = false; + this.VIGNETTE = false; + this.VIGNETTEBLENDMODEMULTIPLY = false; + this.VIGNETTEBLENDMODEOPAQUE = false; + this.TONEMAPPING = 0; + this.CONTRAST = false; + this.COLORCURVES = false; + this.COLORGRADING = false; + this.COLORGRADING3D = false; + this.SAMPLER3DGREENDEPTH = false; + this.SAMPLER3DBGRMAP = false; + this.DITHER = false; + this.IMAGEPROCESSINGPOSTPROCESS = false; + this.EXPOSURE = false; + this.SKIPFINALCOLORCLAMP = false; + this.rebuild(); + } +} + +/** + * This represents the base class for particle system in Babylon. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function. + * @example https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro + */ +class BaseParticleSystem { + /** + * Gets or sets a texture used to add random noise to particle positions + */ + get noiseTexture() { + return this._noiseTexture; + } + set noiseTexture(value) { + if (this._noiseTexture === value) { + return; + } + this._noiseTexture = value; + this._reset(); + } + /** + * Gets or sets whether an animation sprite sheet is enabled or not on the particle system + */ + get isAnimationSheetEnabled() { + return this._isAnimationSheetEnabled; + } + set isAnimationSheetEnabled(value) { + if (this._isAnimationSheetEnabled == value) { + return; + } + this._isAnimationSheetEnabled = value; + this._reset(); + } + /** + * Gets or sets a boolean enabling the use of logarithmic depth buffers, which is good for wide depth buffers. + */ + get useLogarithmicDepth() { + return this._useLogarithmicDepth; + } + set useLogarithmicDepth(value) { + this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported; + } + /** + * Get hosting scene + * @returns the scene + */ + getScene() { + return this._scene; + } + _hasTargetStopDurationDependantGradient() { + return ((this._startSizeGradients && this._startSizeGradients.length > 0) || + (this._emitRateGradients && this._emitRateGradients.length > 0) || + (this._lifeTimeGradients && this._lifeTimeGradients.length > 0)); + } + /** + * Gets the current list of drag gradients. + * You must use addDragGradient and removeDragGradient to update this list + * @returns the list of drag gradients + */ + getDragGradients() { + return this._dragGradients; + } + /** + * Gets the current list of limit velocity gradients. + * You must use addLimitVelocityGradient and removeLimitVelocityGradient to update this list + * @returns the list of limit velocity gradients + */ + getLimitVelocityGradients() { + return this._limitVelocityGradients; + } + /** + * Gets the current list of color gradients. + * You must use addColorGradient and removeColorGradient to update this list + * @returns the list of color gradients + */ + getColorGradients() { + return this._colorGradients; + } + /** + * Gets the current list of size gradients. + * You must use addSizeGradient and removeSizeGradient to update this list + * @returns the list of size gradients + */ + getSizeGradients() { + return this._sizeGradients; + } + /** + * Gets the current list of color remap gradients. + * You must use addColorRemapGradient and removeColorRemapGradient to update this list + * @returns the list of color remap gradients + */ + getColorRemapGradients() { + return this._colorRemapGradients; + } + /** + * Gets the current list of alpha remap gradients. + * You must use addAlphaRemapGradient and removeAlphaRemapGradient to update this list + * @returns the list of alpha remap gradients + */ + getAlphaRemapGradients() { + return this._alphaRemapGradients; + } + /** + * Gets the current list of life time gradients. + * You must use addLifeTimeGradient and removeLifeTimeGradient to update this list + * @returns the list of life time gradients + */ + getLifeTimeGradients() { + return this._lifeTimeGradients; + } + /** + * Gets the current list of angular speed gradients. + * You must use addAngularSpeedGradient and removeAngularSpeedGradient to update this list + * @returns the list of angular speed gradients + */ + getAngularSpeedGradients() { + return this._angularSpeedGradients; + } + /** + * Gets the current list of velocity gradients. + * You must use addVelocityGradient and removeVelocityGradient to update this list + * @returns the list of velocity gradients + */ + getVelocityGradients() { + return this._velocityGradients; + } + /** + * Gets the current list of start size gradients. + * You must use addStartSizeGradient and removeStartSizeGradient to update this list + * @returns the list of start size gradients + */ + getStartSizeGradients() { + return this._startSizeGradients; + } + /** + * Gets the current list of emit rate gradients. + * You must use addEmitRateGradient and removeEmitRateGradient to update this list + * @returns the list of emit rate gradients + */ + getEmitRateGradients() { + return this._emitRateGradients; + } + /** + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + * This only works when particleEmitterTyps is a BoxParticleEmitter + */ + get direction1() { + if (this.particleEmitterType.direction1) { + return this.particleEmitterType.direction1; + } + return Vector3.Zero(); + } + set direction1(value) { + if (this.particleEmitterType.direction1) { + this.particleEmitterType.direction1 = value; + } + } + /** + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + * This only works when particleEmitterTyps is a BoxParticleEmitter + */ + get direction2() { + if (this.particleEmitterType.direction2) { + return this.particleEmitterType.direction2; + } + return Vector3.Zero(); + } + set direction2(value) { + if (this.particleEmitterType.direction2) { + this.particleEmitterType.direction2 = value; + } + } + /** + * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + * This only works when particleEmitterTyps is a BoxParticleEmitter + */ + get minEmitBox() { + if (this.particleEmitterType.minEmitBox) { + return this.particleEmitterType.minEmitBox; + } + return Vector3.Zero(); + } + set minEmitBox(value) { + if (this.particleEmitterType.minEmitBox) { + this.particleEmitterType.minEmitBox = value; + } + } + /** + * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + * This only works when particleEmitterTyps is a BoxParticleEmitter + */ + get maxEmitBox() { + if (this.particleEmitterType.maxEmitBox) { + return this.particleEmitterType.maxEmitBox; + } + return Vector3.Zero(); + } + set maxEmitBox(value) { + if (this.particleEmitterType.maxEmitBox) { + this.particleEmitterType.maxEmitBox = value; + } + } + /** + * Gets or sets the billboard mode to use when isBillboardBased = true. + * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED + */ + get billboardMode() { + return this._billboardMode; + } + set billboardMode(value) { + if (this._billboardMode === value) { + return; + } + this._billboardMode = value; + this._reset(); + } + /** + * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction + */ + get isBillboardBased() { + return this._isBillboardBased; + } + set isBillboardBased(value) { + if (this._isBillboardBased === value) { + return; + } + this._isBillboardBased = value; + this._reset(); + } + /** + * Gets the image processing configuration used either in this material. + */ + get imageProcessingConfiguration() { + return this._imageProcessingConfiguration; + } + /** + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ + set imageProcessingConfiguration(value) { + this._attachImageProcessingConfiguration(value); + } + /** + * Attaches a new image processing configuration to the Standard Material. + * @param configuration + */ + _attachImageProcessingConfiguration(configuration) { + if (configuration === this._imageProcessingConfiguration) { + return; + } + // Pick the scene configuration if needed. + if (!configuration && this._scene) { + this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration; + } + else { + this._imageProcessingConfiguration = configuration; + } + } + /** @internal */ + _reset() { } + /** + * @internal + */ + _removeGradientAndTexture(gradient, gradients, texture) { + if (!gradients) { + return this; + } + let index = 0; + for (const valueGradient of gradients) { + if (valueGradient.gradient === gradient) { + gradients.splice(index, 1); + break; + } + index++; + } + if (texture) { + texture.dispose(); + } + return this; + } + /** + * Instantiates a particle system. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * @param name The name of the particle system + */ + constructor(name) { + /** + * List of animations used by the particle system. + */ + this.animations = []; + /** + * The rendering group used by the Particle system to chose when to render. + */ + this.renderingGroupId = 0; + /** + * The emitter represents the Mesh or position we are attaching the particle system to. + */ + this.emitter = Vector3.Zero(); + /** + * The maximum number of particles to emit per frame + */ + this.emitRate = 10; + /** + * If you want to launch only a few particles at once, that can be done, as well. + */ + this.manualEmitCount = -1; + /** + * The overall motion speed (0.01 is default update speed, faster updates = faster animation) + */ + this.updateSpeed = 0.01; + /** + * The amount of time the particle system is running (depends of the overall update speed). + */ + this.targetStopDuration = 0; + /** + * Specifies whether the particle system will be disposed once it reaches the end of the animation. + */ + this.disposeOnStop = false; + /** + * Minimum power of emitting particles. + */ + this.minEmitPower = 1; + /** + * Maximum power of emitting particles. + */ + this.maxEmitPower = 1; + /** + * Minimum life time of emitting particles. + */ + this.minLifeTime = 1; + /** + * Maximum life time of emitting particles. + */ + this.maxLifeTime = 1; + /** + * Minimum Size of emitting particles. + */ + this.minSize = 1; + /** + * Maximum Size of emitting particles. + */ + this.maxSize = 1; + /** + * Minimum scale of emitting particles on X axis. + */ + this.minScaleX = 1; + /** + * Maximum scale of emitting particles on X axis. + */ + this.maxScaleX = 1; + /** + * Minimum scale of emitting particles on Y axis. + */ + this.minScaleY = 1; + /** + * Maximum scale of emitting particles on Y axis. + */ + this.maxScaleY = 1; + /** + * Gets or sets the minimal initial rotation in radians. + */ + this.minInitialRotation = 0; + /** + * Gets or sets the maximal initial rotation in radians. + */ + this.maxInitialRotation = 0; + /** + * Minimum angular speed of emitting particles (Z-axis rotation for each particle). + */ + this.minAngularSpeed = 0; + /** + * Maximum angular speed of emitting particles (Z-axis rotation for each particle). + */ + this.maxAngularSpeed = 0; + /** + * The layer mask we are rendering the particles through. + */ + this.layerMask = 0x0fffffff; + /** + * This can help using your own shader to render the particle system. + * The according effect will be created + */ + this.customShader = null; + /** + * By default particle system starts as soon as they are created. This prevents the + * automatic start to happen and let you decide when to start emitting particles. + */ + this.preventAutoStart = false; + /** + * Gets or sets a boolean indicating that this particle system will allow fog to be rendered on it (false by default) + */ + this.applyFog = false; + /** @internal */ + this._wasDispatched = false; + this._rootUrl = ""; + /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ + this.noiseStrength = new Vector3(10, 10, 10); + /** + * Callback triggered when the particle animation is ending. + */ + this.onAnimationEnd = null; + /** + * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD. + */ + this.blendMode = BaseParticleSystem.BLENDMODE_ONEONE; + /** + * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls + * to override the particles. + */ + this.forceDepthWrite = false; + /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */ + this.preWarmCycles = 0; + /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ + this.preWarmStepOffset = 1; + /** + * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime) + */ + this.spriteCellChangeSpeed = 1; + /** + * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display + */ + this.startSpriteCellID = 0; + /** + * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display + */ + this.endSpriteCellID = 0; + /** + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use + */ + this.spriteCellWidth = 0; + /** + * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use + */ + this.spriteCellHeight = 0; + /** + * If using a spritesheet (isAnimationSheetEnabled), defines wether the sprite animation is looping + */ + this.spriteCellLoop = true; + /** + * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID + */ + this.spriteRandomStartCell = false; + /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ + this.translationPivot = new Vector2(0, 0); + /** + * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called + */ + this.beginAnimationOnStart = false; + /** + * Gets or sets the frame to start the animation from when beginAnimationOnStart is true + */ + this.beginAnimationFrom = 0; + /** + * Gets or sets the frame to end the animation on when beginAnimationOnStart is true + */ + this.beginAnimationTo = 60; + /** + * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true + */ + this.beginAnimationLoop = false; + /** + * Gets or sets a world offset applied to all particles + */ + this.worldOffset = new Vector3(0, 0, 0); + this._useLogarithmicDepth = false; + /** + * You can use gravity if you want to give an orientation to your particles. + */ + this.gravity = Vector3.Zero(); + this._colorGradients = null; + this._sizeGradients = null; + this._lifeTimeGradients = null; + this._angularSpeedGradients = null; + this._velocityGradients = null; + this._limitVelocityGradients = null; + this._dragGradients = null; + this._emitRateGradients = null; + this._startSizeGradients = null; + this._rampGradients = null; + this._colorRemapGradients = null; + this._alphaRemapGradients = null; + /** + * Defines the delay in milliseconds before starting the system (0 by default) + */ + this.startDelay = 0; + /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */ + this.limitVelocityDamping = 0.4; + /** + * Random color of each particle after it has been emitted, between color1 and color2 vectors + */ + this.color1 = new Color4(1.0, 1.0, 1.0, 1.0); + /** + * Random color of each particle after it has been emitted, between color1 and color2 vectors + */ + this.color2 = new Color4(1.0, 1.0, 1.0, 1.0); + /** + * Color the particle will have at the end of its lifetime + */ + this.colorDead = new Color4(0, 0, 0, 1.0); + /** + * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel + */ + this.textureMask = new Color4(1.0, 1.0, 1.0, 1.0); + /** @internal */ + this._isSubEmitter = false; + /** @internal */ + this._billboardMode = 7; + /** @internal */ + this._isBillboardBased = true; + /** + * Local cache of defines for image processing. + */ + this._imageProcessingConfigurationDefines = new ImageProcessingConfigurationDefines(); + this.id = name; + this.name = name; + } + /** + * Creates a Point Emitter for the particle system (emits directly from the emitter position) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + */ + createPointEmitter(direction1, direction2) { + throw new Error("Method not implemented."); + } + /** + * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) + * @param radius The radius of the hemisphere to emit from + * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + */ + createHemisphericEmitter(radius = 1, radiusRange = 1) { + throw new Error("Method not implemented."); + } + /** + * Creates a Sphere Emitter for the particle system (emits along the sphere radius) + * @param radius The radius of the sphere to emit from + * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + */ + createSphereEmitter(radius = 1, radiusRange = 1) { + throw new Error("Method not implemented."); + } + /** + * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) + * @param radius The radius of the sphere to emit from + * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere + * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere + */ + createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + throw new Error("Method not implemented."); + } + /** + * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position) + * @param radius The radius of the emission cylinder + * @param height The height of the emission cylinder + * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius + * @param directionRandomizer How much to randomize the particle direction [0-1] + */ + createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) { + throw new Error("Method not implemented."); + } + /** + * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2) + * @param radius The radius of the cylinder to emit from + * @param height The height of the emission cylinder + * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder + * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder + */ + createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + throw new Error("Method not implemented."); + } + /** + * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) + * @param radius The radius of the cone to emit from + * @param angle The base angle of the cone + */ + createConeEmitter(radius = 1, angle = Math.PI / 4) { + throw new Error("Method not implemented."); + } + createDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + throw new Error("Method not implemented."); + } + /** + * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox + * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox + */ + createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) { + throw new Error("Method not implemented."); + } +} +/** + * Source color is added to the destination color without alpha affecting the result + */ +BaseParticleSystem.BLENDMODE_ONEONE = 0; +/** + * Blend current color and particle color using particle’s alpha + */ +BaseParticleSystem.BLENDMODE_STANDARD = 1; +/** + * Add current color and particle color multiplied by particle’s alpha + */ +BaseParticleSystem.BLENDMODE_ADD = 2; +/** + * Multiply current color with particle color + */ +BaseParticleSystem.BLENDMODE_MULTIPLY = 3; +/** + * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha + */ +BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4; +// Register Class Name +RegisterClass("BABYLON.BaseParticleSystem", BaseParticleSystem); + +/** + * Block used to expand a Color3/4 into 4 outputs (one for each component) + */ +class ColorSplitterBlock extends NodeMaterialBlock { + /** + * Create a new ColorSplitterBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, true); + this.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, true); + this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3); + this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float); + this.inputsAreExclusive = true; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ColorSplitterBlock"; + } + /** + * Gets the rgba component (input) + */ + get rgba() { + return this._inputs[0]; + } + /** + * Gets the rgb component (input) + */ + get rgbIn() { + return this._inputs[1]; + } + /** + * Gets the rgb component (output) + */ + get rgbOut() { + return this._outputs[0]; + } + /** + * Gets the r component (output) + */ + get r() { + return this._outputs[1]; + } + /** + * Gets the g component (output) + */ + get g() { + return this._outputs[2]; + } + /** + * Gets the b component (output) + */ + get b() { + return this._outputs[3]; + } + /** + * Gets the a component (output) + */ + get a() { + return this._outputs[4]; + } + _inputRename(name) { + if (name === "rgb ") { + return "rgbIn"; + } + return name; + } + _outputRename(name) { + if (name === "rgb") { + return "rgbOut"; + } + return name; + } + _buildBlock(state) { + super._buildBlock(state); + const input = this.rgba.isConnected ? this.rgba : this.rgbIn; + if (!input.isConnected) { + return; + } + const rgbOutput = this._outputs[0]; + const rOutput = this._outputs[1]; + const gOutput = this._outputs[2]; + const bOutput = this._outputs[3]; + const aOutput = this._outputs[4]; + if (rgbOutput.hasEndpoints) { + state.compilationString += state._declareOutput(rgbOutput) + ` = ${input.associatedVariableName}.rgb;\n`; + } + if (rOutput.hasEndpoints) { + state.compilationString += state._declareOutput(rOutput) + ` = ${input.associatedVariableName}.r;\n`; + } + if (gOutput.hasEndpoints) { + state.compilationString += state._declareOutput(gOutput) + ` = ${input.associatedVariableName}.g;\n`; + } + if (bOutput.hasEndpoints) { + state.compilationString += state._declareOutput(bOutput) + ` = ${input.associatedVariableName}.b;\n`; + } + if (aOutput.hasEndpoints) { + state.compilationString += state._declareOutput(aOutput) + ` = ${input.associatedVariableName}.a;\n`; + } + return this; + } +} +RegisterClass("BABYLON.ColorSplitterBlock", ColorSplitterBlock); + +/** + * Defines the Procedural Texture scene component responsible to manage any Procedural Texture + * in a given scene. + */ +class ProceduralTextureSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_PROCEDURALTEXTURE; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do here. + } + /** + * Disposes the component and the associated resources. + */ + dispose() { + // Nothing to do here. + } + _beforeClear() { + if (this.scene.proceduralTexturesEnabled) { + Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0); + for (let proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) { + const proceduralTexture = this.scene.proceduralTextures[proceduralIndex]; + if (proceduralTexture._shouldRender()) { + proceduralTexture.render(); + } + } + Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0); + } + } +} + +/** + * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes calmpler' images. + * This is the base class of any Procedural texture and contains most of the shareable code. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures + */ +class ProceduralTexture extends Texture { + /** + * Gets the shader language type used to generate vertex and fragment source code. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Instantiates a new procedural texture. + * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images. + * This is the base class of any Procedural texture and contains most of the shareable code. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures + * @param name Define the name of the texture + * @param size Define the size of the texture to create + * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later: + * * object: \{ fragmentElement: "fragmentShaderCode" \}, used with shader code in script tags + * * object: \{ fragmentSource: "fragment shader code string" \}, the string contains the shader code + * * string: the string contains a name "XXX" to lookup in Effect.ShadersStore["XXXFragmentShader"] + * @param scene Define the scene the texture belongs to + * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture + * @param generateMipMaps Define if the texture should creates mip maps or not + * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube) + * @param textureType The FBO internal texture type + */ + constructor(name, size, fragment, scene, fallbackTexture = null, generateMipMaps = true, isCube = false, textureType = 0) { + super(null, scene, !generateMipMaps); + /** + * Define if the texture is enabled or not (disabled texture will not render) + */ + this.isEnabled = true; + /** + * Define if the texture must be cleared before rendering (default is true) + */ + this.autoClear = true; + /** + * Event raised when the texture is generated + */ + this.onGeneratedObservable = new Observable(); + /** + * Event raised before the texture is generated + */ + this.onBeforeGenerationObservable = new Observable(); + /** + * Gets or sets the node material used to create this texture (null if the texture was manually created) + */ + this.nodeMaterialSource = null; + /** + * Define the list of custom preprocessor defines used in the shader + */ + this.defines = ""; + /** @internal */ + this._textures = {}; + this._currentRefreshId = -1; + this._frameId = -1; + this._refreshRate = 1; + this._vertexBuffers = {}; + this._uniforms = new Array(); + this._samplers = new Array(); + this._floats = {}; + this._ints = {}; + this._floatsArrays = {}; + this._colors3 = {}; + this._colors4 = {}; + this._vectors2 = {}; + this._vectors3 = {}; + this._vectors4 = {}; + this._matrices = {}; + this._fallbackTextureUsed = false; + this._cachedDefines = null; + this._contentUpdateId = -1; + this._rtWrapper = null; + if (fallbackTexture !== null && !(fallbackTexture instanceof Texture)) { + this._options = fallbackTexture; + this._fallbackTexture = fallbackTexture.fallbackTexture ?? null; + } + else { + this._options = {}; + this._fallbackTexture = fallbackTexture; + } + this._shaderLanguage = this._options.shaderLanguage ?? 0 /* ShaderLanguage.GLSL */; + scene = this.getScene() || EngineStore.LastCreatedScene; + let component = scene._getComponent(SceneComponentConstants.NAME_PROCEDURALTEXTURE); + if (!component) { + component = new ProceduralTextureSceneComponent(scene); + scene._addComponent(component); + } + scene.proceduralTextures.push(this); + this._fullEngine = scene.getEngine(); + this.name = name; + this.isRenderTarget = true; + this._size = size; + this._textureType = textureType; + this._generateMipMaps = generateMipMaps; + this._drawWrapper = new DrawWrapper(this._fullEngine); + this.setFragment(fragment); + const rtWrapper = this._createRtWrapper(isCube, size, generateMipMaps, textureType); + this._texture = rtWrapper.texture; + // VBO + const vertices = []; + vertices.push(1, 1); + vertices.push(-1, 1); + vertices.push(-1, -1); + vertices.push(1, -1); + this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(this._fullEngine, vertices, VertexBuffer.PositionKind, false, false, 2); + this._createIndexBuffer(); + } + _createRtWrapper(isCube, size, generateMipMaps, textureType) { + if (isCube) { + this._rtWrapper = this._fullEngine.createRenderTargetCubeTexture(size, { + generateMipMaps: generateMipMaps, + generateDepthBuffer: false, + generateStencilBuffer: false, + type: textureType, + ...this._options, + }); + this.setFloat("face", 0); + } + else { + this._rtWrapper = this._fullEngine.createRenderTargetTexture(size, { + generateMipMaps: generateMipMaps, + generateDepthBuffer: false, + generateStencilBuffer: false, + type: textureType, + ...this._options, + }); + if (this._rtWrapper.is3D) { + this.setFloat("layer", 0); + this.setInt("layerNum", 0); + } + } + return this._rtWrapper; + } + /** + * The effect that is created when initializing the post process. + * @returns The created effect corresponding the postprocess. + */ + getEffect() { + return this._drawWrapper.effect; + } + /** + * @internal + */ + _setEffect(effect) { + this._drawWrapper.effect = effect; + } + /** + * Gets texture content (Use this function wisely as reading from a texture can be slow) + * @returns an ArrayBufferView promise (Uint8Array or Float32Array) + */ + getContent() { + if (this._contentData && this._frameId === this._contentUpdateId) { + return this._contentData; + } + if (this._contentData) { + this._contentData.then((buffer) => { + this._contentData = this.readPixels(0, 0, buffer); + this._contentUpdateId = this._frameId; + }); + } + else { + this._contentData = this.readPixels(0, 0); + this._contentUpdateId = this._frameId; + } + return this._contentData; + } + _createIndexBuffer() { + const engine = this._fullEngine; + // Indices + const indices = []; + indices.push(0); + indices.push(1); + indices.push(2); + indices.push(0); + indices.push(2); + indices.push(3); + this._indexBuffer = engine.createIndexBuffer(indices); + } + /** @internal */ + _rebuild() { + const vb = this._vertexBuffers[VertexBuffer.PositionKind]; + if (vb) { + vb._rebuild(); + } + this._createIndexBuffer(); + if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) { + this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE; + } + } + /** + * Resets the texture in order to recreate its associated resources. + * This can be called in case of context loss or if you change the shader code and need to regenerate the texture with the new code + */ + reset() { + this._drawWrapper.effect?.dispose(); + this._drawWrapper.effect = null; + this._cachedDefines = null; + } + _getDefines() { + return this.defines; + } + /** + * Executes a function when the texture will be ready to be drawn. + * @param func The callback to be used. + */ + executeWhenReady(func) { + if (this.isReady()) { + func(this); + return; + } + const effect = this.getEffect(); + if (effect) { + effect.executeWhenCompiled(() => { + func(this); + }); + } + } + /** + * Is the texture ready to be used ? (rendered at least once) + * @returns true if ready, otherwise, false. + */ + isReady() { + const engine = this._fullEngine; + if (this.nodeMaterialSource) { + return this._drawWrapper.effect.isReady(); + } + if (!this._fragment) { + return false; + } + if (this._fallbackTextureUsed) { + return true; + } + if (!this._texture) { + return false; + } + const defines = this._getDefines(); + if (this._drawWrapper.effect && defines === this._cachedDefines && this._drawWrapper.effect.isReady()) { + return true; + } + const shaders = { + vertex: "procedural", + fragmentElement: this._fragment.fragmentElement, + fragmentSource: this._fragment.fragmentSource, + fragment: typeof this._fragment === "string" ? this._fragment : undefined, + }; + if (this._cachedDefines !== defines) { + this._cachedDefines = defines; + this._drawWrapper.effect = engine.createEffect(shaders, [VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, () => { + this._rtWrapper?.dispose(); + this._rtWrapper = this._texture = null; + if (this._fallbackTexture) { + this._texture = this._fallbackTexture._texture; + if (this._texture) { + this._texture.incrementReferences(); + } + } + this._fallbackTextureUsed = true; + }, undefined, this._shaderLanguage, async () => { + if (this._options.extraInitializationsAsync) { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => procedural_vertex$1), this._options.extraInitializationsAsync()]); + } + else { + await Promise.all([Promise.resolve().then(() => procedural_vertex), this._options.extraInitializationsAsync()]); + } + } + else { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => procedural_vertex$1); + } + else { + await Promise.resolve().then(() => procedural_vertex); + } + } + }); + } + return this._drawWrapper.effect.isReady(); + } + /** + * Resets the refresh counter of the texture and start bak from scratch. + * Could be useful to regenerate the texture if it is setup to render only once. + */ + resetRefreshCounter() { + this._currentRefreshId = -1; + } + /** + * Set the fragment shader to use in order to render the texture. + * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property. + */ + setFragment(fragment) { + this._fragment = fragment; + } + /** + * Define the refresh rate of the texture or the rendering frequency. + * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... + */ + get refreshRate() { + return this._refreshRate; + } + set refreshRate(value) { + this._refreshRate = value; + this.resetRefreshCounter(); + } + /** @internal */ + _shouldRender() { + if (!this.isEnabled || !this.isReady() || !this._texture) { + if (this._texture) { + this._texture.isReady = false; + } + return false; + } + if (this._fallbackTextureUsed) { + return false; + } + if (this._currentRefreshId === -1) { + // At least render once + this._currentRefreshId = 1; + this._frameId++; + return true; + } + if (this.refreshRate === this._currentRefreshId) { + this._currentRefreshId = 1; + this._frameId++; + return true; + } + this._currentRefreshId++; + return false; + } + /** + * Get the size the texture is rendering at. + * @returns the size (on cube texture it is always squared) + */ + getRenderSize() { + return this._size; + } + /** + * Resize the texture to new value. + * @param size Define the new size the texture should have + * @param generateMipMaps Define whether the new texture should create mip maps + */ + resize(size, generateMipMaps) { + if (this._fallbackTextureUsed || !this._rtWrapper || !this._texture) { + return; + } + const isCube = this._texture.isCube; + this._rtWrapper.dispose(); + const rtWrapper = this._createRtWrapper(isCube, size, generateMipMaps, this._textureType); + this._texture = rtWrapper.texture; + // Update properties + this._size = size; + this._generateMipMaps = generateMipMaps; + } + _checkUniform(uniformName) { + if (this._uniforms.indexOf(uniformName) === -1) { + this._uniforms.push(uniformName); + } + } + /** + * Set a texture in the shader program used to render. + * @param name Define the name of the uniform samplers as defined in the shader + * @param texture Define the texture to bind to this sampler + * @returns the texture itself allowing "fluent" like uniform updates + */ + setTexture(name, texture) { + if (this._samplers.indexOf(name) === -1) { + this._samplers.push(name); + } + this._textures[name] = texture; + return this; + } + /** + * Set a float in the shader. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the texture itself allowing "fluent" like uniform updates + */ + setFloat(name, value) { + this._checkUniform(name); + this._floats[name] = value; + return this; + } + /** + * Set a int in the shader. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the texture itself allowing "fluent" like uniform updates + */ + setInt(name, value) { + this._checkUniform(name); + this._ints[name] = value; + return this; + } + /** + * Set an array of floats in the shader. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the texture itself allowing "fluent" like uniform updates + */ + setFloats(name, value) { + this._checkUniform(name); + this._floatsArrays[name] = value; + return this; + } + /** + * Set a vec3 in the shader from a Color3. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the texture itself allowing "fluent" like uniform updates + */ + setColor3(name, value) { + this._checkUniform(name); + this._colors3[name] = value; + return this; + } + /** + * Set a vec4 in the shader from a Color4. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the texture itself allowing "fluent" like uniform updates + */ + setColor4(name, value) { + this._checkUniform(name); + this._colors4[name] = value; + return this; + } + /** + * Set a vec2 in the shader from a Vector2. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the texture itself allowing "fluent" like uniform updates + */ + setVector2(name, value) { + this._checkUniform(name); + this._vectors2[name] = value; + return this; + } + /** + * Set a vec3 in the shader from a Vector3. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the texture itself allowing "fluent" like uniform updates + */ + setVector3(name, value) { + this._checkUniform(name); + this._vectors3[name] = value; + return this; + } + /** + * Set a vec4 in the shader from a Vector4. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the texture itself allowing "fluent" like uniform updates + */ + setVector4(name, value) { + this._checkUniform(name); + this._vectors4[name] = value; + return this; + } + /** + * Set a mat4 in the shader from a MAtrix. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @returns the texture itself allowing "fluent" like uniform updates + */ + setMatrix(name, value) { + this._checkUniform(name); + this._matrices[name] = value; + return this; + } + /** + * Render the texture to its associated render target. + * @param useCameraPostProcess Define if camera post process should be applied to the texture + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + render(useCameraPostProcess) { + const scene = this.getScene(); + if (!scene) { + return; + } + const engine = this._fullEngine; + // Render + engine.enableEffect(this._drawWrapper); + this.onBeforeGenerationObservable.notifyObservers(this); + engine.setState(false); + if (!this.nodeMaterialSource) { + // Texture + for (const name in this._textures) { + this._drawWrapper.effect.setTexture(name, this._textures[name]); + } + // Float + for (const name in this._ints) { + this._drawWrapper.effect.setInt(name, this._ints[name]); + } + // Float + for (const name in this._floats) { + this._drawWrapper.effect.setFloat(name, this._floats[name]); + } + // Floats + for (const name in this._floatsArrays) { + this._drawWrapper.effect.setArray(name, this._floatsArrays[name]); + } + // Color3 + for (const name in this._colors3) { + this._drawWrapper.effect.setColor3(name, this._colors3[name]); + } + // Color4 + for (const name in this._colors4) { + const color = this._colors4[name]; + this._drawWrapper.effect.setFloat4(name, color.r, color.g, color.b, color.a); + } + // Vector2 + for (const name in this._vectors2) { + this._drawWrapper.effect.setVector2(name, this._vectors2[name]); + } + // Vector3 + for (const name in this._vectors3) { + this._drawWrapper.effect.setVector3(name, this._vectors3[name]); + } + // Vector4 + for (const name in this._vectors4) { + this._drawWrapper.effect.setVector4(name, this._vectors4[name]); + } + // Matrix + for (const name in this._matrices) { + this._drawWrapper.effect.setMatrix(name, this._matrices[name]); + } + } + if (!this._texture || !this._rtWrapper) { + return; + } + engine._debugPushGroup?.(`procedural texture generation for ${this.name}`, 1); + const viewPort = engine.currentViewport; + if (this.isCube) { + for (let face = 0; face < 6; face++) { + engine.bindFramebuffer(this._rtWrapper, face, undefined, undefined, true); + // VBOs + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect); + this._drawWrapper.effect.setFloat("face", face); + // Clear + if (this.autoClear) { + engine.clear(scene.clearColor, true, false, false); + } + // Draw order + engine.drawElementsType(Material.TriangleFillMode, 0, 6); + // Unbind and restore viewport + engine.unBindFramebuffer(this._rtWrapper, true); + } + } + else { + let numLayers = 1; + if (this._rtWrapper.is3D) { + numLayers = this._rtWrapper.depth; + } + else if (this._rtWrapper.is2DArray) { + numLayers = this._rtWrapper.layers; + } + for (let layer = 0; layer < numLayers; layer++) { + engine.bindFramebuffer(this._rtWrapper, 0, undefined, undefined, true, 0, layer); + // VBOs + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect); + if (this._rtWrapper.is3D || this._rtWrapper.is2DArray) { + this._drawWrapper.effect?.setFloat("layer", numLayers !== 1 ? layer / (numLayers - 1) : 0); + this._drawWrapper.effect?.setInt("layerNum", layer); + for (const name in this._textures) { + this._drawWrapper.effect.setTexture(name, this._textures[name]); + } + } + // Clear + if (this.autoClear) { + engine.clear(scene.clearColor, true, false, false); + } + // Draw order + engine.drawElementsType(Material.TriangleFillMode, 0, 6); + // Unbind and restore viewport + engine.unBindFramebuffer(this._rtWrapper, !this._generateMipMaps); + } + } + if (viewPort) { + engine.setViewport(viewPort); + } + // Mipmaps + if (this.isCube) { + engine.generateMipMapsForCubemap(this._texture, true); + } + engine._debugPopGroup?.(1); + if (this.onGenerated) { + this.onGenerated(); + } + this.onGeneratedObservable.notifyObservers(this); + } + /** + * Clone the texture. + * @returns the cloned texture + */ + clone() { + const textureSize = this.getSize(); + const newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps); + // Base texture + newTexture.hasAlpha = this.hasAlpha; + newTexture.level = this.level; + // RenderTarget Texture + newTexture.coordinatesMode = this.coordinatesMode; + return newTexture; + } + /** + * Dispose the texture and release its associated resources. + */ + dispose() { + const scene = this.getScene(); + if (!scene) { + return; + } + const index = scene.proceduralTextures.indexOf(this); + if (index >= 0) { + scene.proceduralTextures.splice(index, 1); + } + const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind]; + if (vertexBuffer) { + vertexBuffer.dispose(); + this._vertexBuffers[VertexBuffer.PositionKind] = null; + } + if (this._indexBuffer && this._fullEngine._releaseBuffer(this._indexBuffer)) { + this._indexBuffer = null; + } + this.onGeneratedObservable.clear(); + this.onBeforeGenerationObservable.clear(); + super.dispose(); + } +} +__decorate([ + serialize() +], ProceduralTexture.prototype, "isEnabled", void 0); +__decorate([ + serialize() +], ProceduralTexture.prototype, "autoClear", void 0); +__decorate([ + serialize() +], ProceduralTexture.prototype, "_generateMipMaps", void 0); +__decorate([ + serialize() +], ProceduralTexture.prototype, "_size", void 0); +__decorate([ + serialize() +], ProceduralTexture.prototype, "refreshRate", null); +RegisterClass("BABYLON.ProceduralTexture", ProceduralTexture); + +/** + * Operations supported by the Trigonometry block + */ +var TrigonometryBlockOperations; +(function (TrigonometryBlockOperations) { + /** Cos */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Cos"] = 0] = "Cos"; + /** Sin */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Sin"] = 1] = "Sin"; + /** Abs */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Abs"] = 2] = "Abs"; + /** Exp */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Exp"] = 3] = "Exp"; + /** Exp2 */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Exp2"] = 4] = "Exp2"; + /** Round */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Round"] = 5] = "Round"; + /** Floor */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Floor"] = 6] = "Floor"; + /** Ceiling */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Ceiling"] = 7] = "Ceiling"; + /** Square root */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Sqrt"] = 8] = "Sqrt"; + /** Log */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Log"] = 9] = "Log"; + /** Tangent */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Tan"] = 10] = "Tan"; + /** Arc tangent */ + TrigonometryBlockOperations[TrigonometryBlockOperations["ArcTan"] = 11] = "ArcTan"; + /** Arc cosinus */ + TrigonometryBlockOperations[TrigonometryBlockOperations["ArcCos"] = 12] = "ArcCos"; + /** Arc sinus */ + TrigonometryBlockOperations[TrigonometryBlockOperations["ArcSin"] = 13] = "ArcSin"; + /** Fraction */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Fract"] = 14] = "Fract"; + /** Sign */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Sign"] = 15] = "Sign"; + /** To radians (from degrees) */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Radians"] = 16] = "Radians"; + /** To degrees (from radians) */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Degrees"] = 17] = "Degrees"; + /** To Set a = b */ + TrigonometryBlockOperations[TrigonometryBlockOperations["Set"] = 18] = "Set"; +})(TrigonometryBlockOperations || (TrigonometryBlockOperations = {})); +/** + * Block used to apply trigonometry operation to floats + */ +class TrigonometryBlock extends NodeMaterialBlock { + /** + * Creates a new TrigonometryBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Gets or sets the operation applied by the block + */ + this.operation = TrigonometryBlockOperations.Cos; + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "TrigonometryBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + let operation = ""; + switch (this.operation) { + case TrigonometryBlockOperations.Cos: { + operation = "cos"; + break; + } + case TrigonometryBlockOperations.Sin: { + operation = "sin"; + break; + } + case TrigonometryBlockOperations.Abs: { + operation = "abs"; + break; + } + case TrigonometryBlockOperations.Exp: { + operation = "exp"; + break; + } + case TrigonometryBlockOperations.Exp2: { + operation = "exp2"; + break; + } + case TrigonometryBlockOperations.Round: { + operation = "round"; + break; + } + case TrigonometryBlockOperations.Floor: { + operation = "floor"; + break; + } + case TrigonometryBlockOperations.Ceiling: { + operation = "ceil"; + break; + } + case TrigonometryBlockOperations.Sqrt: { + operation = "sqrt"; + break; + } + case TrigonometryBlockOperations.Log: { + operation = "log"; + break; + } + case TrigonometryBlockOperations.Tan: { + operation = "tan"; + break; + } + case TrigonometryBlockOperations.ArcTan: { + operation = "atan"; + break; + } + case TrigonometryBlockOperations.ArcCos: { + operation = "acos"; + break; + } + case TrigonometryBlockOperations.ArcSin: { + operation = "asin"; + break; + } + case TrigonometryBlockOperations.Fract: { + operation = "fract"; + break; + } + case TrigonometryBlockOperations.Sign: { + operation = "sign"; + break; + } + case TrigonometryBlockOperations.Radians: { + operation = "radians"; + break; + } + case TrigonometryBlockOperations.Degrees: { + operation = "degrees"; + break; + } + case TrigonometryBlockOperations.Set: { + operation = ""; + break; + } + } + state.compilationString += state._declareOutput(output) + ` = ${operation}(${this.input.associatedVariableName});\n`; + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.operation = this.operation; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.operation = serializationObject.operation; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${TrigonometryBlockOperations[this.operation]};\n`; + return codeString; + } +} +__decorate([ + editableInPropertyPage("Operation", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "Cos", value: TrigonometryBlockOperations.Cos }, + { label: "Sin", value: TrigonometryBlockOperations.Sin }, + { label: "Abs", value: TrigonometryBlockOperations.Abs }, + { label: "Exp", value: TrigonometryBlockOperations.Exp }, + { label: "Exp2", value: TrigonometryBlockOperations.Exp2 }, + { label: "Round", value: TrigonometryBlockOperations.Round }, + { label: "Floor", value: TrigonometryBlockOperations.Floor }, + { label: "Ceiling", value: TrigonometryBlockOperations.Ceiling }, + { label: "Sqrt", value: TrigonometryBlockOperations.Sqrt }, + { label: "Log", value: TrigonometryBlockOperations.Log }, + { label: "Tan", value: TrigonometryBlockOperations.Tan }, + { label: "ArcTan", value: TrigonometryBlockOperations.ArcTan }, + { label: "ArcCos", value: TrigonometryBlockOperations.ArcCos }, + { label: "ArcSin", value: TrigonometryBlockOperations.ArcSin }, + { label: "Fract", value: TrigonometryBlockOperations.Fract }, + { label: "Sign", value: TrigonometryBlockOperations.Sign }, + { label: "Radians", value: TrigonometryBlockOperations.Radians }, + { label: "Degrees", value: TrigonometryBlockOperations.Degrees }, + { label: "Set", value: TrigonometryBlockOperations.Set }, + ], + }) +], TrigonometryBlock.prototype, "operation", void 0); +RegisterClass("BABYLON.TrigonometryBlock", TrigonometryBlock); + +const onCreatedEffectParameters = { effect: null, subMesh: null }; +/** @internal */ +class NodeMaterialDefines extends MaterialDefines { + /** + * Creates a new NodeMaterialDefines + */ + constructor() { + super(); + /** Normal */ + this.NORMAL = false; + /** Tangent */ + this.TANGENT = false; + /** Vertex color */ + this.VERTEXCOLOR_NME = false; + /** Uv1 **/ + this.UV1 = false; + /** Uv2 **/ + this.UV2 = false; + /** Uv3 **/ + this.UV3 = false; + /** Uv4 **/ + this.UV4 = false; + /** Uv5 **/ + this.UV5 = false; + /** Uv6 **/ + this.UV6 = false; + /** Prepass **/ + this.PREPASS = false; + /** Prepass normal */ + this.PREPASS_NORMAL = false; + /** Prepass normal index */ + this.PREPASS_NORMAL_INDEX = -1; + /** Prepass world normal */ + this.PREPASS_WORLD_NORMAL = false; + /** Prepass world normal index */ + this.PREPASS_WORLD_NORMAL_INDEX = -1; + /** Prepass position */ + this.PREPASS_POSITION = false; + /** Prepass position index */ + this.PREPASS_POSITION_INDEX = -1; + /** Prepass local position */ + this.PREPASS_LOCAL_POSITION = false; + /** Prepass local position index */ + this.PREPASS_LOCAL_POSITION_INDEX = -1; + /** Prepass depth */ + this.PREPASS_DEPTH = false; + /** Prepass depth index */ + this.PREPASS_DEPTH_INDEX = -1; + /** Clip-space depth */ + this.PREPASS_SCREENSPACE_DEPTH = false; + /** Clip-space depth index */ + this.PREPASS_SCREENSPACE_DEPTH_INDEX = -1; + /** Scene MRT count */ + this.SCENE_MRT_COUNT = 0; + /** BONES */ + this.NUM_BONE_INFLUENCERS = 0; + /** Bones per mesh */ + this.BonesPerMesh = 0; + /** Using texture for bone storage */ + this.BONETEXTURE = false; + /** MORPH TARGETS */ + this.MORPHTARGETS = false; + /** Morph target position */ + this.MORPHTARGETS_POSITION = false; + /** Morph target normal */ + this.MORPHTARGETS_NORMAL = false; + /** Morph target tangent */ + this.MORPHTARGETS_TANGENT = false; + /** Morph target uv */ + this.MORPHTARGETS_UV = false; + /** Morph target uv2 */ + this.MORPHTARGETS_UV2 = false; + this.MORPHTARGETS_COLOR = false; + /** Morph target support positions */ + this.MORPHTARGETTEXTURE_HASPOSITIONS = false; + /** Morph target support normals */ + this.MORPHTARGETTEXTURE_HASNORMALS = false; + /** Morph target support tangents */ + this.MORPHTARGETTEXTURE_HASTANGENTS = false; + /** Morph target support uvs */ + this.MORPHTARGETTEXTURE_HASUVS = false; + /** Morph target support uv2s */ + this.MORPHTARGETTEXTURE_HASUV2S = false; + this.MORPHTARGETTEXTURE_HASCOLORS = false; + /** Number of morph influencers */ + this.NUM_MORPH_INFLUENCERS = 0; + /** Using a texture to store morph target data */ + this.MORPHTARGETS_TEXTURE = false; + /** IMAGE PROCESSING */ + this.IMAGEPROCESSING = false; + /** Vignette */ + this.VIGNETTE = false; + /** Multiply blend mode for vignette */ + this.VIGNETTEBLENDMODEMULTIPLY = false; + /** Opaque blend mode for vignette */ + this.VIGNETTEBLENDMODEOPAQUE = false; + /** Tone mapping */ + this.TONEMAPPING = 0; + /** Contrast */ + this.CONTRAST = false; + /** Exposure */ + this.EXPOSURE = false; + /** Color curves */ + this.COLORCURVES = false; + /** Color grading */ + this.COLORGRADING = false; + /** 3D color grading */ + this.COLORGRADING3D = false; + /** Sampler green depth */ + this.SAMPLER3DGREENDEPTH = false; + /** Sampler for BGR map */ + this.SAMPLER3DBGRMAP = false; + /** Dithering */ + this.DITHER = false; + /** Using post process for image processing */ + this.IMAGEPROCESSINGPOSTPROCESS = false; + /** Skip color clamp */ + this.SKIPFINALCOLORCLAMP = false; + /** MISC. */ + this.BUMPDIRECTUV = 0; + /** Camera is orthographic */ + this.CAMERA_ORTHOGRAPHIC = false; + /** Camera is perspective */ + this.CAMERA_PERSPECTIVE = false; + this.AREALIGHTSUPPORTED = true; + this.AREALIGHTNOROUGHTNESS = true; + this.rebuild(); + } + /** + * Set the value of a specific key + * @param name defines the name of the key to set + * @param value defines the value to set + * @param markAsUnprocessedIfDirty Flag to indicate to the cache that this value needs processing + */ + setValue(name, value, markAsUnprocessedIfDirty = false) { + if (this[name] === undefined) { + this._keys.push(name); + } + if (markAsUnprocessedIfDirty && this[name] !== value) { + this.markAsUnprocessed(); + } + this[name] = value; + } +} +/** + * Class used to create a node based material built by assembling shader blocks + */ +class NodeMaterial extends PushMaterial { + /** + * Checks if a block is a texture block + * @param block The block to check + * @returns True if the block is a texture block + */ + static _BlockIsTextureBlock(block) { + return (block.getClassName() === "TextureBlock" || + block.getClassName() === "ReflectionTextureBaseBlock" || + block.getClassName() === "ReflectionTextureBlock" || + block.getClassName() === "ReflectionBlock" || + block.getClassName() === "RefractionBlock" || + block.getClassName() === "CurrentScreenBlock" || + block.getClassName() === "ParticleTextureBlock" || + block.getClassName() === "ImageSourceBlock" || + block.getClassName() === "TriPlanarBlock" || + block.getClassName() === "BiPlanarBlock" || + block.getClassName() === "PrePassTextureBlock"); + } + set _glowModeEnabled(value) { + this._useAdditionalColor = value; + } + /** Get the inspector from bundle or global + * @returns the global NME + */ + _getGlobalNodeMaterialEditor() { + // UMD Global name detection from Webpack Bundle UMD Name. + if (typeof NODEEDITOR !== "undefined") { + return NODEEDITOR; + } + // In case of module let's check the global emitted from the editor entry point. + if (typeof BABYLON !== "undefined" && typeof BABYLON.NodeEditor !== "undefined") { + return BABYLON; + } + return undefined; + } + /** Gets or sets the active shader language */ + get shaderLanguage() { + return this._options?.shaderLanguage || NodeMaterial.DefaultShaderLanguage; + } + set shaderLanguage(value) { + this._options.shaderLanguage = value; + } + /** Gets or sets options to control the node material overall behavior */ + get options() { + return this._options; + } + set options(options) { + this._options = options; + } + /** + * Gets the image processing configuration used either in this material. + */ + get imageProcessingConfiguration() { + return this._imageProcessingConfiguration; + } + /** + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ + set imageProcessingConfiguration(value) { + this._attachImageProcessingConfiguration(value); + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + } + /** + * Gets or sets the mode property + */ + get mode() { + return this._mode; + } + set mode(value) { + this._mode = value; + } + /** Gets or sets the unique identifier used to identified the effect associated with the material */ + get buildId() { + return this._buildId; + } + set buildId(value) { + this._buildId = value; + } + /** + * Create a new node based material + * @param name defines the material name + * @param scene defines the hosting scene + * @param options defines creation option + */ + constructor(name, scene, options = {}) { + super(name, scene || EngineStore.LastCreatedScene); + this._buildId = NodeMaterial._BuildIdGenerator++; + this._buildWasSuccessful = false; + this._cachedWorldViewMatrix = new Matrix(); + this._cachedWorldViewProjectionMatrix = new Matrix(); + this._optimizers = new Array(); + this._animationFrame = -1; + this._buildIsInProgress = false; + this.BJSNODEMATERIALEDITOR = this._getGlobalNodeMaterialEditor(); + /** @internal */ + this._useAdditionalColor = false; + /** + * Gets or sets data used by visual editor + * @see https://nme.babylonjs.com + */ + this.editorData = null; + /** + * Gets or sets a boolean indicating that alpha value must be ignored (This will turn alpha blending off even if an alpha value is produced by the material) + */ + this.ignoreAlpha = false; + /** + * Defines the maximum number of lights that can be used in the material + */ + this.maxSimultaneousLights = 4; + /** + * Observable raised when the material is built + */ + this.onBuildObservable = new Observable(); + /** + * Observable raised when an error is detected + */ + this.onBuildErrorObservable = new Observable(); + /** + * Gets or sets the root nodes of the material vertex shader + */ + this._vertexOutputNodes = new Array(); + /** + * Gets or sets the root nodes of the material fragment (pixel) shader + */ + this._fragmentOutputNodes = new Array(); + /** + * Gets an array of blocks that needs to be serialized even if they are not yet connected + */ + this.attachedBlocks = []; + /** + * Specifies the mode of the node material + * @internal + */ + this._mode = NodeMaterialModes.Material; + /** + * Gets or sets a boolean indicating that alpha blending must be enabled no matter what alpha value or alpha channel of the FragmentBlock are + */ + this.forceAlphaBlending = false; + if (!NodeMaterial.UseNativeShaderLanguageOfEngine && options && options.shaderLanguage === 1 /* ShaderLanguage.WGSL */ && !this.getScene().getEngine().isWebGPU) { + throw new Error("WebGPU shader language is only supported with WebGPU engine"); + } + this._options = { + emitComments: false, + shaderLanguage: NodeMaterial.DefaultShaderLanguage, + ...options, + }; + if (NodeMaterial.UseNativeShaderLanguageOfEngine) { + this._options.shaderLanguage = this.getScene().getEngine().isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */; + } + // Setup the default processing configuration to the scene. + this._attachImageProcessingConfiguration(null); + } + /** + * Gets the current class name of the material e.g. "NodeMaterial" + * @returns the class name + */ + getClassName() { + return "NodeMaterial"; + } + /** + * Attaches a new image processing configuration to the Standard Material. + * @param configuration + */ + _attachImageProcessingConfiguration(configuration) { + if (configuration === this._imageProcessingConfiguration) { + return; + } + // Detaches observer. + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + // Pick the scene configuration if needed. + if (!configuration) { + this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; + } + else { + this._imageProcessingConfiguration = configuration; + } + // Attaches observer. + if (this._imageProcessingConfiguration) { + this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { + this._markAllSubMeshesAsImageProcessingDirty(); + }); + } + } + /** + * Get a block by its name + * @param name defines the name of the block to retrieve + * @returns the required block or null if not found + */ + getBlockByName(name) { + let result = null; + for (const block of this.attachedBlocks) { + if (block.name === name) { + if (!result) { + result = block; + } + else { + Tools.Warn("More than one block was found with the name `" + name + "`"); + return result; + } + } + } + return result; + } + /** + * Get a block using a predicate + * @param predicate defines the predicate used to find the good candidate + * @returns the required block or null if not found + */ + getBlockByPredicate(predicate) { + for (const block of this.attachedBlocks) { + if (predicate(block)) { + return block; + } + } + return null; + } + /** + * Get an input block using a predicate + * @param predicate defines the predicate used to find the good candidate + * @returns the required input block or null if not found + */ + getInputBlockByPredicate(predicate) { + for (const block of this.attachedBlocks) { + if (block.isInput && predicate(block)) { + return block; + } + } + return null; + } + /** + * Gets the list of input blocks attached to this material + * @returns an array of InputBlocks + */ + getInputBlocks() { + const blocks = []; + for (const block of this.attachedBlocks) { + if (block.isInput) { + blocks.push(block); + } + } + return blocks; + } + /** + * Adds a new optimizer to the list of optimizers + * @param optimizer defines the optimizers to add + * @returns the current material + */ + registerOptimizer(optimizer) { + const index = this._optimizers.indexOf(optimizer); + if (index > -1) { + return; + } + this._optimizers.push(optimizer); + return this; + } + /** + * Remove an optimizer from the list of optimizers + * @param optimizer defines the optimizers to remove + * @returns the current material + */ + unregisterOptimizer(optimizer) { + const index = this._optimizers.indexOf(optimizer); + if (index === -1) { + return; + } + this._optimizers.splice(index, 1); + return this; + } + /** + * Add a new block to the list of output nodes + * @param node defines the node to add + * @returns the current material + */ + addOutputNode(node) { + if (node.target === null) { + // eslint-disable-next-line no-throw-literal + throw "This node is not meant to be an output node. You may want to explicitly set its target value."; + } + if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) { + this._addVertexOutputNode(node); + } + if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) { + this._addFragmentOutputNode(node); + } + return this; + } + /** + * Remove a block from the list of root nodes + * @param node defines the node to remove + * @returns the current material + */ + removeOutputNode(node) { + if (node.target === null) { + return this; + } + if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) { + this._removeVertexOutputNode(node); + } + if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) { + this._removeFragmentOutputNode(node); + } + return this; + } + _addVertexOutputNode(node) { + if (this._vertexOutputNodes.indexOf(node) !== -1) { + return; + } + node.target = NodeMaterialBlockTargets.Vertex; + this._vertexOutputNodes.push(node); + return this; + } + _removeVertexOutputNode(node) { + const index = this._vertexOutputNodes.indexOf(node); + if (index === -1) { + return; + } + this._vertexOutputNodes.splice(index, 1); + return this; + } + _addFragmentOutputNode(node) { + if (this._fragmentOutputNodes.indexOf(node) !== -1) { + return; + } + node.target = NodeMaterialBlockTargets.Fragment; + this._fragmentOutputNodes.push(node); + return this; + } + _removeFragmentOutputNode(node) { + const index = this._fragmentOutputNodes.indexOf(node); + if (index === -1) { + return; + } + this._fragmentOutputNodes.splice(index, 1); + return this; + } + get _supportGlowLayer() { + if (this._fragmentOutputNodes.length === 0) { + return false; + } + if (this._fragmentOutputNodes.some((f) => f.additionalColor && f.additionalColor.isConnected)) { + return true; + } + return false; + } + /** + * Specifies if the material will require alpha blending + * @returns a boolean specifying if alpha blending is needed + */ + needAlphaBlending() { + if (this.ignoreAlpha) { + return false; + } + return this.forceAlphaBlending || this.alpha < 1.0 || (this._sharedData && this._sharedData.hints.needAlphaBlending); + } + /** + * Specifies if this material should be rendered in alpha test mode + * @returns a boolean specifying if an alpha test is needed. + */ + needAlphaTesting() { + return this._sharedData && this._sharedData.hints.needAlphaTesting; + } + _processInitializeOnLink(block, state, nodesToProcessForOtherBuildState, autoConfigure = true) { + if (block.target === NodeMaterialBlockTargets.VertexAndFragment) { + nodesToProcessForOtherBuildState.push(block); + } + else if (state.target === NodeMaterialBlockTargets.Fragment && block.target === NodeMaterialBlockTargets.Vertex && block._preparationId !== this._buildId) { + nodesToProcessForOtherBuildState.push(block); + } + this._initializeBlock(block, state, nodesToProcessForOtherBuildState, autoConfigure); + } + _attachBlock(node) { + if (this.attachedBlocks.indexOf(node) === -1) { + if (node.isUnique) { + const className = node.getClassName(); + for (const other of this.attachedBlocks) { + if (other.getClassName() === className) { + // eslint-disable-next-line no-throw-literal + throw `Cannot have multiple blocks of type ${className} in the same NodeMaterial`; + } + } + } + this.attachedBlocks.push(node); + } + } + _initializeBlock(node, state, nodesToProcessForOtherBuildState, autoConfigure = true) { + node.initialize(state); + if (autoConfigure) { + node.autoConfigure(this); + } + node._preparationId = this._buildId; + this._attachBlock(node); + for (const input of node.inputs) { + input.associatedVariableName = ""; + const connectedPoint = input.connectedPoint; + if (connectedPoint && !connectedPoint._preventBubbleUp) { + const block = connectedPoint.ownerBlock; + if (block !== node) { + this._processInitializeOnLink(block, state, nodesToProcessForOtherBuildState, autoConfigure); + } + } + } + // Loop + if (node.isLoop) { + // We need to keep the storage write block in the active blocks + const loopBlock = node; + if (loopBlock.loopID.hasEndpoints) { + for (const endpoint of loopBlock.loopID.endpoints) { + const block = endpoint.ownerBlock; + if (block.outputs.length !== 0) { + continue; + } + state._terminalBlocks.add(block); // Attach the storage write only + this._processInitializeOnLink(block, state, nodesToProcessForOtherBuildState, autoConfigure); + } + } + } + else if (node.isTeleportOut) { + // Teleportation + const teleport = node; + if (teleport.entryPoint) { + this._processInitializeOnLink(teleport.entryPoint, state, nodesToProcessForOtherBuildState, autoConfigure); + } + } + for (const output of node.outputs) { + output.associatedVariableName = ""; + } + } + _resetDualBlocks(node, id) { + if (node.target === NodeMaterialBlockTargets.VertexAndFragment) { + node.buildId = id; + } + for (const input of node.inputs) { + const connectedPoint = input.connectedPoint; + if (connectedPoint && !connectedPoint._preventBubbleUp) { + const block = connectedPoint.ownerBlock; + if (block !== node) { + this._resetDualBlocks(block, id); + } + } + } + // If this is a teleport out, we need to reset the connected block + if (node.isTeleportOut) { + const teleportOut = node; + if (teleportOut.entryPoint) { + this._resetDualBlocks(teleportOut.entryPoint, id); + } + } + else if (node.isLoop) { + // Loop + const loopBlock = node; + if (loopBlock.loopID.hasEndpoints) { + for (const endpoint of loopBlock.loopID.endpoints) { + const block = endpoint.ownerBlock; + if (block.outputs.length !== 0) { + continue; + } + this._resetDualBlocks(block, id); + } + } + } + } + /** + * Remove a block from the current node material + * @param block defines the block to remove + */ + removeBlock(block) { + const attachedBlockIndex = this.attachedBlocks.indexOf(block); + if (attachedBlockIndex > -1) { + this.attachedBlocks.splice(attachedBlockIndex, 1); + } + if (block.isFinalMerger) { + this.removeOutputNode(block); + } + } + /** + * Build the material and generates the inner effect + * @param verbose defines if the build should log activity + * @param updateBuildId defines if the internal build Id should be updated (default is true) + * @param autoConfigure defines if the autoConfigure method should be called when initializing blocks (default is false) + */ + build(verbose = false, updateBuildId = true, autoConfigure = false) { + if (this._buildIsInProgress) { + Logger.Warn("Build is already in progress, You can use NodeMaterial.onBuildObservable to determine when the build is completed."); + return; + } + this._buildIsInProgress = true; + // First time? + if (!this._vertexCompilationState && !autoConfigure) { + autoConfigure = true; + } + this._buildWasSuccessful = false; + const engine = this.getScene().getEngine(); + const allowEmptyVertexProgram = this._mode === NodeMaterialModes.Particle; + if (this._vertexOutputNodes.length === 0 && !allowEmptyVertexProgram) { + // eslint-disable-next-line no-throw-literal + throw "You must define at least one vertexOutputNode"; + } + if (this._fragmentOutputNodes.length === 0) { + // eslint-disable-next-line no-throw-literal + throw "You must define at least one fragmentOutputNode"; + } + // Compilation state + this._vertexCompilationState = new NodeMaterialBuildState(); + this._vertexCompilationState.supportUniformBuffers = engine.supportsUniformBuffers; + this._vertexCompilationState.target = NodeMaterialBlockTargets.Vertex; + this._fragmentCompilationState = new NodeMaterialBuildState(); + this._fragmentCompilationState.supportUniformBuffers = engine.supportsUniformBuffers; + this._fragmentCompilationState.target = NodeMaterialBlockTargets.Fragment; + // Shared data + const needToPurgeList = this._fragmentOutputNodes.filter((n) => n._isFinalOutputAndActive).length > 1; + let fragmentOutputNodes = this._fragmentOutputNodes; + if (needToPurgeList) { + // Get all but the final output nodes + fragmentOutputNodes = this._fragmentOutputNodes.filter((n) => !n._isFinalOutputAndActive); + // Get the first with precedence on + fragmentOutputNodes.push(this._fragmentOutputNodes.filter((n) => n._isFinalOutputAndActive && n._hasPrecedence)[0]); + } + this._sharedData = new NodeMaterialBuildStateSharedData(); + this._sharedData.nodeMaterial = this; + this._sharedData.fragmentOutputNodes = fragmentOutputNodes; + this._vertexCompilationState.sharedData = this._sharedData; + this._fragmentCompilationState.sharedData = this._sharedData; + this._sharedData.buildId = this._buildId; + this._sharedData.emitComments = this._options.emitComments; + this._sharedData.verbose = verbose; + this._sharedData.scene = this.getScene(); + this._sharedData.allowEmptyVertexProgram = allowEmptyVertexProgram; + // Initialize blocks + const vertexNodes = []; + const fragmentNodes = []; + for (const vertexOutputNode of this._vertexOutputNodes) { + vertexNodes.push(vertexOutputNode); + this._initializeBlock(vertexOutputNode, this._vertexCompilationState, fragmentNodes, autoConfigure); + } + for (const fragmentOutputNode of fragmentOutputNodes) { + fragmentNodes.push(fragmentOutputNode); + this._initializeBlock(fragmentOutputNode, this._fragmentCompilationState, vertexNodes, autoConfigure); + } + // Are blocks code ready? + let waitingNodeCount = 0; + for (const node of this.attachedBlocks) { + if (!node.codeIsReady) { + waitingNodeCount++; + node.onCodeIsReadyObservable.addOnce(() => { + waitingNodeCount--; + if (waitingNodeCount === 0) { + this._finishBuildProcess(verbose, updateBuildId, vertexNodes, fragmentNodes); + } + }); + } + } + if (waitingNodeCount !== 0) { + return; + } + this._finishBuildProcess(verbose, updateBuildId, vertexNodes, fragmentNodes); + } + _finishBuildProcess(verbose = false, updateBuildId = true, vertexNodes, fragmentNodes) { + // Optimize + this.optimize(); + // Vertex + for (const vertexOutputNode of vertexNodes) { + vertexOutputNode.build(this._vertexCompilationState, vertexNodes); + } + // Fragment + this._fragmentCompilationState.uniforms = this._vertexCompilationState.uniforms.slice(0); + this._fragmentCompilationState._uniformDeclaration = this._vertexCompilationState._uniformDeclaration; + this._fragmentCompilationState._constantDeclaration = this._vertexCompilationState._constantDeclaration; + this._fragmentCompilationState._vertexState = this._vertexCompilationState; + for (const fragmentOutputNode of fragmentNodes) { + this._resetDualBlocks(fragmentOutputNode, this._buildId - 1); + } + for (const fragmentOutputNode of fragmentNodes) { + fragmentOutputNode.build(this._fragmentCompilationState, fragmentNodes); + } + // Finalize + this._vertexCompilationState.finalize(this._vertexCompilationState); + this._fragmentCompilationState.finalize(this._fragmentCompilationState); + if (updateBuildId) { + this._buildId = NodeMaterial._BuildIdGenerator++; + } + // Errors + const noError = this._sharedData.emitErrors(this.onBuildErrorObservable); + if (verbose) { + Logger.Log("Vertex shader:"); + Logger.Log(this._vertexCompilationState.compilationString); + Logger.Log("Fragment shader:"); + Logger.Log(this._fragmentCompilationState.compilationString); + } + this._buildIsInProgress = false; + this._buildWasSuccessful = true; + if (noError) { + this.onBuildObservable.notifyObservers(this); + } + // Wipe defines + const meshes = this.getScene().meshes; + for (const mesh of meshes) { + if (!mesh.subMeshes) { + continue; + } + for (const subMesh of mesh.subMeshes) { + if (subMesh.getMaterial() !== this) { + continue; + } + if (!subMesh.materialDefines) { + continue; + } + const defines = subMesh.materialDefines; + defines.markAllAsDirty(); + defines.reset(); + } + } + if (this.prePassTextureInputs.length) { + this.getScene().enablePrePassRenderer(); + } + const prePassRenderer = this.getScene().prePassRenderer; + if (prePassRenderer) { + prePassRenderer.markAsDirty(); + } + } + /** + * Runs an optimization phase to try to improve the shader code + */ + optimize() { + for (const optimizer of this._optimizers) { + optimizer.optimize(this._vertexOutputNodes, this._fragmentOutputNodes); + } + } + _prepareDefinesForAttributes(mesh, defines) { + const oldNormal = defines["NORMAL"]; + const oldTangent = defines["TANGENT"]; + const oldColor = defines["VERTEXCOLOR_NME"]; + defines["NORMAL"] = mesh.isVerticesDataPresent(VertexBuffer.NormalKind); + defines["TANGENT"] = mesh.isVerticesDataPresent(VertexBuffer.TangentKind); + const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind); + defines["VERTEXCOLOR_NME"] = hasVertexColors; + let uvChanged = false; + for (let i = 1; i <= 6; ++i) { + const oldUV = defines["UV" + i]; + defines["UV" + i] = mesh.isVerticesDataPresent(`uv${i === 1 ? "" : i}`); + uvChanged = uvChanged || defines["UV" + i] !== oldUV; + } + // PrePass + const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency; + PrepareDefinesForPrePass(this.getScene(), defines, !oit); + MaterialHelperGeometryRendering.PrepareDefines(this.getScene().getEngine().currentRenderPassId, mesh, defines); + if (oldNormal !== defines["NORMAL"] || oldTangent !== defines["TANGENT"] || oldColor !== defines["VERTEXCOLOR_NME"] || uvChanged) { + defines.markAsAttributesDirty(); + } + } + /** + * Can this material render to prepass + */ + get isPrePassCapable() { + return true; + } + /** + * Outputs written to the prepass + */ + get prePassTextureOutputs() { + const prePassOutputBlock = this.getBlockByPredicate((block) => block.getClassName() === "PrePassOutputBlock"); + const result = [4]; + if (!prePassOutputBlock) { + return result; + } + // Cannot write to prepass if we alread read from prepass + if (this.prePassTextureInputs.length) { + return result; + } + if (prePassOutputBlock.viewDepth.isConnected) { + result.push(5); + } + if (prePassOutputBlock.screenDepth.isConnected) { + result.push(10); + } + if (prePassOutputBlock.viewNormal.isConnected) { + result.push(6); + } + if (prePassOutputBlock.worldNormal.isConnected) { + result.push(8); + } + if (prePassOutputBlock.worldPosition.isConnected) { + result.push(1); + } + if (prePassOutputBlock.localPosition.isConnected) { + result.push(9); + } + if (prePassOutputBlock.reflectivity.isConnected) { + result.push(3); + } + if (prePassOutputBlock.velocity.isConnected) { + result.push(2); + } + if (prePassOutputBlock.velocityLinear.isConnected) { + result.push(11); + } + return result; + } + /** + * Gets the list of prepass texture required + */ + get prePassTextureInputs() { + const prePassTextureBlocks = this.getAllTextureBlocks().filter((block) => block.getClassName() === "PrePassTextureBlock"); + const result = []; + for (const block of prePassTextureBlocks) { + if (block.position.isConnected && !result.includes(1)) { + result.push(1); + } + if (block.localPosition.isConnected && !result.includes(9)) { + result.push(9); + } + if (block.depth.isConnected && !result.includes(5)) { + result.push(5); + } + if (block.screenDepth.isConnected && !result.includes(10)) { + result.push(10); + } + if (block.normal.isConnected && !result.includes(6)) { + result.push(6); + } + if (block.worldNormal.isConnected && !result.includes(8)) { + result.push(8); + } + } + return result; + } + /** + * Sets the required values to the prepass renderer. + * @param prePassRenderer defines the prepass renderer to set + * @returns true if the pre pass is needed + */ + setPrePassRenderer(prePassRenderer) { + const prePassTexturesRequired = this.prePassTextureInputs.concat(this.prePassTextureOutputs); + if (prePassRenderer && prePassTexturesRequired.length > 1) { + let cfg = prePassRenderer.getEffectConfiguration("nodeMaterial"); + if (!cfg) { + cfg = prePassRenderer.addEffectConfiguration({ + enabled: true, + needsImageProcessing: false, + name: "nodeMaterial", + texturesRequired: [], + }); + } + for (const prePassTexture of prePassTexturesRequired) { + if (!cfg.texturesRequired.includes(prePassTexture)) { + cfg.texturesRequired.push(prePassTexture); + } + } + cfg.enabled = true; + } + // COLOR_TEXTURE is always required for prepass, length > 1 means + // we actually need to write to special prepass textures + return prePassTexturesRequired.length > 1; + } + /** + * Create a post process from the material + * @param camera The camera to apply the render pass to. + * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size) + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA) + * @returns the post process created + */ + createPostProcess(camera, options = 1, samplingMode = 1, engine, reusable, textureType = 0, textureFormat = 5) { + if (this.mode !== NodeMaterialModes.PostProcess) { + Logger.Log("Incompatible material mode"); + return null; + } + return this._createEffectForPostProcess(null, camera, options, samplingMode, engine, reusable, textureType, textureFormat); + } + /** + * Create the post process effect from the material + * @param postProcess The post process to create the effect for + */ + createEffectForPostProcess(postProcess) { + this._createEffectForPostProcess(postProcess); + } + _createEffectForPostProcess(postProcess, camera, options = 1, samplingMode = 1, engine, reusable, textureType = 0, textureFormat = 5) { + let tempName = this.name + this._buildId; + const defines = new NodeMaterialDefines(); + const dummyMesh = new Mesh(tempName + "PostProcess", this.getScene()); + let buildId = this._buildId; + this._processDefines(dummyMesh, defines); + Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString, this.shaderLanguage); + if (!postProcess) { + postProcess = new PostProcess(this.name + "PostProcess", tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, options, camera, samplingMode, engine, reusable, defines.toString(), textureType, tempName, { maxSimultaneousLights: this.maxSimultaneousLights }, false, textureFormat, this.shaderLanguage); + } + else { + postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName); + } + postProcess.nodeMaterialSource = this; + postProcess.onDisposeObservable.add(() => { + dummyMesh.dispose(); + }); + postProcess.onApplyObservable.add((effect) => { + if (buildId !== this._buildId) { + delete Effect.ShadersStore[tempName + "VertexShader"]; + delete Effect.ShadersStore[tempName + "PixelShader"]; + tempName = this.name + this._buildId; + defines.markAllAsDirty(); + buildId = this._buildId; + } + const result = this._processDefines(dummyMesh, defines); + if (result) { + Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString); + TimingTools.SetImmediate(() => postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName)); + } + this._checkInternals(effect); + }); + return postProcess; + } + /** + * Create a new procedural texture based on this node material + * @param size defines the size of the texture + * @param scene defines the hosting scene + * @returns the new procedural texture attached to this node material + */ + createProceduralTexture(size, scene) { + if (this.mode !== NodeMaterialModes.ProceduralTexture) { + Logger.Log("Incompatible material mode"); + return null; + } + let tempName = this.name + this._buildId; + const proceduralTexture = new ProceduralTexture(tempName, size, null, scene); + const dummyMesh = new Mesh(tempName + "Procedural", this.getScene()); + dummyMesh.reservedDataStore = { + hidden: true, + }; + const defines = new NodeMaterialDefines(); + const result = this._processDefines(dummyMesh, defines); + Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString, this.shaderLanguage); + let effect = this.getScene().getEngine().createEffect({ + vertexElement: tempName, + fragmentElement: tempName, + }, [VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString(), result?.fallbacks, undefined, undefined, undefined, this.shaderLanguage); + proceduralTexture.nodeMaterialSource = this; + proceduralTexture._setEffect(effect); + let buildId = this._buildId; + const refreshEffect = () => { + if (buildId !== this._buildId) { + delete Effect.ShadersStore[tempName + "VertexShader"]; + delete Effect.ShadersStore[tempName + "PixelShader"]; + tempName = this.name + this._buildId; + defines.markAllAsDirty(); + buildId = this._buildId; + } + const result = this._processDefines(dummyMesh, defines); + if (result) { + Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString, this.shaderLanguage); + TimingTools.SetImmediate(() => { + effect = this.getScene().getEngine().createEffect({ + vertexElement: tempName, + fragmentElement: tempName, + }, [VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString(), result?.fallbacks, undefined); + proceduralTexture._setEffect(effect); + }); + } + this._checkInternals(effect); + }; + proceduralTexture.onBeforeGenerationObservable.add(() => { + refreshEffect(); + }); + // This is needed if the procedural texture is not set to refresh automatically + this.onBuildObservable.add(() => { + refreshEffect(); + }); + return proceduralTexture; + } + _createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined = "") { + let tempName = this.name + this._buildId + "_" + blendMode; + if (!defines) { + defines = new NodeMaterialDefines(); + } + if (!dummyMesh) { + dummyMesh = this.getScene().getMeshByName(this.name + "Particle"); + if (!dummyMesh) { + dummyMesh = new Mesh(this.name + "Particle", this.getScene()); + dummyMesh.reservedDataStore = { + hidden: true, + }; + } + } + let buildId = this._buildId; + const particleSystemDefines = []; + let join = particleSystemDefinesJoined; + if (!effect) { + const result = this._processDefines(dummyMesh, defines); + Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, undefined, this.shaderLanguage); + particleSystem.fillDefines(particleSystemDefines, blendMode, false); + join = particleSystemDefines.join("\n"); + effect = this.getScene() + .getEngine() + .createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + "\n" + join, result?.fallbacks, onCompiled, onError, particleSystem, this.shaderLanguage); + particleSystem.setCustomEffect(effect, blendMode); + } + effect.onBindObservable.add((effect) => { + if (buildId !== this._buildId) { + delete Effect.ShadersStore[tempName + "PixelShader"]; + tempName = this.name + this._buildId + "_" + blendMode; + defines.markAllAsDirty(); + buildId = this._buildId; + } + particleSystemDefines.length = 0; + particleSystem.fillDefines(particleSystemDefines, blendMode, false); + const particleSystemDefinesJoinedCurrent = particleSystemDefines.join("\n"); + if (particleSystemDefinesJoinedCurrent !== join) { + defines.markAllAsDirty(); + join = particleSystemDefinesJoinedCurrent; + } + const result = this._processDefines(dummyMesh, defines); + if (result) { + Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, undefined, this.shaderLanguage); + effect = this.getScene() + .getEngine() + .createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + "\n" + join, result?.fallbacks, onCompiled, onError, particleSystem); + particleSystem.setCustomEffect(effect, blendMode); + this._createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined); // add the effect.onBindObservable observer + return; + } + this._checkInternals(effect); + }); + } + _checkInternals(effect) { + // Animated blocks + if (this._sharedData.animatedInputs) { + const scene = this.getScene(); + const frameId = scene.getFrameId(); + if (this._animationFrame !== frameId) { + for (const input of this._sharedData.animatedInputs) { + input.animate(scene); + } + this._animationFrame = frameId; + } + } + // Bindable blocks + for (const block of this._sharedData.bindableBlocks) { + block.bind(effect, this); + } + // Connection points + for (const inputBlock of this._sharedData.inputBlocks) { + inputBlock._transmit(effect, this.getScene(), this); + } + } + /** + * Create the effect to be used as the custom effect for a particle system + * @param particleSystem Particle system to create the effect for + * @param onCompiled defines a function to call when the effect creation is successful + * @param onError defines a function to call when the effect creation has failed + */ + createEffectForParticles(particleSystem, onCompiled, onError) { + if (this.mode !== NodeMaterialModes.Particle) { + Logger.Log("Incompatible material mode"); + return; + } + this._createEffectForParticles(particleSystem, BaseParticleSystem.BLENDMODE_ONEONE, onCompiled, onError); + this._createEffectForParticles(particleSystem, BaseParticleSystem.BLENDMODE_MULTIPLY, onCompiled, onError); + } + /** + * Use this material as the shadow depth wrapper of a target material + * @param targetMaterial defines the target material + */ + createAsShadowDepthWrapper(targetMaterial) { + if (this.mode !== NodeMaterialModes.Material) { + Logger.Log("Incompatible material mode"); + return; + } + targetMaterial.shadowDepthWrapper = new BABYLON.ShadowDepthWrapper(this, this.getScene()); + } + _processDefines(mesh, defines, useInstances = false, subMesh) { + let result = null; + // Global defines + const scene = this.getScene(); + if (PrepareDefinesForCamera(scene, defines)) { + defines.markAsMiscDirty(); + } + // Shared defines + this._sharedData.blocksWithDefines.forEach((b) => { + b.initializeDefines(mesh, this, defines, useInstances); + }); + this._sharedData.blocksWithDefines.forEach((b) => { + b.prepareDefines(mesh, this, defines, useInstances, subMesh); + }); + // Need to recompile? + if (defines.isDirty) { + const lightDisposed = defines._areLightsDisposed; + defines.markAsProcessed(); + // Repeatable content generators + this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString; + this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString; + this._sharedData.repeatableContentBlocks.forEach((b) => { + b.replaceRepeatableContent(this._vertexCompilationState, this._fragmentCompilationState, mesh, defines); + }); + // Uniforms + const uniformBuffers = []; + this._sharedData.dynamicUniformBlocks.forEach((b) => { + b.updateUniformsAndSamples(this._vertexCompilationState, this, defines, uniformBuffers); + }); + const mergedUniforms = this._vertexCompilationState.uniforms; + this._fragmentCompilationState.uniforms.forEach((u) => { + const index = mergedUniforms.indexOf(u); + if (index === -1) { + mergedUniforms.push(u); + } + }); + // Samplers + const mergedSamplers = this._vertexCompilationState.samplers; + this._fragmentCompilationState.samplers.forEach((s) => { + const index = mergedSamplers.indexOf(s); + if (index === -1) { + mergedSamplers.push(s); + } + }); + const fallbacks = new EffectFallbacks(); + this._sharedData.blocksWithFallbacks.forEach((b) => { + b.provideFallbacks(mesh, fallbacks); + }); + result = { + lightDisposed, + uniformBuffers, + mergedUniforms, + mergedSamplers, + fallbacks, + }; + } + return result; + } + /** + * Get if the submesh is ready to be used and all its information available. + * Child classes can use it to update shaders + * @param mesh defines the mesh to check + * @param subMesh defines which submesh to check + * @param useInstances specifies that instances should be used + * @returns a boolean indicating that the submesh is ready or not + */ + isReadyForSubMesh(mesh, subMesh, useInstances = false) { + if (!this._buildWasSuccessful) { + return false; + } + const scene = this.getScene(); + if (this._sharedData.animatedInputs) { + const frameId = scene.getFrameId(); + if (this._animationFrame !== frameId) { + for (const input of this._sharedData.animatedInputs) { + input.animate(scene); + } + this._animationFrame = frameId; + } + } + const drawWrapper = subMesh._drawWrapper; + if (drawWrapper.effect && this.isFrozen) { + if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) { + return true; + } + } + if (!subMesh.materialDefines || typeof subMesh.materialDefines === "string") { + subMesh.materialDefines = new NodeMaterialDefines(); + } + const defines = subMesh.materialDefines; + if (this._isReadyForSubMesh(subMesh)) { + return true; + } + const engine = scene.getEngine(); + this._prepareDefinesForAttributes(mesh, defines); + // Check if blocks are ready + if (this._sharedData.blockingBlocks.some((b) => !b.isReady(mesh, this, defines, useInstances))) { + return false; + } + const result = this._processDefines(mesh, defines, useInstances, subMesh); + if (result) { + const previousEffect = subMesh.effect; + // Compilation + const join = defines.toString(); + let effect = engine.createEffect({ + vertex: "nodeMaterial" + this._buildId, + fragment: "nodeMaterial" + this._buildId, + vertexSource: this._vertexCompilationState.compilationString, + fragmentSource: this._fragmentCompilationState.compilationString, + }, { + attributes: this._vertexCompilationState.attributes, + uniformsNames: result.mergedUniforms, + uniformBuffersNames: result.uniformBuffers, + samplers: result.mergedSamplers, + defines: join, + fallbacks: result.fallbacks, + onCompiled: this.onCompiled, + onError: this.onError, + multiTarget: defines.PREPASS, + indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }, + shaderLanguage: this.shaderLanguage, + }, engine); + if (effect) { + if (this._onEffectCreatedObservable) { + onCreatedEffectParameters.effect = effect; + onCreatedEffectParameters.subMesh = subMesh; + this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters); + } + // Use previous effect while new one is compiling + if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) { + effect = previousEffect; + defines.markAsUnprocessed(); + if (result.lightDisposed) { + // re register in case it takes more than one frame. + defines._areLightsDisposed = true; + return false; + } + } + else { + scene.resetCachedMaterial(); + subMesh.setEffect(effect, defines, this._materialContext); + } + } + } + // Check if Area Lights have LTC texture. + if (defines["AREALIGHTUSED"]) { + for (let index = 0; index < mesh.lightSources.length; index++) { + if (!mesh.lightSources[index]._isReady()) { + return false; + } + } + } + if (!subMesh.effect || !subMesh.effect.isReady()) { + return false; + } + defines._renderId = scene.getRenderId(); + drawWrapper._wasPreviouslyReady = true; + drawWrapper._wasPreviouslyUsingInstances = useInstances; + this._checkScenePerformancePriority(); + return true; + } + /** + * Get a string representing the shaders built by the current node graph + */ + get compiledShaders() { + if (!this._buildWasSuccessful) { + this.build(); + } + return `// Vertex shader\n${this._vertexCompilationState.compilationString}\n\n// Fragment shader\n${this._fragmentCompilationState.compilationString}`; + } + /** + * Binds the world matrix to the material + * @param world defines the world transformation matrix + */ + bindOnlyWorldMatrix(world) { + const scene = this.getScene(); + if (!this._activeEffect) { + return; + } + const hints = this._sharedData.hints; + if (hints.needWorldViewMatrix) { + world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix); + } + if (hints.needWorldViewProjectionMatrix) { + world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix); + } + // Connection points + for (const inputBlock of this._sharedData.inputBlocks) { + inputBlock._transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix); + } + } + /** + * Binds the submesh to this material by preparing the effect and shader to draw + * @param world defines the world transformation matrix + * @param mesh defines the mesh containing the submesh + * @param subMesh defines the submesh to bind the material to + */ + bindForSubMesh(world, mesh, subMesh) { + const scene = this.getScene(); + const effect = subMesh.effect; + if (!effect) { + return; + } + this._activeEffect = effect; + // Matrices + this.bindOnlyWorldMatrix(world); + const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility); + const sharedData = this._sharedData; + if (mustRebind) { + // Bindable blocks + for (const block of sharedData.bindableBlocks) { + block.bind(effect, this, mesh, subMesh); + } + for (const block of sharedData.forcedBindableBlocks) { + block.bind(effect, this, mesh, subMesh); + } + // Connection points + for (const inputBlock of sharedData.inputBlocks) { + inputBlock._transmit(effect, scene, this); + } + } + else if (!this.isFrozen) { + for (const block of sharedData.forcedBindableBlocks) { + block.bind(effect, this, mesh, subMesh); + } + } + this._afterBind(mesh, this._activeEffect, subMesh); + } + /** + * Gets the active textures from the material + * @returns an array of textures + */ + getActiveTextures() { + const activeTextures = super.getActiveTextures(); + if (this._sharedData) { + activeTextures.push(...this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture)); + } + return activeTextures; + } + /** + * Gets the list of texture blocks + * Note that this method will only return blocks that are reachable from the final block(s) and only after the material has been built! + * @returns an array of texture blocks + */ + getTextureBlocks() { + if (!this._sharedData) { + return []; + } + return this._sharedData.textureBlocks; + } + /** + * Gets the list of all texture blocks + * Note that this method will scan all attachedBlocks and return blocks that are texture blocks + * @returns + */ + getAllTextureBlocks() { + const textureBlocks = []; + for (const block of this.attachedBlocks) { + if (NodeMaterial._BlockIsTextureBlock(block)) { + textureBlocks.push(block); + } + } + return textureBlocks; + } + /** + * Specifies if the material uses a texture + * @param texture defines the texture to check against the material + * @returns a boolean specifying if the material uses the texture + */ + hasTexture(texture) { + if (super.hasTexture(texture)) { + return true; + } + if (!this._sharedData) { + return false; + } + for (const t of this._sharedData.textureBlocks) { + if (t.texture === texture) { + return true; + } + } + return false; + } + /** + * Disposes the material + * @param forceDisposeEffect specifies if effects should be forcefully disposed + * @param forceDisposeTextures specifies if textures should be forcefully disposed + * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh + */ + dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { + if (forceDisposeTextures) { + for (const texture of this.getTextureBlocks() + .filter((tb) => tb.texture) + .map((tb) => tb.texture)) { + texture.dispose(); + } + } + for (const block of this.attachedBlocks) { + block.dispose(); + } + this.attachedBlocks.length = 0; + this._sharedData = null; + this._vertexCompilationState = null; + this._fragmentCompilationState = null; + this.onBuildObservable.clear(); + this.onBuildErrorObservable.clear(); + if (this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + this._imageProcessingObserver = null; + } + super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh); + } + /** Creates the node editor window. + * @param additionalConfig Define the configuration of the editor + */ + _createNodeEditor(additionalConfig) { + const nodeEditorConfig = { + nodeMaterial: this, + ...additionalConfig, + }; + this.BJSNODEMATERIALEDITOR.NodeEditor.Show(nodeEditorConfig); + } + /** + * Launch the node material editor + * @param config Define the configuration of the editor + * @returns a promise fulfilled when the node editor is visible + */ + edit(config) { + return new Promise((resolve) => { + this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor(); + if (typeof this.BJSNODEMATERIALEDITOR == "undefined") { + const editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL; + // Load editor and add it to the DOM + Tools.LoadBabylonScript(editorUrl, () => { + this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor(); + this._createNodeEditor(config?.nodeEditorConfig); + resolve(); + }); + } + else { + // Otherwise creates the editor + this._createNodeEditor(config?.nodeEditorConfig); + resolve(); + } + }); + } + /** + * Clear the current material + */ + clear() { + this._vertexOutputNodes.length = 0; + this._fragmentOutputNodes.length = 0; + this.attachedBlocks.length = 0; + this._buildIsInProgress = false; + } + /** + * Clear the current material and set it to a default state + */ + setToDefault() { + this.clear(); + this.editorData = null; + const positionInput = new InputBlock("Position"); + positionInput.setAsAttribute("position"); + const worldInput = new InputBlock("World"); + worldInput.setAsSystemValue(NodeMaterialSystemValues.World); + const worldPos = new TransformBlock("WorldPos"); + positionInput.connectTo(worldPos); + worldInput.connectTo(worldPos); + const viewProjectionInput = new InputBlock("ViewProjection"); + viewProjectionInput.setAsSystemValue(NodeMaterialSystemValues.ViewProjection); + const worldPosdMultipliedByViewProjection = new TransformBlock("WorldPos * ViewProjectionTransform"); + worldPos.connectTo(worldPosdMultipliedByViewProjection); + viewProjectionInput.connectTo(worldPosdMultipliedByViewProjection); + const vertexOutput = new VertexOutputBlock("VertexOutput"); + worldPosdMultipliedByViewProjection.connectTo(vertexOutput); + // Pixel + const pixelColor = new InputBlock("color"); + pixelColor.value = new Color4(0.8, 0.8, 0.8, 1); + const fragmentOutput = new FragmentOutputBlock("FragmentOutput"); + pixelColor.connectTo(fragmentOutput); + // Add to nodes + this.addOutputNode(vertexOutput); + this.addOutputNode(fragmentOutput); + this._mode = NodeMaterialModes.Material; + } + /** + * Clear the current material and set it to a default state for post process + */ + setToDefaultPostProcess() { + this.clear(); + this.editorData = null; + const position = new InputBlock("Position"); + position.setAsAttribute("position2d"); + const const1 = new InputBlock("Constant1"); + const1.isConstant = true; + const1.value = 1; + const vmerger = new VectorMergerBlock("Position3D"); + position.connectTo(vmerger); + const1.connectTo(vmerger, { input: "w" }); + const vertexOutput = new VertexOutputBlock("VertexOutput"); + vmerger.connectTo(vertexOutput); + // Pixel + const scale = new InputBlock("Scale"); + scale.visibleInInspector = true; + scale.value = new Vector2(1, 1); + const uv0 = new RemapBlock("uv0"); + position.connectTo(uv0); + const uv = new MultiplyBlock("UV scale"); + uv0.connectTo(uv); + scale.connectTo(uv); + const currentScreen = new CurrentScreenBlock("CurrentScreen"); + uv.connectTo(currentScreen); + const textureUrl = Tools.GetAssetUrl("https://assets.babylonjs.com/core/nme/currentScreenPostProcess.png"); + currentScreen.texture = new Texture(textureUrl, this.getScene()); + const fragmentOutput = new FragmentOutputBlock("FragmentOutput"); + currentScreen.connectTo(fragmentOutput, { output: "rgba" }); + // Add to nodes + this.addOutputNode(vertexOutput); + this.addOutputNode(fragmentOutput); + this._mode = NodeMaterialModes.PostProcess; + } + /** + * Clear the current material and set it to a default state for procedural texture + */ + setToDefaultProceduralTexture() { + this.clear(); + this.editorData = null; + const position = new InputBlock("Position"); + position.setAsAttribute("position2d"); + const const1 = new InputBlock("Constant1"); + const1.isConstant = true; + const1.value = 1; + const vmerger = new VectorMergerBlock("Position3D"); + position.connectTo(vmerger); + const1.connectTo(vmerger, { input: "w" }); + const vertexOutput = new VertexOutputBlock("VertexOutput"); + vmerger.connectTo(vertexOutput); + // Pixel + const time = new InputBlock("Time"); + time.value = 0; + time.min = 0; + time.max = 0; + time.isBoolean = false; + time.matrixMode = 0; + time.animationType = AnimatedInputBlockTypes.Time; + time.isConstant = false; + const color = new InputBlock("Color3"); + color.value = new Color3(1, 1, 1); + color.isConstant = false; + const fragmentOutput = new FragmentOutputBlock("FragmentOutput"); + const vectorMerger = new VectorMergerBlock("VectorMerger"); + vectorMerger.visibleInInspector = false; + const cos = new TrigonometryBlock("Cos"); + cos.operation = TrigonometryBlockOperations.Cos; + position.connectTo(vectorMerger); + time.output.connectTo(cos.input); + cos.output.connectTo(vectorMerger.z); + vectorMerger.xyzOut.connectTo(fragmentOutput.rgb); + // Add to nodes + this.addOutputNode(vertexOutput); + this.addOutputNode(fragmentOutput); + this._mode = NodeMaterialModes.ProceduralTexture; + } + /** + * Clear the current material and set it to a default state for particle + */ + setToDefaultParticle() { + this.clear(); + this.editorData = null; + // Pixel + const uv = new InputBlock("uv"); + uv.setAsAttribute("particle_uv"); + const texture = new ParticleTextureBlock("ParticleTexture"); + uv.connectTo(texture); + const color = new InputBlock("Color"); + color.setAsAttribute("particle_color"); + const multiply = new MultiplyBlock("Texture * Color"); + texture.connectTo(multiply); + color.connectTo(multiply); + const rampGradient = new ParticleRampGradientBlock("ParticleRampGradient"); + multiply.connectTo(rampGradient); + const cSplitter = new ColorSplitterBlock("ColorSplitter"); + color.connectTo(cSplitter); + const blendMultiply = new ParticleBlendMultiplyBlock("ParticleBlendMultiply"); + rampGradient.connectTo(blendMultiply); + texture.connectTo(blendMultiply, { output: "a" }); + cSplitter.connectTo(blendMultiply, { output: "a" }); + const fragmentOutput = new FragmentOutputBlock("FragmentOutput"); + blendMultiply.connectTo(fragmentOutput); + // Add to nodes + this.addOutputNode(fragmentOutput); + this._mode = NodeMaterialModes.Particle; + } + /** + * Loads the current Node Material from a url pointing to a file save by the Node Material Editor + * @deprecated Please use NodeMaterial.ParseFromFileAsync instead + * @param url defines the url to load from + * @param rootUrl defines the root URL for nested url in the node material + * @returns a promise that will fulfil when the material is fully loaded + */ + async loadAsync(url, rootUrl = "") { + return NodeMaterial.ParseFromFileAsync("", url, this.getScene(), rootUrl, true, this); + } + _gatherBlocks(rootNode, list) { + if (list.indexOf(rootNode) !== -1) { + return; + } + list.push(rootNode); + for (const input of rootNode.inputs) { + const connectedPoint = input.connectedPoint; + if (connectedPoint) { + const block = connectedPoint.ownerBlock; + if (block !== rootNode) { + this._gatherBlocks(block, list); + } + } + } + // Teleportation + if (rootNode.isTeleportOut) { + const block = rootNode; + if (block.entryPoint) { + this._gatherBlocks(block.entryPoint, list); + } + } + } + /** + * Generate a string containing the code declaration required to create an equivalent of this material + * @returns a string + */ + generateCode() { + let alreadyDumped = []; + const vertexBlocks = []; + const uniqueNames = ["const", "var", "let"]; + // Gets active blocks + for (const outputNode of this._vertexOutputNodes) { + this._gatherBlocks(outputNode, vertexBlocks); + } + const fragmentBlocks = []; + for (const outputNode of this._fragmentOutputNodes) { + this._gatherBlocks(outputNode, fragmentBlocks); + } + // Generate vertex shader + let codeString = `var nodeMaterial = new BABYLON.NodeMaterial("${this.name || "node material"}");\n`; + codeString += `nodeMaterial.mode = BABYLON.NodeMaterialModes.${NodeMaterialModes[this.mode]};\n`; + for (const node of vertexBlocks) { + if (node.isInput && alreadyDumped.indexOf(node) === -1) { + codeString += node._dumpCode(uniqueNames, alreadyDumped); + } + } + // Generate fragment shader + for (const node of fragmentBlocks) { + if (node.isInput && alreadyDumped.indexOf(node) === -1) { + codeString += node._dumpCode(uniqueNames, alreadyDumped); + } + } + // Connections + alreadyDumped = []; + codeString += "\n// Connections\n"; + for (const node of this._vertexOutputNodes) { + codeString += node._dumpCodeForOutputConnections(alreadyDumped); + } + for (const node of this._fragmentOutputNodes) { + codeString += node._dumpCodeForOutputConnections(alreadyDumped); + } + // Output nodes + codeString += "\n// Output nodes\n"; + for (const node of this._vertexOutputNodes) { + codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\n`; + } + for (const node of this._fragmentOutputNodes) { + codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\n`; + } + codeString += `nodeMaterial.build();\n`; + return codeString; + } + /** + * Serializes this material in a JSON representation + * @param selectedBlocks defines an optional list of blocks to serialize + * @returns the serialized material object + */ + serialize(selectedBlocks) { + const serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this); + serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy + let blocks = []; + if (selectedBlocks) { + blocks = selectedBlocks; + } + else { + serializationObject.customType = "BABYLON.NodeMaterial"; + serializationObject.outputNodes = []; + // Outputs + for (const outputNode of this._vertexOutputNodes) { + this._gatherBlocks(outputNode, blocks); + serializationObject.outputNodes.push(outputNode.uniqueId); + } + for (const outputNode of this._fragmentOutputNodes) { + this._gatherBlocks(outputNode, blocks); + if (serializationObject.outputNodes.indexOf(outputNode.uniqueId) === -1) { + serializationObject.outputNodes.push(outputNode.uniqueId); + } + } + } + // Blocks + serializationObject.blocks = []; + for (const block of blocks) { + serializationObject.blocks.push(block.serialize()); + } + if (!selectedBlocks) { + for (const block of this.attachedBlocks) { + if (blocks.indexOf(block) !== -1) { + continue; + } + serializationObject.blocks.push(block.serialize()); + } + } + serializationObject.uniqueId = this.uniqueId; + return serializationObject; + } + _restoreConnections(block, source, map) { + for (const outputPoint of block.outputs) { + for (const candidate of source.blocks) { + const target = map[candidate.id]; + if (!target) { + continue; + } + for (const input of candidate.inputs) { + if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) { + const inputPoint = target.getInputByName(input.inputName); + if (!inputPoint || inputPoint.isConnected) { + continue; + } + outputPoint.connectTo(inputPoint, true); + this._restoreConnections(target, source, map); + continue; + } + } + } + } + } + /** + * Clear the current graph and load a new one from a serialization object + * @param source defines the JSON representation of the material + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @param merge defines whether or not the source must be merged or replace the current content + * @param urlRewriter defines a function used to rewrite urls + */ + parseSerializedObject(source, rootUrl = "", merge = false, urlRewriter) { + if (!merge) { + this.clear(); + } + const map = {}; + // Create blocks + for (const parsedBlock of source.blocks) { + const blockType = GetClass(parsedBlock.customType); + if (blockType) { + const block = new blockType(); + block._deserialize(parsedBlock, this.getScene(), rootUrl, urlRewriter); + map[parsedBlock.id] = block; + this.attachedBlocks.push(block); + } + } + // Reconnect teleportation + for (const block of this.attachedBlocks) { + if (block.isTeleportOut) { + const teleportOut = block; + const id = teleportOut._tempEntryPointUniqueId; + if (id) { + const source = map[id]; + source.attachToEndpoint(teleportOut); + } + } + } + // Connections - Starts with input blocks only (except if in "merge" mode where we scan all blocks) + for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) { + const parsedBlock = source.blocks[blockIndex]; + const block = map[parsedBlock.id]; + if (!block) { + continue; + } + if (block.inputs.length && !merge) { + continue; + } + this._restoreConnections(block, source, map); + } + // Outputs + if (source.outputNodes) { + for (const outputNodeId of source.outputNodes) { + this.addOutputNode(map[outputNodeId]); + } + } + // UI related info + if (source.locations || (source.editorData && source.editorData.locations)) { + const locations = source.locations || source.editorData.locations; + for (const location of locations) { + if (map[location.blockId]) { + location.blockId = map[location.blockId].uniqueId; + } + } + if (merge && this.editorData && this.editorData.locations) { + locations.concat(this.editorData.locations); + } + if (source.locations) { + this.editorData = { + locations: locations, + }; + } + else { + this.editorData = source.editorData; + this.editorData.locations = locations; + } + const blockMap = []; + for (const key in map) { + blockMap[key] = map[key].uniqueId; + } + this.editorData.map = blockMap; + } + this.comment = source.comment; + if (source.forceAlphaBlending !== undefined) { + this.forceAlphaBlending = source.forceAlphaBlending; + } + if (source.alphaMode !== undefined) { + this.alphaMode = source.alphaMode; + } + if (!merge) { + this._mode = source.mode ?? NodeMaterialModes.Material; + } + } + /** + * Clear the current graph and load a new one from a serialization object + * @param source defines the JSON representation of the material + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @param merge defines whether or not the source must be merged or replace the current content + * @deprecated Please use the parseSerializedObject method instead + */ + loadFromSerialization(source, rootUrl = "", merge = false) { + this.parseSerializedObject(source, rootUrl, merge); + } + /** + * Makes a duplicate of the current material. + * @param name defines the name to use for the new material + * @param shareEffect defines if the clone material should share the same effect (default is false) + * @returns the cloned material + */ + clone(name, shareEffect = false) { + const serializationObject = this.serialize(); + const clone = SerializationHelper.Clone(() => new NodeMaterial(name, this.getScene(), this.options), this); + clone.id = name; + clone.name = name; + clone.parseSerializedObject(serializationObject); + clone._buildId = this._buildId; + clone.build(false, !shareEffect); + return clone; + } + /** + * Awaits for all the material textures to be ready before resolving the returned promise. + * @returns A promise that resolves when the textures are ready. + */ + whenTexturesReadyAsync() { + // Ensures all textures are ready to render. + const textureReadyPromises = []; + this.getActiveTextures().forEach((texture) => { + const internalTexture = texture.getInternalTexture(); + if (internalTexture && !internalTexture.isReady) { + textureReadyPromises.push(new Promise((textureResolve, textureReject) => { + internalTexture.onLoadedObservable.addOnce(() => { + textureResolve(); + }); + internalTexture.onErrorObservable.addOnce((e) => { + textureReject(e); + }); + })); + } + }); + return Promise.all(textureReadyPromises); + } + /** + * Creates a node material from parsed material data + * @param source defines the JSON representation of the material + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @param shaderLanguage defines the language to use (GLSL by default) + * @returns a new node material + */ + static Parse(source, scene, rootUrl = "", shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + const nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(source.name, scene, { shaderLanguage: shaderLanguage }), source, scene, rootUrl); + nodeMaterial.parseSerializedObject(source, rootUrl); + nodeMaterial.build(); + return nodeMaterial; + } + /** + * Creates a node material from a snippet saved in a remote file + * @param name defines the name of the material to create + * @param url defines the url to load from + * @param scene defines the hosting scene + * @param rootUrl defines the root URL for nested url in the node material + * @param skipBuild defines whether to build the node material + * @param targetMaterial defines a material to use instead of creating a new one + * @param urlRewriter defines a function used to rewrite urls + * @param options defines options to be used with the node material + * @returns a promise that will resolve to the new node material + */ + static async ParseFromFileAsync(name, url, scene, rootUrl = "", skipBuild = false, targetMaterial, urlRewriter, options) { + const material = targetMaterial ?? new NodeMaterial(name, scene, options); + const data = await scene._loadFileAsync(url); + const serializationObject = JSON.parse(data); + material.parseSerializedObject(serializationObject, rootUrl, undefined, urlRewriter); + if (!skipBuild) { + material.build(); + } + return material; + } + /** + * Creates a node material from a snippet saved by the node material editor + * @param snippetId defines the snippet to load + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @param nodeMaterial defines a node material to update (instead of creating a new one) + * @param skipBuild defines whether to build the node material + * @param waitForTextureReadyness defines whether to wait for texture readiness resolving the promise (default: false) + * @param urlRewriter defines a function used to rewrite urls + * @param options defines options to be used with the node material + * @returns a promise that will resolve to the new node material + */ + static ParseFromSnippetAsync(snippetId, scene = EngineStore.LastCreatedScene, rootUrl = "", nodeMaterial, skipBuild = false, waitForTextureReadyness = false, urlRewriter, options) { + if (snippetId === "_BLANK") { + return Promise.resolve(NodeMaterial.CreateDefault("blank", scene)); + } + return new Promise((resolve, reject) => { + const request = new WebRequest(); + request.addEventListener("readystatechange", () => { + if (request.readyState == 4) { + if (request.status == 200) { + const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); + const serializationObject = JSON.parse(snippet.nodeMaterial); + if (!nodeMaterial) { + nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(snippetId, scene, options), serializationObject, scene, rootUrl); + nodeMaterial.uniqueId = scene.getUniqueId(); + } + nodeMaterial.parseSerializedObject(serializationObject, undefined, undefined, urlRewriter); + nodeMaterial.snippetId = snippetId; + // We reset sideOrientation to default value + nodeMaterial.sideOrientation = null; + try { + if (!skipBuild) { + nodeMaterial.build(); + } + } + catch (err) { + reject(err); + } + if (waitForTextureReadyness) { + nodeMaterial + .whenTexturesReadyAsync() + .then(() => { + resolve(nodeMaterial); + }) + .catch((err) => { + reject(err); + }); + } + else { + resolve(nodeMaterial); + } + } + else { + reject("Unable to load the snippet " + snippetId); + } + } + }); + request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); + request.send(); + }); + } + /** + * Creates a new node material set to default basic configuration + * @param name defines the name of the material + * @param scene defines the hosting scene + * @returns a new NodeMaterial + */ + static CreateDefault(name, scene) { + const newMaterial = new NodeMaterial(name, scene); + newMaterial.setToDefault(); + newMaterial.build(); + return newMaterial; + } +} +NodeMaterial._BuildIdGenerator = 0; +/** Define the Url to load node editor script */ +NodeMaterial.EditorURL = `${Tools._DefaultCdnUrl}/v${AbstractEngine.Version}/nodeEditor/babylon.nodeEditor.js`; +/** Define the Url to load snippets */ +NodeMaterial.SnippetUrl = `https://snippet.babylonjs.com`; +/** Gets or sets a boolean indicating that node materials should not deserialize textures from json / snippet content */ +NodeMaterial.IgnoreTexturesAtLoadTime = false; +/** Defines default shader language when no option is defined */ +NodeMaterial.DefaultShaderLanguage = 0 /* ShaderLanguage.GLSL */; +/** If true, the node material will use GLSL if the engine is WebGL and WGSL if it's WebGPU. It takes priority over DefaultShaderLanguage if it's true */ +NodeMaterial.UseNativeShaderLanguageOfEngine = false; +__decorate([ + serialize() +], NodeMaterial.prototype, "ignoreAlpha", void 0); +__decorate([ + serialize() +], NodeMaterial.prototype, "maxSimultaneousLights", void 0); +__decorate([ + serialize("mode") +], NodeMaterial.prototype, "_mode", void 0); +__decorate([ + serialize("comment") +], NodeMaterial.prototype, "comment", void 0); +__decorate([ + serialize() +], NodeMaterial.prototype, "forceAlphaBlending", void 0); +RegisterClass("BABYLON.NodeMaterial", NodeMaterial); + +/** + * @internal + */ +SubMesh.prototype._projectOnTrianglesToRef = function (vector, positions, indices, step, checkStopper, ref) { + // Triangles test + const proj = TmpVectors.Vector3[0]; + const tmp = TmpVectors.Vector3[1]; + let distance = +Infinity; + for (let index = this.indexStart; index < this.indexStart + this.indexCount - (3 - step); index += step) { + const indexA = indices[index]; + const indexB = indices[index + 1]; + const indexC = indices[index + 2]; + if (checkStopper && indexC === 0xffffffff) { + index += 2; + continue; + } + const p0 = positions[indexA]; + const p1 = positions[indexB]; + const p2 = positions[indexC]; + // stay defensive and don't check against undefined positions. + if (!p0 || !p1 || !p2) { + continue; + } + const tmpDist = Vector3.ProjectOnTriangleToRef(vector, p0, p1, p2, tmp); + if (tmpDist < distance) { + proj.copyFrom(tmp); + distance = tmpDist; + } + } + ref.copyFrom(proj); + return distance; +}; +/** + * @internal + */ +SubMesh.prototype._projectOnUnIndexedTrianglesToRef = function (vector, positions, indices, ref) { + // Triangles test + const proj = TmpVectors.Vector3[0]; + const tmp = TmpVectors.Vector3[1]; + let distance = +Infinity; + for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) { + const p0 = positions[index]; + const p1 = positions[index + 1]; + const p2 = positions[index + 2]; + const tmpDist = Vector3.ProjectOnTriangleToRef(vector, p0, p1, p2, tmp); + if (tmpDist < distance) { + proj.copyFrom(tmp); + distance = tmpDist; + } + } + ref.copyFrom(proj); + return distance; +}; +SubMesh.prototype.projectToRef = function (vector, positions, indices, ref) { + const material = this.getMaterial(); + if (!material) { + return -1; + } + let step = 3; + let checkStopper = false; + switch (material.fillMode) { + case 3: + case 5: + case 6: + case 8: + return -1; + case 7: + step = 1; + checkStopper = true; + break; + } + // LineMesh first as it's also a Mesh... + if (material.fillMode === 4) { + return -1; + } + else { + // Check if mesh is unindexed + if (!indices.length && this._mesh._unIndexed) { + return this._projectOnUnIndexedTrianglesToRef(vector, positions, indices, ref); + } + return this._projectOnTrianglesToRef(vector, positions, indices, step, checkStopper, ref); + } +}; + +// Tracks the interaction animation state when using a motion controller with a near interaction orb +var ControllerOrbAnimationState; +(function (ControllerOrbAnimationState) { + /** + * Orb is invisible + */ + ControllerOrbAnimationState[ControllerOrbAnimationState["DEHYDRATED"] = 0] = "DEHYDRATED"; + /** + * Orb is visible and inside the hover range + */ + ControllerOrbAnimationState[ControllerOrbAnimationState["HOVER"] = 1] = "HOVER"; + /** + * Orb is visible and touching a near interaction target + */ + ControllerOrbAnimationState[ControllerOrbAnimationState["TOUCH"] = 2] = "TOUCH"; +})(ControllerOrbAnimationState || (ControllerOrbAnimationState = {})); +/** + * Where should the near interaction mesh be attached to when using a motion controller for near interaction + */ +var WebXRNearControllerMode; +(function (WebXRNearControllerMode) { + /** + * Motion controllers will not support near interaction + */ + WebXRNearControllerMode[WebXRNearControllerMode["DISABLED"] = 0] = "DISABLED"; + /** + * The interaction point for motion controllers will be inside of them + */ + WebXRNearControllerMode[WebXRNearControllerMode["CENTERED_ON_CONTROLLER"] = 1] = "CENTERED_ON_CONTROLLER"; + /** + * The interaction point for motion controllers will be in front of the controller + */ + WebXRNearControllerMode[WebXRNearControllerMode["CENTERED_IN_FRONT"] = 2] = "CENTERED_IN_FRONT"; +})(WebXRNearControllerMode || (WebXRNearControllerMode = {})); +const _tmpVectors = [new Vector3(), new Vector3(), new Vector3(), new Vector3()]; +/** + * A module that will enable near interaction near interaction for hands and motion controllers of XR Input Sources + */ +class WebXRNearInteraction extends WebXRAbstractFeature { + /** + * constructs a new background remover module + * @param _xrSessionManager the session manager for this module + * @param _options read-only options to be used in this module + */ + constructor(_xrSessionManager, _options) { + super(_xrSessionManager); + this._options = _options; + this._tmpRay = new Ray(new Vector3(), new Vector3()); + this._attachController = (xrController) => { + if (this._controllers[xrController.uniqueId]) { + // already attached + return; + } + // get two new meshes + const { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction } = this._generateNewTouchPointMesh(); + const selectionMesh = this._generateVisualCue(); + this._controllers[xrController.uniqueId] = { + xrController, + meshUnderPointer: null, + nearInteractionTargetMesh: null, + pick: null, + stalePick: null, + touchCollisionMesh, + touchCollisionMeshFunction: touchCollisionMeshFunction, + hydrateCollisionMeshFunction: hydrateCollisionMeshFunction, + currentAnimationState: ControllerOrbAnimationState.DEHYDRATED, + grabRay: new Ray(new Vector3(), new Vector3()), + hoverInteraction: false, + nearInteraction: false, + grabInteraction: false, + downTriggered: false, + id: WebXRNearInteraction._IdCounter++, + pickedPointVisualCue: selectionMesh, + }; + this._controllers[xrController.uniqueId]._worldScaleObserver = + this._controllers[xrController.uniqueId]._worldScaleObserver || + this._xrSessionManager.onWorldScaleFactorChangedObservable.add((values) => { + if (values.newScaleFactor !== values.previousScaleFactor) { + this._controllers[xrController.uniqueId].touchCollisionMesh.dispose(); + this._controllers[xrController.uniqueId].pickedPointVisualCue.dispose(); + const { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction } = this._generateNewTouchPointMesh(); + this._controllers[xrController.uniqueId].touchCollisionMesh = touchCollisionMesh; + this._controllers[xrController.uniqueId].touchCollisionMeshFunction = touchCollisionMeshFunction; + this._controllers[xrController.uniqueId].hydrateCollisionMeshFunction = hydrateCollisionMeshFunction; + this._controllers[xrController.uniqueId].pickedPointVisualCue = this._generateVisualCue(); + } + }); + if (this._attachedController) { + if (!this._options.enableNearInteractionOnAllControllers && + this._options.preferredHandedness && + xrController.inputSource.handedness === this._options.preferredHandedness) { + this._attachedController = xrController.uniqueId; + } + } + else { + if (!this._options.enableNearInteractionOnAllControllers) { + this._attachedController = xrController.uniqueId; + } + } + switch (xrController.inputSource.targetRayMode) { + case "tracked-pointer": + return this._attachNearInteractionMode(xrController); + case "gaze": + return null; + case "screen": + return null; + } + }; + this._controllers = {}; + this._farInteractionFeature = null; + /** + * default color of the selection ring + */ + this.selectionMeshDefaultColor = new Color3(0.8, 0.8, 0.8); + /** + * This color will be applied to the selection ring when selection is triggered + */ + this.selectionMeshPickedColor = new Color3(0.3, 0.3, 1.0); + /** + * If set to true, the selection mesh will always be hidden. Otherwise it will be shown only when needed + */ + this.alwaysHideSelectionMesh = false; + this._hoverRadius = 0.1; + this._pickRadius = 0.02; + this._controllerPickRadius = 0.03; // The radius is slightly larger here to make it easier to manipulate since it's not tied to the hand position + this._nearGrabLengthScale = 5; + this._scene = this._xrSessionManager.scene; + if (this._options.nearInteractionControllerMode === undefined) { + this._options.nearInteractionControllerMode = 2 /* WebXRNearControllerMode.CENTERED_IN_FRONT */; + } + if (this._options.farInteractionFeature) { + this._farInteractionFeature = this._options.farInteractionFeature; + } + } + /** + * Attach this feature + * Will usually be called by the features manager + * + * @returns true if successful. + */ + attach() { + if (!super.attach()) { + return false; + } + this._options.xrInput.controllers.forEach(this._attachController); + this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController); + this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => { + // REMOVE the controller + this._detachController(controller.uniqueId); + }); + this._scene.constantlyUpdateMeshUnderPointer = true; + return true; + } + /** + * Detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + if (!super.detach()) { + return false; + } + Object.keys(this._controllers).forEach((controllerId) => { + this._detachController(controllerId); + }); + return true; + } + /** + * Will get the mesh under a specific pointer. + * `scene.meshUnderPointer` will only return one mesh - either left or right. + * @param controllerId the controllerId to check + * @returns The mesh under pointer or null if no mesh is under the pointer + */ + getMeshUnderPointer(controllerId) { + if (this._controllers[controllerId]) { + return this._controllers[controllerId].meshUnderPointer; + } + else { + return null; + } + } + /** + * Get the xr controller that correlates to the pointer id in the pointer event + * + * @param id the pointer id to search for + * @returns the controller that correlates to this id or null if not found + */ + getXRControllerByPointerId(id) { + const keys = Object.keys(this._controllers); + for (let i = 0; i < keys.length; ++i) { + if (this._controllers[keys[i]].id === id) { + return this._controllers[keys[i]].xrController || null; + } + } + return null; + } + /** + * This function sets webXRControllerPointerSelection feature that will be disabled when + * the hover range is reached for a mesh and will be reattached when not in hover range. + * This is used to remove the selection rays when moving. + * @param farInteractionFeature the feature to disable when finger is in hover range for a mesh + */ + setFarInteractionFeature(farInteractionFeature) { + this._farInteractionFeature = farInteractionFeature; + } + /** + * Filter used for near interaction pick and hover + * @param mesh the mesh candidate to be pick-filtered + * @returns if the mesh should be included in the list of candidate meshes for near interaction + */ + _nearPickPredicate(mesh) { + return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearPickable; + } + /** + * Filter used for near interaction grab + * @param mesh the mesh candidate to be pick-filtered + * @returns if the mesh should be included in the list of candidate meshes for near interaction + */ + _nearGrabPredicate(mesh) { + return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearGrabbable; + } + /** + * Filter used for any near interaction + * @param mesh the mesh candidate to be pick-filtered + * @returns if the mesh should be included in the list of candidate meshes for near interaction + */ + _nearInteractionPredicate(mesh) { + return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && (mesh.isNearPickable || mesh.isNearGrabbable); + } + _controllerAvailablePredicate(mesh, controllerId) { + let parent = mesh; + while (parent) { + if (parent.reservedDataStore && parent.reservedDataStore.nearInteraction && parent.reservedDataStore.nearInteraction.excludedControllerId === controllerId) { + return false; + } + parent = parent.parent; + } + return true; + } + _handleTransitionAnimation(controllerData, newState) { + if (controllerData.currentAnimationState === newState || + this._options.nearInteractionControllerMode !== 2 /* WebXRNearControllerMode.CENTERED_IN_FRONT */ || + !!controllerData.xrController?.inputSource.hand) { + return; + } + // Don't always break to allow for animation fallthrough on rare cases of multi-transitions + if (newState > controllerData.currentAnimationState) { + switch (controllerData.currentAnimationState) { + case ControllerOrbAnimationState.DEHYDRATED: { + controllerData.hydrateCollisionMeshFunction(true); + if (newState === ControllerOrbAnimationState.HOVER) { + break; + } + } + // eslint-disable-next-line no-fallthrough + case ControllerOrbAnimationState.HOVER: { + controllerData.touchCollisionMeshFunction(true); + if (newState === ControllerOrbAnimationState.TOUCH) { + break; + } + } + } + } + else { + switch (controllerData.currentAnimationState) { + case ControllerOrbAnimationState.TOUCH: { + controllerData.touchCollisionMeshFunction(false); + if (newState === ControllerOrbAnimationState.HOVER) { + break; + } + } + // eslint-disable-next-line no-fallthrough + case ControllerOrbAnimationState.HOVER: { + controllerData.hydrateCollisionMeshFunction(false); + if (newState === ControllerOrbAnimationState.DEHYDRATED) { + break; + } + } + } + } + controllerData.currentAnimationState = newState; + } + _processTouchPoint(id, position, orientation) { + const controllerData = this._controllers[id]; + // Position and orientation could be temporary values, se we take care of them before calling any functions that use temporary vectors/quaternions + controllerData.grabRay.origin.copyFrom(position); + orientation.toEulerAnglesToRef(TmpVectors.Vector3[0]); + controllerData.grabRay.direction.copyFrom(TmpVectors.Vector3[0]); + if (this._options.nearInteractionControllerMode === 2 /* WebXRNearControllerMode.CENTERED_IN_FRONT */ && !controllerData.xrController?.inputSource.hand) { + // offset the touch point in the direction the transform is facing + controllerData.xrController.getWorldPointerRayToRef(this._tmpRay); + controllerData.grabRay.origin.addInPlace(this._tmpRay.direction.scale(0.05)); + } + controllerData.grabRay.length = this._nearGrabLengthScale * this._hoverRadius * this._xrSessionManager.worldScalingFactor; + controllerData.touchCollisionMesh.position.copyFrom(controllerData.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor); + } + _onXRFrame(_xrFrame) { + Object.keys(this._controllers).forEach((id) => { + // only do this for the selected pointer + const controllerData = this._controllers[id]; + const handData = controllerData.xrController?.inputSource.hand; + // If near interaction is not enabled/available for this controller, return early + if ((!this._options.enableNearInteractionOnAllControllers && id !== this._attachedController) || + !controllerData.xrController || + (!handData && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad))) { + controllerData.pick = null; + return; + } + controllerData.hoverInteraction = false; + controllerData.nearInteraction = false; + // Every frame check collisions/input + if (controllerData.xrController) { + if (handData) { + const xrIndexTip = handData.get("index-finger-tip"); + if (xrIndexTip) { + const indexTipPose = _xrFrame.getJointPose(xrIndexTip, this._xrSessionManager.referenceSpace); + if (indexTipPose && indexTipPose.transform) { + const axisRHSMultiplier = this._scene.useRightHandedSystem ? 1 : -1; + TmpVectors.Vector3[0].set(indexTipPose.transform.position.x, indexTipPose.transform.position.y, indexTipPose.transform.position.z * axisRHSMultiplier); + TmpVectors.Quaternion[0].set(indexTipPose.transform.orientation.x, indexTipPose.transform.orientation.y, indexTipPose.transform.orientation.z * axisRHSMultiplier, indexTipPose.transform.orientation.w * axisRHSMultiplier); + this._processTouchPoint(id, TmpVectors.Vector3[0], TmpVectors.Quaternion[0]); + } + } + } + else if (controllerData.xrController.inputSource.gamepad && this._options.nearInteractionControllerMode !== 0 /* WebXRNearControllerMode.DISABLED */) { + let controllerPose = controllerData.xrController.pointer; + if (controllerData.xrController.grip && this._options.nearInteractionControllerMode === 1 /* WebXRNearControllerMode.CENTERED_ON_CONTROLLER */) { + controllerPose = controllerData.xrController.grip; + } + this._processTouchPoint(id, controllerPose.position, controllerPose.rotationQuaternion); + } + } + else { + return; + } + const accuratePickInfo = (originalScenePick, utilityScenePick) => { + let pick = null; + if (!utilityScenePick || !utilityScenePick.hit) { + // No hit in utility scene + pick = originalScenePick; + } + else if (!originalScenePick || !originalScenePick.hit) { + // No hit in original scene + pick = utilityScenePick; + } + else if (utilityScenePick.distance < originalScenePick.distance) { + // Hit is closer in utility scene + pick = utilityScenePick; + } + else { + // Hit is closer in original scene + pick = originalScenePick; + } + return pick; + }; + const populateNearInteractionInfo = (nearInteractionInfo) => { + let result = new PickingInfo(); + let nearInteractionAtOrigin = false; + const nearInteraction = nearInteractionInfo && nearInteractionInfo.pickedPoint && nearInteractionInfo.hit; + if (nearInteractionInfo?.pickedPoint) { + nearInteractionAtOrigin = nearInteractionInfo.pickedPoint.x === 0 && nearInteractionInfo.pickedPoint.y === 0 && nearInteractionInfo.pickedPoint.z === 0; + } + if (nearInteraction && !nearInteractionAtOrigin) { + result = nearInteractionInfo; + } + return result; + }; + // Don't perform touch logic while grabbing, to prevent triggering touch interactions while in the middle of a grab interaction + // Dont update cursor logic either - the cursor should already be visible for the grab to be in range, + // and in order to maintain its position on the target mesh it is parented for the duration of the grab. + if (!controllerData.grabInteraction) { + let pick = null; + // near interaction hover + let utilitySceneHoverPick = null; + if (this._options.useUtilityLayer && this._utilityLayerScene) { + utilitySceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius * this._xrSessionManager.worldScalingFactor, this._utilityLayerScene, (mesh) => this._nearInteractionPredicate(mesh)); + } + const originalSceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius * this._xrSessionManager.worldScalingFactor, this._scene, (mesh) => this._nearInteractionPredicate(mesh)); + const hoverPickInfo = accuratePickInfo(originalSceneHoverPick, utilitySceneHoverPick); + if (hoverPickInfo && hoverPickInfo.hit) { + pick = populateNearInteractionInfo(hoverPickInfo); + if (pick.hit) { + controllerData.hoverInteraction = true; + } + } + // near interaction pick + if (controllerData.hoverInteraction) { + let utilitySceneNearPick = null; + const radius = (handData ? this._pickRadius : this._controllerPickRadius) * this._xrSessionManager.worldScalingFactor; + if (this._options.useUtilityLayer && this._utilityLayerScene) { + utilitySceneNearPick = this._pickWithSphere(controllerData, radius, this._utilityLayerScene, (mesh) => this._nearPickPredicate(mesh)); + } + const originalSceneNearPick = this._pickWithSphere(controllerData, radius, this._scene, (mesh) => this._nearPickPredicate(mesh)); + const pickInfo = accuratePickInfo(originalSceneNearPick, utilitySceneNearPick); + const nearPick = populateNearInteractionInfo(pickInfo); + if (nearPick.hit) { + // Near pick takes precedence over hover interaction + pick = nearPick; + controllerData.nearInteraction = true; + } + } + controllerData.stalePick = controllerData.pick; + controllerData.pick = pick; + // Update mesh under pointer + if (controllerData.pick && controllerData.pick.pickedPoint && controllerData.pick.hit) { + controllerData.meshUnderPointer = controllerData.pick.pickedMesh; + controllerData.pickedPointVisualCue.position.copyFrom(controllerData.pick.pickedPoint); + controllerData.pickedPointVisualCue.isVisible = !this.alwaysHideSelectionMesh; + if (this._farInteractionFeature && this._farInteractionFeature.attached) { + this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, true); + } + } + else { + controllerData.meshUnderPointer = null; + controllerData.pickedPointVisualCue.isVisible = false; + if (this._farInteractionFeature && this._farInteractionFeature.attached) { + this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, false); + } + } + } + // Update the interaction animation. Only updates if the visible touch mesh is active + let state = ControllerOrbAnimationState.DEHYDRATED; + if (controllerData.grabInteraction || controllerData.nearInteraction) { + state = ControllerOrbAnimationState.TOUCH; + } + else if (controllerData.hoverInteraction) { + state = ControllerOrbAnimationState.HOVER; + } + this._handleTransitionAnimation(controllerData, state); + }); + } + get _utilityLayerScene() { + return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene; + } + _generateVisualCue() { + const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene; + const selectionMesh = CreateSphere("nearInteraction", { + diameter: 0.0035 * 3 * this._xrSessionManager.worldScalingFactor, + }, sceneToRenderTo); + selectionMesh.bakeCurrentTransformIntoVertices(); + selectionMesh.isPickable = false; + selectionMesh.isVisible = false; + selectionMesh.rotationQuaternion = Quaternion.Identity(); + const targetMat = new StandardMaterial("targetMat", sceneToRenderTo); + targetMat.specularColor = Color3.Black(); + targetMat.emissiveColor = this.selectionMeshDefaultColor; + targetMat.backFaceCulling = false; + selectionMesh.material = targetMat; + return selectionMesh; + } + _isControllerReadyForNearInteraction(id) { + if (this._farInteractionFeature) { + return this._farInteractionFeature._getPointerSelectionDisabledByPointerId(id); + } + return true; + } + _attachNearInteractionMode(xrController) { + const controllerData = this._controllers[xrController.uniqueId]; + const pointerEventInit = { + pointerId: controllerData.id, + pointerType: "xr-near", + }; + controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => { + if ((!this._options.enableNearInteractionOnAllControllers && xrController.uniqueId !== this._attachedController) || + !controllerData.xrController || + (!controllerData.xrController.inputSource.hand && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad))) { + return; + } + if (controllerData.pick) { + controllerData.pick.ray = controllerData.grabRay; + } + if (controllerData.pick && this._isControllerReadyForNearInteraction(controllerData.id)) { + this._scene.simulatePointerMove(controllerData.pick, pointerEventInit); + } + // Near pick pointer event + if (controllerData.nearInteraction && controllerData.pick && controllerData.pick.hit) { + if (!controllerData.nearInteractionTargetMesh) { + this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); + controllerData.nearInteractionTargetMesh = controllerData.meshUnderPointer; + controllerData.downTriggered = true; + } + } + else if (controllerData.nearInteractionTargetMesh && controllerData.stalePick) { + this._scene.simulatePointerUp(controllerData.stalePick, pointerEventInit); + controllerData.downTriggered = false; + controllerData.nearInteractionTargetMesh = null; + } + }); + const grabCheck = (pressed) => { + if (this._options.enableNearInteractionOnAllControllers || + (xrController.uniqueId === this._attachedController && this._isControllerReadyForNearInteraction(controllerData.id))) { + if (controllerData.pick) { + controllerData.pick.ray = controllerData.grabRay; + } + if (pressed && controllerData.pick && controllerData.meshUnderPointer && this._nearGrabPredicate(controllerData.meshUnderPointer)) { + controllerData.grabInteraction = true; + controllerData.pickedPointVisualCue.isVisible = false; + this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); + controllerData.downTriggered = true; + } + else if (!pressed && controllerData.pick && controllerData.grabInteraction) { + this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); + controllerData.downTriggered = false; + controllerData.grabInteraction = false; + controllerData.pickedPointVisualCue.isVisible = !this.alwaysHideSelectionMesh; + } + } + else { + if (pressed && !this._options.enableNearInteractionOnAllControllers && !this._options.disableSwitchOnClick) { + this._attachedController = xrController.uniqueId; + } + } + }; + if (xrController.inputSource.gamepad) { + const init = (motionController) => { + controllerData.squeezeComponent = motionController.getComponent("grasp"); + if (controllerData.squeezeComponent) { + controllerData.onSqueezeButtonChangedObserver = controllerData.squeezeComponent.onButtonStateChangedObservable.add((component) => { + if (component.changes.pressed) { + const pressed = component.changes.pressed.current; + grabCheck(pressed); + } + }); + } + else { + controllerData.selectionComponent = motionController.getMainComponent(); + controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => { + if (component.changes.pressed) { + const pressed = component.changes.pressed.current; + grabCheck(pressed); + } + }); + } + }; + if (xrController.motionController) { + init(xrController.motionController); + } + else { + xrController.onMotionControllerInitObservable.add(init); + } + } + else { + // use the select and squeeze events + const selectStartListener = (event) => { + if (controllerData.xrController && + event.inputSource === controllerData.xrController.inputSource && + controllerData.pick && + this._isControllerReadyForNearInteraction(controllerData.id) && + controllerData.meshUnderPointer && + this._nearGrabPredicate(controllerData.meshUnderPointer)) { + controllerData.grabInteraction = true; + controllerData.pickedPointVisualCue.isVisible = false; + this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); + controllerData.downTriggered = true; + } + }; + const selectEndListener = (event) => { + if (controllerData.xrController && + event.inputSource === controllerData.xrController.inputSource && + controllerData.pick && + this._isControllerReadyForNearInteraction(controllerData.id)) { + this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); + controllerData.grabInteraction = false; + controllerData.pickedPointVisualCue.isVisible = !this.alwaysHideSelectionMesh; + controllerData.downTriggered = false; + } + }; + controllerData.eventListeners = { + selectend: selectEndListener, + selectstart: selectStartListener, + }; + this._xrSessionManager.session.addEventListener("selectstart", selectStartListener); + this._xrSessionManager.session.addEventListener("selectend", selectEndListener); + } + } + _detachController(xrControllerUniqueId) { + const controllerData = this._controllers[xrControllerUniqueId]; + if (!controllerData) { + return; + } + if (controllerData.squeezeComponent) { + if (controllerData.onSqueezeButtonChangedObserver) { + controllerData.squeezeComponent.onButtonStateChangedObservable.remove(controllerData.onSqueezeButtonChangedObserver); + } + } + if (controllerData.selectionComponent) { + if (controllerData.onButtonChangedObserver) { + controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver); + } + } + if (controllerData.onFrameObserver) { + this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver); + } + if (controllerData.eventListeners) { + Object.keys(controllerData.eventListeners).forEach((eventName) => { + const func = controllerData.eventListeners && controllerData.eventListeners[eventName]; + if (func) { + this._xrSessionManager.session.removeEventListener(eventName, func); + } + }); + } + controllerData.touchCollisionMesh.dispose(); + controllerData.pickedPointVisualCue.dispose(); + this._xrSessionManager.runInXRFrame(() => { + if (!controllerData.downTriggered) { + return; + } + // Fire a pointerup in case controller was detached before a pointerup event was fired + const pointerEventInit = { + pointerId: controllerData.id, + pointerType: "xr-near", + }; + this._scene.simulatePointerUp(new PickingInfo(), pointerEventInit); + }); + // remove world scale observer + if (controllerData._worldScaleObserver) { + this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(controllerData._worldScaleObserver); + } + // remove from the map + delete this._controllers[xrControllerUniqueId]; + if (this._attachedController === xrControllerUniqueId) { + // check for other controllers + const keys = Object.keys(this._controllers); + if (keys.length) { + this._attachedController = keys[0]; + } + else { + this._attachedController = ""; + } + } + } + _generateNewTouchPointMesh() { + const worldScale = this._xrSessionManager.worldScalingFactor; + // populate information for near hover, pick and pinch + const meshCreationScene = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene; + const touchCollisionMesh = CreateSphere("PickSphere", { diameter: 1 * worldScale }, meshCreationScene); + touchCollisionMesh.isVisible = false; + // Generate the material for the touch mesh visuals + if (this._options.motionControllerOrbMaterial) { + touchCollisionMesh.material = this._options.motionControllerOrbMaterial; + } + else { + let parsePromise; + if (this._options.motionControllerTouchMaterialSnippetUrl) { + parsePromise = NodeMaterial.ParseFromFileAsync("motionControllerTouchMaterial", this._options.motionControllerTouchMaterialSnippetUrl, meshCreationScene); + } + else { + parsePromise = NodeMaterial.ParseFromSnippetAsync("8RUNKL#3", meshCreationScene); + } + parsePromise + .then((mat) => { + touchCollisionMesh.material = mat; + }) + .catch((err) => { + Logger.Warn(`Error creating touch material in WebXRNearInteraction: ${err}`); + }); + } + const easingFunction = new QuadraticEase(); + easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT); + // Adjust the visual size based off of the size of the touch collision orb. + // Having the size perfectly match for hover gives a more accurate tell for when the user will start interacting with the target + // Sizes for other states are somewhat arbitrary, as they are based on what feels nice during an interaction + const hoverSizeVec = new Vector3(this._controllerPickRadius, this._controllerPickRadius, this._controllerPickRadius).scaleInPlace(worldScale); + const touchSize = this._controllerPickRadius * (4 / 3); + const touchSizeVec = new Vector3(touchSize, touchSize, touchSize).scaleInPlace(worldScale); + const hydrateTransitionSize = this._controllerPickRadius * (7 / 6); + const hydrateTransitionSizeVec = new Vector3(hydrateTransitionSize, hydrateTransitionSize, hydrateTransitionSize).scaleInPlace(worldScale); + const touchHoverTransitionSize = this._controllerPickRadius * (4 / 5); + const touchHoverTransitionSizeVec = new Vector3(touchHoverTransitionSize, touchHoverTransitionSize, touchHoverTransitionSize).scaleInPlace(worldScale); + const hoverTouchTransitionSize = this._controllerPickRadius * (3 / 2); + const hoverTouchTransitionSizeVec = new Vector3(hoverTouchTransitionSize, hoverTouchTransitionSize, hoverTouchTransitionSize).scaleInPlace(worldScale); + const touchKeys = [ + { frame: 0, value: hoverSizeVec }, + { frame: 10, value: hoverTouchTransitionSizeVec }, + { frame: 18, value: touchSizeVec }, + ]; + const releaseKeys = [ + { frame: 0, value: touchSizeVec }, + { frame: 10, value: touchHoverTransitionSizeVec }, + { frame: 18, value: hoverSizeVec }, + ]; + const hydrateKeys = [ + { frame: 0, value: Vector3.ZeroReadOnly }, + { frame: 12, value: hydrateTransitionSizeVec }, + { frame: 15, value: hoverSizeVec }, + ]; + const dehydrateKeys = [ + { frame: 0, value: hoverSizeVec }, + { frame: 10, value: Vector3.ZeroReadOnly }, + { frame: 15, value: Vector3.ZeroReadOnly }, + ]; + const touchAction = new Animation("touch", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT); + const releaseAction = new Animation("release", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT); + const hydrateAction = new Animation("hydrate", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT); + const dehydrateAction = new Animation("dehydrate", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT); + touchAction.setEasingFunction(easingFunction); + releaseAction.setEasingFunction(easingFunction); + hydrateAction.setEasingFunction(easingFunction); + dehydrateAction.setEasingFunction(easingFunction); + touchAction.setKeys(touchKeys); + releaseAction.setKeys(releaseKeys); + hydrateAction.setKeys(hydrateKeys); + dehydrateAction.setKeys(dehydrateKeys); + const touchCollisionMeshFunction = (isTouch) => { + const action = isTouch ? touchAction : releaseAction; + meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action], 0, 18, false, 1); + }; + const hydrateCollisionMeshFunction = (isHydration) => { + const action = isHydration ? hydrateAction : dehydrateAction; + if (isHydration) { + touchCollisionMesh.isVisible = true; + } + meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action], 0, 15, false, 1, () => { + if (!isHydration) { + touchCollisionMesh.isVisible = false; + } + }); + }; + return { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction }; + } + _pickWithSphere(controllerData, radius, sceneToUse, predicate) { + const pickingInfo = new PickingInfo(); + pickingInfo.distance = +Infinity; + if (controllerData.touchCollisionMesh && controllerData.xrController) { + const position = controllerData.touchCollisionMesh.position; + const sphere = BoundingSphere.CreateFromCenterAndRadius(position, radius); + for (let meshIndex = 0; meshIndex < sceneToUse.meshes.length; meshIndex++) { + const mesh = sceneToUse.meshes[meshIndex]; + if (!predicate(mesh) || !this._controllerAvailablePredicate(mesh, controllerData.xrController.uniqueId)) { + continue; + } + const result = WebXRNearInteraction.PickMeshWithSphere(mesh, sphere); + if (result && result.hit && result.distance < pickingInfo.distance) { + pickingInfo.hit = result.hit; + pickingInfo.pickedMesh = mesh; + pickingInfo.pickedPoint = result.pickedPoint; + pickingInfo.aimTransform = controllerData.xrController.pointer; + pickingInfo.gripTransform = controllerData.xrController.grip || null; + pickingInfo.originMesh = controllerData.touchCollisionMesh; + pickingInfo.distance = result.distance; + pickingInfo.bu = result.bu; + pickingInfo.bv = result.bv; + pickingInfo.faceId = result.faceId; + pickingInfo.subMeshId = result.subMeshId; + } + } + } + return pickingInfo; + } + /** + * Picks a mesh with a sphere + * @param mesh the mesh to pick + * @param sphere picking sphere in world coordinates + * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check + * @returns the picking info + */ + static PickMeshWithSphere(mesh, sphere, skipBoundingInfo = false) { + const subMeshes = mesh.subMeshes; + const pi = new PickingInfo(); + const boundingInfo = mesh.getBoundingInfo(); + if (!mesh._generatePointsArray()) { + return pi; + } + if (!mesh.subMeshes || !boundingInfo) { + return pi; + } + if (!skipBoundingInfo && !BoundingSphere.Intersects(boundingInfo.boundingSphere, sphere)) { + return pi; + } + const result = _tmpVectors[0]; + const tmpVec = _tmpVectors[1]; + _tmpVectors[2].setAll(0); + _tmpVectors[3].setAll(0); + const tmpRay = new Ray(_tmpVectors[2], _tmpVectors[3], 1); + let distance = +Infinity; + let tmp, tmpDistanceSphereToCenter, tmpDistanceSurfaceToCenter, intersectionInfo; + const center = TmpVectors.Vector3[2]; + const worldToMesh = TmpVectors.Matrix[0]; + worldToMesh.copyFrom(mesh.getWorldMatrix()); + worldToMesh.invert(); + Vector3.TransformCoordinatesToRef(sphere.center, worldToMesh, center); + for (let index = 0; index < subMeshes.length; index++) { + const subMesh = subMeshes[index]; + subMesh.projectToRef(center, mesh._positions, mesh.getIndices(), tmpVec); + Vector3.TransformCoordinatesToRef(tmpVec, mesh.getWorldMatrix(), tmpVec); + tmp = Vector3.Distance(tmpVec, sphere.center); + // Check for finger inside of mesh + tmpDistanceSurfaceToCenter = Vector3.DistanceSquared(tmpVec, mesh.getAbsolutePosition()); + tmpDistanceSphereToCenter = Vector3.DistanceSquared(sphere.center, mesh.getAbsolutePosition()); + if (tmpDistanceSphereToCenter !== -1 && tmpDistanceSurfaceToCenter !== -1 && tmpDistanceSurfaceToCenter > tmpDistanceSphereToCenter) { + tmp = 0; + tmpVec.copyFrom(sphere.center); + } + if (tmp !== -1 && tmp < distance) { + distance = tmp; + // ray between the sphere center and the point on the mesh + Ray.CreateFromToToRef(sphere.center, tmpVec, tmpRay); + tmpRay.length = distance * 2; + intersectionInfo = tmpRay.intersectsMesh(mesh); + result.copyFrom(tmpVec); + } + } + if (distance < sphere.radius) { + pi.hit = true; + pi.distance = distance; + pi.pickedMesh = mesh; + pi.pickedPoint = result.clone(); + if (intersectionInfo && intersectionInfo.bu !== null && intersectionInfo.bv !== null) { + pi.faceId = intersectionInfo.faceId; + pi.subMeshId = intersectionInfo.subMeshId; + pi.bu = intersectionInfo.bu; + pi.bv = intersectionInfo.bv; + } + } + return pi; + } +} +WebXRNearInteraction._IdCounter = 200; +/** + * The module's name + */ +WebXRNearInteraction.Name = WebXRFeatureName.NEAR_INTERACTION; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRNearInteraction.Version = 1; +//Register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRNearInteraction.Name, (xrSessionManager, options) => { + return () => new WebXRNearInteraction(xrSessionManager, options); +}, WebXRNearInteraction.Version, true); + +/** + * Button which can be used to enter a different mode of XR + */ +class WebXREnterExitUIButton { + /** + * Creates a WebXREnterExitUIButton + * @param element button element + * @param sessionMode XR initialization session mode + * @param referenceSpaceType the type of reference space to be used + */ + constructor( + /** button element */ + element, + /** XR initialization options for the button */ + sessionMode, + /** Reference space type */ + referenceSpaceType) { + this.element = element; + this.sessionMode = sessionMode; + this.referenceSpaceType = referenceSpaceType; + } + /** + * Extendable function which can be used to update the button's visuals when the state changes + * @param activeButton the current active button in the UI + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + update(activeButton) { } +} +/** + * UI to allow the user to enter/exit XR mode + */ +class WebXREnterExitUI { + /** + * Construct a new EnterExit UI class + * + * @param _scene babylon scene object to use + * @param options (read-only) version of the options passed to this UI + */ + constructor(_scene, + /** version of the options passed to this UI */ + options) { + this._scene = _scene; + this.options = options; + this._activeButton = null; + this._buttons = []; + /** + * Fired every time the active button is changed. + * + * When xr is entered via a button that launches xr that button will be the callback parameter + * + * When exiting xr the callback parameter will be null) + */ + this.activeButtonChangedObservable = new Observable(); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + this._onSessionGranted = (evt) => { + // This section is for future reference. + // As per specs, evt.session.mode should have the supported session mode, but no browser supports it for now. + // // check if the session granted is the same as the one requested + // const grantedMode = (evt.session as any).mode; + // if (grantedMode) { + // this._buttons.some((btn, idx) => { + // if (btn.sessionMode === grantedMode) { + // this._enterXRWithButtonIndex(idx); + // return true; + // } + // return false; + // }); + // } else + if (this._helper) { + this._enterXRWithButtonIndex(0); + } + }; + this.overlay = document.createElement("div"); + this.overlay.classList.add("xr-button-overlay"); + // prepare for session granted event + if (!options.ignoreSessionGrantedEvent && navigator.xr) { + navigator.xr.addEventListener("sessiongranted", this._onSessionGranted); + } + // if served over HTTP, warn people. + // Hopefully the browsers will catch up + if (typeof window !== "undefined") { + if (window.location && window.location.protocol === "http:" && window.location.hostname !== "localhost") { + Tools.Warn("WebXR can only be served over HTTPS"); + throw new Error("WebXR can only be served over HTTPS"); + } + } + if (options.customButtons) { + this._buttons = options.customButtons; + } + else { + this.overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;"; + const sessionMode = options.sessionMode || "immersive-vr"; + const referenceSpaceType = options.referenceSpaceType || "local-floor"; + const url = typeof SVGSVGElement === "undefined" + ? "https://cdn.babylonjs.com/Assets/vrButton.png" + : "data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A"; + let css = ".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(" + + url + + "); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }"; + css += '.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}'; + const style = document.createElement("style"); + style.appendChild(document.createTextNode(css)); + document.getElementsByTagName("head")[0].appendChild(style); + const hmdBtn = document.createElement("button"); + hmdBtn.className = "babylonVRicon"; + hmdBtn.title = `${sessionMode} - ${referenceSpaceType}`; + this._buttons.push(new WebXREnterExitUIButton(hmdBtn, sessionMode, referenceSpaceType)); + this._buttons[this._buttons.length - 1].update = function (activeButton) { + this.element.style.display = activeButton === null || activeButton === this ? "" : "none"; + hmdBtn.className = "babylonVRicon" + (activeButton === this ? " vrdisplaypresenting" : ""); + }; + this._updateButtons(null); + } + const renderCanvas = _scene.getEngine().getInputElement(); + if (renderCanvas && renderCanvas.parentNode) { + renderCanvas.parentNode.appendChild(this.overlay); + _scene.onDisposeObservable.addOnce(() => { + this.dispose(); + }); + } + } + /** + * Set the helper to be used with this UI component. + * The UI is bound to an experience helper. If not provided the UI can still be used but the events should be registered by the developer. + * + * @param helper the experience helper to attach + * @param renderTarget an optional render target (in case it is created outside of the helper scope) + * @returns a promise that resolves when the ui is ready + */ + async setHelperAsync(helper, renderTarget) { + this._helper = helper; + this._renderTarget = renderTarget; + const supportedPromises = this._buttons.map((btn) => { + return helper.sessionManager.isSessionSupportedAsync(btn.sessionMode); + }); + helper.onStateChangedObservable.add((state) => { + if (state == 3 /* WebXRState.NOT_IN_XR */) { + this._updateButtons(null); + } + }); + const results = await Promise.all(supportedPromises); + results.forEach((supported, i) => { + if (supported) { + this.overlay.appendChild(this._buttons[i].element); + this._buttons[i].element.onclick = this._enterXRWithButtonIndex.bind(this, i); + } + else { + Tools.Warn(`Session mode "${this._buttons[i].sessionMode}" not supported in browser`); + } + }); + } + /** + * Creates UI to allow the user to enter/exit XR mode + * @param scene the scene to add the ui to + * @param helper the xr experience helper to enter/exit xr with + * @param options options to configure the UI + * @returns the created ui + */ + static async CreateAsync(scene, helper, options) { + const ui = new WebXREnterExitUI(scene, options); + await ui.setHelperAsync(helper, options.renderTarget || undefined); + return ui; + } + async _enterXRWithButtonIndex(idx = 0) { + if (this._helper.state == 2 /* WebXRState.IN_XR */) { + await this._helper.exitXRAsync(); + this._updateButtons(null); + } + else if (this._helper.state == 3 /* WebXRState.NOT_IN_XR */) { + try { + await this._helper.enterXRAsync(this._buttons[idx].sessionMode, this._buttons[idx].referenceSpaceType, this._renderTarget, { + optionalFeatures: this.options.optionalFeatures, + requiredFeatures: this.options.requiredFeatures, + }); + this._updateButtons(this._buttons[idx]); + } + catch (e) { + // make sure button is visible + this._updateButtons(null); + const element = this._buttons[idx].element; + const prevTitle = element.title; + element.title = "Error entering XR session : " + prevTitle; + element.classList.add("xr-error"); + if (this.options.onError) { + this.options.onError(e); + } + } + } + } + /** + * Disposes of the XR UI component + */ + dispose() { + const renderCanvas = this._scene.getEngine().getInputElement(); + if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this.overlay)) { + renderCanvas.parentNode.removeChild(this.overlay); + } + this.activeButtonChangedObservable.clear(); + navigator.xr.removeEventListener("sessiongranted", this._onSessionGranted); + } + _updateButtons(activeButton) { + this._activeButton = activeButton; + this._buttons.forEach((b) => { + b.update(this._activeButton); + }); + this.activeButtonChangedObservable.notifyObservers(this._activeButton); + } +} + +/** + * Parts of the hands divided to writs and finger names + */ +var HandPart; +(function (HandPart) { + /** + * HandPart - Wrist + */ + HandPart["WRIST"] = "wrist"; + /** + * HandPart - The thumb + */ + HandPart["THUMB"] = "thumb"; + /** + * HandPart - Index finger + */ + HandPart["INDEX"] = "index"; + /** + * HandPart - Middle finger + */ + HandPart["MIDDLE"] = "middle"; + /** + * HandPart - Ring finger + */ + HandPart["RING"] = "ring"; + /** + * HandPart - Little finger + */ + HandPart["LITTLE"] = "little"; +})(HandPart || (HandPart = {})); +/** + * Joints of the hand as defined by the WebXR specification. + * https://immersive-web.github.io/webxr-hand-input/#skeleton-joints-section + */ +var WebXRHandJoint; +(function (WebXRHandJoint) { + /** Wrist */ + WebXRHandJoint["WRIST"] = "wrist"; + /** Thumb near wrist */ + WebXRHandJoint["THUMB_METACARPAL"] = "thumb-metacarpal"; + /** Thumb first knuckle */ + WebXRHandJoint["THUMB_PHALANX_PROXIMAL"] = "thumb-phalanx-proximal"; + /** Thumb second knuckle */ + WebXRHandJoint["THUMB_PHALANX_DISTAL"] = "thumb-phalanx-distal"; + /** Thumb tip */ + WebXRHandJoint["THUMB_TIP"] = "thumb-tip"; + /** Index finger near wrist */ + WebXRHandJoint["INDEX_FINGER_METACARPAL"] = "index-finger-metacarpal"; + /** Index finger first knuckle */ + WebXRHandJoint["INDEX_FINGER_PHALANX_PROXIMAL"] = "index-finger-phalanx-proximal"; + /** Index finger second knuckle */ + WebXRHandJoint["INDEX_FINGER_PHALANX_INTERMEDIATE"] = "index-finger-phalanx-intermediate"; + /** Index finger third knuckle */ + WebXRHandJoint["INDEX_FINGER_PHALANX_DISTAL"] = "index-finger-phalanx-distal"; + /** Index finger tip */ + WebXRHandJoint["INDEX_FINGER_TIP"] = "index-finger-tip"; + /** Middle finger near wrist */ + WebXRHandJoint["MIDDLE_FINGER_METACARPAL"] = "middle-finger-metacarpal"; + /** Middle finger first knuckle */ + WebXRHandJoint["MIDDLE_FINGER_PHALANX_PROXIMAL"] = "middle-finger-phalanx-proximal"; + /** Middle finger second knuckle */ + WebXRHandJoint["MIDDLE_FINGER_PHALANX_INTERMEDIATE"] = "middle-finger-phalanx-intermediate"; + /** Middle finger third knuckle */ + WebXRHandJoint["MIDDLE_FINGER_PHALANX_DISTAL"] = "middle-finger-phalanx-distal"; + /** Middle finger tip */ + WebXRHandJoint["MIDDLE_FINGER_TIP"] = "middle-finger-tip"; + /** Ring finger near wrist */ + WebXRHandJoint["RING_FINGER_METACARPAL"] = "ring-finger-metacarpal"; + /** Ring finger first knuckle */ + WebXRHandJoint["RING_FINGER_PHALANX_PROXIMAL"] = "ring-finger-phalanx-proximal"; + /** Ring finger second knuckle */ + WebXRHandJoint["RING_FINGER_PHALANX_INTERMEDIATE"] = "ring-finger-phalanx-intermediate"; + /** Ring finger third knuckle */ + WebXRHandJoint["RING_FINGER_PHALANX_DISTAL"] = "ring-finger-phalanx-distal"; + /** Ring finger tip */ + WebXRHandJoint["RING_FINGER_TIP"] = "ring-finger-tip"; + /** Pinky finger near wrist */ + WebXRHandJoint["PINKY_FINGER_METACARPAL"] = "pinky-finger-metacarpal"; + /** Pinky finger first knuckle */ + WebXRHandJoint["PINKY_FINGER_PHALANX_PROXIMAL"] = "pinky-finger-phalanx-proximal"; + /** Pinky finger second knuckle */ + WebXRHandJoint["PINKY_FINGER_PHALANX_INTERMEDIATE"] = "pinky-finger-phalanx-intermediate"; + /** Pinky finger third knuckle */ + WebXRHandJoint["PINKY_FINGER_PHALANX_DISTAL"] = "pinky-finger-phalanx-distal"; + /** Pinky finger tip */ + WebXRHandJoint["PINKY_FINGER_TIP"] = "pinky-finger-tip"; +})(WebXRHandJoint || (WebXRHandJoint = {})); +const handJointReferenceArray = [ + "wrist" /* WebXRHandJoint.WRIST */, + "thumb-metacarpal" /* WebXRHandJoint.THUMB_METACARPAL */, + "thumb-phalanx-proximal" /* WebXRHandJoint.THUMB_PHALANX_PROXIMAL */, + "thumb-phalanx-distal" /* WebXRHandJoint.THUMB_PHALANX_DISTAL */, + "thumb-tip" /* WebXRHandJoint.THUMB_TIP */, + "index-finger-metacarpal" /* WebXRHandJoint.INDEX_FINGER_METACARPAL */, + "index-finger-phalanx-proximal" /* WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL */, + "index-finger-phalanx-intermediate" /* WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE */, + "index-finger-phalanx-distal" /* WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL */, + "index-finger-tip" /* WebXRHandJoint.INDEX_FINGER_TIP */, + "middle-finger-metacarpal" /* WebXRHandJoint.MIDDLE_FINGER_METACARPAL */, + "middle-finger-phalanx-proximal" /* WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL */, + "middle-finger-phalanx-intermediate" /* WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE */, + "middle-finger-phalanx-distal" /* WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL */, + "middle-finger-tip" /* WebXRHandJoint.MIDDLE_FINGER_TIP */, + "ring-finger-metacarpal" /* WebXRHandJoint.RING_FINGER_METACARPAL */, + "ring-finger-phalanx-proximal" /* WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL */, + "ring-finger-phalanx-intermediate" /* WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE */, + "ring-finger-phalanx-distal" /* WebXRHandJoint.RING_FINGER_PHALANX_DISTAL */, + "ring-finger-tip" /* WebXRHandJoint.RING_FINGER_TIP */, + "pinky-finger-metacarpal" /* WebXRHandJoint.PINKY_FINGER_METACARPAL */, + "pinky-finger-phalanx-proximal" /* WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL */, + "pinky-finger-phalanx-intermediate" /* WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE */, + "pinky-finger-phalanx-distal" /* WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL */, + "pinky-finger-tip" /* WebXRHandJoint.PINKY_FINGER_TIP */, +]; +const handPartsDefinition = { + ["wrist" /* HandPart.WRIST */]: ["wrist" /* WebXRHandJoint.WRIST */], + ["thumb" /* HandPart.THUMB */]: ["thumb-metacarpal" /* WebXRHandJoint.THUMB_METACARPAL */, "thumb-phalanx-proximal" /* WebXRHandJoint.THUMB_PHALANX_PROXIMAL */, "thumb-phalanx-distal" /* WebXRHandJoint.THUMB_PHALANX_DISTAL */, "thumb-tip" /* WebXRHandJoint.THUMB_TIP */], + ["index" /* HandPart.INDEX */]: [ + "index-finger-metacarpal" /* WebXRHandJoint.INDEX_FINGER_METACARPAL */, + "index-finger-phalanx-proximal" /* WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL */, + "index-finger-phalanx-intermediate" /* WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE */, + "index-finger-phalanx-distal" /* WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL */, + "index-finger-tip" /* WebXRHandJoint.INDEX_FINGER_TIP */, + ], + ["middle" /* HandPart.MIDDLE */]: [ + "middle-finger-metacarpal" /* WebXRHandJoint.MIDDLE_FINGER_METACARPAL */, + "middle-finger-phalanx-proximal" /* WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL */, + "middle-finger-phalanx-intermediate" /* WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE */, + "middle-finger-phalanx-distal" /* WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL */, + "middle-finger-tip" /* WebXRHandJoint.MIDDLE_FINGER_TIP */, + ], + ["ring" /* HandPart.RING */]: [ + "ring-finger-metacarpal" /* WebXRHandJoint.RING_FINGER_METACARPAL */, + "ring-finger-phalanx-proximal" /* WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL */, + "ring-finger-phalanx-intermediate" /* WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE */, + "ring-finger-phalanx-distal" /* WebXRHandJoint.RING_FINGER_PHALANX_DISTAL */, + "ring-finger-tip" /* WebXRHandJoint.RING_FINGER_TIP */, + ], + ["little" /* HandPart.LITTLE */]: [ + "pinky-finger-metacarpal" /* WebXRHandJoint.PINKY_FINGER_METACARPAL */, + "pinky-finger-phalanx-proximal" /* WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL */, + "pinky-finger-phalanx-intermediate" /* WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE */, + "pinky-finger-phalanx-distal" /* WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL */, + "pinky-finger-tip" /* WebXRHandJoint.PINKY_FINGER_TIP */, + ], +}; +/** + * Representing a single hand (with its corresponding native XRHand object) + */ +class WebXRHand { + /** + * Get the hand mesh. + */ + get handMesh() { + return this._handMesh; + } + /** + * Get meshes of part of the hand. + * @param part The part of hand to get. + * @returns An array of meshes that correlate to the hand part requested. + */ + getHandPartMeshes(part) { + return handPartsDefinition[part].map((name) => this._jointMeshes[handJointReferenceArray.indexOf(name)]); + } + /** + * Retrieves a mesh linked to a named joint in the hand. + * @param jointName The name of the joint. + * @returns An AbstractMesh whose position corresponds with the joint position. + */ + getJointMesh(jointName) { + return this._jointMeshes[handJointReferenceArray.indexOf(jointName)]; + } + /** + * Construct a new hand object + * @param xrController The controller to which the hand correlates. + * @param _jointMeshes The meshes to be used to track the hand joints. + * @param _handMesh An optional hand mesh. + * @param rigMapping An optional rig mapping for the hand mesh. + * If not provided (but a hand mesh is provided), + * it will be assumed that the hand mesh's bones are named + * directly after the WebXR bone names. + * @param _leftHandedMeshes Are the hand meshes left-handed-system meshes + * @param _jointsInvisible Are the tracked joint meshes visible + * @param _jointScaleFactor Scale factor for all joint meshes + */ + constructor( + /** The controller to which the hand correlates. */ + xrController, _jointMeshes, _handMesh, + /** An optional rig mapping for the hand mesh. If not provided (but a hand mesh is provided), + * it will be assumed that the hand mesh's bones are named directly after the WebXR bone names. */ + rigMapping, _leftHandedMeshes = false, _jointsInvisible = false, _jointScaleFactor = 1) { + this.xrController = xrController; + this._jointMeshes = _jointMeshes; + this._handMesh = _handMesh; + this.rigMapping = rigMapping; + this._leftHandedMeshes = _leftHandedMeshes; + this._jointsInvisible = _jointsInvisible; + this._jointScaleFactor = _jointScaleFactor; + /** + * This observable will notify registered observers when the hand object has been set with a new mesh. + * you can get the hand mesh using `webxrHand.handMesh` + */ + this.onHandMeshSetObservable = new Observable(); + /** + * Transform nodes that will directly receive the transforms from the WebXR matrix data. + */ + this._jointTransforms = new Array(handJointReferenceArray.length); + /** + * The float array that will directly receive the transform matrix data from WebXR. + */ + this._jointTransformMatrices = new Float32Array(handJointReferenceArray.length * 16); + this._tempJointMatrix = new Matrix(); + /** + * The float array that will directly receive the joint radii from WebXR. + */ + this._jointRadii = new Float32Array(handJointReferenceArray.length); + this._scene = _jointMeshes[0].getScene(); + // Initialize the joint transform quaternions and link the transforms to the bones. + for (let jointIdx = 0; jointIdx < this._jointTransforms.length; jointIdx++) { + this._jointTransforms[jointIdx] = new TransformNode(handJointReferenceArray[jointIdx], this._scene); + this._jointTransforms[jointIdx].rotationQuaternion = new Quaternion(); + // Set the rotation quaternion so we can use it later for tracking. + if (_jointMeshes[jointIdx].rotationQuaternion) { + _jointMeshes[jointIdx].rotationQuaternion = new Quaternion(); + } + else { + _jointMeshes[jointIdx].rotationQuaternion?.set(0, 0, 0, 1); + } + } + if (_handMesh) { + // Note that this logic needs to happen after we initialize the joint tracking transform nodes. + this.setHandMesh(_handMesh, rigMapping); + } + // hide the motion controller, if available/loaded + if (this.xrController.motionController) { + if (this.xrController.motionController.rootMesh) { + this.xrController.motionController.rootMesh.dispose(false, true); + } + } + this.xrController.onMotionControllerInitObservable.add((motionController) => { + motionController._doNotLoadControllerMesh = true; + }); + } + /** + * Sets the current hand mesh to render for the WebXRHand. + * @param handMesh The rigged hand mesh that will be tracked to the user's hand. + * @param rigMapping The mapping from XRHandJoint to bone names to use with the mesh. + * @param _xrSessionManager The XRSessionManager used to initialize the hand mesh. + */ + setHandMesh(handMesh, rigMapping, _xrSessionManager) { + this._handMesh = handMesh; + // Avoid any strange frustum culling. We will manually control visibility via attach and detach. + handMesh.alwaysSelectAsActiveMesh = true; + handMesh.getChildMeshes().forEach((mesh) => { + mesh.alwaysSelectAsActiveMesh = true; + }); + // Link the bones in the hand mesh to the transform nodes that will be bound to the WebXR tracked joints. + if (this._handMesh.skeleton) { + const handMeshSkeleton = this._handMesh.skeleton; + handJointReferenceArray.forEach((jointName, jointIdx) => { + const jointBoneIdx = handMeshSkeleton.getBoneIndexByName(rigMapping ? rigMapping[jointName] : jointName); + if (jointBoneIdx !== -1) { + handMeshSkeleton.bones[jointBoneIdx].linkTransformNode(this._jointTransforms[jointIdx]); + } + }); + } + this.onHandMeshSetObservable.notifyObservers(this); + } + /** + * Update this hand from the latest xr frame. + * @param xrFrame The latest frame received from WebXR. + * @param referenceSpace The current viewer reference space. + */ + updateFromXRFrame(xrFrame, referenceSpace) { + const hand = this.xrController.inputSource.hand; + if (!hand) { + return; + } + // TODO: Modify webxr.d.ts to better match WebXR IDL so we don't need this any cast. + const anyHand = hand; + const jointSpaces = handJointReferenceArray.map((jointName) => anyHand[jointName] || hand.get(jointName)); + let trackingSuccessful = false; + if (xrFrame.fillPoses && xrFrame.fillJointRadii) { + trackingSuccessful = xrFrame.fillPoses(jointSpaces, referenceSpace, this._jointTransformMatrices) && xrFrame.fillJointRadii(jointSpaces, this._jointRadii); + } + else if (xrFrame.getJointPose) { + trackingSuccessful = true; + // Warning: This codepath is slow by comparison, only here for compat. + for (let jointIdx = 0; jointIdx < jointSpaces.length; jointIdx++) { + const jointPose = xrFrame.getJointPose(jointSpaces[jointIdx], referenceSpace); + if (jointPose) { + this._jointTransformMatrices.set(jointPose.transform.matrix, jointIdx * 16); + this._jointRadii[jointIdx] = jointPose.radius || 0.008; + } + else { + trackingSuccessful = false; + break; + } + } + } + if (!trackingSuccessful) { + return; + } + handJointReferenceArray.forEach((_jointName, jointIdx) => { + const jointTransform = this._jointTransforms[jointIdx]; + Matrix.FromArrayToRef(this._jointTransformMatrices, jointIdx * 16, this._tempJointMatrix); + this._tempJointMatrix.decompose(undefined, jointTransform.rotationQuaternion, jointTransform.position); + // The radius we need to make the joint in order for it to roughly cover the joints of the user's real hand. + const scaledJointRadius = this._jointRadii[jointIdx] * this._jointScaleFactor; + const jointMesh = this._jointMeshes[jointIdx]; + jointMesh.isVisible = !this._handMesh && !this._jointsInvisible; + jointMesh.position.copyFrom(jointTransform.position); + jointMesh.rotationQuaternion.copyFrom(jointTransform.rotationQuaternion); + jointMesh.scaling.setAll(scaledJointRadius); + // The WebXR data comes as right-handed, so we might need to do some conversions. + if (!this._scene.useRightHandedSystem) { + jointMesh.position.z *= -1; + jointMesh.rotationQuaternion.z *= -1; + jointMesh.rotationQuaternion.w *= -1; + if (this._leftHandedMeshes && this._handMesh) { + jointTransform.position.z *= -1; + jointTransform.rotationQuaternion.z *= -1; + jointTransform.rotationQuaternion.w *= -1; + } + } + }); + if (this._handMesh) { + this._handMesh.isVisible = true; + } + } + /** + * Dispose this Hand object + * @param disposeMeshes Should the meshes be disposed as well + */ + dispose(disposeMeshes = false) { + if (this._handMesh) { + if (disposeMeshes) { + this._handMesh.skeleton?.dispose(); + this._handMesh.dispose(false, true); + } + else { + this._handMesh.isVisible = false; + } + } + this._jointTransforms.forEach((transform) => transform.dispose()); + this._jointTransforms.length = 0; + this.onHandMeshSetObservable.clear(); + } +} +/** + * WebXR Hand Joint tracking feature, available for selected browsers and devices + */ +class WebXRHandTracking extends WebXRAbstractFeature { + static _GenerateTrackedJointMeshes(featureOptions, originalMesh = CreateIcoSphere("jointParent", WebXRHandTracking._ICOSPHERE_PARAMS)) { + const meshes = {}; + ["left", "right"].map((handedness) => { + const trackedMeshes = []; + originalMesh.isVisible = !!featureOptions.jointMeshes?.keepOriginalVisible; + for (let i = 0; i < handJointReferenceArray.length; ++i) { + let newInstance = originalMesh.createInstance(`${handedness}-handJoint-${i}`); + if (featureOptions.jointMeshes?.onHandJointMeshGenerated) { + const returnedMesh = featureOptions.jointMeshes.onHandJointMeshGenerated(newInstance, i, handedness); + if (returnedMesh) { + if (returnedMesh !== newInstance) { + newInstance.dispose(); + newInstance = returnedMesh; + } + } + } + newInstance.isPickable = false; + if (featureOptions.jointMeshes?.enablePhysics) { + const props = featureOptions.jointMeshes?.physicsProps || {}; + // downscale the instances so that physics will be initialized correctly + newInstance.scaling.setAll(0.02); + const type = props.impostorType !== undefined ? props.impostorType : PhysicsImpostor.SphereImpostor; + newInstance.physicsImpostor = new PhysicsImpostor(newInstance, type, { mass: 0, ...props }); + } + newInstance.rotationQuaternion = new Quaternion(); + newInstance.isVisible = false; + trackedMeshes.push(newInstance); + } + meshes[handedness] = trackedMeshes; + }); + return { left: meshes.left, right: meshes.right }; + } + static _GenerateDefaultHandMeshesAsync(scene, xrSessionManager, options) { + // eslint-disable-next-line no-async-promise-executor + return new Promise(async (resolve) => { + const riggedMeshes = {}; + // check the cache, defensive + if (WebXRHandTracking._RightHandGLB?.meshes[1]?.isDisposed()) { + WebXRHandTracking._RightHandGLB = null; + } + if (WebXRHandTracking._LeftHandGLB?.meshes[1]?.isDisposed()) { + WebXRHandTracking._LeftHandGLB = null; + } + const handsDefined = !!(WebXRHandTracking._RightHandGLB && WebXRHandTracking._LeftHandGLB); + // load them in parallel + const defaulrHandGLBUrl = Tools.GetAssetUrl(WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL); + const handGLBs = await Promise.all([ + WebXRHandTracking._RightHandGLB || SceneLoader.ImportMeshAsync("", defaulrHandGLBUrl, WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME, scene), + WebXRHandTracking._LeftHandGLB || SceneLoader.ImportMeshAsync("", defaulrHandGLBUrl, WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME, scene), + ]); + WebXRHandTracking._RightHandGLB = handGLBs[0]; + WebXRHandTracking._LeftHandGLB = handGLBs[1]; + const shaderUrl = Tools.GetAssetUrl(WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL); + const handShader = await NodeMaterial.ParseFromFileAsync("handShader", shaderUrl, scene, undefined, true); + // depth prepass and alpha mode + handShader.needDepthPrePass = true; + handShader.transparencyMode = Material.MATERIAL_ALPHABLEND; + handShader.alphaMode = 2; + // build node materials + handShader.build(false); + // shader + const handColors = { + base: Color3.FromInts(116, 63, 203), + fresnel: Color3.FromInts(149, 102, 229), + fingerColor: Color3.FromInts(177, 130, 255), + tipFresnel: Color3.FromInts(220, 200, 255), + ...options?.handMeshes?.customColors, + }; + const handNodes = { + base: handShader.getBlockByName("baseColor"), + fresnel: handShader.getBlockByName("fresnelColor"), + fingerColor: handShader.getBlockByName("fingerColor"), + tipFresnel: handShader.getBlockByName("tipFresnelColor"), + }; + handNodes.base.value = handColors.base; + handNodes.fresnel.value = handColors.fresnel; + handNodes.fingerColor.value = handColors.fingerColor; + handNodes.tipFresnel.value = handColors.tipFresnel; + const isMultiview = xrSessionManager._getBaseLayerWrapper()?.isMultiview; + ["left", "right"].forEach((handedness) => { + const handGLB = handedness == "left" ? WebXRHandTracking._LeftHandGLB : WebXRHandTracking._RightHandGLB; + if (!handGLB) { + // this should never happen! + throw new Error("Could not load hand model"); + } + const handMesh = handGLB.meshes[1]; + handMesh._internalAbstractMeshDataInfo._computeBonesUsingShaders = true; + // if in multiview do not use the material + if (!isMultiview && !options?.handMeshes?.disableHandShader) { + handMesh.material = handShader.clone(`${handedness}HandShaderClone`, true); + } + handMesh.isVisible = false; + riggedMeshes[handedness] = handMesh; + // single change for left handed systems + if (!handsDefined && !scene.useRightHandedSystem) { + handGLB.meshes[1].rotate(Axis.Y, Math.PI); + } + }); + handShader.dispose(); + resolve({ left: riggedMeshes.left, right: riggedMeshes.right }); + }); + } + /** + * Generates a mapping from XRHandJoint to bone name for the default hand mesh. + * @param handedness The handedness being mapped for. + * @returns A mapping from XRHandJoint to bone name. + */ + static _GenerateDefaultHandMeshRigMapping(handedness) { + const H = handedness == "right" ? "R" : "L"; + return { + ["wrist" /* WebXRHandJoint.WRIST */]: `wrist_${H}`, + ["thumb-metacarpal" /* WebXRHandJoint.THUMB_METACARPAL */]: `thumb_metacarpal_${H}`, + ["thumb-phalanx-proximal" /* WebXRHandJoint.THUMB_PHALANX_PROXIMAL */]: `thumb_proxPhalanx_${H}`, + ["thumb-phalanx-distal" /* WebXRHandJoint.THUMB_PHALANX_DISTAL */]: `thumb_distPhalanx_${H}`, + ["thumb-tip" /* WebXRHandJoint.THUMB_TIP */]: `thumb_tip_${H}`, + ["index-finger-metacarpal" /* WebXRHandJoint.INDEX_FINGER_METACARPAL */]: `index_metacarpal_${H}`, + ["index-finger-phalanx-proximal" /* WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL */]: `index_proxPhalanx_${H}`, + ["index-finger-phalanx-intermediate" /* WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE */]: `index_intPhalanx_${H}`, + ["index-finger-phalanx-distal" /* WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL */]: `index_distPhalanx_${H}`, + ["index-finger-tip" /* WebXRHandJoint.INDEX_FINGER_TIP */]: `index_tip_${H}`, + ["middle-finger-metacarpal" /* WebXRHandJoint.MIDDLE_FINGER_METACARPAL */]: `middle_metacarpal_${H}`, + ["middle-finger-phalanx-proximal" /* WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL */]: `middle_proxPhalanx_${H}`, + ["middle-finger-phalanx-intermediate" /* WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE */]: `middle_intPhalanx_${H}`, + ["middle-finger-phalanx-distal" /* WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL */]: `middle_distPhalanx_${H}`, + ["middle-finger-tip" /* WebXRHandJoint.MIDDLE_FINGER_TIP */]: `middle_tip_${H}`, + ["ring-finger-metacarpal" /* WebXRHandJoint.RING_FINGER_METACARPAL */]: `ring_metacarpal_${H}`, + ["ring-finger-phalanx-proximal" /* WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL */]: `ring_proxPhalanx_${H}`, + ["ring-finger-phalanx-intermediate" /* WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE */]: `ring_intPhalanx_${H}`, + ["ring-finger-phalanx-distal" /* WebXRHandJoint.RING_FINGER_PHALANX_DISTAL */]: `ring_distPhalanx_${H}`, + ["ring-finger-tip" /* WebXRHandJoint.RING_FINGER_TIP */]: `ring_tip_${H}`, + ["pinky-finger-metacarpal" /* WebXRHandJoint.PINKY_FINGER_METACARPAL */]: `little_metacarpal_${H}`, + ["pinky-finger-phalanx-proximal" /* WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL */]: `little_proxPhalanx_${H}`, + ["pinky-finger-phalanx-intermediate" /* WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE */]: `little_intPhalanx_${H}`, + ["pinky-finger-phalanx-distal" /* WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL */]: `little_distPhalanx_${H}`, + ["pinky-finger-tip" /* WebXRHandJoint.PINKY_FINGER_TIP */]: `little_tip_${H}`, + }; + } + /** + * Check if the needed objects are defined. + * This does not mean that the feature is enabled, but that the objects needed are well defined. + * @returns true if the needed objects for this feature are defined + */ + isCompatible() { + return typeof XRHand !== "undefined"; + } + /** + * Get the hand object according to the controller id + * @param controllerId the controller id to which we want to get the hand + * @returns null if not found or the WebXRHand object if found + */ + getHandByControllerId(controllerId) { + return this._attachedHands[controllerId]; + } + /** + * Get a hand object according to the requested handedness + * @param handedness the handedness to request + * @returns null if not found or the WebXRHand object if found + */ + getHandByHandedness(handedness) { + if (handedness == "none") { + return null; + } + return this._trackingHands[handedness]; + } + /** + * Creates a new instance of the XR hand tracking feature. + * @param _xrSessionManager An instance of WebXRSessionManager. + * @param options Options to use when constructing this feature. + */ + constructor(_xrSessionManager, + /** Options to use when constructing this feature. */ + options) { + super(_xrSessionManager); + this.options = options; + this._attachedHands = {}; + this._trackingHands = { left: null, right: null }; + this._handResources = { jointMeshes: null, handMeshes: null, rigMappings: null }; + this._worldScaleObserver = null; + /** + * This observable will notify registered observers when a new hand object was added and initialized + */ + this.onHandAddedObservable = new Observable(); + /** + * This observable will notify its observers right before the hand object is disposed + */ + this.onHandRemovedObservable = new Observable(); + this._attachHand = (xrController) => { + if (!xrController.inputSource.hand || xrController.inputSource.handedness == "none" || !this._handResources.jointMeshes) { + return; + } + const handedness = xrController.inputSource.handedness; + const webxrHand = new WebXRHand(xrController, this._handResources.jointMeshes[handedness], this._handResources.handMeshes && this._handResources.handMeshes[handedness], this._handResources.rigMappings && this._handResources.rigMappings[handedness], this.options.handMeshes?.meshesUseLeftHandedCoordinates, this.options.jointMeshes?.invisible, this.options.jointMeshes?.scaleFactor); + this._attachedHands[xrController.uniqueId] = webxrHand; + this._trackingHands[handedness] = webxrHand; + this.onHandAddedObservable.notifyObservers(webxrHand); + }; + this._detachHand = (xrController) => { + this._detachHandById(xrController.uniqueId); + }; + this.xrNativeFeatureName = "hand-tracking"; + // Support legacy versions of the options object by copying over joint mesh properties + const anyOptions = options; + const anyJointMeshOptions = anyOptions.jointMeshes; + if (anyJointMeshOptions) { + if (typeof anyJointMeshOptions.disableDefaultHandMesh !== "undefined") { + options.handMeshes = options.handMeshes || {}; + options.handMeshes.disableDefaultMeshes = anyJointMeshOptions.disableDefaultHandMesh; + } + if (typeof anyJointMeshOptions.handMeshes !== "undefined") { + options.handMeshes = options.handMeshes || {}; + options.handMeshes.customMeshes = anyJointMeshOptions.handMeshes; + } + if (typeof anyJointMeshOptions.leftHandedSystemMeshes !== "undefined") { + options.handMeshes = options.handMeshes || {}; + options.handMeshes.meshesUseLeftHandedCoordinates = anyJointMeshOptions.leftHandedSystemMeshes; + } + if (typeof anyJointMeshOptions.rigMapping !== "undefined") { + options.handMeshes = options.handMeshes || {}; + const leftRigMapping = {}; + const rightRigMapping = {}; + [ + [anyJointMeshOptions.rigMapping.left, leftRigMapping], + [anyJointMeshOptions.rigMapping.right, rightRigMapping], + ].forEach((rigMappingTuple) => { + const legacyRigMapping = rigMappingTuple[0]; + const rigMapping = rigMappingTuple[1]; + legacyRigMapping.forEach((modelJointName, index) => { + rigMapping[handJointReferenceArray[index]] = modelJointName; + }); + }); + options.handMeshes.customRigMappings = { + left: leftRigMapping, + right: rightRigMapping, + }; + } + } + } + /** + * Attach this feature. + * Will usually be called by the features manager. + * + * @returns true if successful. + */ + attach() { + if (!super.attach()) { + return false; + } + if (!this._handResources.jointMeshes) { + this._originalMesh = this._originalMesh || this.options.jointMeshes?.sourceMesh || CreateIcoSphere("jointParent", WebXRHandTracking._ICOSPHERE_PARAMS); + this._originalMesh.isVisible = false; + this._handResources.jointMeshes = WebXRHandTracking._GenerateTrackedJointMeshes(this.options, this._originalMesh); + } + this._handResources.handMeshes = this.options.handMeshes?.customMeshes || null; + this._handResources.rigMappings = this.options.handMeshes?.customRigMappings || null; + // If they didn't supply custom meshes and are not disabling the default meshes... + if (!this.options.handMeshes?.customMeshes && !this.options.handMeshes?.disableDefaultMeshes) { + WebXRHandTracking._GenerateDefaultHandMeshesAsync(EngineStore.LastCreatedScene, this._xrSessionManager, this.options).then((defaultHandMeshes) => { + this._handResources.handMeshes = defaultHandMeshes; + this._handResources.rigMappings = { + left: WebXRHandTracking._GenerateDefaultHandMeshRigMapping("left"), + right: WebXRHandTracking._GenerateDefaultHandMeshRigMapping("right"), + }; + // Apply meshes to existing hands if already tracking. + this._trackingHands.left?.setHandMesh(this._handResources.handMeshes.left, this._handResources.rigMappings.left, this._xrSessionManager); + this._trackingHands.right?.setHandMesh(this._handResources.handMeshes.right, this._handResources.rigMappings.right, this._xrSessionManager); + this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor); + this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor); + }); + this._worldScaleObserver = this._xrSessionManager.onWorldScaleFactorChangedObservable.add((scalingFactors) => { + if (this._handResources.handMeshes) { + this._handResources.handMeshes.left.scaling.scaleInPlace(scalingFactors.newScaleFactor / scalingFactors.previousScaleFactor); + this._handResources.handMeshes.right.scaling.scaleInPlace(scalingFactors.newScaleFactor / scalingFactors.previousScaleFactor); + } + }); + } + this.options.xrInput.controllers.forEach(this._attachHand); + this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable, this._attachHand); + this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable, this._detachHand); + return true; + } + _onXRFrame(_xrFrame) { + this._trackingHands.left?.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace); + this._trackingHands.right?.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace); + } + _detachHandById(controllerId, disposeMesh) { + const hand = this.getHandByControllerId(controllerId); + if (hand) { + const handedness = hand.xrController.inputSource.handedness == "left" ? "left" : "right"; + if (this._trackingHands[handedness]?.xrController.uniqueId === controllerId) { + this._trackingHands[handedness] = null; + } + this.onHandRemovedObservable.notifyObservers(hand); + hand.dispose(disposeMesh); + delete this._attachedHands[controllerId]; + } + } + /** + * Detach this feature. + * Will usually be called by the features manager. + * + * @returns true if successful. + */ + detach() { + if (!super.detach()) { + return false; + } + Object.keys(this._attachedHands).forEach((uniqueId) => this._detachHandById(uniqueId, this.options.handMeshes?.disposeOnSessionEnd)); + if (this.options.handMeshes?.disposeOnSessionEnd) { + if (this._handResources.jointMeshes) { + this._handResources.jointMeshes.left.forEach((trackedMesh) => trackedMesh.dispose()); + this._handResources.jointMeshes.right.forEach((trackedMesh) => trackedMesh.dispose()); + this._handResources.jointMeshes = null; + } + if (this._handResources.handMeshes) { + this._handResources.handMeshes.left.dispose(); + this._handResources.handMeshes.right.dispose(); + this._handResources.handMeshes = null; + } + WebXRHandTracking._RightHandGLB?.meshes.forEach((mesh) => mesh.dispose()); + WebXRHandTracking._LeftHandGLB?.meshes.forEach((mesh) => mesh.dispose()); + WebXRHandTracking._RightHandGLB = null; + WebXRHandTracking._LeftHandGLB = null; + this._originalMesh?.dispose(); + this._originalMesh = undefined; + } + // remove world scale observer + if (this._worldScaleObserver) { + this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver); + } + return true; + } + /** + * Dispose this feature and all of the resources attached. + */ + dispose() { + super.dispose(); + this.onHandAddedObservable.clear(); + this.onHandRemovedObservable.clear(); + if (this._handResources.handMeshes && !this.options.handMeshes?.customMeshes) { + // this will dispose the cached meshes + this._handResources.handMeshes.left.dispose(); + this._handResources.handMeshes.right.dispose(); + // remove the cached meshes + WebXRHandTracking._RightHandGLB?.meshes.forEach((mesh) => mesh.dispose()); + WebXRHandTracking._LeftHandGLB?.meshes.forEach((mesh) => mesh.dispose()); + WebXRHandTracking._RightHandGLB = null; + WebXRHandTracking._LeftHandGLB = null; + } + if (this._handResources.jointMeshes) { + this._handResources.jointMeshes.left.forEach((trackedMesh) => trackedMesh.dispose()); + this._handResources.jointMeshes.right.forEach((trackedMesh) => trackedMesh.dispose()); + } + } +} +/** + * The module's name + */ +WebXRHandTracking.Name = WebXRFeatureName.HAND_TRACKING; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRHandTracking.Version = 1; +/** The base URL for the default hand model. */ +WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL = "https://assets.babylonjs.com/core/HandMeshes/"; +/** The filename to use for the default right hand model. */ +WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME = "r_hand_rhs.glb"; +/** The filename to use for the default left hand model. */ +WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME = "l_hand_rhs.glb"; +/** The URL pointing to the default hand model NodeMaterial shader. */ +WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL = "https://assets.babylonjs.com/core/HandMeshes/handsShader.json"; +// We want to use lightweight models, diameter will initially be 1 but scaled to the values returned from WebXR. +WebXRHandTracking._ICOSPHERE_PARAMS = { radius: 0.5, flat: false, subdivisions: 2 }; +WebXRHandTracking._RightHandGLB = null; +WebXRHandTracking._LeftHandGLB = null; +//register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRHandTracking.Name, (xrSessionManager, options) => { + return () => new WebXRHandTracking(xrSessionManager, options); +}, WebXRHandTracking.Version, false); + +/** + * This is a teleportation feature to be used with WebXR-enabled motion controllers. + * When enabled and attached, the feature will allow a user to move around and rotate in the scene using + * the input of the attached controllers. + */ +class WebXRMotionControllerTeleportation extends WebXRAbstractFeature { + /** + * Is rotation enabled when moving forward? + * Disabling this feature will prevent the user from deciding the direction when teleporting + */ + get rotationEnabled() { + return this._rotationEnabled; + } + /** + * Sets whether rotation is enabled or not + * @param enabled is rotation enabled when teleportation is shown + */ + set rotationEnabled(enabled) { + this._rotationEnabled = enabled; + if (this._options.teleportationTargetMesh) { + const children = this._options.teleportationTargetMesh.getChildMeshes(false, (node) => node.name === "rotationCone"); + if (children[0]) { + children[0].setEnabled(enabled); + } + } + } + /** + * Exposes the currently set teleportation target mesh. + */ + get teleportationTargetMesh() { + return this._options.teleportationTargetMesh || null; + } + /** + * constructs a new teleportation system + * @param _xrSessionManager an instance of WebXRSessionManager + * @param _options configuration object for this feature + */ + constructor(_xrSessionManager, _options) { + super(_xrSessionManager); + this._options = _options; + this._controllers = {}; + this._snappedToPoint = false; + this._cachedColor4White = new Color4(1, 1, 1, 1); + this._tmpRay = new Ray(new Vector3(), new Vector3()); + this._tmpVector = new Vector3(); + this._tmpQuaternion = new Quaternion(); + this._worldScaleObserver = null; + /** + * Skip the next teleportation. This can be controlled by the user to prevent the user from teleportation + * to sections that are not yet "unlocked", but should still show the teleportation mesh. + */ + this.skipNextTeleportation = false; + /** + * Is movement backwards enabled + */ + this.backwardsMovementEnabled = true; + /** + * Distance to travel when moving backwards + */ + this.backwardsTeleportationDistance = 0.7; + /** + * The distance from the user to the inspection point in the direction of the controller + * A higher number will allow the user to move further + * defaults to 5 (meters, in xr units) + */ + this.parabolicCheckRadius = 5; + /** + * Should the module support parabolic ray on top of direct ray + * If enabled, the user will be able to point "at the sky" and move according to predefined radius distance + * Very helpful when moving between floors / different heights + */ + this.parabolicRayEnabled = true; + /** + * The second type of ray - straight line. + * Should it be enabled or should the parabolic line be the only one. + */ + this.straightRayEnabled = true; + /** + * How much rotation should be applied when rotating right and left + */ + this.rotationAngle = Math.PI / 8; + /** + * This observable will notify when the target mesh position was updated. + * The picking info it provides contains the point to which the target mesh will move () + */ + this.onTargetMeshPositionUpdatedObservable = new Observable(); + /** + * Is teleportation enabled. Can be used to allow rotation only. + */ + this.teleportationEnabled = true; + this._rotationEnabled = true; + /** + * Observable raised before camera rotation + */ + this.onBeforeCameraTeleportRotation = new Observable(); + /** + * Observable raised after camera rotation + */ + this.onAfterCameraTeleportRotation = new Observable(); + this._attachController = (xrController) => { + if (this._controllers[xrController.uniqueId] || (this._options.forceHandedness && xrController.inputSource.handedness !== this._options.forceHandedness)) { + // already attached + return; + } + this._controllers[xrController.uniqueId] = { + xrController, + teleportationState: { + forward: false, + backwards: false, + rotating: false, + currentRotation: 0, + baseRotation: 0, + blocked: false, + initialHit: false, + mainComponentUsed: false, + }, + }; + const controllerData = this._controllers[xrController.uniqueId]; + // motion controller only available to gamepad-enabled input sources. + if (controllerData.xrController.inputSource.targetRayMode === "tracked-pointer" && controllerData.xrController.inputSource.gamepad) { + // motion controller support + const initMotionController = () => { + if (xrController.motionController) { + const movementController = xrController.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE) || + xrController.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE); + if (!movementController || this._options.useMainComponentOnly) { + // use trigger to move on long press + const mainComponent = xrController.motionController.getMainComponent(); + if (!mainComponent) { + return; + } + controllerData.teleportationState.mainComponentUsed = true; + controllerData.teleportationComponent = mainComponent; + controllerData.onButtonChangedObserver = mainComponent.onButtonStateChangedObservable.add(() => { + if (!this.teleportationEnabled) { + return; + } + const teleportLocal = () => { + // simulate "forward" thumbstick push + controllerData.teleportationState.forward = true; + controllerData.teleportationState.initialHit = false; + this._currentTeleportationControllerId = controllerData.xrController.uniqueId; + controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y; + controllerData.teleportationState.currentRotation = 0; + const timeToSelect = this._options.timeToTeleport || 3000; + setAndStartTimer({ + timeout: timeToSelect, + contextObservable: this._xrSessionManager.onXRFrameObservable, + breakCondition: () => !mainComponent.pressed, + onEnded: () => { + if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId && controllerData.teleportationState.forward) { + this._teleportForward(xrController.uniqueId); + } + }, + }); + }; + // did "pressed" changed? + if (mainComponent.changes.pressed) { + if (mainComponent.changes.pressed.current) { + // delay if the start time is defined + if (this._options.timeToTeleportStart) { + setAndStartTimer({ + timeout: this._options.timeToTeleportStart, + contextObservable: this._xrSessionManager.onXRFrameObservable, + onEnded: () => { + // check if still pressed + if (mainComponent.pressed) { + teleportLocal(); + } + }, + }); + } + else { + teleportLocal(); + } + } + else { + controllerData.teleportationState.forward = false; + this._currentTeleportationControllerId = ""; + } + } + }); + } + else { + controllerData.teleportationComponent = movementController; + // use thumbstick (or touchpad if thumbstick not available) + controllerData.onAxisChangedObserver = movementController.onAxisValueChangedObservable.add((axesData) => { + if (axesData.y <= 0.7 && controllerData.teleportationState.backwards) { + controllerData.teleportationState.backwards = false; + } + if (axesData.y > 0.7 && !controllerData.teleportationState.forward && this.backwardsMovementEnabled && !this.snapPointsOnly) { + // teleport backwards + // General gist: Go Back N units, cast a ray towards the floor. If collided, move. + if (!controllerData.teleportationState.backwards) { + controllerData.teleportationState.backwards = true; + // teleport backwards ONCE + this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion); + this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector); + // get only the y rotation + this._tmpVector.x = 0; + this._tmpVector.z = 0; + // get the quaternion + Quaternion.FromEulerVectorToRef(this._tmpVector, this._tmpQuaternion); + this._tmpVector.set(0, 0, this.backwardsTeleportationDistance * (this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1)); + this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion, this._tmpVector); + this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position); + this._tmpRay.origin.copyFrom(this._tmpVector); + // This will prevent the user from "falling" to a lower platform! + // TODO - should this be a flag? 'allow falling to lower platforms'? + this._tmpRay.length = this._options.xrInput.xrCamera.realWorldHeight + 0.1; + // Right handed system had here "1" instead of -1. This is unneeded. + this._tmpRay.direction.set(0, -1, 0); + const pick = this._xrSessionManager.scene.pickWithRay(this._tmpRay, (o) => { + return this._floorMeshes.indexOf(o) !== -1; + }); + // pick must exist, but stay safe + if (pick && pick.pickedPoint) { + // Teleport the users feet to where they targeted. Ignore the Y axis. + // If the "falling to lower platforms" feature is implemented the Y axis should be set here as well + this._options.xrInput.xrCamera.position.x = pick.pickedPoint.x; + this._options.xrInput.xrCamera.position.z = pick.pickedPoint.z; + } + } + } + if (axesData.y < -0.7 && !this._currentTeleportationControllerId && !controllerData.teleportationState.rotating && this.teleportationEnabled) { + controllerData.teleportationState.forward = true; + this._currentTeleportationControllerId = controllerData.xrController.uniqueId; + controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y; + } + if (axesData.x) { + if (!controllerData.teleportationState.forward) { + if (!controllerData.teleportationState.rotating && Math.abs(axesData.x) > 0.7) { + // rotate in the right direction positive is right + controllerData.teleportationState.rotating = true; + const rotation = this.rotationAngle * (axesData.x > 0 ? 1 : -1) * (this._xrSessionManager.scene.useRightHandedSystem ? -1 : 1); + this.onBeforeCameraTeleportRotation.notifyObservers(rotation); + Quaternion.FromEulerAngles(0, rotation, 0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion, this._options.xrInput.xrCamera.rotationQuaternion); + this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion); + } + } + else { + if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId) { + // set the rotation of the forward movement + if (this.rotationEnabled) { + setTimeout(() => { + controllerData.teleportationState.currentRotation = Math.atan2(axesData.x, axesData.y * (this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1)); + }); + } + else { + controllerData.teleportationState.currentRotation = 0; + } + } + } + } + else { + controllerData.teleportationState.rotating = false; + } + if (axesData.x === 0 && axesData.y === 0) { + if (controllerData.teleportationState.blocked) { + controllerData.teleportationState.blocked = false; + this._setTargetMeshVisibility(false); + } + if (controllerData.teleportationState.forward) { + this._teleportForward(xrController.uniqueId); + } + } + }); + } + } + }; + if (xrController.motionController) { + initMotionController(); + } + else { + xrController.onMotionControllerInitObservable.addOnce(() => { + initMotionController(); + }); + } + } + else { + controllerData.teleportationState.mainComponentUsed = true; + let breakObserver = false; + const teleportLocal = () => { + this._currentTeleportationControllerId = controllerData.xrController.uniqueId; + controllerData.teleportationState.forward = true; + controllerData.teleportationState.initialHit = false; + controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y; + controllerData.teleportationState.currentRotation = 0; + const timeToSelect = this._options.timeToTeleport || 3000; + setAndStartTimer({ + timeout: timeToSelect, + contextObservable: this._xrSessionManager.onXRFrameObservable, + onEnded: () => { + if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId && controllerData.teleportationState.forward) { + this._teleportForward(xrController.uniqueId); + } + }, + }); + }; + this._xrSessionManager.scene.onPointerObservable.add((pointerInfo) => { + if (pointerInfo.type === PointerEventTypes.POINTERDOWN) { + breakObserver = false; + // check if start time is defined + if (this._options.timeToTeleportStart) { + setAndStartTimer({ + timeout: this._options.timeToTeleportStart, + contextObservable: this._xrSessionManager.onXRFrameObservable, + onEnded: () => { + // make sure pointer up was not triggered during this time + if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId) { + teleportLocal(); + } + }, + breakCondition: () => { + if (breakObserver) { + breakObserver = false; + return true; + } + return false; + }, + }); + } + else { + teleportLocal(); + } + } + else if (pointerInfo.type === PointerEventTypes.POINTERUP) { + breakObserver = true; + controllerData.teleportationState.forward = false; + this._currentTeleportationControllerId = ""; + } + }); + } + }; + this._colorArray = Array(24).fill(this._cachedColor4White); + // create default mesh if not provided + if (!this._options.teleportationTargetMesh) { + this._createDefaultTargetMesh(); + } + this._floorMeshes = this._options.floorMeshes || []; + this._snapToPositions = this._options.snapPositions || []; + this._blockedRayColor = this._options.blockedRayColor || new Color4(1, 0, 0, 0.75); + this._setTargetMeshVisibility(false); + // set the observables + this.onBeforeCameraTeleport = _options.xrInput.xrCamera.onBeforeCameraTeleport; + this.onAfterCameraTeleport = _options.xrInput.xrCamera.onAfterCameraTeleport; + this.parabolicCheckRadius *= this._xrSessionManager.worldScalingFactor; + this._worldScaleObserver = _xrSessionManager.onWorldScaleFactorChangedObservable.add((values) => { + this.parabolicCheckRadius = (this.parabolicCheckRadius / values.previousScaleFactor) * values.newScaleFactor; + this._options.teleportationTargetMesh?.scaling.scaleInPlace(values.newScaleFactor / values.previousScaleFactor); + }); + } + /** + * Get the snapPointsOnly flag + */ + get snapPointsOnly() { + return !!this._options.snapPointsOnly; + } + /** + * Sets the snapPointsOnly flag + * @param snapToPoints should teleportation be exclusively to snap points + */ + set snapPointsOnly(snapToPoints) { + this._options.snapPointsOnly = snapToPoints; + } + /** + * Add a new mesh to the floor meshes array + * @param mesh the mesh to use as floor mesh + */ + addFloorMesh(mesh) { + this._floorMeshes.push(mesh); + } + /** + * Add a mesh to the list of meshes blocking the teleportation ray + * @param mesh The mesh to add to the teleportation-blocking meshes + */ + addBlockerMesh(mesh) { + this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || []; + this._options.pickBlockerMeshes.push(mesh); + } + /** + * Add a new snap-to point to fix teleportation to this position + * @param newSnapPoint The new Snap-To point + */ + addSnapPoint(newSnapPoint) { + this._snapToPositions.push(newSnapPoint); + } + attach() { + if (!super.attach()) { + return false; + } + // Safety reset + this._currentTeleportationControllerId = ""; + this._options.xrInput.controllers.forEach(this._attachController); + this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController); + this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => { + // REMOVE the controller + this._detachController(controller.uniqueId); + }); + return true; + } + detach() { + if (!super.detach()) { + return false; + } + Object.keys(this._controllers).forEach((controllerId) => { + this._detachController(controllerId); + }); + this._setTargetMeshVisibility(false); + this._currentTeleportationControllerId = ""; + this._controllers = {}; + return true; + } + dispose() { + super.dispose(); + this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.dispose(false, true); + if (this._worldScaleObserver) { + this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver); + } + this.onTargetMeshPositionUpdatedObservable.clear(); + this.onTargetMeshPositionUpdatedObservable.clear(); + this.onBeforeCameraTeleportRotation.clear(); + this.onAfterCameraTeleportRotation.clear(); + this.onBeforeCameraTeleport.clear(); + this.onAfterCameraTeleport.clear(); + } + /** + * Remove a mesh from the floor meshes array + * @param mesh the mesh to remove + */ + removeFloorMesh(mesh) { + const index = this._floorMeshes.indexOf(mesh); + if (index !== -1) { + this._floorMeshes.splice(index, 1); + } + } + /** + * Remove a mesh from the blocker meshes array + * @param mesh the mesh to remove + */ + removeBlockerMesh(mesh) { + this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || []; + const index = this._options.pickBlockerMeshes.indexOf(mesh); + if (index !== -1) { + this._options.pickBlockerMeshes.splice(index, 1); + } + } + /** + * Remove a mesh from the floor meshes array using its name + * @param name the mesh name to remove + */ + removeFloorMeshByName(name) { + const mesh = this._xrSessionManager.scene.getMeshByName(name); + if (mesh) { + this.removeFloorMesh(mesh); + } + } + /** + * This function will iterate through the array, searching for this point or equal to it. It will then remove it from the snap-to array + * @param snapPointToRemove the point (or a clone of it) to be removed from the array + * @returns was the point found and removed or not + */ + removeSnapPoint(snapPointToRemove) { + // check if the object is in the array + let index = this._snapToPositions.indexOf(snapPointToRemove); + // if not found as an object, compare to the points + if (index === -1) { + for (let i = 0; i < this._snapToPositions.length; ++i) { + // equals? index is i, break the loop + if (this._snapToPositions[i].equals(snapPointToRemove)) { + index = i; + break; + } + } + } + // index is not -1? remove the object + if (index !== -1) { + this._snapToPositions.splice(index, 1); + return true; + } + return false; + } + /** + * This function sets a selection feature that will be disabled when + * the forward ray is shown and will be reattached when hidden. + * This is used to remove the selection rays when moving. + * @param selectionFeature the feature to disable when forward movement is enabled + */ + setSelectionFeature(selectionFeature) { + this._selectionFeature = selectionFeature; + } + _onXRFrame(_xrFrame) { + const frame = this._xrSessionManager.currentFrame; + const scene = this._xrSessionManager.scene; + if (!this.attach || !frame) { + return; + } + // render target if needed + const targetMesh = this._options.teleportationTargetMesh; + if (this._currentTeleportationControllerId) { + if (!targetMesh) { + return; + } + targetMesh.rotationQuaternion = targetMesh.rotationQuaternion || new Quaternion(); + const controllerData = this._controllers[this._currentTeleportationControllerId]; + if (controllerData && controllerData.teleportationState.forward) { + // set the rotation + Quaternion.RotationYawPitchRollToRef(controllerData.teleportationState.currentRotation + controllerData.teleportationState.baseRotation, 0, 0, targetMesh.rotationQuaternion); + // set the ray and position + let hitPossible = false; + const controlSelectionFeature = controllerData.xrController.inputSource.targetRayMode !== "transient-pointer"; + controllerData.xrController.getWorldPointerRayToRef(this._tmpRay); + if (this.straightRayEnabled) { + // first check if direct ray possible + // pick grounds that are LOWER only. upper will use parabolic path + const pick = scene.pickWithRay(this._tmpRay, (o) => { + if (this._options.blockerMeshesPredicate && this._options.blockerMeshesPredicate(o)) { + return true; + } + if (this._options.blockAllPickableMeshes && o.isPickable) { + return true; + } + // check for mesh-blockers + if (this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(o) !== -1) { + return true; + } + const index = this._floorMeshes.indexOf(o); + if (index === -1) { + return false; + } + return this._floorMeshes[index].absolutePosition.y < this._options.xrInput.xrCamera.globalPosition.y; + }); + const floorMeshPicked = pick && pick.pickedMesh && this._floorMeshes.indexOf(pick.pickedMesh) !== -1; + if (pick && pick.pickedMesh && !floorMeshPicked) { + if (controllerData.teleportationState.mainComponentUsed && !controllerData.teleportationState.initialHit) { + controllerData.teleportationState.forward = false; + return; + } + controllerData.teleportationState.blocked = true; + this._setTargetMeshVisibility(false, false, controlSelectionFeature); + this._showParabolicPath(pick); + return; + } + else if (pick && pick.pickedPoint) { + controllerData.teleportationState.initialHit = true; + controllerData.teleportationState.blocked = false; + hitPossible = true; + this._setTargetMeshPosition(pick); + this._setTargetMeshVisibility(true, false, controlSelectionFeature); + this._showParabolicPath(pick); + } + } + // straight ray is still the main ray, but disabling the straight line will force parabolic line. + if (this.parabolicRayEnabled && !hitPossible) { + // radius compensation according to pointer rotation around X + const xRotation = controllerData.xrController.pointer.rotationQuaternion.toEulerAngles().x; + const compensation = 1 + (Math.PI / 2 - Math.abs(xRotation)); + // check parabolic ray + const radius = this.parabolicCheckRadius * compensation; + this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(radius * 2), this._tmpVector); + this._tmpVector.y = this._tmpRay.origin.y; + this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(radius)); + this._tmpVector.subtractToRef(this._tmpRay.origin, this._tmpRay.direction); + this._tmpRay.direction.normalize(); + const pick = scene.pickWithRay(this._tmpRay, (o) => { + if (this._options.blockerMeshesPredicate && this._options.blockerMeshesPredicate(o)) { + return true; + } + if (this._options.blockAllPickableMeshes && o.isPickable) { + return true; + } + // check for mesh-blockers + if (this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(o) !== -1) { + return true; + } + return this._floorMeshes.indexOf(o) !== -1; + }); + const floorMeshPicked = pick && pick.pickedMesh && this._floorMeshes.indexOf(pick.pickedMesh) !== -1; + if (pick && pick.pickedMesh && !floorMeshPicked) { + if (controllerData.teleportationState.mainComponentUsed && !controllerData.teleportationState.initialHit) { + controllerData.teleportationState.forward = false; + return; + } + controllerData.teleportationState.blocked = true; + this._setTargetMeshVisibility(false, false, controlSelectionFeature); + this._showParabolicPath(pick); + return; + } + else if (pick && pick.pickedPoint) { + controllerData.teleportationState.initialHit = true; + controllerData.teleportationState.blocked = false; + hitPossible = true; + this._setTargetMeshPosition(pick); + this._setTargetMeshVisibility(true, false, controlSelectionFeature); + this._showParabolicPath(pick); + } + } + // if needed, set visible: + this._setTargetMeshVisibility(hitPossible, false, controlSelectionFeature); + } + else { + this._setTargetMeshVisibility(false, false, true); + } + } + else { + this._disposeBezierCurve(); + this._setTargetMeshVisibility(false, false, true); + } + } + _createDefaultTargetMesh() { + // set defaults + this._options.defaultTargetMeshOptions = this._options.defaultTargetMeshOptions || {}; + const sceneToRenderTo = this._options.useUtilityLayer + ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene + : this._xrSessionManager.scene; + const teleportationTarget = CreateGround("teleportationTarget", { width: 2, height: 2, subdivisions: 2 }, sceneToRenderTo); + teleportationTarget.isPickable = false; + if (this._options.defaultTargetMeshOptions.teleportationCircleMaterial) { + teleportationTarget.material = this._options.defaultTargetMeshOptions.teleportationCircleMaterial; + } + else { + const length = 512; + const dynamicTexture = new DynamicTexture("teleportationPlaneDynamicTexture", length, sceneToRenderTo, true); + dynamicTexture.hasAlpha = true; + const context = dynamicTexture.getContext(); + const centerX = length / 2; + const centerY = length / 2; + const radius = 200; + context.beginPath(); + context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); + context.fillStyle = this._options.defaultTargetMeshOptions.teleportationFillColor || "#444444"; + context.fill(); + context.lineWidth = 10; + context.strokeStyle = this._options.defaultTargetMeshOptions.teleportationBorderColor || "#FFFFFF"; + context.stroke(); + context.closePath(); + dynamicTexture.update(); + const teleportationCircleMaterial = new StandardMaterial("teleportationPlaneMaterial", sceneToRenderTo); + teleportationCircleMaterial.diffuseTexture = dynamicTexture; + teleportationTarget.material = teleportationCircleMaterial; + } + const torus = CreateTorus("torusTeleportation", { + diameter: 0.75, + thickness: 0.1, + tessellation: 20, + }, sceneToRenderTo); + torus.isPickable = false; + torus.parent = teleportationTarget; + if (!this._options.defaultTargetMeshOptions.disableAnimation) { + const animationInnerCircle = new Animation("animationInnerCircle", "position.y", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE); + const keys = []; + keys.push({ + frame: 0, + value: 0, + }); + keys.push({ + frame: 30, + value: 0.4, + }); + keys.push({ + frame: 60, + value: 0, + }); + animationInnerCircle.setKeys(keys); + const easingFunction = new SineEase(); + easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT); + animationInnerCircle.setEasingFunction(easingFunction); + torus.animations = []; + torus.animations.push(animationInnerCircle); + sceneToRenderTo.beginAnimation(torus, 0, 60, true); + } + const cone = CreateCylinder("rotationCone", { diameterTop: 0, tessellation: 4 }, sceneToRenderTo); + cone.isPickable = false; + cone.scaling.set(0.5, 0.12, 0.2); + cone.rotate(Axis.X, Math.PI / 2); + cone.position.z = 0.6; + cone.parent = torus; + if (this._options.defaultTargetMeshOptions.torusArrowMaterial) { + torus.material = this._options.defaultTargetMeshOptions.torusArrowMaterial; + cone.material = this._options.defaultTargetMeshOptions.torusArrowMaterial; + } + else { + const torusConeMaterial = new StandardMaterial("torusConsMat", sceneToRenderTo); + torusConeMaterial.disableLighting = !!this._options.defaultTargetMeshOptions.disableLighting; + if (torusConeMaterial.disableLighting) { + torusConeMaterial.emissiveColor = new Color3(0.3, 0.3, 1.0); + } + else { + torusConeMaterial.diffuseColor = new Color3(0.3, 0.3, 1.0); + } + torusConeMaterial.alpha = 0.9; + torus.material = torusConeMaterial; + cone.material = torusConeMaterial; + this._teleportationRingMaterial = torusConeMaterial; + } + if (this._options.renderingGroupId !== undefined) { + teleportationTarget.renderingGroupId = this._options.renderingGroupId; + torus.renderingGroupId = this._options.renderingGroupId; + cone.renderingGroupId = this._options.renderingGroupId; + } + this._options.teleportationTargetMesh = teleportationTarget; + this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor); + // hide the teleportation target mesh right after creating it. + this._setTargetMeshVisibility(false); + } + _detachController(xrControllerUniqueId) { + const controllerData = this._controllers[xrControllerUniqueId]; + if (!controllerData) { + return; + } + if (controllerData.teleportationComponent) { + if (controllerData.onAxisChangedObserver) { + controllerData.teleportationComponent.onAxisValueChangedObservable.remove(controllerData.onAxisChangedObserver); + } + if (controllerData.onButtonChangedObserver) { + controllerData.teleportationComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver); + } + } + // remove from the map + delete this._controllers[xrControllerUniqueId]; + } + _findClosestSnapPointWithRadius(realPosition, radius = this._options.snapToPositionRadius || 0.8) { + let closestPoint = null; + let closestDistance = Number.MAX_VALUE; + if (this._snapToPositions.length) { + const radiusSquared = radius * radius; + this._snapToPositions.forEach((position) => { + const dist = Vector3.DistanceSquared(position, realPosition); + if (dist <= radiusSquared && dist < closestDistance) { + closestDistance = dist; + closestPoint = position; + } + }); + } + return closestPoint; + } + _setTargetMeshPosition(pickInfo) { + const newPosition = pickInfo.pickedPoint; + if (!this._options.teleportationTargetMesh || !newPosition) { + return; + } + const snapPosition = this._findClosestSnapPointWithRadius(newPosition); + this._snappedToPoint = !!snapPosition; + if (this.snapPointsOnly && !this._snappedToPoint && this._teleportationRingMaterial) { + this._teleportationRingMaterial.diffuseColor.set(1.0, 0.3, 0.3); + } + else if (this.snapPointsOnly && this._snappedToPoint && this._teleportationRingMaterial) { + this._teleportationRingMaterial.diffuseColor.set(0.3, 0.3, 1.0); + } + this._options.teleportationTargetMesh.position.copyFrom(snapPosition || newPosition); + this._options.teleportationTargetMesh.position.y += 0.01; + this.onTargetMeshPositionUpdatedObservable.notifyObservers(pickInfo); + } + _setTargetMeshVisibility(visible, force, controlSelectionFeature) { + if (!this._options.teleportationTargetMesh) { + return; + } + if (this._options.teleportationTargetMesh.isVisible === visible && !force) { + return; + } + this._options.teleportationTargetMesh.isVisible = visible; + this._options.teleportationTargetMesh.getChildren(undefined, false).forEach((m) => { + m.isVisible = visible; + }); + if (!visible) { + if (this._quadraticBezierCurve) { + this._quadraticBezierCurve.dispose(); + this._quadraticBezierCurve = null; + } + if (this._selectionFeature && controlSelectionFeature) { + this._selectionFeature.attach(); + } + } + else { + if (this._selectionFeature && controlSelectionFeature) { + this._selectionFeature.detach(); + } + } + } + _disposeBezierCurve() { + if (this._quadraticBezierCurve) { + this._quadraticBezierCurve.dispose(); + this._quadraticBezierCurve = null; + } + } + _showParabolicPath(pickInfo) { + if (!pickInfo.pickedPoint || !this._currentTeleportationControllerId) { + return; + } + const sceneToRenderTo = this._options.useUtilityLayer + ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene + : this._xrSessionManager.scene; + const controllerData = this._controllers[this._currentTeleportationControllerId]; + const quadraticBezierVectors = Curve3.CreateQuadraticBezier(controllerData.xrController.pointer.absolutePosition, pickInfo.ray.origin, pickInfo.pickedPoint, 25); + const color = controllerData.teleportationState.blocked ? this._blockedRayColor : undefined; + const colorsArray = this._colorArray.fill(color || this._cachedColor4White); + // take out the first 2 points, to not start directly from the controller + const points = quadraticBezierVectors.getPoints(); + points.shift(); + points.shift(); + if (!this._options.generateRayPathMesh) { + this._quadraticBezierCurve = CreateLines("teleportation path line", { points: points, instance: this._quadraticBezierCurve, updatable: true, colors: colorsArray }, sceneToRenderTo); + } + else { + this._quadraticBezierCurve = this._options.generateRayPathMesh(quadraticBezierVectors.getPoints(), pickInfo); + } + this._quadraticBezierCurve.isPickable = false; + if (this._options.renderingGroupId !== undefined) { + this._quadraticBezierCurve.renderingGroupId = this._options.renderingGroupId; + } + } + _teleportForward(controllerId) { + const controllerData = this._controllers[controllerId]; + if (!controllerData || !controllerData.teleportationState.forward || !this.teleportationEnabled) { + return; + } + controllerData.teleportationState.forward = false; + this._currentTeleportationControllerId = ""; + if (this.snapPointsOnly && !this._snappedToPoint) { + return; + } + if (this.skipNextTeleportation) { + this.skipNextTeleportation = false; + return; + } + // do the movement forward here + if (this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.isVisible) { + const height = this._options.xrInput.xrCamera.realWorldHeight; + this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position); + this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position); + this._options.xrInput.xrCamera.position.y += height; + Quaternion.FromEulerAngles(0, controllerData.teleportationState.currentRotation - (this._xrSessionManager.scene.useRightHandedSystem ? Math.PI : 0), 0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion, this._options.xrInput.xrCamera.rotationQuaternion); + this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position); + } + } +} +/** + * The module's name + */ +WebXRMotionControllerTeleportation.Name = WebXRFeatureName.TELEPORTATION; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the webxr specs version + */ +WebXRMotionControllerTeleportation.Version = 1; +WebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name, (xrSessionManager, options) => { + return () => new WebXRMotionControllerTeleportation(xrSessionManager, options); +}, WebXRMotionControllerTeleportation.Version, true); + +/** + * Default experience for webxr + */ +class WebXRDefaultExperience { + constructor() { } + /** + * Creates the default xr experience + * @param scene scene + * @param options options for basic configuration + * @returns resulting WebXRDefaultExperience + */ + static CreateAsync(scene, options = {}) { + const result = new WebXRDefaultExperience(); + scene.onDisposeObservable.addOnce(() => { + result.dispose(); + }); + // init the UI right after construction + if (!options.disableDefaultUI) { + const uiOptions = { + renderTarget: result.renderTarget, + ...(options.uiOptions || {}), + }; + if (options.optionalFeatures) { + if (typeof options.optionalFeatures === "boolean") { + uiOptions.optionalFeatures = ["hit-test", "anchors", "plane-detection", "hand-tracking"]; + } + else { + uiOptions.optionalFeatures = options.optionalFeatures; + } + } + result.enterExitUI = new WebXREnterExitUI(scene, uiOptions); + } + // Create base experience + return WebXRExperienceHelper.CreateAsync(scene) + .then((xrHelper) => { + result.baseExperience = xrHelper; + if (options.ignoreNativeCameraTransformation) { + result.baseExperience.camera.compensateOnFirstFrame = false; + } + // Add controller support + result.input = new WebXRInput(xrHelper.sessionManager, xrHelper.camera, { + controllerOptions: { + renderingGroupId: options.renderingGroupId, + }, + ...(options.inputOptions || {}), + }); + if (!options.disablePointerSelection) { + // Add default pointer selection + const pointerSelectionOptions = { + ...options.pointerSelectionOptions, + xrInput: result.input, + renderingGroupId: options.renderingGroupId, + }; + result.pointerSelection = (result.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name, options.useStablePlugins ? "stable" : "latest", pointerSelectionOptions)); + if (!options.disableTeleportation) { + // Add default teleportation, including rotation + result.teleportation = result.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.Name, options.useStablePlugins ? "stable" : "latest", { + floorMeshes: options.floorMeshes, + xrInput: result.input, + renderingGroupId: options.renderingGroupId, + ...options.teleportationOptions, + }); + result.teleportation.setSelectionFeature(result.pointerSelection); + } + } + if (!options.disableNearInteraction) { + // Add default pointer selection + result.nearInteraction = result.baseExperience.featuresManager.enableFeature(WebXRNearInteraction.Name, options.useStablePlugins ? "stable" : "latest", { + xrInput: result.input, + farInteractionFeature: result.pointerSelection, + renderingGroupId: options.renderingGroupId, + useUtilityLayer: true, + enableNearInteractionOnAllControllers: true, + ...options.nearInteractionOptions, + }); + } + if (!options.disableHandTracking) { + // Add default hand tracking + result.baseExperience.featuresManager.enableFeature(WebXRHandTracking.Name, options.useStablePlugins ? "stable" : "latest", { + xrInput: result.input, + ...options.handSupportOptions, + }, undefined, false); + } + // Create the WebXR output target + result.renderTarget = result.baseExperience.sessionManager.getWebXRRenderTarget(options.outputCanvasOptions); + if (!options.disableDefaultUI) { + // Create ui for entering/exiting xr + return result.enterExitUI.setHelperAsync(result.baseExperience, result.renderTarget); + } + else { + return; + } + }) + .then(() => { + return result; + }) + .catch((error) => { + Logger.Error("Error initializing XR"); + Logger.Error(error); + return result; + }); + } + /** + * Disposes of the experience helper + */ + dispose() { + if (this.baseExperience) { + this.baseExperience.dispose(); + } + if (this.input) { + this.input.dispose(); + } + if (this.enterExitUI) { + this.enterExitUI.dispose(); + } + if (this.renderTarget) { + this.renderTarget.dispose(); + } + } +} + +Scene.prototype.createDefaultLight = function (replace = false) { + // Dispose existing light in replace mode. + if (replace) { + if (this.lights) { + for (let i = 0; i < this.lights.length; i++) { + this.lights[i].dispose(); + } + } + } + // Light + if (this.lights.length === 0) { + new HemisphericLight("default light", Vector3.Up(), this); + } +}; +Scene.prototype.createDefaultCamera = function (createArcRotateCamera = false, replace = false, attachCameraControls = false) { + // Dispose existing camera in replace mode. + if (replace) { + if (this.activeCamera) { + this.activeCamera.dispose(); + this.activeCamera = null; + } + } + // Camera + if (!this.activeCamera) { + const worldExtends = this.getWorldExtends((mesh) => mesh.isVisible && mesh.isEnabled()); + const worldSize = worldExtends.max.subtract(worldExtends.min); + const worldCenter = worldExtends.min.add(worldSize.scale(0.5)); + let camera; + let radius = worldSize.length() * 1.5; + // empty scene scenario! + if (!isFinite(radius)) { + radius = 1; + worldCenter.copyFromFloats(0, 0, 0); + } + if (createArcRotateCamera) { + const arcRotateCamera = new ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this); + arcRotateCamera.lowerRadiusLimit = radius * 0.01; + arcRotateCamera.wheelPrecision = 100 / radius; + camera = arcRotateCamera; + } + else { + const freeCamera = new FreeCamera("default camera", new Vector3(worldCenter.x, worldCenter.y, -radius), this); + freeCamera.setTarget(worldCenter); + camera = freeCamera; + } + camera.minZ = radius * 0.01; + camera.maxZ = radius * 1000; + camera.speed = radius * 0.2; + this.activeCamera = camera; + if (attachCameraControls) { + camera.attachControl(); + } + } +}; +Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera = false, replace = false, attachCameraControls = false) { + this.createDefaultLight(replace); + this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls); +}; +Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr = false, scale = 1000, blur = 0, setGlobalEnvTexture = true) { + if (!environmentTexture) { + Logger.Warn("Can not create default skybox without environment texture."); + return null; + } + if (setGlobalEnvTexture) { + if (environmentTexture) { + this.environmentTexture = environmentTexture; + } + } + // Skybox + const hdrSkybox = CreateBox("hdrSkyBox", { size: scale }, this); + if (pbr) { + const hdrSkyboxMaterial = new PBRMaterial("skyBox", this); + hdrSkyboxMaterial.backFaceCulling = false; + hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone(); + if (hdrSkyboxMaterial.reflectionTexture) { + hdrSkyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE; + } + hdrSkyboxMaterial.microSurface = 1.0 - blur; + hdrSkyboxMaterial.disableLighting = true; + hdrSkyboxMaterial.twoSidedLighting = true; + hdrSkybox.material = hdrSkyboxMaterial; + } + else { + const skyboxMaterial = new StandardMaterial("skyBox", this); + skyboxMaterial.backFaceCulling = false; + skyboxMaterial.reflectionTexture = environmentTexture.clone(); + if (skyboxMaterial.reflectionTexture) { + skyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE; + } + skyboxMaterial.disableLighting = true; + hdrSkybox.material = skyboxMaterial; + } + hdrSkybox.isPickable = false; + hdrSkybox.infiniteDistance = true; + hdrSkybox.ignoreCameraMaxZ = true; + return hdrSkybox; +}; +Scene.prototype.createDefaultEnvironment = function (options) { + if (EnvironmentHelper) { + return new EnvironmentHelper(options, this); + } + return null; +}; +Scene.prototype.createDefaultVRExperience = function (webVROptions = {}) { + return new VRExperienceHelper(this, webVROptions); +}; +Scene.prototype.createDefaultXRExperienceAsync = function (options = {}) { + return WebXRDefaultExperience.CreateAsync(this, options).then((helper) => { + return helper; + }); +}; + +function removeSource(video) { + // Remove any elements, etc. + while (video.firstChild) { + video.removeChild(video.firstChild); + } + // detach srcObject + video.srcObject = null; + // Set a blank src (https://html.spec.whatwg.org/multipage/media.html#best-practices-for-authors-using-media-elements) + video.src = ""; + // Prevent non-important errors maybe (https://twitter.com/beraliv/status/1205214277956775936) + video.removeAttribute("src"); +} +/** + * If you want to display a video in your scene, this is the special texture for that. + * This special texture works similar to other textures, with the exception of a few parameters. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/videoTexture + */ +class VideoTexture extends Texture { + /** + * Event triggered when a dom action is required by the user to play the video. + * This happens due to recent changes in browser policies preventing video to auto start. + */ + get onUserActionRequestedObservable() { + if (!this._onUserActionRequestedObservable) { + this._onUserActionRequestedObservable = new Observable(); + } + return this._onUserActionRequestedObservable; + } + _processError(reason) { + this._errorFound = true; + if (this._onError) { + this._onError(reason?.message); + } + else { + Logger.Error(reason?.message); + } + } + _handlePlay() { + this._errorFound = false; + this.video.play().catch((reason) => { + if (reason?.name === "NotAllowedError") { + if (this._onUserActionRequestedObservable && this._onUserActionRequestedObservable.hasObservers()) { + this._onUserActionRequestedObservable.notifyObservers(this); + return; + } + else if (!this.video.muted) { + Logger.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"); + this.video.muted = true; + this._errorFound = false; + this.video.play().catch((otherReason) => { + this._processError(otherReason); + }); + return; + } + } + this._processError(reason); + }); + } + /** + * Creates a video texture. + * If you want to display a video in your scene, this is the special texture for that. + * This special texture works similar to other textures, with the exception of a few parameters. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/videoTexture + * @param name optional name, will detect from video source, if not defined + * @param src can be used to provide an url, array of urls or an already setup HTML video element. + * @param scene is obviously the current scene. + * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated). + * @param invertY is false by default but can be used to invert video on Y axis + * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default + * @param settings allows finer control over video usage + * @param onError defines a callback triggered when an error occurred during the loading session + * @param format defines the texture format to use (Engine.TEXTUREFORMAT_RGBA by default) + */ + constructor(name, src, scene, generateMipMaps = false, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) { + super(null, scene, !generateMipMaps, invertY); + this._externalTexture = null; + this._onUserActionRequestedObservable = null; + this._stillImageCaptured = false; + this._displayingPosterTexture = false; + this._frameId = -1; + this._currentSrc = null; + this._errorFound = false; + /** + * Serialize the flag to define this texture as a video texture + */ + this.isVideo = true; + this._resizeInternalTexture = () => { + // Cleanup the old texture before replacing it + if (this._texture != null) { + this._texture.dispose(); + } + if (!this._getEngine().needPOTTextures || (Tools.IsExponentOfTwo(this.video.videoWidth) && Tools.IsExponentOfTwo(this.video.videoHeight))) { + this.wrapU = Texture.WRAP_ADDRESSMODE; + this.wrapV = Texture.WRAP_ADDRESSMODE; + } + else { + this.wrapU = Texture.CLAMP_ADDRESSMODE; + this.wrapV = Texture.CLAMP_ADDRESSMODE; + this._generateMipMaps = false; + } + this._texture = this._getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this.samplingMode); + this._texture.format = this._format ?? 5; + // Reset the frame ID and update the new texture to ensure it pulls in the current video frame + this._frameId = -1; + this._updateInternalTexture(); + }; + this._createInternalTexture = () => { + if (this._texture != null) { + if (this._displayingPosterTexture) { + this._displayingPosterTexture = false; + } + else { + return; + } + } + this.video.addEventListener("resize", this._resizeInternalTexture); + this._resizeInternalTexture(); + if (!this.video.autoplay && !this._settings.poster && !this._settings.independentVideoSource) { + const oldHandler = this.video.onplaying; + const oldMuted = this.video.muted; + this.video.muted = true; + this.video.onplaying = () => { + this.video.muted = oldMuted; + this.video.onplaying = oldHandler; + this._updateInternalTexture(); + if (!this._errorFound) { + this.video.pause(); + } + if (this.onLoadObservable.hasObservers()) { + this.onLoadObservable.notifyObservers(this); + } + }; + this._handlePlay(); + } + else { + this._updateInternalTexture(); + if (this.onLoadObservable.hasObservers()) { + this.onLoadObservable.notifyObservers(this); + } + } + }; + this._reset = () => { + if (this._texture == null) { + return; + } + if (!this._displayingPosterTexture) { + this._texture.dispose(); + this._texture = null; + } + }; + this._updateInternalTexture = () => { + if (this._texture == null) { + return; + } + if (this.video.readyState < this.video.HAVE_CURRENT_DATA) { + return; + } + if (this._displayingPosterTexture) { + return; + } + const frameId = this.getScene().getFrameId(); + if (this._frameId === frameId) { + return; + } + this._frameId = frameId; + this._getEngine().updateVideoTexture(this._texture, this._externalTexture ? this._externalTexture : this.video, this._invertY); + }; + this._settings = { + autoPlay: true, + loop: true, + autoUpdateTexture: true, + ...settings, + }; + this._onError = onError; + this._generateMipMaps = generateMipMaps; + this._initialSamplingMode = samplingMode; + this.autoUpdateTexture = this._settings.autoUpdateTexture; + this._currentSrc = src; + this.name = name || this._getName(src); + this.video = this._getVideo(src); + const engineWebGPU = this._engine; + const createExternalTexture = engineWebGPU?.createExternalTexture; + if (createExternalTexture) { + this._externalTexture = createExternalTexture.call(engineWebGPU, this.video); + } + if (!this._settings.independentVideoSource) { + if (this._settings.poster) { + this.video.poster = this._settings.poster; + } + if (this._settings.autoPlay !== undefined) { + this.video.autoplay = this._settings.autoPlay; + } + if (this._settings.loop !== undefined) { + this.video.loop = this._settings.loop; + } + if (this._settings.muted !== undefined) { + this.video.muted = this._settings.muted; + } + this.video.setAttribute("playsinline", ""); + this.video.addEventListener("paused", this._updateInternalTexture); + this.video.addEventListener("seeked", this._updateInternalTexture); + this.video.addEventListener("loadeddata", this._updateInternalTexture); + this.video.addEventListener("emptied", this._reset); + if (this._settings.autoPlay) { + this._handlePlay(); + } + } + this._createInternalTextureOnEvent = this._settings.poster && !this._settings.autoPlay ? "play" : "canplay"; + this.video.addEventListener(this._createInternalTextureOnEvent, this._createInternalTexture); + this._format = format; + const videoHasEnoughData = this.video.readyState >= this.video.HAVE_CURRENT_DATA; + if (this._settings.poster && (!this._settings.autoPlay || !videoHasEnoughData)) { + this._texture = this._getEngine().createTexture(this._settings.poster, false, !this.invertY, scene); + this._displayingPosterTexture = true; + } + else if (videoHasEnoughData) { + this._createInternalTexture(); + } + } + /** + * Get the current class name of the video texture useful for serialization or dynamic coding. + * @returns "VideoTexture" + */ + getClassName() { + return "VideoTexture"; + } + _getName(src) { + if (src instanceof HTMLVideoElement) { + return src.currentSrc; + } + if (typeof src === "object") { + return src.toString(); + } + return src; + } + _getVideo(src) { + if (src.isNative) { + return src; + } + if (src instanceof HTMLVideoElement) { + Tools.SetCorsBehavior(src.currentSrc, src); + return src; + } + const video = document.createElement("video"); + if (typeof src === "string") { + Tools.SetCorsBehavior(src, video); + video.src = src; + } + else { + Tools.SetCorsBehavior(src[0], video); + src.forEach((url) => { + const source = document.createElement("source"); + source.src = url; + video.appendChild(source); + }); + } + this.onDisposeObservable.addOnce(() => { + removeSource(video); + }); + return video; + } + /** + * @internal Internal method to initiate `update`. + */ + _rebuild() { + this.update(); + } + /** + * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false. + */ + update() { + if (!this.autoUpdateTexture) { + // Expecting user to call `updateTexture` manually + return; + } + this.updateTexture(true); + } + /** + * Update Texture in `manual` mode. Does not do anything if not visible or paused. + * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or otherwise. + */ + updateTexture(isVisible) { + if (!isVisible) { + return; + } + if (this.video.paused && this._stillImageCaptured) { + return; + } + this._stillImageCaptured = true; + this._updateInternalTexture(); + } + /** + * Get the underlying external texture (if supported by the current engine, else null) + */ + get externalTexture() { + return this._externalTexture; + } + /** + * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported. + * @param url New url. + */ + updateURL(url) { + this.video.src = url; + this._currentSrc = url; + } + /** + * Clones the texture. + * @returns the cloned texture + */ + clone() { + return new VideoTexture(this.name, this._currentSrc, this.getScene(), this._generateMipMaps, this.invertY, this.samplingMode, this._settings); + } + /** + * Dispose the texture and release its associated resources. + */ + dispose() { + super.dispose(); + this._currentSrc = null; + if (this._onUserActionRequestedObservable) { + this._onUserActionRequestedObservable.clear(); + this._onUserActionRequestedObservable = null; + } + this.video.removeEventListener(this._createInternalTextureOnEvent, this._createInternalTexture); + if (!this._settings.independentVideoSource) { + this.video.removeEventListener("paused", this._updateInternalTexture); + this.video.removeEventListener("seeked", this._updateInternalTexture); + this.video.removeEventListener("loadeddata", this._updateInternalTexture); + this.video.removeEventListener("emptied", this._reset); + this.video.removeEventListener("resize", this._resizeInternalTexture); + this.video.pause(); + } + this._externalTexture?.dispose(); + } + /** + * Creates a video texture straight from a stream. + * @param scene Define the scene the texture should be created in + * @param stream Define the stream the texture should be created from + * @param constraints video constraints + * @param invertY Defines if the video should be stored with invert Y set to true (true by default) + * @returns The created video texture as a promise + */ + static CreateFromStreamAsync(scene, stream, constraints, invertY = true) { + const video = scene.getEngine().createVideoElement(constraints); + if (scene.getEngine()._badOS) { + // Yes... I know and I hope to remove it soon... + document.body.appendChild(video); + video.style.transform = "scale(0.0001, 0.0001)"; + video.style.opacity = "0"; + video.style.position = "fixed"; + video.style.bottom = "0px"; + video.style.right = "0px"; + } + video.setAttribute("autoplay", ""); + video.setAttribute("muted", "true"); + video.setAttribute("playsinline", ""); + video.muted = true; + if (video.isNative) ; + else { + if (typeof video.srcObject == "object") { + video.srcObject = stream; + } + else { + // older API. See https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL#using_object_urls_for_media_streams + video.src = window.URL && window.URL.createObjectURL(stream); + } + } + return new Promise((resolve) => { + const onPlaying = () => { + const videoTexture = new VideoTexture("video", video, scene, true, invertY, undefined, undefined, undefined, 4); + if (scene.getEngine()._badOS) { + videoTexture.onDisposeObservable.addOnce(() => { + video.remove(); + }); + } + videoTexture.onDisposeObservable.addOnce(() => { + removeSource(video); + }); + resolve(videoTexture); + video.removeEventListener("playing", onPlaying); + }; + video.addEventListener("playing", onPlaying); + video.play(); + }); + } + /** + * Creates a video texture straight from your WebCam video feed. + * @param scene Define the scene the texture should be created in + * @param constraints Define the constraints to use to create the web cam feed from WebRTC + * @param audioConstaints Define the audio constraints to use to create the web cam feed from WebRTC + * @param invertY Defines if the video should be stored with invert Y set to true (true by default) + * @returns The created video texture as a promise + */ + static async CreateFromWebCamAsync(scene, constraints, audioConstaints = false, invertY = true) { + if (navigator.mediaDevices) { + const stream = await navigator.mediaDevices.getUserMedia({ + video: constraints, + audio: audioConstaints, + }); + const videoTexture = await this.CreateFromStreamAsync(scene, stream, constraints, invertY); + videoTexture.onDisposeObservable.addOnce(() => { + stream.getTracks().forEach((track) => { + track.stop(); + }); + }); + return videoTexture; + } + return Promise.reject("No support for userMedia on this device"); + } + /** + * Creates a video texture straight from your WebCam video feed. + * @param scene Defines the scene the texture should be created in + * @param onReady Defines a callback to triggered once the texture will be ready + * @param constraints Defines the constraints to use to create the web cam feed from WebRTC + * @param audioConstaints Defines the audio constraints to use to create the web cam feed from WebRTC + * @param invertY Defines if the video should be stored with invert Y set to true (true by default) + */ + static CreateFromWebCam(scene, onReady, constraints, audioConstaints = false, invertY = true) { + this.CreateFromWebCamAsync(scene, constraints, audioConstaints, invertY) + .then(function (videoTexture) { + if (onReady) { + onReady(videoTexture); + } + }) + .catch(function (err) { + Logger.Error(err.name); + }); + } +} +__decorate([ + serialize("settings") +], VideoTexture.prototype, "_settings", void 0); +__decorate([ + serialize("src") +], VideoTexture.prototype, "_currentSrc", void 0); +__decorate([ + serialize() +], VideoTexture.prototype, "isVideo", void 0); +Texture._CreateVideoTexture = (name, src, scene, generateMipMaps = false, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) => { + return new VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings, onError, format); +}; +// Some exporters relies on Tools.Instantiate +RegisterClass("BABYLON.VideoTexture", VideoTexture); + +/** + * Display a 360/180 degree video on an approximately spherical surface, useful for VR applications or skyboxes. + * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene. + * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere. + * Potential additions to this helper include zoom and and non-infinite distance rendering effects. + */ +class VideoDome extends TextureDome { + /** + * Get the video texture associated with this video dome + */ + get videoTexture() { + return this._texture; + } + /** + * Get the video mode of this dome + */ + get videoMode() { + return this.textureMode; + } + /** + * Set the video mode of this dome. + * @see textureMode + */ + set videoMode(value) { + this.textureMode = value; + } + _initTexture(urlsOrElement, scene, options) { + const tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster }; + const texture = new VideoTexture((this.name || "videoDome") + "_texture", urlsOrElement, scene, options.generateMipMaps, this._useDirectMapping, Texture.TRILINEAR_SAMPLINGMODE, tempOptions); + // optional configuration + if (options.clickToPlay) { + this._pointerObserver = scene.onPointerObservable.add((data) => { + data.pickInfo?.pickedMesh === this.mesh && this._texture.video.play(); + }, PointerEventTypes.POINTERDOWN); + } + this._textureObserver = texture.onLoadObservable.add(() => { + this.onLoadObservable.notifyObservers(); + }); + return texture; + } + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse, disposeMaterialAndTextures = false) { + this._texture.onLoadObservable.remove(this._textureObserver); + this._scene.onPointerObservable.remove(this._pointerObserver); + super.dispose(doNotRecurse, disposeMaterialAndTextures); + } +} +/** + * Define the video source as a Monoscopic panoramic 360 video. + */ +VideoDome.MODE_MONOSCOPIC = TextureDome.MODE_MONOSCOPIC; +/** + * Define the video source as a Stereoscopic TopBottom/OverUnder panoramic 360 video. + */ +VideoDome.MODE_TOPBOTTOM = TextureDome.MODE_TOPBOTTOM; +/** + * Define the video source as a Stereoscopic Side by Side panoramic 360 video. + */ +VideoDome.MODE_SIDEBYSIDE = TextureDome.MODE_SIDEBYSIDE; + +/** + * The effect layer Helps adding post process effect blended with the main pass. + * + * This can be for instance use to generate glow or highlight effects on the scene. + * + * The effect layer class can not be used directly and is intented to inherited from to be + * customized per effects. + */ +class EffectLayer { + get _shouldRender() { + return this._thinEffectLayer._shouldRender; + } + set _shouldRender(value) { + this._thinEffectLayer._shouldRender = value; + } + get _emissiveTextureAndColor() { + return this._thinEffectLayer._emissiveTextureAndColor; + } + set _emissiveTextureAndColor(value) { + this._thinEffectLayer._emissiveTextureAndColor = value; + } + get _effectIntensity() { + return this._thinEffectLayer._effectIntensity; + } + set _effectIntensity(value) { + this._thinEffectLayer._effectIntensity = value; + } + /** + * Force all the effect layers to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ + static get ForceGLSL() { + return ThinEffectLayer.ForceGLSL; + } + static set ForceGLSL(value) { + ThinEffectLayer.ForceGLSL = value; + } + /** + * The name of the layer + */ + get name() { + return this._thinEffectLayer.name; + } + set name(value) { + this._thinEffectLayer.name = value; + } + /** + * The clear color of the texture used to generate the glow map. + */ + get neutralColor() { + return this._thinEffectLayer.neutralColor; + } + set neutralColor(value) { + this._thinEffectLayer.neutralColor = value; + } + /** + * Specifies whether the highlight layer is enabled or not. + */ + get isEnabled() { + return this._thinEffectLayer.isEnabled; + } + set isEnabled(value) { + this._thinEffectLayer.isEnabled = value; + } + /** + * Gets the camera attached to the layer. + */ + get camera() { + return this._thinEffectLayer.camera; + } + /** + * Gets the rendering group id the layer should render in. + */ + get renderingGroupId() { + return this._thinEffectLayer.renderingGroupId; + } + set renderingGroupId(renderingGroupId) { + this._thinEffectLayer.renderingGroupId = renderingGroupId; + } + /** + * Specifies if the bounding boxes should be rendered normally or if they should undergo the effect of the layer + */ + get disableBoundingBoxesFromEffectLayer() { + return this._thinEffectLayer.disableBoundingBoxesFromEffectLayer; + } + set disableBoundingBoxesFromEffectLayer(value) { + this._thinEffectLayer.disableBoundingBoxesFromEffectLayer = value; + } + /** + * Gets the main texture where the effect is rendered + */ + get mainTexture() { + return this._mainTexture; + } + get _shaderLanguage() { + return this._thinEffectLayer.shaderLanguage; + } + /** + * Gets the shader language used in this material. + */ + get shaderLanguage() { + return this._thinEffectLayer.shaderLanguage; + } + /** + * Sets a specific material to be used to render a mesh/a list of meshes in the layer + * @param mesh mesh or array of meshes + * @param material material to use by the layer when rendering the mesh(es). If undefined is passed, the specific material created by the layer will be used. + */ + setMaterialForRendering(mesh, material) { + this._thinEffectLayer.setMaterialForRendering(mesh, material); + } + /** + * Gets the intensity of the effect for a specific mesh. + * @param mesh The mesh to get the effect intensity for + * @returns The intensity of the effect for the mesh + */ + getEffectIntensity(mesh) { + return this._thinEffectLayer.getEffectIntensity(mesh); + } + /** + * Sets the intensity of the effect for a specific mesh. + * @param mesh The mesh to set the effect intensity for + * @param intensity The intensity of the effect for the mesh + */ + setEffectIntensity(mesh, intensity) { + this._thinEffectLayer.setEffectIntensity(mesh, intensity); + } + /** + * Instantiates a new effect Layer and references it in the scene. + * @param name The name of the layer + * @param scene The scene to use the layer in + * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false + * @param thinEffectLayer The thin instance of the effect layer (optional) + */ + constructor( + /** The Friendly of the effect in the scene */ + name, scene, forceGLSL = false, thinEffectLayer) { + this._maxSize = 0; + this._mainTextureDesiredSize = { width: 0, height: 0 }; + this._postProcesses = []; + this._textures = []; + /** + * An event triggered when the effect layer has been disposed. + */ + this.onDisposeObservable = new Observable(); + /** + * An event triggered when the effect layer is about rendering the main texture with the glowy parts. + */ + this.onBeforeRenderMainTextureObservable = new Observable(); + /** + * An event triggered when the generated texture is being merged in the scene. + */ + this.onBeforeComposeObservable = new Observable(); + /** + * An event triggered when the mesh is rendered into the effect render target. + */ + this.onBeforeRenderMeshToEffect = new Observable(); + /** + * An event triggered after the mesh has been rendered into the effect render target. + */ + this.onAfterRenderMeshToEffect = new Observable(); + /** + * An event triggered when the generated texture has been merged in the scene. + */ + this.onAfterComposeObservable = new Observable(); + /** + * An event triggered when the effect layer changes its size. + */ + this.onSizeChangedObservable = new Observable(); + this._internalThinEffectLayer = !thinEffectLayer; + if (!thinEffectLayer) { + thinEffectLayer = new ThinEffectLayer(name, scene, forceGLSL, false, this._importShadersAsync.bind(this)); + thinEffectLayer.getEffectName = this.getEffectName.bind(this); + thinEffectLayer.isReady = this.isReady.bind(this); + thinEffectLayer._createMergeEffect = this._createMergeEffect.bind(this); + thinEffectLayer._createTextureAndPostProcesses = this._createTextureAndPostProcesses.bind(this); + thinEffectLayer._internalCompose = this._internalRender.bind(this); + thinEffectLayer._setEmissiveTextureAndColor = this._setEmissiveTextureAndColor.bind(this); + thinEffectLayer._numInternalDraws = this._numInternalDraws.bind(this); + thinEffectLayer._addCustomEffectDefines = this._addCustomEffectDefines.bind(this); + thinEffectLayer.hasMesh = this.hasMesh.bind(this); + thinEffectLayer.shouldRender = this.shouldRender.bind(this); + thinEffectLayer._shouldRenderMesh = this._shouldRenderMesh.bind(this); + thinEffectLayer._canRenderMesh = this._canRenderMesh.bind(this); + thinEffectLayer._useMeshMaterial = this._useMeshMaterial.bind(this); + } + this._thinEffectLayer = thinEffectLayer; + this.name = name; + this._scene = scene || EngineStore.LastCreatedScene; + EffectLayer._SceneComponentInitialization(this._scene); + this._engine = this._scene.getEngine(); + this._maxSize = this._engine.getCaps().maxTextureSize; + this._scene.effectLayers.push(this); + this._thinEffectLayer.onDisposeObservable.add(() => { + this.onDisposeObservable.notifyObservers(this); + }); + this._thinEffectLayer.onBeforeRenderLayerObservable.add(() => { + this.onBeforeRenderMainTextureObservable.notifyObservers(this); + }); + this._thinEffectLayer.onBeforeComposeObservable.add(() => { + this.onBeforeComposeObservable.notifyObservers(this); + }); + this._thinEffectLayer.onBeforeRenderMeshToEffect.add((mesh) => { + this.onBeforeRenderMeshToEffect.notifyObservers(mesh); + }); + this._thinEffectLayer.onAfterRenderMeshToEffect.add((mesh) => { + this.onAfterRenderMeshToEffect.notifyObservers(mesh); + }); + this._thinEffectLayer.onAfterComposeObservable.add(() => { + this.onAfterComposeObservable.notifyObservers(this); + }); + } + get _shadersLoaded() { + return this._thinEffectLayer._shadersLoaded; + } + set _shadersLoaded(value) { + this._thinEffectLayer._shadersLoaded = value; + } + /** + * Number of times _internalRender will be called. Some effect layers need to render the mesh several times, so they should override this method with the number of times the mesh should be rendered + * @returns Number of times a mesh must be rendered in the layer + */ + _numInternalDraws() { + return this._internalThinEffectLayer ? 1 : this._thinEffectLayer._numInternalDraws(); + } + /** + * Initializes the effect layer with the required options. + * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information) + */ + _init(options) { + // Adapt options + this._effectLayerOptions = { + mainTextureRatio: 0.5, + alphaBlendingMode: 2, + camera: null, + renderingGroupId: -1, + mainTextureType: 0, + generateStencilBuffer: false, + ...options, + }; + this._setMainTextureSize(); + this._thinEffectLayer._init(options); + this._createMainTexture(); + this._createTextureAndPostProcesses(); + } + /** + * Sets the main texture desired size which is the closest power of two + * of the engine canvas size. + */ + _setMainTextureSize() { + if (this._effectLayerOptions.mainTextureFixedSize) { + this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize; + this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize; + } + else { + this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio; + this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio; + this._mainTextureDesiredSize.width = this._engine.needPOTTextures + ? GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) + : this._mainTextureDesiredSize.width; + this._mainTextureDesiredSize.height = this._engine.needPOTTextures + ? GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) + : this._mainTextureDesiredSize.height; + } + this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width); + this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height); + } + /** + * Creates the main texture for the effect layer. + */ + _createMainTexture() { + this._mainTexture = new RenderTargetTexture("EffectLayerMainRTT", { + width: this._mainTextureDesiredSize.width, + height: this._mainTextureDesiredSize.height, + }, this._scene, { + type: this._effectLayerOptions.mainTextureType, + samplingMode: Texture.TRILINEAR_SAMPLINGMODE, + generateStencilBuffer: this._effectLayerOptions.generateStencilBuffer, + existingObjectRenderer: this._thinEffectLayer.objectRenderer, + }); + this._mainTexture.activeCamera = this._effectLayerOptions.camera; + this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE; + this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE; + this._mainTexture.anisotropicFilteringLevel = 1; + this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); + this._mainTexture.renderParticles = false; + this._mainTexture.renderList = null; + this._mainTexture.ignoreCameraViewport = true; + this._mainTexture.onClearObservable.add((engine) => { + engine.clear(this.neutralColor, true, true, true); + }); + } + /** + * Adds specific effects defines. + * @param defines The defines to add specifics to. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _addCustomEffectDefines(defines) { + // Nothing to add by default. + } + /** + * Checks for the readiness of the element composing the layer. + * @param subMesh the mesh to check for + * @param useInstances specify whether or not to use instances to render the mesh + * @param emissiveTexture the associated emissive texture used to generate the glow + * @returns true if ready otherwise, false + */ + _isReady(subMesh, useInstances, emissiveTexture) { + return this._internalThinEffectLayer + ? this._thinEffectLayer._internalIsSubMeshReady(subMesh, useInstances, emissiveTexture) + : this._thinEffectLayer._isSubMeshReady(subMesh, useInstances, emissiveTexture); + } + async _importShadersAsync() { } + _arePostProcessAndMergeReady() { + return this._internalThinEffectLayer ? this._thinEffectLayer._internalIsLayerReady() : this._thinEffectLayer.isLayerReady(); + } + /** + * Checks if the layer is ready to be used. + * @returns true if the layer is ready to be used + */ + isLayerReady() { + return this._arePostProcessAndMergeReady() && this._mainTexture.isReady(); + } + /** + * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene. + */ + render() { + if (!this._thinEffectLayer.compose()) { + return; + } + // Handle size changes. + const size = this._mainTexture.getSize(); + this._setMainTextureSize(); + if ((size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) && + this._mainTextureDesiredSize.width !== 0 && + this._mainTextureDesiredSize.height !== 0) { + // Recreate RTT and post processes on size change. + this.onSizeChangedObservable.notifyObservers(this); + this._disposeTextureAndPostProcesses(); + this._createMainTexture(); + this._createTextureAndPostProcesses(); + } + } + /** + * Determine if a given mesh will be used in the current effect. + * @param mesh mesh to test + * @returns true if the mesh will be used + */ + hasMesh(mesh) { + return this._internalThinEffectLayer ? this._thinEffectLayer._internalHasMesh(mesh) : this._thinEffectLayer.hasMesh(mesh); + } + /** + * Returns true if the layer contains information to display, otherwise false. + * @returns true if the glow layer should be rendered + */ + shouldRender() { + return this._internalThinEffectLayer ? this._thinEffectLayer._internalShouldRender() : this._thinEffectLayer.shouldRender(); + } + /** + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _shouldRenderMesh(mesh) { + return this._internalThinEffectLayer ? true : this._thinEffectLayer._shouldRenderMesh(mesh); + } + /** + * Returns true if the mesh can be rendered, otherwise false. + * @param mesh The mesh to render + * @param material The material used on the mesh + * @returns true if it can be rendered otherwise false + */ + _canRenderMesh(mesh, material) { + return this._internalThinEffectLayer ? this._thinEffectLayer._internalCanRenderMesh(mesh, material) : this._thinEffectLayer._canRenderMesh(mesh, material); + } + /** + * Returns true if the mesh should render, otherwise false. + * @returns true if it should render otherwise false + */ + _shouldRenderEmissiveTextureForMesh() { + return true; + } + /** + * Defines whether the current material of the mesh should be use to render the effect. + * @param mesh defines the current mesh to render + * @returns true if the mesh material should be use + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _useMeshMaterial(mesh) { + return this._internalThinEffectLayer ? false : this._thinEffectLayer._useMeshMaterial(mesh); + } + /** + * Rebuild the required buffers. + * @internal Internal use only. + */ + _rebuild() { + this._thinEffectLayer._rebuild(); + } + /** + * Dispose only the render target textures and post process. + */ + _disposeTextureAndPostProcesses() { + this._mainTexture.dispose(); + for (let i = 0; i < this._postProcesses.length; i++) { + if (this._postProcesses[i]) { + this._postProcesses[i].dispose(); + } + } + this._postProcesses = []; + for (let i = 0; i < this._textures.length; i++) { + if (this._textures[i]) { + this._textures[i].dispose(); + } + } + this._textures = []; + } + /** + * Dispose the highlight layer and free resources. + */ + dispose() { + this._thinEffectLayer.dispose(); + // Clean textures and post processes + this._disposeTextureAndPostProcesses(); + // Remove from scene + const index = this._scene.effectLayers.indexOf(this, 0); + if (index > -1) { + this._scene.effectLayers.splice(index, 1); + } + // Callback + this.onDisposeObservable.clear(); + this.onBeforeRenderMainTextureObservable.clear(); + this.onBeforeComposeObservable.clear(); + this.onBeforeRenderMeshToEffect.clear(); + this.onAfterRenderMeshToEffect.clear(); + this.onAfterComposeObservable.clear(); + this.onSizeChangedObservable.clear(); + } + /** + * Gets the class name of the effect layer + * @returns the string with the class name of the effect layer + */ + getClassName() { + return "EffectLayer"; + } + /** + * Creates an effect layer from parsed effect layer data + * @param parsedEffectLayer defines effect layer data + * @param scene defines the current scene + * @param rootUrl defines the root URL containing the effect layer information + * @returns a parsed effect Layer + */ + static Parse(parsedEffectLayer, scene, rootUrl) { + const effectLayerType = Tools.Instantiate(parsedEffectLayer.customType); + return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl); + } +} +/** + * @internal + */ +EffectLayer._SceneComponentInitialization = (_) => { + throw _WarnImport("EffectLayerSceneComponent"); +}; +__decorate([ + serialize() +], EffectLayer.prototype, "name", null); +__decorate([ + serializeAsColor4() +], EffectLayer.prototype, "neutralColor", null); +__decorate([ + serialize() +], EffectLayer.prototype, "isEnabled", null); +__decorate([ + serializeAsCameraReference() +], EffectLayer.prototype, "camera", null); +__decorate([ + serialize() +], EffectLayer.prototype, "renderingGroupId", null); +__decorate([ + serialize() +], EffectLayer.prototype, "disableBoundingBoxesFromEffectLayer", null); + +// Adds the parser to the scene parsers. +AddParser(SceneComponentConstants.NAME_EFFECTLAYER, (parsedData, scene, container, rootUrl) => { + if (parsedData.effectLayers) { + if (!container.effectLayers) { + container.effectLayers = []; + } + for (let index = 0; index < parsedData.effectLayers.length; index++) { + const effectLayer = EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl); + container.effectLayers.push(effectLayer); + } + } +}); +Scene.prototype.removeEffectLayer = function (toRemove) { + const index = this.effectLayers.indexOf(toRemove); + if (index !== -1) { + this.effectLayers.splice(index, 1); + } + return index; +}; +Scene.prototype.addEffectLayer = function (newEffectLayer) { + this.effectLayers.push(newEffectLayer); +}; +/** + * Defines the layer scene component responsible to manage any effect layers + * in a given scene. + */ +class EffectLayerSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_EFFECTLAYER; + this._renderEffects = false; + this._needStencil = false; + this._previousStencilState = false; + this.scene = scene || EngineStore.LastCreatedScene; + if (!this.scene) { + return; + } + this._engine = this.scene.getEngine(); + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._isReadyForMeshStage.registerStep(SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh); + this.scene._cameraDrawRenderTargetStage.registerStep(SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture); + this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil); + this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup); + this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack); + this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + const layers = this.scene.effectLayers; + for (const effectLayer of layers) { + effectLayer._rebuild(); + } + } + /** + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to + */ + serialize(serializationObject) { + // Effect layers + serializationObject.effectLayers = []; + const layers = this.scene.effectLayers; + for (const effectLayer of layers) { + if (effectLayer.serialize) { + serializationObject.effectLayers.push(effectLayer.serialize()); + } + } + } + /** + * Adds all the elements from the container to the scene + * @param container the container holding the elements + */ + addFromContainer(container) { + if (!container.effectLayers) { + return; + } + container.effectLayers.forEach((o) => { + this.scene.addEffectLayer(o); + }); + } + /** + * Removes all the elements in the container from the scene + * @param container contains the elements to remove + * @param dispose if the removed element should be disposed (default: false) + */ + removeFromContainer(container, dispose) { + if (!container.effectLayers) { + return; + } + container.effectLayers.forEach((o) => { + this.scene.removeEffectLayer(o); + if (dispose) { + o.dispose(); + } + }); + } + /** + * Disposes the component and the associated resources. + */ + dispose() { + const layers = this.scene.effectLayers; + while (layers.length) { + layers[0].dispose(); + } + } + _isReadyForMesh(mesh, hardwareInstancedRendering) { + const currentRenderPassId = this._engine.currentRenderPassId; + const layers = this.scene.effectLayers; + for (const layer of layers) { + if (!layer.hasMesh(mesh)) { + continue; + } + const renderTarget = layer._mainTexture; + this._engine.currentRenderPassId = renderTarget.renderPassId; + for (const subMesh of mesh.subMeshes) { + if (!layer.isReady(subMesh, hardwareInstancedRendering)) { + this._engine.currentRenderPassId = currentRenderPassId; + return false; + } + } + } + this._engine.currentRenderPassId = currentRenderPassId; + return true; + } + _renderMainTexture(camera) { + this._renderEffects = false; + this._needStencil = false; + let needRebind = false; + const layers = this.scene.effectLayers; + if (layers && layers.length > 0) { + this._previousStencilState = this._engine.getStencilBuffer(); + for (const effectLayer of layers) { + if (effectLayer.shouldRender() && + (!effectLayer.camera || + (effectLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === effectLayer.camera) || + (effectLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) { + this._renderEffects = true; + this._needStencil = this._needStencil || effectLayer.needStencil(); + const renderTarget = effectLayer._mainTexture; + if (renderTarget._shouldRender()) { + this.scene.incrementRenderId(); + renderTarget.render(false, false); + needRebind = true; + } + } + } + this.scene.incrementRenderId(); + } + return needRebind; + } + _setStencil() { + // Activate effect Layer stencil + if (this._needStencil) { + this._engine.setStencilBuffer(true); + } + } + _setStencilBack() { + // Restore effect Layer stencil + if (this._needStencil) { + this._engine.setStencilBuffer(this._previousStencilState); + } + } + _draw(renderingGroupId) { + if (this._renderEffects) { + this._engine.setDepthBuffer(false); + const layers = this.scene.effectLayers; + for (let i = 0; i < layers.length; i++) { + const effectLayer = layers[i]; + if (effectLayer.renderingGroupId === renderingGroupId) { + if (effectLayer.shouldRender()) { + effectLayer.render(); + } + } + } + this._engine.setDepthBuffer(true); + } + } + _drawCamera() { + if (this._renderEffects) { + this._draw(-1); + } + } + _drawRenderingGroup(index) { + if (!this.scene._isInIntermediateRendering() && this._renderEffects) { + this._draw(index); + } + } +} +EffectLayer._SceneComponentInitialization = (scene) => { + let component = scene._getComponent(SceneComponentConstants.NAME_EFFECTLAYER); + if (!component) { + component = new EffectLayerSceneComponent(scene); + scene._addComponent(component); + } +}; + +Scene.prototype.getGlowLayerByName = function (name) { + for (let index = 0; index < this.effectLayers?.length; index++) { + if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) { + return this.effectLayers[index]; + } + } + return null; +}; +/** + * The glow layer Helps adding a glow effect around the emissive parts of a mesh. + * + * Once instantiated in a scene, by default, all the emissive meshes will glow. + * + * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/mesh/glowLayer + */ +class GlowLayer extends EffectLayer { + /** + * Effect Name of the layer. + */ + static get EffectName() { + return ThinGlowLayer.EffectName; + } + /** + * Sets the kernel size of the blur. + */ + set blurKernelSize(value) { + this._thinEffectLayer.blurKernelSize = value; + } + /** + * Gets the kernel size of the blur. + */ + get blurKernelSize() { + return this._thinEffectLayer.blurKernelSize; + } + /** + * Sets the glow intensity. + */ + set intensity(value) { + this._thinEffectLayer.intensity = value; + } + /** + * Gets the glow intensity. + */ + get intensity() { + return this._thinEffectLayer.intensity; + } + /** + * Callback used to let the user override the color selection on a per mesh basis + */ + get customEmissiveColorSelector() { + return this._thinEffectLayer.customEmissiveColorSelector; + } + set customEmissiveColorSelector(value) { + this._thinEffectLayer.customEmissiveColorSelector = value; + } + /** + * Callback used to let the user override the texture selection on a per mesh basis + */ + get customEmissiveTextureSelector() { + return this._thinEffectLayer.customEmissiveTextureSelector; + } + set customEmissiveTextureSelector(value) { + this._thinEffectLayer.customEmissiveTextureSelector = value; + } + /** + * Instantiates a new glow Layer and references it to the scene. + * @param name The name of the layer + * @param scene The scene to use the layer in + * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information) + */ + constructor(name, scene, options) { + super(name, scene, false, new ThinGlowLayer(name, scene, options)); + // Adapt options + this._options = { + mainTextureRatio: GlowLayer.DefaultTextureRatio, + blurKernelSize: 32, + mainTextureFixedSize: undefined, + camera: null, + mainTextureSamples: 1, + renderingGroupId: -1, + ldrMerge: false, + alphaBlendingMode: 1, + mainTextureType: 0, + generateStencilBuffer: false, + ...options, + }; + // Initialize the layer + this._init(this._options); + } + /** + * Get the effect name of the layer. + * @returns The effect name + */ + getEffectName() { + return GlowLayer.EffectName; + } + /** + * @internal + * Create the merge effect. This is the shader use to blit the information back + * to the main canvas at the end of the scene rendering. + */ + _createMergeEffect() { + return this._thinEffectLayer._createMergeEffect(); + } + /** + * Creates the render target textures and post processes used in the glow layer. + */ + _createTextureAndPostProcesses() { + this._thinEffectLayer._renderPassId = this._mainTexture.renderPassId; + let blurTextureWidth = this._mainTextureDesiredSize.width; + let blurTextureHeight = this._mainTextureDesiredSize.height; + blurTextureWidth = this._engine.needPOTTextures ? GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth; + blurTextureHeight = this._engine.needPOTTextures ? GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight; + let textureType = 0; + if (this._engine.getCaps().textureHalfFloatRender) { + textureType = 2; + } + else { + textureType = 0; + } + this._blurTexture1 = new RenderTargetTexture("GlowLayerBlurRTT", { + width: blurTextureWidth, + height: blurTextureHeight, + }, this._scene, false, true, textureType); + this._blurTexture1.wrapU = Texture.CLAMP_ADDRESSMODE; + this._blurTexture1.wrapV = Texture.CLAMP_ADDRESSMODE; + this._blurTexture1.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); + this._blurTexture1.renderParticles = false; + this._blurTexture1.ignoreCameraViewport = true; + const blurTextureWidth2 = Math.floor(blurTextureWidth / 2); + const blurTextureHeight2 = Math.floor(blurTextureHeight / 2); + this._blurTexture2 = new RenderTargetTexture("GlowLayerBlurRTT2", { + width: blurTextureWidth2, + height: blurTextureHeight2, + }, this._scene, false, true, textureType); + this._blurTexture2.wrapU = Texture.CLAMP_ADDRESSMODE; + this._blurTexture2.wrapV = Texture.CLAMP_ADDRESSMODE; + this._blurTexture2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); + this._blurTexture2.renderParticles = false; + this._blurTexture2.ignoreCameraViewport = true; + this._textures = [this._blurTexture1, this._blurTexture2]; + this._thinEffectLayer.bindTexturesForCompose = (effect) => { + effect.setTexture("textureSampler", this._blurTexture1); + effect.setTexture("textureSampler2", this._blurTexture2); + effect.setFloat("offset", this.intensity); + }; + this._thinEffectLayer._createTextureAndPostProcesses(); + const thinBlurPostProcesses1 = this._thinEffectLayer._postProcesses[0]; + this._horizontalBlurPostprocess1 = new BlurPostProcess("GlowLayerHBP1", thinBlurPostProcesses1.direction, thinBlurPostProcesses1.kernel, { + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine: this._scene.getEngine(), + width: blurTextureWidth, + height: blurTextureHeight, + textureType, + effectWrapper: thinBlurPostProcesses1, + }); + this._horizontalBlurPostprocess1.width = blurTextureWidth; + this._horizontalBlurPostprocess1.height = blurTextureHeight; + this._horizontalBlurPostprocess1.externalTextureSamplerBinding = true; + this._horizontalBlurPostprocess1.onApplyObservable.add((effect) => { + effect.setTexture("textureSampler", this._mainTexture); + }); + const thinBlurPostProcesses2 = this._thinEffectLayer._postProcesses[1]; + this._verticalBlurPostprocess1 = new BlurPostProcess("GlowLayerVBP1", thinBlurPostProcesses2.direction, thinBlurPostProcesses2.kernel, { + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine: this._scene.getEngine(), + width: blurTextureWidth, + height: blurTextureHeight, + textureType, + effectWrapper: thinBlurPostProcesses2, + }); + const thinBlurPostProcesses3 = this._thinEffectLayer._postProcesses[2]; + this._horizontalBlurPostprocess2 = new BlurPostProcess("GlowLayerHBP2", thinBlurPostProcesses3.direction, thinBlurPostProcesses3.kernel, { + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine: this._scene.getEngine(), + width: blurTextureWidth2, + height: blurTextureHeight2, + textureType, + effectWrapper: thinBlurPostProcesses3, + }); + this._horizontalBlurPostprocess2.width = blurTextureWidth2; + this._horizontalBlurPostprocess2.height = blurTextureHeight2; + this._horizontalBlurPostprocess2.externalTextureSamplerBinding = true; + this._horizontalBlurPostprocess2.onApplyObservable.add((effect) => { + effect.setTexture("textureSampler", this._blurTexture1); + }); + const thinBlurPostProcesses4 = this._thinEffectLayer._postProcesses[3]; + this._verticalBlurPostprocess2 = new BlurPostProcess("GlowLayerVBP2", thinBlurPostProcesses4.direction, thinBlurPostProcesses4.kernel, { + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine: this._scene.getEngine(), + width: blurTextureWidth2, + height: blurTextureHeight2, + textureType, + effectWrapper: thinBlurPostProcesses4, + }); + this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2]; + this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1]; + this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2]; + this._mainTexture.samples = this._options.mainTextureSamples; + this._mainTexture.onAfterUnbindObservable.add(() => { + const internalTexture = this._blurTexture1.renderTarget; + if (internalTexture) { + this._scene.postProcessManager.directRender(this._postProcesses1, internalTexture, true); + const internalTexture2 = this._blurTexture2.renderTarget; + if (internalTexture2) { + this._scene.postProcessManager.directRender(this._postProcesses2, internalTexture2, true); + } + this._engine.unBindFramebuffer(internalTexture2 ?? internalTexture, true); + } + }); + // Prevent autoClear. + this._postProcesses.map((pp) => { + pp.autoClear = false; + }); + } + /** + * Checks for the readiness of the element composing the layer. + * @param subMesh the mesh to check for + * @param useInstances specify whether or not to use instances to render the mesh + * @returns true if ready otherwise, false + */ + isReady(subMesh, useInstances) { + return this._thinEffectLayer.isReady(subMesh, useInstances); + } + /** + * @returns whether or not the layer needs stencil enabled during the mesh rendering. + */ + needStencil() { + return false; + } + /** + * Returns true if the mesh can be rendered, otherwise false. + * @param mesh The mesh to render + * @param material The material used on the mesh + * @returns true if it can be rendered otherwise false + */ + _canRenderMesh(mesh, material) { + return this._thinEffectLayer._canRenderMesh(mesh, material); + } + /** + * Implementation specific of rendering the generating effect on the main canvas. + * @param effect The effect used to render through + */ + _internalRender(effect) { + this._thinEffectLayer._internalCompose(effect); + } + /** + * Sets the required values for both the emissive texture and and the main color. + * @param mesh + * @param subMesh + * @param material + */ + _setEmissiveTextureAndColor(mesh, subMesh, material) { + this._thinEffectLayer._setEmissiveTextureAndColor(mesh, subMesh, material); + } + /** + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false + */ + _shouldRenderMesh(mesh) { + return this._thinEffectLayer._shouldRenderMesh(mesh); + } + /** + * Adds specific effects defines. + * @param defines The defines to add specifics to. + */ + _addCustomEffectDefines(defines) { + this._thinEffectLayer._addCustomEffectDefines(defines); + } + /** + * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer. + * @param mesh The mesh to exclude from the glow layer + */ + addExcludedMesh(mesh) { + this._thinEffectLayer.addExcludedMesh(mesh); + } + /** + * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer. + * @param mesh The mesh to remove + */ + removeExcludedMesh(mesh) { + this._thinEffectLayer.removeExcludedMesh(mesh); + } + /** + * Add a mesh in the inclusion list to impact or being impacted by the glow layer. + * @param mesh The mesh to include in the glow layer + */ + addIncludedOnlyMesh(mesh) { + this._thinEffectLayer.addIncludedOnlyMesh(mesh); + } + /** + * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer. + * @param mesh The mesh to remove + */ + removeIncludedOnlyMesh(mesh) { + this._thinEffectLayer.removeIncludedOnlyMesh(mesh); + } + /** + * Determine if a given mesh will be used in the glow layer + * @param mesh The mesh to test + * @returns true if the mesh will be highlighted by the current glow layer + */ + hasMesh(mesh) { + return this._thinEffectLayer.hasMesh(mesh); + } + /** + * Defines whether the current material of the mesh should be use to render the effect. + * @param mesh defines the current mesh to render + * @returns true if the material of the mesh should be use to render the effect + */ + _useMeshMaterial(mesh) { + return this._thinEffectLayer._useMeshMaterial(mesh); + } + /** + * Add a mesh to be rendered through its own material and not with emissive only. + * @param mesh The mesh for which we need to use its material + */ + referenceMeshToUseItsOwnMaterial(mesh) { + this._thinEffectLayer.referenceMeshToUseItsOwnMaterial(mesh); + } + /** + * Remove a mesh from being rendered through its own material and not with emissive only. + * @param mesh The mesh for which we need to not use its material + */ + unReferenceMeshFromUsingItsOwnMaterial(mesh) { + this._thinEffectLayer.unReferenceMeshFromUsingItsOwnMaterial(mesh, this._mainTexture.renderPassId); + } + /** + * Free any resources and references associated to a mesh. + * Internal use + * @param mesh The mesh to free. + * @internal + */ + _disposeMesh(mesh) { + this._thinEffectLayer._disposeMesh(mesh); + } + /** + * Gets the class name of the effect layer + * @returns the string with the class name of the effect layer + */ + getClassName() { + return "GlowLayer"; + } + /** + * Serializes this glow layer + * @returns a serialized glow layer object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.customType = "BABYLON.GlowLayer"; + let index; + // Included meshes + serializationObject.includedMeshes = []; + const includedOnlyMeshes = this._thinEffectLayer._includedOnlyMeshes; + if (includedOnlyMeshes.length) { + for (index = 0; index < includedOnlyMeshes.length; index++) { + const mesh = this._scene.getMeshByUniqueId(includedOnlyMeshes[index]); + if (mesh) { + serializationObject.includedMeshes.push(mesh.id); + } + } + } + // Excluded meshes + serializationObject.excludedMeshes = []; + const excludedMeshes = this._thinEffectLayer._excludedMeshes; + if (excludedMeshes.length) { + for (index = 0; index < excludedMeshes.length; index++) { + const mesh = this._scene.getMeshByUniqueId(excludedMeshes[index]); + if (mesh) { + serializationObject.excludedMeshes.push(mesh.id); + } + } + } + return serializationObject; + } + /** + * Creates a Glow Layer from parsed glow layer data + * @param parsedGlowLayer defines glow layer data + * @param scene defines the current scene + * @param rootUrl defines the root URL containing the glow layer information + * @returns a parsed Glow Layer + */ + static Parse(parsedGlowLayer, scene, rootUrl) { + const gl = SerializationHelper.Parse(() => new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options), parsedGlowLayer, scene, rootUrl); + let index; + // Excluded meshes + for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) { + const mesh = scene.getMeshById(parsedGlowLayer.excludedMeshes[index]); + if (mesh) { + gl.addExcludedMesh(mesh); + } + } + // Included meshes + for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) { + const mesh = scene.getMeshById(parsedGlowLayer.includedMeshes[index]); + if (mesh) { + gl.addIncludedOnlyMesh(mesh); + } + } + return gl; + } +} +/** + * The default blur kernel size used for the glow. + */ +GlowLayer.DefaultBlurKernelSize = 32; +/** + * The default texture size ratio used for the glow. + */ +GlowLayer.DefaultTextureRatio = 0.5; +__decorate([ + serialize() +], GlowLayer.prototype, "blurKernelSize", null); +__decorate([ + serialize() +], GlowLayer.prototype, "intensity", null); +__decorate([ + serialize("options") +], GlowLayer.prototype, "_options", void 0); +RegisterClass("BABYLON.GlowLayer", GlowLayer); + +Scene.prototype.getHighlightLayerByName = function (name) { + for (let index = 0; index < this.effectLayers?.length; index++) { + if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) { + return this.effectLayers[index]; + } + } + return null; +}; +/** + * Special Glow Blur post process only blurring the alpha channel + * It enforces keeping the most luminous color in the color channel. + */ +class GlowBlurPostProcess extends PostProcess { + constructor(name, direction, kernel, options, camera = null, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable) { + const localOptions = { + uniforms: ThinGlowBlurPostProcess.Uniforms, + size: typeof options === "number" ? options : undefined, + camera, + samplingMode, + engine, + reusable, + ...options, + }; + super(name, ThinGlowBlurPostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinGlowBlurPostProcess(name, engine, direction, kernel, localOptions) : undefined, + ...localOptions, + }); + this.direction = direction; + this.kernel = kernel; + this.onApplyObservable.add(() => { + this._effectWrapper.textureWidth = this.width; + this._effectWrapper.textureHeight = this.height; + }); + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => glowBlurPostProcess_fragment)); + } + else { + list.push(Promise.resolve().then(() => glowBlurPostProcess_fragment$1)); + } + super._gatherImports(useWebGPU, list); + } +} +/** + * The highlight layer Helps adding a glow effect around a mesh. + * + * Once instantiated in a scene, simply use the addMesh or removeMesh method to add or remove + * glowy meshes to your scene. + * + * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!! + */ +class HighlightLayer extends EffectLayer { + /** + * The neutral color used during the preparation of the glow effect. + * This is black by default as the blend operation is a blend operation. + */ + static get NeutralColor() { + return ThinHighlightLayer.NeutralColor; + } + static set NeutralColor(value) { + ThinHighlightLayer.NeutralColor = value; + } + /** + * Specifies whether or not the inner glow is ACTIVE in the layer. + */ + get innerGlow() { + return this._thinEffectLayer.innerGlow; + } + set innerGlow(value) { + this._thinEffectLayer.innerGlow = value; + } + /** + * Specifies whether or not the outer glow is ACTIVE in the layer. + */ + get outerGlow() { + return this._thinEffectLayer.outerGlow; + } + set outerGlow(value) { + this._thinEffectLayer.outerGlow = value; + } + /** + * Specifies the horizontal size of the blur. + */ + set blurHorizontalSize(value) { + this._thinEffectLayer.blurHorizontalSize = value; + } + /** + * Specifies the vertical size of the blur. + */ + set blurVerticalSize(value) { + this._thinEffectLayer.blurVerticalSize = value; + } + /** + * Gets the horizontal size of the blur. + */ + get blurHorizontalSize() { + return this._thinEffectLayer.blurHorizontalSize; + } + /** + * Gets the vertical size of the blur. + */ + get blurVerticalSize() { + return this._thinEffectLayer.blurVerticalSize; + } + /** + * Instantiates a new highlight Layer and references it to the scene.. + * @param name The name of the layer + * @param scene The scene to use the layer in + * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information) + */ + constructor(name, scene, options) { + super(name, scene, options !== undefined ? !!options.forceGLSL : false, new ThinHighlightLayer(name, scene, options)); + /** + * An event triggered when the highlight layer is being blurred. + */ + this.onBeforeBlurObservable = new Observable(); + /** + * An event triggered when the highlight layer has been blurred. + */ + this.onAfterBlurObservable = new Observable(); + // Warn on stencil + if (!this._engine.isStencilEnable) { + Logger.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"); + } + // Adapt options + this._options = { + mainTextureRatio: 0.5, + blurTextureSizeRatio: 0.5, + mainTextureFixedSize: 0, + blurHorizontalSize: 1.0, + blurVerticalSize: 1.0, + alphaBlendingMode: 2, + camera: null, + renderingGroupId: -1, + mainTextureType: 0, + forceGLSL: false, + isStroke: false, + ...options, + }; + // Initialize the layer + this._init(this._options); + // Do not render as long as no meshes have been added + this._shouldRender = false; + } + /** + * Get the effect name of the layer. + * @returns The effect name + */ + getEffectName() { + return HighlightLayer.EffectName; + } + _numInternalDraws() { + return 2; // we need two rendering, one for the inner glow and the other for the outer glow + } + /** + * Create the merge effect. This is the shader use to blit the information back + * to the main canvas at the end of the scene rendering. + * @returns The effect created + */ + _createMergeEffect() { + return this._thinEffectLayer._createMergeEffect(); + } + /** + * Creates the render target textures and post processes used in the highlight layer. + */ + _createTextureAndPostProcesses() { + let blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio; + let blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio; + blurTextureWidth = this._engine.needPOTTextures ? GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth; + blurTextureHeight = this._engine.needPOTTextures ? GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight; + let textureType = 0; + if (this._engine.getCaps().textureHalfFloatRender) { + textureType = 2; + } + else { + textureType = 0; + } + this._blurTexture = new RenderTargetTexture("HighlightLayerBlurRTT", { + width: blurTextureWidth, + height: blurTextureHeight, + }, this._scene, false, true, textureType); + this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE; + this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE; + this._blurTexture.anisotropicFilteringLevel = 16; + this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE); + this._blurTexture.renderParticles = false; + this._blurTexture.ignoreCameraViewport = true; + this._textures = [this._blurTexture]; + this._thinEffectLayer.bindTexturesForCompose = (effect) => { + effect.setTexture("textureSampler", this._blurTexture); + }; + this._thinEffectLayer._createTextureAndPostProcesses(); + if (this._options.alphaBlendingMode === 2) { + this._downSamplePostprocess = new PassPostProcess("HighlightLayerPPP", { + size: this._options.blurTextureSizeRatio, + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine: this._scene.getEngine(), + effectWrapper: this._thinEffectLayer._postProcesses[0], + }); + this._downSamplePostprocess.externalTextureSamplerBinding = true; + this._downSamplePostprocess.onApplyObservable.add((effect) => { + effect.setTexture("textureSampler", this._mainTexture); + }); + this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new Vector2(1.0, 0), this._options.blurHorizontalSize, { + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine: this._scene.getEngine(), + effectWrapper: this._thinEffectLayer._postProcesses[1], + }); + this._horizontalBlurPostprocess.onApplyObservable.add((effect) => { + effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); + }); + this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new Vector2(0, 1.0), this._options.blurVerticalSize, { + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine: this._scene.getEngine(), + effectWrapper: this._thinEffectLayer._postProcesses[2], + }); + this._verticalBlurPostprocess.onApplyObservable.add((effect) => { + effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); + }); + this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess]; + } + else { + this._horizontalBlurPostprocess = new BlurPostProcess("HighlightLayerHBP", new Vector2(1.0, 0), this._options.blurHorizontalSize / 2, { + size: { + width: blurTextureWidth, + height: blurTextureHeight, + }, + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine: this._scene.getEngine(), + textureType, + effectWrapper: this._thinEffectLayer._postProcesses[0], + }); + this._horizontalBlurPostprocess.width = blurTextureWidth; + this._horizontalBlurPostprocess.height = blurTextureHeight; + this._horizontalBlurPostprocess.externalTextureSamplerBinding = true; + this._horizontalBlurPostprocess.onApplyObservable.add((effect) => { + effect.setTexture("textureSampler", this._mainTexture); + }); + this._verticalBlurPostprocess = new BlurPostProcess("HighlightLayerVBP", new Vector2(0, 1.0), this._options.blurVerticalSize / 2, { + size: { + width: blurTextureWidth, + height: blurTextureHeight, + }, + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine: this._scene.getEngine(), + textureType, + }); + this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess]; + } + this._mainTexture.onAfterUnbindObservable.add(() => { + this.onBeforeBlurObservable.notifyObservers(this); + const internalTexture = this._blurTexture.renderTarget; + if (internalTexture) { + this._scene.postProcessManager.directRender(this._postProcesses, internalTexture, true); + this._engine.unBindFramebuffer(internalTexture, true); + } + this.onAfterBlurObservable.notifyObservers(this); + }); + // Prevent autoClear. + this._postProcesses.map((pp) => { + pp.autoClear = false; + }); + } + /** + * @returns whether or not the layer needs stencil enabled during the mesh rendering. + */ + needStencil() { + return this._thinEffectLayer.needStencil(); + } + /** + * Checks for the readiness of the element composing the layer. + * @param subMesh the mesh to check for + * @param useInstances specify whether or not to use instances to render the mesh + * @returns true if ready otherwise, false + */ + isReady(subMesh, useInstances) { + return this._thinEffectLayer.isReady(subMesh, useInstances); + } + /** + * Implementation specific of rendering the generating effect on the main canvas. + * @param effect The effect used to render through + * @param renderIndex + */ + _internalRender(effect, renderIndex) { + this._thinEffectLayer._internalCompose(effect, renderIndex); + } + /** + * @returns true if the layer contains information to display, otherwise false. + */ + shouldRender() { + return this._thinEffectLayer.shouldRender(); + } + /** + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false + */ + _shouldRenderMesh(mesh) { + return this._thinEffectLayer._shouldRenderMesh(mesh); + } + /** + * Returns true if the mesh can be rendered, otherwise false. + * @param mesh The mesh to render + * @param material The material used on the mesh + * @returns true if it can be rendered otherwise false + */ + _canRenderMesh(mesh, material) { + return this._thinEffectLayer._canRenderMesh(mesh, material); + } + /** + * Adds specific effects defines. + * @param defines The defines to add specifics to. + */ + _addCustomEffectDefines(defines) { + this._thinEffectLayer._addCustomEffectDefines(defines); + } + /** + * Sets the required values for both the emissive texture and and the main color. + * @param mesh + * @param subMesh + * @param material + */ + _setEmissiveTextureAndColor(mesh, subMesh, material) { + this._thinEffectLayer._setEmissiveTextureAndColor(mesh, subMesh, material); + } + /** + * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer. + * @param mesh The mesh to exclude from the highlight layer + */ + addExcludedMesh(mesh) { + this._thinEffectLayer.addExcludedMesh(mesh); + } + /** + * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer. + * @param mesh The mesh to highlight + */ + removeExcludedMesh(mesh) { + this._thinEffectLayer.removeExcludedMesh(mesh); + } + /** + * Determine if a given mesh will be highlighted by the current HighlightLayer + * @param mesh mesh to test + * @returns true if the mesh will be highlighted by the current HighlightLayer + */ + hasMesh(mesh) { + return this._thinEffectLayer.hasMesh(mesh); + } + /** + * Add a mesh in the highlight layer in order to make it glow with the chosen color. + * @param mesh The mesh to highlight + * @param color The color of the highlight + * @param glowEmissiveOnly Extract the glow from the emissive texture + */ + addMesh(mesh, color, glowEmissiveOnly = false) { + this._thinEffectLayer.addMesh(mesh, color, glowEmissiveOnly); + } + /** + * Remove a mesh from the highlight layer in order to make it stop glowing. + * @param mesh The mesh to highlight + */ + removeMesh(mesh) { + this._thinEffectLayer.removeMesh(mesh); + } + /** + * Remove all the meshes currently referenced in the highlight layer + */ + removeAllMeshes() { + this._thinEffectLayer.removeAllMeshes(); + } + /** + * Free any resources and references associated to a mesh. + * Internal use + * @param mesh The mesh to free. + * @internal + */ + _disposeMesh(mesh) { + this._thinEffectLayer._disposeMesh(mesh); + } + /** + * Gets the class name of the effect layer + * @returns the string with the class name of the effect layer + */ + getClassName() { + return "HighlightLayer"; + } + /** + * Serializes this Highlight layer + * @returns a serialized Highlight layer object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.customType = "BABYLON.HighlightLayer"; + // Highlighted meshes + serializationObject.meshes = []; + const meshes = this._thinEffectLayer._meshes; + if (meshes) { + for (const m in meshes) { + const mesh = meshes[m]; + if (mesh) { + serializationObject.meshes.push({ + glowEmissiveOnly: mesh.glowEmissiveOnly, + color: mesh.color.asArray(), + meshId: mesh.mesh.id, + }); + } + } + } + // Excluded meshes + serializationObject.excludedMeshes = []; + const excludedMeshes = this._thinEffectLayer._excludedMeshes; + if (excludedMeshes) { + for (const e in excludedMeshes) { + const excludedMesh = excludedMeshes[e]; + if (excludedMesh) { + serializationObject.excludedMeshes.push(excludedMesh.mesh.id); + } + } + } + return serializationObject; + } + /** + * Creates a Highlight layer from parsed Highlight layer data + * @param parsedHightlightLayer defines the Highlight layer data + * @param scene defines the current scene + * @param rootUrl defines the root URL containing the Highlight layer information + * @returns a parsed Highlight layer + */ + static Parse(parsedHightlightLayer, scene, rootUrl) { + const hl = SerializationHelper.Parse(() => new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options), parsedHightlightLayer, scene, rootUrl); + let index; + // Excluded meshes + for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) { + const mesh = scene.getMeshById(parsedHightlightLayer.excludedMeshes[index]); + if (mesh) { + hl.addExcludedMesh(mesh); + } + } + // Included meshes + for (index = 0; index < parsedHightlightLayer.meshes.length; index++) { + const highlightedMesh = parsedHightlightLayer.meshes[index]; + const mesh = scene.getMeshById(highlightedMesh.meshId); + if (mesh) { + hl.addMesh(mesh, Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly); + } + } + return hl; + } +} +/** + * Effect Name of the highlight layer. + */ +HighlightLayer.EffectName = "HighlightLayer"; +__decorate([ + serialize() +], HighlightLayer.prototype, "innerGlow", null); +__decorate([ + serialize() +], HighlightLayer.prototype, "outerGlow", null); +__decorate([ + serialize() +], HighlightLayer.prototype, "blurHorizontalSize", null); +__decorate([ + serialize() +], HighlightLayer.prototype, "blurVerticalSize", null); +__decorate([ + serialize("options") +], HighlightLayer.prototype, "_options", void 0); +RegisterClass("BABYLON.HighlightLayer", HighlightLayer); + +// Do not edit. +const name$7y = "helperFunctions"; +const shader$7x = `const float PI=3.1415926535897932384626433832795;const float TWO_PI=6.283185307179586;const float HALF_PI=1.5707963267948966;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float RECIPROCAL_PI4=0.07957747154594767;const float HALF_MIN=5.96046448e-08; +const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; +#define saturate(x) clamp(x,0.0,1.0) +#define absEps(x) abs(x)+Epsilon +#define maxEps(x) max(x,Epsilon) +#define saturateEps(x) clamp(x,Epsilon,1.0) +mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( +vec3(i0.x,i1.x,i2.x), +vec3(i0.y,i1.y,i2.y), +vec3(i0.z,i1.z,i2.z) +);return outMatrix;} +mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), +b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), +b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} +#if USE_EXACT_SRGB_CONVERSIONS +vec3 toLinearSpaceExact(vec3 color) +{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); +#else +return +vec3( +color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, +color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, +color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); +#endif +} +vec3 toGammaSpaceExact(vec3 color) +{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); +#else +return +vec3( +color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, +color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, +color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); +#endif +} +#endif +float toLinearSpace(float color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; +#else +return pow(color,LinearEncodePowerApprox); +#endif +} +vec3 toLinearSpace(vec3 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toLinearSpaceExact(color); +#else +return pow(color,vec3(LinearEncodePowerApprox)); +#endif +} +vec4 toLinearSpace(vec4 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toLinearSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); +#endif +} +float toGammaSpace(float color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; +#else +return pow(color,GammaEncodePowerApprox); +#endif +} +vec3 toGammaSpace(vec3 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toGammaSpaceExact(color); +#else +return pow(color,vec3(GammaEncodePowerApprox)); +#endif +} +vec4 toGammaSpace(vec4 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toGammaSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); +#endif +} +float square(float value) +{return value*value;} +vec3 square(vec3 value) +{return value*value;} +float pow5(float value) {float sq=value*value;return sq*sq*value;} +float getLuminance(vec3 color) +{return saturate(dot(color,LuminanceEncodeApprox));} +float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} +float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} +const float rgbdMaxRange=255.;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =saturate(floor(D)/255.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(saturate(rgb),D);} +vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} +vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} +vec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*TWO_PI-PI;float latitude=HALF_PI-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;} +float sqrtClamped(float value) {return sqrt(max(value,0.));} +float avg(vec3 value) {return dot(value,vec3(0.333333333));}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$7y]) { + ShaderStore.IncludesShadersStore[name$7y] = shader$7x; +} +/** @internal */ +const helperFunctions = { name: name$7y, shader: shader$7x }; + +const helperFunctions$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + helperFunctions +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7x = "glowMapGenerationPixelShader"; +const shader$7w = `#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) +#include +#endif +#ifdef DIFFUSE +varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; +#endif +#ifdef OPACITY +varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; +#endif +#ifdef EMISSIVE +varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; +#endif +#ifdef VERTEXALPHA +varying vec4 vColor; +#endif +uniform vec4 glowColor;uniform float glowIntensity; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include +vec4 finalColor=glowColor; +#ifdef DIFFUSE +vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); +#ifdef DIFFUSE_ISLINEAR +albedoTexture=toGammaSpace(albedoTexture); +#endif +#ifdef GLOW +finalColor.a*=albedoTexture.a; +#endif +#ifdef HIGHLIGHT +finalColor.a=albedoTexture.a; +#endif +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); +#ifdef OPACITYRGB +finalColor.a*=getLuminance(opacityMap.rgb); +#else +finalColor.a*=opacityMap.a; +#endif +finalColor.a*=opacityIntensity; +#endif +#ifdef VERTEXALPHA +finalColor.a*=vColor.a; +#endif +#ifdef ALPHATEST +if (finalColor.a +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +uniform mat4 viewProjection;varying vec4 vPosition; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef DIFFUSE +varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; +#endif +#ifdef OPACITY +varying vec2 vUVOpacity;uniform mat4 opacityMatrix; +#endif +#ifdef EMISSIVE +varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; +#endif +#ifdef VERTEXALPHA +attribute vec4 color;varying vec4 vColor; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef UV2 +vec2 uv2Updated=uv2; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef CUBEMAP +vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); +#else +vPosition=viewProjection*worldPos;gl_Position=vPosition; +#endif +#ifdef DIFFUSE +#ifdef DIFFUSEUV1 +vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef DIFFUSEUV2 +vUVDiffuse=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); +#endif +#endif +#ifdef OPACITY +#ifdef OPACITYUV1 +vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef OPACITYUV2 +vUVOpacity=vec2(opacityMatrix*vec4(uv2Updated,1.0,0.0)); +#endif +#endif +#ifdef EMISSIVE +#ifdef EMISSIVEUV1 +vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef EMISSIVEUV2 +vUVEmissive=vec2(emissiveMatrix*vec4(uv2Updated,1.0,0.0)); +#endif +#endif +#ifdef VERTEXALPHA +vColor=color; +#endif +#include +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7w]) { + ShaderStore.ShadersStore[name$7w] = shader$7v; +} +/** @internal */ +const glowMapGenerationVertexShader = { name: name$7w, shader: shader$7v }; + +const glowMapGeneration_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + glowMapGenerationVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7v = "clipPlaneFragmentDeclaration"; +const shader$7u = `#ifdef CLIPPLANE +varying fClipDistance: f32; +#endif +#ifdef CLIPPLANE2 +varying fClipDistance2: f32; +#endif +#ifdef CLIPPLANE3 +varying fClipDistance3: f32; +#endif +#ifdef CLIPPLANE4 +varying fClipDistance4: f32; +#endif +#ifdef CLIPPLANE5 +varying fClipDistance5: f32; +#endif +#ifdef CLIPPLANE6 +varying fClipDistance6: f32; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7v]) { + ShaderStore.IncludesShadersStoreWGSL[name$7v] = shader$7u; +} +/** @internal */ +const clipPlaneFragmentDeclarationWGSL = { name: name$7v, shader: shader$7u }; + +const clipPlaneFragmentDeclaration = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + clipPlaneFragmentDeclarationWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7u = "clipPlaneFragment"; +const shader$7t = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +if (false) {} +#endif +#ifdef CLIPPLANE +else if (fragmentInputs.fClipDistance>0.0) +{discard;} +#endif +#ifdef CLIPPLANE2 +else if (fragmentInputs.fClipDistance2>0.0) +{discard;} +#endif +#ifdef CLIPPLANE3 +else if (fragmentInputs.fClipDistance3>0.0) +{discard;} +#endif +#ifdef CLIPPLANE4 +else if (fragmentInputs.fClipDistance4>0.0) +{discard;} +#endif +#ifdef CLIPPLANE5 +else if (fragmentInputs.fClipDistance5>0.0) +{discard;} +#endif +#ifdef CLIPPLANE6 +else if (fragmentInputs.fClipDistance6>0.0) +{discard;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7u]) { + ShaderStore.IncludesShadersStoreWGSL[name$7u] = shader$7t; +} +/** @internal */ +const clipPlaneFragmentWGSL = { name: name$7u, shader: shader$7t }; + +const clipPlaneFragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + clipPlaneFragmentWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7t = "glowMapGenerationPixelShader"; +const shader$7s = `#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) +#include +#endif +#ifdef DIFFUSE +varying vUVDiffuse: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; +#endif +#ifdef OPACITY +varying vUVOpacity: vec2f;var opacitySamplerSampler: sampler;var opacitySampler: texture_2d;uniform opacityIntensity: f32; +#endif +#ifdef EMISSIVE +varying vUVEmissive: vec2f;var emissiveSamplerSampler: sampler;var emissiveSampler: texture_2d; +#endif +#ifdef VERTEXALPHA +varying vColor: vec4f; +#endif +uniform glowColor: vec4f;uniform glowIntensity: f32; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#include +var finalColor: vec4f=uniforms.glowColor; +#ifdef DIFFUSE +var albedoTexture: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUVDiffuse); +#ifdef DIFFUSE_ISLINEAR +albedoTexture=toGammaSpace(albedoTexture); +#endif +#ifdef GLOW +finalColor=vec4f(finalColor.rgb,finalColor.a*albedoTexture.a); +#endif +#ifdef HIGHLIGHT +finalColor=vec4f(finalColor.rgb,albedoTexture.a); +#endif +#endif +#ifdef OPACITY +var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vUVOpacity); +#ifdef OPACITYRGB +finalColor=vec4f(finalColor.rgb,finalColor.a*getLuminance(opacityMap.rgb)); +#else +finalColor=vec4f(finalColor.rgb,finalColor.a*opacityMap.a); +#endif +finalColor=vec4f(finalColor.rgb,finalColor.a*uniforms.opacityIntensity); +#endif +#ifdef VERTEXALPHA +finalColor=vec4f(finalColor.rgb,finalColor.a*fragmentInputs.vColor.a); +#endif +#ifdef ALPHATEST +if (finalColor.a;varying fClipDistance: f32; +#endif +#ifdef CLIPPLANE2 +uniform vClipPlane2: vec4;varying fClipDistance2: f32; +#endif +#ifdef CLIPPLANE3 +uniform vClipPlane3: vec4;varying fClipDistance3: f32; +#endif +#ifdef CLIPPLANE4 +uniform vClipPlane4: vec4;varying fClipDistance4: f32; +#endif +#ifdef CLIPPLANE5 +uniform vClipPlane5: vec4;varying fClipDistance5: f32; +#endif +#ifdef CLIPPLANE6 +uniform vClipPlane6: vec4;varying fClipDistance6: f32; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7s]) { + ShaderStore.IncludesShadersStoreWGSL[name$7s] = shader$7r; +} +/** @internal */ +const clipPlaneVertexDeclarationWGSL = { name: name$7s, shader: shader$7r }; + +const clipPlaneVertexDeclaration = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + clipPlaneVertexDeclarationWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7r = "clipPlaneVertex"; +const shader$7q = `#ifdef CLIPPLANE +vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); +#endif +#ifdef CLIPPLANE2 +vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); +#endif +#ifdef CLIPPLANE3 +vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); +#endif +#ifdef CLIPPLANE4 +vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); +#endif +#ifdef CLIPPLANE5 +vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); +#endif +#ifdef CLIPPLANE6 +vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7r]) { + ShaderStore.IncludesShadersStoreWGSL[name$7r] = shader$7q; +} +/** @internal */ +const clipPlaneVertexWGSL = { name: name$7r, shader: shader$7q }; + +const clipPlaneVertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + clipPlaneVertexWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7q = "glowMapGenerationVertexShader"; +const shader$7p = `attribute position: vec3f; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +uniform viewProjection: mat4x4f;varying vPosition: vec4f; +#ifdef UV1 +attribute uv: vec2f; +#endif +#ifdef UV2 +attribute uv2: vec2f; +#endif +#ifdef DIFFUSE +varying vUVDiffuse: vec2f;uniform diffuseMatrix: mat4x4f; +#endif +#ifdef OPACITY +varying vUVOpacity: vec2f;uniform opacityMatrix: mat4x4f; +#endif +#ifdef EMISSIVE +varying vUVEmissive: vec2f;uniform emissiveMatrix: mat4x4f; +#endif +#ifdef VERTEXALPHA +attribute color: vec4f;varying vColor: vec4f; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position; +#ifdef UV1 +var uvUpdated: vec2f=input.uv; +#endif +#ifdef UV2 +var uv2Updated: vec2f=input.uv2; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0); +#ifdef CUBEMAP +vertexOutputs.vPosition=worldPos;vertexOutputs.position=uniforms.viewProjection*finalWorld* vec4f(input.position,1.0); +#else +vertexOutputs.vPosition=uniforms.viewProjection*worldPos;vertexOutputs.position=vertexOutputs.vPosition; +#endif +#ifdef DIFFUSE +#ifdef DIFFUSEUV1 +vertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; +#endif +#ifdef DIFFUSEUV2 +vertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy; +#endif +#endif +#ifdef OPACITY +#ifdef OPACITYUV1 +vertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uvUpdated,1.0,0.0)).xy; +#endif +#ifdef OPACITYUV2 +vertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uv2Updated,1.0,0.0)).xy; +#endif +#endif +#ifdef EMISSIVE +#ifdef EMISSIVEUV1 +vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uvUpdated,1.0,0.0)).xy; +#endif +#ifdef EMISSIVEUV2 +vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uv2Updated,1.0,0.0)).xy; +#endif +#endif +#ifdef VERTEXALPHA +vertexOutputs.vColor=vertexInputs.color; +#endif +#include +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7q]) { + ShaderStore.ShadersStoreWGSL[name$7q] = shader$7p; +} +/** @internal */ +const glowMapGenerationVertexShaderWGSL = { name: name$7q, shader: shader$7p }; + +const glowMapGeneration_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + glowMapGenerationVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7p = "glowMapMergePixelShader"; +const shader$7o = `varying vec2 vUV;uniform sampler2D textureSampler; +#ifdef EMISSIVE +uniform sampler2D textureSampler2; +#endif +uniform float offset; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV); +#ifdef EMISSIVE +baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; +#else +baseColor.a=abs(offset-baseColor.a); +#ifdef STROKE +float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; +#endif +#endif +#if LDR +baseColor=clamp(baseColor,0.,1.0); +#endif +gl_FragColor=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7p]) { + ShaderStore.ShadersStore[name$7p] = shader$7o; +} +/** @internal */ +const glowMapMergePixelShader = { name: name$7p, shader: shader$7o }; + +const glowMapMerge_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + glowMapMergePixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7o = "glowMapMergeVertexShader"; +const shader$7n = `attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7o]) { + ShaderStore.ShadersStore[name$7o] = shader$7n; +} +/** @internal */ +const glowMapMergeVertexShader = { name: name$7o, shader: shader$7n }; + +const glowMapMerge_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + glowMapMergeVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7n = "glowBlurPostProcessPixelShader"; +const shader$7m = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color) +{return dot(color,vec3(0.2126,0.7152,0.0722));} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++) +{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;} +gl_FragColor=baseColor;}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7n]) { + ShaderStore.ShadersStore[name$7n] = shader$7m; +} +/** @internal */ +const glowBlurPostProcessPixelShader = { name: name$7n, shader: shader$7m }; + +const glowBlurPostProcess_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + glowBlurPostProcessPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7m = "glowMapMergePixelShader"; +const shader$7l = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; +#ifdef EMISSIVE +var textureSampler2Sampler: sampler;var textureSampler2: texture_2d; +#endif +uniform offset: f32; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV); +#ifdef EMISSIVE +baseColor+=textureSample(textureSampler2,textureSampler2Sampler,input.vUV);baseColor*=uniforms.offset; +#else +baseColor=vec4f(baseColor.rgb,abs(uniforms.offset-baseColor.a)); +#ifdef STROKE +var alpha: f32=smoothstep(.0,.1,baseColor.a);baseColor=vec4f(baseColor.rgb*alpha,alpha); +#endif +#endif +#if LDR +baseColor=clamp(baseColor,vec4f(0.),vec4f(1.0)); +#endif +fragmentOutputs.color=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7m]) { + ShaderStore.ShadersStoreWGSL[name$7m] = shader$7l; +} +/** @internal */ +const glowMapMergePixelShaderWGSL = { name: name$7m, shader: shader$7l }; + +const glowMapMerge_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + glowMapMergePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7l = "glowMapMergeVertexShader"; +const shader$7k = `attribute position: vec2f;varying vUV: vec2f; +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5); +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position= vec4f(input.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7l]) { + ShaderStore.ShadersStoreWGSL[name$7l] = shader$7k; +} +/** @internal */ +const glowMapMergeVertexShaderWGSL = { name: name$7l, shader: shader$7k }; + +const glowMapMerge_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + glowMapMergeVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7k = "glowBlurPostProcessPixelShader"; +const shader$7j = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform direction: vec2f;uniform blurWidth: f32;fn getLuminance(color: vec3f)->f32 +{return dot(color, vec3f(0.2126,0.7152,0.0722));} +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var weights: array;weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;var texelSize: vec2f= vec2f(1.0/uniforms.screenSize.x,1.0/uniforms.screenSize.y);var texelStep: vec2f=texelSize*uniforms.direction*uniforms.blurWidth;var start: vec2f=input.vUV-3.0*texelStep;var baseColor: vec4f= vec4f(0.,0.,0.,0.);var texelOffset: vec2f= vec2f(0.,0.);for (var i: i32=0; i<7; i++) +{var texel: vec4f=textureSample(textureSampler,textureSamplerSampler,start+texelOffset);baseColor=vec4f(baseColor.rgb,baseColor.a+texel.a*weights[i]);var luminance: f32=getLuminance(baseColor.rgb);var luminanceTexel: f32=getLuminance(texel.rgb);var choice: f32=step(luminanceTexel,luminance);baseColor=vec4f(choice*baseColor.rgb+(1.0-choice)*texel.rgb,baseColor.a);texelOffset+=texelStep;} +fragmentOutputs.color=baseColor;}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7k]) { + ShaderStore.ShadersStoreWGSL[name$7k] = shader$7j; +} +/** @internal */ +const glowBlurPostProcessPixelShaderWGSL = { name: name$7k, shader: shader$7j }; + +const glowBlurPostProcess_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + glowBlurPostProcessPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7j = "layerPixelShader"; +const shader$7i = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV); +#if defined(CONVERT_TO_GAMMA) +baseColor.rgb=toGammaSpace(baseColor.rgb); +#elif defined(CONVERT_TO_LINEAR) +baseColor.rgb=toLinearSpace(baseColor.rgb); +#endif +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +gl_FragColor=baseColor*color; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7j]) { + ShaderStore.ShadersStore[name$7j] = shader$7i; +} + +// Do not edit. +const name$7i = "layerVertexShader"; +const shader$7h = `attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7i]) { + ShaderStore.ShadersStore[name$7i] = shader$7h; +} + +// Do not edit. +const name$7h = "layerPixelShader"; +const shader$7g = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform color: vec4f; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV); +#if defined(CONVERT_TO_GAMMA) +baseColor=toGammaSpace(baseColor); +#elif defined(CONVERT_TO_LINEAR) +baseColor=toLinearSpaceVec4(baseColor); +#endif +#ifdef ALPHATEST +if (baseColor.a<0.4) {discard;} +#endif +fragmentOutputs.color=baseColor*uniforms.color; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7h]) { + ShaderStore.ShadersStoreWGSL[name$7h] = shader$7g; +} + +// Do not edit. +const name$7g = "layerVertexShader"; +const shader$7f = `attribute position: vec2f;uniform scale: vec2f;uniform offset: vec2f;uniform textureMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +var shiftedPosition: vec2f=input.position*uniforms.scale+uniforms.offset;vertexOutputs.vUV=(uniforms.textureMatrix* vec4f(shiftedPosition*madd+madd,1.0,0.0)).xy;vertexOutputs.position= vec4f(shiftedPosition,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7g]) { + ShaderStore.ShadersStoreWGSL[name$7g] = shader$7f; +} + +/** + * This represents one of the lens effect in a `lensFlareSystem`. + * It controls one of the individual texture used in the effect. + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare + */ +class LensFlare { + /** + * Creates a new Lens Flare. + * This represents one of the lens effect in a `lensFlareSystem`. + * It controls one of the individual texture used in the effect. + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare + * @param size Define the size of the lens flare (a floating value between 0 and 1) + * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind. + * @param color Define the lens color + * @param imgUrl Define the lens texture url + * @param system Define the `lensFlareSystem` this flare is part of + * @returns The newly created Lens Flare + */ + static AddFlare(size, position, color, imgUrl, system) { + return new LensFlare(size, position, color, imgUrl, system); + } + /** + * Instantiates a new Lens Flare. + * This represents one of the lens effect in a `lensFlareSystem`. + * It controls one of the individual texture used in the effect. + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare + * @param size Define the size of the lens flare in the system (a floating value between 0 and 1) + * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind. + * @param color Define the lens color + * @param imgUrl Define the lens texture url + * @param system Define the `lensFlareSystem` this flare is part of + */ + constructor( + /** + * Define the size of the lens flare in the system (a floating value between 0 and 1) + */ + size, + /** + * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind. + */ + position, color, imgUrl, system) { + this.size = size; + this.position = position; + /** + * Define the alpha mode to render this particular lens. + */ + this.alphaMode = 6; + this.color = color || new Color3(1, 1, 1); + this.texture = imgUrl ? new Texture(imgUrl, system.getScene(), true) : null; + this._system = system; + const engine = system.scene.getEngine(); + system._onShadersLoaded.addOnce(() => { + this._drawWrapper = new DrawWrapper(engine); + this._drawWrapper.effect = engine.createEffect("lensFlare", [VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "", undefined, undefined, undefined, undefined, system.shaderLanguage); + }); + system.lensFlares.push(this); + } + /** + * Dispose and release the lens flare with its associated resources. + */ + dispose() { + if (this.texture) { + this.texture.dispose(); + } + // Remove from scene + const index = this._system.lensFlares.indexOf(this); + this._system.lensFlares.splice(index, 1); + } +} + +/** + * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses. + * It is usually composed of several `lensFlare`. + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare + */ +class LensFlareSystem { + /** Gets the scene */ + get scene() { + return this._scene; + } + /** + * Gets the shader language used in this system. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Instantiates a lens flare system. + * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses. + * It is usually composed of several `lensFlare`. + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare + * @param name Define the name of the lens flare system in the scene + * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh). + * @param scene Define the scene the lens flare system belongs to + */ + constructor( + /** + * Define the name of the lens flare system + */ + name, emitter, scene) { + this.name = name; + /** + * List of lens flares used in this system. + */ + this.lensFlares = []; + /** + * Define a limit from the border the lens flare can be visible. + */ + this.borderLimit = 300; + /** + * Define a viewport border we do not want to see the lens flare in. + */ + this.viewportBorder = 0; + /** + * Restricts the rendering of the effect to only the camera rendering this layer mask. + */ + this.layerMask = 0x0fffffff; + /** Shader language used by the system */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._vertexBuffers = {}; + this._isEnabled = true; + /** @internal */ + this._onShadersLoaded = new Observable(undefined, true); + this._shadersLoaded = false; + this._scene = scene || EngineStore.LastCreatedScene; + LensFlareSystem._SceneComponentInitialization(this._scene); + this._emitter = emitter; + this.id = name; + scene.lensFlareSystems.push(this); + this.meshesSelectionPredicate = (m) => (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && (m.layerMask & scene.activeCamera.layerMask) != 0); + const engine = scene.getEngine(); + // VBO + const vertices = []; + vertices.push(1, 1); + vertices.push(-1, 1); + vertices.push(-1, -1); + vertices.push(1, -1); + this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2); + // Indices + this._createIndexBuffer(); + this._initShaderSourceAsync(); + } + async _initShaderSourceAsync() { + const engine = this._scene.getEngine(); + if (engine.isWebGPU && !LensFlareSystem.ForceGLSL) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + await Promise.all([Promise.resolve().then(() => lensFlare_fragment), Promise.resolve().then(() => lensFlare_vertex)]); + } + else { + await Promise.all([Promise.resolve().then(() => lensFlare_fragment$1), Promise.resolve().then(() => lensFlare_vertex$1)]); + } + this._shadersLoaded = true; + this._onShadersLoaded.notifyObservers(); + } + _createIndexBuffer() { + const indices = []; + indices.push(0); + indices.push(1); + indices.push(2); + indices.push(0); + indices.push(2); + indices.push(3); + this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices); + } + /** + * Define if the lens flare system is enabled. + */ + get isEnabled() { + return this._isEnabled; + } + set isEnabled(value) { + this._isEnabled = value; + } + /** + * Get the scene the effects belongs to. + * @returns the scene holding the lens flare system + */ + getScene() { + return this._scene; + } + /** + * Get the emitter of the lens flare system. + * It defines the source of the lens flares (it can be a camera, a light or a mesh). + * @returns the emitter of the lens flare system + */ + getEmitter() { + return this._emitter; + } + /** + * Set the emitter of the lens flare system. + * It defines the source of the lens flares (it can be a camera, a light or a mesh). + * @param newEmitter Define the new emitter of the system + */ + setEmitter(newEmitter) { + this._emitter = newEmitter; + } + /** + * Get the lens flare system emitter position. + * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh). + * @returns the position + */ + getEmitterPosition() { + return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position; + } + /** + * @internal + */ + computeEffectivePosition(globalViewport) { + let position = this.getEmitterPosition(); + position = Vector3.Project(position, Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport); + this._positionX = position.x; + this._positionY = position.y; + position = Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix()); + if (this.viewportBorder > 0) { + globalViewport.x -= this.viewportBorder; + globalViewport.y -= this.viewportBorder; + globalViewport.width += this.viewportBorder * 2; + globalViewport.height += this.viewportBorder * 2; + position.x += this.viewportBorder; + position.y += this.viewportBorder; + this._positionX += this.viewportBorder; + this._positionY += this.viewportBorder; + } + const rhs = this._scene.useRightHandedSystem; + const okZ = (position.z > 0 && !rhs) || (position.z < 0 && rhs); + if (okZ) { + if (this._positionX > globalViewport.x && this._positionX < globalViewport.x + globalViewport.width) { + if (this._positionY > globalViewport.y && this._positionY < globalViewport.y + globalViewport.height) { + return true; + } + } + return true; + } + return false; + } + /** @internal */ + _isVisible() { + if (!this._isEnabled || !this._scene.activeCamera) { + return false; + } + const emitterPosition = this.getEmitterPosition(); + const direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition); + const distance = direction.length(); + direction.normalize(); + const ray = new Ray(this._scene.activeCamera.globalPosition, direction); + const pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true); + return !pickInfo || !pickInfo.hit || pickInfo.distance > distance; + } + /** + * @internal + */ + render() { + if (!this._scene.activeCamera || !this._shadersLoaded) { + return false; + } + const engine = this._scene.getEngine(); + const viewport = this._scene.activeCamera.viewport; + const globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true)); + // Position + if (!this.computeEffectivePosition(globalViewport)) { + return false; + } + // Visibility + if (!this._isVisible()) { + return false; + } + // Intensity + let awayX; + let awayY; + if (this._positionX < this.borderLimit + globalViewport.x) { + awayX = this.borderLimit + globalViewport.x - this._positionX; + } + else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) { + awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit; + } + else { + awayX = 0; + } + if (this._positionY < this.borderLimit + globalViewport.y) { + awayY = this.borderLimit + globalViewport.y - this._positionY; + } + else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) { + awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit; + } + else { + awayY = 0; + } + let away = awayX > awayY ? awayX : awayY; + away -= this.viewportBorder; + if (away > this.borderLimit) { + away = this.borderLimit; + } + let intensity = 1.0 - Clamp(away / this.borderLimit, 0, 1); + if (intensity < 0) { + return false; + } + if (intensity > 1.0) { + intensity = 1.0; + } + if (this.viewportBorder > 0) { + globalViewport.x += this.viewportBorder; + globalViewport.y += this.viewportBorder; + globalViewport.width -= this.viewportBorder * 2; + globalViewport.height -= this.viewportBorder * 2; + this._positionX -= this.viewportBorder; + this._positionY -= this.viewportBorder; + } + // Position + const centerX = globalViewport.x + globalViewport.width / 2; + const centerY = globalViewport.y + globalViewport.height / 2; + const distX = centerX - this._positionX; + const distY = centerY - this._positionY; + // Effects + engine.setState(false); + engine.setDepthBuffer(false); + // Flares + for (let index = 0; index < this.lensFlares.length; index++) { + const flare = this.lensFlares[index]; + if (!flare._drawWrapper.effect.isReady() || (flare.texture && !flare.texture.isReady())) { + continue; + } + engine.enableEffect(flare._drawWrapper); + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, flare._drawWrapper.effect); + engine.setAlphaMode(flare.alphaMode); + const x = centerX - distX * flare.position; + const y = centerY - distY * flare.position; + const cw = flare.size; + const ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true); + const cx = 2 * ((x - globalViewport.x) / globalViewport.width) - 1.0; + const cy = 1.0 - 2 * ((y - globalViewport.y) / globalViewport.height); + const viewportMatrix = Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1); + flare._drawWrapper.effect.setMatrix("viewportMatrix", viewportMatrix); + // Texture + flare._drawWrapper.effect.setTexture("textureSampler", flare.texture); + // Color + flare._drawWrapper.effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0); + // Draw order + engine.drawElementsType(Material.TriangleFillMode, 0, 6); + } + engine.setDepthBuffer(true); + engine.setAlphaMode(0); + return true; + } + /** + * Rebuilds the lens flare system + */ + rebuild() { + this._createIndexBuffer(); + for (const key in this._vertexBuffers) { + this._vertexBuffers[key]?._rebuild(); + } + } + /** + * Dispose and release the lens flare with its associated resources. + */ + dispose() { + this._onShadersLoaded.clear(); + const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind]; + if (vertexBuffer) { + vertexBuffer.dispose(); + this._vertexBuffers[VertexBuffer.PositionKind] = null; + } + if (this._indexBuffer) { + this._scene.getEngine()._releaseBuffer(this._indexBuffer); + this._indexBuffer = null; + } + while (this.lensFlares.length) { + this.lensFlares[0].dispose(); + } + // Remove from scene + const index = this._scene.lensFlareSystems.indexOf(this); + this._scene.lensFlareSystems.splice(index, 1); + } + /** + * Parse a lens flare system from a JSON representation + * @param parsedLensFlareSystem Define the JSON to parse + * @param scene Define the scene the parsed system should be instantiated in + * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures + * @returns the parsed system + */ + static Parse(parsedLensFlareSystem, scene, rootUrl) { + const emitter = scene.getLastEntryById(parsedLensFlareSystem.emitterId); + const name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId; + const lensFlareSystem = new LensFlareSystem(name, emitter, scene); + lensFlareSystem.id = parsedLensFlareSystem.id || name; + lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit; + for (let index = 0; index < parsedLensFlareSystem.flares.length; index++) { + const parsedFlare = parsedLensFlareSystem.flares[index]; + LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem); + } + return lensFlareSystem; + } + /** + * Serialize the current Lens Flare System into a JSON representation. + * @returns the serialized JSON + */ + serialize() { + const serializationObject = {}; + serializationObject.id = this.id; + serializationObject.name = this.name; + serializationObject.emitterId = this.getEmitter().id; + serializationObject.borderLimit = this.borderLimit; + serializationObject.flares = []; + for (let index = 0; index < this.lensFlares.length; index++) { + const flare = this.lensFlares[index]; + serializationObject.flares.push({ + size: flare.size, + position: flare.position, + color: flare.color.asArray(), + textureName: Tools.GetFilename(flare.texture ? flare.texture.name : ""), + }); + } + return serializationObject; + } +} +/** + * Force all the lens flare systems to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +LensFlareSystem.ForceGLSL = false; +/** + * @internal + */ +LensFlareSystem._SceneComponentInitialization = (_) => { + throw _WarnImport("LensFlareSystemSceneComponent"); +}; + +// Adds the parser to the scene parsers. +AddParser(SceneComponentConstants.NAME_LENSFLARESYSTEM, (parsedData, scene, container, rootUrl) => { + // Lens flares + if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) { + if (!container.lensFlareSystems) { + container.lensFlareSystems = []; + } + for (let index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) { + const parsedLensFlareSystem = parsedData.lensFlareSystems[index]; + const lf = LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl); + container.lensFlareSystems.push(lf); + } + } +}); +Scene.prototype.getLensFlareSystemByName = function (name) { + for (let index = 0; index < this.lensFlareSystems.length; index++) { + if (this.lensFlareSystems[index].name === name) { + return this.lensFlareSystems[index]; + } + } + return null; +}; +Scene.prototype.getLensFlareSystemById = function (id) { + for (let index = 0; index < this.lensFlareSystems.length; index++) { + if (this.lensFlareSystems[index].id === id) { + return this.lensFlareSystems[index]; + } + } + return null; +}; +Scene.prototype.getLensFlareSystemByID = function (id) { + return this.getLensFlareSystemById(id); +}; +Scene.prototype.removeLensFlareSystem = function (toRemove) { + const index = this.lensFlareSystems.indexOf(toRemove); + if (index !== -1) { + this.lensFlareSystems.splice(index, 1); + } + return index; +}; +Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) { + this.lensFlareSystems.push(newLensFlareSystem); +}; +/** + * Defines the lens flare scene component responsible to manage any lens flares + * in a given scene. + */ +class LensFlareSystemSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_LENSFLARESYSTEM; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + for (let index = 0; index < this.scene.lensFlareSystems.length; index++) { + this.scene.lensFlareSystems[index].rebuild(); + } + } + /** + * Adds all the elements from the container to the scene + * @param container the container holding the elements + */ + addFromContainer(container) { + if (!container.lensFlareSystems) { + return; + } + container.lensFlareSystems.forEach((o) => { + this.scene.addLensFlareSystem(o); + }); + } + /** + * Removes all the elements in the container from the scene + * @param container contains the elements to remove + * @param dispose if the removed element should be disposed (default: false) + */ + removeFromContainer(container, dispose) { + if (!container.lensFlareSystems) { + return; + } + container.lensFlareSystems.forEach((o) => { + this.scene.removeLensFlareSystem(o); + if (dispose) { + o.dispose(); + } + }); + } + /** + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to + */ + serialize(serializationObject) { + // Lens flares + serializationObject.lensFlareSystems = []; + const lensFlareSystems = this.scene.lensFlareSystems; + for (const lensFlareSystem of lensFlareSystems) { + serializationObject.lensFlareSystems.push(lensFlareSystem.serialize()); + } + } + /** + * Disposes the component and the associated resources. + */ + dispose() { + const lensFlareSystems = this.scene.lensFlareSystems; + while (lensFlareSystems.length) { + lensFlareSystems[0].dispose(); + } + } + _draw(camera) { + // Lens flares + if (this.scene.lensFlaresEnabled) { + const lensFlareSystems = this.scene.lensFlareSystems; + Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0); + for (const lensFlareSystem of lensFlareSystems) { + if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) { + lensFlareSystem.render(); + } + } + Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0); + } + } +} +LensFlareSystem._SceneComponentInitialization = (scene) => { + let component = scene._getComponent(SceneComponentConstants.NAME_LENSFLARESYSTEM); + if (!component) { + component = new LensFlareSystemSceneComponent(scene); + scene._addComponent(component); + } +}; + +// Do not edit. +const name$7f = "lensFlarePixelShader"; +const shader$7e = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7f]) { + ShaderStore.ShadersStore[name$7f] = shader$7e; +} +/** @internal */ +const lensFlarePixelShader = { name: name$7f, shader: shader$7e }; + +const lensFlare_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lensFlarePixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7e = "lensFlareVertexShader"; +const shader$7d = `attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7e]) { + ShaderStore.ShadersStore[name$7e] = shader$7d; +} +/** @internal */ +const lensFlareVertexShader = { name: name$7e, shader: shader$7d }; + +const lensFlare_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lensFlareVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7d = "lensFlarePixelShader"; +const shader$7c = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform color: vec4f; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);fragmentOutputs.color=baseColor*uniforms.color; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7d]) { + ShaderStore.ShadersStoreWGSL[name$7d] = shader$7c; +} +/** @internal */ +const lensFlarePixelShaderWGSL = { name: name$7d, shader: shader$7c }; + +const lensFlare_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lensFlarePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7c = "lensFlareVertexShader"; +const shader$7b = `attribute position: vec2f;uniform viewportMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position=uniforms.viewportMatrix* vec4f(input.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$7c]) { + ShaderStore.ShadersStoreWGSL[name$7c] = shader$7b; +} +/** @internal */ +const lensFlareVertexShaderWGSL = { name: name$7c, shader: shader$7b }; + +const lensFlare_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lensFlareVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7b = "packingFunctions"; +const shader$7a = `fn pack(depth: f32)->vec4f +{const bit_shift: vec4f= vec4f(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const bit_mask: vec4f= vec4f(0.0,1.0/255.0,1.0/255.0,1.0/255.0);var res: vec4f=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} +fn unpack(color: vec4f)->f32 +{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7b]) { + ShaderStore.IncludesShadersStoreWGSL[name$7b] = shader$7a; +} +/** @internal */ +const packingFunctionsWGSL = { name: name$7b, shader: shader$7a }; + +const packingFunctions = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + packingFunctionsWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$7a = "bayerDitherFunctions"; +const shader$79 = `fn bayerDither2(_P: vec2f)->f32 {return ((2.0*_P.y+_P.x+1.0)%(4.0));} +fn bayerDither4(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); +var P2: vec2f=floor(0.5*((_P)%(4.0))); +return 4.0*bayerDither2(P1)+bayerDither2(P2);} +fn bayerDither8(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); +var P2: vec2f=floor(0.5 *((_P)%(4.0))); +var P4: vec2f=floor(0.25*((_P)%(8.0))); +return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$7a]) { + ShaderStore.IncludesShadersStoreWGSL[name$7a] = shader$79; +} + +// Do not edit. +const name$79 = "shadowMapFragmentExtraDeclaration"; +const shader$78 = `#if SM_FLOAT==0 +#include +#endif +#if SM_SOFTTRANSPARENTSHADOW==1 +#include +uniform softTransparentShadowSM: vec2f; +#endif +varying vDepthMetricSM: f32; +#if SM_USEDISTANCE==1 +uniform lightDataSM: vec3f;varying vPositionWSM: vec3f; +#endif +uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying zSM: f32; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$79]) { + ShaderStore.IncludesShadersStoreWGSL[name$79] = shader$78; +} + +// Do not edit. +const name$78 = "shadowMapFragment"; +const shader$77 = `var depthSM: f32=fragmentInputs.vDepthMetricSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +#if SM_USEDISTANCE==1 +depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +depthSM=(-fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; +#else +depthSM=(fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; +#endif +#endif +depthSM=clamp(depthSM,0.0,1.0); +#ifdef USE_REVERSE_DEPTHBUFFER +fragmentOutputs.fragDepth=clamp(1.0-depthSM,0.0,1.0); +#else +fragmentOutputs.fragDepth=clamp(depthSM,0.0,1.0); +#endif +#elif SM_USEDISTANCE==1 +depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; +#endif +#if SM_ESM==1 +depthSM=clamp(exp(-min(87.,uniforms.biasAndScaleSM.z*depthSM)),0.,1.); +#endif +#if SM_FLOAT==1 +fragmentOutputs.color= vec4f(depthSM,1.0,1.0,1.0); +#else +fragmentOutputs.color=pack(depthSM); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$78]) { + ShaderStore.IncludesShadersStoreWGSL[name$78] = shader$77; +} +/** @internal */ +const shadowMapFragmentWGSL = { name: name$78, shader: shader$77 }; + +const shadowMapFragment$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowMapFragmentWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$77 = "shadowMapPixelShader"; +const shader$76 = `#include +#ifdef ALPHATEXTURE +varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#include +#ifdef ALPHATEXTURE +var opacityMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV);var alphaFromAlphaTexture: f32=opacityMap.a; +#if SM_SOFTTRANSPARENTSHADOW==1 +if (uniforms.softTransparentShadowSM.y==1.0) {opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;} +#endif +#ifdef ALPHATESTVALUE +if (alphaFromAlphaTexture=uniforms.softTransparentShadowSM.x*alphaFromAlphaTexture) {discard;} +#else +if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x) {discard;} +#endif +#endif +#include +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$77]) { + ShaderStore.ShadersStoreWGSL[name$77] = shader$76; +} +/** @internal */ +const shadowMapPixelShaderWGSL = { name: name$77, shader: shader$76 }; + +const shadowMap_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowMapPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$76 = "shadowMapVertexExtraDeclaration"; +const shader$75 = `#if SM_NORMALBIAS==1 +uniform lightDataSM: vec3f; +#endif +uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;varying vDepthMetricSM: f32; +#if SM_USEDISTANCE==1 +varying vPositionWSM: vec3f; +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying zSM: f32; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$76]) { + ShaderStore.IncludesShadersStoreWGSL[name$76] = shader$75; +} + +// Do not edit. +const name$75 = "shadowMapVertexNormalBias"; +const shader$74 = `#if SM_NORMALBIAS==1 +#if SM_DIRECTIONINLIGHTDATA==1 +var worldLightDirSM: vec3f=normalize(-uniforms.lightDataSM.xyz); +#else +var directionToLightSM: vec3f=uniforms.lightDataSM.xyz-worldPos.xyz;var worldLightDirSM: vec3f=normalize(directionToLightSM); +#endif +var ndlSM: f32=dot(vNormalW,worldLightDirSM);var sinNLSM: f32=sqrt(1.0-ndlSM*ndlSM);var normalBiasSM: f32=uniforms.biasAndScaleSM.y*sinNLSM;worldPos=vec4f(worldPos.xyz-vNormalW*normalBiasSM,worldPos.w); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$75]) { + ShaderStore.IncludesShadersStoreWGSL[name$75] = shader$74; +} + +// Do not edit. +const name$74 = "shadowMapVertexMetric"; +const shader$73 = `#if SM_USEDISTANCE==1 +vertexOutputs.vPositionWSM=worldPos.xyz; +#endif +#if SM_DEPTHTEXTURE==1 +#ifdef IS_NDC_HALF_ZRANGE +#define BIASFACTOR 0.5 +#else +#define BIASFACTOR 1.0 +#endif +#ifdef USE_REVERSE_DEPTHBUFFER +vertexOutputs.position.z-=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR; +#else +vertexOutputs.position.z+=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR; +#endif +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +vertexOutputs.zSM=vertexOutputs.position.z;vertexOutputs.position.z=0.0; +#elif SM_USEDISTANCE==0 +#ifdef USE_REVERSE_DEPTHBUFFER +vertexOutputs.vDepthMetricSM=(-vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; +#else +vertexOutputs.vDepthMetricSM=(vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$74]) { + ShaderStore.IncludesShadersStoreWGSL[name$74] = shader$73; +} +/** @internal */ +const shadowMapVertexMetricWGSL = { name: name$74, shader: shader$73 }; + +const shadowMapVertexMetric$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowMapVertexMetricWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$73 = "shadowMapVertexShader"; +const shader$72 = `attribute position: vec3f; +#ifdef NORMAL +attribute normal: vec3f; +#endif +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef INSTANCES +attribute world0: vec4f;attribute world1: vec4f;attribute world2: vec4f;attribute world3: vec4f; +#endif +#include +#include +#include +#ifdef ALPHATEXTURE +varying vUV: vec2f;uniform diffuseMatrix: mat4x4f; +#ifdef UV1 +attribute uv: vec2f; +#endif +#ifdef UV2 +attribute uv2: vec2f; +#endif +#endif +#include +#include +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position; +#ifdef UV1 +var uvUpdated: vec2f=input.uv; +#endif +#ifdef UV2 +var uv2Updated: vec2f=input.uv2; +#endif +#ifdef NORMAL +var normalUpdated: vec3f=input.normal; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0); +#ifdef NORMAL +var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +var vNormalW: vec3f=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +var vNormalW: vec3f=normalize(normWorldSM*normalUpdated); +#endif +#endif +#include +vertexOutputs.position=scene.viewProjection*worldPos; +#include +#ifdef ALPHATEXTURE +#ifdef UV1 +vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; +#endif +#ifdef UV2 +vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy; +#endif +#endif +#include +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$73]) { + ShaderStore.ShadersStoreWGSL[name$73] = shader$72; +} +/** @internal */ +const shadowMapVertexShaderWGSL = { name: name$73, shader: shader$72 }; + +const shadowMap_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowMapVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$72 = "depthBoxBlurPixelShader"; +const shader$71 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var colorDepth: vec4f=vec4f(0.0);for (var x: i32=-OFFSET; x<=OFFSET; x++) {for (var y: i32=-OFFSET; y<=OFFSET; y++) {colorDepth+=textureSample(textureSampler,textureSamplerSampler,input.vUV+ vec2f(f32(x),f32(y))/uniforms.screenSize);}} +fragmentOutputs.color=(colorDepth/ f32((OFFSET*2+1)*(OFFSET*2+1)));}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$72]) { + ShaderStore.ShadersStoreWGSL[name$72] = shader$71; +} +/** @internal */ +const depthBoxBlurPixelShaderWGSL = { name: name$72, shader: shader$71 }; + +const depthBoxBlur_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + depthBoxBlurPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$71 = "shadowMapFragmentSoftTransparentShadow"; +const shader$70 = `#if SM_SOFTTRANSPARENTSHADOW==1 +if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alpha) {discard;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$71]) { + ShaderStore.IncludesShadersStoreWGSL[name$71] = shader$70; +} +/** @internal */ +const shadowMapFragmentSoftTransparentShadowWGSL = { name: name$71, shader: shader$70 }; + +const shadowMapFragmentSoftTransparentShadow$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowMapFragmentSoftTransparentShadowWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$70 = "bayerDitherFunctions"; +const shader$6$ = `float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} +float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); +vec2 P2=floor(0.5*mod(_P,4.0)); +return 4.0*bayerDither2(P1)+bayerDither2(P2);} +float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); +vec2 P2=floor(0.5 *mod(_P,4.0)); +vec2 P4=floor(0.25*mod(_P,8.0)); +return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$70]) { + ShaderStore.IncludesShadersStore[name$70] = shader$6$; +} + +// Do not edit. +const name$6$ = "shadowMapFragmentExtraDeclaration"; +const shader$6_ = `#if SM_FLOAT==0 +#include +#endif +#if SM_SOFTTRANSPARENTSHADOW==1 +#include +uniform vec2 softTransparentShadowSM; +#endif +varying float vDepthMetricSM; +#if SM_USEDISTANCE==1 +uniform vec3 lightDataSM;varying vec3 vPositionWSM; +#endif +uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying float zSM; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6$]) { + ShaderStore.IncludesShadersStore[name$6$] = shader$6_; +} + +// Do not edit. +const name$6_ = "shadowMapFragment"; +const shader$6Z = `float depthSM=vDepthMetricSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +#if SM_USEDISTANCE==1 +depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#endif +depthSM=clamp(depthSM,0.0,1.0); +#ifdef USE_REVERSE_DEPTHBUFFER +gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); +#else +gl_FragDepth=clamp(depthSM,0.0,1.0); +#endif +#elif SM_USEDISTANCE==1 +depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#if SM_ESM==1 +depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); +#endif +#if SM_FLOAT==1 +gl_FragColor=vec4(depthSM,1.0,1.0,1.0); +#else +gl_FragColor=pack(depthSM); +#endif +return;`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6_]) { + ShaderStore.IncludesShadersStore[name$6_] = shader$6Z; +} +/** @internal */ +const shadowMapFragment = { name: name$6_, shader: shader$6Z }; + +const shadowMapFragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowMapFragment +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6Z = "shadowMapPixelShader"; +const shader$6Y = `#include +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include +#ifdef ALPHATEXTURE +vec4 opacityMap=texture2D(diffuseSampler,vUV);float alphaFromAlphaTexture=opacityMap.a; +#if SM_SOFTTRANSPARENTSHADOW==1 +if (softTransparentShadowSM.y==1.0) {opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;} +#endif +#ifdef ALPHATESTVALUE +if (alphaFromAlphaTexture=softTransparentShadowSM.x*alphaFromAlphaTexture) discard; +#else +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x) discard; +#endif +#endif +#include +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$6Z]) { + ShaderStore.ShadersStore[name$6Z] = shader$6Y; +} +/** @internal */ +const shadowMapPixelShader = { name: name$6Z, shader: shader$6Y }; + +const shadowMap_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowMapPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6Y = "sceneVertexDeclaration"; +const shader$6X = `uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6Y]) { + ShaderStore.IncludesShadersStore[name$6Y] = shader$6X; +} + +// Do not edit. +const name$6X = "meshVertexDeclaration"; +const shader$6W = `uniform mat4 world;uniform float visibility; +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6X]) { + ShaderStore.IncludesShadersStore[name$6X] = shader$6W; +} + +// Do not edit. +const name$6W = "shadowMapVertexDeclaration"; +const shader$6V = `#include +#include +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6W]) { + ShaderStore.IncludesShadersStore[name$6W] = shader$6V; +} + +// Do not edit. +const name$6V = "sceneUboDeclaration"; +const shader$6U = `layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; +#ifdef MULTIVIEW +mat4 viewProjectionR; +#endif +mat4 view;mat4 projection;vec4 vEyePosition;}; +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6V]) { + ShaderStore.IncludesShadersStore[name$6V] = shader$6U; +} + +// Do not edit. +const name$6U = "meshUboDeclaration"; +const shader$6T = `#ifdef WEBGL2 +uniform mat4 world;uniform float visibility; +#else +layout(std140,column_major) uniform;uniform Mesh +{mat4 world;float visibility;}; +#endif +#define WORLD_UBO +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6U]) { + ShaderStore.IncludesShadersStore[name$6U] = shader$6T; +} + +// Do not edit. +const name$6T = "shadowMapUboDeclaration"; +const shader$6S = `layout(std140,column_major) uniform; +#include +#include +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6T]) { + ShaderStore.IncludesShadersStore[name$6T] = shader$6S; +} + +// Do not edit. +const name$6S = "shadowMapVertexExtraDeclaration"; +const shader$6R = `#if SM_NORMALBIAS==1 +uniform vec3 lightDataSM; +#endif +uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; +#if SM_USEDISTANCE==1 +varying vec3 vPositionWSM; +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying float zSM; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6S]) { + ShaderStore.IncludesShadersStore[name$6S] = shader$6R; +} + +// Do not edit. +const name$6R = "shadowMapVertexNormalBias"; +const shader$6Q = `#if SM_NORMALBIAS==1 +#if SM_DIRECTIONINLIGHTDATA==1 +vec3 worldLightDirSM=normalize(-lightDataSM.xyz); +#else +vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); +#endif +float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6R]) { + ShaderStore.IncludesShadersStore[name$6R] = shader$6Q; +} + +// Do not edit. +const name$6Q = "shadowMapVertexMetric"; +const shader$6P = `#if SM_USEDISTANCE==1 +vPositionWSM=worldPos.xyz; +#endif +#if SM_DEPTHTEXTURE==1 +#ifdef IS_NDC_HALF_ZRANGE +#define BIASFACTOR 0.5 +#else +#define BIASFACTOR 1.0 +#endif +#ifdef USE_REVERSE_DEPTHBUFFER +gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; +#else +gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; +#endif +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +zSM=gl_Position.z;gl_Position.z=0.0; +#elif SM_USEDISTANCE==0 +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6Q]) { + ShaderStore.IncludesShadersStore[name$6Q] = shader$6P; +} +/** @internal */ +const shadowMapVertexMetric = { name: name$6Q, shader: shader$6P }; + +const shadowMapVertexMetric$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowMapVertexMetric +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6P = "shadowMapVertexShader"; +const shader$6O = `attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#endif +#include +#include<__decl__shadowMapVertex> +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#include +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef UV2 +vec2 uv2Updated=uv2; +#endif +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normWorldSM=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vec3 vNormalW=normalize(normWorldSM*normalUpdated); +#endif +#endif +#include +gl_Position=viewProjection*worldPos; +#include +#ifdef ALPHATEXTURE +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); +#endif +#endif +#include +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$6P]) { + ShaderStore.ShadersStore[name$6P] = shader$6O; +} +/** @internal */ +const shadowMapVertexShader = { name: name$6P, shader: shader$6O }; + +const shadowMap_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowMapVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6O = "depthBoxBlurPixelShader"; +const shader$6N = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) +for (int y=-OFFSET; y<=OFFSET; y++) +colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$6O]) { + ShaderStore.ShadersStore[name$6O] = shader$6N; +} +/** @internal */ +const depthBoxBlurPixelShader = { name: name$6O, shader: shader$6N }; + +const depthBoxBlur_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + depthBoxBlurPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6N = "shadowMapFragmentSoftTransparentShadow"; +const shader$6M = `#if SM_SOFTTRANSPARENTSHADOW==1 +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alpha) discard; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6N]) { + ShaderStore.IncludesShadersStore[name$6N] = shader$6M; +} +/** @internal */ +const shadowMapFragmentSoftTransparentShadow = { name: name$6N, shader: shader$6M }; + +const shadowMapFragmentSoftTransparentShadow$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowMapFragmentSoftTransparentShadow +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Loads LTC texture data from Babylon.js CDN. + * @returns Promise with data for LTC1 and LTC2 textures for area lights. + */ +async function DecodeLTCTextureDataAsync() { + const ltc1 = new Uint16Array(64 * 64 * 4); + const ltc2 = new Uint16Array(64 * 64 * 4); + const file = await Tools.LoadFileAsync(Tools.GetAssetUrl("https://assets.babylonjs.com/core/areaLights/areaLightsLTC.bin")); + const ltcEncoded = new Uint16Array(file); + const pixelCount = ltcEncoded.length / 8; + for (let pixelIndex = 0; pixelIndex < pixelCount; pixelIndex++) { + ltc1[pixelIndex * 4] = ltcEncoded[pixelIndex * 8]; + ltc1[pixelIndex * 4 + 1] = ltcEncoded[pixelIndex * 8 + 1]; + ltc1[pixelIndex * 4 + 2] = ltcEncoded[pixelIndex * 8 + 2]; + ltc1[pixelIndex * 4 + 3] = ltcEncoded[pixelIndex * 8 + 3]; + ltc2[pixelIndex * 4] = ltcEncoded[pixelIndex * 8 + 4]; + ltc2[pixelIndex * 4 + 1] = ltcEncoded[pixelIndex * 8 + 5]; + ltc2[pixelIndex * 4 + 2] = ltcEncoded[pixelIndex * 8 + 6]; + ltc2[pixelIndex * 4 + 3] = ltcEncoded[pixelIndex * 8 + 7]; + } + return [ltc1, ltc2]; +} + +function CreateSceneLTCTextures(scene) { + const useDelayedTextureLoading = scene.useDelayedTextureLoading; + scene.useDelayedTextureLoading = false; + const previousState = scene._blockEntityCollection; + scene._blockEntityCollection = false; + scene._ltcTextures = { + LTC1: RawTexture.CreateRGBATexture(null, 64, 64, scene.getEngine(), false, false, 2, 2, 0, false, true), + LTC2: RawTexture.CreateRGBATexture(null, 64, 64, scene.getEngine(), false, false, 2, 2, 0, false, true), + }; + scene._blockEntityCollection = previousState; + scene._ltcTextures.LTC1.wrapU = Texture.CLAMP_ADDRESSMODE; + scene._ltcTextures.LTC1.wrapV = Texture.CLAMP_ADDRESSMODE; + scene._ltcTextures.LTC2.wrapU = Texture.CLAMP_ADDRESSMODE; + scene._ltcTextures.LTC2.wrapV = Texture.CLAMP_ADDRESSMODE; + scene.useDelayedTextureLoading = useDelayedTextureLoading; + DecodeLTCTextureDataAsync() + .then((textureData) => { + if (scene._ltcTextures) { + const ltc1 = scene._ltcTextures?.LTC1; + ltc1.update(textureData[0]); + const ltc2 = scene._ltcTextures?.LTC2; + ltc2.update(textureData[1]); + scene.onDisposeObservable.addOnce(() => { + scene._ltcTextures?.LTC1.dispose(); + scene._ltcTextures?.LTC2.dispose(); + }); + } + }) + .catch((error) => { + Logger.Error(`Area Light fail to get LTC textures data. Error: ${error}`); + }); +} +/** + * Abstract Area Light class that servers as parent for all Area Lights implementations. + * The light is emitted from the area in the -Z direction. + */ +class AreaLight extends Light { + /** + * Creates a area light object. + * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + * @param name The friendly name of the light + * @param position The position of the area light. + * @param scene The scene the light belongs to + */ + constructor(name, position, scene) { + super(name, scene); + this.position = position; + if (!this._scene._ltcTextures) { + CreateSceneLTCTextures(this._scene); + } + } + transferTexturesToEffect(effect) { + if (this._scene._ltcTextures) { + effect.setTexture("areaLightsLTC1Sampler", this._scene._ltcTextures.LTC1); + effect.setTexture("areaLightsLTC2Sampler", this._scene._ltcTextures.LTC2); + } + return this; + } + /** + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect + */ + prepareLightSpecificDefines(defines, lightIndex) { + defines["AREALIGHT" + lightIndex] = true; + defines["AREALIGHTUSED"] = true; + } + _isReady() { + if (this._scene._ltcTextures) { + return this._scene._ltcTextures.LTC1.isReady() && this._scene._ltcTextures.LTC2.isReady(); + } + return false; + } +} + +Node$2.AddNodeConstructor("Light_Type_4", (name, scene) => { + return () => new RectAreaLight(name, Vector3.Zero(), 1, 1, scene); +}); +/** + * A rectangular area light defined by an unique point in world space, a width and a height. + * The light is emitted from the rectangular area in the -Z direction. + */ +class RectAreaLight extends AreaLight { + /** + * Rect Area Light width. + */ + get width() { + return this._width.x; + } + /** + * Rect Area Light width. + */ + set width(value) { + this._width.x = value; + } + /** + * Rect Area Light height. + */ + get height() { + return this._height.y; + } + /** + * Rect Area Light height. + */ + set height(value) { + this._height.y = value; + } + /** + * Creates a rectangular area light object. + * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction + * @param name The friendly name of the light + * @param position The position of the area light. + * @param width The width of the area light. + * @param height The height of the area light. + * @param scene The scene the light belongs to + */ + constructor(name, position, width, height, scene) { + super(name, position, scene); + this._width = new Vector3(width, 0, 0); + this._height = new Vector3(0, height, 0); + this._pointTransformedPosition = Vector3.Zero(); + this._pointTransformedWidth = Vector3.Zero(); + this._pointTransformedHeight = Vector3.Zero(); + } + /** + * Returns the string "RectAreaLight" + * @returns the class name + */ + getClassName() { + return "RectAreaLight"; + } + /** + * Returns the integer 4. + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + getTypeID() { + return Light.LIGHTTYPEID_RECT_AREALIGHT; + } + _buildUniformLayout() { + this._uniformBuffer.addUniform("vLightData", 4); + this._uniformBuffer.addUniform("vLightDiffuse", 4); + this._uniformBuffer.addUniform("vLightSpecular", 4); + this._uniformBuffer.addUniform("vLightWidth", 4); + this._uniformBuffer.addUniform("vLightHeight", 4); + this._uniformBuffer.addUniform("shadowsInfo", 3); + this._uniformBuffer.addUniform("depthValues", 2); + this._uniformBuffer.create(); + } + _computeTransformedInformation() { + if (this.parent && this.parent.getWorldMatrix) { + Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._pointTransformedPosition); + Vector3.TransformNormalToRef(this._width, this.parent.getWorldMatrix(), this._pointTransformedWidth); + Vector3.TransformNormalToRef(this._height, this.parent.getWorldMatrix(), this._pointTransformedHeight); + return true; + } + return false; + } + /** + * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string). + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The point light + */ + transferToEffect(effect, lightIndex) { + if (this._computeTransformedInformation()) { + this._uniformBuffer.updateFloat4("vLightData", this._pointTransformedPosition.x, this._pointTransformedPosition.y, this._pointTransformedPosition.z, 0, lightIndex); + this._uniformBuffer.updateFloat4("vLightWidth", this._pointTransformedWidth.x / 2, this._pointTransformedWidth.y / 2, this._pointTransformedWidth.z / 2, 0, lightIndex); + this._uniformBuffer.updateFloat4("vLightHeight", this._pointTransformedHeight.x / 2, this._pointTransformedHeight.y / 2, this._pointTransformedHeight.z / 2, 0, lightIndex); + } + else { + this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex); + this._uniformBuffer.updateFloat4("vLightWidth", this._width.x / 2, this._width.y / 2, this._width.z / 2, 0.0, lightIndex); + this._uniformBuffer.updateFloat4("vLightHeight", this._height.x / 2, this._height.y / 2, this._height.z / 2, 0.0, lightIndex); + } + return this; + } + transferToNodeMaterialEffect(effect, lightDataUniformName) { + if (this._computeTransformedInformation()) { + effect.setFloat3(lightDataUniformName, this._pointTransformedPosition.x, this._pointTransformedPosition.y, this._pointTransformedPosition.z); + } + else { + effect.setFloat3(lightDataUniformName, this.position.x, this.position.y, this.position.z); + } + return this; + } +} +__decorate([ + serialize() +], RectAreaLight.prototype, "width", null); +__decorate([ + serialize() +], RectAreaLight.prototype, "height", null); +// Register Class Name +RegisterClass("BABYLON.RectAreaLight", RectAreaLight); + +function lineToArray(line) { + return line + .split(" ") + .filter((x) => x !== "") + .map((x) => parseFloat(x)); +} +function readArray(dataPointer, count, targetArray) { + while (targetArray.length !== count) { + const line = lineToArray(dataPointer.lines[dataPointer.index++]); + targetArray.push(...line); + } +} +function interpolateCandelaValues(data, phi, theta) { + let phiIndex = 0; + let thetaIndex = 0; + let startTheta = 0; + let endTheta = 0; + let startPhi = 0; + let endPhi = 0; + // Check if the angle is outside the range + for (let index = 0; index < data.numberOfHorizontalAngles - 1; index++) { + if (theta < data.horizontalAngles[index + 1] || index === data.numberOfHorizontalAngles - 2) { + thetaIndex = index; + startTheta = data.horizontalAngles[index]; + endTheta = data.horizontalAngles[index + 1]; + break; + } + } + for (let index = 0; index < data.numberOfVerticalAngles - 1; index++) { + if (phi < data.verticalAngles[index + 1] || index === data.numberOfVerticalAngles - 2) { + phiIndex = index; + startPhi = data.verticalAngles[index]; + endPhi = data.verticalAngles[index + 1]; + break; + } + } + const deltaTheta = endTheta - startTheta; + const deltaPhi = endPhi - startPhi; + if (deltaPhi === 0) { + return 0; + } + // Interpolate + const t1 = deltaTheta === 0 ? 0 : (theta - startTheta) / deltaTheta; + const t2 = (phi - startPhi) / deltaPhi; + const nextThetaIndex = deltaTheta === 0 ? thetaIndex : thetaIndex + 1; + const v1 = Lerp(data.candelaValues[thetaIndex][phiIndex], data.candelaValues[nextThetaIndex][phiIndex], t1); + const v2 = Lerp(data.candelaValues[thetaIndex][phiIndex + 1], data.candelaValues[nextThetaIndex][phiIndex + 1], t1); + const v = Lerp(v1, v2, t2); + return v; +} +/** + * Generates IES data buffer from a string representing the IES data. + * @param uint8Array defines the IES data + * @returns the IES data buffer + * @see https://ieslibrary.com/browse + * @see https://playground.babylonjs.com/#UQGPDT#1 + */ +function LoadIESData(uint8Array) { + const decoder = new TextDecoder("utf-8"); + const source = decoder.decode(uint8Array); + // Read data + const dataPointer = { + lines: source.split("\n"), + index: 0, + }; + const data = { version: dataPointer.lines[0], candelaValues: [], horizontalAngles: [], verticalAngles: [], numberOfHorizontalAngles: 0, numberOfVerticalAngles: 0 }; + // Skip metadata + dataPointer.index = 1; + while (dataPointer.lines.length > 0 && !dataPointer.lines[dataPointer.index].includes("TILT=")) { + dataPointer.index++; + } + // Process tilt data? + if (dataPointer.lines[dataPointer.index].includes("INCLUDE")) ; + dataPointer.index++; + // Header + const header = lineToArray(dataPointer.lines[dataPointer.index++]); + data.numberOfLights = header[0]; + data.lumensPerLamp = header[1]; + data.candelaMultiplier = header[2]; + data.numberOfVerticalAngles = header[3]; + data.numberOfHorizontalAngles = header[4]; + data.photometricType = header[5]; // We ignore cylindrical type for now. Will add support later if needed + data.unitsType = header[6]; + data.width = header[7]; + data.length = header[8]; + data.height = header[9]; + // Additional data + const additionalData = lineToArray(dataPointer.lines[dataPointer.index++]); + data.ballastFactor = additionalData[0]; + data.fileGenerationType = additionalData[1]; + data.inputWatts = additionalData[2]; + // Prepare arrays + for (let index = 0; index < data.numberOfHorizontalAngles; index++) { + data.candelaValues[index] = []; + } + // Vertical angles + readArray(dataPointer, data.numberOfVerticalAngles, data.verticalAngles); + // Horizontal angles + readArray(dataPointer, data.numberOfHorizontalAngles, data.horizontalAngles); + // Candela values + for (let index = 0; index < data.numberOfHorizontalAngles; index++) { + readArray(dataPointer, data.numberOfVerticalAngles, data.candelaValues[index]); + } + // Evaluate candela values + let maxCandela = -1; + for (let index = 0; index < data.numberOfHorizontalAngles; index++) { + for (let subIndex = 0; subIndex < data.numberOfVerticalAngles; subIndex++) { + data.candelaValues[index][subIndex] *= data.candelaValues[index][subIndex] * data.candelaMultiplier * data.ballastFactor * data.fileGenerationType; + maxCandela = Math.max(maxCandela, data.candelaValues[index][subIndex]); + } + } + // Normalize candela values + if (maxCandela > 0) { + for (let index = 0; index < data.numberOfHorizontalAngles; index++) { + for (let subIndex = 0; subIndex < data.numberOfVerticalAngles; subIndex++) { + data.candelaValues[index][subIndex] /= maxCandela; + } + } + } + // Create the cylindrical texture + const height = 180; + const width = height * 2; + const size = width * height; + const arrayBuffer = new Float32Array(width * height); + // Fill the texture + const startTheta = data.horizontalAngles[0]; + const endTheta = data.horizontalAngles[data.numberOfHorizontalAngles - 1]; + for (let index = 0; index < size; index++) { + let theta = index % width; + const phi = Math.floor(index / width); + // Symmetry + if (endTheta - startTheta !== 0 && (theta < startTheta || theta >= endTheta)) { + theta %= endTheta * 2; + if (theta > endTheta) { + theta = endTheta * 2 - theta; + } + } + arrayBuffer[phi + theta * height] = interpolateCandelaValues(data, phi, theta); + } + // So far we only need the first half of the first row of the texture as we only support IES for spot light. We can add support for other types later. + return { + width: width / 2, + height: 1, + data: arrayBuffer, + }; +} + +/** + * Class used for the default loading screen + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen + */ +class DefaultLoadingScreen { + /** + * Creates a new default loading screen + * @param _renderingCanvas defines the canvas used to render the scene + * @param _loadingText defines the default text to display + * @param _loadingDivBackgroundColor defines the default background color + */ + constructor(_renderingCanvas, _loadingText = "", _loadingDivBackgroundColor = "black") { + this._renderingCanvas = _renderingCanvas; + this._loadingText = _loadingText; + this._loadingDivBackgroundColor = _loadingDivBackgroundColor; + /** + * Maps a loading `HTMLDivElement` to a tuple containing the associated `HTMLCanvasElement` + * and its `DOMRect` (or `null` if not yet available). + */ + this._loadingDivToRenderingCanvasMap = new Map(); + // Resize + this._resizeLoadingUI = () => { + if (!this._isLoading) { + return; + } + this._loadingDivToRenderingCanvasMap.forEach(([canvas, previousCanvasRect], loadingDiv) => { + const currentCanvasRect = canvas.getBoundingClientRect(); + if (this._isCanvasLayoutChanged(previousCanvasRect, currentCanvasRect)) { + const canvasPositioning = window.getComputedStyle(canvas).position; + loadingDiv.style.position = canvasPositioning === "fixed" ? "fixed" : "absolute"; + loadingDiv.style.left = currentCanvasRect.left + window.scrollX + "px"; + loadingDiv.style.top = currentCanvasRect.top + window.scrollY + "px"; + loadingDiv.style.width = currentCanvasRect.width + "px"; + loadingDiv.style.height = currentCanvasRect.height + "px"; + this._loadingDivToRenderingCanvasMap.set(loadingDiv, [canvas, currentCanvasRect]); + } + }); + }; + } + /** + * Function called to display the loading screen + */ + displayLoadingUI() { + if (this._isLoading) { + // Do not add a loading screen if it is already loading + return; + } + this._isLoading = true; + // get current engine by rendering canvas + this._engine = EngineStore.Instances.find((engine) => engine.getRenderingCanvas() === this._renderingCanvas); + const loadingDiv = document.createElement("div"); + loadingDiv.id = "babylonjsLoadingDiv"; + loadingDiv.style.opacity = "0"; + loadingDiv.style.transition = "opacity 1.5s ease"; + loadingDiv.style.pointerEvents = "none"; + loadingDiv.style.display = "grid"; + loadingDiv.style.gridTemplateRows = "100%"; + loadingDiv.style.gridTemplateColumns = "100%"; + loadingDiv.style.justifyItems = "center"; + loadingDiv.style.alignItems = "center"; + // Loading text + this._loadingTextDiv = document.createElement("div"); + this._loadingTextDiv.style.position = "absolute"; + this._loadingTextDiv.style.left = "0"; + this._loadingTextDiv.style.top = "50%"; + this._loadingTextDiv.style.marginTop = "80px"; + this._loadingTextDiv.style.width = "100%"; + this._loadingTextDiv.style.height = "20px"; + this._loadingTextDiv.style.fontFamily = "Arial"; + this._loadingTextDiv.style.fontSize = "14px"; + this._loadingTextDiv.style.color = "white"; + this._loadingTextDiv.style.textAlign = "center"; + this._loadingTextDiv.style.zIndex = "1"; + this._loadingTextDiv.innerHTML = "Loading"; + loadingDiv.appendChild(this._loadingTextDiv); + //set the predefined text + this._loadingTextDiv.innerHTML = this._loadingText; + // Generating keyframes + this._style = document.createElement("style"); + this._style.type = "text/css"; + const keyFrames = `@-webkit-keyframes spin1 {\ + 0% { -webkit-transform: rotate(0deg);} + 100% { -webkit-transform: rotate(360deg);} + }\ + @keyframes spin1 {\ + 0% { transform: rotate(0deg);} + 100% { transform: rotate(360deg);} + }`; + this._style.innerHTML = keyFrames; + document.getElementsByTagName("head")[0].appendChild(this._style); + const svgSupport = !!window.SVGSVGElement; + // Loading img + const imgBack = new Image(); + if (!DefaultLoadingScreen.DefaultLogoUrl) { + imgBack.src = !svgSupport + ? "https://cdn.babylonjs.com/Assets/babylonLogo.png" + : `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+`; + } + else { + imgBack.src = DefaultLoadingScreen.DefaultLogoUrl; + } + imgBack.style.width = "150px"; + imgBack.style.gridColumn = "1"; + imgBack.style.gridRow = "1"; + imgBack.style.top = "50%"; + imgBack.style.left = "50%"; + imgBack.style.transform = "translate(-50%, -50%)"; + imgBack.style.position = "absolute"; + const imageSpinnerContainer = document.createElement("div"); + imageSpinnerContainer.style.width = "300px"; + imageSpinnerContainer.style.gridColumn = "1"; + imageSpinnerContainer.style.gridRow = "1"; + imageSpinnerContainer.style.top = "50%"; + imageSpinnerContainer.style.left = "50%"; + imageSpinnerContainer.style.transform = "translate(-50%, -50%)"; + imageSpinnerContainer.style.position = "absolute"; + // Loading spinner + const imgSpinner = new Image(); + if (!DefaultLoadingScreen.DefaultSpinnerUrl) { + imgSpinner.src = !svgSupport + ? "https://cdn.babylonjs.com/Assets/loadingIcon.png" + : `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==`; + } + else { + imgSpinner.src = DefaultLoadingScreen.DefaultSpinnerUrl; + } + imgSpinner.style.animation = "spin1 0.75s infinite linear"; + imgSpinner.style.transformOrigin = "50% 50%"; + if (!svgSupport) { + const logoSize = { w: 16, h: 18.5 }; + const loadingSize = { w: 30, h: 30 }; + // set styling correctly + imgBack.style.width = `${logoSize.w}vh`; + imgBack.style.height = `${logoSize.h}vh`; + imgBack.style.left = `calc(50% - ${logoSize.w / 2}vh)`; + imgBack.style.top = `calc(50% - ${logoSize.h / 2}vh)`; + imgSpinner.style.width = `${loadingSize.w}vh`; + imgSpinner.style.height = `${loadingSize.h}vh`; + imgSpinner.style.left = `calc(50% - ${loadingSize.w / 2}vh)`; + imgSpinner.style.top = `calc(50% - ${loadingSize.h / 2}vh)`; + } + imageSpinnerContainer.appendChild(imgSpinner); + loadingDiv.appendChild(imgBack); + loadingDiv.appendChild(imageSpinnerContainer); + loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor; + loadingDiv.style.opacity = "1"; + const canvases = []; + const views = this._engine.views; + if (views?.length) { + for (const view of views) { + if (view.enabled) { + canvases.push(view.target); + } + } + } + else { + canvases.push(this._renderingCanvas); + } + canvases.forEach((canvas, index) => { + const clonedLoadingDiv = loadingDiv.cloneNode(true); + clonedLoadingDiv.id += `-${index}`; + this._loadingDivToRenderingCanvasMap.set(clonedLoadingDiv, [canvas, null]); + }); + this._resizeLoadingUI(); + this._resizeObserver = this._engine.onResizeObservable.add(() => { + this._resizeLoadingUI(); + }); + this._loadingDivToRenderingCanvasMap.forEach((_, loadingDiv) => { + document.body.appendChild(loadingDiv); + }); + } + /** + * Function called to hide the loading screen + */ + hideLoadingUI() { + if (!this._isLoading) { + return; + } + let completedTransitions = 0; + const onTransitionEnd = (event) => { + const loadingDiv = event.target; + // ensure that ending transition event is generated by one of the current loadingDivs + const isTransitionEndOnLoadingDiv = this._loadingDivToRenderingCanvasMap.has(loadingDiv); + if (isTransitionEndOnLoadingDiv) { + completedTransitions++; + loadingDiv.remove(); + const allTransitionsCompleted = completedTransitions === this._loadingDivToRenderingCanvasMap.size; + if (allTransitionsCompleted) { + if (this._loadingTextDiv) { + this._loadingTextDiv.remove(); + this._loadingTextDiv = null; + } + if (this._style) { + this._style.remove(); + this._style = null; + } + window.removeEventListener("transitionend", onTransitionEnd); + this._engine.onResizeObservable.remove(this._resizeObserver); + this._loadingDivToRenderingCanvasMap.clear(); + this._engine = null; + this._isLoading = false; + } + } + }; + this._loadingDivToRenderingCanvasMap.forEach((_, loadingDiv) => { + loadingDiv.style.opacity = "0"; + }); + window.addEventListener("transitionend", onTransitionEnd); + } + /** + * Gets or sets the text to display while loading + */ + set loadingUIText(text) { + this._loadingText = text; + if (this._loadingTextDiv) { + this._loadingDivToRenderingCanvasMap.forEach((_, loadingDiv) => { + // set loadingTextDiv of current loadingDiv + loadingDiv.children[0].innerHTML = this._loadingText; + }); + } + } + get loadingUIText() { + return this._loadingText; + } + /** + * Gets or sets the color to use for the background + */ + get loadingUIBackgroundColor() { + return this._loadingDivBackgroundColor; + } + set loadingUIBackgroundColor(color) { + this._loadingDivBackgroundColor = color; + if (!this._isLoading) { + return; + } + this._loadingDivToRenderingCanvasMap.forEach((_, loadingDiv) => { + loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor; + }); + } + /** + * Checks if the layout of the canvas has changed by comparing the current layout + * rectangle with the previous one. + * + * This function compares of the two `DOMRect` objects to determine if any of the layout dimensions have changed. + * If the layout has changed or if there is no previous layout (i.e., `previousCanvasRect` is `null`), + * it returns `true`. Otherwise, it returns `false`. + * + * @param previousCanvasRect defines the previously recorded `DOMRect` of the canvas, or `null` if no previous state exists. + * @param currentCanvasRect defines the current `DOMRect` of the canvas to compare against the previous layout. + * @returns `true` if the layout has changed, otherwise `false`. + */ + _isCanvasLayoutChanged(previousCanvasRect, currentCanvasRect) { + return (!previousCanvasRect || + previousCanvasRect.left !== currentCanvasRect.left || + previousCanvasRect.top !== currentCanvasRect.top || + previousCanvasRect.right !== currentCanvasRect.right || + previousCanvasRect.bottom !== currentCanvasRect.bottom || + previousCanvasRect.width !== currentCanvasRect.width || + previousCanvasRect.height !== currentCanvasRect.height || + previousCanvasRect.x !== currentCanvasRect.x || + previousCanvasRect.y !== currentCanvasRect.y); + } +} +/** Gets or sets the logo url to use for the default loading screen */ +DefaultLoadingScreen.DefaultLogoUrl = ""; +/** Gets or sets the spinner url to use for the default loading screen */ +DefaultLoadingScreen.DefaultSpinnerUrl = ""; +AbstractEngine.DefaultLoadingScreenFactory = (canvas) => { + return new DefaultLoadingScreen(canvas); +}; + +/** + * Helper class useful to convert panorama picture to their cubemap representation in 6 faces. + */ +class PanoramaToCubeMapTools { + /** + * Converts a panorama stored in RGB right to left up to down format into a cubemap (6 faces). + * + * @param float32Array The source data. + * @param inputWidth The width of the input panorama. + * @param inputHeight The height of the input panorama. + * @param size The willing size of the generated cubemap (each faces will be size * size pixels) + * @param supersample enable supersampling the cubemap + * @returns The cubemap data + */ + static ConvertPanoramaToCubemap(float32Array, inputWidth, inputHeight, size, supersample = false) { + if (!float32Array) { + // eslint-disable-next-line no-throw-literal + throw "ConvertPanoramaToCubemap: input cannot be null"; + } + if (float32Array.length != inputWidth * inputHeight * 3) { + // eslint-disable-next-line no-throw-literal + throw "ConvertPanoramaToCubemap: input size is wrong"; + } + const textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight, supersample); + const textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight, supersample); + const textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight, supersample); + const textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight, supersample); + const textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight, supersample); + const textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight, supersample); + return { + front: textureFront, + back: textureBack, + left: textureLeft, + right: textureRight, + up: textureUp, + down: textureDown, + size: size, + type: 1, + format: 4, + gammaSpace: false, + }; + } + static CreateCubemapTexture(texSize, faceData, float32Array, inputWidth, inputHeight, supersample = false) { + const buffer = new ArrayBuffer(texSize * texSize * 4 * 3); + const textureArray = new Float32Array(buffer); + // If supersampling, determine number of samples needed when source texture width is divided for 4 cube faces + const samples = supersample ? Math.max(1, Math.round(inputWidth / 4 / texSize)) : 1; + const sampleFactor = 1 / samples; + const sampleFactorSqr = sampleFactor * sampleFactor; + const rotDX1 = faceData[1].subtract(faceData[0]).scale(sampleFactor / texSize); + const rotDX2 = faceData[3].subtract(faceData[2]).scale(sampleFactor / texSize); + const dy = 1 / texSize; + let fy = 0; + for (let y = 0; y < texSize; y++) { + for (let sy = 0; sy < samples; sy++) { + let xv1 = faceData[0]; + let xv2 = faceData[2]; + for (let x = 0; x < texSize; x++) { + for (let sx = 0; sx < samples; sx++) { + const v = xv2.subtract(xv1).scale(fy).add(xv1); + v.normalize(); + const color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight); + // 3 channels per pixels + textureArray[y * texSize * 3 + x * 3 + 0] += color.r * sampleFactorSqr; + textureArray[y * texSize * 3 + x * 3 + 1] += color.g * sampleFactorSqr; + textureArray[y * texSize * 3 + x * 3 + 2] += color.b * sampleFactorSqr; + xv1 = xv1.add(rotDX1); + xv2 = xv2.add(rotDX2); + } + } + fy += dy * sampleFactor; + } + } + return textureArray; + } + static CalcProjectionSpherical(vDir, float32Array, inputWidth, inputHeight) { + let theta = Math.atan2(vDir.z, vDir.x); + const phi = Math.acos(vDir.y); + while (theta < -Math.PI) { + theta += 2 * Math.PI; + } + while (theta > Math.PI) { + theta -= 2 * Math.PI; + } + let dx = theta / Math.PI; + const dy = phi / Math.PI; + // recenter. + dx = dx * 0.5 + 0.5; + let px = Math.round(dx * inputWidth); + if (px < 0) { + px = 0; + } + else if (px >= inputWidth) { + px = inputWidth - 1; + } + let py = Math.round(dy * inputHeight); + if (py < 0) { + py = 0; + } + else if (py >= inputHeight) { + py = inputHeight - 1; + } + const inputY = inputHeight - py - 1; + const r = float32Array[inputY * inputWidth * 3 + px * 3 + 0]; + const g = float32Array[inputY * inputWidth * 3 + px * 3 + 1]; + const b = float32Array[inputY * inputWidth * 3 + px * 3 + 2]; + return { + r: r, + g: g, + b: b, + }; + } +} +PanoramaToCubeMapTools.FACE_LEFT = [new Vector3(-1, -1, -1), new Vector3(1.0, -1, -1), new Vector3(-1, 1.0, -1), new Vector3(1.0, 1.0, -1)]; +PanoramaToCubeMapTools.FACE_RIGHT = [new Vector3(1.0, -1, 1.0), new Vector3(-1, -1, 1.0), new Vector3(1.0, 1.0, 1.0), new Vector3(-1, 1.0, 1.0)]; +PanoramaToCubeMapTools.FACE_FRONT = [new Vector3(1.0, -1, -1), new Vector3(1.0, -1, 1.0), new Vector3(1.0, 1.0, -1), new Vector3(1.0, 1.0, 1.0)]; +PanoramaToCubeMapTools.FACE_BACK = [new Vector3(-1, -1, 1.0), new Vector3(-1, -1, -1), new Vector3(-1, 1.0, 1.0), new Vector3(-1, 1.0, -1)]; +PanoramaToCubeMapTools.FACE_DOWN = [new Vector3(1.0, 1.0, -1), new Vector3(1.0, 1.0, 1.0), new Vector3(-1, 1.0, -1), new Vector3(-1, 1.0, 1.0)]; +PanoramaToCubeMapTools.FACE_UP = [new Vector3(-1, -1, -1), new Vector3(-1, -1, 1.0), new Vector3(1.0, -1, -1), new Vector3(1.0, -1, 1.0)]; + +/* This groups tools to convert HDR texture to native colors array. */ +function ldexp(mantissa, exponent) { + if (exponent > 1023) { + return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023); + } + if (exponent < -1074) { + return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074); + } + return mantissa * Math.pow(2, exponent); +} +function rgbe2float(float32array, red, green, blue, exponent, index) { + if (exponent > 0) { + /*nonzero pixel*/ + exponent = ldexp(1.0, exponent - (128 + 8)); + float32array[index + 0] = red * exponent; + float32array[index + 1] = green * exponent; + float32array[index + 2] = blue * exponent; + } + else { + float32array[index + 0] = 0; + float32array[index + 1] = 0; + float32array[index + 2] = 0; + } +} +function readStringLine(uint8array, startIndex) { + let line = ""; + let character = ""; + for (let i = startIndex; i < uint8array.length - startIndex; i++) { + character = String.fromCharCode(uint8array[i]); + if (character == "\n") { + break; + } + line += character; + } + return line; +} +/** + * Reads header information from an RGBE texture stored in a native array. + * More information on this format are available here: + * https://en.wikipedia.org/wiki/RGBE_image_format + * + * @param uint8array The binary file stored in native array. + * @returns The header information. + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function RGBE_ReadHeader(uint8array) { + let height = 0; + let width = 0; + let line = readStringLine(uint8array, 0); + if (line[0] != "#" || line[1] != "?") { + // eslint-disable-next-line no-throw-literal + throw "Bad HDR Format."; + } + let endOfHeader = false; + let findFormat = false; + let lineIndex = 0; + do { + lineIndex += line.length + 1; + line = readStringLine(uint8array, lineIndex); + if (line == "FORMAT=32-bit_rle_rgbe") { + findFormat = true; + } + else if (line.length == 0) { + endOfHeader = true; + } + } while (!endOfHeader); + if (!findFormat) { + // eslint-disable-next-line no-throw-literal + throw "HDR Bad header format, unsupported FORMAT"; + } + lineIndex += line.length + 1; + line = readStringLine(uint8array, lineIndex); + const sizeRegexp = /^-Y (.*) \+X (.*)$/g; + const match = sizeRegexp.exec(line); + // TODO. Support +Y and -X if needed. + if (!match || match.length < 3) { + // eslint-disable-next-line no-throw-literal + throw "HDR Bad header format, no size"; + } + width = parseInt(match[2]); + height = parseInt(match[1]); + if (width < 8 || width > 0x7fff) { + // eslint-disable-next-line no-throw-literal + throw "HDR Bad header format, unsupported size"; + } + lineIndex += line.length + 1; + return { + height: height, + width: width, + dataPosition: lineIndex, + }; +} +/** + * Returns the cubemap information (each faces texture data) extracted from an RGBE texture. + * This RGBE texture needs to store the information as a panorama. + * + * More information on this format are available here: + * https://en.wikipedia.org/wiki/RGBE_image_format + * + * @param buffer The binary file stored in an array buffer. + * @param size The expected size of the extracted cubemap. + * @param supersample enable supersampling the cubemap (default: false) + * @returns The Cube Map information. + */ +function GetCubeMapTextureData(buffer, size, supersample = false) { + const uint8array = new Uint8Array(buffer); + const hdrInfo = RGBE_ReadHeader(uint8array); + const data = RGBE_ReadPixels(uint8array, hdrInfo); + const cubeMapData = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size, supersample); + return cubeMapData; +} +/** + * Returns the pixels data extracted from an RGBE texture. + * This pixels will be stored left to right up to down in the R G B order in one array. + * + * More information on this format are available here: + * https://en.wikipedia.org/wiki/RGBE_image_format + * + * @param uint8array The binary file stored in an array buffer. + * @param hdrInfo The header information of the file. + * @returns The pixels data in RGB right to left up to down order. + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function RGBE_ReadPixels(uint8array, hdrInfo) { + return readRGBEPixelsRLE(uint8array, hdrInfo); +} +function readRGBEPixelsRLE(uint8array, hdrInfo) { + let num_scanlines = hdrInfo.height; + const scanline_width = hdrInfo.width; + let a, b, c, d, count; + let dataIndex = hdrInfo.dataPosition; + let index = 0, endIndex = 0, i = 0; + const scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E + const scanLineArray = new Uint8Array(scanLineArrayBuffer); + // 3 channels of 4 bytes per pixel in float. + const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3); + const resultArray = new Float32Array(resultBuffer); + // read in each successive scanline + while (num_scanlines > 0) { + a = uint8array[dataIndex++]; + b = uint8array[dataIndex++]; + c = uint8array[dataIndex++]; + d = uint8array[dataIndex++]; + if (a != 2 || b != 2 || c & 0x80 || hdrInfo.width < 8 || hdrInfo.width > 32767) { + return readRGBEPixelsNotRLE(uint8array, hdrInfo); + } + if (((c << 8) | d) != scanline_width) { + // eslint-disable-next-line no-throw-literal + throw "HDR Bad header format, wrong scan line width"; + } + index = 0; + // read each of the four channels for the scanline into the buffer + for (i = 0; i < 4; i++) { + endIndex = (i + 1) * scanline_width; + while (index < endIndex) { + a = uint8array[dataIndex++]; + b = uint8array[dataIndex++]; + if (a > 128) { + // a run of the same value + count = a - 128; + if (count == 0 || count > endIndex - index) { + // eslint-disable-next-line no-throw-literal + throw "HDR Bad Format, bad scanline data (run)"; + } + while (count-- > 0) { + scanLineArray[index++] = b; + } + } + else { + // a non-run + count = a; + if (count == 0 || count > endIndex - index) { + // eslint-disable-next-line no-throw-literal + throw "HDR Bad Format, bad scanline data (non-run)"; + } + scanLineArray[index++] = b; + if (--count > 0) { + for (let j = 0; j < count; j++) { + scanLineArray[index++] = uint8array[dataIndex++]; + } + } + } + } + } + // now convert data from buffer into floats + for (i = 0; i < scanline_width; i++) { + a = scanLineArray[i]; + b = scanLineArray[i + scanline_width]; + c = scanLineArray[i + 2 * scanline_width]; + d = scanLineArray[i + 3 * scanline_width]; + rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3); + } + num_scanlines--; + } + return resultArray; +} +function readRGBEPixelsNotRLE(uint8array, hdrInfo) { + // this file is not run length encoded + // read values sequentially + let num_scanlines = hdrInfo.height; + const scanline_width = hdrInfo.width; + let a, b, c, d, i; + let dataIndex = hdrInfo.dataPosition; + // 3 channels of 4 bytes per pixel in float. + const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3); + const resultArray = new Float32Array(resultBuffer); + // read in each successive scanline + while (num_scanlines > 0) { + for (i = 0; i < hdrInfo.width; i++) { + a = uint8array[dataIndex++]; + b = uint8array[dataIndex++]; + c = uint8array[dataIndex++]; + d = uint8array[dataIndex++]; + rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3); + } + num_scanlines--; + } + return resultArray; +} + +/** + * Filters HDR maps to get correct renderings of PBR reflections + */ +class HDRFiltering { + /** + * Instantiates HDR filter for reflection maps + * + * @param engine Thin engine + * @param options Options + */ + constructor(engine, options = {}) { + this._lodGenerationOffset = 0; + this._lodGenerationScale = 0.8; + /** + * Quality switch for prefiltering. Should be set to `4096` unless + * you care about baking speed. + */ + this.quality = 4096; + /** + * Scales pixel intensity for the input HDR map. + */ + this.hdrScale = 1; + // pass + this._engine = engine; + this.hdrScale = options.hdrScale || this.hdrScale; + this.quality = options.quality || this.quality; + } + _createRenderTarget(size) { + let textureType = 0; + if (this._engine.getCaps().textureHalfFloatRender) { + textureType = 2; + } + else if (this._engine.getCaps().textureFloatRender) { + textureType = 1; + } + const rtWrapper = this._engine.createRenderTargetCubeTexture(size, { + format: 5, + type: textureType, + createMipMaps: true, + generateMipMaps: false, + generateDepthBuffer: false, + generateStencilBuffer: false, + samplingMode: 1, + label: "HDR_Radiance_Filtering_Target", + }); + this._engine.updateTextureWrappingMode(rtWrapper.texture, 0, 0, 0); + this._engine.updateTextureSamplingMode(3, rtWrapper.texture, true); + return rtWrapper; + } + _prefilterInternal(texture) { + const width = texture.getSize().width; + const mipmapsCount = ILog2(width) + 1; + const effect = this._effectWrapper.effect; + const outputTexture = this._createRenderTarget(width); + this._effectRenderer.saveStates(); + this._effectRenderer.setViewport(); + const intTexture = texture.getInternalTexture(); + if (intTexture) { + // Just in case generate fresh clean mips. + this._engine.updateTextureSamplingMode(3, intTexture, true); + } + this._effectRenderer.applyEffectWrapper(this._effectWrapper); + const directions = [ + [new Vector3(0, 0, -1), new Vector3(0, -1, 0), new Vector3(1, 0, 0)], // PositiveX + [new Vector3(0, 0, 1), new Vector3(0, -1, 0), new Vector3(-1, 0, 0)], // NegativeX + [new Vector3(1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0)], // PositiveY + [new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)], // NegativeY + [new Vector3(1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, 1)], // PositiveZ + [new Vector3(-1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, -1)], // NegativeZ + ]; + effect.setFloat("hdrScale", this.hdrScale); + effect.setFloat2("vFilteringInfo", texture.getSize().width, mipmapsCount); + effect.setTexture("inputTexture", texture); + for (let face = 0; face < 6; face++) { + effect.setVector3("up", directions[face][0]); + effect.setVector3("right", directions[face][1]); + effect.setVector3("front", directions[face][2]); + for (let lod = 0; lod < mipmapsCount; lod++) { + this._engine.bindFramebuffer(outputTexture, face, undefined, undefined, true, lod); + this._effectRenderer.applyEffectWrapper(this._effectWrapper); + let alpha = Math.pow(2, (lod - this._lodGenerationOffset) / this._lodGenerationScale) / width; + if (lod === 0) { + alpha = 0; + } + effect.setFloat("alphaG", alpha); + this._effectRenderer.draw(); + } + } + // Cleanup + this._effectRenderer.restoreStates(); + this._engine.restoreDefaultFramebuffer(); + this._engine._releaseTexture(texture._texture); + // Internal Swap + const type = outputTexture.texture.type; + const format = outputTexture.texture.format; + outputTexture._swapAndDie(texture._texture); + texture._texture.type = type; + texture._texture.format = format; + // New settings + texture.gammaSpace = false; + texture.lodGenerationOffset = this._lodGenerationOffset; + texture.lodGenerationScale = this._lodGenerationScale; + texture._prefiltered = true; + return texture; + } + _createEffect(texture, onCompiled) { + const defines = []; + if (texture.gammaSpace) { + defines.push("#define GAMMA_INPUT"); + } + defines.push("#define NUM_SAMPLES " + this.quality + "u"); // unsigned int + const isWebGPU = this._engine.isWebGPU; + const effectWrapper = new EffectWrapper({ + engine: this._engine, + name: "hdrFiltering", + vertexShader: "hdrFiltering", + fragmentShader: "hdrFiltering", + samplerNames: ["inputTexture"], + uniformNames: ["vSampleDirections", "vWeights", "up", "right", "front", "vFilteringInfo", "hdrScale", "alphaG"], + useShaderStore: true, + defines, + onCompiled: onCompiled, + shaderLanguage: isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, + extraInitializationsAsync: async () => { + if (isWebGPU) { + await Promise.all([Promise.resolve().then(() => hdrFiltering_vertex), Promise.resolve().then(() => hdrFiltering_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => hdrFiltering_vertex$1), Promise.resolve().then(() => hdrFiltering_fragment$1)]); + } + }, + }); + return effectWrapper; + } + /** + * Get a value indicating if the filter is ready to be used + * @param texture Texture to filter + * @returns true if the filter is ready + */ + isReady(texture) { + return texture.isReady() && this._effectWrapper.effect.isReady(); + } + /** + * Prefilters a cube texture to have mipmap levels representing roughness values. + * Prefiltering will be invoked at the end of next rendering pass. + * This has to be done once the map is loaded, and has not been prefiltered by a third party software. + * See http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf for more information + * @param texture Texture to filter + * @returns Promise called when prefiltering is done + */ + async prefilter(texture) { + if (!this._engine._features.allowTexturePrefiltering) { + throw new Error("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."); + } + this._effectRenderer = new EffectRenderer(this._engine); + this._effectWrapper = this._createEffect(texture); + await this._effectWrapper.effect.whenCompiledAsync(); + this._prefilterInternal(texture); + this._effectRenderer.dispose(); + this._effectWrapper.dispose(); + } +} + +/** + * Build cdf maps to be used for IBL importance sampling. + */ +class IblCdfGenerator { + /** + * Gets the IBL source texture being used by the CDF renderer + */ + get iblSource() { + return this._iblSource; + } + /** + * Sets the IBL source texture to be used by the CDF renderer. + * This will trigger recreation of the CDF assets. + */ + set iblSource(source) { + if (this._iblSource === source) { + return; + } + this._disposeTextures(); + this._iblSource = source; + if (!source) { + return; + } + if (source.isCube) { + if (source.isReadyOrNotBlocking()) { + this._recreateAssetsFromNewIbl(); + } + else { + source.onLoadObservable.addOnce(this._recreateAssetsFromNewIbl.bind(this, source)); + } + } + else { + if (source.isReadyOrNotBlocking()) { + this._recreateAssetsFromNewIbl(); + } + else { + source.onLoadObservable.addOnce(this._recreateAssetsFromNewIbl.bind(this, source)); + } + } + } + _recreateAssetsFromNewIbl() { + if (this._debugPass) { + this._debugPass.dispose(); + } + this._createTextures(); + if (this._debugPass) { + // Recreate the debug pass because of the new textures + this._createDebugPass(); + } + } + /** + * Return the cumulative distribution function (CDF) texture + * @returns Return the cumulative distribution function (CDF) texture + */ + getIcdfTexture() { + return this._icdfPT ? this._icdfPT : this._dummyTexture; + } + /** + * Sets params that control the position and scaling of the debug display on the screen. + * @param x Screen X offset of the debug display (0-1) + * @param y Screen Y offset of the debug display (0-1) + * @param widthScale X scale of the debug display (0-1) + * @param heightScale Y scale of the debug display (0-1) + */ + setDebugDisplayParams(x, y, widthScale, heightScale) { + this._debugSizeParams.set(x, y, widthScale, heightScale); + } + /** + * The name of the debug pass post process + */ + get debugPassName() { + return this._debugPassName; + } + /** + * Gets the debug pass post process + * @returns The post process + */ + getDebugPassPP() { + if (!this._debugPass) { + this._createDebugPass(); + } + return this._debugPass; + } + /** + * Instanciates the CDF renderer + * @param sceneOrEngine Scene to attach to + * @returns The CDF renderer + */ + constructor(sceneOrEngine) { + /** Enable the debug view for this pass */ + this.debugEnabled = false; + this._debugSizeParams = new Vector4(0.0, 0.0, 1.0, 1.0); + this._debugPassName = "CDF Debug"; + /** + * Observable that triggers when the CDF renderer is ready + */ + this.onGeneratedObservable = new Observable(); + if (sceneOrEngine) { + if (IblCdfGenerator._IsScene(sceneOrEngine)) { + this._scene = sceneOrEngine; + } + else { + this._engine = sceneOrEngine; + } + } + else { + this._scene = EngineStore.LastCreatedScene; + } + if (this._scene) { + this._engine = this._scene.getEngine(); + } + const blackPixels = new Uint16Array([0, 0, 0, 255]); + this._dummyTexture = new RawTexture(blackPixels, 1, 1, Engine.TEXTUREFORMAT_RGBA, sceneOrEngine, false, false, undefined, 2); + if (this._scene) { + IblCdfGenerator._SceneComponentInitialization(this._scene); + } + } + _createTextures() { + const size = this._iblSource ? { width: this._iblSource.getSize().width, height: this._iblSource.getSize().height } : { width: 1, height: 1 }; + if (!this._iblSource) { + this._iblSource = RawTexture.CreateRTexture(new Uint8Array([255]), 1, 1, this._engine, false, false, 1, 0); + this._iblSource.name = "Placeholder IBL Source"; + } + if (this._iblSource.isCube) { + size.width *= 4; + size.height *= 2; + // Force the resolution to be a power of 2 because we rely on the + // auto-mipmap generation for the scaled luminance texture to produce + // a 1x1 mip that represents the true average pixel intensity of the IBL. + size.width = 1 << Math.floor(Math.log2(size.width)); + size.height = 1 << Math.floor(Math.log2(size.height)); + } + const isWebGPU = this._engine.isWebGPU; + // Create CDF maps (Cumulative Distribution Function) to assist in importance sampling + const cdfOptions = { + generateDepthBuffer: false, + generateMipMaps: false, + format: 6, + type: 1, + samplingMode: 1, + shaderLanguage: isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, + gammaSpace: false, + extraInitializationsAsync: async () => { + if (isWebGPU) { + await Promise.all([Promise.resolve().then(() => iblCdfx_fragment$1), Promise.resolve().then(() => iblCdfy_fragment$1), Promise.resolve().then(() => iblScaledLuminance_fragment$1)]); + } + else { + await Promise.all([Promise.resolve().then(() => iblCdfx_fragment), Promise.resolve().then(() => iblCdfy_fragment), Promise.resolve().then(() => iblScaledLuminance_fragment)]); + } + }, + }; + const icdfOptions = { + generateDepthBuffer: false, + generateMipMaps: false, + format: 5, + type: 2, + samplingMode: 1, + shaderLanguage: isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, + gammaSpace: false, + extraInitializationsAsync: async () => { + if (isWebGPU) { + await Promise.all([Promise.resolve().then(() => iblIcdf_fragment$1)]); + } + else { + await Promise.all([Promise.resolve().then(() => iblIcdf_fragment)]); + } + }, + }; + this._cdfyPT = new ProceduralTexture("cdfyTexture", { width: size.width, height: size.height + 1 }, "iblCdfy", this._scene, cdfOptions, false, false); + this._cdfyPT.autoClear = false; + this._cdfyPT.setTexture("iblSource", this._iblSource); + this._cdfyPT.setInt("iblHeight", size.height); + this._cdfyPT.wrapV = 0; + this._cdfyPT.refreshRate = 0; + if (this._iblSource.isCube) { + this._cdfyPT.defines = "#define IBL_USE_CUBE_MAP\n"; + } + this._cdfxPT = new ProceduralTexture("cdfxTexture", { width: size.width + 1, height: 1 }, "iblCdfx", this._scene, cdfOptions, false, false); + this._cdfxPT.autoClear = false; + this._cdfxPT.setTexture("cdfy", this._cdfyPT); + this._cdfxPT.refreshRate = 0; + this._cdfxPT.wrapU = 0; + this._scaledLuminancePT = new ProceduralTexture("iblScaledLuminance", { width: size.width, height: size.height }, "iblScaledLuminance", this._scene, { ...cdfOptions, samplingMode: 3, generateMipMaps: true }, true, false); + this._scaledLuminancePT.autoClear = false; + this._scaledLuminancePT.setTexture("iblSource", this._iblSource); + this._scaledLuminancePT.setInt("iblHeight", size.height); + this._scaledLuminancePT.setInt("iblWidth", size.width); + this._scaledLuminancePT.refreshRate = 0; + if (this._iblSource.isCube) { + this._scaledLuminancePT.defines = "#define IBL_USE_CUBE_MAP\n"; + } + this._icdfPT = new ProceduralTexture("icdfTexture", { width: size.width, height: size.height }, "iblIcdf", this._scene, icdfOptions, false, false); + this._icdfPT.autoClear = false; + this._icdfPT.setTexture("cdfy", this._cdfyPT); + this._icdfPT.setTexture("cdfx", this._cdfxPT); + this._icdfPT.setTexture("iblSource", this._iblSource); + this._icdfPT.setTexture("scaledLuminanceSampler", this._scaledLuminancePT); + this._icdfPT.refreshRate = 0; + this._icdfPT.wrapV = 0; + this._icdfPT.wrapU = 0; + if (this._iblSource.isCube) { + this._icdfPT.defines = "#define IBL_USE_CUBE_MAP\n"; + } + // Once the textures are generated, notify that they are ready to use. + this._icdfPT.onGeneratedObservable.addOnce(() => { + this.onGeneratedObservable.notifyObservers(); + }); + } + _disposeTextures() { + this._cdfyPT?.dispose(); + this._cdfxPT?.dispose(); + this._icdfPT?.dispose(); + this._scaledLuminancePT?.dispose(); + } + _createDebugPass() { + if (this._debugPass) { + this._debugPass.dispose(); + } + const isWebGPU = this._engine.isWebGPU; + const debugOptions = { + width: this._engine.getRenderWidth(), + height: this._engine.getRenderHeight(), + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine: this._engine, + textureType: 0, + uniforms: ["sizeParams"], + samplers: ["cdfy", "icdf", "cdfx", "iblSource"], + defines: this._iblSource?.isCube ? "#define IBL_USE_CUBE_MAP\n" : "", + shaderLanguage: isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, + extraInitializations: (useWebGPU, list) => { + if (useWebGPU) { + list.push(Promise.resolve().then(() => iblCdfDebug_fragment$1)); + } + else { + list.push(Promise.resolve().then(() => iblCdfDebug_fragment)); + } + }, + }; + this._debugPass = new PostProcess(this._debugPassName, "iblCdfDebug", debugOptions); + const debugEffect = this._debugPass.getEffect(); + if (debugEffect) { + debugEffect.defines = this._iblSource?.isCube ? "#define IBL_USE_CUBE_MAP\n" : ""; + } + if (this._iblSource?.isCube) { + this._debugPass.updateEffect("#define IBL_USE_CUBE_MAP\n"); + } + this._debugPass.onApplyObservable.add((effect) => { + effect.setTexture("cdfy", this._cdfyPT); + effect.setTexture("icdf", this._icdfPT); + effect.setTexture("cdfx", this._cdfxPT); + effect.setTexture("iblSource", this._iblSource); + effect.setFloat4("sizeParams", this._debugSizeParams.x, this._debugSizeParams.y, this._debugSizeParams.z, this._debugSizeParams.w); + }); + } + /** + * Checks if the CDF renderer is ready + * @returns true if the CDF renderer is ready + */ + isReady() { + return (this._iblSource && + this._iblSource.name !== "Placeholder IBL Source" && + this._iblSource.isReady() && + this._cdfyPT && + this._cdfyPT.isReady() && + this._icdfPT && + this._icdfPT.isReady() && + this._cdfxPT && + this._cdfxPT.isReady() && + this._scaledLuminancePT && + this._scaledLuminancePT.isReady()); + } + /** + * Explicitly trigger generation of CDF maps when they are ready to render. + * @returns Promise that resolves when the CDF maps are rendered. + */ + renderWhenReady() { + // Once the textures are generated, notify that they are ready to use. + this._icdfPT.onGeneratedObservable.addOnce(() => { + this.onGeneratedObservable.notifyObservers(); + }); + const promises = []; + const renderTargets = [this._cdfyPT, this._cdfxPT, this._scaledLuminancePT, this._icdfPT]; + renderTargets.forEach((target) => { + promises.push(new Promise((resolve) => { + if (target.isReady()) { + resolve(); + } + else { + target.getEffect().executeWhenCompiled(() => { + resolve(); + }); + } + })); + }); + return Promise.all(promises).then(() => { + renderTargets.forEach((target) => { + target.render(); + }); + }); + } + /** + * Disposes the CDF renderer and associated resources + */ + dispose() { + this._disposeTextures(); + this._dummyTexture.dispose(); + if (this._debugPass) { + this._debugPass.dispose(); + } + this.onGeneratedObservable.clear(); + } + static _IsScene(sceneOrEngine) { + return sceneOrEngine.getClassName() === "Scene"; + } +} +/** + * @internal + */ +IblCdfGenerator._SceneComponentInitialization = (_) => { + throw _WarnImport("IblCdfGeneratorSceneComponentSceneComponent"); +}; + +/** + * Filters HDR maps to get correct renderings of PBR reflections + */ +class HDRIrradianceFiltering { + /** + * Instantiates HDR filter for irradiance map + * + * @param engine Thin engine + * @param options Options + */ + constructor(engine, options = {}) { + /** + * Quality switch for prefiltering. Should be set to `4096` unless + * you care about baking speed. + */ + this.quality = 4096; + /** + * Scales pixel intensity for the input HDR map. + */ + this.hdrScale = 1; + /** + * Use the Cumulative Distribution Function (CDF) for filtering + */ + this.useCdf = false; + // pass + this._engine = engine; + this.hdrScale = options.hdrScale || this.hdrScale; + this.quality = options.quality || this.quality; + this.useCdf = options.useCdf || this.useCdf; + } + _createRenderTarget(size) { + let textureType = 0; + if (this._engine.getCaps().textureHalfFloatRender) { + textureType = 2; + } + else if (this._engine.getCaps().textureFloatRender) { + textureType = 1; + } + const rtWrapper = this._engine.createRenderTargetCubeTexture(size, { + format: 5, + type: textureType, + createMipMaps: false, + generateMipMaps: false, + generateDepthBuffer: false, + generateStencilBuffer: false, + samplingMode: 2, + label: "HDR_Irradiance_Filtering_Target", + }); + this._engine.updateTextureWrappingMode(rtWrapper.texture, 0, 0, 0); + return rtWrapper; + } + _prefilterInternal(texture) { + const width = texture.getSize().width; + const mipmapsCount = ILog2(width); + const effect = this._effectWrapper.effect; + // Choose a power of 2 size for the irradiance map. + // It can be much smaller than the original texture. + const irradianceSize = Math.max(32, 1 << ILog2(width >> 3)); + const outputTexture = this._createRenderTarget(irradianceSize); + this._effectRenderer.saveStates(); + this._effectRenderer.setViewport(); + this._effectRenderer.applyEffectWrapper(this._effectWrapper); + const directions = [ + [new Vector3(0, 0, -1), new Vector3(0, -1, 0), new Vector3(1, 0, 0)], // PositiveX + [new Vector3(0, 0, 1), new Vector3(0, -1, 0), new Vector3(-1, 0, 0)], // NegativeX + [new Vector3(1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0)], // PositiveY + [new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)], // NegativeY + [new Vector3(1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, 1)], // PositiveZ + [new Vector3(-1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, -1)], // NegativeZ + ]; + effect.setFloat("hdrScale", this.hdrScale); + effect.setFloat2("vFilteringInfo", texture.getSize().width, mipmapsCount); + effect.setTexture("inputTexture", texture); + if (this._cdfGenerator) { + effect.setTexture("icdfTexture", this._cdfGenerator.getIcdfTexture()); + } + for (let face = 0; face < 6; face++) { + effect.setVector3("up", directions[face][0]); + effect.setVector3("right", directions[face][1]); + effect.setVector3("front", directions[face][2]); + this._engine.bindFramebuffer(outputTexture, face, undefined, undefined, true); + this._effectRenderer.applyEffectWrapper(this._effectWrapper); + this._effectRenderer.draw(); + } + // Cleanup + this._effectRenderer.restoreStates(); + this._engine.restoreDefaultFramebuffer(); + effect.setTexture("inputTexture", null); + effect.setTexture("icdfTexture", null); + const irradianceTexture = new BaseTexture(texture.getScene(), outputTexture.texture); + irradianceTexture.name = texture.name + "_irradiance"; + irradianceTexture.displayName = texture.name + "_irradiance"; + irradianceTexture.gammaSpace = false; + return irradianceTexture; + } + _createEffect(texture, onCompiled) { + const defines = []; + if (texture.gammaSpace) { + defines.push("#define GAMMA_INPUT"); + } + defines.push("#define NUM_SAMPLES " + this.quality + "u"); // unsigned int + const isWebGPU = this._engine.isWebGPU; + const samplers = ["inputTexture"]; + if (this._cdfGenerator) { + samplers.push("icdfTexture"); + defines.push("#define IBL_CDF_FILTERING"); + } + const effectWrapper = new EffectWrapper({ + engine: this._engine, + name: "HDRIrradianceFiltering", + vertexShader: "hdrIrradianceFiltering", + fragmentShader: "hdrIrradianceFiltering", + samplerNames: samplers, + uniformNames: ["vSampleDirections", "vWeights", "up", "right", "front", "vFilteringInfo", "hdrScale"], + useShaderStore: true, + defines, + onCompiled: onCompiled, + shaderLanguage: isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, + extraInitializationsAsync: async () => { + if (isWebGPU) { + await Promise.all([Promise.resolve().then(() => hdrIrradianceFiltering_vertex), Promise.resolve().then(() => hdrIrradianceFiltering_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => hdrIrradianceFiltering_vertex$1), Promise.resolve().then(() => hdrIrradianceFiltering_fragment$1)]); + } + }, + }); + return effectWrapper; + } + /** + * Get a value indicating if the filter is ready to be used + * @param texture Texture to filter + * @returns true if the filter is ready + */ + isReady(texture) { + return texture.isReady() && this._effectWrapper.effect.isReady(); + } + /** + * Prefilters a cube texture to contain IBL irradiance. + * Prefiltering will be invoked at the end of next rendering pass. + * This has to be done once the map is loaded, and has not been prefiltered by a third party software. + * See http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf for more information + * @param texture Texture to filter + * @returns Promise called when prefiltering is done + */ + async prefilter(texture) { + if (!this._engine._features.allowTexturePrefiltering) { + throw new Error("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."); + } + if (this.useCdf) { + this._cdfGenerator = new IblCdfGenerator(this._engine); + this._cdfGenerator.iblSource = texture; + await this._cdfGenerator.renderWhenReady(); + } + this._effectRenderer = new EffectRenderer(this._engine); + this._effectWrapper = this._createEffect(texture); + await this._effectWrapper.effect.whenCompiledAsync(); + const irradianceTexture = this._prefilterInternal(texture); + this._effectRenderer.dispose(); + this._effectWrapper.dispose(); + this._cdfGenerator?.dispose(); + return irradianceTexture; + } +} + +/** + * This represents a texture coming from an HDR input. + * + * The only supported format is currently panorama picture stored in RGBE format. + * Example of such files can be found on Poly Haven: https://polyhaven.com/hdris + */ +class HDRCubeTexture extends BaseTexture { + /** + * Sets whether or not the texture is blocking during loading. + */ + set isBlocking(value) { + this._isBlocking = value; + } + /** + * Gets whether or not the texture is blocking during loading. + */ + get isBlocking() { + return this._isBlocking; + } + /** + * Sets texture matrix rotation angle around Y axis in radians. + */ + set rotationY(value) { + this._rotationY = value; + this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY)); + } + /** + * Gets texture matrix rotation angle around Y axis radians. + */ + get rotationY() { + return this._rotationY; + } + /** + * Gets or sets the size of the bounding box associated with the cube texture + * When defined, the cubemap will switch to local mode + * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity + * @example https://www.babylonjs-playground.com/#RNASML + */ + set boundingBoxSize(value) { + if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { + return; + } + this._boundingBoxSize = value; + const scene = this.getScene(); + if (scene) { + scene.markAllMaterialsAsDirty(1); + } + } + get boundingBoxSize() { + return this._boundingBoxSize; + } + /** + * Instantiates an HDRTexture from the following parameters. + * + * @param url The location of the HDR raw data (Panorama stored in RGBE format) + * @param sceneOrEngine The scene or engine the texture will be used in + * @param size The cubemap desired size (the more it increases the longer the generation will be) + * @param noMipmap Forces to not generate the mipmap if true + * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process + * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) + * @param prefilterOnLoad Prefilters HDR texture to allow use of this texture as a PBR reflection texture. + * @param onLoad on success callback function + * @param onError on error callback function + * @param supersample Defines if texture must be supersampled (default: false) + * @param prefilterIrradianceOnLoad Prefilters HDR texture to allow use of this texture for irradiance lighting. + * @param prefilterUsingCdf Defines if the prefiltering should be done using a CDF instead of the default approach. + */ + constructor(url, sceneOrEngine, size, noMipmap = false, generateHarmonics = true, gammaSpace = false, prefilterOnLoad = false, onLoad = null, onError = null, supersample = false, prefilterIrradianceOnLoad = false, prefilterUsingCdf = false) { + super(sceneOrEngine); + this._generateHarmonics = true; + this._onError = null; + this._isBlocking = true; + this._rotationY = 0; + /** + * Gets or sets the center of the bounding box associated with the cube texture + * It must define where the camera used to render the texture was set + */ + this.boundingBoxPosition = Vector3.Zero(); + /** + * Observable triggered once the texture has been loaded. + */ + this.onLoadObservable = new Observable(); + if (!url) { + return; + } + this._coordinatesMode = Texture.CUBIC_MODE; + this.name = url; + this.url = url; + this.hasAlpha = false; + this.isCube = true; + this._textureMatrix = Matrix.Identity(); + this._prefilterOnLoad = prefilterOnLoad; + this._prefilterIrradianceOnLoad = prefilterIrradianceOnLoad; + this._prefilterUsingCdf = prefilterUsingCdf; + this._onLoad = () => { + this.onLoadObservable.notifyObservers(this); + if (onLoad) { + onLoad(); + } + }; + this._onError = onError; + this.gammaSpace = gammaSpace; + this._noMipmap = noMipmap; + this._size = size; + // CDF is very sensitive to lost precision due to downsampling. This can result in + // noticeable brightness differences with different resolutions. Enabling supersampling + // mitigates this. + this._supersample = supersample || prefilterUsingCdf; + this._generateHarmonics = generateHarmonics; + this._texture = this._getFromCache(url, this._noMipmap, undefined, undefined, undefined, this.isCube); + if (!this._texture) { + if (!this.getScene()?.useDelayedTextureLoading) { + this._loadTexture(); + } + else { + this.delayLoadState = 4; + } + } + else { + if (this._texture.isReady) { + Tools.SetImmediate(() => this._onLoad()); + } + else { + this._texture.onLoadedObservable.add(this._onLoad); + } + } + } + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "HDRCubeTexture" + */ + getClassName() { + return "HDRCubeTexture"; + } + /** + * Occurs when the file is raw .hdr file. + */ + _loadTexture() { + const engine = this._getEngine(); + const caps = engine.getCaps(); + let textureType = 0; + if (caps.textureFloat && caps.textureFloatLinearFiltering) { + textureType = 1; + } + else if (caps.textureHalfFloat && caps.textureHalfFloatLinearFiltering) { + textureType = 2; + } + const callback = (buffer) => { + this.lodGenerationOffset = 0.0; + this.lodGenerationScale = 0.8; + // Extract the raw linear data. + const data = GetCubeMapTextureData(buffer, this._size, this._supersample); + // Generate harmonics if needed. + if (this._generateHarmonics) { + const sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data); + this.sphericalPolynomial = sphericalPolynomial; + } + const results = []; + let byteArray = null; + let shortArray = null; + // Push each faces. + for (let j = 0; j < 6; j++) { + // Create fallback array + if (textureType === 2) { + shortArray = new Uint16Array(this._size * this._size * 3); + } + else if (textureType === 0) { + // 3 channels of 1 bytes per pixel in bytes. + byteArray = new Uint8Array(this._size * this._size * 3); + } + const dataFace = data[HDRCubeTexture._FacesMapping[j]]; + // If special cases. + if (this.gammaSpace || shortArray || byteArray) { + for (let i = 0; i < this._size * this._size; i++) { + // Put in gamma space if requested. + if (this.gammaSpace) { + dataFace[i * 3 + 0] = Math.pow(dataFace[i * 3 + 0], ToGammaSpace); + dataFace[i * 3 + 1] = Math.pow(dataFace[i * 3 + 1], ToGammaSpace); + dataFace[i * 3 + 2] = Math.pow(dataFace[i * 3 + 2], ToGammaSpace); + } + // Convert to half float texture for fallback. + if (shortArray) { + shortArray[i * 3 + 0] = ToHalfFloat$1(dataFace[i * 3 + 0]); + shortArray[i * 3 + 1] = ToHalfFloat$1(dataFace[i * 3 + 1]); + shortArray[i * 3 + 2] = ToHalfFloat$1(dataFace[i * 3 + 2]); + } + // Convert to int texture for fallback. + if (byteArray) { + let r = Math.max(dataFace[i * 3 + 0] * 255, 0); + let g = Math.max(dataFace[i * 3 + 1] * 255, 0); + let b = Math.max(dataFace[i * 3 + 2] * 255, 0); + // May use luminance instead if the result is not accurate. + const max = Math.max(Math.max(r, g), b); + if (max > 255) { + const scale = 255 / max; + r *= scale; + g *= scale; + b *= scale; + } + byteArray[i * 3 + 0] = r; + byteArray[i * 3 + 1] = g; + byteArray[i * 3 + 2] = b; + } + } + } + if (shortArray) { + results.push(shortArray); + } + else if (byteArray) { + results.push(byteArray); + } + else { + results.push(dataFace); + } + } + return results; + }; + if (engine._features.allowTexturePrefiltering && (this._prefilterOnLoad || this._prefilterIrradianceOnLoad)) { + const previousOnLoad = this._onLoad; + const hdrFiltering = new HDRFiltering(engine); + this._onLoad = () => { + let irradiancePromise = Promise.resolve(null); + let radiancePromise = Promise.resolve(); + if (this._prefilterIrradianceOnLoad) { + const hdrIrradianceFiltering = new HDRIrradianceFiltering(engine, { useCdf: this._prefilterUsingCdf }); + irradiancePromise = hdrIrradianceFiltering.prefilter(this); + } + if (this._prefilterOnLoad) { + radiancePromise = hdrFiltering.prefilter(this); + } + Promise.all([irradiancePromise, radiancePromise]).then((results) => { + const irradianceTexture = results[0]; + if (this._prefilterIrradianceOnLoad && irradianceTexture) { + this.irradianceTexture = irradianceTexture; + const scene = this.getScene(); + if (scene) { + scene.markAllMaterialsAsDirty(1); + } + } + if (previousOnLoad) { + previousOnLoad(); + } + }); + }; + } + this._texture = engine.createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, 4, textureType, this._noMipmap, callback, null, this._onLoad, this._onError); + } + clone() { + const newTexture = new HDRCubeTexture(this.url, this.getScene() || this._getEngine(), this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace); + // Base texture + newTexture.level = this.level; + newTexture.wrapU = this.wrapU; + newTexture.wrapV = this.wrapV; + newTexture.coordinatesIndex = this.coordinatesIndex; + newTexture.coordinatesMode = this.coordinatesMode; + return newTexture; + } + // Methods + delayLoad() { + if (this.delayLoadState !== 4) { + return; + } + this.delayLoadState = 1; + this._texture = this._getFromCache(this.url, this._noMipmap); + if (!this._texture) { + this._loadTexture(); + } + } + /** + * Get the texture reflection matrix used to rotate/transform the reflection. + * @returns the reflection matrix + */ + getReflectionTextureMatrix() { + return this._textureMatrix; + } + /** + * Set the texture reflection matrix used to rotate/transform the reflection. + * @param value Define the reflection matrix to set + */ + setReflectionTextureMatrix(value) { + this._textureMatrix = value; + if (value.updateFlag === this._textureMatrix.updateFlag) { + return; + } + if (value.isIdentity() !== this._textureMatrix.isIdentity()) { + this.getScene()?.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1); + } + } + /** + * Dispose the texture and release its associated resources. + */ + dispose() { + this.onLoadObservable.clear(); + super.dispose(); + } + /** + * Parses a JSON representation of an HDR Texture in order to create the texture + * @param parsedTexture Define the JSON representation + * @param scene Define the scene the texture should be created in + * @param rootUrl Define the root url in case we need to load relative dependencies + * @returns the newly created texture after parsing + */ + static Parse(parsedTexture, scene, rootUrl) { + let texture = null; + if (parsedTexture.name && !parsedTexture.isRenderTarget) { + texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace); + texture.name = parsedTexture.name; + texture.hasAlpha = parsedTexture.hasAlpha; + texture.level = parsedTexture.level; + texture.coordinatesMode = parsedTexture.coordinatesMode; + texture.isBlocking = parsedTexture.isBlocking; + } + if (texture) { + if (parsedTexture.boundingBoxPosition) { + texture.boundingBoxPosition = Vector3.FromArray(parsedTexture.boundingBoxPosition); + } + if (parsedTexture.boundingBoxSize) { + texture.boundingBoxSize = Vector3.FromArray(parsedTexture.boundingBoxSize); + } + if (parsedTexture.rotationY) { + texture.rotationY = parsedTexture.rotationY; + } + } + return texture; + } + serialize() { + if (!this.name) { + return null; + } + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.hasAlpha = this.hasAlpha; + serializationObject.isCube = true; + serializationObject.level = this.level; + serializationObject.size = this._size; + serializationObject.coordinatesMode = this.coordinatesMode; + serializationObject.useInGammaSpace = this.gammaSpace; + serializationObject.generateHarmonics = this._generateHarmonics; + serializationObject.customType = "BABYLON.HDRCubeTexture"; + serializationObject.noMipmap = this._noMipmap; + serializationObject.isBlocking = this._isBlocking; + serializationObject.rotationY = this._rotationY; + return serializationObject; + } +} +HDRCubeTexture._FacesMapping = ["right", "left", "up", "down", "front", "back"]; +RegisterClass("BABYLON.HDRCubeTexture", HDRCubeTexture); + +/** + * Base class for results of casts. + */ +class CastingResult { + constructor() { + this._hasHit = false; + this._hitNormal = Vector3.Zero(); + this._hitPoint = Vector3.Zero(); + this._triangleIndex = -1; + } + /** + * Gets the hit point. + */ + get hitPoint() { + return this._hitPoint; + } + /** + * Gets the hit normal. + */ + get hitNormal() { + return this._hitNormal; + } + /** + * Gets if there was a hit + */ + get hasHit() { + return this._hasHit; + } + /* + * The index of the original triangle which was hit. Will be -1 if contact point is not on a mesh shape + */ + get triangleIndex() { + return this._triangleIndex; + } + /** + * Sets the hit data + * @param hitNormal defines the normal in world space + * @param hitPoint defines the point in world space + * @param triangleIndex defines the index of the triangle in case of mesh shape + */ + setHitData(hitNormal, hitPoint, triangleIndex) { + this._hasHit = true; + this._hitNormal.set(hitNormal.x, hitNormal.y, hitNormal.z); + this._hitPoint.set(hitPoint.x, hitPoint.y, hitPoint.z); + this._triangleIndex = triangleIndex ?? -1; + } + /** + * Resets all the values to default + */ + reset() { + this._hasHit = false; + this._hitNormal.setAll(0); + this._hitPoint.setAll(0); + this._triangleIndex = -1; + this.body = undefined; + this.bodyIndex = undefined; + this.shape = undefined; + } +} + +/** + * Holds the data for the raycast result + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine + */ +class PhysicsRaycastResult extends CastingResult { + constructor() { + super(...arguments); + this._hitDistance = 0; + this._rayFromWorld = Vector3.Zero(); + this._rayToWorld = Vector3.Zero(); + } + /** + * Gets the distance from the hit + */ + get hitDistance() { + return this._hitDistance; + } + /** + * Gets the hit normal/direction in the world + */ + get hitNormalWorld() { + return this._hitNormal; + } + /** + * Gets the hit point in the world + */ + get hitPointWorld() { + return this._hitPoint; + } + /** + * Gets the ray "start point" of the ray in the world + */ + get rayFromWorld() { + return this._rayFromWorld; + } + /** + * Gets the ray "end point" of the ray in the world + */ + get rayToWorld() { + return this._rayToWorld; + } + /** + * Sets the distance from the start point to the hit point + * @param distance defines the distance to set + */ + setHitDistance(distance) { + this._hitDistance = distance; + } + /** + * Calculates the distance manually + */ + calculateHitDistance() { + this._hitDistance = Vector3.Distance(this._rayFromWorld, this._hitPoint); + } + /** + * Resets all the values to default + * @param from The from point on world space + * @param to The to point on world space + */ + reset(from = Vector3.Zero(), to = Vector3.Zero()) { + super.reset(); + this._rayFromWorld.copyFrom(from); + this._rayToWorld.copyFrom(to); + this._hitDistance = 0; + } +} + +/** + * Class used to control physics engine + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine + */ +let PhysicsEngine$1 = class PhysicsEngine { + /** + * + * @returns version + */ + getPluginVersion() { + return this._physicsPlugin.getPluginVersion(); + } + /** + * @virtual + * Factory used to create the default physics plugin. + * @returns The default physics plugin + */ + static DefaultPluginFactory() { + throw _WarnImport("CannonJSPlugin"); + } + /** + * Creates a new Physics Engine + * @param gravity defines the gravity vector used by the simulation + * @param _physicsPlugin defines the plugin to use (CannonJS by default) + */ + constructor(gravity, _physicsPlugin = PhysicsEngine.DefaultPluginFactory()) { + this._physicsPlugin = _physicsPlugin; + /** + * Global value used to control the smallest number supported by the simulation + */ + this._impostors = []; + this._joints = []; + this._subTimeStep = 0; + this._uniqueIdCounter = 0; + if (!this._physicsPlugin.isSupported()) { + throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. " + "Please make sure it is included."); + } + gravity = gravity || new Vector3(0, -9.807, 0); + this.setGravity(gravity); + this.setTimeStep(); + } + /** + * Sets the gravity vector used by the simulation + * @param gravity defines the gravity vector to use + */ + setGravity(gravity) { + this.gravity = gravity; + this._physicsPlugin.setGravity(this.gravity); + } + /** + * Set the time step of the physics engine. + * Default is 1/60. + * To slow it down, enter 1/600 for example. + * To speed it up, 1/30 + * @param newTimeStep defines the new timestep to apply to this world. + */ + setTimeStep(newTimeStep = 1 / 60) { + this._physicsPlugin.setTimeStep(newTimeStep); + } + /** + * Get the time step of the physics engine. + * @returns the current time step + */ + getTimeStep() { + return this._physicsPlugin.getTimeStep(); + } + /** + * Set the sub time step of the physics engine. + * Default is 0 meaning there is no sub steps + * To increase physics resolution precision, set a small value (like 1 ms) + * @param subTimeStep defines the new sub timestep used for physics resolution. + */ + setSubTimeStep(subTimeStep = 0) { + this._subTimeStep = subTimeStep; + } + /** + * Get the sub time step of the physics engine. + * @returns the current sub time step + */ + getSubTimeStep() { + return this._subTimeStep; + } + /** + * Release all resources + */ + dispose() { + this._impostors.forEach(function (impostor) { + impostor.dispose(); + }); + this._physicsPlugin.dispose(); + } + /** + * Gets the name of the current physics plugin + * @returns the name of the plugin + */ + getPhysicsPluginName() { + return this._physicsPlugin.name; + } + /** + * Adding a new impostor for the impostor tracking. + * This will be done by the impostor itself. + * @param impostor the impostor to add + */ + addImpostor(impostor) { + this._impostors.push(impostor); + impostor.uniqueId = this._uniqueIdCounter++; + //if no parent, generate the body + if (!impostor.parent) { + this._physicsPlugin.generatePhysicsBody(impostor); + } + } + /** + * Remove an impostor from the engine. + * This impostor and its mesh will not longer be updated by the physics engine. + * @param impostor the impostor to remove + */ + removeImpostor(impostor) { + const index = this._impostors.indexOf(impostor); + if (index > -1) { + const removed = this._impostors.splice(index, 1); + //Is it needed? + if (removed.length) { + this.getPhysicsPlugin().removePhysicsBody(impostor); + } + } + } + /** + * Add a joint to the physics engine + * @param mainImpostor defines the main impostor to which the joint is added. + * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint + * @param joint defines the joint that will connect both impostors. + */ + addJoint(mainImpostor, connectedImpostor, joint) { + const impostorJoint = { + mainImpostor: mainImpostor, + connectedImpostor: connectedImpostor, + joint: joint, + }; + joint.physicsPlugin = this._physicsPlugin; + this._joints.push(impostorJoint); + this._physicsPlugin.generateJoint(impostorJoint); + } + /** + * Removes a joint from the simulation + * @param mainImpostor defines the impostor used with the joint + * @param connectedImpostor defines the other impostor connected to the main one by the joint + * @param joint defines the joint to remove + */ + removeJoint(mainImpostor, connectedImpostor, joint) { + const matchingJoints = this._joints.filter(function (impostorJoint) { + return impostorJoint.connectedImpostor === connectedImpostor && impostorJoint.joint === joint && impostorJoint.mainImpostor === mainImpostor; + }); + if (matchingJoints.length) { + this._physicsPlugin.removeJoint(matchingJoints[0]); + //TODO remove it from the list as well + } + } + /** + * Called by the scene. No need to call it. + * @param delta defines the timespan between frames + */ + _step(delta) { + //check if any mesh has no body / requires an update + this._impostors.forEach((impostor) => { + if (impostor.isBodyInitRequired()) { + this._physicsPlugin.generatePhysicsBody(impostor); + } + }); + if (delta > 0.1) { + delta = 0.1; + } + else if (delta <= 0) { + delta = 1.0 / 60.0; + } + this._physicsPlugin.executeStep(delta, this._impostors); + } + /** + * Gets the current plugin used to run the simulation + * @returns current plugin + */ + getPhysicsPlugin() { + return this._physicsPlugin; + } + /** + * Gets the list of physic impostors + * @returns an array of PhysicsImpostor + */ + getImpostors() { + return this._impostors; + } + /** + * Gets the impostor for a physics enabled object + * @param object defines the object impersonated by the impostor + * @returns the PhysicsImpostor or null if not found + */ + getImpostorForPhysicsObject(object) { + for (let i = 0; i < this._impostors.length; ++i) { + if (this._impostors[i].object === object) { + return this._impostors[i]; + } + } + return null; + } + /** + * Gets the impostor for a physics body object + * @param body defines physics body used by the impostor + * @returns the PhysicsImpostor or null if not found + */ + getImpostorWithPhysicsBody(body) { + for (let i = 0; i < this._impostors.length; ++i) { + if (this._impostors[i].physicsBody === body) { + return this._impostors[i]; + } + } + return null; + } + /** + * Does a raycast in the physics world + * @param from when should the ray start? + * @param to when should the ray end? + * @returns PhysicsRaycastResult + */ + raycast(from, to) { + return this._physicsPlugin.raycast(from, to); + } + /** + * Does a raycast in the physics world + * @param from when should the ray start? + * @param to when should the ray end? + * @param result resulting PhysicsRaycastResult + * @returns true if the ray hits an impostor, else false + */ + raycastToRef(from, to, result) { + return this._physicsPlugin.raycastToRef(from, to, result); + } +}; + +/** @internal */ +class CannonJSPlugin { + constructor(_useDeltaForWorldStep = true, iterations = 10, cannonInjection = CANNON) { + this._useDeltaForWorldStep = _useDeltaForWorldStep; + this.name = "CannonJSPlugin"; + this._physicsMaterials = new Array(); + this._fixedTimeStep = 1 / 60; + this._physicsBodiesToRemoveAfterStep = new Array(); + this._firstFrame = true; + this._tmpQuaternion = new Quaternion(); + this._minus90X = new Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475); + this._plus90X = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475); + this._tmpPosition = Vector3.Zero(); + this._tmpDeltaPosition = Vector3.Zero(); + this._tmpUnityRotation = new Quaternion(); + this.BJSCANNON = cannonInjection; + if (!this.isSupported()) { + Logger.Error("CannonJS is not available. Please make sure you included the js file."); + return; + } + this._extendNamespace(); + this.world = new this.BJSCANNON.World(); + this.world.broadphase = new this.BJSCANNON.NaiveBroadphase(); + this.world.solver.iterations = iterations; + this._cannonRaycastResult = new this.BJSCANNON.RaycastResult(); + this._raycastResult = new PhysicsRaycastResult(); + } + /** + * + * @returns plugin version + */ + getPluginVersion() { + return 1; + } + setGravity(gravity) { + const vec = gravity; + this.world.gravity.set(vec.x, vec.y, vec.z); + } + setTimeStep(timeStep) { + this._fixedTimeStep = timeStep; + } + getTimeStep() { + return this._fixedTimeStep; + } + executeStep(delta, impostors) { + // due to cannon's architecture, the first frame's before-step is skipped. + if (this._firstFrame) { + this._firstFrame = false; + for (const impostor of impostors) { + if (!(impostor.type == PhysicsImpostor.HeightmapImpostor || impostor.type === PhysicsImpostor.PlaneImpostor)) { + impostor.beforeStep(); + } + } + } + this.world.step(this._useDeltaForWorldStep ? delta : this._fixedTimeStep); + this._removeMarkedPhysicsBodiesFromWorld(); + } + _removeMarkedPhysicsBodiesFromWorld() { + if (this._physicsBodiesToRemoveAfterStep.length > 0) { + this._physicsBodiesToRemoveAfterStep.forEach((physicsBody) => { + if (typeof this.world.removeBody === "function") { + this.world.removeBody(physicsBody); + } + else { + this.world.remove(physicsBody); + } + }); + this._physicsBodiesToRemoveAfterStep.length = 0; + } + } + applyImpulse(impostor, force, contactPoint) { + const worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z); + const impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z); + impostor.physicsBody.applyImpulse(impulse, worldPoint); + } + applyForce(impostor, force, contactPoint) { + const worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z); + const impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z); + impostor.physicsBody.applyForce(impulse, worldPoint); + } + generatePhysicsBody(impostor) { + // When calling forceUpdate generatePhysicsBody is called again, ensure that the updated body does not instantly collide with removed body + this._removeMarkedPhysicsBodiesFromWorld(); + //parent-child relationship. Does this impostor have a parent impostor? + if (impostor.parent) { + if (impostor.physicsBody) { + this.removePhysicsBody(impostor); + //TODO is that needed? + impostor.forceUpdate(); + } + return; + } + //should a new body be created for this impostor? + if (impostor.isBodyInitRequired()) { + const shape = this._createShape(impostor); + if (!shape) { + Logger.Warn("It was not possible to create a physics body for this object."); + return; + } + //unregister events if body is being changed + const oldBody = impostor.physicsBody; + if (oldBody) { + this.removePhysicsBody(impostor); + } + //create the body and material + const material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution")); + const bodyCreationObject = { + mass: impostor.getParam("mass"), + material: material, + }; + // A simple extend, in case native options were used. + const nativeOptions = impostor.getParam("nativeOptions"); + for (const key in nativeOptions) { + if (Object.prototype.hasOwnProperty.call(nativeOptions, key)) { + bodyCreationObject[key] = nativeOptions[key]; + } + } + impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject); + impostor.physicsBody.addEventListener("collide", impostor.onCollide); + this.world.addEventListener("preStep", impostor.beforeStep); + this.world.addEventListener("postStep", impostor.afterStep); + impostor.physicsBody.addShape(shape); + if (typeof this.world.addBody === "function") { + this.world.addBody(impostor.physicsBody); + } + else { + this.world.add(impostor.physicsBody); + } + //try to keep the body moving in the right direction by taking old properties. + //Should be tested! + if (oldBody) { + ["force", "torque", "velocity", "angularVelocity"].forEach(function (param) { + const vec = oldBody[param]; + impostor.physicsBody[param].set(vec.x, vec.y, vec.z); + }); + } + this._processChildMeshes(impostor); + } + //now update the body's transformation + this._updatePhysicsBodyTransformation(impostor); + } + _processChildMeshes(mainImpostor) { + const meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : []; + const mainRotation = mainImpostor.object.rotationQuaternion; + if (mainRotation) { + mainRotation.conjugateToRef(this._tmpQuaternion); + } + else { + this._tmpQuaternion.set(0, 0, 0, 1); + } + if (meshChildren.length) { + const processMesh = (mesh) => { + if (!mesh.rotationQuaternion) { + return; + } + const childImpostor = mesh.getPhysicsImpostor(); + if (childImpostor) { + const parent = childImpostor.parent; + if (parent !== mainImpostor && mesh.parent) { + const pPosition = mesh.getAbsolutePosition().subtract(mesh.parent.getAbsolutePosition()); + const q = mesh.rotationQuaternion.multiply(this._tmpQuaternion); + if (childImpostor.physicsBody) { + this.removePhysicsBody(childImpostor); + childImpostor.physicsBody = null; + } + childImpostor.parent = mainImpostor; + childImpostor.resetUpdateFlags(); + mainImpostor.physicsBody.addShape(this._createShape(childImpostor), new this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new this.BJSCANNON.Quaternion(q.x, q.y, q.z, q.w)); + //Add the mass of the children. + mainImpostor.physicsBody.mass += childImpostor.getParam("mass"); + } + } + mesh.getChildMeshes(true) + .filter((m) => !!m.physicsImpostor) + .forEach(processMesh); + }; + meshChildren.filter((m) => !!m.physicsImpostor).forEach(processMesh); + } + } + removePhysicsBody(impostor) { + impostor.physicsBody.removeEventListener("collide", impostor.onCollide); + this.world.removeEventListener("preStep", impostor.beforeStep); + this.world.removeEventListener("postStep", impostor.afterStep); + // Only remove the physics body after the physics step to avoid disrupting cannon's internal state + if (this._physicsBodiesToRemoveAfterStep.indexOf(impostor.physicsBody) === -1) { + this._physicsBodiesToRemoveAfterStep.push(impostor.physicsBody); + } + } + generateJoint(impostorJoint) { + const mainBody = impostorJoint.mainImpostor.physicsBody; + const connectedBody = impostorJoint.connectedImpostor.physicsBody; + if (!mainBody || !connectedBody) { + return; + } + let constraint; + const jointData = impostorJoint.joint.jointData; + //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html + const constraintData = { + pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().set(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z) : null, + pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().set(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z) : null, + axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().set(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z) : null, + axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().set(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z) : null, + maxForce: jointData.nativeParams.maxForce, + collideConnected: !!jointData.collision, + }; + switch (impostorJoint.joint.type) { + case PhysicsJoint.HingeJoint: + case PhysicsJoint.Hinge2Joint: + constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData); + break; + case PhysicsJoint.DistanceJoint: + constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2); + break; + case PhysicsJoint.SpringJoint: { + const springData = jointData; + constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, { + restLength: springData.length, + stiffness: springData.stiffness, + damping: springData.damping, + localAnchorA: constraintData.pivotA, + localAnchorB: constraintData.pivotB, + }); + break; + } + case PhysicsJoint.LockJoint: + constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData); + break; + case PhysicsJoint.PointToPointJoint: + case PhysicsJoint.BallAndSocketJoint: + default: + constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotB, constraintData.maxForce); + break; + } + //set the collideConnected flag after the creation, since DistanceJoint ignores it. + constraint.collideConnected = !!jointData.collision; + impostorJoint.joint.physicsJoint = constraint; + //don't add spring as constraint, as it is not one. + if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) { + this.world.addConstraint(constraint); + } + else { + impostorJoint.joint.jointData.forceApplicationCallback = + impostorJoint.joint.jointData.forceApplicationCallback || + function () { + constraint.applyForce(); + }; + impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback); + } + } + removeJoint(impostorJoint) { + if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) { + this.world.removeConstraint(impostorJoint.joint.physicsJoint); + } + else { + impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback); + } + } + _addMaterial(name, friction, restitution) { + let index; + let mat; + for (index = 0; index < this._physicsMaterials.length; index++) { + mat = this._physicsMaterials[index]; + if (mat.friction === friction && mat.restitution === restitution) { + return mat; + } + } + const currentMat = new this.BJSCANNON.Material(name); + currentMat.friction = friction; + currentMat.restitution = restitution; + this._physicsMaterials.push(currentMat); + return currentMat; + } + _checkWithEpsilon(value) { + return value < Epsilon ? Epsilon : value; + } + _createShape(impostor) { + const object = impostor.object; + let returnValue; + const impostorExtents = impostor.getObjectExtents(); + switch (impostor.type) { + case PhysicsImpostor.SphereImpostor: { + const radiusX = impostorExtents.x; + const radiusY = impostorExtents.y; + const radiusZ = impostorExtents.z; + returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2); + break; + } + //TMP also for cylinder - TODO Cannon supports cylinder natively. + case PhysicsImpostor.CylinderImpostor: { + let nativeParams = impostor.getParam("nativeOptions"); + if (!nativeParams) { + nativeParams = {}; + } + const radiusTop = nativeParams.radiusTop !== undefined ? nativeParams.radiusTop : this._checkWithEpsilon(impostorExtents.x) / 2; + const radiusBottom = nativeParams.radiusBottom !== undefined ? nativeParams.radiusBottom : this._checkWithEpsilon(impostorExtents.x) / 2; + const height = nativeParams.height !== undefined ? nativeParams.height : this._checkWithEpsilon(impostorExtents.y); + const numSegments = nativeParams.numSegments !== undefined ? nativeParams.numSegments : 16; + returnValue = new this.BJSCANNON.Cylinder(radiusTop, radiusBottom, height, numSegments); + // Rotate 90 degrees as this shape is horizontal in cannon + const quat = new this.BJSCANNON.Quaternion(); + quat.setFromAxisAngle(new this.BJSCANNON.Vec3(1, 0, 0), -Math.PI / 2); + const translation = new this.BJSCANNON.Vec3(0, 0, 0); + returnValue.transformAllPoints(translation, quat); + break; + } + case PhysicsImpostor.BoxImpostor: { + const box = impostorExtents.scale(0.5); + returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z))); + break; + } + case PhysicsImpostor.PlaneImpostor: + Logger.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"); + returnValue = new this.BJSCANNON.Plane(); + break; + case PhysicsImpostor.MeshImpostor: { + // should transform the vertex data to world coordinates!! + const rawVerts = object.getVerticesData ? object.getVerticesData(VertexBuffer.PositionKind) : []; + const rawFaces = object.getIndices ? object.getIndices() : []; + if (!rawVerts) { + Logger.Warn("Tried to create a MeshImpostor for an object without vertices. This will fail."); + return; + } + // get only scale! so the object could transform correctly. + const oldPosition = object.position.clone(); + const oldRotation = object.rotation && object.rotation.clone(); + const oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone(); + object.position.copyFromFloats(0, 0, 0); + object.rotation && object.rotation.copyFromFloats(0, 0, 0); + object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation()); + object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace(); + const transform = object.computeWorldMatrix(true); + // convert rawVerts to object space + const transformedVertices = []; + let index; + for (index = 0; index < rawVerts.length; index += 3) { + Vector3.TransformCoordinates(Vector3.FromArray(rawVerts, index), transform).toArray(transformedVertices, index); + } + Logger.Warn("MeshImpostor only collides against spheres."); + returnValue = new this.BJSCANNON.Trimesh(transformedVertices, rawFaces); + //now set back the transformation! + object.position.copyFrom(oldPosition); + oldRotation && object.rotation && object.rotation.copyFrom(oldRotation); + oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion); + break; + } + case PhysicsImpostor.HeightmapImpostor: { + const oldPosition2 = object.position.clone(); + const oldRotation2 = object.rotation && object.rotation.clone(); + const oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone(); + object.position.copyFromFloats(0, 0, 0); + object.rotation && object.rotation.copyFromFloats(0, 0, 0); + object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation()); + object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace(); + object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X); + returnValue = this._createHeightmap(object); + object.position.copyFrom(oldPosition2); + oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2); + oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2); + object.computeWorldMatrix(true); + break; + } + case PhysicsImpostor.ParticleImpostor: + returnValue = new this.BJSCANNON.Particle(); + break; + case PhysicsImpostor.NoImpostor: + returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0, 0, 0)); + break; + } + return returnValue; + } + _createHeightmap(object, pointDepth) { + let pos = object.getVerticesData(VertexBuffer.PositionKind); + const transform = object.computeWorldMatrix(true); + // convert rawVerts to object space + const transformedVertices = []; + let index; + for (index = 0; index < pos.length; index += 3) { + Vector3.TransformCoordinates(Vector3.FromArray(pos, index), transform).toArray(transformedVertices, index); + } + pos = transformedVertices; + const matrix = new Array(); + //For now pointDepth will not be used and will be automatically calculated. + //Future reference - try and find the best place to add a reference to the pointDepth variable. + const arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1); + const boundingInfo = object.getBoundingInfo(); + const dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y); + const minY = boundingInfo.boundingBox.extendSizeWorld.z; + const elementSize = (dim * 2) / arraySize; + for (let i = 0; i < pos.length; i = i + 3) { + const x = Math.round(pos[i + 0] / elementSize + arraySize / 2); + const z = Math.round((pos[i + 1] / elementSize - arraySize / 2) * -1); + const y = -pos[i + 2] + minY; + if (!matrix[x]) { + matrix[x] = []; + } + if (!matrix[x][z]) { + matrix[x][z] = y; + } + matrix[x][z] = Math.max(y, matrix[x][z]); + } + for (let x = 0; x <= arraySize; ++x) { + if (!matrix[x]) { + let loc = 1; + while (!matrix[(x + loc) % arraySize]) { + loc++; + } + matrix[x] = matrix[(x + loc) % arraySize].slice(); + //console.log("missing x", x); + } + for (let z = 0; z <= arraySize; ++z) { + if (!matrix[x][z]) { + let loc = 1; + let newValue; + while (newValue === undefined) { + newValue = matrix[x][(z + loc++) % arraySize]; + } + matrix[x][z] = newValue; + } + } + } + const shape = new this.BJSCANNON.Heightfield(matrix, { + elementSize: elementSize, + }); + //For future reference, needed for body transformation + shape.minY = minY; + return shape; + } + _updatePhysicsBodyTransformation(impostor) { + const object = impostor.object; + //make sure it is updated... + object.computeWorldMatrix && object.computeWorldMatrix(true); + if (!object.getBoundingInfo()) { + return; + } + const center = impostor.getObjectCenter(); + //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld) + // The delta between the mesh position and the mesh bounding box center + this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center)); + this._tmpDeltaPosition.divideInPlace(impostor.object.scaling); + this._tmpPosition.copyFrom(center); + let quaternion = object.rotationQuaternion; + if (!quaternion) { + return; + } + //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis. + //ideally these would be rotated at time of creation like cylinder but they dont extend ConvexPolyhedron + if (impostor.type === PhysicsImpostor.PlaneImpostor || impostor.type === PhysicsImpostor.HeightmapImpostor) { + //-90 DEG in X, precalculated + quaternion = quaternion.multiply(this._minus90X); + //Invert! (Precalculated, 90 deg in X) + //No need to clone. this will never change. + impostor.setDeltaRotation(this._plus90X); + } + //If it is a heightfield, if should be centered. + if (impostor.type === PhysicsImpostor.HeightmapImpostor) { + const mesh = object; + let boundingInfo = mesh.getBoundingInfo(); + //calculate the correct body position: + const rotationQuaternion = mesh.rotationQuaternion; + mesh.rotationQuaternion = this._tmpUnityRotation; + mesh.computeWorldMatrix(true); + //get original center with no rotation + const c = center.clone(); + let oldPivot = mesh.getPivotMatrix(); + if (oldPivot) { + // create a copy the pivot Matrix as it is modified in place + oldPivot = oldPivot.clone(); + } + else { + oldPivot = Matrix.Identity(); + } + //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps) + const p = Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z); + mesh.setPreTransformMatrix(p); + mesh.computeWorldMatrix(true); + // force bounding box recomputation + boundingInfo = mesh.getBoundingInfo(); + //calculate the translation + const translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate(); + this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z); + //add it inverted to the delta + this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c)); + this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y; + //rotation is back + mesh.rotationQuaternion = rotationQuaternion; + mesh.setPreTransformMatrix(oldPivot); + mesh.computeWorldMatrix(true); + } + else if (impostor.type === PhysicsImpostor.MeshImpostor) { + this._tmpDeltaPosition.copyFromFloats(0, 0, 0); + } + impostor.setDeltaPosition(this._tmpDeltaPosition); + //Now update the impostor object + impostor.physicsBody.position.set(this._tmpPosition.x, this._tmpPosition.y, this._tmpPosition.z); + impostor.physicsBody.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w); + } + setTransformationFromPhysicsBody(impostor) { + impostor.object.position.set(impostor.physicsBody.position.x, impostor.physicsBody.position.y, impostor.physicsBody.position.z); + if (impostor.object.rotationQuaternion) { + const q = impostor.physicsBody.quaternion; + impostor.object.rotationQuaternion.set(q.x, q.y, q.z, q.w); + } + } + setPhysicsBodyTransformation(impostor, newPosition, newRotation) { + impostor.physicsBody.position.set(newPosition.x, newPosition.y, newPosition.z); + impostor.physicsBody.quaternion.set(newRotation.x, newRotation.y, newRotation.z, newRotation.w); + } + isSupported() { + return this.BJSCANNON !== undefined; + } + setLinearVelocity(impostor, velocity) { + impostor.physicsBody.velocity.set(velocity.x, velocity.y, velocity.z); + } + setAngularVelocity(impostor, velocity) { + impostor.physicsBody.angularVelocity.set(velocity.x, velocity.y, velocity.z); + } + getLinearVelocity(impostor) { + const v = impostor.physicsBody.velocity; + if (!v) { + return null; + } + return new Vector3(v.x, v.y, v.z); + } + getAngularVelocity(impostor) { + const v = impostor.physicsBody.angularVelocity; + if (!v) { + return null; + } + return new Vector3(v.x, v.y, v.z); + } + setBodyMass(impostor, mass) { + impostor.physicsBody.mass = mass; + impostor.physicsBody.updateMassProperties(); + } + getBodyMass(impostor) { + return impostor.physicsBody.mass; + } + getBodyFriction(impostor) { + return impostor.physicsBody.material.friction; + } + setBodyFriction(impostor, friction) { + impostor.physicsBody.material.friction = friction; + } + getBodyRestitution(impostor) { + return impostor.physicsBody.material.restitution; + } + setBodyRestitution(impostor, restitution) { + impostor.physicsBody.material.restitution = restitution; + } + sleepBody(impostor) { + impostor.physicsBody.sleep(); + } + wakeUpBody(impostor) { + impostor.physicsBody.wakeUp(); + } + updateDistanceJoint(joint, maxDistance) { + joint.physicsJoint.distance = maxDistance; + } + setMotor(joint, speed, maxForce, motorIndex) { + if (!motorIndex) { + joint.physicsJoint.enableMotor(); + joint.physicsJoint.setMotorSpeed(speed); + if (maxForce) { + this.setLimit(joint, maxForce); + } + } + } + setLimit(joint, minForce, maxForce) { + joint.physicsJoint.motorEquation.maxForce = maxForce; + joint.physicsJoint.motorEquation.minForce = minForce === void 0 ? -minForce : minForce; + } + syncMeshWithImpostor(mesh, impostor) { + const body = impostor.physicsBody; + mesh.position.x = body.position.x; + mesh.position.y = body.position.y; + mesh.position.z = body.position.z; + if (mesh.rotationQuaternion) { + mesh.rotationQuaternion.x = body.quaternion.x; + mesh.rotationQuaternion.y = body.quaternion.y; + mesh.rotationQuaternion.z = body.quaternion.z; + mesh.rotationQuaternion.w = body.quaternion.w; + } + } + getRadius(impostor) { + const shape = impostor.physicsBody.shapes[0]; + return shape.boundingSphereRadius; + } + getBoxSizeToRef(impostor, result) { + const shape = impostor.physicsBody.shapes[0]; + result.x = shape.halfExtents.x * 2; + result.y = shape.halfExtents.y * 2; + result.z = shape.halfExtents.z * 2; + } + dispose() { } + _extendNamespace() { + //this will force cannon to execute at least one step when using interpolation + const step_tmp1 = new this.BJSCANNON.Vec3(); + const engine = this.BJSCANNON; + this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) { + maxSubSteps = maxSubSteps || 10; + timeSinceLastCalled = timeSinceLastCalled || 0; + if (timeSinceLastCalled === 0) { + this.internalStep(dt); + this.time += dt; + } + else { + let internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt); + internalSteps = Math.min(internalSteps, maxSubSteps) || 1; + const t0 = performance.now(); + for (let i = 0; i !== internalSteps; i++) { + this.internalStep(dt); + if (performance.now() - t0 > dt * 1000) { + break; + } + } + this.time += timeSinceLastCalled; + const h = this.time % dt; + const h_div_dt = h / dt; + const interpvelo = step_tmp1; + const bodies = this.bodies; + for (let j = 0; j !== bodies.length; j++) { + const b = bodies[j]; + if (b.type !== engine.Body.STATIC && b.sleepState !== engine.Body.SLEEPING) { + b.position.vsub(b.previousPosition, interpvelo); + interpvelo.scale(h_div_dt, interpvelo); + b.position.vadd(interpvelo, b.interpolatedPosition); + } + else { + b.interpolatedPosition.set(b.position.x, b.position.y, b.position.z); + b.interpolatedQuaternion.set(b.quaternion.x, b.quaternion.y, b.quaternion.z, b.quaternion.w); + } + } + } + }; + } + /** + * Does a raycast in the physics world + * @param from when should the ray start? + * @param to when should the ray end? + * @returns PhysicsRaycastResult + */ + raycast(from, to) { + this._raycastResult.reset(from, to); + this.raycastToRef(from, to, this._raycastResult); + return this._raycastResult; + } + /** + * Does a raycast in the physics world + * @param from when should the ray start? + * @param to when should the ray end? + * @param result resulting PhysicsRaycastResult + */ + raycastToRef(from, to, result) { + this._cannonRaycastResult.reset(); + this.world.raycastClosest(from, to, {}, this._cannonRaycastResult); + result.reset(from, to); + if (this._cannonRaycastResult.hasHit) { + // TODO: do we also want to get the body it hit? + result.setHitData({ + x: this._cannonRaycastResult.hitNormalWorld.x, + y: this._cannonRaycastResult.hitNormalWorld.y, + z: this._cannonRaycastResult.hitNormalWorld.z, + }, { + x: this._cannonRaycastResult.hitPointWorld.x, + y: this._cannonRaycastResult.hitPointWorld.y, + z: this._cannonRaycastResult.hitPointWorld.z, + }); + result.setHitDistance(this._cannonRaycastResult.distance); + } + } +} +PhysicsEngine$1.DefaultPluginFactory = () => { + return new CannonJSPlugin(); +}; + +/** @internal */ +class OimoJSPlugin { + constructor(_useDeltaForWorldStep = true, iterations, oimoInjection = OIMO) { + this._useDeltaForWorldStep = _useDeltaForWorldStep; + this.name = "OimoJSPlugin"; + this._fixedTimeStep = 1 / 60; + this._tmpImpostorsArray = []; + this._tmpPositionVector = Vector3.Zero(); + this.BJSOIMO = oimoInjection; + this.world = new this.BJSOIMO.World({ + iterations: iterations, + }); + this.world.clear(); + this._raycastResult = new PhysicsRaycastResult(); + } + /** + * + * @returns plugin version + */ + getPluginVersion() { + return 1; + } + setGravity(gravity) { + this.world.gravity.set(gravity.x, gravity.y, gravity.z); + } + setTimeStep(timeStep) { + this.world.timeStep = timeStep; + } + getTimeStep() { + return this.world.timeStep; + } + executeStep(delta, impostors) { + impostors.forEach(function (impostor) { + impostor.beforeStep(); + }); + this.world.timeStep = this._useDeltaForWorldStep ? delta : this._fixedTimeStep; + this.world.step(); + impostors.forEach((impostor) => { + impostor.afterStep(); + //update the ordered impostors array + this._tmpImpostorsArray[impostor.uniqueId] = impostor; + }); + //check for collisions + let contact = this.world.contacts; + while (contact !== null) { + if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) { + contact = contact.next; + continue; + } + //is this body colliding with any other? get the impostor + const mainImpostor = this._tmpImpostorsArray[+contact.body1.name]; + const collidingImpostor = this._tmpImpostorsArray[+contact.body2.name]; + if (!mainImpostor || !collidingImpostor) { + contact = contact.next; + continue; + } + mainImpostor.onCollide({ body: collidingImpostor.physicsBody, point: null, distance: 0, impulse: 0, normal: null }); + collidingImpostor.onCollide({ body: mainImpostor.physicsBody, point: null, distance: 0, impulse: 0, normal: null }); + contact = contact.next; + } + } + applyImpulse(impostor, force, contactPoint) { + const mass = impostor.physicsBody.mass; + impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass)); + } + applyForce(impostor, force, contactPoint) { + Logger.Warn("Oimo doesn't support applying force. Using impulse instead."); + this.applyImpulse(impostor, force, contactPoint); + } + generatePhysicsBody(impostor) { + //parent-child relationship. Does this impostor has a parent impostor? + if (impostor.parent) { + if (impostor.physicsBody) { + this.removePhysicsBody(impostor); + //TODO is that needed? + impostor.forceUpdate(); + } + return; + } + if (impostor.isBodyInitRequired()) { + const bodyConfig = { + name: impostor.uniqueId, + //Oimo must have mass, also for static objects. + config: [impostor.getParam("mass") || 0.001, impostor.getParam("friction"), impostor.getParam("restitution")], + size: [], + type: [], + pos: [], + posShape: [], + rot: [], + rotShape: [], + move: impostor.getParam("mass") !== 0, + density: impostor.getParam("mass"), + friction: impostor.getParam("friction"), + restitution: impostor.getParam("restitution"), + //Supporting older versions of Oimo + world: this.world, + }; + const impostors = [impostor]; + const addToArray = (parent) => { + if (!parent.getChildMeshes) { + return; + } + parent.getChildMeshes().forEach(function (m) { + if (m.physicsImpostor) { + impostors.push(m.physicsImpostor); + //m.physicsImpostor._init(); + } + }); + }; + addToArray(impostor.object); + const checkWithEpsilon = (value) => { + return Math.max(value, Epsilon); + }; + const globalQuaternion = new Quaternion(); + impostors.forEach((i) => { + if (!i.object.rotationQuaternion) { + return; + } + //get the correct bounding box + const oldQuaternion = i.object.rotationQuaternion; + globalQuaternion.copyFrom(oldQuaternion); + i.object.rotationQuaternion.set(0, 0, 0, 1); + i.object.computeWorldMatrix(true); + const rot = globalQuaternion.toEulerAngles(); + const impostorExtents = i.getObjectExtents(); + // eslint-disable-next-line no-loss-of-precision + const radToDeg = 57.295779513082320876; + if (i === impostor) { + const center = impostor.getObjectCenter(); + impostor.object.getAbsolutePivotPoint().subtractToRef(center, this._tmpPositionVector); + this._tmpPositionVector.divideInPlace(impostor.object.scaling); + //Can also use Array.prototype.push.apply + bodyConfig.pos.push(center.x); + bodyConfig.pos.push(center.y); + bodyConfig.pos.push(center.z); + bodyConfig.posShape.push(0, 0, 0); + bodyConfig.rotShape.push(0, 0, 0); + } + else { + const localPosition = i.object.position.clone(); + bodyConfig.posShape.push(localPosition.x); + bodyConfig.posShape.push(localPosition.y); + bodyConfig.posShape.push(localPosition.z); + // bodyConfig.pos.push(0, 0, 0); + bodyConfig.rotShape.push(rot.x * radToDeg, rot.y * radToDeg, rot.z * radToDeg); + } + i.object.rotationQuaternion.copyFrom(globalQuaternion); + // register mesh + switch (i.type) { + case PhysicsImpostor.ParticleImpostor: + Logger.Warn("No Particle support in OIMO.js. using SphereImpostor instead"); + // eslint-disable-next-line no-fallthrough + case PhysicsImpostor.SphereImpostor: { + const radiusX = impostorExtents.x; + const radiusY = impostorExtents.y; + const radiusZ = impostorExtents.z; + const size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2; + bodyConfig.type.push("sphere"); + //due to the way oimo works with compounds, add 3 times + bodyConfig.size.push(size); + bodyConfig.size.push(size); + bodyConfig.size.push(size); + break; + } + case PhysicsImpostor.CylinderImpostor: { + const sizeX = checkWithEpsilon(impostorExtents.x) / 2; + const sizeY = checkWithEpsilon(impostorExtents.y); + bodyConfig.type.push("cylinder"); + bodyConfig.size.push(sizeX); + bodyConfig.size.push(sizeY); + //due to the way oimo works with compounds, add one more value. + bodyConfig.size.push(sizeY); + break; + } + case PhysicsImpostor.PlaneImpostor: + case PhysicsImpostor.BoxImpostor: + default: { + const sizeX = checkWithEpsilon(impostorExtents.x); + const sizeY = checkWithEpsilon(impostorExtents.y); + const sizeZ = checkWithEpsilon(impostorExtents.z); + bodyConfig.type.push("box"); + //if (i === impostor) { + bodyConfig.size.push(sizeX); + bodyConfig.size.push(sizeY); + bodyConfig.size.push(sizeZ); + //} else { + // bodyConfig.size.push(0,0,0); + //} + break; + } + } + //actually not needed, but hey... + i.object.rotationQuaternion = oldQuaternion; + }); + impostor.physicsBody = this.world.add(bodyConfig); + // set the quaternion, ignoring the previously defined (euler) rotation + impostor.physicsBody.resetQuaternion(globalQuaternion); + // update with delta 0, so the body will receive the new rotation. + impostor.physicsBody.updatePosition(0); + } + else { + this._tmpPositionVector.copyFromFloats(0, 0, 0); + } + impostor.setDeltaPosition(this._tmpPositionVector); + //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center); + //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion); + } + removePhysicsBody(impostor) { + //impostor.physicsBody.dispose(); + this.world.removeRigidBody(impostor.physicsBody); + } + generateJoint(impostorJoint) { + const mainBody = impostorJoint.mainImpostor.physicsBody; + const connectedBody = impostorJoint.connectedImpostor.physicsBody; + if (!mainBody || !connectedBody) { + return; + } + const jointData = impostorJoint.joint.jointData; + const options = jointData.nativeParams || {}; + let type; + const nativeJointData = { + body1: mainBody, + body2: connectedBody, + axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null), + axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null), + pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null), + pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null), + min: options.min, + max: options.max, + collision: options.collision || jointData.collision, + spring: options.spring, + //supporting older version of Oimo + world: this.world, + }; + switch (impostorJoint.joint.type) { + case PhysicsJoint.BallAndSocketJoint: + type = "jointBall"; + break; + case PhysicsJoint.SpringJoint: { + Logger.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead"); + const springData = jointData; + nativeJointData.min = springData.length || nativeJointData.min; + //Max should also be set, just make sure it is at least min + nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max); + } + // eslint-disable-next-line no-fallthrough + case PhysicsJoint.DistanceJoint: + type = "jointDistance"; + nativeJointData.max = jointData.maxDistance; + break; + case PhysicsJoint.PrismaticJoint: + type = "jointPrisme"; + break; + case PhysicsJoint.SliderJoint: + type = "jointSlide"; + break; + case PhysicsJoint.WheelJoint: + type = "jointWheel"; + break; + case PhysicsJoint.HingeJoint: + default: + type = "jointHinge"; + break; + } + nativeJointData.type = type; + impostorJoint.joint.physicsJoint = this.world.add(nativeJointData); + } + removeJoint(impostorJoint) { + //Bug in Oimo prevents us from disposing a joint in the playground + //joint.joint.physicsJoint.dispose(); + //So we will bruteforce it! + try { + this.world.removeJoint(impostorJoint.joint.physicsJoint); + } + catch (e) { + Logger.Warn(e); + } + } + isSupported() { + return this.BJSOIMO !== undefined; + } + setTransformationFromPhysicsBody(impostor) { + if (!impostor.physicsBody.sleeping) { + if (impostor.physicsBody.shapes.next) { + let parent = impostor.physicsBody.shapes; + while (parent.next) { + parent = parent.next; + } + impostor.object.position.set(parent.position.x, parent.position.y, parent.position.z); + } + else { + const pos = impostor.physicsBody.getPosition(); + impostor.object.position.set(pos.x, pos.y, pos.z); + } + if (impostor.object.rotationQuaternion) { + const quat = impostor.physicsBody.getQuaternion(); + impostor.object.rotationQuaternion.set(quat.x, quat.y, quat.z, quat.w); + } + } + } + setPhysicsBodyTransformation(impostor, newPosition, newRotation) { + const body = impostor.physicsBody; + // disable bidirectional for compound meshes + if (impostor.physicsBody.shapes.next) { + return; + } + body.position.set(newPosition.x, newPosition.y, newPosition.z); + body.orientation.set(newRotation.x, newRotation.y, newRotation.z, newRotation.w); + body.syncShapes(); + body.awake(); + } + /*private _getLastShape(body: any): any { + var lastShape = body.shapes; + while (lastShape.next) { + lastShape = lastShape.next; + } + return lastShape; + }*/ + setLinearVelocity(impostor, velocity) { + impostor.physicsBody.linearVelocity.set(velocity.x, velocity.y, velocity.z); + } + setAngularVelocity(impostor, velocity) { + impostor.physicsBody.angularVelocity.set(velocity.x, velocity.y, velocity.z); + } + getLinearVelocity(impostor) { + const v = impostor.physicsBody.linearVelocity; + if (!v) { + return null; + } + return new Vector3(v.x, v.y, v.z); + } + getAngularVelocity(impostor) { + const v = impostor.physicsBody.angularVelocity; + if (!v) { + return null; + } + return new Vector3(v.x, v.y, v.z); + } + setBodyMass(impostor, mass) { + const staticBody = mass === 0; + //this will actually set the body's density and not its mass. + //But this is how oimo treats the mass variable. + impostor.physicsBody.shapes.density = staticBody ? 1 : mass; + impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1); + } + getBodyMass(impostor) { + return impostor.physicsBody.shapes.density; + } + getBodyFriction(impostor) { + return impostor.physicsBody.shapes.friction; + } + setBodyFriction(impostor, friction) { + impostor.physicsBody.shapes.friction = friction; + } + getBodyRestitution(impostor) { + return impostor.physicsBody.shapes.restitution; + } + setBodyRestitution(impostor, restitution) { + impostor.physicsBody.shapes.restitution = restitution; + } + sleepBody(impostor) { + impostor.physicsBody.sleep(); + } + wakeUpBody(impostor) { + impostor.physicsBody.awake(); + } + updateDistanceJoint(joint, maxDistance, minDistance) { + joint.physicsJoint.limitMotor.upperLimit = maxDistance; + if (minDistance !== void 0) { + joint.physicsJoint.limitMotor.lowerLimit = minDistance; + } + } + setMotor(joint, speed, force, motorIndex) { + if (force !== undefined) { + Logger.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"); + } + else { + force = 1e6; + } + speed *= -1; + //TODO separate rotational and transational motors. + const motor = motorIndex + ? joint.physicsJoint.rotationalLimitMotor2 + : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor; + if (motor) { + motor.setMotor(speed, force); + } + } + setLimit(joint, upperLimit, lowerLimit, motorIndex) { + //TODO separate rotational and transational motors. + const motor = motorIndex + ? joint.physicsJoint.rotationalLimitMotor2 + : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor; + if (motor) { + motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit); + } + } + syncMeshWithImpostor(mesh, impostor) { + const body = impostor.physicsBody; + mesh.position.x = body.position.x; + mesh.position.y = body.position.y; + mesh.position.z = body.position.z; + if (mesh.rotationQuaternion) { + mesh.rotationQuaternion.x = body.orientation.x; + mesh.rotationQuaternion.y = body.orientation.y; + mesh.rotationQuaternion.z = body.orientation.z; + mesh.rotationQuaternion.w = body.orientation.w; + } + } + getRadius(impostor) { + return impostor.physicsBody.shapes.radius; + } + getBoxSizeToRef(impostor, result) { + const shape = impostor.physicsBody.shapes; + result.x = shape.halfWidth * 2; + result.y = shape.halfHeight * 2; + result.z = shape.halfDepth * 2; + } + dispose() { + this.world.clear(); + } + /** + * Does a raycast in the physics world + * @param from when should the ray start? + * @param to when should the ray end? + * @returns PhysicsRaycastResult + */ + raycast(from, to) { + Logger.Warn("raycast is not currently supported by the Oimo physics plugin"); + this._raycastResult.reset(from, to); + return this._raycastResult; + } + /** + * Does a raycast in the physics world + * @param from when should the ray start? + * @param to when should the ray end? + * @param result resulting PhysicsRaycastResult + */ + raycastToRef(from, to, result) { + Logger.Warn("raycast is not currently supported by the Oimo physics plugin"); + result.reset(from, to); + } +} + +/** + * AmmoJS Physics plugin + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine + * @see https://github.com/kripken/ammo.js/ + */ +class AmmoJSPlugin { + /** + * Initializes the ammoJS plugin + * @param _useDeltaForWorldStep if the time between frames should be used when calculating physics steps (Default: true) + * @param ammoInjection can be used to inject your own ammo reference + * @param overlappingPairCache can be used to specify your own overlapping pair cache + */ + constructor(_useDeltaForWorldStep = true, ammoInjection = Ammo, overlappingPairCache = null) { + this._useDeltaForWorldStep = _useDeltaForWorldStep; + /** + * Reference to the Ammo library + */ + this.bjsAMMO = {}; + /** + * Name of the plugin + */ + this.name = "AmmoJSPlugin"; + this._timeStep = 1 / 60; + this._fixedTimeStep = 1 / 60; + this._maxSteps = 5; + this._tmpQuaternion = new Quaternion(); + this._tmpContactCallbackResult = false; + this._tmpContactPoint = new Vector3(); + this._tmpContactNormal = new Vector3(); + this._tmpVec3 = new Vector3(); + this._tmpMatrix = new Matrix(); + if (typeof ammoInjection === "function") { + Logger.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin."); + return; + } + else { + this.bjsAMMO = ammoInjection; + } + if (!this.isSupported()) { + Logger.Error("AmmoJS is not available. Please make sure you included the js file."); + return; + } + // Initialize the physics world + this._collisionConfiguration = new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration(); + this._dispatcher = new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration); + this._overlappingPairCache = overlappingPairCache || new this.bjsAMMO.btDbvtBroadphase(); + this._solver = new this.bjsAMMO.btSequentialImpulseConstraintSolver(); + this._softBodySolver = new this.bjsAMMO.btDefaultSoftBodySolver(); + this.world = new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher, this._overlappingPairCache, this._solver, this._collisionConfiguration, this._softBodySolver); + this._tmpAmmoConcreteContactResultCallback = new this.bjsAMMO.ConcreteContactResultCallback(); + this._tmpAmmoConcreteContactResultCallback.addSingleResult = (contactPoint) => { + contactPoint = this.bjsAMMO.wrapPointer(contactPoint, this.bjsAMMO.btManifoldPoint); + const worldPoint = contactPoint.getPositionWorldOnA(); + const worldNormal = contactPoint.m_normalWorldOnB; + this._tmpContactPoint.x = worldPoint.x(); + this._tmpContactPoint.y = worldPoint.y(); + this._tmpContactPoint.z = worldPoint.z(); + this._tmpContactNormal.x = worldNormal.x(); + this._tmpContactNormal.y = worldNormal.y(); + this._tmpContactNormal.z = worldNormal.z(); + this._tmpContactImpulse = contactPoint.getAppliedImpulse(); + this._tmpContactDistance = contactPoint.getDistance(); + this._tmpContactCallbackResult = true; + }; + this._raycastResult = new PhysicsRaycastResult(); + // Create temp ammo variables + this._tmpAmmoTransform = new this.bjsAMMO.btTransform(); + this._tmpAmmoTransform.setIdentity(); + this._tmpAmmoQuaternion = new this.bjsAMMO.btQuaternion(0, 0, 0, 1); + this._tmpAmmoVectorA = new this.bjsAMMO.btVector3(0, 0, 0); + this._tmpAmmoVectorB = new this.bjsAMMO.btVector3(0, 0, 0); + this._tmpAmmoVectorC = new this.bjsAMMO.btVector3(0, 0, 0); + this._tmpAmmoVectorD = new this.bjsAMMO.btVector3(0, 0, 0); + } + /** + * + * @returns plugin version + */ + getPluginVersion() { + return 1; + } + /** + * Sets the gravity of the physics world (m/(s^2)) + * @param gravity Gravity to set + */ + setGravity(gravity) { + this._tmpAmmoVectorA.setValue(gravity.x, gravity.y, gravity.z); + this.world.setGravity(this._tmpAmmoVectorA); + this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA); + } + /** + * Amount of time to step forward on each frame (only used if useDeltaForWorldStep is false in the constructor) + * @param timeStep timestep to use in seconds + */ + setTimeStep(timeStep) { + this._timeStep = timeStep; + } + /** + * Increment to step forward in the physics engine (If timeStep is set to 1/60 and fixedTimeStep is set to 1/120 the physics engine should run 2 steps per frame) (Default: 1/60) + * @param fixedTimeStep fixedTimeStep to use in seconds + */ + setFixedTimeStep(fixedTimeStep) { + this._fixedTimeStep = fixedTimeStep; + } + /** + * Sets the maximum number of steps by the physics engine per frame (Default: 5) + * @param maxSteps the maximum number of steps by the physics engine per frame + */ + setMaxSteps(maxSteps) { + this._maxSteps = maxSteps; + } + /** + * Gets the current timestep (only used if useDeltaForWorldStep is false in the constructor) + * @returns the current timestep in seconds + */ + getTimeStep() { + return this._timeStep; + } + // Ammo's contactTest and contactPairTest take a callback that runs synchronously, wrap them so that they are easier to consume + _isImpostorInContact(impostor) { + this._tmpContactCallbackResult = false; + this.world.contactTest(impostor.physicsBody, this._tmpAmmoConcreteContactResultCallback); + return this._tmpContactCallbackResult; + } + // Ammo's collision events have some weird quirks + // contactPairTest fires too many events as it fires events even when objects are close together but contactTest does not + // so only fire event if both contactTest and contactPairTest have a hit + _isImpostorPairInContact(impostorA, impostorB) { + this._tmpContactCallbackResult = false; + this.world.contactPairTest(impostorA.physicsBody, impostorB.physicsBody, this._tmpAmmoConcreteContactResultCallback); + return this._tmpContactCallbackResult; + } + // Ammo's behavior when maxSteps > 0 does not behave as described in docs + // @see http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World + // + // When maxSteps is 0 do the entire simulation in one step + // When maxSteps is > 0, run up to maxStep times, if on the last step the (remaining step - fixedTimeStep) is < fixedTimeStep, the remainder will be used for the step. (eg. if remainder is 1.001 and fixedTimeStep is 1 the last step will be 1.001, if instead it did 2 steps (1, 0.001) issues occuered when having a tiny step in ammo) + // Note: To get deterministic physics, timeStep would always need to be divisible by fixedTimeStep + _stepSimulation(timeStep = 1 / 60, maxSteps = 10, fixedTimeStep = 1 / 60) { + if (maxSteps == 0) { + this.world.stepSimulation(timeStep, 0); + } + else { + while (maxSteps > 0 && timeStep > 0) { + if (timeStep - fixedTimeStep < fixedTimeStep) { + this.world.stepSimulation(timeStep, 0); + timeStep = 0; + } + else { + timeStep -= fixedTimeStep; + this.world.stepSimulation(fixedTimeStep, 0); + } + maxSteps--; + } + } + } + /** + * Moves the physics simulation forward delta seconds and updates the given physics imposters + * Prior to the step the imposters physics location is set to the position of the babylon meshes + * After the step the babylon meshes are set to the position of the physics imposters + * @param delta amount of time to step forward + * @param impostors array of imposters to update before/after the step + */ + executeStep(delta, impostors) { + for (const impostor of impostors) { + // Update physics world objects to match babylon world + if (!impostor.soft) { + impostor.beforeStep(); + } + } + this._stepSimulation(this._useDeltaForWorldStep ? delta : this._timeStep, this._maxSteps, this._fixedTimeStep); + for (const mainImpostor of impostors) { + // After physics update make babylon world objects match physics world objects + if (mainImpostor.soft) { + this._afterSoftStep(mainImpostor); + } + else { + mainImpostor.afterStep(); + } + // Handle collision event + if (mainImpostor._onPhysicsCollideCallbacks.length > 0) { + if (this._isImpostorInContact(mainImpostor)) { + for (const collideCallback of mainImpostor._onPhysicsCollideCallbacks) { + for (const otherImpostor of collideCallback.otherImpostors) { + if (mainImpostor.physicsBody.isActive() || otherImpostor.physicsBody.isActive()) { + if (this._isImpostorPairInContact(mainImpostor, otherImpostor)) { + mainImpostor.onCollide({ + body: otherImpostor.physicsBody, + point: this._tmpContactPoint, + distance: this._tmpContactDistance, + impulse: this._tmpContactImpulse, + normal: this._tmpContactNormal, + }); + otherImpostor.onCollide({ + body: mainImpostor.physicsBody, + point: this._tmpContactPoint, + distance: this._tmpContactDistance, + impulse: this._tmpContactImpulse, + normal: this._tmpContactNormal, + }); + } + } + } + } + } + } + } + } + /** + * Update babylon mesh to match physics world object + * @param impostor imposter to match + */ + _afterSoftStep(impostor) { + if (impostor.type === PhysicsImpostor.RopeImpostor) { + this._ropeStep(impostor); + } + else { + this._softbodyOrClothStep(impostor); + } + } + /** + * Update babylon mesh vertices vertices to match physics world softbody or cloth + * @param impostor imposter to match + */ + _ropeStep(impostor) { + const bodyVertices = impostor.physicsBody.get_m_nodes(); + const nbVertices = bodyVertices.size(); + let node; + let nodePositions; + let x, y, z; + const path = new Array(); + for (let n = 0; n < nbVertices; n++) { + node = bodyVertices.at(n); + nodePositions = node.get_m_x(); + x = nodePositions.x(); + y = nodePositions.y(); + z = nodePositions.z(); + path.push(new Vector3(x, y, z)); + } + const object = impostor.object; + const shape = impostor.getParam("shape"); + if (impostor._isFromLine) { + impostor.object = CreateLines("lines", { points: path, instance: object }); + } + else { + impostor.object = ExtrudeShape("ext", { shape: shape, path: path, instance: object }); + } + } + /** + * Update babylon mesh vertices vertices to match physics world softbody or cloth + * @param impostor imposter to match + */ + _softbodyOrClothStep(impostor) { + const normalDirection = impostor.type === PhysicsImpostor.ClothImpostor ? 1 : -1; + const object = impostor.object; + let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind); + if (!vertexPositions) { + vertexPositions = []; + } + let vertexNormals = object.getVerticesData(VertexBuffer.NormalKind); + if (!vertexNormals) { + vertexNormals = []; + } + const nbVertices = vertexPositions.length / 3; + const bodyVertices = impostor.physicsBody.get_m_nodes(); + let node; + let nodePositions; + let x, y, z; + let nx, ny, nz; + for (let n = 0; n < nbVertices; n++) { + node = bodyVertices.at(n); + nodePositions = node.get_m_x(); + x = nodePositions.x(); + y = nodePositions.y(); + z = nodePositions.z() * normalDirection; + const nodeNormals = node.get_m_n(); + nx = nodeNormals.x(); + ny = nodeNormals.y(); + nz = nodeNormals.z() * normalDirection; + vertexPositions[3 * n] = x; + vertexPositions[3 * n + 1] = y; + vertexPositions[3 * n + 2] = z; + vertexNormals[3 * n] = nx; + vertexNormals[3 * n + 1] = ny; + vertexNormals[3 * n + 2] = nz; + } + const vertex_data = new VertexData(); + vertex_data.positions = vertexPositions; + vertex_data.normals = vertexNormals; + vertex_data.uvs = object.getVerticesData(VertexBuffer.UVKind); + vertex_data.colors = object.getVerticesData(VertexBuffer.ColorKind); + if (object && object.getIndices) { + vertex_data.indices = object.getIndices(); + } + vertex_data.applyToMesh(object); + } + /** + * Applies an impulse on the imposter + * @param impostor imposter to apply impulse to + * @param force amount of force to be applied to the imposter + * @param contactPoint the location to apply the impulse on the imposter + */ + applyImpulse(impostor, force, contactPoint) { + if (!impostor.soft) { + impostor.physicsBody.activate(); + const worldPoint = this._tmpAmmoVectorA; + const impulse = this._tmpAmmoVectorB; + // Convert contactPoint relative to center of mass + if (impostor.object && impostor.object.getWorldMatrix) { + contactPoint.subtractInPlace(impostor.object.getWorldMatrix().getTranslation()); + } + worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z); + impulse.setValue(force.x, force.y, force.z); + impostor.physicsBody.applyImpulse(impulse, worldPoint); + } + else { + Logger.Warn("Cannot be applied to a soft body"); + } + } + /** + * Applies a force on the imposter + * @param impostor imposter to apply force + * @param force amount of force to be applied to the imposter + * @param contactPoint the location to apply the force on the imposter + */ + applyForce(impostor, force, contactPoint) { + if (!impostor.soft) { + impostor.physicsBody.activate(); + const worldPoint = this._tmpAmmoVectorA; + const impulse = this._tmpAmmoVectorB; + // Convert contactPoint relative to center of mass + if (impostor.object && impostor.object.getWorldMatrix) { + const localTranslation = impostor.object.getWorldMatrix().getTranslation(); + worldPoint.setValue(contactPoint.x - localTranslation.x, contactPoint.y - localTranslation.y, contactPoint.z - localTranslation.z); + } + else { + worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z); + } + impulse.setValue(force.x, force.y, force.z); + impostor.physicsBody.applyForce(impulse, worldPoint); + } + else { + Logger.Warn("Cannot be applied to a soft body"); + } + } + /** + * Creates a physics body using the plugin + * @param impostor the imposter to create the physics body on + */ + generatePhysicsBody(impostor) { + // Note: this method will not be called on child imposotrs for compound impostors + impostor._pluginData.toDispose = []; + //parent-child relationship + if (impostor.parent) { + if (impostor.physicsBody) { + this.removePhysicsBody(impostor); + impostor.forceUpdate(); + } + return; + } + if (impostor.isBodyInitRequired()) { + const colShape = this._createShape(impostor); + const mass = impostor.getParam("mass"); + impostor._pluginData.mass = mass; + if (impostor.soft) { + colShape.get_m_cfg().set_collisions(0x11); + colShape.get_m_cfg().set_kDP(impostor.getParam("damping")); + this.bjsAMMO.castObject(colShape, this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(impostor.getParam("margin")); + colShape.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG); + this.world.addSoftBody(colShape, 1, -1); + impostor.physicsBody = colShape; + impostor._pluginData.toDispose.push(colShape); + this.setBodyPressure(impostor, 0); + if (impostor.type === PhysicsImpostor.SoftbodyImpostor) { + this.setBodyPressure(impostor, impostor.getParam("pressure")); + } + this.setBodyStiffness(impostor, impostor.getParam("stiffness")); + this.setBodyVelocityIterations(impostor, impostor.getParam("velocityIterations")); + this.setBodyPositionIterations(impostor, impostor.getParam("positionIterations")); + } + else { + const localInertia = new this.bjsAMMO.btVector3(0, 0, 0); + const startTransform = new this.bjsAMMO.btTransform(); + impostor.object.computeWorldMatrix(true); + startTransform.setIdentity(); + if (mass !== 0) { + colShape.calculateLocalInertia(mass, localInertia); + } + this._tmpAmmoVectorA.setValue(impostor.object.position.x, impostor.object.position.y, impostor.object.position.z); + this._tmpAmmoQuaternion.setValue(impostor.object.rotationQuaternion.x, impostor.object.rotationQuaternion.y, impostor.object.rotationQuaternion.z, impostor.object.rotationQuaternion.w); + startTransform.setOrigin(this._tmpAmmoVectorA); + startTransform.setRotation(this._tmpAmmoQuaternion); + const myMotionState = new this.bjsAMMO.btDefaultMotionState(startTransform); + const rbInfo = new this.bjsAMMO.btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia); + const body = new this.bjsAMMO.btRigidBody(rbInfo); + // Make objects kinematic if it's mass is 0 + if (mass === 0) { + body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin._KINEMATIC_FLAG); + body.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG); + } + // Disable collision if NoImpostor, but keep collision if shape is btCompoundShape + if (impostor.type == PhysicsImpostor.NoImpostor && !colShape.getChildShape) { + body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin._DISABLE_COLLISION_FLAG); + } + // compute delta position: compensate the difference between shape center and mesh origin + if (impostor.type !== PhysicsImpostor.MeshImpostor && impostor.type !== PhysicsImpostor.NoImpostor) { + const boundingInfo = impostor.object.getBoundingInfo(); + this._tmpVec3.copyFrom(impostor.object.getAbsolutePosition()); + this._tmpVec3.subtractInPlace(boundingInfo.boundingBox.centerWorld); + this._tmpVec3.x /= impostor.object.scaling.x; + this._tmpVec3.y /= impostor.object.scaling.y; + this._tmpVec3.z /= impostor.object.scaling.z; + impostor.setDeltaPosition(this._tmpVec3); + } + const group = impostor.getParam("group"); + const mask = impostor.getParam("mask"); + if (group && mask) { + this.world.addRigidBody(body, group, mask); + } + else { + this.world.addRigidBody(body); + } + impostor.physicsBody = body; + impostor._pluginData.toDispose = impostor._pluginData.toDispose.concat([body, rbInfo, myMotionState, startTransform, localInertia, colShape]); + } + this.setBodyRestitution(impostor, impostor.getParam("restitution")); + this.setBodyFriction(impostor, impostor.getParam("friction")); + } + } + /** + * Removes the physics body from the imposter and disposes of the body's memory + * @param impostor imposter to remove the physics body from + */ + removePhysicsBody(impostor) { + if (this.world) { + if (impostor.soft) { + this.world.removeSoftBody(impostor.physicsBody); + } + else { + this.world.removeRigidBody(impostor.physicsBody); + } + if (impostor._pluginData) { + impostor._pluginData.toDispose.forEach((d) => { + this.bjsAMMO.destroy(d); + }); + impostor._pluginData.toDispose = []; + } + } + } + /** + * Generates a joint + * @param impostorJoint the imposter joint to create the joint with + */ + generateJoint(impostorJoint) { + const mainBody = impostorJoint.mainImpostor.physicsBody; + const connectedBody = impostorJoint.connectedImpostor.physicsBody; + if (!mainBody || !connectedBody) { + return; + } + // if the joint is already created, don't create it again for preventing memory leaks + if (impostorJoint.joint.physicsJoint) { + return; + } + const jointData = impostorJoint.joint.jointData; + if (!jointData.mainPivot) { + jointData.mainPivot = new Vector3(0, 0, 0); + } + if (!jointData.connectedPivot) { + jointData.connectedPivot = new Vector3(0, 0, 0); + } + let joint; + switch (impostorJoint.joint.type) { + case PhysicsJoint.DistanceJoint: { + const distance = jointData.maxDistance; + if (distance) { + jointData.mainPivot = new Vector3(0, -distance / 2, 0); + jointData.connectedPivot = new Vector3(0, distance / 2, 0); + } + const mainPivot = this._tmpAmmoVectorA; + mainPivot.setValue(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z); + const connectedPivot = this._tmpAmmoVectorB; + connectedPivot.setValue(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z); + joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, mainPivot, connectedPivot); + break; + } + case PhysicsJoint.HingeJoint: { + if (!jointData.mainAxis) { + jointData.mainAxis = new Vector3(0, 0, 0); + } + if (!jointData.connectedAxis) { + jointData.connectedAxis = new Vector3(0, 0, 0); + } + const mainPivot = this._tmpAmmoVectorA; + mainPivot.setValue(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z); + const connectedPivot = this._tmpAmmoVectorB; + connectedPivot.setValue(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z); + const mainAxis = this._tmpAmmoVectorC; + mainAxis.setValue(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z); + const connectedAxis = this._tmpAmmoVectorD; + connectedAxis.setValue(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z); + joint = new this.bjsAMMO.btHingeConstraint(mainBody, connectedBody, mainPivot, connectedPivot, mainAxis, connectedAxis); + break; + } + case PhysicsJoint.BallAndSocketJoint: { + const mainPivot = this._tmpAmmoVectorA; + mainPivot.setValue(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z); + const connectedPivot = this._tmpAmmoVectorB; + connectedPivot.setValue(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z); + joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, mainPivot, connectedPivot); + break; + } + default: { + Logger.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"); + const mainPivot = this._tmpAmmoVectorA; + mainPivot.setValue(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z); + const connectedPivot = this._tmpAmmoVectorB; + connectedPivot.setValue(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z); + joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, mainPivot, connectedPivot); + break; + } + } + this.world.addConstraint(joint, !impostorJoint.joint.jointData.collision); + impostorJoint.joint.physicsJoint = joint; + } + /** + * Removes a joint + * @param impostorJoint the imposter joint to remove the joint from + */ + removeJoint(impostorJoint) { + if (this.world) { + this.world.removeConstraint(impostorJoint.joint.physicsJoint); + } + this.bjsAMMO.destroy(impostorJoint.joint.physicsJoint); + } + // adds all verticies (including child verticies) to the triangle mesh + _addMeshVerts(btTriangleMesh, topLevelObject, object) { + let triangleCount = 0; + if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) { + let indices = object.getIndices(); + if (!indices) { + indices = []; + } + let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind); + if (!vertexPositions) { + vertexPositions = []; + } + let localMatrix; + if (topLevelObject && topLevelObject !== object) { + // top level matrix used for shape transform doesn't take scale into account. + // Moreover, every children vertex position must be in that space. + // So, each vertex position here is transform by (mesh world matrix * toplevelMatrix -1) + let topLevelQuaternion; + if (topLevelObject.rotationQuaternion) { + topLevelQuaternion = topLevelObject.rotationQuaternion; + } + else if (topLevelObject.rotation) { + topLevelQuaternion = Quaternion.FromEulerAngles(topLevelObject.rotation.x, topLevelObject.rotation.y, topLevelObject.rotation.z); + } + else { + topLevelQuaternion = Quaternion.Identity(); + } + const topLevelMatrix = Matrix.Compose(Vector3.One(), topLevelQuaternion, topLevelObject.position); + topLevelMatrix.invertToRef(this._tmpMatrix); + const wm = object.computeWorldMatrix(false); + localMatrix = wm.multiply(this._tmpMatrix); + } + else { + // current top level is same as object level -> only use local scaling + Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix); + localMatrix = this._tmpMatrix; + } + const faceCount = indices.length / 3; + for (let i = 0; i < faceCount; i++) { + const triPoints = []; + for (let point = 0; point < 3; point++) { + let v = new Vector3(vertexPositions[indices[i * 3 + point] * 3 + 0], vertexPositions[indices[i * 3 + point] * 3 + 1], vertexPositions[indices[i * 3 + point] * 3 + 2]); + v = Vector3.TransformCoordinates(v, localMatrix); + let vec; + if (point == 0) { + vec = this._tmpAmmoVectorA; + } + else if (point == 1) { + vec = this._tmpAmmoVectorB; + } + else { + vec = this._tmpAmmoVectorC; + } + vec.setValue(v.x, v.y, v.z); + triPoints.push(vec); + } + btTriangleMesh.addTriangle(triPoints[0], triPoints[1], triPoints[2]); + triangleCount++; + } + object.getChildMeshes().forEach((m) => { + triangleCount += this._addMeshVerts(btTriangleMesh, topLevelObject, m); + }); + } + return triangleCount; + } + /** + * Initialise the soft body vertices to match its object's (mesh) vertices + * Softbody vertices (nodes) are in world space and to match this + * The object's position and rotation is set to zero and so its vertices are also then set in world space + * @param impostor to create the softbody for + * @returns the number of vertices added to the softbody + */ + _softVertexData(impostor) { + const object = impostor.object; + if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) { + object.getIndices(); + let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind); + if (!vertexPositions) { + vertexPositions = []; + } + let vertexNormals = object.getVerticesData(VertexBuffer.NormalKind); + if (!vertexNormals) { + vertexNormals = []; + } + object.computeWorldMatrix(false); + const newPoints = []; + const newNorms = []; + for (let i = 0; i < vertexPositions.length; i += 3) { + let v = new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]); + let n = new Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]); + v = Vector3.TransformCoordinates(v, object.getWorldMatrix()); + n = Vector3.TransformNormal(n, object.getWorldMatrix()); + newPoints.push(v.x, v.y, v.z); + newNorms.push(n.x, n.y, n.z); + } + const vertex_data = new VertexData(); + vertex_data.positions = newPoints; + vertex_data.normals = newNorms; + vertex_data.uvs = object.getVerticesData(VertexBuffer.UVKind); + vertex_data.colors = object.getVerticesData(VertexBuffer.ColorKind); + if (object && object.getIndices) { + vertex_data.indices = object.getIndices(); + } + vertex_data.applyToMesh(object); + object.position = Vector3.Zero(); + object.rotationQuaternion = null; + object.rotation = Vector3.Zero(); + object.computeWorldMatrix(true); + return vertex_data; + } + return VertexData.ExtractFromMesh(object); + } + /** + * Create an impostor's soft body + * @param impostor to create the softbody for + * @returns the softbody + */ + _createSoftbody(impostor) { + const object = impostor.object; + if (object && object.getIndices) { + let indices = object.getIndices(); + if (!indices) { + indices = []; + } + const vertex_data = this._softVertexData(impostor); + const vertexPositions = vertex_data.positions; + const vertexNormals = vertex_data.normals; + if (vertexPositions === null || vertexNormals === null) { + return new this.bjsAMMO.btCompoundShape(); + } + else { + const triPoints = []; + const triNorms = []; + for (let i = 0; i < vertexPositions.length; i += 3) { + const v = new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]); + const n = new Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]); + triPoints.push(v.x, v.y, -v.z); + triNorms.push(n.x, n.y, -n.z); + } + const softBody = new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(), triPoints, object.getIndices(), indices.length / 3, true); + const nbVertices = vertexPositions.length / 3; + const bodyVertices = softBody.get_m_nodes(); + let node; + let nodeNormals; + for (let i = 0; i < nbVertices; i++) { + node = bodyVertices.at(i); + nodeNormals = node.get_m_n(); + nodeNormals.setX(triNorms[3 * i]); + nodeNormals.setY(triNorms[3 * i + 1]); + nodeNormals.setZ(triNorms[3 * i + 2]); + } + return softBody; + } + } + } + /** + * Create cloth for an impostor + * @param impostor to create the softbody for + * @returns the cloth + */ + _createCloth(impostor) { + const object = impostor.object; + if (object && object.getIndices) { + object.getIndices(); + const vertex_data = this._softVertexData(impostor); + const vertexPositions = vertex_data.positions; + const vertexNormals = vertex_data.normals; + if (vertexPositions === null || vertexNormals === null) { + return new this.bjsAMMO.btCompoundShape(); + } + else { + const len = vertexPositions.length; + const segments = Math.sqrt(len / 3); + impostor.segments = segments; + const segs = segments - 1; + this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]); + this._tmpAmmoVectorB.setValue(vertexPositions[3 * segs], vertexPositions[3 * segs + 1], vertexPositions[3 * segs + 2]); + this._tmpAmmoVectorD.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]); + this._tmpAmmoVectorC.setValue(vertexPositions[len - 3 - 3 * segs], vertexPositions[len - 2 - 3 * segs], vertexPositions[len - 1 - 3 * segs]); + const clothBody = new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, this._tmpAmmoVectorC, this._tmpAmmoVectorD, segments, segments, impostor.getParam("fixedPoints"), true); + return clothBody; + } + } + } + /** + * Create rope for an impostor + * @param impostor to create the softbody for + * @returns the rope + */ + _createRope(impostor) { + let len; + let segments; + const vertex_data = this._softVertexData(impostor); + const vertexPositions = vertex_data.positions; + const vertexNormals = vertex_data.normals; + if (vertexPositions === null || vertexNormals === null) { + return new this.bjsAMMO.btCompoundShape(); + } + //force the mesh to be updatable + vertex_data.applyToMesh(impostor.object, true); + impostor._isFromLine = true; + // If in lines mesh all normals will be zero + const vertexSquared = vertexNormals.map((x) => x * x); + const reducer = (accumulator, currentValue) => accumulator + currentValue; + const reduced = vertexSquared.reduce(reducer); + if (reduced === 0) { + // line mesh + len = vertexPositions.length; + segments = len / 3 - 1; + this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]); + this._tmpAmmoVectorB.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]); + } + else { + //extruded mesh + impostor._isFromLine = false; + const pathVectors = impostor.getParam("path"); + const shape = impostor.getParam("shape"); + if (shape === null) { + Logger.Warn("No shape available for extruded mesh"); + return new this.bjsAMMO.btCompoundShape(); + } + len = pathVectors.length; + segments = len - 1; + this._tmpAmmoVectorA.setValue(pathVectors[0].x, pathVectors[0].y, pathVectors[0].z); + this._tmpAmmoVectorB.setValue(pathVectors[len - 1].x, pathVectors[len - 1].y, pathVectors[len - 1].z); + } + impostor.segments = segments; + let fixedPoints = impostor.getParam("fixedPoints"); + fixedPoints = fixedPoints > 3 ? 3 : fixedPoints; + const ropeBody = new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, segments - 1, fixedPoints); + ropeBody.get_m_cfg().set_collisions(0x11); + return ropeBody; + } + /** + * Create a custom physics impostor shape using the plugin's onCreateCustomShape handler + * @param impostor to create the custom physics shape for + * @returns the custom physics shape + */ + _createCustom(impostor) { + let returnValue = null; + if (this.onCreateCustomShape) { + returnValue = this.onCreateCustomShape(impostor); + } + if (returnValue == null) { + returnValue = new this.bjsAMMO.btCompoundShape(); + } + return returnValue; + } + // adds all verticies (including child verticies) to the convex hull shape + _addHullVerts(btConvexHullShape, topLevelObject, object) { + let triangleCount = 0; + if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) { + let indices = object.getIndices(); + if (!indices) { + indices = []; + } + let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind); + if (!vertexPositions) { + vertexPositions = []; + } + object.computeWorldMatrix(false); + const faceCount = indices.length / 3; + for (let i = 0; i < faceCount; i++) { + const triPoints = []; + for (let point = 0; point < 3; point++) { + let v = new Vector3(vertexPositions[indices[i * 3 + point] * 3 + 0], vertexPositions[indices[i * 3 + point] * 3 + 1], vertexPositions[indices[i * 3 + point] * 3 + 2]); + // Adjust for initial scaling + Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix); + v = Vector3.TransformCoordinates(v, this._tmpMatrix); + let vec; + if (point == 0) { + vec = this._tmpAmmoVectorA; + } + else if (point == 1) { + vec = this._tmpAmmoVectorB; + } + else { + vec = this._tmpAmmoVectorC; + } + vec.setValue(v.x, v.y, v.z); + triPoints.push(vec); + } + btConvexHullShape.addPoint(triPoints[0], true); + btConvexHullShape.addPoint(triPoints[1], true); + btConvexHullShape.addPoint(triPoints[2], true); + triangleCount++; + } + object.getChildMeshes().forEach((m) => { + triangleCount += this._addHullVerts(btConvexHullShape, topLevelObject, m); + }); + } + return triangleCount; + } + _createShape(impostor, ignoreChildren = false) { + const object = impostor.object; + let returnValue; + const impostorExtents = impostor.getObjectExtents(); + if (!ignoreChildren) { + const meshChildren = impostor.object.getChildMeshes ? impostor.object.getChildMeshes(true) : []; + returnValue = new this.bjsAMMO.btCompoundShape(); + // Add shape of all children to the compound shape + let childrenAdded = 0; + meshChildren.forEach((childMesh) => { + const childImpostor = childMesh.getPhysicsImpostor(); + if (childImpostor) { + if (childImpostor.type == PhysicsImpostor.MeshImpostor) { + // eslint-disable-next-line no-throw-literal + throw "A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)"; + } + const shape = this._createShape(childImpostor); + // Position needs to be scaled based on parent's scaling + const parentMat = childMesh.parent.getWorldMatrix().clone(); + const s = new Vector3(); + parentMat.decompose(s); + this._tmpAmmoTransform.getOrigin().setValue(childMesh.position.x * s.x, childMesh.position.y * s.y, childMesh.position.z * s.z); + this._tmpAmmoQuaternion.setValue(childMesh.rotationQuaternion.x, childMesh.rotationQuaternion.y, childMesh.rotationQuaternion.z, childMesh.rotationQuaternion.w); + this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion); + returnValue.addChildShape(this._tmpAmmoTransform, shape); + childImpostor.dispose(); + childrenAdded++; + } + }); + if (childrenAdded > 0) { + // Add parents shape as a child if present + if (impostor.type != PhysicsImpostor.NoImpostor) { + const shape = this._createShape(impostor, true); + if (shape) { + this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0); + this._tmpAmmoQuaternion.setValue(0, 0, 0, 1); + this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion); + returnValue.addChildShape(this._tmpAmmoTransform, shape); + } + } + return returnValue; + } + else { + // If no children with impostors create the actual shape below instead + this.bjsAMMO.destroy(returnValue); + returnValue = null; + } + } + switch (impostor.type) { + case PhysicsImpostor.SphereImpostor: + // Is there a better way to compare floats number? With an epsilon or with a Math function + if (WithinEpsilon(impostorExtents.x, impostorExtents.y, 0.0001) && WithinEpsilon(impostorExtents.x, impostorExtents.z, 0.0001)) { + returnValue = new this.bjsAMMO.btSphereShape(impostorExtents.x / 2); + } + else { + // create a btMultiSphereShape because it's not possible to set a local scaling on a btSphereShape + this._tmpAmmoVectorA.setValue(0, 0, 0); + const positions = [this._tmpAmmoVectorA]; + const radii = [1]; + returnValue = new this.bjsAMMO.btMultiSphereShape(positions, radii, 1); + this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2); + returnValue.setLocalScaling(this._tmpAmmoVectorA); + } + break; + case PhysicsImpostor.CapsuleImpostor: + { + // https://pybullet.org/Bullet/BulletFull/classbtCapsuleShape.html#details + // Height is just the height between the center of each 'sphere' of the capsule caps + const capRadius = impostorExtents.x / 2; + returnValue = new this.bjsAMMO.btCapsuleShape(capRadius, impostorExtents.y - capRadius * 2); + } + break; + case PhysicsImpostor.CylinderImpostor: + this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2); + returnValue = new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA); + break; + case PhysicsImpostor.PlaneImpostor: + case PhysicsImpostor.BoxImpostor: + this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2); + returnValue = new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA); + break; + case PhysicsImpostor.MeshImpostor: { + if (impostor.getParam("mass") == 0) { + // Only create btBvhTriangleMeshShape if the impostor is static + // See https://pybullet.org/Bullet/phpBB3/viewtopic.php?t=7283 + if (this.onCreateCustomMeshImpostor) { + returnValue = this.onCreateCustomMeshImpostor(impostor); + } + else { + const triMesh = new this.bjsAMMO.btTriangleMesh(); + impostor._pluginData.toDispose.push(triMesh); + const triangleCount = this._addMeshVerts(triMesh, object, object); + if (triangleCount == 0) { + returnValue = new this.bjsAMMO.btCompoundShape(); + } + else { + returnValue = new this.bjsAMMO.btBvhTriangleMeshShape(triMesh); + } + } + break; + } + } + // Otherwise create convexHullImpostor + // eslint-disable-next-line no-fallthrough + case PhysicsImpostor.ConvexHullImpostor: { + if (this.onCreateCustomConvexHullImpostor) { + returnValue = this.onCreateCustomConvexHullImpostor(impostor); + } + else { + const convexHull = new this.bjsAMMO.btConvexHullShape(); + const triangleCount = this._addHullVerts(convexHull, object, object); + if (triangleCount == 0) { + // Cleanup Unused Convex Hull Shape + impostor._pluginData.toDispose.push(convexHull); + returnValue = new this.bjsAMMO.btCompoundShape(); + } + else { + returnValue = convexHull; + } + } + break; + } + case PhysicsImpostor.NoImpostor: + // Fill with sphere but collision is disabled on the rigid body in generatePhysicsBody, using an empty shape caused unexpected movement with joints + returnValue = new this.bjsAMMO.btSphereShape(impostorExtents.x / 2); + break; + case PhysicsImpostor.CustomImpostor: + // Only usable when the plugin's onCreateCustomShape is set + returnValue = this._createCustom(impostor); + break; + case PhysicsImpostor.SoftbodyImpostor: + // Only usable with a mesh that has sufficient and shared vertices + returnValue = this._createSoftbody(impostor); + break; + case PhysicsImpostor.ClothImpostor: + // Only usable with a ground mesh that has sufficient and shared vertices + returnValue = this._createCloth(impostor); + break; + case PhysicsImpostor.RopeImpostor: + // Only usable with a line mesh or an extruded mesh that is updatable + returnValue = this._createRope(impostor); + break; + default: + Logger.Warn("The impostor type is not currently supported by the ammo plugin."); + break; + } + return returnValue; + } + /** + * Sets the mesh body position/rotation from the babylon impostor + * @param impostor imposter containing the physics body and babylon object + */ + setTransformationFromPhysicsBody(impostor) { + impostor.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform); + impostor.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z()); + if (!impostor.object.rotationQuaternion) { + if (impostor.object.rotation) { + this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w()); + this._tmpQuaternion.toEulerAnglesToRef(impostor.object.rotation); + } + } + else { + impostor.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w()); + } + } + /** + * Sets the babylon object's position/rotation from the physics body's position/rotation + * @param impostor imposter containing the physics body and babylon object + * @param newPosition new position + * @param newRotation new rotation + */ + setPhysicsBodyTransformation(impostor, newPosition, newRotation) { + const trans = impostor.physicsBody.getWorldTransform(); + // If rotation/position has changed update and activate rigged body + if (Math.abs(trans.getOrigin().x() - newPosition.x) > Epsilon || + Math.abs(trans.getOrigin().y() - newPosition.y) > Epsilon || + Math.abs(trans.getOrigin().z() - newPosition.z) > Epsilon || + Math.abs(trans.getRotation().x() - newRotation.x) > Epsilon || + Math.abs(trans.getRotation().y() - newRotation.y) > Epsilon || + Math.abs(trans.getRotation().z() - newRotation.z) > Epsilon || + Math.abs(trans.getRotation().w() - newRotation.w) > Epsilon) { + this._tmpAmmoVectorA.setValue(newPosition.x, newPosition.y, newPosition.z); + trans.setOrigin(this._tmpAmmoVectorA); + this._tmpAmmoQuaternion.setValue(newRotation.x, newRotation.y, newRotation.z, newRotation.w); + trans.setRotation(this._tmpAmmoQuaternion); + impostor.physicsBody.setWorldTransform(trans); + if (impostor.mass == 0) { + // Kinematic objects must be updated using motion state + const motionState = impostor.physicsBody.getMotionState(); + if (motionState) { + motionState.setWorldTransform(trans); + } + } + else { + impostor.physicsBody.activate(); + } + } + } + /** + * If this plugin is supported + * @returns true if its supported + */ + isSupported() { + return this.bjsAMMO !== undefined; + } + /** + * Sets the linear velocity of the physics body + * @param impostor imposter to set the velocity on + * @param velocity velocity to set + */ + setLinearVelocity(impostor, velocity) { + this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z); + if (impostor.soft) { + impostor.physicsBody.linearVelocity(this._tmpAmmoVectorA); + } + else { + impostor.physicsBody.setLinearVelocity(this._tmpAmmoVectorA); + } + } + /** + * Sets the angular velocity of the physics body + * @param impostor imposter to set the velocity on + * @param velocity velocity to set + */ + setAngularVelocity(impostor, velocity) { + this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z); + if (impostor.soft) { + impostor.physicsBody.angularVelocity(this._tmpAmmoVectorA); + } + else { + impostor.physicsBody.setAngularVelocity(this._tmpAmmoVectorA); + } + } + /** + * gets the linear velocity + * @param impostor imposter to get linear velocity from + * @returns linear velocity + */ + getLinearVelocity(impostor) { + let v; + if (impostor.soft) { + v = impostor.physicsBody.linearVelocity(); + } + else { + v = impostor.physicsBody.getLinearVelocity(); + } + if (!v) { + return null; + } + const result = new Vector3(v.x(), v.y(), v.z()); + this.bjsAMMO.destroy(v); + return result; + } + /** + * gets the angular velocity + * @param impostor imposter to get angular velocity from + * @returns angular velocity + */ + getAngularVelocity(impostor) { + let v; + if (impostor.soft) { + v = impostor.physicsBody.angularVelocity(); + } + else { + v = impostor.physicsBody.getAngularVelocity(); + } + if (!v) { + return null; + } + const result = new Vector3(v.x(), v.y(), v.z()); + this.bjsAMMO.destroy(v); + return result; + } + /** + * Sets the mass of physics body + * @param impostor imposter to set the mass on + * @param mass mass to set + */ + setBodyMass(impostor, mass) { + if (impostor.soft) { + impostor.physicsBody.setTotalMass(mass, false); + } + else { + impostor.physicsBody.setMassProps(mass); + } + impostor._pluginData.mass = mass; + } + /** + * Gets the mass of the physics body + * @param impostor imposter to get the mass from + * @returns mass + */ + getBodyMass(impostor) { + return impostor._pluginData.mass || 0; + } + /** + * Gets friction of the impostor + * @param impostor impostor to get friction from + * @returns friction value + */ + getBodyFriction(impostor) { + return impostor._pluginData.friction || 0; + } + /** + * Sets friction of the impostor + * @param impostor impostor to set friction on + * @param friction friction value + */ + setBodyFriction(impostor, friction) { + if (impostor.soft) { + impostor.physicsBody.get_m_cfg().set_kDF(friction); + } + else { + impostor.physicsBody.setFriction(friction); + } + impostor._pluginData.friction = friction; + } + /** + * Gets restitution of the impostor + * @param impostor impostor to get restitution from + * @returns restitution value + */ + getBodyRestitution(impostor) { + return impostor._pluginData.restitution || 0; + } + /** + * Sets restitution of the impostor + * @param impostor impostor to set resitution on + * @param restitution resitution value + */ + setBodyRestitution(impostor, restitution) { + impostor.physicsBody.setRestitution(restitution); + impostor._pluginData.restitution = restitution; + } + /** + * Gets pressure inside the impostor + * @param impostor impostor to get pressure from + * @returns pressure value + */ + getBodyPressure(impostor) { + if (!impostor.soft) { + Logger.Warn("Pressure is not a property of a rigid body"); + return 0; + } + return impostor._pluginData.pressure || 0; + } + /** + * Sets pressure inside a soft body impostor + * Cloth and rope must remain 0 pressure + * @param impostor impostor to set pressure on + * @param pressure pressure value + */ + setBodyPressure(impostor, pressure) { + if (impostor.soft) { + if (impostor.type === PhysicsImpostor.SoftbodyImpostor) { + impostor.physicsBody.get_m_cfg().set_kPR(pressure); + impostor._pluginData.pressure = pressure; + } + else { + impostor.physicsBody.get_m_cfg().set_kPR(0); + impostor._pluginData.pressure = 0; + } + } + else { + Logger.Warn("Pressure can only be applied to a softbody"); + } + } + /** + * Gets stiffness of the impostor + * @param impostor impostor to get stiffness from + * @returns pressure value + */ + getBodyStiffness(impostor) { + if (!impostor.soft) { + Logger.Warn("Stiffness is not a property of a rigid body"); + return 0; + } + return impostor._pluginData.stiffness || 0; + } + /** + * Sets stiffness of the impostor + * @param impostor impostor to set stiffness on + * @param stiffness stiffness value from 0 to 1 + */ + setBodyStiffness(impostor, stiffness) { + if (impostor.soft) { + stiffness = stiffness < 0 ? 0 : stiffness; + stiffness = stiffness > 1 ? 1 : stiffness; + impostor.physicsBody.get_m_materials().at(0).set_m_kLST(stiffness); + impostor._pluginData.stiffness = stiffness; + } + else { + Logger.Warn("Stiffness cannot be applied to a rigid body"); + } + } + /** + * Gets velocityIterations of the impostor + * @param impostor impostor to get velocity iterations from + * @returns velocityIterations value + */ + getBodyVelocityIterations(impostor) { + if (!impostor.soft) { + Logger.Warn("Velocity iterations is not a property of a rigid body"); + return 0; + } + return impostor._pluginData.velocityIterations || 0; + } + /** + * Sets velocityIterations of the impostor + * @param impostor impostor to set velocity iterations on + * @param velocityIterations velocityIterations value + */ + setBodyVelocityIterations(impostor, velocityIterations) { + if (impostor.soft) { + velocityIterations = velocityIterations < 0 ? 0 : velocityIterations; + impostor.physicsBody.get_m_cfg().set_viterations(velocityIterations); + impostor._pluginData.velocityIterations = velocityIterations; + } + else { + Logger.Warn("Velocity iterations cannot be applied to a rigid body"); + } + } + /** + * Gets positionIterations of the impostor + * @param impostor impostor to get position iterations from + * @returns positionIterations value + */ + getBodyPositionIterations(impostor) { + if (!impostor.soft) { + Logger.Warn("Position iterations is not a property of a rigid body"); + return 0; + } + return impostor._pluginData.positionIterations || 0; + } + /** + * Sets positionIterations of the impostor + * @param impostor impostor to set position on + * @param positionIterations positionIterations value + */ + setBodyPositionIterations(impostor, positionIterations) { + if (impostor.soft) { + positionIterations = positionIterations < 0 ? 0 : positionIterations; + impostor.physicsBody.get_m_cfg().set_piterations(positionIterations); + impostor._pluginData.positionIterations = positionIterations; + } + else { + Logger.Warn("Position iterations cannot be applied to a rigid body"); + } + } + /** + * Append an anchor to a cloth object + * @param impostor is the cloth impostor to add anchor to + * @param otherImpostor is the rigid impostor to anchor to + * @param width ratio across width from 0 to 1 + * @param height ratio up height from 0 to 1 + * @param influence the elasticity between cloth impostor and anchor from 0, very stretchy to 1, little stretch + * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false + */ + appendAnchor(impostor, otherImpostor, width, height, influence = 1, noCollisionBetweenLinkedBodies = false) { + const segs = impostor.segments; + const nbAcross = Math.round((segs - 1) * width); + const nbUp = Math.round((segs - 1) * height); + const nbDown = segs - 1 - nbUp; + const node = nbAcross + segs * nbDown; + impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence); + } + /** + * Append an hook to a rope object + * @param impostor is the rope impostor to add hook to + * @param otherImpostor is the rigid impostor to hook to + * @param length ratio along the rope from 0 to 1 + * @param influence the elasticity between soft impostor and anchor from 0, very stretchy to 1, little stretch + * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false + */ + appendHook(impostor, otherImpostor, length, influence = 1, noCollisionBetweenLinkedBodies = false) { + const node = Math.round(impostor.segments * length); + impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence); + } + /** + * Sleeps the physics body and stops it from being active + * @param impostor impostor to sleep + */ + sleepBody(impostor) { + impostor.physicsBody.forceActivationState(0); + } + /** + * Activates the physics body + * @param impostor impostor to activate + */ + wakeUpBody(impostor) { + impostor.physicsBody.activate(); + } + /** + * Updates the distance parameters of the joint + */ + updateDistanceJoint() { + Logger.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin"); + } + /** + * Sets a motor on the joint + * @param joint joint to set motor on + * @param speed speed of the motor + * @param maxForce maximum force of the motor + */ + setMotor(joint, speed, maxForce) { + joint.physicsJoint.enableAngularMotor(true, speed, maxForce); + } + /** + * Sets the motors limit + */ + setLimit() { + Logger.Warn("setLimit is not currently supported by the Ammo physics plugin"); + } + /** + * Syncs the position and rotation of a mesh with the impostor + * @param mesh mesh to sync + * @param impostor impostor to update the mesh with + */ + syncMeshWithImpostor(mesh, impostor) { + const body = impostor.physicsBody; + body.getMotionState().getWorldTransform(this._tmpAmmoTransform); + mesh.position.x = this._tmpAmmoTransform.getOrigin().x(); + mesh.position.y = this._tmpAmmoTransform.getOrigin().y(); + mesh.position.z = this._tmpAmmoTransform.getOrigin().z(); + if (mesh.rotationQuaternion) { + mesh.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x(); + mesh.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y(); + mesh.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z(); + mesh.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w(); + } + } + /** + * Gets the radius of the impostor + * @param impostor impostor to get radius from + * @returns the radius + */ + getRadius(impostor) { + const extents = impostor.getObjectExtents(); + return extents.x / 2; + } + /** + * Gets the box size of the impostor + * @param impostor impostor to get box size from + * @param result the resulting box size + */ + getBoxSizeToRef(impostor, result) { + const extents = impostor.getObjectExtents(); + result.x = extents.x; + result.y = extents.y; + result.z = extents.z; + } + /** + * Disposes of the impostor + */ + dispose() { + // Dispose of world + this.bjsAMMO.destroy(this.world); + this.bjsAMMO.destroy(this._softBodySolver); + this.bjsAMMO.destroy(this._solver); + this.bjsAMMO.destroy(this._overlappingPairCache); + this.bjsAMMO.destroy(this._dispatcher); + this.bjsAMMO.destroy(this._collisionConfiguration); + // Dispose of temp variables + this.bjsAMMO.destroy(this._tmpAmmoVectorA); + this.bjsAMMO.destroy(this._tmpAmmoVectorB); + this.bjsAMMO.destroy(this._tmpAmmoVectorC); + this.bjsAMMO.destroy(this._tmpAmmoVectorD); + this.bjsAMMO.destroy(this._tmpAmmoTransform); + this.bjsAMMO.destroy(this._tmpAmmoQuaternion); + this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback); + this.world = null; + } + /** + * Does a raycast in the physics world + * @param from where should the ray start? + * @param to where should the ray end? + * @returns PhysicsRaycastResult + */ + raycast(from, to) { + this.raycastToRef(from, to, this._raycastResult); + return this._raycastResult; + } + /** + * Does a raycast in the physics world + * @param from when should the ray start? + * @param to when should the ray end? + * @param result resulting PhysicsRaycastResult + */ + raycastToRef(from, to, result) { + this._tmpAmmoVectorRCA = new this.bjsAMMO.btVector3(from.x, from.y, from.z); + this._tmpAmmoVectorRCB = new this.bjsAMMO.btVector3(to.x, to.y, to.z); + const rayCallback = new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB); + this.world.rayTest(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB, rayCallback); + result.reset(from, to); + if (rayCallback.hasHit()) { + // TODO: do we want/need the body? If so, set all the data + /* + var rigidBody = this.bjsAMMO.btRigidBody.prototype.upcast( + rayCallback.get_m_collisionObject() + ); + var body = {}; + */ + result.setHitData({ + x: rayCallback.get_m_hitNormalWorld().x(), + y: rayCallback.get_m_hitNormalWorld().y(), + z: rayCallback.get_m_hitNormalWorld().z(), + }, { + x: rayCallback.get_m_hitPointWorld().x(), + y: rayCallback.get_m_hitPointWorld().y(), + z: rayCallback.get_m_hitPointWorld().z(), + }); + result.calculateHitDistance(); + } + this.bjsAMMO.destroy(rayCallback); + this.bjsAMMO.destroy(this._tmpAmmoVectorRCA); + this.bjsAMMO.destroy(this._tmpAmmoVectorRCB); + } +} +AmmoJSPlugin._DISABLE_COLLISION_FLAG = 4; +AmmoJSPlugin._KINEMATIC_FLAG = 2; +AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG = 4; + +Scene.prototype.removeReflectionProbe = function (toRemove) { + if (!this.reflectionProbes) { + return -1; + } + const index = this.reflectionProbes.indexOf(toRemove); + if (index !== -1) { + this.reflectionProbes.splice(index, 1); + } + return index; +}; +Scene.prototype.addReflectionProbe = function (newReflectionProbe) { + if (!this.reflectionProbes) { + this.reflectionProbes = []; + } + this.reflectionProbes.push(newReflectionProbe); +}; +/** + * Class used to generate realtime reflection / refraction cube textures + * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/reflectionProbes + */ +class ReflectionProbe { + /** + * Creates a new reflection probe + * @param name defines the name of the probe + * @param size defines the texture resolution (for each face) + * @param scene defines the hosting scene + * @param generateMipMaps defines if mip maps should be generated automatically (true by default) + * @param useFloat defines if HDR data (float data) should be used to store colors (false by default) + * @param linearSpace defines if the probe should be generated in linear space or not (false by default) + */ + constructor( + /** defines the name of the probe */ + name, size, scene, generateMipMaps = true, useFloat = false, linearSpace = false) { + this.name = name; + this._viewMatrix = Matrix.Identity(); + this._target = Vector3.Zero(); + this._add = Vector3.Zero(); + this._invertYAxis = false; + /** Gets or sets probe position (center of the cube map) */ + this.position = Vector3.Zero(); + /** + * Gets or sets an object used to store user defined information for the reflection probe. + */ + this.metadata = null; + /** @internal */ + this._parentContainer = null; + this._scene = scene; + if (scene.getEngine().supportsUniformBuffers) { + this._sceneUBOs = []; + for (let i = 0; i < 6; ++i) { + this._sceneUBOs.push(scene.createSceneUniformBuffer(`Scene for Reflection Probe (name "${name}") face #${i}`)); + } + } + // Create the scene field if not exist. + if (!this._scene.reflectionProbes) { + this._scene.reflectionProbes = []; + } + this._scene.reflectionProbes.push(this); + let textureType = 0; + if (useFloat) { + const caps = this._scene.getEngine().getCaps(); + if (caps.textureHalfFloatRender) { + textureType = 2; + } + else if (caps.textureFloatRender) { + textureType = 1; + } + } + this._renderTargetTexture = new RenderTargetTexture(name, size, scene, generateMipMaps, true, textureType, true); + this._renderTargetTexture.gammaSpace = !linearSpace; + this._renderTargetTexture.invertZ = scene.useRightHandedSystem; + const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer; + this._renderTargetTexture.onBeforeRenderObservable.add((faceIndex) => { + if (this._sceneUBOs) { + scene.setSceneUniformBuffer(this._sceneUBOs[faceIndex]); + scene.getSceneUniformBuffer().unbindEffect(); + } + switch (faceIndex) { + case 0: + this._add.copyFromFloats(1, 0, 0); + break; + case 1: + this._add.copyFromFloats(-1, 0, 0); + break; + case 2: + this._add.copyFromFloats(0, this._invertYAxis ? 1 : -1, 0); + break; + case 3: + this._add.copyFromFloats(0, this._invertYAxis ? -1 : 1, 0); + break; + case 4: + this._add.copyFromFloats(0, 0, scene.useRightHandedSystem ? -1 : 1); + break; + case 5: + this._add.copyFromFloats(0, 0, scene.useRightHandedSystem ? 1 : -1); + break; + } + if (this._attachedMesh) { + this.position.copyFrom(this._attachedMesh.getAbsolutePosition()); + } + this.position.addToRef(this._add, this._target); + const lookAtFunction = scene.useRightHandedSystem ? Matrix.LookAtRHToRef : Matrix.LookAtLHToRef; + const perspectiveFunction = scene.useRightHandedSystem ? Matrix.PerspectiveFovRH : Matrix.PerspectiveFovLH; + lookAtFunction(this.position, this._target, Vector3.Up(), this._viewMatrix); + if (scene.activeCamera) { + this._projectionMatrix = perspectiveFunction(Math.PI / 2, 1, useReverseDepthBuffer ? scene.activeCamera.maxZ : scene.activeCamera.minZ, useReverseDepthBuffer ? scene.activeCamera.minZ : scene.activeCamera.maxZ, this._scene.getEngine().isNDCHalfZRange); + scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix); + if (scene.activeCamera.isRigCamera && !this._renderTargetTexture.activeCamera) { + this._renderTargetTexture.activeCamera = scene.activeCamera.rigParent || null; + } + } + scene._forcedViewPosition = this.position; + }); + let currentApplyByPostProcess; + this._renderTargetTexture.onBeforeBindObservable.add(() => { + this._currentSceneUBO = scene.getSceneUniformBuffer(); + scene.getEngine()._debugPushGroup?.(`reflection probe generation for ${name}`, 1); + currentApplyByPostProcess = this._scene.imageProcessingConfiguration.applyByPostProcess; + if (linearSpace) { + scene.imageProcessingConfiguration.applyByPostProcess = true; + } + }); + this._renderTargetTexture.onAfterUnbindObservable.add(() => { + scene.imageProcessingConfiguration.applyByPostProcess = currentApplyByPostProcess; + scene._forcedViewPosition = null; + if (this._sceneUBOs) { + scene.setSceneUniformBuffer(this._currentSceneUBO); + } + scene.updateTransformMatrix(true); + scene.getEngine()._debugPopGroup?.(1); + }); + } + /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */ + get samples() { + return this._renderTargetTexture.samples; + } + set samples(value) { + this._renderTargetTexture.samples = value; + } + /** Gets or sets the refresh rate to use (on every frame by default) */ + get refreshRate() { + return this._renderTargetTexture.refreshRate; + } + set refreshRate(value) { + this._renderTargetTexture.refreshRate = value; + } + /** + * Gets the hosting scene + * @returns a Scene + */ + getScene() { + return this._scene; + } + /** Gets the internal CubeTexture used to render to */ + get cubeTexture() { + return this._renderTargetTexture; + } + /** Gets or sets the list of meshes to render */ + get renderList() { + return this._renderTargetTexture.renderList; + } + set renderList(value) { + this._renderTargetTexture.renderList = value; + } + /** + * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position) + * @param mesh defines the mesh to attach to + */ + attachToMesh(mesh) { + this._attachedMesh = mesh; + } + /** + * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups + * @param renderingGroupId The rendering group id corresponding to its index + * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. + */ + setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) { + this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); + } + /** + * Clean all associated resources + */ + dispose() { + const index = this._scene.reflectionProbes.indexOf(this); + if (index !== -1) { + // Remove from the scene if found + this._scene.reflectionProbes.splice(index, 1); + } + if (this._parentContainer) { + const index = this._parentContainer.reflectionProbes.indexOf(this); + if (index > -1) { + this._parentContainer.reflectionProbes.splice(index, 1); + } + this._parentContainer = null; + } + if (this._renderTargetTexture) { + this._renderTargetTexture.dispose(); + this._renderTargetTexture = null; + } + if (this._sceneUBOs) { + for (const ubo of this._sceneUBOs) { + ubo.dispose(); + } + this._sceneUBOs = []; + } + } + /** + * Converts the reflection probe information to a readable string for debug purpose. + * @param fullDetails Supports for multiple levels of logging within scene loading + * @returns the human readable reflection probe info + */ + toString(fullDetails) { + let ret = "Name: " + this.name; + if (fullDetails) { + ret += ", position: " + this.position.toString(); + if (this._attachedMesh) { + ret += ", attached mesh: " + this._attachedMesh.name; + } + } + return ret; + } + /** + * Get the class name of the refection probe. + * @returns "ReflectionProbe" + */ + getClassName() { + return "ReflectionProbe"; + } + /** + * Serialize the reflection probe to a JSON representation we can easily use in the respective Parse function. + * @returns The JSON representation of the texture + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this, this._renderTargetTexture.serialize()); + serializationObject.isReflectionProbe = true; + serializationObject.metadata = this.metadata; + return serializationObject; + } + /** + * Parse the JSON representation of a reflection probe in order to recreate the reflection probe in the given scene. + * @param parsedReflectionProbe Define the JSON representation of the reflection probe + * @param scene Define the scene the parsed reflection probe should be instantiated in + * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies + * @returns The parsed reflection probe if successful + */ + static Parse(parsedReflectionProbe, scene, rootUrl) { + let reflectionProbe = null; + if (scene.reflectionProbes) { + for (let index = 0; index < scene.reflectionProbes.length; index++) { + const rp = scene.reflectionProbes[index]; + if (rp.name === parsedReflectionProbe.name) { + reflectionProbe = rp; + break; + } + } + } + reflectionProbe = SerializationHelper.Parse(() => reflectionProbe || new ReflectionProbe(parsedReflectionProbe.name, parsedReflectionProbe.renderTargetSize, scene, parsedReflectionProbe._generateMipMaps), parsedReflectionProbe, scene, rootUrl); + reflectionProbe.cubeTexture._waitingRenderList = parsedReflectionProbe.renderList; + if (parsedReflectionProbe._attachedMesh) { + reflectionProbe.attachToMesh(scene.getMeshById(parsedReflectionProbe._attachedMesh)); + } + if (parsedReflectionProbe.metadata) { + reflectionProbe.metadata = parsedReflectionProbe.metadata; + } + return reflectionProbe; + } +} +__decorate([ + serializeAsMeshReference() +], ReflectionProbe.prototype, "_attachedMesh", void 0); +__decorate([ + serializeAsVector3() +], ReflectionProbe.prototype, "position", void 0); + +/** + * ThinSprite Class used to represent a thin sprite + * This is the base class for sprites but can also directly be used with ThinEngine + * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites + */ +class ThinSprite { + /** + * Returns a boolean indicating if the animation is started + */ + get animationStarted() { + return this._animationStarted; + } + /** Gets the initial key for the animation (setting it will restart the animation) */ + get fromIndex() { + return this._fromIndex; + } + /** Gets or sets the end key for the animation (setting it will restart the animation) */ + get toIndex() { + return this._toIndex; + } + /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation) */ + get loopAnimation() { + return this._loopAnimation; + } + /** Gets or sets the delay between cell changes (setting it will restart the animation) */ + get delay() { + return Math.max(this._delay, 1); + } + /** + * Creates a new Thin Sprite + */ + constructor() { + /** Gets or sets the width */ + this.width = 1.0; + /** Gets or sets the height */ + this.height = 1.0; + /** Gets or sets rotation angle */ + this.angle = 0; + /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */ + this.invertU = false; + /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */ + this.invertV = false; + /** Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true */ + this.isVisible = true; + this._animationStarted = false; + this._loopAnimation = false; + this._fromIndex = 0; + this._toIndex = 0; + this._delay = 0; + this._direction = 1; + this._time = 0; + this._onBaseAnimationEnd = null; + this.position = { x: 1.0, y: 1.0, z: 1.0 }; + this.color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; + } + /** + * Starts an animation + * @param from defines the initial key + * @param to defines the end key + * @param loop defines if the animation must loop + * @param delay defines the start delay (in ms) + * @param onAnimationEnd defines a callback for when the animation ends + */ + playAnimation(from, to, loop, delay, onAnimationEnd) { + this._fromIndex = from; + this._toIndex = to; + this._loopAnimation = loop; + this._delay = delay || 1; + this._animationStarted = true; + this._onBaseAnimationEnd = onAnimationEnd; + if (from < to) { + this._direction = 1; + } + else { + this._direction = -1; + this._toIndex = from; + this._fromIndex = to; + } + this.cellIndex = from; + this._time = 0; + } + /** Stops current animation (if any) */ + stopAnimation() { + this._animationStarted = false; + } + /** + * @internal + */ + _animate(deltaTime) { + if (!this._animationStarted) { + return; + } + this._time += deltaTime; + if (this._time > this._delay) { + this._time = this._time % this._delay; + this.cellIndex += this._direction; + if ((this._direction > 0 && this.cellIndex > this._toIndex) || (this._direction < 0 && this.cellIndex < this._fromIndex)) { + if (this._loopAnimation) { + this.cellIndex = this._direction > 0 ? this._fromIndex : this._toIndex; + } + else { + this.cellIndex = this._toIndex; + this._animationStarted = false; + if (this._onBaseAnimationEnd) { + this._onBaseAnimationEnd(); + } + } + } + } + } +} + +/** + * Class used to represent a sprite + * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites + */ +class Sprite extends ThinSprite { + /** + * Gets or sets the sprite size + */ + get size() { + return this.width; + } + set size(value) { + this.width = value; + this.height = value; + } + /** + * Gets the manager of this sprite + */ + get manager() { + return this._manager; + } + /** + * Creates a new Sprite + * @param name defines the name + * @param manager defines the manager + */ + constructor( + /** defines the name */ + name, manager) { + super(); + this.name = name; + /** Gets the list of attached animations */ + this.animations = new Array(); + /** Gets or sets a boolean indicating if the sprite can be picked */ + this.isPickable = false; + /** Gets or sets a boolean indicating that sprite texture alpha will be used for precise picking (false by default) */ + this.useAlphaForPicking = false; + /** + * An event triggered when the control has been disposed + */ + this.onDisposeObservable = new Observable(); + this._onAnimationEnd = null; + this._endAnimation = () => { + if (this._onAnimationEnd) { + this._onAnimationEnd(); + } + if (this.disposeWhenFinishedAnimating) { + this.dispose(); + } + }; + this.color = new Color4(1.0, 1.0, 1.0, 1.0); + this.position = Vector3.Zero(); + this._manager = manager; + this._manager.sprites.push(this); + this.uniqueId = this._manager.scene.getUniqueId(); + } + /** + * Returns the string "Sprite" + * @returns "Sprite" + */ + getClassName() { + return "Sprite"; + } + /** Gets or sets the initial key for the animation (setting it will restart the animation) */ + get fromIndex() { + return this._fromIndex; + } + set fromIndex(value) { + this.playAnimation(value, this._toIndex, this._loopAnimation, this._delay, this._onAnimationEnd); + } + /** Gets or sets the end key for the animation (setting it will restart the animation) */ + get toIndex() { + return this._toIndex; + } + set toIndex(value) { + this.playAnimation(this._fromIndex, value, this._loopAnimation, this._delay, this._onAnimationEnd); + } + /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation) */ + get loopAnimation() { + return this._loopAnimation; + } + set loopAnimation(value) { + this.playAnimation(this._fromIndex, this._toIndex, value, this._delay, this._onAnimationEnd); + } + /** Gets or sets the delay between cell changes (setting it will restart the animation) */ + get delay() { + return Math.max(this._delay, 1); + } + set delay(value) { + this.playAnimation(this._fromIndex, this._toIndex, this._loopAnimation, value, this._onAnimationEnd); + } + /** + * Starts an animation + * @param from defines the initial key + * @param to defines the end key + * @param loop defines if the animation must loop + * @param delay defines the start delay (in ms) + * @param onAnimationEnd defines a callback to call when animation ends + */ + playAnimation(from, to, loop, delay, onAnimationEnd = null) { + this._onAnimationEnd = onAnimationEnd; + super.playAnimation(from, to, loop, delay, this._endAnimation); + } + /** Release associated resources */ + dispose() { + for (let i = 0; i < this._manager.sprites.length; i++) { + if (this._manager.sprites[i] == this) { + this._manager.sprites.splice(i, 1); + } + } + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + } + /** + * Serializes the sprite to a JSON object + * @returns the JSON object + */ + serialize() { + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.position = this.position.asArray(); + serializationObject.color = this.color.asArray(); + serializationObject.width = this.width; + serializationObject.height = this.height; + serializationObject.angle = this.angle; + serializationObject.cellIndex = this.cellIndex; + serializationObject.cellRef = this.cellRef; + serializationObject.invertU = this.invertU; + serializationObject.invertV = this.invertV; + serializationObject.disposeWhenFinishedAnimating = this.disposeWhenFinishedAnimating; + serializationObject.isPickable = this.isPickable; + serializationObject.isVisible = this.isVisible; + serializationObject.useAlphaForPicking = this.useAlphaForPicking; + serializationObject.animationStarted = this.animationStarted; + serializationObject.fromIndex = this.fromIndex; + serializationObject.toIndex = this.toIndex; + serializationObject.loopAnimation = this.loopAnimation; + serializationObject.delay = this.delay; + return serializationObject; + } + /** + * Parses a JSON object to create a new sprite + * @param parsedSprite The JSON object to parse + * @param manager defines the hosting manager + * @returns the new sprite + */ + static Parse(parsedSprite, manager) { + const sprite = new Sprite(parsedSprite.name, manager); + sprite.position = Vector3.FromArray(parsedSprite.position); + sprite.color = Color4.FromArray(parsedSprite.color); + sprite.width = parsedSprite.width; + sprite.height = parsedSprite.height; + sprite.angle = parsedSprite.angle; + sprite.cellIndex = parsedSprite.cellIndex; + sprite.cellRef = parsedSprite.cellRef; + sprite.invertU = parsedSprite.invertU; + sprite.invertV = parsedSprite.invertV; + sprite.disposeWhenFinishedAnimating = parsedSprite.disposeWhenFinishedAnimating; + sprite.isPickable = parsedSprite.isPickable; + sprite.isVisible = parsedSprite.isVisible; + sprite.useAlphaForPicking = parsedSprite.useAlphaForPicking; + sprite._fromIndex = parsedSprite.fromIndex; + sprite._toIndex = parsedSprite.toIndex; + sprite._loopAnimation = parsedSprite.loopAnimation; + sprite._delay = parsedSprite.delay; + if (parsedSprite.animationStarted) { + sprite.playAnimation(sprite.fromIndex, sprite.toIndex, sprite.loopAnimation, sprite.delay); + } + return sprite; + } +} + +Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) { + if (!PickingInfo) { + return null; + } + let pickingInfo = null; + if (!camera) { + if (!this.activeCamera) { + return null; + } + camera = this.activeCamera; + } + if (this.spriteManagers && this.spriteManagers.length > 0) { + for (let spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) { + const spriteManager = this.spriteManagers[spriteIndex]; + if (!spriteManager.isPickable) { + continue; + } + const result = spriteManager.intersects(ray, camera, predicate, fastCheck); + if (!result || !result.hit) { + continue; + } + if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) { + continue; + } + pickingInfo = result; + if (fastCheck) { + break; + } + } + } + return pickingInfo || new PickingInfo(); +}; +Scene.prototype._internalMultiPickSprites = function (ray, predicate, camera) { + if (!PickingInfo) { + return null; + } + let pickingInfos = []; + if (!camera) { + if (!this.activeCamera) { + return null; + } + camera = this.activeCamera; + } + if (this.spriteManagers && this.spriteManagers.length > 0) { + for (let spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) { + const spriteManager = this.spriteManagers[spriteIndex]; + if (!spriteManager.isPickable) { + continue; + } + const results = spriteManager.multiIntersects(ray, camera, predicate); + if (results !== null) { + pickingInfos = pickingInfos.concat(results); + } + } + } + return pickingInfos; +}; +Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) { + if (!this._tempSpritePickingRay) { + return null; + } + CreatePickingRayInCameraSpaceToRef(this, x, y, this._tempSpritePickingRay, camera); + const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera); + if (result) { + result.ray = CreatePickingRayInCameraSpace(this, x, y, camera); + } + return result; +}; +Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) { + if (!this._tempSpritePickingRay) { + return null; + } + if (!camera) { + if (!this.activeCamera) { + return null; + } + camera = this.activeCamera; + } + Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay); + const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera); + if (result) { + result.ray = ray; + } + return result; +}; +Scene.prototype.multiPickSprite = function (x, y, predicate, camera) { + CreatePickingRayInCameraSpaceToRef(this, x, y, this._tempSpritePickingRay, camera); + return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera); +}; +Scene.prototype.multiPickSpriteWithRay = function (ray, predicate, camera) { + if (!this._tempSpritePickingRay) { + return null; + } + if (!camera) { + if (!this.activeCamera) { + return null; + } + camera = this.activeCamera; + } + Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay); + return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera); +}; +Scene.prototype.setPointerOverSprite = function (sprite) { + if (this._pointerOverSprite === sprite) { + return; + } + if (this._pointerOverSprite && this._pointerOverSprite.actionManager) { + this._pointerOverSprite.actionManager.processTrigger(10, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)); + } + this._pointerOverSprite = sprite; + if (this._pointerOverSprite && this._pointerOverSprite.actionManager) { + this._pointerOverSprite.actionManager.processTrigger(9, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)); + } +}; +Scene.prototype.getPointerOverSprite = function () { + return this._pointerOverSprite; +}; +/** + * Defines the sprite scene component responsible to manage sprites + * in a given scene. + */ +class SpriteSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpfull to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_SPRITE; + this.scene = scene; + this.scene.spriteManagers = []; + this.scene._tempSpritePickingRay = Ray ? Ray.Zero() : null; + this.scene.onBeforeSpritesRenderingObservable = new Observable(); + this.scene.onAfterSpritesRenderingObservable = new Observable(); + this._spritePredicate = (sprite) => { + if (!sprite.actionManager) { + return false; + } + return sprite.isPickable && sprite.actionManager.hasPointerTriggers; + }; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._pointerMoveStage.registerStep(SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove); + this.scene._pointerDownStage.registerStep(SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown); + this.scene._pointerUpStage.registerStep(SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + /** Nothing to do for sprites */ + } + /** + * Disposes the component and the associated resources. + */ + dispose() { + this.scene.onBeforeSpritesRenderingObservable.clear(); + this.scene.onAfterSpritesRenderingObservable.clear(); + const spriteManagers = this.scene.spriteManagers; + if (!spriteManagers) { + return; + } + while (spriteManagers.length) { + spriteManagers[0].dispose(); + } + } + _pickSpriteButKeepRay(originalPointerInfo, x, y, fastCheck, camera) { + const result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera); + if (result) { + result.ray = originalPointerInfo ? originalPointerInfo.ray : null; + } + return result; + } + _pointerMove(unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, element) { + const scene = this.scene; + if (isMeshPicked) { + scene.setPointerOverSprite(null); + } + else { + pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined); + if (pickResult && pickResult.hit && pickResult.pickedSprite) { + scene.setPointerOverSprite(pickResult.pickedSprite); + if (!scene.doNotHandleCursors && element) { + if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) { + element.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor; + } + else { + element.style.cursor = scene.hoverCursor; + } + } + } + else { + scene.setPointerOverSprite(null); + } + } + return pickResult; + } + _pointerDown(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) { + const scene = this.scene; + scene._pickedDownSprite = null; + if (scene.spriteManagers && scene.spriteManagers.length > 0) { + pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined); + if (pickResult && pickResult.hit && pickResult.pickedSprite) { + if (pickResult.pickedSprite.actionManager) { + scene._pickedDownSprite = pickResult.pickedSprite; + switch (evt.button) { + case 0: + pickResult.pickedSprite.actionManager.processTrigger(2, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); + break; + case 1: + pickResult.pickedSprite.actionManager.processTrigger(4, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); + break; + case 2: + pickResult.pickedSprite.actionManager.processTrigger(3, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); + break; + } + if (pickResult.pickedSprite.actionManager) { + pickResult.pickedSprite.actionManager.processTrigger(5, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); + } + } + } + } + return pickResult; + } + _pointerUp(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt, doubleClick) { + const scene = this.scene; + if (scene.spriteManagers && scene.spriteManagers.length > 0) { + const spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined); + if (spritePickResult) { + if (spritePickResult.hit && spritePickResult.pickedSprite) { + if (spritePickResult.pickedSprite.actionManager) { + spritePickResult.pickedSprite.actionManager.processTrigger(7, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt)); + if (spritePickResult.pickedSprite.actionManager) { + if (!this.scene._inputManager._isPointerSwiping()) { + spritePickResult.pickedSprite.actionManager.processTrigger(1, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt)); + } + if (doubleClick) { + spritePickResult.pickedSprite.actionManager.processTrigger(6, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt)); + } + } + } + } + if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) { + scene._pickedDownSprite.actionManager.processTrigger(16, ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt)); + } + } + } + return pickResult; + } +} + +/** + * Class used to render sprites. + * + * It can be used either to render Sprites or ThinSprites with ThinEngine only. + */ +class SpriteRenderer { + /** + * Gets or sets a boolean indicating if the manager must consider scene fog when rendering + */ + get fogEnabled() { + return this._fogEnabled; + } + set fogEnabled(value) { + if (this._fogEnabled === value) { + return; + } + this._fogEnabled = value; + this._createEffects(); + } + /** + * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes) + * You can try switching to logarithmic depth. + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/logarithmicDepthBuffer + */ + get useLogarithmicDepth() { + return this._useLogarithmicDepth; + } + set useLogarithmicDepth(value) { + const fragmentDepthSupported = !!this._scene?.getEngine().getCaps().fragmentDepthSupported; + if (value && !fragmentDepthSupported) { + Logger.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it."); + } + this._useLogarithmicDepth = value && fragmentDepthSupported; + this._createEffects(); + } + /** + * Gets the capacity of the manager + */ + get capacity() { + return this._capacity; + } + /** + * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering + * Note that pixel perfect mode is not supported in WebGL 1 + */ + get pixelPerfect() { + return this._pixelPerfect; + } + set pixelPerfect(value) { + if (this._pixelPerfect === value) { + return; + } + this._pixelPerfect = value; + this._createEffects(); + } + /** + * Gets the shader language used in this renderer. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Creates a new sprite renderer + * @param engine defines the engine the renderer works with + * @param capacity defines the maximum allowed number of sprites + * @param epsilon defines the epsilon value to align texture (0.01 by default) + * @param scene defines the hosting scene + * @param rendererOptions options for the sprite renderer + */ + constructor(engine, capacity, epsilon = 0.01, scene = null, rendererOptions) { + /** + * Blend mode use to render the particle, it can be any of + * the static undefined properties provided in this class. + * Default value is 2 + */ + this.blendMode = 2; + /** + * Gets or sets a boolean indicating if alpha mode is automatically + * reset. + */ + this.autoResetAlpha = true; + /** + * Disables writing to the depth buffer when rendering the sprites. + * It can be handy to disable depth writing when using textures without alpha channel + * and setting some specific blend modes. + */ + this.disableDepthWrite = false; + this._fogEnabled = true; + this._pixelPerfect = false; + /** Shader language used by the material */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._useVAO = false; + this._useInstancing = false; + this._vertexBuffers = {}; + this._isDisposed = false; + this._shadersLoaded = false; + this._pixelPerfect = rendererOptions?.pixelPerfect ?? false; + this._capacity = capacity; + this._epsilon = epsilon; + this._engine = engine; + this._useInstancing = engine.getCaps().instancedArrays && engine._features.supportSpriteInstancing; + this._useVAO = engine.getCaps().vertexArrayObject && !engine.disableVertexArrayObjects; + this._scene = scene; + if (!this._useInstancing) { + this._buildIndexBuffer(); + } + // VBO + // 18 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellLeft, cellTop, cellWidth, cellHeight, color r, color g, color b, color a) + // 16 when using instances + this._vertexBufferSize = this._useInstancing ? 16 : 18; + this._vertexData = new Float32Array(capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4)); + this._buffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize); + const positions = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing); + const options = this._buffer.createVertexBuffer("options", 4, 2, this._vertexBufferSize, this._useInstancing); + let offset = 6; + let offsets; + if (this._useInstancing) { + const spriteData = new Float32Array([ + this._epsilon, + this._epsilon, + 1 - this._epsilon, + this._epsilon, + this._epsilon, + 1 - this._epsilon, + 1 - this._epsilon, + 1 - this._epsilon, + ]); + this._spriteBuffer = new Buffer(engine, spriteData, false, 2); + offsets = this._spriteBuffer.createVertexBuffer("offsets", 0, 2); + } + else { + offsets = this._buffer.createVertexBuffer("offsets", offset, 2, this._vertexBufferSize, this._useInstancing); + offset += 2; + } + const inverts = this._buffer.createVertexBuffer("inverts", offset, 2, this._vertexBufferSize, this._useInstancing); + const cellInfo = this._buffer.createVertexBuffer("cellInfo", offset + 2, 4, this._vertexBufferSize, this._useInstancing); + const colors = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, offset + 6, 4, this._vertexBufferSize, this._useInstancing); + this._vertexBuffers[VertexBuffer.PositionKind] = positions; + this._vertexBuffers["options"] = options; + this._vertexBuffers["offsets"] = offsets; + this._vertexBuffers["inverts"] = inverts; + this._vertexBuffers["cellInfo"] = cellInfo; + this._vertexBuffers[VertexBuffer.ColorKind] = colors; + this._initShaderSourceAsync(); + } + async _initShaderSourceAsync() { + const engine = this._engine; + if (engine.isWebGPU && !SpriteRenderer.ForceGLSL) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + await Promise.all([Promise.resolve().then(() => sprites_vertex), Promise.resolve().then(() => sprites_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => sprites_vertex$1), Promise.resolve().then(() => sprites_fragment$1)]); + } + this._shadersLoaded = true; + this._createEffects(); + } + _createEffects() { + if (this._isDisposed || !this._shadersLoaded) { + return; + } + this._drawWrapperBase?.dispose(); + this._drawWrapperDepth?.dispose(); + this._drawWrapperBase = new DrawWrapper(this._engine); + this._drawWrapperDepth = new DrawWrapper(this._engine, false); + if (this._drawWrapperBase.drawContext) { + this._drawWrapperBase.drawContext.useInstancing = this._useInstancing; + } + if (this._drawWrapperDepth.drawContext) { + this._drawWrapperDepth.drawContext.useInstancing = this._useInstancing; + } + let defines = ""; + if (this._pixelPerfect) { + defines += "#define PIXEL_PERFECT\n"; + } + if (this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0 && this._fogEnabled) { + defines += "#define FOG\n"; + } + if (this._useLogarithmicDepth) { + defines += "#define LOGARITHMICDEPTH\n"; + } + this._drawWrapperBase.effect = this._engine.createEffect("sprites", [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor", "logarithmicDepthConstant"], ["diffuseSampler"], defines, undefined, undefined, undefined, undefined, this._shaderLanguage); + this._drawWrapperDepth.effect = this._drawWrapperBase.effect; + this._drawWrapperBase.effect._refCount++; + this._drawWrapperDepth.materialContext = this._drawWrapperBase.materialContext; + } + /** + * Render all child sprites + * @param sprites defines the list of sprites to render + * @param deltaTime defines the time since last frame + * @param viewMatrix defines the viewMatrix to use to render the sprites + * @param projectionMatrix defines the projectionMatrix to use to render the sprites + * @param customSpriteUpdate defines a custom function to update the sprites data before they render + */ + render(sprites, deltaTime, viewMatrix, projectionMatrix, customSpriteUpdate = null) { + if (!this._shadersLoaded || !this.texture || !this.texture.isReady() || !sprites.length) { + return; + } + const drawWrapper = this._drawWrapperBase; + const drawWrapperDepth = this._drawWrapperDepth; + const shouldRenderFog = this.fogEnabled && this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0; + const effect = drawWrapper.effect; + // Check + if (!effect.isReady()) { + return; + } + const engine = this._engine; + const useRightHandedSystem = !!(this._scene && this._scene.useRightHandedSystem); + // Sprites + const max = Math.min(this._capacity, sprites.length); + let offset = 0; + let noSprite = true; + for (let index = 0; index < max; index++) { + const sprite = sprites[index]; + if (!sprite || !sprite.isVisible) { + continue; + } + noSprite = false; + sprite._animate(deltaTime); + const baseSize = this.texture.getBaseSize(); // This could be change by the user inside the animate callback (like onAnimationEnd) + this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize, useRightHandedSystem, customSpriteUpdate); + if (!this._useInstancing) { + this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize, useRightHandedSystem, customSpriteUpdate); + this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize, useRightHandedSystem, customSpriteUpdate); + this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize, useRightHandedSystem, customSpriteUpdate); + } + } + if (noSprite) { + return; + } + this._buffer.update(this._vertexData); + const culling = !!engine.depthCullingState.cull; + const zOffset = engine.depthCullingState.zOffset; + const zOffsetUnits = engine.depthCullingState.zOffsetUnits; + engine.setState(culling, zOffset, false, false, undefined, undefined, zOffsetUnits); + // Render + engine.enableEffect(drawWrapper); + effect.setTexture("diffuseSampler", this.texture); + effect.setMatrix("view", viewMatrix); + effect.setMatrix("projection", projectionMatrix); + // Scene Info + if (shouldRenderFog) { + const scene = this._scene; + // Fog + effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); + effect.setColor3("vFogColor", scene.fogColor); + } + // Log. depth + if (this.useLogarithmicDepth && this._scene) { + BindLogDepth(drawWrapper.defines, effect, this._scene); + } + if (this._useVAO) { + if (!this._vertexArrayObject) { + this._vertexArrayObject = engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect); + } + engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer); + } + else { + // VBOs + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); + } + // Draw order + engine.depthCullingState.depthFunc = engine.useReverseDepthBuffer ? 518 : 515; + if (!this.disableDepthWrite) { + effect.setBool("alphaTest", true); + engine.setColorWrite(false); + engine.enableEffect(drawWrapperDepth); + if (this._useInstancing) { + engine.drawArraysType(7, 0, 4, offset); + } + else { + engine.drawElementsType(0, 0, (offset / 4) * 6); + } + engine.enableEffect(drawWrapper); + engine.setColorWrite(true); + effect.setBool("alphaTest", false); + } + engine.setAlphaMode(this.blendMode); + if (this._useInstancing) { + engine.drawArraysType(7, 0, 4, offset); + } + else { + engine.drawElementsType(0, 0, (offset / 4) * 6); + } + if (this.autoResetAlpha) { + engine.setAlphaMode(0); + } + // Restore Right Handed + if (useRightHandedSystem) { + this._scene.getEngine().setState(culling, zOffset, false, true, undefined, undefined, zOffsetUnits); + } + engine.unbindInstanceAttributes(); + } + _appendSpriteVertex(index, sprite, offsetX, offsetY, baseSize, useRightHandedSystem, customSpriteUpdate) { + let arrayOffset = index * this._vertexBufferSize; + if (offsetX === 0) { + offsetX = this._epsilon; + } + else if (offsetX === 1) { + offsetX = 1 - this._epsilon; + } + if (offsetY === 0) { + offsetY = this._epsilon; + } + else if (offsetY === 1) { + offsetY = 1 - this._epsilon; + } + if (customSpriteUpdate) { + customSpriteUpdate(sprite, baseSize); + } + else { + if (!sprite.cellIndex) { + sprite.cellIndex = 0; + } + const rowSize = baseSize.width / this.cellWidth; + const offset = (sprite.cellIndex / rowSize) >> 0; + sprite._xOffset = ((sprite.cellIndex - offset * rowSize) * this.cellWidth) / baseSize.width; + sprite._yOffset = (offset * this.cellHeight) / baseSize.height; + sprite._xSize = this.cellWidth; + sprite._ySize = this.cellHeight; + } + // Positions + this._vertexData[arrayOffset] = sprite.position.x; + this._vertexData[arrayOffset + 1] = sprite.position.y; + this._vertexData[arrayOffset + 2] = sprite.position.z; + this._vertexData[arrayOffset + 3] = sprite.angle; + // Options + this._vertexData[arrayOffset + 4] = sprite.width; + this._vertexData[arrayOffset + 5] = sprite.height; + if (!this._useInstancing) { + this._vertexData[arrayOffset + 6] = offsetX; + this._vertexData[arrayOffset + 7] = offsetY; + } + else { + arrayOffset -= 2; + } + // Inverts according to Right Handed + if (useRightHandedSystem) { + this._vertexData[arrayOffset + 8] = sprite.invertU ? 0 : 1; + } + else { + this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0; + } + this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0; + this._vertexData[arrayOffset + 10] = sprite._xOffset; + this._vertexData[arrayOffset + 11] = sprite._yOffset; + this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width; + this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height; + // Color + this._vertexData[arrayOffset + 14] = sprite.color.r; + this._vertexData[arrayOffset + 15] = sprite.color.g; + this._vertexData[arrayOffset + 16] = sprite.color.b; + this._vertexData[arrayOffset + 17] = sprite.color.a; + } + _buildIndexBuffer() { + const indices = []; + let index = 0; + for (let count = 0; count < this._capacity; count++) { + indices.push(index); + indices.push(index + 1); + indices.push(index + 2); + indices.push(index); + indices.push(index + 2); + indices.push(index + 3); + index += 4; + } + this._indexBuffer = this._engine.createIndexBuffer(indices); + } + /** + * Rebuilds the renderer (after a context lost, for eg) + */ + rebuild() { + if (this._indexBuffer) { + this._buildIndexBuffer(); + } + if (this._useVAO) { + this._vertexArrayObject = undefined; + } + this._buffer._rebuild(); + for (const key in this._vertexBuffers) { + const vertexBuffer = this._vertexBuffers[key]; + vertexBuffer._rebuild(); + } + this._spriteBuffer?._rebuild(); + } + /** + * Release associated resources + */ + dispose() { + if (this._buffer) { + this._buffer.dispose(); + this._buffer = null; + } + if (this._spriteBuffer) { + this._spriteBuffer.dispose(); + this._spriteBuffer = null; + } + if (this._indexBuffer) { + this._engine._releaseBuffer(this._indexBuffer); + this._indexBuffer = null; + } + if (this._vertexArrayObject) { + this._engine.releaseVertexArrayObject(this._vertexArrayObject); + this._vertexArrayObject = null; + } + if (this.texture) { + this.texture.dispose(); + this.texture = null; + } + this._drawWrapperBase?.dispose(); + this._drawWrapperDepth?.dispose(); + this._isDisposed = true; + } +} +/** + * Force all the sprites to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +SpriteRenderer.ForceGLSL = false; + +/** + * Class used to manage multiple sprites on the same spritesheet + * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites + */ +class SpriteManager { + /** + * Callback called when the manager is disposed + */ + set onDispose(callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + } + /** + * Gets the array of sprites + */ + get children() { + return this.sprites; + } + /** + * Gets the hosting scene + */ + get scene() { + return this._scene; + } + /** + * Gets the capacity of the manager + */ + get capacity() { + return this._spriteRenderer.capacity; + } + /** + * Gets or sets the spritesheet texture + */ + get texture() { + return this._spriteRenderer.texture; + } + set texture(value) { + value.wrapU = Texture.CLAMP_ADDRESSMODE; + value.wrapV = Texture.CLAMP_ADDRESSMODE; + this._spriteRenderer.texture = value; + this._textureContent = null; + } + /** Defines the default width of a cell in the spritesheet */ + get cellWidth() { + return this._spriteRenderer.cellWidth; + } + set cellWidth(value) { + this._spriteRenderer.cellWidth = value; + } + /** Defines the default height of a cell in the spritesheet */ + get cellHeight() { + return this._spriteRenderer.cellHeight; + } + set cellHeight(value) { + this._spriteRenderer.cellHeight = value; + } + /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */ + get fogEnabled() { + return this._spriteRenderer.fogEnabled; + } + set fogEnabled(value) { + this._spriteRenderer.fogEnabled = value; + } + /** Gets or sets a boolean indicating if the manager must use logarithmic depth when rendering */ + get useLogarithmicDepth() { + return this._spriteRenderer.useLogarithmicDepth; + } + set useLogarithmicDepth(value) { + this._spriteRenderer.useLogarithmicDepth = value; + } + /** + * Blend mode use to render the particle, it can be any of + * the static undefined properties provided in this class. + * Default value is 2 + */ + get blendMode() { + return this._spriteRenderer.blendMode; + } + set blendMode(blendMode) { + this._spriteRenderer.blendMode = blendMode; + } + /** Disables writing to the depth buffer when rendering the sprites. + * It can be handy to disable depth writing when using textures without alpha channel + * and setting some specific blend modes. + */ + get disableDepthWrite() { + return this._disableDepthWrite; + } + set disableDepthWrite(value) { + this._disableDepthWrite = value; + this._spriteRenderer.disableDepthWrite = value; + } + /** + * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering + * In this mode, sprites are rendered as "pixel art", which means that they appear as pixelated but remain stable when moving or when rotated or scaled. + * Note that for this mode to work as expected, the sprite texture must use the BILINEAR sampling mode, not NEAREST! + */ + get pixelPerfect() { + return this._spriteRenderer.pixelPerfect; + } + set pixelPerfect(value) { + this._spriteRenderer.pixelPerfect = value; + if (value && this.texture.samplingMode !== 3) { + this.texture.updateSamplingMode(3); + } + } + /** + * Creates a new sprite manager + * @param name defines the manager's name + * @param imgUrl defines the sprite sheet url + * @param capacity defines the maximum allowed number of sprites + * @param cellSize defines the size of a sprite cell + * @param scene defines the hosting scene + * @param epsilon defines the epsilon value to align texture (0.01 by default) + * @param samplingMode defines the sampling mode to use with spritesheet + * @param fromPacked set to false; do not alter + * @param spriteJSON null otherwise a JSON object defining sprite sheet data; do not alter + * @param options options used to create the SpriteManager instance + */ + constructor( + /** defines the manager's name */ + name, imgUrl, capacity, cellSize, scene, epsilon = 0.01, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, fromPacked = false, spriteJSON = null, options) { + this.name = name; + /** Gets the list of sprites */ + this.sprites = []; + /** Gets or sets the rendering group id (0 by default) */ + this.renderingGroupId = 0; + /** Gets or sets camera layer mask */ + this.layerMask = 0x0fffffff; + /** Gets or sets a boolean indicating if the sprites are pickable */ + this.isPickable = false; + /** + * Gets or sets an object used to store user defined information for the sprite manager + */ + this.metadata = null; + /** @internal */ + this._wasDispatched = false; + /** + * An event triggered when the manager is disposed. + */ + this.onDisposeObservable = new Observable(); + this._disableDepthWrite = false; + /** True when packed cell data from JSON file is ready*/ + this._packedAndReady = false; + this._customUpdate = (sprite, baseSize) => { + if (!sprite.cellRef) { + sprite.cellIndex = 0; + } + const num = sprite.cellIndex; + if (typeof num === "number" && isFinite(num) && Math.floor(num) === num) { + sprite.cellRef = this._spriteMap[sprite.cellIndex]; + } + sprite._xOffset = this._cellData[sprite.cellRef].frame.x / baseSize.width; + sprite._yOffset = this._cellData[sprite.cellRef].frame.y / baseSize.height; + sprite._xSize = this._cellData[sprite.cellRef].frame.w; + sprite._ySize = this._cellData[sprite.cellRef].frame.h; + }; + if (!scene) { + scene = EngineStore.LastCreatedScene; + } + if (!scene._getComponent(SceneComponentConstants.NAME_SPRITE)) { + scene._addComponent(new SpriteSceneComponent(scene)); + } + this._fromPacked = fromPacked; + this._scene = scene; + const engine = this._scene.getEngine(); + this._spriteRenderer = new SpriteRenderer(engine, capacity, epsilon, scene, options?.spriteRendererOptions); + if (cellSize.width && cellSize.height) { + this.cellWidth = cellSize.width; + this.cellHeight = cellSize.height; + } + else if (cellSize !== undefined) { + this.cellWidth = cellSize; + this.cellHeight = cellSize; + } + else { + this._spriteRenderer = null; + return; + } + this._scene.spriteManagers && this._scene.spriteManagers.push(this); + this.uniqueId = this.scene.getUniqueId(); + if (imgUrl) { + this.texture = new Texture(imgUrl, scene, true, false, samplingMode); + } + if (this._fromPacked) { + this._makePacked(imgUrl, spriteJSON); + } + } + /** + * Returns the string "SpriteManager" + * @returns "SpriteManager" + */ + getClassName() { + return "SpriteManager"; + } + _makePacked(imgUrl, spriteJSON) { + if (spriteJSON !== null) { + try { + //Get the JSON and Check its structure. If its an array parse it if its a JSON string etc... + let celldata; + if (typeof spriteJSON === "string") { + celldata = JSON.parse(spriteJSON); + } + else { + celldata = spriteJSON; + } + if (celldata.frames.length) { + const frametemp = {}; + for (let i = 0; i < celldata.frames.length; i++) { + const _f = celldata.frames[i]; + if (typeof Object.keys(_f)[0] !== "string") { + throw new Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter."); + } + const name = _f[Object.keys(_f)[0]]; + frametemp[name] = _f; + } + celldata.frames = frametemp; + } + const spritemap = Reflect.ownKeys(celldata.frames); + this._spriteMap = spritemap; + this._packedAndReady = true; + this._cellData = celldata.frames; + } + catch (e) { + this._fromPacked = false; + this._packedAndReady = false; + throw new Error("Invalid JSON from string. Spritesheet managed with constant cell size."); + } + } + else { + const re = /\./g; + let li; + do { + li = re.lastIndex; + re.test(imgUrl); + } while (re.lastIndex > 0); + const jsonUrl = imgUrl.substring(0, li - 1) + ".json"; + const onerror = () => { + Logger.Error("JSON ERROR: Unable to load JSON file."); + this._fromPacked = false; + this._packedAndReady = false; + }; + const onload = (data) => { + try { + const celldata = JSON.parse(data); + const spritemap = Reflect.ownKeys(celldata.frames); + this._spriteMap = spritemap; + this._packedAndReady = true; + this._cellData = celldata.frames; + } + catch (e) { + this._fromPacked = false; + this._packedAndReady = false; + throw new Error("Invalid JSON format. Please check documentation for format specifications."); + } + }; + Tools.LoadFile(jsonUrl, onload, undefined, undefined, false, onerror); + } + } + _checkTextureAlpha(sprite, ray, distance, min, max) { + if (!sprite.useAlphaForPicking || !this.texture?.isReady()) { + return true; + } + const textureSize = this.texture.getSize(); + if (!this._textureContent) { + this._textureContent = new Uint8Array(textureSize.width * textureSize.height * 4); + this.texture.readPixels(0, 0, this._textureContent); + } + const contactPoint = TmpVectors.Vector3[0]; + contactPoint.copyFrom(ray.direction); + contactPoint.normalize(); + contactPoint.scaleInPlace(distance); + contactPoint.addInPlace(ray.origin); + const contactPointU = (contactPoint.x - min.x) / (max.x - min.x); + const contactPointV = 1.0 - (contactPoint.y - min.y) / (max.y - min.y); + const u = (sprite._xOffset * textureSize.width + contactPointU * sprite._xSize) | 0; + const v = (sprite._yOffset * textureSize.height + contactPointV * sprite._ySize) | 0; + const alpha = this._textureContent[(u + v * textureSize.width) * 4 + 3]; + return alpha > 0.5; + } + /** + * Intersects the sprites with a ray + * @param ray defines the ray to intersect with + * @param camera defines the current active camera + * @param predicate defines a predicate used to select candidate sprites + * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer) + * @returns null if no hit or a PickingInfo + */ + intersects(ray, camera, predicate, fastCheck) { + const count = Math.min(this.capacity, this.sprites.length); + const min = Vector3.Zero(); + const max = Vector3.Zero(); + let distance = Number.MAX_VALUE; + let currentSprite = null; + const pickedPoint = TmpVectors.Vector3[0]; + const cameraSpacePosition = TmpVectors.Vector3[1]; + const cameraView = camera.getViewMatrix(); + let activeRay = ray; + let pickedRay = ray; + for (let index = 0; index < count; index++) { + const sprite = this.sprites[index]; + if (!sprite) { + continue; + } + if (predicate) { + if (!predicate(sprite)) { + continue; + } + } + else if (!sprite.isPickable) { + continue; + } + Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition); + if (sprite.angle) { + // Create a rotation matrix to rotate the ray to the sprite's rotation + Matrix.TranslationToRef(-cameraSpacePosition.x, -cameraSpacePosition.y, 0, TmpVectors.Matrix[1]); + Matrix.TranslationToRef(cameraSpacePosition.x, cameraSpacePosition.y, 0, TmpVectors.Matrix[2]); + Matrix.RotationZToRef(-sprite.angle, TmpVectors.Matrix[3]); + // inv translation x rotation x translation + TmpVectors.Matrix[1].multiplyToRef(TmpVectors.Matrix[3], TmpVectors.Matrix[4]); + TmpVectors.Matrix[4].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[0]); + activeRay = ray.clone(); + Vector3.TransformCoordinatesToRef(ray.origin, TmpVectors.Matrix[0], activeRay.origin); + Vector3.TransformNormalToRef(ray.direction, TmpVectors.Matrix[0], activeRay.direction); + } + else { + activeRay = ray; + } + min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z); + max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z); + if (activeRay.intersectsBoxMinMax(min, max)) { + const currentDistance = Vector3.Distance(cameraSpacePosition, activeRay.origin); + if (distance > currentDistance) { + if (!this._checkTextureAlpha(sprite, activeRay, currentDistance, min, max)) { + continue; + } + pickedRay = activeRay; + distance = currentDistance; + currentSprite = sprite; + if (fastCheck) { + break; + } + } + } + } + if (currentSprite) { + const result = new PickingInfo(); + cameraView.invertToRef(TmpVectors.Matrix[0]); + result.hit = true; + result.pickedSprite = currentSprite; + result.distance = distance; + // Get picked point + const direction = TmpVectors.Vector3[2]; + direction.copyFrom(pickedRay.direction); + direction.normalize(); + direction.scaleInPlace(distance); + pickedRay.origin.addToRef(direction, pickedPoint); + result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]); + return result; + } + return null; + } + /** + * Intersects the sprites with a ray + * @param ray defines the ray to intersect with + * @param camera defines the current active camera + * @param predicate defines a predicate used to select candidate sprites + * @returns null if no hit or a PickingInfo array + */ + multiIntersects(ray, camera, predicate) { + const count = Math.min(this.capacity, this.sprites.length); + const min = Vector3.Zero(); + const max = Vector3.Zero(); + let distance; + const results = []; + const pickedPoint = TmpVectors.Vector3[0].copyFromFloats(0, 0, 0); + const cameraSpacePosition = TmpVectors.Vector3[1].copyFromFloats(0, 0, 0); + const cameraView = camera.getViewMatrix(); + for (let index = 0; index < count; index++) { + const sprite = this.sprites[index]; + if (!sprite) { + continue; + } + if (predicate) { + if (!predicate(sprite)) { + continue; + } + } + else if (!sprite.isPickable) { + continue; + } + Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition); + min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z); + max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z); + if (ray.intersectsBoxMinMax(min, max)) { + distance = Vector3.Distance(cameraSpacePosition, ray.origin); + if (!this._checkTextureAlpha(sprite, ray, distance, min, max)) { + continue; + } + const result = new PickingInfo(); + results.push(result); + cameraView.invertToRef(TmpVectors.Matrix[0]); + result.hit = true; + result.pickedSprite = sprite; + result.distance = distance; + // Get picked point + const direction = TmpVectors.Vector3[2]; + direction.copyFrom(ray.direction); + direction.normalize(); + direction.scaleInPlace(distance); + ray.origin.addToRef(direction, pickedPoint); + result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]); + } + } + return results; + } + /** + * Render all child sprites + */ + render() { + // Check + if (this._fromPacked && (!this._packedAndReady || !this._spriteMap || !this._cellData)) { + return; + } + const engine = this._scene.getEngine(); + const deltaTime = engine.getDeltaTime(); + if (this._packedAndReady) { + this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix(), this._customUpdate); + } + else { + this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix()); + } + } + /** + * Rebuilds the manager (after a context lost, for eg) + */ + rebuild() { + this._spriteRenderer?.rebuild(); + } + /** + * Release associated resources + */ + dispose() { + if (this._spriteRenderer) { + this._spriteRenderer.dispose(); + this._spriteRenderer = null; + } + this._textureContent = null; + // Remove from scene + if (this._scene.spriteManagers) { + const index = this._scene.spriteManagers.indexOf(this); + this._scene.spriteManagers.splice(index, 1); + } + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + this.metadata = null; + } + /** + * Serializes the sprite manager to a JSON object + * @param serializeTexture defines if the texture must be serialized as well + * @returns the JSON object + */ + serialize(serializeTexture = false) { + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.capacity = this.capacity; + serializationObject.cellWidth = this.cellWidth; + serializationObject.cellHeight = this.cellHeight; + serializationObject.fogEnabled = this.fogEnabled; + serializationObject.blendMode = this.blendMode; + serializationObject.disableDepthWrite = this.disableDepthWrite; + serializationObject.pixelPerfect = this.pixelPerfect; + serializationObject.useLogarithmicDepth = this.useLogarithmicDepth; + if (this.texture) { + if (serializeTexture) { + serializationObject.texture = this.texture.serialize(); + } + else { + serializationObject.textureUrl = this.texture.name; + serializationObject.invertY = this.texture._invertY; + } + } + serializationObject.sprites = []; + for (const sprite of this.sprites) { + serializationObject.sprites.push(sprite.serialize()); + } + serializationObject.metadata = this.metadata; + return serializationObject; + } + /** + * Parses a JSON object to create a new sprite manager. + * @param parsedManager The JSON object to parse + * @param scene The scene to create the sprite manager + * @param rootUrl The root url to use to load external dependencies like texture + * @returns the new sprite manager + */ + static Parse(parsedManager, scene, rootUrl) { + const manager = new SpriteManager(parsedManager.name, "", parsedManager.capacity, { + width: parsedManager.cellWidth, + height: parsedManager.cellHeight, + }, scene); + if (parsedManager.fogEnabled !== undefined) { + manager.fogEnabled = parsedManager.fogEnabled; + } + if (parsedManager.blendMode !== undefined) { + manager.blendMode = parsedManager.blendMode; + } + if (parsedManager.disableDepthWrite !== undefined) { + manager.disableDepthWrite = parsedManager.disableDepthWrite; + } + if (parsedManager.pixelPerfect !== undefined) { + manager.pixelPerfect = parsedManager.pixelPerfect; + } + if (parsedManager.useLogarithmicDepth !== undefined) { + manager.useLogarithmicDepth = parsedManager.useLogarithmicDepth; + } + if (parsedManager.metadata !== undefined) { + manager.metadata = parsedManager.metadata; + } + if (parsedManager.texture) { + manager.texture = Texture.Parse(parsedManager.texture, scene, rootUrl); + } + else if (parsedManager.textureName) { + manager.texture = new Texture(rootUrl + parsedManager.textureUrl, scene, false, parsedManager.invertY !== undefined ? parsedManager.invertY : true); + } + for (const parsedSprite of parsedManager.sprites) { + Sprite.Parse(parsedSprite, manager); + } + return manager; + } + /** + * Creates a sprite manager from a snippet saved in a remote file + * @param name defines the name of the sprite manager to create (can be null or empty to use the one from the json data) + * @param url defines the url to load from + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a promise that will resolve to the new sprite manager + */ + static ParseFromFileAsync(name, url, scene, rootUrl = "") { + return new Promise((resolve, reject) => { + const request = new WebRequest(); + request.addEventListener("readystatechange", () => { + if (request.readyState == 4) { + if (request.status == 200) { + const serializationObject = JSON.parse(request.responseText); + const output = SpriteManager.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl); + if (name) { + output.name = name; + } + resolve(output); + } + else { + reject("Unable to load the sprite manager"); + } + } + }); + request.open("GET", url); + request.send(); + }); + } + /** + * Creates a sprite manager from a snippet saved by the sprite editor + * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one) + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a promise that will resolve to the new sprite manager + */ + static ParseFromSnippetAsync(snippetId, scene, rootUrl = "") { + if (snippetId === "_BLANK") { + return Promise.resolve(new SpriteManager("Default sprite manager", "//playground.babylonjs.com/textures/player.png", 500, 64, scene)); + } + return new Promise((resolve, reject) => { + const request = new WebRequest(); + request.addEventListener("readystatechange", () => { + if (request.readyState == 4) { + if (request.status == 200) { + const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); + const serializationObject = JSON.parse(snippet.spriteManager); + const output = SpriteManager.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl); + output.snippetId = snippetId; + resolve(output); + } + else { + reject("Unable to load the snippet " + snippetId); + } + } + }); + request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); + request.send(); + }); + } +} +/** Define the Url to load snippets */ +SpriteManager.SnippetUrl = `https://snippet.babylonjs.com`; +/** + * Creates a sprite manager from a snippet saved by the sprite editor + * @deprecated Please use ParseFromSnippetAsync instead + * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one) + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a promise that will resolve to the new sprite manager + */ +SpriteManager.CreateFromSnippetAsync = SpriteManager.ParseFromSnippetAsync; + +/** + * Helps setting up some configuration for the babylon file loader. + */ +class BabylonFileLoaderConfiguration { +} +/** + * The loader does not allow injecting custom physics engine into the plugins. + * Unfortunately in ES6, we need to manually inject them into the plugin. + * So you could set this variable to your engine import to make it work. + */ +BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine = undefined; +let tempIndexContainer = {}; +let tempMaterialIndexContainer = {}; +let tempMorphTargetManagerIndexContainer = {}; +const parseMaterialByPredicate = (predicate, parsedData, scene, rootUrl) => { + if (!parsedData.materials) { + return null; + } + for (let index = 0, cache = parsedData.materials.length; index < cache; index++) { + const parsedMaterial = parsedData.materials[index]; + if (predicate(parsedMaterial)) { + return { parsedMaterial, material: Material.Parse(parsedMaterial, scene, rootUrl) }; + } + } + return null; +}; +const isDescendantOf = (mesh, names, hierarchyIds) => { + for (const i in names) { + if (mesh.name === names[i]) { + hierarchyIds.push(mesh.id); + return true; + } + } + if (mesh.parentId !== undefined && hierarchyIds.indexOf(mesh.parentId) !== -1) { + hierarchyIds.push(mesh.id); + return true; + } + return false; +}; +// eslint-disable-next-line @typescript-eslint/naming-convention +const logOperation = (operation, producer) => { + return (operation + + " of " + + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown")); +}; +const loadDetailLevels = (scene, mesh) => { + const mastermesh = mesh; + // Every value specified in the ids array of the lod data points to another mesh which should be used as the lower LOD level. + // The distances (or coverages) array values specified are used along with the lod mesh ids as a hint to determine the switching threshold for the various LODs. + if (mesh._waitingData.lods) { + if (mesh._waitingData.lods.ids && mesh._waitingData.lods.ids.length > 0) { + const lodmeshes = mesh._waitingData.lods.ids; + const wasenabled = mastermesh.isEnabled(false); + if (mesh._waitingData.lods.distances) { + const distances = mesh._waitingData.lods.distances; + if (distances.length >= lodmeshes.length) { + const culling = distances.length > lodmeshes.length ? distances[distances.length - 1] : 0; + mastermesh.setEnabled(false); + for (let index = 0; index < lodmeshes.length; index++) { + const lodid = lodmeshes[index]; + const lodmesh = scene.getMeshById(lodid); + if (lodmesh != null) { + mastermesh.addLODLevel(distances[index], lodmesh); + } + } + if (culling > 0) { + mastermesh.addLODLevel(culling, null); + } + if (wasenabled === true) { + mastermesh.setEnabled(true); + } + } + else { + Tools.Warn("Invalid level of detail distances for " + mesh.name); + } + } + } + mesh._waitingData.lods = null; + } +}; +const findParent = (parentId, parentInstanceIndex, scene) => { + if (typeof parentId !== "number") { + const parentEntry = scene.getLastEntryById(parentId); + if (parentEntry && parentInstanceIndex !== undefined && parentInstanceIndex !== null) { + const instance = parentEntry.instances[parseInt(parentInstanceIndex)]; + return instance; + } + return parentEntry; + } + const parent = tempIndexContainer[parentId]; + if (parent && parentInstanceIndex !== undefined && parentInstanceIndex !== null) { + const instance = parent.instances[parseInt(parentInstanceIndex)]; + return instance; + } + return parent; +}; +const findMaterial = (materialId, scene) => { + if (typeof materialId !== "number") { + return scene.getLastMaterialById(materialId, true); + } + return tempMaterialIndexContainer[materialId]; +}; +const loadAssetContainer = (scene, data, rootUrl, onError, addToScene = false) => { + const container = new AssetContainer(scene); + // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details + // when SceneLoader.debugLogging = true (default), or exception encountered. + // Everything stored in var log instead of writing separate lines to support only writing in exception, + // and avoid problems with multiple concurrent .babylon loads. + let log = "importScene has failed JSON parse"; + try { + // eslint-disable-next-line no-var + var parsedData = JSON.parse(data); + log = ""; + const fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING; + let index; + let cache; + // Environment texture + if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) { + // PBR needed for both HDR texture (gamma space) & a sky box + const isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true; + if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") { + const hdrSize = parsedData.environmentTextureSize ? parsedData.environmentTextureSize : 128; + const hdrTexture = new HDRCubeTexture((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, hdrSize, true, !isPBR, undefined, parsedData.environmentTexturePrefilterOnLoad); + if (parsedData.environmentTextureRotationY) { + hdrTexture.rotationY = parsedData.environmentTextureRotationY; + } + scene.environmentTexture = hdrTexture; + } + else { + if (typeof parsedData.environmentTexture === "object") { + const environmentTexture = CubeTexture.Parse(parsedData.environmentTexture, scene, rootUrl); + scene.environmentTexture = environmentTexture; + } + else if (parsedData.environmentTexture.endsWith(".env")) { + const compressedTexture = new CubeTexture((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, parsedData.environmentTextureForcedExtension); + if (parsedData.environmentTextureRotationY) { + compressedTexture.rotationY = parsedData.environmentTextureRotationY; + } + scene.environmentTexture = compressedTexture; + } + else { + const cubeTexture = CubeTexture.CreateFromPrefilteredData((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, parsedData.environmentTextureForcedExtension); + if (parsedData.environmentTextureRotationY) { + cubeTexture.rotationY = parsedData.environmentTextureRotationY; + } + scene.environmentTexture = cubeTexture; + } + } + if (parsedData.createDefaultSkybox === true) { + const skyboxScale = scene.activeCamera !== undefined && scene.activeCamera !== null ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000; + const skyboxBlurLevel = parsedData.skyboxBlurLevel || 0; + scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel); + } + container.environmentTexture = scene.environmentTexture; + } + // Environment Intensity + if (parsedData.environmentIntensity !== undefined && parsedData.environmentIntensity !== null) { + scene.environmentIntensity = parsedData.environmentIntensity; + } + // IBL Intensity + if (parsedData.iblIntensity !== undefined && parsedData.iblIntensity !== null) { + scene.iblIntensity = parsedData.iblIntensity; + } + // Lights + if (parsedData.lights !== undefined && parsedData.lights !== null) { + for (index = 0, cache = parsedData.lights.length; index < cache; index++) { + const parsedLight = parsedData.lights[index]; + const light = Light.Parse(parsedLight, scene); + if (light) { + tempIndexContainer[parsedLight.uniqueId] = light; + container.lights.push(light); + light._parentContainer = container; + log += index === 0 ? "\n\tLights:" : ""; + log += "\n\t\t" + light.toString(fullDetails); + } + } + } + // Reflection probes + if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) { + for (index = 0, cache = parsedData.reflectionProbes.length; index < cache; index++) { + const parsedReflectionProbe = parsedData.reflectionProbes[index]; + const reflectionProbe = ReflectionProbe.Parse(parsedReflectionProbe, scene, rootUrl); + if (reflectionProbe) { + container.reflectionProbes.push(reflectionProbe); + reflectionProbe._parentContainer = container; + log += index === 0 ? "\n\tReflection Probes:" : ""; + log += "\n\t\t" + reflectionProbe.toString(fullDetails); + } + } + } + // Animations + if (parsedData.animations !== undefined && parsedData.animations !== null) { + for (index = 0, cache = parsedData.animations.length; index < cache; index++) { + const parsedAnimation = parsedData.animations[index]; + const internalClass = GetClass("BABYLON.Animation"); + if (internalClass) { + const animation = internalClass.Parse(parsedAnimation); + scene.animations.push(animation); + container.animations.push(animation); + log += index === 0 ? "\n\tAnimations:" : ""; + log += "\n\t\t" + animation.toString(fullDetails); + } + } + } + // Materials + if (parsedData.materials !== undefined && parsedData.materials !== null) { + for (index = 0, cache = parsedData.materials.length; index < cache; index++) { + const parsedMaterial = parsedData.materials[index]; + const mat = Material.Parse(parsedMaterial, scene, rootUrl); + if (mat) { + tempMaterialIndexContainer[parsedMaterial.uniqueId || parsedMaterial.id] = mat; + container.materials.push(mat); + mat._parentContainer = container; + log += index === 0 ? "\n\tMaterials:" : ""; + log += "\n\t\t" + mat.toString(fullDetails); + // Textures + const textures = mat.getActiveTextures(); + textures.forEach((t) => { + if (container.textures.indexOf(t) == -1) { + container.textures.push(t); + t._parentContainer = container; + } + }); + } + } + } + if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) { + for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) { + const parsedMultiMaterial = parsedData.multiMaterials[index]; + const mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene); + tempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat; + container.multiMaterials.push(mmat); + mmat._parentContainer = container; + log += index === 0 ? "\n\tMultiMaterials:" : ""; + log += "\n\t\t" + mmat.toString(fullDetails); + // Textures + const textures = mmat.getActiveTextures(); + textures.forEach((t) => { + if (container.textures.indexOf(t) == -1) { + container.textures.push(t); + t._parentContainer = container; + } + }); + } + } + // Morph targets + if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) { + for (const parsedManager of parsedData.morphTargetManagers) { + const manager = MorphTargetManager.Parse(parsedManager, scene); + tempMorphTargetManagerIndexContainer[parsedManager.id] = manager; + container.morphTargetManagers.push(manager); + manager._parentContainer = container; + } + } + // Skeletons + if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) { + for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) { + const parsedSkeleton = parsedData.skeletons[index]; + const skeleton = Skeleton.Parse(parsedSkeleton, scene); + container.skeletons.push(skeleton); + skeleton._parentContainer = container; + log += index === 0 ? "\n\tSkeletons:" : ""; + log += "\n\t\t" + skeleton.toString(fullDetails); + } + } + // Geometries + const geometries = parsedData.geometries; + if (geometries !== undefined && geometries !== null) { + const addedGeometry = new Array(); + // VertexData + const vertexData = geometries.vertexData; + if (vertexData !== undefined && vertexData !== null) { + for (index = 0, cache = vertexData.length; index < cache; index++) { + const parsedVertexData = vertexData[index]; + addedGeometry.push(Geometry.Parse(parsedVertexData, scene, rootUrl)); + } + } + addedGeometry.forEach((g) => { + if (g) { + container.geometries.push(g); + g._parentContainer = container; + } + }); + } + // Transform nodes + if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) { + for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) { + const parsedTransformNode = parsedData.transformNodes[index]; + const node = TransformNode.Parse(parsedTransformNode, scene, rootUrl); + tempIndexContainer[parsedTransformNode.uniqueId] = node; + container.transformNodes.push(node); + node._parentContainer = container; + } + } + // Meshes + if (parsedData.meshes !== undefined && parsedData.meshes !== null) { + for (index = 0, cache = parsedData.meshes.length; index < cache; index++) { + const parsedMesh = parsedData.meshes[index]; + const mesh = Mesh.Parse(parsedMesh, scene, rootUrl); + tempIndexContainer[parsedMesh.uniqueId] = mesh; + container.meshes.push(mesh); + mesh._parentContainer = container; + if (mesh.hasInstances) { + for (const instance of mesh.instances) { + container.meshes.push(instance); + instance._parentContainer = container; + } + } + log += index === 0 ? "\n\tMeshes:" : ""; + log += "\n\t\t" + mesh.toString(fullDetails); + } + } + // Cameras + if (parsedData.cameras !== undefined && parsedData.cameras !== null) { + for (index = 0, cache = parsedData.cameras.length; index < cache; index++) { + const parsedCamera = parsedData.cameras[index]; + const camera = Camera.Parse(parsedCamera, scene); + tempIndexContainer[parsedCamera.uniqueId] = camera; + container.cameras.push(camera); + camera._parentContainer = container; + log += index === 0 ? "\n\tCameras:" : ""; + log += "\n\t\t" + camera.toString(fullDetails); + } + } + // Postprocesses + if (parsedData.postProcesses !== undefined && parsedData.postProcesses !== null) { + for (index = 0, cache = parsedData.postProcesses.length; index < cache; index++) { + const parsedPostProcess = parsedData.postProcesses[index]; + const postProcess = PostProcess.Parse(parsedPostProcess, scene, rootUrl); + if (postProcess) { + container.postProcesses.push(postProcess); + postProcess._parentContainer = container; + log += index === 0 ? "\nPostprocesses:" : ""; + log += "\n\t\t" + postProcess.toString(); + } + } + } + // Animation Groups + if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) { + for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) { + const parsedAnimationGroup = parsedData.animationGroups[index]; + const animationGroup = AnimationGroup.Parse(parsedAnimationGroup, scene); + container.animationGroups.push(animationGroup); + animationGroup._parentContainer = container; + log += index === 0 ? "\n\tAnimationGroups:" : ""; + log += "\n\t\t" + animationGroup.toString(fullDetails); + } + } + // Sprites + if (parsedData.spriteManagers) { + for (let index = 0, cache = parsedData.spriteManagers.length; index < cache; index++) { + const parsedSpriteManager = parsedData.spriteManagers[index]; + const spriteManager = SpriteManager.Parse(parsedSpriteManager, scene, rootUrl); + log += "\n\t\tSpriteManager " + spriteManager.name; + } + } + // Browsing all the graph to connect the dots + for (index = 0, cache = scene.cameras.length; index < cache; index++) { + const camera = scene.cameras[index]; + if (camera._waitingParentId !== null) { + camera.parent = findParent(camera._waitingParentId, camera._waitingParentInstanceIndex, scene); + camera._waitingParentId = null; + camera._waitingParentInstanceIndex = null; + } + } + for (index = 0, cache = scene.lights.length; index < cache; index++) { + const light = scene.lights[index]; + if (light && light._waitingParentId !== null) { + light.parent = findParent(light._waitingParentId, light._waitingParentInstanceIndex, scene); + light._waitingParentId = null; + light._waitingParentInstanceIndex = null; + } + } + // Connect parents & children and parse actions and lods + for (index = 0, cache = scene.transformNodes.length; index < cache; index++) { + const transformNode = scene.transformNodes[index]; + if (transformNode._waitingParentId !== null) { + transformNode.parent = findParent(transformNode._waitingParentId, transformNode._waitingParentInstanceIndex, scene); + transformNode._waitingParentId = null; + transformNode._waitingParentInstanceIndex = null; + } + } + for (index = 0, cache = scene.meshes.length; index < cache; index++) { + const mesh = scene.meshes[index]; + if (mesh._waitingParentId !== null) { + mesh.parent = findParent(mesh._waitingParentId, mesh._waitingParentInstanceIndex, scene); + mesh._waitingParentId = null; + mesh._waitingParentInstanceIndex = null; + } + if (mesh._waitingData.lods) { + loadDetailLevels(scene, mesh); + } + } + // link multimats with materials + scene.multiMaterials.forEach((multimat) => { + multimat._waitingSubMaterialsUniqueIds.forEach((subMaterial) => { + multimat.subMaterials.push(findMaterial(subMaterial, scene)); + }); + multimat._waitingSubMaterialsUniqueIds = []; + }); + // link meshes with materials + scene.meshes.forEach((mesh) => { + if (mesh._waitingMaterialId !== null) { + mesh.material = findMaterial(mesh._waitingMaterialId, scene); + mesh._waitingMaterialId = null; + } + }); + // link meshes with morph target managers + scene.meshes.forEach((mesh) => { + if (mesh._waitingMorphTargetManagerId !== null) { + mesh.morphTargetManager = tempMorphTargetManagerIndexContainer[mesh._waitingMorphTargetManagerId]; + mesh._waitingMorphTargetManagerId = null; + } + }); + // link skeleton transform nodes + for (index = 0, cache = scene.skeletons.length; index < cache; index++) { + const skeleton = scene.skeletons[index]; + if (skeleton._hasWaitingData) { + if (skeleton.bones != null) { + skeleton.bones.forEach((bone) => { + if (bone._waitingTransformNodeId) { + const linkTransformNode = scene.getLastEntryById(bone._waitingTransformNodeId); + if (linkTransformNode) { + bone.linkTransformNode(linkTransformNode); + } + bone._waitingTransformNodeId = null; + } + }); + } + skeleton._hasWaitingData = null; + } + } + // freeze world matrix application + for (index = 0, cache = scene.meshes.length; index < cache; index++) { + const currentMesh = scene.meshes[index]; + if (currentMesh._waitingData.freezeWorldMatrix) { + currentMesh.freezeWorldMatrix(); + currentMesh._waitingData.freezeWorldMatrix = null; + } + else { + currentMesh.computeWorldMatrix(true); + } + } + // Lights exclusions / inclusions + for (index = 0, cache = scene.lights.length; index < cache; index++) { + const light = scene.lights[index]; + // Excluded check + if (light._excludedMeshesIds.length > 0) { + for (let excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) { + const excludedMesh = scene.getMeshById(light._excludedMeshesIds[excludedIndex]); + if (excludedMesh) { + light.excludedMeshes.push(excludedMesh); + } + } + light._excludedMeshesIds = []; + } + // Included check + if (light._includedOnlyMeshesIds.length > 0) { + for (let includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) { + const includedOnlyMesh = scene.getMeshById(light._includedOnlyMeshesIds[includedOnlyIndex]); + if (includedOnlyMesh) { + light.includedOnlyMeshes.push(includedOnlyMesh); + } + } + light._includedOnlyMeshesIds = []; + } + } + scene.geometries.forEach((g) => { + g._loadedUniqueId = ""; + }); + Parse(parsedData, scene, container, rootUrl); + // Actions (scene) Done last as it can access other objects. + for (index = 0, cache = scene.meshes.length; index < cache; index++) { + const mesh = scene.meshes[index]; + if (mesh._waitingData.actions) { + ActionManager.Parse(mesh._waitingData.actions, mesh, scene); + mesh._waitingData.actions = null; + } + } + if (parsedData.actions !== undefined && parsedData.actions !== null) { + ActionManager.Parse(parsedData.actions, null, scene); + } + } + catch (err) { + const msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log; + if (onError) { + onError(msg, err); + } + else { + Logger.Log(msg); + throw err; + } + } + finally { + tempIndexContainer = {}; + tempMaterialIndexContainer = {}; + tempMorphTargetManagerIndexContainer = {}; + if (!addToScene) { + container.removeAllFromScene(); + } + if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) { + Logger.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : "")); + } + } + return container; +}; +SceneLoader.RegisterPlugin({ + name: "babylon.js", + extensions: ".babylon", + canDirectLoad: (data) => { + if (data.indexOf("babylon") !== -1) { + // We consider that the producer string is filled + return true; + } + return false; + }, + importMesh: (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) => { + // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details + // when SceneLoader.debugLogging = true (default), or exception encountered. + // Everything stored in var log instead of writing separate lines to support only writing in exception, + // and avoid problems with multiple concurrent .babylon loads. + let log = "importMesh has failed JSON parse"; + try { + // eslint-disable-next-line no-var + var parsedData = JSON.parse(data); + log = ""; + const fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING; + if (!meshesNames) { + meshesNames = null; + } + else if (!Array.isArray(meshesNames)) { + meshesNames = [meshesNames]; + } + const hierarchyIds = []; + const parsedIdToNodeMap = new Map(); + // Transform nodes (the overall idea is to load all of them as this is super fast and then get rid of the ones we don't need) + const loadedTransformNodes = []; + if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) { + for (let index = 0, cache = parsedData.transformNodes.length; index < cache; index++) { + const parsedJSONTransformNode = parsedData.transformNodes[index]; + const parsedTransformNode = TransformNode.Parse(parsedJSONTransformNode, scene, rootUrl); + loadedTransformNodes.push(parsedTransformNode); + parsedIdToNodeMap.set(parsedTransformNode._waitingParsedUniqueId, parsedTransformNode); + parsedTransformNode._waitingParsedUniqueId = null; + } + } + if (parsedData.meshes !== undefined && parsedData.meshes !== null) { + const loadedSkeletonsIds = []; + const loadedMaterialsIds = []; + const loadedMaterialsUniqueIds = []; + const loadedMorphTargetManagerIds = []; + for (let index = 0, cache = parsedData.meshes.length; index < cache; index++) { + const parsedMesh = parsedData.meshes[index]; + if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) { + if (meshesNames !== null) { + // Remove found mesh name from list. + delete meshesNames[meshesNames.indexOf(parsedMesh.name)]; + } + //Geometry? + if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) { + //does the file contain geometries? + if (parsedData.geometries !== undefined && parsedData.geometries !== null) { + //find the correct geometry and add it to the scene + let found = false; + ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach((geometryType) => { + if (found === true || !parsedData.geometries[geometryType] || !Array.isArray(parsedData.geometries[geometryType])) { + return; + } + else { + parsedData.geometries[geometryType].forEach((parsedGeometryData) => { + if (parsedGeometryData.id === parsedMesh.geometryId) { + switch (geometryType) { + case "vertexData": + Geometry.Parse(parsedGeometryData, scene, rootUrl); + break; + } + found = true; + } + }); + } + }); + if (found === false) { + Logger.Warn("Geometry not found for mesh " + parsedMesh.id); + } + } + } + // Material ? + if (parsedMesh.materialUniqueId || parsedMesh.materialId) { + // if we have a unique ID, look up and store in loadedMaterialsUniqueIds, else use loadedMaterialsIds + const materialArray = parsedMesh.materialUniqueId ? loadedMaterialsUniqueIds : loadedMaterialsIds; + let materialFound = materialArray.indexOf(parsedMesh.materialUniqueId || parsedMesh.materialId) !== -1; + if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) { + // Loads a submaterial of a multimaterial + const loadSubMaterial = (subMatId, predicate) => { + materialArray.push(subMatId); + const mat = parseMaterialByPredicate(predicate, parsedData, scene, rootUrl); + if (mat && mat.material) { + tempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material; + log += "\n\tMaterial " + mat.material.toString(fullDetails); + } + }; + for (let multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) { + const parsedMultiMaterial = parsedData.multiMaterials[multimatIndex]; + if ((parsedMesh.materialUniqueId && parsedMultiMaterial.uniqueId === parsedMesh.materialUniqueId) || + parsedMultiMaterial.id === parsedMesh.materialId) { + if (parsedMultiMaterial.materialsUniqueIds) { + // if the materials inside the multimat are stored by unique id + parsedMultiMaterial.materialsUniqueIds.forEach((subMatId) => loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.uniqueId === subMatId)); + } + else { + // if the mats are stored by id instead + parsedMultiMaterial.materials.forEach((subMatId) => loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.id === subMatId)); + } + materialArray.push(parsedMultiMaterial.uniqueId || parsedMultiMaterial.id); + const mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene); + tempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat; + if (mmat) { + materialFound = true; + log += "\n\tMulti-Material " + mmat.toString(fullDetails); + } + break; + } + } + } + if (materialFound === false) { + materialArray.push(parsedMesh.materialUniqueId || parsedMesh.materialId); + const mat = parseMaterialByPredicate((parsedMaterial) => (parsedMesh.materialUniqueId && parsedMaterial.uniqueId === parsedMesh.materialUniqueId) || parsedMaterial.id === parsedMesh.materialId, parsedData, scene, rootUrl); + if (!mat || !mat.material) { + Logger.Warn("Material not found for mesh " + parsedMesh.id); + } + else { + tempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material; + log += "\n\tMaterial " + mat.material.toString(fullDetails); + } + } + } + // Skeleton ? + if (parsedMesh.skeletonId !== null && + parsedMesh.skeletonId !== undefined && + parsedData.skeletonId !== -1 && + parsedData.skeletons !== undefined && + parsedData.skeletons !== null) { + const skeletonAlreadyLoaded = loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1; + if (!skeletonAlreadyLoaded) { + for (let skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) { + const parsedSkeleton = parsedData.skeletons[skeletonIndex]; + if (parsedSkeleton.id === parsedMesh.skeletonId) { + const skeleton = Skeleton.Parse(parsedSkeleton, scene); + skeletons.push(skeleton); + loadedSkeletonsIds.push(parsedSkeleton.id); + log += "\n\tSkeleton " + skeleton.toString(fullDetails); + } + } + } + } + // Morph targets ? + if (parsedMesh.morphTargetManagerId > -1 && parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) { + const morphTargetManagerAlreadyLoaded = loadedMorphTargetManagerIds.indexOf(parsedMesh.morphTargetManagerId) > -1; + if (!morphTargetManagerAlreadyLoaded) { + for (let morphTargetManagerIndex = 0; morphTargetManagerIndex < parsedData.morphTargetManagers.length; morphTargetManagerIndex++) { + const parsedManager = parsedData.morphTargetManagers[morphTargetManagerIndex]; + if (parsedManager.id === parsedMesh.morphTargetManagerId) { + const morphTargetManager = MorphTargetManager.Parse(parsedManager, scene); + tempMorphTargetManagerIndexContainer[parsedManager.id] = morphTargetManager; + loadedMorphTargetManagerIds.push(parsedManager.id); + log += "\nMorph target manager" + morphTargetManager.toString(); + } + } + } + } + const mesh = Mesh.Parse(parsedMesh, scene, rootUrl); + meshes.push(mesh); + parsedIdToNodeMap.set(mesh._waitingParsedUniqueId, mesh); + mesh._waitingParsedUniqueId = null; + log += "\n\tMesh " + mesh.toString(fullDetails); + } + } + // link multimats with materials + scene.multiMaterials.forEach((multimat) => { + multimat._waitingSubMaterialsUniqueIds.forEach((subMaterial) => { + multimat.subMaterials.push(findMaterial(subMaterial, scene)); + }); + multimat._waitingSubMaterialsUniqueIds = []; + }); + // link meshes with materials + scene.meshes.forEach((mesh) => { + if (mesh._waitingMaterialId !== null) { + mesh.material = findMaterial(mesh._waitingMaterialId, scene); + mesh._waitingMaterialId = null; + } + }); + // link meshes with morph target managers + scene.meshes.forEach((mesh) => { + if (mesh._waitingMorphTargetManagerId !== null) { + mesh.morphTargetManager = tempMorphTargetManagerIndexContainer[mesh._waitingMorphTargetManagerId]; + mesh._waitingMorphTargetManagerId = null; + } + }); + // Connecting parents and lods + for (let index = 0, cache = scene.transformNodes.length; index < cache; index++) { + const transformNode = scene.transformNodes[index]; + if (transformNode._waitingParentId !== null) { + let parent = parsedIdToNodeMap.get(parseInt(transformNode._waitingParentId)) || null; + if (parent === null) { + parent = scene.getLastEntryById(transformNode._waitingParentId); + } + let parentNode = parent; + if (transformNode._waitingParentInstanceIndex) { + parentNode = parent.instances[parseInt(transformNode._waitingParentInstanceIndex)]; + transformNode._waitingParentInstanceIndex = null; + } + transformNode.parent = parentNode; + transformNode._waitingParentId = null; + } + } + let currentMesh; + for (let index = 0, cache = scene.meshes.length; index < cache; index++) { + currentMesh = scene.meshes[index]; + if (currentMesh._waitingParentId) { + let parent = parsedIdToNodeMap.get(parseInt(currentMesh._waitingParentId)) || null; + if (parent === null) { + parent = scene.getLastEntryById(currentMesh._waitingParentId); + } + let parentNode = parent; + if (currentMesh._waitingParentInstanceIndex) { + parentNode = parent.instances[parseInt(currentMesh._waitingParentInstanceIndex)]; + currentMesh._waitingParentInstanceIndex = null; + } + currentMesh.parent = parentNode; + currentMesh._waitingParentId = null; + } + if (currentMesh._waitingData.lods) { + loadDetailLevels(scene, currentMesh); + } + } + // Remove unused transform nodes + for (const transformNode of loadedTransformNodes) { + const childMeshes = transformNode.getChildMeshes(false); + if (!childMeshes.length) { + transformNode.dispose(); + } + } + // link skeleton transform nodes + for (let index = 0, cache = scene.skeletons.length; index < cache; index++) { + const skeleton = scene.skeletons[index]; + if (skeleton._hasWaitingData) { + if (skeleton.bones != null) { + skeleton.bones.forEach((bone) => { + if (bone._waitingTransformNodeId) { + const linkTransformNode = scene.getLastEntryById(bone._waitingTransformNodeId); + if (linkTransformNode) { + bone.linkTransformNode(linkTransformNode); + } + bone._waitingTransformNodeId = null; + } + }); + } + skeleton._hasWaitingData = null; + } + } + // freeze and compute world matrix application + for (let index = 0, cache = scene.meshes.length; index < cache; index++) { + currentMesh = scene.meshes[index]; + if (currentMesh._waitingData.freezeWorldMatrix) { + currentMesh.freezeWorldMatrix(); + currentMesh._waitingData.freezeWorldMatrix = null; + } + else { + currentMesh.computeWorldMatrix(true); + } + } + } + // Particles + if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) { + const parser = GetIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM); + if (parser) { + for (let index = 0, cache = parsedData.particleSystems.length; index < cache; index++) { + const parsedParticleSystem = parsedData.particleSystems[index]; + if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) { + particleSystems.push(parser(parsedParticleSystem, scene, rootUrl)); + } + } + } + } + scene.geometries.forEach((g) => { + g._loadedUniqueId = ""; + }); + return true; + } + catch (err) { + const msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log; + if (onError) { + onError(msg, err); + } + else { + Logger.Log(msg); + throw err; + } + } + finally { + if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) { + Logger.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : "")); + } + tempMaterialIndexContainer = {}; + tempMorphTargetManagerIndexContainer = {}; + } + return false; + }, + load: (scene, data, rootUrl, onError) => { + // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details + // when SceneLoader.debugLogging = true (default), or exception encountered. + // Everything stored in var log instead of writing separate lines to support only writing in exception, + // and avoid problems with multiple concurrent .babylon loads. + let log = "importScene has failed JSON parse"; + try { + // eslint-disable-next-line no-var + var parsedData = JSON.parse(data); + log = ""; + // Scene + if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) { + scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !SceneLoader.ForceFullSceneLoadingForIncremental; + } + if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) { + scene.autoClear = parsedData.autoClear; + } + if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) { + scene.clearColor = Color4.FromArray(parsedData.clearColor); + } + if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) { + scene.ambientColor = Color3.FromArray(parsedData.ambientColor); + } + if (parsedData.gravity !== undefined && parsedData.gravity !== null) { + scene.gravity = Vector3.FromArray(parsedData.gravity); + } + if (parsedData.useRightHandedSystem !== undefined) { + scene.useRightHandedSystem = !!parsedData.useRightHandedSystem; + } + // Fog + if (parsedData.fogMode !== undefined && parsedData.fogMode !== null) { + scene.fogMode = parsedData.fogMode; + } + if (parsedData.fogColor !== undefined && parsedData.fogColor !== null) { + scene.fogColor = Color3.FromArray(parsedData.fogColor); + } + if (parsedData.fogStart !== undefined && parsedData.fogStart !== null) { + scene.fogStart = parsedData.fogStart; + } + if (parsedData.fogEnd !== undefined && parsedData.fogEnd !== null) { + scene.fogEnd = parsedData.fogEnd; + } + if (parsedData.fogDensity !== undefined && parsedData.fogDensity !== null) { + scene.fogDensity = parsedData.fogDensity; + } + log += "\tFog mode for scene: "; + switch (scene.fogMode) { + case 0: + log += "none\n"; + break; + // getters not compiling, so using hardcoded + case 1: + log += "exp\n"; + break; + case 2: + log += "exp2\n"; + break; + case 3: + log += "linear\n"; + break; + } + //Physics + if (parsedData.physicsEnabled) { + let physicsPlugin; + if (parsedData.physicsEngine === "cannon" || parsedData.physicsEngine === CannonJSPlugin.name) { + physicsPlugin = new CannonJSPlugin(undefined, undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine); + } + else if (parsedData.physicsEngine === "oimo" || parsedData.physicsEngine === OimoJSPlugin.name) { + physicsPlugin = new OimoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine); + } + else if (parsedData.physicsEngine === "ammo" || parsedData.physicsEngine === AmmoJSPlugin.name) { + physicsPlugin = new AmmoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine, undefined); + } + log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n"; + //else - default engine, which is currently oimo + const physicsGravity = parsedData.gravity ? Vector3.FromArray(parsedData.gravity) : parsedData.physicsGravity ? Vector3.FromArray(parsedData.physicsGravity) : null; + scene.enablePhysics(physicsGravity, physicsPlugin); + } + // Metadata + if (parsedData.metadata !== undefined && parsedData.metadata !== null) { + scene.metadata = parsedData.metadata; + } + //collisions, if defined. otherwise, default is true + if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) { + scene.collisionsEnabled = parsedData.collisionsEnabled; + } + const container = loadAssetContainer(scene, data, rootUrl, onError, true); + if (!container) { + return false; + } + if (parsedData.autoAnimate) { + scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0); + } + if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) { + scene.setActiveCameraById(parsedData.activeCameraID); + } + // Finish + return true; + } + catch (err) { + const msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log; + if (onError) { + onError(msg, err); + } + else { + Logger.Log(msg); + throw err; + } + } + finally { + if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) { + Logger.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : "")); + } + } + return false; + }, + loadAssetContainer: (scene, data, rootUrl, onError) => { + const container = loadAssetContainer(scene, data, rootUrl, onError); + return container; + }, +}); + +// Do not edit. +const name$6M = "backgroundUboDeclaration"; +const shader$6L = `uniform vPrimaryColor: vec4f;uniform vPrimaryColorShadow: vec4f;uniform vDiffuseInfos: vec2f;uniform vReflectionInfos: vec2f;uniform diffuseMatrix: mat4x4f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform fFovMultiplier: f32;uniform pointSize: f32;uniform shadowLevel: f32;uniform alpha: f32;uniform vBackgroundCenter: vec3f;uniform vReflectionControl: vec4f;uniform projectedGroundInfos: vec2f; +#include +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6M]) { + ShaderStore.IncludesShadersStoreWGSL[name$6M] = shader$6L; +} + +// Do not edit. +const name$6L = "fogVertexDeclaration"; +const shader$6K = `#ifdef FOG +varying vFogDistance: vec3f; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6L]) { + ShaderStore.IncludesShadersStoreWGSL[name$6L] = shader$6K; +} + +// Do not edit. +const name$6K = "lightVxUboDeclaration"; +const shader$6J = `#ifdef LIGHT{X} +struct Light{X} +{vLightData: vec4f, +vLightDiffuse: vec4f, +vLightSpecular: vec4f, +#ifdef SPOTLIGHT{X} +vLightDirection: vec4f, +vLightFalloff: vec4f, +#elif defined(POINTLIGHT{X}) +vLightFalloff: vec4f, +#elif defined(HEMILIGHT{X}) +vLightGround: vec3f, +#endif +#if defined(AREALIGHT{X}) +vLightWidth: vec4f, +vLightHeight: vec4f, +#endif +shadowsInfo: vec4f, +depthValues: vec2f} ;var light{X} : Light{X}; +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f; +#elif defined(SHADOWCUBE{X}) +#else +varying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f; +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6K]) { + ShaderStore.IncludesShadersStoreWGSL[name$6K] = shader$6J; +} +/** @internal */ +const lightVxUboDeclarationWGSL = { name: name$6K, shader: shader$6J }; + +const lightVxUboDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lightVxUboDeclarationWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6J = "logDepthDeclaration"; +const shader$6I = `#ifdef LOGARITHMICDEPTH +uniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6J]) { + ShaderStore.IncludesShadersStoreWGSL[name$6J] = shader$6I; +} + +// Do not edit. +const name$6I = "fogVertex"; +const shader$6H = `#ifdef FOG +#ifdef SCENE_UBO +vertexOutputs.vFogDistance=(scene.view*worldPos).xyz; +#else +vertexOutputs.vFogDistance=(uniforms.view*worldPos).xyz; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6I]) { + ShaderStore.IncludesShadersStoreWGSL[name$6I] = shader$6H; +} + +// Do not edit. +const name$6H = "shadowsVertex"; +const shader$6G = `#ifdef SHADOWS +#if defined(SHADOWCSM{X}) +vertexOutputs.vPositionFromCamera{X}=scene.view*worldPos; +#if SHADOWCSMNUM_CASCADES{X}>0 +vertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos; +#ifdef USE_REVERSE_DEPTHBUFFER +vertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#else +vertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#endif +#endif +#if SHADOWCSMNUM_CASCADES{X}>1 +vertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos; +#ifdef USE_REVERSE_DEPTHBUFFER +vertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#else +vertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#endif +#endif +#if SHADOWCSMNUM_CASCADES{X}>2 +vertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos; +#ifdef USE_REVERSE_DEPTHBUFFER +vertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#else +vertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#endif +#endif +#if SHADOWCSMNUM_CASCADES{X}>3 +vertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos; +#ifdef USE_REVERSE_DEPTHBUFFER +vertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#else +vertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#endif +#endif +#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X}) +vertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos; +#ifdef USE_REVERSE_DEPTHBUFFER +vertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#else +vertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6H]) { + ShaderStore.IncludesShadersStoreWGSL[name$6H] = shader$6G; +} +/** @internal */ +const shadowsVertexWGSL = { name: name$6H, shader: shader$6G }; + +const shadowsVertex$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowsVertexWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6G = "logDepthVertex"; +const shader$6F = `#ifdef LOGARITHMICDEPTH +vertexOutputs.vFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vertexOutputs.vFragmentDepth))*uniforms.logarithmicDepthConstant; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6G]) { + ShaderStore.IncludesShadersStoreWGSL[name$6G] = shader$6F; +} + +// Do not edit. +const name$6F = "backgroundVertexShader"; +const shader$6E = `#include +#include +attribute position: vec3f; +#ifdef NORMAL +attribute normal: vec3f; +#endif +#include +#include +#include +varying vPositionW: vec3f; +#ifdef NORMAL +varying vNormalW: vec3f; +#endif +#ifdef UV1 +attribute uv: vec2f; +#endif +#ifdef UV2 +attribute uv2: vec2f; +#endif +#ifdef MAINUV1 +varying vMainUV1: vec2f; +#endif +#ifdef MAINUV2 +varying vMainUV2: vec2f; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +varying vDiffuseUV: vec2f; +#endif +#include +#include +#include[0..maxSimultaneousLights] +#ifdef REFLECTIONMAP_SKYBOX +varying vPositionUVW: vec3f; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vDirectionW: vec3f; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +#ifdef REFLECTIONMAP_SKYBOX +vertexOutputs.vPositionUVW=input.position; +#endif +#include +#include +#include +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(input.position,1.0);} else {vertexOutputs.position=scene.viewProjectionR*finalWorld* vec4f(input.position,1.0);} +#else +vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(input.position,1.0); +#endif +var worldPos: vec4f=finalWorld* vec4f(input.position,1.0);vertexOutputs.vPositionW= worldPos.xyz; +#ifdef NORMAL +var normalWorld: mat3x3f=mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz); +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vertexOutputs.vNormalW=normalize(normalWorld*input.normal); +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vertexOutputs.vDirectionW=normalize((finalWorld*vec4f(input.position,0.0)).xyz); +#ifdef EQUIRECTANGULAR_RELFECTION_FOV +var screenToWorld: mat3x3f=inverseMat3( mat3x3f(finalWorld*scene.viewProjection));var segment: vec3f=mix(vertexOutputs.vDirectionW,screenToWorld* vec3f(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vertexOutputs.vDirectionW=normalize(segment);} else {vertexOutputs.vDirectionW=normalize(vertexOutputs.vDirectionW+(vertexOutputs.vDirectionW-segment));} +#endif +#endif +#ifndef UV1 +var uv: vec2f=vec2f(0.,0.); +#else +var uv=input.uv; +#endif +#ifndef UV2 +var uv2: vec2f=vec2f(0.,0.); +#else +var uv2=input.uv2; +#endif +#ifdef MAINUV1 +vertexOutputs.vMainUV1=uv; +#endif +#ifdef MAINUV2 +vertexOutputs.vMainUV2=uv2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +if (uniforms.vDiffuseInfos.x==0.) +{vertexOutputs.vDiffuseUV= (uniforms.diffuseMatrix* vec4f(uv,1.0,0.0)).xy;} +else +{vertexOutputs.vDiffuseUV= (uniforms.diffuseMatrix* vec4f(uv2,1.0,0.0)).xy;} +#endif +#include +#include +#include[0..maxSimultaneousLights] +#ifdef VERTEXCOLOR +vertexOutputs.vColor=vertexInputs.color; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$6F]) { + ShaderStore.ShadersStoreWGSL[name$6F] = shader$6E; +} +/** @internal */ +const backgroundVertexShaderWGSL = { name: name$6F, shader: shader$6E }; + +const background_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + backgroundVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6E = "reflectionFunction"; +const shader$6D = `fn computeFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f +{var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0); } +fn computeMirroredFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f +{var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(1.0-s,t,0); } +fn computeEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f +{var cameraToVertex: vec3f=normalize(worldPos.xyz-eyePosition);var r: vec3f=normalize(reflect(cameraToVertex,worldNormal));r= (reflectionMatrix* vec4f(r,0)).xyz;var lon: f32=atan2(r.z,r.x);var lat: f32=acos(r.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0);} +fn computeSphericalCoords(worldPos: vec4f,worldNormal: vec3f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f +{var viewDir: vec3f=normalize((view*worldPos).xyz);var viewNormal: vec3f=normalize((view* vec4f(worldNormal,0.0)).xyz);var r: vec3f=reflect(viewDir,viewNormal);r= (reflectionMatrix* vec4f(r,0)).xyz;r.z=r.z-1.0;var m: f32=2.0*length(r);return vec3f(r.x/m+0.5,1.0-r.y/m-0.5,0);} +fn computePlanarCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f +{var viewDir: vec3f=worldPos.xyz-eyePosition;var coords: vec3f=normalize(reflect(viewDir,worldNormal));return (reflectionMatrix* vec4f(coords,1)).xyz;} +fn computeCubicCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f +{var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords= (reflectionMatrix* vec4f(coords,0)).xyz; +#ifdef INVERTCUBICMAP +coords.y*=-1.0; +#endif +return coords;} +fn computeCubicLocalCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f,reflectionSize: vec3f,reflectionPosition: vec3f)->vec3f +{var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=(reflectionMatrix* vec4f(coords,0)).xyz; +#ifdef INVERTCUBICMAP +coords.y*=-1.0; +#endif +return coords;} +fn computeProjectionCoords(worldPos: vec4f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f +{return (reflectionMatrix*(view*worldPos)).xyz;} +fn computeSkyBoxCoords(positionW: vec3f,reflectionMatrix: mat4x4f)->vec3f +{return (reflectionMatrix* vec4f(positionW,1.)).xyz;} +#ifdef REFLECTION +fn computeReflectionCoords(worldPos: vec4f,worldNormal: vec3f)->vec3f +{ +#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED +var direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction); +#endif +#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED +var direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction); +#endif +#ifdef REFLECTIONMAP_EQUIRECTANGULAR +return computeEquirectangularCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_SPHERICAL +return computeSphericalCoords(worldPos,worldNormal,scene.view,uniforms.reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_PLANAR +return computePlanarCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_CUBIC +#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC +return computeCubicLocalCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix,uniforms.vReflectionSize,uniforms.vReflectionPosition); +#else +return computeCubicCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix); +#endif +#endif +#ifdef REFLECTIONMAP_PROJECTION +return computeProjectionCoords(worldPos,scene.view,uniforms.reflectionMatrix); +#endif +#ifndef REFLECTIONMAP_CUBIC +#ifdef REFLECTIONMAP_SKYBOX +return computeSkyBoxCoords(fragmentInputs.vPositionUVW,uniforms.reflectionMatrix); +#endif +#endif +#ifdef REFLECTIONMAP_EXPLICIT +return vec3f(0,0,0); +#endif +} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6E]) { + ShaderStore.IncludesShadersStoreWGSL[name$6E] = shader$6D; +} + +const reflectionFunction$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6D = "imageProcessingDeclaration"; +const shader$6C = `#ifdef EXPOSURE +uniform exposureLinear: f32; +#endif +#ifdef CONTRAST +uniform contrast: f32; +#endif +#if defined(VIGNETTE) || defined(DITHER) +uniform vInverseScreenSize: vec2f; +#endif +#ifdef VIGNETTE +uniform vignetteSettings1: vec4f;uniform vignetteSettings2: vec4f; +#endif +#ifdef COLORCURVES +uniform vCameraColorCurveNegative: vec4f;uniform vCameraColorCurveNeutral: vec4f;uniform vCameraColorCurvePositive: vec4f; +#endif +#ifdef COLORGRADING +#ifdef COLORGRADING3D +var txColorTransformSampler: sampler;var txColorTransform: texture_3d; +#else +var txColorTransformSampler: sampler;var txColorTransform: texture_2d; +#endif +uniform colorTransformSettings: vec4f; +#endif +#ifdef DITHER +uniform ditherIntensity: f32; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6D]) { + ShaderStore.IncludesShadersStoreWGSL[name$6D] = shader$6C; +} +/** @internal */ +const imageProcessingDeclarationWGSL = { name: name$6D, shader: shader$6C }; + +const imageProcessingDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + imageProcessingDeclarationWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6C = "lightUboDeclaration"; +const shader$6B = `#ifdef LIGHT{X} +struct Light{X} +{vLightData: vec4f, +vLightDiffuse: vec4f, +vLightSpecular: vec4f, +#ifdef SPOTLIGHT{X} +vLightDirection: vec4f, +vLightFalloff: vec4f, +#elif defined(POINTLIGHT{X}) +vLightFalloff: vec4f, +#elif defined(HEMILIGHT{X}) +vLightGround: vec3f, +#endif +#if defined(AREALIGHT{X}) +vLightWidth: vec4f, +vLightHeight: vec4f, +#endif +shadowsInfo: vec4f, +depthValues: vec2f} ;var light{X} : Light{X}; +#ifdef IESLIGHTTEXTURE{X} +var iesLightTexture{X}Sampler: sampler;var iesLightTexture{X}: texture_2d; +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}Sampler: sampler;var projectionLightTexture{X}: texture_2d; +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform lightMatrix{X}: array;uniform viewFrustumZ{X}: array;uniform frustumLengths{X}: array;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var vPositionFromLight{X}: array;var vDepthMetric{X} : array; +#if defined(SHADOWPCSS{X}) +var shadowTexture{X}Sampler: sampler_comparison; +var shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array;uniform lightSizeUVCorrection{X}: array;uniform depthCorrection{X}: array;uniform penumbraDarkness{X}: f32; +#elif defined(SHADOWPCF{X}) +var shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array; +#else +var shadowTexture{X}Sampler: sampler; +var shadowTexture{X}: texture_2d_array; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vCascadeColorsMultiplier{X}: array=array +( +vec3f ( 1.5,0.0,0.0 ), +vec3f ( 0.0,1.5,0.0 ), +vec3f ( 0.0,0.0,5.5 ), +vec3f ( 1.5,0.0,5.5 ), +vec3f ( 1.5,1.5,0.0 ), +vec3f ( 1.0,1.0,1.0 ), +vec3f ( 0.0,1.0,5.5 ), +vec3f ( 0.5,3.5,0.75 ) +); +#endif +#elif defined(SHADOWCUBE{X}) +var shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube; +#else +varying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32; +#if defined(SHADOWPCSS{X}) +var shadowTexture{X}Sampler: sampler_comparison; +var shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler; +var depthTexture{X}: texture_2d; +#elif defined(SHADOWPCF{X}) +var shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d; +#else +var shadowTexture{X}Sampler: sampler; +var shadowTexture{X}: texture_2d; +#endif +uniform lightMatrix{X}: mat4x4f; +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6C]) { + ShaderStore.IncludesShadersStoreWGSL[name$6C] = shader$6B; +} +/** @internal */ +const lightUboDeclarationWGSL = { name: name$6C, shader: shader$6B }; + +const lightUboDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lightUboDeclarationWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6B = "ltcHelperFunctions"; +const shader$6A = `fn LTCUv(N: vec3f,V: vec3f,roughness: f32)->vec2f {var LUTSIZE: f32=64.0;var LUTSCALE: f32=( LUTSIZE-1.0 )/LUTSIZE;var LUTBIAS:f32=0.5/LUTSIZE;var dotNV:f32=saturate( dot( N,V ) );var uv:vec2f=vec2f( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;} +fn LTCClippedSphereFormFactor( f:vec3f )->f32 {var l: f32=length( f );return max( ( l*l+f.z )/( l+1.0 ),0.0 );} +fn LTCEdgeVectorFormFactor( v1:vec3f,v2:vec3f )->vec3f {var x:f32=dot( v1,v2 );var y:f32=abs( x );var a:f32=0.8543985+( 0.4965155+0.0145206*y )*y;var b:f32=3.4175940+( 4.1616724+y )*y;var v:f32=a/b;var thetaSintheta:f32=0.0;if( x>0.0 ) +{thetaSintheta=v;} +else +{thetaSintheta=0.5*inverseSqrt( max( 1.0-x*x,0.00000001 ) )-v;} +return cross( v1,v2 )*thetaSintheta;} +fn LTCEvaluate( N:vec3f,V:vec3f,P:vec3f,mInv: mat3x3,rectCoords0:vec3f,rectCoords1:vec3f,rectCoords2:vec3f,rectCoords3:vec3f )->vec3f {var v1:vec3f=rectCoords1-rectCoords0;var v2:vec3f=rectCoords3-rectCoords0;var lightNormal:vec3f=cross( v1,v2 );if( dot( lightNormal,P-rectCoords0 )<0.0 ){return vec3f( 0.0 );} +var T1:vec3f=normalize( V-N*dot( V,N ) );var T2:vec3f=- cross( N,T1 ); +var mat: mat3x3=mInv*transposeMat3( mat3x3( T1,T2,N ) );var coords0: vec3f=mat*( rectCoords0-P );var coords1: vec3f=mat*( rectCoords1-P );var coords2: vec3f=mat*( rectCoords2-P );var coords3: vec3f=mat*( rectCoords3-P );coords0=normalize( coords0 );coords1=normalize( coords1 );coords2=normalize( coords2 );coords3=normalize( coords3 );var vectorFormFactor:vec3f=vec3( 0.0 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords0,coords1 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords1,coords2 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords2,coords3 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords3,coords0 );var result:f32=LTCClippedSphereFormFactor( vectorFormFactor );return vec3f( result );} +struct areaLightData +{Diffuse: vec3f, +Specular: vec3f, +Fresnel: vec4f};fn computeAreaLightSpecularDiffuseFresnel(ltc1: texture_2d,ltc1Sampler:sampler,ltc2:texture_2d,ltc2Sampler:sampler,viewDir: vec3f,normal:vec3f,position:vec3f,lightPos:vec3f,halfWidth:vec3f, halfHeight:vec3f,roughness:f32)->areaLightData {var result: areaLightData;var rectCoords0:vec3f=lightPos+halfWidth-halfHeight; +var rectCoords1:vec3f=lightPos-halfWidth-halfHeight;var rectCoords2:vec3f=lightPos-halfWidth+halfHeight;var rectCoords3:vec3f=lightPos+halfWidth+halfHeight; +#ifdef SPECULARTERM +var uv:vec2f=LTCUv( normal,viewDir,roughness );var t1:vec4f=textureSample( ltc1,ltc1Sampler,uv );var t2:vec4f=textureSample( ltc2,ltc2Sampler,uv );var mInv:mat3x3=mat3x3( +vec3f( t1.x,0,t1.y ), +vec3f( 0,1, 0 ), +vec3f( t1.z,0,t1.w ) +);result.Fresnel=t2;result.Specular=LTCEvaluate( normal,viewDir,position,mInv,rectCoords0,rectCoords1,rectCoords2,rectCoords3 ); +#endif +var mInvEmpty:mat3x3=mat3x3( +vec3f( 1,0,0 ), +vec3f( 0,1,0 ), +vec3f( 0,0,1 ) +);result.Diffuse+=LTCEvaluate( normal,viewDir,position,mInvEmpty,rectCoords0,rectCoords1,rectCoords2,rectCoords3 );return result;}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6B]) { + ShaderStore.IncludesShadersStoreWGSL[name$6B] = shader$6A; +} + +// Do not edit. +const name$6A = "lightsFragmentFunctions"; +const shader$6z = `struct lightingInfo +{diffuse: vec3f, +#ifdef SPECULARTERM +specular: vec3f, +#endif +#ifdef NDOTL +ndl: f32, +#endif +};fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.) +{var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var attenuation: f32=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} +else +{lightVectorW=normalize(-lightData.xyz);} +var ndl: f32=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +var angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +fn getAttenuation(cosAngle: f32,exponent: f32)->f32 {return max(0.,pow(cosAngle,exponent));} +fn getIESAttenuation(cosAngle: f32,iesLightTexture: texture_2d,iesLightTextureSampler: sampler)->f32 {var angle=acos(cosAngle)/PI;return textureSampleLevel(iesLightTexture,iesLightTextureSampler,vec2f(angle,0),0.).r;} +fn computeBasicSpotLighting(viewDirectionW: vec3f,lightVectorW: vec3f,vNormal: vec3f,attenuation: f32,diffuseColor: vec3f,specularColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +var angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +fn computeIESSpotLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32,iesLightTexture: texture_2d,iesLightTextureSampler: sampler)->lightingInfo {var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var dotProduct=dot(lightDirection.xyz,-lightVectorW);var cosAngle: f32=max(0.,dotProduct);if (cosAngle>=lightDirection.w) +{attenuation*=getIESAttenuation(dotProduct,iesLightTexture,iesLightTextureSampler);return computeBasicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);} +var result: lightingInfo;result.diffuse=vec3f(0.); +#ifdef SPECULARTERM +result.specular=vec3f(0.); +#endif +#ifdef NDOTL +result.ndl=0.; +#endif +return result;} +fn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) +{attenuation*=getAttenuation(cosAngle,lightData.w);return computeBasicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);} +var result: lightingInfo;result.diffuse=vec3f(0.); +#ifdef SPECULARTERM +result.specular=vec3f(0.); +#endif +#ifdef NDOTL +result.ndl=0.; +#endif +return result;} +fn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=dot(vNormal,lightData.xyz)*0.5+0.5; +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=mix(groundColor,diffuseColor,ndl); +#ifdef SPECULARTERM +var angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; +#endif +return result;} +fn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;} +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +#include +var areaLightsLTC1SamplerSampler: sampler;var areaLightsLTC1Sampler: texture_2d;var areaLightsLTC2SamplerSampler: sampler;var areaLightsLTC2Sampler: texture_2d;fn computeAreaLighting(ltc1: texture_2d,ltc1Sampler:sampler,ltc2:texture_2d,ltc2Sampler:sampler,viewDirectionW: vec3f,vNormal:vec3f,vPosition:vec3f,lightPosition:vec3f,halfWidth:vec3f, halfHeight:vec3f,diffuseColor:vec3f,specularColor:vec3f,roughness:f32 )->lightingInfo +{var result: lightingInfo;var data: areaLightData=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc1Sampler,ltc2,ltc2Sampler,viewDirectionW,vNormal,vPosition,lightPosition,halfWidth,halfHeight,roughness); +#ifdef SPECULARTERM +var fresnel:vec3f=( specularColor*data.Fresnel.x+( vec3f( 1.0 )-specularColor )*data.Fresnel.y );result.specular+=specularColor*fresnel*data.Specular; +#endif +result.diffuse+=diffuseColor*data.Diffuse;return result;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6A]) { + ShaderStore.IncludesShadersStoreWGSL[name$6A] = shader$6z; +} +/** @internal */ +const lightsFragmentFunctionsWGSL = { name: name$6A, shader: shader$6z }; + +const lightsFragmentFunctions$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lightsFragmentFunctionsWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6z = "shadowsFragmentFunctions"; +const shader$6y = `#ifdef SHADOWS +#ifndef SHADOWFLOAT +fn unpack(color: vec4f)->f32 +{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} +#endif +fn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32 +{var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} +fn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32 +{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +var shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight)); +#else +var shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x; +#endif +return select(1.0,darkness,depth>shadow);} +fn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32 +{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0); +#ifndef SHADOWFLOAT +if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize)),shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32 +{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +var shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight)); +#else +var shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x; +#endif +var esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;} +fn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32 +{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +var shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight)); +#else +var shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x; +#endif +var esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;} +fn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32 +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +var shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer)); +#else +var shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x; +#endif +return select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );} +fn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32 +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +var shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.)); +#else +var shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x; +#endif +return select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}} +fn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760); +#ifndef SHADOWFLOAT +if (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.)),shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32 +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +var shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.)); +#else +var shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x; +#endif +var esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +fn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32 +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +var shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.)); +#else +var shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x; +#endif +var esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +fn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32 +{ +#ifdef IS_NDC_HALF_ZRANGE +return clipSpace.z; +#else +return uvDepth.z; +#endif +} +const GREATEST_LESS_THAN_ONE: f32=0.99999994; +#define DISABLE_UNIFORMITY_ANALYSIS +fn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32 +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +fn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +var st: vec2f=fract(uv); +var base_uv: vec2f=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +var uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +fn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +var st: vec2f=fract(uv); +var base_uv: vec2f=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +var uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +fn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32 +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +fn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +var st: vec2f=fract(uv); +var base_uv: vec2f=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +var uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +fn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +var st: vec2f=fract(uv); +var base_uv: vec2f=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +var uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +const PoissonSamplers32: array=array ( +vec3f(0.06407013,0.05409927,0.), +vec3f(0.7366577,0.5789394,0.), +vec3f(-0.6270542,-0.5320278,0.), +vec3f(-0.4096107,0.8411095,0.), +vec3f(0.6849564,-0.4990818,0.), +vec3f(-0.874181,-0.04579735,0.), +vec3f(0.9989998,0.0009880066,0.), +vec3f(-0.004920578,-0.9151649,0.), +vec3f(0.1805763,0.9747483,0.), +vec3f(-0.2138451,0.2635818,0.), +vec3f(0.109845,0.3884785,0.), +vec3f(0.06876755,-0.3581074,0.), +vec3f(0.374073,-0.7661266,0.), +vec3f(0.3079132,-0.1216763,0.), +vec3f(-0.3794335,-0.8271583,0.), +vec3f(-0.203878,-0.07715034,0.), +vec3f(0.5912697,0.1469799,0.), +vec3f(-0.88069,0.3031784,0.), +vec3f(0.5040108,0.8283722,0.), +vec3f(-0.5844124,0.5494877,0.), +vec3f(0.6017799,-0.1726654,0.), +vec3f(-0.5554981,0.1559997,0.), +vec3f(-0.3016369,-0.3900928,0.), +vec3f(-0.5550632,-0.1723762,0.), +vec3f(0.925029,0.2995041,0.), +vec3f(-0.2473137,0.5538505,0.), +vec3f(0.9183037,-0.2862392,0.), +vec3f(0.2469421,0.6718712,0.), +vec3f(0.3916397,-0.4328209,0.), +vec3f(-0.03576927,-0.6220032,0.), +vec3f(-0.04661255,0.7995201,0.), +vec3f(0.4402924,0.3640312,0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.), +vec3f(0.) +);const PoissonSamplers64: array=array ( +vec3f(-0.613392,0.617481,0.), +vec3f(0.170019,-0.040254,0.), +vec3f(-0.299417,0.791925,0.), +vec3f(0.645680,0.493210,0.), +vec3f(-0.651784,0.717887,0.), +vec3f(0.421003,0.027070,0.), +vec3f(-0.817194,-0.271096,0.), +vec3f(-0.705374,-0.668203,0.), +vec3f(0.977050,-0.108615,0.), +vec3f(0.063326,0.142369,0.), +vec3f(0.203528,0.214331,0.), +vec3f(-0.667531,0.326090,0.), +vec3f(-0.098422,-0.295755,0.), +vec3f(-0.885922,0.215369,0.), +vec3f(0.566637,0.605213,0.), +vec3f(0.039766,-0.396100,0.), +vec3f(0.751946,0.453352,0.), +vec3f(0.078707,-0.715323,0.), +vec3f(-0.075838,-0.529344,0.), +vec3f(0.724479,-0.580798,0.), +vec3f(0.222999,-0.215125,0.), +vec3f(-0.467574,-0.405438,0.), +vec3f(-0.248268,-0.814753,0.), +vec3f(0.354411,-0.887570,0.), +vec3f(0.175817,0.382366,0.), +vec3f(0.487472,-0.063082,0.), +vec3f(-0.084078,0.898312,0.), +vec3f(0.488876,-0.783441,0.), +vec3f(0.470016,0.217933,0.), +vec3f(-0.696890,-0.549791,0.), +vec3f(-0.149693,0.605762,0.), +vec3f(0.034211,0.979980,0.), +vec3f(0.503098,-0.308878,0.), +vec3f(-0.016205,-0.872921,0.), +vec3f(0.385784,-0.393902,0.), +vec3f(-0.146886,-0.859249,0.), +vec3f(0.643361,0.164098,0.), +vec3f(0.634388,-0.049471,0.), +vec3f(-0.688894,0.007843,0.), +vec3f(0.464034,-0.188818,0.), +vec3f(-0.440840,0.137486,0.), +vec3f(0.364483,0.511704,0.), +vec3f(0.034028,0.325968,0.), +vec3f(0.099094,-0.308023,0.), +vec3f(0.693960,-0.366253,0.), +vec3f(0.678884,-0.204688,0.), +vec3f(0.001801,0.780328,0.), +vec3f(0.145177,-0.898984,0.), +vec3f(0.062655,-0.611866,0.), +vec3f(0.315226,-0.604297,0.), +vec3f(-0.780145,0.486251,0.), +vec3f(-0.371868,0.882138,0.), +vec3f(0.200476,0.494430,0.), +vec3f(-0.494552,-0.711051,0.), +vec3f(0.612476,0.705252,0.), +vec3f(-0.578845,-0.768792,0.), +vec3f(-0.772454,-0.090976,0.), +vec3f(0.504440,0.372295,0.), +vec3f(0.155736,0.065157,0.), +vec3f(0.391522,0.849605,0.), +vec3f(-0.620106,-0.328104,0.), +vec3f(0.789239,-0.419965,0.), +vec3f(-0.545396,0.538133,0.), +vec3f(-0.178564,-0.596057,0.) +);fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array)->f32 +{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;var exitCondition: bool=depthMetric>1.0 || depthMetric<0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 +{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);} +fn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 +{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);} +fn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 +{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);} +fn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 +{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} +fn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 +{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} +fn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 +{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6z]) { + ShaderStore.IncludesShadersStoreWGSL[name$6z] = shader$6y; +} +/** @internal */ +const shadowsFragmentFunctionsWGSL = { name: name$6z, shader: shader$6y }; + +const shadowsFragmentFunctions$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + shadowsFragmentFunctionsWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6y = "imageProcessingFunctions"; +const shader$6x = `#if TONEMAPPING==3 +const PBRNeutralStartCompression: f32=0.8-0.04;const PBRNeutralDesaturation: f32=0.15;fn PBRNeutralToneMapping( color: vec3f )->vec3f {var x: f32=min(color.r,min(color.g,color.b));var offset: f32=select(0.04,x-6.25*x*x,x<0.08);var result=color;result-=offset;var peak: f32=max(result.r,max(result.g,result.b));if (peakvec3f +{var a: vec3f=v*(v+0.0245786)-0.000090537;var b: vec3f=v*(0.983729*v+0.4329510)+0.238081;return a/b;} +fn ACESFitted(color: vec3f)->vec3f +{var output=ACESInputMat*color;output=RRTAndODTFit(output);output=ACESOutputMat*output;output=saturateVec3(output);return output;} +#endif +#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS +fn applyImageProcessing(result: vec4f)->vec4f { +#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART +var rgb=result.rgb;; +#ifdef EXPOSURE +rgb*=uniforms.exposureLinear; +#endif +#ifdef VIGNETTE +var viewportXY: vec2f=fragmentInputs.position.xy*uniforms.vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;var vignetteXY1: vec3f= vec3f(viewportXY*uniforms.vignetteSettings1.xy+uniforms.vignetteSettings1.zw,1.0);var vignetteTerm: f32=dot(vignetteXY1,vignetteXY1);var vignette: f32=pow(vignetteTerm,uniforms.vignetteSettings2.w);var vignetteColor: vec3f=uniforms.vignetteSettings2.rgb; +#ifdef VIGNETTEBLENDMODEMULTIPLY +var vignetteColorMultiplier: vec3f=mix(vignetteColor, vec3f(1,1,1),vignette);rgb*=vignetteColorMultiplier; +#endif +#ifdef VIGNETTEBLENDMODEOPAQUE +rgb=mix(vignetteColor,rgb,vignette); +#endif +#endif +#if TONEMAPPING==3 +rgb=PBRNeutralToneMapping(rgb); +#elif TONEMAPPING==2 +rgb=ACESFitted(rgb); +#elif TONEMAPPING==1 +const tonemappingCalibration: f32=1.590579;rgb=1.0-exp2(-tonemappingCalibration*rgb); +#endif +rgb=toGammaSpaceVec3(rgb);rgb=saturateVec3(rgb); +#ifdef CONTRAST +var resultHighContrast: vec3f=rgb*rgb*(3.0-2.0*rgb);if (uniforms.contrast<1.0) {rgb=mix( vec3f(0.5,0.5,0.5),rgb,uniforms.contrast);} else {rgb=mix(rgb,resultHighContrast,uniforms.contrast-1.0);} +#endif +#ifdef COLORGRADING +var colorTransformInput: vec3f=rgb*uniforms.colorTransformSettings.xxx+uniforms.colorTransformSettings.yyy; +#ifdef COLORGRADING3D +var colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput).rgb; +#else +var colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz).rgb; +#endif +rgb=mix(rgb,colorTransformOutput,uniforms.colorTransformSettings.www); +#endif +#ifdef COLORCURVES +var luma: f32=getLuminance(rgb);var curveMix: vec2f=clamp( vec2f(luma*3.0-1.5,luma*-3.0+1.5), vec2f(0.0), vec2f(1.0));var colorCurve: vec4f=uniforms.vCameraColorCurveNeutral+curveMix.x*uniforms.vCameraColorCurvePositive-curveMix.y*uniforms.vCameraColorCurveNegative;rgb*=colorCurve.rgb;rgb=mix( vec3f(luma),rgb,colorCurve.a); +#endif +#ifdef DITHER +var rand: f32=getRand(fragmentInputs.position.xy*uniforms.vInverseScreenSize);var dither: f32=mix(-uniforms.ditherIntensity,uniforms.ditherIntensity,rand);rgb=saturateVec3(rgb+ vec3f(dither)); +#endif +#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND +return vec4f(rgb,result.a);}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6y]) { + ShaderStore.IncludesShadersStoreWGSL[name$6y] = shader$6x; +} +/** @internal */ +const imageProcessingFunctionsWGSL = { name: name$6y, shader: shader$6x }; + +const imageProcessingFunctions$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + imageProcessingFunctionsWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6x = "fogFragmentDeclaration"; +const shader$6w = `#ifdef FOG +#define FOGMODE_NONE 0. +#define FOGMODE_EXP 1. +#define FOGMODE_EXP2 2. +#define FOGMODE_LINEAR 3. +const E=2.71828;uniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32 +{var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x) +{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} +else if (FOGMODE_EXP==uniforms.vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDensity);} +else if (FOGMODE_EXP2==uniforms.vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} +return clamp(fogCoeff,0.0,1.0);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6x]) { + ShaderStore.IncludesShadersStoreWGSL[name$6x] = shader$6w; +} + +const fogFragmentDeclaration$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6w = "intersectionFunctions"; +const shader$6v = `fn diskIntersectWithBackFaceCulling(ro: vec3f,rd: vec3f,c: vec3f,r: f32)->f32 {var d: f32=rd.y;if(d>0.0) { return 1e6; } +var o: vec3f=ro-c;var t: f32=-o.y/d;var q: vec3f=o+rd*t;return select(1e6,t,(dot(q,q)vec2f {var oc: vec3f=ro-ce;var b: f32=dot(oc,rd);var c: f32=dot(oc,oc)-ra*ra;var h: f32=b*b-c;if(h<0.0) { return vec2f(-1.,-1.); } +h=sqrt(h);return vec2f(-b+h,-b-h);} +fn sphereIntersectFromOrigin(ro: vec3f,rd: vec3f,ra: f32)->vec2f {var b: f32=dot(ro,rd);var c: f32=dot(ro,ro)-ra*ra;var h: f32=b*b-c;if(h<0.0) { return vec2f(-1.,-1.); } +h=sqrt(h);return vec2f(-b+h,-b-h);}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6w]) { + ShaderStore.IncludesShadersStoreWGSL[name$6w] = shader$6v; +} + +// Do not edit. +const name$6v = "lightFragment"; +const shader$6u = `#ifdef LIGHT{X} +#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) +#else +var diffuse{X}: vec4f=light{X}.vLightDiffuse; +#define CUSTOM_LIGHT{X}_COLOR +#ifdef PBR +#ifdef SPOTLIGHT{X} +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW); +#elif defined(POINTLIGHT{X}) +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW); +#elif defined(HEMILIGHT{X}) +preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(DIRLIGHT{X}) +preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(AREALIGHT{X}) && defined(AREALIGHTSUPPORTED) +preInfo=computeAreaPreLightingInfo(areaLightsLTC1Sampler,areaLightsLTC1SamplerSampler,areaLightsLTC2Sampler,areaLightsLTC2SamplerSampler,viewDirectionW,normalW,fragmentInputs.vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,roughness); +#endif +preInfo.NdotV=NdotV; +#ifdef SPOTLIGHT{X} +#ifdef LIGHT_FALLOFF_GLTF{X} +preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); +#ifdef IESLIGHTTEXTURE{X} +preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler); +#else +preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); +#endif +#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) +preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); +#ifdef IESLIGHTTEXTURE{X} +preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler); +#else +preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); +#endif +#elif defined(LIGHT_FALLOFF_STANDARD{X}) +preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); +#ifdef IESLIGHTTEXTURE{X} +preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler); +#else +preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); +#endif +#else +preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); +#ifdef IESLIGHTTEXTURE{X} +preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler); +#else +preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); +#endif +#endif +#elif defined(POINTLIGHT{X}) +#ifdef LIGHT_FALLOFF_GLTF{X} +preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); +#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) +preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); +#elif defined(LIGHT_FALLOFF_STANDARD{X}) +preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); +#else +preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); +#endif +#else +preInfo.attenuation=1.0; +#endif +#if defined(HEMILIGHT{X}) || defined(AREALIGHT{X}) +preInfo.roughness=roughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +#ifdef IRIDESCENCE +preInfo.iridescenceIntensity=iridescenceIntensity; +#endif +#ifdef HEMILIGHT{X} +info.diffuse=computeHemisphericDiffuseLighting(preInfo,diffuse{X}.rgb,light{X}.vLightGround); +#elif AREALIGHT{X} +info.diffuse=computeAreaDiffuseLighting(preInfo,diffuse{X}.rgb); +#elif defined(SS_TRANSLUCENCY) +info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance,subSurfaceOut.translucencyIntensity,surfaceAlbedo.rgb); +#else +info.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb); +#endif +#ifdef SPECULARTERM +#if AREALIGHT{X} +info.specular=computeAreaSpecularLighting(preInfo,light{X}.vLightSpecular.rgb); +#else +#ifdef ANISOTROPIC +info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb); +#else +info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb); +#endif +#endif +#endif +#ifndef AREALIGHT{X} +#ifdef SHEEN +#ifdef SHEEN_LINKWITHALBEDO +preInfo.roughness=sheenOut.sheenIntensity; +#else +#ifdef HEMILIGHT{X} +preInfo.roughness=sheenOut.sheenRoughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +#endif +info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb); +#endif +#ifdef CLEARCOAT +#ifdef HEMILIGHT{X} +preInfo.roughness=clearcoatOut.clearCoatRoughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,diffuse{X}.rgb); +#ifdef CLEARCOAT_TINT +absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; +#ifdef SPECULARTERM +info.specular*=absorption; +#endif +#endif +info.diffuse*=info.clearCoat.w; +#ifdef SPECULARTERM +info.specular*=info.clearCoat.w; +#endif +#ifdef SHEEN +info.sheen*=info.clearCoat.w; +#endif +#endif +#endif +#else +#ifdef SPOTLIGHT{X} +#ifdef IESLIGHTTEXTURE{X} +info=computeIESSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness,iesLightTexture{X},iesLightTexture{X}Sampler); +#else +info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness); +#endif +#elif defined(HEMILIGHT{X}) +info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); +#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) +info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness); +#elif define(AREALIGHT{X}) && defined(AREALIGHTSUPPORTED) +info=computeAreaLighting(areaLightsLTC1Sampler,areaLightsLTC1SamplerSampler,areaLightsLTC2Sampler,areaLightsLTC2SamplerSampler,viewDirectionW,normalW,fragmentInputs.vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,diffuse{X}.rgb,light{X}.vLightSpecular.rgb, +#ifdef AREALIGHTNOROUGHTNESS +0.5 +#else +uniforms.vReflectionInfos.y +#endif +); +#endif +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,uniforms.textureProjectionMatrix{X},fragmentInputs.vPositionW); +#endif +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSMDEBUG{X} +var shadowDebug{X}: vec3f; +#endif +#ifdef SHADOWCSM{X} +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +var index{X}: i32=-1; +#else +var index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1; +#endif +var diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i=0.) {index{X}=i;break;}} +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +if (index{X}>=0) +#endif +{ +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); +#else +shadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); +#endif +#else +shadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}]; +#endif +#ifndef SHADOWCSMNOBLEND{X} +var frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) +{index{X}+=1;var nextShadow: f32=0.; +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +nextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); +#else +nextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); +#endif +#else +nextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +shadow=mix(nextShadow,shadow,diffRatio); +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); +#endif +} +#endif +} +#elif defined(SHADOWCLOSEESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithCloseESMCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithESMCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPOISSON{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithPoissonSamplingCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#else +#if defined(SHADOWCUBE{X}) +shadow=computeShadowCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#endif +#ifdef SHADOWONLY +#ifndef SHADOWINUSE +#define SHADOWINUSE +#endif +globalShadow+=shadow;shadowLightCount+=1.0; +#endif +#else +shadow=1.; +#endif +aggShadow+=shadow;numLights+=1.0; +#ifndef SHADOWONLY +#ifdef CUSTOMUSERLIGHTING +diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); +#ifdef SPECULARTERM +specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); +#endif +#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) +diffuseBase+=lightmapColor.rgb*shadow; +#ifdef SPECULARTERM +#ifndef LIGHTMAPNOSPECULAR{X} +specularBase+=info.specular*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef CLEARCOAT +#ifndef LIGHTMAPNOSPECULAR{X} +clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef SHEEN +#ifndef LIGHTMAPNOSPECULAR{X} +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#else +#ifdef SHADOWCSMDEBUG{X} +diffuseBase+=info.diffuse*shadowDebug{X}; +#else +diffuseBase+=info.diffuse*shadow; +#endif +#ifdef SPECULARTERM +specularBase+=info.specular*shadow; +#endif +#ifdef CLEARCOAT +clearCoatBase+=info.clearCoat.rgb*shadow; +#endif +#ifdef SHEEN +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6v]) { + ShaderStore.IncludesShadersStoreWGSL[name$6v] = shader$6u; +} +/** @internal */ +const lightFragmentWGSL = { name: name$6v, shader: shader$6u }; + +const lightFragment$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lightFragmentWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6u = "logDepthFragment"; +const shader$6t = `#ifdef LOGARITHMICDEPTH +fragmentOutputs.fragDepth=log2(fragmentInputs.vFragmentDepth)*uniforms.logarithmicDepthConstant*0.5; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6u]) { + ShaderStore.IncludesShadersStoreWGSL[name$6u] = shader$6t; +} + +// Do not edit. +const name$6t = "fogFragment"; +const shader$6s = `#ifdef FOG +var fog: f32=CalcFogFactor(); +#ifdef PBR +fog=toLinearSpace(fog); +#endif +color= vec4f(mix(uniforms.vFogColor,color.rgb,fog),color.a); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$6t]) { + ShaderStore.IncludesShadersStoreWGSL[name$6t] = shader$6s; +} + +// Do not edit. +const name$6s = "backgroundPixelShader"; +const shader$6r = `#include +#include +varying vPositionW: vec3f; +#ifdef MAINUV1 +varying vMainUV1: vec2f; +#endif +#ifdef MAINUV2 +varying vMainUV2: vec2f; +#endif +#ifdef NORMAL +varying vNormalW: vec3f; +#endif +#ifdef DIFFUSE +#if DIFFUSEDIRECTUV==1 +#define vDiffuseUV vMainUV1 +#elif DIFFUSEDIRECTUV==2 +#define vDiffuseUV vMainUV2 +#else +varying vDiffuseUV: vec2f; +#endif +var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +var reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube; +#ifdef TEXTURELODSUPPORT +#else +var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube; +#endif +#else +var reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d; +#ifdef TEXTURELODSUPPORT +#else +var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vPositionUVW: vec3f; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vDirectionW: vec3f; +#endif +#endif +#include +#endif +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE; +#endif +#ifndef SHADOWONLY +#define SHADOWONLY; +#endif +#include +#include[0..maxSimultaneousLights] +#include +#include +#include +#include +#include +#include +#ifdef REFLECTIONFRESNEL +#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +fn fresnelSchlickEnvironmentGGX(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f +{var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#ifdef PROJECTED_GROUND +#include +fn project(viewDirectionW: vec3f,eyePosition: vec3f)->vec3f {var radius: f32=uniforms.projectedGroundInfos.x;var height: f32=uniforms.projectedGroundInfos.y;var camDir: vec3f=-viewDirectionW;var skySphereDistance: f32=sphereIntersectFromOrigin(eyePosition,camDir,radius).x;var skySpherePositionW: vec3f=eyePosition+camDir*skySphereDistance;var p: vec3f=normalize(skySpherePositionW);var upEyePosition=vec3f(eyePosition.x,eyePosition.y-height,eyePosition.z);var sIntersection: f32=sphereIntersectFromOrigin(upEyePosition,p,radius).x;var h: vec3f= vec3f(0.0,-height,0.0);var dIntersection: f32=diskIntersectWithBackFaceCulling(upEyePosition,p,h,radius);p=(upEyePosition+min(sIntersection,dIntersection)*p);return p;} +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW); +#ifdef NORMAL +var normalW: vec3f=normalize(fragmentInputs.vNormalW); +#else +var normalW: vec3f= vec3f(0.0,1.0,0.0); +#endif +var shadow: f32=1.;var globalShadow: f32=0.;var shadowLightCount: f32=0.;var aggShadow: f32=0.;var numLights: f32=0.; +#include[0..maxSimultaneousLights] +#ifdef SHADOWINUSE +globalShadow/=shadowLightCount; +#else +globalShadow=1.0; +#endif +#ifndef BACKMAT_SHADOWONLY +var reflectionColor: vec4f= vec4f(1.,1.,1.,1.); +#ifdef REFLECTION +#ifdef PROJECTED_GROUND +var reflectionVector: vec3f=project(viewDirectionW,scene.vEyePosition.xyz);reflectionVector= (uniforms.reflectionMatrix*vec4f(reflectionVector,1.)).xyz; +#else +var reflectionVector: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +var reflectionCoords: vec3f=reflectionVector; +#else +var reflectionCoords: vec2f=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +#ifdef REFLECTIONBLUR +var reflectionLOD: f32=uniforms.vReflectionInfos.y; +#ifdef TEXTURELODSUPPORT +reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD); +#else +var lodReflectionNormalized: f32=saturate(reflectionLOD);var lodReflectionNormalizedDoubled: f32=lodReflectionNormalized*2.0;var reflectionSpecularMid: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( +textureSample(reflectionrHighSampler,reflectionrHighSamplerSampler,reflectionCoords), +reflectionSpecularMid, +lodReflectionNormalizedDoubled +);} else {reflectionColor=mix( +reflectionSpecularMid, +textureSample(reflectionLowSampler,reflectionLowSamplerSampler,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#else +var reflectionSample: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);reflectionColor=reflectionSample; +#endif +#ifdef RGBDREFLECTION +reflectionColor=vec4f(fromRGBD(reflectionColor).rgb,reflectionColor.a); +#endif +#ifdef GAMMAREFLECTION +reflectionColor=vec4f(toLinearSpaceVec3(reflectionColor.rgb),reflectionColor.a); +#endif +#ifdef REFLECTIONBGR +reflectionColor=vec4f(reflectionColor.bgr,reflectionColor.a); +#endif +reflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a); +#endif +var diffuseColor: vec3f= vec3f(1.,1.,1.);var finalAlpha: f32=uniforms.alpha; +#ifdef DIFFUSE +var diffuseMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vDiffuseUV); +#ifdef GAMMADIFFUSE +diffuseMap=vec4f(toLinearSpaceVec3(diffuseMap.rgb),diffuseMap.a); +#endif +diffuseMap=vec4f(diffuseMap.rgb *uniforms.vDiffuseInfos.y,diffuseMap.a); +#ifdef DIFFUSEHASALPHA +finalAlpha*=diffuseMap.a; +#endif +diffuseColor=diffuseMap.rgb; +#endif +#ifdef REFLECTIONFRESNEL +var colorBase: vec3f=diffuseColor; +#else +var colorBase: vec3f=reflectionColor.rgb*diffuseColor; +#endif +colorBase=max(colorBase,vec3f(0.0)); +#ifdef USERGBCOLOR +var finalColor: vec3f=colorBase; +#else +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +var mainColor: vec3f=mix(uniforms.vPrimaryColorShadow.rgb,uniforms.vPrimaryColor.rgb,colorBase); +#else +var mainColor: vec3f=uniforms.vPrimaryColor.rgb; +#endif +var finalColor: vec3f=colorBase*mainColor; +#endif +#ifdef REFLECTIONFRESNEL +var reflectionAmount: vec3f=uniforms.vReflectionControl.xxx;var reflectionReflectance0: vec3f=uniforms.vReflectionControl.yyy;var reflectionReflectance90: vec3f=uniforms.vReflectionControl.zzz;var VdotN: f32=dot(normalize(scene.vEyePosition.xyz),normalW);var planarReflectionFresnel: vec3f=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; +#ifdef REFLECTIONFALLOFF +var reflectionDistanceFalloff: f32=1.0-saturate(length(vPositionW.xyz-uniforms.vBackgroundCenter)*uniforms.vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; +#endif +finalColor=mix(finalColor,reflectionColor.rgb,saturateVec3(reflectionAmount)); +#endif +#ifdef OPACITYFRESNEL +var viewAngleToFloor: f32=dot(normalW,normalize(scene.vEyePosition.xyz-uniforms.vBackgroundCenter));const startAngle: f32=0.1;var fadeFactor: f32=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; +#endif +#ifdef SHADOWINUSE +finalColor=mix(finalColor*uniforms.shadowLevel,finalColor,globalShadow); +#endif +var color: vec4f= vec4f(finalColor,finalAlpha); +#else +var color: vec4f= vec4f(uniforms.vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*uniforms.alpha); +#endif +#include +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +#if !defined(SKIPFINALCOLORCLAMP) +color=vec4f(clamp(color.rgb,vec3f(0.),vec3f(30.0)),color.a); +#endif +#else +color=applyImageProcessing(color); +#endif +#ifdef PREMULTIPLYALPHA +color=vec4f(color.rgb *color.a,color.a); +#endif +#ifdef NOISE +color=vec4f(color.rgb+dither(fragmentInputs.vPositionW.xy,0.5),color.a);color=max(color,vec4f(0.0)); +#endif +fragmentOutputs.color=color; +#define CUSTOM_FRAGMENT_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$6s]) { + ShaderStore.ShadersStoreWGSL[name$6s] = shader$6r; +} +/** @internal */ +const backgroundPixelShaderWGSL = { name: name$6s, shader: shader$6r }; + +const background_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + backgroundPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6r = "backgroundVertexDeclaration"; +const shader$6q = `uniform mat4 view;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +uniform float shadowLevel; +#ifdef DIFFUSE +uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6r]) { + ShaderStore.IncludesShadersStore[name$6r] = shader$6q; +} + +// Do not edit. +const name$6q = "backgroundUboDeclaration"; +const shader$6p = `layout(std140,column_major) uniform;uniform Material +{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;}; +#include +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6q]) { + ShaderStore.IncludesShadersStore[name$6q] = shader$6p; +} + +// Do not edit. +const name$6p = "fogVertexDeclaration"; +const shader$6o = `#ifdef FOG +varying vec3 vFogDistance; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6p]) { + ShaderStore.IncludesShadersStore[name$6p] = shader$6o; +} + +// Do not edit. +const name$6o = "lightVxFragmentDeclaration"; +const shader$6n = `#ifdef LIGHT{X} +uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; +#ifdef SPECULARTERM +uniform vec4 vLightSpecular{X}; +#else +vec4 vLightSpecular{X}=vec4(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#elif defined(SHADOWCUBE{X}) +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; +#endif +uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; +#endif +#ifdef SPOTLIGHT{X} +uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; +#elif defined(POINTLIGHT{X}) +uniform vec4 vLightFalloff{X}; +#elif defined(HEMILIGHT{X}) +uniform vec3 vLightGround{X}; +#endif +#if defined(AREALIGHT{X}) +uniform vec4 vLightWidth{X};uniform vec4 vLightHeight{X}; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6o]) { + ShaderStore.IncludesShadersStore[name$6o] = shader$6n; +} +/** @internal */ +const lightVxFragmentDeclaration = { name: name$6o, shader: shader$6n }; + +const lightVxFragmentDeclaration$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lightVxFragmentDeclaration +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6n = "lightVxUboDeclaration"; +const shader$6m = `#ifdef LIGHT{X} +uniform Light{X} +{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; +#ifdef SPOTLIGHT{X} +vec4 vLightDirection;vec4 vLightFalloff; +#elif defined(POINTLIGHT{X}) +vec4 vLightFalloff; +#elif defined(HEMILIGHT{X}) +vec3 vLightGround; +#endif +#if defined(AREALIGHT{X}) +vec4 vLightWidth;vec4 vLightHeight; +#endif +vec4 shadowsInfo;vec2 depthValues;} light{X}; +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#elif defined(SHADOWCUBE{X}) +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6n]) { + ShaderStore.IncludesShadersStore[name$6n] = shader$6m; +} +/** @internal */ +const lightVxUboDeclaration = { name: name$6n, shader: shader$6m }; + +const lightVxUboDeclaration$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lightVxUboDeclaration +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6m = "logDepthDeclaration"; +const shader$6l = `#ifdef LOGARITHMICDEPTH +uniform float logarithmicDepthConstant;varying float vFragmentDepth; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6m]) { + ShaderStore.IncludesShadersStore[name$6m] = shader$6l; +} + +// Do not edit. +const name$6l = "fogVertex"; +const shader$6k = `#ifdef FOG +vFogDistance=(view*worldPos).xyz; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6l]) { + ShaderStore.IncludesShadersStore[name$6l] = shader$6k; +} + +// Do not edit. +const name$6k = "shadowsVertex"; +const shader$6j = `#ifdef SHADOWS +#if defined(SHADOWCSM{X}) +vPositionFromCamera{X}=view*worldPos;for (int i=0; i +#include +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include +#include +#include +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef MAINUV1 +varying vec2 vMainUV1; +#endif +#ifdef MAINUV2 +varying vec2 vMainUV2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +varying vec2 vDiffuseUV; +#endif +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=position; +#endif +#include +#include +#include +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} +#else +gl_Position=viewProjection*finalWorld*vec4(position,1.0); +#endif +vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normal); +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); +#ifdef EQUIRECTANGULAR_RELFECTION_FOV +mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} +#endif +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uv; +#endif +#ifdef MAINUV2 +vMainUV2=uv2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +if (vDiffuseInfos.x==0.) +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} +else +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} +#endif +#include +#include +#include[0..maxSimultaneousLights] +#ifdef VERTEXCOLOR +vColor=colorUpdated; +#endif +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$6i]) { + ShaderStore.ShadersStore[name$6i] = shader$6h; +} +/** @internal */ +const backgroundVertexShader = { name: name$6i, shader: shader$6h }; + +const background_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + backgroundVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6h = "backgroundFragmentDeclaration"; +const shader$6g = `uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +uniform vec4 vPrimaryColorShadow; +#endif +uniform float shadowLevel;uniform float alpha; +#ifdef DIFFUSE +uniform vec2 vDiffuseInfos; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; +#endif +#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) +uniform vec3 vBackgroundCenter; +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 vReflectionControl; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) +uniform mat4 view; +#endif +#ifdef PROJECTED_GROUND +uniform vec2 projectedGroundInfos; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6h]) { + ShaderStore.IncludesShadersStore[name$6h] = shader$6g; +} + +// Do not edit. +const name$6g = "reflectionFunction"; +const shader$6f = `vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) +{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); } +vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) +{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); } +vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) +{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);} +vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix) +{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);} +vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) +{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));} +vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) +{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0)); +#ifdef INVERTCUBICMAP +coords.y*=-1.0; +#endif +return coords;} +vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition) +{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0)); +#ifdef INVERTCUBICMAP +coords.y*=-1.0; +#endif +return coords;} +vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix) +{return vec3(reflectionMatrix*(view*worldPos));} +vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix) +{return vec3(reflectionMatrix*vec4(positionW,1.));} +#ifdef REFLECTION +vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal) +{ +#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED +vec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction); +#endif +#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED +vec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction); +#endif +#ifdef REFLECTIONMAP_EQUIRECTANGULAR +return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_SPHERICAL +return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_PLANAR +return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_CUBIC +#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC +return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition); +#else +return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); +#endif +#endif +#ifdef REFLECTIONMAP_PROJECTION +return computeProjectionCoords(worldPos,view,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_SKYBOX +return computeSkyBoxCoords(vPositionUVW,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_EXPLICIT +return vec3(0,0,0); +#endif +} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6g]) { + ShaderStore.IncludesShadersStore[name$6g] = shader$6f; +} + +const reflectionFunction = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6f = "imageProcessingDeclaration"; +const shader$6e = `#ifdef EXPOSURE +uniform float exposureLinear; +#endif +#ifdef CONTRAST +uniform float contrast; +#endif +#if defined(VIGNETTE) || defined(DITHER) +uniform vec2 vInverseScreenSize; +#endif +#ifdef VIGNETTE +uniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2; +#endif +#ifdef COLORCURVES +uniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive; +#endif +#ifdef COLORGRADING +#ifdef COLORGRADING3D +uniform highp sampler3D txColorTransform; +#else +uniform sampler2D txColorTransform; +#endif +uniform vec4 colorTransformSettings; +#endif +#ifdef DITHER +uniform float ditherIntensity; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6f]) { + ShaderStore.IncludesShadersStore[name$6f] = shader$6e; +} +/** @internal */ +const imageProcessingDeclaration = { name: name$6f, shader: shader$6e }; + +const imageProcessingDeclaration$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + imageProcessingDeclaration +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6e = "lightFragmentDeclaration"; +const shader$6d = `#ifdef LIGHT{X} +uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; +#ifdef SPECULARTERM +uniform vec4 vLightSpecular{X}; +#else +vec4 vLightSpecular{X}=vec4(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DArrayShadow shadowTexture{X}; +#else +uniform highp sampler2DArray shadowTexture{X}; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] +( +vec3 ( 1.5,0.0,0.0 ), +vec3 ( 0.0,1.5,0.0 ), +vec3 ( 0.0,0.0,5.5 ), +vec3 ( 1.5,0.0,5.5 ), +vec3 ( 1.5,1.5,0.0 ), +vec3 ( 1.0,1.0,1.0 ), +vec3 ( 0.0,1.0,5.5 ), +vec3 ( 0.5,3.5,0.75 ) +);vec3 shadowDebug{X}; +#endif +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +int index{X}=-1; +#else +int index{X}=SHADOWCSMNUM_CASCADES{X}-1; +#endif +float diff{X}=0.; +#elif defined(SHADOWCUBE{X}) +uniform samplerCube shadowTexture{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowTexture{X}; +#else +uniform sampler2D shadowTexture{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; +#endif +#ifdef SPOTLIGHT{X} +uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; +#elif defined(POINTLIGHT{X}) +uniform vec4 vLightFalloff{X}; +#elif defined(HEMILIGHT{X}) +uniform vec3 vLightGround{X}; +#endif +#ifdef AREALIGHT{X} +uniform vec4 vLightWidth{X};uniform vec4 vLightHeight{X}; +#endif +#ifdef IESLIGHTTEXTURE{X} +uniform sampler2D iesLightTexture{X}; +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X}; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6e]) { + ShaderStore.IncludesShadersStore[name$6e] = shader$6d; +} +/** @internal */ +const lightFragmentDeclaration = { name: name$6e, shader: shader$6d }; + +const lightFragmentDeclaration$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lightFragmentDeclaration +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6d = "lightUboDeclaration"; +const shader$6c = `#ifdef LIGHT{X} +uniform Light{X} +{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; +#ifdef SPOTLIGHT{X} +vec4 vLightDirection;vec4 vLightFalloff; +#elif defined(POINTLIGHT{X}) +vec4 vLightFalloff; +#elif defined(HEMILIGHT{X}) +vec3 vLightGround; +#endif +#if defined(AREALIGHT{X}) +vec4 vLightWidth;vec4 vLightHeight; +#endif +vec4 shadowsInfo;vec2 depthValues;} light{X}; +#ifdef IESLIGHTTEXTURE{X} +uniform sampler2D iesLightTexture{X}; +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X}; +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DArrayShadow shadowTexture{X}; +#else +uniform highp sampler2DArray shadowTexture{X}; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] +( +vec3 ( 1.5,0.0,0.0 ), +vec3 ( 0.0,1.5,0.0 ), +vec3 ( 0.0,0.0,5.5 ), +vec3 ( 1.5,0.0,5.5 ), +vec3 ( 1.5,1.5,0.0 ), +vec3 ( 1.0,1.0,1.0 ), +vec3 ( 0.0,1.0,5.5 ), +vec3 ( 0.5,3.5,0.75 ) +);vec3 shadowDebug{X}; +#endif +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +int index{X}=-1; +#else +int index{X}=SHADOWCSMNUM_CASCADES{X}-1; +#endif +float diff{X}=0.; +#elif defined(SHADOWCUBE{X}) +uniform samplerCube shadowTexture{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowTexture{X}; +#else +uniform sampler2D shadowTexture{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6d]) { + ShaderStore.IncludesShadersStore[name$6d] = shader$6c; +} +/** @internal */ +const lightUboDeclaration = { name: name$6d, shader: shader$6c }; + +const lightUboDeclaration$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lightUboDeclaration +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6c = "ltcHelperFunctions"; +const shader$6b = `vec2 LTCUv( const in vec3 N,const in vec3 V,const in float roughness ) {const float LUTSIZE=64.0;const float LUTSCALE=( LUTSIZE-1.0 )/LUTSIZE;const float LUTBIAS=0.5/LUTSIZE;float dotNV=saturate( dot( N,V ) );vec2 uv=vec2( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;} +float LTCClippedSphereFormFactor( const in vec3 f ) {float l=length( f );return max( ( l*l+f.z )/( l+1.0 ),0.0 );} +vec3 LTCEdgeVectorFormFactor( const in vec3 v1,const in vec3 v2 ) {float x=dot( v1,v2 );float y=abs( x );float a=0.8543985+( 0.4965155+0.0145206*y )*y;float b=3.4175940+( 4.1616724+y )*y;float v=a/b;float thetaSintheta=0.0;if( x>0.0 ) +{thetaSintheta=v;} +else +{thetaSintheta=0.5*inversesqrt( max( 1.0-x*x,1e-7 ) )-v;} +return cross( v1,v2 )*thetaSintheta;} +vec3 LTCEvaluate( const in vec3 N,const in vec3 V,const in vec3 P,const in mat3 mInv,const in vec3 rectCoords[ 4 ] ) {vec3 v1=rectCoords[ 1 ]-rectCoords[ 0 ];vec3 v2=rectCoords[ 3 ]-rectCoords[ 0 ];vec3 lightNormal=cross( v1,v2 );if( dot( lightNormal,P-rectCoords[ 0 ] )<0.0 ) return vec3( 0.0 );vec3 T1,T2;T1=normalize( V-N*dot( V,N ) );T2=- cross( N,T1 ); +mat3 mat=mInv*transposeMat3( mat3( T1,T2,N ) );vec3 coords[ 4 ];coords[ 0 ]=mat*( rectCoords[ 0 ]-P );coords[ 1 ]=mat*( rectCoords[ 1 ]-P );coords[ 2 ]=mat*( rectCoords[ 2 ]-P );coords[ 3 ]=mat*( rectCoords[ 3 ]-P );coords[ 0 ]=normalize( coords[ 0 ] );coords[ 1 ]=normalize( coords[ 1 ] );coords[ 2 ]=normalize( coords[ 2 ] );coords[ 3 ]=normalize( coords[ 3 ] );vec3 vectorFormFactor=vec3( 0.0 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 0 ],coords[ 1 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 1 ],coords[ 2 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 2 ],coords[ 3 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 3 ],coords[ 0 ] );float result=LTCClippedSphereFormFactor( vectorFormFactor );return vec3( result );} +struct areaLightData +{vec3 Diffuse;vec3 Specular;vec4 Fresnel;}; +#define inline +areaLightData computeAreaLightSpecularDiffuseFresnel(const in sampler2D ltc1,const in sampler2D ltc2,const in vec3 viewDir,const in vec3 normal,const in vec3 position,const in vec3 lightPos,const in vec3 halfWidth,const in vec3 halfHeight,const in float roughness) +{areaLightData result;vec3 rectCoords[ 4 ];rectCoords[ 0 ]=lightPos+halfWidth-halfHeight; +rectCoords[ 1 ]=lightPos-halfWidth-halfHeight;rectCoords[ 2 ]=lightPos-halfWidth+halfHeight;rectCoords[ 3 ]=lightPos+halfWidth+halfHeight; +#ifdef SPECULARTERM +vec2 uv=LTCUv( normal,viewDir,roughness );vec4 t1=texture2D( ltc1,uv );vec4 t2=texture2D( ltc2,uv );mat3 mInv=mat3( +vec3( t1.x,0,t1.y ), +vec3( 0,1, 0 ), +vec3( t1.z,0,t1.w ) +);result.Specular=LTCEvaluate( normal,viewDir,position,mInv,rectCoords );result.Fresnel=t2; +#endif +result.Diffuse=LTCEvaluate( normal,viewDir,position,mat3( 1.0 ),rectCoords );return result;}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6c]) { + ShaderStore.IncludesShadersStore[name$6c] = shader$6b; +} + +// Do not edit. +const name$6b = "lightsFragmentFunctions"; +const shader$6a = `struct lightingInfo +{vec3 diffuse; +#ifdef SPECULARTERM +vec3 specular; +#endif +#ifdef NDOTL +float ndl; +#endif +};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) +{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} +else +{lightVectorW=normalize(-lightData.xyz);} +float ndl=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +float getAttenuation(float cosAngle,float exponent) {return max(0.,pow(cosAngle,exponent));} +float getIESAttenuation(float cosAngle,sampler2D iesLightSampler) {float angle=acos(cosAngle)/PI;return texture2D(iesLightSampler,vec2(angle,0.)).r;} +lightingInfo basicSpotLighting(vec3 viewDirectionW,vec3 lightVectorW,vec3 vNormal,float attenuation,vec3 diffuseColor,vec3 specularColor,float glossiness) {lightingInfo result; +float ndl=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +lightingInfo computeIESSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness,sampler2D iesLightSampler) { +vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float dotProduct=dot(lightDirection.xyz,-lightVectorW);float cosAngle=max(0.,dotProduct);if (cosAngle>=lightDirection.w) +{ +attenuation*=getIESAttenuation(dotProduct,iesLightSampler);return basicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);} +lightingInfo result;result.diffuse=vec3(0.); +#ifdef SPECULARTERM +result.specular=vec3(0.); +#endif +#ifdef NDOTL +result.ndl=0.; +#endif +return result;} +lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) +{ +attenuation*=getAttenuation(cosAngle,lightData.w);return basicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);} +lightingInfo result;result.diffuse=vec3(0.); +#ifdef SPECULARTERM +result.specular=vec3(0.); +#endif +#ifdef NDOTL +result.ndl=0.; +#endif +return result;} +lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=mix(groundColor,diffuseColor,ndl); +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; +#endif +return result;} +#define inline +vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;} +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +#include +uniform sampler2D areaLightsLTC1Sampler;uniform sampler2D areaLightsLTC2Sampler; +#define inline +lightingInfo computeAreaLighting(sampler2D ltc1,sampler2D ltc2,vec3 viewDirectionW,vec3 vNormal,vec3 vPosition,vec3 lightPosition,vec3 halfWidth,vec3 halfHeight,vec3 diffuseColor,vec3 specularColor,float roughness) +{lightingInfo result;areaLightData data=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc2,viewDirectionW,vNormal,vPosition,lightPosition,halfWidth,halfHeight,roughness); +#ifdef SPECULARTERM +vec3 fresnel=( specularColor*data.Fresnel.x+( vec3( 1.0 )-specularColor )*data.Fresnel.y );result.specular+=specularColor*fresnel*data.Specular; +#endif +result.diffuse+=diffuseColor*data.Diffuse;return result;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$6b]) { + ShaderStore.IncludesShadersStore[name$6b] = shader$6a; +} +/** @internal */ +const lightsFragmentFunctions = { name: name$6b, shader: shader$6a }; + +const lightsFragmentFunctions$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lightsFragmentFunctions +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6a = "shadowsFragmentFunctions"; +const shader$69 = `#ifdef SHADOWS +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +#ifndef SHADOWFLOAT +float unpack(vec4 color) +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} +#endif +float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) +{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} +#define inline +float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +float shadow=unpack(textureCube(shadowSampler,directionToLight)); +#else +float shadow=textureCube(shadowSampler,directionToLight).x; +#endif +return depth>shadow ? darkness : 1.0;} +#define inline +float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); +#ifndef SHADOWFLOAT +if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} +#endif +#define inline +float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} +#define inline +float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); +#ifndef SHADOWFLOAT +if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +#ifdef IS_NDC_HALF_ZRANGE +#define ZINCLIP clipSpace.z +#else +#define ZINCLIP uvDepth.z +#endif +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define GREATEST_LESS_THAN_ONE 0.99999994 +#define DISABLE_UNIFORMITY_ANALYSIS +#define inline +float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +const vec3 PoissonSamplers32[64]=vec3[64]( +vec3(0.06407013,0.05409927,0.), +vec3(0.7366577,0.5789394,0.), +vec3(-0.6270542,-0.5320278,0.), +vec3(-0.4096107,0.8411095,0.), +vec3(0.6849564,-0.4990818,0.), +vec3(-0.874181,-0.04579735,0.), +vec3(0.9989998,0.0009880066,0.), +vec3(-0.004920578,-0.9151649,0.), +vec3(0.1805763,0.9747483,0.), +vec3(-0.2138451,0.2635818,0.), +vec3(0.109845,0.3884785,0.), +vec3(0.06876755,-0.3581074,0.), +vec3(0.374073,-0.7661266,0.), +vec3(0.3079132,-0.1216763,0.), +vec3(-0.3794335,-0.8271583,0.), +vec3(-0.203878,-0.07715034,0.), +vec3(0.5912697,0.1469799,0.), +vec3(-0.88069,0.3031784,0.), +vec3(0.5040108,0.8283722,0.), +vec3(-0.5844124,0.5494877,0.), +vec3(0.6017799,-0.1726654,0.), +vec3(-0.5554981,0.1559997,0.), +vec3(-0.3016369,-0.3900928,0.), +vec3(-0.5550632,-0.1723762,0.), +vec3(0.925029,0.2995041,0.), +vec3(-0.2473137,0.5538505,0.), +vec3(0.9183037,-0.2862392,0.), +vec3(0.2469421,0.6718712,0.), +vec3(0.3916397,-0.4328209,0.), +vec3(-0.03576927,-0.6220032,0.), +vec3(-0.04661255,0.7995201,0.), +vec3(0.4402924,0.3640312,0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.) +);const vec3 PoissonSamplers64[64]=vec3[64]( +vec3(-0.613392,0.617481,0.), +vec3(0.170019,-0.040254,0.), +vec3(-0.299417,0.791925,0.), +vec3(0.645680,0.493210,0.), +vec3(-0.651784,0.717887,0.), +vec3(0.421003,0.027070,0.), +vec3(-0.817194,-0.271096,0.), +vec3(-0.705374,-0.668203,0.), +vec3(0.977050,-0.108615,0.), +vec3(0.063326,0.142369,0.), +vec3(0.203528,0.214331,0.), +vec3(-0.667531,0.326090,0.), +vec3(-0.098422,-0.295755,0.), +vec3(-0.885922,0.215369,0.), +vec3(0.566637,0.605213,0.), +vec3(0.039766,-0.396100,0.), +vec3(0.751946,0.453352,0.), +vec3(0.078707,-0.715323,0.), +vec3(-0.075838,-0.529344,0.), +vec3(0.724479,-0.580798,0.), +vec3(0.222999,-0.215125,0.), +vec3(-0.467574,-0.405438,0.), +vec3(-0.248268,-0.814753,0.), +vec3(0.354411,-0.887570,0.), +vec3(0.175817,0.382366,0.), +vec3(0.487472,-0.063082,0.), +vec3(-0.084078,0.898312,0.), +vec3(0.488876,-0.783441,0.), +vec3(0.470016,0.217933,0.), +vec3(-0.696890,-0.549791,0.), +vec3(-0.149693,0.605762,0.), +vec3(0.034211,0.979980,0.), +vec3(0.503098,-0.308878,0.), +vec3(-0.016205,-0.872921,0.), +vec3(0.385784,-0.393902,0.), +vec3(-0.146886,-0.859249,0.), +vec3(0.643361,0.164098,0.), +vec3(0.634388,-0.049471,0.), +vec3(-0.688894,0.007843,0.), +vec3(0.464034,-0.188818,0.), +vec3(-0.440840,0.137486,0.), +vec3(0.364483,0.511704,0.), +vec3(0.034028,0.325968,0.), +vec3(0.099094,-0.308023,0.), +vec3(0.693960,-0.366253,0.), +vec3(0.678884,-0.204688,0.), +vec3(0.001801,0.780328,0.), +vec3(0.145177,-0.898984,0.), +vec3(0.062655,-0.611866,0.), +vec3(0.315226,-0.604297,0.), +vec3(-0.780145,0.486251,0.), +vec3(-0.371868,0.882138,0.), +vec3(0.200476,0.494430,0.), +vec3(-0.494552,-0.711051,0.), +vec3(0.612476,0.705252,0.), +vec3(-0.578845,-0.768792,0.), +vec3(-0.772454,-0.090976,0.), +vec3(0.504440,0.372295,0.), +vec3(0.155736,0.065157,0.), +vec3(0.391522,0.849605,0.), +vec3(-0.620106,-0.328104,0.), +vec3(0.789239,-0.419965,0.), +vec3(-0.545396,0.538133,0.), +vec3(-0.178564,-0.596057,0.) +); +#define inline +float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i0.0) { return 1e6; } +vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)=0.) {index{X}=i;break;}} +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +if (index{X}>=0) +#endif +{ +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#else +shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#endif +#else +shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; +#endif +#ifndef SHADOWCSMNOBLEND{X} +float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) +{index{X}+=1;float nextShadow=0.; +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#else +nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#endif +#else +nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +shadow=mix(nextShadow,shadow,diffRatio); +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); +#endif +} +#endif +} +#elif defined(SHADOWCLOSEESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPOISSON{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#else +#if defined(SHADOWCUBE{X}) +shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#endif +#ifdef SHADOWONLY +#ifndef SHADOWINUSE +#define SHADOWINUSE +#endif +globalShadow+=shadow;shadowLightCount+=1.0; +#endif +#else +shadow=1.; +#endif +aggShadow+=shadow;numLights+=1.0; +#ifndef SHADOWONLY +#ifdef CUSTOMUSERLIGHTING +diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); +#ifdef SPECULARTERM +specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); +#endif +#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) +diffuseBase+=lightmapColor.rgb*shadow; +#ifdef SPECULARTERM +#ifndef LIGHTMAPNOSPECULAR{X} +specularBase+=info.specular*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef CLEARCOAT +#ifndef LIGHTMAPNOSPECULAR{X} +clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef SHEEN +#ifndef LIGHTMAPNOSPECULAR{X} +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#else +#ifdef SHADOWCSMDEBUG{X} +diffuseBase+=info.diffuse*shadowDebug{X}; +#else +diffuseBase+=info.diffuse*shadow; +#endif +#ifdef SPECULARTERM +specularBase+=info.specular*shadow; +#endif +#ifdef CLEARCOAT +clearCoatBase+=info.clearCoat.rgb*shadow; +#endif +#ifdef SHEEN +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$66]) { + ShaderStore.IncludesShadersStore[name$66] = shader$65; +} +/** @internal */ +const lightFragment = { name: name$66, shader: shader$65 }; + +const lightFragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lightFragment +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$65 = "logDepthFragment"; +const shader$64 = `#ifdef LOGARITHMICDEPTH +gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$65]) { + ShaderStore.IncludesShadersStore[name$65] = shader$64; +} + +// Do not edit. +const name$64 = "fogFragment"; +const shader$63 = `#ifdef FOG +float fog=CalcFogFactor(); +#ifdef PBR +fog=toLinearSpace(fog); +#endif +color.rgb=mix(vFogColor,color.rgb,fog); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$64]) { + ShaderStore.IncludesShadersStore[name$64] = shader$63; +} + +// Do not edit. +const name$63 = "backgroundPixelShader"; +const shader$62 = `#ifdef TEXTURELODSUPPORT +#extension GL_EXT_shader_texture_lod : enable +#endif +precision highp float; +#include<__decl__backgroundFragment> +#include +varying vec3 vPositionW; +#ifdef MAINUV1 +varying vec2 vMainUV1; +#endif +#ifdef MAINUV2 +varying vec2 vMainUV2; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef DIFFUSE +#if DIFFUSEDIRECTUV==1 +#define vDiffuseUV vMainUV1 +#elif DIFFUSEDIRECTUV==2 +#define vDiffuseUV vMainUV2 +#else +varying vec2 vDiffuseUV; +#endif +uniform sampler2D diffuseSampler; +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +#define sampleReflection(s,c) textureCube(s,c) +uniform samplerCube reflectionSampler; +#ifdef TEXTURELODSUPPORT +#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#else +#define sampleReflection(s,c) texture2D(s,c) +uniform sampler2D reflectionSampler; +#ifdef TEXTURELODSUPPORT +#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include +#endif +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE; +#endif +#ifndef SHADOWONLY +#define SHADOWONLY; +#endif +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include +#include +#include +#ifdef REFLECTIONFRESNEL +#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) +{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#ifdef PROJECTED_GROUND +#include +vec3 project(vec3 viewDirectionW,vec3 eyePosition) {float radius=projectedGroundInfos.x;float height=projectedGroundInfos.y;vec3 camDir=-viewDirectionW;float skySphereDistance=sphereIntersectFromOrigin(eyePosition,camDir,radius).x;vec3 skySpherePositionW=eyePosition+camDir*skySphereDistance;vec3 p=normalize(skySpherePositionW);eyePosition.y-=height;float sIntersection=sphereIntersectFromOrigin(eyePosition,p,radius).x;vec3 h=vec3(0.0,-height,0.0);float dIntersection=diskIntersectWithBackFaceCulling(eyePosition,p,h,radius);p=(eyePosition+min(sIntersection,dIntersection)*p);return p;} +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(0.0,1.0,0.0); +#endif +float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.; +#include[0..maxSimultaneousLights] +#ifdef SHADOWINUSE +globalShadow/=shadowLightCount; +#else +globalShadow=1.0; +#endif +#ifndef BACKMAT_SHADOWONLY +vec4 reflectionColor=vec4(1.,1.,1.,1.); +#ifdef REFLECTION +#ifdef PROJECTED_GROUND +vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.)); +#else +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords=reflectionVector; +#else +vec2 reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +#ifdef REFLECTIONBLUR +float reflectionLOD=vReflectionInfos.y; +#ifdef TEXTURELODSUPPORT +reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); +#else +float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( +sampleReflection(reflectionSamplerHigh,reflectionCoords), +reflectionSpecularMid, +lodReflectionNormalizedDoubled +);} else {reflectionColor=mix( +reflectionSpecularMid, +sampleReflection(reflectionSamplerLow,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#else +vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef GAMMAREFLECTION +reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); +#endif +#ifdef REFLECTIONBGR +reflectionColor.rgb=reflectionColor.bgr; +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#endif +vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; +#ifdef DIFFUSE +vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); +#ifdef GAMMADIFFUSE +diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); +#endif +diffuseMap.rgb*=vDiffuseInfos.y; +#ifdef DIFFUSEHASALPHA +finalAlpha*=diffuseMap.a; +#endif +diffuseColor=diffuseMap.rgb; +#endif +#ifdef REFLECTIONFRESNEL +vec3 colorBase=diffuseColor; +#else +vec3 colorBase=reflectionColor.rgb*diffuseColor; +#endif +colorBase=max(colorBase,0.0); +#ifdef USERGBCOLOR +vec3 finalColor=colorBase; +#else +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); +#else +vec3 mainColor=vPrimaryColor.rgb; +#endif +vec3 finalColor=colorBase*mainColor; +#endif +#ifdef REFLECTIONFRESNEL +vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; +#ifdef REFLECTIONFALLOFF +float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; +#endif +finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); +#endif +#ifdef OPACITYFRESNEL +float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; +#endif +#ifdef SHADOWINUSE +finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); +#endif +vec4 color=vec4(finalColor,finalAlpha); +#else +vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); +#endif +#include +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +#if !defined(SKIPFINALCOLORCLAMP) +color.rgb=clamp(color.rgb,0.,30.0); +#endif +#else +color=applyImageProcessing(color); +#endif +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#ifdef NOISE +color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); +#endif +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$63]) { + ShaderStore.ShadersStore[name$63] = shader$62; +} +/** @internal */ +const backgroundPixelShader = { name: name$63, shader: shader$62 }; + +const background_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + backgroundPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * This represents all the required information to add a fresnel effect on a material: + * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/fresnelParameters + */ +class FresnelParameters { + /** + * Define if the fresnel effect is enable or not. + */ + get isEnabled() { + return this._isEnabled; + } + set isEnabled(value) { + if (this._isEnabled === value) { + return; + } + this._isEnabled = value; + AbstractEngine.MarkAllMaterialsAsDirty(4 | 16); + } + /** + * Creates a new FresnelParameters object. + * + * @param options provide your own settings to optionally to override defaults + */ + constructor(options = {}) { + this._isEnabled = true; + this.bias = options.bias === undefined ? 0 : options.bias; + this.power = options.power === undefined ? 1 : options.power; + this.leftColor = options.leftColor || Color3.White(); + this.rightColor = options.rightColor || Color3.Black(); + if (options.isEnabled === false) { + this.isEnabled = false; + } + } + /** + * Clones the current fresnel and its values + * @returns a clone fresnel configuration + */ + clone() { + const newFresnelParameters = new FresnelParameters(); + DeepCopier.DeepCopy(this, newFresnelParameters); + return newFresnelParameters; + } + /** + * Determines equality between FresnelParameters objects + * @param otherFresnelParameters defines the second operand + * @returns true if the power, bias, leftColor, rightColor and isEnabled values are equal to the given ones + */ + equals(otherFresnelParameters) { + return (otherFresnelParameters && + this.bias === otherFresnelParameters.bias && + this.power === otherFresnelParameters.power && + this.leftColor.equals(otherFresnelParameters.leftColor) && + this.rightColor.equals(otherFresnelParameters.rightColor) && + this.isEnabled === otherFresnelParameters.isEnabled); + } + /** + * Serializes the current fresnel parameters to a JSON representation. + * @returns the JSON serialization + */ + serialize() { + return { + isEnabled: this.isEnabled, + leftColor: this.leftColor.asArray(), + rightColor: this.rightColor.asArray(), + bias: this.bias, + power: this.power, + }; + } + /** + * Parse a JSON object and deserialize it to a new Fresnel parameter object. + * @param parsedFresnelParameters Define the JSON representation + * @returns the parsed parameters + */ + static Parse(parsedFresnelParameters) { + return new FresnelParameters({ + isEnabled: parsedFresnelParameters.isEnabled, + leftColor: Color3.FromArray(parsedFresnelParameters.leftColor), + rightColor: Color3.FromArray(parsedFresnelParameters.rightColor), + bias: parsedFresnelParameters.bias, + power: parsedFresnelParameters.power || 1.0, + }); + } +} +// References the dependencies. +SerializationHelper._FresnelParametersParser = FresnelParameters.Parse; + +// Do not edit. +const name$62 = "colorPixelShader"; +const shader$61 = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +#define VERTEXCOLOR +varying vec4 vColor; +#else +uniform vec4 color; +#endif +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +gl_FragColor=vColor; +#else +gl_FragColor=color; +#endif +#include(color,gl_FragColor) +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$62]) { + ShaderStore.ShadersStore[name$62] = shader$61; +} +/** @internal */ +const colorPixelShader = { name: name$62, shader: shader$61 }; + +const color_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + colorPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$61 = "vertexColorMixing"; +const shader$60 = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +vColor=vec4(1.0); +#ifdef VERTEXCOLOR +#ifdef VERTEXALPHA +vColor*=colorUpdated; +#else +vColor.rgb*=colorUpdated.rgb; +#endif +#endif +#ifdef INSTANCESCOLOR +vColor*=instanceColor; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$61]) { + ShaderStore.IncludesShadersStore[name$61] = shader$60; +} + +// Do not edit. +const name$60 = "colorVertexShader"; +const shader$5$ = `attribute vec3 position; +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +#ifdef FOG +uniform mat4 view; +#endif +#include +uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#ifdef VERTEXCOLOR +vec4 colorUpdated=color; +#endif +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#include +#include +#include +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$60]) { + ShaderStore.ShadersStore[name$60] = shader$5$; +} +/** @internal */ +const colorVertexShader = { name: name$60, shader: shader$5$ }; + +const color_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + colorVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * The Physically based simple base material of BJS. + * + * This enables better naming and convention enforcements on top of the pbrMaterial. + * It is used as the base class for both the specGloss and metalRough conventions. + */ +class PBRBaseSimpleMaterial extends PBRBaseMaterial { + /** + * Gets the current double sided mode. + */ + get doubleSided() { + return this._twoSidedLighting; + } + /** + * If sets to true and backfaceCulling is false, normals will be flipped on the backside. + */ + set doubleSided(value) { + if (this._twoSidedLighting === value) { + return; + } + this._twoSidedLighting = value; + this.backFaceCulling = !value; + this._markAllSubMeshesAsTexturesDirty(); + } + /** + * Instantiates a new PBRMaterial instance. + * + * @param name The material name + * @param scene The scene the material will be use in. + */ + constructor(name, scene) { + super(name, scene); + /** + * Number of Simultaneous lights allowed on the material. + */ + this.maxSimultaneousLights = 4; + /** + * If sets to true, disables all the lights affecting the material. + */ + this.disableLighting = false; + /** + * If sets to true, x component of normal map value will invert (x = 1.0 - x). + */ + this.invertNormalMapX = false; + /** + * If sets to true, y component of normal map value will invert (y = 1.0 - y). + */ + this.invertNormalMapY = false; + /** + * Emissivie color used to self-illuminate the model. + */ + this.emissiveColor = new Color3(0, 0, 0); + /** + * Occlusion Channel Strength. + */ + this.occlusionStrength = 1.0; + /** + * If true, the light map contains occlusion information instead of lighting info. + */ + this.useLightmapAsShadowmap = false; + this._useAlphaFromAlbedoTexture = true; + this._useAmbientInGrayScale = true; + } + getClassName() { + return "PBRBaseSimpleMaterial"; + } +} +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsLightsDirty") +], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsLightsDirty") +], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture") +], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture") +], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0); +__decorate([ + serializeAsColor3("emissive"), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength") +], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture") +], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff") +], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0); +__decorate([ + serialize() +], PBRBaseSimpleMaterial.prototype, "doubleSided", null); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", null) +], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0); + +/** + * The PBR material of BJS following the metal roughness convention. + * + * This fits to the PBR convention in the GLTF definition: + * https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md + */ +class PBRMetallicRoughnessMaterial extends PBRBaseSimpleMaterial { + /** + * Instantiates a new PBRMetalRoughnessMaterial instance. + * + * @param name The material name + * @param scene The scene the material will be use in. + */ + constructor(name, scene) { + super(name, scene); + this._useRoughnessFromMetallicTextureAlpha = false; + this._useRoughnessFromMetallicTextureGreen = true; + this._useMetallnessFromMetallicTextureBlue = true; + this.metallic = 1.0; + this.roughness = 1.0; + } + /** + * @returns the current class name of the material. + */ + getClassName() { + return "PBRMetallicRoughnessMaterial"; + } + /** + * Makes a duplicate of the current material. + * @param name - name to use for the new material. + * @returns cloned material instance + */ + clone(name) { + const clone = SerializationHelper.Clone(() => new PBRMetallicRoughnessMaterial(name, this.getScene()), this); + clone.id = name; + clone.name = name; + this.clearCoat.copyTo(clone.clearCoat); + this.anisotropy.copyTo(clone.anisotropy); + this.brdf.copyTo(clone.brdf); + this.sheen.copyTo(clone.sheen); + this.subSurface.copyTo(clone.subSurface); + return clone; + } + /** + * Serialize the material to a parsable JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial"; + if (!this.clearCoat.doNotSerialize) { + serializationObject.clearCoat = this.clearCoat.serialize(); + } + if (!this.anisotropy.doNotSerialize) { + serializationObject.anisotropy = this.anisotropy.serialize(); + } + if (!this.brdf.doNotSerialize) { + serializationObject.brdf = this.brdf.serialize(); + } + if (!this.sheen.doNotSerialize) { + serializationObject.sheen = this.sheen.serialize(); + } + if (!this.subSurface.doNotSerialize) { + serializationObject.subSurface = this.subSurface.serialize(); + } + if (!this.iridescence.doNotSerialize) { + serializationObject.iridescence = this.iridescence.serialize(); + } + return serializationObject; + } + /** + * Parses a JSON object corresponding to the serialize function. + * @param source - JSON source object. + * @param scene - Defines the scene we are parsing for + * @param rootUrl - Defines the rootUrl of this parsed object + * @returns a new PBRMetalRoughnessMaterial + */ + static Parse(source, scene, rootUrl) { + const material = SerializationHelper.Parse(() => new PBRMetallicRoughnessMaterial(source.name, scene), source, scene, rootUrl); + if (source.clearCoat) { + material.clearCoat.parse(source.clearCoat, scene, rootUrl); + } + if (source.anisotropy) { + material.anisotropy.parse(source.anisotropy, scene, rootUrl); + } + if (source.brdf) { + material.brdf.parse(source.brdf, scene, rootUrl); + } + if (source.sheen) { + material.sheen.parse(source.sheen, scene, rootUrl); + } + if (source.subSurface) { + material.subSurface.parse(source.subSurface, scene, rootUrl); + } + if (source.iridescence) { + material.iridescence.parse(source.iridescence, scene, rootUrl); + } + return material; + } +} +__decorate([ + serializeAsColor3(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor") +], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture") +], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture") +], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0); +RegisterClass("BABYLON.PBRMetallicRoughnessMaterial", PBRMetallicRoughnessMaterial); + +/** + * The PBR material of BJS following the specular glossiness convention. + * + * This fits to the PBR convention in the GLTF definition: + * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness + */ +class PBRSpecularGlossinessMaterial extends PBRBaseSimpleMaterial { + /** + * Specifies if the reflectivity texture contains the glossiness information in its alpha channel. + */ + get useMicroSurfaceFromReflectivityMapAlpha() { + return this._useMicroSurfaceFromReflectivityMapAlpha; + } + /** + * Instantiates a new PBRSpecularGlossinessMaterial instance. + * + * @param name The material name + * @param scene The scene the material will be use in. + */ + constructor(name, scene) { + super(name, scene); + this._useMicroSurfaceFromReflectivityMapAlpha = true; + } + /** + * @returns the current class name of the material. + */ + getClassName() { + return "PBRSpecularGlossinessMaterial"; + } + /** + * Makes a duplicate of the current material. + * @param name - name to use for the new material. + * @returns cloned material instance + */ + clone(name) { + const clone = SerializationHelper.Clone(() => new PBRSpecularGlossinessMaterial(name, this.getScene()), this); + clone.id = name; + clone.name = name; + this.clearCoat.copyTo(clone.clearCoat); + this.anisotropy.copyTo(clone.anisotropy); + this.brdf.copyTo(clone.brdf); + this.sheen.copyTo(clone.sheen); + this.subSurface.copyTo(clone.subSurface); + return clone; + } + /** + * Serialize the material to a parsable JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial"; + if (!this.clearCoat.doNotSerialize) { + serializationObject.clearCoat = this.clearCoat.serialize(); + } + if (!this.anisotropy.doNotSerialize) { + serializationObject.anisotropy = this.anisotropy.serialize(); + } + if (!this.brdf.doNotSerialize) { + serializationObject.brdf = this.brdf.serialize(); + } + if (!this.sheen.doNotSerialize) { + serializationObject.sheen = this.sheen.serialize(); + } + if (!this.subSurface.doNotSerialize) { + serializationObject.subSurface = this.subSurface.serialize(); + } + if (!this.iridescence.doNotSerialize) { + serializationObject.iridescence = this.iridescence.serialize(); + } + return serializationObject; + } + /** + * Parses a JSON object corresponding to the serialize function. + * @param source - JSON source object. + * @param scene - the scene to parse to. + * @param rootUrl - root url of the assets. + * @returns a new PBRSpecularGlossinessMaterial. + */ + static Parse(source, scene, rootUrl) { + const material = SerializationHelper.Parse(() => new PBRSpecularGlossinessMaterial(source.name, scene), source, scene, rootUrl); + if (source.clearCoat) { + material.clearCoat.parse(source.clearCoat, scene, rootUrl); + } + if (source.anisotropy) { + material.anisotropy.parse(source.anisotropy, scene, rootUrl); + } + if (source.brdf) { + material.brdf.parse(source.brdf, scene, rootUrl); + } + if (source.sheen) { + material.sheen.parse(source.sheen, scene, rootUrl); + } + if (source.subSurface) { + material.subSurface.parse(source.subSurface, scene, rootUrl); + } + if (source.iridescence) { + material.iridescence.parse(source.iridescence, scene, rootUrl); + } + return material; + } +} +__decorate([ + serializeAsColor3("diffuse"), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor") +], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture") +], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0); +__decorate([ + serializeAsColor3("specular"), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor") +], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface") +], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0); +__decorate([ + serializeAsTexture(), + expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture") +], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0); +RegisterClass("BABYLON.PBRSpecularGlossinessMaterial", PBRSpecularGlossinessMaterial); + +// Do not edit. +const name$5$ = "pbrUboDeclaration"; +const shader$5_ = `uniform vAlbedoInfos: vec2f;uniform vBaseWeightInfos: vec2f;uniform vAmbientInfos: vec4f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vReflectivityInfos: vec3f;uniform vMicroSurfaceSamplerInfos: vec2f;uniform vReflectionInfos: vec2f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vBumpInfos: vec3f;uniform albedoMatrix: mat4x4f;uniform baseWeightMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform reflectivityMatrix: mat4x4f;uniform microSurfaceSamplerMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionColor: vec3f;uniform vAlbedoColor: vec4f;uniform baseWeight: f32;uniform vLightingIntensity: vec4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform pointSize: f32;uniform vReflectivityColor: vec4f;uniform vEmissiveColor: vec3f;uniform vAmbientColor: vec3f;uniform vDebugMode: vec2f;uniform vMetallicReflectanceFactors: vec4f;uniform vMetallicReflectanceInfos: vec2f;uniform metallicReflectanceMatrix: mat4x4f;uniform vReflectanceInfos: vec2f;uniform reflectanceMatrix: mat4x4f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f; +#define ADDITIONAL_UBO_DECLARATION +#include +#include +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5$]) { + ShaderStore.IncludesShadersStoreWGSL[name$5$] = shader$5_; +} + +// Do not edit. +const name$5_ = "uvAttributeDeclaration"; +const shader$5Z = `#ifdef UV{X} +attribute uv{X}: vec2f; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5_]) { + ShaderStore.IncludesShadersStoreWGSL[name$5_] = shader$5Z; +} + +// Do not edit. +const name$5Z = "mainUVVaryingDeclaration"; +const shader$5Y = `#ifdef MAINUV{X} +varying vMainUV{X}: vec2f; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5Z]) { + ShaderStore.IncludesShadersStoreWGSL[name$5Z] = shader$5Y; +} + +// Do not edit. +const name$5Y = "prePassVertexDeclaration"; +const shader$5X = `#ifdef PREPASS +#ifdef PREPASS_LOCAL_POSITION +varying vPosition : vec3f; +#endif +#ifdef PREPASS_DEPTH +varying vViewPos: vec3f; +#endif +#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) +uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5Y]) { + ShaderStore.IncludesShadersStoreWGSL[name$5Y] = shader$5X; +} + +// Do not edit. +const name$5X = "samplerVertexDeclaration"; +const shader$5W = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +varying v_VARYINGNAME_UV: vec2f; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5X]) { + ShaderStore.IncludesShadersStoreWGSL[name$5X] = shader$5W; +} + +// Do not edit. +const name$5W = "harmonicsFunctions"; +const shader$5V = `#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {return uniforms.vSphericalL00 ++ uniforms.vSphericalL1_1*(normal.y) ++ uniforms.vSphericalL10*(normal.z) ++ uniforms.vSphericalL11*(normal.x) ++ uniforms.vSphericalL2_2*(normal.y*normal.x) ++ uniforms.vSphericalL2_1*(normal.y*normal.z) ++ uniforms.vSphericalL20*((3.0*normal.z*normal.z)-1.0) ++ uniforms.vSphericalL21*(normal.z*normal.x) ++ uniforms.vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} +#else +fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {var Nx: f32=normal.x;var Ny: f32=normal.y;var Nz: f32=normal.z;var C1: vec3f=uniforms.vSphericalZZ.rgb;var Cx: vec3f=uniforms.vSphericalX.rgb;var Cy: vec3f=uniforms.vSphericalY.rgb;var Cz: vec3f=uniforms.vSphericalZ.rgb;var Cxx_zz: vec3f=uniforms.vSphericalXX_ZZ.rgb;var Cyy_zz: vec3f=uniforms.vSphericalYY_ZZ.rgb;var Cxy: vec3f=uniforms.vSphericalXY.rgb;var Cyz: vec3f=uniforms.vSphericalYZ.rgb;var Czx: vec3f=uniforms.vSphericalZX.rgb;var a1: vec3f=Cyy_zz*Ny+Cy;var a2: vec3f=Cyz*Nz+a1;var b1: vec3f=Czx*Nz+Cx;var b2: vec3f=Cxy*Ny+b1;var b3: vec3f=Cxx_zz*Nx+b2;var t1: vec3f=Cz *Nz+C1;var t2: vec3f=a2 *Ny+t1;var t3: vec3f=b3 *Nx+t2;return t3;} +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5W]) { + ShaderStore.IncludesShadersStoreWGSL[name$5W] = shader$5V; +} + +// Do not edit. +const name$5V = "bumpVertexDeclaration"; +const shader$5U = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5V]) { + ShaderStore.IncludesShadersStoreWGSL[name$5V] = shader$5U; +} + +// Do not edit. +const name$5U = "prePassVertex"; +const shader$5T = `#ifdef PREPASS_DEPTH +vertexOutputs.vViewPos=(scene.view*worldPos).rgb; +#endif +#ifdef PREPASS_LOCAL_POSITION +vertexOutputs.vPosition=positionUpdated.xyz; +#endif +#if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED) +vertexOutputs.vCurrentPosition=scene.viewProjection*worldPos; +#if NUM_BONE_INFLUENCERS>0 +var previousInfluence: mat4x4f;previousInfluence=mPreviousBones[ i32(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[ i32(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[ i32(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[ i32(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0); +#else +vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5U]) { + ShaderStore.IncludesShadersStoreWGSL[name$5U] = shader$5T; +} + +// Do not edit. +const name$5T = "uvVariableDeclaration"; +const shader$5S = `#ifdef MAINUV{X} +#if !defined(UV{X}) +var uv{X}: vec2f=vec2f(0.,0.); +#else +var uv{X}: vec2f=vertexInputs.uv{X}; +#endif +vertexOutputs.vMainUV{X}=uv{X}; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5T]) { + ShaderStore.IncludesShadersStoreWGSL[name$5T] = shader$5S; +} + +// Do not edit. +const name$5S = "samplerVertexImplementation"; +const shader$5R = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +if (uniforms.v_INFONAME_==0.) +{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uvUpdated,1.0,0.0)).xy;} +#ifdef UV2 +else if (uniforms.v_INFONAME_==1.) +{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uv2Updated,1.0,0.0)).xy;} +#endif +#ifdef UV3 +else if (uniforms.v_INFONAME_==2.) +{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv3,1.0,0.0)).xy;} +#endif +#ifdef UV4 +else if (uniforms.v_INFONAME_==3.) +{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv4,1.0,0.0)).xy;} +#endif +#ifdef UV5 +else if (uniforms.v_INFONAME_==4.) +{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv5,1.0,0.0)).xy;} +#endif +#ifdef UV6 +else if (uniforms.v_INFONAME_==5.) +{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv6,1.0,0.0)).xy;} +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5S]) { + ShaderStore.IncludesShadersStoreWGSL[name$5S] = shader$5R; +} + +// Do not edit. +const name$5R = "bumpVertex"; +const shader$5Q = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +var tbnNormal: vec3f=normalize(normalUpdated);var tbnTangent: vec3f=normalize(tangentUpdated.xyz);var tbnBitangent: vec3f=cross(tbnNormal,tbnTangent)*tangentUpdated.w;var matTemp= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz)* mat3x3f(tbnTangent,tbnBitangent,tbnNormal);vertexOutputs.vTBN0=matTemp[0];vertexOutputs.vTBN1=matTemp[1];vertexOutputs.vTBN2=matTemp[2]; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5R]) { + ShaderStore.IncludesShadersStoreWGSL[name$5R] = shader$5Q; +} + +// Do not edit. +const name$5Q = "vertexColorMixing"; +const shader$5P = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +vertexOutputs.vColor=vec4f(1.0); +#ifdef VERTEXCOLOR +#ifdef VERTEXALPHA +vertexOutputs.vColor*=vertexInputs.color; +#else +vertexOutputs.vColor=vec4f(vertexOutputs.vColor.rgb*vertexInputs.color.rgb,vertexOutputs.vColor.a); +#endif +#endif +#ifdef INSTANCESCOLOR +vertexOutputs.vColor*=vertexInputs.instanceColor; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5Q]) { + ShaderStore.IncludesShadersStoreWGSL[name$5Q] = shader$5P; +} + +// Do not edit. +const name$5P = "pbrVertexShader"; +const shader$5O = `#include +#define CUSTOM_VERTEX_BEGIN +attribute position: vec3f; +#ifdef NORMAL +attribute normal: vec3f; +#endif +#ifdef TANGENT +attribute tangent: vec4f; +#endif +#ifdef UV1 +attribute uv: vec2f; +#endif +#include[2..7] +#include[1..7] +#ifdef VERTEXCOLOR +attribute color: vec4f; +#endif +#include +#include +#include +#include +#include +#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) +#include(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) +#endif +#ifdef SUBSURFACE +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor) +#endif +varying vPositionW: vec3f; +#if DEBUGMODE>0 +varying vClipSpacePosition: vec4f; +#endif +#ifdef NORMAL +varying vNormalW: vec3f; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vEnvironmentIrradiance: vec3f; +#include +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vColor: vec4f; +#endif +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vPositionUVW: vec3f; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vDirectionW: vec3f; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +var positionUpdated: vec3f=vertexInputs.position; +#ifdef NORMAL +var normalUpdated: vec3f=vertexInputs.normal; +#endif +#ifdef TANGENT +var tangentUpdated: vec4f=vertexInputs.tangent; +#endif +#ifdef UV1 +var uvUpdated: vec2f=vertexInputs.uv; +#endif +#ifdef UV2 +var uv2Updated: vec2f=vertexInputs.uv2; +#endif +#ifdef VERTEXCOLOR +var colorUpdated: vec4f=vertexInputs.color; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vertexOutputs.vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include +#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED) +vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0); +#endif +#include +#include +var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);vertexOutputs.vPositionW= worldPos.xyz; +#ifdef PREPASS +#include +#endif +#ifdef NORMAL +var normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated); +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +var reflectionVector: vec3f= (uniforms.reflectionMatrix* vec4f(vertexOutputs.vNormalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +vertexOutputs.vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;} +#else +vertexOutputs.position=scene.viewProjection*worldPos; +#endif +#if DEBUGMODE>0 +vertexOutputs.vClipSpacePosition=vertexOutputs.position; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vertexOutputs.vDirectionW=normalize((finalWorld*vec4f(positionUpdated,0.0)).xyz); +#endif +#ifndef UV1 +var uvUpdated: vec2f= vec2f(0.,0.); +#endif +#ifdef MAINUV1 +vertexOutputs.vMainUV1=uvUpdated; +#endif +#ifndef UV2 +var uv2Updated: vec2f= vec2f(0.,0.); +#endif +#ifdef MAINUV2 +vertexOutputs.vMainUV2=uv2Updated; +#endif +#include[3..7] +#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) +#include(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight,_MATRIXNAME_,baseWeight,_INFONAME_,BaseWeightInfos.x) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z) +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) +#endif +#ifdef SUBSURFACE +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) +#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x) +#endif +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#include +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$5P]) { + ShaderStore.ShadersStoreWGSL[name$5P] = shader$5O; +} +/** @internal */ +const pbrVertexShaderWGSL = { name: name$5P, shader: shader$5O }; + +const pbr_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + pbrVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$5O = "prePassDeclaration"; +const shader$5N = `#ifdef PREPASS +#ifdef PREPASS_LOCAL_POSITION +varying vPosition : vec3f; +#endif +#ifdef PREPASS_DEPTH +varying vViewPos: vec3f; +#endif +#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) +varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5O]) { + ShaderStore.IncludesShadersStoreWGSL[name$5O] = shader$5N; +} + +// Do not edit. +const name$5N = "oitDeclaration"; +const shader$5M = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY +#define MAX_DEPTH 99999.0 +var oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5N]) { + ShaderStore.IncludesShadersStoreWGSL[name$5N] = shader$5M; +} + +// Do not edit. +const name$5M = "pbrFragmentExtraDeclaration"; +const shader$5L = `varying vPositionW: vec3f; +#if DEBUGMODE>0 +varying vClipSpacePosition: vec4f; +#endif +#include[1..7] +#ifdef NORMAL +varying vNormalW: vec3f; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vEnvironmentIrradiance: vec3f; +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vColor: vec4f; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5M]) { + ShaderStore.IncludesShadersStoreWGSL[name$5M] = shader$5L; +} + +// Do not edit. +const name$5L = "samplerFragmentDeclaration"; +const shader$5K = `#ifdef _DEFINENAME_ +#if _DEFINENAME_DIRECTUV==1 +#define v_VARYINGNAME_UV vMainUV1 +#elif _DEFINENAME_DIRECTUV==2 +#define v_VARYINGNAME_UV vMainUV2 +#elif _DEFINENAME_DIRECTUV==3 +#define v_VARYINGNAME_UV vMainUV3 +#elif _DEFINENAME_DIRECTUV==4 +#define v_VARYINGNAME_UV vMainUV4 +#elif _DEFINENAME_DIRECTUV==5 +#define v_VARYINGNAME_UV vMainUV5 +#elif _DEFINENAME_DIRECTUV==6 +#define v_VARYINGNAME_UV vMainUV6 +#else +varying v_VARYINGNAME_UV: vec2f; +#endif +var _SAMPLERNAME_SamplerSampler: sampler;var _SAMPLERNAME_Sampler: texture_2d; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5L]) { + ShaderStore.IncludesShadersStoreWGSL[name$5L] = shader$5K; +} + +// Do not edit. +const name$5K = "samplerFragmentAlternateDeclaration"; +const shader$5J = `#ifdef _DEFINENAME_ +#if _DEFINENAME_DIRECTUV==1 +#define v_VARYINGNAME_UV vMainUV1 +#elif _DEFINENAME_DIRECTUV==2 +#define v_VARYINGNAME_UV vMainUV2 +#elif _DEFINENAME_DIRECTUV==3 +#define v_VARYINGNAME_UV vMainUV3 +#elif _DEFINENAME_DIRECTUV==4 +#define v_VARYINGNAME_UV vMainUV4 +#elif _DEFINENAME_DIRECTUV==5 +#define v_VARYINGNAME_UV vMainUV5 +#elif _DEFINENAME_DIRECTUV==6 +#define v_VARYINGNAME_UV vMainUV6 +#else +varying v_VARYINGNAME_UV: vec2f; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5K]) { + ShaderStore.IncludesShadersStoreWGSL[name$5K] = shader$5J; +} + +// Do not edit. +const name$5J = "pbrFragmentSamplersDeclaration"; +const shader$5I = `#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) +#include(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) +var clearCoatRoughnessSamplerSampler: sampler;var clearCoatRoughnessSampler: texture_2d; +#endif +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) +var sheenRoughnessSamplerSampler: sampler;var sheenRoughnessSampler: texture_2d; +#endif +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +var reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube; +#ifdef LODBASEDMICROSFURACE +#else +var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube; +#endif +#ifdef USEIRRADIANCEMAP +var irradianceSamplerSampler: sampler;var irradianceSampler: texture_cube; +#endif +#else +var reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d; +#ifdef LODBASEDMICROSFURACE +#else +var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d; +#endif +#ifdef USEIRRADIANCEMAP +var irradianceSamplerSampler: sampler;var irradianceSampler: texture_2d; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vPositionUVW: vec3f; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vDirectionW: vec3f; +#endif +#endif +#endif +#ifdef ENVIRONMENTBRDF +var environmentBrdfSamplerSampler: sampler;var environmentBrdfSampler: texture_2d; +#endif +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +var areaLightsLTC1SamplerSampler: sampler;var areaLightsLTC1Sampler: texture_2d;var areaLightsLTC2SamplerSampler: sampler;var areaLightsLTC2Sampler: texture_2d; +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +#ifdef SS_REFRACTIONMAP_3D +var refractionSamplerSampler: sampler;var refractionSampler: texture_cube; +#ifdef LODBASEDMICROSFURACE +#else +var refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_cube;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_cube; +#endif +#else +var refractionSamplerSampler: sampler;var refractionSampler: texture_2d; +#ifdef LODBASEDMICROSFURACE +#else +var refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_2d;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_2d; +#endif +#endif +#endif +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor) +#endif +#ifdef IBL_CDF_FILTERING +var icdfSamplerSampler: sampler;var icdfSampler: texture_2d; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5J]) { + ShaderStore.IncludesShadersStoreWGSL[name$5J] = shader$5I; +} + +// Do not edit. +const name$5I = "subSurfaceScatteringFunctions"; +const shader$5H = `fn testLightingForSSS(diffusionProfile: f32)->bool +{return diffusionProfile<1.;}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5I]) { + ShaderStore.IncludesShadersStoreWGSL[name$5I] = shader$5H; +} + +// Do not edit. +const name$5H = "importanceSampling"; +const shader$5G = `fn hemisphereCosSample(u: vec2f)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=1.-u.y;var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +fn hemisphereImportanceSampleDggx(u: vec2f,a: f32)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +fn hemisphereImportanceSampleDCharlie(u: vec2f,a: f32)->vec3f { +var phi: f32=2.*PI*u.x;var sinTheta: f32=pow(u.y,a/(2.*a+1.));var cosTheta: f32=sqrt(1.-sinTheta*sinTheta);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5H]) { + ShaderStore.IncludesShadersStoreWGSL[name$5H] = shader$5G; +} + +// Do not edit. +const name$5G = "pbrHelperFunctions"; +const shader$5F = `#define MINIMUMVARIANCE 0.0005 +fn convertRoughnessToAverageSlope(roughness: f32)->f32 +{return roughness*roughness+MINIMUMVARIANCE;} +fn fresnelGrazingReflectance(reflectance0: f32)->f32 {var reflectance90: f32=saturate(reflectance0*25.0);return reflectance90;} +fn getAARoughnessFactors(normalVector: vec3f)->vec2f { +#ifdef SPECULARAA +var nDfdx: vec3f=dpdx(normalVector.xyz);var nDfdy: vec3f=dpdy(normalVector.xyz);var slopeSquare: f32=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));var geometricRoughnessFactor: f32=pow(saturate(slopeSquare),0.333);var geometricAlphaGFactor: f32=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2f(geometricRoughnessFactor,geometricAlphaGFactor); +#else +return vec2f(0.); +#endif +} +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_LEGACY +fn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2f(alphaT,alphaB);} +fn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var anisotropicFrameDirection: vec3f=select(T,B,anisotropy>=0.0);var anisotropicFrameTangent: vec3f=cross(normalize(anisotropicFrameDirection),V);var anisotropicFrameNormal: vec3f=cross(anisotropicFrameTangent,anisotropicFrameDirection);var anisotropicNormal: vec3f=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} +#else +fn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG,MINIMUMVARIANCE);return vec2f(alphaT,alphaB);} +fn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var bentNormal: vec3f=cross(B,V);bentNormal=normalize(cross(bentNormal,B));var sq=1.0-anisotropy*(1.0-roughness);var a: f32=sq*sq*sq*sq;bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} +#endif +#endif +#if defined(CLEARCOAT) || defined(SS_REFRACTION) +fn cocaLambertVec3(alpha: vec3f,distance: f32)->vec3f {return exp(-alpha*distance);} +fn cocaLambert(NdotVRefract: f32,NdotLRefract: f32,alpha: vec3f,thickness: f32)->vec3f {return cocaLambertVec3(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} +fn computeColorAtDistanceInMedia(color: vec3f,distance: f32)->vec3f {return -log(color)/distance;} +fn computeClearCoatAbsorption(NdotVRefract: f32,NdotLRefract: f32,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var clearCoatAbsorption: vec3f=mix( vec3f(1.0), +cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), +clearCoatIntensity);return clearCoatAbsorption;} +#endif +#ifdef MICROSURFACEAUTOMATIC +fn computeDefaultMicroSurface(microSurface: f32,reflectivityColor: vec3f)->f32 +{const kReflectivityNoAlphaWorkflow_SmoothnessMax: f32=0.95;var reflectivityLuminance: f32=getLuminance(reflectivityColor);var reflectivityLuma: f32=sqrt(reflectivityLuminance);var resultMicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return resultMicroSurface;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5G]) { + ShaderStore.IncludesShadersStoreWGSL[name$5G] = shader$5F; +} + +// Do not edit. +const name$5F = "pbrDirectLightingSetupFunctions"; +const shader$5E = `struct preLightingInfo +{lightOffset: vec3f, +lightDistanceSquared: f32, +lightDistance: f32, +attenuation: f32, +L: vec3f, +H: vec3f, +NdotV: f32, +NdotLUnclamped: f32, +NdotL: f32, +VdotH: f32, +roughness: f32, +#ifdef IRIDESCENCE +iridescenceIntensity: f32 +#endif +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +areaLightDiffuse: vec3f, +#ifdef SPECULARTERM +areaLightSpecular: vec3f, +areaLightFresnel: vec4f +#endif +#endif +};fn computePointAndSpotPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f,posW: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +fn computeDirectionalPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +fn computeHemisphericPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; +#ifdef SPECULARTERM +result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); +#endif +return result;} +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +#include +fn computeAreaPreLightingInfo(ltc1: texture_2d,ltc1Sampler:sampler,ltc2:texture_2d,ltc2Sampler:sampler,viewDirectionW: vec3f,vNormal:vec3f,vPosition:vec3f,lightCenter:vec3f,halfWidth:vec3f, halfHeight:vec3f,roughness:f32)->preLightingInfo {var result: preLightingInfo;var data: areaLightData=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc1Sampler,ltc2,ltc2Sampler,viewDirectionW,vNormal,vPosition,lightCenter,halfWidth,halfHeight,roughness); +#ifdef SPECULARTERM +result.areaLightFresnel=data.Fresnel;result.areaLightSpecular=data.Specular; +#endif +result.areaLightDiffuse+=data.Diffuse;return result;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5F]) { + ShaderStore.IncludesShadersStoreWGSL[name$5F] = shader$5E; +} + +// Do not edit. +const name$5E = "pbrDirectLightingFalloffFunctions"; +const shader$5D = `fn computeDistanceLightFalloff_Standard(lightOffset: vec3f,range: f32)->f32 +{return max(0.,1.0-length(lightOffset)/range);} +fn computeDistanceLightFalloff_Physical(lightDistanceSquared: f32)->f32 +{return 1.0/maxEps(lightDistanceSquared);} +fn computeDistanceLightFalloff_GLTF(lightDistanceSquared: f32,inverseSquaredRange: f32)->f32 +{var lightDistanceFalloff: f32=1.0/maxEps(lightDistanceSquared);var factor: f32=lightDistanceSquared*inverseSquaredRange;var attenuation: f32=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} +fn computeDirectionalLightFalloff_IES(lightDirection: vec3f,directionToLightCenterW: vec3f,iesLightTexture: texture_2d,iesLightTextureSampler: sampler)->f32 +{var cosAngle: f32=dot(-lightDirection,directionToLightCenterW);var angle=acos(cosAngle)/PI;return textureSampleLevel(iesLightTexture,iesLightTextureSampler,vec2f(angle,0),0.).r;} +fn computeDistanceLightFalloff(lightOffset: vec3f,lightDistanceSquared: f32,range: f32,inverseSquaredRange: f32)->f32 +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDistanceLightFalloff_Physical(lightDistanceSquared); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); +#else +return computeDistanceLightFalloff_Standard(lightOffset,range); +#endif +} +fn computeDirectionalLightFalloff_Standard(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32)->f32 +{var falloff: f32=0.0;var cosAngle: f32=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) +{falloff=max(0.,pow(cosAngle,exponent));} +return falloff;} +fn computeDirectionalLightFalloff_Physical(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32)->f32 +{const kMinusLog2ConeAngleIntensityRatio: f32=6.64385618977; +var concentrationKappa: f32=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);var lightDirectionSpreadSG: vec4f= vec4f(-lightDirection*concentrationKappa,-concentrationKappa);var falloff: f32=exp2(dot( vec4f(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} +fn computeDirectionalLightFalloff_GLTF(lightDirection: vec3f,directionToLightCenterW: vec3f,lightAngleScale: f32,lightAngleOffset: f32)->f32 +{var cd: f32=dot(-lightDirection,directionToLightCenterW);var falloff: f32=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} +fn computeDirectionalLightFalloff(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32,lightAngleScale: f32,lightAngleOffset: f32)->f32 +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); +#else +return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); +#endif +}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5E]) { + ShaderStore.IncludesShadersStoreWGSL[name$5E] = shader$5D; +} + +// Do not edit. +const name$5D = "pbrBRDFFunctions"; +const shader$5C = `#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +#ifdef MS_BRDF_ENERGY_CONSERVATION +fn getEnergyConservationFactor(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} +#endif +#ifdef ENVIRONMENTBRDF +fn getBRDFLookup(NdotV: f32,perceptualRoughness: f32)->vec3f {var UV: vec2f= vec2f(NdotV,perceptualRoughness);var brdfLookup: vec4f= textureSample(environmentBrdfSampler,environmentBrdfSamplerSampler,UV); +#ifdef ENVIRONMENTBRDF_RGBD +brdfLookup=vec4f(fromRGBD(brdfLookup.rgba),brdfLookup.a); +#endif +return brdfLookup.rgb;} +fn getReflectanceFromBRDFWithEnvLookup(specularEnvironmentR0: vec3f,specularEnvironmentR90: vec3f,environmentBrdf: vec3f)->vec3f { +#ifdef BRDF_V_HEIGHT_CORRELATED +var reflectance: vec3f=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; +#else +var reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; +#endif +return reflectance;} +fn getReflectanceFromBRDFLookup(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f { +#ifdef BRDF_V_HEIGHT_CORRELATED +var reflectance: vec3f=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); +#else +var reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; +#endif +return reflectance;} +#endif +/* NOT USED +#if defined(SHEEN) && defined(SHEEN_SOFTER) +fn getBRDFLookupCharlieSheen(NdotV: f32,perceptualRoughness: f32)->f32 +{var c: f32=1.0-NdotV;var c3: f32=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} +#endif +*/ +#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) +fn getReflectanceFromAnalyticalBRDFLookup_Jones(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f +{var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +/** +* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. +* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table +*/ +fn getSheenReflectanceFromBRDFLookup(reflectance0: vec3f,environmentBrdf: vec3f)->vec3f {var sheenEnvironmentReflectance: vec3f=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} +#endif +fn fresnelSchlickGGXVec3(VdotH: f32,reflectance0: vec3f,reflectance90: vec3f)->vec3f +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +fn fresnelSchlickGGX(VdotH: f32,reflectance0: f32,reflectance90: f32)->f32 +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +#ifdef CLEARCOAT +fn getR0RemappedForClearCoat(f0: vec3f)->vec3f { +#ifdef CLEARCOAT_DEFAULTIOR +#ifdef MOBILE +return saturateVec3(f0*(f0*0.526868+0.529324)-0.0482256); +#else +return saturateVec3(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); +#endif +#else +var s: vec3f=sqrt(f0);var t: vec3f=(uniforms.vClearCoatRefractionParams.z+uniforms.vClearCoatRefractionParams.w*s)/(uniforms.vClearCoatRefractionParams.w+uniforms.vClearCoatRefractionParams.z*s);return squareVec3(t); +#endif +} +#endif +#ifdef IRIDESCENCE +const XYZ_TO_REC709: mat3x3f= mat3x3f( +3.2404542,-0.9692660, 0.0556434, +-1.5371385, 1.8760108,-0.2040259, +-0.4985314, 0.0415560, 1.0572252 +);fn getIORTfromAirToSurfaceR0(f0: vec3f)->vec3f {var sqrtF0: vec3f=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} +fn getR0fromIORsVec3(iorT: vec3f,iorI: f32)->vec3f {return squareVec3((iorT- vec3f(iorI))/(iorT+ vec3f(iorI)));} +fn getR0fromIORs(iorT: f32,iorI: f32)->f32 {return square((iorT-iorI)/(iorT+iorI));} +fn evalSensitivity(opd: f32,shift: vec3f)->vec3f {var phase: f32=2.0*PI*opd*1.0e-9;const val: vec3f= vec3f(5.4856e-13,4.4201e-13,5.2481e-13);const pos: vec3f= vec3f(1.6810e+06,1.7953e+06,2.2084e+06);const vr: vec3f= vec3f(4.3278e+09,9.3046e+09,6.6121e+09);var xyz: vec3f=val*sqrt(2.0*PI*vr)*cos(pos*phase+shift)*exp(-square(phase)*vr);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;var srgb: vec3f=XYZ_TO_REC709*xyz;return srgb;} +fn evalIridescence(outsideIOR: f32,eta2: f32,cosTheta1: f32,thinFilmThickness: f32,baseF0: vec3f)->vec3f {var I: vec3f= vec3f(1.0);var iridescenceIOR: f32=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));var sinTheta2Sq: f32=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));var cosTheta2Sq: f32=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} +var cosTheta2: f32=sqrt(cosTheta2Sq);var R0: f32=getR0fromIORs(iridescenceIOR,outsideIOR);var R12: f32=fresnelSchlickGGX(cosTheta1,R0,1.);var R21: f32=R12;var T121: f32=1.0-R12;var phi12: f32=0.0;if (iridescenceIORf32 +{var a2: f32=alphaG*alphaG;var d: f32=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);} +#ifdef SHEEN +fn normalDistributionFunction_CharlieSheen(NdotH: f32,alphaG: f32)->f32 +{var invR: f32=1./alphaG;var cos2h: f32=NdotH*NdotH;var sin2h: f32=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);} +#endif +#ifdef ANISOTROPIC +fn normalDistributionFunction_BurleyGGX_Anisotropic(NdotH: f32,TdotH: f32,BdotH: f32,alphaTB: vec2f)->f32 {var a2: f32=alphaTB.x*alphaTB.y;var v: vec3f= vec3f(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);var v2: f32=dot(v,v);var w2: f32=a2/v2;return a2*w2*w2*RECIPROCAL_PI;} +#endif +#ifdef BRDF_V_HEIGHT_CORRELATED +fn smithVisibility_GGXCorrelated(NdotL: f32,NdotV: f32,alphaG: f32)->f32 { +#ifdef MOBILE +var GGXV: f32=NdotL*(NdotV*(1.0-alphaG)+alphaG);var GGXL: f32=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL); +#else +var a2: f32=alphaG*alphaG;var GGXV: f32=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);var GGXL: f32=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL); +#endif +} +#else +fn smithVisibilityG1_TrowbridgeReitzGGXFast(dot: f32,alphaG: f32)->f32 +{ +#ifdef MOBILE +return 1.0/(dot+alphaG+(1.0-alphaG)*dot )); +#else +var alphaSquared: f32=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot)); +#endif +} +fn smithVisibility_TrowbridgeReitzGGXFast(NdotL: f32,NdotV: f32,alphaG: f32)->f32 +{var visibility: f32=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;} +#endif +#ifdef ANISOTROPIC +fn smithVisibility_GGXCorrelated_Anisotropic(NdotL: f32,NdotV: f32,TdotV: f32,BdotV: f32,TdotL: f32,BdotL: f32,alphaTB: vec2f)->f32 {var lambdaV: f32=NdotL*length( vec3f(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));var lambdaL: f32=NdotV*length( vec3f(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));var v: f32=0.5/(lambdaV+lambdaL);return v;} +#endif +#ifdef CLEARCOAT +fn visibility_Kelemen(VdotH: f32)->f32 {return 0.25/(VdotH*VdotH); } +#endif +#ifdef SHEEN +fn visibility_Ashikhmin(NdotL: f32,NdotV: f32)->f32 +{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));} +/* NOT USED +#ifdef SHEEN_SOFTER +fn l(x: f32,alphaG: f32)->f32 +{var oneMinusAlphaSq: f32=(1.0-alphaG)*(1.0-alphaG);var a: f32=mix(21.5473,25.3245,oneMinusAlphaSq);var b: f32=mix(3.82987,3.32435,oneMinusAlphaSq);var c: f32=mix(0.19823,0.16801,oneMinusAlphaSq);var d: f32=mix(-1.97760,-1.27393,oneMinusAlphaSq);var e: f32=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;} +fn lambdaSheen(cosTheta: f32,alphaG: f32)->f32 +{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));} +fn visibility_CharlieSheen(NdotL: f32,NdotV: f32,alphaG: f32)->f32 +{var G: f32=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);} +#endif +*/ +#endif +fn diffuseBRDF_Burley(NdotL: f32,NdotV: f32,VdotH: f32,roughness: f32)->f32 {var diffuseFresnelNV: f32=pow5(saturateEps(1.0-NdotL));var diffuseFresnelNL: f32=pow5(saturateEps(1.0-NdotV));var diffuseFresnel90: f32=0.5+2.0*VdotH*VdotH*roughness;var fresnel: f32 = +(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) * +(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;} +#ifdef SS_TRANSLUCENCY +fn transmittanceBRDF_Burley(tintColor: vec3f,diffusionDistance: vec3f,thickness: f32)->vec3f {var S: vec3f=1./maxEpsVec3(diffusionDistance);var temp: vec3f=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);} +fn computeWrappedDiffuseNdotL(NdotL: f32,w: f32)->f32 {var t: f32=1.0+w;var invt2: f32=1.0/(t*t);return saturate((NdotL+w)*invt2);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5D]) { + ShaderStore.IncludesShadersStoreWGSL[name$5D] = shader$5C; +} + +// Do not edit. +const name$5C = "hdrFilteringFunctions"; +const shader$5B = `#ifdef NUM_SAMPLES +#if NUM_SAMPLES>0 +fn radicalInverse_VdC(value: u32)->f32 +{var bits=(value<<16u) | (value>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return f32(bits)*2.3283064365386963e-10; } +fn hammersley(i: u32,N: u32)->vec2f +{return vec2f( f32(i)/ f32(N),radicalInverse_VdC(i));} +fn log4(x: f32)->f32 {return log2(x)/2.;} +fn uv_to_normal(uv: vec2f)->vec3f {var N: vec3f;var uvRange: vec2f=uv;var theta: f32=uvRange.x*2.0*PI;var phi: f32=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;} +const NUM_SAMPLES_FLOAT: f32= f32(NUM_SAMPLES);const NUM_SAMPLES_FLOAT_INVERSED: f32=1./NUM_SAMPLES_FLOAT;const K: f32=4.;fn irradiance(inputTexture: texture_cube,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f +#ifdef IBL_CDF_FILTERING +,icdfSampler: texture_2d,icdfSamplerSampler: sampler +#endif +)->vec3f +{var n: vec3f=normalize(inputN);var result: vec3f= vec3f(0.0); +#ifndef IBL_CDF_FILTERING +var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n); +#endif +var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);for(var i: u32=0u; i0.) { +#ifdef IBL_CDF_FILTERING +var pdf: f32=textureSampleLevel(icdfSampler,icdfSamplerSampler,T,0.0).z;var c: vec3f=textureSampleLevel(inputTexture,inputSampler,Ls,0.0).rgb; +#else +var pdf_inversed: f32=PI/NoL;var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp(l,0.0,maxLevel);var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*Ls,mipLevel).rgb; +#endif +#ifdef GAMMA_INPUT +c=toLinearSpaceVec3(c); +#endif +#ifdef IBL_CDF_FILTERING +var light: vec3f=vec3f(0.0);if (pdf>1e-6) {light=vec3f(1.0)/vec3f(pdf)*c;} +result+=NoL*light; +#else +result+=c; +#endif +}} +result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} +fn radiance(alphaG: f32,inputTexture: texture_cube,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f)->vec3f +{var n: vec3f=normalize(inputN);var c: vec3f=textureSample(inputTexture,inputSampler,n).rgb; +if (alphaG==0.) { +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +return c;} else {var result: vec3f= vec3f(0.);var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);var weight: f32=0.;for(var i: u32=0u; i0.) {var pdf_inversed: f32=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp( f32(l),0.0,maxLevel);weight+=NoL;var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*L,mipLevel).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +result+=c*NoL;}} +result=result/weight;return result;}} +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5C]) { + ShaderStore.IncludesShadersStoreWGSL[name$5C] = shader$5B; +} + +// Do not edit. +const name$5B = "pbrDirectLightingFunctions"; +const shader$5A = `#define CLEARCOATREFLECTANCE90 1.0 +struct lightingInfo +{diffuse: vec3f, +#ifdef SPECULARTERM +specular: vec3f, +#endif +#ifdef CLEARCOAT +clearCoat: vec4f, +#endif +#ifdef SHEEN +sheen: vec3f +#endif +};fn adjustRoughnessFromLightProperties(roughness: f32,lightRadius: f32,lightDistance: f32)->f32 { +#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) +var lightRoughness: f32=lightRadius/lightDistance;var totalRoughness: f32=saturate(lightRoughness+roughness);return totalRoughness; +#else +return roughness; +#endif +} +fn computeHemisphericDiffuseLighting(info: preLightingInfo,lightColor: vec3f,groundColor: vec3f)->vec3f {return mix(groundColor,lightColor,info.NdotL);} +fn computeDiffuseLighting(info: preLightingInfo,lightColor: vec3f)->vec3f {var diffuseTerm: f32=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} +fn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f{var strq: vec4f=textureProjectionMatrix* vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return toLinearSpaceVec3(textureColor);} +#ifdef SS_TRANSLUCENCY +fn computeDiffuseAndTransmittedLighting(info: preLightingInfo,lightColor: vec3f,transmittance: vec3f,transmittanceIntensity: f32,surfaceAlbedo: vec3f)->vec3f {var transmittanceNdotL=vec3f(0.0);var NdotL: f32=absEps(info.NdotLUnclamped);if (info.NdotLUnclamped<0.0) {var wrapNdotL: f32=computeWrappedDiffuseNdotL(NdotL,0.02);var trAdapt: f32=step(0.,info.NdotLUnclamped);transmittanceNdotL=mix(transmittance*wrapNdotL, vec3f(wrapNdotL),trAdapt);} +var diffuseTerm: f32=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return (transmittanceNdotL/PI+(1.0-transmittanceIntensity)*diffuseTerm*surfaceAlbedo*info.NdotL)*info.attenuation*lightColor;} +#endif +#ifdef SPECULARTERM +fn computeSpecularLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +var distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); +#ifdef BRDF_V_HEIGHT_CORRELATED +var smithVisibility: f32=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); +#else +var smithVisibility: f32=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); +#endif +var specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef ANISOTROPIC +fn computeAnisotropicSpecularLighting(info: preLightingInfo,V: vec3f,N: vec3f,T: vec3f,B: vec3f,anisotropy: f32,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var TdotH: f32=dot(T,info.H);var BdotH: f32=dot(B,info.H);var TdotV: f32=dot(T,V);var BdotV: f32=dot(B,V);var TdotL: f32=dot(T,info.L);var BdotL: f32=dot(B,info.L);var alphaG: f32=convertRoughnessToAverageSlope(info.roughness);var alphaTB: vec2f=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,vec2f(geometricRoughnessFactor*geometricRoughnessFactor));var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +var distribution: f32=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);var smithVisibility: f32=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);var specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef CLEARCOAT +fn computeClearCoatLighting(info: preLightingInfo,Ncc: vec3f,geometricRoughnessFactor: f32,clearCoatIntensity: f32,lightColor: vec3f)->vec4f {var NccdotL: f32=saturateEps(dot(Ncc,info.L));var NccdotH: f32=saturateEps(dot(Ncc,info.H));var clearCoatRoughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness);var fresnel: f32=fresnelSchlickGGX(info.VdotH,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;var distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);var kelemenVisibility: f32=visibility_Kelemen(info.VdotH);var clearCoatTerm: f32=fresnel*distribution*kelemenVisibility;return vec4f( +clearCoatTerm*info.attenuation*NccdotL*lightColor, +1.0-fresnel +);} +fn computeClearCoatLightingAbsorption(NdotVRefract: f32,L: vec3f,Ncc: vec3f,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var LRefract: vec3f=-refract(L,Ncc,uniforms.vClearCoatRefractionParams.y);var NdotLRefract: f32=saturateEps(dot(Ncc,LRefract));var absorption: vec3f=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} +#endif +#ifdef SHEEN +fn computeSheenLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: f32=1.;var distribution: f32=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER +var visibility: f32=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); +#else */ +var visibility: f32=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ +var sheenTerm: f32=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +fn computeAreaDiffuseLighting(info: preLightingInfo,lightColor: vec3f)->vec3f {return info.areaLightDiffuse*lightColor;} +fn computeAreaSpecularLighting(info: preLightingInfo,specularColor: vec3f)->vec3f {var fresnel:vec3f =( specularColor*info.areaLightFresnel.x+( vec3f( 1.0 )-specularColor )*info.areaLightFresnel.y );return specularColor*fresnel*info.areaLightSpecular;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5B]) { + ShaderStore.IncludesShadersStoreWGSL[name$5B] = shader$5A; +} + +// Do not edit. +const name$5A = "pbrIBLFunctions"; +const shader$5z = `#if defined(REFLECTION) || defined(SS_REFRACTION) +fn getLodFromAlphaG(cubeMapDimensionPixels: f32,microsurfaceAverageSlope: f32)->f32 {var microsurfaceAverageSlopeTexels: f32=cubeMapDimensionPixels*microsurfaceAverageSlope;var lod: f32=log2(microsurfaceAverageSlopeTexels);return lod;} +fn getLinearLodFromRoughness(cubeMapDimensionPixels: f32,roughness: f32)->f32 {var lod: f32=log2(cubeMapDimensionPixels)*roughness;return lod;} +#endif +#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) +fn environmentRadianceOcclusion(ambientOcclusion: f32,NdotVUnclamped: f32)->f32 {var temp: f32=NdotVUnclamped+ambientOcclusion;return saturate(temp*temp-1.0+ambientOcclusion);} +#endif +#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) +fn environmentHorizonOcclusion(view: vec3f,normal: vec3f,geometricNormal: vec3f)->f32 {var reflection: vec3f=reflect(view,normal);var temp: f32=saturate(1.0+1.1*dot(reflection,geometricNormal));return temp*temp;} +#endif +#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) +fn UNPACK_LOD(x: f32)->f32 {return (1.0-x)*255.0;} +fn getLodFromAlphaGNdotV(cubeMapDimensionPixels: f32,alphaG: f32,NdotV: f32)->f32 {var microsurfaceAverageSlope: f32=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5A]) { + ShaderStore.IncludesShadersStoreWGSL[name$5A] = shader$5z; +} + +// Do not edit. +const name$5z = "bumpFragmentMainFunctions"; +const shader$5y = `#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) +#if defined(TANGENT) && defined(NORMAL) +varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f; +#endif +#ifdef OBJECTSPACE_NORMALMAP +uniform normalMatrix: mat4x4f;fn toNormalMatrix(m: mat4x4f)->mat4x4f +{var a00=m[0][0];var a01=m[0][1];var a02=m[0][2];var a03=m[0][3];var a10=m[1][0];var a11=m[1][1];var a12=m[1][2];var a13=m[1][3];var a20=m[2][0]; +var a21=m[2][1];var a22=m[2][2];var a23=m[2][3];var a30=m[3][0]; +var a31=m[3][1];var a32=m[3][2];var a33=m[3][3];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi=mat4x4( +(a11*b11-a12*b10+a13*b09)/det, +(a02*b10-a01*b11-a03*b09)/det, +(a31*b05-a32*b04+a33*b03)/det, +(a22*b04-a21*b05-a23*b03)/det, +(a12*b08-a10*b11-a13*b07)/det, +(a00*b11-a02*b08+a03*b07)/det, +(a32*b02-a30*b05-a33*b01)/det, +(a20*b05-a22*b02+a23*b01)/det, +(a10*b10-a11*b08+a13*b06)/det, +(a01*b08-a00*b10-a03*b06)/det, +(a30*b04-a31*b02+a33*b00)/det, +(a21*b02-a20*b04-a23*b00)/det, +(a11*b07-a10*b09-a12*b06)/det, +(a00*b09-a01*b07+a02*b06)/det, +(a31*b01-a30*b03-a32*b00)/det, +(a20*b03-a21*b01+a22*b00)/det);return mat4x4(mi[0][0],mi[1][0],mi[2][0],mi[3][0], +mi[0][1],mi[1][1],mi[2][1],mi[3][1], +mi[0][2],mi[1][2],mi[2][2],mi[3][2], +mi[0][3],mi[1][3],mi[2][3],mi[3][3]);} +#endif +fn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f +{var output=normal; +#ifdef NORMALXYSCALE +output=normalize(output* vec3f(scale,scale,1.0)); +#endif +return normalize(cotangentFrame*output);} +fn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f +{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);} +fn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f +{var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5z]) { + ShaderStore.IncludesShadersStoreWGSL[name$5z] = shader$5y; +} +/** @internal */ +const bumpFragmentMainFunctionsWGSL = { name: name$5z, shader: shader$5y }; + +const bumpFragmentMainFunctions$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bumpFragmentMainFunctionsWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$5y = "bumpFragmentFunctions"; +const shader$5x = `#if defined(BUMP) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) +#endif +#if defined(DETAIL) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) +#endif +#if defined(BUMP) && defined(PARALLAX) +const minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; icurrRayHeight) +{var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} +else +{currRayHeight-=stepSize;vLastOffset=vCurrOffset; +#ifdef PARALLAX_RHS +vCurrOffset-=stepSize*vMaxOffset; +#else +vCurrOffset+=stepSize*vMaxOffset; +#endif +lastSampledHeight=currSampledHeight;}} +return vCurrOffset;} +fn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f +{var height: f32=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height; +#ifdef PARALLAX_RHS +return texCoordOffset; +#else +return -texCoordOffset; +#endif +} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5y]) { + ShaderStore.IncludesShadersStoreWGSL[name$5y] = shader$5x; +} +/** @internal */ +const bumpFragmentFunctionsWGSL = { name: name$5y, shader: shader$5x }; + +const bumpFragmentFunctions$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bumpFragmentFunctionsWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$5x = "pbrBlockAlbedoOpacity"; +const shader$5w = `struct albedoOpacityOutParams +{surfaceAlbedo: vec3f, +alpha: f32}; +#define pbr_inline +fn albedoOpacityBlock( +vAlbedoColor: vec4f +#ifdef ALBEDO +,albedoTexture: vec4f +,albedoInfos: vec2f +#endif +,baseWeight: f32 +#ifdef BASEWEIGHT +,baseWeightTexture: vec4f +,vBaseWeightInfos: vec2f +#endif +#ifdef OPACITY +,opacityMap: vec4f +,vOpacityInfos: vec2f +#endif +#ifdef DETAIL +,detailColor: vec4f +,vDetailInfos: vec4f +#endif +#ifdef DECAL +,decalColor: vec4f +,vDecalInfos: vec4f +#endif +)->albedoOpacityOutParams +{var outParams: albedoOpacityOutParams;var surfaceAlbedo: vec3f=vAlbedoColor.rgb;var alpha: f32=vAlbedoColor.a; +#ifdef ALBEDO +#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) +alpha*=albedoTexture.a; +#endif +#ifdef GAMMAALBEDO +surfaceAlbedo*=toLinearSpaceVec3(albedoTexture.rgb); +#else +surfaceAlbedo*=albedoTexture.rgb; +#endif +surfaceAlbedo*=albedoInfos.y; +#endif +#ifndef DECAL_AFTER_DETAIL +#include +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +surfaceAlbedo*=fragmentInputs.vColor.rgb; +#endif +#ifdef DETAIL +var detailAlbedo: f32=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; +#endif +#ifdef DECAL_AFTER_DETAIL +#include +#endif +#define CUSTOM_FRAGMENT_UPDATE_ALBEDO +surfaceAlbedo*=baseWeight; +#ifdef BASEWEIGHT +surfaceAlbedo*=baseWeightTexture.r; +#endif +#ifdef OPACITY +#ifdef OPACITYRGB +alpha=getLuminance(opacityMap.rgb); +#else +alpha*=opacityMap.a; +#endif +alpha*=vOpacityInfos.y; +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=fragmentInputs.vColor.a; +#endif +#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) +#ifdef ALPHATEST +#if DEBUGMODE != 88 +if (alpha0 +#ifdef METALLICWORKFLOW +metallicRoughness: vec2f, +#ifdef REFLECTIVITY +surfaceMetallicColorMap: vec4f, +#endif +#ifndef FROSTBITE_REFLECTANCE +metallicF0: vec3f, +#endif +#else +#ifdef REFLECTIVITY +surfaceReflectivityColorMap: vec4f, +#endif +#endif +#endif +}; +#define pbr_inline +fn reflectivityBlock( +vReflectivityColor: vec4f +#ifdef METALLICWORKFLOW +,surfaceAlbedo: vec3f +,metallicReflectanceFactors: vec4f +#endif +#ifdef REFLECTIVITY +,reflectivityInfos: vec3f +,surfaceMetallicOrReflectivityColorMap: vec4f +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +,ambientOcclusionColorIn: vec3f +#endif +#ifdef MICROSURFACEMAP +,microSurfaceTexel: vec4f +#endif +#ifdef DETAIL +,detailColor: vec4f +,vDetailInfos: vec4f +#endif +)->reflectivityOutParams +{var outParams: reflectivityOutParams;var microSurface: f32=vReflectivityColor.a;var surfaceReflectivityColor: vec3f=vReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +var metallicRoughness: vec2f=surfaceReflectivityColor.rg; +#ifdef REFLECTIVITY +#if DEBUGMODE>0 +outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef AOSTOREINMETALMAPRED +var aoStoreInMetalMap: vec3f= vec3f(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); +#endif +#ifdef METALLNESSSTOREINMETALMAPBLUE +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; +#else +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; +#endif +#ifdef ROUGHNESSSTOREINMETALMAPALPHA +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; +#else +#ifdef ROUGHNESSSTOREINMETALMAPGREEN +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; +#endif +#endif +#endif +#ifdef DETAIL +var detailRoughness: f32=mix(0.5,detailColor.b,vDetailInfos.w);var loLerp: f32=mix(0.,metallicRoughness.g,detailRoughness*2.);var hiLerp: f32=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); +#endif +#ifdef MICROSURFACEMAP +metallicRoughness.g*=microSurfaceTexel.r; +#endif +#if DEBUGMODE>0 +outParams.metallicRoughness=metallicRoughness; +#endif +#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS +microSurface=1.0-metallicRoughness.g;var baseColor: vec3f=surfaceAlbedo; +#ifdef FROSTBITE_REFLECTANCE +outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); +#else +var metallicF0: vec3f=metallicReflectanceFactors.rgb; +#if DEBUGMODE>0 +outParams.metallicF0=metallicF0; +#endif +outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0), vec3f(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); +#endif +#else +#ifdef REFLECTIVITY +surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; +#if DEBUGMODE>0 +outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef MICROSURFACEFROMREFLECTIVITYMAP +microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; +#else +#ifdef MICROSURFACEAUTOMATIC +microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); +#endif +#ifdef MICROSURFACEMAP +microSurface*=microSurfaceTexel.r; +#endif +#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE +#endif +#endif +#endif +microSurface=saturate(microSurface);var roughness: f32=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;return outParams;} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5w]) { + ShaderStore.IncludesShadersStoreWGSL[name$5w] = shader$5v; +} + +// Do not edit. +const name$5v = "pbrBlockAmbientOcclusion"; +const shader$5u = `struct ambientOcclusionOutParams +{ambientOcclusionColor: vec3f, +#if DEBUGMODE>0 && defined(AMBIENT) +ambientOcclusionColorMap: vec3f +#endif +}; +#define pbr_inline +fn ambientOcclusionBlock( +#ifdef AMBIENT +ambientOcclusionColorMap_: vec3f, +vAmbientInfos: vec4f +#endif +)->ambientOcclusionOutParams +{ +var outParams: ambientOcclusionOutParams;var ambientOcclusionColor: vec3f= vec3f(1.,1.,1.); +#ifdef AMBIENT +var ambientOcclusionColorMap: vec3f=ambientOcclusionColorMap_*vAmbientInfos.y; +#ifdef AMBIENTINGRAYSCALE +ambientOcclusionColorMap= vec3f(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); +#endif +ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); +#if DEBUGMODE>0 +outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; +#endif +#endif +outParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5v]) { + ShaderStore.IncludesShadersStoreWGSL[name$5v] = shader$5u; +} + +// Do not edit. +const name$5u = "pbrBlockAlphaFresnel"; +const shader$5t = `#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +struct alphaFresnelOutParams +{alpha: f32};fn faceforward(N: vec3,I: vec3,Nref: vec3)->vec3 {return select(N,-N,dot(Nref,I)>0.0);} +#define pbr_inline +fn alphaFresnelBlock( +normalW: vec3f, +viewDirectionW: vec3f, +alpha: f32, +microSurface: f32 +)->alphaFresnelOutParams +{var outParams: alphaFresnelOutParams;var opacityPerceptual: f32=alpha; +#ifdef LINEARALPHAFRESNEL +var opacity0: f32=opacityPerceptual; +#else +var opacity0: f32=opacityPerceptual*opacityPerceptual; +#endif +var opacity90: f32=fresnelGrazingReflectance(opacity0);var normalForward: vec3f=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)), vec3f(opacity0), vec3f(opacity90),sqrt(microSurface)).x; +#ifdef ALPHATEST +if (outParams.alpha0 && defined(ANISOTROPIC_TEXTURE) +anisotropyMapData: vec3f +#endif +}; +#define pbr_inline +fn anisotropicBlock( +vAnisotropy: vec3f, +roughness: f32, +#ifdef ANISOTROPIC_TEXTURE +anisotropyMapData: vec3f, +#endif +TBN: mat3x3f, +normalW: vec3f, +viewDirectionW: vec3f +)->anisotropicOutParams +{ +var outParams: anisotropicOutParams;var anisotropy: f32=vAnisotropy.b;var anisotropyDirection: vec3f= vec3f(vAnisotropy.xy,0.); +#ifdef ANISOTROPIC_TEXTURE +var amd=anisotropyMapData.rg;anisotropy*=anisotropyMapData.b; +#if DEBUGMODE>0 +outParams.anisotropyMapData=anisotropyMapData; +#endif +amd=amd*2.0-1.0; +#ifdef ANISOTROPIC_LEGACY +anisotropyDirection=vec3f(anisotropyDirection.xy*amd,anisotropyDirection.z); +#else +anisotropyDirection=vec3f(mat2x2f(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(amd),anisotropyDirection.z); +#endif +#endif +var anisoTBN: mat3x3f= mat3x3f(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));var anisotropicTangent: vec3f=normalize(anisoTBN*anisotropyDirection);var anisotropicBitangent: vec3f=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5t]) { + ShaderStore.IncludesShadersStoreWGSL[name$5t] = shader$5s; +} + +// Do not edit. +const name$5s = "pbrBlockReflection"; +const shader$5r = `#ifdef REFLECTION +struct reflectionOutParams +{environmentRadiance: vec4f +,environmentIrradiance: vec3f +#ifdef REFLECTIONMAP_3D +,reflectionCoords: vec3f +#else +,reflectionCoords: vec2f +#endif +#ifdef SS_TRANSLUCENCY +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +,irradianceVector: vec3f +#endif +#endif +#endif +}; +#define pbr_inline +#ifdef REFLECTIONMAP_3D +fn createReflectionCoords( +vPositionW: vec3f, +normalW: vec3f, +#ifdef ANISOTROPIC +anisotropicOut: anisotropicOutParams, +#endif +)->vec3f +{var reflectionCoords: vec3f; +#else +fn createReflectionCoords( +vPositionW: vec3f, +normalW: vec3f, +#ifdef ANISOTROPIC +anisotropicOut: anisotropicOutParams, +#endif +)->vec2f +{ +var reflectionCoords: vec2f; +#endif +#ifdef ANISOTROPIC +var reflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),anisotropicOut.anisotropicNormal); +#else +var reflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +reflectionCoords=reflectionVector; +#else +reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +return reflectionCoords;} +#define pbr_inline +fn sampleReflectionTexture( +alphaG: f32 +,vReflectionMicrosurfaceInfos: vec3f +,vReflectionInfos: vec2f +,vReflectionColor: vec3f +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +,NdotVUnclamped: f32 +#endif +#ifdef LINEARSPECULARREFLECTION +,roughness: f32 +#endif +#ifdef REFLECTIONMAP_3D +,reflectionSampler: texture_cube +,reflectionSamplerSampler: sampler +,reflectionCoords: vec3f +#else +,reflectionSampler: texture_2d +,reflectionSamplerSampler: sampler +,reflectionCoords: vec2f +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +,reflectionLowSampler: texture_cube +,reflectionLowSamplerSampler: sampler +,reflectionHighSampler: texture_cube +,reflectionHighSamplerSampler: sampler +#else +,reflectionLowSampler: texture_2d +,reflectionLowSamplerSampler: sampler +,reflectionHighSampler: texture_2d +,reflectionHighSamplerSampler: sampler +#endif +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo: vec2f +#endif +)->vec4f +{var environmentRadiance: vec4f; +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +var reflectionLOD: f32=getLodFromAlphaGNdotV(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); +#elif defined(LINEARSPECULARREFLECTION) +var reflectionLOD: f32=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); +#else +var reflectionLOD: f32=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); +#endif +#ifdef LODBASEDMICROSFURACE +reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; +#ifdef LODINREFLECTIONALPHA +var automaticReflectionLOD: f32=UNPACK_LOD(textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords).a);var requestedReflectionLOD: f32=max(automaticReflectionLOD,reflectionLOD); +#else +var requestedReflectionLOD: f32=reflectionLOD; +#endif +#ifdef REALTIME_FILTERING +environmentRadiance= vec4f(radiance(alphaG,reflectionSampler,reflectionSamplerSampler,reflectionCoords,vReflectionFilteringInfo),1.0); +#else +environmentRadiance=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD); +#endif +#else +var lodReflectionNormalized: f32=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));var lodReflectionNormalizedDoubled: f32=lodReflectionNormalized*2.0;var environmentMid: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( +textureSample(reflectionHighSampler,reflectionHighSamplerSampler,reflectionCoords), +environmentMid, +lodReflectionNormalizedDoubled +);} else {environmentRadiance=mix( +environmentMid, +textureSample(reflectionLowSampler,reflectionLowSamplerSampler,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +var envRadiance=environmentRadiance.rgb; +#ifdef RGBDREFLECTION +envRadiance=fromRGBD(environmentRadiance); +#endif +#ifdef GAMMAREFLECTION +envRadiance=toLinearSpaceVec3(environmentRadiance.rgb); +#endif +envRadiance*=vReflectionInfos.x;envRadiance*=vReflectionColor.rgb;return vec4f(envRadiance,environmentRadiance.a);} +#define pbr_inline +fn reflectionBlock( +vPositionW: vec3f +,normalW: vec3f +,alphaG: f32 +,vReflectionMicrosurfaceInfos: vec3f +,vReflectionInfos: vec2f +,vReflectionColor: vec3f +#ifdef ANISOTROPIC +,anisotropicOut: anisotropicOutParams +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +,NdotVUnclamped: f32 +#endif +#ifdef LINEARSPECULARREFLECTION +,roughness: f32 +#endif +#ifdef REFLECTIONMAP_3D +,reflectionSampler: texture_cube +,reflectionSamplerSampler: sampler +#else +,reflectionSampler: texture_2d +,reflectionSamplerSampler: sampler +#endif +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +,vEnvironmentIrradiance: vec3f +#endif +#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D)) +,reflectionMatrix: mat4x4f +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +,irradianceSampler: texture_cube +,irradianceSamplerSampler: sampler +#else +,irradianceSampler: texture_2d +,irradianceSamplerSampler: sampler +#endif +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +,reflectionLowSampler: texture_cube +,reflectionLowSamplerSampler: sampler +,reflectionHighSampler: texture_cube +,reflectionHighSamplerSampler: sampler +#else +,reflectionLowSampler: texture_2d +,reflectionLowSamplerSampler: sampler +,reflectionHighSampler: texture_2d +,reflectionHighSamplerSampler: sampler +#endif +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo: vec2f +#ifdef IBL_CDF_FILTERING +,icdfSampler: texture_2d +,icdfSamplerSampler: sampler +#endif +#endif +)->reflectionOutParams +{var outParams: reflectionOutParams;var environmentRadiance: vec4f= vec4f(0.,0.,0.,0.); +#ifdef REFLECTIONMAP_3D +var reflectionCoords: vec3f= vec3f(0.); +#else +var reflectionCoords: vec2f= vec2f(0.); +#endif +reflectionCoords=createReflectionCoords( +vPositionW, +normalW, +#ifdef ANISOTROPIC +anisotropicOut, +#endif +);environmentRadiance=sampleReflectionTexture( +alphaG +,vReflectionMicrosurfaceInfos +,vReflectionInfos +,vReflectionColor +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +,NdotVUnclamped +#endif +#ifdef LINEARSPECULARREFLECTION +,roughness +#endif +#ifdef REFLECTIONMAP_3D +,reflectionSampler +,reflectionSamplerSampler +,reflectionCoords +#else +,reflectionSampler +,reflectionSamplerSampler +,reflectionCoords +#endif +#ifndef LODBASEDMICROSFURACE +,reflectionLowSampler +,reflectionLowSamplerSampler +,reflectionHighSampler +,reflectionHighSamplerSampler +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo +#endif +);var environmentIrradiance: vec3f= vec3f(0.,0.,0.); +#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D)) +#ifdef ANISOTROPIC +var irradianceVector: vec3f= (reflectionMatrix* vec4f(anisotropicOut.anisotropicNormal,0)).xyz; +#else +var irradianceVector: vec3f= (reflectionMatrix* vec4f(normalW,0)).xyz; +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#endif +#ifdef USESPHERICALFROMREFLECTIONMAP +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +environmentIrradiance=vEnvironmentIrradiance; +#else +#if defined(REALTIME_FILTERING) +environmentIrradiance=irradiance(reflectionSampler,reflectionSamplerSampler,irradianceVector,vReflectionFilteringInfo +#ifdef IBL_CDF_FILTERING +,icdfSampler +,icdfSamplerSampler +#endif +); +#else +environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); +#endif +#ifdef SS_TRANSLUCENCY +outParams.irradianceVector=irradianceVector; +#endif +#endif +#elif defined(USEIRRADIANCEMAP) +#ifdef REFLECTIONMAP_3D +var environmentIrradiance4: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,irradianceVector); +#else +var environmentIrradiance4: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,reflectionCoords); +#endif +environmentIrradiance=environmentIrradiance4.rgb; +#ifdef RGBDREFLECTION +environmentIrradiance=fromRGBD(environmentIrradiance4); +#endif +#ifdef GAMMAREFLECTION +environmentIrradiance=toLinearSpaceVec3(environmentIrradiance.rgb); +#endif +#endif +environmentIrradiance*=vReflectionColor.rgb; +#ifdef MIX_IBL_RADIANCE_WITH_IRRADIANCE +outParams.environmentRadiance=vec4f(mix(environmentRadiance.rgb,environmentIrradiance,alphaG),environmentRadiance.a); +#else +outParams.environmentRadiance=environmentRadiance; +#endif +outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5s]) { + ShaderStore.IncludesShadersStoreWGSL[name$5s] = shader$5r; +} + +// Do not edit. +const name$5r = "pbrBlockSheen"; +const shader$5q = `#ifdef SHEEN +struct sheenOutParams +{sheenIntensity: f32 +,sheenColor: vec3f +,sheenRoughness: f32 +#ifdef SHEEN_LINKWITHALBEDO +,surfaceAlbedo: vec3f +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +,sheenAlbedoScaling: f32 +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +,finalSheenRadianceScaled: vec3f +#endif +#if DEBUGMODE>0 +#ifdef SHEEN_TEXTURE +,sheenMapData: vec4f +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +,sheenEnvironmentReflectance: vec3f +#endif +#endif +}; +#define pbr_inline +fn sheenBlock( +vSheenColor: vec4f +#ifdef SHEEN_ROUGHNESS +,vSheenRoughness: f32 +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +,sheenMapRoughnessData: vec4f +#endif +#endif +,roughness: f32 +#ifdef SHEEN_TEXTURE +,sheenMapData: vec4f +,sheenMapLevel: f32 +#endif +,reflectance: f32 +#ifdef SHEEN_LINKWITHALBEDO +,baseColor: vec3f +,surfaceAlbedo: vec3f +#endif +#ifdef ENVIRONMENTBRDF +,NdotV: f32 +,environmentBrdf: vec3f +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +,AARoughnessFactors: vec2f +,vReflectionMicrosurfaceInfos: vec3f +,vReflectionInfos: vec2f +,vReflectionColor: vec3f +,vLightingIntensity: vec4f +#ifdef REFLECTIONMAP_3D +,reflectionSampler: texture_cube +,reflectionSamplerSampler: sampler +,reflectionCoords: vec3f +#else +,reflectionSampler: texture_2d +,reflectionSamplerSampler: sampler +,reflectionCoords: vec2f +#endif +,NdotVUnclamped: f32 +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +,reflectionLowSampler: texture_cube +,reflectionLowSamplerSampler: sampler +,reflectionHighSampler: texture_cube +,reflectionHighSamplerSampler: sampler +#else +,reflectionLowSampler: texture_2d +,reflectionLowSamplerSampler: sampler +,reflectionHighSampler: texture_2d +,reflectionHighSamplerSampler: sampler +#endif +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo: vec2f +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +,seo: f32 +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +,eho: f32 +#endif +#endif +)->sheenOutParams +{var outParams: sheenOutParams;var sheenIntensity: f32=vSheenColor.a; +#ifdef SHEEN_TEXTURE +#if DEBUGMODE>0 +outParams.sheenMapData=sheenMapData; +#endif +#endif +#ifdef SHEEN_LINKWITHALBEDO +var sheenFactor: f32=pow5(1.0-sheenIntensity);var sheenColor: vec3f=baseColor.rgb*(1.0-sheenFactor);var sheenRoughness: f32=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#else +var sheenColor: vec3f=vSheenColor.rgb; +#ifdef SHEEN_TEXTURE +#ifdef SHEEN_GAMMATEXTURE +sheenColor*=toLinearSpaceVec3(sheenMapData.rgb); +#else +sheenColor*=sheenMapData.rgb; +#endif +sheenColor*=sheenMapLevel; +#endif +#ifdef SHEEN_ROUGHNESS +var sheenRoughness: f32=vSheenRoughness; +#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE +#if defined(SHEEN_TEXTURE) +sheenRoughness*=sheenMapData.a; +#endif +#elif defined(SHEEN_TEXTURE_ROUGHNESS) +sheenRoughness*=sheenMapRoughnessData.a; +#endif +#else +var sheenRoughness: f32=roughness; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#endif +#if !defined(SHEEN_ALBEDOSCALING) +sheenIntensity*=(1.-reflectance); +#endif +sheenColor*=sheenIntensity; +#endif +#ifdef ENVIRONMENTBRDF +/*#ifdef SHEEN_SOFTER +var environmentSheenBrdf: vec3f= vec3f(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); +#else*/ +#ifdef SHEEN_ROUGHNESS +var environmentSheenBrdf: vec3f=getBRDFLookup(NdotV,sheenRoughness); +#else +var environmentSheenBrdf: vec3f=environmentBrdf; +#endif +/*#endif*/ +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +var sheenAlphaG: f32=convertRoughnessToAverageSlope(sheenRoughness); +#ifdef SPECULARAA +sheenAlphaG+=AARoughnessFactors.y; +#endif +var environmentSheenRadiance: vec4f= vec4f(0.,0.,0.,0.);environmentSheenRadiance=sampleReflectionTexture( +sheenAlphaG +,vReflectionMicrosurfaceInfos +,vReflectionInfos +,vReflectionColor +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +,NdotVUnclamped +#endif +#ifdef LINEARSPECULARREFLECTION +,sheenRoughness +#endif +,reflectionSampler +,reflectionSamplerSampler +,reflectionCoords +#ifndef LODBASEDMICROSFURACE +,reflectionLowSampler +,reflectionLowSamplerSampler +,reflectionHighSampler +,reflectionHighSamplerSampler +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo +#endif +);var sheenEnvironmentReflectance: vec3f=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +sheenEnvironmentReflectance*=seo; +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +sheenEnvironmentReflectance*=eho; +#endif +#if DEBUGMODE>0 +outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; +#endif +outParams.finalSheenRadianceScaled= +environmentSheenRadiance.rgb * +sheenEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; +#endif +outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5r]) { + ShaderStore.IncludesShadersStoreWGSL[name$5r] = shader$5q; +} + +// Do not edit. +const name$5q = "pbrBlockClearcoat"; +const shader$5p = `struct clearcoatOutParams +{specularEnvironmentR0: vec3f, +conservationFactor: f32, +clearCoatNormalW: vec3f, +clearCoatAARoughnessFactors: vec2f, +clearCoatIntensity: f32, +clearCoatRoughness: f32, +#ifdef REFLECTION +finalClearCoatRadianceScaled: vec3f, +#endif +#ifdef CLEARCOAT_TINT +absorption: vec3f, +clearCoatNdotVRefract: f32, +clearCoatColor: vec3f, +clearCoatThickness: f32, +#endif +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +energyConservationFactorClearCoat: vec3f, +#endif +#if DEBUGMODE>0 +#ifdef CLEARCOAT_BUMP +TBNClearCoat: mat3x3f, +#endif +#ifdef CLEARCOAT_TEXTURE +clearCoatMapData: vec2f, +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +clearCoatTintMapData: vec4f, +#endif +#ifdef REFLECTION +environmentClearCoatRadiance: vec4f, +clearCoatEnvironmentReflectance: vec3f, +#endif +clearCoatNdotV: f32 +#endif +}; +#ifdef CLEARCOAT +#define pbr_inline +fn clearcoatBlock( +vPositionW: vec3f +,geometricNormalW: vec3f +,viewDirectionW: vec3f +,vClearCoatParams: vec2f +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +,clearCoatMapRoughnessData: vec4f +#endif +,specularEnvironmentR0: vec3f +#ifdef CLEARCOAT_TEXTURE +,clearCoatMapData: vec2f +#endif +#ifdef CLEARCOAT_TINT +,vClearCoatTintParams: vec4f +,clearCoatColorAtDistance: f32 +,vClearCoatRefractionParams: vec4f +#ifdef CLEARCOAT_TINT_TEXTURE +,clearCoatTintMapData: vec4f +#endif +#endif +#ifdef CLEARCOAT_BUMP +,vClearCoatBumpInfos: vec2f +,clearCoatBumpMapData: vec4f +,vClearCoatBumpUV: vec2f +#if defined(TANGENT) && defined(NORMAL) +,vTBN: mat3x3f +#else +,vClearCoatTangentSpaceParams: vec2f +#endif +#ifdef OBJECTSPACE_NORMALMAP +,normalMatrix: mat4x4f +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +,faceNormal: vec3f +#endif +#ifdef REFLECTION +,vReflectionMicrosurfaceInfos: vec3f +,vReflectionInfos: vec2f +,vReflectionColor: vec3f +,vLightingIntensity: vec4f +#ifdef REFLECTIONMAP_3D +,reflectionSampler: texture_cube +,reflectionSamplerSampler: sampler +#else +,reflectionSampler: texture_2d +,reflectionSamplerSampler: sampler +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +,reflectionLowSampler: texture_cube +,reflectionLowSamplerSampler: sampler +,reflectionHighSampler: texture_cube +,reflectionHighSamplerSampler: sampler +#else +,reflectionLowSampler: texture_2d +,reflectionLowSamplerSampler: sampler +,reflectionHighSampler: texture_2d +,reflectionHighSamplerSampler: sampler +#endif +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo: vec2f +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +,frontFacingMultiplier: f32 +#endif +)->clearcoatOutParams +{var outParams: clearcoatOutParams;var clearCoatIntensity: f32=vClearCoatParams.x;var clearCoatRoughness: f32=vClearCoatParams.y; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE +clearCoatRoughness*=clearCoatMapData.y; +#endif +#if DEBUGMODE>0 +outParams.clearCoatMapData=clearCoatMapData; +#endif +#endif +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +clearCoatRoughness*=clearCoatMapRoughnessData.y; +#endif +outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; +#ifdef CLEARCOAT_TINT +var clearCoatColor: vec3f=vClearCoatTintParams.rgb;var clearCoatThickness: f32=vClearCoatTintParams.a; +#ifdef CLEARCOAT_TINT_TEXTURE +#ifdef CLEARCOAT_TINT_GAMMATEXTURE +clearCoatColor*=toLinearSpaceVec3(clearCoatTintMapData.rgb); +#else +clearCoatColor*=clearCoatTintMapData.rgb; +#endif +clearCoatThickness*=clearCoatTintMapData.a; +#if DEBUGMODE>0 +outParams.clearCoatTintMapData=clearCoatTintMapData; +#endif +#endif +outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; +#endif +#ifdef CLEARCOAT_REMAP_F0 +var specularEnvironmentR0Updated: vec3f=getR0RemappedForClearCoat(specularEnvironmentR0); +#else +var specularEnvironmentR0Updated: vec3f=specularEnvironmentR0; +#endif +outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);var clearCoatNormalW: vec3f=geometricNormalW; +#ifdef CLEARCOAT_BUMP +#ifdef NORMALXYSCALE +var clearCoatNormalScale: f32=1.0; +#else +var clearCoatNormalScale: f32=vClearCoatBumpInfos.y; +#endif +#if defined(TANGENT) && defined(NORMAL) +var TBNClearCoat: mat3x3f=vTBN; +#else +var TBNClearCoatUV: vec2f=vClearCoatBumpUV*frontFacingMultiplier;var TBNClearCoat: mat3x3f=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); +#endif +#if DEBUGMODE>0 +outParams.TBNClearCoat=TBNClearCoat; +#endif +#ifdef OBJECTSPACE_NORMALMAP +clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize( mat3x3f(normalMatrix[0].xyz,normalMatrix[1].xyz,normalMatrix[2].xyz)*clearCoatNormalW); +#else +clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; +#endif +outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);var clearCoatNdotVUnclamped: f32=dot(clearCoatNormalW,viewDirectionW);var clearCoatNdotV: f32=absEps(clearCoatNdotVUnclamped); +#if DEBUGMODE>0 +outParams.clearCoatNdotV=clearCoatNdotV; +#endif +#ifdef CLEARCOAT_TINT +var clearCoatVRefract: vec3f=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); +#endif +#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) +var environmentClearCoatBrdf: vec3f=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); +#endif +#if defined(REFLECTION) +var clearCoatAlphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness); +#ifdef SPECULARAA +clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; +#endif +var environmentClearCoatRadiance: vec4f= vec4f(0.,0.,0.,0.);var clearCoatReflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),clearCoatNormalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +clearCoatReflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +var clearCoatReflectionCoords: vec3f=clearCoatReflectionVector; +#else +var clearCoatReflectionCoords: vec2f=clearCoatReflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +clearCoatReflectionCoords/=clearCoatReflectionVector.z; +#endif +clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; +#endif +environmentClearCoatRadiance=sampleReflectionTexture( +clearCoatAlphaG +,vReflectionMicrosurfaceInfos +,vReflectionInfos +,vReflectionColor +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +,clearCoatNdotVUnclamped +#endif +#ifdef LINEARSPECULARREFLECTION +,clearCoatRoughness +#endif +,reflectionSampler +,reflectionSamplerSampler +,clearCoatReflectionCoords +#ifndef LODBASEDMICROSFURACE +,reflectionLowSampler +,reflectionLowSamplerSampler +,reflectionHighSampler +,reflectionHighSamplerSampler +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo +#endif +); +#if DEBUGMODE>0 +outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +var clearCoatEnvironmentReflectance: vec3f=getReflectanceFromBRDFLookup(vec3f(uniforms.vClearCoatRefractionParams.x),environmentClearCoatBrdf); +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +var clearCoatEho: f32=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; +#endif +#endif +#endif +#else +var clearCoatEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV, vec3f(1.), vec3f(1.),sqrt(1.-clearCoatRoughness)); +#endif +clearCoatEnvironmentReflectance*=clearCoatIntensity; +#if DEBUGMODE>0 +outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; +#endif +outParams.finalClearCoatRadianceScaled= +environmentClearCoatRadiance.rgb * +clearCoatEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(CLEARCOAT_TINT) +outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); +#endif +var fresnelIBLClearCoat: f32=fresnelSchlickGGX(clearCoatNdotV,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); +#endif +return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5q]) { + ShaderStore.IncludesShadersStoreWGSL[name$5q] = shader$5p; +} + +// Do not edit. +const name$5p = "pbrBlockIridescence"; +const shader$5o = `struct iridescenceOutParams +{iridescenceIntensity: f32, +iridescenceIOR: f32, +iridescenceThickness: f32, +specularEnvironmentR0: vec3f}; +#ifdef IRIDESCENCE +fn iridescenceBlock( +vIridescenceParams: vec4f +,viewAngle_: f32 +,specularEnvironmentR0: vec3f +#ifdef IRIDESCENCE_TEXTURE +,iridescenceMapData: vec2f +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +,iridescenceThicknessMapData: vec2f +#endif +#ifdef CLEARCOAT +,NdotVUnclamped: f32 +,vClearCoatParams: vec2f +#ifdef CLEARCOAT_TEXTURE +,clearCoatMapData: vec2f +#endif +#endif +)->iridescenceOutParams +{var outParams: iridescenceOutParams;var iridescenceIntensity: f32=vIridescenceParams.x;var iridescenceIOR: f32=vIridescenceParams.y;var iridescenceThicknessMin: f32=vIridescenceParams.z;var iridescenceThicknessMax: f32=vIridescenceParams.w;var iridescenceThicknessWeight: f32=1.;var viewAngle=viewAngle_; +#ifdef IRIDESCENCE_TEXTURE +iridescenceIntensity*=iridescenceMapData.x; +#endif +#if defined(IRIDESCENCE_THICKNESS_TEXTURE) +iridescenceThicknessWeight=iridescenceThicknessMapData.g; +#endif +var iridescenceThickness: f32=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);var topIor: f32=1.; +#ifdef CLEARCOAT +var clearCoatIntensity: f32=vClearCoatParams.x; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#endif +topIor=mix(1.0,uniforms.vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+((1.0/topIor)*(1.0/topIor))*((NdotVUnclamped*NdotVUnclamped)-1.0)); +#endif +var iridescenceFresnel: vec3f=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5p]) { + ShaderStore.IncludesShadersStoreWGSL[name$5p] = shader$5o; +} + +// Do not edit. +const name$5o = "pbrBlockSubSurface"; +const shader$5n = `struct subSurfaceOutParams +{specularEnvironmentReflectance: vec3f, +#ifdef SS_REFRACTION +finalRefraction: vec3f, +surfaceAlbedo: vec3f, +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha: f32, +#endif +#ifdef REFLECTION +refractionFactorForIrradiance: f32, +#endif +#endif +#ifdef SS_TRANSLUCENCY +transmittance: vec3f, +translucencyIntensity: f32, +#ifdef REFLECTION +refractionIrradiance: vec3f, +#endif +#endif +#if DEBUGMODE>0 +#ifdef SS_THICKNESSANDMASK_TEXTURE +thicknessMap: vec4f, +#endif +#ifdef SS_REFRACTION +environmentRefraction: vec4f, +refractionTransmittance: vec3f +#endif +#endif +}; +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +#define pbr_inline +fn sampleEnvironmentRefraction( +ior: f32 +,thickness: f32 +,refractionLOD: f32 +,normalW: vec3f +,vPositionW: vec3f +,viewDirectionW: vec3f +,view: mat4x4f +,vRefractionInfos: vec4f +,refractionMatrix: mat4x4f +,vRefractionMicrosurfaceInfos: vec4f +,alphaG: f32 +#ifdef SS_REFRACTIONMAP_3D +,refractionSampler: texture_cube +,refractionSamplerSampler: sampler +#ifndef LODBASEDMICROSFURACE +,refractionLowSampler: texture_cube +,refractionLowSamplerSampler: sampler +,refractionHighSampler: texture_cube +,refractionHighSamplerSampler: sampler +#endif +#else +,refractionSampler: texture_2d +,refractionSamplerSampler: sampler +#ifndef LODBASEDMICROSFURACE +,refractionLowSampler: texture_2d +,refractionLowSamplerSampler: sampler +,refractionHighSampler: texture_2d +,refractionHighSamplerSampler: sampler +#endif +#endif +#ifdef ANISOTROPIC +,anisotropicOut: anisotropicOutParams +#endif +#ifdef REALTIME_FILTERING +,vRefractionFilteringInfo: vec2f +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,refractionPosition: vec3f +,refractionSize: vec3f +#endif +)->vec4f {var environmentRefraction: vec4f= vec4f(0.,0.,0.,0.); +#ifdef ANISOTROPIC +var refractionVector: vec3f=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior); +#else +var refractionVector: vec3f=refract(-viewDirectionW,normalW,ior); +#endif +#ifdef SS_REFRACTIONMAP_OPPOSITEZ +refractionVector.z*=-1.0; +#endif +#ifdef SS_REFRACTIONMAP_3D +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;var refractionCoords: vec3f=refractionVector;refractionCoords= (refractionMatrix* vec4f(refractionCoords,0)).xyz; +#else +#ifdef SS_USE_THICKNESS_AS_DEPTH +var vRefractionUVW: vec3f= (refractionMatrix*(view* vec4f(vPositionW+refractionVector*thickness,1.0))).xyz; +#else +var vRefractionUVW: vec3f= (refractionMatrix*(view* vec4f(vPositionW+refractionVector*vRefractionInfos.z,1.0))).xyz; +#endif +var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; +#endif +#ifdef LODBASEDMICROSFURACE +var lod=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; +#ifdef SS_LODINREFRACTIONALPHA +var automaticRefractionLOD: f32=UNPACK_LOD(textureSample(refractionSampler,refractionSamplerSampler,refractionCoords).a);var requestedRefractionLOD: f32=max(automaticRefractionLOD,lod); +#else +var requestedRefractionLOD: f32=lod; +#endif +#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) +environmentRefraction= vec4f(radiance(alphaG,refractionSampler,refractionSamplerSampler,refractionCoords,vRefractionFilteringInfo),1.0); +#else +environmentRefraction=textureSampleLevel(refractionSampler,refractionSamplerSampler,refractionCoords,requestedRefractionLOD); +#endif +#else +var lodRefractionNormalized: f32=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));var lodRefractionNormalizedDoubled: f32=lodRefractionNormalized*2.0;var environmentRefractionMid: vec4f=textureSample(refractionSampler,refractionSamplerSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( +textureSample(refractionHighSampler,refractionHighSamplerSampler,refractionCoords), +environmentRefractionMid, +lodRefractionNormalizedDoubled +);} else {environmentRefraction=mix( +environmentRefractionMid, +textureSample(refractionLowSampler,refractionLowSamplerSampler,refractionCoords), +lodRefractionNormalizedDoubled-1.0 +);} +#endif +var refraction=environmentRefraction.rgb; +#ifdef SS_RGBDREFRACTION +refraction=fromRGBD(environmentRefraction); +#endif +#ifdef SS_GAMMAREFRACTION +refraction=toLinearSpaceVec3(environmentRefraction.rgb); +#endif +return vec4f(refraction,environmentRefraction.a);} +#endif +#define pbr_inline +fn subSurfaceBlock( +vSubSurfaceIntensity: vec3f +,vThicknessParam: vec2f +,vTintColor: vec4f +,normalW: vec3f +,specularEnvironmentReflectance: vec3f +#ifdef SS_THICKNESSANDMASK_TEXTURE +,thicknessMap: vec4f +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +,refractionIntensityMap: vec4f +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +,translucencyIntensityMap: vec4f +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +,reflectionMatrix: mat4x4f +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +,irradianceVector_: vec3f +#endif +#if defined(REALTIME_FILTERING) +,reflectionSampler: texture_cube +,reflectionSamplerSampler: sampler +,vReflectionFilteringInfo: vec2f +#ifdef IBL_CDF_FILTERING +,icdfSampler: texture_2d +,icdfSamplerSampler: sampler +#endif +#endif +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +,irradianceSampler: texture_cube +,irradianceSamplerSampler: sampler +#else +,irradianceSampler: texture_2d +,irradianceSamplerSampler: sampler +#endif +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +,surfaceAlbedo: vec3f +#endif +#ifdef SS_REFRACTION +,vPositionW: vec3f +,viewDirectionW: vec3f +,view: mat4x4f +,vRefractionInfos: vec4f +,refractionMatrix: mat4x4f +,vRefractionMicrosurfaceInfos: vec4f +,vLightingIntensity: vec4f +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +,alpha: f32 +#endif +#ifdef SS_LODINREFRACTIONALPHA +,NdotVUnclamped: f32 +#endif +#ifdef SS_LINEARSPECULARREFRACTION +,roughness: f32 +#endif +,alphaG: f32 +#ifdef SS_REFRACTIONMAP_3D +,refractionSampler: texture_cube +,refractionSamplerSampler: sampler +#ifndef LODBASEDMICROSFURACE +,refractionLowSampler: texture_cube +,refractionLowSamplerSampler: sampler +,refractionHighSampler: texture_cube +,refractionHighSamplerSampler: sampler +#endif +#else +,refractionSampler: texture_2d +,refractionSamplerSampler: sampler +#ifndef LODBASEDMICROSFURACE +,refractionLowSampler: texture_2d +,refractionLowSamplerSampler: sampler +,refractionHighSampler: texture_2d +,refractionHighSamplerSampler: sampler +#endif +#endif +#ifdef ANISOTROPIC +,anisotropicOut: anisotropicOutParams +#endif +#ifdef REALTIME_FILTERING +,vRefractionFilteringInfo: vec2f +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,refractionPosition: vec3f +,refractionSize: vec3f +#endif +#ifdef SS_DISPERSION +,dispersion: f32 +#endif +#endif +#ifdef SS_TRANSLUCENCY +,vDiffusionDistance: vec3f +,vTranslucencyColor: vec4f +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE +,translucencyColorMap: vec4f +#endif +#endif +)->subSurfaceOutParams +{var outParams: subSurfaceOutParams;outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; +#ifdef SS_REFRACTION +var refractionIntensity: f32=vSubSurfaceIntensity.x; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; +#endif +#endif +#ifdef SS_TRANSLUCENCY +var translucencyIntensity: f32=vSubSurfaceIntensity.y; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +#ifdef SS_USE_GLTF_TEXTURES +var thickness: f32=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; +#else +var thickness: f32=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; +#endif +#if DEBUGMODE>0 +outParams.thicknessMap=thicknessMap; +#endif +#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS) +#ifdef SS_USE_GLTF_TEXTURES +refractionIntensity*=thicknessMap.r; +#else +refractionIntensity*=thicknessMap.g; +#endif +#endif +#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS) +#ifdef SS_USE_GLTF_TEXTURES +translucencyIntensity*=thicknessMap.a; +#else +translucencyIntensity*=thicknessMap.b; +#endif +#endif +#else +var thickness: f32=vThicknessParam.y; +#endif +#if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE) +#ifdef SS_USE_GLTF_TEXTURES +refractionIntensity*=refractionIntensityMap.r; +#else +refractionIntensity*=refractionIntensityMap.g; +#endif +#endif +#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE) +#ifdef SS_USE_GLTF_TEXTURES +translucencyIntensity*=translucencyIntensityMap.a; +#else +translucencyIntensity*=translucencyIntensityMap.b; +#endif +#endif +#ifdef SS_TRANSLUCENCY +thickness=maxEps(thickness);var translucencyColor: vec4f=vTranslucencyColor; +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE +translucencyColor*=translucencyColorMap; +#endif +var transmittance: vec3f=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; +#endif +#ifdef SS_REFRACTION +var environmentRefraction: vec4f= vec4f(0.,0.,0.,0.); +#ifdef SS_HAS_THICKNESS +var ior: f32=vRefractionInfos.y; +#else +var ior: f32=vRefractionMicrosurfaceInfos.w; +#endif +#ifdef SS_LODINREFRACTIONALPHA +var refractionAlphaG: f32=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLodFromAlphaGNdotV(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); +#elif defined(SS_LINEARSPECULARREFRACTION) +var refractionRoughness: f32=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); +#else +var refractionAlphaG: f32=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); +#endif +var refraction_ior: f32=vRefractionInfos.y; +#ifdef SS_DISPERSION +var realIOR: f32=1.0/refraction_ior;var iorDispersionSpread: f32=0.04*dispersion*(realIOR-1.0);var iors: vec3f= vec3f(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (var i: i32=0; i<3; i++) {refraction_ior=iors[i]; +#endif +var envSample: vec4f=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG +#ifdef SS_REFRACTIONMAP_3D +,refractionSampler +,refractionSamplerSampler +#ifndef LODBASEDMICROSFURACE +,refractionLowSampler +,refractionLowSamplerSampler +,refractionHighSampler +,refractionHighSamplerSampler +#endif +#else +,refractionSampler +,refractionSamplerSampler +#ifndef LODBASEDMICROSFURACE +,refractionLowSampler +,refractionLowSamplerSampler +,refractionHighSampler +,refractionHighSamplerSampler +#endif +#endif +#ifdef ANISOTROPIC +,anisotropicOut +#endif +#ifdef REALTIME_FILTERING +,vRefractionFilteringInfo +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,refractionPosition +,refractionSize +#endif +); +#ifdef SS_DISPERSION +environmentRefraction[i]=envSample[i];} +#else +environmentRefraction=envSample; +#endif +environmentRefraction=vec4f(environmentRefraction.rgb*vRefractionInfos.x,environmentRefraction.a); +#endif +#ifdef SS_REFRACTION +var refractionTransmittance: vec3f= vec3f(refractionIntensity); +#ifdef SS_THICKNESSANDMASK_TEXTURE +var volumeAlbedo: vec3f=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambertVec3(volumeAlbedo,thickness); +#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) +var maxChannel: f32=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);var volumeAlbedo: vec3f=saturateVec3(maxChannel*surfaceAlbedo);environmentRefraction=vec4f(environmentRefraction.rgb*volumeAlbedo,environmentRefraction.a); +#else +var volumeAlbedo: vec3f=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambertVec3(volumeAlbedo,vThicknessParam.y); +#endif +#ifdef SS_ALBEDOFORREFRACTIONTINT +environmentRefraction=vec4f(environmentRefraction.rgb*surfaceAlbedo.rgb,environmentRefraction.a); +#endif +outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); +#ifdef REFLECTION +outParams.refractionFactorForIrradiance=(1.-refractionIntensity); +#endif +#ifdef UNUSED_MULTIPLEBOUNCES +var bounceSpecularEnvironmentReflectance: vec3f=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); +#endif +refractionTransmittance*=1.0-max(outParams.specularEnvironmentReflectance.r,max(outParams.specularEnvironmentReflectance.g,outParams.specularEnvironmentReflectance.b)); +#if DEBUGMODE>0 +outParams.refractionTransmittance=refractionTransmittance; +#endif +outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; +#if DEBUGMODE>0 +outParams.environmentRefraction=environmentRefraction; +#endif +#endif +#if defined(REFLECTION) && defined(SS_TRANSLUCENCY) +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) +var irradianceVector: vec3f= (reflectionMatrix* vec4f(normalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#else +var irradianceVector: vec3f=irradianceVector_; +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) +#if defined(REALTIME_FILTERING) +var refractionIrradiance: vec3f=irradiance(reflectionSampler,reflectionSamplerSampler,-irradianceVector,vReflectionFilteringInfo +#ifdef IBL_CDF_FILTERING +,icdfSampler +,icdfSamplerSampler +#endif +); +#else +var refractionIrradiance: vec3f=computeEnvironmentIrradiance(-irradianceVector); +#endif +#elif defined(USEIRRADIANCEMAP) +#ifdef REFLECTIONMAP_3D +var irradianceCoords: vec3f=irradianceVector; +#else +var irradianceCoords: vec2f=irradianceVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +irradianceCoords/=irradianceVector.z; +#endif +irradianceCoords.y=1.0-irradianceCoords.y; +#endif +var temp: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,-irradianceCoords);var refractionIrradiance=temp.rgb; +#ifdef RGBDREFLECTION +refractionIrradiance=fromRGBD(temp).rgb; +#endif +#ifdef GAMMAREFLECTION +refractionIrradiance=toLinearSpaceVec3(refractionIrradiance); +#endif +#else +var refractionIrradiance: vec3f= vec3f(0.); +#endif +refractionIrradiance*=transmittance; +#ifdef SS_ALBEDOFORTRANSLUCENCYTINT +refractionIrradiance*=surfaceAlbedo.rgb; +#endif +outParams.refractionIrradiance=refractionIrradiance; +#endif +return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5o]) { + ShaderStore.IncludesShadersStoreWGSL[name$5o] = shader$5n; +} + +// Do not edit. +const name$5n = "pbrBlockNormalGeometric"; +const shader$5m = `var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW); +#ifdef NORMAL +var normalW: vec3f=normalize(input.vNormalW); +#else +var normalW: vec3f=normalize(cross(dpdx(input.vPositionW),dpdy(input.vPositionW)))*scene.vEyePosition.w; +#endif +var geometricNormalW: vec3f=normalW; +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +geometricNormalW=select(-geometricNormalW,geometricNormalW,fragmentInputs.frontFacing); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5n]) { + ShaderStore.IncludesShadersStoreWGSL[name$5n] = shader$5m; +} + +// Do not edit. +const name$5m = "bumpFragment"; +const shader$5l = `var uvOffset: vec2f= vec2f(0.0,0.0); +#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) +#ifdef NORMALXYSCALE +var normalScale: f32=1.0; +#elif defined(BUMP) +var normalScale: f32=uniforms.vBumpInfos.y; +#else +var normalScale: f32=1.0; +#endif +#if defined(TANGENT) && defined(NORMAL) +var TBN: mat3x3f=mat3x3(input.vTBN0,input.vTBN1,input.vTBN2); +#elif defined(BUMP) +var TBNUV: vec2f=select(-fragmentInputs.vBumpUV,fragmentInputs.vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV,uniforms.vTangentSpaceParams); +#else +var TBNUV: vec2f=select(-fragmentInputs.vDetailUV,fragmentInputs.vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV, vec2f(1.,1.)); +#endif +#elif defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +var TBN: mat3x3f=mat3x3(input.vTBN0,input.vTBN1,input.vTBN2); +#else +var TBNUV: vec2f=select( -fragmentInputs.vMainUV1,fragmentInputs.vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,input.vPositionW,TBNUV, vec2f(1.,1.)); +#endif +#endif +#ifdef PARALLAX +var invTBN: mat3x3f=transposeMat3(TBN); +#ifdef PARALLAXOCCLUSION +uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,fragmentInputs.vBumpUV,uniforms.vBumpInfos.z); +#else +uvOffset=parallaxOffset(invTBN*viewDirectionW,uniforms.vBumpInfos.z); +#endif +#endif +#ifdef DETAIL +var detailColor: vec4f=textureSample(detailSampler,detailSamplerSampler,fragmentInputs.vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB); +#endif +#ifdef BUMP +#ifdef OBJECTSPACE_NORMALMAP +#define CUSTOM_FRAGMENT_BUMP_FRAGMENT +normalW=normalize(textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3x3f(uniforms.normalMatrix[0].xyz,uniforms.normalMatrix[1].xyz,uniforms.normalMatrix[2].xyz)*normalW); +#elif !defined(DETAIL) +normalW=perturbNormal(TBN,textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz,uniforms.vBumpInfos.y); +#else +var bumpNormal: vec3f=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz*2.0-1.0; +#if DETAIL_NORMALBLENDMETHOD==0 +detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); +#elif DETAIL_NORMALBLENDMETHOD==1 +detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; +#endif +normalW=perturbNormalBase(TBN,blendedNormal,uniforms.vBumpInfos.y); +#endif +#elif defined(DETAIL) +detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);normalW=perturbNormalBase(TBN,detailNormal,uniforms.vDetailInfos.z); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5m]) { + ShaderStore.IncludesShadersStoreWGSL[name$5m] = shader$5l; +} +/** @internal */ +const bumpFragmentWGSL = { name: name$5m, shader: shader$5l }; + +const bumpFragment$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bumpFragmentWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$5l = "pbrBlockNormalFinal"; +const shader$5k = `#if defined(FORCENORMALFORWARD) && defined(NORMAL) +var faceNormal: vec3f=normalize(cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)))*scene.vEyePosition.w; +#if defined(TWOSIDEDLIGHTING) +faceNormal=select(-faceNormal,faceNormal,fragmentInputs.frontFacing); +#endif +normalW*=sign(dot(normalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +normalW=select(-normalW,normalW,fragmentInputs.frontFacing); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5l]) { + ShaderStore.IncludesShadersStoreWGSL[name$5l] = shader$5k; +} + +// Do not edit. +const name$5k = "depthPrePass"; +const shader$5j = `#ifdef DEPTHPREPASS +fragmentOutputs.color= vec4f(0.,0.,0.,1.0);return fragmentOutputs; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5k]) { + ShaderStore.IncludesShadersStoreWGSL[name$5k] = shader$5j; +} + +// Do not edit. +const name$5j = "pbrBlockLightmapInit"; +const shader$5i = `#ifdef LIGHTMAP +var lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a); +#endif +#ifdef GAMMALIGHTMAP +lightmapColor=vec4f(toLinearSpaceVec3(lightmapColor.rgb),lightmapColor.a); +#endif +lightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5j]) { + ShaderStore.IncludesShadersStoreWGSL[name$5j] = shader$5i; +} + +// Do not edit. +const name$5i = "pbrBlockGeometryInfo"; +const shader$5h = `var NdotVUnclamped: f32=dot(normalW,viewDirectionW);var NdotV: f32=absEps(NdotVUnclamped);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var AARoughnessFactors: vec2f=getAARoughnessFactors(normalW.xyz); +#ifdef SPECULARAA +alphaG+=AARoughnessFactors.y; +#endif +#if defined(ENVIRONMENTBRDF) +var environmentBrdf: vec3f=getBRDFLookup(NdotV,roughness); +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +#ifdef AMBIENTINGRAYSCALE +var ambientMonochrome: f32=aoOut.ambientOcclusionColor.r; +#else +var ambientMonochrome: f32=getLuminance(aoOut.ambientOcclusionColor); +#endif +var seo: f32=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +var eho: f32=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); +#endif +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5i]) { + ShaderStore.IncludesShadersStoreWGSL[name$5i] = shader$5h; +} + +// Do not edit. +const name$5h = "pbrBlockReflectance0"; +const shader$5g = `var reflectance: f32=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);var specularEnvironmentR0: vec3f=reflectivityOut.surfaceReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +var specularEnvironmentR90: vec3f= vec3f(metallicReflectanceFactors.a); +#else +var specularEnvironmentR90: vec3f= vec3f(1.0,1.0,1.0); +#endif +#ifdef ALPHAFRESNEL +var reflectance90: f32=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5h]) { + ShaderStore.IncludesShadersStoreWGSL[name$5h] = shader$5g; +} + +// Do not edit. +const name$5g = "pbrBlockReflectance"; +const shader$5f = `#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +var specularEnvironmentReflectance: vec3f=getReflectanceFromBRDFWithEnvLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); +#ifdef RADIANCEOCCLUSION +specularEnvironmentReflectance*=seo; +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +specularEnvironmentReflectance*=eho; +#endif +#endif +#endif +#else +var specularEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); +#endif +#ifdef CLEARCOAT +specularEnvironmentReflectance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +specularEnvironmentReflectance*=clearcoatOut.absorption; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5g]) { + ShaderStore.IncludesShadersStoreWGSL[name$5g] = shader$5f; +} + +// Do not edit. +const name$5f = "pbrBlockDirectLighting"; +const shader$5e = `var diffuseBase: vec3f=vec3f(0.,0.,0.); +#ifdef SPECULARTERM +var specularBase: vec3f=vec3f(0.,0.,0.); +#endif +#ifdef CLEARCOAT +var clearCoatBase: vec3f=vec3f(0.,0.,0.); +#endif +#ifdef SHEEN +var sheenBase: vec3f=vec3f(0.,0.,0.); +#endif +var preInfo: preLightingInfo;var info: lightingInfo;var shadow: f32=1.; +var aggShadow: f32=0.;var numLights: f32=0.; +#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +var absorption: vec3f=vec3f(0.); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5f]) { + ShaderStore.IncludesShadersStoreWGSL[name$5f] = shader$5e; +} + +// Do not edit. +const name$5e = "pbrBlockFinalLitComponents"; +const shader$5d = `aggShadow=aggShadow/numLights; +#if defined(ENVIRONMENTBRDF) +#ifdef MS_BRDF_ENERGY_CONSERVATION +var energyConservationFactor: vec3f=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); +#endif +#endif +#ifndef METALLICWORKFLOW +#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION +surfaceAlbedo=(1.-reflectance)*surfaceAlbedo.rgb; +#endif +#endif +#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) +surfaceAlbedo=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; +#endif +#ifdef REFLECTION +var finalIrradiance: vec3f=reflectionOut.environmentIrradiance; +#if defined(CLEARCOAT) +finalIrradiance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +finalIrradiance*=clearcoatOut.absorption; +#endif +#endif +finalIrradiance*=surfaceAlbedo.rgb; +#if defined(SS_REFRACTION) +finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; +#endif +#if defined(SS_TRANSLUCENCY) +finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; +#endif +finalIrradiance*=uniforms.vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; +#endif +#ifdef SPECULARTERM +var finalSpecular: vec3f=specularBase;finalSpecular=max(finalSpecular,vec3f(0.0));var finalSpecularScaled: vec3f=finalSpecular*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalSpecularScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalSpecularScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef REFLECTION +var finalRadiance: vec3f=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;var finalRadianceScaled: vec3f=finalRadiance*uniforms.vLightingIntensity.z; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalRadianceScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalRadianceScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef SHEEN +var finalSheen: vec3f=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,vec3f(0.0));var finalSheenScaled: vec3f=finalSheen*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w; +#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef CLEARCOAT +var finalClearCoat: vec3f=clearCoatBase;finalClearCoat=max(finalClearCoat,vec3f(0.0));var finalClearCoatScaled: vec3f=finalClearCoat*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; +#ifdef CLEARCOAT_TINT +subSurfaceOut.finalRefraction*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef ALPHABLEND +var luminanceOverAlpha: f32=0.0; +#if defined(REFLECTION) && defined(RADIANCEOVERALPHA) +luminanceOverAlpha+=getLuminance(finalRadianceScaled); +#if defined(CLEARCOAT) +luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); +#endif +#endif +#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) +luminanceOverAlpha+=getLuminance(finalSpecularScaled); +#endif +#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) +luminanceOverAlpha+=getLuminance(finalClearCoatScaled); +#endif +#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) +alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5e]) { + ShaderStore.IncludesShadersStoreWGSL[name$5e] = shader$5d; +} + +// Do not edit. +const name$5d = "pbrBlockFinalUnlitComponents"; +const shader$5c = `var finalDiffuse: vec3f=diffuseBase; +#if !defined(SS_TRANSLUCENCY) +finalDiffuse*=surfaceAlbedo.rgb; +#endif +finalDiffuse=max(finalDiffuse,vec3f(0.0));finalDiffuse*=uniforms.vLightingIntensity.x;var finalAmbient: vec3f=uniforms.vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;var finalEmissive: vec3f=uniforms.vEmissiveColor; +#ifdef EMISSIVE +var emissiveColorTex: vec3f=textureSample(emissiveSampler,emissiveSamplerSampler,fragmentInputs.vEmissiveUV+uvOffset).rgb; +#ifdef GAMMAEMISSIVE +finalEmissive*=toLinearSpaceVec3(emissiveColorTex.rgb); +#else +finalEmissive*=emissiveColorTex.rgb; +#endif +finalEmissive*= uniforms.vEmissiveInfos.y; +#endif +finalEmissive*=uniforms.vLightingIntensity.y; +#ifdef AMBIENT +var ambientOcclusionForDirectDiffuse: vec3f=mix( vec3f(1.),aoOut.ambientOcclusionColor,uniforms.vAmbientInfos.w); +#else +var ambientOcclusionForDirectDiffuse: vec3f=aoOut.ambientOcclusionColor; +#endif +finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5d]) { + ShaderStore.IncludesShadersStoreWGSL[name$5d] = shader$5c; +} + +// Do not edit. +const name$5c = "pbrBlockFinalColorComposition"; +const shader$5b = `var finalColor: vec4f= vec4f( +#ifndef UNLIT +#ifdef REFLECTION +finalIrradiance + +#endif +#ifdef SPECULARTERM +finalSpecularScaled + +#endif +#ifdef SHEEN +finalSheenScaled + +#endif +#ifdef CLEARCOAT +finalClearCoatScaled + +#endif +#ifdef REFLECTION +finalRadianceScaled + +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled + +#endif +#ifdef CLEARCOAT +clearcoatOut.finalClearCoatRadianceScaled + +#endif +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction + +#endif +#endif +finalAmbient + +finalDiffuse, +alpha); +#ifdef LIGHTMAP +#ifndef LIGHTMAPEXCLUDED +#ifdef USELIGHTMAPASSHADOWMAP +finalColor=vec4f(finalColor.rgb*lightmapColor.rgb,finalColor.a); +#else +finalColor=vec4f(finalColor.rgb+lightmapColor.rgb,finalColor.a); +#endif +#endif +#endif +finalColor=vec4f(finalColor.rgb+finalEmissive,finalColor.a); +#define CUSTOM_FRAGMENT_BEFORE_FOG +finalColor=max(finalColor,vec4f(0.0)); +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5c]) { + ShaderStore.IncludesShadersStoreWGSL[name$5c] = shader$5b; +} + +// Do not edit. +const name$5b = "pbrBlockImageProcessing"; +const shader$5a = `#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) +#if !defined(SKIPFINALCOLORCLAMP) +finalColor=vec4f(clamp(finalColor.rgb,vec3f(0.),vec3f(30.0)),finalColor.a); +#endif +#else +finalColor=applyImageProcessing(finalColor); +#endif +finalColor=vec4f(finalColor.rgb,finalColor.a*mesh.visibility); +#ifdef PREMULTIPLYALPHA +finalColor=vec4f(finalColor.rgb*finalColor.a,finalColor.a);; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5b]) { + ShaderStore.IncludesShadersStoreWGSL[name$5b] = shader$5a; +} + +// Do not edit. +const name$5a = "pbrBlockPrePass"; +const shader$59 = `var writeGeometryInfo: f32=select(0.0,1.0,finalColor.a>ALPHATESTVALUE);var fragData: array,SCENE_MRT_COUNT>; +#ifdef PREPASS_POSITION +fragData[PREPASS_POSITION_INDEX]= vec4f(fragmentInputs.vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_LOCAL_POSITION +fragData[PREPASS_LOCAL_POSITION_INDEX]=vec4f(fragmentInputs.vPosition,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +var a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo); +#elif defined(PREPASS_VELOCITY_LINEAR) +var velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w) - +(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO +fragData[PREPASS_ALBEDO_INDEX]=vec4f(surfaceAlbedo,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +var sqAlbedo : vec3f=sqrt(surfaceAlbedo); +#endif +#ifdef PREPASS_IRRADIANCE +var irradiance : vec3f=finalDiffuse; +#ifndef UNLIT +#ifdef REFLECTION +irradiance+=finalIrradiance; +#endif +#endif +#ifdef SS_SCATTERING +#ifdef PREPASS_COLOR +fragData[PREPASS_COLOR_INDEX]=vec4f(finalColor.rgb-irradiance,finalColor.a); +#endif +irradiance/=sqAlbedo;fragData[PREPASS_IRRADIANCE_INDEX]=vec4f(clamp(irradiance,vec3f(0.),vec3f(1.)),writeGeometryInfo*uniforms.scatteringDiffusionProfile/255.); +#else +#ifdef PREPASS_COLOR +fragData[PREPASS_COLOR_INDEX]=finalColor; +#endif +fragData[PREPASS_IRRADIANCE_INDEX]=vec4f(clamp(irradiance,vec3f(0.),vec3f(1.)),writeGeometryInfo); +#endif +#elif defined(PREPASS_COLOR) +fragData[PREPASS_COLOR_INDEX]=vec4f(finalColor.rgb,finalColor.a); +#endif +#ifdef PREPASS_DEPTH +fragData[PREPASS_DEPTH_INDEX]=vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_SCREENSPACE_DEPTH +fragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +fragData[PREPASS_NORMAL_INDEX]=vec4f(normalW,writeGeometryInfo); +#else +fragData[PREPASS_NORMAL_INDEX]=vec4f(normalize((scene.view*vec4f(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_WORLD_NORMAL +fragData[PREPASS_WORLD_NORMAL_INDEX]=vec4f(normalW*0.5+0.5,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +fragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4f(sqAlbedo,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#ifndef UNLIT +fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(specularEnvironmentR0,microSurface)*writeGeometryInfo; +#else +fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(0.0,0.0,0.0,1.0)*writeGeometryInfo; +#endif +#endif +#if SCENE_MRT_COUNT>0 +fragmentOutputs.fragData0=fragData[0]; +#endif +#if SCENE_MRT_COUNT>1 +fragmentOutputs.fragData1=fragData[1]; +#endif +#if SCENE_MRT_COUNT>2 +fragmentOutputs.fragData2=fragData[2]; +#endif +#if SCENE_MRT_COUNT>3 +fragmentOutputs.fragData3=fragData[3]; +#endif +#if SCENE_MRT_COUNT>4 +fragmentOutputs.fragData4=fragData[4]; +#endif +#if SCENE_MRT_COUNT>5 +fragmentOutputs.fragData5=fragData[5]; +#endif +#if SCENE_MRT_COUNT>6 +fragmentOutputs.fragData6=fragData[6]; +#endif +#if SCENE_MRT_COUNT>7 +fragmentOutputs.fragData7=fragData[7]; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5a]) { + ShaderStore.IncludesShadersStoreWGSL[name$5a] = shader$59; +} + +// Do not edit. +const name$59 = "oitFragment"; +const shader$58 = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY +var fragDepth: f32=fragmentInputs.position.z; +#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS +var halfFloat: u32=pack2x16float( vec2f(fragDepth));var full: vec2f=unpack2x16float(halfFloat);fragDepth=full.x; +#endif +var fragCoord: vec2i=vec2i(fragmentInputs.position.xy);var lastDepth: vec2f=textureLoad(oitDepthSampler,fragCoord,0).rg;var lastFrontColor: vec4f=textureLoad(oitFrontColorSampler,fragCoord,0);fragmentOutputs.depth=vec2f(-MAX_DEPTH);fragmentOutputs.frontColor=lastFrontColor;fragmentOutputs.backColor= vec4f(0.0); +#ifdef USE_REVERSE_DEPTHBUFFER +var furthestDepth: f32=-lastDepth.x;var nearestDepth: f32=lastDepth.y; +#else +var nearestDepth: f32=-lastDepth.x;var furthestDepth: f32=lastDepth.y; +#endif +var alphaMultiplier: f32=1.0-lastFrontColor.a; +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepth>nearestDepth || fragDepthfurthestDepth) { +#endif +return fragmentOutputs;} +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepthfurthestDepth) { +#else +if (fragDepth>nearestDepth && fragDepth0 +if (input.vClipSpacePosition.x/input.vClipSpacePosition.w>=uniforms.vDebugMode.x) {var color: vec3f; +#if DEBUGMODE==1 +color=fragmentInputs.vPositionW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==2 && defined(NORMAL) +color=fragmentInputs.vNormalW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) +color=TBN[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) +color=TBN[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==5 +color=normalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==6 && defined(MAINUV1) +color= vec3f(input.vMainUV1,0.0); +#elif DEBUGMODE==7 && defined(MAINUV2) +color= vec3f(input.vMainUV2,0.0); +#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +color=clearcoatOut.TBNClearCoat[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +color=clearcoatOut.TBNClearCoat[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==10 && defined(CLEARCOAT) +color=clearcoatOut.clearCoatNormalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==11 && defined(ANISOTROPIC) +color=anisotropicOut.anisotropicNormal; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==12 && defined(ANISOTROPIC) +color=anisotropicOut.anisotropicTangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==13 && defined(ANISOTROPIC) +color=anisotropicOut.anisotropicBitangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==20 && defined(ALBEDO) +color=albedoTexture.rgb; +#ifndef GAMMAALBEDO +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==21 && defined(AMBIENT) +color=aoOut.ambientOcclusionColorMap.rgb; +#elif DEBUGMODE==22 && defined(OPACITY) +color=opacityMap.rgb; +#elif DEBUGMODE==23 && defined(EMISSIVE) +color=emissiveColorTex.rgb; +#ifndef GAMMAEMISSIVE +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==24 && defined(LIGHTMAP) +color=lightmapColor; +#ifndef GAMMALIGHTMAP +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) +color=reflectivityOut.surfaceMetallicColorMap.rgb; +#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) +color=reflectivityOut.surfaceReflectivityColorMap.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) +color= vec3f(clearcoatOut.clearCoatMapData.rg,0.0); +#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +color=clearcoatOut.clearCoatTintMapData.rgb; +#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) +color=sheenOut.sheenMapData.rgb; +#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) +color=anisotropicOut.anisotropyMapData.rgb; +#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) +color=subSurfaceOut.thicknessMap.rgb; +#elif DEBUGMODE==32 && defined(BUMP) +color=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).rgb; +#elif DEBUGMODE==40 && defined(SS_REFRACTION) +color=subSurfaceOut.environmentRefraction.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==41 && defined(REFLECTION) +color=reflectionOut.environmentRadiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) +color=clearcoatOut.environmentClearCoatRadiance.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==50 +color=diffuseBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==51 && defined(SPECULARTERM) +color=specularBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==52 && defined(CLEARCOAT) +color=clearCoatBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==53 && defined(SHEEN) +color=sheenBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==54 && defined(REFLECTION) +color=reflectionOut.environmentIrradiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==60 +color=surfaceAlbedo.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==61 +color=clearcoatOut.specularEnvironmentR0; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==62 && defined(METALLICWORKFLOW) +color= vec3f(reflectivityOut.metallicRoughness.r); +#elif DEBUGMODE==71 && defined(METALLICWORKFLOW) +color=reflectivityOut.metallicF0; +#elif DEBUGMODE==63 +color= vec3f(roughness); +#elif DEBUGMODE==64 +color= vec3f(alphaG); +#elif DEBUGMODE==65 +color= vec3f(NdotV); +#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +color=clearcoatOut.clearCoatColor; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==67 && defined(CLEARCOAT) +color= vec3f(clearcoatOut.clearCoatRoughness); +#elif DEBUGMODE==68 && defined(CLEARCOAT) +color= vec3f(clearcoatOut.clearCoatNdotV); +#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) +color=subSurfaceOut.transmittance; +#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) +color=subSurfaceOut.refractionTransmittance; +#elif DEBUGMODE==72 +color= vec3f(microSurface); +#elif DEBUGMODE==73 +color=uniforms.vAlbedoColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) +color=uniforms.vReflectivityColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==75 +color=uniforms.vEmissiveColor; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) +color= vec3f(seo); +#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +color= vec3f(eho); +#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) +color= vec3f(energyConservationFactor); +#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +color=specularEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +color=clearcoatOut.clearCoatEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) +color=sheenOut.sheenEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==86 && defined(ALPHABLEND) +color= vec3f(luminanceOverAlpha); +#elif DEBUGMODE==87 +color= vec3f(alpha); +#elif DEBUGMODE==88 && defined(ALBEDO) +color= vec3f(albedoTexture.a); +#elif DEBUGMODE==89 +color=aoOut.ambientOcclusionColor; +#else +var stripeWidth: f32=30.;var stripePos: f32=abs(floor(input.position.x/stripeWidth));var whichColor: f32=((stripePos)%(2.));var color1: vec3f= vec3f(.6,.2,.2);var color2: vec3f= vec3f(.3,.1,.1);color=mix(color1,color2,whichColor); +#endif +color*=uniforms.vDebugMode.y; +#ifdef DEBUGMODE_NORMALIZE +color=normalize(color)*0.5+0.5; +#endif +#ifdef DEBUGMODE_GAMMA +color=toGammaSpaceVec3(color); +#endif +fragmentOutputs.color=vec4f(color,1.0); +#ifdef PREPASS +fragmentOutputs.fragData0=toLinearSpaceVec3(color); +fragmentOutputs.fragData1=vec4f(0.,0.,0.,0.); +#endif +#ifdef DEBUGMODE_FORCERETURN +return fragmentOutputs; +#endif +} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$58]) { + ShaderStore.IncludesShadersStoreWGSL[name$58] = shader$57; +} + +// Do not edit. +const name$57 = "pbrPixelShader"; +const shader$56 = `#define CUSTOM_FRAGMENT_BEGIN +#include[SCENE_MRT_COUNT] +#include +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE +#endif +#include +#include +#include[0..maxSimultaneousLights] +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef REFLECTION +#include +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#include +#include +#include +var albedoOpacityOut: albedoOpacityOutParams; +#ifdef ALBEDO +var albedoTexture: vec4f=textureSample(albedoSampler,albedoSamplerSampler,fragmentInputs.vAlbedoUV+uvOffset); +#endif +#ifdef BASEWEIGHT +var baseWeightTexture: vec4f=textureSample(baseWeightSampler,baseWeightSamplerSampler,fragmentInputs.vBaseWeightUV+uvOffset); +#endif +#ifdef OPACITY +var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset); +#endif +#ifdef DECAL +var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset); +#endif +albedoOpacityOut=albedoOpacityBlock( +uniforms.vAlbedoColor +#ifdef ALBEDO +,albedoTexture +,uniforms.vAlbedoInfos +#endif +,uniforms.baseWeight +#ifdef BASEWEIGHT +,baseWeightTexture +,uniforms.vBaseWeightInfos +#endif +#ifdef OPACITY +,opacityMap +,uniforms.vOpacityInfos +#endif +#ifdef DETAIL +,detailColor +,uniforms.vDetailInfos +#endif +#ifdef DECAL +,decalColor +,uniforms.vDecalInfos +#endif +);var surfaceAlbedo: vec3f=albedoOpacityOut.surfaceAlbedo;var alpha: f32=albedoOpacityOut.alpha; +#define CUSTOM_FRAGMENT_UPDATE_ALPHA +#include +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +var aoOut: ambientOcclusionOutParams; +#ifdef AMBIENT +var ambientOcclusionColorMap: vec3f=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb; +#endif +aoOut=ambientOcclusionBlock( +#ifdef AMBIENT +ambientOcclusionColorMap, +uniforms.vAmbientInfos +#endif +); +#include +#ifdef UNLIT +var diffuseBase: vec3f= vec3f(1.,1.,1.); +#else +var baseColor: vec3f=surfaceAlbedo;var reflectivityOut: reflectivityOutParams; +#if defined(REFLECTIVITY) +var surfaceMetallicOrReflectivityColorMap: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,fragmentInputs.vReflectivityUV+uvOffset);var baseReflectivity: vec4f=surfaceMetallicOrReflectivityColorMap; +#ifndef METALLICWORKFLOW +#ifdef REFLECTIVITY_GAMMA +surfaceMetallicOrReflectivityColorMap=toLinearSpaceVec4(surfaceMetallicOrReflectivityColorMap); +#endif +surfaceMetallicOrReflectivityColorMap=vec4f(surfaceMetallicOrReflectivityColorMap.rgb*uniforms.vReflectivityInfos.y,surfaceMetallicOrReflectivityColorMap.a); +#endif +#endif +#if defined(MICROSURFACEMAP) +var microSurfaceTexel: vec4f=textureSample(microSurfaceSampler,microSurfaceSamplerSampler,fragmentInputs.vMicroSurfaceSamplerUV+uvOffset)*uniforms.vMicroSurfaceSamplerInfos.y; +#endif +#ifdef METALLICWORKFLOW +var metallicReflectanceFactors: vec4f=uniforms.vMetallicReflectanceFactors; +#ifdef REFLECTANCE +var reflectanceFactorsMap: vec4f=textureSample(reflectanceSampler,reflectanceSamplerSampler,fragmentInputs.vReflectanceUV+uvOffset); +#ifdef REFLECTANCE_GAMMA +reflectanceFactorsMap=toLinearSpaceVec4(reflectanceFactorsMap); +#endif +metallicReflectanceFactors=vec4f(metallicReflectanceFactors.rgb*reflectanceFactorsMap.rgb,metallicReflectanceFactors.a); +#endif +#ifdef METALLIC_REFLECTANCE +var metallicReflectanceFactorsMap: vec4f=textureSample(metallicReflectanceSampler,metallicReflectanceSamplerSampler,fragmentInputs.vMetallicReflectanceUV+uvOffset); +#ifdef METALLIC_REFLECTANCE_GAMMA +metallicReflectanceFactorsMap=toLinearSpaceVec4(metallicReflectanceFactorsMap); +#endif +#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY +metallicReflectanceFactors=vec4f(metallicReflectanceFactors.rgb*metallicReflectanceFactorsMap.rgb,metallicReflectanceFactors.a); +#endif +metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; +#endif +#endif +reflectivityOut=reflectivityBlock( +uniforms.vReflectivityColor +#ifdef METALLICWORKFLOW +,surfaceAlbedo +,metallicReflectanceFactors +#endif +#ifdef REFLECTIVITY +,uniforms.vReflectivityInfos +,surfaceMetallicOrReflectivityColorMap +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +,aoOut.ambientOcclusionColor +#endif +#ifdef MICROSURFACEMAP +,microSurfaceTexel +#endif +#ifdef DETAIL +,detailColor +,uniforms.vDetailInfos +#endif +);var microSurface: f32=reflectivityOut.microSurface;var roughness: f32=reflectivityOut.roughness; +#ifdef METALLICWORKFLOW +surfaceAlbedo=reflectivityOut.surfaceAlbedo; +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; +#endif +#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +var alphaFresnelOut: alphaFresnelOutParams;alphaFresnelOut=alphaFresnelBlock( +normalW, +viewDirectionW, +alpha, +microSurface +);alpha=alphaFresnelOut.alpha; +#endif +#endif +#include +#ifdef ANISOTROPIC +var anisotropicOut: anisotropicOutParams; +#ifdef ANISOTROPIC_TEXTURE +var anisotropyMapData: vec3f=textureSample(anisotropySampler,anisotropySamplerSampler,fragmentInputs.vAnisotropyUV+uvOffset).rgb*uniforms.vAnisotropyInfos.y; +#endif +anisotropicOut=anisotropicBlock( +uniforms.vAnisotropy, +roughness, +#ifdef ANISOTROPIC_TEXTURE +anisotropyMapData, +#endif +TBN, +normalW, +viewDirectionW +); +#endif +#ifdef REFLECTION +var reflectionOut: reflectionOutParams; +#ifndef USE_CUSTOM_REFLECTION +reflectionOut=reflectionBlock( +fragmentInputs.vPositionW +,normalW +,alphaG +,uniforms.vReflectionMicrosurfaceInfos +,uniforms.vReflectionInfos +,uniforms.vReflectionColor +#ifdef ANISOTROPIC +,anisotropicOut +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +,NdotVUnclamped +#endif +#ifdef LINEARSPECULARREFLECTION +,roughness +#endif +,reflectionSampler +,reflectionSamplerSampler +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +,fragmentInputs.vEnvironmentIrradiance +#endif +#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D)) +,uniforms.reflectionMatrix +#endif +#ifdef USEIRRADIANCEMAP +,irradianceSampler +,irradianceSamplerSampler +#endif +#ifndef LODBASEDMICROSFURACE +,reflectionLowSampler +,reflectionLowSamplerSampler +,reflectionHighSampler +,reflectionHighSamplerSampler +#endif +#ifdef REALTIME_FILTERING +,uniforms.vReflectionFilteringInfo +#ifdef IBL_CDF_FILTERING +,icdfSampler +,icdfSamplerSampler +#endif +#endif +); +#else +#define CUSTOM_REFLECTION +#endif +#endif +#include +#ifdef SHEEN +var sheenOut: sheenOutParams; +#ifdef SHEEN_TEXTURE +var sheenMapData: vec4f=textureSample(sheenSampler,sheenSamplerSampler,fragmentInputs.vSheenUV+uvOffset); +#endif +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +var sheenMapRoughnessData: vec4f=textureSample(sheenRoughnessSampler,sheenRoughnessSamplerSampler,fragmentInputs.vSheenRoughnessUV+uvOffset)*uniforms.vSheenInfos.w; +#endif +sheenOut=sheenBlock( +uniforms.vSheenColor +#ifdef SHEEN_ROUGHNESS +,uniforms.vSheenRoughness +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +,sheenMapRoughnessData +#endif +#endif +,roughness +#ifdef SHEEN_TEXTURE +,sheenMapData +,uniforms.vSheenInfos.y +#endif +,reflectance +#ifdef SHEEN_LINKWITHALBEDO +,baseColor +,surfaceAlbedo +#endif +#ifdef ENVIRONMENTBRDF +,NdotV +,environmentBrdf +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +,AARoughnessFactors +,uniforms.vReflectionMicrosurfaceInfos +,uniforms.vReflectionInfos +,uniforms.vReflectionColor +,uniforms.vLightingIntensity +,reflectionSampler +,reflectionSamplerSampler +,reflectionOut.reflectionCoords +,NdotVUnclamped +#ifndef LODBASEDMICROSFURACE +,reflectionLowSampler +,reflectionLowSamplerSampler +,reflectionHighSampler +,reflectionHighSamplerSampler +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +,seo +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +,eho +#endif +#endif +); +#ifdef SHEEN_LINKWITHALBEDO +surfaceAlbedo=sheenOut.surfaceAlbedo; +#endif +#endif +#ifdef CLEARCOAT +#ifdef CLEARCOAT_TEXTURE +var clearCoatMapData: vec2f=textureSample(clearCoatSampler,clearCoatSamplerSampler,fragmentInputs.vClearCoatUV+uvOffset).rg*uniforms.vClearCoatInfos.y; +#endif +#endif +#ifdef IRIDESCENCE +var iridescenceOut: iridescenceOutParams; +#ifdef IRIDESCENCE_TEXTURE +var iridescenceMapData: vec2f=textureSample(iridescenceSampler,iridescenceSamplerSampler,fragmentInputs.vIridescenceUV+uvOffset).rg*uniforms.vIridescenceInfos.y; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +var iridescenceThicknessMapData: vec2f=textureSample(iridescenceThicknessSampler,iridescenceThicknessSamplerSampler,fragmentInputs.vIridescenceThicknessUV+uvOffset).rg*uniforms.vIridescenceInfos.w; +#endif +iridescenceOut=iridescenceBlock( +uniforms.vIridescenceParams +,NdotV +,specularEnvironmentR0 +#ifdef IRIDESCENCE_TEXTURE +,iridescenceMapData +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +,iridescenceThicknessMapData +#endif +#ifdef CLEARCOAT +,NdotVUnclamped +,uniforms.vClearCoatParams +#ifdef CLEARCOAT_TEXTURE +,clearCoatMapData +#endif +#endif +);var iridescenceIntensity: f32=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; +#endif +var clearcoatOut: clearcoatOutParams; +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +var clearCoatMapRoughnessData: vec4f=textureSample(clearCoatRoughnessSampler,clearCoatRoughnessSamplerSampler,fragmentInputs.vClearCoatRoughnessUV+uvOffset)*uniforms.vClearCoatInfos.w; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +var clearCoatTintMapData: vec4f=textureSample(clearCoatTintSampler,clearCoatTintSamplerSampler,fragmentInputs.vClearCoatTintUV+uvOffset); +#endif +#ifdef CLEARCOAT_BUMP +var clearCoatBumpMapData: vec4f=textureSample(clearCoatBumpSampler,clearCoatBumpSamplerSampler,fragmentInputs.vClearCoatBumpUV+uvOffset); +#endif +clearcoatOut=clearcoatBlock( +fragmentInputs.vPositionW +,geometricNormalW +,viewDirectionW +,uniforms.vClearCoatParams +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +,clearCoatMapRoughnessData +#endif +,specularEnvironmentR0 +#ifdef CLEARCOAT_TEXTURE +,clearCoatMapData +#endif +#ifdef CLEARCOAT_TINT +,uniforms.vClearCoatTintParams +,uniforms.clearCoatColorAtDistance +,uniforms.vClearCoatRefractionParams +#ifdef CLEARCOAT_TINT_TEXTURE +,clearCoatTintMapData +#endif +#endif +#ifdef CLEARCOAT_BUMP +,uniforms.vClearCoatBumpInfos +,clearCoatBumpMapData +,fragmentInputs.vClearCoatBumpUV +#if defined(TANGENT) && defined(NORMAL) +,mat3x3(input.vTBN0,input.vTBN1,input.vTBN2) +#else +,uniforms.vClearCoatTangentSpaceParams +#endif +#ifdef OBJECTSPACE_NORMALMAP +,uniforms.normalMatrix +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +,faceNormal +#endif +#ifdef REFLECTION +,uniforms.vReflectionMicrosurfaceInfos +,uniforms.vReflectionInfos +,uniforms.vReflectionColor +,uniforms.vLightingIntensity +,reflectionSampler +,reflectionSamplerSampler +#ifndef LODBASEDMICROSFURACE +,reflectionLowSampler +,reflectionLowSamplerSampler +,reflectionHighSampler +,reflectionHighSamplerSampler +#endif +#ifdef REALTIME_FILTERING +,uniforms.vReflectionFilteringInfo +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +,select(-1.,1.,fragmentInputs.frontFacing) +#endif +); +#else +clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; +#endif +#include +var subSurfaceOut: subSurfaceOutParams; +#ifdef SUBSURFACE +#ifdef SS_THICKNESSANDMASK_TEXTURE +var thicknessMap: vec4f=textureSample(thicknessSampler,thicknessSamplerSampler,fragmentInputs.vThicknessUV+uvOffset); +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +var refractionIntensityMap: vec4f=textureSample(refractionIntensitySampler,refractionIntensitySamplerSampler,fragmentInputs.vRefractionIntensityUV+uvOffset); +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +var translucencyIntensityMap: vec4f=textureSample(translucencyIntensitySampler,translucencyIntensitySamplerSampler,fragmentInputs.vTranslucencyIntensityUV+uvOffset); +#endif +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE +var translucencyColorMap: vec4f=textureSample(translucencyColorSampler,translucencyColorSamplerSampler,fragmentInputs.vTranslucencyColorUV+uvOffset); +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA +translucencyColorMap=toLinearSpaceVec4(translucencyColorMap); +#endif +#endif +subSurfaceOut=subSurfaceBlock( +uniforms.vSubSurfaceIntensity +,uniforms.vThicknessParam +,uniforms.vTintColor +,normalW +,specularEnvironmentReflectance +#ifdef SS_THICKNESSANDMASK_TEXTURE +,thicknessMap +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +,refractionIntensityMap +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +,translucencyIntensityMap +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +,uniforms.reflectionMatrix +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +,reflectionOut.irradianceVector +#endif +#if defined(REALTIME_FILTERING) +,reflectionSampler +,reflectionSamplerSampler +,vReflectionFilteringInfo +#ifdef IBL_CDF_FILTERING +,icdfSampler +,icdfSamplerSampler +#endif +#endif +#endif +#ifdef USEIRRADIANCEMAP +,irradianceSampler +,irradianceSamplerSampler +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +,surfaceAlbedo +#endif +#ifdef SS_REFRACTION +,fragmentInputs.vPositionW +,viewDirectionW +,scene.view +,uniforms.vRefractionInfos +,uniforms.refractionMatrix +,uniforms.vRefractionMicrosurfaceInfos +,uniforms.vLightingIntensity +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +,alpha +#endif +#ifdef SS_LODINREFRACTIONALPHA +,NdotVUnclamped +#endif +#ifdef SS_LINEARSPECULARREFRACTION +,roughness +#endif +,alphaG +,refractionSampler +,refractionSamplerSampler +#ifndef LODBASEDMICROSFURACE +,refractionLowSampler +,refractionLowSamplerSampler +,refractionHighSampler +,refractionHighSamplerSampler +#endif +#ifdef ANISOTROPIC +,anisotropicOut +#endif +#ifdef REALTIME_FILTERING +,uniforms.vRefractionFilteringInfo +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,uniforms.vRefractionPosition +,uniforms.vRefractionSize +#endif +#ifdef SS_DISPERSION +,dispersion +#endif +#endif +#ifdef SS_TRANSLUCENCY +,uniforms.vDiffusionDistance +,uniforms.vTranslucencyColor +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE +,translucencyColorMap +#endif +#endif +); +#ifdef SS_REFRACTION +surfaceAlbedo=subSurfaceOut.surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha=subSurfaceOut.alpha; +#endif +#endif +#else +subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; +#endif +#include +#include[0..maxSimultaneousLights] +#include +#endif +#include +#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION +#include +#include +#include(color,finalColor) +#include +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +#include +#endif +#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY) +fragmentOutputs.color=finalColor; +#endif +#include +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+finalColor.rgb*finalColor.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-finalColor.a));} else {fragmentOutputs.backColor+=finalColor;} +#endif +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$57]) { + ShaderStore.ShadersStoreWGSL[name$57] = shader$56; +} +/** @internal */ +const pbrPixelShaderWGSL = { name: name$57, shader: shader$56 }; + +const pbr_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + pbrPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$56 = "decalVertexDeclaration"; +const shader$55 = `#ifdef DECAL +uniform vec4 vDecalInfos;uniform mat4 decalMatrix; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$56]) { + ShaderStore.IncludesShadersStore[name$56] = shader$55; +} + +// Do not edit. +const name$55 = "pbrVertexDeclaration"; +const shader$54 = `uniform mat4 view;uniform mat4 viewProjection; +#ifdef MULTIVIEW +mat4 viewProjectionR; +#endif +#ifdef ALBEDO +uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; +#endif +#ifdef BASEWEIGHT +uniform mat4 baseWeightMatrix;uniform vec2 vBaseWeightInfos; +#endif +#ifdef AMBIENT +uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; +#endif +#ifdef OPACITY +uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; +#endif +#ifdef REFLECTIVITY +uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; +#endif +#ifdef METALLIC_REFLECTANCE +uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; +#endif +#ifdef REFLECTANCE +uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; +#endif +#ifdef MICROSURFACEMAP +uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; +#endif +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform vec4 vClearCoatInfos; +#endif +#ifdef CLEARCOAT_TEXTURE +uniform mat4 clearCoatMatrix; +#endif +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS +uniform mat4 clearCoatRoughnessMatrix; +#endif +#ifdef CLEARCOAT_BUMP +uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; +#endif +#ifdef CLEARCOAT_TINT_TEXTURE +uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; +#endif +#endif +#ifdef IRIDESCENCE +#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) +uniform vec4 vIridescenceInfos; +#endif +#ifdef IRIDESCENCE_TEXTURE +uniform mat4 iridescenceMatrix; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +uniform mat4 iridescenceThicknessMatrix; +#endif +#endif +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_TEXTURE +uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; +#endif +#endif +#ifdef SHEEN +#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) +uniform vec4 vSheenInfos; +#endif +#ifdef SHEEN_TEXTURE +uniform mat4 sheenMatrix; +#endif +#ifdef SHEEN_TEXTURE_ROUGHNESS +uniform mat4 sheenRoughnessMatrix; +#endif +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE +uniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix; +#endif +#endif +#ifdef NORMAL +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; +#else +uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; +#endif +#endif +#endif +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos;uniform mat4 detailMatrix; +#endif +#include +#define ADDITIONAL_VERTEX_DECLARATION +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$55]) { + ShaderStore.IncludesShadersStore[name$55] = shader$54; +} + +// Do not edit. +const name$54 = "pbrUboDeclaration"; +const shader$53 = `layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec2 vBaseWeightInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 baseWeightMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;float baseWeight;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; +#define ADDITIONAL_UBO_DECLARATION +}; +#include +#include +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$54]) { + ShaderStore.IncludesShadersStore[name$54] = shader$53; +} + +// Do not edit. +const name$53 = "uvAttributeDeclaration"; +const shader$52 = `#ifdef UV{X} +attribute vec2 uv{X}; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$53]) { + ShaderStore.IncludesShadersStore[name$53] = shader$52; +} + +// Do not edit. +const name$52 = "mainUVVaryingDeclaration"; +const shader$51 = `#ifdef MAINUV{X} +varying vec2 vMainUV{X}; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$52]) { + ShaderStore.IncludesShadersStore[name$52] = shader$51; +} + +// Do not edit. +const name$51 = "prePassVertexDeclaration"; +const shader$50 = `#ifdef PREPASS +#ifdef PREPASS_LOCAL_POSITION +varying vec3 vPosition; +#endif +#ifdef PREPASS_DEPTH +varying vec3 vViewPos; +#endif +#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$51]) { + ShaderStore.IncludesShadersStore[name$51] = shader$50; +} + +// Do not edit. +const name$50 = "samplerVertexDeclaration"; +const shader$4$ = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +varying vec2 v_VARYINGNAME_UV; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$50]) { + ShaderStore.IncludesShadersStore[name$50] = shader$4$; +} + +// Do not edit. +const name$4$ = "harmonicsFunctions"; +const shader$4_ = `#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 ++ vSphericalL1_1*(normal.y) ++ vSphericalL10*(normal.z) ++ vSphericalL11*(normal.x) ++ vSphericalL2_2*(normal.y*normal.x) ++ vSphericalL2_1*(normal.y*normal.z) ++ vSphericalL20*((3.0*normal.z*normal.z)-1.0) ++ vSphericalL21*(normal.z*normal.x) ++ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} +#else +vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4$]) { + ShaderStore.IncludesShadersStore[name$4$] = shader$4_; +} + +// Do not edit. +const name$4_ = "bumpVertexDeclaration"; +const shader$4Z = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +varying mat3 vTBN; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4_]) { + ShaderStore.IncludesShadersStore[name$4_] = shader$4Z; +} + +// Do not edit. +const name$4Z = "prePassVertex"; +const shader$4Y = `#ifdef PREPASS_DEPTH +vViewPos=(view*worldPos).rgb; +#endif +#ifdef PREPASS_LOCAL_POSITION +vPosition=positionUpdated.xyz; +#endif +#if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*worldPos; +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4Z]) { + ShaderStore.IncludesShadersStore[name$4Z] = shader$4Y; +} + +// Do not edit. +const name$4Y = "uvVariableDeclaration"; +const shader$4X = `#if !defined(UV{X}) && defined(MAINUV{X}) +vec2 uv{X}=vec2(0.,0.); +#endif +#ifdef MAINUV{X} +vMainUV{X}=uv{X}; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4Y]) { + ShaderStore.IncludesShadersStore[name$4Y] = shader$4X; +} + +// Do not edit. +const name$4X = "samplerVertexImplementation"; +const shader$4W = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +if (v_INFONAME_==0.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} +#ifdef UV2 +else if (v_INFONAME_==1.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2Updated,1.0,0.0));} +#endif +#ifdef UV3 +else if (v_INFONAME_==2.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} +#endif +#ifdef UV4 +else if (v_INFONAME_==3.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} +#endif +#ifdef UV5 +else if (v_INFONAME_==4.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} +#endif +#ifdef UV6 +else if (v_INFONAME_==5.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4X]) { + ShaderStore.IncludesShadersStore[name$4X] = shader$4W; +} + +// Do not edit. +const name$4W = "bumpVertex"; +const shader$4V = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4W]) { + ShaderStore.IncludesShadersStore[name$4W] = shader$4V; +} + +// Do not edit. +const name$4V = "pbrVertexShader"; +const shader$4U = `#define CUSTOM_VERTEX_EXTENSION +precision highp float; +#include<__decl__pbrVertex> +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include[2..7] +#include[1..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +#include +#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) +#include(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) +#endif +#ifdef SUBSURFACE +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor) +#endif +varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#include +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef UV2 +vec2 uv2Updated=uv2; +#endif +#ifdef VERTEXCOLOR +vec4 colorUpdated=color; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include +#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); +#ifdef PREPASS +#include +#endif +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#if DEBUGMODE>0 +vClipSpacePosition=gl_Position; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2Updated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#ifdef MAINUV2 +vMainUV2=uv2Updated; +#endif +#include[3..7] +#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) +#include(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight,_MATRIXNAME_,baseWeight,_INFONAME_,BaseWeightInfos.x) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z) +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) +#endif +#ifdef SUBSURFACE +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) +#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x) +#endif +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$4V]) { + ShaderStore.ShadersStore[name$4V] = shader$4U; +} +/** @internal */ +const pbrVertexShader = { name: name$4V, shader: shader$4U }; + +const pbr_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + pbrVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$4U = "prePassDeclaration"; +const shader$4T = `#ifdef PREPASS +#extension GL_EXT_draw_buffers : require +layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; +#ifdef PREPASS_LOCAL_POSITION +varying highp vec3 vPosition; +#endif +#ifdef PREPASS_DEPTH +varying highp vec3 vViewPos; +#endif +#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) +varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4U]) { + ShaderStore.IncludesShadersStore[name$4U] = shader$4T; +} + +// Do not edit. +const name$4T = "oitDeclaration"; +const shader$4S = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY +#extension GL_EXT_draw_buffers : require +layout(location=0) out vec2 depth; +layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; +#define MAX_DEPTH 99999.0 +highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4T]) { + ShaderStore.IncludesShadersStore[name$4T] = shader$4S; +} + +// Do not edit. +const name$4S = "decalFragmentDeclaration"; +const shader$4R = `#ifdef DECAL +uniform vec4 vDecalInfos; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4S]) { + ShaderStore.IncludesShadersStore[name$4S] = shader$4R; +} + +// Do not edit. +const name$4R = "pbrFragmentDeclaration"; +const shader$4Q = `uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform float baseWeight;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; +#ifdef ALBEDO +uniform vec2 vAlbedoInfos; +#endif +#ifdef BASEWEIGHT +uniform vec2 vBaseWeightInfos; +#endif +#ifdef AMBIENT +uniform vec4 vAmbientInfos; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#ifdef OPACITY +uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos; +#endif +#ifdef REFLECTIVITY +uniform vec3 vReflectivityInfos; +#endif +#ifdef MICROSURFACEMAP +uniform vec2 vMicroSurfaceSamplerInfos; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) +uniform mat4 view; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos; +#ifdef REALTIME_FILTERING +uniform vec2 vReflectionFilteringInfo; +#endif +uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; +#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) +uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; +#endif +#ifdef CLEARCOAT +uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; +#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform vec4 vClearCoatInfos; +#endif +#ifdef CLEARCOAT_TEXTURE +uniform mat4 clearCoatMatrix; +#endif +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS +uniform mat4 clearCoatRoughnessMatrix; +#endif +#ifdef CLEARCOAT_BUMP +uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; +#endif +#ifdef CLEARCOAT_TINT +uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; +#ifdef CLEARCOAT_TINT_TEXTURE +uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; +#endif +#endif +#endif +#ifdef IRIDESCENCE +uniform vec4 vIridescenceParams; +#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) +uniform vec4 vIridescenceInfos; +#endif +#ifdef IRIDESCENCE_TEXTURE +uniform mat4 iridescenceMatrix; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +uniform mat4 iridescenceThicknessMatrix; +#endif +#endif +#ifdef ANISOTROPIC +uniform vec3 vAnisotropy; +#ifdef ANISOTROPIC_TEXTURE +uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; +#endif +#endif +#ifdef SHEEN +uniform vec4 vSheenColor; +#ifdef SHEEN_ROUGHNESS +uniform float vSheenRoughness; +#endif +#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) +uniform vec4 vSheenInfos; +#endif +#ifdef SHEEN_TEXTURE +uniform mat4 sheenMatrix; +#endif +#ifdef SHEEN_TEXTURE_ROUGHNESS +uniform mat4 sheenRoughnessMatrix; +#endif +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; +#ifdef REALTIME_FILTERING +uniform vec2 vRefractionFilteringInfo; +#endif +#ifdef SS_DISPERSION +uniform float dispersion; +#endif +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; +#endif +uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor; +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE +uniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix; +#endif +#endif +#ifdef PREPASS +#ifdef SS_SCATTERING +uniform float scatteringDiffusionProfile; +#endif +#endif +#if DEBUGMODE>0 +uniform vec2 vDebugMode; +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos; +#endif +#include +#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; +#else +uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; +#endif +#endif +#define ADDITIONAL_FRAGMENT_DECLARATION +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4R]) { + ShaderStore.IncludesShadersStore[name$4R] = shader$4Q; +} + +// Do not edit. +const name$4Q = "pbrFragmentExtraDeclaration"; +const shader$4P = `varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#include[1..7] +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4Q]) { + ShaderStore.IncludesShadersStore[name$4Q] = shader$4P; +} + +// Do not edit. +const name$4P = "samplerFragmentDeclaration"; +const shader$4O = `#ifdef _DEFINENAME_ +#if _DEFINENAME_DIRECTUV==1 +#define v_VARYINGNAME_UV vMainUV1 +#elif _DEFINENAME_DIRECTUV==2 +#define v_VARYINGNAME_UV vMainUV2 +#elif _DEFINENAME_DIRECTUV==3 +#define v_VARYINGNAME_UV vMainUV3 +#elif _DEFINENAME_DIRECTUV==4 +#define v_VARYINGNAME_UV vMainUV4 +#elif _DEFINENAME_DIRECTUV==5 +#define v_VARYINGNAME_UV vMainUV5 +#elif _DEFINENAME_DIRECTUV==6 +#define v_VARYINGNAME_UV vMainUV6 +#else +varying vec2 v_VARYINGNAME_UV; +#endif +uniform sampler2D _SAMPLERNAME_Sampler; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4P]) { + ShaderStore.IncludesShadersStore[name$4P] = shader$4O; +} + +// Do not edit. +const name$4O = "samplerFragmentAlternateDeclaration"; +const shader$4N = `#ifdef _DEFINENAME_ +#if _DEFINENAME_DIRECTUV==1 +#define v_VARYINGNAME_UV vMainUV1 +#elif _DEFINENAME_DIRECTUV==2 +#define v_VARYINGNAME_UV vMainUV2 +#elif _DEFINENAME_DIRECTUV==3 +#define v_VARYINGNAME_UV vMainUV3 +#elif _DEFINENAME_DIRECTUV==4 +#define v_VARYINGNAME_UV vMainUV4 +#elif _DEFINENAME_DIRECTUV==5 +#define v_VARYINGNAME_UV vMainUV5 +#elif _DEFINENAME_DIRECTUV==6 +#define v_VARYINGNAME_UV vMainUV6 +#else +varying vec2 v_VARYINGNAME_UV; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4O]) { + ShaderStore.IncludesShadersStore[name$4O] = shader$4N; +} + +// Do not edit. +const name$4N = "pbrFragmentSamplersDeclaration"; +const shader$4M = `#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) +#include(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform sampler2D clearCoatRoughnessSampler; +#endif +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) +uniform sampler2D sheenRoughnessSampler; +#endif +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +#define sampleReflection(s,c) textureCube(s,c) +uniform samplerCube reflectionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#ifdef USEIRRADIANCEMAP +uniform samplerCube irradianceSampler; +#endif +#else +#define sampleReflection(s,c) texture2D(s,c) +uniform sampler2D reflectionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; +#endif +#ifdef USEIRRADIANCEMAP +uniform sampler2D irradianceSampler; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#endif +#ifdef ENVIRONMENTBRDF +uniform sampler2D environmentBrdfSampler; +#endif +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +uniform sampler2D areaLightsLTC1Sampler;uniform sampler2D areaLightsLTC2Sampler; +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +#ifdef SS_REFRACTIONMAP_3D +#define sampleRefraction(s,c) textureCube(s,c) +uniform samplerCube refractionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; +#endif +#else +#define sampleRefraction(s,c) texture2D(s,c) +uniform sampler2D refractionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; +#endif +#endif +#endif +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor) +#endif +#ifdef IBL_CDF_FILTERING +uniform sampler2D icdfSampler; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4N]) { + ShaderStore.IncludesShadersStore[name$4N] = shader$4M; +} + +// Do not edit. +const name$4M = "subSurfaceScatteringFunctions"; +const shader$4L = `bool testLightingForSSS(float diffusionProfile) +{return diffusionProfile<1.;}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4M]) { + ShaderStore.IncludesShadersStore[name$4M] = shader$4L; +} + +// Do not edit. +const name$4L = "importanceSampling"; +const shader$4K = `vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { +float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4L]) { + ShaderStore.IncludesShadersStore[name$4L] = shader$4K; +} + +// Do not edit. +const name$4K = "pbrHelperFunctions"; +const shader$4J = `#define MINIMUMVARIANCE 0.0005 +float convertRoughnessToAverageSlope(float roughness) +{return square(roughness)+MINIMUMVARIANCE;} +float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} +vec2 getAARoughnessFactors(vec3 normalVector) { +#ifdef SPECULARAA +vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); +#else +return vec2(0.); +#endif +} +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_LEGACY +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection;if (anisotropy>=0.0) {anisotropicFrameDirection=B;} else {anisotropicFrameDirection=T;} +vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} +#else +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} +#endif +#endif +#if defined(CLEARCOAT) || defined(SS_REFRACTION) +vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} +vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} +vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} +vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), +cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), +clearCoatIntensity);return clearCoatAbsorption;} +#endif +#ifdef MICROSURFACEAUTOMATIC +float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) +{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4K]) { + ShaderStore.IncludesShadersStore[name$4K] = shader$4J; +} + +// Do not edit. +const name$4J = "pbrDirectLightingSetupFunctions"; +const shader$4I = `struct preLightingInfo +{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; +#ifdef IRIDESCENCE +float iridescenceIntensity; +#endif +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +vec3 areaLightDiffuse; +#ifdef SPECULARTERM +vec3 areaLightSpecular;vec4 areaLightFresnel; +#endif +#endif +};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N,vec3 posW) {preLightingInfo result;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; +#ifdef SPECULARTERM +result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); +#endif +return result;} +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +#include +preLightingInfo computeAreaPreLightingInfo(sampler2D ltc1,sampler2D ltc2,vec3 viewDirectionW,vec3 vNormal,vec3 vPosition,vec4 lightData,vec3 halfWidth,vec3 halfHeight,float roughness ) +{preLightingInfo result;result.lightOffset=lightData.xyz-vPosition;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);areaLightData data=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc2,viewDirectionW,vNormal,vPosition,lightData.xyz,halfWidth,halfHeight,roughness); +#ifdef SPECULARTERM +result.areaLightFresnel=data.Fresnel;result.areaLightSpecular=data.Specular; +#endif +result.areaLightDiffuse=data.Diffuse;return result;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4J]) { + ShaderStore.IncludesShadersStore[name$4J] = shader$4I; +} + +// Do not edit. +const name$4I = "pbrDirectLightingFalloffFunctions"; +const shader$4H = `float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) +{return max(0.,1.0-length(lightOffset)/range);} +float computeDistanceLightFalloff_Physical(float lightDistanceSquared) +{return 1.0/maxEps(lightDistanceSquared);} +float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) +{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} +float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDistanceLightFalloff_Physical(lightDistanceSquared); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); +#else +return computeDistanceLightFalloff_Standard(lightOffset,range); +#endif +} +float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) +{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) +{falloff=max(0.,pow(cosAngle,exponent));} +return falloff;} +float computeDirectionalLightFalloff_IES(vec3 lightDirection,vec3 directionToLightCenterW,sampler2D iesLightSampler) +{float cosAngle=dot(-lightDirection,directionToLightCenterW);float angle=acos(cosAngle)/PI;return texture2D(iesLightSampler,vec2(angle,0.)).r;} +float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) +{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; +float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} +float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) +{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} +float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); +#else +return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); +#endif +}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4I]) { + ShaderStore.IncludesShadersStore[name$4I] = shader$4H; +} + +// Do not edit. +const name$4H = "pbrBRDFFunctions"; +const shader$4G = `#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} +#endif +#ifdef ENVIRONMENTBRDF +vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); +#ifdef ENVIRONMENTBRDF_RGBD +brdfLookup.rgb=fromRGBD(brdfLookup.rgba); +#endif +return brdfLookup.rgb;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; +#endif +return reflectance;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; +#endif +return reflectance;} +#endif +/* NOT USED +#if defined(SHEEN) && defined(SHEEN_SOFTER) +float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) +{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} +#endif +*/ +#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) +vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) +{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +/** +* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. +* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table +*/ +vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} +#endif +vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +#ifdef CLEARCOAT +vec3 getR0RemappedForClearCoat(vec3 f0) { +#ifdef CLEARCOAT_DEFAULTIOR +#ifdef MOBILE +return saturate(f0*(f0*0.526868+0.529324)-0.0482256); +#else +return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); +#endif +#else +vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); +#endif +} +#endif +#ifdef IRIDESCENCE +const mat3 XYZ_TO_REC709=mat3( +3.2404542,-0.9692660, 0.0556434, +-1.5371385, 1.8760108,-0.2040259, +-0.4985314, 0.0415560, 1.0572252 +);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} +vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} +float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} +vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} +vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} +float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0 +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +float radicalInverse_VdC(uint bits) +{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } +vec2 hammersley(uint i,uint N) +{return vec2(float(i)/float(N),radicalInverse_VdC(i));} +#else +float vanDerCorpus(int n,int base) +{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) +{if(n>0) +{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} +return result;} +vec2 hammersley(int i,int N) +{return vec2(float(i)/float(N),vanDerCorpus(i,2));} +#endif +float log4(float x) {return log2(x)/2.;} +vec3 uv_to_normal(vec2 uv) {vec3 N;vec2 uvRange=uv;float theta=uvRange.x*2.0*PI;float phi=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;} +const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; +#define inline +vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo +#ifdef IBL_CDF_FILTERING +,sampler2D icdfSampler +#endif +) +{vec3 n=normalize(inputN);vec3 result=vec3(0.0); +#ifndef IBL_CDF_FILTERING +vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n); +#endif +float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +for(uint i=0u; i0.) { +#ifdef IBL_CDF_FILTERING +float pdf=textureLod(icdfSampler,T,0.0).z;vec3 c=textureCubeLodEXT(inputTexture,Ls,0.0).rgb; +#else +float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; +#endif +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +#ifdef IBL_CDF_FILTERING +vec3 light=pdf<1e-6 ? vec3(0.0) : vec3(1.0)/vec3(pdf)*c;result+=NoL*light; +#else +result+=c; +#endif +}} +result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} +#define inline +vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) +{vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; +if (alphaG==0.) { +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +for(uint i=0u; i0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +result+=c*NoL;}} +result=result/weight;return result;}} +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4G]) { + ShaderStore.IncludesShadersStore[name$4G] = shader$4F; +} + +// Do not edit. +const name$4F = "pbrDirectLightingFunctions"; +const shader$4E = `#define CLEARCOATREFLECTANCE90 1.0 +struct lightingInfo +{vec3 diffuse; +#ifdef SPECULARTERM +vec3 specular; +#endif +#ifdef CLEARCOAT +vec4 clearCoat; +#endif +#ifdef SHEEN +vec3 sheen; +#endif +};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { +#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) +float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; +#else +return roughness; +#endif +} +vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +vec3 computeAreaDiffuseLighting(preLightingInfo info,vec3 lightColor) {return info.areaLightDiffuse*lightColor;} +#endif +vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} +#define inline +vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} +#ifdef SS_TRANSLUCENCY +vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance,float transmittanceIntensity,vec3 surfaceAlbedo) {vec3 transmittanceNdotL=vec3(0.);float NdotL=absEps(info.NdotLUnclamped);if (info.NdotLUnclamped<0.0) {float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);} +float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return (transmittanceNdotL/PI+(1.0-transmittanceIntensity)*diffuseTerm*surfaceAlbedo*info.NdotL)*info.attenuation*lightColor;} +#endif +#ifdef SPECULARTERM +vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); +#ifdef BRDF_V_HEIGHT_CORRELATED +float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); +#else +float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); +#endif +vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) +vec3 computeAreaSpecularLighting(preLightingInfo info,vec3 specularColor) {vec3 fresnel=( specularColor*info.areaLightFresnel.x+( vec3( 1.0 )-specularColor )*info.areaLightFresnel.y );return specularColor*fresnel*info.areaLightSpecular;} +#endif +#endif +#ifdef ANISOTROPIC +vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef CLEARCOAT +vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( +clearCoatTerm*info.attenuation*NccdotL*lightColor, +1.0-fresnel +);} +vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} +#endif +#ifdef SHEEN +vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER +float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); +#else */ +float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ +float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4F]) { + ShaderStore.IncludesShadersStore[name$4F] = shader$4E; +} + +// Do not edit. +const name$4E = "pbrIBLFunctions"; +const shader$4D = `#if defined(REFLECTION) || defined(SS_REFRACTION) +float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} +float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} +#endif +#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) +float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} +#endif +#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) +float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} +#endif +#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) +#define UNPACK_LOD(x) (1.0-x)*255.0 +float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4E]) { + ShaderStore.IncludesShadersStore[name$4E] = shader$4D; +} + +// Do not edit. +const name$4D = "bumpFragmentMainFunctions"; +const shader$4C = `#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) +#if defined(TANGENT) && defined(NORMAL) +varying mat3 vTBN; +#endif +#ifdef OBJECTSPACE_NORMALMAP +uniform mat4 normalMatrix; +#if defined(WEBGL2) || defined(WEBGPU) +mat4 toNormalMatrix(mat4 wMatrix) +{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;} +#else +mat4 toNormalMatrix(mat4 m) +{float +a00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3], +a10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3], +a20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3], +a30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3], +b00=a00*a11-a01*a10, +b01=a00*a12-a02*a10, +b02=a00*a13-a03*a10, +b03=a01*a12-a02*a11, +b04=a01*a13-a03*a11, +b05=a02*a13-a03*a12, +b06=a20*a31-a21*a30, +b07=a20*a32-a22*a30, +b08=a20*a33-a23*a30, +b09=a21*a32-a22*a31, +b10=a21*a33-a23*a31, +b11=a22*a33-a23*a32, +det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4( +a11*b11-a12*b10+a13*b09, +a02*b10-a01*b11-a03*b09, +a31*b05-a32*b04+a33*b03, +a22*b04-a21*b05-a23*b03, +a12*b08-a10*b11-a13*b07, +a00*b11-a02*b08+a03*b07, +a32*b02-a30*b05-a33*b01, +a20*b05-a22*b02+a23*b01, +a10*b10-a11*b08+a13*b06, +a01*b08-a00*b10-a03*b06, +a30*b04-a31*b02+a33*b00, +a21*b02-a20*b04-a23*b00, +a11*b07-a10*b09-a12*b06, +a00*b09-a01*b07+a02*b06, +a31*b01-a30*b03-a32*b00, +a20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0], +mi[0][1],mi[1][1],mi[2][1],mi[3][1], +mi[0][2],mi[1][2],mi[2][2],mi[3][2], +mi[0][3],mi[1][3],mi[2][3],mi[3][3]);} +#endif +#endif +vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale) +{ +#ifdef NORMALXYSCALE +normal=normalize(normal*vec3(scale,scale,1.0)); +#endif +return normalize(cotangentFrame*normal);} +vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale) +{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);} +mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams) +{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4D]) { + ShaderStore.IncludesShadersStore[name$4D] = shader$4C; +} +/** @internal */ +const bumpFragmentMainFunctions = { name: name$4D, shader: shader$4C }; + +const bumpFragmentMainFunctions$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bumpFragmentMainFunctions +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$4C = "bumpFragmentFunctions"; +const shader$4B = `#if defined(BUMP) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) +#endif +#if defined(DETAIL) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) +#endif +#if defined(BUMP) && defined(PARALLAX) +const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; icurrRayHeight) +{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} +else +{currRayHeight-=stepSize;vLastOffset=vCurrOffset; +#ifdef PARALLAX_RHS +vCurrOffset-=stepSize*vMaxOffset; +#else +vCurrOffset+=stepSize*vMaxOffset; +#endif +lastSampledHeight=currSampledHeight;}} +return vCurrOffset;} +vec2 parallaxOffset(vec3 viewDir,float heightScale) +{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height; +#ifdef PARALLAX_RHS +return texCoordOffset; +#else +return -texCoordOffset; +#endif +} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4C]) { + ShaderStore.IncludesShadersStore[name$4C] = shader$4B; +} +/** @internal */ +const bumpFragmentFunctions = { name: name$4C, shader: shader$4B }; + +const bumpFragmentFunctions$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bumpFragmentFunctions +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$4B = "decalFragment"; +const shader$4A = `#ifdef DECAL +#ifdef GAMMADECAL +decalColor.rgb=toLinearSpace(decalColor.rgb); +#endif +#ifdef DECAL_SMOOTHALPHA +decalColor.a*=decalColor.a; +#endif +surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4B]) { + ShaderStore.IncludesShadersStore[name$4B] = shader$4A; +} + +// Do not edit. +const name$4A = "pbrBlockAlbedoOpacity"; +const shader$4z = `struct albedoOpacityOutParams +{vec3 surfaceAlbedo;float alpha;}; +#define pbr_inline +albedoOpacityOutParams albedoOpacityBlock( +in vec4 vAlbedoColor +#ifdef ALBEDO +,in vec4 albedoTexture +,in vec2 albedoInfos +#endif +,in float baseWeight +#ifdef BASEWEIGHT +,in vec4 baseWeightTexture +,in vec2 vBaseWeightInfos +#endif +#ifdef OPACITY +,in vec4 opacityMap +,in vec2 vOpacityInfos +#endif +#ifdef DETAIL +,in vec4 detailColor +,in vec4 vDetailInfos +#endif +#ifdef DECAL +,in vec4 decalColor +,in vec4 vDecalInfos +#endif +) +{albedoOpacityOutParams outParams;vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; +#ifdef ALBEDO +#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) +alpha*=albedoTexture.a; +#endif +#ifdef GAMMAALBEDO +surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); +#else +surfaceAlbedo*=albedoTexture.rgb; +#endif +surfaceAlbedo*=albedoInfos.y; +#endif +#ifndef DECAL_AFTER_DETAIL +#include +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +surfaceAlbedo*=vColor.rgb; +#endif +#ifdef DETAIL +float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; +#endif +#ifdef DECAL_AFTER_DETAIL +#include +#endif +#define CUSTOM_FRAGMENT_UPDATE_ALBEDO +surfaceAlbedo*=baseWeight; +#ifdef BASEWEIGHT +surfaceAlbedo*=baseWeightTexture.r; +#endif +#ifdef OPACITY +#ifdef OPACITYRGB +alpha=getLuminance(opacityMap.rgb); +#else +alpha*=opacityMap.a; +#endif +alpha*=vOpacityInfos.y; +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) +#ifdef ALPHATEST +#if DEBUGMODE != 88 +if (alpha0 +#ifdef METALLICWORKFLOW +vec2 metallicRoughness; +#ifdef REFLECTIVITY +vec4 surfaceMetallicColorMap; +#endif +#ifndef FROSTBITE_REFLECTANCE +vec3 metallicF0; +#endif +#else +#ifdef REFLECTIVITY +vec4 surfaceReflectivityColorMap; +#endif +#endif +#endif +}; +#define pbr_inline +reflectivityOutParams reflectivityBlock( +in vec4 vReflectivityColor +#ifdef METALLICWORKFLOW +,in vec3 surfaceAlbedo +,in vec4 metallicReflectanceFactors +#endif +#ifdef REFLECTIVITY +,in vec3 reflectivityInfos +,in vec4 surfaceMetallicOrReflectivityColorMap +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +,in vec3 ambientOcclusionColorIn +#endif +#ifdef MICROSURFACEMAP +,in vec4 microSurfaceTexel +#endif +#ifdef DETAIL +,in vec4 detailColor +,in vec4 vDetailInfos +#endif +) +{reflectivityOutParams outParams;float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +vec2 metallicRoughness=surfaceReflectivityColor.rg; +#ifdef REFLECTIVITY +#if DEBUGMODE>0 +outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef AOSTOREINMETALMAPRED +vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); +#endif +#ifdef METALLNESSSTOREINMETALMAPBLUE +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; +#else +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; +#endif +#ifdef ROUGHNESSSTOREINMETALMAPALPHA +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; +#else +#ifdef ROUGHNESSSTOREINMETALMAPGREEN +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; +#endif +#endif +#endif +#ifdef DETAIL +float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); +#endif +#ifdef MICROSURFACEMAP +metallicRoughness.g*=microSurfaceTexel.r; +#endif +#if DEBUGMODE>0 +outParams.metallicRoughness=metallicRoughness; +#endif +#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS +microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; +#ifdef FROSTBITE_REFLECTANCE +outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); +#else +vec3 metallicF0=metallicReflectanceFactors.rgb; +#if DEBUGMODE>0 +outParams.metallicF0=metallicF0; +#endif +outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); +#endif +#else +#ifdef REFLECTIVITY +surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; +#if DEBUGMODE>0 +outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef MICROSURFACEFROMREFLECTIVITYMAP +microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; +#else +#ifdef MICROSURFACEAUTOMATIC +microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); +#endif +#ifdef MICROSURFACEMAP +microSurface*=microSurfaceTexel.r; +#endif +#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE +#endif +#endif +#endif +microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;return outParams;} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4z]) { + ShaderStore.IncludesShadersStore[name$4z] = shader$4y; +} + +// Do not edit. +const name$4y = "pbrBlockAmbientOcclusion"; +const shader$4x = `struct ambientOcclusionOutParams +{vec3 ambientOcclusionColor; +#if DEBUGMODE>0 && defined(AMBIENT) +vec3 ambientOcclusionColorMap; +#endif +};ambientOcclusionOutParams ambientOcclusionBlock( +#ifdef AMBIENT +in vec3 ambientOcclusionColorMap_, +in vec4 vAmbientInfos +#endif +) +{ambientOcclusionOutParams outParams;vec3 ambientOcclusionColor=vec3(1.,1.,1.); +#ifdef AMBIENT +vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; +#ifdef AMBIENTINGRAYSCALE +ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); +#endif +ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); +#if DEBUGMODE>0 +outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; +#endif +#endif +outParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4y]) { + ShaderStore.IncludesShadersStore[name$4y] = shader$4x; +} + +// Do not edit. +const name$4x = "pbrBlockAlphaFresnel"; +const shader$4w = `#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +struct alphaFresnelOutParams +{float alpha;}; +#define pbr_inline +alphaFresnelOutParams alphaFresnelBlock( +in vec3 normalW, +in vec3 viewDirectionW, +in float alpha, +in float microSurface +) +{alphaFresnelOutParams outParams;float opacityPerceptual=alpha; +#ifdef LINEARALPHAFRESNEL +float opacity0=opacityPerceptual; +#else +float opacity0=opacityPerceptual*opacityPerceptual; +#endif +float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; +#ifdef ALPHATEST +if (outParams.alpha0 && defined(ANISOTROPIC_TEXTURE) +vec3 anisotropyMapData; +#endif +}; +#define pbr_inline +anisotropicOutParams anisotropicBlock( +in vec3 vAnisotropy, +in float roughness, +#ifdef ANISOTROPIC_TEXTURE +in vec3 anisotropyMapData, +#endif +in mat3 TBN, +in vec3 normalW, +in vec3 viewDirectionW +) +{anisotropicOutParams outParams;float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); +#ifdef ANISOTROPIC_TEXTURE +anisotropy*=anisotropyMapData.b; +#if DEBUGMODE>0 +outParams.anisotropyMapData=anisotropyMapData; +#endif +anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; +#ifdef ANISOTROPIC_LEGACY +anisotropyDirection.rg*=anisotropyMapData.rg; +#else +anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); +#endif +#endif +mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4w]) { + ShaderStore.IncludesShadersStore[name$4w] = shader$4v; +} + +// Do not edit. +const name$4v = "pbrBlockReflection"; +const shader$4u = `#ifdef REFLECTION +struct reflectionOutParams +{vec4 environmentRadiance;vec3 environmentIrradiance; +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords; +#else +vec2 reflectionCoords; +#endif +#ifdef SS_TRANSLUCENCY +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +vec3 irradianceVector; +#endif +#endif +#endif +}; +#define pbr_inline +void createReflectionCoords( +in vec3 vPositionW, +in vec3 normalW, +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#ifdef REFLECTIONMAP_3D +out vec3 reflectionCoords +#else +out vec2 reflectionCoords +#endif +) +{ +#ifdef ANISOTROPIC +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); +#else +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +reflectionCoords=reflectionVector; +#else +reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +} +#define pbr_inline +#define inline +void sampleReflectionTexture( +in float alphaG, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +in float NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +in float roughness, +#endif +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +const vec3 reflectionCoords, +#else +in sampler2D reflectionSampler, +const vec2 reflectionCoords, +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +out vec4 environmentRadiance +) +{ +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); +#elif defined(LINEARSPECULARREFLECTION) +float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); +#else +float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); +#endif +#ifdef LODBASEDMICROSFURACE +reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; +#ifdef LODINREFLECTIONALPHA +float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); +#else +float requestedReflectionLOD=reflectionLOD; +#endif +#ifdef REALTIME_FILTERING +environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); +#else +environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); +#endif +#else +float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( +sampleReflection(reflectionSamplerHigh,reflectionCoords), +environmentMid, +lodReflectionNormalizedDoubled +);} else {environmentRadiance=mix( +environmentMid, +sampleReflection(reflectionSamplerLow,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#ifdef RGBDREFLECTION +environmentRadiance.rgb=fromRGBD(environmentRadiance); +#endif +#ifdef GAMMAREFLECTION +environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); +#endif +environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} +#define pbr_inline +#define inline +reflectionOutParams reflectionBlock( +in vec3 vPositionW +,in vec3 normalW +,in float alphaG +,in vec3 vReflectionMicrosurfaceInfos +,in vec2 vReflectionInfos +,in vec3 vReflectionColor +#ifdef ANISOTROPIC +,in anisotropicOutParams anisotropicOut +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +,in float NdotVUnclamped +#endif +#ifdef LINEARSPECULARREFLECTION +,in float roughness +#endif +#ifdef REFLECTIONMAP_3D +,in samplerCube reflectionSampler +#else +,in sampler2D reflectionSampler +#endif +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +,in vec3 vEnvironmentIrradiance +#endif +#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D)) +,in mat4 reflectionMatrix +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +,in samplerCube irradianceSampler +#else +,in sampler2D irradianceSampler +#endif +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +,in samplerCube reflectionSamplerLow +,in samplerCube reflectionSamplerHigh +#else +,in sampler2D reflectionSamplerLow +,in sampler2D reflectionSamplerHigh +#endif +#endif +#ifdef REALTIME_FILTERING +,in vec2 vReflectionFilteringInfo +#ifdef IBL_CDF_FILTERING +,in sampler2D icdfSampler +#endif +#endif +) +{reflectionOutParams outParams;vec4 environmentRadiance=vec4(0.,0.,0.,0.); +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords=vec3(0.); +#else +vec2 reflectionCoords=vec2(0.); +#endif +createReflectionCoords( +vPositionW, +normalW, +#ifdef ANISOTROPIC +anisotropicOut, +#endif +reflectionCoords +);sampleReflectionTexture( +alphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +roughness, +#endif +#ifdef REFLECTIONMAP_3D +reflectionSampler, +reflectionCoords, +#else +reflectionSampler, +reflectionCoords, +#endif +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentRadiance +);vec3 environmentIrradiance=vec3(0.,0.,0.); +#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D)) +#ifdef ANISOTROPIC +vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; +#else +vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#endif +#ifdef USESPHERICALFROMREFLECTIONMAP +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +environmentIrradiance=vEnvironmentIrradiance; +#else +#if defined(REALTIME_FILTERING) +environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo +#ifdef IBL_CDF_FILTERING +,icdfSampler +#endif +); +#else +environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); +#endif +#ifdef SS_TRANSLUCENCY +outParams.irradianceVector=irradianceVector; +#endif +#endif +#elif defined(USEIRRADIANCEMAP) +#ifdef REFLECTIONMAP_3D +vec4 environmentIrradiance4=sampleReflection(irradianceSampler,irradianceVector); +#else +vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords); +#endif +environmentIrradiance=environmentIrradiance4.rgb; +#ifdef RGBDREFLECTION +environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); +#endif +#ifdef GAMMAREFLECTION +environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); +#endif +#endif +environmentIrradiance*=vReflectionColor.rgb*vReflectionInfos.x; +#ifdef MIX_IBL_RADIANCE_WITH_IRRADIANCE +outParams.environmentRadiance=vec4(mix(environmentRadiance.rgb,environmentIrradiance,alphaG),environmentRadiance.a); +#else +outParams.environmentRadiance=environmentRadiance; +#endif +outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4v]) { + ShaderStore.IncludesShadersStore[name$4v] = shader$4u; +} + +// Do not edit. +const name$4u = "pbrBlockSheen"; +const shader$4t = `#ifdef SHEEN +struct sheenOutParams +{float sheenIntensity;vec3 sheenColor;float sheenRoughness; +#ifdef SHEEN_LINKWITHALBEDO +vec3 surfaceAlbedo; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +float sheenAlbedoScaling; +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +vec3 finalSheenRadianceScaled; +#endif +#if DEBUGMODE>0 +#ifdef SHEEN_TEXTURE +vec4 sheenMapData; +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +vec3 sheenEnvironmentReflectance; +#endif +#endif +}; +#define pbr_inline +#define inline +sheenOutParams sheenBlock( +in vec4 vSheenColor +#ifdef SHEEN_ROUGHNESS +,in float vSheenRoughness +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +,in vec4 sheenMapRoughnessData +#endif +#endif +,in float roughness +#ifdef SHEEN_TEXTURE +,in vec4 sheenMapData +,in float sheenMapLevel +#endif +,in float reflectance +#ifdef SHEEN_LINKWITHALBEDO +,in vec3 baseColor +,in vec3 surfaceAlbedo +#endif +#ifdef ENVIRONMENTBRDF +,in float NdotV +,in vec3 environmentBrdf +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +,in vec2 AARoughnessFactors +,in vec3 vReflectionMicrosurfaceInfos +,in vec2 vReflectionInfos +,in vec3 vReflectionColor +,in vec4 vLightingIntensity +#ifdef REFLECTIONMAP_3D +,in samplerCube reflectionSampler +,in vec3 reflectionCoords +#else +,in sampler2D reflectionSampler +,in vec2 reflectionCoords +#endif +,in float NdotVUnclamped +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +,in samplerCube reflectionSamplerLow +,in samplerCube reflectionSamplerHigh +#else +,in sampler2D reflectionSamplerLow +,in sampler2D reflectionSamplerHigh +#endif +#endif +#ifdef REALTIME_FILTERING +,in vec2 vReflectionFilteringInfo +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +,in float seo +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +,in float eho +#endif +#endif +) +{sheenOutParams outParams;float sheenIntensity=vSheenColor.a; +#ifdef SHEEN_TEXTURE +#if DEBUGMODE>0 +outParams.sheenMapData=sheenMapData; +#endif +#endif +#ifdef SHEEN_LINKWITHALBEDO +float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#else +vec3 sheenColor=vSheenColor.rgb; +#ifdef SHEEN_TEXTURE +#ifdef SHEEN_GAMMATEXTURE +sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); +#else +sheenColor.rgb*=sheenMapData.rgb; +#endif +sheenColor.rgb*=sheenMapLevel; +#endif +#ifdef SHEEN_ROUGHNESS +float sheenRoughness=vSheenRoughness; +#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE +#if defined(SHEEN_TEXTURE) +sheenRoughness*=sheenMapData.a; +#endif +#elif defined(SHEEN_TEXTURE_ROUGHNESS) +sheenRoughness*=sheenMapRoughnessData.a; +#endif +#else +float sheenRoughness=roughness; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#endif +#if !defined(SHEEN_ALBEDOSCALING) +sheenIntensity*=(1.-reflectance); +#endif +sheenColor*=sheenIntensity; +#endif +#ifdef ENVIRONMENTBRDF +/*#ifdef SHEEN_SOFTER +vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); +#else*/ +#ifdef SHEEN_ROUGHNESS +vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); +#else +vec3 environmentSheenBrdf=environmentBrdf; +#endif +/*#endif*/ +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); +#ifdef SPECULARAA +sheenAlphaG+=AARoughnessFactors.y; +#endif +vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( +sheenAlphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +sheenRoughness, +#endif +reflectionSampler, +reflectionCoords, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentSheenRadiance +);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +sheenEnvironmentReflectance*=seo; +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +sheenEnvironmentReflectance*=eho; +#endif +#if DEBUGMODE>0 +outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; +#endif +outParams.finalSheenRadianceScaled= +environmentSheenRadiance.rgb * +sheenEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; +#endif +outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4u]) { + ShaderStore.IncludesShadersStore[name$4u] = shader$4t; +} + +// Do not edit. +const name$4t = "pbrBlockClearcoat"; +const shader$4s = `struct clearcoatOutParams +{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; +#ifdef REFLECTION +vec3 finalClearCoatRadianceScaled; +#endif +#ifdef CLEARCOAT_TINT +vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; +#endif +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +vec3 energyConservationFactorClearCoat; +#endif +#if DEBUGMODE>0 +#ifdef CLEARCOAT_BUMP +mat3 TBNClearCoat; +#endif +#ifdef CLEARCOAT_TEXTURE +vec2 clearCoatMapData; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +vec4 clearCoatTintMapData; +#endif +#ifdef REFLECTION +vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; +#endif +float clearCoatNdotV; +#endif +}; +#ifdef CLEARCOAT +#define pbr_inline +#define inline +clearcoatOutParams clearcoatBlock( +in vec3 vPositionW +,in vec3 geometricNormalW +,in vec3 viewDirectionW +,in vec2 vClearCoatParams +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +,in vec4 clearCoatMapRoughnessData +#endif +,in vec3 specularEnvironmentR0 +#ifdef CLEARCOAT_TEXTURE +,in vec2 clearCoatMapData +#endif +#ifdef CLEARCOAT_TINT +,in vec4 vClearCoatTintParams +,in float clearCoatColorAtDistance +,in vec4 vClearCoatRefractionParams +#ifdef CLEARCOAT_TINT_TEXTURE +,in vec4 clearCoatTintMapData +#endif +#endif +#ifdef CLEARCOAT_BUMP +,in vec2 vClearCoatBumpInfos +,in vec4 clearCoatBumpMapData +,in vec2 vClearCoatBumpUV +#if defined(TANGENT) && defined(NORMAL) +,in mat3 vTBN +#else +,in vec2 vClearCoatTangentSpaceParams +#endif +#ifdef OBJECTSPACE_NORMALMAP +,in mat4 normalMatrix +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +,in vec3 faceNormal +#endif +#ifdef REFLECTION +,in vec3 vReflectionMicrosurfaceInfos +,in vec2 vReflectionInfos +,in vec3 vReflectionColor +,in vec4 vLightingIntensity +#ifdef REFLECTIONMAP_3D +,in samplerCube reflectionSampler +#else +,in sampler2D reflectionSampler +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +,in samplerCube reflectionSamplerLow +,in samplerCube reflectionSamplerHigh +#else +,in sampler2D reflectionSamplerLow +,in sampler2D reflectionSamplerHigh +#endif +#endif +#ifdef REALTIME_FILTERING +,in vec2 vReflectionFilteringInfo +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +,in float frontFacingMultiplier +#endif +) +{clearcoatOutParams outParams;float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE +clearCoatRoughness*=clearCoatMapData.y; +#endif +#if DEBUGMODE>0 +outParams.clearCoatMapData=clearCoatMapData; +#endif +#endif +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +clearCoatRoughness*=clearCoatMapRoughnessData.y; +#endif +outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; +#ifdef CLEARCOAT_TINT +vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; +#ifdef CLEARCOAT_TINT_TEXTURE +#ifdef CLEARCOAT_TINT_GAMMATEXTURE +clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); +#else +clearCoatColor*=clearCoatTintMapData.rgb; +#endif +clearCoatThickness*=clearCoatTintMapData.a; +#if DEBUGMODE>0 +outParams.clearCoatTintMapData=clearCoatTintMapData; +#endif +#endif +outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; +#endif +#ifdef CLEARCOAT_REMAP_F0 +vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); +#else +vec3 specularEnvironmentR0Updated=specularEnvironmentR0; +#endif +outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; +#ifdef CLEARCOAT_BUMP +#ifdef NORMALXYSCALE +float clearCoatNormalScale=1.0; +#else +float clearCoatNormalScale=vClearCoatBumpInfos.y; +#endif +#if defined(TANGENT) && defined(NORMAL) +mat3 TBNClearCoat=vTBN; +#else +vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); +#endif +#if DEBUGMODE>0 +outParams.TBNClearCoat=TBNClearCoat; +#endif +#ifdef OBJECTSPACE_NORMALMAP +clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); +#else +clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; +#endif +outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); +#if DEBUGMODE>0 +outParams.clearCoatNdotV=clearCoatNdotV; +#endif +#ifdef CLEARCOAT_TINT +vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); +#endif +#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) +vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); +#endif +#if defined(REFLECTION) +float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); +#ifdef SPECULARAA +clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; +#endif +vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +clearCoatReflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +vec3 clearCoatReflectionCoords=clearCoatReflectionVector; +#else +vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +clearCoatReflectionCoords/=clearCoatReflectionVector.z; +#endif +clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; +#endif +sampleReflectionTexture( +clearCoatAlphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +clearCoatNdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +clearCoatRoughness, +#endif +reflectionSampler, +clearCoatReflectionCoords, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentClearCoatRadiance +); +#if DEBUGMODE>0 +outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; +#endif +#endif +#endif +#else +vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); +#endif +clearCoatEnvironmentReflectance*=clearCoatIntensity; +#if DEBUGMODE>0 +outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; +#endif +outParams.finalClearCoatRadianceScaled= +environmentClearCoatRadiance.rgb * +clearCoatEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(CLEARCOAT_TINT) +outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); +#endif +float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); +#endif +return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4t]) { + ShaderStore.IncludesShadersStore[name$4t] = shader$4s; +} + +// Do not edit. +const name$4s = "pbrBlockIridescence"; +const shader$4r = `struct iridescenceOutParams +{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; +#ifdef IRIDESCENCE +#define pbr_inline +#define inline +iridescenceOutParams iridescenceBlock( +in vec4 vIridescenceParams +,in float viewAngle +,in vec3 specularEnvironmentR0 +#ifdef IRIDESCENCE_TEXTURE +,in vec2 iridescenceMapData +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +,in vec2 iridescenceThicknessMapData +#endif +#ifdef CLEARCOAT +,in float NdotVUnclamped +,in vec2 vClearCoatParams +#ifdef CLEARCOAT_TEXTURE +,in vec2 clearCoatMapData +#endif +#endif +) +{iridescenceOutParams outParams;float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; +#ifdef IRIDESCENCE_TEXTURE +iridescenceIntensity*=iridescenceMapData.x; +#endif +#if defined(IRIDESCENCE_THICKNESS_TEXTURE) +iridescenceThicknessWeight=iridescenceThicknessMapData.g; +#endif +float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; +#ifdef CLEARCOAT +float clearCoatIntensity=vClearCoatParams.x; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#endif +topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); +#endif +vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4s]) { + ShaderStore.IncludesShadersStore[name$4s] = shader$4r; +} + +// Do not edit. +const name$4r = "pbrBlockSubSurface"; +const shader$4q = `struct subSurfaceOutParams +{vec3 specularEnvironmentReflectance; +#ifdef SS_REFRACTION +vec3 finalRefraction;vec3 surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +float alpha; +#endif +#ifdef REFLECTION +float refractionFactorForIrradiance; +#endif +#endif +#ifdef SS_TRANSLUCENCY +vec3 transmittance;float translucencyIntensity; +#ifdef REFLECTION +vec3 refractionIrradiance; +#endif +#endif +#if DEBUGMODE>0 +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec4 thicknessMap; +#endif +#ifdef SS_REFRACTION +vec4 environmentRefraction;vec3 refractionTransmittance; +#endif +#endif +}; +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +#define pbr_inline +#define inline +vec4 sampleEnvironmentRefraction( +in float ior +,in float thickness +,in float refractionLOD +,in vec3 normalW +,in vec3 vPositionW +,in vec3 viewDirectionW +,in mat4 view +,in vec4 vRefractionInfos +,in mat4 refractionMatrix +,in vec4 vRefractionMicrosurfaceInfos +,in float alphaG +#ifdef SS_REFRACTIONMAP_3D +,in samplerCube refractionSampler +#ifndef LODBASEDMICROSFURACE +,in samplerCube refractionSamplerLow +,in samplerCube refractionSamplerHigh +#endif +#else +,in sampler2D refractionSampler +#ifndef LODBASEDMICROSFURACE +,in sampler2D refractionSamplerLow +,in sampler2D refractionSamplerHigh +#endif +#endif +#ifdef ANISOTROPIC +,in anisotropicOutParams anisotropicOut +#endif +#ifdef REALTIME_FILTERING +,in vec2 vRefractionFilteringInfo +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,in vec3 refractionPosition +,in vec3 refractionSize +#endif +) {vec4 environmentRefraction=vec4(0.,0.,0.,0.); +#ifdef ANISOTROPIC +vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior); +#else +vec3 refractionVector=refract(-viewDirectionW,normalW,ior); +#endif +#ifdef SS_REFRACTIONMAP_OPPOSITEZ +refractionVector.z*=-1.0; +#endif +#ifdef SS_REFRACTIONMAP_3D +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); +#else +#ifdef SS_USE_THICKNESS_AS_DEPTH +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); +#endif +vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; +#endif +#ifdef LODBASEDMICROSFURACE +refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; +#ifdef SS_LODINREFRACTIONALPHA +float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); +#else +float requestedRefractionLOD=refractionLOD; +#endif +#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) +environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); +#else +environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); +#endif +#else +float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( +sampleRefraction(refractionSamplerHigh,refractionCoords), +environmentRefractionMid, +lodRefractionNormalizedDoubled +);} else {environmentRefraction=mix( +environmentRefractionMid, +sampleRefraction(refractionSamplerLow,refractionCoords), +lodRefractionNormalizedDoubled-1.0 +);} +#endif +#ifdef SS_RGBDREFRACTION +environmentRefraction.rgb=fromRGBD(environmentRefraction); +#endif +#ifdef SS_GAMMAREFRACTION +environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); +#endif +return environmentRefraction;} +#endif +#define pbr_inline +#define inline +subSurfaceOutParams subSurfaceBlock( +in vec3 vSubSurfaceIntensity +,in vec2 vThicknessParam +,in vec4 vTintColor +,in vec3 normalW +,in vec3 specularEnvironmentReflectance +#ifdef SS_THICKNESSANDMASK_TEXTURE +,in vec4 thicknessMap +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +,in vec4 refractionIntensityMap +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +,in vec4 translucencyIntensityMap +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +,in mat4 reflectionMatrix +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +,in vec3 irradianceVector_ +#endif +#if defined(REALTIME_FILTERING) +,in samplerCube reflectionSampler +,in vec2 vReflectionFilteringInfo +#ifdef IBL_CDF_FILTERING +,in sampler2D icdfSampler +#endif +#endif +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +,in samplerCube irradianceSampler +#else +,in sampler2D irradianceSampler +#endif +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +,in vec3 surfaceAlbedo +#endif +#ifdef SS_REFRACTION +,in vec3 vPositionW +,in vec3 viewDirectionW +,in mat4 view +,in vec4 vRefractionInfos +,in mat4 refractionMatrix +,in vec4 vRefractionMicrosurfaceInfos +,in vec4 vLightingIntensity +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +,in float alpha +#endif +#ifdef SS_LODINREFRACTIONALPHA +,in float NdotVUnclamped +#endif +#ifdef SS_LINEARSPECULARREFRACTION +,in float roughness +#endif +,in float alphaG +#ifdef SS_REFRACTIONMAP_3D +,in samplerCube refractionSampler +#ifndef LODBASEDMICROSFURACE +,in samplerCube refractionSamplerLow +,in samplerCube refractionSamplerHigh +#endif +#else +,in sampler2D refractionSampler +#ifndef LODBASEDMICROSFURACE +,in sampler2D refractionSamplerLow +,in sampler2D refractionSamplerHigh +#endif +#endif +#ifdef ANISOTROPIC +,in anisotropicOutParams anisotropicOut +#endif +#ifdef REALTIME_FILTERING +,in vec2 vRefractionFilteringInfo +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,in vec3 refractionPosition +,in vec3 refractionSize +#endif +#ifdef SS_DISPERSION +,in float dispersion +#endif +#endif +#ifdef SS_TRANSLUCENCY +,in vec3 vDiffusionDistance +,in vec4 vTranslucencyColor +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE +,in vec4 translucencyColorMap +#endif +#endif +) +{subSurfaceOutParams outParams;outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; +#ifdef SS_REFRACTION +float refractionIntensity=vSubSurfaceIntensity.x; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; +#endif +#endif +#ifdef SS_TRANSLUCENCY +float translucencyIntensity=vSubSurfaceIntensity.y; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +#ifdef SS_USE_GLTF_TEXTURES +float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; +#else +float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; +#endif +#if DEBUGMODE>0 +outParams.thicknessMap=thicknessMap; +#endif +#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS) +#ifdef SS_USE_GLTF_TEXTURES +refractionIntensity*=thicknessMap.r; +#else +refractionIntensity*=thicknessMap.g; +#endif +#endif +#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS) +#ifdef SS_USE_GLTF_TEXTURES +translucencyIntensity*=thicknessMap.a; +#else +translucencyIntensity*=thicknessMap.b; +#endif +#endif +#else +float thickness=vThicknessParam.y; +#endif +#if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE) +#ifdef SS_USE_GLTF_TEXTURES +refractionIntensity*=refractionIntensityMap.r; +#else +refractionIntensity*=refractionIntensityMap.g; +#endif +#endif +#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE) +#ifdef SS_USE_GLTF_TEXTURES +translucencyIntensity*=translucencyIntensityMap.a; +#else +translucencyIntensity*=translucencyIntensityMap.b; +#endif +#endif +#ifdef SS_TRANSLUCENCY +thickness=maxEps(thickness);vec4 translucencyColor=vTranslucencyColor; +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE +translucencyColor*=translucencyColorMap; +#endif +vec3 transmittance=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; +#endif +#ifdef SS_REFRACTION +vec4 environmentRefraction=vec4(0.,0.,0.,0.); +#ifdef SS_HAS_THICKNESS +float ior=vRefractionInfos.y; +#else +float ior=vRefractionMicrosurfaceInfos.w; +#endif +#ifdef SS_LODINREFRACTIONALPHA +float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); +#elif defined(SS_LINEARSPECULARREFRACTION) +float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); +#else +float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); +#endif +float refraction_ior=vRefractionInfos.y; +#ifdef SS_DISPERSION +float realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i]; +#endif +vec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG +#ifdef SS_REFRACTIONMAP_3D +,refractionSampler +#ifndef LODBASEDMICROSFURACE +,refractionSamplerLow +,refractionSamplerHigh +#endif +#else +,refractionSampler +#ifndef LODBASEDMICROSFURACE +,refractionSamplerLow +,refractionSamplerHigh +#endif +#endif +#ifdef ANISOTROPIC +,anisotropicOut +#endif +#ifdef REALTIME_FILTERING +,vRefractionFilteringInfo +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,refractionPosition +,refractionSize +#endif +); +#ifdef SS_DISPERSION +environmentRefraction[i]=envSample[i];} +#else +environmentRefraction=envSample; +#endif +environmentRefraction.rgb*=vRefractionInfos.x; +#endif +#ifdef SS_REFRACTION +vec3 refractionTransmittance=vec3(refractionIntensity); +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); +#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) +float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; +#else +vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); +#endif +#ifdef SS_ALBEDOFORREFRACTIONTINT +environmentRefraction.rgb*=surfaceAlbedo.rgb; +#endif +outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); +#ifdef REFLECTION +outParams.refractionFactorForIrradiance=(1.-refractionIntensity); +#endif +#ifdef UNUSED_MULTIPLEBOUNCES +vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); +#endif +refractionTransmittance*=1.0-max(outParams.specularEnvironmentReflectance.r,max(outParams.specularEnvironmentReflectance.g,outParams.specularEnvironmentReflectance.b)); +#if DEBUGMODE>0 +outParams.refractionTransmittance=refractionTransmittance; +#endif +outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; +#if DEBUGMODE>0 +outParams.environmentRefraction=environmentRefraction; +#endif +#endif +#if defined(REFLECTION) && defined(SS_TRANSLUCENCY) +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) +vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#else +vec3 irradianceVector=irradianceVector_; +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) +#if defined(REALTIME_FILTERING) +vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo +#ifdef IBL_CDF_FILTERING +,icdfSampler +#endif +); +#else +vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); +#endif +#elif defined(USEIRRADIANCEMAP) +#ifdef REFLECTIONMAP_3D +vec3 irradianceCoords=irradianceVector; +#else +vec2 irradianceCoords=irradianceVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +irradianceCoords/=irradianceVector.z; +#endif +irradianceCoords.y=1.0-irradianceCoords.y; +#endif +vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); +#ifdef RGBDREFLECTION +refractionIrradiance.rgb=fromRGBD(refractionIrradiance); +#endif +#ifdef GAMMAREFLECTION +refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); +#endif +#else +vec4 refractionIrradiance=vec4(0.); +#endif +refractionIrradiance.rgb*=transmittance; +#ifdef SS_ALBEDOFORTRANSLUCENCYTINT +refractionIrradiance.rgb*=surfaceAlbedo.rgb; +#endif +outParams.refractionIrradiance=refractionIrradiance.rgb; +#endif +return outParams;} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4r]) { + ShaderStore.IncludesShadersStore[name$4r] = shader$4q; +} + +// Do not edit. +const name$4q = "pbrBlockNormalGeometric"; +const shader$4p = `vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; +#endif +vec3 geometricNormalW=normalW; +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4q]) { + ShaderStore.IncludesShadersStore[name$4q] = shader$4p; +} + +// Do not edit. +const name$4p = "bumpFragment"; +const shader$4o = `vec2 uvOffset=vec2(0.0,0.0); +#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) +#ifdef NORMALXYSCALE +float normalScale=1.0; +#elif defined(BUMP) +float normalScale=vBumpInfos.y; +#else +float normalScale=1.0; +#endif +#if defined(TANGENT) && defined(NORMAL) +mat3 TBN=vTBN; +#elif defined(BUMP) +vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); +#else +vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); +#endif +#elif defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +mat3 TBN=vTBN; +#else +vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); +#endif +#endif +#ifdef PARALLAX +mat3 invTBN=transposeMat3(TBN); +#ifdef PARALLAXOCCLUSION +uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); +#else +uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); +#endif +#endif +#ifdef DETAIL +vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); +#endif +#ifdef BUMP +#ifdef OBJECTSPACE_NORMALMAP +#define CUSTOM_FRAGMENT_BUMP_FRAGMENT +normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); +#elif !defined(DETAIL) +normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); +#else +vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; +#if DETAIL_NORMALBLENDMETHOD==0 +detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); +#elif DETAIL_NORMALBLENDMETHOD==1 +detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; +#endif +normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); +#endif +#elif defined(DETAIL) +detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4p]) { + ShaderStore.IncludesShadersStore[name$4p] = shader$4o; +} +/** @internal */ +const bumpFragment = { name: name$4p, shader: shader$4o }; + +const bumpFragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bumpFragment +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$4o = "pbrBlockNormalFinal"; +const shader$4n = `#if defined(FORCENORMALFORWARD) && defined(NORMAL) +vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; +#if defined(TWOSIDEDLIGHTING) +faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; +#endif +normalW*=sign(dot(normalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4o]) { + ShaderStore.IncludesShadersStore[name$4o] = shader$4n; +} + +// Do not edit. +const name$4n = "depthPrePass"; +const shader$4m = `#ifdef DEPTHPREPASS +gl_FragColor=vec4(0.,0.,0.,1.0);return; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4n]) { + ShaderStore.IncludesShadersStore[name$4n] = shader$4m; +} + +// Do not edit. +const name$4m = "pbrBlockLightmapInit"; +const shader$4l = `#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +#ifdef GAMMALIGHTMAP +lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4m]) { + ShaderStore.IncludesShadersStore[name$4m] = shader$4l; +} + +// Do not edit. +const name$4l = "pbrBlockGeometryInfo"; +const shader$4k = `float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); +#ifdef SPECULARAA +alphaG+=AARoughnessFactors.y; +#endif +#if defined(ENVIRONMENTBRDF) +vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +#ifdef AMBIENTINGRAYSCALE +float ambientMonochrome=aoOut.ambientOcclusionColor.r; +#else +float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); +#endif +float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); +#endif +#endif +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4l]) { + ShaderStore.IncludesShadersStore[name$4l] = shader$4k; +} + +// Do not edit. +const name$4k = "pbrBlockReflectance0"; +const shader$4j = `float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); +#else +vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); +#endif +#ifdef ALPHAFRESNEL +float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4k]) { + ShaderStore.IncludesShadersStore[name$4k] = shader$4j; +} + +// Do not edit. +const name$4j = "pbrBlockReflectance"; +const shader$4i = `#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); +#ifdef RADIANCEOCCLUSION +specularEnvironmentReflectance*=seo; +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +specularEnvironmentReflectance*=eho; +#endif +#endif +#endif +#else +vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); +#endif +#ifdef CLEARCOAT +specularEnvironmentReflectance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +specularEnvironmentReflectance*=clearcoatOut.absorption; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4j]) { + ShaderStore.IncludesShadersStore[name$4j] = shader$4i; +} + +// Do not edit. +const name$4i = "pbrBlockDirectLighting"; +const shader$4h = `vec3 diffuseBase=vec3(0.,0.,0.); +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +#ifdef CLEARCOAT +vec3 clearCoatBase=vec3(0.,0.,0.); +#endif +#ifdef SHEEN +vec3 sheenBase=vec3(0.,0.,0.); +#endif +preLightingInfo preInfo;lightingInfo info;float shadow=1.; +float aggShadow=0.;float numLights=0.; +#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +vec3 absorption=vec3(0.); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4i]) { + ShaderStore.IncludesShadersStore[name$4i] = shader$4h; +} + +// Do not edit. +const name$4h = "pbrBlockFinalLitComponents"; +const shader$4g = `aggShadow=aggShadow/numLights; +#if defined(ENVIRONMENTBRDF) +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); +#endif +#endif +#ifndef METALLICWORKFLOW +#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION +surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; +#endif +#endif +#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) +surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; +#endif +#ifdef REFLECTION +vec3 finalIrradiance=reflectionOut.environmentIrradiance; +#if defined(CLEARCOAT) +finalIrradiance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +finalIrradiance*=clearcoatOut.absorption; +#endif +#endif +finalIrradiance*=surfaceAlbedo.rgb; +#if defined(SS_REFRACTION) +finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; +#endif +#if defined(SS_TRANSLUCENCY) +finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; +#endif +finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalSpecularScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalSpecularScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef REFLECTION +vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalRadianceScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalRadianceScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef SHEEN +vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; +#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef CLEARCOAT +vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; +#ifdef CLEARCOAT_TINT +subSurfaceOut.finalRefraction*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef ALPHABLEND +float luminanceOverAlpha=0.0; +#if defined(REFLECTION) && defined(RADIANCEOVERALPHA) +luminanceOverAlpha+=getLuminance(finalRadianceScaled); +#if defined(CLEARCOAT) +luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); +#endif +#endif +#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) +luminanceOverAlpha+=getLuminance(finalSpecularScaled); +#endif +#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) +luminanceOverAlpha+=getLuminance(finalClearCoatScaled); +#endif +#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) +alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4h]) { + ShaderStore.IncludesShadersStore[name$4h] = shader$4g; +} + +// Do not edit. +const name$4g = "pbrBlockFinalUnlitComponents"; +const shader$4f = `vec3 finalDiffuse=diffuseBase; +#if !defined(SS_TRANSLUCENCY) +finalDiffuse*=surfaceAlbedo.rgb; +#endif +finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; +#ifdef EMISSIVE +vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; +#ifdef GAMMAEMISSIVE +finalEmissive*=toLinearSpace(emissiveColorTex.rgb); +#else +finalEmissive*=emissiveColorTex.rgb; +#endif +finalEmissive*= vEmissiveInfos.y; +#endif +finalEmissive*=vLightingIntensity.y; +#ifdef AMBIENT +vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); +#else +vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; +#endif +finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4g]) { + ShaderStore.IncludesShadersStore[name$4g] = shader$4f; +} + +// Do not edit. +const name$4f = "pbrBlockFinalColorComposition"; +const shader$4e = `vec4 finalColor=vec4( +#ifndef UNLIT +#ifdef REFLECTION +finalIrradiance + +#endif +#ifdef SPECULARTERM +finalSpecularScaled + +#endif +#ifdef SHEEN +finalSheenScaled + +#endif +#ifdef CLEARCOAT +finalClearCoatScaled + +#endif +#ifdef REFLECTION +finalRadianceScaled + +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled + +#endif +#ifdef CLEARCOAT +clearcoatOut.finalClearCoatRadianceScaled + +#endif +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction + +#endif +#endif +finalAmbient + +finalDiffuse, +alpha); +#ifdef LIGHTMAP +#ifndef LIGHTMAPEXCLUDED +#ifdef USELIGHTMAPASSHADOWMAP +finalColor.rgb*=lightmapColor.rgb; +#else +finalColor.rgb+=lightmapColor.rgb; +#endif +#endif +#endif +finalColor.rgb+=finalEmissive; +#define CUSTOM_FRAGMENT_BEFORE_FOG +finalColor=max(finalColor,0.0); +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4f]) { + ShaderStore.IncludesShadersStore[name$4f] = shader$4e; +} + +// Do not edit. +const name$4e = "pbrBlockImageProcessing"; +const shader$4d = `#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) +#if !defined(SKIPFINALCOLORCLAMP) +finalColor.rgb=clamp(finalColor.rgb,0.,30.0); +#endif +#else +finalColor=applyImageProcessing(finalColor); +#endif +finalColor.a*=visibility; +#ifdef PREMULTIPLYALPHA +finalColor.rgb*=finalColor.a; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4e]) { + ShaderStore.IncludesShadersStore[name$4e] = shader$4d; +} + +// Do not edit. +const name$4d = "pbrBlockPrePass"; +const shader$4c = `float writeGeometryInfo=finalColor.a>ALPHATESTVALUE ? 1.0 : 0.0; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_LOCAL_POSITION +gl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition,writeGeometryInfo); +#endif +#if defined(PREPASS_VELOCITY) +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#elif defined(PREPASS_VELOCITY_LINEAR) +vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w)-(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO +gl_FragData[PREPASS_ALBEDO_INDEX]=vec4(surfaceAlbedo,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +vec3 sqAlbedo=sqrt(surfaceAlbedo); +#endif +#ifdef PREPASS_IRRADIANCE +vec3 irradiance=finalDiffuse; +#ifndef UNLIT +#ifdef REFLECTION +irradiance+=finalIrradiance; +#endif +#endif +#ifdef SS_SCATTERING +#ifdef PREPASS_COLOR +gl_FragData[PREPASS_COLOR_INDEX]=vec4(finalColor.rgb-irradiance,finalColor.a); +#endif +irradiance/=sqAlbedo; +#else +#ifdef PREPASS_COLOR +gl_FragData[PREPASS_COLOR_INDEX]=finalColor; +#endif +float scatteringDiffusionProfile=255.; +#endif +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); +#elif defined(PREPASS_COLOR) +gl_FragData[PREPASS_COLOR_INDEX]=vec4(finalColor.rgb,finalColor.a); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_SCREENSPACE_DEPTH +gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_WORLD_NORMAL +gl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#ifndef UNLIT +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4d]) { + ShaderStore.IncludesShadersStore[name$4d] = shader$4c; +} + +// Do not edit. +const name$4c = "oitFragment"; +const shader$4b = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY +float fragDepth=gl_FragCoord.z; +#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS +uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; +#endif +ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); +#ifdef USE_REVERSE_DEPTHBUFFER +float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; +#else +float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; +#endif +float alphaMultiplier=1.0-lastFrontColor.a; +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepth>nearestDepth || fragDepthfurthestDepth) { +#endif +return;} +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepthfurthestDepth) { +#else +if (fragDepth>nearestDepth && fragDepth0 +if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { +#if DEBUGMODE==1 +gl_FragColor.rgb=vPositionW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==2 && defined(NORMAL) +gl_FragColor.rgb=vNormalW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) +gl_FragColor.rgb=TBN[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) +gl_FragColor.rgb=TBN[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==5 +gl_FragColor.rgb=normalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==6 && defined(MAINUV1) +gl_FragColor.rgb=vec3(vMainUV1,0.0); +#elif DEBUGMODE==7 && defined(MAINUV2) +gl_FragColor.rgb=vec3(vMainUV2,0.0); +#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==10 && defined(CLEARCOAT) +gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==11 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicNormal; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==12 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicTangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==13 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==20 && defined(ALBEDO) +gl_FragColor.rgb=albedoTexture.rgb; +#ifndef GAMMAALBEDO +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==21 && defined(AMBIENT) +gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; +#elif DEBUGMODE==22 && defined(OPACITY) +gl_FragColor.rgb=opacityMap.rgb; +#elif DEBUGMODE==23 && defined(EMISSIVE) +gl_FragColor.rgb=emissiveColorTex.rgb; +#ifndef GAMMAEMISSIVE +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==24 && defined(LIGHTMAP) +gl_FragColor.rgb=lightmapColor.rgb; +#ifndef GAMMALIGHTMAP +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; +#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); +#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; +#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) +gl_FragColor.rgb=sheenOut.sheenMapData.rgb; +#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) +gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; +#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) +gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; +#elif DEBUGMODE==32 && defined(BUMP) +gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; +#elif DEBUGMODE==40 && defined(SS_REFRACTION) +gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==41 && defined(REFLECTION) +gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) +gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==50 +gl_FragColor.rgb=diffuseBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==51 && defined(SPECULARTERM) +gl_FragColor.rgb=specularBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==52 && defined(CLEARCOAT) +gl_FragColor.rgb=clearCoatBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==53 && defined(SHEEN) +gl_FragColor.rgb=sheenBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==54 && defined(REFLECTION) +gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==60 +gl_FragColor.rgb=surfaceAlbedo.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==61 +gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==62 && defined(METALLICWORKFLOW) +gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); +#elif DEBUGMODE==71 && defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.metallicF0; +#elif DEBUGMODE==63 +gl_FragColor.rgb=vec3(roughness); +#elif DEBUGMODE==64 +gl_FragColor.rgb=vec3(alphaG); +#elif DEBUGMODE==65 +gl_FragColor.rgb=vec3(NdotV); +#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==67 && defined(CLEARCOAT) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); +#elif DEBUGMODE==68 && defined(CLEARCOAT) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); +#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) +gl_FragColor.rgb=subSurfaceOut.transmittance; +#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) +gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; +#elif DEBUGMODE==72 +gl_FragColor.rgb=vec3(microSurface); +#elif DEBUGMODE==73 +gl_FragColor.rgb=vAlbedoColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) +gl_FragColor.rgb=vReflectivityColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==75 +gl_FragColor.rgb=vEmissiveColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) +gl_FragColor.rgb=vec3(seo); +#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +gl_FragColor.rgb=vec3(eho); +#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) +gl_FragColor.rgb=vec3(energyConservationFactor); +#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +gl_FragColor.rgb=specularEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) +gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==86 && defined(ALPHABLEND) +gl_FragColor.rgb=vec3(luminanceOverAlpha); +#elif DEBUGMODE==87 +gl_FragColor.rgb=vec3(alpha); +#elif DEBUGMODE==88 && defined(ALBEDO) +gl_FragColor.rgb=vec3(albedoTexture.a); +#elif DEBUGMODE==89 +gl_FragColor.rgb=aoOut.ambientOcclusionColor.rgb; +#else +float stripeWidth=30.;float stripePos=floor(gl_FragCoord.x/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); +#endif +gl_FragColor.rgb*=vDebugMode.y; +#ifdef DEBUGMODE_NORMALIZE +gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; +#endif +#ifdef DEBUGMODE_GAMMA +gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); +#endif +gl_FragColor.a=1.0; +#ifdef PREPASS +gl_FragData[0]=toLinearSpace(gl_FragColor); +gl_FragData[1]=vec4(0.,0.,0.,0.); +#endif +#ifdef DEBUGMODE_FORCERETURN +return; +#endif +} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$4b]) { + ShaderStore.IncludesShadersStore[name$4b] = shader$4a; +} + +// Do not edit. +const name$4a = "pbrPixelShader"; +const shader$49 = `#define CUSTOM_FRAGMENT_EXTENSION +#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#extension GL_OES_standard_derivatives : enable +#endif +#ifdef LODBASEDMICROSFURACE +#extension GL_EXT_shader_texture_lod : enable +#endif +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include[SCENE_MRT_COUNT] +precision highp float; +#include +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE +#endif +#include<__decl__pbrFragment> +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef REFLECTION +#include +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#include +#include +#include +albedoOpacityOutParams albedoOpacityOut; +#ifdef ALBEDO +vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); +#endif +#ifdef BASEWEIGHT +vec4 baseWeightTexture=texture2D(baseWeightSampler,vBaseWeightUV+uvOffset); +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#endif +#ifdef DECAL +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#endif +albedoOpacityOut=albedoOpacityBlock( +vAlbedoColor +#ifdef ALBEDO +,albedoTexture +,vAlbedoInfos +#endif +,baseWeight +#ifdef BASEWEIGHT +,baseWeightTexture +,vBaseWeightInfos +#endif +#ifdef OPACITY +,opacityMap +,vOpacityInfos +#endif +#ifdef DETAIL +,detailColor +,vDetailInfos +#endif +#ifdef DECAL +,decalColor +,vDecalInfos +#endif +);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; +#define CUSTOM_FRAGMENT_UPDATE_ALPHA +#include +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +ambientOcclusionOutParams aoOut; +#ifdef AMBIENT +vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; +#endif +aoOut=ambientOcclusionBlock( +#ifdef AMBIENT +ambientOcclusionColorMap, +vAmbientInfos +#endif +); +#include +#ifdef UNLIT +vec3 diffuseBase=vec3(1.,1.,1.); +#else +vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; +#if defined(REFLECTIVITY) +vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; +#ifndef METALLICWORKFLOW +#ifdef REFLECTIVITY_GAMMA +surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); +#endif +surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; +#endif +#endif +#if defined(MICROSURFACEMAP) +vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; +#endif +#ifdef METALLICWORKFLOW +vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; +#ifdef REFLECTANCE +vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); +#ifdef REFLECTANCE_GAMMA +reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); +#endif +metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; +#endif +#ifdef METALLIC_REFLECTANCE +vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); +#ifdef METALLIC_REFLECTANCE_GAMMA +metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); +#endif +#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY +metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; +#endif +metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; +#endif +#endif +reflectivityOut=reflectivityBlock( +vReflectivityColor +#ifdef METALLICWORKFLOW +,surfaceAlbedo +,metallicReflectanceFactors +#endif +#ifdef REFLECTIVITY +,vReflectivityInfos +,surfaceMetallicOrReflectivityColorMap +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +,aoOut.ambientOcclusionColor +#endif +#ifdef MICROSURFACEMAP +,microSurfaceTexel +#endif +#ifdef DETAIL +,detailColor +,vDetailInfos +#endif +);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; +#ifdef METALLICWORKFLOW +surfaceAlbedo=reflectivityOut.surfaceAlbedo; +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; +#endif +#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +alphaFresnelOutParams alphaFresnelOut;alphaFresnelOut=alphaFresnelBlock( +normalW, +viewDirectionW, +alpha, +microSurface +);alpha=alphaFresnelOut.alpha; +#endif +#endif +#include +#ifdef ANISOTROPIC +anisotropicOutParams anisotropicOut; +#ifdef ANISOTROPIC_TEXTURE +vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; +#endif +anisotropicOut=anisotropicBlock( +vAnisotropy, +roughness, +#ifdef ANISOTROPIC_TEXTURE +anisotropyMapData, +#endif +TBN, +normalW, +viewDirectionW +); +#endif +#ifdef REFLECTION +reflectionOutParams reflectionOut; +#ifndef USE_CUSTOM_REFLECTION +reflectionOut=reflectionBlock( +vPositionW +,normalW +,alphaG +,vReflectionMicrosurfaceInfos +,vReflectionInfos +,vReflectionColor +#ifdef ANISOTROPIC +,anisotropicOut +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +,NdotVUnclamped +#endif +#ifdef LINEARSPECULARREFLECTION +,roughness +#endif +,reflectionSampler +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +,vEnvironmentIrradiance +#endif +#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D)) +,reflectionMatrix +#endif +#ifdef USEIRRADIANCEMAP +,irradianceSampler +#endif +#ifndef LODBASEDMICROSFURACE +,reflectionSamplerLow +,reflectionSamplerHigh +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo +#ifdef IBL_CDF_FILTERING +,icdfSampler +#endif +#endif +); +#else +#define CUSTOM_REFLECTION +#endif +#endif +#include +#ifdef SHEEN +sheenOutParams sheenOut; +#ifdef SHEEN_TEXTURE +vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); +#endif +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; +#endif +sheenOut=sheenBlock( +vSheenColor +#ifdef SHEEN_ROUGHNESS +,vSheenRoughness +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +,sheenMapRoughnessData +#endif +#endif +,roughness +#ifdef SHEEN_TEXTURE +,sheenMapData +,vSheenInfos.y +#endif +,reflectance +#ifdef SHEEN_LINKWITHALBEDO +,baseColor +,surfaceAlbedo +#endif +#ifdef ENVIRONMENTBRDF +,NdotV +,environmentBrdf +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +,AARoughnessFactors +,vReflectionMicrosurfaceInfos +,vReflectionInfos +,vReflectionColor +,vLightingIntensity +,reflectionSampler +,reflectionOut.reflectionCoords +,NdotVUnclamped +#ifndef LODBASEDMICROSFURACE +,reflectionSamplerLow +,reflectionSamplerHigh +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +,seo +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +,eho +#endif +#endif +); +#ifdef SHEEN_LINKWITHALBEDO +surfaceAlbedo=sheenOut.surfaceAlbedo; +#endif +#endif +#ifdef CLEARCOAT +#ifdef CLEARCOAT_TEXTURE +vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; +#endif +#endif +#ifdef IRIDESCENCE +iridescenceOutParams iridescenceOut; +#ifdef IRIDESCENCE_TEXTURE +vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; +#endif +iridescenceOut=iridescenceBlock( +vIridescenceParams +,NdotV +,specularEnvironmentR0 +#ifdef IRIDESCENCE_TEXTURE +,iridescenceMapData +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +,iridescenceThicknessMapData +#endif +#ifdef CLEARCOAT +,NdotVUnclamped +,vClearCoatParams +#ifdef CLEARCOAT_TEXTURE +,clearCoatMapData +#endif +#endif +);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; +#endif +clearcoatOutParams clearcoatOut; +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); +#endif +#ifdef CLEARCOAT_BUMP +vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); +#endif +clearcoatOut=clearcoatBlock( +vPositionW +,geometricNormalW +,viewDirectionW +,vClearCoatParams +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +,clearCoatMapRoughnessData +#endif +,specularEnvironmentR0 +#ifdef CLEARCOAT_TEXTURE +,clearCoatMapData +#endif +#ifdef CLEARCOAT_TINT +,vClearCoatTintParams +,clearCoatColorAtDistance +,vClearCoatRefractionParams +#ifdef CLEARCOAT_TINT_TEXTURE +,clearCoatTintMapData +#endif +#endif +#ifdef CLEARCOAT_BUMP +,vClearCoatBumpInfos +,clearCoatBumpMapData +,vClearCoatBumpUV +#if defined(TANGENT) && defined(NORMAL) +,vTBN +#else +,vClearCoatTangentSpaceParams +#endif +#ifdef OBJECTSPACE_NORMALMAP +,normalMatrix +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +,faceNormal +#endif +#ifdef REFLECTION +,vReflectionMicrosurfaceInfos +,vReflectionInfos +,vReflectionColor +,vLightingIntensity +,reflectionSampler +#ifndef LODBASEDMICROSFURACE +,reflectionSamplerLow +,reflectionSamplerHigh +#endif +#ifdef REALTIME_FILTERING +,vReflectionFilteringInfo +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +,(gl_FrontFacing ? 1. : -1.) +#endif +); +#else +clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; +#endif +#include +subSurfaceOutParams subSurfaceOut; +#ifdef SUBSURFACE +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); +#endif +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE +vec4 translucencyColorMap=texture2D(translucencyColorSampler,vTranslucencyColorUV+uvOffset); +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA +translucencyColorMap=toLinearSpace(translucencyColorMap); +#endif +#endif +subSurfaceOut=subSurfaceBlock( +vSubSurfaceIntensity +,vThicknessParam +,vTintColor +,normalW +,specularEnvironmentReflectance +#ifdef SS_THICKNESSANDMASK_TEXTURE +,thicknessMap +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +,refractionIntensityMap +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +,translucencyIntensityMap +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +,reflectionMatrix +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +,reflectionOut.irradianceVector +#endif +#if defined(REALTIME_FILTERING) +,reflectionSampler +,vReflectionFilteringInfo +#ifdef IBL_CDF_FILTERING +,icdfSampler +#endif +#endif +#endif +#ifdef USEIRRADIANCEMAP +,irradianceSampler +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +,surfaceAlbedo +#endif +#ifdef SS_REFRACTION +,vPositionW +,viewDirectionW +,view +,vRefractionInfos +,refractionMatrix +,vRefractionMicrosurfaceInfos +,vLightingIntensity +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +,alpha +#endif +#ifdef SS_LODINREFRACTIONALPHA +,NdotVUnclamped +#endif +#ifdef SS_LINEARSPECULARREFRACTION +,roughness +#endif +,alphaG +,refractionSampler +#ifndef LODBASEDMICROSFURACE +,refractionSamplerLow +,refractionSamplerHigh +#endif +#ifdef ANISOTROPIC +,anisotropicOut +#endif +#ifdef REALTIME_FILTERING +,vRefractionFilteringInfo +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,vRefractionPosition +,vRefractionSize +#endif +#ifdef SS_DISPERSION +,dispersion +#endif +#endif +#ifdef SS_TRANSLUCENCY +,vDiffusionDistance +,vTranslucencyColor +#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE +,translucencyColorMap +#endif +#endif +); +#ifdef SS_REFRACTION +surfaceAlbedo=subSurfaceOut.surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha=subSurfaceOut.alpha; +#endif +#endif +#else +subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; +#endif +#include +#include[0..maxSimultaneousLights] +#include +#endif +#include +#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION +#include +#include +#include(color,finalColor) +#include +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +#include +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=finalColor; +#endif +#include +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} +#endif +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$4a]) { + ShaderStore.ShadersStore[name$4a] = shader$49; +} +/** @internal */ +const pbrPixelShader = { name: name$4a, shader: shader$49 }; + +const pbr_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + pbrPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Language of the shader code + */ +var ShaderLanguage; +(function (ShaderLanguage) { + /** language is GLSL (used by WebGL) */ + ShaderLanguage[ShaderLanguage["GLSL"] = 0] = "GLSL"; + /** language is WGSL (used by WebGPU) */ + ShaderLanguage[ShaderLanguage["WGSL"] = 1] = "WGSL"; +})(ShaderLanguage || (ShaderLanguage = {})); + +/** + * This represents a color grading texture. This acts as a lookup table LUT, useful during post process + * It can help converting any input color in a desired output one. This can then be used to create effects + * from sepia, black and white to sixties or futuristic rendering... + * + * The only supported format is currently 3dl. + * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table + */ +class ColorGradingTexture extends BaseTexture { + /** + * Instantiates a ColorGradingTexture from the following parameters. + * + * @param url The location of the color grading data (currently only supporting 3dl) + * @param sceneOrEngine The scene or engine the texture will be used in + * @param onLoad defines a callback triggered when the texture has been loaded + */ + constructor(url, sceneOrEngine, onLoad = null) { + super(sceneOrEngine); + if (!url) { + return; + } + this._textureMatrix = Matrix.Identity(); + this.name = url; + this.url = url; + this._onLoad = onLoad; + this._texture = this._getFromCache(url, true); + if (!this._texture) { + const scene = this.getScene(); + if (scene) { + if (!scene.useDelayedTextureLoading) { + this._loadTexture(); + } + else { + this.delayLoadState = 4; + } + } + else { + this._loadTexture(); + } + } + else { + this._triggerOnLoad(); + } + } + /** + * Fires the onload event from the constructor if requested. + */ + _triggerOnLoad() { + if (this._onLoad) { + this._onLoad(); + } + } + /** + * @returns the texture matrix used in most of the material. + * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in). + */ + getTextureMatrix() { + return this._textureMatrix; + } + /** + * Occurs when the file being loaded is a .3dl LUT file. + * @returns the 3D LUT texture + */ + _load3dlTexture() { + const engine = this._getEngine(); + let texture; + if (!engine._features.support3DTextures) { + texture = engine.createRawTexture(null, 1, 1, 5, false, false, 2, null, 0); + } + else { + texture = engine.createRawTexture3D(null, 1, 1, 1, 5, false, false, 2, null, 0); + } + this._texture = texture; + this._texture.isReady = false; + this.isCube = false; + this.is3D = engine._features.support3DTextures; + this.wrapU = 0; + this.wrapV = 0; + this.wrapR = 0; + this.anisotropicFilteringLevel = 1; + const callback = (text) => { + if (typeof text !== "string") { + return; + } + let data = null; + let tempData = null; + let line; + const lines = text.split("\n"); + let size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0; + let maxColor = 0; + for (let i = 0; i < lines.length; i++) { + line = lines[i]; + if (!ColorGradingTexture._NoneEmptyLineRegex.test(line)) { + continue; + } + if (line.indexOf("#") === 0) { + continue; + } + const words = line.split(" "); + if (size === 0) { + // Number of space + one + size = words.length; + data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8 + tempData = new Float32Array(size * size * size * 4); + continue; + } + if (size != 0) { + const r = Math.max(parseInt(words[0]), 0); + const g = Math.max(parseInt(words[1]), 0); + const b = Math.max(parseInt(words[2]), 0); + maxColor = Math.max(r, maxColor); + maxColor = Math.max(g, maxColor); + maxColor = Math.max(b, maxColor); + const pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4; + if (tempData) { + tempData[pixelStorageIndex + 0] = r; + tempData[pixelStorageIndex + 1] = g; + tempData[pixelStorageIndex + 2] = b; + } + // Keep for reference in case of back compat problems. + // pixelIndexSlice++; + // if (pixelIndexSlice % size == 0) { + // pixelIndexH++; + // pixelIndexSlice = 0; + // if (pixelIndexH % size == 0) { + // pixelIndexW++; + // pixelIndexH = 0; + // } + // } + pixelIndexH++; + if (pixelIndexH % size == 0) { + pixelIndexSlice++; + pixelIndexH = 0; + if (pixelIndexSlice % size == 0) { + pixelIndexW++; + pixelIndexSlice = 0; + } + } + } + } + if (tempData && data) { + for (let i = 0; i < tempData.length; i++) { + if (i > 0 && (i + 1) % 4 === 0) { + data[i] = 255; + } + else { + const value = tempData[i]; + data[i] = (value / maxColor) * 255; + } + } + } + if (texture.is3D) { + texture.updateSize(size, size, size); + engine.updateRawTexture3D(texture, data, 5, false); + } + else { + texture.updateSize(size * size, size); + engine.updateRawTexture(texture, data, 5, false); + } + texture.isReady = true; + this._triggerOnLoad(); + }; + const scene = this.getScene(); + if (scene) { + scene._loadFile(this.url, callback); + } + else { + engine._loadFile(this.url, callback); + } + return this._texture; + } + /** + * Starts the loading process of the texture. + */ + _loadTexture() { + if (this.url) { + const url = this.url.toLocaleLowerCase(); + if (url.endsWith(".3dl") || url.startsWith("blob:")) { + this._load3dlTexture(); + } + } + } + /** + * Clones the color grading texture. + * @returns the cloned texture + */ + clone() { + const newTexture = new ColorGradingTexture(this.url, this.getScene() || this._getEngine()); + // Base texture + newTexture.level = this.level; + return newTexture; + } + /** + * Called during delayed load for textures. + */ + delayLoad() { + if (this.delayLoadState !== 4) { + return; + } + this.delayLoadState = 1; + this._texture = this._getFromCache(this.url, true); + if (!this._texture) { + this._loadTexture(); + } + } + /** + * Parses a color grading texture serialized by Babylon. + * @param parsedTexture The texture information being parsedTexture + * @param scene The scene to load the texture in + * @returns A color grading texture + */ + static Parse(parsedTexture, scene) { + let texture = null; + if (parsedTexture.name && !parsedTexture.isRenderTarget) { + texture = new ColorGradingTexture(parsedTexture.name, scene); + texture.name = parsedTexture.name; + texture.level = parsedTexture.level; + } + return texture; + } + /** + * Serializes the LUT texture to json format. + * @returns The JSON representation of the texture + */ + serialize() { + if (!this.name) { + return null; + } + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.level = this.level; + serializationObject.customType = "BABYLON.ColorGradingTexture"; + return serializationObject; + } +} +/** + * Empty line regex stored for GC. + */ +ColorGradingTexture._NoneEmptyLineRegex = /\S+/; +RegisterClass("BABYLON.ColorGradingTexture", ColorGradingTexture); + +/** + * This represents a texture coming from an equirectangular image supported by the web browser canvas. + */ +class EquiRectangularCubeTexture extends BaseTexture { + /** + * Instantiates an EquiRectangularCubeTexture from the following parameters. + * @param url The location of the image + * @param scene The scene the texture will be used in + * @param size The cubemap desired size (the more it increases the longer the generation will be) + * @param noMipmap Forces to not generate the mipmap if true + * @param gammaSpace Specifies if the texture will be used in gamma or linear space + * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space) + * @param onLoad — defines a callback called when texture is loaded + * @param onError — defines a callback called if there is an error + * @param supersample — defines if texture must be supersampled (default: false) + */ + constructor(url, scene, size, noMipmap = false, gammaSpace = true, onLoad = null, onError = null, supersample = false) { + super(scene); + this._onLoad = null; + this._onError = null; + if (!url) { + throw new Error("Image url is not set"); + } + this._coordinatesMode = Texture.CUBIC_MODE; + this.name = url; + this.url = url; + this._size = size; + this._supersample = supersample; + this._noMipmap = noMipmap; + this.gammaSpace = gammaSpace; + this._onLoad = onLoad; + this._onError = onError; + this.hasAlpha = false; + this.isCube = true; + this._texture = this._getFromCache(url, this._noMipmap, undefined, undefined, undefined, this.isCube); + if (!this._texture) { + if (!scene.useDelayedTextureLoading) { + this._loadImage(() => this._loadTexture(), this._onError); + } + else { + this.delayLoadState = 4; + } + } + else if (onLoad) { + if (this._texture.isReady) { + Tools.SetImmediate(() => onLoad()); + } + else { + this._texture.onLoadedObservable.add(onLoad); + } + } + } + /** + * Load the image data, by putting the image on a canvas and extracting its buffer. + * @param loadTextureCallback + * @param onError + */ + _loadImage(loadTextureCallback, onError) { + const scene = this.getScene(); + if (!scene) { + return; + } + // Create texture before loading + const texture = scene + .getEngine() + .createRawCubeTexture(null, this._size, 4, scene.getEngine().getCaps().textureFloat ? 1 : 7, !this._noMipmap, false, 3); + texture.generateMipMaps = !this._noMipmap; + scene.addPendingData(texture); + texture.url = this.url; + texture.isReady = false; + scene.getEngine()._internalTexturesCache.push(texture); + this._texture = texture; + LoadImage(this.url, (image) => { + this._width = image.width; + this._height = image.height; + let canvas; + if (IsDocumentAvailable()) { + canvas = document.createElement("canvas"); + canvas.width = this._width; + canvas.height = this._height; + } + else { + // Canvas is not available in the current environment + canvas = new OffscreenCanvas(this._width, this._height); + } + const ctx = canvas.getContext("2d"); + ctx.drawImage(image, 0, 0); + const imageData = ctx.getImageData(0, 0, image.width, image.height); + this._buffer = imageData.data.buffer; + if (canvas.remove) { + canvas.remove(); + } + loadTextureCallback(); + }, (_, e) => { + scene.removePendingData(texture); + if (onError) { + onError(`${this.getClassName()} could not be loaded`, e); + } + }, scene ? scene.offlineProvider : null); + } + /** + * Convert the image buffer into a cubemap and create a CubeTexture. + */ + _loadTexture() { + const scene = this.getScene(); + const callback = () => { + const imageData = this._getFloat32ArrayFromArrayBuffer(this._buffer); + // Extract the raw linear data. + const data = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(imageData, this._width, this._height, this._size, this._supersample); + const results = []; + // Push each faces. + for (let i = 0; i < 6; i++) { + const dataFace = data[EquiRectangularCubeTexture._FacesMapping[i]]; + results.push(dataFace); + } + return results; + }; + if (!scene) { + return; + } + const faceDataArrays = callback(); + const texture = this._texture; + scene.getEngine().updateRawCubeTexture(texture, faceDataArrays, texture.format, texture.type, texture.invertY); + texture.isReady = true; + scene.removePendingData(texture); + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + if (this._onLoad) { + this._onLoad(); + } + } + /** + * Convert the ArrayBuffer into a Float32Array and drop the transparency channel. + * @param buffer The ArrayBuffer that should be converted. + * @returns The buffer as Float32Array. + */ + _getFloat32ArrayFromArrayBuffer(buffer) { + const dataView = new DataView(buffer); + const floatImageData = new Float32Array((buffer.byteLength * 3) / 4); + let k = 0; + for (let i = 0; i < buffer.byteLength; i++) { + // We drop the transparency channel, because we do not need/want it + if ((i + 1) % 4 !== 0) { + floatImageData[k++] = dataView.getUint8(i) / 255; + } + } + return floatImageData; + } + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "EquiRectangularCubeTexture" + */ + getClassName() { + return "EquiRectangularCubeTexture"; + } + /** + * Create a clone of the current EquiRectangularCubeTexture and return it. + * @returns A clone of the current EquiRectangularCubeTexture. + */ + clone() { + const scene = this.getScene(); + if (!scene) { + return this; + } + const newTexture = new EquiRectangularCubeTexture(this.url, scene, this._size, this._noMipmap, this.gammaSpace); + // Base texture + newTexture.level = this.level; + newTexture.wrapU = this.wrapU; + newTexture.wrapV = this.wrapV; + newTexture.coordinatesIndex = this.coordinatesIndex; + newTexture.coordinatesMode = this.coordinatesMode; + return newTexture; + } +} +/** The six faces of the cube. */ +EquiRectangularCubeTexture._FacesMapping = ["right", "left", "up", "down", "front", "back"]; + +/** + * This represents the smallest workload to use an already existing element (Canvas or Video) as a texture. + * To be as efficient as possible depending on your constraints nothing aside the first upload + * is automatically managed. + * It is a cheap VideoTexture or DynamicTexture if you prefer to keep full control of the elements + * in your application. + * + * As the update is not automatic, you need to call them manually. + */ +class HtmlElementTexture extends BaseTexture { + /** + * Instantiates a HtmlElementTexture from the following parameters. + * + * @param name Defines the name of the texture + * @param element Defines the video or canvas the texture is filled with + * @param options Defines the other none mandatory texture creation options + */ + constructor(name, element, options) { + super(options.scene || options.engine); + /** + * Observable triggered once the texture has been loaded. + */ + this.onLoadObservable = new Observable(); + if (!element || (!options.engine && !options.scene)) { + return; + } + options = { + ...HtmlElementTexture._DefaultOptions, + ...options, + }; + this._generateMipMaps = options.generateMipMaps; + this._samplingMode = options.samplingMode; + this._textureMatrix = Matrix.Identity(); + this._format = options.format; + this.name = name; + this.element = element; + this._isVideo = !!element.getVideoPlaybackQuality; + if (this._isVideo) { + const engineWebGPU = this._engine; + const createExternalTexture = engineWebGPU?.createExternalTexture; + if (createExternalTexture) { + this._externalTexture = createExternalTexture.call(engineWebGPU, element); + } + } + this.anisotropicFilteringLevel = 1; + this._createInternalTexture(); + } + _createInternalTexture() { + let width = 0; + let height = 0; + if (this._isVideo) { + width = this.element.videoWidth; + height = this.element.videoHeight; + } + else { + width = this.element.width; + height = this.element.height; + } + const engine = this._getEngine(); + if (engine) { + this._texture = engine.createDynamicTexture(width, height, this._generateMipMaps, this._samplingMode); + this._texture.format = this._format; + } + this.update(); + } + /** + * @returns the texture matrix used in most of the material. + */ + getTextureMatrix() { + return this._textureMatrix; + } + /** + * Updates the content of the texture. + * @param invertY Defines whether the texture should be inverted on Y (false by default on video and true on canvas) + */ + update(invertY = null) { + const engine = this._getEngine(); + if (this._texture == null || engine == null) { + return; + } + const wasReady = this.isReady(); + if (this._isVideo) { + const videoElement = this.element; + if (videoElement.readyState < videoElement.HAVE_CURRENT_DATA) { + return; + } + engine.updateVideoTexture(this._texture, this._externalTexture ? this._externalTexture : videoElement, invertY === null ? true : invertY); + } + else { + const canvasElement = this.element; + engine.updateDynamicTexture(this._texture, canvasElement, invertY === null ? true : invertY, false, this._format); + } + if (!wasReady && this.isReady()) { + this.onLoadObservable.notifyObservers(this); + } + } + /** + * Dispose the texture and release its associated resources. + */ + dispose() { + this.onLoadObservable.clear(); + super.dispose(); + } +} +HtmlElementTexture._DefaultOptions = { + generateMipMaps: false, + samplingMode: 2, + format: 5, + engine: null, + scene: null, +}; + +//private static _TYPE_NO_DATA = 0; +const _TYPE_INDEXED = 1; +const _TYPE_RGB = 2; +const _TYPE_GREY = 3; +const _TYPE_RLE_INDEXED = 9; +const _TYPE_RLE_RGB = 10; +const _TYPE_RLE_GREY = 11; +const _ORIGIN_MASK = 0x30; +const _ORIGIN_SHIFT = 0x04; +const _ORIGIN_BL = 0x00; +const _ORIGIN_BR = 0x01; +const _ORIGIN_UL = 0x02; +const _ORIGIN_UR = 0x03; +/** + * Gets the header of a TGA file + * @param data defines the TGA data + * @returns the header + */ +function GetTGAHeader(data) { + let offset = 0; + const header = { + id_length: data[offset++], + colormap_type: data[offset++], + image_type: data[offset++], + colormap_index: data[offset++] | (data[offset++] << 8), + colormap_length: data[offset++] | (data[offset++] << 8), + colormap_size: data[offset++], + origin: [data[offset++] | (data[offset++] << 8), data[offset++] | (data[offset++] << 8)], + width: data[offset++] | (data[offset++] << 8), + height: data[offset++] | (data[offset++] << 8), + pixel_size: data[offset++], + flags: data[offset++], + }; + return header; +} +/** + * Uploads TGA content to a Babylon Texture + * @internal + */ +function UploadContent(texture, data) { + // Not enough data to contain header ? + if (data.length < 19) { + Logger.Error("Unable to load TGA file - Not enough data to contain header"); + return; + } + // Read Header + let offset = 18; + const header = GetTGAHeader(data); + // Assume it's a valid Targa file. + if (header.id_length + offset > data.length) { + Logger.Error("Unable to load TGA file - Not enough data"); + return; + } + // Skip not needed data + offset += header.id_length; + let use_rle = false; + let use_pal = false; + let use_grey = false; + // Get some informations. + switch (header.image_type) { + case _TYPE_RLE_INDEXED: + use_rle = true; + // eslint-disable-next-line no-fallthrough + case _TYPE_INDEXED: + use_pal = true; + break; + case _TYPE_RLE_RGB: + use_rle = true; + // eslint-disable-next-line no-fallthrough + case _TYPE_RGB: + // use_rgb = true; + break; + case _TYPE_RLE_GREY: + use_rle = true; + // eslint-disable-next-line no-fallthrough + case _TYPE_GREY: + use_grey = true; + break; + } + let pixel_data; + // var numAlphaBits = header.flags & 0xf; + const pixel_size = header.pixel_size >> 3; + const pixel_total = header.width * header.height * pixel_size; + // Read palettes + let palettes; + if (use_pal) { + palettes = data.subarray(offset, (offset += header.colormap_length * (header.colormap_size >> 3))); + } + // Read LRE + if (use_rle) { + pixel_data = new Uint8Array(pixel_total); + let c, count, i; + let localOffset = 0; + const pixels = new Uint8Array(pixel_size); + while (offset < pixel_total && localOffset < pixel_total) { + c = data[offset++]; + count = (c & 0x7f) + 1; + // RLE pixels + if (c & 0x80) { + // Bind pixel tmp array + for (i = 0; i < pixel_size; ++i) { + pixels[i] = data[offset++]; + } + // Copy pixel array + for (i = 0; i < count; ++i) { + pixel_data.set(pixels, localOffset + i * pixel_size); + } + localOffset += pixel_size * count; + } + // Raw pixels + else { + count *= pixel_size; + for (i = 0; i < count; ++i) { + pixel_data[localOffset + i] = data[offset++]; + } + localOffset += count; + } + } + } + // RAW Pixels + else { + pixel_data = data.subarray(offset, (offset += use_pal ? header.width * header.height : pixel_total)); + } + // Load to texture + let x_start, y_start, x_step, y_step, y_end, x_end; + switch ((header.flags & _ORIGIN_MASK) >> _ORIGIN_SHIFT) { + default: + case _ORIGIN_UL: + x_start = 0; + x_step = 1; + x_end = header.width; + y_start = 0; + y_step = 1; + y_end = header.height; + break; + case _ORIGIN_BL: + x_start = 0; + x_step = 1; + x_end = header.width; + y_start = header.height - 1; + y_step = -1; + y_end = -1; + break; + case _ORIGIN_UR: + x_start = header.width - 1; + x_step = -1; + x_end = -1; + y_start = 0; + y_step = 1; + y_end = header.height; + break; + case _ORIGIN_BR: + x_start = header.width - 1; + x_step = -1; + x_end = -1; + y_start = header.height - 1; + y_step = -1; + y_end = -1; + break; + } + // Load the specify method + const func = "_getImageData" + (use_grey ? "Grey" : "") + header.pixel_size + "bits"; + const imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end); + const engine = texture.getEngine(); + engine._uploadDataToTextureDirectly(texture, imageData); +} +/** + * @internal + */ +function _getImageData8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { + const image = pixel_data, colormap = palettes; + const width = header.width, height = header.height; + let color, i = 0, x, y; + const imageData = new Uint8Array(width * height * 4); + for (y = y_start; y !== y_end; y += y_step) { + for (x = x_start; x !== x_end; x += x_step, i++) { + color = image[i]; + imageData[(x + width * y) * 4 + 3] = 255; + imageData[(x + width * y) * 4 + 2] = colormap[color * 3 + 0]; + imageData[(x + width * y) * 4 + 1] = colormap[color * 3 + 1]; + imageData[(x + width * y) * 4 + 0] = colormap[color * 3 + 2]; + } + } + return imageData; +} +/** + * @internal + */ +function _getImageData16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { + const image = pixel_data; + const width = header.width, height = header.height; + let color, i = 0, x, y; + const imageData = new Uint8Array(width * height * 4); + for (y = y_start; y !== y_end; y += y_step) { + for (x = x_start; x !== x_end; x += x_step, i += 2) { + color = image[i + 0] + (image[i + 1] << 8); // Inversed ? + const r = ((((color & 0x7c00) >> 10) * 255) / 0x1f) | 0; + const g = ((((color & 0x03e0) >> 5) * 255) / 0x1f) | 0; + const b = (((color & 0x001f) * 255) / 0x1f) | 0; + imageData[(x + width * y) * 4 + 0] = r; + imageData[(x + width * y) * 4 + 1] = g; + imageData[(x + width * y) * 4 + 2] = b; + imageData[(x + width * y) * 4 + 3] = color & 0x8000 ? 0 : 255; + } + } + return imageData; +} +/** + * @internal + */ +function _getImageData24bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { + const image = pixel_data; + const width = header.width, height = header.height; + let i = 0, x, y; + const imageData = new Uint8Array(width * height * 4); + for (y = y_start; y !== y_end; y += y_step) { + for (x = x_start; x !== x_end; x += x_step, i += 3) { + imageData[(x + width * y) * 4 + 3] = 255; + imageData[(x + width * y) * 4 + 2] = image[i + 0]; + imageData[(x + width * y) * 4 + 1] = image[i + 1]; + imageData[(x + width * y) * 4 + 0] = image[i + 2]; + } + } + return imageData; +} +/** + * @internal + */ +function _getImageData32bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { + const image = pixel_data; + const width = header.width, height = header.height; + let i = 0, x, y; + const imageData = new Uint8Array(width * height * 4); + for (y = y_start; y !== y_end; y += y_step) { + for (x = x_start; x !== x_end; x += x_step, i += 4) { + imageData[(x + width * y) * 4 + 2] = image[i + 0]; + imageData[(x + width * y) * 4 + 1] = image[i + 1]; + imageData[(x + width * y) * 4 + 0] = image[i + 2]; + imageData[(x + width * y) * 4 + 3] = image[i + 3]; + } + } + return imageData; +} +/** + * @internal + */ +function _getImageDataGrey8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { + const image = pixel_data; + const width = header.width, height = header.height; + let color, i = 0, x, y; + const imageData = new Uint8Array(width * height * 4); + for (y = y_start; y !== y_end; y += y_step) { + for (x = x_start; x !== x_end; x += x_step, i++) { + color = image[i]; + imageData[(x + width * y) * 4 + 0] = color; + imageData[(x + width * y) * 4 + 1] = color; + imageData[(x + width * y) * 4 + 2] = color; + imageData[(x + width * y) * 4 + 3] = 255; + } + } + return imageData; +} +/** + * @internal + */ +function _getImageDataGrey16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { + const image = pixel_data; + const width = header.width, height = header.height; + let i = 0, x, y; + const imageData = new Uint8Array(width * height * 4); + for (y = y_start; y !== y_end; y += y_step) { + for (x = x_start; x !== x_end; x += x_step, i += 2) { + imageData[(x + width * y) * 4 + 0] = image[i + 0]; + imageData[(x + width * y) * 4 + 1] = image[i + 0]; + imageData[(x + width * y) * 4 + 2] = image[i + 0]; + imageData[(x + width * y) * 4 + 3] = image[i + 1]; + } + } + return imageData; +} +/** + * Based on jsTGALoader - Javascript loader for TGA file + * By Vincent Thibault + * @see http://blog.robrowser.com/javascript-tga-loader.html + */ +const TGATools = { + /** + * Gets the header of a TGA file + * @param data defines the TGA data + * @returns the header + */ + GetTGAHeader, + /** + * Uploads TGA content to a Babylon Texture + * @internal + */ + UploadContent, + /** @internal */ + _getImageData8bits, + /** @internal */ + _getImageData16bits, + /** @internal */ + _getImageData24bits, + /** @internal */ + _getImageData32bits, + /** @internal */ + _getImageDataGrey8bits, + /** @internal */ + _getImageDataGrey16bits, +}; + +/** + * Implementation of the TGA Texture Loader. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _TGATextureLoader { + constructor() { + /** + * Defines whether the loader supports cascade loading the different faces. + */ + this.supportCascades = false; + } + /** + * Uploads the cube texture data to the WebGL texture. It has already been bound. + */ + loadCubeData() { + // eslint-disable-next-line no-throw-literal + throw ".env not supported in Cube."; + } + /** + * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + */ + loadData(data, texture, callback) { + const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + const header = GetTGAHeader(bytes); + callback(header.width, header.height, texture.generateMipMaps, false, () => { + UploadContent(texture, bytes); + }); + } +} + +const tgaTextureLoader = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + _TGATextureLoader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Implementation of the HDR Texture Loader. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _HDRTextureLoader { + constructor() { + /** + * Defines whether the loader supports cascade loading the different faces. + */ + this.supportCascades = false; + } + /** + * Uploads the cube texture data to the WebGL texture. It has already been bound. + * Cube texture are not supported by .hdr files + */ + loadCubeData() { + // eslint-disable-next-line no-throw-literal + throw ".hdr not supported in Cube."; + } + /** + * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + */ + loadData(data, texture, callback) { + const uint8array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + const hdrInfo = RGBE_ReadHeader(uint8array); + const pixelsDataRGB32 = RGBE_ReadPixels(uint8array, hdrInfo); + const pixels = hdrInfo.width * hdrInfo.height; + const pixelsDataRGBA32 = new Float32Array(pixels * 4); + for (let i = 0; i < pixels; i += 1) { + pixelsDataRGBA32[i * 4] = pixelsDataRGB32[i * 3]; + pixelsDataRGBA32[i * 4 + 1] = pixelsDataRGB32[i * 3 + 1]; + pixelsDataRGBA32[i * 4 + 2] = pixelsDataRGB32[i * 3 + 2]; + pixelsDataRGBA32[i * 4 + 3] = 1; + } + callback(hdrInfo.width, hdrInfo.height, texture.generateMipMaps, false, () => { + const engine = texture.getEngine(); + texture.type = 1; + texture.format = 5; + texture._gammaSpace = false; + engine._uploadDataToTextureDirectly(texture, pixelsDataRGBA32); + }); + } +} + +const hdrTextureLoader = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + _HDRTextureLoader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * The worker function that gets converted to a blob url to pass into a worker. + * To be used if a developer wants to create their own worker instance and inject it instead of using the default worker. + */ +function workerFunction() { + const _BASIS_FORMAT = { + cTFETC1: 0, + cTFETC2: 1, + cTFBC1: 2, + cTFBC3: 3, + cTFBC7: 6, + cTFPVRTC1_4_RGB: 8, + cTFPVRTC1_4_RGBA: 9, + cTFASTC_4x4: 10, + cTFRGB565: 14}; + let transcoderModulePromise = null; + onmessage = (event) => { + if (event.data.action === "init") { + // Load the transcoder if it hasn't been yet + if (event.data.url) { + // make sure we loaded the script correctly + try { + importScripts(event.data.url); + } + catch (e) { + postMessage({ action: "error", error: e }); + } + } + if (!transcoderModulePromise) { + transcoderModulePromise = BASIS({ + // Override wasm binary + wasmBinary: event.data.wasmBinary, + }); + } + if (transcoderModulePromise !== null) { + transcoderModulePromise.then((m) => { + BASIS = m; + m.initializeBasis(); + postMessage({ action: "init" }); + }); + } + } + else if (event.data.action === "transcode") { + // Transcode the basis image and return the resulting pixels + const config = event.data.config; + const imgData = event.data.imageData; + const loadedFile = new BASIS.BasisFile(imgData); + const fileInfo = GetFileInfo(loadedFile); + let format = event.data.ignoreSupportedFormats ? null : GetSupportedTranscodeFormat(event.data.config, fileInfo); + let needsConversion = false; + if (format === null) { + needsConversion = true; + format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1; + } + // Begin transcode + let success = true; + if (!loadedFile.startTranscoding()) { + success = false; + } + const buffers = []; + for (let imageIndex = 0; imageIndex < fileInfo.images.length; imageIndex++) { + if (!success) { + break; + } + const image = fileInfo.images[imageIndex]; + if (config.loadSingleImage === undefined || config.loadSingleImage === imageIndex) { + let mipCount = image.levels.length; + if (config.loadMipmapLevels === false) { + mipCount = 1; + } + for (let levelIndex = 0; levelIndex < mipCount; levelIndex++) { + const levelInfo = image.levels[levelIndex]; + const pixels = TranscodeLevel(loadedFile, imageIndex, levelIndex, format, needsConversion); + if (!pixels) { + success = false; + break; + } + levelInfo.transcodedPixels = pixels; + buffers.push(levelInfo.transcodedPixels.buffer); + } + } + } + // Close file + loadedFile.close(); + loadedFile.delete(); + if (needsConversion) { + format = -1; + } + if (!success) { + postMessage({ action: "transcode", success: success, id: event.data.id }); + } + else { + postMessage({ action: "transcode", success: success, id: event.data.id, fileInfo: fileInfo, format: format }, buffers); + } + } + }; + /** + * Detects the supported transcode format for the file + * @param config transcode config + * @param fileInfo info about the file + * @returns the chosed format or null if none are supported + */ + function GetSupportedTranscodeFormat(config, fileInfo) { + let format = null; + if (config.supportedCompressionFormats) { + if (config.supportedCompressionFormats.astc) { + format = _BASIS_FORMAT.cTFASTC_4x4; + } + else if (config.supportedCompressionFormats.bc7) { + format = _BASIS_FORMAT.cTFBC7; + } + else if (config.supportedCompressionFormats.s3tc) { + format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1; + } + else if (config.supportedCompressionFormats.pvrtc) { + format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFPVRTC1_4_RGBA : _BASIS_FORMAT.cTFPVRTC1_4_RGB; + } + else if (config.supportedCompressionFormats.etc2) { + format = _BASIS_FORMAT.cTFETC2; + } + else if (config.supportedCompressionFormats.etc1) { + format = _BASIS_FORMAT.cTFETC1; + } + else { + format = _BASIS_FORMAT.cTFRGB565; + } + } + return format; + } + /** + * Retrieves information about the basis file eg. dimensions + * @param basisFile the basis file to get the info from + * @returns information about the basis file + */ + function GetFileInfo(basisFile) { + const hasAlpha = basisFile.getHasAlpha(); + const imageCount = basisFile.getNumImages(); + const images = []; + for (let i = 0; i < imageCount; i++) { + const imageInfo = { + levels: [], + }; + const levelCount = basisFile.getNumLevels(i); + for (let level = 0; level < levelCount; level++) { + const levelInfo = { + width: basisFile.getImageWidth(i, level), + height: basisFile.getImageHeight(i, level), + }; + imageInfo.levels.push(levelInfo); + } + images.push(imageInfo); + } + const info = { hasAlpha, images }; + return info; + } + function TranscodeLevel(loadedFile, imageIndex, levelIndex, format, convertToRgb565) { + const dstSize = loadedFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, format); + let dst = new Uint8Array(dstSize); + if (!loadedFile.transcodeImage(dst, imageIndex, levelIndex, format, 1, 0)) { + return null; + } + // If no supported format is found, load as dxt and convert to rgb565 + if (convertToRgb565) { + const alignedWidth = (loadedFile.getImageWidth(imageIndex, levelIndex) + 3) & -4; + const alignedHeight = (loadedFile.getImageHeight(imageIndex, levelIndex) + 3) & -4; + dst = ConvertDxtToRgb565(dst, 0, alignedWidth, alignedHeight); + } + return dst; + } + /** + * From https://github.com/BinomialLLC/basis_universal/blob/master/webgl/texture/dxt-to-rgb565.js + * An unoptimized version of dxtToRgb565. Also, the floating + * point math used to compute the colors actually results in + * slightly different colors compared to hardware DXT decoders. + * @param src dxt src pixels + * @param srcByteOffset offset for the start of src + * @param width aligned width of the image + * @param height aligned height of the image + * @returns the converted pixels + */ + function ConvertDxtToRgb565(src, srcByteOffset, width, height) { + const c = new Uint16Array(4); + const dst = new Uint16Array(width * height); + const blockWidth = width / 4; + const blockHeight = height / 4; + for (let blockY = 0; blockY < blockHeight; blockY++) { + for (let blockX = 0; blockX < blockWidth; blockX++) { + const i = srcByteOffset + 8 * (blockY * blockWidth + blockX); + c[0] = src[i] | (src[i + 1] << 8); + c[1] = src[i + 2] | (src[i + 3] << 8); + c[2] = + ((2 * (c[0] & 0x1f) + 1 * (c[1] & 0x1f)) / 3) | + (((2 * (c[0] & 0x7e0) + 1 * (c[1] & 0x7e0)) / 3) & 0x7e0) | + (((2 * (c[0] & 0xf800) + 1 * (c[1] & 0xf800)) / 3) & 0xf800); + c[3] = + ((2 * (c[1] & 0x1f) + 1 * (c[0] & 0x1f)) / 3) | + (((2 * (c[1] & 0x7e0) + 1 * (c[0] & 0x7e0)) / 3) & 0x7e0) | + (((2 * (c[1] & 0xf800) + 1 * (c[0] & 0xf800)) / 3) & 0xf800); + for (let row = 0; row < 4; row++) { + const m = src[i + 4 + row]; + let dstI = (blockY * 4 + row) * width + blockX * 4; + dst[dstI++] = c[m & 0x3]; + dst[dstI++] = c[(m >> 2) & 0x3]; + dst[dstI++] = c[(m >> 4) & 0x3]; + dst[dstI++] = c[(m >> 6) & 0x3]; + } + } + } + return dst; + } +} +/** + * Initialize a web worker with the basis transcoder + * @param worker the worker to initialize + * @param wasmBinary the wasm binary to load into the worker + * @param moduleUrl the url to the basis transcoder module + * @returns a promise that resolves when the worker is initialized + */ +function initializeWebWorker(worker, wasmBinary, moduleUrl) { + return new Promise((res, reject) => { + const initHandler = (msg) => { + if (msg.data.action === "init") { + worker.removeEventListener("message", initHandler); + res(worker); + } + else if (msg.data.action === "error") { + reject(msg.data.error || "error initializing worker"); + } + }; + worker.addEventListener("message", initHandler); + // we can use transferable objects here because the worker will own the ArrayBuffer + worker.postMessage({ action: "init", url: moduleUrl ? Tools.GetBabylonScriptURL(moduleUrl) : undefined, wasmBinary }, [wasmBinary]); + }); +} + +/** + * @internal + * Enum of basis transcoder formats + */ +var BASIS_FORMATS; +(function (BASIS_FORMATS) { + BASIS_FORMATS[BASIS_FORMATS["cTFETC1"] = 0] = "cTFETC1"; + BASIS_FORMATS[BASIS_FORMATS["cTFETC2"] = 1] = "cTFETC2"; + BASIS_FORMATS[BASIS_FORMATS["cTFBC1"] = 2] = "cTFBC1"; + BASIS_FORMATS[BASIS_FORMATS["cTFBC3"] = 3] = "cTFBC3"; + BASIS_FORMATS[BASIS_FORMATS["cTFBC4"] = 4] = "cTFBC4"; + BASIS_FORMATS[BASIS_FORMATS["cTFBC5"] = 5] = "cTFBC5"; + BASIS_FORMATS[BASIS_FORMATS["cTFBC7"] = 6] = "cTFBC7"; + BASIS_FORMATS[BASIS_FORMATS["cTFPVRTC1_4_RGB"] = 8] = "cTFPVRTC1_4_RGB"; + BASIS_FORMATS[BASIS_FORMATS["cTFPVRTC1_4_RGBA"] = 9] = "cTFPVRTC1_4_RGBA"; + BASIS_FORMATS[BASIS_FORMATS["cTFASTC_4x4"] = 10] = "cTFASTC_4x4"; + BASIS_FORMATS[BASIS_FORMATS["cTFATC_RGB"] = 11] = "cTFATC_RGB"; + BASIS_FORMATS[BASIS_FORMATS["cTFATC_RGBA_INTERPOLATED_ALPHA"] = 12] = "cTFATC_RGBA_INTERPOLATED_ALPHA"; + BASIS_FORMATS[BASIS_FORMATS["cTFRGBA32"] = 13] = "cTFRGBA32"; + BASIS_FORMATS[BASIS_FORMATS["cTFRGB565"] = 14] = "cTFRGB565"; + BASIS_FORMATS[BASIS_FORMATS["cTFBGR565"] = 15] = "cTFBGR565"; + BASIS_FORMATS[BASIS_FORMATS["cTFRGBA4444"] = 16] = "cTFRGBA4444"; + BASIS_FORMATS[BASIS_FORMATS["cTFFXT1_RGB"] = 17] = "cTFFXT1_RGB"; + BASIS_FORMATS[BASIS_FORMATS["cTFPVRTC2_4_RGB"] = 18] = "cTFPVRTC2_4_RGB"; + BASIS_FORMATS[BASIS_FORMATS["cTFPVRTC2_4_RGBA"] = 19] = "cTFPVRTC2_4_RGBA"; + BASIS_FORMATS[BASIS_FORMATS["cTFETC2_EAC_R11"] = 20] = "cTFETC2_EAC_R11"; + BASIS_FORMATS[BASIS_FORMATS["cTFETC2_EAC_RG11"] = 21] = "cTFETC2_EAC_RG11"; +})(BASIS_FORMATS || (BASIS_FORMATS = {})); +/** + * Used to load .Basis files + * See https://github.com/BinomialLLC/basis_universal/tree/master/webgl + */ +const BasisToolsOptions = { + /** + * URL to use when loading the basis transcoder + */ + JSModuleURL: `${Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`, + /** + * URL to use when loading the wasm module for the transcoder + */ + WasmModuleURL: `${Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`, +}; +/** + * Get the internal format to be passed to texImage2D corresponding to the .basis format value + * @param basisFormat format chosen from GetSupportedTranscodeFormat + * @param engine + * @returns internal format corresponding to the Basis format + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +const GetInternalFormatFromBasisFormat = (basisFormat, engine) => { + let format; + switch (basisFormat) { + case BASIS_FORMATS.cTFETC1: + format = 36196; + break; + case BASIS_FORMATS.cTFBC1: + format = 33776; + break; + case BASIS_FORMATS.cTFBC4: + format = 33779; + break; + case BASIS_FORMATS.cTFASTC_4x4: + format = 37808; + break; + case BASIS_FORMATS.cTFETC2: + format = 37496; + break; + case BASIS_FORMATS.cTFBC7: + format = 36492; + break; + } + if (format === undefined) { + // eslint-disable-next-line no-throw-literal + throw "The chosen Basis transcoder format is not currently supported"; + } + return format; +}; +let _WorkerPromise = null; +let _Worker = null; +let _actionId = 0; +const _IgnoreSupportedFormats = false; +const _CreateWorkerAsync = () => { + if (!_WorkerPromise) { + _WorkerPromise = new Promise((res, reject) => { + if (_Worker) { + res(_Worker); + } + else { + Tools.LoadFileAsync(Tools.GetBabylonScriptURL(BasisToolsOptions.WasmModuleURL)) + .then((wasmBinary) => { + if (typeof URL !== "function") { + return reject("Basis transcoder requires an environment with a URL constructor"); + } + const workerBlobUrl = URL.createObjectURL(new Blob([`(${workerFunction})()`], { type: "application/javascript" })); + _Worker = new Worker(workerBlobUrl); + initializeWebWorker(_Worker, wasmBinary, BasisToolsOptions.JSModuleURL).then(res, reject); + }) + .catch(reject); + } + }); + } + return _WorkerPromise; +}; +/** + * Transcodes a loaded image file to compressed pixel data + * @param data image data to transcode + * @param config configuration options for the transcoding + * @returns a promise resulting in the transcoded image + */ +const TranscodeAsync = (data, config) => { + const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data; + return new Promise((res, rej) => { + _CreateWorkerAsync().then(() => { + const actionId = _actionId++; + const messageHandler = (msg) => { + if (msg.data.action === "transcode" && msg.data.id === actionId) { + _Worker.removeEventListener("message", messageHandler); + if (!msg.data.success) { + rej("Transcode is not supported on this device"); + } + else { + res(msg.data); + } + } + }; + _Worker.addEventListener("message", messageHandler); + const dataViewCopy = new Uint8Array(dataView.byteLength); + dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength)); + _Worker.postMessage({ action: "transcode", id: actionId, imageData: dataViewCopy, config: config, ignoreSupportedFormats: _IgnoreSupportedFormats }, [ + dataViewCopy.buffer, + ]); + }, (error) => { + rej(error); + }); + }); +}; +/** + * Binds a texture according to its underlying target. + * @param texture texture to bind + * @param engine the engine to bind the texture in + */ +const BindTexture = (texture, engine) => { + let target = engine._gl?.TEXTURE_2D; + if (texture.isCube) { + target = engine._gl?.TEXTURE_CUBE_MAP; + } + engine._bindTextureDirectly(target, texture, true); +}; +/** + * Loads a texture from the transcode result + * @param texture texture load to + * @param transcodeResult the result of transcoding the basis file to load from + */ +const LoadTextureFromTranscodeResult = (texture, transcodeResult) => { + const engine = texture.getEngine(); + for (let i = 0; i < transcodeResult.fileInfo.images.length; i++) { + const rootImage = transcodeResult.fileInfo.images[i].levels[0]; + texture._invertVScale = texture.invertY; + if (transcodeResult.format === -1 || transcodeResult.format === BASIS_FORMATS.cTFRGB565) { + // No compatable compressed format found, fallback to RGB + texture.type = 10; + texture.format = 4; + if (engine._features.basisNeedsPOT && (Math.log2(rootImage.width) % 1 !== 0 || Math.log2(rootImage.height) % 1 !== 0)) { + // Create non power of two texture + const source = new InternalTexture(engine, 2 /* InternalTextureSource.Temp */); + texture._invertVScale = texture.invertY; + source.type = 10; + source.format = 4; + // Fallback requires aligned width/height + source.width = (rootImage.width + 3) & -4; + source.height = (rootImage.height + 3) & -4; + BindTexture(source, engine); + engine._uploadDataToTextureDirectly(source, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true); + // Resize to power of two + engine._rescaleTexture(source, texture, engine.scenes[0], engine._getInternalFormat(4), () => { + engine._releaseTexture(source); + BindTexture(texture, engine); + }); + } + else { + // Fallback is already inverted + texture._invertVScale = !texture.invertY; + // Upload directly + texture.width = (rootImage.width + 3) & -4; + texture.height = (rootImage.height + 3) & -4; + texture.samplingMode = 2; + BindTexture(texture, engine); + engine._uploadDataToTextureDirectly(texture, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true); + } + } + else { + texture.width = rootImage.width; + texture.height = rootImage.height; + texture.generateMipMaps = transcodeResult.fileInfo.images[i].levels.length > 1; + const format = BasisTools.GetInternalFormatFromBasisFormat(transcodeResult.format, engine); + texture.format = format; + BindTexture(texture, engine); + // Upload all mip levels in the file + transcodeResult.fileInfo.images[i].levels.forEach((level, index) => { + engine._uploadCompressedDataToTextureDirectly(texture, format, level.width, level.height, level.transcodedPixels, i, index); + }); + if (engine._features.basisNeedsPOT && (Math.log2(texture.width) % 1 !== 0 || Math.log2(texture.height) % 1 !== 0)) { + Tools.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."); + texture._cachedWrapU = Texture.CLAMP_ADDRESSMODE; + texture._cachedWrapV = Texture.CLAMP_ADDRESSMODE; + } + } + } +}; +/** + * Used to load .Basis files + * See https://github.com/BinomialLLC/basis_universal/tree/master/webgl + */ +const BasisTools = { + /** + * URL to use when loading the basis transcoder + */ + JSModuleURL: BasisToolsOptions.JSModuleURL, + /** + * URL to use when loading the wasm module for the transcoder + */ + WasmModuleURL: BasisToolsOptions.WasmModuleURL, + /** + * Get the internal format to be passed to texImage2D corresponding to the .basis format value + * @param basisFormat format chosen from GetSupportedTranscodeFormat + * @returns internal format corresponding to the Basis format + */ + GetInternalFormatFromBasisFormat, + /** + * Transcodes a loaded image file to compressed pixel data + * @param data image data to transcode + * @param config configuration options for the transcoding + * @returns a promise resulting in the transcoded image + */ + TranscodeAsync, + /** + * Loads a texture from the transcode result + * @param texture texture load to + * @param transcodeResult the result of transcoding the basis file to load from + */ + LoadTextureFromTranscodeResult, +}; +Object.defineProperty(BasisTools, "JSModuleURL", { + get: function () { + return BasisToolsOptions.JSModuleURL; + }, + set: function (value) { + BasisToolsOptions.JSModuleURL = value; + }, +}); +Object.defineProperty(BasisTools, "WasmModuleURL", { + get: function () { + return BasisToolsOptions.WasmModuleURL; + }, + set: function (value) { + BasisToolsOptions.WasmModuleURL = value; + }, +}); + +/** + * Loader for .basis file format + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _BasisTextureLoader { + constructor() { + /** + * Defines whether the loader supports cascade loading the different faces. + */ + this.supportCascades = false; + } + /** + * Uploads the cube texture data to the WebGL texture. It has already been bound. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param createPolynomials will be true if polynomials have been requested + * @param onLoad defines the callback to trigger once the texture is ready + * @param onError defines the callback to trigger in case of error + */ + loadCubeData(data, texture, createPolynomials, onLoad, onError) { + if (Array.isArray(data)) { + return; + } + const caps = texture.getEngine().getCaps(); + const transcodeConfig = { + supportedCompressionFormats: { + etc1: caps.etc1 ? true : false, + s3tc: caps.s3tc ? true : false, + pvrtc: caps.pvrtc ? true : false, + etc2: caps.etc2 ? true : false, + astc: caps.astc ? true : false, + bc7: caps.bptc ? true : false, + }, + }; + TranscodeAsync(data, transcodeConfig) + .then((result) => { + const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps; + LoadTextureFromTranscodeResult(texture, result); + texture.getEngine()._setCubeMapTextureParams(texture, hasMipmap); + texture.isReady = true; + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + if (onLoad) { + onLoad(); + } + }) + .catch((err) => { + const errorMessage = "Failed to transcode Basis file, transcoding may not be supported on this device"; + Tools.Warn(errorMessage); + texture.isReady = true; + if (onError) { + onError(err); + } + }); + } + /** + * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + */ + loadData(data, texture, callback) { + const caps = texture.getEngine().getCaps(); + const transcodeConfig = { + supportedCompressionFormats: { + etc1: caps.etc1 ? true : false, + s3tc: caps.s3tc ? true : false, + pvrtc: caps.pvrtc ? true : false, + etc2: caps.etc2 ? true : false, + astc: caps.astc ? true : false, + bc7: caps.bptc ? true : false, + }, + }; + TranscodeAsync(data, transcodeConfig) + .then((result) => { + const rootImage = result.fileInfo.images[0].levels[0]; + const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps; + callback(rootImage.width, rootImage.height, hasMipmap, result.format !== -1, () => { + LoadTextureFromTranscodeResult(texture, result); + }); + }) + .catch((err) => { + Tools.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"); + Tools.Warn(`Failed to transcode Basis file: ${err}`); + callback(0, 0, false, false, () => { }, true); + }); + } +} + +const basisTextureLoader = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + _BasisTextureLoader +}, Symbol.toStringTag, { value: 'Module' })); + +const INT32_SIZE = 4; +const FLOAT32_SIZE = 4; +const INT8_SIZE = 1; +const INT16_SIZE = 2; +const ULONG_SIZE = 8; +const USHORT_RANGE = 1 << 16; +const BITMAP_SIZE = USHORT_RANGE >> 3; +const HUF_ENCBITS = 16; +const HUF_DECBITS = 14; +const HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; +const HUF_DECSIZE = 1 << HUF_DECBITS; +const HUF_DECMASK = HUF_DECSIZE - 1; +const SHORT_ZEROCODE_RUN = 59; +const LONG_ZEROCODE_RUN = 63; +const SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; + +/** + * Inspired by https://github.com/sciecode/three.js/blob/dev/examples/jsm/loaders/EXRLoader.js + * Referred to the original Industrial Light & Magic OpenEXR implementation and the TinyEXR / Syoyo Fujita + * implementation. + */ +// /* +// Copyright (c) 2014 - 2017, Syoyo Fujita +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Syoyo Fujita nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// */ +// // TinyEXR contains some OpenEXR code, which is licensed under ------------ +// /////////////////////////////////////////////////////////////////////////// +// // +// // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas +// // Digital Ltd. LLC +// // +// // All rights reserved. +// // +// // Redistribution and use in source and binary forms, with or without +// // modification, are permitted provided that the following conditions are +// // met: +// // * Redistributions of source code must retain the above copyright +// // notice, this list of conditions and the following disclaimer. +// // * Redistributions in binary form must reproduce the above +// // copyright notice, this list of conditions and the following disclaimer +// // in the documentation and/or other materials provided with the +// // distribution. +// // * Neither the name of Industrial Light & Magic nor the names of +// // its contributors may be used to endorse or promote products derived +// // from this software without specific prior written permission. +// // +// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// // +// /////////////////////////////////////////////////////////////////////////// +// // End of OpenEXR license ------------------------------------------------- +var CompressionCodes; +(function (CompressionCodes) { + CompressionCodes[CompressionCodes["NO_COMPRESSION"] = 0] = "NO_COMPRESSION"; + CompressionCodes[CompressionCodes["RLE_COMPRESSION"] = 1] = "RLE_COMPRESSION"; + CompressionCodes[CompressionCodes["ZIPS_COMPRESSION"] = 2] = "ZIPS_COMPRESSION"; + CompressionCodes[CompressionCodes["ZIP_COMPRESSION"] = 3] = "ZIP_COMPRESSION"; + CompressionCodes[CompressionCodes["PIZ_COMPRESSION"] = 4] = "PIZ_COMPRESSION"; + CompressionCodes[CompressionCodes["PXR24_COMPRESSION"] = 5] = "PXR24_COMPRESSION"; +})(CompressionCodes || (CompressionCodes = {})); +var LineOrders; +(function (LineOrders) { + LineOrders[LineOrders["INCREASING_Y"] = 0] = "INCREASING_Y"; + LineOrders[LineOrders["DECREASING_Y"] = 1] = "DECREASING_Y"; +})(LineOrders || (LineOrders = {})); +const _tables = _GenerateTables(); +// Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf +function _GenerateTables() { + // float32 to float16 helpers + const buffer = new ArrayBuffer(4); + const floatView = new Float32Array(buffer); + const uint32View = new Uint32Array(buffer); + const baseTable = new Uint32Array(512); + const shiftTable = new Uint32Array(512); + for (let i = 0; i < 256; ++i) { + const e = i - 127; + // very small number (0, -0) + if (e < -27) { + baseTable[i] = 0x0000; + baseTable[i | 0x100] = 0x8000; + shiftTable[i] = 24; + shiftTable[i | 0x100] = 24; + // small number (denorm) + } + else if (e < -14) { + baseTable[i] = 0x0400 >> (-e - 14); + baseTable[i | 0x100] = (0x0400 >> (-e - 14)) | 0x8000; + shiftTable[i] = -e - 1; + shiftTable[i | 0x100] = -e - 1; + // normal number + } + else if (e <= 15) { + baseTable[i] = (e + 15) << 10; + baseTable[i | 0x100] = ((e + 15) << 10) | 0x8000; + shiftTable[i] = 13; + shiftTable[i | 0x100] = 13; + // large number (Infinity, -Infinity) + } + else if (e < 128) { + baseTable[i] = 0x7c00; + baseTable[i | 0x100] = 0xfc00; + shiftTable[i] = 24; + shiftTable[i | 0x100] = 24; + // stay (NaN, Infinity, -Infinity) + } + else { + baseTable[i] = 0x7c00; + baseTable[i | 0x100] = 0xfc00; + shiftTable[i] = 13; + shiftTable[i | 0x100] = 13; + } + } + // float16 to float32 helpers + const mantissaTable = new Uint32Array(2048); + const exponentTable = new Uint32Array(64); + const offsetTable = new Uint32Array(64); + for (let i = 1; i < 1024; ++i) { + let m = i << 13; // zero pad mantissa bits + let e = 0; // zero exponent + // normalized + while ((m & 0x00800000) === 0) { + m <<= 1; + e -= 0x00800000; // decrement exponent + } + m &= -8388609; // clear leading 1 bit + e += 0x38800000; // adjust bias + mantissaTable[i] = m | e; + } + for (let i = 1024; i < 2048; ++i) { + mantissaTable[i] = 0x38000000 + ((i - 1024) << 13); + } + for (let i = 1; i < 31; ++i) { + exponentTable[i] = i << 23; + } + exponentTable[31] = 0x47800000; + exponentTable[32] = 0x80000000; + for (let i = 33; i < 63; ++i) { + exponentTable[i] = 0x80000000 + ((i - 32) << 23); + } + exponentTable[63] = 0xc7800000; + for (let i = 1; i < 64; ++i) { + if (i !== 32) { + offsetTable[i] = 1024; + } + } + return { + floatView: floatView, + uint32View: uint32View, + baseTable: baseTable, + shiftTable: shiftTable, + mantissaTable: mantissaTable, + exponentTable: exponentTable, + offsetTable: offsetTable, + }; +} +/** + * Parse a null terminated string from the buffer + * @param buffer buffer to read from + * @param offset current offset in the buffer + * @returns a string + */ +function ParseNullTerminatedString(buffer, offset) { + const uintBuffer = new Uint8Array(buffer); + let endOffset = 0; + while (uintBuffer[offset.value + endOffset] != 0) { + endOffset += 1; + } + const stringValue = new TextDecoder().decode(uintBuffer.slice(offset.value, offset.value + endOffset)); + offset.value = offset.value + endOffset + 1; + return stringValue; +} +/** + * Parse an int32 from the buffer + * @param dataView dataview on the data + * @param offset current offset in the data view + * @returns an int32 + */ +function ParseInt32(dataView, offset) { + const value = dataView.getInt32(offset.value, true); + offset.value += INT32_SIZE; + return value; +} +/** + * Parse an uint32 from the buffer + * @param dataView data view to read from + * @param offset offset in the data view + * @returns an uint32 + */ +function ParseUint32(dataView, offset) { + const value = dataView.getUint32(offset.value, true); + offset.value += INT32_SIZE; + return value; +} +/** + * Parse an uint8 from the buffer + * @param dataView dataview on the data + * @param offset current offset in the data view + * @returns an uint8 + */ +function ParseUint8(dataView, offset) { + const value = dataView.getUint8(offset.value); + offset.value += INT8_SIZE; + return value; +} +/** + * Parse an uint16 from the buffer + * @param dataView dataview on the data + * @param offset current offset in the data view + * @returns an uint16 + */ +function ParseUint16(dataView, offset) { + const value = dataView.getUint16(offset.value, true); + offset.value += INT16_SIZE; + return value; +} +/** + * Parse an uint8 from an array buffer + * @param array array buffer + * @param offset current offset in the data view + * @returns an uint16 + */ +function ParseUint8Array(array, offset) { + const value = array[offset.value]; + offset.value += INT8_SIZE; + return value; +} +/** + * Parse an int64 from the buffer + * @param dataView dataview on the data + * @param offset current offset in the data view + * @returns an int64 + */ +function ParseInt64(dataView, offset) { + let int; + if ("getBigInt64" in DataView.prototype) { + int = Number(dataView.getBigInt64(offset.value, true)); + } + else { + int = dataView.getUint32(offset.value + 4, true) + Number(dataView.getUint32(offset.value, true) << 32); + } + offset.value += ULONG_SIZE; + return int; +} +/** + * Parse a float32 from the buffer + * @param dataView dataview on the data + * @param offset current offset in the data view + * @returns a float32 + */ +function ParseFloat32(dataView, offset) { + const value = dataView.getFloat32(offset.value, true); + offset.value += FLOAT32_SIZE; + return value; +} +/** + * Parse a float16 from the buffer + * @param dataView dataview on the data + * @param offset current offset in the data view + * @returns a float16 + */ +function ParseFloat16(dataView, offset) { + return DecodeFloat16(ParseUint16(dataView, offset)); +} +function DecodeFloat16(binary) { + const exponent = (binary & 0x7c00) >> 10; + const fraction = binary & 0x03ff; + return ((binary >> 15 ? -1 : 1) * + (exponent ? (exponent === 0x1f ? (fraction ? NaN : Infinity) : Math.pow(2, exponent - 15) * (1 + fraction / 0x400)) : 6.103515625e-5 * (fraction / 0x400))); +} +function ToHalfFloat(value) { + if (Math.abs(value) > 65504) { + throw new Error("Value out of range.Consider using float instead of half-float."); + } + value = Clamp(value, -65504, 65504); + _tables.floatView[0] = value; + const f = _tables.uint32View[0]; + const e = (f >> 23) & 0x1ff; + return _tables.baseTable[e] + ((f & 0x007fffff) >> _tables.shiftTable[e]); +} +/** + * Decode a float32 from the buffer + * @param dataView dataview on the data + * @param offset current offset in the data view + * @returns a float32 + */ +function DecodeFloat32(dataView, offset) { + return ToHalfFloat(ParseFloat32(dataView, offset)); +} +function ParseFixedLengthString(buffer, offset, size) { + const stringValue = new TextDecoder().decode(new Uint8Array(buffer).slice(offset.value, offset.value + size)); + offset.value = offset.value + size; + return stringValue; +} +function ParseRational(dataView, offset) { + const x = ParseInt32(dataView, offset); + const y = ParseUint32(dataView, offset); + return [x, y]; +} +function ParseTimecode(dataView, offset) { + const x = ParseUint32(dataView, offset); + const y = ParseUint32(dataView, offset); + return [x, y]; +} +function ParseV2f(dataView, offset) { + const x = ParseFloat32(dataView, offset); + const y = ParseFloat32(dataView, offset); + return [x, y]; +} +function ParseV3f(dataView, offset) { + const x = ParseFloat32(dataView, offset); + const y = ParseFloat32(dataView, offset); + const z = ParseFloat32(dataView, offset); + return [x, y, z]; +} +function ParseChlist(dataView, offset, size) { + const startOffset = offset.value; + const channels = []; + while (offset.value < startOffset + size - 1) { + const name = ParseNullTerminatedString(dataView.buffer, offset); + const pixelType = ParseInt32(dataView, offset); + const pLinear = ParseUint8(dataView, offset); + offset.value += 3; // reserved, three chars + const xSampling = ParseInt32(dataView, offset); + const ySampling = ParseInt32(dataView, offset); + channels.push({ + name: name, + pixelType: pixelType, + pLinear: pLinear, + xSampling: xSampling, + ySampling: ySampling, + }); + } + offset.value += 1; + return channels; +} +function ParseChromaticities(dataView, offset) { + const redX = ParseFloat32(dataView, offset); + const redY = ParseFloat32(dataView, offset); + const greenX = ParseFloat32(dataView, offset); + const greenY = ParseFloat32(dataView, offset); + const blueX = ParseFloat32(dataView, offset); + const blueY = ParseFloat32(dataView, offset); + const whiteX = ParseFloat32(dataView, offset); + const whiteY = ParseFloat32(dataView, offset); + return { redX: redX, redY: redY, greenX: greenX, greenY: greenY, blueX: blueX, blueY: blueY, whiteX: whiteX, whiteY: whiteY }; +} +function ParseCompression(dataView, offset) { + return ParseUint8(dataView, offset); +} +function ParseBox2i(dataView, offset) { + const xMin = ParseInt32(dataView, offset); + const yMin = ParseInt32(dataView, offset); + const xMax = ParseInt32(dataView, offset); + const yMax = ParseInt32(dataView, offset); + return { xMin: xMin, yMin: yMin, xMax: xMax, yMax: yMax }; +} +function ParseLineOrder(dataView, offset) { + const lineOrder = ParseUint8(dataView, offset); + return LineOrders[lineOrder]; +} +/** + * Parse a value from the data view + * @param dataView defines the data view to read from + * @param offset defines the current offset in the data view + * @param type defines the type of the value to read + * @param size defines the size of the value to read + * @returns the parsed value + */ +function ParseValue(dataView, offset, type, size) { + switch (type) { + case "string": + case "stringvector": + case "iccProfile": + return ParseFixedLengthString(dataView.buffer, offset, size); + case "chlist": + return ParseChlist(dataView, offset, size); + case "chromaticities": + return ParseChromaticities(dataView, offset); + case "compression": + return ParseCompression(dataView, offset); + case "box2i": + return ParseBox2i(dataView, offset); + case "lineOrder": + return ParseLineOrder(dataView, offset); + case "float": + return ParseFloat32(dataView, offset); + case "v2f": + return ParseV2f(dataView, offset); + case "v3f": + return ParseV3f(dataView, offset); + case "int": + return ParseInt32(dataView, offset); + case "rational": + return ParseRational(dataView, offset); + case "timecode": + return ParseTimecode(dataView, offset); + case "preview": + offset.value += size; + return "skipped"; + default: + offset.value += size; + return undefined; + } +} +/** + * Revert the endianness of the data + * @param source defines the source + */ +function Predictor(source) { + for (let t = 1; t < source.length; t++) { + const d = source[t - 1] + source[t] - 128; + source[t] = d; + } +} +/** + * Interleave pixels + * @param source defines the data source + * @param out defines the output + */ +function InterleaveScalar(source, out) { + let t1 = 0; + let t2 = Math.floor((source.length + 1) / 2); + let s = 0; + const stop = source.length - 1; + // eslint-disable-next-line no-constant-condition + while (true) { + if (s > stop) { + break; + } + out[s++] = source[t1++]; + if (s > stop) { + break; + } + out[s++] = source[t2++]; + } +} + +/* eslint-disable @typescript-eslint/naming-convention */ +/** + * Inspired by https://github.com/sciecode/three.js/blob/dev/examples/jsm/loaders/EXRLoader.js + * Referred to the original Industrial Light & Magic OpenEXR implementation and the TinyEXR / Syoyo Fujita + * implementation. + */ +// /* +// Copyright (c) 2014 - 2017, Syoyo Fujita +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Syoyo Fujita nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// */ +// // TinyEXR contains some OpenEXR code, which is licensed under ------------ +// /////////////////////////////////////////////////////////////////////////// +// // +// // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas +// // Digital Ltd. LLC +// // +// // All rights reserved. +// // +// // Redistribution and use in source and binary forms, with or without +// // modification, are permitted provided that the following conditions are +// // met: +// // * Redistributions of source code must retain the above copyright +// // notice, this list of conditions and the following disclaimer. +// // * Redistributions in binary form must reproduce the above +// // copyright notice, this list of conditions and the following disclaimer +// // in the documentation and/or other materials provided with the +// // distribution. +// // * Neither the name of Industrial Light & Magic nor the names of +// // its contributors may be used to endorse or promote products derived +// // from this software without specific prior written permission. +// // +// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// // +// /////////////////////////////////////////////////////////////////////////// +// // End of OpenEXR license ------------------------------------------------- +const EXR_MAGIC = 20000630; +/** + * Gets the EXR header + * @param dataView defines the data view to read from + * @param offset defines the offset to start reading from + * @returns the header + */ +function GetExrHeader(dataView, offset) { + if (dataView.getUint32(0, true) != EXR_MAGIC) { + throw new Error("Incorrect OpenEXR format"); + } + const version = dataView.getUint8(4); + const specData = dataView.getUint8(5); // fullMask + const spec = { + singleTile: !!(specData & 2), + longName: !!(specData & 4), + deepFormat: !!(specData & 8), + multiPart: !!(specData & 16), + }; + offset.value = 8; + const headerData = {}; + let keepReading = true; + while (keepReading) { + const attributeName = ParseNullTerminatedString(dataView.buffer, offset); + if (!attributeName) { + keepReading = false; + } + else { + const attributeType = ParseNullTerminatedString(dataView.buffer, offset); + const attributeSize = ParseUint32(dataView, offset); + const attributeValue = ParseValue(dataView, offset, attributeType, attributeSize); + if (attributeValue === undefined) { + Logger.Warn(`Unknown header attribute type ${attributeType}'.`); + } + else { + headerData[attributeName] = attributeValue; + } + } + } + if ((specData & -5) != 0) { + throw new Error("Unsupported file format"); + } + return { version: version, spec: spec, ...headerData }; +} + +/** + * Inspired by https://github.com/sciecode/three.js/blob/dev/examples/jsm/loaders/EXRLoader.js + * Referred to the original Industrial Light & Magic OpenEXR implementation and the TinyEXR / Syoyo Fujita + * implementation. + */ +// /* +// Copyright (c) 2014 - 2017, Syoyo Fujita +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Syoyo Fujita nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// */ +// // TinyEXR contains some OpenEXR code, which is licensed under ------------ +// /////////////////////////////////////////////////////////////////////////// +// // +// // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas +// // Digital Ltd. LLC +// // +// // All rights reserved. +// // +// // Redistribution and use in source and binary forms, with or without +// // modification, are permitted provided that the following conditions are +// // met: +// // * Redistributions of source code must retain the above copyright +// // notice, this list of conditions and the following disclaimer. +// // * Redistributions in binary form must reproduce the above +// // copyright notice, this list of conditions and the following disclaimer +// // in the documentation and/or other materials provided with the +// // distribution. +// // * Neither the name of Industrial Light & Magic nor the names of +// // its contributors may be used to endorse or promote products derived +// // from this software without specific prior written permission. +// // +// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// // +// /////////////////////////////////////////////////////////////////////////// +// // End of OpenEXR license ------------------------------------------------- +const NBITS = 16; +const A_OFFSET = 1 << (NBITS - 1); +const MOD_MASK = (1 << NBITS) - 1; +/** @internal */ +function ReverseLutFromBitmap(bitmap, lut) { + let k = 0; + for (let i = 0; i < USHORT_RANGE; ++i) { + if (i == 0 || bitmap[i >> 3] & (1 << (i & 7))) { + lut[k++] = i; + } + } + const n = k - 1; + while (k < USHORT_RANGE) + lut[k++] = 0; + return n; +} +function HufClearDecTable(hdec) { + for (let i = 0; i < HUF_DECSIZE; i++) { + hdec[i] = {}; + hdec[i].len = 0; + hdec[i].lit = 0; + hdec[i].p = null; + } +} +function GetBits(nBits, c, lc, array, offset) { + while (lc < nBits) { + c = (c << 8) | ParseUint8Array(array, offset); + lc += 8; + } + lc -= nBits; + return { + l: (c >> lc) & ((1 << nBits) - 1), + c, + lc, + }; +} +function GetChar(c, lc, array, offset) { + c = (c << 8) | ParseUint8Array(array, offset); + lc += 8; + return { + c, + lc, + }; +} +function GetCode(po, rlc, c, lc, array, offset, outBuffer, outBufferOffset, outBufferEndOffset) { + if (po == rlc) { + if (lc < 8) { + const gc = GetChar(c, lc, array, offset); + c = gc.c; + lc = gc.lc; + } + lc -= 8; + let cs = c >> lc; + cs = new Uint8Array([cs])[0]; + if (outBufferOffset.value + cs > outBufferEndOffset) { + return null; + } + const s = outBuffer[outBufferOffset.value - 1]; + while (cs-- > 0) { + outBuffer[outBufferOffset.value++] = s; + } + } + else if (outBufferOffset.value < outBufferEndOffset) { + outBuffer[outBufferOffset.value++] = po; + } + else { + return null; + } + return { c, lc }; +} +const HufTableBuffer = new Array(59); +function HufCanonicalCodeTable(hcode) { + for (let i = 0; i <= 58; ++i) + HufTableBuffer[i] = 0; + for (let i = 0; i < HUF_ENCSIZE; ++i) + HufTableBuffer[hcode[i]] += 1; + let c = 0; + for (let i = 58; i > 0; --i) { + const nc = (c + HufTableBuffer[i]) >> 1; + HufTableBuffer[i] = c; + c = nc; + } + for (let i = 0; i < HUF_ENCSIZE; ++i) { + const l = hcode[i]; + if (l > 0) + hcode[i] = l | (HufTableBuffer[l]++ << 6); + } +} +function HufUnpackEncTable(array, offset, ni, im, iM, hcode) { + const p = offset; + let c = 0; + let lc = 0; + for (; im <= iM; im++) { + if (p.value - offset.value > ni) { + return; + } + let gb = GetBits(6, c, lc, array, p); + const l = gb.l; + c = gb.c; + lc = gb.lc; + hcode[im] = l; + if (l == LONG_ZEROCODE_RUN) { + if (p.value - offset.value > ni) { + throw new Error("Error in HufUnpackEncTable"); + } + gb = GetBits(8, c, lc, array, p); + let zerun = gb.l + SHORTEST_LONG_RUN; + c = gb.c; + lc = gb.lc; + if (im + zerun > iM + 1) { + throw new Error("Error in HufUnpackEncTable"); + } + while (zerun--) + hcode[im++] = 0; + im--; + } + else if (l >= SHORT_ZEROCODE_RUN) { + let zerun = l - SHORT_ZEROCODE_RUN + 2; + if (im + zerun > iM + 1) { + throw new Error("Error in HufUnpackEncTable"); + } + while (zerun--) + hcode[im++] = 0; + im--; + } + } + HufCanonicalCodeTable(hcode); +} +function HufLength(code) { + return code & 63; +} +function HufCode(code) { + return code >> 6; +} +function HufBuildDecTable(hcode, im, iM, hdecod) { + for (; im <= iM; im++) { + const c = HufCode(hcode[im]); + const l = HufLength(hcode[im]); + if (c >> l) { + throw new Error("Invalid table entry"); + } + if (l > HUF_DECBITS) { + const pl = hdecod[c >> (l - HUF_DECBITS)]; + if (pl.len) { + throw new Error("Invalid table entry"); + } + pl.lit++; + if (pl.p) { + const p = pl.p; + pl.p = new Array(pl.lit); + for (let i = 0; i < pl.lit - 1; ++i) { + pl.p[i] = p[i]; + } + } + else { + pl.p = new Array(1); + } + pl.p[pl.lit - 1] = im; + } + else if (l) { + let plOffset = 0; + for (let i = 1 << (HUF_DECBITS - l); i > 0; i--) { + const pl = hdecod[(c << (HUF_DECBITS - l)) + plOffset]; + if (pl.len || pl.p) { + throw new Error("Invalid table entry"); + } + pl.len = l; + pl.lit = im; + plOffset++; + } + } + } + return true; +} +function HufDecode(encodingTable, decodingTable, array, offset, ni, rlc, no, outBuffer, outOffset) { + let c = 0; + let lc = 0; + const outBufferEndOffset = no; + const inOffsetEnd = Math.trunc(offset.value + (ni + 7) / 8); + while (offset.value < inOffsetEnd) { + let gc = GetChar(c, lc, array, offset); + c = gc.c; + lc = gc.lc; + while (lc >= HUF_DECBITS) { + const index = (c >> (lc - HUF_DECBITS)) & HUF_DECMASK; + const pl = decodingTable[index]; + if (pl.len) { + lc -= pl.len; + const gCode = GetCode(pl.lit, rlc, c, lc, array, offset, outBuffer, outOffset, outBufferEndOffset); + if (gCode) { + c = gCode.c; + lc = gCode.lc; + } + } + else { + if (!pl.p) { + throw new Error("hufDecode issues"); + } + let j; + for (j = 0; j < pl.lit; j++) { + const l = HufLength(encodingTable[pl.p[j]]); + while (lc < l && offset.value < inOffsetEnd) { + gc = GetChar(c, lc, array, offset); + c = gc.c; + lc = gc.lc; + } + if (lc >= l) { + if (HufCode(encodingTable[pl.p[j]]) == ((c >> (lc - l)) & ((1 << l) - 1))) { + lc -= l; + const gCode = GetCode(pl.p[j], rlc, c, lc, array, offset, outBuffer, outOffset, outBufferEndOffset); + if (gCode) { + c = gCode.c; + lc = gCode.lc; + } + break; + } + } + } + if (j == pl.lit) { + throw new Error("HufDecode issues"); + } + } + } + } + const i = (8 - ni) & 7; + c >>= i; + lc -= i; + while (lc > 0) { + const pl = decodingTable[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; + if (pl.len) { + lc -= pl.len; + const gCode = GetCode(pl.lit, rlc, c, lc, array, offset, outBuffer, outOffset, outBufferEndOffset); + if (gCode) { + c = gCode.c; + lc = gCode.lc; + } + } + else { + throw new Error("HufDecode issues"); + } + } + return true; +} +/** @internal */ +function HufUncompress(array, dataView, offset, nCompressed, outBuffer, nRaw) { + const outOffset = { value: 0 }; + const initialInOffset = offset.value; + const im = ParseUint32(dataView, offset); + const iM = ParseUint32(dataView, offset); + offset.value += 4; + const nBits = ParseUint32(dataView, offset); + offset.value += 4; + if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) { + throw new Error("Wrong HUF_ENCSIZE"); + } + const freq = new Array(HUF_ENCSIZE); + const hdec = new Array(HUF_DECSIZE); + HufClearDecTable(hdec); + const ni = nCompressed - (offset.value - initialInOffset); + HufUnpackEncTable(array, offset, ni, im, iM, freq); + if (nBits > 8 * (nCompressed - (offset.value - initialInOffset))) { + throw new Error("Wrong hufUncompress"); + } + HufBuildDecTable(freq, im, iM, hdec); + HufDecode(freq, hdec, array, offset, nBits, iM, nRaw, outBuffer, outOffset); +} +function UInt16(value) { + return value & 0xffff; +} +function Int16(value) { + const ref = UInt16(value); + return ref > 0x7fff ? ref - 0x10000 : ref; +} +function Wdec14(l, h) { + const ls = Int16(l); + const hs = Int16(h); + const hi = hs; + const ai = ls + (hi & 1) + (hi >> 1); + const as = ai; + const bs = ai - hi; + return { a: as, b: bs }; +} +function Wdec16(l, h) { + const m = UInt16(l); + const d = UInt16(h); + const bb = (m - (d >> 1)) & MOD_MASK; + const aa = (d + bb - A_OFFSET) & MOD_MASK; + return { a: aa, b: bb }; +} +/** @internal */ +function Wav2Decode(buffer, j, nx, ox, ny, oy, mx) { + const w14 = mx < 1 << 14; + const n = nx > ny ? ny : nx; + let p = 1; + let p2; + let py; + while (p <= n) + p <<= 1; + p >>= 1; + p2 = p; + p >>= 1; + while (p >= 1) { + py = 0; + const ey = py + oy * (ny - p2); + const oy1 = oy * p; + const oy2 = oy * p2; + const ox1 = ox * p; + const ox2 = ox * p2; + let i00, i01, i10, i11; + for (; py <= ey; py += oy2) { + let px = py; + const ex = py + ox * (nx - p2); + for (; px <= ex; px += ox2) { + const p01 = px + ox1; + const p10 = px + oy1; + const p11 = p10 + ox1; + if (w14) { + let result = Wdec14(buffer[px + j], buffer[p10 + j]); + i00 = result.a; + i10 = result.b; + result = Wdec14(buffer[p01 + j], buffer[p11 + j]); + i01 = result.a; + i11 = result.b; + result = Wdec14(i00, i01); + buffer[px + j] = result.a; + buffer[p01 + j] = result.b; + result = Wdec14(i10, i11); + buffer[p10 + j] = result.a; + buffer[p11 + j] = result.b; + } + else { + let result = Wdec16(buffer[px + j], buffer[p10 + j]); + i00 = result.a; + i10 = result.b; + result = Wdec16(buffer[p01 + j], buffer[p11 + j]); + i01 = result.a; + i11 = result.b; + result = Wdec16(i00, i01); + buffer[px + j] = result.a; + buffer[p01 + j] = result.b; + result = Wdec16(i10, i11); + buffer[p10 + j] = result.a; + buffer[p11 + j] = result.b; + } + } + if (nx & p) { + const p10 = px + oy1; + let result; + if (w14) { + result = Wdec14(buffer[px + j], buffer[p10 + j]); + } + else { + result = Wdec16(buffer[px + j], buffer[p10 + j]); + } + i00 = result.a; + buffer[p10 + j] = result.b; + buffer[px + j] = i00; + } + } + if (ny & p) { + let px = py; + const ex = py + ox * (nx - p2); + for (; px <= ex; px += ox2) { + const p01 = px + ox1; + let result; + if (w14) { + result = Wdec14(buffer[px + j], buffer[p01 + j]); + } + else { + result = Wdec16(buffer[px + j], buffer[p01 + j]); + } + i00 = result.a; + buffer[p01 + j] = result.b; + buffer[px + j] = i00; + } + } + p2 = p; + p >>= 1; + } + return py; +} +/** @internal */ +function ApplyLut(lut, data, nData) { + for (let i = 0; i < nData; ++i) { + data[i] = lut[data[i]]; + } +} + +/** + * Inspired by https://github.com/sciecode/three.js/blob/dev/examples/jsm/loaders/EXRLoader.js + * Referred to the original Industrial Light & Magic OpenEXR implementation and the TinyEXR / Syoyo Fujita + * implementation. + */ +// /* +// Copyright (c) 2014 - 2017, Syoyo Fujita +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Syoyo Fujita nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// */ +// // TinyEXR contains some OpenEXR code, which is licensed under ------------ +// /////////////////////////////////////////////////////////////////////////// +// // +// // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas +// // Digital Ltd. LLC +// // +// // All rights reserved. +// // +// // Redistribution and use in source and binary forms, with or without +// // modification, are permitted provided that the following conditions are +// // met: +// // * Redistributions of source code must retain the above copyright +// // notice, this list of conditions and the following disclaimer. +// // * Redistributions in binary form must reproduce the above +// // copyright notice, this list of conditions and the following disclaimer +// // in the documentation and/or other materials provided with the +// // distribution. +// // * Neither the name of Industrial Light & Magic nor the names of +// // its contributors may be used to endorse or promote products derived +// // from this software without specific prior written permission. +// // +// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// // +// /////////////////////////////////////////////////////////////////////////// +// // End of OpenEXR license ------------------------------------------------- +/** @internal */ +function DecodeRunLength(source) { + let size = source.byteLength; + const out = new Array(); + let p = 0; + const reader = new DataView(source); + while (size > 0) { + const l = reader.getInt8(p++); + if (l < 0) { + const count = -l; + size -= count + 1; + for (let i = 0; i < count; i++) { + out.push(reader.getUint8(p++)); + } + } + else { + const count = l; + size -= 2; + const value = reader.getUint8(p++); + for (let i = 0; i < count + 1; i++) { + out.push(value); + } + } + } + return out; +} + +/** + * No compression + * @param decoder defines the decoder to use + * @returns a decompressed data view + */ +function UncompressRAW(decoder) { + return new DataView(decoder.array.buffer, decoder.offset.value, decoder.size); +} +/** + * RLE compression + * @param decoder defines the decoder to use + * @returns a decompressed data view + */ +function UncompressRLE(decoder) { + const compressed = decoder.viewer.buffer.slice(decoder.offset.value, decoder.offset.value + decoder.size); + const rawBuffer = new Uint8Array(DecodeRunLength(compressed)); + const tmpBuffer = new Uint8Array(rawBuffer.length); + Predictor(rawBuffer); + InterleaveScalar(rawBuffer, tmpBuffer); + return new DataView(tmpBuffer.buffer); +} +/** + * Zip compression + * @param decoder defines the decoder to use + * @returns a decompressed data view + */ +function UncompressZIP(decoder) { + const compressed = decoder.array.slice(decoder.offset.value, decoder.offset.value + decoder.size); + const rawBuffer = fflate.unzlibSync(compressed); + const tmpBuffer = new Uint8Array(rawBuffer.length); + Predictor(rawBuffer); + InterleaveScalar(rawBuffer, tmpBuffer); + return new DataView(tmpBuffer.buffer); +} +/** + * PXR compression + * @param decoder defines the decoder to use + * @returns a decompressed data view + */ +function UncompressPXR(decoder) { + const compressed = decoder.array.slice(decoder.offset.value, decoder.offset.value + decoder.size); + const rawBuffer = fflate.unzlibSync(compressed); + const sz = decoder.lines * decoder.channels * decoder.width; + const tmpBuffer = decoder.type == 1 ? new Uint16Array(sz) : new Uint32Array(sz); + let tmpBufferEnd = 0; + let writePtr = 0; + const ptr = new Array(4); + for (let y = 0; y < decoder.lines; y++) { + for (let c = 0; c < decoder.channels; c++) { + let pixel = 0; + switch (decoder.type) { + case 1: + ptr[0] = tmpBufferEnd; + ptr[1] = ptr[0] + decoder.width; + tmpBufferEnd = ptr[1] + decoder.width; + for (let j = 0; j < decoder.width; ++j) { + const diff = (rawBuffer[ptr[0]++] << 8) | rawBuffer[ptr[1]++]; + pixel += diff; + tmpBuffer[writePtr] = pixel; + writePtr++; + } + break; + case 2: + ptr[0] = tmpBufferEnd; + ptr[1] = ptr[0] + decoder.width; + ptr[2] = ptr[1] + decoder.width; + tmpBufferEnd = ptr[2] + decoder.width; + for (let j = 0; j < decoder.width; ++j) { + const diff = (rawBuffer[ptr[0]++] << 24) | (rawBuffer[ptr[1]++] << 16) | (rawBuffer[ptr[2]++] << 8); + pixel += diff; + tmpBuffer[writePtr] = pixel; + writePtr++; + } + break; + } + } + } + return new DataView(tmpBuffer.buffer); +} +/** + * PIZ compression + * @param decoder defines the decoder to use + * @returns a decompressed data view + */ +function UncompressPIZ(decoder) { + const inDataView = decoder.viewer; + const inOffset = { value: decoder.offset.value }; + const outBuffer = new Uint16Array(decoder.width * decoder.scanlineBlockSize * (decoder.channels * decoder.type)); + const bitmap = new Uint8Array(BITMAP_SIZE); + // Setup channel info + let outBufferEnd = 0; + const pizChannelData = new Array(decoder.channels); + for (let i = 0; i < decoder.channels; i++) { + pizChannelData[i] = {}; + pizChannelData[i]["start"] = outBufferEnd; + pizChannelData[i]["end"] = pizChannelData[i]["start"]; + pizChannelData[i]["nx"] = decoder.width; + pizChannelData[i]["ny"] = decoder.lines; + pizChannelData[i]["size"] = decoder.type; + outBufferEnd += pizChannelData[i].nx * pizChannelData[i].ny * pizChannelData[i].size; + } + // Read range compression data + const minNonZero = ParseUint16(inDataView, inOffset); + const maxNonZero = ParseUint16(inDataView, inOffset); + if (maxNonZero >= BITMAP_SIZE) { + throw new Error("Wrong PIZ_COMPRESSION BITMAP_SIZE"); + } + if (minNonZero <= maxNonZero) { + for (let i = 0; i < maxNonZero - minNonZero + 1; i++) { + bitmap[i + minNonZero] = ParseUint8(inDataView, inOffset); + } + } + // Reverse LUT + const lut = new Uint16Array(USHORT_RANGE); + const maxValue = ReverseLutFromBitmap(bitmap, lut); + const length = ParseUint32(inDataView, inOffset); + // Huffman decoding + HufUncompress(decoder.array, inDataView, inOffset, length, outBuffer, outBufferEnd); + // Wavelet decoding + for (let i = 0; i < decoder.channels; ++i) { + const cd = pizChannelData[i]; + for (let j = 0; j < pizChannelData[i].size; ++j) { + Wav2Decode(outBuffer, cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); + } + } + // Expand the pixel data to their original range + ApplyLut(lut, outBuffer, outBufferEnd); + // Rearrange the pixel data into the format expected by the caller. + let tmpOffset = 0; + const tmpBuffer = new Uint8Array(outBuffer.buffer.byteLength); + for (let y = 0; y < decoder.lines; y++) { + for (let c = 0; c < decoder.channels; c++) { + const cd = pizChannelData[c]; + const n = cd.nx * cd.size; + const cp = new Uint8Array(outBuffer.buffer, cd.end * INT16_SIZE, n * INT16_SIZE); + tmpBuffer.set(cp, tmpOffset); + tmpOffset += n * INT16_SIZE; + cd.end += n; + } + } + return new DataView(tmpBuffer.buffer); +} + +var EXROutputType; +(function (EXROutputType) { + EXROutputType[EXROutputType["Float"] = 0] = "Float"; + EXROutputType[EXROutputType["HalfFloat"] = 1] = "HalfFloat"; +})(EXROutputType || (EXROutputType = {})); +/** + * Class used to store configuration of the exr loader + */ +class ExrLoaderGlobalConfiguration { +} +/** + * Defines the default output type to use (Half float by default) + */ +ExrLoaderGlobalConfiguration.DefaultOutputType = EXROutputType.HalfFloat; +/** + * Url to use to load the fflate library (for zip decompression) + */ +ExrLoaderGlobalConfiguration.FFLATEUrl = "https://unpkg.com/fflate@0.8.2"; + +/** + * Inspired by https://github.com/sciecode/three.js/blob/dev/examples/jsm/loaders/EXRLoader.js + * Referred to the original Industrial Light & Magic OpenEXR implementation and the TinyEXR / Syoyo Fujita + * implementation. + */ +// /* +// Copyright (c) 2014 - 2017, Syoyo Fujita +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Syoyo Fujita nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// */ +// // TinyEXR contains some OpenEXR code, which is licensed under ------------ +// /////////////////////////////////////////////////////////////////////////// +// // +// // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas +// // Digital Ltd. LLC +// // +// // All rights reserved. +// // +// // Redistribution and use in source and binary forms, with or without +// // modification, are permitted provided that the following conditions are +// // met: +// // * Redistributions of source code must retain the above copyright +// // notice, this list of conditions and the following disclaimer. +// // * Redistributions in binary form must reproduce the above +// // copyright notice, this list of conditions and the following disclaimer +// // in the documentation and/or other materials provided with the +// // distribution. +// // * Neither the name of Industrial Light & Magic nor the names of +// // its contributors may be used to endorse or promote products derived +// // from this software without specific prior written permission. +// // +// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// // +// /////////////////////////////////////////////////////////////////////////// +// // End of OpenEXR license ------------------------------------------------- +/** + * Create a decoder for the exr file + * @param header header of the exr file + * @param dataView dataview of the exr file + * @param offset current offset + * @param outputType expected output type (float or half float) + * @returns a promise that resolves with the decoder + */ +async function CreateDecoderAsync(header, dataView, offset, outputType) { + const decoder = { + size: 0, + viewer: dataView, + array: new Uint8Array(dataView.buffer), + offset: offset, + width: header.dataWindow.xMax - header.dataWindow.xMin + 1, + height: header.dataWindow.yMax - header.dataWindow.yMin + 1, + channels: header.channels.length, + channelLineOffsets: {}, + scanOrder: () => 0, + bytesPerLine: 0, + outLineWidth: 0, + lines: 0, + scanlineBlockSize: 0, + inputSize: null, + type: 0, + uncompress: null, + getter: () => 0, + format: 5, + outputChannels: 0, + decodeChannels: {}, + blockCount: null, + byteArray: null, + linearSpace: false, + textureType: 0, + }; + switch (header.compression) { + case CompressionCodes.NO_COMPRESSION: + decoder.lines = 1; + decoder.uncompress = UncompressRAW; + break; + case CompressionCodes.RLE_COMPRESSION: + decoder.lines = 1; + decoder.uncompress = UncompressRLE; + break; + case CompressionCodes.ZIPS_COMPRESSION: + decoder.lines = 1; + decoder.uncompress = UncompressZIP; + await Tools.LoadScriptAsync(ExrLoaderGlobalConfiguration.FFLATEUrl); + break; + case CompressionCodes.ZIP_COMPRESSION: + decoder.lines = 16; + decoder.uncompress = UncompressZIP; + await Tools.LoadScriptAsync(ExrLoaderGlobalConfiguration.FFLATEUrl); + break; + case CompressionCodes.PIZ_COMPRESSION: + decoder.lines = 32; + decoder.uncompress = UncompressPIZ; + break; + case CompressionCodes.PXR24_COMPRESSION: + decoder.lines = 16; + decoder.uncompress = UncompressPXR; + await Tools.LoadScriptAsync(ExrLoaderGlobalConfiguration.FFLATEUrl); + break; + default: + throw new Error(CompressionCodes[header.compression] + " is unsupported"); + } + decoder.scanlineBlockSize = decoder.lines; + const channels = {}; + for (const channel of header.channels) { + switch (channel.name) { + case "Y": + case "R": + case "G": + case "B": + case "A": + channels[channel.name] = true; + decoder.type = channel.pixelType; + } + } + // RGB images will be converted to RGBA format, preventing software emulation in select devices. + let fillAlpha = false; + if (channels.R && channels.G && channels.B) { + fillAlpha = !channels.A; + decoder.outputChannels = 4; + decoder.decodeChannels = { R: 0, G: 1, B: 2, A: 3 }; + } + else if (channels.Y) { + decoder.outputChannels = 1; + decoder.decodeChannels = { Y: 0 }; + } + else { + throw new Error("EXRLoader.parse: file contains unsupported data channels."); + } + if (decoder.type === 1) { + // half + switch (outputType) { + case EXROutputType.Float: + decoder.getter = ParseFloat16; + decoder.inputSize = INT16_SIZE; + break; + case EXROutputType.HalfFloat: + decoder.getter = ParseUint16; + decoder.inputSize = INT16_SIZE; + break; + } + } + else if (decoder.type === 2) { + // float + switch (outputType) { + case EXROutputType.Float: + decoder.getter = ParseFloat32; + decoder.inputSize = FLOAT32_SIZE; + break; + case EXROutputType.HalfFloat: + decoder.getter = DecodeFloat32; + decoder.inputSize = FLOAT32_SIZE; + } + } + else { + throw new Error("Unsupported pixelType " + decoder.type + " for " + header.compression); + } + decoder.blockCount = decoder.height / decoder.scanlineBlockSize; + for (let i = 0; i < decoder.blockCount; i++) { + ParseInt64(dataView, offset); // scanlineOffset + } + // we should be passed the scanline offset table, ready to start reading pixel data. + const size = decoder.width * decoder.height * decoder.outputChannels; + switch (outputType) { + case EXROutputType.Float: + decoder.byteArray = new Float32Array(size); + decoder.textureType = 1; + // Fill initially with 1s for the alpha value if the texture is not RGBA, RGB values will be overwritten + if (fillAlpha) { + decoder.byteArray.fill(1, 0, size); + } + break; + case EXROutputType.HalfFloat: + decoder.byteArray = new Uint16Array(size); + decoder.textureType = 2; + if (fillAlpha) { + decoder.byteArray.fill(0x3c00, 0, size); // Uint16Array holds half float data, 0x3C00 is 1 + } + break; + default: + throw new Error("Unsupported type: " + outputType); + } + let byteOffset = 0; + for (const channel of header.channels) { + if (decoder.decodeChannels[channel.name] !== undefined) { + decoder.channelLineOffsets[channel.name] = byteOffset * decoder.width; + } + byteOffset += channel.pixelType * 2; + } + decoder.bytesPerLine = decoder.width * byteOffset; + decoder.outLineWidth = decoder.width * decoder.outputChannels; + if (header.lineOrder === "INCREASING_Y") { + decoder.scanOrder = (y) => y; + } + else { + decoder.scanOrder = (y) => decoder.height - 1 - y; + } + if (decoder.outputChannels == 4) { + decoder.format = 5; + decoder.linearSpace = true; + } + else { + decoder.format = 6; + decoder.linearSpace = false; + } + return decoder; +} +/** + * Scan the data of the exr file + * @param decoder decoder to use + * @param header header of the exr file + * @param dataView dataview of the exr file + * @param offset current offset + */ +function ScanData(decoder, header, dataView, offset) { + const tmpOffset = { value: 0 }; + for (let scanlineBlockIdx = 0; scanlineBlockIdx < decoder.height / decoder.scanlineBlockSize; scanlineBlockIdx++) { + const line = ParseInt32(dataView, offset) - header.dataWindow.yMin; // line_no + decoder.size = ParseUint32(dataView, offset); // data_len + decoder.lines = line + decoder.scanlineBlockSize > decoder.height ? decoder.height - line : decoder.scanlineBlockSize; + const isCompressed = decoder.size < decoder.lines * decoder.bytesPerLine; + const viewer = isCompressed && decoder.uncompress ? decoder.uncompress(decoder) : UncompressRAW(decoder); + offset.value += decoder.size; + for (let line_y = 0; line_y < decoder.scanlineBlockSize; line_y++) { + const scan_y = scanlineBlockIdx * decoder.scanlineBlockSize; + const true_y = line_y + decoder.scanOrder(scan_y); + if (true_y >= decoder.height) { + continue; + } + const lineOffset = line_y * decoder.bytesPerLine; + const outLineOffset = (decoder.height - 1 - true_y) * decoder.outLineWidth; + for (let channelID = 0; channelID < decoder.channels; channelID++) { + const name = header.channels[channelID].name; + const lOff = decoder.channelLineOffsets[name]; + const cOff = decoder.decodeChannels[name]; + if (cOff === undefined) { + continue; + } + tmpOffset.value = lineOffset + lOff; + for (let x = 0; x < decoder.width; x++) { + const outIndex = outLineOffset + x * decoder.outputChannels + cOff; + if (decoder.byteArray) { + decoder.byteArray[outIndex] = decoder.getter(viewer, tmpOffset); + } + } + } + } + } +} + +/** + * Inspired by https://github.com/sciecode/three.js/blob/dev/examples/jsm/loaders/EXRLoader.js + * Referred to the original Industrial Light & Magic OpenEXR implementation and the TinyEXR / Syoyo Fujita + * implementation. + */ +// /* +// Copyright (c) 2014 - 2017, Syoyo Fujita +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Syoyo Fujita nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// */ +// // TinyEXR contains some OpenEXR code, which is licensed under ------------ +// /////////////////////////////////////////////////////////////////////////// +// // +// // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas +// // Digital Ltd. LLC +// // +// // All rights reserved. +// // +// // Redistribution and use in source and binary forms, with or without +// // modification, are permitted provided that the following conditions are +// // met: +// // * Redistributions of source code must retain the above copyright +// // notice, this list of conditions and the following disclaimer. +// // * Redistributions in binary form must reproduce the above +// // copyright notice, this list of conditions and the following disclaimer +// // in the documentation and/or other materials provided with the +// // distribution. +// // * Neither the name of Industrial Light & Magic nor the names of +// // its contributors may be used to endorse or promote products derived +// // from this software without specific prior written permission. +// // +// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// // +// /////////////////////////////////////////////////////////////////////////// +// // End of OpenEXR license ------------------------------------------------- +/** + * Loader for .exr file format + * @see [PIZ compression](https://playground.babylonjs.com/#4RN0VF#151) + * @see [ZIP compression](https://playground.babylonjs.com/#4RN0VF#146) + * @see [RLE compression](https://playground.babylonjs.com/#4RN0VF#149) + * @see [PXR24 compression](https://playground.babylonjs.com/#4RN0VF#150) + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _ExrTextureLoader { + constructor() { + /** + * Defines whether the loader supports cascade loading the different faces. + */ + this.supportCascades = false; + } + /** + * Uploads the cube texture data to the WebGL texture. It has already been bound. + * @param _data contains the texture data + * @param _texture defines the BabylonJS internal texture + * @param _createPolynomials will be true if polynomials have been requested + * @param _onLoad defines the callback to trigger once the texture is ready + * @param _onError defines the callback to trigger in case of error + * Cube texture are not supported by .exr files + */ + loadCubeData(_data, _texture, _createPolynomials, _onLoad, _onError) { + // eslint-disable-next-line no-throw-literal + throw ".exr not supported in Cube."; + } + /** + * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + */ + async loadData(data, texture, callback) { + const dataView = new DataView(data.buffer); + const offset = { value: 0 }; + const header = GetExrHeader(dataView, offset); + const decoder = await CreateDecoderAsync(header, dataView, offset, ExrLoaderGlobalConfiguration.DefaultOutputType); + ScanData(decoder, header, dataView, offset); + // Updating texture + const width = header.dataWindow.xMax - header.dataWindow.xMin + 1; + const height = header.dataWindow.yMax - header.dataWindow.yMin + 1; + callback(width, height, texture.generateMipMaps, false, () => { + const engine = texture.getEngine(); + texture.format = header.format; + texture.type = decoder.textureType; + texture.invertY = false; + texture._gammaSpace = !header.linearSpace; + if (decoder.byteArray) { + engine._uploadDataToTextureDirectly(texture, decoder.byteArray, 0, 0, undefined, true); + } + }); + } +} + +const exrTextureLoader = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + _ExrTextureLoader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Implementation of the IES Texture Loader. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class _IESTextureLoader { + constructor() { + /** + * Defines whether the loader supports cascade loading the different faces. + */ + this.supportCascades = false; + } + /** + * Uploads the cube texture data to the WebGL texture. It has already been bound. + */ + loadCubeData() { + // eslint-disable-next-line no-throw-literal + throw ".ies not supported in Cube."; + } + /** + * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + */ + loadData(data, texture, callback) { + const uint8array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + const textureData = LoadIESData(uint8array); + callback(textureData.width, textureData.height, false, false, () => { + const engine = texture.getEngine(); + texture.type = 1; + texture.format = 6; + texture._gammaSpace = false; + engine._uploadDataToTextureDirectly(texture, textureData.data); + }); + } +} + +const iesTextureLoader = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + _IESTextureLoader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * A multi render target, like a render target provides the ability to render to a texture. + * Unlike the render target, it can render to several draw buffers (render textures) in one draw. + * This is specially interesting in deferred rendering or for any effects requiring more than + * just one color from a single pass. + */ +class MultiRenderTarget extends RenderTargetTexture { + /** + * Get if draw buffers (render textures) are currently supported by the used hardware and browser. + */ + get isSupported() { + return this._engine?.getCaps().drawBuffersExtension ?? false; + } + /** + * Get the list of textures generated by the multi render target. + */ + get textures() { + return this._textures; + } + /** + * Gets the number of textures in this MRT. This number can be different from `_textures.length` in case a depth texture is generated. + */ + get count() { + return this._count; + } + /** + * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set + */ + get depthTexture() { + return this._textures[this._textures.length - 1]; + } + /** + * Set the wrapping mode on U of all the textures we are rendering to. + * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE) + */ + set wrapU(wrap) { + if (this._textures) { + for (let i = 0; i < this._textures.length; i++) { + this._textures[i].wrapU = wrap; + } + } + } + /** + * Set the wrapping mode on V of all the textures we are rendering to. + * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE) + */ + set wrapV(wrap) { + if (this._textures) { + for (let i = 0; i < this._textures.length; i++) { + this._textures[i].wrapV = wrap; + } + } + } + /** + * Instantiate a new multi render target texture. + * A multi render target, like a render target provides the ability to render to a texture. + * Unlike the render target, it can render to several draw buffers (render textures) in one draw. + * This is specially interesting in deferred rendering or for any effects requiring more than + * just one color from a single pass. + * @param name Define the name of the texture + * @param size Define the size of the buffers to render to + * @param count Define the number of target we are rendering into + * @param scene Define the scene the texture belongs to + * @param options Define the options used to create the multi render target + * @param textureNames Define the names to set to the textures (if count \> 0 - optional) + */ + constructor(name, size, count, scene, options, textureNames) { + const generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false; + const generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false; + const depthTextureFormat = options && options.depthTextureFormat ? options.depthTextureFormat : 15; + const doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio; + const drawOnlyOnFirstAttachmentByDefault = options && options.drawOnlyOnFirstAttachmentByDefault ? options.drawOnlyOnFirstAttachmentByDefault : false; + super(name, size, scene, generateMipMaps, doNotChangeAspectRatio, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true); + if (!this.isSupported) { + this.dispose(); + return; + } + this._textureNames = textureNames; + const types = []; + const samplingModes = []; + const useSRGBBuffers = []; + const formats = []; + const targetTypes = []; + const faceIndex = []; + const layerIndex = []; + const layerCounts = []; + this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options); + const generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; + const generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer; + const samples = options && options.samples ? options.samples : 1; + this._multiRenderTargetOptions = { + samplingModes: samplingModes, + generateMipMaps: generateMipMaps, + generateDepthBuffer: generateDepthBuffer, + generateStencilBuffer: generateStencilBuffer, + generateDepthTexture: generateDepthTexture, + depthTextureFormat: depthTextureFormat, + types: types, + textureCount: count, + useSRGBBuffers: useSRGBBuffers, + samples, + formats: formats, + targetTypes: targetTypes, + faceIndex: faceIndex, + layerIndex: layerIndex, + layerCounts: layerCounts, + labels: textureNames, + label: name, + }; + this._count = count; + this._drawOnlyOnFirstAttachmentByDefault = drawOnlyOnFirstAttachmentByDefault; + if (count > 0) { + this._createInternalTextures(); + this._createTextures(textureNames); + } + } + _initTypes(count, types, samplingModes, useSRGBBuffers, formats, targets, faceIndex, layerIndex, layerCounts, options) { + for (let i = 0; i < count; i++) { + if (options && options.types && options.types[i] !== undefined) { + types.push(options.types[i]); + } + else { + types.push(options && options.defaultType ? options.defaultType : 0); + } + if (options && options.samplingModes && options.samplingModes[i] !== undefined) { + samplingModes.push(options.samplingModes[i]); + } + else { + samplingModes.push(Texture.BILINEAR_SAMPLINGMODE); + } + if (options && options.useSRGBBuffers && options.useSRGBBuffers[i] !== undefined) { + useSRGBBuffers.push(options.useSRGBBuffers[i]); + } + else { + useSRGBBuffers.push(false); + } + if (options && options.formats && options.formats[i] !== undefined) { + formats.push(options.formats[i]); + } + else { + formats.push(5); + } + if (options && options.targetTypes && options.targetTypes[i] !== undefined) { + targets.push(options.targetTypes[i]); + } + else { + targets.push(3553); + } + if (options && options.faceIndex && options.faceIndex[i] !== undefined) { + faceIndex.push(options.faceIndex[i]); + } + else { + faceIndex.push(0); + } + if (options && options.layerIndex && options.layerIndex[i] !== undefined) { + layerIndex.push(options.layerIndex[i]); + } + else { + layerIndex.push(0); + } + if (options && options.layerCounts && options.layerCounts[i] !== undefined) { + layerCounts.push(options.layerCounts[i]); + } + else { + layerCounts.push(1); + } + } + } + _createInternaTextureIndexMapping() { + const mapMainInternalTexture2Index = {}; + const mapInternalTexture2MainIndex = []; + if (!this._renderTarget) { + return mapInternalTexture2MainIndex; + } + const internalTextures = this._renderTarget.textures; + for (let i = 0; i < internalTextures.length; i++) { + const texture = internalTextures[i]; + if (!texture) { + continue; + } + const mainIndex = mapMainInternalTexture2Index[texture.uniqueId]; + if (mainIndex !== undefined) { + mapInternalTexture2MainIndex[i] = mainIndex; + } + else { + mapMainInternalTexture2Index[texture.uniqueId] = i; + } + } + return mapInternalTexture2MainIndex; + } + /** + * @internal + */ + _rebuild(fromContextLost = false, forceFullRebuild = false, textureNames) { + if (this._count < 1 || fromContextLost) { + return; + } + const mapInternalTexture2MainIndex = this._createInternaTextureIndexMapping(); + this.releaseInternalTextures(); + this._createInternalTextures(); + if (forceFullRebuild) { + this._releaseTextures(); + this._createTextures(textureNames); + } + const internalTextures = this._renderTarget.textures; + for (let i = 0; i < internalTextures.length; i++) { + const texture = this._textures[i]; + if (mapInternalTexture2MainIndex[i] !== undefined) { + this._renderTarget.setTexture(internalTextures[mapInternalTexture2MainIndex[i]], i); + } + texture._texture = internalTextures[i]; + if (texture._texture) { + texture._noMipmap = !texture._texture.useMipMaps; + texture._useSRGBBuffer = texture._texture._useSRGBBuffer; + } + } + if (this.samples !== 1) { + this._renderTarget.setSamples(this.samples, !this._drawOnlyOnFirstAttachmentByDefault, true); + } + } + _createInternalTextures() { + this._renderTarget = this._getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions, !this._drawOnlyOnFirstAttachmentByDefault); + this._texture = this._renderTarget.texture; + } + _releaseTextures() { + if (this._textures) { + for (let i = 0; i < this._textures.length; i++) { + this._textures[i]._texture = null; // internal textures are released by a call to releaseInternalTextures() + this._textures[i].dispose(); + } + } + } + _createTextures(textureNames) { + const internalTextures = this._renderTarget.textures; + this._textures = []; + for (let i = 0; i < internalTextures.length; i++) { + const texture = new Texture(null, this.getScene()); + if (textureNames?.[i]) { + texture.name = textureNames[i]; + } + texture._texture = internalTextures[i]; + if (texture._texture) { + texture._noMipmap = !texture._texture.useMipMaps; + texture._useSRGBBuffer = texture._texture._useSRGBBuffer; + } + this._textures.push(texture); + } + } + /** + * Replaces an internal texture within the MRT. Useful to share textures between MultiRenderTarget. + * @param texture The new texture to set in the MRT + * @param index The index of the texture to replace + * @param disposePrevious Set to true if the previous internal texture should be disposed + */ + setInternalTexture(texture, index, disposePrevious = true) { + if (!this.renderTarget) { + return; + } + if (index === 0) { + this._texture = texture; + } + this.renderTarget.setTexture(texture, index, disposePrevious); + if (!this.textures[index]) { + this.textures[index] = new Texture(null, this.getScene()); + this.textures[index].name = this._textureNames?.[index] ?? this.textures[index].name; + } + this.textures[index]._texture = texture; + this.textures[index]._noMipmap = !texture.useMipMaps; + this.textures[index]._useSRGBBuffer = texture._useSRGBBuffer; + this._count = this.renderTarget.textures ? this.renderTarget.textures.length : 0; + if (this._multiRenderTargetOptions.types) { + this._multiRenderTargetOptions.types[index] = texture.type; + } + if (this._multiRenderTargetOptions.samplingModes) { + this._multiRenderTargetOptions.samplingModes[index] = texture.samplingMode; + } + if (this._multiRenderTargetOptions.useSRGBBuffers) { + this._multiRenderTargetOptions.useSRGBBuffers[index] = texture._useSRGBBuffer; + } + if (this._multiRenderTargetOptions.targetTypes && this._multiRenderTargetOptions.targetTypes[index] !== -1) { + let target = 0; + if (texture.is2DArray) { + target = 35866; + } + else if (texture.isCube) { + target = 34067; + } /*else if (texture.isCubeArray) { + target = 3735928559; + }*/ + else if (texture.is3D) { + target = 32879; + } + else { + target = 3553; + } + this._multiRenderTargetOptions.targetTypes[index] = target; + } + } + /** + * Changes an attached texture's face index or layer. + * @param index The index of the texture to modify the attachment of + * @param layerIndex The layer index of the texture to be attached to the framebuffer + * @param faceIndex The face index of the texture to be attached to the framebuffer + */ + setLayerAndFaceIndex(index, layerIndex = -1, faceIndex = -1) { + if (!this.textures[index] || !this.renderTarget) { + return; + } + if (this._multiRenderTargetOptions.layerIndex) { + this._multiRenderTargetOptions.layerIndex[index] = layerIndex; + } + if (this._multiRenderTargetOptions.faceIndex) { + this._multiRenderTargetOptions.faceIndex[index] = faceIndex; + } + this.renderTarget.setLayerAndFaceIndex(index, layerIndex, faceIndex); + } + /** + * Changes every attached texture's face index or layer. + * @param layerIndices The layer indices of the texture to be attached to the framebuffer + * @param faceIndices The face indices of the texture to be attached to the framebuffer + */ + setLayerAndFaceIndices(layerIndices, faceIndices) { + if (!this.renderTarget) { + return; + } + this._multiRenderTargetOptions.layerIndex = layerIndices; + this._multiRenderTargetOptions.faceIndex = faceIndices; + this.renderTarget.setLayerAndFaceIndices(layerIndices, faceIndices); + } + /** + * Define the number of samples used if MSAA is enabled. + */ + get samples() { + return this._samples; + } + set samples(value) { + if (this._renderTarget) { + this._samples = this._renderTarget.setSamples(value); + } + else { + // In case samples are set with 0 textures created, we must save the desired samples value + this._samples = value; + } + } + /** + * Resize all the textures in the multi render target. + * Be careful as it will recreate all the data in the new texture. + * @param size Define the new size + */ + resize(size) { + this._processSizeParameter(size); + this._rebuild(false, undefined, this._textureNames); + } + /** + * Changes the number of render targets in this MRT + * Be careful as it will recreate all the data in the new texture. + * @param count new texture count + * @param options Specifies texture types and sampling modes for new textures + * @param textureNames Specifies the names of the textures (optional) + */ + updateCount(count, options, textureNames) { + this._multiRenderTargetOptions.textureCount = count; + this._count = count; + const types = []; + const samplingModes = []; + const useSRGBBuffers = []; + const formats = []; + const targetTypes = []; + const faceIndex = []; + const layerIndex = []; + const layerCounts = []; + this._textureNames = textureNames; + this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options); + this._multiRenderTargetOptions.types = types; + this._multiRenderTargetOptions.samplingModes = samplingModes; + this._multiRenderTargetOptions.useSRGBBuffers = useSRGBBuffers; + this._multiRenderTargetOptions.formats = formats; + this._multiRenderTargetOptions.targetTypes = targetTypes; + this._multiRenderTargetOptions.faceIndex = faceIndex; + this._multiRenderTargetOptions.layerIndex = layerIndex; + this._multiRenderTargetOptions.layerCounts = layerCounts; + this._multiRenderTargetOptions.labels = textureNames; + this._rebuild(false, true, textureNames); + } + _unbindFrameBuffer(engine, faceIndex) { + if (this._renderTarget) { + engine.unBindMultiColorAttachmentFramebuffer(this._renderTarget, this.isCube, () => { + this.onAfterRenderObservable.notifyObservers(faceIndex); + }); + } + } + /** + * Dispose the render targets and their associated resources + * @param doNotDisposeInternalTextures if set to true, internal textures won't be disposed (default: false). + */ + dispose(doNotDisposeInternalTextures = false) { + this._releaseTextures(); + if (!doNotDisposeInternalTextures) { + this.releaseInternalTextures(); + } + else { + // Prevent internal texture dispose in super.dispose + this._texture = null; + } + super.dispose(); + } + /** + * Release all the underlying texture used as draw buffers (render textures). + */ + releaseInternalTextures() { + const internalTextures = this._renderTarget?.textures; + if (!internalTextures) { + return; + } + for (let i = internalTextures.length - 1; i >= 0; i--) { + this._textures[i]._texture = null; + } + this._renderTarget?.dispose(); + this._renderTarget = null; + } +} + +// Do not edit. +const name$49 = "noisePixelShader"; +const shader$48 = `uniform float brightness;uniform float persistence;uniform float timeScale;varying vec2 vUV;vec2 hash22(vec2 p) +{p=p*mat2(127.1,311.7,269.5,183.3);p=-1.0+2.0*fract(sin(p)*43758.5453123);return sin(p*6.283+timeScale);} +float interpolationNoise(vec2 p) +{vec2 pi=floor(p);vec2 pf=p-pi;vec2 w=pf*pf*(3.-2.*pf);float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));float xm1=mix(f00,f10,w.x);float xm2=mix(f01,f11,w.x);float ym=mix(xm1,xm2,w.y); +return ym;} +float perlinNoise2D(float x,float y) +{float sum=0.0;float frequency=0.0;float amplitude=0.0;for(int i=0; iFragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.vPosition=input.position;vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position= vec4f(input.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$48]) { + ShaderStore.ShadersStoreWGSL[name$48] = shader$47; +} +/** @internal */ +const proceduralVertexShaderWGSL = { name: name$48, shader: shader$47 }; + +const procedural_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + proceduralVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$47 = "proceduralVertexShader"; +const shader$46 = `attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$47]) { + ShaderStore.ShadersStore[name$47] = shader$46; +} +/** @internal */ +const proceduralVertexShader = { name: name$47, shader: shader$46 }; + +const procedural_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + proceduralVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$46 = "hdrFilteringVertexShader"; +const shader$45 = `attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +mat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$46]) { + ShaderStore.ShadersStore[name$46] = shader$45; +} +/** @internal */ +const hdrFilteringVertexShader = { name: name$46, shader: shader$45 }; + +const hdrFiltering_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + hdrFilteringVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$45 = "hdrFilteringPixelShader"; +const shader$44 = `#include +#include +#include +#include +uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$45]) { + ShaderStore.ShadersStore[name$45] = shader$44; +} +/** @internal */ +const hdrFilteringPixelShader = { name: name$45, shader: shader$44 }; + +const hdrFiltering_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + hdrFilteringPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$44 = "hdrFilteringVertexShader"; +const shader$43 = `attribute position: vec2f;varying direction: vec3f;uniform up: vec3f;uniform right: vec3f;uniform front: vec3f; +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +var view: mat3x3f= mat3x3f(uniforms.up,uniforms.right,uniforms.front);vertexOutputs.direction=view*vec3f(input.position,1.0);vertexOutputs.position= vec4f(input.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$44]) { + ShaderStore.ShadersStoreWGSL[name$44] = shader$43; +} +/** @internal */ +const hdrFilteringVertexShaderWGSL = { name: name$44, shader: shader$43 }; + +const hdrFiltering_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + hdrFilteringVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$43 = "hdrFilteringPixelShader"; +const shader$42 = `#include +#include +#include +#include +uniform alphaG: f32;var inputTextureSampler: sampler;var inputTexture: texture_cube;uniform vFilteringInfo: vec2f;uniform hdrScale: f32;varying direction: vec3f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=radiance(uniforms.alphaG,inputTexture,inputTextureSampler,input.direction,uniforms.vFilteringInfo);fragmentOutputs.color= vec4f(color*uniforms.hdrScale,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$43]) { + ShaderStore.ShadersStoreWGSL[name$43] = shader$42; +} +/** @internal */ +const hdrFilteringPixelShaderWGSL = { name: name$43, shader: shader$42 }; + +const hdrFiltering_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + hdrFilteringPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$42 = "hdrIrradianceFilteringVertexShader"; +const shader$41 = `attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +mat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$42]) { + ShaderStore.ShadersStore[name$42] = shader$41; +} +/** @internal */ +const hdrIrradianceFilteringVertexShader = { name: name$42, shader: shader$41 }; + +const hdrIrradianceFiltering_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + hdrIrradianceFilteringVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$41 = "hdrIrradianceFilteringPixelShader"; +const shader$40 = `#include +#include +#include +#include +uniform samplerCube inputTexture; +#ifdef IBL_CDF_FILTERING +uniform sampler2D icdfTexture; +#endif +uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=irradiance(inputTexture,direction,vFilteringInfo +#ifdef IBL_CDF_FILTERING +,icdfTexture +#endif +);gl_FragColor=vec4(color*hdrScale,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$41]) { + ShaderStore.ShadersStore[name$41] = shader$40; +} +/** @internal */ +const hdrIrradianceFilteringPixelShader = { name: name$41, shader: shader$40 }; + +const hdrIrradianceFiltering_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + hdrIrradianceFilteringPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$40 = "hdrIrradianceFilteringVertexShader"; +const shader$3$ = `attribute position: vec2f;varying direction: vec3f;uniform up: vec3f;uniform right: vec3f;uniform front: vec3f; +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +var view: mat3x3f= mat3x3f(uniforms.up,uniforms.right,uniforms.front);vertexOutputs.direction=view*vec3f(input.position,1.0);vertexOutputs.position= vec4f(input.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$40]) { + ShaderStore.ShadersStoreWGSL[name$40] = shader$3$; +} +/** @internal */ +const hdrIrradianceFilteringVertexShaderWGSL = { name: name$40, shader: shader$3$ }; + +const hdrIrradianceFiltering_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + hdrIrradianceFilteringVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3$ = "hdrIrradianceFilteringPixelShader"; +const shader$3_ = `#include +#include +#include +#include +var inputTextureSampler: sampler;var inputTexture: texture_cube; +#ifdef IBL_CDF_FILTERING +var icdfTextureSampler: sampler;var icdfTexture: texture_2d; +#endif +uniform vFilteringInfo: vec2f;uniform hdrScale: f32;varying direction: vec3f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=irradiance(inputTexture,inputTextureSampler,input.direction,uniforms.vFilteringInfo +#ifdef IBL_CDF_FILTERING +,icdfTexture,icdfTextureSampler +#endif +);fragmentOutputs.color= vec4f(color*uniforms.hdrScale,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3$]) { + ShaderStore.ShadersStoreWGSL[name$3$] = shader$3_; +} +/** @internal */ +const hdrIrradianceFilteringPixelShaderWGSL = { name: name$3$, shader: shader$3_ }; + +const hdrIrradianceFiltering_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + hdrIrradianceFilteringPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Enum defining the mode of a NodeMaterialBlockConnectionPoint + */ +var NodeMaterialBlockConnectionPointMode; +(function (NodeMaterialBlockConnectionPointMode) { + /** Value is an uniform */ + NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Uniform"] = 0] = "Uniform"; + /** Value is a mesh attribute */ + NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Attribute"] = 1] = "Attribute"; + /** Value is a varying between vertex and fragment shaders */ + NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Varying"] = 2] = "Varying"; + /** Mode is undefined */ + NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Undefined"] = 3] = "Undefined"; +})(NodeMaterialBlockConnectionPointMode || (NodeMaterialBlockConnectionPointMode = {})); + +/** + * Defines a connection point to be used for points with a custom object type + */ +class NodeMaterialConnectionPointCustomObject extends NodeMaterialConnectionPoint { + /** + * Creates a new connection point + * @param name defines the connection point name + * @param ownerBlock defines the block hosting this connection point + * @param direction defines the direction of the connection point + * @param _blockType + * @param _blockName + */ + constructor(name, ownerBlock, direction, + // @internal + _blockType, _blockName) { + super(name, ownerBlock, direction); + this._blockType = _blockType; + this._blockName = _blockName; + this.needDualDirectionValidation = true; + } + /** + * Gets a number indicating if the current point can be connected to another point + * @param connectionPoint defines the other connection point + * @returns a number defining the compatibility state + */ + checkCompatibilityState(connectionPoint) { + return connectionPoint instanceof NodeMaterialConnectionPointCustomObject && connectionPoint._blockName === this._blockName + ? 0 /* NodeMaterialConnectionPointCompatibilityStates.Compatible */ + : 1 /* NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible */; + } + /** + * Creates a block suitable to be used as an input for this input point. + * If null is returned, a block based on the point type will be created. + * @returns The returned string parameter is the name of the output point of NodeMaterialBlock (first parameter of the returned array) that can be connected to the input + */ + createCustomInputBlock() { + return [new this._blockType(this._blockName), this.name]; + } +} + +/** + * Block used for the Gaussian Splatting + */ +class GaussianSplattingBlock extends NodeMaterialBlock { + /** + * Create a new GaussianSplattingBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Vertex); + this._isUnique = true; + this.registerInput("splatPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("splatScale", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Vertex); + this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("projection", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex); + this.registerOutput("splatVertex", NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockTargets.Vertex); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GaussianSplattingBlock"; + } + /** + * Gets the position input component + */ + get splatPosition() { + return this._inputs[0]; + } + /** + * Gets the scale input component + */ + get splatScale() { + return this._inputs[1]; + } + /** + * Gets the View matrix input component + */ + get world() { + return this._inputs[2]; + } + /** + * Gets the View matrix input component + */ + get view() { + return this._inputs[3]; + } + /** + * Gets the projection matrix input component + */ + get projection() { + return this._inputs[4]; + } + /** + * Gets the splatVertex output component + */ + get splatVertex() { + return this._outputs[0]; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("focal"); + state._excludeVariableName("invViewport"); + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Fragment) { + return; + } + const comments = `//${this.name}`; + state._emitFunctionFromInclude("gaussianSplattingVertexDeclaration", comments); + state._emitFunctionFromInclude("gaussianSplatting", comments); + state._emitUniformFromString("focal", NodeMaterialBlockConnectionPointTypes.Vector2); + state._emitUniformFromString("invViewport", NodeMaterialBlockConnectionPointTypes.Vector2); + state.attributes.push(VertexBuffer.PositionKind); + state.sharedData.nodeMaterial.backFaceCulling = false; + const splatPosition = this.splatPosition; + const splatScale = this.splatScale; + const world = this.world; + const view = this.view; + const projection = this.projection; + const output = this.splatVertex; + const addF = state.fSuffix; + let splatScaleParameter = `vec2${addF}(1.,1.)`; + if (splatScale.isConnected) { + splatScaleParameter = splatScale.associatedVariableName; + } + let input = "position"; + let uniforms = ""; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + input = "input.position"; + uniforms = ", uniforms.focal, uniforms.invViewport"; + } + state.compilationString += `${state._declareOutput(output)} = gaussianSplatting(${input}, ${splatPosition.associatedVariableName}, ${splatScaleParameter}, covA, covB, ${world.associatedVariableName}, ${view.associatedVariableName}, ${projection.associatedVariableName}${uniforms});\n`; + return this; + } +} +RegisterClass("BABYLON.GaussianSplattingBlock", GaussianSplattingBlock); + +/** + * Block used for the Gaussian Splatting Fragment part + */ +class GaussianBlock extends NodeMaterialBlock { + /** + * Create a new GaussianBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this._isUnique = false; + this.registerInput("splatColor", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment); + this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GaussianBlock"; + } + /** + * Gets the color input component + */ + get splatColor() { + return this._inputs[0]; + } + /** + * Gets the rgba output component + */ + get rgba() { + return this._outputs[0]; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("vPosition"); + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Vertex) { + return; + } + // Emit code + const comments = `//${this.name}`; + state._emitFunctionFromInclude("clipPlaneFragmentDeclaration", comments); + state._emitFunctionFromInclude("logDepthDeclaration", comments); + state._emitFunctionFromInclude("fogFragmentDeclaration", comments); + state._emitFunctionFromInclude("gaussianSplattingFragmentDeclaration", comments); + state._emitVaryingFromString("vPosition", NodeMaterialBlockConnectionPointTypes.Vector2); + const color = this.splatColor; + const output = this._outputs[0]; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + state.compilationString += `${state._declareOutput(output)} = gaussianColor(${color.associatedVariableName}, input.vPosition);\n`; + } + else { + state.compilationString += `${state._declareOutput(output)} = gaussianColor(${color.associatedVariableName});\n`; + } + return this; + } +} +RegisterClass("BABYLON.GaussianBlock", GaussianBlock); + +// Do not edit. +const name$3_ = "gaussianSplattingFragmentDeclaration"; +const shader$3Z = `vec4 gaussianColor(vec4 inColor) +{float A=-dot(vPosition,vPosition);if (A<-4.0) discard;float B=exp(A)*inColor.a; +#include +vec3 color=inColor.rgb; +#ifdef FOG +#include +#endif +return vec4(color,B);} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$3_]) { + ShaderStore.IncludesShadersStore[name$3_] = shader$3Z; +} + +// Do not edit. +const name$3Z = "gaussianSplattingPixelShader"; +const shader$3Y = `#include +#include +#include +varying vec4 vColor;varying vec2 vPosition; +#include +void main () { +#include +gl_FragColor=gaussianColor(vColor);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3Z]) { + ShaderStore.ShadersStore[name$3Z] = shader$3Y; +} +/** @internal */ +const gaussianSplattingPixelShader = { name: name$3Z, shader: shader$3Y }; + +const gaussianSplatting_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + gaussianSplattingPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3Y = "gaussianSplattingVertexDeclaration"; +const shader$3X = `attribute vec2 position;uniform mat4 view;uniform mat4 projection;uniform mat4 world;uniform vec4 vEyePosition;`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$3Y]) { + ShaderStore.IncludesShadersStore[name$3Y] = shader$3X; +} + +// Do not edit. +const name$3X = "gaussianSplattingUboDeclaration"; +const shader$3W = `#include +#include +attribute vec2 position;`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$3X]) { + ShaderStore.IncludesShadersStore[name$3X] = shader$3W; +} + +// Do not edit. +const name$3W = "gaussianSplatting"; +const shader$3V = `#if !defined(WEBGL2) && !defined(WEBGPU) && !defined(NATIVE) +mat3 transpose(mat3 matrix) {return mat3(matrix[0][0],matrix[1][0],matrix[2][0], +matrix[0][1],matrix[1][1],matrix[2][1], +matrix[0][2],matrix[1][2],matrix[2][2]);} +#endif +vec2 getDataUV(float index,vec2 textureSize) {float y=floor(index/textureSize.x);float x=index-y*textureSize.x;return vec2((x+0.5)/textureSize.x,(y+0.5)/textureSize.y);} +#if SH_DEGREE>0 +ivec2 getDataUVint(float index,vec2 textureSize) {float y=floor(index/textureSize.x);float x=index-y*textureSize.x;return ivec2(uint(x+0.5),uint(y+0.5));} +#endif +struct Splat {vec4 center;vec4 color;vec4 covA;vec4 covB; +#if SH_DEGREE>0 +uvec4 sh0; +#endif +#if SH_DEGREE>1 +uvec4 sh1; +#endif +#if SH_DEGREE>2 +uvec4 sh2; +#endif +};Splat readSplat(float splatIndex) +{Splat splat;vec2 splatUV=getDataUV(splatIndex,dataTextureSize);splat.center=texture2D(centersTexture,splatUV);splat.color=texture2D(colorsTexture,splatUV);splat.covA=texture2D(covariancesATexture,splatUV)*splat.center.w;splat.covB=texture2D(covariancesBTexture,splatUV)*splat.center.w; +#if SH_DEGREE>0 +ivec2 splatUVint=getDataUVint(splatIndex,dataTextureSize);splat.sh0=texelFetch(shTexture0,splatUVint,0); +#endif +#if SH_DEGREE>1 +splat.sh1=texelFetch(shTexture1,splatUVint,0); +#endif +#if SH_DEGREE>2 +splat.sh2=texelFetch(shTexture2,splatUVint,0); +#endif +return splat;} +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +vec3 computeColorFromSHDegree(vec3 dir,const vec3 sh[16]) +{const float SH_C0=0.28209479;const float SH_C1=0.48860251;float SH_C2[5];SH_C2[0]=1.092548430;SH_C2[1]=-1.09254843;SH_C2[2]=0.315391565;SH_C2[3]=-1.09254843;SH_C2[4]=0.546274215;float SH_C3[7];SH_C3[0]=-0.59004358;SH_C3[1]=2.890611442;SH_C3[2]=-0.45704579;SH_C3[3]=0.373176332;SH_C3[4]=-0.45704579;SH_C3[5]=1.445305721;SH_C3[6]=-0.59004358;vec3 result=/*SH_C0**/sh[0]; +#if SH_DEGREE>0 +float x=dir.x;float y=dir.y;float z=dir.z;result+=- SH_C1*y*sh[1]+SH_C1*z*sh[2]-SH_C1*x*sh[3]; +#if SH_DEGREE>1 +float xx=x*x,yy=y*y,zz=z*z;float xy=x*y,yz=y*z,xz=x*z;result+= +SH_C2[0]*xy*sh[4] + +SH_C2[1]*yz*sh[5] + +SH_C2[2]*(2.0*zz-xx-yy)*sh[6] + +SH_C2[3]*xz*sh[7] + +SH_C2[4]*(xx-yy)*sh[8]; +#if SH_DEGREE>2 +result+= +SH_C3[0]*y*(3.0*xx-yy)*sh[9] + +SH_C3[1]*xy*z*sh[10] + +SH_C3[2]*y*(4.0*zz-xx-yy)*sh[11] + +SH_C3[3]*z*(2.0*zz-3.0*xx-3.0*yy)*sh[12] + +SH_C3[4]*x*(4.0*zz-xx-yy)*sh[13] + +SH_C3[5]*z*(xx-yy)*sh[14] + +SH_C3[6]*x*(xx-3.0*yy)*sh[15]; +#endif +#endif +#endif +return result;} +vec4 decompose(uint value) +{vec4 components=vec4( +float((value ) & 255u), +float((value>>uint( 8)) & 255u), +float((value>>uint(16)) & 255u), +float((value>>uint(24)) & 255u));return components*vec4(2./255.)-vec4(1.);} +vec3 computeSH(Splat splat,vec3 color,vec3 dir) +{vec3 sh[16];sh[0]=color; +#if SH_DEGREE>0 +vec4 sh00=decompose(splat.sh0.x);vec4 sh01=decompose(splat.sh0.y);vec4 sh02=decompose(splat.sh0.z);sh[1]=vec3(sh00.x,sh00.y,sh00.z);sh[2]=vec3(sh00.w,sh01.x,sh01.y);sh[3]=vec3(sh01.z,sh01.w,sh02.x); +#endif +#if SH_DEGREE>1 +vec4 sh03=decompose(splat.sh0.w);vec4 sh04=decompose(splat.sh1.x);vec4 sh05=decompose(splat.sh1.y);sh[4]=vec3(sh02.y,sh02.z,sh02.w);sh[5]=vec3(sh03.x,sh03.y,sh03.z);sh[6]=vec3(sh03.w,sh04.x,sh04.y);sh[7]=vec3(sh04.z,sh04.w,sh05.x);sh[8]=vec3(sh05.y,sh05.z,sh05.w); +#endif +#if SH_DEGREE>2 +vec4 sh06=decompose(splat.sh1.z);vec4 sh07=decompose(splat.sh1.w);vec4 sh08=decompose(splat.sh2.x);vec4 sh09=decompose(splat.sh2.y);vec4 sh10=decompose(splat.sh2.z);vec4 sh11=decompose(splat.sh2.w);sh[9]=vec3(sh06.x,sh06.y,sh06.z);sh[10]=vec3(sh06.w,sh07.x,sh07.y);sh[11]=vec3(sh07.z,sh07.w,sh08.x);sh[12]=vec3(sh08.y,sh08.z,sh08.w);sh[13]=vec3(sh09.x,sh09.y,sh09.z);sh[14]=vec3(sh09.w,sh10.x,sh10.y);sh[15]=vec3(sh10.z,sh10.w,sh11.x); +#endif +return computeColorFromSHDegree(dir,sh);} +#else +vec3 computeSH(Splat splat,vec3 color,vec3 dir) +{return color;} +#endif +vec4 gaussianSplatting(vec2 meshPos,vec3 worldPos,vec2 scale,vec3 covA,vec3 covB,mat4 worldMatrix,mat4 viewMatrix,mat4 projectionMatrix) +{mat4 modelView=viewMatrix*worldMatrix;vec4 camspace=viewMatrix*vec4(worldPos,1.);vec4 pos2d=projectionMatrix*camspace;float bounds=1.2*pos2d.w;if (pos2d.z<-pos2d.w || pos2d.x<-bounds || pos2d.x>bounds +|| pos2d.y<-bounds || pos2d.y>bounds) {return vec4(0.0,0.0,2.0,1.0);} +mat3 Vrk=mat3( +covA.x,covA.y,covA.z, +covA.y,covB.x,covB.y, +covA.z,covB.y,covB.z +);mat3 J=mat3( +focal.x/camspace.z,0.,-(focal.x*camspace.x)/(camspace.z*camspace.z), +0.,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z), +0.,0.,0. +);mat3 invy=mat3(1,0,0,0,-1,0,0,0,1);mat3 T=invy*transpose(mat3(modelView))*J;mat3 cov2d=transpose(T)*Vrk*T;float mid=(cov2d[0][0]+cov2d[1][1])/2.0;float radius=length(vec2((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));float epsilon=0.0001;float lambda1=mid+radius+epsilon,lambda2=mid-radius+epsilon;if (lambda2<0.0) +{return vec4(0.0,0.0,2.0,1.0);} +vec2 diagonalVector=normalize(vec2(cov2d[0][1],lambda1-cov2d[0][0]));vec2 majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;vec2 minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);vec2 vCenter=vec2(pos2d);return vec4( +vCenter ++ ((meshPos.x*majorAxis ++ meshPos.y*minorAxis)*invViewport*pos2d.w)*scale,pos2d.zw);}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$3W]) { + ShaderStore.IncludesShadersStore[name$3W] = shader$3V; +} + +// Do not edit. +const name$3V = "gaussianSplattingVertexShader"; +const shader$3U = `#include<__decl__gaussianSplattingVertex> +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include +#include +#include +#include +attribute float splatIndex;uniform vec2 invViewport;uniform vec2 dataTextureSize;uniform vec2 focal;uniform sampler2D covariancesATexture;uniform sampler2D covariancesBTexture;uniform sampler2D centersTexture;uniform sampler2D colorsTexture; +#if SH_DEGREE>0 +uniform highp usampler2D shTexture0; +#endif +#if SH_DEGREE>1 +uniform highp usampler2D shTexture1; +#endif +#if SH_DEGREE>2 +uniform highp usampler2D shTexture2; +#endif +varying vec4 vColor;varying vec2 vPosition; +#include +void main () {Splat splat=readSplat(splatIndex);vec3 covA=splat.covA.xyz;vec3 covB=vec3(splat.covA.w,splat.covB.xy);vec4 worldPos=world*vec4(splat.center.xyz,1.0);vColor=splat.color;vPosition=position; +#if SH_DEGREE>0 +mat3 worldRot=mat3(world);mat3 normWorldRot=inverseMat3(worldRot);vec3 dir=normalize(normWorldRot*(worldPos.xyz-vEyePosition.xyz));dir.y*=-1.; +vColor.xyz=computeSH(splat,splat.color.xyz,dir); +#endif +gl_Position=gaussianSplatting(position,worldPos.xyz,vec2(1.,1.),covA,covB,world,view,projection); +#include +#include +#include +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3V]) { + ShaderStore.ShadersStore[name$3V] = shader$3U; +} +/** @internal */ +const gaussianSplattingVertexShader = { name: name$3V, shader: shader$3U }; + +const gaussianSplatting_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + gaussianSplattingVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3U = "gaussianSplattingFragmentDeclaration"; +const shader$3T = `fn gaussianColor(inColor: vec4f,inPosition: vec2f)->vec4f +{var A : f32=-dot(inPosition,inPosition);if (A>-4.0) +{var B: f32=exp(A)*inColor.a; +#include +var color: vec3f=inColor.rgb; +#ifdef FOG +#include +#endif +return vec4f(color,B);} else {return vec4f(0.0);}} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$3U]) { + ShaderStore.IncludesShadersStoreWGSL[name$3U] = shader$3T; +} + +// Do not edit. +const name$3T = "gaussianSplattingPixelShader"; +const shader$3S = `#include +#include +#include +varying vColor: vec4f;varying vPosition: vec2f; +#include +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#include +fragmentOutputs.color=gaussianColor(input.vColor,input.vPosition);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3T]) { + ShaderStore.ShadersStoreWGSL[name$3T] = shader$3S; +} +/** @internal */ +const gaussianSplattingPixelShaderWGSL = { name: name$3T, shader: shader$3S }; + +const gaussianSplatting_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + gaussianSplattingPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3S = "gaussianSplatting"; +const shader$3R = `fn getDataUV(index: f32,dataTextureSize: vec2f)->vec2 {let y: f32=floor(index/dataTextureSize.x);let x: f32=index-y*dataTextureSize.x;return vec2f((x+0.5),(y+0.5));} +struct Splat {center: vec4f, +color: vec4f, +covA: vec4f, +covB: vec4f, +#if SH_DEGREE>0 +sh0: vec4, +#endif +#if SH_DEGREE>1 +sh1: vec4, +#endif +#if SH_DEGREE>2 +sh2: vec4, +#endif +};fn readSplat(splatIndex: f32,dataTextureSize: vec2f)->Splat {var splat: Splat;let splatUV=getDataUV(splatIndex,dataTextureSize);let splatUVi32=vec2(i32(splatUV.x),i32(splatUV.y));splat.center=textureLoad(centersTexture,splatUVi32,0);splat.color=textureLoad(colorsTexture,splatUVi32,0);splat.covA=textureLoad(covariancesATexture,splatUVi32,0)*splat.center.w;splat.covB=textureLoad(covariancesBTexture,splatUVi32,0)*splat.center.w; +#if SH_DEGREE>0 +splat.sh0=textureLoad(shTexture0,splatUVi32,0); +#endif +#if SH_DEGREE>1 +splat.sh1=textureLoad(shTexture1,splatUVi32,0); +#endif +#if SH_DEGREE>2 +splat.sh2=textureLoad(shTexture2,splatUVi32,0); +#endif +return splat;} +fn computeColorFromSHDegree(dir: vec3f,sh: array,16>)->vec3f +{let SH_C0: f32=0.28209479;let SH_C1: f32=0.48860251;var SH_C2: array=array( +1.092548430, +-1.09254843, +0.315391565, +-1.09254843, +0.546274215 +);var SH_C3: array=array( +-0.59004358, +2.890611442, +-0.45704579, +0.373176332, +-0.45704579, +1.445305721, +-0.59004358 +);var result: vec3f=/*SH_C0**/sh[0]; +#if SH_DEGREE>0 +let x: f32=dir.x;let y: f32=dir.y;let z: f32=dir.z;result+=-SH_C1*y*sh[1]+SH_C1*z*sh[2]-SH_C1*x*sh[3]; +#if SH_DEGREE>1 +let xx: f32=x*x;let yy: f32=y*y;let zz: f32=z*z;let xy: f32=x*y;let yz: f32=y*z;let xz: f32=x*z;result+= +SH_C2[0]*xy*sh[4] + +SH_C2[1]*yz*sh[5] + +SH_C2[2]*(2.0f*zz-xx-yy)*sh[6] + +SH_C2[3]*xz*sh[7] + +SH_C2[4]*(xx-yy)*sh[8]; +#if SH_DEGREE>2 +result+= +SH_C3[0]*y*(3.0f*xx-yy)*sh[9] + +SH_C3[1]*xy*z*sh[10] + +SH_C3[2]*y*(4.0f*zz-xx-yy)*sh[11] + +SH_C3[3]*z*(2.0f*zz-3.0f*xx-3.0f*yy)*sh[12] + +SH_C3[4]*x*(4.0f*zz-xx-yy)*sh[13] + +SH_C3[5]*z*(xx-yy)*sh[14] + +SH_C3[6]*x*(xx-3.0f*yy)*sh[15]; +#endif +#endif +#endif +return result;} +fn decompose(value: u32)->vec4f +{let components : vec4f=vec4f( +f32((value ) & 255u), +f32((value>>u32( 8)) & 255u), +f32((value>>u32(16)) & 255u), +f32((value>>u32(24)) & 255u));return components*vec4f(2./255.)-vec4f(1.);} +fn computeSH(splat: Splat,color: vec3f,dir: vec3f)->vec3f +{var sh: array,16>;sh[0]=color; +#if SH_DEGREE>0 +let sh00: vec4f=decompose(splat.sh0.x);let sh01: vec4f=decompose(splat.sh0.y);let sh02: vec4f=decompose(splat.sh0.z);sh[1]=vec3f(sh00.x,sh00.y,sh00.z);sh[2]=vec3f(sh00.w,sh01.x,sh01.y);sh[3]=vec3f(sh01.z,sh01.w,sh02.x); +#endif +#if SH_DEGREE>1 +let sh03: vec4f=decompose(splat.sh0.w);let sh04: vec4f=decompose(splat.sh1.x);let sh05: vec4f=decompose(splat.sh1.y);sh[4]=vec3f(sh02.y,sh02.z,sh02.w);sh[5]=vec3f(sh03.x,sh03.y,sh03.z);sh[6]=vec3f(sh03.w,sh04.x,sh04.y);sh[7]=vec3f(sh04.z,sh04.w,sh05.x);sh[8]=vec3f(sh05.y,sh05.z,sh05.w); +#endif +#if SH_DEGREE>2 +let sh06: vec4f=decompose(splat.sh1.z);let sh07: vec4f=decompose(splat.sh1.w);let sh08: vec4f=decompose(splat.sh2.x);let sh09: vec4f=decompose(splat.sh2.y);let sh10: vec4f=decompose(splat.sh2.z);let sh11: vec4f=decompose(splat.sh2.w);sh[9]=vec3f(sh06.x,sh06.y,sh06.z);sh[10]=vec3f(sh06.w,sh07.x,sh07.y);sh[11]=vec3f(sh07.z,sh07.w,sh08.x);sh[12]=vec3f(sh08.y,sh08.z,sh08.w);sh[13]=vec3f(sh09.x,sh09.y,sh09.z);sh[14]=vec3f(sh09.w,sh10.x,sh10.y);sh[15]=vec3f(sh10.z,sh10.w,sh11.x); +#endif +return computeColorFromSHDegree(dir,sh);} +fn gaussianSplatting( +meshPos: vec2, +worldPos: vec3, +scale: vec2, +covA: vec3, +covB: vec3, +worldMatrix: mat4x4, +viewMatrix: mat4x4, +projectionMatrix: mat4x4, +focal: vec2f, +invViewport: vec2f +)->vec4f {let modelView=viewMatrix*worldMatrix;let camspace=viewMatrix*vec4f(worldPos,1.0);let pos2d=projectionMatrix*camspace;let bounds=1.2*pos2d.w;if (pos2d.z<0. || pos2d.x<-bounds || pos2d.x>bounds || pos2d.y<-bounds || pos2d.y>bounds) {return vec4f(0.0,0.0,2.0,1.0);} +let Vrk=mat3x3( +covA.x,covA.y,covA.z, +covA.y,covB.x,covB.y, +covA.z,covB.y,covB.z +);let J=mat3x3( +focal.x/camspace.z,0.0,-(focal.x*camspace.x)/(camspace.z*camspace.z), +0.0,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z), +0.0,0.0,0.0 +);let invy=mat3x3( +1.0,0.0,0.0, +0.0,-1.0,0.0, +0.0,0.0,1.0 +);let T=invy*transpose(mat3x3( +modelView[0].xyz, +modelView[1].xyz, +modelView[2].xyz))*J;let cov2d=transpose(T)*Vrk*T;let mid=(cov2d[0][0]+cov2d[1][1])/2.0;let radius=length(vec2((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));let lambda1=mid+radius;let lambda2=mid-radius;if (lambda2<0.0) {return vec4f(0.0,0.0,2.0,1.0);} +let diagonalVector=normalize(vec2(cov2d[0][1],lambda1-cov2d[0][0]));let majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;let minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);let vCenter=vec2(pos2d.x,pos2d.y);return vec4f( +vCenter+((meshPos.x*majorAxis+meshPos.y*minorAxis)*invViewport*pos2d.w)*scale, +pos2d.z, +pos2d.w +);} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$3S]) { + ShaderStore.IncludesShadersStoreWGSL[name$3S] = shader$3R; +} + +// Do not edit. +const name$3R = "gaussianSplattingVertexShader"; +const shader$3Q = `#include +#include +#include +#include +#include +attribute splatIndex: f32;attribute position: vec2f;uniform invViewport: vec2f;uniform dataTextureSize: vec2f;uniform focal: vec2f;var covariancesATexture: texture_2d;var covariancesBTexture: texture_2d;var centersTexture: texture_2d;var colorsTexture: texture_2d; +#if SH_DEGREE>0 +var shTexture0: texture_2d; +#endif +#if SH_DEGREE>1 +var shTexture1: texture_2d; +#endif +#if SH_DEGREE>2 +var shTexture2: texture_2d; +#endif +varying vColor: vec4f;varying vPosition: vec2f; +#include +@vertex +fn main(input : VertexInputs)->FragmentInputs {var splat: Splat=readSplat(input.splatIndex,uniforms.dataTextureSize);var covA: vec3f=splat.covA.xyz;var covB: vec3f=vec3f(splat.covA.w,splat.covB.xy);let worldPos: vec4f=mesh.world*vec4f(splat.center.xyz,1.0);vertexOutputs.vPosition=input.position; +#if SH_DEGREE>0 +let dir: vec3f=normalize(worldPos.xyz-scene.vEyePosition.xyz);vertexOutputs.vColor=vec4f(computeSH(splat,splat.color.xyz,dir),1.0); +#else +vertexOutputs.vColor=splat.color; +#endif +vertexOutputs.position=gaussianSplatting(input.position,worldPos.xyz,vec2f(1.0,1.0),covA,covB,mesh.world,scene.view,scene.projection,uniforms.focal,uniforms.invViewport); +#include +#include +#include +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3R]) { + ShaderStore.ShadersStoreWGSL[name$3R] = shader$3Q; +} +/** @internal */ +const gaussianSplattingVertexShaderWGSL = { name: name$3R, shader: shader$3Q }; + +const gaussianSplatting_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + gaussianSplattingVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * @internal + */ +class GaussianSplattingMaterialDefines extends MaterialDefines { + /** + * Constructor of the defines. + */ + constructor() { + super(); + this.FOG = false; + this.THIN_INSTANCES = true; + this.LOGARITHMICDEPTH = false; + this.CLIPPLANE = false; + this.CLIPPLANE2 = false; + this.CLIPPLANE3 = false; + this.CLIPPLANE4 = false; + this.CLIPPLANE5 = false; + this.CLIPPLANE6 = false; + this.SH_DEGREE = 0; + this.rebuild(); + } +} +/** + * GaussianSplattingMaterial material used to render Gaussian Splatting + * @experimental + */ +class GaussianSplattingMaterial extends PushMaterial { + /** + * Instantiates a Gaussian Splatting Material in the given scene + * @param name The friendly name of the material + * @param scene The scene to add the material to + */ + constructor(name, scene) { + super(name, scene); + this.backFaceCulling = false; + } + /** + * Gets a boolean indicating that current material needs to register RTT + */ + get hasRenderTargetTextures() { + return false; + } + /** + * Specifies whether or not this material should be rendered in alpha test mode. + * @returns false + */ + needAlphaTesting() { + return false; + } + /** + * Specifies whether or not this material should be rendered in alpha blend mode. + * @returns true + */ + needAlphaBlending() { + return true; + } + /** + * Checks whether the material is ready to be rendered for a given mesh. + * @param mesh The mesh to render + * @param subMesh The submesh to check against + * @returns true if all the dependencies are ready (Textures, Effects...) + */ + isReadyForSubMesh(mesh, subMesh) { + const useInstances = true; + const drawWrapper = subMesh._drawWrapper; + if (drawWrapper.effect && this.isFrozen) { + if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) { + return true; + } + } + if (!subMesh.materialDefines) { + subMesh.materialDefines = new GaussianSplattingMaterialDefines(); + } + const scene = this.getScene(); + const defines = subMesh.materialDefines; + if (this._isReadyForSubMesh(subMesh)) { + return true; + } + const engine = scene.getEngine(); + // Misc. + PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, false, defines); + // Values that need to be evaluated on every frame + PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, true); + // Attribs + PrepareDefinesForAttributes(mesh, defines, false, false); + // SH is disabled for webGL1 + if (engine.version > 1 || engine.isWebGPU) { + defines["SH_DEGREE"] = mesh.shDegree; + } + // Get correct effect + if (defines.isDirty) { + defines.markAsProcessed(); + scene.resetCachedMaterial(); + //Attributes + const attribs = [VertexBuffer.PositionKind, "splatIndex"]; + PrepareAttributesForInstances(attribs, defines); + const uniforms = ["world", "view", "projection", "vFogInfos", "vFogColor", "logarithmicDepthConstant", "invViewport", "dataTextureSize", "focal", "vEyePosition"]; + const samplers = ["covariancesATexture", "covariancesBTexture", "centersTexture", "colorsTexture", "shTexture0", "shTexture1", "shTexture2"]; + const uniformBuffers = ["Scene", "Mesh"]; + PrepareUniformsAndSamplersList({ + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: defines, + }); + addClipPlaneUniforms(uniforms); + const join = defines.toString(); + const effect = scene.getEngine().createEffect("gaussianSplatting", { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: join, + onCompiled: this.onCompiled, + onError: this.onError, + indexParameters: {}, + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => gaussianSplatting_fragment), Promise.resolve().then(() => gaussianSplatting_vertex)]); + } + else { + await Promise.all([Promise.resolve().then(() => gaussianSplatting_fragment$1), Promise.resolve().then(() => gaussianSplatting_vertex$1)]); + } + }, + }, engine); + subMesh.setEffect(effect, defines, this._materialContext); + } + if (!subMesh.effect || !subMesh.effect.isReady()) { + return false; + } + defines._renderId = scene.getRenderId(); + drawWrapper._wasPreviouslyReady = true; + drawWrapper._wasPreviouslyUsingInstances = useInstances; + return true; + } + /** + * Bind material effect for a specific Gaussian Splatting mesh + * @param mesh Gaussian splatting mesh + * @param effect Splatting material or node material + * @param scene scene that contains mesh and camera used for rendering + */ + static BindEffect(mesh, effect, scene) { + const engine = scene.getEngine(); + const camera = scene.activeCamera; + const renderWidth = engine.getRenderWidth(); + const renderHeight = engine.getRenderHeight(); + // check if rigcamera, get number of rigs + const numberOfRigs = camera?.rigParent?.rigCameras.length || 1; + effect.setFloat2("invViewport", 1 / (renderWidth / numberOfRigs), 1 / renderHeight); + let focal = 1000; + if (camera) { + /* + more explicit version: + const t = camera.getProjectionMatrix().m[5]; + const FovY = Math.atan(1.0 / t) * 2.0; + focal = renderHeight / 2.0 / Math.tan(FovY / 2.0); + Using a shorter version here to not have tan(atan) and 2.0 factor + */ + const t = camera.getProjectionMatrix().m[5]; + if (camera.fovMode == Camera.FOVMODE_VERTICAL_FIXED) { + focal = (renderHeight * t) / 2.0; + } + else { + focal = (renderWidth * t) / 2.0; + } + } + effect.setFloat2("focal", focal, focal); + const gsMesh = mesh; + if (gsMesh.covariancesATexture) { + const textureSize = gsMesh.covariancesATexture.getSize(); + effect.setFloat2("dataTextureSize", textureSize.width, textureSize.height); + effect.setTexture("covariancesATexture", gsMesh.covariancesATexture); + effect.setTexture("covariancesBTexture", gsMesh.covariancesBTexture); + effect.setTexture("centersTexture", gsMesh.centersTexture); + effect.setTexture("colorsTexture", gsMesh.colorsTexture); + if (gsMesh.shTextures) { + for (let i = 0; i < gsMesh.shTextures?.length; i++) { + effect.setTexture(`shTexture${i}`, gsMesh.shTextures[i]); + } + } + } + } + /** + * Binds the submesh to this material by preparing the effect and shader to draw + * @param world defines the world transformation matrix + * @param mesh defines the mesh containing the submesh + * @param subMesh defines the submesh to bind the material to + */ + bindForSubMesh(world, mesh, subMesh) { + const scene = this.getScene(); + const defines = subMesh.materialDefines; + if (!defines) { + return; + } + const effect = subMesh.effect; + if (!effect) { + return; + } + this._activeEffect = effect; + // Matrices Mesh. + mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); + mesh.transferToEffect(world); + // Bind data + const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility); + if (mustRebind) { + this.bindView(effect); + this.bindViewProjection(effect); + GaussianSplattingMaterial.BindEffect(mesh, this._activeEffect, scene); + // Clip plane + bindClipPlane(effect, this, scene); + } + else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) { + this._needToBindSceneUbo = true; + } + // Fog + BindFogParameters(scene, mesh, effect); + // Log. depth + if (this.useLogarithmicDepth) { + BindLogDepth(defines, effect, scene); + } + this._afterBind(mesh, this._activeEffect, subMesh); + } + /** + * Clones the material. + * @param name The cloned name. + * @returns The cloned material. + */ + clone(name) { + return SerializationHelper.Clone(() => new GaussianSplattingMaterial(name, this.getScene()), this); + } + /** + * Serializes the current material to its JSON representation. + * @returns The JSON representation. + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.customType = "BABYLON.GaussianSplattingMaterial"; + return serializationObject; + } + /** + * Gets the class name of the material + * @returns "GaussianSplattingMaterial" + */ + getClassName() { + return "GaussianSplattingMaterial"; + } + /** + * Parse a JSON input to create back a Gaussian Splatting material. + * @param source The JSON data to parse + * @param scene The scene to create the parsed material in + * @param rootUrl The root url of the assets the material depends upon + * @returns the instantiated GaussianSplattingMaterial. + */ + static Parse(source, scene, rootUrl) { + return SerializationHelper.Parse(() => new GaussianSplattingMaterial(source.name, scene), source, scene, rootUrl); + } +} +RegisterClass("BABYLON.GaussianSplattingMaterial", GaussianSplattingMaterial); + +/** + * Block used for Reading components of the Gaussian Splatting + */ +class SplatReaderBlock extends NodeMaterialBlock { + /** + * Create a new SplatReaderBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Vertex); + this._isUnique = true; + this.registerInput("splatIndex", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Vertex); + this.registerOutput("splatPosition", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Vertex); + this.registerOutput("splatColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Vertex); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SplatReaderBlock"; + } + /** + * Gets the splat index input component + */ + get splatIndex() { + return this._inputs[0]; + } + /** + * Gets the splatPosition output component + */ + get splatPosition() { + return this._outputs[0]; + } + /** + * Gets the splatColor output component + */ + get splatColor() { + return this._outputs[1]; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("covA"); + state._excludeVariableName("covB"); + state._excludeVariableName("vPosition"); + state._excludeVariableName("covariancesATexture"); + state._excludeVariableName("covariancesBTexture"); + state._excludeVariableName("centersTexture"); + state._excludeVariableName("colorsTexture"); + state._excludeVariableName("dataTextureSize"); + } + bind(effect, nodeMaterial, mesh) { + if (!mesh) { + return; + } + const scene = mesh.getScene(); + GaussianSplattingMaterial.BindEffect(mesh, effect, scene); + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Fragment) { + return; + } + state.sharedData.bindableBlocks.push(this); + // Emit code + const comments = `//${this.name}`; + state._emit2DSampler("covariancesATexture"); + state._emit2DSampler("covariancesBTexture"); + state._emit2DSampler("centersTexture"); + state._emit2DSampler("colorsTexture"); + state._emitFunctionFromInclude("gaussianSplattingVertexDeclaration", comments); + state._emitFunctionFromInclude("gaussianSplatting", comments); + state._emitVaryingFromString("vPosition", NodeMaterialBlockConnectionPointTypes.Vector2); + state._emitUniformFromString("dataTextureSize", NodeMaterialBlockConnectionPointTypes.Vector2); + const splatIndex = this.splatIndex; + const splatPosition = this.splatPosition; + const splatColor = this.splatColor; + const splatVariablename = state._getFreeVariableName("splat"); + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + state.compilationString += `var ${splatVariablename}: Splat = readSplat(${splatIndex.associatedVariableName}, uniforms.dataTextureSize);\n`; + state.compilationString += `var covA: vec3f = splat.covA.xyz; var covB: vec3f = vec3f(splat.covA.w, splat.covB.xy);\n`; + state.compilationString += "vertexOutputs.vPosition = input.position;\n"; + } + else { + state.compilationString += `Splat ${splatVariablename} = readSplat(${splatIndex.associatedVariableName});\n`; + state.compilationString += `vec3 covA = splat.covA.xyz; vec3 covB = vec3(splat.covA.w, splat.covB.xy);\n`; + state.compilationString += "vPosition = position;\n"; + } + state.compilationString += `${state._declareOutput(splatPosition)} = ${splatVariablename}.center.xyz;\n`; + state.compilationString += `${state._declareOutput(splatColor)} = ${splatVariablename}.color;\n`; + return this; + } +} +RegisterClass("BABYLON.SplatReaderBlock", SplatReaderBlock); + +/** + * Block used to add support for vertex skinning (bones) + */ +class BonesBlock extends NodeMaterialBlock { + /** + * Creates a new BonesBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Vertex); + this.registerInput("matricesIndices", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("matricesWeights", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("matricesIndicesExtra", NodeMaterialBlockConnectionPointTypes.Vector4, true); + this.registerInput("matricesWeightsExtra", NodeMaterialBlockConnectionPointTypes.Vector4, true); + this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("boneSampler"); + state._excludeVariableName("boneTextureWidth"); + state._excludeVariableName("mBones"); + state._excludeVariableName("BonesPerMesh"); + this._initShaderSourceAsync(state.shaderLanguage); + } + async _initShaderSourceAsync(shaderLanguage) { + this._codeIsReady = false; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => bonesDeclaration), Promise.resolve().then(() => bonesVertex)]); + } + else { + await Promise.all([Promise.resolve().then(() => bonesDeclaration$2), Promise.resolve().then(() => bonesVertex$2)]); + } + this._codeIsReady = true; + this.onCodeIsReadyObservable.notifyObservers(this); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "BonesBlock"; + } + /** + * Gets the matrix indices input component + */ + get matricesIndices() { + return this._inputs[0]; + } + /** + * Gets the matrix weights input component + */ + get matricesWeights() { + return this._inputs[1]; + } + /** + * Gets the extra matrix indices input component + */ + get matricesIndicesExtra() { + return this._inputs[2]; + } + /** + * Gets the extra matrix weights input component + */ + get matricesWeightsExtra() { + return this._inputs[3]; + } + /** + * Gets the world input component + */ + get world() { + return this._inputs[4]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.matricesIndices.isConnected) { + let matricesIndicesInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "matricesIndices" && additionalFilteringInfo(b)); + if (!matricesIndicesInput) { + matricesIndicesInput = new InputBlock("matricesIndices"); + matricesIndicesInput.setAsAttribute("matricesIndices"); + } + matricesIndicesInput.output.connectTo(this.matricesIndices); + } + if (!this.matricesWeights.isConnected) { + let matricesWeightsInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "matricesWeights" && additionalFilteringInfo(b)); + if (!matricesWeightsInput) { + matricesWeightsInput = new InputBlock("matricesWeights"); + matricesWeightsInput.setAsAttribute("matricesWeights"); + } + matricesWeightsInput.output.connectTo(this.matricesWeights); + } + if (!this.world.isConnected) { + let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World && additionalFilteringInfo(b)); + if (!worldInput) { + worldInput = new InputBlock("world"); + worldInput.setAsSystemValue(NodeMaterialSystemValues.World); + } + worldInput.output.connectTo(this.world); + } + } + provideFallbacks(mesh, fallbacks) { + if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + fallbacks.addCPUSkinningFallback(0, mesh); + } + } + bind(effect, nodeMaterial, mesh) { + BindBonesParameters(mesh, effect); + } + prepareDefines(mesh, nodeMaterial, defines) { + if (!defines._areAttributesDirty) { + return; + } + PrepareDefinesForBones(mesh, defines); + } + _buildBlock(state) { + super._buildBlock(state); + // Register for compilation fallbacks + state.sharedData.blocksWithFallbacks.push(this); + // Register for binding + state.sharedData.forcedBindableBlocks.push(this); + // Register for defines + state.sharedData.blocksWithDefines.push(this); + // Register internal uniforms and samplers + state.uniforms.push("boneTextureWidth"); + state.uniforms.push("mBones"); + state.samplers.push("boneSampler"); + // Emit code + const comments = `//${this.name}`; + state._emitFunctionFromInclude("bonesDeclaration", comments, { + removeAttributes: true, + removeUniforms: false, + removeVaryings: true, + removeIfDef: false, + }); + const influenceVariablename = state._getFreeVariableName("influence"); + state.compilationString += state._emitCodeFromInclude("bonesVertex", comments, { + replaceStrings: [ + { + search: /finalWorld=finalWorld\*influence;/, + replace: "", + }, + { + search: /influence/gm, + replace: influenceVariablename, + }, + ], + }); + const output = this._outputs[0]; + const worldInput = this.world; + state.compilationString += `#if NUM_BONE_INFLUENCERS>0\n`; + state.compilationString += state._declareOutput(output) + ` = ${worldInput.associatedVariableName} * ${influenceVariablename};\n`; + state.compilationString += `#else\n`; + state.compilationString += state._declareOutput(output) + ` = ${worldInput.associatedVariableName};\n`; + state.compilationString += `#endif\n`; + return this; + } +} +RegisterClass("BABYLON.BonesBlock", BonesBlock); + +/** + * Block used to add support for instances + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances + */ +class InstancesBlock extends NodeMaterialBlock { + /** + * Creates a new InstancesBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Vertex); + this.registerInput("world0", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("world1", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("world2", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("world3", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, true); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix); + this.registerOutput("instanceID", NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "InstancesBlock"; + } + /** + * Gets the first world row input component + */ + get world0() { + return this._inputs[0]; + } + /** + * Gets the second world row input component + */ + get world1() { + return this._inputs[1]; + } + /** + * Gets the third world row input component + */ + get world2() { + return this._inputs[2]; + } + /** + * Gets the forth world row input component + */ + get world3() { + return this._inputs[3]; + } + /** + * Gets the world input component + */ + get world() { + return this._inputs[4]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the instanceID component + */ + get instanceID() { + return this._outputs[1]; + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.world0.connectedPoint) { + let world0Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world0" && additionalFilteringInfo(b)); + if (!world0Input) { + world0Input = new InputBlock("world0"); + world0Input.setAsAttribute("world0"); + } + world0Input.output.connectTo(this.world0); + } + if (!this.world1.connectedPoint) { + let world1Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world1" && additionalFilteringInfo(b)); + if (!world1Input) { + world1Input = new InputBlock("world1"); + world1Input.setAsAttribute("world1"); + } + world1Input.output.connectTo(this.world1); + } + if (!this.world2.connectedPoint) { + let world2Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world2" && additionalFilteringInfo(b)); + if (!world2Input) { + world2Input = new InputBlock("world2"); + world2Input.setAsAttribute("world2"); + } + world2Input.output.connectTo(this.world2); + } + if (!this.world3.connectedPoint) { + let world3Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world3" && additionalFilteringInfo(b)); + if (!world3Input) { + world3Input = new InputBlock("world3"); + world3Input.setAsAttribute("world3"); + } + world3Input.output.connectTo(this.world3); + } + if (!this.world.connectedPoint) { + let worldInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world" && additionalFilteringInfo(b)); + if (!worldInput) { + worldInput = new InputBlock("world"); + worldInput.setAsSystemValue(NodeMaterialSystemValues.World); + } + worldInput.output.connectTo(this.world); + } + this.world.define = "!INSTANCES || THIN_INSTANCES"; + } + prepareDefines(mesh, nodeMaterial, defines, useInstances = false, subMesh) { + let changed = false; + if (defines["INSTANCES"] !== useInstances) { + defines.setValue("INSTANCES", useInstances); + changed = true; + } + if (subMesh && defines["THIN_INSTANCES"] !== !!subMesh?.getRenderingMesh().hasThinInstances) { + defines.setValue("THIN_INSTANCES", !!subMesh?.getRenderingMesh().hasThinInstances); + changed = true; + } + if (changed) { + defines.markAsUnprocessed(); + } + } + _buildBlock(state) { + super._buildBlock(state); + const engine = state.sharedData.scene.getEngine(); + // Register for defines + state.sharedData.blocksWithDefines.push(this); + // Emit code + const output = this._outputs[0]; + const instanceID = this._outputs[1]; + const world0 = this.world0; + const world1 = this.world1; + const world2 = this.world2; + const world3 = this.world3; + let mat4 = "mat4"; + let instance = "gl_InstanceID"; + let floatCast = "float"; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + mat4 = "mat4x4f"; + instance = "vertexInputs.instanceIndex"; + floatCast = "f32"; + } + state.compilationString += `#ifdef INSTANCES\n`; + state.compilationString += + state._declareOutput(output) + + ` = ${mat4}(${world0.associatedVariableName}, ${world1.associatedVariableName}, ${world2.associatedVariableName}, ${world3.associatedVariableName});\n`; + state.compilationString += `#ifdef THIN_INSTANCES\n`; + state.compilationString += `${output.associatedVariableName} = ${this.world.associatedVariableName} * ${output.associatedVariableName};\n`; + state.compilationString += `#endif\n`; + if (engine._caps.canUseGLInstanceID) { + state.compilationString += state._declareOutput(instanceID) + ` = ${floatCast}(${instance});\n`; + } + else { + state.compilationString += state._declareOutput(instanceID) + ` = 0.0;\n`; + } + state.compilationString += `#else\n`; + state.compilationString += state._declareOutput(output) + ` = ${this.world.associatedVariableName};\n`; + state.compilationString += state._declareOutput(instanceID) + ` = 0.0;\n`; + state.compilationString += `#endif\n`; + return this; + } +} +RegisterClass("BABYLON.InstancesBlock", InstancesBlock); + +/** + * Block used to add morph targets support to vertex shader + */ +class MorphTargetsBlock extends NodeMaterialBlock { + /** + * Create a new MorphTargetsBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Vertex); + this.registerInput("position", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerInput("tangent", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.tangent.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerInput("uv2", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4); + this.registerOutput("positionOutput", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerOutput("normalOutput", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerOutput("tangentOutput", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("uvOutput", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerOutput("uv2Output", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerOutput("colorOutput", NodeMaterialBlockConnectionPointTypes.Color4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MorphTargetsBlock"; + } + /** + * Gets the position input component + */ + get position() { + return this._inputs[0]; + } + /** + * Gets the normal input component + */ + get normal() { + return this._inputs[1]; + } + /** + * Gets the tangent input component + */ + get tangent() { + return this._inputs[2]; + } + /** + * Gets the uv input component + */ + get uv() { + return this._inputs[3]; + } + /** + * Gets the uv2 input component + */ + get uv2() { + return this._inputs[4]; + } + /** + * Gets the color input component + */ + get color() { + return this._inputs[5]; + } + /** + * Gets the position output component + */ + get positionOutput() { + return this._outputs[0]; + } + /** + * Gets the normal output component + */ + get normalOutput() { + return this._outputs[1]; + } + /** + * Gets the tangent output component + */ + get tangentOutput() { + return this._outputs[2]; + } + /** + * Gets the uv output component + */ + get uvOutput() { + return this._outputs[3]; + } + /** + * Gets the uv2 output component + */ + get uv2Output() { + return this._outputs[4]; + } + /** + * Gets the color output component + */ + get colorOutput() { + return this._outputs[5]; + } + initialize(state) { + state._excludeVariableName("morphTargetInfluences"); + this._initShaderSourceAsync(state.shaderLanguage); + } + async _initShaderSourceAsync(shaderLanguage) { + this._codeIsReady = false; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([ + Promise.resolve().then(() => morphTargetsVertex), + Promise.resolve().then(() => morphTargetsVertexDeclaration), + Promise.resolve().then(() => morphTargetsVertexGlobal), + Promise.resolve().then(() => morphTargetsVertexGlobalDeclaration), + ]); + } + else { + await Promise.all([ + Promise.resolve().then(() => morphTargetsVertex$2), + Promise.resolve().then(() => morphTargetsVertexDeclaration$2), + Promise.resolve().then(() => morphTargetsVertexGlobal$2), + Promise.resolve().then(() => morphTargetsVertexGlobalDeclaration$2), + ]); + } + this._codeIsReady = true; + this.onCodeIsReadyObservable.notifyObservers(this); + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.position.isConnected) { + let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "position" && additionalFilteringInfo(b)); + if (!positionInput) { + positionInput = new InputBlock("position"); + positionInput.setAsAttribute(); + } + positionInput.output.connectTo(this.position); + } + if (!this.normal.isConnected) { + let normalInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "normal" && additionalFilteringInfo(b)); + if (!normalInput) { + normalInput = new InputBlock("normal"); + normalInput.setAsAttribute("normal"); + } + normalInput.output.connectTo(this.normal); + } + if (!this.tangent.isConnected) { + let tangentInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "tangent" && additionalFilteringInfo(b)); + if (!tangentInput) { + tangentInput = new InputBlock("tangent"); + tangentInput.setAsAttribute("tangent"); + } + tangentInput.output.connectTo(this.tangent); + } + if (!this.uv.isConnected) { + let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv" && additionalFilteringInfo(b)); + if (!uvInput) { + uvInput = new InputBlock("uv"); + uvInput.setAsAttribute("uv"); + } + uvInput.output.connectTo(this.uv); + } + if (!this.uv2.isConnected) { + let uv2Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv2" && additionalFilteringInfo(b)); + if (!uv2Input) { + uv2Input = new InputBlock("uv2"); + uv2Input.setAsAttribute("uv2"); + } + uv2Input.output.connectTo(this.uv2); + } + if (!this.color.isConnected) { + let colorInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "color" && additionalFilteringInfo(b)); + if (!colorInput) { + colorInput = new InputBlock("color"); + colorInput.setAsAttribute("color"); + } + colorInput.output.connectTo(this.color); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + if (mesh.morphTargetManager) { + const morphTargetManager = mesh.morphTargetManager; + if (morphTargetManager?.isUsingTextureForTargets && (morphTargetManager.numMaxInfluencers || morphTargetManager.numInfluencers) !== defines["NUM_MORPH_INFLUENCERS"]) { + defines.markAsAttributesDirty(); + } + } + if (!defines._areAttributesDirty) { + return; + } + PrepareDefinesForMorphTargets(mesh, defines); + } + bind(effect, nodeMaterial, mesh) { + if (mesh && mesh.morphTargetManager && mesh.morphTargetManager.numInfluencers > 0) { + BindMorphTargetParameters(mesh, effect); + if (mesh.morphTargetManager.isUsingTextureForTargets) { + mesh.morphTargetManager._bind(effect); + } + } + } + replaceRepeatableContent(vertexShaderState, fragmentShaderState, mesh, defines) { + const position = this.position; + const normal = this.normal; + const tangent = this.tangent; + const uv = this.uv; + const uv2 = this.uv2; + const color = this.color; + const positionOutput = this.positionOutput; + const normalOutput = this.normalOutput; + const tangentOutput = this.tangentOutput; + const uvOutput = this.uvOutput; + const uv2Output = this.uv2Output; + const colorOutput = this.colorOutput; + const state = vertexShaderState; + const repeatCount = defines.NUM_MORPH_INFLUENCERS; + const manager = mesh.morphTargetManager; + const supportPositions = manager && manager.supportsPositions; + const supportNormals = manager && manager.supportsNormals; + const supportTangents = manager && manager.supportsTangents; + const supportUVs = manager && manager.supportsUVs; + const supportUV2s = manager && manager.supportsUV2s; + const supportColors = manager && manager.supportsColors; + let injectionCode = ""; + if (manager?.isUsingTextureForTargets && repeatCount > 0) { + injectionCode += `${state._declareLocalVar("vertexID", NodeMaterialBlockConnectionPointTypes.Float)};\n`; + } + injectionCode += `#ifdef MORPHTARGETS\n`; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + const uniformsPrefix = isWebGPU ? "uniforms." : ""; + if (manager?.isUsingTextureForTargets) { + injectionCode += `for (${isWebGPU ? "var" : "int"} i = 0; i < NUM_MORPH_INFLUENCERS; i++) {\n`; + injectionCode += `if (i >= ${uniformsPrefix}morphTargetCount) { break; }\n`; + injectionCode += `vertexID = ${isWebGPU ? "f32(vertexInputs.vertexIndex" : "float(gl_VertexID"}) * ${uniformsPrefix}morphTargetTextureInfo.x;\n`; + if (supportPositions) { + injectionCode += `#ifdef MORPHTARGETS_POSITION\n`; + injectionCode += `${positionOutput.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${position.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[i];\n`; + injectionCode += `#endif\n`; + } + injectionCode += `#ifdef MORPHTARGETTEXTURE_HASPOSITIONS\n`; + injectionCode += `vertexID += 1.0;\n`; + injectionCode += `#endif\n`; + if (supportNormals) { + injectionCode += `#ifdef MORPHTARGETS_NORMAL\n`; + injectionCode += `${normalOutput.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${normal.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[i];\n`; + injectionCode += `#endif\n`; + } + injectionCode += `#ifdef MORPHTARGETTEXTURE_HASNORMALS\n`; + injectionCode += `vertexID += 1.0;\n`; + injectionCode += `#endif\n`; + if (supportUVs) { + injectionCode += `#ifdef MORPHTARGETS_UV\n`; + injectionCode += `${uvOutput.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${uv.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[i];\n`; + injectionCode += `#endif\n`; + } + injectionCode += `#ifdef MORPHTARGETTEXTURE_HASUVS\n`; + injectionCode += `vertexID += 1.0;\n`; + injectionCode += `#endif\n`; + if (supportTangents) { + injectionCode += `#ifdef MORPHTARGETS_TANGENT\n`; + injectionCode += `${tangentOutput.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${tangent.associatedVariableName}.xyz) * ${uniformsPrefix}morphTargetInfluences[i];\n`; + if (tangent.type === NodeMaterialBlockConnectionPointTypes.Vector4) { + injectionCode += `${tangentOutput.associatedVariableName}.w = ${tangent.associatedVariableName}.w;\n`; + } + else { + injectionCode += `${tangentOutput.associatedVariableName}.w = 1.;\n`; + } + injectionCode += `#endif\n`; + } + injectionCode += `#ifdef MORPHTARGETTEXTURE_HASTANGENTS\n`; + injectionCode += `vertexID += 1.0;\n`; + injectionCode += `#endif\n`; + if (supportUV2s) { + injectionCode += `#ifdef MORPHTARGETS_UV2\n`; + injectionCode += `${uv2Output.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${uv2.associatedVariableName}) * morphTargetInfluences[i];\n`; + injectionCode += `#endif\n`; + } + injectionCode += `#ifdef MORPHTARGETTEXTURE_HASUV2S\n`; + injectionCode += `vertexID += 1.0;\n`; + injectionCode += `#endif\n`; + if (supportColors) { + injectionCode += `#ifdef MORPHTARGETS_COLOR\n`; + injectionCode += `${colorOutput.associatedVariableName} += (readVector4FromRawSampler(i, vertexID) - ${color.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[i];\n`; + injectionCode += `#endif\n`; + } + injectionCode += "}\n"; + } + else { + for (let index = 0; index < repeatCount; index++) { + if (supportPositions) { + injectionCode += `#ifdef MORPHTARGETS_POSITION\n`; + injectionCode += `${positionOutput.associatedVariableName} += (position${index} - ${position.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[${index}];\n`; + injectionCode += `#endif\n`; + } + if (supportNormals && defines["NORMAL"]) { + injectionCode += `#ifdef MORPHTARGETS_NORMAL\n`; + injectionCode += `${normalOutput.associatedVariableName} += (normal${index} - ${normal.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[${index}];\n`; + injectionCode += `#endif\n`; + } + if (supportUVs && defines["UV1"]) { + injectionCode += `#ifdef MORPHTARGETS_UV\n`; + injectionCode += `${uvOutput.associatedVariableName}.xy += (uv_${index} - ${uv.associatedVariableName}.xy) * ${uniformsPrefix}morphTargetInfluences[${index}];\n`; + injectionCode += `#endif\n`; + } + if (supportTangents && defines["TANGENT"]) { + injectionCode += `#ifdef MORPHTARGETS_TANGENT\n`; + injectionCode += `${tangentOutput.associatedVariableName}.xyz += (tangent${index} - ${tangent.associatedVariableName}.xyz) * ${uniformsPrefix}morphTargetInfluences[${index}];\n`; + if (tangent.type === NodeMaterialBlockConnectionPointTypes.Vector4) { + injectionCode += `${tangentOutput.associatedVariableName}.w = ${tangent.associatedVariableName}.w;\n`; + } + else { + injectionCode += `${tangentOutput.associatedVariableName}.w = 1.;\n`; + } + injectionCode += `#endif\n`; + } + if (supportUV2s && defines["UV2"]) { + injectionCode += `#ifdef MORPHTARGETS_UV2\n`; + injectionCode += `${uv2Output.associatedVariableName}.xy += (uv2_${index} - ${uv2.associatedVariableName}.xy) * morphTargetInfluences[${index}];\n`; + injectionCode += `#endif\n`; + } + if (supportColors && defines["VERTEXCOLOR_NME"]) { + injectionCode += `#ifdef MORPHTARGETS_COLOR\n`; + injectionCode += `${colorOutput.associatedVariableName} += (color${index} - ${color.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[${index}];\n`; + injectionCode += `#endif\n`; + } + } + } + injectionCode += `#endif\n`; + state.compilationString = state.compilationString.replace(this._repeatableContentAnchor, injectionCode); + if (repeatCount > 0) { + for (let index = 0; index < repeatCount; index++) { + if (supportPositions) { + state.attributes.push(VertexBuffer.PositionKind + index); + } + if (supportNormals && defines["NORMAL"]) { + state.attributes.push(VertexBuffer.NormalKind + index); + } + if (supportTangents && defines["TANGENT"]) { + state.attributes.push(VertexBuffer.TangentKind + index); + } + if (supportUVs && defines["UV1"]) { + state.attributes.push(VertexBuffer.UVKind + "_" + index); + } + if (supportUV2s && defines["UV2"]) { + state.attributes.push(VertexBuffer.UV2Kind + "_" + index); + } + if (supportColors && defines["VERTEXCOLOR_NME"]) { + state.attributes.push(VertexBuffer.ColorKind + index); + } + } + } + } + _buildBlock(state) { + super._buildBlock(state); + // Register for defines + state.sharedData.blocksWithDefines.push(this); + // Register for binding + state.sharedData.bindableBlocks.push(this); + // Register for repeatable content generation + state.sharedData.repeatableContentBlocks.push(this); + // Emit code + const position = this.position; + const normal = this.normal; + const tangent = this.tangent; + const uv = this.uv; + const uv2 = this.uv2; + const color = this.color; + const positionOutput = this.positionOutput; + const normalOutput = this.normalOutput; + const tangentOutput = this.tangentOutput; + const uvOutput = this.uvOutput; + const uv2Output = this.uv2Output; + const colorOutput = this.colorOutput; + const comments = `//${this.name}`; + state.uniforms.push("morphTargetInfluences"); + state.uniforms.push("morphTargetCount"); + state.uniforms.push("morphTargetTextureInfo"); + state.uniforms.push("morphTargetTextureIndices"); + state.samplers.push("morphTargets"); + state._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration", comments); + state._emitFunctionFromInclude("morphTargetsVertexDeclaration", comments, { + repeatKey: "maxSimultaneousMorphTargets", + }); + state.compilationString += `${state._declareOutput(positionOutput)} = ${position.associatedVariableName};\n`; + state.compilationString += `#ifdef NORMAL\n`; + state.compilationString += `${state._declareOutput(normalOutput)} = ${normal.associatedVariableName};\n`; + state.compilationString += `#else\n`; + state.compilationString += `${state._declareOutput(normalOutput)} = vec3(0., 0., 0.);\n`; + state.compilationString += `#endif\n`; + state.compilationString += `#ifdef TANGENT\n`; + state.compilationString += `${state._declareOutput(tangentOutput)} = ${tangent.associatedVariableName};\n`; + state.compilationString += `#else\n`; + state.compilationString += `${state._declareOutput(tangentOutput)} = vec4(0., 0., 0., 0.);\n`; + state.compilationString += `#endif\n`; + state.compilationString += `#ifdef UV1\n`; + state.compilationString += `${state._declareOutput(uvOutput)} = ${uv.associatedVariableName};\n`; + state.compilationString += `#else\n`; + state.compilationString += `${state._declareOutput(uvOutput)} = vec2(0., 0.);\n`; + state.compilationString += `#endif\n`; + state.compilationString += `#ifdef UV2\n`; + state.compilationString += `${state._declareOutput(uv2Output)} = ${uv2.associatedVariableName};\n`; + state.compilationString += `#else\n`; + state.compilationString += `${state._declareOutput(uv2Output)} = vec2(0., 0.);\n`; + state.compilationString += `#endif\n`; + state.compilationString += `#ifdef VERTEXCOLOR_NME\n`; + state.compilationString += `${state._declareOutput(colorOutput)} = ${color.associatedVariableName};\n`; + state.compilationString += `#else\n`; + state.compilationString += `${state._declareOutput(colorOutput)} = vec4(0., 0., 0., 0.);\n`; + state.compilationString += `#endif\n`; + // Repeatable content + this._repeatableContentAnchor = state._repeatableContentAnchor; + state.compilationString += this._repeatableContentAnchor; + return this; + } +} +RegisterClass("BABYLON.MorphTargetsBlock", MorphTargetsBlock); + +/** + * Block used to get data information from a light + */ +class LightInformationBlock extends NodeMaterialBlock { + /** + * Creates a new LightInformationBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Vertex); + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); + this.registerOutput("direction", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerOutput("color", NodeMaterialBlockConnectionPointTypes.Color3); + this.registerOutput("intensity", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("shadowBias", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("shadowNormalBias", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("shadowDepthScale", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("shadowDepthRange", NodeMaterialBlockConnectionPointTypes.Vector2); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "LightInformationBlock"; + } + /** + * Gets the world position input component + */ + get worldPosition() { + return this._inputs[0]; + } + /** + * Gets the direction output component + */ + get direction() { + return this._outputs[0]; + } + /** + * Gets the direction output component + */ + get color() { + return this._outputs[1]; + } + /** + * Gets the direction output component + */ + get intensity() { + return this._outputs[2]; + } + /** + * Gets the shadow bias output component + */ + get shadowBias() { + return this._outputs[3]; + } + /** + * Gets the shadow normal bias output component + */ + get shadowNormalBias() { + return this._outputs[4]; + } + /** + * Gets the shadow depth scale component + */ + get shadowDepthScale() { + return this._outputs[5]; + } + /** + * Gets the shadow depth range component + */ + get shadowDepthRange() { + return this._outputs[6]; + } + bind(effect, nodeMaterial, mesh) { + if (!mesh) { + return; + } + if (this.light && this.light.isDisposed()) { + this.light = null; + } + let light = this.light; + const scene = nodeMaterial.getScene(); + if (!light && scene.lights.length) { + light = this.light = scene.lights[0]; + this._forcePrepareDefines = true; + } + if (!light || !light.isEnabled) { + effect.setFloat3(this._lightDataUniformName, 0, 0, 0); + effect.setFloat4(this._lightColorUniformName, 0, 0, 0, 0); + return; + } + light.transferToNodeMaterialEffect(effect, this._lightDataUniformName); + effect.setColor4(this._lightColorUniformName, light.diffuse, light.intensity); + const generator = light.getShadowGenerator(); + if (this.shadowBias.hasEndpoints || this.shadowNormalBias.hasEndpoints || this.shadowDepthScale.hasEndpoints) { + if (generator) { + effect.setFloat3(this._lightShadowUniformName, generator.bias, generator.normalBias, generator.depthScale); + } + else { + effect.setFloat3(this._lightShadowUniformName, 0, 0, 0); + } + } + if (this.shadowDepthRange) { + if (generator && scene.activeCamera) { + const shadowLight = light; + effect.setFloat2(this._lightShadowExtraUniformName, shadowLight.getDepthMinZ(scene.activeCamera), shadowLight.getDepthMinZ(scene.activeCamera) + shadowLight.getDepthMaxZ(scene.activeCamera)); + } + else { + effect.setFloat2(this._lightShadowExtraUniformName, 0, 0); + } + } + } + prepareDefines(mesh, nodeMaterial, defines) { + if (!defines._areLightsDirty && !this._forcePrepareDefines) { + return; + } + this._forcePrepareDefines = false; + const light = this.light; + defines.setValue(this._lightTypeDefineName, light && light instanceof PointLight ? true : false, true); + } + _buildBlock(state) { + super._buildBlock(state); + state.sharedData.bindableBlocks.push(this); + state.sharedData.blocksWithDefines.push(this); + const direction = this.direction; + const color = this.color; + const intensity = this.intensity; + const shadowBias = this.shadowBias; + const shadowNormalBias = this.shadowNormalBias; + const shadowDepthScale = this.shadowDepthScale; + const shadowDepthRange = this.shadowDepthRange; + this._lightDataUniformName = state._getFreeVariableName("lightData"); + this._lightColorUniformName = state._getFreeVariableName("lightColor"); + this._lightShadowUniformName = state._getFreeVariableName("shadowData"); + this._lightShadowExtraUniformName = state._getFreeVariableName("shadowExtraData"); + this._lightTypeDefineName = state._getFreeDefineName("LIGHTPOINTTYPE"); + const uniformAdd = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "uniforms." : ""; + state._emitUniformFromString(this._lightDataUniformName, NodeMaterialBlockConnectionPointTypes.Vector3); + state._emitUniformFromString(this._lightColorUniformName, NodeMaterialBlockConnectionPointTypes.Vector4); + state.compilationString += `#ifdef ${this._lightTypeDefineName}\n`; + state.compilationString += + state._declareOutput(direction) + ` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${uniformAdd}${this._lightDataUniformName});\n`; + state.compilationString += `#else\n`; + state.compilationString += state._declareOutput(direction) + ` = ${uniformAdd}${this._lightDataUniformName};\n`; + state.compilationString += `#endif\n`; + state.compilationString += state._declareOutput(color) + ` = ${uniformAdd}${this._lightColorUniformName}.rgb;\n`; + state.compilationString += state._declareOutput(intensity) + ` = ${uniformAdd}${this._lightColorUniformName}.a;\n`; + if (shadowBias.hasEndpoints || shadowNormalBias.hasEndpoints || shadowDepthScale.hasEndpoints) { + state._emitUniformFromString(this._lightShadowUniformName, NodeMaterialBlockConnectionPointTypes.Vector3); + if (shadowBias.hasEndpoints) { + state.compilationString += state._declareOutput(shadowBias) + ` = ${uniformAdd}${this._lightShadowUniformName}.x;\n`; + } + if (shadowNormalBias.hasEndpoints) { + state.compilationString += state._declareOutput(shadowNormalBias) + ` = ${uniformAdd}${this._lightShadowUniformName}.y;\n`; + } + if (shadowDepthScale.hasEndpoints) { + state.compilationString += state._declareOutput(shadowDepthScale) + ` = ${uniformAdd}${this._lightShadowUniformName}.z;\n`; + } + } + if (shadowDepthRange.hasEndpoints) { + state._emitUniformFromString(this._lightShadowExtraUniformName, NodeMaterialBlockConnectionPointTypes.Vector2); + state.compilationString += state._declareOutput(shadowDepthRange) + ` = ${this._lightShadowUniformName};\n`; + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + if (this.light) { + serializationObject.lightId = this.light.id; + } + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + if (serializationObject.lightId) { + this.light = scene.getLightById(serializationObject.lightId); + } + } +} +RegisterClass("BABYLON.LightInformationBlock", LightInformationBlock); + +/** + * Block used to add image processing support to fragment shader + */ +class ImageProcessingBlock extends NodeMaterialBlock { + /** + * Create a new ImageProcessingBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + /** + * Defines if the input should be converted to linear space (default: true) + */ + this.convertInputToLinearSpace = true; + this.registerInput("color", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color4); + this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | + NodeMaterialBlockConnectionPointTypes.Color4 | + NodeMaterialBlockConnectionPointTypes.Vector3 | + NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ImageProcessingBlock"; + } + /** + * Gets the color input component + */ + get color() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the rgb component + */ + get rgb() { + return this._outputs[1]; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("exposureLinear"); + state._excludeVariableName("contrast"); + state._excludeVariableName("vInverseScreenSize"); + state._excludeVariableName("vignetteSettings1"); + state._excludeVariableName("vignetteSettings2"); + state._excludeVariableName("vCameraColorCurveNegative"); + state._excludeVariableName("vCameraColorCurveNeutral"); + state._excludeVariableName("vCameraColorCurvePositive"); + state._excludeVariableName("txColorTransform"); + state._excludeVariableName("colorTransformSettings"); + state._excludeVariableName("ditherIntensity"); + this._initShaderSourceAsync(state.shaderLanguage); + } + async _initShaderSourceAsync(shaderLanguage) { + this._codeIsReady = false; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([ + Promise.resolve().then(() => helperFunctions$2), + Promise.resolve().then(() => imageProcessingDeclaration$2), + Promise.resolve().then(() => imageProcessingFunctions$2), + ]); + } + else { + await Promise.all([ + Promise.resolve().then(() => helperFunctions$1), + Promise.resolve().then(() => imageProcessingDeclaration$1), + Promise.resolve().then(() => imageProcessingFunctions$1), + ]); + } + this._codeIsReady = true; + this.onCodeIsReadyObservable.notifyObservers(this); + } + isReady(mesh, nodeMaterial, defines) { + if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) { + if (!nodeMaterial.imageProcessingConfiguration.isReady()) { + return false; + } + } + return true; + } + prepareDefines(mesh, nodeMaterial, defines) { + if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) { + nodeMaterial.imageProcessingConfiguration.prepareDefines(defines); + } + } + bind(effect, nodeMaterial, mesh) { + if (!mesh) { + return; + } + if (!nodeMaterial.imageProcessingConfiguration) { + return; + } + nodeMaterial.imageProcessingConfiguration.bind(effect); + } + _buildBlock(state) { + super._buildBlock(state); + // Register for defines + state.sharedData.blocksWithDefines.push(this); + // Register for blocking + state.sharedData.blockingBlocks.push(this); + // Register for binding + state.sharedData.bindableBlocks.push(this); + // Uniforms + state.uniforms.push("exposureLinear"); + state.uniforms.push("contrast"); + state.uniforms.push("vInverseScreenSize"); + state.uniforms.push("vignetteSettings1"); + state.uniforms.push("vignetteSettings2"); + state.uniforms.push("vCameraColorCurveNegative"); + state.uniforms.push("vCameraColorCurveNeutral"); + state.uniforms.push("vCameraColorCurvePositive"); + state.uniforms.push("txColorTransform"); + state.uniforms.push("colorTransformSettings"); + state.uniforms.push("ditherIntensity"); + // Emit code + const color = this.color; + const output = this._outputs[0]; + const comments = `//${this.name}`; + const overrideText = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "Vec3" : ""; + state._emitFunctionFromInclude("helperFunctions", comments); + state._emitFunctionFromInclude("imageProcessingDeclaration", comments); + state._emitFunctionFromInclude("imageProcessingFunctions", comments); + if (color.connectedPoint?.isConnected) { + if (color.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Color4 || color.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4) { + state.compilationString += `${state._declareOutput(output)} = ${color.associatedVariableName};\n`; + } + else { + state.compilationString += `${state._declareOutput(output)} = vec4${state.fSuffix}(${color.associatedVariableName}, 1.0);\n`; + } + state.compilationString += `#ifdef IMAGEPROCESSINGPOSTPROCESS\n`; + if (this.convertInputToLinearSpace) { + state.compilationString += `${output.associatedVariableName} = vec4${state.fSuffix}(toLinearSpace${overrideText}(${color.associatedVariableName}.rgb), ${color.associatedVariableName}.a);\n`; + } + state.compilationString += `#else\n`; + state.compilationString += `#ifdef IMAGEPROCESSING\n`; + if (this.convertInputToLinearSpace) { + state.compilationString += `${output.associatedVariableName} = vec4${state.fSuffix}(toLinearSpace${overrideText}(${color.associatedVariableName}.rgb), ${color.associatedVariableName}.a);\n`; + } + state.compilationString += `${output.associatedVariableName} = applyImageProcessing(${output.associatedVariableName});\n`; + state.compilationString += `#endif\n`; + state.compilationString += `#endif\n`; + if (this.rgb.hasEndpoints) { + state.compilationString += state._declareOutput(this.rgb) + ` = ${this.output.associatedVariableName}.xyz;\n`; + } + } + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.convertInputToLinearSpace = this.convertInputToLinearSpace; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.convertInputToLinearSpace = serializationObject.convertInputToLinearSpace ?? true; + } +} +__decorate([ + editableInPropertyPage("Convert input to linear space", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED") +], ImageProcessingBlock.prototype, "convertInputToLinearSpace", void 0); +RegisterClass("BABYLON.ImageProcessingBlock", ImageProcessingBlock); + +/** + * Block used to implement TBN matrix + */ +class TBNBlock extends NodeMaterialBlock { + /** + * Create a new TBNBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment, true); + this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect, false); + this.normal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerInput("tangent", NodeMaterialBlockConnectionPointTypes.Vector4, false); + this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false); + this.registerOutput("TBN", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("TBN", this, 1 /* NodeMaterialConnectionPointDirection.Output */, TBNBlock, "TBNBlock")); + this.registerOutput("row0", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("row1", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("row2", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "TBNBlock"; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("tbnNormal"); + state._excludeVariableName("tbnTangent"); + state._excludeVariableName("tbnBitangent"); + state._excludeVariableName("TBN"); + } + /** + * Gets the normal input component + */ + get normal() { + return this._inputs[0]; + } + /** + * Gets the tangent input component + */ + get tangent() { + return this._inputs[1]; + } + /** + * Gets the world matrix input component + */ + get world() { + return this._inputs[2]; + } + /** + * Gets the TBN output component + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + get TBN() { + return this._outputs[0]; + } + /** + * Gets the row0 of the output matrix + */ + get row0() { + return this._outputs[1]; + } + /** + * Gets the row1 of the output matrix + */ + get row1() { + return this._outputs[2]; + } + /** + * Gets the row2 of the output matrix + */ + get row2() { + return this._outputs[3]; + } + get target() { + return NodeMaterialBlockTargets.Fragment; + } + set target(value) { } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.world.isConnected) { + let worldInput = material.getInputBlockByPredicate((b) => b.isSystemValue && b.systemValue === NodeMaterialSystemValues.World && additionalFilteringInfo(b)); + if (!worldInput) { + worldInput = new InputBlock("world"); + worldInput.setAsSystemValue(NodeMaterialSystemValues.World); + } + worldInput.output.connectTo(this.world); + } + if (!this.normal.isConnected) { + let normalInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "normal" && additionalFilteringInfo(b)); + if (!normalInput) { + normalInput = new InputBlock("normal"); + normalInput.setAsAttribute("normal"); + } + normalInput.output.connectTo(this.normal); + } + if (!this.tangent.isConnected) { + let tangentInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "tangent" && b.type === NodeMaterialBlockConnectionPointTypes.Vector4 && additionalFilteringInfo(b)); + if (!tangentInput) { + tangentInput = new InputBlock("tangent"); + tangentInput.setAsAttribute("tangent"); + } + tangentInput.output.connectTo(this.tangent); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + const normal = this.normal; + const tangent = this.tangent; + let normalAvailable = normal.isConnected; + if (normal.connectInputBlock?.isAttribute && !mesh.isVerticesDataPresent(normal.connectInputBlock?.name)) { + normalAvailable = false; + } + let tangentAvailable = tangent.isConnected; + if (tangent.connectInputBlock?.isAttribute && !mesh.isVerticesDataPresent(tangent.connectInputBlock?.name)) { + tangentAvailable = false; + } + const useTBNBlock = normalAvailable && tangentAvailable; + defines.setValue("TBNBLOCK", useTBNBlock, true); + } + _buildBlock(state) { + super._buildBlock(state); + const normal = this.normal; + const tangent = this.tangent; + const world = this.world; + const TBN = this.TBN; + const row0 = this.row0; + const row1 = this.row1; + const row2 = this.row2; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + const mat3 = isWebGPU ? "mat3x3f" : "mat3"; + const fSuffix = isWebGPU ? "f" : ""; + // Fragment + if (state.target === NodeMaterialBlockTargets.Fragment) { + state.compilationString += ` + // ${this.name} + ${state._declareLocalVar("tbnNormal", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${normal.associatedVariableName}).xyz; + ${state._declareLocalVar("tbnTangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${tangent.associatedVariableName}.xyz); + ${state._declareLocalVar("tbnBitangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = cross(tbnNormal, tbnTangent) * ${tangent.associatedVariableName}.w; + ${isWebGPU ? "var" : "mat3"} ${TBN.associatedVariableName} = ${mat3}(${world.associatedVariableName}[0].xyz, ${world.associatedVariableName}[1].xyz, ${world.associatedVariableName}[2].xyz) * ${mat3}(tbnTangent, tbnBitangent, tbnNormal); + `; + if (row0.hasEndpoints) { + state.compilationString += + state._declareOutput(row0) + + ` = vec3${fSuffix}(${TBN.associatedVariableName}[0][0], ${TBN.associatedVariableName}[0][1], ${TBN.associatedVariableName}[0][2]);\n`; + } + if (row1.hasEndpoints) { + state.compilationString += + state._declareOutput(row1) + + ` = vec3${fSuffix}(${TBN.associatedVariableName}[1[0], ${TBN.associatedVariableName}[1][1], ${TBN.associatedVariableName}[1][2]);\n`; + } + if (row2.hasEndpoints) { + state.compilationString += + state._declareOutput(row2) + + ` = vec3${fSuffix}(${TBN.associatedVariableName}[2][0], ${TBN.associatedVariableName}[2][1], ${TBN.associatedVariableName}[2][2]);\n`; + } + state.sharedData.blocksWithDefines.push(this); + } + return this; + } +} +RegisterClass("BABYLON.TBNBlock", TBNBlock); + +/** + * Block used to perturb normals based on a normal map + */ +class PerturbNormalBlock extends NodeMaterialBlock { + /** + * Create a new PerturbNormalBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this._tangentSpaceParameterName = ""; + this._tangentCorrectionFactorName = ""; + this._worldMatrixName = ""; + /** Gets or sets a boolean indicating that normal should be inverted on X axis */ + this.invertX = false; + /** Gets or sets a boolean indicating that normal should be inverted on Y axis */ + this.invertY = false; + /** Gets or sets a boolean indicating that parallax occlusion should be enabled */ + this.useParallaxOcclusion = false; + /** Gets or sets a boolean indicating that sampling mode is in Object space */ + this.useObjectSpaceNormalMap = false; + this._isUnique = true; + // Vertex + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false); + this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false); + this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, true); + this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, false); + this.registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes.Color3, false); + this.registerInput("strength", NodeMaterialBlockConnectionPointTypes.Float, false); + this.registerInput("viewDirection", NodeMaterialBlockConnectionPointTypes.Vector3, true); + this.registerInput("parallaxScale", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("parallaxHeight", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("TBN", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("TBN", this, 0 /* NodeMaterialConnectionPointDirection.Input */, TBNBlock, "TBNBlock")); + this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, true); + // Fragment + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("uvOffset", NodeMaterialBlockConnectionPointTypes.Vector2); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "PerturbNormalBlock"; + } + /** + * Gets the world position input component + */ + get worldPosition() { + return this._inputs[0]; + } + /** + * Gets the world normal input component + */ + get worldNormal() { + return this._inputs[1]; + } + /** + * Gets the world tangent input component + */ + get worldTangent() { + return this._inputs[2]; + } + /** + * Gets the uv input component + */ + get uv() { + return this._inputs[3]; + } + /** + * Gets the normal map color input component + */ + get normalMapColor() { + return this._inputs[4]; + } + /** + * Gets the strength input component + */ + get strength() { + return this._inputs[5]; + } + /** + * Gets the view direction input component + */ + get viewDirection() { + return this._inputs[6]; + } + /** + * Gets the parallax scale input component + */ + get parallaxScale() { + return this._inputs[7]; + } + /** + * Gets the parallax height input component + */ + get parallaxHeight() { + return this._inputs[8]; + } + /** + * Gets the TBN input component + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + get TBN() { + return this._inputs[9]; + } + /** + * Gets the World input component + */ + get world() { + return this._inputs[10]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the uv offset output component + */ + get uvOffset() { + return this._outputs[1]; + } + initialize(state) { + this._initShaderSourceAsync(state.shaderLanguage); + } + async _initShaderSourceAsync(shaderLanguage) { + this._codeIsReady = false; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([ + Promise.resolve().then(() => bumpFragment$2), + Promise.resolve().then(() => bumpFragmentMainFunctions$2), + Promise.resolve().then(() => bumpFragmentFunctions$2), + ]); + } + else { + await Promise.all([ + Promise.resolve().then(() => bumpFragment$1), + Promise.resolve().then(() => bumpFragmentMainFunctions$1), + Promise.resolve().then(() => bumpFragmentFunctions$1), + ]); + } + this._codeIsReady = true; + this.onCodeIsReadyObservable.notifyObservers(this); + } + prepareDefines(mesh, nodeMaterial, defines) { + const normalSamplerName = this.normalMapColor.connectedPoint._ownerBlock.samplerName; + const useParallax = this.viewDirection.isConnected && ((this.useParallaxOcclusion && normalSamplerName) || (!this.useParallaxOcclusion && this.parallaxHeight.isConnected)); + defines.setValue("BUMP", true); + defines.setValue("PARALLAX", useParallax, true); + defines.setValue("PARALLAX_RHS", nodeMaterial.getScene().useRightHandedSystem, true); + defines.setValue("PARALLAXOCCLUSION", this.useParallaxOcclusion, true); + defines.setValue("OBJECTSPACE_NORMALMAP", this.useObjectSpaceNormalMap, true); + } + bind(effect, nodeMaterial, mesh) { + if (nodeMaterial.getScene()._mirroredCameraPosition) { + effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? 1.0 : -1, this.invertY ? 1.0 : -1); + } + else { + effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? -1 : 1.0, this.invertY ? -1 : 1.0); + } + if (mesh) { + effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1); + if (this.useObjectSpaceNormalMap && !this.world.isConnected) { + // World default to the mesh world matrix + effect.setMatrix(this._worldMatrixName, mesh.getWorldMatrix()); + } + } + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.uv.isConnected) { + let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv" && additionalFilteringInfo(b)); + if (!uvInput) { + uvInput = new InputBlock("uv"); + uvInput.setAsAttribute(); + } + uvInput.output.connectTo(this.uv); + } + if (!this.strength.isConnected) { + const strengthInput = new InputBlock("strength"); + strengthInput.value = 1.0; + strengthInput.output.connectTo(this.strength); + } + } + _buildBlock(state) { + super._buildBlock(state); + const comments = `//${this.name}`; + const uv = this.uv; + const worldPosition = this.worldPosition; + const worldNormal = this.worldNormal; + const worldTangent = this.worldTangent; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + const mat3 = isWebGPU ? "mat3x3f" : "mat3"; + const fSuffix = isWebGPU ? "f" : ""; + const uniformPrefix = isWebGPU ? "uniforms." : ""; + const fragmentInputsPrefix = isWebGPU ? "fragmentInputs." : ""; + state.sharedData.blocksWithDefines.push(this); + state.sharedData.bindableBlocks.push(this); + this._tangentSpaceParameterName = state._getFreeDefineName("tangentSpaceParameter"); + state._emitUniformFromString(this._tangentSpaceParameterName, NodeMaterialBlockConnectionPointTypes.Vector2); + this._tangentCorrectionFactorName = state._getFreeDefineName("tangentCorrectionFactor"); + state._emitUniformFromString(this._tangentCorrectionFactorName, NodeMaterialBlockConnectionPointTypes.Float); + this._worldMatrixName = state._getFreeDefineName("perturbNormalWorldMatrix"); + state._emitUniformFromString(this._worldMatrixName, NodeMaterialBlockConnectionPointTypes.Matrix); + let normalSamplerName = null; + if (this.normalMapColor.connectedPoint) { + normalSamplerName = this.normalMapColor.connectedPoint._ownerBlock.samplerName; + } + const useParallax = this.viewDirection.isConnected && ((this.useParallaxOcclusion && normalSamplerName) || (!this.useParallaxOcclusion && this.parallaxHeight.isConnected)); + const replaceForParallaxInfos = !this.parallaxScale.isConnectedToInputBlock + ? "0.05" + : this.parallaxScale.connectInputBlock.isConstant + ? state._emitFloat(this.parallaxScale.connectInputBlock.value) + : this.parallaxScale.associatedVariableName; + const replaceForBumpInfos = this.strength.isConnectedToInputBlock && this.strength.connectInputBlock.isConstant + ? `\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${state._emitFloat(this.strength.connectInputBlock.value)}` + : `\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${this.strength.associatedVariableName}`; + if (!isWebGPU) { + state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); + } + const tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" }; + const tbnVarying = { search: /varying mat3 vTBN;/g, replace: "" }; + const normalMatrixReplaceString = { search: isWebGPU ? /uniform normalMatrix: mat4x4f;/g : /uniform mat4 normalMatrix;/g, replace: "" }; + const TBN = this.TBN; + if (TBN.isConnected) { + state.compilationString += ` + #ifdef TBNBLOCK + ${isWebGPU ? "var" : "mat3"} vTBN = ${TBN.associatedVariableName}; + #endif + `; + } + else if (worldTangent.isConnected) { + state.compilationString += `${state._declareLocalVar("tbnNormal", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldNormal.associatedVariableName}.xyz);\n`; + state.compilationString += `${state._declareLocalVar("tbnTangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldTangent.associatedVariableName}.xyz);\n`; + state.compilationString += `${state._declareLocalVar("tbnBitangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = cross(tbnNormal, tbnTangent) * ${uniformPrefix}${this._tangentCorrectionFactorName};\n`; + state.compilationString += `${isWebGPU ? "var" : "mat3"} vTBN = ${mat3}(tbnTangent, tbnBitangent, tbnNormal);\n`; + } + let replaceStrings = [tangentReplaceString, tbnVarying, normalMatrixReplaceString]; + if (isWebGPU) { + replaceStrings.push({ search: /varying vTBN0: vec3f;/g, replace: "" }); + replaceStrings.push({ search: /varying vTBN1: vec3f;/g, replace: "" }); + replaceStrings.push({ search: /varying vTBN2: vec3f;/g, replace: "" }); + } + state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, { + replaceStrings: replaceStrings, + }); + const replaceString0 = isWebGPU + ? "fn parallaxOcclusion(vViewDirCoT: vec3f, vNormalCoT: vec3f, texCoord: vec2f, parallaxScale:f32, bumpSampler: texture_2d, bumpSamplerSampler: sampler)" + : "#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"; + const searchExp0 = isWebGPU + ? /fn parallaxOcclusion\(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32\)/g + : /vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g; + const replaceString1 = isWebGPU + ? "fn parallaxOffset(viewDir: vec3f, heightScale: f32, height_: f32)" + : "vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"; + const searchExp1 = isWebGPU ? /fn parallaxOffset\(viewDir: vec3f,heightScale: f32\)/g : /vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g; + state._emitFunctionFromInclude("bumpFragmentFunctions", comments, { + replaceStrings: [ + { search: /#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g, replace: "" }, + { search: /uniform sampler2D bumpSampler;/g, replace: "" }, + { + search: searchExp0, + replace: replaceString0, + }, + { search: searchExp1, replace: replaceString1 }, + { search: /texture.+?bumpSampler,.*?vBumpUV\)\.w/g, replace: "height_" }, + ], + }); + const normalRead = isWebGPU ? `textureSample(${normalSamplerName}, ${normalSamplerName + `Sampler`}` : `texture2D(${normalSamplerName}`; + const uvForPerturbNormal = !useParallax || !normalSamplerName ? this.normalMapColor.associatedVariableName : `${normalRead}, ${uv.associatedVariableName} + uvOffset).xyz`; + const tempOutput = state._getFreeVariableName("tempOutput"); + state.compilationString += state._declareLocalVar(tempOutput, NodeMaterialBlockConnectionPointTypes.Vector3) + ` = vec3${fSuffix}(0.);\n`; + replaceStrings = [ + { search: new RegExp(`texture.+?bumpSampler${isWebGPU ? "Sampler,fragmentInputs." : ","}vBumpUV\\)`, "g"), replace: `${uvForPerturbNormal}` }, + { + search: /#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g, + replace: `${state._declareLocalVar("normalMatrix", NodeMaterialBlockConnectionPointTypes.Matrix)} = toNormalMatrix(${this.world.isConnected ? this.world.associatedVariableName : uniformPrefix + this._worldMatrixName});`, + }, + { + search: new RegExp(`perturbNormal\\(TBN,texture.+?bumpSampler${isWebGPU ? "Sampler,fragmentInputs." : ","}vBumpUV\\+uvOffset\\).xyz,${uniformPrefix}vBumpInfos.y\\)`, "g"), + replace: `perturbNormal(TBN, ${uvForPerturbNormal}, ${uniformPrefix}vBumpInfos.y)`, + }, + { + search: /parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,(fragmentInputs\.)?vBumpUV,(uniforms\.)?vBumpInfos.z\)/g, + replace: `parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), ${fragmentInputsPrefix}vBumpUV, ${uniformPrefix}vBumpInfos.z, ${isWebGPU + ? useParallax && this.useParallaxOcclusion + ? `${normalSamplerName}, ${normalSamplerName + `Sampler`}` + : "bump, bumpSampler" + : useParallax && this.useParallaxOcclusion + ? normalSamplerName + : "bumpSampler"})`, + }, + { + search: /parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g, + replace: `parallaxOffset(invTBN * viewDirectionW, ${uniformPrefix}vBumpInfos.z, ${useParallax ? this.parallaxHeight.associatedVariableName : "0."})`, + }, + { search: isWebGPU ? /uniforms.vBumpInfos.y/g : /vBumpInfos.y/g, replace: replaceForBumpInfos }, + { search: isWebGPU ? /uniforms.vBumpInfos.z/g : /vBumpInfos.z/g, replace: replaceForParallaxInfos }, + { search: /normalW=/g, replace: tempOutput + " = " }, + isWebGPU + ? { + search: /mat3x3f\(uniforms\.normalMatrix\[0\].xyz,uniforms\.normalMatrix\[1\]\.xyz,uniforms\.normalMatrix\[2\].xyz\)\*normalW/g, + replace: `${mat3}(normalMatrix[0].xyz, normalMatrix[1].xyz, normalMatrix[2].xyz) * ` + tempOutput, + } + : { + search: /mat3\(normalMatrix\)\*normalW/g, + replace: `${mat3}(normalMatrix) * ` + tempOutput, + }, + { search: /normalW/g, replace: worldNormal.associatedVariableName + ".xyz" }, + { search: /viewDirectionW/g, replace: useParallax ? this.viewDirection.associatedVariableName : `vec3${fSuffix}(0.)` }, + tangentReplaceString, + ]; + if (isWebGPU) { + replaceStrings.push({ search: /fragmentInputs.vBumpUV/g, replace: uv.associatedVariableName }); + replaceStrings.push({ search: /input.vPositionW/g, replace: worldPosition.associatedVariableName + ".xyz" }); + replaceStrings.push({ search: /uniforms.vTangentSpaceParams/g, replace: uniformPrefix + this._tangentSpaceParameterName }); + replaceStrings.push({ search: /var TBN: mat3x3f=mat3x3\(input.vTBN0,input.vTBN1,input.vTBN2\);/g, replace: `var TBN = vTBN;` }); + } + else { + replaceStrings.push({ search: /vBumpUV/g, replace: uv.associatedVariableName }); + replaceStrings.push({ search: /vPositionW/g, replace: worldPosition.associatedVariableName + ".xyz" }); + replaceStrings.push({ search: /vTangentSpaceParams/g, replace: uniformPrefix + this._tangentSpaceParameterName }); + } + state.compilationString += state._emitCodeFromInclude("bumpFragment", comments, { + replaceStrings: replaceStrings, + }); + state.compilationString += state._declareOutput(this.output) + ` = vec4${fSuffix}(${tempOutput}, 0.);\n`; + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.invertX = ${this.invertX};\n`; + codeString += `${this._codeVariableName}.invertY = ${this.invertY};\n`; + codeString += `${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\n`; + codeString += `${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.invertX = this.invertX; + serializationObject.invertY = this.invertY; + serializationObject.useParallaxOcclusion = this.useParallaxOcclusion; + serializationObject.useObjectSpaceNormalMap = this.useObjectSpaceNormalMap; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.invertX = serializationObject.invertX; + this.invertY = serializationObject.invertY; + this.useParallaxOcclusion = !!serializationObject.useParallaxOcclusion; + this.useObjectSpaceNormalMap = !!serializationObject.useObjectSpaceNormalMap; + } +} +__decorate([ + editableInPropertyPage("Invert X axis", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES", { embedded: true, notifiers: { update: true } }) +], PerturbNormalBlock.prototype, "invertX", void 0); +__decorate([ + editableInPropertyPage("Invert Y axis", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES", { embedded: true, notifiers: { update: true } }) +], PerturbNormalBlock.prototype, "invertY", void 0); +__decorate([ + editableInPropertyPage("Use parallax occlusion", 0 /* PropertyTypeForEdition.Boolean */, undefined, { embedded: true }) +], PerturbNormalBlock.prototype, "useParallaxOcclusion", void 0); +__decorate([ + editableInPropertyPage("Object Space Mode", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES", { embedded: true, notifiers: { update: true } }) +], PerturbNormalBlock.prototype, "useObjectSpaceNormalMap", void 0); +RegisterClass("BABYLON.PerturbNormalBlock", PerturbNormalBlock); + +/** + * Block used to discard a pixel if a value is smaller than a cutoff + */ +class DiscardBlock extends NodeMaterialBlock { + /** + * Create a new DiscardBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment, true); + this.registerInput("value", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("cutoff", NodeMaterialBlockConnectionPointTypes.Float, true); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "DiscardBlock"; + } + /** + * Gets the color input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the cutoff input component + */ + get cutoff() { + return this._inputs[1]; + } + _buildBlock(state) { + super._buildBlock(state); + state.sharedData.hints.needAlphaTesting = true; + if (!this.cutoff.isConnected || !this.value.isConnected) { + return; + } + state.compilationString += `if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) { discard; }\n`; + return this; + } +} +RegisterClass("BABYLON.DiscardBlock", DiscardBlock); + +/** + * Block used to test if the fragment shader is front facing + */ +class FrontFacingBlock extends NodeMaterialBlock { + /** + * Creates a new FrontFacingBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "FrontFacingBlock"; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Vertex) { + // eslint-disable-next-line no-throw-literal + throw "FrontFacingBlock must only be used in a fragment shader"; + } + const output = this._outputs[0]; + state.compilationString += + state._declareOutput(output) + + ` = ${state._generateTernary("1.0", "0.0", state.shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? "gl_FrontFacing" : "fragmentInputs.frontFacing")};\n`; + return this; + } +} +RegisterClass("BABYLON.FrontFacingBlock", FrontFacingBlock); + +/** + * Block used to get the derivative value on x and y of a given input + */ +class DerivativeBlock extends NodeMaterialBlock { + /** + * Create a new DerivativeBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect, false); + this.registerOutput("dx", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this.registerOutput("dy", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._outputs[1]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "DerivativeBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the derivative output on x + */ + get dx() { + return this._outputs[0]; + } + /** + * Gets the derivative output on y + */ + get dy() { + return this._outputs[1]; + } + _buildBlock(state) { + super._buildBlock(state); + const dx = this._outputs[0]; + const dy = this._outputs[1]; + state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); + let dpdx = "dFdx"; + let dpdy = "dFdy"; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + dpdx = "dpdx"; + dpdy = "dpdy"; + } + if (dx.hasEndpoints) { + state.compilationString += state._declareOutput(dx) + ` = ${dpdx}(${this.input.associatedVariableName});\n`; + } + if (dy.hasEndpoints) { + state.compilationString += state._declareOutput(dy) + ` = ${dpdy}(${this.input.associatedVariableName});\n`; + } + return this; + } +} +RegisterClass("BABYLON.DerivativeBlock", DerivativeBlock); + +/** + * Block used to make gl_FragCoord available + */ +class FragCoordBlock extends NodeMaterialBlock { + /** + * Creates a new FragCoordBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment); + this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockTargets.Fragment); + this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + this.registerOutput("z", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + this.registerOutput("w", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "FragCoordBlock"; + } + /** + * Gets the xy component + */ + get xy() { + return this._outputs[0]; + } + /** + * Gets the xyz component + */ + get xyz() { + return this._outputs[1]; + } + /** + * Gets the xyzw component + */ + get xyzw() { + return this._outputs[2]; + } + /** + * Gets the x component + */ + get x() { + return this._outputs[3]; + } + /** + * Gets the y component + */ + get y() { + return this._outputs[4]; + } + /** + * Gets the z component + */ + get z() { + return this._outputs[5]; + } + /** + * Gets the w component + */ + get output() { + return this._outputs[6]; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + writeOutputs(state) { + let code = ""; + const coord = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "fragmentInputs.position" : "gl_FragCoord"; + for (const output of this._outputs) { + if (output.hasEndpoints) { + code += `${state._declareOutput(output)} = ${coord}.${output.name};\n`; + } + } + return code; + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Vertex) { + // eslint-disable-next-line no-throw-literal + throw "FragCoordBlock must only be used in a fragment shader"; + } + state.compilationString += this.writeOutputs(state); + return this; + } +} +RegisterClass("BABYLON.FragCoordBlock", FragCoordBlock); + +/** + * Block used to get the screen sizes + */ +class ScreenSizeBlock extends NodeMaterialBlock { + /** + * Creates a new ScreenSizeBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment); + this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ScreenSizeBlock"; + } + /** + * Gets the xy component + */ + get xy() { + return this._outputs[0]; + } + /** + * Gets the x component + */ + get x() { + return this._outputs[1]; + } + /** + * Gets the y component + */ + get y() { + return this._outputs[2]; + } + bind(effect) { + const engine = this._scene.getEngine(); + effect.setFloat2(this._varName, engine.getRenderWidth(), engine.getRenderHeight()); + } + // eslint-disable-next-line @typescript-eslint/naming-convention + writeOutputs(state, varName) { + let code = ""; + for (const output of this._outputs) { + if (output.hasEndpoints) { + code += `${state._declareOutput(output)} = ${varName}.${output.name};\n`; + } + } + return code; + } + _buildBlock(state) { + super._buildBlock(state); + this._scene = state.sharedData.scene; + if (state.target === NodeMaterialBlockTargets.Vertex) { + // eslint-disable-next-line no-throw-literal + throw "ScreenSizeBlock must only be used in a fragment shader"; + } + state.sharedData.bindableBlocks.push(this); + this._varName = state._getFreeVariableName("screenSize"); + state._emitUniformFromString(this._varName, NodeMaterialBlockConnectionPointTypes.Vector2); + const prefix = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "uniforms." : ""; + state.compilationString += this.writeOutputs(state, prefix + this._varName); + return this; + } +} +RegisterClass("BABYLON.ScreenSizeBlock", ScreenSizeBlock); + +/** + * Block used to transform a vector3 or a vector4 into screen space + */ +class ScreenSpaceBlock extends NodeMaterialBlock { + /** + * Creates a new ScreenSpaceBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this.registerInput("vector", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("worldViewProjection", NodeMaterialBlockConnectionPointTypes.Matrix); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float); + this.inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ScreenSpaceBlock"; + } + /** + * Gets the vector input + */ + get vector() { + return this._inputs[0]; + } + /** + * Gets the worldViewProjection transform input + */ + get worldViewProjection() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the x output component + */ + get x() { + return this._outputs[1]; + } + /** + * Gets the y output component + */ + get y() { + return this._outputs[2]; + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.worldViewProjection.isConnected) { + let worldViewProjectionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.WorldViewProjection && additionalFilteringInfo(b)); + if (!worldViewProjectionInput) { + worldViewProjectionInput = new InputBlock("worldViewProjection"); + worldViewProjectionInput.setAsSystemValue(NodeMaterialSystemValues.WorldViewProjection); + } + worldViewProjectionInput.output.connectTo(this.worldViewProjection); + } + } + _buildBlock(state) { + super._buildBlock(state); + const vector = this.vector; + const worldViewProjection = this.worldViewProjection; + if (!vector.connectedPoint) { + return; + } + const worldViewProjectionName = worldViewProjection.associatedVariableName; + const tempVariableName = state._getFreeVariableName("screenSpaceTemp"); + switch (vector.connectedPoint.type) { + case NodeMaterialBlockConnectionPointTypes.Vector3: + state.compilationString += `${state._declareLocalVar(tempVariableName, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${worldViewProjectionName} * vec4${state.fSuffix}(${vector.associatedVariableName}, 1.0);\n`; + break; + case NodeMaterialBlockConnectionPointTypes.Vector4: + state.compilationString += `${state._declareLocalVar(tempVariableName, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${worldViewProjectionName} * ${vector.associatedVariableName};\n`; + break; + } + state.compilationString += `${tempVariableName} = vec4${state.fSuffix}(${tempVariableName}.xy / ${tempVariableName}.w, ${tempVariableName}.zw);`; + state.compilationString += `${tempVariableName} = vec4${state.fSuffix}(${tempVariableName}.xy * 0.5 + vec2${state.fSuffix}(0.5, 0.5), ${tempVariableName}.zw);`; + if (this.output.hasEndpoints) { + state.compilationString += state._declareOutput(this.output) + ` = ${tempVariableName}.xy;\n`; + } + if (this.x.hasEndpoints) { + state.compilationString += state._declareOutput(this.x) + ` = ${tempVariableName}.x;\n`; + } + if (this.y.hasEndpoints) { + state.compilationString += state._declareOutput(this.y) + ` = ${tempVariableName}.y;\n`; + } + return this; + } +} +RegisterClass("BABYLON.ScreenSpaceBlock", ScreenSpaceBlock); + +/** + * Block used to generate a twirl + */ +class TwirlBlock extends NodeMaterialBlock { + /** + * Creates a new TwirlBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerInput("strength", NodeMaterialBlockConnectionPointTypes.Float); + this.registerInput("center", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerInput("offset", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "TwirlBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the strength component + */ + get strength() { + return this._inputs[1]; + } + /** + * Gets the center component + */ + get center() { + return this._inputs[2]; + } + /** + * Gets the offset component + */ + get offset() { + return this._inputs[3]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the x output component + */ + get x() { + return this._outputs[1]; + } + /** + * Gets the y output component + */ + get y() { + return this._outputs[2]; + } + autoConfigure() { + if (!this.center.isConnected) { + const centerInput = new InputBlock("center"); + centerInput.value = new Vector2(0.5, 0.5); + centerInput.output.connectTo(this.center); + } + if (!this.strength.isConnected) { + const strengthInput = new InputBlock("strength"); + strengthInput.value = 1.0; + strengthInput.output.connectTo(this.strength); + } + if (!this.offset.isConnected) { + const offsetInput = new InputBlock("offset"); + offsetInput.value = new Vector2(0, 0); + offsetInput.output.connectTo(this.offset); + } + } + _buildBlock(state) { + super._buildBlock(state); + const tempDelta = state._getFreeVariableName("delta"); + const tempAngle = state._getFreeVariableName("angle"); + const tempX = state._getFreeVariableName("x"); + const tempY = state._getFreeVariableName("y"); + const tempResult = state._getFreeVariableName("result"); + state.compilationString += ` + ${state._declareLocalVar(tempDelta, NodeMaterialBlockConnectionPointTypes.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; + ${state._declareLocalVar(tempAngle, NodeMaterialBlockConnectionPointTypes.Float)} = ${this.strength.associatedVariableName} * length(${tempDelta}); + ${state._declareLocalVar(tempX, NodeMaterialBlockConnectionPointTypes.Float)} = cos(${tempAngle}) * ${tempDelta}.x - sin(${tempAngle}) * ${tempDelta}.y; + ${state._declareLocalVar(tempY, NodeMaterialBlockConnectionPointTypes.Float)} = sin(${tempAngle}) * ${tempDelta}.x + cos(${tempAngle}) * ${tempDelta}.y; + ${state._declareLocalVar(tempResult, NodeMaterialBlockConnectionPointTypes.Vector2)} = vec2(${tempX} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${tempY} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); + `; + if (this.output.hasEndpoints) { + state.compilationString += state._declareOutput(this.output) + ` = ${tempResult};\n`; + } + if (this.x.hasEndpoints) { + state.compilationString += state._declareOutput(this.x) + ` = ${tempResult}.x;\n`; + } + if (this.y.hasEndpoints) { + state.compilationString += state._declareOutput(this.y) + ` = ${tempResult}.y;\n`; + } + return this; + } +} +RegisterClass("BABYLON.TwirlBlock", TwirlBlock); + +/** + * Block used to convert a height vector to a normal + */ +class HeightToNormalBlock extends NodeMaterialBlock { + /** + * Creates a new HeightToNormalBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + /** + * Defines if the output should be generated in world or tangent space. + * Note that in tangent space the result is also scaled by 0.5 and offsetted by 0.5 so that it can directly be used as a PerturbNormal.normalMapColor input + */ + this.generateInWorldSpace = false; + /** + * Defines that the worldNormal input will be normalized by the HeightToNormal block before being used + */ + this.automaticNormalizationNormal = true; + /** + * Defines that the worldTangent input will be normalized by the HeightToNormal block before being used + */ + this.automaticNormalizationTangent = true; + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Float); + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3); + this._inputs[3].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "HeightToNormalBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the position component + */ + get worldPosition() { + return this._inputs[1]; + } + /** + * Gets the normal component + */ + get worldNormal() { + return this._inputs[2]; + } + /** + * Gets the tangent component + */ + get worldTangent() { + return this._inputs[3]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the xyz component + */ + get xyz() { + return this._outputs[1]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + const fPrefix = state.fSuffix; + if (!this.generateInWorldSpace && !this.worldTangent.isConnected) { + Logger.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`); + } + const startCode = this.generateInWorldSpace + ? "" + : ` + vec3 biTangent = cross(norm, tgt); + mat3 TBN = mat3(tgt, biTangent, norm); + `; + const endCode = this.generateInWorldSpace + ? "" + : ` + result = TBN * result; + result = result * vec3(0.5) + vec3(0.5); + `; + let heightToNormal = ` + vec4 heightToNormal(float height, vec3 position, vec3 tangent, vec3 normal) { + vec3 tgt = ${this.automaticNormalizationTangent ? "normalize(tangent);" : "tangent;"} + vec3 norm = ${this.automaticNormalizationNormal ? "normalize(normal);" : "normal;"} + ${startCode} + vec3 worlddX = dFdx(position); + vec3 worlddY = dFdy(position); + vec3 crossX = cross(norm, worlddX); + vec3 crossY = cross(worlddY, norm); + float d = abs(dot(crossY, worlddX)); + vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); + inToNormal.y *= -1.0; + vec3 result = normalize((d * norm) - inToNormal); + ${endCode} + return vec4(result, 0.); + }`; + if (isWebGPU) { + heightToNormal = state._babylonSLtoWGSL(heightToNormal); + } + else { + state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); + } + state._emitFunction("heightToNormal", heightToNormal, "// heightToNormal"); + state.compilationString += + state._declareOutput(output) + + ` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected ? this.worldTangent.associatedVariableName : `vec3${fPrefix}(0.)`}.xyz, ${this.worldNormal.associatedVariableName});\n`; + if (this.xyz.hasEndpoints) { + state.compilationString += state._declareOutput(this.xyz) + ` = ${this.output.associatedVariableName}.xyz;\n`; + } + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\n`; + codeString += `${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\n`; + codeString += `${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.generateInWorldSpace = this.generateInWorldSpace; + serializationObject.automaticNormalizationNormal = this.automaticNormalizationNormal; + serializationObject.automaticNormalizationTangent = this.automaticNormalizationTangent; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.generateInWorldSpace = serializationObject.generateInWorldSpace; + this.automaticNormalizationNormal = serializationObject.automaticNormalizationNormal; + this.automaticNormalizationTangent = serializationObject.automaticNormalizationTangent; + } +} +__decorate([ + editableInPropertyPage("Generate in world space instead of tangent space", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES", { notifiers: { update: true } }) +], HeightToNormalBlock.prototype, "generateInWorldSpace", void 0); +__decorate([ + editableInPropertyPage("Force normalization for the worldNormal input", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES", { notifiers: { update: true } }) +], HeightToNormalBlock.prototype, "automaticNormalizationNormal", void 0); +__decorate([ + editableInPropertyPage("Force normalization for the worldTangent input", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES", { notifiers: { update: true } }) +], HeightToNormalBlock.prototype, "automaticNormalizationTangent", void 0); +RegisterClass("BABYLON.HeightToNormalBlock", HeightToNormalBlock); + +/** + * Block used to write the fragment depth + */ +class FragDepthBlock extends NodeMaterialBlock { + /** + * Create a new FragDepthBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment, true); + this.registerInput("depth", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("worldPos", NodeMaterialBlockConnectionPointTypes.Vector4, true); + this.registerInput("viewProjection", NodeMaterialBlockConnectionPointTypes.Matrix, true); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "FragDepthBlock"; + } + /** + * Gets the depth input component + */ + get depth() { + return this._inputs[0]; + } + /** + * Gets the worldPos input component + */ + get worldPos() { + return this._inputs[1]; + } + /** + * Gets the viewProjection input component + */ + get viewProjection() { + return this._inputs[2]; + } + _buildBlock(state) { + super._buildBlock(state); + const fragDepth = state.shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? "gl_FragDepth" : "fragmentOutputs.fragDepth"; + if (this.depth.isConnected) { + state.compilationString += `${fragDepth} = ${this.depth.associatedVariableName};\n`; + } + else if (this.worldPos.isConnected && this.viewProjection.isConnected) { + state.compilationString += ` + ${state._declareLocalVar("p", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; + ${state._declareLocalVar("v", NodeMaterialBlockConnectionPointTypes.Float)} = p.z / p.w; + #ifndef IS_NDC_HALF_ZRANGE + v = v * 0.5 + 0.5; + #endif + ${fragDepth} = v; + + `; + } + else { + Logger.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"); + } + return this; + } +} +RegisterClass("BABYLON.FragDepthBlock", FragDepthBlock); + +/** + * Block used to output the depth to a shadow map + */ +class ShadowMapBlock extends NodeMaterialBlock { + /** + * Create a new ShadowMapBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false); + this.registerInput("viewProjection", NodeMaterialBlockConnectionPointTypes.Matrix, false); + this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerOutput("depth", NodeMaterialBlockConnectionPointTypes.Vector3); + this.worldNormal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ShadowMapBlock"; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("vPositionWSM"); + state._excludeVariableName("lightDataSM"); + state._excludeVariableName("biasAndScaleSM"); + state._excludeVariableName("depthValuesSM"); + state._excludeVariableName("clipPos"); + state._excludeVariableName("worldPos"); + state._excludeVariableName("zSM"); + this._initShaderSourceAsync(state.shaderLanguage); + } + async _initShaderSourceAsync(shaderLanguage) { + this._codeIsReady = false; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([ + Promise.resolve().then(() => shadowMapVertexMetric$2), + Promise.resolve().then(() => packingFunctions), + Promise.resolve().then(() => shadowMapFragment$2), + ]); + } + else { + await Promise.all([ + Promise.resolve().then(() => shadowMapVertexMetric$1), + Promise.resolve().then(() => packingFunctions$2), + Promise.resolve().then(() => shadowMapFragment$1), + ]); + } + this._codeIsReady = true; + this.onCodeIsReadyObservable.notifyObservers(this); + } + /** + * Gets the world position input component + */ + get worldPosition() { + return this._inputs[0]; + } + /** + * Gets the view x projection input component + */ + get viewProjection() { + return this._inputs[1]; + } + /** + * Gets the world normal input component + */ + get worldNormal() { + return this._inputs[2]; + } + /** + * Gets the depth output component + */ + get depth() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const comments = `//${this.name}`; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + state._emitUniformFromString("biasAndScaleSM", NodeMaterialBlockConnectionPointTypes.Vector3); + state._emitUniformFromString("lightDataSM", NodeMaterialBlockConnectionPointTypes.Vector3); + state._emitUniformFromString("depthValuesSM", NodeMaterialBlockConnectionPointTypes.Vector2); + state._emitFunctionFromInclude("packingFunctions", comments); + state.compilationString += `${state._declareLocalVar("worldPos", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this.worldPosition.associatedVariableName};\n`; + state.compilationString += `${state._declareLocalVar("vPositionWSM", NodeMaterialBlockConnectionPointTypes.Vector3)};\n`; + state.compilationString += `${state._declareLocalVar("vDepthMetricSM", NodeMaterialBlockConnectionPointTypes.Float)} = 0.0;\n`; + state.compilationString += `${state._declareLocalVar("zSM", NodeMaterialBlockConnectionPointTypes.Float)};\n`; + if (this.worldNormal.isConnected) { + state.compilationString += `${state._declareLocalVar("vNormalW", NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;\n`; + state.compilationString += state._emitCodeFromInclude("shadowMapVertexNormalBias", comments); + } + state.compilationString += `${state._declareLocalVar("clipPos", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this.viewProjection.associatedVariableName} * worldPos;\n`; + state.compilationString += state._emitCodeFromInclude("shadowMapVertexMetric", comments, { + replaceStrings: [ + { + search: /gl_Position/g, + replace: "clipPos", + }, + { + search: /vertexOutputs.position/g, + replace: "clipPos", + }, + { + search: /vertexOutputs\.vDepthMetricSM/g, + replace: "vDepthMetricSM", + }, + ], + }); + state.compilationString += state._emitCodeFromInclude("shadowMapFragment", comments, { + replaceStrings: [ + { + search: /return;/g, + replace: "", + }, + { + search: /fragmentInputs\.vDepthMetricSM/g, + replace: "vDepthMetricSM", + }, + ], + }); + const output = isWebGPU ? "fragmentOutputs.fragDepth" : "gl_FragDepth"; + state.compilationString += ` + #if SM_DEPTHTEXTURE == 1 + #ifdef IS_NDC_HALF_ZRANGE + ${output} = (clipPos.z / clipPos.w); + #else + ${output} = (clipPos.z / clipPos.w) * 0.5 + 0.5; + #endif + #endif + `; + state.compilationString += `${state._declareOutput(this.depth)} = vec3${state.fSuffix}(depthSM, 1., 1.);\n`; + return this; + } +} +RegisterClass("BABYLON.ShadowMapBlock", ShadowMapBlock); + +/** + * Block used to output values on the prepass textures + * @see https://playground.babylonjs.com/#WW65SN#9 + */ +class PrePassOutputBlock extends NodeMaterialBlock { + /** + * Create a new PrePassOutputBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment, true); + this.registerInput("viewDepth", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("screenDepth", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("localPosition", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("viewNormal", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("reflectivity", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("velocity", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("velocityLinear", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.inputs[2].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + this.inputs[3].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + this.inputs[4].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + this.inputs[5].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + this.inputs[6].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | + NodeMaterialBlockConnectionPointTypes.Vector4 | + NodeMaterialBlockConnectionPointTypes.Color3 | + NodeMaterialBlockConnectionPointTypes.Color4); + this.inputs[7].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + this.inputs[8].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "PrePassOutputBlock"; + } + /** + * Gets the view depth component + */ + get viewDepth() { + return this._inputs[0]; + } + /** + * Gets the screen depth component + */ + get screenDepth() { + return this._inputs[1]; + } + /** + * Gets the world position component + */ + get worldPosition() { + return this._inputs[2]; + } + /** + * Gets the position in local space component + */ + get localPosition() { + return this._inputs[3]; + } + /** + * Gets the view normal component + */ + get viewNormal() { + return this._inputs[4]; + } + /** + * Gets the world normal component + */ + get worldNormal() { + return this._inputs[5]; + } + /** + * Gets the reflectivity component + */ + get reflectivity() { + return this._inputs[6]; + } + /** + * Gets the velocity component + */ + get velocity() { + return this._inputs[7]; + } + /** + * Gets the linear velocity component + */ + get velocityLinear() { + return this._inputs[8]; + } + _getFragData(isWebGPU, index) { + return isWebGPU ? `fragmentOutputs.fragData${index}` : `gl_FragData[${index}]`; + } + _buildBlock(state) { + super._buildBlock(state); + const worldPosition = this.worldPosition; + const localPosition = this.localPosition; + const viewNormal = this.viewNormal; + const worldNormal = this.worldNormal; + const viewDepth = this.viewDepth; + const reflectivity = this.reflectivity; + const screenDepth = this.screenDepth; + const velocity = this.velocity; + const velocityLinear = this.velocityLinear; + state.sharedData.blocksWithDefines.push(this); + const comments = `//${this.name}`; + const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4); + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + state._emitFunctionFromInclude("helperFunctions", comments); + state.compilationString += `#if defined(PREPASS)\r\n`; + state.compilationString += isWebGPU ? `var fragData: array, SCENE_MRT_COUNT>;\r\n` : `vec4 fragData[SCENE_MRT_COUNT];\r\n`; + state.compilationString += `#ifdef PREPASS_DEPTH\r\n`; + if (viewDepth.connectedPoint) { + state.compilationString += ` fragData[PREPASS_DEPTH_INDEX] = ${vec4}(${viewDepth.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`; + } + else { + // We have to write something on the viewDepth output or it will raise a gl error + state.compilationString += ` fragData[PREPASS_DEPTH_INDEX] = ${vec4}(0.0, 0.0, 0.0, 0.0);\r\n`; + } + state.compilationString += `#endif\r\n`; + state.compilationString += `#ifdef PREPASS_SCREENSPACE_DEPTH\r\n`; + if (screenDepth.connectedPoint) { + state.compilationString += ` gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX] = vec4(${screenDepth.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`; + } + else { + // We have to write something on the viewDepth output or it will raise a gl error + state.compilationString += ` gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n`; + } + state.compilationString += `#endif\r\n`; + state.compilationString += `#ifdef PREPASS_POSITION\r\n`; + if (worldPosition.connectedPoint) { + state.compilationString += `fragData[PREPASS_POSITION_INDEX] = ${vec4}(${worldPosition.associatedVariableName}.rgb, ${worldPosition.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? worldPosition.associatedVariableName + ".a" : "1.0"});\r\n`; + } + else { + // We have to write something on the position output or it will raise a gl error + state.compilationString += ` fragData[PREPASS_POSITION_INDEX] = ${vec4}(0.0, 0.0, 0.0, 0.0);\r\n`; + } + state.compilationString += `#endif\r\n`; + state.compilationString += `#ifdef PREPASS_LOCAL_POSITION\r\n`; + if (localPosition.connectedPoint) { + state.compilationString += ` gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(${localPosition.associatedVariableName}.rgb, ${localPosition.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? localPosition.associatedVariableName + ".a" : "1.0"});\r\n`; + } + else { + // We have to write something on the position output or it will raise a gl error + state.compilationString += ` gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n`; + } + state.compilationString += `#endif\r\n`; + state.compilationString += `#ifdef PREPASS_NORMAL\r\n`; + if (viewNormal.connectedPoint) { + state.compilationString += ` fragData[PREPASS_NORMAL_INDEX] = ${vec4}(${viewNormal.associatedVariableName}.rgb, ${viewNormal.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? viewNormal.associatedVariableName + ".a" : "1.0"});\r\n`; + } + else { + // We have to write something on the normal output or it will raise a gl error + state.compilationString += ` fragData[PREPASS_NORMAL_INDEX] = ${vec4}(0.0, 0.0, 0.0, 0.0);\r\n`; + } + state.compilationString += `#endif\r\n`; + state.compilationString += `#ifdef PREPASS_WORLD_NORMAL\r\n`; + if (worldNormal.connectedPoint) { + state.compilationString += ` gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(${worldNormal.associatedVariableName}.rgb, ${worldNormal.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? worldNormal.associatedVariableName + ".a" : "1.0"});\r\n`; + } + else { + // We have to write something on the normal output or it will raise a gl error + state.compilationString += ` gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n`; + } + state.compilationString += `#endif\r\n`; + state.compilationString += `#ifdef PREPASS_REFLECTIVITY\r\n`; + if (reflectivity.connectedPoint) { + state.compilationString += ` fragData[PREPASS_REFLECTIVITY_INDEX] = ${vec4}(${reflectivity.associatedVariableName}.rgb, ${reflectivity.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? reflectivity.associatedVariableName + ".a" : "1.0"});\r\n`; + } + else { + // We have to write something on the reflectivity output or it will raise a gl error + state.compilationString += ` fragData[PREPASS_REFLECTIVITY_INDEX] = ${vec4}(0.0, 0.0, 0.0, 1.0);\r\n`; + } + state.compilationString += `#endif\r\n`; + state.compilationString += `#ifdef PREPASS_VELOCITY\r\n`; + if (velocity.connectedPoint) { + state.compilationString += ` fragData[PREPASS_VELOCITY_INDEX] = ${vec4}(${velocity.associatedVariableName}.rgb, ${velocity.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? velocity.associatedVariableName + ".a" : "1.0"});\r\n`; + } + else { + // We have to write something on the reflectivity output or it will raise a gl error + state.compilationString += ` fragData[PREPASS_VELOCITY_INDEX] = ${vec4}(0.0, 0.0, 0.0, 1.0);\r\n`; + } + state.compilationString += `#endif\r\n`; + state.compilationString += `#ifdef PREPASS_VELOCITY_LINEAR\r\n`; + if (velocityLinear.connectedPoint) { + state.compilationString += ` fragData[PREPASS_VELOCITY_LINEAR_INDEX] = ${vec4}(${velocityLinear.associatedVariableName}.rgb, ${velocityLinear.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? velocityLinear.associatedVariableName + ".a" : "1.0"});\r\n`; + } + else { + // We have to write something on the reflectivity output or it will raise a gl error + state.compilationString += ` fragData[PREPASS_VELOCITY_LINEAR_INDEX] = ${vec4}(0.0, 0.0, 0.0, 1.0);\r\n`; + } + state.compilationString += `#endif\r\n`; + state.compilationString += `#if SCENE_MRT_COUNT > 1\r\n`; + state.compilationString += `${this._getFragData(isWebGPU, 1)} = fragData[1];\r\n`; + state.compilationString += `#endif\r\n`; + state.compilationString += `#if SCENE_MRT_COUNT > 2\r\n`; + state.compilationString += `${this._getFragData(isWebGPU, 2)} = fragData[2];\r\n`; + state.compilationString += `#endif\r\n`; + state.compilationString += `#if SCENE_MRT_COUNT > 3\r\n`; + state.compilationString += `${this._getFragData(isWebGPU, 3)} = fragData[3];\r\n`; + state.compilationString += `#endif\r\n`; + state.compilationString += `#if SCENE_MRT_COUNT > 4\r\n`; + state.compilationString += `${this._getFragData(isWebGPU, 4)} = fragData[4];\r\n`; + state.compilationString += `#endif\r\n`; + state.compilationString += `#if SCENE_MRT_COUNT > 5\r\n`; + state.compilationString += `${this._getFragData(isWebGPU, 5)} = fragData[5];\r\n`; + state.compilationString += `#endif\r\n`; + state.compilationString += `#if SCENE_MRT_COUNT > 6\r\n`; + state.compilationString += `${this._getFragData(isWebGPU, 6)} = fragData[6];\r\n`; + state.compilationString += `#endif\r\n`; + state.compilationString += `#if SCENE_MRT_COUNT > 7\r\n`; + state.compilationString += `${this._getFragData(isWebGPU, 7)} = fragData[7];\r\n`; + state.compilationString += `#endif\r\n`; + state.compilationString += `#endif\r\n`; + return this; + } +} +RegisterClass("BABYLON.PrePassOutputBlock", PrePassOutputBlock); + +/** + * Block used to add support for scene fog + */ +class FogBlock extends NodeMaterialBlock { + /** + * Create a new FogBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.VertexAndFragment, false); + // Vertex + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex); + // Fragment + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("fogColor", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Fragment); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.input.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Color4); + this.fogColor.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Color4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "FogBlock"; + } + /** + * Gets the world position input component + */ + get worldPosition() { + return this._inputs[0]; + } + /** + * Gets the view input component + */ + get view() { + return this._inputs[1]; + } + /** + * Gets the color input component + */ + get input() { + return this._inputs[2]; + } + /** + * Gets the fog color input component + */ + get fogColor() { + return this._inputs[3]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + initialize(state) { + this._initShaderSourceAsync(state.shaderLanguage); + } + async _initShaderSourceAsync(shaderLanguage) { + this._codeIsReady = false; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => fogFragmentDeclaration$1); + } + else { + await Promise.resolve().then(() => fogFragmentDeclaration); + } + this._codeIsReady = true; + this.onCodeIsReadyObservable.notifyObservers(this); + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.view.isConnected) { + let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View && additionalFilteringInfo(b)); + if (!viewInput) { + viewInput = new InputBlock("view"); + viewInput.setAsSystemValue(NodeMaterialSystemValues.View); + } + viewInput.output.connectTo(this.view); + } + if (!this.fogColor.isConnected) { + let fogColorInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.FogColor && additionalFilteringInfo(b)); + if (!fogColorInput) { + fogColorInput = new InputBlock("fogColor", undefined, NodeMaterialBlockConnectionPointTypes.Color3); + fogColorInput.setAsSystemValue(NodeMaterialSystemValues.FogColor); + } + fogColorInput.output.connectTo(this.fogColor); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + const scene = mesh.getScene(); + defines.setValue("FOG", nodeMaterial.fogEnabled && GetFogState(mesh, scene)); + } + bind(effect, nodeMaterial, mesh) { + if (!mesh) { + return; + } + const scene = mesh.getScene(); + effect.setFloat4(this._fogParameters, scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Fragment) { + state.sharedData.blocksWithDefines.push(this); + state.sharedData.bindableBlocks.push(this); + let replaceStrings = []; + let prefix1 = ""; + let prefix2 = ""; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + replaceStrings = [ + { search: /fn CalcFogFactor\(\)/, replace: "fn CalcFogFactor(vFogDistance: vec3f, vFogInfos: vec4f)" }, + { search: /uniforms.vFogInfos/g, replace: "vFogInfos" }, + { search: /fragmentInputs.vFogDistance/g, replace: "vFogDistance" }, + ]; + prefix1 = "fragmentInputs."; + prefix2 = "uniforms."; + } + else { + replaceStrings = [{ search: /float CalcFogFactor\(\)/, replace: "float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)" }]; + } + state._emitFunctionFromInclude("fogFragmentDeclaration", `//${this.name}`, { + removeUniforms: true, + removeVaryings: true, + removeIfDef: false, + replaceStrings: replaceStrings, + }); + const tempFogVariablename = state._getFreeVariableName("fog"); + const color = this.input; + const fogColor = this.fogColor; + this._fogParameters = state._getFreeVariableName("fogParameters"); + const output = this._outputs[0]; + state._emitUniformFromString(this._fogParameters, NodeMaterialBlockConnectionPointTypes.Vector4); + state.compilationString += `#ifdef FOG\n`; + state.compilationString += `${state._declareLocalVar(tempFogVariablename, NodeMaterialBlockConnectionPointTypes.Float)} = CalcFogFactor(${prefix1}${this._fogDistanceName}, ${prefix2}${this._fogParameters});\n`; + state.compilationString += + state._declareOutput(output) + + ` = ${tempFogVariablename} * ${color.associatedVariableName}.rgb + (1.0 - ${tempFogVariablename}) * ${fogColor.associatedVariableName}.rgb;\n`; + state.compilationString += `#else\n${state._declareOutput(output)} = ${color.associatedVariableName}.rgb;\n`; + state.compilationString += `#endif\n`; + } + else { + const worldPos = this.worldPosition; + const view = this.view; + this._fogDistanceName = state._getFreeVariableName("vFogDistance"); + state._emitVaryingFromString(this._fogDistanceName, NodeMaterialBlockConnectionPointTypes.Vector3); + const prefix = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "vertexOutputs." : ""; + state.compilationString += `${prefix}${this._fogDistanceName} = (${view.associatedVariableName} * ${worldPos.associatedVariableName}).xyz;\n`; + } + return this; + } +} +RegisterClass("BABYLON.FogBlock", FogBlock); + +/** + * Block used to add light in the fragment shader + */ +class LightBlock extends NodeMaterialBlock { + static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) { + const that = block; + if (that.worldPosition.isConnected) { + that.generateOnlyFragmentCode = !that.generateOnlyFragmentCode; + Logger.Error("The worldPosition input must not be connected to be able to switch!"); + return false; + } + that._setTarget(); + return true; + } + _setTarget() { + this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment); + this.getInputByName("worldPosition").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; + } + /** + * Create a new LightBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.VertexAndFragment); + this._lightId = 0; + /** Indicates that no code should be generated in the vertex shader. Can be useful in some specific circumstances (like when doing ray marching for eg) */ + this.generateOnlyFragmentCode = false; + this._isUnique = true; + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("glossiness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("glossPower", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("diffuseColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("specularColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, true); + this.registerOutput("diffuseOutput", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("specularOutput", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("shadow", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "LightBlock"; + } + /** + * Gets the world position input component + */ + get worldPosition() { + return this._inputs[0]; + } + /** + * Gets the world normal input component + */ + get worldNormal() { + return this._inputs[1]; + } + /** + * Gets the camera (or eye) position component + */ + get cameraPosition() { + return this._inputs[2]; + } + /** + * Gets the glossiness component + */ + get glossiness() { + return this._inputs[3]; + } + /** + * Gets the glossiness power component + */ + get glossPower() { + return this._inputs[4]; + } + /** + * Gets the diffuse color component + */ + get diffuseColor() { + return this._inputs[5]; + } + /** + * Gets the specular color component + */ + get specularColor() { + return this._inputs[6]; + } + /** + * Gets the view matrix component + */ + get view() { + return this._inputs[7]; + } + /** + * Gets the diffuse output component + */ + get diffuseOutput() { + return this._outputs[0]; + } + /** + * Gets the specular output component + */ + get specularOutput() { + return this._outputs[1]; + } + /** + * Gets the shadow output component + */ + get shadow() { + return this._outputs[2]; + } + initialize(state) { + this._initShaderSourceAsync(state.shaderLanguage); + } + async _initShaderSourceAsync(shaderLanguage) { + this._codeIsReady = false; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([ + Promise.resolve().then(() => lightFragment$2), + Promise.resolve().then(() => lightUboDeclaration$2), + Promise.resolve().then(() => lightVxUboDeclaration$2), + Promise.resolve().then(() => helperFunctions$2), + Promise.resolve().then(() => lightsFragmentFunctions$2), + Promise.resolve().then(() => shadowsFragmentFunctions$2), + Promise.resolve().then(() => shadowsVertex$2), + ]); + } + else { + await Promise.all([ + Promise.resolve().then(() => lightFragmentDeclaration$1), + Promise.resolve().then(() => lightFragment$1), + Promise.resolve().then(() => lightUboDeclaration$1), + Promise.resolve().then(() => lightVxUboDeclaration$1), + Promise.resolve().then(() => lightVxFragmentDeclaration$1), + Promise.resolve().then(() => helperFunctions$1), + Promise.resolve().then(() => lightsFragmentFunctions$1), + Promise.resolve().then(() => shadowsFragmentFunctions$1), + Promise.resolve().then(() => shadowsVertex$1), + ]); + } + this._codeIsReady = true; + this.onCodeIsReadyObservable.notifyObservers(this); + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.cameraPosition.isConnected) { + let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition && additionalFilteringInfo(b)); + if (!cameraPositionInput) { + cameraPositionInput = new InputBlock("cameraPosition"); + cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition); + } + cameraPositionInput.output.connectTo(this.cameraPosition); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + if (!defines._areLightsDirty) { + return; + } + const scene = mesh.getScene(); + if (!this.light) { + PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights); + } + else { + const state = { + needNormals: false, + needRebuild: false, + lightmapMode: false, + shadowEnabled: false, + specularEnabled: false, + }; + PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state); + if (state.needRebuild) { + defines.rebuild(); + } + } + } + updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) { + state.samplers.push("areaLightsLTC1Sampler"); + state.samplers.push("areaLightsLTC2Sampler"); + for (let lightIndex = 0; lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) { + if (!defines["LIGHT" + lightIndex]) { + break; + } + const onlyUpdateBuffersList = state.uniforms.indexOf("vLightData" + lightIndex) >= 0; + PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffers, onlyUpdateBuffersList, defines["IESLIGHTTEXTURE" + lightIndex]); + } + } + bind(effect, nodeMaterial, mesh) { + if (!mesh) { + return; + } + const scene = mesh.getScene(); + if (!this.light) { + BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights); + } + else { + BindLight(this.light, this._lightId, scene, effect, true); + } + } + _injectVertexCode(state) { + const worldPos = this.worldPosition; + const comments = `//${this.name}`; + // Declaration + if (!this.light) { + // Emit for all lights + state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, { + repeatKey: "maxSimultaneousLights", + }); + this._lightId = 0; + state.sharedData.dynamicUniformBlocks.push(this); + } + else { + this._lightId = (state.counters["lightCounter"] !== undefined ? state.counters["lightCounter"] : -1) + 1; + state.counters["lightCounter"] = this._lightId; + state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, { + replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }], + }, this._lightId.toString()); + } + // Inject code in vertex + const worldPosVaryingName = "v_" + worldPos.associatedVariableName; + if (state._emitVaryingFromString(worldPosVaryingName, NodeMaterialBlockConnectionPointTypes.Vector4)) { + state.compilationString += (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "vertexOutputs." : "") + `${worldPosVaryingName} = ${worldPos.associatedVariableName};\n`; + } + if (this.light) { + state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { + replaceStrings: [ + { search: /{X}/g, replace: this._lightId.toString() }, + { search: /worldPos/g, replace: worldPos.associatedVariableName }, + ], + }); + } + else { + state.compilationString += `${state._declareLocalVar("worldPos", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${worldPos.associatedVariableName};\n`; + if (this.view.isConnected) { + state.compilationString += `${state._declareLocalVar("view", NodeMaterialBlockConnectionPointTypes.Matrix)} = ${this.view.associatedVariableName};\n`; + } + state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { + repeatKey: "maxSimultaneousLights", + }); + } + } + _injectUBODeclaration(state) { + const comments = `//${this.name}`; + if (!this.light) { + // Emit for all lights + state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, { + repeatKey: "maxSimultaneousLights", + substitutionVars: this.generateOnlyFragmentCode ? "varying," : undefined, + }); + } + else { + state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, { + replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }], + }, this._lightId.toString()); + } + } + _buildBlock(state) { + super._buildBlock(state); + const isWGSL = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + const addF = isWGSL ? "f" : ""; + const comments = `//${this.name}`; + if (state.target !== NodeMaterialBlockTargets.Fragment) { + // Vertex + this._injectVertexCode(state); + return; + } + if (this.generateOnlyFragmentCode) { + state.sharedData.dynamicUniformBlocks.push(this); + } + // Fragment + const accessor = isWGSL ? "fragmentInputs." : ""; + state.sharedData.forcedBindableBlocks.push(this); + state.sharedData.blocksWithDefines.push(this); + const worldPos = this.worldPosition; + let worldPosVariableName = worldPos.associatedVariableName; + if (this.generateOnlyFragmentCode) { + worldPosVariableName = state._getFreeVariableName("globalWorldPos"); + state._emitFunction("light_globalworldpos", `${state._declareLocalVar(worldPosVariableName, NodeMaterialBlockConnectionPointTypes.Vector3)};\n`, comments); + state.compilationString += `${worldPosVariableName} = ${worldPos.associatedVariableName}.xyz;\n`; + state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { + repeatKey: "maxSimultaneousLights", + substitutionVars: this.generateOnlyFragmentCode ? `worldPos,${worldPos.associatedVariableName}` : undefined, + }); + } + else { + worldPosVariableName = accessor + "v_" + worldPosVariableName + ".xyz"; + } + state._emitFunctionFromInclude("helperFunctions", comments); + let replaceString = { search: /vPositionW/g, replace: worldPosVariableName }; + if (isWGSL) { + replaceString = { search: /fragmentInputs\.vPositionW/g, replace: worldPosVariableName }; + } + state._emitFunctionFromInclude("lightsFragmentFunctions", comments, { + replaceStrings: [replaceString], + }); + state._emitFunctionFromInclude("shadowsFragmentFunctions", comments, { + replaceStrings: [replaceString], + }); + this._injectUBODeclaration(state); + // Code + if (this._lightId === 0) { + if (state._registerTempVariable("viewDirectionW")) { + state.compilationString += `${state._declareLocalVar("viewDirectionW", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${worldPosVariableName});\n`; + } + state.compilationString += isWGSL ? `var info: lightingInfo;\n` : `lightingInfo info;\n`; + state.compilationString += `${state._declareLocalVar("shadow", NodeMaterialBlockConnectionPointTypes.Float)} = 1.;\n`; + state.compilationString += `${state._declareLocalVar("aggShadow", NodeMaterialBlockConnectionPointTypes.Float)} = 0.;\n`; + state.compilationString += `${state._declareLocalVar("numLights", NodeMaterialBlockConnectionPointTypes.Float)} = 0.;\n`; + state.compilationString += `${state._declareLocalVar("glossiness", NodeMaterialBlockConnectionPointTypes.Float)} = ${this.glossiness.isConnected ? this.glossiness.associatedVariableName : "1.0"} * ${this.glossPower.isConnected ? this.glossPower.associatedVariableName : "1024.0"};\n`; + state.compilationString += `${state._declareLocalVar("diffuseBase", NodeMaterialBlockConnectionPointTypes.Vector3)} = vec3${addF}(0., 0., 0.);\n`; + state.compilationString += `${state._declareLocalVar("specularBase", NodeMaterialBlockConnectionPointTypes.Vector3)} = vec3${addF}(0., 0., 0.);\n`; + state.compilationString += `${state._declareLocalVar("normalW", NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;\n`; + } + if (this.light) { + let replaceString = { search: /vPositionW/g, replace: worldPosVariableName + ".xyz" }; + if (isWGSL) { + replaceString = { search: /fragmentInputs\.vPositionW/g, replace: worldPosVariableName + ".xyz" }; + } + state.compilationString += state._emitCodeFromInclude("lightFragment", comments, { + replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }, replaceString], + }); + } + else { + let substitutionVars = `vPositionW,${worldPosVariableName}.xyz`; + if (isWGSL) { + substitutionVars = `fragmentInputs.vPositionW,${worldPosVariableName}.xyz`; + } + state.compilationString += state._emitCodeFromInclude("lightFragment", comments, { + repeatKey: "maxSimultaneousLights", + substitutionVars: substitutionVars, + }); + } + if (this._lightId === 0) { + state.compilationString += `aggShadow = aggShadow / numLights;\n`; + } + const diffuseOutput = this.diffuseOutput; + const specularOutput = this.specularOutput; + state.compilationString += + state._declareOutput(diffuseOutput) + ` = diffuseBase${this.diffuseColor.isConnected ? " * " + this.diffuseColor.associatedVariableName : ""};\n`; + if (specularOutput.hasEndpoints) { + state.compilationString += + state._declareOutput(specularOutput) + ` = specularBase${this.specularColor.isConnected ? " * " + this.specularColor.associatedVariableName : ""};\n`; + } + if (this.shadow.hasEndpoints) { + state.compilationString += state._declareOutput(this.shadow) + ` = aggShadow;\n`; + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode; + if (this.light) { + serializationObject.lightId = this.light.id; + } + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + if (serializationObject.lightId) { + this.light = scene.getLightById(serializationObject.lightId); + } + this.generateOnlyFragmentCode = serializationObject.generateOnlyFragmentCode; + this._setTarget(); + } +} +__decorate([ + editableInPropertyPage("Generate only fragment code", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { + notifiers: { rebuild: true, update: true, onValidation: LightBlock._OnGenerateOnlyFragmentCodeChanged }, + }) +], LightBlock.prototype, "generateOnlyFragmentCode", void 0); +RegisterClass("BABYLON.LightBlock", LightBlock); + +/** + * Block used to provide an image for a TextureBlock + */ +class ImageSourceBlock extends NodeMaterialBlock { + /** + * Gets or sets the texture associated with the node + */ + get texture() { + return this._texture; + } + set texture(texture) { + if (this._texture === texture) { + return; + } + const scene = texture?.getScene() ?? EngineStore.LastCreatedScene; + if (!texture && scene) { + scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this._texture); + }); + } + this._texture = texture; + if (texture && scene) { + scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(texture); + }); + } + } + /** + * Gets the sampler name associated with this image source + */ + get samplerName() { + return this._samplerName; + } + /** + * Creates a new ImageSourceBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.VertexAndFragment); + this.registerOutput("source", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source", this, 1 /* NodeMaterialConnectionPointDirection.Output */, ImageSourceBlock, "ImageSourceBlock")); + this.registerOutput("dimensions", NodeMaterialBlockConnectionPointTypes.Vector2); + } + bind(effect) { + if (!this.texture) { + return; + } + effect.setTexture(this._samplerName, this.texture); + } + isReady() { + if (this.texture && !this.texture.isReadyOrNotBlocking()) { + return false; + } + return true; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ImageSourceBlock"; + } + /** + * Gets the output component + */ + get source() { + return this._outputs[0]; + } + /** + * Gets the dimension component + */ + get dimensions() { + return this._outputs[1]; + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Vertex) { + this._samplerName = state._getFreeVariableName(this.name + "Texture"); + // Declarations + state.sharedData.blockingBlocks.push(this); + state.sharedData.textureBlocks.push(this); + state.sharedData.bindableBlocks.push(this); + } + if (this.dimensions.isConnected) { + let affect = ""; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + affect = `vec2f(textureDimensions(${this._samplerName}, 0).xy)`; + } + else { + affect = `vec2(textureSize(${this._samplerName}, 0).xy)`; + } + state.compilationString += `${state._declareOutput(this.dimensions)} = ${affect};\n`; + } + state._emit2DSampler(this._samplerName); + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + if (!this.texture) { + return codeString; + } + codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`; + codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`; + codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`; + codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`; + codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`; + codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`; + codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`; + codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`; + codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`; + codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`; + codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + if (this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture") { + serializationObject.texture = this.texture.serialize(); + } + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl, urlRewriter) { + super._deserialize(serializationObject, scene, rootUrl, urlRewriter); + if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) { + if (serializationObject.texture.url.indexOf("data:") === 0) { + rootUrl = ""; + } + else if (urlRewriter) { + serializationObject.texture.url = urlRewriter(serializationObject.texture.url); + serializationObject.texture.name = serializationObject.texture.url; + } + this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl); + } + } +} +RegisterClass("BABYLON.ImageSourceBlock", ImageSourceBlock); + +/** + * Block used to read a texture from a sampler + */ +class TextureBlock extends NodeMaterialBlock { + /** + * Gets or sets the texture associated with the node + */ + get texture() { + if (this.source.isConnected) { + return (this.source.connectedPoint?.ownerBlock).texture; + } + return this._texture; + } + set texture(texture) { + if (this._texture === texture) { + return; + } + const scene = texture?.getScene() ?? EngineStore.LastCreatedScene; + if (!texture && scene) { + scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this._texture); + }); + } + this._texture = texture; + if (texture && scene) { + scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(texture); + }); + } + } + static _IsPrePassTextureBlock(block) { + return block?.getClassName() === "PrePassTextureBlock"; + } + get _isSourcePrePass() { + return TextureBlock._IsPrePassTextureBlock(this._imageSource); + } + /** + * Gets the sampler name associated with this texture + */ + get samplerName() { + if (this._imageSource) { + if (!TextureBlock._IsPrePassTextureBlock(this._imageSource)) { + return this._imageSource.samplerName; + } + if (this.source.connectedPoint) { + return this._imageSource.getSamplerName(this.source.connectedPoint); + } + } + return this._samplerName; + } + /** + * Gets a boolean indicating that this block is linked to an ImageSourceBlock + */ + get hasImageSource() { + return this.source.isConnected; + } + /** + * Gets or sets a boolean indicating if content needs to be converted to gamma space + */ + set convertToGammaSpace(value) { + if (value === this._convertToGammaSpace) { + return; + } + this._convertToGammaSpace = value; + if (this.texture) { + const scene = this.texture.getScene() ?? EngineStore.LastCreatedScene; + scene?.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this.texture); + }); + } + } + get convertToGammaSpace() { + return this._convertToGammaSpace; + } + /** + * Gets or sets a boolean indicating if content needs to be converted to linear space + */ + set convertToLinearSpace(value) { + if (value === this._convertToLinearSpace) { + return; + } + this._convertToLinearSpace = value; + if (this.texture) { + const scene = this.texture.getScene() ?? EngineStore.LastCreatedScene; + scene?.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this.texture); + }); + } + } + get convertToLinearSpace() { + return this._convertToLinearSpace; + } + /** + * Create a new TextureBlock + * @param name defines the block name + * @param fragmentOnly + */ + constructor(name, fragmentOnly = false) { + super(name, fragmentOnly ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment); + this._convertToGammaSpace = false; + this._convertToLinearSpace = false; + /** + * Gets or sets a boolean indicating if multiplication of texture with level should be disabled + */ + this.disableLevelMultiplication = false; + this._fragmentOnly = fragmentOnly; + this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment); + this.registerInput("source", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source", this, 0 /* NodeMaterialConnectionPointDirection.Input */, ImageSourceBlock, "ImageSourceBlock")); + this.registerInput("layer", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("lod", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral); + this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral); + this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("level", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + this._inputs[0]._prioritizeVertex = !fragmentOnly; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "TextureBlock"; + } + /** + * Gets the uv input component + */ + get uv() { + return this._inputs[0]; + } + /** + * Gets the source input component + */ + get source() { + return this._inputs[1]; + } + /** + * Gets the layer input component + */ + get layer() { + return this._inputs[2]; + } + /** + * Gets the LOD input component + */ + get lod() { + return this._inputs[3]; + } + /** + * Gets the rgba output component + */ + get rgba() { + return this._outputs[0]; + } + /** + * Gets the rgb output component + */ + get rgb() { + return this._outputs[1]; + } + /** + * Gets the r output component + */ + get r() { + return this._outputs[2]; + } + /** + * Gets the g output component + */ + get g() { + return this._outputs[3]; + } + /** + * Gets the b output component + */ + get b() { + return this._outputs[4]; + } + /** + * Gets the a output component + */ + get a() { + return this._outputs[5]; + } + /** + * Gets the level output component + */ + get level() { + return this._outputs[6]; + } + _isTiedToFragment(input) { + if (input.target === NodeMaterialBlockTargets.Fragment) { + return true; + } + if (input.target === NodeMaterialBlockTargets.Vertex) { + return false; + } + if (input.target === NodeMaterialBlockTargets.Neutral || input.target === NodeMaterialBlockTargets.VertexAndFragment) { + const parentBlock = input.ownerBlock; + if (parentBlock.target === NodeMaterialBlockTargets.Fragment) { + return true; + } + for (const input of parentBlock.inputs) { + if (!input.isConnected) { + continue; + } + if (this._isTiedToFragment(input.connectedPoint)) { + return true; + } + } + } + return false; + } + _getEffectiveTarget() { + if (this._fragmentOnly) { + return NodeMaterialBlockTargets.Fragment; + } + // TextureBlock has a special optimizations for uvs that come from the vertex shaders as they can be packed into a single varyings. + // But we need to detect uvs coming from fragment then + if (!this.uv.isConnected) { + return NodeMaterialBlockTargets.VertexAndFragment; + } + if (this.uv.sourceBlock.isInput) { + return NodeMaterialBlockTargets.VertexAndFragment; + } + if (this._isTiedToFragment(this.uv.connectedPoint)) { + return NodeMaterialBlockTargets.Fragment; + } + return NodeMaterialBlockTargets.VertexAndFragment; + } + get target() { + return this._getEffectiveTarget(); + } + set target(value) { } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.uv.isConnected) { + if (material.mode === NodeMaterialModes.PostProcess) { + const uvInput = material.getBlockByPredicate((b) => b.name === "uv" && additionalFilteringInfo(b)); + if (uvInput) { + uvInput.connectTo(this); + } + } + else if (material.mode !== NodeMaterialModes.ProceduralTexture) { + const attributeName = material.mode === NodeMaterialModes.Particle ? "particle_uv" : "uv"; + let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === attributeName && additionalFilteringInfo(b)); + if (!uvInput) { + uvInput = new InputBlock("uv"); + uvInput.setAsAttribute(attributeName); + } + uvInput.output.connectTo(this.uv); + } + } + } + initializeDefines(mesh, nodeMaterial, defines) { + if (!defines._areTexturesDirty) { + return; + } + if (this._mainUVDefineName !== undefined) { + defines.setValue(this._mainUVDefineName, false, true); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + if (!defines._areTexturesDirty) { + return; + } + if (!this.texture || !this.texture.getTextureMatrix) { + if (this._isMixed) { + defines.setValue(this._defineName, false, true); + defines.setValue(this._mainUVDefineName, true, true); + } + return; + } + const toGamma = this.convertToGammaSpace && this.texture && !this.texture.gammaSpace; + const toLinear = this.convertToLinearSpace && this.texture && this.texture.gammaSpace; + // Not a bug... Name defines the texture space not the required conversion + defines.setValue(this._linearDefineName, toGamma, true); + defines.setValue(this._gammaDefineName, toLinear, true); + if (this._isMixed) { + if (!this.texture.getTextureMatrix().isIdentityAs3x2()) { + defines.setValue(this._defineName, true); + if (defines[this._mainUVDefineName] == undefined) { + defines.setValue(this._mainUVDefineName, false, true); + } + } + else { + defines.setValue(this._defineName, false, true); + defines.setValue(this._mainUVDefineName, true, true); + } + } + } + isReady() { + if (this._isSourcePrePass) { + return true; + } + if (this.texture && !this.texture.isReadyOrNotBlocking()) { + return false; + } + return true; + } + bind(effect) { + if (this._isSourcePrePass) { + effect.setFloat(this._textureInfoName, 1); + } + if (!this.texture) { + return; + } + if (this._isMixed) { + effect.setFloat(this._textureInfoName, this.texture.level); + effect.setMatrix(this._textureTransformName, this.texture.getTextureMatrix()); + } + if (!this._imageSource) { + effect.setTexture(this._samplerName, this.texture); + } + } + get _isMixed() { + return this.target !== NodeMaterialBlockTargets.Fragment; + } + _injectVertexCode(state) { + const uvInput = this.uv; + // Inject code in vertex + this._defineName = state._getFreeDefineName("UVTRANSFORM"); + this._mainUVDefineName = "VMAIN" + uvInput.declarationVariableName.toUpperCase(); + this._mainUVName = "vMain" + uvInput.declarationVariableName; + this._transformedUVName = state._getFreeVariableName("transformedUV"); + this._textureTransformName = state._getFreeVariableName("textureTransform"); + this._textureInfoName = state._getFreeVariableName("textureInfoName"); + this.level.associatedVariableName = this._textureInfoName; + state._emitVaryingFromString(this._transformedUVName, NodeMaterialBlockConnectionPointTypes.Vector2, this._defineName); + state._emitVaryingFromString(this._mainUVName, NodeMaterialBlockConnectionPointTypes.Vector2, this._mainUVDefineName); + state._emitUniformFromString(this._textureTransformName, NodeMaterialBlockConnectionPointTypes.Matrix, this._defineName); + const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4); + const vec2 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector2); + state.compilationString += `#ifdef ${this._defineName}\n`; + state.compilationString += `${state._getVaryingName(this._transformedUVName)} = ${vec2}(${this._textureTransformName} * ${vec4}(${uvInput.associatedVariableName}.xy, 1.0, 0.0));\n`; + state.compilationString += `#elif defined(${this._mainUVDefineName})\n`; + let automaticPrefix = ""; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + if (uvInput.isConnectedToInputBlock && uvInput.associatedVariableName.indexOf("vertexInputs.") === -1) { + automaticPrefix = "vertexInputs."; // Force the prefix + } + } + state.compilationString += `${state._getVaryingName(this._mainUVName)} = ${automaticPrefix}${uvInput.associatedVariableName}.xy;\n`; + state.compilationString += `#endif\n`; + if (!this._outputs.some((o) => o.isConnectedInVertexShader)) { + return; + } + this._writeTextureRead(state, true); + for (const output of this._outputs) { + if (output.hasEndpoints && output.name !== "level") { + this._writeOutput(state, output, output.name, true); + } + } + } + _getUVW(uvName) { + let coords = uvName; + const is2DArrayTexture = this._texture?._texture?.is2DArray ?? false; + const is3D = this._texture?._texture?.is3D ?? false; + if (is2DArrayTexture) { + const layerValue = this.layer.isConnected ? this.layer.associatedVariableName : "0"; + coords = `vec3(${uvName}, ${layerValue})`; + } + else if (is3D) { + const layerValue = this.layer.isConnected ? this.layer.associatedVariableName : "0"; + coords = `vec3(${uvName}, ${layerValue})`; + } + return coords; + } + _samplerFunc(state) { + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return state.target === NodeMaterialBlockTargets.Vertex ? "textureSampleLevel" : "textureSample"; + } + return this.lod.isConnected ? "texture2DLodEXT" : "texture2D"; + } + get _samplerLodSuffix() { + return this.lod.isConnected ? `, ${this.lod.associatedVariableName}` : ""; + } + _generateTextureSample(uv, state) { + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + const isVertex = state.target === NodeMaterialBlockTargets.Vertex; + return `${this._samplerFunc(state)}(${this.samplerName},${this.samplerName + `Sampler`}, ${this._getUVW(uv)}${this._samplerLodSuffix}${isVertex ? ", 0" : ""})`; + } + return `${this._samplerFunc(state)}(${this.samplerName}, ${this._getUVW(uv)}${this._samplerLodSuffix})`; + } + _generateTextureLookup(state) { + state.compilationString += `#ifdef ${this._defineName}\n`; + state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(state._getVaryingName(this._transformedUVName), state)};\n`; + state.compilationString += `#elif defined(${this._mainUVDefineName})\n`; + state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(this._mainUVName ? state._getVaryingName(this._mainUVName) : this.uv.associatedVariableName, state)}${this._samplerLodSuffix};\n`; + state.compilationString += `#endif\n`; + } + _writeTextureRead(state, vertexMode = false) { + const uvInput = this.uv; + if (vertexMode) { + if (state.target === NodeMaterialBlockTargets.Fragment) { + return; + } + this._generateTextureLookup(state); + return; + } + if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { + state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(uvInput.associatedVariableName, state)}${this._samplerLodSuffix};\n`; + return; + } + this._generateTextureLookup(state); + } + _generateConversionCode(state, output, swizzle) { + if (swizzle !== "a") { + // no conversion if the output is "a" (alpha) + if (!this.texture || !this.texture.gammaSpace) { + state.compilationString += `#ifdef ${this._linearDefineName} + ${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName}); + #endif + `; + } + state.compilationString += `#ifdef ${this._gammaDefineName} + ${output.associatedVariableName} = ${state._toLinearSpace(output)}; + #endif + `; + } + } + _writeOutput(state, output, swizzle, vertexMode = false) { + if (vertexMode) { + if (state.target === NodeMaterialBlockTargets.Fragment) { + return; + } + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};\n`; + this._generateConversionCode(state, output, swizzle); + return; + } + if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};\n`; + this._generateConversionCode(state, output, swizzle); + return; + } + let complement = ""; + if (!this.disableLevelMultiplication) { + complement = ` * ${(state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "uniforms." : "") + this._textureInfoName}`; + } + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle}${complement};\n`; + this._generateConversionCode(state, output, swizzle); + } + _buildBlock(state) { + super._buildBlock(state); + if (this.source.isConnected) { + this._imageSource = this.source.connectedPoint.ownerBlock; + } + else { + this._imageSource = null; + } + if (state.target === NodeMaterialBlockTargets.Vertex || this._fragmentOnly || state.target === NodeMaterialBlockTargets.Fragment) { + this._tempTextureRead = state._getFreeVariableName("tempTextureRead"); + this._linearDefineName = state._getFreeDefineName("ISLINEAR"); + this._gammaDefineName = state._getFreeDefineName("ISGAMMA"); + } + if ((!this._isMixed && state.target === NodeMaterialBlockTargets.Fragment) || (this._isMixed && state.target === NodeMaterialBlockTargets.Vertex)) { + if (!this._imageSource) { + const varName = state._getFreeVariableName(this.name); + this._samplerName = varName + "Texture"; + if (this._texture?._texture?.is2DArray) { + state._emit2DArraySampler(this._samplerName); + } + else { + state._emit2DSampler(this._samplerName); + } + } + // Declarations + state.sharedData.blockingBlocks.push(this); + state.sharedData.textureBlocks.push(this); + state.sharedData.blocksWithDefines.push(this); + state.sharedData.bindableBlocks.push(this); + } + if (state.target !== NodeMaterialBlockTargets.Fragment) { + // Vertex + this._injectVertexCode(state); + return; + } + // Fragment + if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) { + return; + } + if (this._isMixed && !this._imageSource) { + // Reexport the sampler + if (this._texture?._texture?.is2DArray) { + state._emit2DArraySampler(this._samplerName); + } + else { + state._emit2DSampler(this._samplerName); + } + } + const comments = `//${this.name}`; + state._emitFunctionFromInclude("helperFunctions", comments); + if (this._isMixed) { + state._emitUniformFromString(this._textureInfoName, NodeMaterialBlockConnectionPointTypes.Float); + } + this._writeTextureRead(state); + for (const output of this._outputs) { + if (output.hasEndpoints && output.name !== "level") { + this._writeOutput(state, output, output.name); + } + } + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`; + codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`; + codeString += `${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`; + if (!this.texture) { + return codeString; + } + codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`; + codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`; + codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`; + codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`; + codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`; + codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`; + codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`; + codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`; + codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`; + codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`; + codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.convertToGammaSpace = this.convertToGammaSpace; + serializationObject.convertToLinearSpace = this.convertToLinearSpace; + serializationObject.fragmentOnly = this._fragmentOnly; + serializationObject.disableLevelMultiplication = this.disableLevelMultiplication; + if (!this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture") { + serializationObject.texture = this.texture.serialize(); + } + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl, urlRewriter) { + super._deserialize(serializationObject, scene, rootUrl); + this.convertToGammaSpace = serializationObject.convertToGammaSpace; + this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; + this._fragmentOnly = !!serializationObject.fragmentOnly; + this.disableLevelMultiplication = !!serializationObject.disableLevelMultiplication; + if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) { + if (serializationObject.texture.url.indexOf("data:") === 0) { + rootUrl = ""; + } + else if (urlRewriter) { + serializationObject.texture.url = urlRewriter(serializationObject.texture.url); + serializationObject.texture.name = serializationObject.texture.url; + } + this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl); + } + } +} +RegisterClass("BABYLON.TextureBlock", TextureBlock); + +/** + * Base block used to read a reflection texture from a sampler + */ +class ReflectionTextureBaseBlock extends NodeMaterialBlock { + /** + * Gets or sets the texture associated with the node + */ + get texture() { + return this._texture; + } + set texture(texture) { + if (this._texture === texture) { + return; + } + const scene = texture?.getScene() ?? EngineStore.LastCreatedScene; + if (!texture && scene) { + scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this._texture); + }); + } + this._texture = texture; + if (texture && scene) { + scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(texture); + }); + } + } + static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) { + const that = block; + return that._onGenerateOnlyFragmentCodeChanged(); + } + _onGenerateOnlyFragmentCodeChanged() { + this._setTarget(); + return true; + } + _setTarget() { + this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment); + } + /** + * Create a new ReflectionTextureBaseBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.VertexAndFragment); + /** Indicates that no code should be generated in the vertex shader. Can be useful in some specific circumstances (like when doing ray marching for eg) */ + this.generateOnlyFragmentCode = false; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ReflectionTextureBaseBlock"; + } + _getTexture() { + return this.texture; + } + initialize(state) { + this._initShaderSourceAsync(state.shaderLanguage); + } + async _initShaderSourceAsync(shaderLanguage) { + this._codeIsReady = false; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => reflectionFunction$1); + } + else { + await Promise.resolve().then(() => reflectionFunction); + } + this._codeIsReady = true; + this.onCodeIsReadyObservable.notifyObservers(this); + } + /** + * Auto configure the node based on the existing material + * @param material defines the material to configure + * @param additionalFilteringInfo defines additional info to be used when filtering inputs (we might want to skip some non relevant blocks) + */ + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.position.isConnected) { + let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "position" && additionalFilteringInfo(b)); + if (!positionInput) { + positionInput = new InputBlock("position"); + positionInput.setAsAttribute(); + } + positionInput.output.connectTo(this.position); + } + if (!this.world.isConnected) { + let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World && additionalFilteringInfo(b)); + if (!worldInput) { + worldInput = new InputBlock("world"); + worldInput.setAsSystemValue(NodeMaterialSystemValues.World); + } + worldInput.output.connectTo(this.world); + } + if (this.view && !this.view.isConnected) { + let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View && additionalFilteringInfo(b)); + if (!viewInput) { + viewInput = new InputBlock("view"); + viewInput.setAsSystemValue(NodeMaterialSystemValues.View); + } + viewInput.output.connectTo(this.view); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + if (!defines._areTexturesDirty) { + return; + } + const texture = this._getTexture(); + if (!texture || !texture.getTextureMatrix) { + return; + } + defines.setValue(this._define3DName, texture.isCube, true); + defines.setValue(this._defineLocalCubicName, texture.boundingBoxSize ? true : false, true); + defines.setValue(this._defineExplicitName, texture.coordinatesMode === 0, true); + defines.setValue(this._defineSkyboxName, texture.coordinatesMode === 5, true); + defines.setValue(this._defineCubicName, texture.coordinatesMode === 3 || texture.coordinatesMode === 6, true); + defines.setValue("INVERTCUBICMAP", texture.coordinatesMode === 6, true); + defines.setValue(this._defineSphericalName, texture.coordinatesMode === 1, true); + defines.setValue(this._definePlanarName, texture.coordinatesMode === 2, true); + defines.setValue(this._defineProjectionName, texture.coordinatesMode === 4, true); + defines.setValue(this._defineEquirectangularName, texture.coordinatesMode === 7, true); + defines.setValue(this._defineEquirectangularFixedName, texture.coordinatesMode === 8, true); + defines.setValue(this._defineMirroredEquirectangularFixedName, texture.coordinatesMode === 9, true); + } + isReady() { + const texture = this._getTexture(); + if (texture && !texture.isReadyOrNotBlocking()) { + return false; + } + return true; + } + bind(effect, nodeMaterial, mesh, _subMesh) { + const texture = this._getTexture(); + if (!mesh || !texture) { + return; + } + effect.setMatrix(this._reflectionMatrixName, texture.getReflectionTextureMatrix()); + if (texture.isCube) { + effect.setTexture(this._cubeSamplerName, texture); + } + else { + effect.setTexture(this._2DSamplerName, texture); + } + if (texture.boundingBoxSize) { + const cubeTexture = texture; + effect.setVector3(this._reflectionPositionName, cubeTexture.boundingBoxPosition); + effect.setVector3(this._reflectionSizeName, cubeTexture.boundingBoxSize); + } + } + /** + * Gets the code to inject in the vertex shader + * @param state current state of the node material building + * @returns the shader code + */ + handleVertexSide(state) { + if (this.generateOnlyFragmentCode && state.target === NodeMaterialBlockTargets.Vertex) { + return ""; + } + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + this._define3DName = state._getFreeDefineName("REFLECTIONMAP_3D"); + this._defineCubicName = state._getFreeDefineName("REFLECTIONMAP_CUBIC"); + this._defineSphericalName = state._getFreeDefineName("REFLECTIONMAP_SPHERICAL"); + this._definePlanarName = state._getFreeDefineName("REFLECTIONMAP_PLANAR"); + this._defineProjectionName = state._getFreeDefineName("REFLECTIONMAP_PROJECTION"); + this._defineExplicitName = state._getFreeDefineName("REFLECTIONMAP_EXPLICIT"); + this._defineEquirectangularName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"); + this._defineLocalCubicName = state._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"); + this._defineMirroredEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"); + this._defineEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"); + this._defineSkyboxName = state._getFreeDefineName("REFLECTIONMAP_SKYBOX"); + this._defineOppositeZ = state._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"); + this._reflectionMatrixName = state._getFreeVariableName("reflectionMatrix"); + state._emitUniformFromString(this._reflectionMatrixName, NodeMaterialBlockConnectionPointTypes.Matrix); + let code = ""; + this._worldPositionNameInFragmentOnlyMode = state._getFreeVariableName("worldPosition"); + const worldPosVaryingName = this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : "v_" + this.worldPosition.associatedVariableName; + if (this.generateOnlyFragmentCode || state._emitVaryingFromString(worldPosVaryingName, NodeMaterialBlockConnectionPointTypes.Vector4)) { + if (this.generateOnlyFragmentCode) { + code += `${state._declareLocalVar(worldPosVaryingName, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this.worldPosition.associatedVariableName};\n`; + } + else { + code += `${isWebGPU ? "vertexOutputs." : ""}${worldPosVaryingName} = ${this.worldPosition.associatedVariableName};\n`; + } + } + this._positionUVWName = state._getFreeVariableName("positionUVW"); + this._directionWName = state._getFreeVariableName("directionW"); + if (this.generateOnlyFragmentCode || state._emitVaryingFromString(this._positionUVWName, NodeMaterialBlockConnectionPointTypes.Vector3, this._defineSkyboxName)) { + code += `#ifdef ${this._defineSkyboxName}\n`; + if (this.generateOnlyFragmentCode) { + code += `${state._declareLocalVar(this._positionUVWName, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this.position.associatedVariableName}.xyz;\n`; + } + else { + code += `${isWebGPU ? "vertexOutputs." : ""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\n`; + } + code += `#endif\n`; + } + if (this.generateOnlyFragmentCode || + state._emitVaryingFromString(this._directionWName, NodeMaterialBlockConnectionPointTypes.Vector3, `defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`)) { + code += `#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\n`; + if (this.generateOnlyFragmentCode) { + code += `${state._declareLocalVar(this._directionWName, NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(vec3${state.fSuffix}(${this.world.associatedVariableName} * vec4${state.fSuffix}(${this.position.associatedVariableName}.xyz, 0.0)));\n`; + } + else { + code += `${isWebGPU ? "vertexOutputs." : ""}${this._directionWName} = normalize(vec3${state.fSuffix}(${this.world.associatedVariableName} * vec4${state.fSuffix}(${this.position.associatedVariableName}.xyz, 0.0)));\n`; + } + code += `#endif\n`; + } + return code; + } + /** + * Handles the inits for the fragment code path + * @param state node material build state + */ + handleFragmentSideInits(state) { + state.sharedData.blockingBlocks.push(this); + state.sharedData.textureBlocks.push(this); + // Samplers + this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler"); + state.samplers.push(this._cubeSamplerName); + this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler"); + state.samplers.push(this._2DSamplerName); + state._samplerDeclaration += `#ifdef ${this._define3DName}\n`; + state._emitCubeSampler(this._cubeSamplerName, "", true); + state._samplerDeclaration += `#else\n`; + state._emit2DSampler(this._2DSamplerName, "", true); + state._samplerDeclaration += `#endif\n`; + // Fragment + state.sharedData.blocksWithDefines.push(this); + state.sharedData.bindableBlocks.push(this); + const comments = `//${this.name}`; + state._emitFunctionFromInclude("helperFunctions", comments); + state._emitFunctionFromInclude("reflectionFunction", comments, { + replaceStrings: [ + { search: /vec3 computeReflectionCoords/g, replace: "void DUMMYFUNC" }, + { search: /fn computeReflectionCoords\(worldPos: vec4f,worldNormal: vec3f\)->vec3f/g, replace: "fn DUMMYFUNC()" }, + ], + }); + this._reflectionColorName = state._getFreeVariableName("reflectionColor"); + this._reflectionVectorName = state._getFreeVariableName("reflectionUVW"); + this._reflectionCoordsName = state._getFreeVariableName("reflectionCoords"); + this._reflectionPositionName = state._getFreeVariableName("vReflectionPosition"); + state._emitUniformFromString(this._reflectionPositionName, NodeMaterialBlockConnectionPointTypes.Vector3); + this._reflectionSizeName = state._getFreeVariableName("vReflectionPosition"); + state._emitUniformFromString(this._reflectionSizeName, NodeMaterialBlockConnectionPointTypes.Vector3); + } + /** + * Generates the reflection coords code for the fragment code path + * @param state defines the build state + * @param worldNormalVarName name of the world normal variable + * @param worldPos name of the world position variable. If not provided, will use the world position connected to this block + * @param onlyReflectionVector if true, generates code only for the reflection vector computation, not for the reflection coordinates + * @param doNotEmitInvertZ if true, does not emit the invertZ code + * @returns the shader code + */ + handleFragmentSideCodeReflectionCoords(state, worldNormalVarName, worldPos, onlyReflectionVector = false, doNotEmitInvertZ = false) { + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + const reflectionMatrix = (isWebGPU ? "uniforms." : "") + this._reflectionMatrixName; + const direction = `normalize(${this._directionWName})`; + const positionUVW = `${this._positionUVWName}`; + const vEyePosition = `${this.cameraPosition.associatedVariableName}`; + const view = `${this.view.associatedVariableName}`; + const fragmentInputsPrefix = isWebGPU ? "fragmentInputs." : ""; + if (!worldPos) { + worldPos = this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : `${fragmentInputsPrefix}v_${this.worldPosition.associatedVariableName}`; + } + worldNormalVarName += ".xyz"; + let code = ` + #ifdef ${this._defineMirroredEquirectangularFixedName} + ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeMirroredFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction}); + #endif + + #ifdef ${this._defineEquirectangularFixedName} + ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction}); + #endif + + #ifdef ${this._defineEquirectangularName} + ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}); + #endif + + #ifdef ${this._defineSphericalName} + ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeSphericalCoords(${worldPos}, ${worldNormalVarName}, ${view}, ${reflectionMatrix}); + #endif + + #ifdef ${this._definePlanarName} + ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computePlanarCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}); + #endif + + #ifdef ${this._defineCubicName} + #ifdef ${this._defineLocalCubicName} + ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeCubicLocalCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); + #else + ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeCubicCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}); + #endif + #endif + + #ifdef ${this._defineProjectionName} + ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeProjectionCoords(${worldPos}, ${view}, ${reflectionMatrix}); + #endif + + #ifdef ${this._defineSkyboxName} + ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeSkyBoxCoords(${positionUVW}, ${reflectionMatrix}); + #endif + + #ifdef ${this._defineExplicitName} + ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = vec3(0, 0, 0); + #endif\n`; + if (!doNotEmitInvertZ) { + code += `#ifdef ${this._defineOppositeZ} + ${this._reflectionVectorName}.z *= -1.0; + #endif\n`; + } + if (!onlyReflectionVector) { + code += ` + #ifdef ${this._define3DName} + ${state._declareLocalVar(this._reflectionCoordsName, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this._reflectionVectorName}; + #else + ${state._declareLocalVar(this._reflectionCoordsName, NodeMaterialBlockConnectionPointTypes.Vector2)} = ${this._reflectionVectorName}.xy; + #ifdef ${this._defineProjectionName} + ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; + #endif + ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; + #endif\n`; + } + return code; + } + /** + * Generates the reflection color code for the fragment code path + * @param state defines the build state + * @param lodVarName name of the lod variable + * @param swizzleLookupTexture swizzle to use for the final color variable + * @returns the shader code + */ + handleFragmentSideCodeReflectionColor(state, lodVarName, swizzleLookupTexture = ".rgb") { + let colorType = NodeMaterialBlockConnectionPointTypes.Vector4; + if (swizzleLookupTexture.length === 3) { + colorType = NodeMaterialBlockConnectionPointTypes.Vector3; + } + let code = `${state._declareLocalVar(this._reflectionColorName, colorType)}; + #ifdef ${this._define3DName}\n`; + if (lodVarName) { + code += `${this._reflectionColorName} = ${state._generateTextureSampleCubeLOD(this._reflectionVectorName, this._cubeSamplerName, lodVarName)}${swizzleLookupTexture};\n`; + } + else { + code += `${this._reflectionColorName} = ${state._generateTextureSampleCube(this._reflectionVectorName, this._cubeSamplerName)}${swizzleLookupTexture};\n`; + } + code += ` + #else\n`; + if (lodVarName) { + code += `${this._reflectionColorName} =${state._generateTextureSampleLOD(this._reflectionCoordsName, this._2DSamplerName, lodVarName)}${swizzleLookupTexture};\n`; + } + else { + code += `${this._reflectionColorName} = ${state._generateTextureSample(this._reflectionCoordsName, this._2DSamplerName)}${swizzleLookupTexture};\n`; + } + code += `#endif\n`; + return code; + } + /** + * Generates the code corresponding to the connected output points + * @param state node material build state + * @param varName name of the variable to output + * @returns the shader code + */ + writeOutputs(state, varName) { + let code = ""; + if (state.target === NodeMaterialBlockTargets.Fragment) { + for (const output of this._outputs) { + if (output.hasEndpoints) { + code += `${state._declareOutput(output)} = ${varName}.${output.name};\n`; + } + } + } + return code; + } + _buildBlock(state) { + super._buildBlock(state); + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + if (!this.texture) { + return codeString; + } + if (this.texture.isCube) { + const forcedExtension = this.texture.forcedExtension; + codeString += `${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${forcedExtension ? '"' + forcedExtension + '"' : "null"});\n`; + } + else { + codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\n`; + } + codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + if (this.texture && !this.texture.isRenderTarget) { + serializationObject.texture = this.texture.serialize(); + } + serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime) { + rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; + if (serializationObject.texture.isCube) { + this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl); + } + else { + this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl); + } + } + this.generateOnlyFragmentCode = serializationObject.generateOnlyFragmentCode; + this._setTarget(); + } +} +__decorate([ + editableInPropertyPage("Generate only fragment code", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { + notifiers: { rebuild: true, update: true, onValidation: ReflectionTextureBaseBlock._OnGenerateOnlyFragmentCodeChanged }, + }) +], ReflectionTextureBaseBlock.prototype, "generateOnlyFragmentCode", void 0); +RegisterClass("BABYLON.ReflectionTextureBaseBlock", ReflectionTextureBaseBlock); + +/** + * Block used to read a reflection texture from a sampler + */ +class ReflectionTextureBlock extends ReflectionTextureBaseBlock { + _onGenerateOnlyFragmentCodeChanged() { + if (this.position.isConnected) { + this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode; + Logger.Error("The position input must not be connected to be able to switch!"); + return false; + } + if (this.worldPosition.isConnected) { + this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode; + Logger.Error("The worldPosition input must not be connected to be able to switch!"); + return false; + } + this._setTarget(); + return true; + } + _setTarget() { + super._setTarget(); + this.getInputByName("position").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; + this.getInputByName("worldPosition").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; + } + /** + * Create a new ReflectionTextureBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("position", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment); // Flagging as fragment as the normal can be changed by fragment code + this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Fragment); + this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment); + this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ReflectionTextureBlock"; + } + /** + * Gets the world position input component + */ + get position() { + return this._inputs[0]; + } + /** + * Gets the world position input component + */ + get worldPosition() { + return this._inputs[1]; + } + /** + * Gets the world normal input component + */ + get worldNormal() { + return this._inputs[2]; + } + /** + * Gets the world input component + */ + get world() { + return this._inputs[3]; + } + /** + * Gets the camera (or eye) position component + */ + get cameraPosition() { + return this._inputs[4]; + } + /** + * Gets the view input component + */ + get view() { + return this._inputs[5]; + } + /** + * Gets the rgb output component + */ + get rgb() { + return this._outputs[0]; + } + /** + * Gets the rgba output component + */ + get rgba() { + return this._outputs[1]; + } + /** + * Gets the r output component + */ + get r() { + return this._outputs[2]; + } + /** + * Gets the g output component + */ + get g() { + return this._outputs[3]; + } + /** + * Gets the b output component + */ + get b() { + return this._outputs[4]; + } + /** + * Gets the a output component + */ + get a() { + return this._outputs[5]; + } + autoConfigure(material, additionalFilteringInfo = () => true) { + super.autoConfigure(material); + if (!this.cameraPosition.isConnected) { + let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition && additionalFilteringInfo(b)); + if (!cameraPositionInput) { + cameraPositionInput = new InputBlock("cameraPosition"); + cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition); + } + cameraPositionInput.output.connectTo(this.cameraPosition); + } + } + _buildBlock(state) { + super._buildBlock(state); + if (!this.texture) { + state.compilationString += this.writeOutputs(state, `vec4${state.fSuffix}(0.)`); + return this; + } + if (state.target !== NodeMaterialBlockTargets.Fragment) { + state.compilationString += this.handleVertexSide(state); + return this; + } + if (this.generateOnlyFragmentCode) { + state.compilationString += this.handleVertexSide(state); + } + this.handleFragmentSideInits(state); + const normalWUnit = state._getFreeVariableName("normalWUnit"); + state.compilationString += `${state._declareLocalVar(normalWUnit, NodeMaterialBlockConnectionPointTypes.Vector4)} = normalize(${this.worldNormal.associatedVariableName});\n`; + state.compilationString += this.handleFragmentSideCodeReflectionCoords(state, normalWUnit); + state.compilationString += this.handleFragmentSideCodeReflectionColor(state, undefined, ""); + state.compilationString += this.writeOutputs(state, this._reflectionColorName); + return this; + } +} +RegisterClass("BABYLON.ReflectionTextureBlock", ReflectionTextureBlock); + +/** + * Block used to retrieve the depth (zbuffer) of the scene + * @since 5.0.0 + */ +class SceneDepthBlock extends NodeMaterialBlock { + /** + * Create a new SceneDepthBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.VertexAndFragment); + /** + * Defines if the depth renderer should be setup in non linear mode + */ + this.useNonLinearDepth = false; + /** + * Defines if the depth renderer should be setup in camera space Z mode (if set, useNonLinearDepth has no effect) + */ + this.storeCameraSpaceZ = false; + /** + * Defines if the depth renderer should be setup in full 32 bits float mode + */ + this.force32itsFloat = false; + this._isUnique = true; + this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment); + this.registerOutput("depth", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + this._inputs[0]._prioritizeVertex = false; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SceneDepthBlock"; + } + /** + * Gets the uv input component + */ + get uv() { + return this._inputs[0]; + } + /** + * Gets the depth output component + */ + get depth() { + return this._outputs[0]; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("textureSampler"); + } + get target() { + if (!this.uv.isConnected) { + return NodeMaterialBlockTargets.VertexAndFragment; + } + if (this.uv.sourceBlock.isInput) { + return NodeMaterialBlockTargets.VertexAndFragment; + } + return NodeMaterialBlockTargets.Fragment; + } + _getTexture(scene) { + const depthRenderer = scene.enableDepthRenderer(undefined, this.useNonLinearDepth, this.force32itsFloat, undefined, this.storeCameraSpaceZ); + return depthRenderer.getDepthMap(); + } + bind(effect, nodeMaterial) { + const texture = this._getTexture(nodeMaterial.getScene()); + effect.setTexture(this._samplerName, texture); + } + _injectVertexCode(state) { + const uvInput = this.uv; + if (uvInput.connectedPoint.ownerBlock.isInput) { + const uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock; + if (!uvInputOwnerBlock.isAttribute) { + state._emitUniformFromString(uvInput.associatedVariableName, uvInput.type === NodeMaterialBlockConnectionPointTypes.Vector3 + ? NodeMaterialBlockConnectionPointTypes.Vector3 + : uvInput.type === NodeMaterialBlockConnectionPointTypes.Vector4 + ? NodeMaterialBlockConnectionPointTypes.Vector4 + : NodeMaterialBlockConnectionPointTypes.Vector2); + } + } + this._mainUVName = "vMain" + uvInput.associatedVariableName; + state._emitVaryingFromString(this._mainUVName, NodeMaterialBlockConnectionPointTypes.Vector2); + state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\n`; + if (!this._outputs.some((o) => o.isConnectedInVertexShader)) { + return; + } + this._writeTextureRead(state, true); + for (const output of this._outputs) { + if (output.hasEndpoints) { + this._writeOutput(state, output, "r", true); + } + } + } + _writeTextureRead(state, vertexMode = false) { + const uvInput = this.uv; + if (vertexMode) { + if (state.target === NodeMaterialBlockTargets.Fragment) { + return; + } + const textureReadFunc = state.shaderLanguage === 0 /* ShaderLanguage.GLSL */ + ? `texture2D(${this._samplerName},` + : `textureSampleLevel(${this._samplerName}, ${this._samplerName + `Sampler`},`; + const complement = state.shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? "" : ", 0"; + state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)}= ${textureReadFunc} ${uvInput.associatedVariableName}.xy${complement});\n`; + return; + } + const textureReadFunc = state.shaderLanguage === 0 /* ShaderLanguage.GLSL */ + ? `texture2D(${this._samplerName},` + : `textureSample(${this._samplerName}, ${this._samplerName + `Sampler`},`; + if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { + state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${textureReadFunc} ${uvInput.associatedVariableName}.xy);\n`; + return; + } + state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${textureReadFunc} ${this._mainUVName});\n`; + } + _writeOutput(state, output, swizzle, vertexMode = false) { + if (vertexMode) { + if (state.target === NodeMaterialBlockTargets.Fragment) { + return; + } + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};\n`; + return; + } + if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};\n`; + return; + } + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};\n`; + } + _buildBlock(state) { + super._buildBlock(state); + this._samplerName = state._getFreeVariableName(this.name + "Sampler"); + this._tempTextureRead = state._getFreeVariableName("tempTextureRead"); + if (state.sharedData.bindableBlocks.indexOf(this) < 0) { + state.sharedData.bindableBlocks.push(this); + } + if (state.target !== NodeMaterialBlockTargets.Fragment) { + // Vertex + state._emit2DSampler(this._samplerName); + this._injectVertexCode(state); + return; + } + // Fragment + if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) { + return; + } + state._emit2DSampler(this._samplerName); + this._writeTextureRead(state); + for (const output of this._outputs) { + if (output.hasEndpoints) { + this._writeOutput(state, output, "r"); + } + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.useNonLinearDepth = this.useNonLinearDepth; + serializationObject.storeCameraSpaceZ = this.storeCameraSpaceZ; + serializationObject.force32itsFloat = this.force32itsFloat; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.useNonLinearDepth = serializationObject.useNonLinearDepth; + this.storeCameraSpaceZ = !!serializationObject.storeCameraSpaceZ; + this.force32itsFloat = serializationObject.force32itsFloat; + } +} +__decorate([ + editableInPropertyPage("Use non linear depth", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { + embedded: true, + notifiers: { + activatePreviewCommand: true, + callback: (scene, block) => { + const sceneDepthBlock = block; + let retVal = false; + if (sceneDepthBlock.useNonLinearDepth) { + sceneDepthBlock.storeCameraSpaceZ = false; + retVal = true; + } + if (scene) { + scene.disableDepthRenderer(); + } + return retVal; + }, + }, + }) +], SceneDepthBlock.prototype, "useNonLinearDepth", void 0); +__decorate([ + editableInPropertyPage("Store Camera space Z", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { + notifiers: { + activatePreviewCommand: true, + callback: (scene, block) => { + const sceneDepthBlock = block; + let retVal = false; + if (sceneDepthBlock.storeCameraSpaceZ) { + sceneDepthBlock.useNonLinearDepth = false; + retVal = true; + } + if (scene) { + scene.disableDepthRenderer(); + } + return retVal; + }, + }, + }) +], SceneDepthBlock.prototype, "storeCameraSpaceZ", void 0); +__decorate([ + editableInPropertyPage("Force 32 bits float", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { + notifiers: { activatePreviewCommand: true, callback: (scene) => scene?.disableDepthRenderer() }, + }) +], SceneDepthBlock.prototype, "force32itsFloat", void 0); +RegisterClass("BABYLON.SceneDepthBlock", SceneDepthBlock); + +/** + * Block used to implement clip planes + */ +class ClipPlanesBlock extends NodeMaterialBlock { + /** + * Create a new ClipPlanesBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.VertexAndFragment, true); + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ClipPlanesBlock"; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("vClipPlane"); + state._excludeVariableName("fClipDistance"); + state._excludeVariableName("vClipPlane2"); + state._excludeVariableName("fClipDistance2"); + state._excludeVariableName("vClipPlane3"); + state._excludeVariableName("fClipDistance3"); + state._excludeVariableName("vClipPlane4"); + state._excludeVariableName("fClipDistance4"); + state._excludeVariableName("vClipPlane5"); + state._excludeVariableName("fClipDistance5"); + state._excludeVariableName("vClipPlane6"); + state._excludeVariableName("fClipDistance6"); + this._initShaderSourceAsync(state.shaderLanguage); + } + async _initShaderSourceAsync(shaderLanguage) { + this._codeIsReady = false; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([ + Promise.resolve().then(() => clipPlaneFragment), + Promise.resolve().then(() => clipPlaneFragmentDeclaration), + Promise.resolve().then(() => clipPlaneVertex), + Promise.resolve().then(() => clipPlaneVertexDeclaration), + ]); + } + else { + await Promise.all([ + Promise.resolve().then(() => clipPlaneFragment$2), + Promise.resolve().then(() => clipPlaneFragmentDeclaration$2), + Promise.resolve().then(() => clipPlaneVertex$2), + Promise.resolve().then(() => clipPlaneVertexDeclaration$2), + ]); + } + this._codeIsReady = true; + this.onCodeIsReadyObservable.notifyObservers(this); + } + /** + * Gets the worldPosition input component + */ + get worldPosition() { + return this._inputs[0]; + } + get target() { + return NodeMaterialBlockTargets.VertexAndFragment; + } + set target(value) { } + prepareDefines(mesh, nodeMaterial, defines) { + const scene = mesh.getScene(); + const useClipPlane1 = (nodeMaterial.clipPlane ?? scene.clipPlane) ? true : false; + const useClipPlane2 = (nodeMaterial.clipPlane2 ?? scene.clipPlane2) ? true : false; + const useClipPlane3 = (nodeMaterial.clipPlane3 ?? scene.clipPlane3) ? true : false; + const useClipPlane4 = (nodeMaterial.clipPlane4 ?? scene.clipPlane4) ? true : false; + const useClipPlane5 = (nodeMaterial.clipPlane5 ?? scene.clipPlane5) ? true : false; + const useClipPlane6 = (nodeMaterial.clipPlane6 ?? scene.clipPlane6) ? true : false; + defines.setValue("CLIPPLANE", useClipPlane1, true); + defines.setValue("CLIPPLANE2", useClipPlane2, true); + defines.setValue("CLIPPLANE3", useClipPlane3, true); + defines.setValue("CLIPPLANE4", useClipPlane4, true); + defines.setValue("CLIPPLANE5", useClipPlane5, true); + defines.setValue("CLIPPLANE6", useClipPlane6, true); + } + bind(effect, nodeMaterial, mesh) { + if (!mesh) { + return; + } + const scene = mesh.getScene(); + bindClipPlane(effect, nodeMaterial, scene); + } + _buildBlock(state) { + super._buildBlock(state); + const comments = `//${this.name}`; + if (state.target !== NodeMaterialBlockTargets.Fragment) { + // Vertex + const worldPos = this.worldPosition; + state._emitFunctionFromInclude("clipPlaneVertexDeclaration", comments, { + replaceStrings: [{ search: /uniform vec4 vClipPlane\d*;/g, replace: "" }], + }); + state.compilationString += state._emitCodeFromInclude("clipPlaneVertex", comments, { + replaceStrings: [{ search: /worldPos/g, replace: worldPos.associatedVariableName }], + }); + state._emitUniformFromString("vClipPlane", NodeMaterialBlockConnectionPointTypes.Vector4); + state._emitUniformFromString("vClipPlane2", NodeMaterialBlockConnectionPointTypes.Vector4); + state._emitUniformFromString("vClipPlane3", NodeMaterialBlockConnectionPointTypes.Vector4); + state._emitUniformFromString("vClipPlane4", NodeMaterialBlockConnectionPointTypes.Vector4); + state._emitUniformFromString("vClipPlane5", NodeMaterialBlockConnectionPointTypes.Vector4); + state._emitUniformFromString("vClipPlane6", NodeMaterialBlockConnectionPointTypes.Vector4); + return; + } + // Fragment + state.sharedData.bindableBlocks.push(this); + state.sharedData.blocksWithDefines.push(this); + state._emitFunctionFromInclude("clipPlaneFragmentDeclaration", comments); + state.compilationString += state._emitCodeFromInclude("clipPlaneFragment", comments); + return this; + } +} +RegisterClass("BABYLON.ClipPlanesBlock", ClipPlanesBlock); + +/** + * Block used to read from prepass textures + */ +class PrePassTextureBlock extends NodeMaterialBlock { + /** + * The texture associated with the node is the prepass texture + */ + get texture() { + return null; + } + set texture(value) { + return; + } + /** + * Creates a new PrePassTextureBlock + * @param name defines the block name + * @param target defines the target of that block (VertexAndFragment by default) + */ + constructor(name, target = NodeMaterialBlockTargets.VertexAndFragment) { + super(name, target, false); + this.registerOutput("position", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("position", this, 1 /* NodeMaterialConnectionPointDirection.Output */, ImageSourceBlock, "ImageSourceBlock")); + this.registerOutput("localPosition", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("localPosition", this, 1 /* NodeMaterialConnectionPointDirection.Output */, ImageSourceBlock, "ImageSourceBlock")); + this.registerOutput("depth", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("depth", this, 1 /* NodeMaterialConnectionPointDirection.Output */, ImageSourceBlock, "ImageSourceBlock")); + this.registerOutput("screenDepth", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("screenDepth", this, 1 /* NodeMaterialConnectionPointDirection.Output */, ImageSourceBlock, "ImageSourceBlock")); + this.registerOutput("normal", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("normal", this, 1 /* NodeMaterialConnectionPointDirection.Output */, ImageSourceBlock, "ImageSourceBlock")); + this.registerOutput("worldNormal", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("worldNormal", this, 1 /* NodeMaterialConnectionPointDirection.Output */, ImageSourceBlock, "ImageSourceBlock")); + } + /** + * Returns the sampler name associated with the node connection point + * @param output defines the connection point to get the associated sampler name + * @returns + */ + getSamplerName(output) { + if (output === this._outputs[0]) { + return this._positionSamplerName; + } + if (output === this._outputs[1]) { + return this._localPositionSamplerName; + } + if (output === this._outputs[2]) { + return this._depthSamplerName; + } + if (output === this._outputs[3]) { + return this._screenSpaceDepthSamplerName; + } + if (output === this._outputs[4]) { + return this._normalSamplerName; + } + if (output === this._outputs[5]) { + return this._worldNormalSamplerName; + } + return ""; + } + /** + * Gets the position texture + */ + get position() { + return this._outputs[0]; + } + /** + * Gets the local position texture + */ + get localPosition() { + return this._outputs[1]; + } + /** + * Gets the depth texture + */ + get depth() { + return this._outputs[2]; + } + /** + * Gets the screen depth texture + */ + get screenDepth() { + return this._outputs[3]; + } + /** + * Gets the normal texture + */ + get normal() { + return this._outputs[4]; + } + /** + * Gets the world normal texture + */ + get worldNormal() { + return this._outputs[5]; + } + /** + * Gets the sampler name associated with this image source + */ + get positionSamplerName() { + return this._positionSamplerName; + } + /** + * Gets the sampler name associated with this image source + */ + get localPositionSamplerName() { + return this._localPositionSamplerName; + } + /** + * Gets the sampler name associated with this image source + */ + get normalSamplerName() { + return this._normalSamplerName; + } + /** + * Gets the sampler name associated with this image source + */ + get worldNormalSamplerName() { + return this._worldNormalSamplerName; + } + /** + * Gets the sampler name associated with this image source + */ + get depthSamplerName() { + return this._depthSamplerName; + } + /** + * Gets the sampler name associated with this image source + */ + get linearDepthSamplerName() { + return this._screenSpaceDepthSamplerName; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "PrePassTextureBlock"; + } + _buildBlock(state) { + super._buildBlock(state); + if (state.target === NodeMaterialBlockTargets.Vertex) { + return; + } + this._positionSamplerName = "prepassPositionSampler"; + this._depthSamplerName = "prepassDepthSampler"; + this._normalSamplerName = "prepassNormalSampler"; + this._worldNormalSamplerName = "prepassWorldNormalSampler"; + this._localPositionSamplerName = "prepassLocalPositionSampler"; + this._screenSpaceDepthSamplerName = "prepassScreenSpaceDepthSampler"; + // Unique sampler names for every prepasstexture block + state.sharedData.variableNames.prepassPositionSampler = 0; + state.sharedData.variableNames.prepassDepthSampler = 0; + state.sharedData.variableNames.prepassNormalSampler = 0; + state.sharedData.variableNames.prepassWorldNormalSampler = 0; + state.sharedData.variableNames.prepassLocalPositionSampler = 0; + state.sharedData.variableNames.prepassScreenSpaceDepthSampler = 0; + // Declarations + state.sharedData.textureBlocks.push(this); + state.sharedData.bindableBlocks.push(this); + if (this.position.isConnected) { + state._emit2DSampler(this._positionSamplerName); + } + if (this.depth.isConnected) { + state._emit2DSampler(this._depthSamplerName); + } + if (this.normal.isConnected) { + state._emit2DSampler(this._normalSamplerName); + } + if (this.worldNormal.isConnected) { + state._emit2DSampler(this._worldNormalSamplerName); + } + if (this.localPosition.isConnected) { + state._emit2DSampler(this._localPositionSamplerName); + } + if (this.screenDepth.isConnected) { + state._emit2DSampler(this._screenSpaceDepthSamplerName); + } + return this; + } + bind(effect, nodeMaterial) { + const scene = nodeMaterial.getScene(); + const prePassRenderer = scene.enablePrePassRenderer(); + if (!prePassRenderer) { + return; + } + const sceneRT = prePassRenderer.defaultRT; + if (!sceneRT.textures) { + return; + } + if (this.position.isConnected) { + effect.setTexture(this._positionSamplerName, sceneRT.textures[prePassRenderer.getIndex(1)]); + } + if (this.localPosition.isConnected) { + effect.setTexture(this._localPositionSamplerName, sceneRT.textures[prePassRenderer.getIndex(9)]); + } + if (this.depth.isConnected) { + effect.setTexture(this._depthSamplerName, sceneRT.textures[prePassRenderer.getIndex(5)]); + } + if (this.screenDepth.isConnected) { + effect.setTexture(this._screenSpaceDepthSamplerName, sceneRT.textures[prePassRenderer.getIndex(10)]); + } + if (this.normal.isConnected) { + effect.setTexture(this._normalSamplerName, sceneRT.textures[prePassRenderer.getIndex(6)]); + } + if (this.worldNormal.isConnected) { + effect.setTexture(this._worldNormalSamplerName, sceneRT.textures[prePassRenderer.getIndex(8)]); + } + } +} +RegisterClass("BABYLON.PrePassTextureBlock", PrePassTextureBlock); + +/** + * Defines a block used to teleport a value to an endpoint + */ +class NodeMaterialTeleportInBlock extends NodeMaterialBlock { + /** Gets the list of attached endpoints */ + get endpoints() { + return this._endpoints; + } + /** + * Gets or sets the target of the block + */ + get target() { + const input = this._inputs[0]; + if (input.isConnected) { + const block = input.connectedPoint.ownerBlock; + if (block.target !== NodeMaterialBlockTargets.VertexAndFragment) { + return block.target; + } + if (input.connectedPoint.target !== NodeMaterialBlockTargets.VertexAndFragment) { + return input.connectedPoint.target; + } + } + return this._target; + } + set target(value) { + if ((this._target & value) !== 0) { + return; + } + this._target = value; + } + /** + * Create a new NodeMaterialTeleportInBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this._endpoints = []; + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeMaterialTeleportInBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * @returns a boolean indicating that this connection will be used in the fragment shader + */ + isConnectedInFragmentShader() { + return this.endpoints.some((e) => e.output.isConnectedInFragmentShader); + } + _dumpCode(uniqueNames, alreadyDumped) { + let codeString = super._dumpCode(uniqueNames, alreadyDumped); + for (const endpoint of this.endpoints) { + if (alreadyDumped.indexOf(endpoint) === -1) { + codeString += endpoint._dumpCode(uniqueNames, alreadyDumped); + } + } + return codeString; + } + /** + * Checks if the current block is an ancestor of a given block + * @param block defines the potential descendant block to check + * @returns true if block is a descendant + */ + isAnAncestorOf(block) { + for (const endpoint of this.endpoints) { + if (endpoint === block) { + return true; + } + if (endpoint.isAnAncestorOf(block)) { + return true; + } + } + return false; + } + /** + * Add an enpoint to this block + * @param endpoint define the endpoint to attach to + */ + attachToEndpoint(endpoint) { + endpoint.detach(); + this._endpoints.push(endpoint); + endpoint._entryPoint = this; + endpoint._outputs[0]._typeConnectionSource = this._inputs[0]; + endpoint._tempEntryPointUniqueId = null; + endpoint.name = "> " + this.name; + this._outputs = this._endpoints.map((e) => e.output); + } + /** + * Remove enpoint from this block + * @param endpoint define the endpoint to remove + */ + detachFromEndpoint(endpoint) { + const index = this._endpoints.indexOf(endpoint); + if (index !== -1) { + this._endpoints.splice(index, 1); + endpoint._outputs[0]._typeConnectionSource = null; + endpoint._entryPoint = null; + this._outputs = this._endpoints.map((e) => e.output); + } + } + /** + * Release resources + */ + dispose() { + super.dispose(); + for (const endpoint of this._endpoints) { + this.detachFromEndpoint(endpoint); + } + this._endpoints = []; + } +} +RegisterClass("BABYLON.NodeMaterialTeleportInBlock", NodeMaterialTeleportInBlock); + +/** + * Defines a block used to receive a value from a teleport entry point + */ +class NodeMaterialTeleportOutBlock extends NodeMaterialBlock { + /** + * Create a new TeleportOutBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** @internal */ + this._entryPoint = null; + /** @internal */ + this._tempEntryPointUniqueId = null; + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + } + /** + * Gets the entry point + */ + get entryPoint() { + return this._entryPoint; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeMaterialTeleportOutBlock"; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets or sets the target of the block + */ + get target() { + return this._entryPoint ? this._entryPoint.target : this._target; + } + set target(value) { + if ((this._target & value) !== 0) { + return; + } + this._target = value; + } + /** Detach from entry point */ + detach() { + if (!this._entryPoint) { + return; + } + this._entryPoint.detachFromEndpoint(this); + } + _buildBlock(state) { + super._buildBlock(state); + if (this.entryPoint) { + state.compilationString += state._declareOutput(this.output) + ` = ${this.entryPoint.input.associatedVariableName};\n`; + } + } + /** + * Clone the current block to a new identical block + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures and relative dependencies + * @returns a copy of the current block + */ + clone(scene, rootUrl = "") { + const clone = super.clone(scene, rootUrl); + if (this.entryPoint) { + this.entryPoint.attachToEndpoint(clone); + } + return clone; + } + _customBuildStep(state, activeBlocks) { + if (this.entryPoint) { + this.entryPoint.build(state, activeBlocks); + } + } + _dumpCode(uniqueNames, alreadyDumped) { + let codeString = ""; + if (this.entryPoint) { + if (alreadyDumped.indexOf(this.entryPoint) === -1) { + codeString += this.entryPoint._dumpCode(uniqueNames, alreadyDumped); + } + } + return codeString + super._dumpCode(uniqueNames, alreadyDumped); + } + _dumpCodeForOutputConnections(alreadyDumped) { + let codeString = super._dumpCodeForOutputConnections(alreadyDumped); + if (this.entryPoint) { + codeString += this.entryPoint._dumpCodeForOutputConnections(alreadyDumped); + } + return codeString; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + if (this.entryPoint) { + codeString += `${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`; + } + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.entryPoint = this.entryPoint?.uniqueId ?? ""; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this._tempEntryPointUniqueId = serializationObject.entryPoint; + } +} +RegisterClass("BABYLON.NodeMaterialTeleportOutBlock", NodeMaterialTeleportOutBlock); + +/** + * Block used to add 2 vectors + */ +class AddBlock extends BaseMathBlock { + /** + * Creates a new AddBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "AddBlock"; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\n`; + return this; + } +} +RegisterClass("BABYLON.AddBlock", AddBlock); + +/** + * Block used to scale a vector by a float + */ +class ScaleBlock extends NodeMaterialBlock { + /** + * Creates a new ScaleBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("factor", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ScaleBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the factor input component + */ + get factor() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};\n`; + return this; + } +} +RegisterClass("BABYLON.ScaleBlock", ScaleBlock); + +/** + * Block used to clamp a float + */ +class ClampBlock extends NodeMaterialBlock { + /** + * Creates a new ClampBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** Gets or sets the minimum range */ + this.minimum = 0.0; + /** Gets or sets the maximum range */ + this.maximum = 1.0; + this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ClampBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const cast = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? state._getShaderType(this.value.type) : ""; + state.compilationString += + state._declareOutput(output) + + ` = clamp(${this.value.associatedVariableName}, ${cast}(${this._writeFloat(this.minimum)}), ${cast}(${this._writeFloat(this.maximum)}));\n`; + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.minimum = ${this.minimum};\n`; + codeString += `${this._codeVariableName}.maximum = ${this.maximum};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.minimum = this.minimum; + serializationObject.maximum = this.maximum; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.minimum = serializationObject.minimum; + this.maximum = serializationObject.maximum; + } +} +__decorate([ + editableInPropertyPage("Minimum", 1 /* PropertyTypeForEdition.Float */, undefined, { embedded: true }) +], ClampBlock.prototype, "minimum", void 0); +__decorate([ + editableInPropertyPage("Maximum", 1 /* PropertyTypeForEdition.Float */, undefined, { embedded: true }) +], ClampBlock.prototype, "maximum", void 0); +RegisterClass("BABYLON.ClampBlock", ClampBlock); + +/** + * Block used to apply a cross product between 2 vectors + */ +class CrossBlock extends NodeMaterialBlock { + /** + * Creates a new CrossBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3); + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2); + this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "CrossBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\n`; + return this; + } +} +RegisterClass("BABYLON.CrossBlock", CrossBlock); + +/** + * Custom block created from user-defined json + */ +class CustomBlock extends NodeMaterialBlock { + /** + * Gets or sets the options for this custom block + */ + get options() { + return this._options; + } + set options(options) { + this._deserializeOptions(options); + } + /** + * Creates a new CustomBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "CustomBlock"; + } + _buildBlock(state) { + super._buildBlock(state); + let code = this._code; + let functionName = this._options.functionName; + // Replace the TYPE_XXX placeholders (if any) + this._inputs.forEach((input) => { + const rexp = new RegExp("\\{TYPE_" + input.name + "\\}", "gm"); + const type = state._getGLType(input.type); + code = code.replace(rexp, type); + functionName = functionName.replace(rexp, type); + }); + this._outputs.forEach((output) => { + const rexp = new RegExp("\\{TYPE_" + output.name + "\\}", "gm"); + const type = state._getGLType(output.type); + code = code.replace(rexp, type); + functionName = functionName.replace(rexp, type); + }); + state._emitFunction(functionName, code, ""); + // Declare the output variables + this._outputs.forEach((output) => { + state.compilationString += state._declareOutput(output) + ";\n"; + }); + // Generate the function call + state.compilationString += functionName + "("; + let hasInput = false; + this._inputs.forEach((input, index) => { + if (index > 0) { + state.compilationString += ", "; + } + if (this._inputSamplers && this._inputSamplers.indexOf(input.name) !== -1) { + state.compilationString += input.connectedPoint?.ownerBlock?.samplerName ?? input.associatedVariableName; + } + else { + state.compilationString += input.associatedVariableName; + } + hasInput = true; + }); + this._outputs.forEach((output, index) => { + if (index > 0 || hasInput) { + state.compilationString += ", "; + } + state.compilationString += output.associatedVariableName; + }); + state.compilationString += ");\n"; + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.options = ${JSON.stringify(this._options)};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.options = this._options; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + this._deserializeOptions(serializationObject.options); + super._deserialize(serializationObject, scene, rootUrl); + } + _deserializeOptions(options) { + this._options = options; + this._code = options.code.join("\n") + "\n"; + this.name = this.name || options.name; + this.target = NodeMaterialBlockTargets[options.target]; + options.inParameters?.forEach((input, index) => { + const type = NodeMaterialBlockConnectionPointTypes[input.type]; + if (input.type === "sampler2D" || input.type === "samplerCube") { + this._inputSamplers = this._inputSamplers || []; + this._inputSamplers.push(input.name); + this.registerInput(input.name, NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(input.name, this, 0 /* NodeMaterialConnectionPointDirection.Input */, ImageSourceBlock, "ImageSourceBlock")); + } + else { + this.registerInput(input.name, type); + } + Object.defineProperty(this, input.name, { + get: function () { + return this._inputs[index]; + }, + enumerable: true, + configurable: true, + }); + }); + options.outParameters?.forEach((output, index) => { + this.registerOutput(output.name, NodeMaterialBlockConnectionPointTypes[output.type]); + Object.defineProperty(this, output.name, { + get: function () { + return this._outputs[index]; + }, + enumerable: true, + configurable: true, + }); + if (output.type === "BasedOnInput") { + this._outputs[index]._typeConnectionSource = this._findInputByName(output.typeFromInput)[0]; + } + }); + options.inLinkedConnectionTypes?.forEach((connection) => { + this._linkConnectionTypes(this._findInputByName(connection.input1)[1], this._findInputByName(connection.input2)[1]); + }); + } + _findInputByName(name) { + if (!name) { + return null; + } + for (let i = 0; i < this._inputs.length; i++) { + if (this._inputs[i].name === name) { + return [this._inputs[i], i]; + } + } + return null; + } +} +RegisterClass("BABYLON.CustomBlock", CustomBlock); + +/** + * Block used to apply a dot product between 2 vectors + */ +class DotBlock extends NodeMaterialBlock { + /** + * Creates a new DotBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "DotBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = dot(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.DotBlock", DotBlock); + +/** + * Block used to normalize a vector + */ +class NormalizeBlock extends NodeMaterialBlock { + /** + * Creates a new NormalizeBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NormalizeBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const input = this._inputs[0]; + state.compilationString += state._declareOutput(output) + ` = normalize(${input.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.NormalizeBlock", NormalizeBlock); + +/** + * Block used to create a Color3/4 out of individual inputs (one for each component) + */ +class ColorMergerBlock extends NodeMaterialBlock { + /** + * Create a new ColorMergerBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Gets or sets the swizzle for r (meaning which component to affect to the output.r) + */ + this.rSwizzle = "r"; + /** + * Gets or sets the swizzle for g (meaning which component to affect to the output.g) + */ + this.gSwizzle = "g"; + /** + * Gets or sets the swizzle for b (meaning which component to affect to the output.b) + */ + this.bSwizzle = "b"; + /** + * Gets or sets the swizzle for a (meaning which component to affect to the output.a) + */ + this.aSwizzle = "a"; + this.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, true); + this.registerInput("r", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("g", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("b", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4); + this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ColorMergerBlock"; + } + /** + * Gets the rgb component (input) + */ + get rgbIn() { + return this._inputs[0]; + } + /** + * Gets the r component (input) + */ + get r() { + return this._inputs[1]; + } + /** + * Gets the g component (input) + */ + get g() { + return this._inputs[2]; + } + /** + * Gets the b component (input) + */ + get b() { + return this._inputs[3]; + } + /** + * Gets the a component (input) + */ + get a() { + return this._inputs[4]; + } + /** + * Gets the rgba component (output) + */ + get rgba() { + return this._outputs[0]; + } + /** + * Gets the rgb component (output) + */ + get rgbOut() { + return this._outputs[1]; + } + /** + * Gets the rgb component (output) + * @deprecated Please use rgbOut instead. + */ + get rgb() { + return this.rgbOut; + } + _inputRename(name) { + if (name === "rgb ") { + return "rgbIn"; + } + return name; + } + _buildSwizzle(len) { + const swizzle = this.rSwizzle + this.gSwizzle + this.bSwizzle + this.aSwizzle; + return "." + swizzle.substring(0, len); + } + _buildBlock(state) { + super._buildBlock(state); + const rInput = this.r; + const gInput = this.g; + const bInput = this.b; + const aInput = this.a; + const rgbInput = this.rgbIn; + const color4Output = this._outputs[0]; + const color3Output = this._outputs[1]; + const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4); + const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3); + if (rgbInput.isConnected) { + if (color4Output.hasEndpoints) { + state.compilationString += + state._declareOutput(color4Output) + + ` = ${vec4}(${rgbInput.associatedVariableName}, ${aInput.isConnected ? this._writeVariable(aInput) : "0.0"})${this._buildSwizzle(4)};\n`; + } + if (color3Output.hasEndpoints) { + state.compilationString += state._declareOutput(color3Output) + ` = ${rgbInput.associatedVariableName}${this._buildSwizzle(3)};\n`; + } + } + else { + if (color4Output.hasEndpoints) { + state.compilationString += + state._declareOutput(color4Output) + + ` = ${vec4}(${rInput.isConnected ? this._writeVariable(rInput) : "0.0"}, ${gInput.isConnected ? this._writeVariable(gInput) : "0.0"}, ${bInput.isConnected ? this._writeVariable(bInput) : "0.0"}, ${aInput.isConnected ? this._writeVariable(aInput) : "0.0"})${this._buildSwizzle(4)};\n`; + } + if (color3Output.hasEndpoints) { + state.compilationString += + state._declareOutput(color3Output) + + ` = ${vec3}(${rInput.isConnected ? this._writeVariable(rInput) : "0.0"}, ${gInput.isConnected ? this._writeVariable(gInput) : "0.0"}, ${bInput.isConnected ? this._writeVariable(bInput) : "0.0"})${this._buildSwizzle(3)};\n`; + } + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.rSwizzle = this.rSwizzle; + serializationObject.gSwizzle = this.gSwizzle; + serializationObject.bSwizzle = this.bSwizzle; + serializationObject.aSwizzle = this.aSwizzle; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.rSwizzle = serializationObject.rSwizzle ?? "r"; + this.gSwizzle = serializationObject.gSwizzle ?? "g"; + this.bSwizzle = serializationObject.bSwizzle ?? "b"; + this.aSwizzle = serializationObject.aSwizzle ?? "a"; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.rSwizzle = "${this.rSwizzle}";\n`; + codeString += `${this._codeVariableName}.gSwizzle = "${this.gSwizzle}";\n`; + codeString += `${this._codeVariableName}.bSwizzle = "${this.bSwizzle}";\n`; + codeString += `${this._codeVariableName}.aSwizzle = "${this.aSwizzle}";\n`; + return codeString; + } +} +RegisterClass("BABYLON.ColorMergerBlock", ColorMergerBlock); + +/** + * Block used to expand a Vector3/4 into 4 outputs (one for each component) + */ +class VectorSplitterBlock extends NodeMaterialBlock { + /** + * Create a new VectorSplitterBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4, true); + this.registerInput("xyz ", NodeMaterialBlockConnectionPointTypes.Vector3, true); + this.registerInput("xy ", NodeMaterialBlockConnectionPointTypes.Vector2, true); + this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerOutput("zw", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("z", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("w", NodeMaterialBlockConnectionPointTypes.Float); + this.inputsAreExclusive = true; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "VectorSplitterBlock"; + } + /** + * Gets the xyzw component (input) + */ + get xyzw() { + return this._inputs[0]; + } + /** + * Gets the xyz component (input) + */ + get xyzIn() { + return this._inputs[1]; + } + /** + * Gets the xy component (input) + */ + get xyIn() { + return this._inputs[2]; + } + /** + * Gets the xyz component (output) + */ + get xyzOut() { + return this._outputs[0]; + } + /** + * Gets the xy component (output) + */ + get xyOut() { + return this._outputs[1]; + } + /** + * Gets the zw component (output) + */ + get zw() { + return this._outputs[2]; + } + /** + * Gets the x component (output) + */ + get x() { + return this._outputs[3]; + } + /** + * Gets the y component (output) + */ + get y() { + return this._outputs[4]; + } + /** + * Gets the z component (output) + */ + get z() { + return this._outputs[5]; + } + /** + * Gets the w component (output) + */ + get w() { + return this._outputs[6]; + } + _inputRename(name) { + switch (name) { + case "xy ": + return "xyIn"; + case "xyz ": + return "xyzIn"; + default: + return name; + } + } + _outputRename(name) { + switch (name) { + case "xy": + return "xyOut"; + case "xyz": + return "xyzOut"; + default: + return name; + } + } + _buildBlock(state) { + super._buildBlock(state); + const input = this.xyzw.isConnected ? this.xyzw : this.xyzIn.isConnected ? this.xyzIn : this.xyIn; + const xyzOutput = this._outputs[0]; + const xyOutput = this._outputs[1]; + const zwOutput = this._outputs[2]; + const xOutput = this._outputs[3]; + const yOutput = this._outputs[4]; + const zOutput = this._outputs[5]; + const wOutput = this._outputs[6]; + const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3); + if (xyzOutput.hasEndpoints) { + if (input === this.xyIn) { + state.compilationString += state._declareOutput(xyzOutput) + ` = ${vec3}(${input.associatedVariableName}, 0.0);\n`; + } + else { + state.compilationString += state._declareOutput(xyzOutput) + ` = ${input.associatedVariableName}.xyz;\n`; + } + } + if (zwOutput.hasEndpoints && this.xyzw.isConnected) { + state.compilationString += state._declareOutput(zwOutput) + ` = ${this.xyzw.associatedVariableName}.zw;\n`; + } + if (xyOutput.hasEndpoints) { + state.compilationString += state._declareOutput(xyOutput) + ` = ${input.associatedVariableName}.xy;\n`; + } + if (xOutput.hasEndpoints) { + state.compilationString += state._declareOutput(xOutput) + ` = ${input.associatedVariableName}.x;\n`; + } + if (yOutput.hasEndpoints) { + state.compilationString += state._declareOutput(yOutput) + ` = ${input.associatedVariableName}.y;\n`; + } + if (zOutput.hasEndpoints) { + state.compilationString += state._declareOutput(zOutput) + ` = ${input.associatedVariableName}.z;\n`; + } + if (wOutput.hasEndpoints) { + state.compilationString += state._declareOutput(wOutput) + ` = ${input.associatedVariableName}.w;\n`; + } + return this; + } +} +RegisterClass("BABYLON.VectorSplitterBlock", VectorSplitterBlock); + +/** + * Block used to lerp between 2 values + */ +class LerpBlock extends NodeMaterialBlock { + /** + * Creates a new LerpBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._linkConnectionTypes(1, 2, true); + this._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "LerpBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the gradient operand input component + */ + get gradient() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += + state._declareOutput(output) + ` = mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.LerpBlock", LerpBlock); + +/** + * Block used to divide 2 vectors + */ +class DivideBlock extends BaseMathBlock { + /** + * Creates a new DivideBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "DivideBlock"; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = ${this.left.associatedVariableName} / ${this.right.associatedVariableName};\n`; + return this; + } +} +RegisterClass("BABYLON.DivideBlock", DivideBlock); + +/** + * Block used to subtract 2 vectors + */ +class SubtractBlock extends BaseMathBlock { + /** + * Creates a new SubtractBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SubtractBlock"; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = ${this.left.associatedVariableName} - ${this.right.associatedVariableName};\n`; + return this; + } +} +RegisterClass("BABYLON.SubtractBlock", SubtractBlock); + +/** + * Block used to step a value + */ +class StepBlock extends NodeMaterialBlock { + /** + * Creates a new StepBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("value", NodeMaterialBlockConnectionPointTypes.Float); + this.registerInput("edge", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "StepBlock"; + } + /** + * Gets the value operand input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the edge operand input component + */ + get edge() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = step(${this.edge.associatedVariableName}, ${this.value.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.StepBlock", StepBlock); + +/** + * Block used to get the opposite (1 - x) of a value + */ +class OneMinusBlock extends NodeMaterialBlock { + /** + * Creates a new OneMinusBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "OneMinusBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = 1. - ${this.input.associatedVariableName};\n`; + return this; + } +} +RegisterClass("BABYLON.OneMinusBlock", OneMinusBlock); +RegisterClass("BABYLON.OppositeBlock", OneMinusBlock); // Backward compatibility + +/** + * Block used to get the view direction + */ +class ViewDirectionBlock extends NodeMaterialBlock { + /** + * Creates a new ViewDirectionBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ViewDirectionBlock"; + } + /** + * Gets the world position component + */ + get worldPosition() { + return this._inputs[0]; + } + /** + * Gets the camera position component + */ + get cameraPosition() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.cameraPosition.isConnected) { + let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition && additionalFilteringInfo(b)); + if (!cameraPositionInput) { + cameraPositionInput = new InputBlock("cameraPosition"); + cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition); + } + cameraPositionInput.output.connectTo(this.cameraPosition); + } + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += + state._declareOutput(output) + ` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\n`; + return this; + } +} +RegisterClass("BABYLON.ViewDirectionBlock", ViewDirectionBlock); + +// Do not edit. +const name$3Q = "fresnelFunction"; +const shader$3P = `#ifdef FRESNEL +float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power) +{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$3Q]) { + ShaderStore.IncludesShadersStore[name$3Q] = shader$3P; +} + +/** + * Block used to compute fresnel value + */ +class FresnelBlock extends NodeMaterialBlock { + /** + * Create a new FresnelBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("viewDirection", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerInput("bias", NodeMaterialBlockConnectionPointTypes.Float); + this.registerInput("power", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("fresnel", NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "FresnelBlock"; + } + /** + * Gets the world normal input component + */ + get worldNormal() { + return this._inputs[0]; + } + /** + * Gets the view direction input component + */ + get viewDirection() { + return this._inputs[1]; + } + /** + * Gets the bias input component + */ + get bias() { + return this._inputs[2]; + } + /** + * Gets the camera (or eye) position component + */ + get power() { + return this._inputs[3]; + } + /** + * Gets the fresnel output component + */ + get fresnel() { + return this._outputs[0]; + } + autoConfigure(material) { + if (!this.viewDirection.isConnected) { + const viewDirectionInput = new ViewDirectionBlock("View direction"); + viewDirectionInput.output.connectTo(this.viewDirection); + viewDirectionInput.autoConfigure(material); + } + if (!this.bias.isConnected) { + const biasInput = new InputBlock("bias"); + biasInput.value = 0; + biasInput.output.connectTo(this.bias); + } + if (!this.power.isConnected) { + const powerInput = new InputBlock("power"); + powerInput.value = 1; + powerInput.output.connectTo(this.power); + } + } + _buildBlock(state) { + super._buildBlock(state); + const comments = `//${this.name}`; + state._emitFunctionFromInclude("fresnelFunction", comments, { removeIfDef: true }); + state.compilationString += + state._declareOutput(this.fresnel) + + ` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.FresnelBlock", FresnelBlock); + +/** + * Block used to get the max of 2 values + */ +class MaxBlock extends NodeMaterialBlock { + /** + * Creates a new MaxBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MaxBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.MaxBlock", MaxBlock); + +/** + * Block used to get the min of 2 values + */ +class MinBlock extends NodeMaterialBlock { + /** + * Creates a new MinBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MinBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.MinBlock", MinBlock); + +/** + * Block used to get the distance between 2 values + */ +class DistanceBlock extends NodeMaterialBlock { + /** + * Creates a new DistanceBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "DistanceBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.DistanceBlock", DistanceBlock); + +/** + * Block used to get the length of a vector + */ +class LengthBlock extends NodeMaterialBlock { + /** + * Creates a new LengthBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "LengthBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = length(${this.value.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.LengthBlock", LengthBlock); + +/** + * Block used to get negative version of a value (i.e. x * -1) + */ +class NegateBlock extends NodeMaterialBlock { + /** + * Creates a new NegateBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NegateBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = -1.0 * ${this.value.associatedVariableName};\n`; + return this; + } +} +RegisterClass("BABYLON.NegateBlock", NegateBlock); + +/** + * Block used to get the value of the first parameter raised to the power of the second + */ +class PowBlock extends NodeMaterialBlock { + /** + * Creates a new PowBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("power", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "PowBlock"; + } + /** + * Gets the value operand input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the power operand input component + */ + get power() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = pow(max(${this.value.associatedVariableName}, 0.), ${this.power.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.PowBlock", PowBlock); + +/** + * Block used to get a random number + */ +class RandomNumberBlock extends NodeMaterialBlock { + /** + * Creates a new RandomNumberBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | + NodeMaterialBlockConnectionPointTypes.Vector3 | + NodeMaterialBlockConnectionPointTypes.Vector4 | + NodeMaterialBlockConnectionPointTypes.Color3 | + NodeMaterialBlockConnectionPointTypes.Color4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "RandomNumberBlock"; + } + /** + * Gets the seed input component + */ + get seed() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const comments = `//${this.name}`; + state._emitFunctionFromInclude("helperFunctions", comments); + state.compilationString += state._declareOutput(output) + ` = getRand(${this.seed.associatedVariableName}.xy);\n`; + return this; + } +} +RegisterClass("BABYLON.RandomNumberBlock", RandomNumberBlock); + +/** + * Block used to compute arc tangent of 2 values + */ +class ArcTan2Block extends NodeMaterialBlock { + /** + * Creates a new ArcTan2Block + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("x", NodeMaterialBlockConnectionPointTypes.Float); + this.registerInput("y", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ArcTan2Block"; + } + /** + * Gets the x operand input component + */ + get x() { + return this._inputs[0]; + } + /** + * Gets the y operand input component + */ + get y() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const func = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "atan2" : "atan"; + state.compilationString += state._declareOutput(output) + ` = ${func}(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.ArcTan2Block", ArcTan2Block); + +/** + * Block used to smooth step a value + */ +class SmoothStepBlock extends NodeMaterialBlock { + /** + * Creates a new SmoothStepBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("edge0", NodeMaterialBlockConnectionPointTypes.Float); + this.registerInput("edge1", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SmoothStepBlock"; + } + /** + * Gets the value operand input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the first edge operand input component + */ + get edge0() { + return this._inputs[1]; + } + /** + * Gets the second edge operand input component + */ + get edge1() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const cast = state._getShaderType(this.value.type); + state.compilationString += + state._declareOutput(output) + + ` = smoothstep(${cast}(${this.edge0.associatedVariableName}), ${cast}(${this.edge1.associatedVariableName}), ${this.value.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.SmoothStepBlock", SmoothStepBlock); + +/** + * Block used to get the reciprocal (1 / x) of a value + */ +class ReciprocalBlock extends NodeMaterialBlock { + /** + * Creates a new ReciprocalBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ReciprocalBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + if (this.input.type === NodeMaterialBlockConnectionPointTypes.Matrix) { + state.compilationString += state._declareOutput(output) + ` = inverse(${this.input.associatedVariableName});\n`; + } + else { + state.compilationString += state._declareOutput(output) + ` = 1. / ${this.input.associatedVariableName};\n`; + } + return this; + } +} +RegisterClass("BABYLON.ReciprocalBlock", ReciprocalBlock); + +/** + * Block used to replace a color by another one + */ +class ReplaceColorBlock extends NodeMaterialBlock { + /** + * Creates a new ReplaceColorBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("reference", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("distance", NodeMaterialBlockConnectionPointTypes.Float); + this.registerInput("replacement", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._linkConnectionTypes(0, 3); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + this._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ReplaceColorBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the reference input component + */ + get reference() { + return this._inputs[1]; + } + /** + * Gets the distance input component + */ + get distance() { + return this._inputs[2]; + } + /** + * Gets the replacement input component + */ + get replacement() { + return this._inputs[3]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + `;\n`; + state.compilationString += `if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\n`; + state.compilationString += `${output.associatedVariableName} = ${this.replacement.associatedVariableName};\n`; + state.compilationString += `} else {\n`; + state.compilationString += `${output.associatedVariableName} = ${this.value.associatedVariableName};\n`; + state.compilationString += `}\n`; + return this; + } +} +RegisterClass("BABYLON.ReplaceColorBlock", ReplaceColorBlock); + +/** + * Block used to posterize a value + * @see https://en.wikipedia.org/wiki/Posterization + */ +class PosterizeBlock extends NodeMaterialBlock { + /** + * Creates a new PosterizeBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("steps", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "PosterizeBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the steps input component + */ + get steps() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += + state._declareOutput(output) + + ` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.PosterizeBlock", PosterizeBlock); + +/** + * Operations supported by the Wave block + */ +var WaveBlockKind; +(function (WaveBlockKind) { + /** SawTooth */ + WaveBlockKind[WaveBlockKind["SawTooth"] = 0] = "SawTooth"; + /** Square */ + WaveBlockKind[WaveBlockKind["Square"] = 1] = "Square"; + /** Triangle */ + WaveBlockKind[WaveBlockKind["Triangle"] = 2] = "Triangle"; +})(WaveBlockKind || (WaveBlockKind = {})); +/** + * Block used to apply wave operation to floats + */ +class WaveBlock extends NodeMaterialBlock { + /** + * Creates a new WaveBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Gets or sets the kibnd of wave to be applied by the block + */ + this.kind = 0 /* WaveBlockKind.SawTooth */; + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "WaveBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + switch (this.kind) { + case 0 /* WaveBlockKind.SawTooth */: { + state.compilationString += state._declareOutput(output) + ` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\n`; + break; + } + case 1 /* WaveBlockKind.Square */: { + state.compilationString += state._declareOutput(output) + ` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\n`; + break; + } + case 2 /* WaveBlockKind.Triangle */: { + state.compilationString += + state._declareOutput(output) + ` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\n`; + break; + } + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.kind = this.kind; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.kind = serializationObject.kind; + } +} +__decorate([ + editableInPropertyPage("Kind", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "SawTooth", value: 0 /* WaveBlockKind.SawTooth */ }, + { label: "Square", value: 1 /* WaveBlockKind.Square */ }, + { label: "Triangle", value: 2 /* WaveBlockKind.Triangle */ }, + ], + }) +], WaveBlock.prototype, "kind", void 0); +RegisterClass("BABYLON.WaveBlock", WaveBlock); + +/** + * Class used to store a color step for the GradientBlock + */ +class GradientBlockColorStep { + /** + * Gets value indicating which step this color is associated with (between 0 and 1) + */ + get step() { + return this._step; + } + /** + * Sets a value indicating which step this color is associated with (between 0 and 1) + */ + set step(val) { + this._step = val; + } + /** + * Gets the color associated with this step + */ + get color() { + return this._color; + } + /** + * Sets the color associated with this step + */ + set color(val) { + this._color = val; + } + /** + * Creates a new GradientBlockColorStep + * @param step defines a value indicating which step this color is associated with (between 0 and 1) + * @param color defines the color associated with this step + */ + constructor(step, color) { + this.step = step; + this.color = color; + } +} +/** + * Block used to return a color from a gradient based on an input value between 0 and 1 + */ +class GradientBlock extends NodeMaterialBlock { + /** calls observable when the value is changed*/ + colorStepsUpdated() { + this.onValueChangedObservable.notifyObservers(this); + } + /** + * Creates a new GradientBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Gets or sets the list of color steps + */ + this.colorSteps = [new GradientBlockColorStep(0, Color3.Black()), new GradientBlockColorStep(1.0, Color3.White())]; + /** Gets an observable raised when the value is changed */ + this.onValueChangedObservable = new Observable(); + this.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Float | + NodeMaterialBlockConnectionPointTypes.Vector2 | + NodeMaterialBlockConnectionPointTypes.Vector3 | + NodeMaterialBlockConnectionPointTypes.Vector4 | + NodeMaterialBlockConnectionPointTypes.Color3 | + NodeMaterialBlockConnectionPointTypes.Color4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GradientBlock"; + } + /** + * Gets the gradient input component + */ + get gradient() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _writeColorConstant(index, vec3) { + const step = this.colorSteps[index]; + return `${vec3}(${step.color.r}, ${step.color.g}, ${step.color.b})`; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3); + if (!this.colorSteps.length || !this.gradient.connectedPoint) { + state.compilationString += state._declareOutput(output) + ` = ${vec3}(0., 0., 0.);\n`; + return; + } + const tempColor = state._getFreeVariableName("gradientTempColor"); + const tempPosition = state._getFreeVariableName("gradientTempPosition"); + state.compilationString += `${state._declareLocalVar(tempColor, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this._writeColorConstant(0, vec3)};\n`; + state.compilationString += `${state._declareLocalVar(tempPosition, NodeMaterialBlockConnectionPointTypes.Float)};\n`; + let gradientSource = this.gradient.associatedVariableName; + if (this.gradient.connectedPoint.type !== NodeMaterialBlockConnectionPointTypes.Float) { + gradientSource += ".x"; + } + for (let index = 1; index < this.colorSteps.length; index++) { + const step = this.colorSteps[index]; + const previousStep = this.colorSteps[index - 1]; + state.compilationString += `${tempPosition} = clamp((${gradientSource} - ${state._emitFloat(previousStep.step)}) / (${state._emitFloat(step.step)} - ${state._emitFloat(previousStep.step)}), 0.0, 1.0) * step(${state._emitFloat(index)}, ${state._emitFloat(this.colorSteps.length - 1)});\n`; + state.compilationString += `${tempColor} = mix(${tempColor}, ${this._writeColorConstant(index, vec3)}, ${tempPosition});\n`; + } + state.compilationString += state._declareOutput(output) + ` = ${tempColor};\n`; + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.colorSteps = []; + for (const step of this.colorSteps) { + serializationObject.colorSteps.push({ + step: step.step, + color: { + r: step.color.r, + g: step.color.g, + b: step.color.b, + }, + }); + } + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.colorSteps.length = 0; + for (const step of serializationObject.colorSteps) { + this.colorSteps.push(new GradientBlockColorStep(step.step, new Color3(step.color.r, step.color.g, step.color.b))); + } + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.colorSteps = [];\n`; + for (const colorStep of this.colorSteps) { + codeString += `${this._codeVariableName}.colorSteps.push(new BABYLON.GradientBlockColorStep(${colorStep.step}, new BABYLON.Color3(${colorStep.color.r}, ${colorStep.color.g}, ${colorStep.color.b})));\n`; + } + return codeString; + } +} +RegisterClass("BABYLON.GradientBlock", GradientBlock); + +/** + * Block used to normalize lerp between 2 values + */ +class NLerpBlock extends NodeMaterialBlock { + /** + * Creates a new NLerpBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._linkConnectionTypes(1, 2, true); + this._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NLerpBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the gradient operand input component + */ + get gradient() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += + state._declareOutput(output) + + ` = normalize(mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName}));\n`; + return this; + } +} +RegisterClass("BABYLON.NLerpBlock", NLerpBlock); + +/** + * block used to Generate a Worley Noise 3D Noise Pattern + */ +// Source: https://github.com/Erkaman/glsl-worley +// Converted to BJS by Pryme8 +// +// Worley Noise 3D +// Return vec2 value range of -1.0->1.0, F1-F2 respectivly +class WorleyNoise3DBlock extends NodeMaterialBlock { + /** + * Creates a new WorleyNoise3DBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** Gets or sets a boolean indicating that normal should be inverted on X axis */ + this.manhattanDistance = false; + this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerInput("jitter", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "WorleyNoise3DBlock"; + } + /** + * Gets the seed input component + */ + get seed() { + return this._inputs[0]; + } + /** + * Gets the jitter input component + */ + get jitter() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the x component + */ + get x() { + return this._outputs[1]; + } + /** + * Gets the y component + */ + get y() { + return this._outputs[2]; + } + _buildBlock(state) { + super._buildBlock(state); + if (!this.seed.isConnected) { + return; + } + if (!this.output.hasEndpoints && !this.x.hasEndpoints && !this.y.hasEndpoints) { + return; + } + let functionString = `vec3 permute(vec3 x){\n`; + functionString += ` return mod((34.0 * x + 1.0) * x, 289.0);\n`; + functionString += `}\n\n`; + functionString += `vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\n`; + functionString += ` return [manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z)];\n`; + functionString += `}\n\n`; + functionString += `vec2 worley(vec3 P, float jitter, bool manhattanDistance){\n`; + functionString += ` float K = 0.142857142857; // 1/7\n`; + functionString += ` float Ko = 0.428571428571; // 1/2-K/2\n`; + functionString += ` float K2 = 0.020408163265306; // 1/(7*7)\n`; + functionString += ` float Kz = 0.166666666667; // 1/6\n`; + functionString += ` float Kzo = 0.416666666667; // 1/2-1/6*2\n`; + functionString += `\n`; + functionString += ` vec3 Pi = mod(floor(P), 289.0);\n`; + functionString += ` vec3 Pf = fract(P) - 0.5;\n`; + functionString += `\n`; + functionString += ` vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\n`; + functionString += ` vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\n`; + functionString += ` vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\n`; + functionString += `\n`; + functionString += ` vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\n`; + functionString += ` vec3 p1 = permute(p + Pi.y - 1.0);\n`; + functionString += ` vec3 p2 = permute(p + Pi.y);\n`; + functionString += ` vec3 p3 = permute(p + Pi.y + 1.0);\n`; + functionString += `\n`; + functionString += ` vec3 p11 = permute(p1 + Pi.z - 1.0);\n`; + functionString += ` vec3 p12 = permute(p1 + Pi.z);\n`; + functionString += ` vec3 p13 = permute(p1 + Pi.z + 1.0);\n`; + functionString += `\n`; + functionString += ` vec3 p21 = permute(p2 + Pi.z - 1.0);\n`; + functionString += ` vec3 p22 = permute(p2 + Pi.z);\n`; + functionString += ` vec3 p23 = permute(p2 + Pi.z + 1.0);\n`; + functionString += `\n`; + functionString += ` vec3 p31 = permute(p3 + Pi.z - 1.0);\n`; + functionString += ` vec3 p32 = permute(p3 + Pi.z);\n`; + functionString += ` vec3 p33 = permute(p3 + Pi.z + 1.0);\n`; + functionString += `\n`; + functionString += ` vec3 ox11 = fract(p11*K) - Ko;\n`; + functionString += ` vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\n`; + functionString += ` vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\n`; + functionString += `\n`; + functionString += ` vec3 ox12 = fract(p12*K) - Ko;\n`; + functionString += ` vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\n`; + functionString += ` vec3 oz12 = floor(p12*K2)*Kz - Kzo;\n`; + functionString += `\n`; + functionString += ` vec3 ox13 = fract(p13*K) - Ko;\n`; + functionString += ` vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\n`; + functionString += ` vec3 oz13 = floor(p13*K2)*Kz - Kzo;\n`; + functionString += `\n`; + functionString += ` vec3 ox21 = fract(p21*K) - Ko;\n`; + functionString += ` vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\n`; + functionString += ` vec3 oz21 = floor(p21*K2)*Kz - Kzo;\n`; + functionString += `\n`; + functionString += ` vec3 ox22 = fract(p22*K) - Ko;\n`; + functionString += ` vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\n`; + functionString += ` vec3 oz22 = floor(p22*K2)*Kz - Kzo;\n`; + functionString += `\n`; + functionString += ` vec3 ox23 = fract(p23*K) - Ko;\n`; + functionString += ` vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\n`; + functionString += ` vec3 oz23 = floor(p23*K2)*Kz - Kzo;\n`; + functionString += `\n`; + functionString += ` vec3 ox31 = fract(p31*K) - Ko;\n`; + functionString += ` vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\n`; + functionString += ` vec3 oz31 = floor(p31*K2)*Kz - Kzo;\n`; + functionString += `\n`; + functionString += ` vec3 ox32 = fract(p32*K) - Ko;\n`; + functionString += ` vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\n`; + functionString += ` vec3 oz32 = floor(p32*K2)*Kz - Kzo;\n`; + functionString += `\n`; + functionString += ` vec3 ox33 = fract(p33*K) - Ko;\n`; + functionString += ` vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\n`; + functionString += ` vec3 oz33 = floor(p33*K2)*Kz - Kzo;\n`; + functionString += `\n`; + functionString += ` vec3 dx11 = Pfx + jitter*ox11;\n`; + functionString += ` vec3 dy11 = Pfy.x + jitter*oy11;\n`; + functionString += ` vec3 dz11 = Pfz.x + jitter*oz11;\n`; + functionString += `\n`; + functionString += ` vec3 dx12 = Pfx + jitter*ox12;\n`; + functionString += ` vec3 dy12 = Pfy.x + jitter*oy12;\n`; + functionString += ` vec3 dz12 = Pfz.y + jitter*oz12;\n`; + functionString += `\n`; + functionString += ` vec3 dx13 = Pfx + jitter*ox13;\n`; + functionString += ` vec3 dy13 = Pfy.x + jitter*oy13;\n`; + functionString += ` vec3 dz13 = Pfz.z + jitter*oz13;\n`; + functionString += `\n`; + functionString += ` vec3 dx21 = Pfx + jitter*ox21;\n`; + functionString += ` vec3 dy21 = Pfy.y + jitter*oy21;\n`; + functionString += ` vec3 dz21 = Pfz.x + jitter*oz21;\n`; + functionString += `\n`; + functionString += ` vec3 dx22 = Pfx + jitter*ox22;\n`; + functionString += ` vec3 dy22 = Pfy.y + jitter*oy22;\n`; + functionString += ` vec3 dz22 = Pfz.y + jitter*oz22;\n`; + functionString += `\n`; + functionString += ` vec3 dx23 = Pfx + jitter*ox23;\n`; + functionString += ` vec3 dy23 = Pfy.y + jitter*oy23;\n`; + functionString += ` vec3 dz23 = Pfz.z + jitter*oz23;\n`; + functionString += `\n`; + functionString += ` vec3 dx31 = Pfx + jitter*ox31;\n`; + functionString += ` vec3 dy31 = Pfy.z + jitter*oy31;\n`; + functionString += ` vec3 dz31 = Pfz.x + jitter*oz31;\n`; + functionString += `\n`; + functionString += ` vec3 dx32 = Pfx + jitter*ox32;\n`; + functionString += ` vec3 dy32 = Pfy.z + jitter*oy32;\n`; + functionString += ` vec3 dz32 = Pfz.y + jitter*oz32;\n`; + functionString += `\n`; + functionString += ` vec3 dx33 = Pfx + jitter*ox33;\n`; + functionString += ` vec3 dy33 = Pfy.z + jitter*oy33;\n`; + functionString += ` vec3 dz33 = Pfz.z + jitter*oz33;\n`; + functionString += `\n`; + functionString += ` vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\n`; + functionString += ` vec3 d12 = dist(dx12, dy12, dz12, manhattanDistance);\n`; + functionString += ` vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\n`; + functionString += ` vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\n`; + functionString += ` vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\n`; + functionString += ` vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\n`; + functionString += ` vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\n`; + functionString += ` vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\n`; + functionString += ` vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\n`; + functionString += `\n`; + functionString += ` vec3 d1a = min(d11, d12);\n`; + functionString += ` d12 = max(d11, d12);\n`; + functionString += ` d11 = min(d1a, d13); // Smallest now not in d12 or d13\n`; + functionString += ` d13 = max(d1a, d13);\n`; + functionString += ` d12 = min(d12, d13); // 2nd smallest now not in d13\n`; + functionString += ` vec3 d2a = min(d21, d22);\n`; + functionString += ` d22 = max(d21, d22);\n`; + functionString += ` d21 = min(d2a, d23); // Smallest now not in d22 or d23\n`; + functionString += ` d23 = max(d2a, d23);\n`; + functionString += ` d22 = min(d22, d23); // 2nd smallest now not in d23\n`; + functionString += ` vec3 d3a = min(d31, d32);\n`; + functionString += ` d32 = max(d31, d32);\n`; + functionString += ` d31 = min(d3a, d33); // Smallest now not in d32 or d33\n`; + functionString += ` d33 = max(d3a, d33);\n`; + functionString += ` d32 = min(d32, d33); // 2nd smallest now not in d33\n`; + functionString += ` vec3 da = min(d11, d21);\n`; + functionString += ` d21 = max(d11, d21);\n`; + functionString += ` d11 = min(da, d31); // Smallest now in d11\n`; + functionString += ` d31 = max(da, d31); // 2nd smallest now not in d31\n`; + functionString += ` if (d11.x >= d11.y) { vec2 temp = d11.yx; d11.x = temp.x; d11.y = temp.y; }\n`; + functionString += ` if (d11.x >= d11.z) { vec2 temp = d11.zx; d11.x = temp.x; d11.z = temp.y; }\n`; + functionString += ` d12 = min(d12, d21); // 2nd smallest now not in d21\n`; + functionString += ` d12 = min(d12, d22); // nor in d22\n`; + functionString += ` d12 = min(d12, d31); // nor in d31\n`; + functionString += ` d12 = min(d12, d32); // nor in d32\n`; + functionString += ` vec2 temp2 = min(d11.yz, d12.xy); // nor in d12.yz\n`; + functionString += ` d11.y = temp2.x;\n`; + functionString += ` d11.z = temp2.y;\n`; + functionString += ` d11.y = min(d11.y, d12.z); // Only two more to go\n`; + functionString += ` d11.y = min(d11.y, d11.z); // Done! (Phew!)\n`; + functionString += ` return sqrt(d11.xy); // F1, F2\n`; + functionString += `}\n\n`; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + functionString = state._babylonSLtoWGSL(functionString); + } + else { + functionString = state._babylonSLtoGLSL(functionString); + } + state._emitFunction("worley3D", functionString, "// Worley3D"); + const tempVariable = state._getFreeVariableName("worleyTemp"); + state.compilationString += `${state._declareLocalVar(tempVariable, NodeMaterialBlockConnectionPointTypes.Vector2)} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance});\n`; + if (this.output.hasEndpoints) { + state.compilationString += state._declareOutput(this.output) + ` = ${tempVariable};\n`; + } + if (this.x.hasEndpoints) { + state.compilationString += state._declareOutput(this.x) + ` = ${tempVariable}.x;\n`; + } + if (this.y.hasEndpoints) { + state.compilationString += state._declareOutput(this.y) + ` = ${tempVariable}.y;\n`; + } + return this; + } + /** + * Exposes the properties to the UI? + * @returns - boolean indicating if the block has properties or not + */ + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance};\n`; + return codeString; + } + /** + * Exposes the properties to the Serialize? + * @returns - a serialized object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.manhattanDistance = this.manhattanDistance; + return serializationObject; + } + /** + * Exposes the properties to the deserialize? + * @param serializationObject + * @param scene + * @param rootUrl + */ + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.manhattanDistance = serializationObject.manhattanDistance; + } +} +__decorate([ + editableInPropertyPage("Use Manhattan Distance", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES", { embedded: true, notifiers: { update: false } }) +], WorleyNoise3DBlock.prototype, "manhattanDistance", void 0); +RegisterClass("BABYLON.WorleyNoise3DBlock", WorleyNoise3DBlock); + +/** + * block used to Generate a Simplex Perlin 3d Noise Pattern + */ +// +// Wombat +// An efficient texture-free GLSL procedural noise library +// Source: https://github.com/BrianSharpe/Wombat +// Derived from: https://github.com/BrianSharpe/GPU-Noise-Lib +// +// I'm not one for copyrights. Use the code however you wish. +// All I ask is that credit be given back to the blog or myself when appropriate. +// And also to let me know if you come up with any changes, improvements, thoughts or interesting uses for this stuff. :) +// Thanks! +// +// Brian Sharpe +// brisharpe CIRCLE_A yahoo DOT com +// http://briansharpe.wordpress.com +// https://github.com/BrianSharpe +// +// +// This is a modified version of Stefan Gustavson's and Ian McEwan's work at http://github.com/ashima/webgl-noise +// Modifications are... +// - faster random number generation +// - analytical final normalization +// - space scaled can have an approx feature size of 1.0 +// - filter kernel changed to fix discontinuities at tetrahedron boundaries +// +// Converted to BJS by Pryme8 +// +// Simplex Perlin Noise 3D +// Return value range of -1.0->1.0 +// +class SimplexPerlin3DBlock extends NodeMaterialBlock { + /** + * Creates a new SimplexPerlin3DBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SimplexPerlin3DBlock"; + } + /** + * Gets the seed operand input component + */ + get seed() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + if (!this.seed.isConnected) { + return; + } + if (!this._outputs[0].hasEndpoints) { + return; + } + let functionString = `const float SKEWFACTOR = 1.0/3.0;\n`; + functionString += `const float UNSKEWFACTOR = 1.0/6.0;\n`; + functionString += `const float SIMPLEX_CORNER_POS = 0.5;\n`; + functionString += `const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\n`; + functionString += `float SimplexPerlin3D( vec3 source ){\n`; + functionString += ` vec3 P = source;\n`; + functionString += ` P.x = [P.x == 0. && P.y == 0. && P.z == 0. ? 0.00001 : P.x];\n`; + functionString += ` P *= SIMPLEX_TETRAHADRON_HEIGHT;\n`; + functionString += ` vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );`; + functionString += ` vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\n`; + functionString += ` vec3 g = step(x0.yzx, x0.xyz);\n`; + functionString += ` vec3 l = 1.0 - g;\n`; + functionString += ` vec3 Pi_1 = min( g.xyz, l.zxy );\n`; + functionString += ` vec3 Pi_2 = max( g.xyz, l.zxy );\n`; + functionString += ` vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\n`; + functionString += ` vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\n`; + functionString += ` vec3 x3 = x0 - SIMPLEX_CORNER_POS;\n`; + functionString += ` vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\n`; + functionString += ` vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\n`; + functionString += ` vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\n`; + functionString += ` Pi = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\n`; + functionString += ` vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\n`; + functionString += ` vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\n`; + functionString += ` Pt *= Pt;\n`; + functionString += ` vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\n`; + functionString += ` Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\n`; + functionString += ` const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\n`; + functionString += ` const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\n`; + functionString += ` vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\n`; + functionString += ` vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\n`; + functionString += ` Pi_1 = [( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods];\n`; + functionString += ` Pi_2 = [( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods];\n`; + functionString += ` vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\n`; + functionString += ` vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\n`; + functionString += ` vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\n`; + functionString += ` vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\n`; + functionString += ` const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\n`; + functionString += ` vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\n`; + functionString += ` kernel_weights = max(0.5 - kernel_weights, vec4(0.));\n`; + functionString += ` kernel_weights = kernel_weights*kernel_weights*kernel_weights;\n`; + functionString += ` return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\n`; + functionString += `}\n`; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + functionString = state._babylonSLtoWGSL(functionString); + } + else { + functionString = state._babylonSLtoGLSL(functionString); + } + state._emitFunction("SimplexPerlin3D", functionString, "// SimplexPerlin3D"); + state.compilationString += state._declareOutput(this._outputs[0]) + ` = SimplexPerlin3D(${this.seed.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.SimplexPerlin3DBlock", SimplexPerlin3DBlock); + +/** + * Block used to blend normals + */ +class NormalBlendBlock extends NodeMaterialBlock { + /** + * Creates a new NormalBlendBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("normalMap0", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("normalMap1", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | + NodeMaterialBlockConnectionPointTypes.Color4 | + NodeMaterialBlockConnectionPointTypes.Vector3 | + NodeMaterialBlockConnectionPointTypes.Vector4); + this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | + NodeMaterialBlockConnectionPointTypes.Color4 | + NodeMaterialBlockConnectionPointTypes.Vector3 | + NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NormalBlendBlock"; + } + /** + * Gets the first input component + */ + get normalMap0() { + return this._inputs[0]; + } + /** + * Gets the second input component + */ + get normalMap1() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const input0 = this._inputs[0]; + const input1 = this._inputs[1]; + const stepR = state._getFreeVariableName("stepR"); + const stepG = state._getFreeVariableName("stepG"); + state.compilationString += `${state._declareLocalVar(stepR, NodeMaterialBlockConnectionPointTypes.Float)} = step(0.5, ${input0.associatedVariableName}.r);\n`; + state.compilationString += `${state._declareLocalVar(stepG, NodeMaterialBlockConnectionPointTypes.Float)} = step(0.5, ${input0.associatedVariableName}.g);\n`; + state.compilationString += state._declareOutput(output) + `;\n`; + state.compilationString += `${output.associatedVariableName}.r = (1.0 - ${stepR}) * ${input0.associatedVariableName}.r * ${input1.associatedVariableName}.r * 2.0 + ${stepR} * (1.0 - (1.0 - ${input0.associatedVariableName}.r) * (1.0 - ${input1.associatedVariableName}.r) * 2.0);\n`; + state.compilationString += `${output.associatedVariableName}.g = (1.0 - ${stepG}) * ${input0.associatedVariableName}.g * ${input1.associatedVariableName}.g * 2.0 + ${stepG} * (1.0 - (1.0 - ${input0.associatedVariableName}.g) * (1.0 - ${input1.associatedVariableName}.g) * 2.0);\n`; + state.compilationString += `${output.associatedVariableName}.b = ${input0.associatedVariableName}.b * ${input1.associatedVariableName}.b;\n`; + return this; + } +} +RegisterClass("BABYLON.NormalBlendBlock", NormalBlendBlock); + +/** + * Block used to rotate a 2d vector by a given angle + */ +class Rotate2dBlock extends NodeMaterialBlock { + /** + * Creates a new Rotate2dBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerInput("angle", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "Rotate2dBlock"; + } + /** + * Gets the input vector + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the input angle + */ + get angle() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.angle.isConnected) { + const angleInput = new InputBlock("angle"); + angleInput.value = 0; + angleInput.output.connectTo(this.angle); + } + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const angle = this.angle; + const input = this.input; + state.compilationString += + state._declareOutput(output) + + ` = vec2(cos(${angle.associatedVariableName}) * ${input.associatedVariableName}.x - sin(${angle.associatedVariableName}) * ${input.associatedVariableName}.y, sin(${angle.associatedVariableName}) * ${input.associatedVariableName}.x + cos(${angle.associatedVariableName}) * ${input.associatedVariableName}.y);\n`; + return this; + } +} +RegisterClass("BABYLON.Rotate2dBlock", Rotate2dBlock); + +/** + * Block used to get the reflected vector from a direction and a normal + */ +class ReflectBlock extends NodeMaterialBlock { + /** + * Creates a new ReflectBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("incident", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | + NodeMaterialBlockConnectionPointTypes.Vector4 | + NodeMaterialBlockConnectionPointTypes.Color3 | + NodeMaterialBlockConnectionPointTypes.Color4); + this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | + NodeMaterialBlockConnectionPointTypes.Vector4 | + NodeMaterialBlockConnectionPointTypes.Color3 | + NodeMaterialBlockConnectionPointTypes.Color4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ReflectBlock"; + } + /** + * Gets the incident component + */ + get incident() { + return this._inputs[0]; + } + /** + * Gets the normal component + */ + get normal() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += state._declareOutput(output) + ` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz);\n`; + return this; + } +} +RegisterClass("BABYLON.ReflectBlock", ReflectBlock); + +/** + * Block used to get the refracted vector from a direction and a normal + */ +class RefractBlock extends NodeMaterialBlock { + /** + * Creates a new RefractBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("incident", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("ior", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | + NodeMaterialBlockConnectionPointTypes.Vector4 | + NodeMaterialBlockConnectionPointTypes.Color3 | + NodeMaterialBlockConnectionPointTypes.Color4); + this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | + NodeMaterialBlockConnectionPointTypes.Vector4 | + NodeMaterialBlockConnectionPointTypes.Color3 | + NodeMaterialBlockConnectionPointTypes.Color4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "RefractBlock"; + } + /** + * Gets the incident component + */ + get incident() { + return this._inputs[0]; + } + /** + * Gets the normal component + */ + get normal() { + return this._inputs[1]; + } + /** + * Gets the index of refraction component + */ + get ior() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + state.compilationString += + state._declareOutput(output) + + ` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.RefractBlock", RefractBlock); + +/** + * Block used to desaturate a color + */ +class DesaturateBlock extends NodeMaterialBlock { + /** + * Creates a new DesaturateBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3); + this.registerInput("level", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "DesaturateBlock"; + } + /** + * Gets the color operand input component + */ + get color() { + return this._inputs[0]; + } + /** + * Gets the level operand input component + */ + get level() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const color = this.color; + const colorName = color.associatedVariableName; + const tempMin = state._getFreeVariableName("colorMin"); + const tempMax = state._getFreeVariableName("colorMax"); + const tempMerge = state._getFreeVariableName("colorMerge"); + state.compilationString += `${state._declareLocalVar(tempMin, NodeMaterialBlockConnectionPointTypes.Float)} = min(min(${colorName}.x, ${colorName}.y), ${colorName}.z);\n`; + state.compilationString += `${state._declareLocalVar(tempMax, NodeMaterialBlockConnectionPointTypes.Float)} = max(max(${colorName}.x, ${colorName}.y), ${colorName}.z);\n`; + state.compilationString += `${state._declareLocalVar(tempMerge, NodeMaterialBlockConnectionPointTypes.Float)} = 0.5 * (${tempMin} + ${tempMax});\n`; + state.compilationString += + state._declareOutput(output) + + ` = mix(${colorName}, ${state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3)}(${tempMerge}, ${tempMerge}, ${tempMerge}), ${this.level.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.DesaturateBlock", DesaturateBlock); + +/** + * Block used to implement the sheen module of the PBR material + */ +class SheenBlock extends NodeMaterialBlock { + /** + * Create a new SheenBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + /** + * If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique. + * It allows the strength of the sheen effect to not depend on the base color of the material, + * making it easier to setup and tweak the effect + */ + this.albedoScaling = false; + /** + * Defines if the sheen is linked to the sheen color. + */ + this.linkSheenWithAlbedo = false; + this._isUnique = true; + this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerOutput("sheen", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("sheen", this, 1 /* NodeMaterialConnectionPointDirection.Output */, SheenBlock, "SheenBlock")); + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("sheenOut"); + state._excludeVariableName("sheenMapData"); + state._excludeVariableName("vSheenColor"); + state._excludeVariableName("vSheenRoughness"); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SheenBlock"; + } + /** + * Gets the intensity input component + */ + get intensity() { + return this._inputs[0]; + } + /** + * Gets the color input component + */ + get color() { + return this._inputs[1]; + } + /** + * Gets the roughness input component + */ + get roughness() { + return this._inputs[2]; + } + /** + * Gets the sheen object output component + */ + get sheen() { + return this._outputs[0]; + } + prepareDefines(mesh, nodeMaterial, defines) { + super.prepareDefines(mesh, nodeMaterial, defines); + defines.setValue("SHEEN", true); + defines.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE", true, true); + defines.setValue("SHEEN_LINKWITHALBEDO", this.linkSheenWithAlbedo, true); + defines.setValue("SHEEN_ROUGHNESS", this.roughness.isConnected, true); + defines.setValue("SHEEN_ALBEDOSCALING", this.albedoScaling, true); + } + /** + * Gets the main code of the block (fragment side) + * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module + * @param state define the build state + * @returns the shader code + */ + getCode(reflectionBlock, state) { + let code = ""; + const color = this.color.isConnected ? this.color.associatedVariableName : `vec3${state.fSuffix}(1.)`; + const intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : "1."; + const roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : "0."; + const texture = `vec4${state.fSuffix}(0.)`; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + code = `#ifdef SHEEN + ${isWebGPU ? "var sheenOut: sheenOutParams" : "sheenOutParams sheenOut"}; + + ${state._declareLocalVar("vSheenColor", NodeMaterialBlockConnectionPointTypes.Vector4)} = vec4${state.fSuffix}(${color}, ${intensity}); + + sheenOut = sheenBlock( + vSheenColor + #ifdef SHEEN_ROUGHNESS + , ${roughness} + #endif + , roughness + #ifdef SHEEN_TEXTURE + , ${texture} + ${isWebGPU ? `, ${texture}Sampler` : ""} + , 1.0 + #endif + , reflectance + #ifdef SHEEN_LINKWITHALBEDO + , baseColor + , surfaceAlbedo + #endif + #ifdef ENVIRONMENTBRDF + , NdotV + , environmentBrdf + #endif + #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) + , AARoughnessFactors + , ${isWebGPU ? "uniforms." : ""}${reflectionBlock?._vReflectionMicrosurfaceInfosName} + , ${reflectionBlock?._vReflectionInfosName} + , ${reflectionBlock?.reflectionColor} + , ${isWebGPU ? "uniforms." : ""}vLightingIntensity + #ifdef ${reflectionBlock?._define3DName} + , ${reflectionBlock?._cubeSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""} + #else + , ${reflectionBlock?._2DSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""} + #endif + , reflectionOut.reflectionCoords + , NdotVUnclamped + #ifndef LODBASEDMICROSFURACE + #ifdef ${reflectionBlock?._define3DName} + , ${reflectionBlock?._cubeSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""} + , ${reflectionBlock?._cubeSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""} + #else + , ${reflectionBlock?._2DSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""} + , ${reflectionBlock?._2DSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""} + #endif + #endif + #if !defined(${reflectionBlock?._defineSkyboxName}) && defined(RADIANCEOCCLUSION) + , seo + #endif + #if !defined(${reflectionBlock?._defineSkyboxName}) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(${reflectionBlock?._define3DName}) + , eho + #endif + #endif + ); + + #ifdef SHEEN_LINKWITHALBEDO + surfaceAlbedo = sheenOut.surfaceAlbedo; + #endif + #endif\n`; + return code; + } + _buildBlock(state) { + if (state.target === NodeMaterialBlockTargets.Fragment) { + state.sharedData.blocksWithDefines.push(this); + } + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.albedoScaling = ${this.albedoScaling};\n`; + codeString += `${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.albedoScaling = this.albedoScaling; + serializationObject.linkSheenWithAlbedo = this.linkSheenWithAlbedo; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.albedoScaling = serializationObject.albedoScaling; + this.linkSheenWithAlbedo = serializationObject.linkSheenWithAlbedo; + } +} +__decorate([ + editableInPropertyPage("Albedo scaling", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES", { embedded: true, notifiers: { update: true } }) +], SheenBlock.prototype, "albedoScaling", void 0); +__decorate([ + editableInPropertyPage("Link sheen with albedo", 0 /* PropertyTypeForEdition.Boolean */, "PROPERTIES", { embedded: true, notifiers: { update: true } }) +], SheenBlock.prototype, "linkSheenWithAlbedo", void 0); +RegisterClass("BABYLON.SheenBlock", SheenBlock); + +/** + * Block used to implement the anisotropy module of the PBR material + */ +class AnisotropyBlock extends NodeMaterialBlock { + /** + * Create a new AnisotropyBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this._tangentCorrectionFactorName = ""; + this._isUnique = true; + this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("direction", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, true); // need this property and the next one in case there's no PerturbNormal block connected to the main PBR block + this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, true); + this.registerInput("TBN", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("TBN", this, 0 /* NodeMaterialConnectionPointDirection.Input */, TBNBlock, "TBNBlock")); + this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerOutput("anisotropy", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("anisotropy", this, 1 /* NodeMaterialConnectionPointDirection.Output */, AnisotropyBlock, "AnisotropyBlock")); + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("anisotropicOut"); + state._excludeVariableName("TBN"); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "AnisotropyBlock"; + } + /** + * Gets the intensity input component + */ + get intensity() { + return this._inputs[0]; + } + /** + * Gets the direction input component + */ + get direction() { + return this._inputs[1]; + } + /** + * Gets the uv input component + */ + get uv() { + return this._inputs[2]; + } + /** + * Gets the worldTangent input component + */ + get worldTangent() { + return this._inputs[3]; + } + /** + * Gets the TBN input component + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + get TBN() { + return this._inputs[4]; + } + /** + * Gets the roughness input component + */ + get roughness() { + return this._inputs[5]; + } + /** + * Gets the anisotropy object output component + */ + get anisotropy() { + return this._outputs[0]; + } + _generateTBNSpace(state) { + let code = ""; + const comments = `//${this.name}`; + const uv = this.uv; + const worldPosition = this.worldPositionConnectionPoint; + const worldNormal = this.worldNormalConnectionPoint; + const worldTangent = this.worldTangent; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + if (!uv.isConnected) { + // we must set the uv input as optional because we may not end up in this method (in case a PerturbNormal block is linked to the PBR material) + // in which case uv is not required. But if we do come here, we do need the uv, so we have to raise an error but not with throw, else + // it will stop the building of the node material and will lead to errors in the editor! + Logger.Error("You must connect the 'uv' input of the Anisotropy block!"); + } + state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); + const tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" }; + const TBN = this.TBN; + if (TBN.isConnected) { + state.compilationString += ` + #ifdef TBNBLOCK + ${isWebGPU ? "var TBN" : "mat3 TBN"} = ${TBN.associatedVariableName}; + #endif + `; + } + else if (worldTangent.isConnected) { + code += `${state._declareLocalVar("tbnNormal", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldNormal.associatedVariableName}.xyz);\n`; + code += `${state._declareLocalVar("tbnTangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldTangent.associatedVariableName}.xyz);\n`; + code += `${state._declareLocalVar("tbnBitangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`; + code += `${isWebGPU ? "var vTBN" : "mat3 vTBN"} = ${isWebGPU ? "mat3x3f" : "mat3"}(tbnTangent, tbnBitangent, tbnNormal);\n`; + } + code += ` + #if defined(${worldTangent.isConnected ? "TANGENT" : "IGNORE"}) && defined(NORMAL) + ${isWebGPU ? "var TBN" : "mat3 TBN"} = vTBN; + #else + ${isWebGPU ? "var TBN" : "mat3 TBN"} = cotangent_frame(${worldNormal.associatedVariableName + ".xyz"}, ${"v_" + worldPosition.associatedVariableName + ".xyz"}, ${uv.isConnected ? uv.associatedVariableName : "vec2(0.)"}, vec2${state.fSuffix}(1., 1.)); + #endif\n`; + state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, { + replaceStrings: [tangentReplaceString], + }); + return code; + } + /** + * Gets the main code of the block (fragment side) + * @param state current state of the node material building + * @param generateTBNSpace if true, the code needed to create the TBN coordinate space is generated + * @returns the shader code + */ + getCode(state, generateTBNSpace = false) { + let code = ""; + if (generateTBNSpace) { + code += this._generateTBNSpace(state); + } + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + const intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : "1.0"; + const direction = this.direction.isConnected ? this.direction.associatedVariableName : "vec2(1., 0.)"; + const roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : "0."; + code += `${isWebGPU ? "var anisotropicOut: anisotropicOutParams" : "anisotropicOutParams anisotropicOut"}; + anisotropicOut = anisotropicBlock( + vec3(${direction}, ${intensity}), + ${roughness}, + #ifdef ANISOTROPIC_TEXTURE + vec3(0.), + #endif + TBN, + normalW, + viewDirectionW + );\n`; + return code; + } + prepareDefines(mesh, nodeMaterial, defines) { + super.prepareDefines(mesh, nodeMaterial, defines); + defines.setValue("ANISOTROPIC", true); + defines.setValue("ANISOTROPIC_TEXTURE", false, true); + defines.setValue("ANISOTROPIC_LEGACY", !this.roughness.isConnected); + } + bind(effect, nodeMaterial, mesh) { + super.bind(effect, nodeMaterial, mesh); + if (mesh) { + effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1); + } + } + _buildBlock(state) { + if (state.target === NodeMaterialBlockTargets.Fragment) { + state.sharedData.blocksWithDefines.push(this); + state.sharedData.bindableBlocks.push(this); + this._tangentCorrectionFactorName = state._getFreeDefineName("tangentCorrectionFactor"); + state._emitUniformFromString(this._tangentCorrectionFactorName, NodeMaterialBlockConnectionPointTypes.Float); + } + return this; + } +} +RegisterClass("BABYLON.AnisotropyBlock", AnisotropyBlock); + +/** + * Block used to implement the reflection module of the PBR material + */ +class ReflectionBlock extends ReflectionTextureBaseBlock { + _onGenerateOnlyFragmentCodeChanged() { + if (this.position.isConnected) { + this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode; + Logger.Error("The position input must not be connected to be able to switch!"); + return false; + } + this._setTarget(); + return true; + } + _setTarget() { + super._setTarget(); + this.getInputByName("position").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; + if (this.generateOnlyFragmentCode) { + this.forceIrradianceInFragment = true; + } + } + /** + * Create a new ReflectionBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Defines if the material uses spherical harmonics vs spherical polynomials for the + * diffuse part of the IBL. + */ + this.useSphericalHarmonics = true; + /** + * Force the shader to compute irradiance in the fragment shader in order to take bump in account. + */ + this.forceIrradianceInFragment = false; + this._isUnique = true; + this.registerInput("position", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); + this.registerOutput("reflection", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("reflection", this, 1 /* NodeMaterialConnectionPointDirection.Output */, ReflectionBlock, "ReflectionBlock")); + this.position.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ReflectionBlock"; + } + /** + * Gets the position input component + */ + get position() { + return this._inputs[0]; + } + /** + * Gets the world position input component + */ + get worldPosition() { + return this.worldPositionConnectionPoint; + } + /** + * Gets the world normal input component + */ + get worldNormal() { + return this.worldNormalConnectionPoint; + } + /** + * Gets the world input component + */ + get world() { + return this._inputs[1]; + } + /** + * Gets the camera (or eye) position component + */ + get cameraPosition() { + return this.cameraPositionConnectionPoint; + } + /** + * Gets the view input component + */ + get view() { + return this.viewConnectionPoint; + } + /** + * Gets the color input component + */ + get color() { + return this._inputs[2]; + } + /** + * Gets the reflection object output component + */ + get reflection() { + return this._outputs[0]; + } + /** + * Returns true if the block has a texture (either its own texture or the environment texture from the scene, if set) + */ + get hasTexture() { + return !!this._getTexture(); + } + /** + * Gets the reflection color (either the name of the variable if the color input is connected, else a default value) + */ + get reflectionColor() { + return this.color.isConnected ? this.color.associatedVariableName : "vec3(1., 1., 1.)"; + } + _getTexture() { + if (this.texture) { + return this.texture; + } + return this._scene.environmentTexture; + } + prepareDefines(mesh, nodeMaterial, defines) { + super.prepareDefines(mesh, nodeMaterial, defines); + const reflectionTexture = this._getTexture(); + const reflection = reflectionTexture && reflectionTexture.getTextureMatrix; + defines.setValue("REFLECTION", reflection, true); + if (!reflection) { + return; + } + defines.setValue(this._defineLODReflectionAlpha, reflectionTexture.lodLevelInAlpha, true); + defines.setValue(this._defineLinearSpecularReflection, reflectionTexture.linearSpecularLOD, true); + defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ, true); + defines.setValue("SPHERICAL_HARMONICS", this.useSphericalHarmonics, true); + defines.setValue("GAMMAREFLECTION", reflectionTexture.gammaSpace, true); + defines.setValue("RGBDREFLECTION", reflectionTexture.isRGBD, true); + if (reflectionTexture && reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) { + if (reflectionTexture.isCube) { + defines.setValue("USESPHERICALFROMREFLECTIONMAP", true); + defines.setValue("USEIRRADIANCEMAP", false); + if (this.forceIrradianceInFragment || this._scene.getEngine().getCaps().maxVaryingVectors <= 8) { + defines.setValue("USESPHERICALINVERTEX", false); + } + else { + defines.setValue("USESPHERICALINVERTEX", true); + } + } + } + } + bind(effect, nodeMaterial, mesh, subMesh) { + super.bind(effect, nodeMaterial, mesh); + const reflectionTexture = this._getTexture(); + if (!reflectionTexture || !subMesh) { + return; + } + if (reflectionTexture.isCube) { + effect.setTexture(this._cubeSamplerName, reflectionTexture); + } + else { + effect.setTexture(this._2DSamplerName, reflectionTexture); + } + const width = reflectionTexture.getSize().width; + effect.setFloat3(this._vReflectionMicrosurfaceInfosName, width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); + effect.setFloat2(this._vReflectionFilteringInfoName, width, Math.log2(width)); + const defines = subMesh.materialDefines; + const polynomials = reflectionTexture.sphericalPolynomial; + if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) { + if (defines.SPHERICAL_HARMONICS) { + const preScaledHarmonics = polynomials.preScaledHarmonics; + effect.setVector3("vSphericalL00", preScaledHarmonics.l00); + effect.setVector3("vSphericalL1_1", preScaledHarmonics.l1_1); + effect.setVector3("vSphericalL10", preScaledHarmonics.l10); + effect.setVector3("vSphericalL11", preScaledHarmonics.l11); + effect.setVector3("vSphericalL2_2", preScaledHarmonics.l2_2); + effect.setVector3("vSphericalL2_1", preScaledHarmonics.l2_1); + effect.setVector3("vSphericalL20", preScaledHarmonics.l20); + effect.setVector3("vSphericalL21", preScaledHarmonics.l21); + effect.setVector3("vSphericalL22", preScaledHarmonics.l22); + } + else { + effect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z); + effect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z); + effect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z); + effect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z); + effect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z); + effect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z); + effect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z); + effect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z); + effect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z); + } + } + } + /** + * Gets the code to inject in the vertex shader + * @param state current state of the node material building + * @returns the shader code + */ + handleVertexSide(state) { + let code = super.handleVertexSide(state); + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + state._emitFunctionFromInclude("harmonicsFunctions", `//${this.name}`, { + replaceStrings: [ + { search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g, replace: "" }, + { search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g, replace: "" }, + ], + }); + const reflectionVectorName = state._getFreeVariableName("reflectionVector"); + this._vEnvironmentIrradianceName = state._getFreeVariableName("vEnvironmentIrradiance"); + state._emitVaryingFromString(this._vEnvironmentIrradianceName, NodeMaterialBlockConnectionPointTypes.Vector3, "defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"); + state._emitUniformFromString("vSphericalL00", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS"); + state._emitUniformFromString("vSphericalL1_1", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS"); + state._emitUniformFromString("vSphericalL10", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS"); + state._emitUniformFromString("vSphericalL11", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS"); + state._emitUniformFromString("vSphericalL2_2", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS"); + state._emitUniformFromString("vSphericalL2_1", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS"); + state._emitUniformFromString("vSphericalL20", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS"); + state._emitUniformFromString("vSphericalL21", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS"); + state._emitUniformFromString("vSphericalL22", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS"); + state._emitUniformFromString("vSphericalX", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true); + state._emitUniformFromString("vSphericalY", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true); + state._emitUniformFromString("vSphericalZ", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true); + state._emitUniformFromString("vSphericalXX_ZZ", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true); + state._emitUniformFromString("vSphericalYY_ZZ", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true); + state._emitUniformFromString("vSphericalZZ", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true); + state._emitUniformFromString("vSphericalXY", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true); + state._emitUniformFromString("vSphericalYZ", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true); + state._emitUniformFromString("vSphericalZX", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true); + code += `#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) + ${state._declareLocalVar(reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = (${(isWebGPU ? "uniforms." : "") + this._reflectionMatrixName} * vec4${state.fSuffix}(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; + #ifdef ${this._defineOppositeZ} + ${reflectionVectorName}.z *= -1.0; + #endif + ${isWebGPU ? "vertexOutputs." : ""}${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${reflectionVectorName}); + #endif\n`; + return code; + } + /** + * Gets the main code of the block (fragment side) + * @param state current state of the node material building + * @param normalVarName name of the existing variable corresponding to the normal + * @returns the shader code + */ + getCode(state, normalVarName) { + let code = ""; + this.handleFragmentSideInits(state); + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + state._emitFunctionFromInclude("harmonicsFunctions", `//${this.name}`, { + replaceStrings: [ + { search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g, replace: "" }, + { search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g, replace: "" }, + ], + }); + if (!isWebGPU) { + state._emitFunction("sampleReflection", ` + #ifdef ${this._define3DName} + #define sampleReflection(s, c) textureCube(s, c) + #else + #define sampleReflection(s, c) texture2D(s, c) + #endif\n`, `//${this.name}`); + state._emitFunction("sampleReflectionLod", ` + #ifdef ${this._define3DName} + #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l) + #else + #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l) + #endif\n`, `//${this.name}`); + } + const computeReflectionCoordsFunc = isWebGPU + ? ` + fn computeReflectionCoordsPBR(worldPos: vec4f, worldNormal: vec3f) -> vec3f { + ${this.handleFragmentSideCodeReflectionCoords(state, "worldNormal", "worldPos", true, true)} + return ${this._reflectionVectorName}; + }\n` + : ` + vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) { + ${this.handleFragmentSideCodeReflectionCoords(state, "worldNormal", "worldPos", true, true)} + return ${this._reflectionVectorName}; + }\n`; + state._emitFunction("computeReflectionCoordsPBR", computeReflectionCoordsFunc, `//${this.name}`); + this._vReflectionMicrosurfaceInfosName = state._getFreeVariableName("vReflectionMicrosurfaceInfos"); + state._emitUniformFromString(this._vReflectionMicrosurfaceInfosName, NodeMaterialBlockConnectionPointTypes.Vector3); + this._vReflectionInfosName = state._getFreeVariableName("vReflectionInfos"); + this._vReflectionFilteringInfoName = state._getFreeVariableName("vReflectionFilteringInfo"); + state._emitUniformFromString(this._vReflectionFilteringInfoName, NodeMaterialBlockConnectionPointTypes.Vector2); + code += `#ifdef REFLECTION + ${state._declareLocalVar(this._vReflectionInfosName, NodeMaterialBlockConnectionPointTypes.Vector2)} = vec2${state.fSuffix}(1., 0.); + + ${isWebGPU ? "var reflectionOut: reflectionOutParams" : "reflectionOutParams reflectionOut"}; + + reflectionOut = reflectionBlock( + ${this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : (isWebGPU ? "input." : "") + "v_" + this.worldPosition.associatedVariableName}.xyz + , ${normalVarName} + , alphaG + , ${(isWebGPU ? "uniforms." : "") + this._vReflectionMicrosurfaceInfosName} + , ${this._vReflectionInfosName} + , ${this.reflectionColor} + #ifdef ANISOTROPIC + ,anisotropicOut + #endif + #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName}) + ,NdotVUnclamped + #endif + #ifdef ${this._defineLinearSpecularReflection} + , roughness + #endif + #ifdef ${this._define3DName} + , ${this._cubeSamplerName} + ${isWebGPU ? `, ${this._cubeSamplerName}Sampler` : ""} + #else + , ${this._2DSamplerName} + ${isWebGPU ? `, ${this._2DSamplerName}Sampler` : ""} + #endif + #if defined(NORMAL) && defined(USESPHERICALINVERTEX) + , ${isWebGPU ? "input." : ""}${this._vEnvironmentIrradianceName} + #endif + #if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D)) + , ${this._reflectionMatrixName} + #endif + #ifdef USEIRRADIANCEMAP + , irradianceSampler // ** not handled ** + ${isWebGPU ? `, irradianceSamplerSampler` : ""} + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${this._define3DName} + , ${this._cubeSamplerName} + ${isWebGPU ? `, ${this._cubeSamplerName}Sampler` : ""} + , ${this._cubeSamplerName} + ${isWebGPU ? `, ${this._cubeSamplerName}Sampler` : ""} + #else + , ${this._2DSamplerName} + ${isWebGPU ? `, ${this._2DSamplerName}Sampler` : ""} + , ${this._2DSamplerName} + ${isWebGPU ? `, ${this._2DSamplerName}Sampler` : ""} + #endif + #endif + #ifdef REALTIME_FILTERING + , ${this._vReflectionFilteringInfoName} + #ifdef IBL_CDF_FILTERING + , icdfSampler // ** not handled ** + ${isWebGPU ? `, icdfSamplerSampler` : ""} + #endif + #endif + ); + #endif\n`; + return code; + } + _buildBlock(state) { + this._scene = state.sharedData.scene; + if (state.target !== NodeMaterialBlockTargets.Fragment) { + this._defineLODReflectionAlpha = state._getFreeDefineName("LODINREFLECTIONALPHA"); + this._defineLinearSpecularReflection = state._getFreeDefineName("LINEARSPECULARREFLECTION"); + } + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + if (this.texture) { + codeString += `${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};\n`; + } + codeString += `${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics};\n`; + codeString += `${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.useSphericalHarmonics = this.useSphericalHarmonics; + serializationObject.forceIrradianceInFragment = this.forceIrradianceInFragment; + serializationObject.gammaSpace = this.texture?.gammaSpace ?? true; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.useSphericalHarmonics = serializationObject.useSphericalHarmonics; + this.forceIrradianceInFragment = serializationObject.forceIrradianceInFragment; + if (this.texture) { + this.texture.gammaSpace = serializationObject.gammaSpace; + } + } +} +__decorate([ + editableInPropertyPage("Spherical Harmonics", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { update: true } }) +], ReflectionBlock.prototype, "useSphericalHarmonics", void 0); +__decorate([ + editableInPropertyPage("Force irradiance in fragment", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { update: true } }) +], ReflectionBlock.prototype, "forceIrradianceInFragment", void 0); +RegisterClass("BABYLON.ReflectionBlock", ReflectionBlock); + +/** + * Block used to implement the clear coat module of the PBR material + */ +class ClearCoatBlock extends NodeMaterialBlock { + /** + * Create a new ClearCoatBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this._tangentCorrectionFactorName = ""; + /** + * Defines if the F0 value should be remapped to account for the interface change in the material. + */ + this.remapF0OnInterfaceChange = true; + this._isUnique = true; + this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("tintColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("tintThickness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, true); + this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.worldNormal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3); + this.registerInput("TBN", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("TBN", this, 0 /* NodeMaterialConnectionPointDirection.Input */, TBNBlock, "TBNBlock")); + this.registerOutput("clearcoat", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("clearcoat", this, 1 /* NodeMaterialConnectionPointDirection.Output */, ClearCoatBlock, "ClearCoatBlock")); + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("clearcoatOut"); + state._excludeVariableName("vClearCoatParams"); + state._excludeVariableName("vClearCoatTintParams"); + state._excludeVariableName("vClearCoatRefractionParams"); + state._excludeVariableName("vClearCoatTangentSpaceParams"); + state._excludeVariableName("vGeometricNormaClearCoatW"); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ClearCoatBlock"; + } + /** + * Gets the intensity input component + */ + get intensity() { + return this._inputs[0]; + } + /** + * Gets the roughness input component + */ + get roughness() { + return this._inputs[1]; + } + /** + * Gets the ior input component + */ + get indexOfRefraction() { + return this._inputs[2]; + } + /** + * Gets the bump texture input component + */ + get normalMapColor() { + return this._inputs[3]; + } + /** + * Gets the uv input component + */ + get uv() { + return this._inputs[4]; + } + /** + * Gets the tint color input component + */ + get tintColor() { + return this._inputs[5]; + } + /** + * Gets the tint "at distance" input component + */ + get tintAtDistance() { + return this._inputs[6]; + } + /** + * Gets the tint thickness input component + */ + get tintThickness() { + return this._inputs[7]; + } + /** + * Gets the world tangent input component + */ + get worldTangent() { + return this._inputs[8]; + } + /** + * Gets the world normal input component + */ + get worldNormal() { + return this._inputs[9]; + } + /** + * Gets the TBN input component + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + get TBN() { + return this._inputs[10]; + } + /** + * Gets the clear coat object output component + */ + get clearcoat() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.intensity.isConnected) { + const intensityInput = new InputBlock("ClearCoat intensity", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); + intensityInput.value = 1; + intensityInput.output.connectTo(this.intensity); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + super.prepareDefines(mesh, nodeMaterial, defines); + defines.setValue("CLEARCOAT", true); + defines.setValue("CLEARCOAT_TEXTURE", false, true); + defines.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE", true, true); + defines.setValue("CLEARCOAT_TINT", this.tintColor.isConnected || this.tintThickness.isConnected || this.tintAtDistance.isConnected, true); + defines.setValue("CLEARCOAT_BUMP", this.normalMapColor.isConnected, true); + defines.setValue("CLEARCOAT_DEFAULTIOR", this.indexOfRefraction.isConnected ? this.indexOfRefraction.connectInputBlock.value === PBRClearCoatConfiguration._DefaultIndexOfRefraction : true, true); + defines.setValue("CLEARCOAT_REMAP_F0", this.remapF0OnInterfaceChange, true); + } + bind(effect, nodeMaterial, mesh) { + super.bind(effect, nodeMaterial, mesh); + // Clear Coat Refraction params + const indexOfRefraction = this.indexOfRefraction.connectInputBlock?.value ?? PBRClearCoatConfiguration._DefaultIndexOfRefraction; + const a = 1 - indexOfRefraction; + const b = 1 + indexOfRefraction; + const f0 = Math.pow(-a / b, 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1. + const eta = 1 / indexOfRefraction; + effect.setFloat4("vClearCoatRefractionParams", f0, eta, a, b); + // Clear Coat tangent space params + const mainPBRBlock = this.clearcoat.hasEndpoints ? this.clearcoat.endpoints[0].ownerBlock : null; + const perturbedNormalBlock = mainPBRBlock?.perturbedNormal.isConnected ? mainPBRBlock.perturbedNormal.connectedPoint.ownerBlock : null; + if (this._scene._mirroredCameraPosition) { + effect.setFloat2("vClearCoatTangentSpaceParams", perturbedNormalBlock?.invertX ? 1.0 : -1, perturbedNormalBlock?.invertY ? 1.0 : -1); + } + else { + effect.setFloat2("vClearCoatTangentSpaceParams", perturbedNormalBlock?.invertX ? -1 : 1.0, perturbedNormalBlock?.invertY ? -1 : 1.0); + } + if (mesh) { + effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1); + } + } + _generateTBNSpace(state, worldPositionVarName, worldNormalVarName) { + let code = ""; + const comments = `//${this.name}`; + const worldTangent = this.worldTangent; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + if (!isWebGPU) { + state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); + } + const tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" }; + const TBN = this.TBN; + if (TBN.isConnected) { + state.compilationString += ` + #ifdef TBNBLOCK + ${isWebGPU ? "var TBN" : "mat3 TBN"} = ${TBN.associatedVariableName}; + #endif + `; + } + else if (worldTangent.isConnected) { + code += `${state._declareLocalVar("tbnNormal", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldNormalVarName}.xyz);\n`; + code += `${state._declareLocalVar("tbnTangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldTangent.associatedVariableName}.xyz);\n`; + code += `${state._declareLocalVar("tbnBitangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`; + code += `${isWebGPU ? "var vTBN" : "mat3 vTBN"} = ${isWebGPU ? "mat3x3f" : "mat3"}(tbnTangent, tbnBitangent, tbnNormal);\n`; + } + state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, { + replaceStrings: [tangentReplaceString], + }); + return code; + } + /** @internal */ + static _GetInitializationCode(state, ccBlock) { + let code = ""; + const intensity = ccBlock?.intensity.isConnected ? ccBlock.intensity.associatedVariableName : "1."; + const roughness = ccBlock?.roughness.isConnected ? ccBlock.roughness.associatedVariableName : "0."; + const tintColor = ccBlock?.tintColor.isConnected ? ccBlock.tintColor.associatedVariableName : `vec3${state.fSuffix}(1.)`; + const tintThickness = ccBlock?.tintThickness.isConnected ? ccBlock.tintThickness.associatedVariableName : "1."; + code += ` + #ifdef CLEARCOAT + ${state._declareLocalVar("vClearCoatParams", NodeMaterialBlockConnectionPointTypes.Vector2)} = vec2${state.fSuffix}(${intensity}, ${roughness}); + ${state._declareLocalVar("vClearCoatTintParams", NodeMaterialBlockConnectionPointTypes.Vector4)} = vec4${state.fSuffix}(${tintColor}, ${tintThickness}); + #endif\n`; + return code; + } + /** + * Gets the main code of the block (fragment side) + * @param state current state of the node material building + * @param ccBlock instance of a ClearCoatBlock or null if the code must be generated without an active clear coat module + * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module + * @param worldPosVarName name of the variable holding the world position + * @param generateTBNSpace if true, the code needed to create the TBN coordinate space is generated + * @param vTBNAvailable indicate that the vTBN variable is already existing because it has already been generated by another block (PerturbNormal or Anisotropy) + * @param worldNormalVarName name of the variable holding the world normal + * @returns the shader code + */ + static GetCode(state, ccBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, worldNormalVarName) { + let code = ""; + const normalMapColor = ccBlock?.normalMapColor.isConnected ? ccBlock.normalMapColor.associatedVariableName : `vec3${state.fSuffix}(0.)`; + const uv = ccBlock?.uv.isConnected ? ccBlock.uv.associatedVariableName : `vec2${state.fSuffix}(0.)`; + const tintAtDistance = ccBlock?.tintAtDistance.isConnected ? ccBlock.tintAtDistance.associatedVariableName : "1."; + const tintTexture = `vec4${state.fSuffix}(0.)`; + if (ccBlock) { + state._emitUniformFromString("vClearCoatRefractionParams", NodeMaterialBlockConnectionPointTypes.Vector4); + state._emitUniformFromString("vClearCoatTangentSpaceParams", NodeMaterialBlockConnectionPointTypes.Vector2); + const normalShading = ccBlock.worldNormal; + code += `${state._declareLocalVar("vGeometricNormaClearCoatW", NodeMaterialBlockConnectionPointTypes.Vector3)} = ${normalShading.isConnected ? "normalize(" + normalShading.associatedVariableName + ".xyz)" : "geometricNormalW"};\n`; + } + else { + code += `${state._declareLocalVar("vGeometricNormaClearCoatW", NodeMaterialBlockConnectionPointTypes.Vector3)} = geometricNormalW;\n`; + } + if (generateTBNSpace && ccBlock) { + code += ccBlock._generateTBNSpace(state, worldPosVarName, worldNormalVarName); + vTBNAvailable = ccBlock.worldTangent.isConnected; + } + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + code += `${isWebGPU ? "var clearcoatOut: clearcoatOutParams" : "clearcoatOutParams clearcoatOut"}; + + #ifdef CLEARCOAT + clearcoatOut = clearcoatBlock( + ${worldPosVarName}.xyz + , vGeometricNormaClearCoatW + , viewDirectionW + , vClearCoatParams + , specularEnvironmentR0 + #ifdef CLEARCOAT_TEXTURE + , vec2${state.fSuffix}(0.) + #endif + #ifdef CLEARCOAT_TINT + , vClearCoatTintParams + , ${tintAtDistance} + , ${isWebGPU ? "uniforms." : ""}vClearCoatRefractionParams + #ifdef CLEARCOAT_TINT_TEXTURE + , ${tintTexture} + #endif + #endif + #ifdef CLEARCOAT_BUMP + , vec2${state.fSuffix}(0., 1.) + , vec4${state.fSuffix}(${normalMapColor}, 0.) + , ${uv} + #if defined(${vTBNAvailable ? "TANGENT" : "IGNORE"}) && defined(NORMAL) + , vTBN + #else + , ${isWebGPU ? "uniforms." : ""}vClearCoatTangentSpaceParams + #endif + #ifdef OBJECTSPACE_NORMALMAP + , normalMatrix + #endif + #endif + #if defined(FORCENORMALFORWARD) && defined(NORMAL) + , faceNormal + #endif + #ifdef REFLECTION + , ${isWebGPU ? "uniforms." : ""}${reflectionBlock?._vReflectionMicrosurfaceInfosName} + , ${reflectionBlock?._vReflectionInfosName} + , ${reflectionBlock?.reflectionColor} + , ${isWebGPU ? "uniforms." : ""}vLightingIntensity + #ifdef ${reflectionBlock?._define3DName} + , ${reflectionBlock?._cubeSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""} + #else + , ${reflectionBlock?._2DSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""} + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${reflectionBlock?._define3DName} + , ${reflectionBlock?._cubeSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""} + , ${reflectionBlock?._cubeSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""} + #else + , ${reflectionBlock?._2DSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""} + , ${reflectionBlock?._2DSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""} + #endif + #endif + #endif + #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) + , (${state._generateTernary("1.", "-1.", isWebGPU ? "fragmentInputs.frontFacing" : "gl_FrontFacing")}) + #endif + ); + #else + clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0; + #endif\n`; + return code; + } + _buildBlock(state) { + this._scene = state.sharedData.scene; + if (state.target === NodeMaterialBlockTargets.Fragment) { + state.sharedData.bindableBlocks.push(this); + state.sharedData.blocksWithDefines.push(this); + this._tangentCorrectionFactorName = state._getFreeDefineName("tangentCorrectionFactor"); + state._emitUniformFromString(this._tangentCorrectionFactorName, NodeMaterialBlockConnectionPointTypes.Float); + } + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.remapF0OnInterfaceChange = this.remapF0OnInterfaceChange; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.remapF0OnInterfaceChange = serializationObject.remapF0OnInterfaceChange ?? true; + } +} +__decorate([ + editableInPropertyPage("Remap F0 on interface change", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true }) +], ClearCoatBlock.prototype, "remapF0OnInterfaceChange", void 0); +RegisterClass("BABYLON.ClearCoatBlock", ClearCoatBlock); + +/** + * Block used to implement the iridescence module of the PBR material + */ +class IridescenceBlock extends NodeMaterialBlock { + /** + * Create a new IridescenceBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this._isUnique = true; + this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("thickness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerOutput("iridescence", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("iridescence", this, 1 /* NodeMaterialConnectionPointDirection.Output */, IridescenceBlock, "IridescenceBlock")); + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("iridescenceOut"); + state._excludeVariableName("vIridescenceParams"); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "IridescenceBlock"; + } + /** + * Gets the intensity input component + */ + get intensity() { + return this._inputs[0]; + } + /** + * Gets the indexOfRefraction input component + */ + get indexOfRefraction() { + return this._inputs[1]; + } + /** + * Gets the thickness input component + */ + get thickness() { + return this._inputs[2]; + } + /** + * Gets the iridescence object output component + */ + get iridescence() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.intensity.isConnected) { + const intensityInput = new InputBlock("Iridescence intensity", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); + intensityInput.value = 1; + intensityInput.output.connectTo(this.intensity); + const indexOfRefractionInput = new InputBlock("Iridescence ior", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); + indexOfRefractionInput.value = 1.3; + indexOfRefractionInput.output.connectTo(this.indexOfRefraction); + const thicknessInput = new InputBlock("Iridescence thickness", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); + thicknessInput.value = 400; + thicknessInput.output.connectTo(this.thickness); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + super.prepareDefines(mesh, nodeMaterial, defines); + defines.setValue("IRIDESCENCE", true, true); + defines.setValue("IRIDESCENCE_TEXTURE", false, true); + defines.setValue("IRIDESCENCE_THICKNESS_TEXTURE", false, true); + } + /** + * Gets the main code of the block (fragment side) + * @param iridescenceBlock instance of a IridescenceBlock or null if the code must be generated without an active iridescence module + * @param state defines the build state + * @returns the shader code + */ + static GetCode(iridescenceBlock, state) { + let code = ""; + const intensityName = iridescenceBlock?.intensity.isConnected ? iridescenceBlock.intensity.associatedVariableName : "1."; + const indexOfRefraction = iridescenceBlock?.indexOfRefraction.isConnected + ? iridescenceBlock.indexOfRefraction.associatedVariableName + : PBRIridescenceConfiguration._DefaultIndexOfRefraction; + const thickness = iridescenceBlock?.thickness.isConnected ? iridescenceBlock.thickness.associatedVariableName : PBRIridescenceConfiguration._DefaultMaximumThickness; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + code += `${isWebGPU ? "var iridescenceOut: iridescenceOutParams" : "iridescenceOutParams iridescenceOut"}; + + #ifdef IRIDESCENCE + iridescenceOut = iridescenceBlock( + vec4(${intensityName}, ${indexOfRefraction}, 1., ${thickness}) + , NdotV + , specularEnvironmentR0 + #ifdef CLEARCOAT + , NdotVUnclamped + , vClearCoatParams + #endif + ); + + ${isWebGPU ? "let" : "float"} iridescenceIntensity = iridescenceOut.iridescenceIntensity; + specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; + #endif\n`; + return code; + } + _buildBlock(state) { + if (state.target === NodeMaterialBlockTargets.Fragment) { + state.sharedData.bindableBlocks.push(this); + state.sharedData.blocksWithDefines.push(this); + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + } +} +RegisterClass("BABYLON.IridescenceBlock", IridescenceBlock); + +/** + * Block used to implement the refraction part of the sub surface module of the PBR material + */ +class RefractionBlock extends NodeMaterialBlock { + /** + * Create a new RefractionBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + /** + * This parameters will make the material used its opacity to control how much it is refracting against not. + * Materials half opaque for instance using refraction could benefit from this control. + */ + this.linkRefractionWithTransparency = false; + /** + * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. + */ + this.invertRefractionY = false; + /** + * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. + */ + this.useThicknessAsDepth = false; + this._isUnique = true; + this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("volumeIndexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerOutput("refraction", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("refraction", this, 1 /* NodeMaterialConnectionPointDirection.Output */, RefractionBlock, "RefractionBlock")); + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("vRefractionPosition"); + state._excludeVariableName("vRefractionSize"); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "RefractionBlock"; + } + /** + * Gets the intensity input component + */ + get intensity() { + return this._inputs[0]; + } + /** + * Gets the tint at distance input component + */ + get tintAtDistance() { + return this._inputs[1]; + } + /** + * Gets the volume index of refraction input component + */ + get volumeIndexOfRefraction() { + return this._inputs[2]; + } + /** + * Gets the view input component + */ + get view() { + return this.viewConnectionPoint; + } + /** + * Gets the refraction object output component + */ + get refraction() { + return this._outputs[0]; + } + /** + * Returns true if the block has a texture + */ + get hasTexture() { + return !!this._getTexture(); + } + _getTexture() { + if (this.texture) { + return this.texture; + } + return this._scene.environmentTexture; + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.intensity.isConnected) { + const intensityInput = new InputBlock("Refraction intensity", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); + intensityInput.value = 1; + intensityInput.output.connectTo(this.intensity); + } + if (this.view && !this.view.isConnected) { + let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View && additionalFilteringInfo(b)); + if (!viewInput) { + viewInput = new InputBlock("view"); + viewInput.setAsSystemValue(NodeMaterialSystemValues.View); + } + viewInput.output.connectTo(this.view); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + super.prepareDefines(mesh, nodeMaterial, defines); + const refractionTexture = this._getTexture(); + const refraction = refractionTexture && refractionTexture.getTextureMatrix; + defines.setValue("SS_REFRACTION", refraction, true); + if (!refraction) { + return; + } + defines.setValue(this._define3DName, refractionTexture.isCube, true); + defines.setValue(this._defineLODRefractionAlpha, refractionTexture.lodLevelInAlpha, true); + defines.setValue(this._defineLinearSpecularRefraction, refractionTexture.linearSpecularLOD, true); + defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem && refractionTexture.isCube ? !refractionTexture.invertZ : refractionTexture.invertZ, true); + defines.setValue("SS_LINKREFRACTIONTOTRANSPARENCY", this.linkRefractionWithTransparency, true); + defines.setValue("SS_GAMMAREFRACTION", refractionTexture.gammaSpace, true); + defines.setValue("SS_RGBDREFRACTION", refractionTexture.isRGBD, true); + defines.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC", refractionTexture.boundingBoxSize ? true : false, true); + defines.setValue("SS_USE_THICKNESS_AS_DEPTH", this.useThicknessAsDepth, true); + } + isReady() { + const texture = this._getTexture(); + if (texture && !texture.isReadyOrNotBlocking()) { + return false; + } + return true; + } + bind(effect, nodeMaterial, mesh) { + super.bind(effect, nodeMaterial, mesh); + const refractionTexture = this._getTexture(); + if (!refractionTexture) { + return; + } + if (refractionTexture.isCube) { + effect.setTexture(this._cubeSamplerName, refractionTexture); + } + else { + effect.setTexture(this._2DSamplerName, refractionTexture); + } + effect.setMatrix(this._refractionMatrixName, refractionTexture.getRefractionTextureMatrix()); + let depth = 1.0; + if (!refractionTexture.isCube) { + if (refractionTexture.depth) { + depth = refractionTexture.depth; + } + } + const indexOfRefraction = this.volumeIndexOfRefraction.connectInputBlock?.value ?? this.indexOfRefractionConnectionPoint.connectInputBlock?.value ?? 1.5; + effect.setFloat4(this._vRefractionInfosName, refractionTexture.level, 1 / indexOfRefraction, depth, this.invertRefractionY ? -1 : 1); + effect.setFloat4(this._vRefractionMicrosurfaceInfosName, refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset, 1 / indexOfRefraction); + const width = refractionTexture.getSize().width; + effect.setFloat2(this._vRefractionFilteringInfoName, width, Math.log2(width)); + if (refractionTexture.boundingBoxSize) { + const cubeTexture = refractionTexture; + effect.setVector3("vRefractionPosition", cubeTexture.boundingBoxPosition); + effect.setVector3("vRefractionSize", cubeTexture.boundingBoxSize); + } + } + /** + * Gets the main code of the block (fragment side) + * @param state current state of the node material building + * @returns the shader code + */ + getCode(state) { + const code = ""; + state.sharedData.blockingBlocks.push(this); + state.sharedData.textureBlocks.push(this); + // Samplers + this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler"); + state.samplers.push(this._cubeSamplerName); + this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler"); + state.samplers.push(this._2DSamplerName); + this._define3DName = state._getFreeDefineName("SS_REFRACTIONMAP_3D"); + const refractionTexture = this._getTexture(); + if (refractionTexture) { + state._samplerDeclaration += `#ifdef ${this._define3DName}\n`; + state._emitCubeSampler(this._cubeSamplerName, undefined, true); + state._samplerDeclaration += `#else\n`; + state._emit2DSampler(this._2DSamplerName, undefined, true); + state._samplerDeclaration += `#endif\n`; + } + // Fragment + state.sharedData.blocksWithDefines.push(this); + state.sharedData.bindableBlocks.push(this); + this._defineLODRefractionAlpha = state._getFreeDefineName("SS_LODINREFRACTIONALPHA"); + this._defineLinearSpecularRefraction = state._getFreeDefineName("SS_LINEARSPECULARREFRACTION"); + this._defineOppositeZ = state._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"); + this._refractionMatrixName = state._getFreeVariableName("refractionMatrix"); + state._emitUniformFromString(this._refractionMatrixName, NodeMaterialBlockConnectionPointTypes.Matrix); + if (state.shaderLanguage !== 1 /* ShaderLanguage.WGSL */) { + state._emitFunction("sampleRefraction", ` + #ifdef ${this._define3DName} + #define sampleRefraction(s, c) textureCube(s, c) + #else + #define sampleRefraction(s, c) texture2D(s, c) + #endif\n`, `//${this.name}`); + state._emitFunction("sampleRefractionLod", ` + #ifdef ${this._define3DName} + #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) + #else + #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) + #endif\n`, `//${this.name}`); + } + this._vRefractionMicrosurfaceInfosName = state._getFreeVariableName("vRefractionMicrosurfaceInfos"); + state._emitUniformFromString(this._vRefractionMicrosurfaceInfosName, NodeMaterialBlockConnectionPointTypes.Vector4); + this._vRefractionInfosName = state._getFreeVariableName("vRefractionInfos"); + state._emitUniformFromString(this._vRefractionInfosName, NodeMaterialBlockConnectionPointTypes.Vector4); + this._vRefractionFilteringInfoName = state._getFreeVariableName("vRefractionFilteringInfo"); + state._emitUniformFromString(this._vRefractionFilteringInfoName, NodeMaterialBlockConnectionPointTypes.Vector2); + state._emitUniformFromString("vRefractionPosition", NodeMaterialBlockConnectionPointTypes.Vector3); + state._emitUniformFromString("vRefractionSize", NodeMaterialBlockConnectionPointTypes.Vector3); + return code; + } + _buildBlock(state) { + this._scene = state.sharedData.scene; + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + if (this.texture) { + if (this.texture.isCube) { + codeString = `${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\n`; + } + else { + codeString = `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\n`; + } + codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`; + } + codeString += `${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\n`; + codeString += `${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\n`; + codeString += `${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + if (this.texture && !this.texture.isRenderTarget) { + serializationObject.texture = this.texture.serialize(); + } + serializationObject.linkRefractionWithTransparency = this.linkRefractionWithTransparency; + serializationObject.invertRefractionY = this.invertRefractionY; + serializationObject.useThicknessAsDepth = this.useThicknessAsDepth; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + if (serializationObject.texture) { + rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; + if (serializationObject.texture.isCube) { + this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl); + } + else { + this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl); + } + } + this.linkRefractionWithTransparency = serializationObject.linkRefractionWithTransparency; + this.invertRefractionY = serializationObject.invertRefractionY; + this.useThicknessAsDepth = !!serializationObject.useThicknessAsDepth; + } +} +__decorate([ + editableInPropertyPage("Link refraction to transparency", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { update: true } }) +], RefractionBlock.prototype, "linkRefractionWithTransparency", void 0); +__decorate([ + editableInPropertyPage("Invert refraction Y", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { update: true } }) +], RefractionBlock.prototype, "invertRefractionY", void 0); +__decorate([ + editableInPropertyPage("Use thickness as depth", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { update: true } }) +], RefractionBlock.prototype, "useThicknessAsDepth", void 0); +RegisterClass("BABYLON.RefractionBlock", RefractionBlock); + +/** + * Block used to implement the sub surface module of the PBR material + */ +class SubSurfaceBlock extends NodeMaterialBlock { + /** + * Create a new SubSurfaceBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment); + this._isUnique = true; + this.registerInput("thickness", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("tintColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("translucencyIntensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("translucencyDiffusionDist", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("refraction", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("refraction", this, 0 /* NodeMaterialConnectionPointDirection.Input */, RefractionBlock, "RefractionBlock")); + this.registerInput("dispersion", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerOutput("subsurface", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("subsurface", this, 1 /* NodeMaterialConnectionPointDirection.Output */, SubSurfaceBlock, "SubSurfaceBlock")); + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("subSurfaceOut"); + state._excludeVariableName("vThicknessParam"); + state._excludeVariableName("vTintColor"); + state._excludeVariableName("vTranslucencyColor"); + state._excludeVariableName("vSubSurfaceIntensity"); + state._excludeVariableName("dispersion"); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SubSurfaceBlock"; + } + /** + * Gets the thickness component + */ + get thickness() { + return this._inputs[0]; + } + /** + * Gets the tint color input component + */ + get tintColor() { + return this._inputs[1]; + } + /** + * Gets the translucency intensity input component + */ + get translucencyIntensity() { + return this._inputs[2]; + } + /** + * Gets the translucency diffusion distance input component + */ + get translucencyDiffusionDist() { + return this._inputs[3]; + } + /** + * Gets the refraction object parameters + */ + get refraction() { + return this._inputs[4]; + } + /** + * Gets the dispersion input component + */ + get dispersion() { + return this._inputs[5]; + } + /** + * Gets the sub surface object output component + */ + get subsurface() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.thickness.isConnected) { + const thicknessInput = new InputBlock("SubSurface thickness", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); + thicknessInput.value = 0; + thicknessInput.output.connectTo(this.thickness); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + super.prepareDefines(mesh, nodeMaterial, defines); + const translucencyEnabled = this.translucencyDiffusionDist.isConnected || this.translucencyIntensity.isConnected; + defines.setValue("SUBSURFACE", translucencyEnabled || this.refraction.isConnected, true); + defines.setValue("SS_TRANSLUCENCY", translucencyEnabled, true); + defines.setValue("SS_THICKNESSANDMASK_TEXTURE", false, true); + defines.setValue("SS_REFRACTIONINTENSITY_TEXTURE", false, true); + defines.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE", false, true); + defines.setValue("SS_USE_GLTF_TEXTURES", false, true); + defines.setValue("SS_DISPERSION", this.dispersion.isConnected, true); + } + /** + * Gets the main code of the block (fragment side) + * @param state current state of the node material building + * @param ssBlock instance of a SubSurfaceBlock or null if the code must be generated without an active sub surface module + * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module + * @param worldPosVarName name of the variable holding the world position + * @returns the shader code + */ + static GetCode(state, ssBlock, reflectionBlock, worldPosVarName) { + let code = ""; + const thickness = ssBlock?.thickness.isConnected ? ssBlock.thickness.associatedVariableName : "0."; + const tintColor = ssBlock?.tintColor.isConnected ? ssBlock.tintColor.associatedVariableName : "vec3(1.)"; + const translucencyIntensity = ssBlock?.translucencyIntensity.isConnected ? ssBlock?.translucencyIntensity.associatedVariableName : "1."; + const translucencyDiffusionDistance = ssBlock?.translucencyDiffusionDist.isConnected ? ssBlock?.translucencyDiffusionDist.associatedVariableName : "vec3(1.)"; + const refractionBlock = (ssBlock?.refraction.isConnected ? ssBlock?.refraction.connectedPoint?.ownerBlock : null); + const refractionTintAtDistance = refractionBlock?.tintAtDistance.isConnected ? refractionBlock.tintAtDistance.associatedVariableName : "1."; + const refractionIntensity = refractionBlock?.intensity.isConnected ? refractionBlock.intensity.associatedVariableName : "1."; + const refractionView = refractionBlock?.view.isConnected ? refractionBlock.view.associatedVariableName : ""; + const dispersion = ssBlock?.dispersion.isConnected ? ssBlock?.dispersion.associatedVariableName : "0.0"; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + code += refractionBlock?.getCode(state) ?? ""; + code += `${isWebGPU ? "var subSurfaceOut: subSurfaceOutParams" : "subSurfaceOutParams subSurfaceOut"}; + + #ifdef SUBSURFACE + ${state._declareLocalVar("vThicknessParam", NodeMaterialBlockConnectionPointTypes.Vector2)} = vec2${state.fSuffix}(0., ${thickness}); + ${state._declareLocalVar("vTintColor", NodeMaterialBlockConnectionPointTypes.Vector4)} = vec4${state.fSuffix}(${tintColor}, ${refractionTintAtDistance}); + ${state._declareLocalVar("vSubSurfaceIntensity", NodeMaterialBlockConnectionPointTypes.Vector3)} = vec3(${refractionIntensity}, ${translucencyIntensity}, 0.); + ${state._declareLocalVar("dispersion", NodeMaterialBlockConnectionPointTypes.Float)} = ${dispersion}; + subSurfaceOut = subSurfaceBlock( + vSubSurfaceIntensity + , vThicknessParam + , vTintColor + , normalW + , specularEnvironmentReflectance + #ifdef SS_THICKNESSANDMASK_TEXTURE + , vec4${state.fSuffix}(0.) + #endif + #ifdef REFLECTION + #ifdef SS_TRANSLUCENCY + , ${(isWebGPU ? "uniforms." : "") + reflectionBlock?._reflectionMatrixName} + #ifdef USESPHERICALFROMREFLECTIONMAP + #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) + , reflectionOut.irradianceVector + #endif + #if defined(REALTIME_FILTERING) + , ${reflectionBlock?._cubeSamplerName} + ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""} + , ${reflectionBlock?._vReflectionFilteringInfoName} + #endif + #endif + #ifdef USEIRRADIANCEMAP + , irradianceSampler + ${isWebGPU ? `, irradianceSamplerSampler` : ""} + #endif + #endif + #endif + #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) + , surfaceAlbedo + #endif + #ifdef SS_REFRACTION + , ${worldPosVarName}.xyz + , viewDirectionW + , ${refractionView} + , ${(isWebGPU ? "uniforms." : "") + (refractionBlock?._vRefractionInfosName ?? "")} + , ${(isWebGPU ? "uniforms." : "") + (refractionBlock?._refractionMatrixName ?? "")} + , ${(isWebGPU ? "uniforms." : "") + (refractionBlock?._vRefractionMicrosurfaceInfosName ?? "")} + , ${isWebGPU ? "uniforms." : ""}vLightingIntensity + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + , alpha + #endif + #ifdef ${refractionBlock?._defineLODRefractionAlpha ?? "IGNORE"} + , NdotVUnclamped + #endif + #ifdef ${refractionBlock?._defineLinearSpecularRefraction ?? "IGNORE"} + , roughness + #endif + , alphaG + #ifdef ${refractionBlock?._define3DName ?? "IGNORE"} + , ${refractionBlock?._cubeSamplerName ?? ""} + ${isWebGPU ? `, ${refractionBlock?._cubeSamplerName}Sampler` : ""} + #else + , ${refractionBlock?._2DSamplerName ?? ""} + ${isWebGPU ? `, ${refractionBlock?._2DSamplerName}Sampler` : ""} + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${refractionBlock?._define3DName ?? "IGNORE"} + , ${refractionBlock?._cubeSamplerName ?? ""} + ${isWebGPU ? `, ${refractionBlock?._cubeSamplerName}Sampler` : ""} + , ${refractionBlock?._cubeSamplerName ?? ""} + ${isWebGPU ? `, ${refractionBlock?._cubeSamplerName}Sampler` : ""} + #else + , ${refractionBlock?._2DSamplerName ?? ""} + ${isWebGPU ? `, ${refractionBlock?._2DSamplerName}Sampler` : ""} + , ${refractionBlock?._2DSamplerName ?? ""} + ${isWebGPU ? `, ${refractionBlock?._2DSamplerName}Sampler` : ""} + #endif + #endif + #ifdef ANISOTROPIC + , anisotropicOut + #endif + #ifdef REALTIME_FILTERING + , ${refractionBlock?._vRefractionFilteringInfoName ?? ""} + #endif + #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC + , vRefractionPosition + , vRefractionSize + #endif + #ifdef SS_DISPERSION + , dispersion + #endif + #endif + #ifdef SS_TRANSLUCENCY + , ${translucencyDiffusionDistance} + , vTintColor + #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE + , vec4${state.fSuffix}(0.) + #endif + #endif + ); + + #ifdef SS_REFRACTION + surfaceAlbedo = subSurfaceOut.surfaceAlbedo; + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha = subSurfaceOut.alpha; + #endif + #endif + #else + subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; + #endif\n`; + return code; + } + _buildBlock(state) { + if (state.target === NodeMaterialBlockTargets.Fragment) { + state.sharedData.blocksWithDefines.push(this); + } + return this; + } +} +RegisterClass("BABYLON.SubSurfaceBlock", SubSurfaceBlock); + +const mapOutputToVariable = { + ambientClr: ["finalAmbient", ""], + diffuseDir: ["finalDiffuse", ""], + specularDir: ["finalSpecularScaled", "!defined(UNLIT) && defined(SPECULARTERM)"], + clearcoatDir: ["finalClearCoatScaled", "!defined(UNLIT) && defined(CLEARCOAT)"], + sheenDir: ["finalSheenScaled", "!defined(UNLIT) && defined(SHEEN)"], + diffuseInd: ["finalIrradiance", "!defined(UNLIT) && defined(REFLECTION)"], + specularInd: ["finalRadianceScaled", "!defined(UNLIT) && defined(REFLECTION)"], + clearcoatInd: ["clearcoatOut.finalClearCoatRadianceScaled", "!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"], + sheenInd: ["sheenOut.finalSheenRadianceScaled", "!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"], + refraction: ["subSurfaceOut.finalRefraction", "!defined(UNLIT) && defined(SS_REFRACTION)"], + lighting: ["finalColor.rgb", ""], + shadow: ["aggShadow", ""], + alpha: ["alpha", ""], +}; +/** + * Block used to implement the PBR metallic/roughness model + * @see https://playground.babylonjs.com/#D8AK3Z#80 + */ +class PBRMetallicRoughnessBlock extends NodeMaterialBlock { + static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) { + const that = block; + if (that.worldPosition.isConnected || that.worldNormal.isConnected) { + that.generateOnlyFragmentCode = !that.generateOnlyFragmentCode; + Logger.Error("The worldPosition and worldNormal inputs must not be connected to be able to switch!"); + return false; + } + that._setTarget(); + return true; + } + _setTarget() { + this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment); + this.getInputByName("worldPosition").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; + this.getInputByName("worldNormal").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; + } + /** + * Create a new ReflectionBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.VertexAndFragment); + this._environmentBRDFTexture = null; + this._metallicReflectanceColor = Color3.White(); + this._metallicF0Factor = 1; + /** + * Intensity of the direct lights e.g. the four lights available in your scene. + * This impacts both the direct diffuse and specular highlights. + */ + this.directIntensity = 1.0; + /** + * Intensity of the environment e.g. how much the environment will light the object + * either through harmonics for rough material or through the reflection for shiny ones. + */ + this.environmentIntensity = 1.0; + /** + * This is a special control allowing the reduction of the specular highlights coming from the + * four lights of the scene. Those highlights may not be needed in full environment lighting. + */ + this.specularIntensity = 1.0; + /** + * Defines the falloff type used in this material. + * It by default is Physical. + */ + this.lightFalloff = 0; + /** + * Specifies that alpha test should be used + */ + this.useAlphaTest = false; + /** + * Defines the alpha limits in alpha test mode. + */ + this.alphaTestCutoff = 0.5; + /** + * Specifies that alpha blending should be used + */ + this.useAlphaBlending = false; + /** + * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones). + * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind. + */ + this.useRadianceOverAlpha = true; + /** + * Specifies that the material will keeps the specular highlights over a transparent surface (only the most luminous ones). + * A car glass is a good example of that. When sun reflects on it you can not see what is behind. + */ + this.useSpecularOverAlpha = true; + /** + * Enables specular anti aliasing in the PBR shader. + * It will both interacts on the Geometry for analytical and IBL lighting. + * It also prefilter the roughness map based on the bump values. + */ + this.enableSpecularAntiAliasing = false; + /** + * Enables realtime filtering on the texture. + */ + this.realTimeFiltering = false; + /** + * Quality switch for realtime filtering + */ + this.realTimeFilteringQuality = 8; + /** + * Defines if the material uses energy conservation. + */ + this.useEnergyConservation = true; + /** + * This parameters will enable/disable radiance occlusion by preventing the radiance to lit + * too much the area relying on ambient texture to define their ambient occlusion. + */ + this.useRadianceOcclusion = true; + /** + * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal + * makes the reflect vector face the model (under horizon). + */ + this.useHorizonOcclusion = true; + /** + * If set to true, no lighting calculations will be applied. + */ + this.unlit = false; + /** + * Force normal to face away from face. + */ + this.forceNormalForward = false; + /** Indicates that no code should be generated in the vertex shader. Can be useful in some specific circumstances (like when doing ray marching for eg) */ + this.generateOnlyFragmentCode = false; + /** + * Defines the material debug mode. + * It helps seeing only some components of the material while troubleshooting. + */ + this.debugMode = 0; + /** + * Specify from where on screen the debug mode should start. + * The value goes from -1 (full screen) to 1 (not visible) + * It helps with side by side comparison against the final render + * This defaults to 0 + */ + this.debugLimit = 0; + /** + * As the default viewing range might not be enough (if the ambient is really small for instance) + * You can use the factor to better multiply the final value. + */ + this.debugFactor = 1; + this._isUnique = true; + this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); + this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false); + this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("perturbedNormal", NodeMaterialBlockConnectionPointTypes.Vector4, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("baseColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("metallic", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); + this.registerInput("ambientOcc", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("opacity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("ambientColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); + this.registerInput("reflection", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("reflection", this, 0 /* NodeMaterialConnectionPointDirection.Input */, ReflectionBlock, "ReflectionBlock")); + this.registerInput("clearcoat", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("clearcoat", this, 0 /* NodeMaterialConnectionPointDirection.Input */, ClearCoatBlock, "ClearCoatBlock")); + this.registerInput("sheen", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("sheen", this, 0 /* NodeMaterialConnectionPointDirection.Input */, SheenBlock, "SheenBlock")); + this.registerInput("subsurface", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("subsurface", this, 0 /* NodeMaterialConnectionPointDirection.Input */, SubSurfaceBlock, "SubSurfaceBlock")); + this.registerInput("anisotropy", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("anisotropy", this, 0 /* NodeMaterialConnectionPointDirection.Input */, AnisotropyBlock, "AnisotropyBlock")); + this.registerInput("iridescence", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("iridescence", this, 0 /* NodeMaterialConnectionPointDirection.Input */, IridescenceBlock, "IridescenceBlock")); + this.registerOutput("ambientClr", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("diffuseDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("specularDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("clearcoatDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("sheenDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("diffuseInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("specularInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("clearcoatInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("sheenInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("refraction", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("lighting", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); + this.registerOutput("shadow", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + this.registerOutput("alpha", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + initialize(state) { + state._excludeVariableName("vLightingIntensity"); + state._excludeVariableName("geometricNormalW"); + state._excludeVariableName("normalW"); + state._excludeVariableName("faceNormal"); + state._excludeVariableName("albedoOpacityOut"); + state._excludeVariableName("surfaceAlbedo"); + state._excludeVariableName("alpha"); + state._excludeVariableName("aoOut"); + state._excludeVariableName("baseColor"); + state._excludeVariableName("reflectivityOut"); + state._excludeVariableName("microSurface"); + state._excludeVariableName("roughness"); + state._excludeVariableName("NdotVUnclamped"); + state._excludeVariableName("NdotV"); + state._excludeVariableName("alphaG"); + state._excludeVariableName("AARoughnessFactors"); + state._excludeVariableName("environmentBrdf"); + state._excludeVariableName("ambientMonochrome"); + state._excludeVariableName("seo"); + state._excludeVariableName("eho"); + state._excludeVariableName("environmentRadiance"); + state._excludeVariableName("irradianceVector"); + state._excludeVariableName("environmentIrradiance"); + state._excludeVariableName("diffuseBase"); + state._excludeVariableName("specularBase"); + state._excludeVariableName("preInfo"); + state._excludeVariableName("info"); + state._excludeVariableName("shadow"); + state._excludeVariableName("finalDiffuse"); + state._excludeVariableName("finalAmbient"); + state._excludeVariableName("ambientOcclusionForDirectDiffuse"); + state._excludeVariableName("finalColor"); + state._excludeVariableName("vClipSpacePosition"); + state._excludeVariableName("vDebugMode"); + this._initShaderSourceAsync(state.shaderLanguage); + } + async _initShaderSourceAsync(shaderLanguage) { + this._codeIsReady = false; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => pbr_vertex$1), Promise.resolve().then(() => pbr_fragment$1)]); + } + else { + await Promise.all([Promise.resolve().then(() => pbr_vertex), Promise.resolve().then(() => pbr_fragment)]); + } + this._codeIsReady = true; + this.onCodeIsReadyObservable.notifyObservers(this); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "PBRMetallicRoughnessBlock"; + } + /** + * Gets the world position input component + */ + get worldPosition() { + return this._inputs[0]; + } + /** + * Gets the world normal input component + */ + get worldNormal() { + return this._inputs[1]; + } + /** + * Gets the view matrix parameter + */ + get view() { + return this._inputs[2]; + } + /** + * Gets the camera position input component + */ + get cameraPosition() { + return this._inputs[3]; + } + /** + * Gets the perturbed normal input component + */ + get perturbedNormal() { + return this._inputs[4]; + } + /** + * Gets the base color input component + */ + get baseColor() { + return this._inputs[5]; + } + /** + * Gets the metallic input component + */ + get metallic() { + return this._inputs[6]; + } + /** + * Gets the roughness input component + */ + get roughness() { + return this._inputs[7]; + } + /** + * Gets the ambient occlusion input component + */ + get ambientOcc() { + return this._inputs[8]; + } + /** + * Gets the opacity input component + */ + get opacity() { + return this._inputs[9]; + } + /** + * Gets the index of refraction input component + */ + get indexOfRefraction() { + return this._inputs[10]; + } + /** + * Gets the ambient color input component + */ + get ambientColor() { + return this._inputs[11]; + } + /** + * Gets the reflection object parameters + */ + get reflection() { + return this._inputs[12]; + } + /** + * Gets the clear coat object parameters + */ + get clearcoat() { + return this._inputs[13]; + } + /** + * Gets the sheen object parameters + */ + get sheen() { + return this._inputs[14]; + } + /** + * Gets the sub surface object parameters + */ + get subsurface() { + return this._inputs[15]; + } + /** + * Gets the anisotropy object parameters + */ + get anisotropy() { + return this._inputs[16]; + } + /** + * Gets the iridescence object parameters + */ + get iridescence() { + return this._inputs[17]; + } + /** + * Gets the ambient output component + */ + get ambientClr() { + return this._outputs[0]; + } + /** + * Gets the diffuse output component + */ + get diffuseDir() { + return this._outputs[1]; + } + /** + * Gets the specular output component + */ + get specularDir() { + return this._outputs[2]; + } + /** + * Gets the clear coat output component + */ + get clearcoatDir() { + return this._outputs[3]; + } + /** + * Gets the sheen output component + */ + get sheenDir() { + return this._outputs[4]; + } + /** + * Gets the indirect diffuse output component + */ + get diffuseInd() { + return this._outputs[5]; + } + /** + * Gets the indirect specular output component + */ + get specularInd() { + return this._outputs[6]; + } + /** + * Gets the indirect clear coat output component + */ + get clearcoatInd() { + return this._outputs[7]; + } + /** + * Gets the indirect sheen output component + */ + get sheenInd() { + return this._outputs[8]; + } + /** + * Gets the refraction output component + */ + get refraction() { + return this._outputs[9]; + } + /** + * Gets the global lighting output component + */ + get lighting() { + return this._outputs[10]; + } + /** + * Gets the shadow output component + */ + get shadow() { + return this._outputs[11]; + } + /** + * Gets the alpha output component + */ + get alpha() { + return this._outputs[12]; + } + autoConfigure(material, additionalFilteringInfo = () => true) { + if (!this.cameraPosition.isConnected) { + let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition && additionalFilteringInfo(b)); + if (!cameraPositionInput) { + cameraPositionInput = new InputBlock("cameraPosition"); + cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition); + } + cameraPositionInput.output.connectTo(this.cameraPosition); + } + if (!this.view.isConnected) { + let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View && additionalFilteringInfo(b)); + if (!viewInput) { + viewInput = new InputBlock("view"); + viewInput.setAsSystemValue(NodeMaterialSystemValues.View); + } + viewInput.output.connectTo(this.view); + } + } + prepareDefines(mesh, nodeMaterial, defines) { + // General + defines.setValue("PBR", true); + defines.setValue("METALLICWORKFLOW", true); + defines.setValue("DEBUGMODE", this.debugMode, true); + defines.setValue("DEBUGMODE_FORCERETURN", true); + defines.setValue("NORMALXYSCALE", true); + defines.setValue("BUMP", this.perturbedNormal.isConnected, true); + defines.setValue("LODBASEDMICROSFURACE", this._scene.getEngine().getCaps().textureLOD); + // Albedo & Opacity + defines.setValue("ALBEDO", false, true); + defines.setValue("OPACITY", this.opacity.isConnected, true); + // Ambient occlusion + defines.setValue("AMBIENT", true, true); + defines.setValue("AMBIENTINGRAYSCALE", false, true); + // Reflectivity + defines.setValue("REFLECTIVITY", false, true); + defines.setValue("AOSTOREINMETALMAPRED", false, true); + defines.setValue("METALLNESSSTOREINMETALMAPBLUE", false, true); + defines.setValue("ROUGHNESSSTOREINMETALMAPALPHA", false, true); + defines.setValue("ROUGHNESSSTOREINMETALMAPGREEN", false, true); + // Lighting & colors + if (this.lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) { + defines.setValue("USEPHYSICALLIGHTFALLOFF", false); + defines.setValue("USEGLTFLIGHTFALLOFF", false); + } + else if (this.lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) { + defines.setValue("USEPHYSICALLIGHTFALLOFF", false); + defines.setValue("USEGLTFLIGHTFALLOFF", true); + } + else { + defines.setValue("USEPHYSICALLIGHTFALLOFF", true); + defines.setValue("USEGLTFLIGHTFALLOFF", false); + } + // Transparency + const alphaTestCutOffString = this.alphaTestCutoff.toString(); + defines.setValue("ALPHABLEND", this.useAlphaBlending, true); + defines.setValue("ALPHAFROMALBEDO", false, true); + defines.setValue("ALPHATEST", this.useAlphaTest, true); + defines.setValue("ALPHATESTVALUE", alphaTestCutOffString.indexOf(".") < 0 ? alphaTestCutOffString + "." : alphaTestCutOffString, true); + defines.setValue("OPACITYRGB", false, true); + // Rendering + defines.setValue("RADIANCEOVERALPHA", this.useRadianceOverAlpha, true); + defines.setValue("SPECULAROVERALPHA", this.useSpecularOverAlpha, true); + defines.setValue("SPECULARAA", this._scene.getEngine().getCaps().standardDerivatives && this.enableSpecularAntiAliasing, true); + defines.setValue("REALTIME_FILTERING", this.realTimeFiltering, true); + const scene = mesh.getScene(); + const engine = scene.getEngine(); + if (engine._features.needTypeSuffixInShaderConstants) { + defines.setValue("NUM_SAMPLES", this.realTimeFilteringQuality + "u", true); + } + else { + defines.setValue("NUM_SAMPLES", "" + this.realTimeFilteringQuality, true); + } + // Advanced + defines.setValue("BRDF_V_HEIGHT_CORRELATED", true); + defines.setValue("MS_BRDF_ENERGY_CONSERVATION", this.useEnergyConservation, true); + defines.setValue("RADIANCEOCCLUSION", this.useRadianceOcclusion, true); + defines.setValue("HORIZONOCCLUSION", this.useHorizonOcclusion, true); + defines.setValue("UNLIT", this.unlit, true); + defines.setValue("FORCENORMALFORWARD", this.forceNormalForward, true); + if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) { + defines.setValue("ENVIRONMENTBRDF", true); + defines.setValue("ENVIRONMENTBRDF_RGBD", this._environmentBRDFTexture.isRGBD, true); + } + else { + defines.setValue("ENVIRONMENTBRDF", false); + defines.setValue("ENVIRONMENTBRDF_RGBD", false); + } + if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) { + nodeMaterial.imageProcessingConfiguration.prepareDefines(defines); + } + if (!defines._areLightsDirty) { + return; + } + if (!this.light) { + // Lights + PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights); + defines._needNormals = true; + // Multiview + PrepareDefinesForMultiview(scene, defines); + } + else { + const state = { + needNormals: false, + needRebuild: false, + lightmapMode: false, + shadowEnabled: false, + specularEnabled: false, + }; + PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state); + if (state.needRebuild) { + defines.rebuild(); + } + } + } + updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) { + for (let lightIndex = 0; lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) { + if (!defines["LIGHT" + lightIndex]) { + break; + } + const onlyUpdateBuffersList = state.uniforms.indexOf("vLightData" + lightIndex) >= 0; + PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffers, onlyUpdateBuffersList, defines["IESLIGHTTEXTURE" + lightIndex]); + } + } + isReady(mesh, nodeMaterial, defines) { + if (this._environmentBRDFTexture && !this._environmentBRDFTexture.isReady()) { + return false; + } + if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) { + if (!nodeMaterial.imageProcessingConfiguration.isReady()) { + return false; + } + } + return true; + } + bind(effect, nodeMaterial, mesh) { + if (!mesh) { + return; + } + const scene = mesh.getScene(); + if (!this.light) { + BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights); + } + else { + BindLight(this.light, this._lightId, scene, effect, true); + } + effect.setTexture(this._environmentBrdfSamplerName, this._environmentBRDFTexture); + effect.setFloat2("vDebugMode", this.debugLimit, this.debugFactor); + const ambientScene = this._scene.ambientColor; + if (ambientScene) { + effect.setColor3("ambientFromScene", ambientScene); + } + const invertNormal = scene.useRightHandedSystem === (scene._mirroredCameraPosition != null); + effect.setFloat(this._invertNormalName, invertNormal ? -1 : 1); + effect.setFloat4("vLightingIntensity", this.directIntensity, 1, this.environmentIntensity * this._scene.environmentIntensity, this.specularIntensity); + // reflectivity bindings + const outsideIOR = 1; // consider air as clear coat and other layers would remap in the shader. + const ior = this.indexOfRefraction.connectInputBlock?.value ?? 1.5; + // We are here deriving our default reflectance from a common value for none metallic surface. + // Based of the schlick fresnel approximation model + // for dielectrics. + const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2); + // Tweak the default F0 and F90 based on our given setup + this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]); + const metallicF90 = this._metallicF0Factor; + effect.setColor4(this._vMetallicReflectanceFactorsName, TmpColors.Color3[0], metallicF90); + if (nodeMaterial.imageProcessingConfiguration) { + nodeMaterial.imageProcessingConfiguration.bind(effect); + } + } + _injectVertexCode(state) { + const worldPos = this.worldPosition; + const worldNormal = this.worldNormal; + const comments = `//${this.name}`; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + // Declaration + if (!this.light) { + // Emit for all lights + state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, { + repeatKey: "maxSimultaneousLights", + }); + this._lightId = 0; + state.sharedData.dynamicUniformBlocks.push(this); + } + else { + this._lightId = (state.counters["lightCounter"] !== undefined ? state.counters["lightCounter"] : -1) + 1; + state.counters["lightCounter"] = this._lightId; + state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, { + replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }], + }, this._lightId.toString()); + } + // Inject code in vertex + const worldPosVaryingName = "v_" + worldPos.associatedVariableName; + if (state._emitVaryingFromString(worldPosVaryingName, NodeMaterialBlockConnectionPointTypes.Vector4)) { + state.compilationString += (isWebGPU ? "vertexOutputs." : "") + `${worldPosVaryingName} = ${worldPos.associatedVariableName};\n`; + } + const worldNormalVaryingName = "v_" + worldNormal.associatedVariableName; + if (state._emitVaryingFromString(worldNormalVaryingName, NodeMaterialBlockConnectionPointTypes.Vector4)) { + state.compilationString += (isWebGPU ? "vertexOutputs." : "") + `${worldNormalVaryingName} = ${worldNormal.associatedVariableName};\n`; + } + const reflectionBlock = this.reflection.isConnected ? this.reflection.connectedPoint?.ownerBlock : null; + if (reflectionBlock) { + reflectionBlock.viewConnectionPoint = this.view; + } + state.compilationString += reflectionBlock?.handleVertexSide(state) ?? ""; + if (state._emitVaryingFromString("vClipSpacePosition", NodeMaterialBlockConnectionPointTypes.Vector4, "defined(IGNORE) || DEBUGMODE > 0")) { + state._injectAtEnd += `#if DEBUGMODE > 0\n`; + state._injectAtEnd += (isWebGPU ? "vertexOutputs." : "") + `vClipSpacePosition = ${isWebGPU ? "vertexOutputs.position" : "gl_Position"};\n`; + state._injectAtEnd += `#endif\n`; + } + if (this.light) { + state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { + replaceStrings: [ + { search: /{X}/g, replace: this._lightId.toString() }, + { search: /worldPos/g, replace: worldPos.associatedVariableName }, + ], + }); + } + else { + state.compilationString += `${state._declareLocalVar("worldPos", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${worldPos.associatedVariableName};\n`; + if (this.view.isConnected) { + state.compilationString += `${state._declareLocalVar("view", NodeMaterialBlockConnectionPointTypes.Matrix)} = ${this.view.associatedVariableName};\n`; + } + state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { + repeatKey: "maxSimultaneousLights", + }); + } + } + _getAlbedoOpacityCode(state) { + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + let code = isWebGPU ? "var albedoOpacityOut: albedoOpacityOutParams;\n" : `albedoOpacityOutParams albedoOpacityOut;\n`; + const albedoColor = this.baseColor.isConnected ? this.baseColor.associatedVariableName : "vec3(1.)"; + const opacity = this.opacity.isConnected ? this.opacity.associatedVariableName : "1."; + code += `albedoOpacityOut = albedoOpacityBlock( + vec4${state.fSuffix}(${albedoColor}, 1.) + #ifdef ALBEDO + ,vec4${state.fSuffix}(1.) + ,vec2${state.fSuffix}(1., 1.) + #endif + ,1. /* Base Weight */ + #ifdef OPACITY + ,vec4${state.fSuffix}(${opacity}) + ,vec2${state.fSuffix}(1., 1.) + #endif + ); + + ${state._declareLocalVar("surfaceAlbedo", NodeMaterialBlockConnectionPointTypes.Vector3)} = albedoOpacityOut.surfaceAlbedo; + ${state._declareLocalVar("alpha", NodeMaterialBlockConnectionPointTypes.Float)} = albedoOpacityOut.alpha;\n`; + return code; + } + _getAmbientOcclusionCode(state) { + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + let code = isWebGPU ? "var aoOut: ambientOcclusionOutParams;\n" : `ambientOcclusionOutParams aoOut;\n`; + const ao = this.ambientOcc.isConnected ? this.ambientOcc.associatedVariableName : "1."; + code += `aoOut = ambientOcclusionBlock( + #ifdef AMBIENT + vec3${state.fSuffix}(${ao}), + vec4${state.fSuffix}(0., 1.0, 1.0, 0.) + #endif + );\n`; + return code; + } + _getReflectivityCode(state) { + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + let code = isWebGPU ? "var reflectivityOut: reflectivityOutParams;\n" : `reflectivityOutParams reflectivityOut;\n`; + const aoIntensity = "1."; + this._vMetallicReflectanceFactorsName = state._getFreeVariableName("vMetallicReflectanceFactors"); + state._emitUniformFromString(this._vMetallicReflectanceFactorsName, NodeMaterialBlockConnectionPointTypes.Vector4); + code += `${state._declareLocalVar("baseColor", NodeMaterialBlockConnectionPointTypes.Vector3)} = surfaceAlbedo; + + reflectivityOut = reflectivityBlock( + vec4${state.fSuffix}(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.) + #ifdef METALLICWORKFLOW + , surfaceAlbedo + , ${(isWebGPU ? "uniforms." : "") + this._vMetallicReflectanceFactorsName} + #endif + #ifdef REFLECTIVITY + , vec3${state.fSuffix}(0., 0., ${aoIntensity}) + , vec4${state.fSuffix}(1.) + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + , aoOut.ambientOcclusionColor + #endif + #ifdef MICROSURFACEMAP + , microSurfaceTexel <== not handled! + #endif + ); + + ${state._declareLocalVar("microSurface", NodeMaterialBlockConnectionPointTypes.Float)} = reflectivityOut.microSurface; + ${state._declareLocalVar("roughness", NodeMaterialBlockConnectionPointTypes.Float)} = reflectivityOut.roughness; + + #ifdef METALLICWORKFLOW + surfaceAlbedo = reflectivityOut.surfaceAlbedo; + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; + #endif\n`; + return code; + } + _buildBlock(state) { + super._buildBlock(state); + this._scene = state.sharedData.scene; + const isWebGPU = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + if (!this._environmentBRDFTexture) { + this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this._scene); + } + const reflectionBlock = this.reflection.isConnected ? this.reflection.connectedPoint?.ownerBlock : null; + if (reflectionBlock) { + // Need those variables to be setup when calling _injectVertexCode + reflectionBlock.worldPositionConnectionPoint = this.worldPosition; + reflectionBlock.cameraPositionConnectionPoint = this.cameraPosition; + reflectionBlock.worldNormalConnectionPoint = this.worldNormal; + reflectionBlock.viewConnectionPoint = this.view; + } + if (state.target !== NodeMaterialBlockTargets.Fragment) { + // Vertex + this._injectVertexCode(state); + return this; + } + // Fragment + state.sharedData.forcedBindableBlocks.push(this); + state.sharedData.blocksWithDefines.push(this); + state.sharedData.blockingBlocks.push(this); + if (this.generateOnlyFragmentCode) { + state.sharedData.dynamicUniformBlocks.push(this); + } + const comments = `//${this.name}`; + const normalShading = this.perturbedNormal; + let worldPosVarName = this.worldPosition.associatedVariableName; + let worldNormalVarName = this.worldNormal.associatedVariableName; + if (this.generateOnlyFragmentCode) { + worldPosVarName = state._getFreeVariableName("globalWorldPos"); + state._emitFunction("pbr_globalworldpos", isWebGPU ? `var ${worldPosVarName}:vec3${state.fSuffix};\n` : `vec3${state.fSuffix} ${worldPosVarName};\n`, comments); + state.compilationString += `${worldPosVarName} = ${this.worldPosition.associatedVariableName}.xyz;\n`; + worldNormalVarName = state._getFreeVariableName("globalWorldNormal"); + state._emitFunction("pbr_globalworldnorm", isWebGPU ? `var ${worldNormalVarName}:vec4${state.fSuffix};\n` : `vec4${state.fSuffix} ${worldNormalVarName};\n`, comments); + state.compilationString += `${worldNormalVarName} = ${this.worldNormal.associatedVariableName};\n`; + state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { + repeatKey: "maxSimultaneousLights", + substitutionVars: this.generateOnlyFragmentCode ? `worldPos,${this.worldPosition.associatedVariableName}` : undefined, + }); + state.compilationString += `#if DEBUGMODE > 0\n`; + state.compilationString += `${state._declareLocalVar("vClipSpacePosition", NodeMaterialBlockConnectionPointTypes.Vector4)} = vec4${state.fSuffix}((vec2${state.fSuffix}(${isWebGPU ? "fragmentInputs.position" : "gl_FragCoord.xy"}) / vec2${state.fSuffix}(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n`; + state.compilationString += `#endif\n`; + } + else { + worldPosVarName = (isWebGPU ? "input." : "") + "v_" + worldPosVarName; + worldNormalVarName = (isWebGPU ? "input." : "") + "v_" + worldNormalVarName; + } + this._environmentBrdfSamplerName = state._getFreeVariableName("environmentBrdfSampler"); + state._emit2DSampler(this._environmentBrdfSamplerName); + state.sharedData.hints.needAlphaBlending = state.sharedData.hints.needAlphaBlending || this.useAlphaBlending; + state.sharedData.hints.needAlphaTesting = state.sharedData.hints.needAlphaTesting || this.useAlphaTest; + state._emitExtension("lod", "#extension GL_EXT_shader_texture_lod : enable", "defined(LODBASEDMICROSFURACE)"); + state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); + state._emitUniformFromString("vDebugMode", NodeMaterialBlockConnectionPointTypes.Vector2, "defined(IGNORE) || DEBUGMODE > 0"); + state._emitUniformFromString("ambientFromScene", NodeMaterialBlockConnectionPointTypes.Vector3); + // Image processing uniforms + state.uniforms.push("exposureLinear"); + state.uniforms.push("contrast"); + state.uniforms.push("vInverseScreenSize"); + state.uniforms.push("vignetteSettings1"); + state.uniforms.push("vignetteSettings2"); + state.uniforms.push("vCameraColorCurveNegative"); + state.uniforms.push("vCameraColorCurveNeutral"); + state.uniforms.push("vCameraColorCurvePositive"); + state.uniforms.push("txColorTransform"); + state.uniforms.push("colorTransformSettings"); + state.uniforms.push("ditherIntensity"); + // + // Includes + // + if (!this.light) { + // Emit for all lights + state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, { + repeatKey: "maxSimultaneousLights", + substitutionVars: this.generateOnlyFragmentCode ? "varying," : undefined, + }); + } + else { + state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, { + replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }], + }, this._lightId.toString()); + } + state._emitFunctionFromInclude("helperFunctions", comments); + state._emitFunctionFromInclude("importanceSampling", comments); + state._emitFunctionFromInclude("pbrHelperFunctions", comments); + state._emitFunctionFromInclude("imageProcessingDeclaration", comments); + state._emitFunctionFromInclude("imageProcessingFunctions", comments); + state._emitFunctionFromInclude("shadowsFragmentFunctions", comments); + state._emitFunctionFromInclude("pbrDirectLightingSetupFunctions", comments); + state._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions", comments); + state._emitFunctionFromInclude("pbrBRDFFunctions", comments, { + replaceStrings: [{ search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" }], + }); + state._emitFunctionFromInclude("hdrFilteringFunctions", comments); + state._emitFunctionFromInclude("pbrDirectLightingFunctions", comments); + state._emitFunctionFromInclude("pbrIBLFunctions", comments); + state._emitFunctionFromInclude("pbrBlockAlbedoOpacity", comments); + state._emitFunctionFromInclude("pbrBlockReflectivity", comments); + state._emitFunctionFromInclude("pbrBlockAmbientOcclusion", comments); + state._emitFunctionFromInclude("pbrBlockAlphaFresnel", comments); + state._emitFunctionFromInclude("pbrBlockAnisotropic", comments); + // + // code + // + state._emitUniformFromString("vLightingIntensity", NodeMaterialBlockConnectionPointTypes.Vector4); + if (reflectionBlock?.generateOnlyFragmentCode) { + state.compilationString += reflectionBlock.handleVertexSide(state); + } + // _____________________________ Geometry Information ____________________________ + this._vNormalWName = state._getFreeVariableName("vNormalW"); + state.compilationString += `${state._declareLocalVar(this._vNormalWName, NodeMaterialBlockConnectionPointTypes.Vector4)} = normalize(${worldNormalVarName});\n`; + if (state._registerTempVariable("viewDirectionW")) { + state.compilationString += `${state._declareLocalVar("viewDirectionW", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${worldPosVarName}.xyz);\n`; + } + state.compilationString += `${state._declareLocalVar("geometricNormalW", NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this._vNormalWName}.xyz;\n`; + state.compilationString += `${state._declareLocalVar("normalW", NodeMaterialBlockConnectionPointTypes.Vector3)} = ${normalShading.isConnected ? "normalize(" + normalShading.associatedVariableName + ".xyz)" : "geometricNormalW"};\n`; + this._invertNormalName = state._getFreeVariableName("invertNormal"); + state._emitUniformFromString(this._invertNormalName, NodeMaterialBlockConnectionPointTypes.Float); + state.compilationString += state._emitCodeFromInclude("pbrBlockNormalFinal", comments, { + replaceStrings: [ + { search: /vPositionW/g, replace: worldPosVarName + ".xyz" }, + { search: /vEyePosition.w/g, replace: this._invertNormalName }, + ], + }); + // _____________________________ Albedo & Opacity ______________________________ + state.compilationString += this._getAlbedoOpacityCode(state); + state.compilationString += state._emitCodeFromInclude("depthPrePass", comments); + // _____________________________ AO _______________________________ + state.compilationString += this._getAmbientOcclusionCode(state); + state.compilationString += state._emitCodeFromInclude("pbrBlockLightmapInit", comments); + // _____________________________ UNLIT _______________________________ + state.compilationString += `#ifdef UNLIT + ${state._declareLocalVar("diffuseBase", NodeMaterialBlockConnectionPointTypes.Vector3)} = vec3${state.fSuffix}(1., 1., 1.); + #else\n`; + // _____________________________ Reflectivity _______________________________ + state.compilationString += this._getReflectivityCode(state); + // _____________________________ Geometry info _________________________________ + state.compilationString += state._emitCodeFromInclude("pbrBlockGeometryInfo", comments, { + replaceStrings: [ + { search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" }, + { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" }, + ], + }); + // _____________________________ Anisotropy _______________________________________ + const anisotropyBlock = this.anisotropy.isConnected ? this.anisotropy.connectedPoint?.ownerBlock : null; + if (anisotropyBlock) { + anisotropyBlock.worldPositionConnectionPoint = this.worldPosition; + anisotropyBlock.worldNormalConnectionPoint = this.worldNormal; + state.compilationString += anisotropyBlock.getCode(state, !this.perturbedNormal.isConnected); + } + // _____________________________ Reflection _______________________________________ + if (reflectionBlock && reflectionBlock.hasTexture) { + state.compilationString += reflectionBlock.getCode(state, anisotropyBlock ? "anisotropicOut.anisotropicNormal" : "normalW"); + } + state._emitFunctionFromInclude("pbrBlockReflection", comments, { + replaceStrings: [ + { search: /computeReflectionCoords/g, replace: "computeReflectionCoordsPBR" }, + { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" }, + { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: reflectionBlock?._defineOppositeZ ?? "REFLECTIONMAP_OPPOSITEZ" }, + { search: /REFLECTIONMAP_PROJECTION/g, replace: reflectionBlock?._defineProjectionName ?? "REFLECTIONMAP_PROJECTION" }, + { search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" }, + { search: /LODINREFLECTIONALPHA/g, replace: reflectionBlock?._defineLODReflectionAlpha ?? "LODINREFLECTIONALPHA" }, + { search: /LINEARSPECULARREFLECTION/g, replace: reflectionBlock?._defineLinearSpecularReflection ?? "LINEARSPECULARREFLECTION" }, + { search: /vReflectionFilteringInfo/g, replace: reflectionBlock?._vReflectionFilteringInfoName ?? "vReflectionFilteringInfo" }, + ], + }); + // ___________________ Compute Reflectance aka R0 F0 info _________________________ + state.compilationString += state._emitCodeFromInclude("pbrBlockReflectance0", comments, { + replaceStrings: [{ search: /metallicReflectanceFactors/g, replace: (isWebGPU ? "uniforms." : "") + this._vMetallicReflectanceFactorsName }], + }); + // ________________________________ Sheen ______________________________ + const sheenBlock = this.sheen.isConnected ? this.sheen.connectedPoint?.ownerBlock : null; + if (sheenBlock) { + state.compilationString += sheenBlock.getCode(reflectionBlock, state); + } + state._emitFunctionFromInclude("pbrBlockSheen", comments, { + replaceStrings: [ + { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" }, + { search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" }, + { search: /LODINREFLECTIONALPHA/g, replace: reflectionBlock?._defineLODReflectionAlpha ?? "LODINREFLECTIONALPHA" }, + { search: /LINEARSPECULARREFLECTION/g, replace: reflectionBlock?._defineLinearSpecularReflection ?? "LINEARSPECULARREFLECTION" }, + ], + }); + // ____________________ Clear Coat Initialization Code _____________________ + const clearcoatBlock = this.clearcoat.isConnected ? this.clearcoat.connectedPoint?.ownerBlock : null; + state.compilationString += ClearCoatBlock._GetInitializationCode(state, clearcoatBlock); + // _____________________________ Iridescence _______________________________ + const iridescenceBlock = this.iridescence.isConnected ? this.iridescence.connectedPoint?.ownerBlock : null; + state.compilationString += IridescenceBlock.GetCode(iridescenceBlock, state); + state._emitFunctionFromInclude("pbrBlockIridescence", comments, { + replaceStrings: [], + }); + // _____________________________ Clear Coat ____________________________ + const generateTBNSpace = !this.perturbedNormal.isConnected && !this.anisotropy.isConnected; + const isTangentConnectedToPerturbNormal = this.perturbedNormal.isConnected && (this.perturbedNormal.connectedPoint?.ownerBlock).worldTangent?.isConnected; + const isTangentConnectedToAnisotropy = this.anisotropy.isConnected && (this.anisotropy.connectedPoint?.ownerBlock).worldTangent.isConnected; + let vTBNAvailable = isTangentConnectedToPerturbNormal || (!this.perturbedNormal.isConnected && isTangentConnectedToAnisotropy); + state.compilationString += ClearCoatBlock.GetCode(state, clearcoatBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, worldNormalVarName); + if (generateTBNSpace) { + vTBNAvailable = clearcoatBlock?.worldTangent.isConnected ?? false; + } + state._emitFunctionFromInclude("pbrBlockClearcoat", comments, { + replaceStrings: [ + { search: /computeReflectionCoords/g, replace: "computeReflectionCoordsPBR" }, + { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" }, + { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: reflectionBlock?._defineOppositeZ ?? "REFLECTIONMAP_OPPOSITEZ" }, + { search: /REFLECTIONMAP_PROJECTION/g, replace: reflectionBlock?._defineProjectionName ?? "REFLECTIONMAP_PROJECTION" }, + { search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" }, + { search: /LODINREFLECTIONALPHA/g, replace: reflectionBlock?._defineLODReflectionAlpha ?? "LODINREFLECTIONALPHA" }, + { search: /LINEARSPECULARREFLECTION/g, replace: reflectionBlock?._defineLinearSpecularReflection ?? "LINEARSPECULARREFLECTION" }, + { search: /defined\(TANGENT\)/g, replace: vTBNAvailable ? "defined(TANGENT)" : "defined(IGNORE)" }, + ], + }); + // _________________________ Specular Environment Reflectance __________________________ + state.compilationString += state._emitCodeFromInclude("pbrBlockReflectance", comments, { + replaceStrings: [ + { search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" }, + { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" }, + ], + }); + // ___________________________________ SubSurface ______________________________________ + const subsurfaceBlock = this.subsurface.isConnected ? this.subsurface.connectedPoint?.ownerBlock : null; + const refractionBlock = this.subsurface.isConnected + ? (this.subsurface.connectedPoint?.ownerBlock).refraction.connectedPoint?.ownerBlock + : null; + if (refractionBlock) { + refractionBlock.viewConnectionPoint = this.view; + refractionBlock.indexOfRefractionConnectionPoint = this.indexOfRefraction; + } + state.compilationString += SubSurfaceBlock.GetCode(state, subsurfaceBlock, reflectionBlock, worldPosVarName); + state._emitFunctionFromInclude("pbrBlockSubSurface", comments, { + replaceStrings: [ + { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" }, + { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: reflectionBlock?._defineOppositeZ ?? "REFLECTIONMAP_OPPOSITEZ" }, + { search: /REFLECTIONMAP_PROJECTION/g, replace: reflectionBlock?._defineProjectionName ?? "REFLECTIONMAP_PROJECTION" }, + { search: /SS_REFRACTIONMAP_3D/g, replace: refractionBlock?._define3DName ?? "SS_REFRACTIONMAP_3D" }, + { search: /SS_LODINREFRACTIONALPHA/g, replace: refractionBlock?._defineLODRefractionAlpha ?? "SS_LODINREFRACTIONALPHA" }, + { search: /SS_LINEARSPECULARREFRACTION/g, replace: refractionBlock?._defineLinearSpecularRefraction ?? "SS_LINEARSPECULARREFRACTION" }, + { search: /SS_REFRACTIONMAP_OPPOSITEZ/g, replace: refractionBlock?._defineOppositeZ ?? "SS_REFRACTIONMAP_OPPOSITEZ" }, + ], + }); + // _____________________________ Direct Lighting Info __________________________________ + state.compilationString += state._emitCodeFromInclude("pbrBlockDirectLighting", comments); + if (this.light) { + state.compilationString += state._emitCodeFromInclude("lightFragment", comments, { + replaceStrings: [ + { search: /{X}/g, replace: this._lightId.toString() }, + { search: new RegExp(`${isWebGPU ? "fragmentInputs." : ""}vPositionW`, "g"), replace: worldPosVarName + ".xyz" }, + ], + }); + } + else { + state.compilationString += state._emitCodeFromInclude("lightFragment", comments, { + repeatKey: "maxSimultaneousLights", + substitutionVars: `${isWebGPU ? "fragmentInputs." : ""}vPositionW,${worldPosVarName}.xyz`, + }); + } + // _____________________________ Compute Final Lit Components ________________________ + state.compilationString += state._emitCodeFromInclude("pbrBlockFinalLitComponents", comments); + // _____________________________ UNLIT (2) ________________________ + state.compilationString += `#endif\n`; // UNLIT + // _____________________________ Compute Final Unlit Components ________________________ + const aoColor = this.ambientColor.isConnected ? this.ambientColor.associatedVariableName : `vec3${state.fSuffix}(0., 0., 0.)`; + let aoDirectLightIntensity = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString(); + if (aoDirectLightIntensity.indexOf(".") === -1) { + aoDirectLightIntensity += "."; + } + let replaceStrings = [ + { search: /vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g, replace: "" }, + { search: new RegExp(`${isWebGPU ? "uniforms." : ""}vAmbientColor`, "g"), replace: aoColor + ` * ${isWebGPU ? "uniforms." : ""}ambientFromScene` }, + { search: new RegExp(`${isWebGPU ? "uniforms." : ""}vAmbientInfos.w`, "g"), replace: aoDirectLightIntensity }, + ]; + if (isWebGPU) { + replaceStrings[0] = { search: /var finalEmissive[\s\S]*?finalEmissive\*=uniforms.vLightingIntensity\.y;/g, replace: "" }; + } + state.compilationString += state._emitCodeFromInclude("pbrBlockFinalUnlitComponents", comments, { + replaceStrings: replaceStrings, + }); + // _____________________________ Output Final Color Composition ________________________ + state.compilationString += state._emitCodeFromInclude("pbrBlockFinalColorComposition", comments, { + replaceStrings: [{ search: /finalEmissive/g, replace: `vec3${state.fSuffix}(0.)` }], + }); + // _____________________________ Apply image processing ________________________ + if (isWebGPU) { + replaceStrings = [{ search: /mesh.visibility/g, replace: "1." }]; + } + else { + replaceStrings = [{ search: /visibility/g, replace: "1." }]; + } + state.compilationString += state._emitCodeFromInclude("pbrBlockImageProcessing", comments, { + replaceStrings: replaceStrings, + }); + // _____________________________ Generate debug code ________________________ + const colorOutput = isWebGPU ? "fragmentOutputs.color" : "gl_FragColor"; + replaceStrings = [ + { search: new RegExp(`${isWebGPU ? "fragmentInputs." : ""}vNormalW`, "g"), replace: this._vNormalWName }, + { search: new RegExp(`${isWebGPU ? "fragmentInputs." : ""}vPositionW`, "g"), replace: worldPosVarName }, + { + search: /albedoTexture\.rgb;/g, + replace: `vec3${state.fSuffix}(1.);\n${colorOutput}.rgb = toGammaSpace(${colorOutput}.rgb);\n`, + }, + ]; + state.compilationString += state._emitCodeFromInclude("pbrDebug", comments, { + replaceStrings: replaceStrings, + }); + // _____________________________ Generate end points ________________________ + for (const output of this._outputs) { + if (output.hasEndpoints) { + const remap = mapOutputToVariable[output.name]; + if (remap) { + const [varName, conditions] = remap; + if (conditions) { + state.compilationString += `#if ${conditions}\n`; + } + state.compilationString += `${state._declareOutput(output)} = ${varName};\n`; + if (conditions) { + state.compilationString += `#else\n`; + state.compilationString += `${state._declareOutput(output)} = vec3${state.fSuffix}(0.);\n`; + state.compilationString += `#endif\n`; + } + } + else { + Logger.Error(`There's no remapping for the ${output.name} end point! No code generated`); + } + } + } + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\n`; + codeString += `${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\n`; + codeString += `${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\n`; + codeString += `${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\n`; + codeString += `${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\n`; + codeString += `${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\n`; + codeString += `${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\n`; + codeString += `${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\n`; + codeString += `${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\n`; + codeString += `${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\n`; + codeString += `${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\n`; + codeString += `${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\n`; + codeString += `${this._codeVariableName}.unlit = ${this.unlit};\n`; + codeString += `${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\n`; + codeString += `${this._codeVariableName}.debugMode = ${this.debugMode};\n`; + codeString += `${this._codeVariableName}.debugLimit = ${this.debugLimit};\n`; + codeString += `${this._codeVariableName}.debugFactor = ${this.debugFactor};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + if (this.light) { + serializationObject.lightId = this.light.id; + } + serializationObject.lightFalloff = this.lightFalloff; + serializationObject.useAlphaTest = this.useAlphaTest; + serializationObject.alphaTestCutoff = this.alphaTestCutoff; + serializationObject.useAlphaBlending = this.useAlphaBlending; + serializationObject.useRadianceOverAlpha = this.useRadianceOverAlpha; + serializationObject.useSpecularOverAlpha = this.useSpecularOverAlpha; + serializationObject.enableSpecularAntiAliasing = this.enableSpecularAntiAliasing; + serializationObject.realTimeFiltering = this.realTimeFiltering; + serializationObject.realTimeFilteringQuality = this.realTimeFilteringQuality; + serializationObject.useEnergyConservation = this.useEnergyConservation; + serializationObject.useRadianceOcclusion = this.useRadianceOcclusion; + serializationObject.useHorizonOcclusion = this.useHorizonOcclusion; + serializationObject.unlit = this.unlit; + serializationObject.forceNormalForward = this.forceNormalForward; + serializationObject.debugMode = this.debugMode; + serializationObject.debugLimit = this.debugLimit; + serializationObject.debugFactor = this.debugFactor; + serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + if (serializationObject.lightId) { + this.light = scene.getLightById(serializationObject.lightId); + } + this.lightFalloff = serializationObject.lightFalloff ?? 0; + this.useAlphaTest = serializationObject.useAlphaTest; + this.alphaTestCutoff = serializationObject.alphaTestCutoff; + this.useAlphaBlending = serializationObject.useAlphaBlending; + this.useRadianceOverAlpha = serializationObject.useRadianceOverAlpha; + this.useSpecularOverAlpha = serializationObject.useSpecularOverAlpha; + this.enableSpecularAntiAliasing = serializationObject.enableSpecularAntiAliasing; + this.realTimeFiltering = !!serializationObject.realTimeFiltering; + this.realTimeFilteringQuality = serializationObject.realTimeFilteringQuality ?? 8; + this.useEnergyConservation = serializationObject.useEnergyConservation; + this.useRadianceOcclusion = serializationObject.useRadianceOcclusion; + this.useHorizonOcclusion = serializationObject.useHorizonOcclusion; + this.unlit = serializationObject.unlit; + this.forceNormalForward = !!serializationObject.forceNormalForward; + this.debugMode = serializationObject.debugMode; + this.debugLimit = serializationObject.debugLimit; + this.debugFactor = serializationObject.debugFactor; + this.generateOnlyFragmentCode = !!serializationObject.generateOnlyFragmentCode; + this._setTarget(); + } +} +__decorate([ + editableInPropertyPage("Direct lights", 1 /* PropertyTypeForEdition.Float */, "INTENSITY", { min: 0, max: 1, notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "directIntensity", void 0); +__decorate([ + editableInPropertyPage("Environment lights", 1 /* PropertyTypeForEdition.Float */, "INTENSITY", { min: 0, max: 1, notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "environmentIntensity", void 0); +__decorate([ + editableInPropertyPage("Specular highlights", 1 /* PropertyTypeForEdition.Float */, "INTENSITY", { min: 0, max: 1, notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "specularIntensity", void 0); +__decorate([ + editableInPropertyPage("Light falloff", 4 /* PropertyTypeForEdition.List */, "LIGHTING & COLORS", { + notifiers: { update: true }, + options: [ + { label: "Physical", value: PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL }, + { label: "GLTF", value: PBRBaseMaterial.LIGHTFALLOFF_GLTF }, + { label: "Standard", value: PBRBaseMaterial.LIGHTFALLOFF_STANDARD }, + ], + }) +], PBRMetallicRoughnessBlock.prototype, "lightFalloff", void 0); +__decorate([ + editableInPropertyPage("Alpha Testing", 0 /* PropertyTypeForEdition.Boolean */, "OPACITY") +], PBRMetallicRoughnessBlock.prototype, "useAlphaTest", void 0); +__decorate([ + editableInPropertyPage("Alpha CutOff", 1 /* PropertyTypeForEdition.Float */, "OPACITY", { min: 0, max: 1, notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "alphaTestCutoff", void 0); +__decorate([ + editableInPropertyPage("Alpha blending", 0 /* PropertyTypeForEdition.Boolean */, "OPACITY") +], PBRMetallicRoughnessBlock.prototype, "useAlphaBlending", void 0); +__decorate([ + editableInPropertyPage("Radiance over alpha", 0 /* PropertyTypeForEdition.Boolean */, "RENDERING", { notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "useRadianceOverAlpha", void 0); +__decorate([ + editableInPropertyPage("Specular over alpha", 0 /* PropertyTypeForEdition.Boolean */, "RENDERING", { notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "useSpecularOverAlpha", void 0); +__decorate([ + editableInPropertyPage("Specular anti-aliasing", 0 /* PropertyTypeForEdition.Boolean */, "RENDERING", { notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "enableSpecularAntiAliasing", void 0); +__decorate([ + editableInPropertyPage("Realtime filtering", 0 /* PropertyTypeForEdition.Boolean */, "RENDERING", { notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "realTimeFiltering", void 0); +__decorate([ + editableInPropertyPage("Realtime filtering quality", 4 /* PropertyTypeForEdition.List */, "RENDERING", { + notifiers: { update: true }, + options: [ + { label: "Low", value: 8 }, + { label: "Medium", value: 16 }, + { label: "High", value: 64 }, + ], + }) +], PBRMetallicRoughnessBlock.prototype, "realTimeFilteringQuality", void 0); +__decorate([ + editableInPropertyPage("Energy Conservation", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "useEnergyConservation", void 0); +__decorate([ + editableInPropertyPage("Radiance occlusion", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "useRadianceOcclusion", void 0); +__decorate([ + editableInPropertyPage("Horizon occlusion", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "useHorizonOcclusion", void 0); +__decorate([ + editableInPropertyPage("Unlit", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "unlit", void 0); +__decorate([ + editableInPropertyPage("Force normal forward", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "forceNormalForward", void 0); +__decorate([ + editableInPropertyPage("Generate only fragment code", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { + notifiers: { rebuild: true, update: true, onValidation: PBRMetallicRoughnessBlock._OnGenerateOnlyFragmentCodeChanged }, + }) +], PBRMetallicRoughnessBlock.prototype, "generateOnlyFragmentCode", void 0); +__decorate([ + editableInPropertyPage("Debug mode", 4 /* PropertyTypeForEdition.List */, "DEBUG", { + notifiers: { update: true }, + options: [ + { label: "None", value: 0 }, + // Geometry + { label: "Normalized position", value: 1 }, + { label: "Normals", value: 2 }, + { label: "Tangents", value: 3 }, + { label: "Bitangents", value: 4 }, + { label: "Bump Normals", value: 5 }, + //{ label: "UV1", value: 6 }, + //{ label: "UV2", value: 7 }, + { label: "ClearCoat Normals", value: 8 }, + { label: "ClearCoat Tangents", value: 9 }, + { label: "ClearCoat Bitangents", value: 10 }, + { label: "Anisotropic Normals", value: 11 }, + { label: "Anisotropic Tangents", value: 12 }, + { label: "Anisotropic Bitangents", value: 13 }, + // Maps + //{ label: "Emissive Map", value: 23 }, + //{ label: "Light Map", value: 24 }, + // Env + { label: "Env Refraction", value: 40 }, + { label: "Env Reflection", value: 41 }, + { label: "Env Clear Coat", value: 42 }, + // Lighting + { label: "Direct Diffuse", value: 50 }, + { label: "Direct Specular", value: 51 }, + { label: "Direct Clear Coat", value: 52 }, + { label: "Direct Sheen", value: 53 }, + { label: "Env Irradiance", value: 54 }, + // Lighting Params + { label: "Surface Albedo", value: 60 }, + { label: "Reflectance 0", value: 61 }, + { label: "Metallic", value: 62 }, + { label: "Metallic F0", value: 71 }, + { label: "Roughness", value: 63 }, + { label: "AlphaG", value: 64 }, + { label: "NdotV", value: 65 }, + { label: "ClearCoat Color", value: 66 }, + { label: "ClearCoat Roughness", value: 67 }, + { label: "ClearCoat NdotV", value: 68 }, + { label: "Transmittance", value: 69 }, + { label: "Refraction Transmittance", value: 70 }, + // Misc + { label: "SEO", value: 80 }, + { label: "EHO", value: 81 }, + { label: "Energy Factor", value: 82 }, + { label: "Specular Reflectance", value: 83 }, + { label: "Clear Coat Reflectance", value: 84 }, + { label: "Sheen Reflectance", value: 85 }, + { label: "Luminance Over Alpha", value: 86 }, + { label: "Alpha", value: 87 }, + { label: "Albedo color", value: 88 }, + { label: "Ambient occlusion color", value: 89 }, + ], + }) +], PBRMetallicRoughnessBlock.prototype, "debugMode", void 0); +__decorate([ + editableInPropertyPage("Split position", 1 /* PropertyTypeForEdition.Float */, "DEBUG", { min: -1, max: 1, notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "debugLimit", void 0); +__decorate([ + editableInPropertyPage("Output factor", 1 /* PropertyTypeForEdition.Float */, "DEBUG", { min: 0, max: 5, notifiers: { update: true } }) +], PBRMetallicRoughnessBlock.prototype, "debugFactor", void 0); +RegisterClass("BABYLON.PBRMetallicRoughnessBlock", PBRMetallicRoughnessBlock); + +/** + * Block used to compute value of one parameter modulo another + */ +class ModBlock extends NodeMaterialBlock { + /** + * Creates a new ModBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ModBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + if (state.shaderLanguage === 0 /* ShaderLanguage.GLSL */) { + state.compilationString += state._declareOutput(output) + ` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`; + } + else { + state.compilationString += state._declareOutput(output) + ` = (${this.left.associatedVariableName} % ${this.right.associatedVariableName});\n`; + } + return this; + } +} +RegisterClass("BABYLON.ModBlock", ModBlock); + +/** + * Block used to build a matrix from 4 Vector4 + */ +class MatrixBuilderBlock extends NodeMaterialBlock { + /** + * Creates a new MatrixBuilder + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("row0", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("row1", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("row2", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerInput("row3", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MatrixBuilder"; + } + /** + * Gets the row0 vector + */ + get row0() { + return this._inputs[0]; + } + /** + * Gets the row1 vector + */ + get row1() { + return this._inputs[1]; + } + /** + * Gets the row2 vector + */ + get row2() { + return this._inputs[2]; + } + /** + * Gets the row3 vector + */ + get row3() { + return this._inputs[3]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.row0.isConnected) { + const row0Input = new InputBlock("row0"); + row0Input.value = new Vector4(1, 0, 0, 0); + row0Input.output.connectTo(this.row0); + } + if (!this.row1.isConnected) { + const row1Input = new InputBlock("row1"); + row1Input.value = new Vector4(0, 1, 0, 0); + row1Input.output.connectTo(this.row1); + } + if (!this.row2.isConnected) { + const row2Input = new InputBlock("row2"); + row2Input.value = new Vector4(0, 0, 1, 0); + row2Input.output.connectTo(this.row2); + } + if (!this.row3.isConnected) { + const row3Input = new InputBlock("row3"); + row3Input.value = new Vector4(0, 0, 0, 1); + row3Input.output.connectTo(this.row3); + } + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const row0 = this.row0; + const row1 = this.row1; + const row2 = this.row2; + const row3 = this.row3; + const mat4 = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "mat4x4f" : "mat4"; + state.compilationString += + state._declareOutput(output) + + ` = ${mat4}(${row0.associatedVariableName}, ${row1.associatedVariableName}, ${row2.associatedVariableName}, ${row3.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.MatrixBuilder", MatrixBuilderBlock); + +/** + * Operations supported by the ConditionalBlock block + */ +var ConditionalBlockConditions; +(function (ConditionalBlockConditions) { + /** Equal */ + ConditionalBlockConditions[ConditionalBlockConditions["Equal"] = 0] = "Equal"; + /** NotEqual */ + ConditionalBlockConditions[ConditionalBlockConditions["NotEqual"] = 1] = "NotEqual"; + /** LessThan */ + ConditionalBlockConditions[ConditionalBlockConditions["LessThan"] = 2] = "LessThan"; + /** GreaterThan */ + ConditionalBlockConditions[ConditionalBlockConditions["GreaterThan"] = 3] = "GreaterThan"; + /** LessOrEqual */ + ConditionalBlockConditions[ConditionalBlockConditions["LessOrEqual"] = 4] = "LessOrEqual"; + /** GreaterOrEqual */ + ConditionalBlockConditions[ConditionalBlockConditions["GreaterOrEqual"] = 5] = "GreaterOrEqual"; + /** Logical Exclusive OR */ + ConditionalBlockConditions[ConditionalBlockConditions["Xor"] = 6] = "Xor"; + /** Logical Or */ + ConditionalBlockConditions[ConditionalBlockConditions["Or"] = 7] = "Or"; + /** Logical And */ + ConditionalBlockConditions[ConditionalBlockConditions["And"] = 8] = "And"; +})(ConditionalBlockConditions || (ConditionalBlockConditions = {})); +/** + * Block used to apply conditional operation between floats + * @since 5.0.0 + */ +class ConditionalBlock extends NodeMaterialBlock { + /** + * Creates a new ConditionalBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Gets or sets the condition applied by the block + */ + this.condition = ConditionalBlockConditions.LessThan; + this.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float); + this.registerInput("b", NodeMaterialBlockConnectionPointTypes.Float); + this.registerInput("true", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("false", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._linkConnectionTypes(2, 3); + this._outputs[0]._typeConnectionSource = this._inputs[2]; + this._outputs[0]._defaultConnectionPointType = NodeMaterialBlockConnectionPointTypes.Float; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ConditionalBlock"; + } + /** + * Gets the first operand component + */ + get a() { + return this._inputs[0]; + } + /** + * Gets the second operand component + */ + get b() { + return this._inputs[1]; + } + /** + * Gets the value to return if condition is true + */ + get true() { + return this._inputs[2]; + } + /** + * Gets the value to return if condition is false + */ + get false() { + return this._inputs[3]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + autoConfigure(nodeMaterial) { + if (!this.true.isConnected) { + const minInput = nodeMaterial.getBlockByPredicate((b) => b.isInput && b.value === 1 && b.name === "True") || new InputBlock("True"); + minInput.value = 1; + minInput.output.connectTo(this.true); + } + if (!this.false.isConnected) { + const maxInput = nodeMaterial.getBlockByPredicate((b) => b.isInput && b.value === 0 && b.name === "False") || new InputBlock("False"); + maxInput.value = 0; + maxInput.output.connectTo(this.false); + } + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const trueStatement = this.true.isConnected ? this.true.associatedVariableName : "1.0"; + const falseStatement = this.false.isConnected ? this.false.associatedVariableName : "0.0"; + switch (this.condition) { + case ConditionalBlockConditions.Equal: { + state.compilationString += + state._declareOutput(output) + + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)};\n`; + break; + } + case ConditionalBlockConditions.NotEqual: { + state.compilationString += + state._declareOutput(output) + + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)};\n`; + break; + } + case ConditionalBlockConditions.LessThan: { + state.compilationString += + state._declareOutput(output) + + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)};\n`; + break; + } + case ConditionalBlockConditions.LessOrEqual: { + state.compilationString += + state._declareOutput(output) + + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)};\n`; + break; + } + case ConditionalBlockConditions.GreaterThan: { + state.compilationString += + state._declareOutput(output) + + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)};\n`; + break; + } + case ConditionalBlockConditions.GreaterOrEqual: { + state.compilationString += + state._declareOutput(output) + + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)};\n`; + break; + } + case ConditionalBlockConditions.Xor: { + state.compilationString += + state._declareOutput(output) + + ` = ${state._generateTernary(trueStatement, falseStatement, `(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)};\n`; + break; + } + case ConditionalBlockConditions.Or: { + state.compilationString += + state._declareOutput(output) + + ` = ${state._generateTernary(trueStatement, falseStatement, `(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)};\n`; + break; + } + case ConditionalBlockConditions.And: { + state.compilationString += + state._declareOutput(output) + + ` = ${state._generateTernary(trueStatement, falseStatement, `(${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0)`)};\n`; + break; + } + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.condition = this.condition; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.condition = serializationObject.condition; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${ConditionalBlockConditions[this.condition]};\n`; + return codeString; + } +} +__decorate([ + editableInPropertyPage("Condition", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "Equal", value: ConditionalBlockConditions.Equal }, + { label: "NotEqual", value: ConditionalBlockConditions.NotEqual }, + { label: "LessThan", value: ConditionalBlockConditions.LessThan }, + { label: "GreaterThan", value: ConditionalBlockConditions.GreaterThan }, + { label: "LessOrEqual", value: ConditionalBlockConditions.LessOrEqual }, + { label: "GreaterOrEqual", value: ConditionalBlockConditions.GreaterOrEqual }, + { label: "Xor", value: ConditionalBlockConditions.Xor }, + { label: "And", value: ConditionalBlockConditions.And }, + { label: "Or", value: ConditionalBlockConditions.Or }, + ], + }) +], ConditionalBlock.prototype, "condition", void 0); +RegisterClass("BABYLON.ConditionalBlock", ConditionalBlock); + +/** + * block used to Generate Fractal Brownian Motion Clouds + */ +class CloudBlock extends NodeMaterialBlock { + /** + * Creates a new CloudBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** Gets or sets the number of octaves */ + this.octaves = 6.0; + this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("chaos", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.registerInput("offsetX", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("offsetY", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("offsetZ", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); + this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2); + this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3); + this._linkConnectionTypes(0, 1); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "CloudBlock"; + } + /** + * Gets the seed input component + */ + get seed() { + return this._inputs[0]; + } + /** + * Gets the chaos input component + */ + get chaos() { + return this._inputs[1]; + } + /** + * Gets the offset X input component + */ + get offsetX() { + return this._inputs[2]; + } + /** + * Gets the offset Y input component + */ + get offsetY() { + return this._inputs[3]; + } + /** + * Gets the offset Z input component + */ + get offsetZ() { + return this._inputs[4]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + if (!this.seed.isConnected) { + return; + } + if (!this._outputs[0].hasEndpoints) { + return; + } + let functionString = ` + + float cloudRandom(float p) { + float temp = fract(p * 0.011); + temp *= temp + 7.5; + temp *= temp + temp; + return fract(temp); + } + + // Based on Morgan McGuire @morgan3d + // https://www.shadertoy.com/view/4dS3Wd + float cloudNoise2(vec2 x, vec2 chaos) { + vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); + + vec2 i = floor(x); + vec2 f = fract(x); + + float n = dot(i, step); + + vec2 u = f * f * (3.0 - 2.0 * f); + return mix( + mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), + mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), + u.y + ); + } + + float cloudNoise3(vec3 x, vec3 chaos) { + vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); + + vec3 i = floor(x); + vec3 f = fract(x); + + float n = dot(i, step); + + vec3 u = f * f * (3.0 - 2.0 * f); + return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), + mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), + mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), + mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); + }`; + let fractalBrownianString = ` + float fbm2(vec2 st, vec2 chaos) { + // Initial values + float value = 0.0; + float amplitude = .5; + float frequency = 0.; + + // Loop of octaves + vec2 tempST = st; + for (int i = 0; i < OCTAVES; i++) { + value += amplitude * cloudNoise2(tempST, chaos); + tempST *= 2.0; + amplitude *= 0.5; + } + return value; + } + + float fbm3(vec3 x, vec3 chaos) { + // Initial values + float value = 0.0; + float amplitude = 0.5; + vec3 tempX = x; + for (int i = 0; i < OCTAVES; i++) { + value += amplitude * cloudNoise3(tempX, chaos); + tempX = tempX * 2.0; + amplitude *= 0.5; + } + return value; + }`; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + functionString = state._babylonSLtoWGSL(functionString); + fractalBrownianString = state._babylonSLtoWGSL(fractalBrownianString); + } + const fbmNewName = `fbm${this.octaves}`; + state._emitFunction("CloudBlockCode", functionString, "// CloudBlockCode"); + state._emitFunction("CloudBlockCodeFBM" + this.octaves, fractalBrownianString.replace(/fbm/gi, fbmNewName).replace(/OCTAVES/gi, (this.octaves | 0).toString()), "// CloudBlockCode FBM"); + const localVariable = state._getFreeVariableName("st"); + const seedType = this.seed.connectedPoint?.type || NodeMaterialBlockConnectionPointTypes.Vector3; + state.compilationString += `${state._declareLocalVar(localVariable, seedType)} = ${this.seed.associatedVariableName};\n`; + if (this.offsetX.isConnected) { + state.compilationString += `${localVariable}.x += 0.1 * ${this.offsetX.associatedVariableName};\n`; + } + if (this.offsetY.isConnected) { + state.compilationString += `${localVariable}.y += 0.1 * ${this.offsetY.associatedVariableName};\n`; + } + if (this.offsetZ.isConnected && seedType === NodeMaterialBlockConnectionPointTypes.Vector3) { + state.compilationString += `${localVariable}.z += 0.1 * ${this.offsetZ.associatedVariableName};\n`; + } + let chaosValue = ""; + if (this.chaos.isConnected) { + chaosValue = this.chaos.associatedVariableName; + } + else { + const addF = state.fSuffix; + chaosValue = this.seed.connectedPoint?.type === NodeMaterialBlockConnectionPointTypes.Vector2 ? `vec2${addF}(0., 0.)` : `vec3${addF}(0., 0., 0.)`; + } + state.compilationString += + state._declareOutput(this._outputs[0]) + + ` = ${fbmNewName}${this.seed.connectedPoint?.type === NodeMaterialBlockConnectionPointTypes.Vector2 ? "2" : "3"}(${localVariable}, ${chaosValue});\n`; + return this; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.octaves = ${this.octaves};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.octaves = this.octaves; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.octaves = serializationObject.octaves; + } +} +__decorate([ + editableInPropertyPage("Octaves", 2 /* PropertyTypeForEdition.Int */, undefined, { embedded: true }) +], CloudBlock.prototype, "octaves", void 0); +RegisterClass("BABYLON.CloudBlock", CloudBlock); + +/** + * block used to Generate a Voronoi Noise Pattern + */ +class VoronoiNoiseBlock extends NodeMaterialBlock { + /** + * Creates a new VoronoiNoiseBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector2); + this.registerInput("offset", NodeMaterialBlockConnectionPointTypes.Float); + this.registerInput("density", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); + this.registerOutput("cells", NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "VoronoiNoiseBlock"; + } + /** + * Gets the seed input component + */ + get seed() { + return this._inputs[0]; + } + /** + * Gets the offset input component + */ + get offset() { + return this._inputs[1]; + } + /** + * Gets the density input component + */ + get density() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the output component + */ + get cells() { + return this._outputs[1]; + } + _buildBlock(state) { + super._buildBlock(state); + if (!this.seed.isConnected) { + return; + } + // Adapted from https://www.shadertoy.com/view/MslGD8 + let functionString = `vec2 voronoiRandom(vec2 p){ + p = vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))); + return fract(sin(p)*18.5453); + } + `; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + functionString = state._babylonSLtoWGSL(functionString); + } + state._emitFunction("voronoiRandom", functionString, "// Voronoi random generator"); + functionString = `void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ + vec2 n = floor(seed * density); + vec2 f = fract(seed * density); + vec3 m = vec3( 8.0 ); + for( int j=-1; j<=1; j++ ){ + for( int i=-1; i<=1; i++ ){ + vec2 g = vec2( float(i), float(j) ); + vec2 o = voronoiRandom( n + g); + vec2 r = g - f + (0.5+0.5*sin(offset+6.2831*o)); + float d = dot( r, r ); + if( d { + return mat.hasTexture(this._texture); + }); + } + this._texture = texture; + if (texture && scene) { + scene.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(texture); + }); + } + } + /** + * Gets the textureY associated with the node + */ + get textureY() { + if (this.sourceY.isConnected) { + return (this.sourceY.connectedPoint?.ownerBlock).texture; + } + return null; + } + /** + * Gets the textureZ associated with the node + */ + get textureZ() { + if (this.sourceZ?.isConnected) { + return (this.sourceY.connectedPoint?.ownerBlock).texture; + } + return null; + } + _getImageSourceBlock(connectionPoint) { + return connectionPoint?.isConnected ? connectionPoint.connectedPoint.ownerBlock : null; + } + /** + * Gets the sampler name associated with this texture + */ + get samplerName() { + const imageSourceBlock = this._getImageSourceBlock(this.source); + if (imageSourceBlock) { + return imageSourceBlock.samplerName; + } + return this._samplerName; + } + /** + * Gets the samplerY name associated with this texture + */ + get samplerYName() { + return this._getImageSourceBlock(this.sourceY)?.samplerName ?? null; + } + /** + * Gets the samplerZ name associated with this texture + */ + get samplerZName() { + return this._getImageSourceBlock(this.sourceZ)?.samplerName ?? null; + } + /** + * Gets a boolean indicating that this block is linked to an ImageSourceBlock + */ + get hasImageSource() { + return this.source.isConnected; + } + /** + * Gets or sets a boolean indicating if content needs to be converted to gamma space + */ + set convertToGammaSpace(value) { + if (value === this._convertToGammaSpace) { + return; + } + this._convertToGammaSpace = value; + if (this.texture) { + const scene = this.texture.getScene() ?? EngineStore.LastCreatedScene; + scene?.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this.texture); + }); + } + } + get convertToGammaSpace() { + return this._convertToGammaSpace; + } + /** + * Gets or sets a boolean indicating if content needs to be converted to linear space + */ + set convertToLinearSpace(value) { + if (value === this._convertToLinearSpace) { + return; + } + this._convertToLinearSpace = value; + if (this.texture) { + const scene = this.texture.getScene() ?? EngineStore.LastCreatedScene; + scene?.markAllMaterialsAsDirty(1, (mat) => { + return mat.hasTexture(this.texture); + }); + } + } + get convertToLinearSpace() { + return this._convertToLinearSpace; + } + /** + * Create a new TriPlanarBlock + * @param name defines the block name + * @param hideSourceZ defines a boolean indicating that normal Z should not be used (false by default) + */ + constructor(name, hideSourceZ = false) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Project the texture(s) for a better fit to a cube + */ + this.projectAsCube = false; + this._convertToGammaSpace = false; + this._convertToLinearSpace = false; + /** + * Gets or sets a boolean indicating if multiplication of texture with level should be disabled + */ + this.disableLevelMultiplication = false; + this.registerInput("position", NodeMaterialBlockConnectionPointTypes.AutoDetect, false); + this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect, false); + this.registerInput("sharpness", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerInput("source", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source", this, 0 /* NodeMaterialConnectionPointDirection.Input */, ImageSourceBlock, "ImageSourceBlock")); + this.registerInput("sourceY", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("sourceY", this, 0 /* NodeMaterialConnectionPointDirection.Input */, ImageSourceBlock, "ImageSourceBlock")); + if (!hideSourceZ) { + this.registerInput("sourceZ", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("sourceZ", this, 0 /* NodeMaterialConnectionPointDirection.Input */, ImageSourceBlock, "ImageSourceBlock")); + } + this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral); + this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral); + this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this.registerOutput("level", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); + this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "TriPlanarBlock"; + } + /** + * Gets the position input component + */ + get position() { + return this._inputs[0]; + } + /** + * Gets the normal input component + */ + get normal() { + return this._inputs[1]; + } + /** + * Gets the sharpness input component + */ + get sharpness() { + return this._inputs[2]; + } + /** + * Gets the source input component + */ + get source() { + return this._inputs[3]; + } + /** + * Gets the sourceY input component + */ + get sourceY() { + return this._inputs[4]; + } + /** + * Gets the sourceZ input component + */ + get sourceZ() { + return this._inputs[5]; + } + /** + * Gets the rgba output component + */ + get rgba() { + return this._outputs[0]; + } + /** + * Gets the rgb output component + */ + get rgb() { + return this._outputs[1]; + } + /** + * Gets the r output component + */ + get r() { + return this._outputs[2]; + } + /** + * Gets the g output component + */ + get g() { + return this._outputs[3]; + } + /** + * Gets the b output component + */ + get b() { + return this._outputs[4]; + } + /** + * Gets the a output component + */ + get a() { + return this._outputs[5]; + } + /** + * Gets the level output component + */ + get level() { + return this._outputs[6]; + } + prepareDefines(mesh, nodeMaterial, defines) { + if (!defines._areTexturesDirty) { + return; + } + const toGamma = this.convertToGammaSpace && this.texture && !this.texture.gammaSpace; + const toLinear = this.convertToLinearSpace && this.texture && this.texture.gammaSpace; + // Not a bug... Name defines the texture space not the required conversion + defines.setValue(this._linearDefineName, toGamma, true); + defines.setValue(this._gammaDefineName, toLinear, true); + } + isReady() { + if (this.texture && !this.texture.isReadyOrNotBlocking()) { + return false; + } + return true; + } + bind(effect) { + if (!this.texture) { + return; + } + effect.setFloat(this._textureInfoName, this.texture.level); + if (!this._imageSource) { + effect.setTexture(this._samplerName, this.texture); + } + } + _samplerFunc(state) { + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return "textureSample"; + } + return "texture2D"; + } + _generateTextureSample(textureName, uv, state) { + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return `${this._samplerFunc(state)}(${textureName},${textureName + `Sampler`}, ${uv})`; + } + return `${this._samplerFunc(state)}(${textureName}, ${uv})`; + } + _generateTextureLookup(state) { + const samplerName = this.samplerName; + const samplerYName = this.samplerYName ?? samplerName; + const samplerZName = this.samplerZName ?? samplerName; + const sharpness = this.sharpness.isConnected ? this.sharpness.associatedVariableName : "1.0"; + const x = state._getFreeVariableName("x"); + const y = state._getFreeVariableName("y"); + const z = state._getFreeVariableName("z"); + const w = state._getFreeVariableName("w"); + const n = state._getFreeVariableName("n"); + const uvx = state._getFreeVariableName("uvx"); + const uvy = state._getFreeVariableName("uvy"); + const uvz = state._getFreeVariableName("uvz"); + state.compilationString += ` + ${state._declareLocalVar(n, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this.normal.associatedVariableName}.xyz; + + ${state._declareLocalVar(uvx, NodeMaterialBlockConnectionPointTypes.Vector2)} = ${this.position.associatedVariableName}.yz; + ${state._declareLocalVar(uvy, NodeMaterialBlockConnectionPointTypes.Vector2)} = ${this.position.associatedVariableName}.zx; + ${state._declareLocalVar(uvz, NodeMaterialBlockConnectionPointTypes.Vector2)} = ${this.position.associatedVariableName}.xy; + `; + if (this.projectAsCube) { + state.compilationString += ` + ${uvx}.xy = ${uvx}.yx; + + if (${n}.x >= 0.0) { + ${uvx}.x = -${uvx}.x; + } + if (${n}.y < 0.0) { + ${uvy}.y = -${uvy}.y; + } + if (${n}.z < 0.0) { + ${uvz}.x = -${uvz}.x; + } + `; + } + const suffix = state.fSuffix; + state.compilationString += ` + ${state._declareLocalVar(x, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(samplerName, uvx, state)}; + ${state._declareLocalVar(y, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(samplerYName, uvy, state)}; + ${state._declareLocalVar(z, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(samplerZName, uvz, state)}; + + // blend weights + ${state._declareLocalVar(w, NodeMaterialBlockConnectionPointTypes.Vector3)} = pow(abs(${n}), vec3${suffix}(${sharpness})); + + // blend and return + ${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = (${x}*${w}.x + ${y}*${w}.y + ${z}*${w}.z) / (${w}.x + ${w}.y + ${w}.z); + `; + } + _generateConversionCode(state, output, swizzle) { + let vecSpecifier = ""; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ && + (output.type === NodeMaterialBlockConnectionPointTypes.Vector3 || output.type === NodeMaterialBlockConnectionPointTypes.Color3)) { + vecSpecifier = "Vec3"; + } + if (swizzle !== "a") { + // no conversion if the output is "a" (alpha) + if (!this.texture || !this.texture.gammaSpace) { + state.compilationString += `#ifdef ${this._linearDefineName} + ${output.associatedVariableName} = toGammaSpace${vecSpecifier}(${output.associatedVariableName}); + #endif + `; + } + state.compilationString += `#ifdef ${this._gammaDefineName} + ${output.associatedVariableName} = toLinearSpace${vecSpecifier}(${output.associatedVariableName}); + #endif + `; + } + } + _writeOutput(state, output, swizzle) { + let complement = ""; + if (!this.disableLevelMultiplication) { + complement = ` * ${state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "uniforms." : ""}${this._textureInfoName}`; + } + state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle}${complement};\n`; + this._generateConversionCode(state, output, swizzle); + } + _buildBlock(state) { + super._buildBlock(state); + if (this.source.isConnected) { + this._imageSource = this.source.connectedPoint.ownerBlock; + } + else { + this._imageSource = null; + } + this._textureInfoName = state._getFreeVariableName("textureInfoName"); + this.level.associatedVariableName = (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "uniforms." : "") + this._textureInfoName; + this._tempTextureRead = state._getFreeVariableName("tempTextureRead"); + this._linearDefineName = state._getFreeDefineName("ISLINEAR"); + this._gammaDefineName = state._getFreeDefineName("ISGAMMA"); + if (!this._imageSource) { + this._samplerName = state._getFreeVariableName(this.name + "Texture"); + state._emit2DSampler(this._samplerName); + } + // Declarations + state.sharedData.blockingBlocks.push(this); + state.sharedData.textureBlocks.push(this); + state.sharedData.blocksWithDefines.push(this); + state.sharedData.bindableBlocks.push(this); + const comments = `//${this.name}`; + state._emitFunctionFromInclude("helperFunctions", comments); + state._emitUniformFromString(this._textureInfoName, NodeMaterialBlockConnectionPointTypes.Float); + this._generateTextureLookup(state); + for (const output of this._outputs) { + if (output.hasEndpoints && output.name !== "level") { + this._writeOutput(state, output, output.name); + } + } + return this; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`; + codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`; + codeString += `${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`; + codeString += `${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\n`; + if (!this.texture) { + return codeString; + } + codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`; + codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`; + codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`; + codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`; + codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`; + codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`; + codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`; + codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`; + codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`; + codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`; + codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`; + return codeString; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.convertToGammaSpace = this.convertToGammaSpace; + serializationObject.convertToLinearSpace = this.convertToLinearSpace; + serializationObject.disableLevelMultiplication = this.disableLevelMultiplication; + serializationObject.projectAsCube = this.projectAsCube; + if (!this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture") { + serializationObject.texture = this.texture.serialize(); + } + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.convertToGammaSpace = serializationObject.convertToGammaSpace; + this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; + this.disableLevelMultiplication = !!serializationObject.disableLevelMultiplication; + this.projectAsCube = !!serializationObject.projectAsCube; + if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) { + rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; + this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl); + } + } +} +__decorate([ + editableInPropertyPage("Project as cube", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { update: true } }) +], TriPlanarBlock.prototype, "projectAsCube", void 0); +RegisterClass("BABYLON.TriPlanarBlock", TriPlanarBlock); + +/** + * Block used to read a texture with triplanar mapping (see https://iquilezles.org/articles/biplanar/) + */ +class BiPlanarBlock extends TriPlanarBlock { + /** + * Create a new BiPlanarBlock + * @param name defines the block name + */ + constructor(name) { + super(name, true); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "BiPlanarBlock"; + } + _declareLocalVarAsVec3I(name, state) { + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return `var ${name}: vec3`; + } + else { + return `ivec3 ${name}`; + } + } + _getTextureGrad(state, samplerName) { + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return `textureSampleGrad(${samplerName},${samplerName + `Sampler`}`; + } + return `textureGrad(${samplerName}`; + } + _generateTextureLookup(state) { + const samplerName = this.samplerName; + const samplerYName = this.samplerYName ?? this.samplerName; + const sharpness = this.sharpness.isConnected ? this.sharpness.associatedVariableName : "1.0"; + const dpdx = state._getFreeVariableName("dxValue"); + const dpdy = state._getFreeVariableName("dyValue"); + const n = state._getFreeVariableName("n"); + const ma = state._getFreeVariableName("ma"); + const mi = state._getFreeVariableName("mi"); + const me = state._getFreeVariableName("me"); + const x = state._getFreeVariableName("x"); + const y = state._getFreeVariableName("y"); + const w = state._getFreeVariableName("w"); + let ivec3 = "ivec3"; + let dpdxFunc = "dFdx"; + let dpdyFunc = "dFdy"; + const suffix = state.fSuffix; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + ivec3 = "vec3"; + dpdxFunc = "dpdx"; + dpdyFunc = "dpdy"; + } + state.compilationString += ` + // grab coord derivatives for texturing + ${state._declareLocalVar(dpdx, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${dpdxFunc}(${this.position.associatedVariableName}.xyz); + ${state._declareLocalVar(dpdy, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${dpdyFunc}(${this.position.associatedVariableName}.xyz); + ${state._declareLocalVar(n, NodeMaterialBlockConnectionPointTypes.Vector3)} = abs(${this.normal.associatedVariableName}.xyz); + + // determine major axis (in x; yz are following axis) + ${this._declareLocalVarAsVec3I(ma, state)} = ${state._generateTernary(`${ivec3}(0,1,2)`, `${state._generateTernary(`${ivec3}(1,2,0)`, `${ivec3}(2,0,1)`, `(${n}.y>${n}.z)`)}`, `(${n}.x>${n}.y && ${n}.x>${n}.z)`)}; + + // determine minor axis (in x; yz are following axis) + ${this._declareLocalVarAsVec3I(mi, state)} = ${state._generateTernary(`${ivec3}(0,1,2)`, `${state._generateTernary(`${ivec3}(1,2,0)`, `${ivec3}(2,0,1)`, `(${n}.y<${n}.z)`)}`, `(${n}.x<${n}.y && ${n}.x<${n}.z)`)}; + + // determine median axis (in x; yz are following axis) + ${this._declareLocalVarAsVec3I(me, state)} = ${ivec3}(3) - ${mi} - ${ma}; + + // project+fetch + ${state._declareLocalVar(x, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._getTextureGrad(state, samplerName)}, vec2${suffix}(${this.position.associatedVariableName}[${ma}.y], ${this.position.associatedVariableName}[${ma}.z]), + vec2${suffix}(${dpdx}[${ma}.y],${dpdx}[${ma}.z]), + vec2${suffix}(${dpdy}[${ma}.y],${dpdy}[${ma}.z])); + ${state._declareLocalVar(y, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._getTextureGrad(state, samplerYName)}, vec2${suffix}(${this.position.associatedVariableName}[${me}.y], ${this.position.associatedVariableName}[${me}.z]), + vec2${suffix}(${dpdx}[${me}.y],${dpdx}[${me}.z]), + vec2${suffix}(${dpdy}[${me}.y],${dpdy}[${me}.z])); + + // blend factors + ${state._declareLocalVar(w, NodeMaterialBlockConnectionPointTypes.Vector2)} = vec2${suffix}(${n}[${ma}.x],${n}[${me}.x]); + // make local support + ${w} = clamp( (${w}-0.5773)/(1.0-0.5773), vec2${suffix}(0.0), vec2${suffix}(1.0) ); + // shape transition + ${w} = pow( ${w}, vec2${suffix}(${sharpness}/8.0) ); + // blend and return + ${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = (${x}*${w}.x + ${y}*${w}.y) / (${w}.x + ${w}.y); + `; + } +} +RegisterClass("BABYLON.BiPlanarBlock", BiPlanarBlock); + +/** + * Block used to compute the determinant of a matrix + */ +class MatrixDeterminantBlock extends NodeMaterialBlock { + /** + * Creates a new MatrixDeterminantBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Matrix); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MatrixDeterminantBlock"; + } + /** + * Gets the input matrix + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this.output; + const input = this.input; + state.compilationString += state._declareOutput(output) + ` = determinant(${input.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.MatrixDeterminantBlock", MatrixDeterminantBlock); + +/** + * Block used to transpose a matrix + */ +class MatrixTransposeBlock extends NodeMaterialBlock { + /** + * Creates a new MatrixTransposeBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Matrix); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MatrixTransposeBlock"; + } + /** + * Gets the input matrix + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this.output; + const input = this.input; + state.compilationString += state._declareOutput(output) + ` = transpose(${input.associatedVariableName});\n`; + return this; + } +} +RegisterClass("BABYLON.MatrixTransposeBlock", MatrixTransposeBlock); + +var MeshAttributeExistsBlockTypes; +(function (MeshAttributeExistsBlockTypes) { + MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["None"] = 0] = "None"; + MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["Normal"] = 1] = "Normal"; + MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["Tangent"] = 2] = "Tangent"; + MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["VertexColor"] = 3] = "VertexColor"; + MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV1"] = 4] = "UV1"; + MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV2"] = 5] = "UV2"; + MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV3"] = 6] = "UV3"; + MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV4"] = 7] = "UV4"; + MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV5"] = 8] = "UV5"; + MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV6"] = 9] = "UV6"; +})(MeshAttributeExistsBlockTypes || (MeshAttributeExistsBlockTypes = {})); +/** + * Block used to check if Mesh attribute of specified type exists + * and provide an alternative fallback input for to use in such case + */ +class MeshAttributeExistsBlock extends NodeMaterialBlock { + /** + * Creates a new MeshAttributeExistsBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Defines which mesh attribute to use + */ + this.attributeType = 0 /* MeshAttributeExistsBlockTypes.None */; + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("fallback", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + // Try to auto determine attributeType + this._inputs[0].onConnectionObservable.add((other) => { + if (this.attributeType) { + // But only if not already specified + return; + } + const sourceBlock = other.ownerBlock; + if (sourceBlock instanceof InputBlock && sourceBlock.isAttribute) { + switch (sourceBlock.name) { + case "color": + this.attributeType = 3 /* MeshAttributeExistsBlockTypes.VertexColor */; + break; + case "normal": + this.attributeType = 1 /* MeshAttributeExistsBlockTypes.Normal */; + break; + case "tangent": + this.attributeType = 2 /* MeshAttributeExistsBlockTypes.Tangent */; + break; + case "uv": + this.attributeType = 4 /* MeshAttributeExistsBlockTypes.UV1 */; + break; + case "uv2": + this.attributeType = 5 /* MeshAttributeExistsBlockTypes.UV2 */; + break; + case "uv3": + this.attributeType = 6 /* MeshAttributeExistsBlockTypes.UV3 */; + break; + case "uv4": + this.attributeType = 7 /* MeshAttributeExistsBlockTypes.UV4 */; + break; + case "uv5": + this.attributeType = 8 /* MeshAttributeExistsBlockTypes.UV5 */; + break; + case "uv6": + this.attributeType = 9 /* MeshAttributeExistsBlockTypes.UV6 */; + break; + } + } + else if (sourceBlock instanceof MorphTargetsBlock) { + switch (this.input.connectedPoint?.name) { + case "normalOutput": + this.attributeType = 1 /* MeshAttributeExistsBlockTypes.Normal */; + break; + case "tangentOutput": + this.attributeType = 2 /* MeshAttributeExistsBlockTypes.Tangent */; + break; + case "uvOutput": + this.attributeType = 4 /* MeshAttributeExistsBlockTypes.UV1 */; + break; + case "uv2Output": + this.attributeType = 5 /* MeshAttributeExistsBlockTypes.UV2 */; + break; + } + } + }); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MeshAttributeExistsBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the fallback component when speciefied attribute doesn't exist + */ + get fallback() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + let attributeDefine = null; + switch (this.attributeType) { + case 3 /* MeshAttributeExistsBlockTypes.VertexColor */: + attributeDefine = "VERTEXCOLOR_NME"; + break; + case 1 /* MeshAttributeExistsBlockTypes.Normal */: + attributeDefine = "NORMAL"; + break; + case 2 /* MeshAttributeExistsBlockTypes.Tangent */: + attributeDefine = "TANGENT"; + break; + case 4 /* MeshAttributeExistsBlockTypes.UV1 */: + attributeDefine = "UV1"; + break; + case 5 /* MeshAttributeExistsBlockTypes.UV2 */: + attributeDefine = "UV2"; + break; + case 6 /* MeshAttributeExistsBlockTypes.UV3 */: + attributeDefine = "UV3"; + break; + case 7 /* MeshAttributeExistsBlockTypes.UV4 */: + attributeDefine = "UV4"; + break; + case 8 /* MeshAttributeExistsBlockTypes.UV5 */: + attributeDefine = "UV5"; + break; + case 9 /* MeshAttributeExistsBlockTypes.UV6 */: + attributeDefine = "UV6"; + break; + } + const output = state._declareOutput(this.output); + if (attributeDefine) { + state.compilationString += `#ifdef ${attributeDefine}\n`; + } + state.compilationString += `${output} = ${this.input.associatedVariableName};\n`; + if (attributeDefine) { + state.compilationString += `#else\n`; + state.compilationString += `${output} = ${this.fallback.associatedVariableName};\n`; + state.compilationString += `#endif\n`; + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.attributeType = this.attributeType; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.attributeType = serializationObject.attributeType ?? 0 /* MeshAttributeExistsBlockTypes.None */; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + codeString += `${this._codeVariableName}.attributeType = ${this.attributeType};\n`; + return codeString; + } +} +__decorate([ + editableInPropertyPage("Attribute lookup", 4 /* PropertyTypeForEdition.List */, undefined, { + notifiers: { update: true }, + embedded: true, + options: [ + { label: "(None)", value: 0 /* MeshAttributeExistsBlockTypes.None */ }, + { label: "Normal", value: 1 /* MeshAttributeExistsBlockTypes.Normal */ }, + { label: "Tangent", value: 2 /* MeshAttributeExistsBlockTypes.Tangent */ }, + { label: "Vertex Color", value: 3 /* MeshAttributeExistsBlockTypes.VertexColor */ }, + { label: "UV1", value: 4 /* MeshAttributeExistsBlockTypes.UV1 */ }, + { label: "UV2", value: 5 /* MeshAttributeExistsBlockTypes.UV2 */ }, + { label: "UV3", value: 6 /* MeshAttributeExistsBlockTypes.UV3 */ }, + { label: "UV4", value: 7 /* MeshAttributeExistsBlockTypes.UV4 */ }, + { label: "UV5", value: 8 /* MeshAttributeExistsBlockTypes.UV5 */ }, + { label: "UV6", value: 9 /* MeshAttributeExistsBlockTypes.UV6 */ }, + ], + }) +], MeshAttributeExistsBlock.prototype, "attributeType", void 0); +RegisterClass("BABYLON.MeshAttributeExistsBlock", MeshAttributeExistsBlock); + +/** + * Types of curves supported by the Curve block + */ +var CurveBlockTypes; +(function (CurveBlockTypes) { + /** EaseInSine */ + CurveBlockTypes[CurveBlockTypes["EaseInSine"] = 0] = "EaseInSine"; + /** EaseOutSine */ + CurveBlockTypes[CurveBlockTypes["EaseOutSine"] = 1] = "EaseOutSine"; + /** EaseInOutSine */ + CurveBlockTypes[CurveBlockTypes["EaseInOutSine"] = 2] = "EaseInOutSine"; + /** EaseInQuad */ + CurveBlockTypes[CurveBlockTypes["EaseInQuad"] = 3] = "EaseInQuad"; + /** EaseOutQuad */ + CurveBlockTypes[CurveBlockTypes["EaseOutQuad"] = 4] = "EaseOutQuad"; + /** EaseInOutQuad */ + CurveBlockTypes[CurveBlockTypes["EaseInOutQuad"] = 5] = "EaseInOutQuad"; + /** EaseInCubic */ + CurveBlockTypes[CurveBlockTypes["EaseInCubic"] = 6] = "EaseInCubic"; + /** EaseOutCubic */ + CurveBlockTypes[CurveBlockTypes["EaseOutCubic"] = 7] = "EaseOutCubic"; + /** EaseInOutCubic */ + CurveBlockTypes[CurveBlockTypes["EaseInOutCubic"] = 8] = "EaseInOutCubic"; + /** EaseInQuart */ + CurveBlockTypes[CurveBlockTypes["EaseInQuart"] = 9] = "EaseInQuart"; + /** EaseOutQuart */ + CurveBlockTypes[CurveBlockTypes["EaseOutQuart"] = 10] = "EaseOutQuart"; + /** EaseInOutQuart */ + CurveBlockTypes[CurveBlockTypes["EaseInOutQuart"] = 11] = "EaseInOutQuart"; + /** EaseInQuint */ + CurveBlockTypes[CurveBlockTypes["EaseInQuint"] = 12] = "EaseInQuint"; + /** EaseOutQuint */ + CurveBlockTypes[CurveBlockTypes["EaseOutQuint"] = 13] = "EaseOutQuint"; + /** EaseInOutQuint */ + CurveBlockTypes[CurveBlockTypes["EaseInOutQuint"] = 14] = "EaseInOutQuint"; + /** EaseInExpo */ + CurveBlockTypes[CurveBlockTypes["EaseInExpo"] = 15] = "EaseInExpo"; + /** EaseOutExpo */ + CurveBlockTypes[CurveBlockTypes["EaseOutExpo"] = 16] = "EaseOutExpo"; + /** EaseInOutExpo */ + CurveBlockTypes[CurveBlockTypes["EaseInOutExpo"] = 17] = "EaseInOutExpo"; + /** EaseInCirc */ + CurveBlockTypes[CurveBlockTypes["EaseInCirc"] = 18] = "EaseInCirc"; + /** EaseOutCirc */ + CurveBlockTypes[CurveBlockTypes["EaseOutCirc"] = 19] = "EaseOutCirc"; + /** EaseInOutCirc */ + CurveBlockTypes[CurveBlockTypes["EaseInOutCirc"] = 20] = "EaseInOutCirc"; + /** EaseInBack */ + CurveBlockTypes[CurveBlockTypes["EaseInBack"] = 21] = "EaseInBack"; + /** EaseOutBack */ + CurveBlockTypes[CurveBlockTypes["EaseOutBack"] = 22] = "EaseOutBack"; + /** EaseInOutBack */ + CurveBlockTypes[CurveBlockTypes["EaseInOutBack"] = 23] = "EaseInOutBack"; + /** EaseInElastic */ + CurveBlockTypes[CurveBlockTypes["EaseInElastic"] = 24] = "EaseInElastic"; + /** EaseOutElastic */ + CurveBlockTypes[CurveBlockTypes["EaseOutElastic"] = 25] = "EaseOutElastic"; + /** EaseInOutElastic */ + CurveBlockTypes[CurveBlockTypes["EaseInOutElastic"] = 26] = "EaseInOutElastic"; +})(CurveBlockTypes || (CurveBlockTypes = {})); +/** + * Block used to apply curve operation + */ +class CurveBlock extends NodeMaterialBlock { + /** + * Creates a new CurveBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Gets or sets the type of the curve applied by the block + */ + this.type = CurveBlockTypes.EaseInOutSine; + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Object); + this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Int); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "CurveBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _duplicateEntry(entry, component) { + return `ret.${component} = ${entry.replace(/VAL/g, "v." + component)}`; + } + _duplicateEntryDirect(entry) { + return `return ${entry.replace(/VAL/g, "v")}`; + } + _duplicateVector(entry, inputType, isWGSL) { + if (inputType === "float" || inputType === "f32") { + return this._duplicateEntryDirect(entry); + } + const size = parseInt(inputType.replace("vec", "")); + let code = isWGSL + ? ` + var ret: vec${size}f = vec${size}f(0.0); + ` + : ` + vec${size} ret = vec${size}(0.0); + `; + for (let i = 1; i <= size; i++) { + code += this._duplicateEntry(entry, i === 1 ? "x" : i === 2 ? "y" : i === 3 ? "z" : "w") + ";\n"; + } + code += "return ret;\n"; + return code; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + let registeredFunction = ""; + let registeredFunctionName = ""; + const inputType = state._getShaderType(this.input.type); + const isWGSL = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */; + registeredFunctionName = CurveBlockTypes[this.type] + "_" + inputType.replace("<", "").replace(">", ""); + switch (this.type) { + case CurveBlockTypes.EaseInSine: + registeredFunction = `return 1.0 - cos((v * 3.1415) / 2.0)`; + break; + case CurveBlockTypes.EaseOutSine: + registeredFunction = `return sin((v * 3.1415) / 2.0)`; + break; + case CurveBlockTypes.EaseInOutSine: + registeredFunction = `return -(cos(v * 3.1415) - 1.0) / 2.0`; + break; + case CurveBlockTypes.EaseInQuad: + registeredFunction = `return v * v`; + break; + case CurveBlockTypes.EaseOutQuad: + registeredFunction = `return (1.0 - v) * (1.0 - v)`; + break; + case CurveBlockTypes.EaseInOutQuad: { + const entry = state._generateTernary("2.0 * VAL * VAL", "1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0", "VAL < 0.5"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInCubic: + registeredFunction = `return v * v * v`; + break; + case CurveBlockTypes.EaseOutCubic: { + const entry = "1.0 - pow(1.0 - VAL, 3.0)"; + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInOutCubic: { + const entry = state._generateTernary("4.0 * VAL * VAL * VAL", "1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0", "VAL < 0.5"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInQuart: + registeredFunction = `return v * v * v * v`; + break; + case CurveBlockTypes.EaseOutQuart: { + const entry = "1.0 - pow(1.0 - VAL, 4.0)"; + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInOutQuart: { + const entry = state._generateTernary("8.0 * VAL * VAL * VAL * VAL", "1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0", "VAL < 0.5"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInQuint: + registeredFunction = `return v * v * v * v * v`; + break; + case CurveBlockTypes.EaseOutQuint: { + const entry = "1.0 - pow(1.0 - VAL, 5.0)"; + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInOutQuint: { + const entry = state._generateTernary("16.0 * VAL * VAL * VAL * VAL * VAL", "1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0", "VAL < 0.5"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInExpo: { + const entry = state._generateTernary("0.0", "pow(2.0, 10.0 * VAL - 10.0)", "VAL == 0.0"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseOutExpo: { + const entry = state._generateTernary("1.0", "1.0 - pow(2.0, -10.0 * VAL)", "VAL == 1.0"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInOutExpo: { + const entry = state._generateTernary("0.0", state._generateTernary("1.0", state._generateTernary("pow(2.0, 20.0 * VAL - 10.0) / 2.0", "(2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0", "VAL < 0.5"), "VAL == 1.0"), "VAL == 0.0"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInCirc: { + const entry = "1.0 - sqrt(1.0 - pow(VAL, 2.0))"; + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseOutCirc: { + const entry = "sqrt(1.0 - pow(VAL - 1.0, 2.0))"; + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInOutCirc: { + const entry = state._generateTernary("(1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0", "(sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0", "VAL < 0.5"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInBack: { + registeredFunction = "return 2.70158 * v * v * v - 1.70158 * v * v"; + break; + } + case CurveBlockTypes.EaseOutBack: { + const entry = "2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)"; + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInOutBack: { + const entry = state._generateTernary("(pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0", "(pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0", "VAL < 0.5"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInElastic: { + const entry = state._generateTernary("0.0", state._generateTernary("1.0", "-pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))", "VAL == 1.0"), "VAL == 0.0"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseOutElastic: { + const entry = state._generateTernary("0.0", state._generateTernary("1.0", "pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0", "VAL == 1.0"), "VAL == 0.0"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + case CurveBlockTypes.EaseInOutElastic: { + const entry = state._generateTernary("0.0", state._generateTernary("1.0", state._generateTernary("-(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0", "(pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0", "VAL < 0.5"), "VAL == 1.0"), "VAL == 0.0"); + registeredFunction = this._duplicateVector(entry, inputType, isWGSL); + break; + } + } + if (isWGSL) { + state._emitFunction(registeredFunctionName, `fn ${registeredFunctionName}(v: ${inputType}) -> ${inputType} {${registeredFunction};}\n`, ""); + } + else { + state._emitFunction(registeredFunctionName, `${inputType} ${registeredFunctionName}(${inputType} v) {${registeredFunction};}\n`, ""); + } + state.compilationString += state._declareOutput(output) + ` = ${registeredFunctionName}(${this.input.associatedVariableName});\n`; + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.curveType = this.type; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.type = serializationObject.curveType; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${CurveBlockTypes[this.type]};\n`; + return codeString; + } +} +__decorate([ + editableInPropertyPage("Type", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "EaseInSine", value: CurveBlockTypes.EaseInSine }, + { label: "EaseOutSine", value: CurveBlockTypes.EaseOutSine }, + { label: "EaseInOutSine", value: CurveBlockTypes.EaseInOutSine }, + { label: "EaseInQuad", value: CurveBlockTypes.EaseInQuad }, + { label: "EaseOutQuad", value: CurveBlockTypes.EaseOutQuad }, + { label: "EaseInOutQuad", value: CurveBlockTypes.EaseInOutQuad }, + { label: "EaseInCubic", value: CurveBlockTypes.EaseInCubic }, + { label: "EaseOutCubic", value: CurveBlockTypes.EaseOutCubic }, + { label: "EaseInOutCubic", value: CurveBlockTypes.EaseInOutCubic }, + { label: "EaseInQuart", value: CurveBlockTypes.EaseInQuart }, + { label: "EaseOutQuart", value: CurveBlockTypes.EaseOutQuart }, + { label: "EaseInOutQuart", value: CurveBlockTypes.EaseInOutQuart }, + { label: "EaseInQuint", value: CurveBlockTypes.EaseInQuint }, + { label: "EaseOutQuint", value: CurveBlockTypes.EaseOutQuint }, + { label: "EaseInOutQuint", value: CurveBlockTypes.EaseInOutQuint }, + { label: "EaseInExpo", value: CurveBlockTypes.EaseInExpo }, + { label: "EaseOutExpo", value: CurveBlockTypes.EaseOutExpo }, + { label: "EaseInOutExpo", value: CurveBlockTypes.EaseInOutExpo }, + { label: "EaseInCirc", value: CurveBlockTypes.EaseInCirc }, + { label: "EaseOutCirc", value: CurveBlockTypes.EaseOutCirc }, + { label: "EaseInOutCirc", value: CurveBlockTypes.EaseInOutCirc }, + { label: "EaseInBack", value: CurveBlockTypes.EaseInBack }, + { label: "EaseOutBack", value: CurveBlockTypes.EaseOutBack }, + { label: "EaseInOutBack", value: CurveBlockTypes.EaseInOutBack }, + { label: "EaseInElastic", value: CurveBlockTypes.EaseInElastic }, + { label: "EaseOutElastic", value: CurveBlockTypes.EaseOutElastic }, + { label: "EaseInOutElastic", value: CurveBlockTypes.EaseInOutElastic }, + ], + }) +], CurveBlock.prototype, "type", void 0); +RegisterClass("BABYLON.CurveBlock", CurveBlock); + +/** + * Block used to apply rgb/hsl convertions + */ +class ColorConverterBlock extends NodeMaterialBlock { + /** + * Create a new ColorConverterBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, true); + this.registerInput("hsl ", NodeMaterialBlockConnectionPointTypes.Color3, true); + this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3); + this.registerOutput("hsl", NodeMaterialBlockConnectionPointTypes.Color3); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ColorConverterBlock"; + } + /** + * Gets the rgb value (input) + */ + get rgbIn() { + return this._inputs[0]; + } + /** + * Gets the hsl value (input) + */ + get hslIn() { + return this._inputs[1]; + } + /** + * Gets the rgb value (output) + */ + get rgbOut() { + return this._outputs[0]; + } + /** + * Gets the hsl value (output) + */ + get hslOut() { + return this._outputs[1]; + } + _inputRename(name) { + if (name === "rgb ") { + return "rgbIn"; + } + if (name === "hsl ") { + return "hslIn"; + } + return name; + } + _buildBlock(state) { + super._buildBlock(state); + const rgbInput = this.rgbIn; + const hslInput = this.hslIn; + const rbgOutput = this._outputs[0]; + const hslOutput = this._outputs[1]; + const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3); + let rgb2hsl = ` + vec3 rgb2hsl(vec3 color) { + float r = color.r; + float g = color.g; + float b = color.b; + + float maxc = max(r, max(g, b)); + float minc = min(r, min(g, b)); + float h = 0.0; + float s = 0.0; + float l = (maxc + minc) / 2.0; + + if (maxc != minc) { + float d = maxc - minc; + if (l > 0.5) { + s = d / (2.0 - maxc - minc); + } else { + s = d / (maxc + minc); + } + + if (maxc == r) { + float add = 0.0; + if (g < b) { + add = 6.0; + } + h = (g - b) / d + add; + } else if (maxc == g) { + h = (b - r) / d + 2.0; + } else if (maxc == b) { + h = (r - g) / d + 4.0; + } + h /= 6.0; + } + + return vec3(h, s, l); + }`; + let hue2rgb = ` + float hue2rgb(float p, float q, float tt) { + float t = tt; + if (t < 0.0) { + t += 1.0; + } + if (t > 1.0) { + t -= 1.0; + } + if (t < 1.0/6.0) { + return p + (q - p) * 6.0 * t; + } + if (t < 1.0/2.0) { + return q; + } + if (t < 2.0/3.0) { + return p + (q - p) * (2.0/3.0 - t) * 6.0; + } + return p; + }`; + let hsl2rgb = ` + vec3 hsl2rgb(vec3 hsl) { + float h = hsl.x; + float s = hsl.y; + float l = hsl.z; + + float r; + float g; + float b; + + if (s == 0.0) { + // Achromatic (grey) + r = l; + g = l; + b = l; + } else { + float q; + + if (l < 0.5) { + q = l * (1.0 + s); + } else { + q = (l + s - l * s); + } + + float p = 2.0 * l - q; + + r = hue2rgb(p, q, h + 1.0/3.0); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1.0/3.0); + } + + return vec3(r, g, b); + }`; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + rgb2hsl = state._babylonSLtoWGSL(rgb2hsl); + hue2rgb = state._babylonSLtoWGSL(hue2rgb); + hsl2rgb = state._babylonSLtoWGSL(hsl2rgb); + } + state._emitFunction("rgb2hsl", rgb2hsl, ""); + state._emitFunction("hue2rgb", hue2rgb, ""); + state._emitFunction("hsl2rgb", hsl2rgb, ""); + if (rgbInput.isConnected) { + if (rbgOutput.hasEndpoints) { + state.compilationString += state._declareOutput(rbgOutput) + ` = ${rgbInput.associatedVariableName};\n`; + } + if (hslOutput.hasEndpoints) { + state.compilationString += state._declareOutput(hslOutput) + ` = rgb2hsl(${rgbInput.associatedVariableName});\n`; + } + } + else if (hslInput.isConnected) { + if (rbgOutput.hasEndpoints) { + state.compilationString += state._declareOutput(rbgOutput) + ` = hsl2rgb(${hslInput.associatedVariableName});\n`; + } + if (hslOutput.hasEndpoints) { + state.compilationString += state._declareOutput(hslOutput) + ` = ${hslInput.associatedVariableName};\n`; + } + } + else { + if (rbgOutput.hasEndpoints) { + state.compilationString += state._declareOutput(rbgOutput) + ` = ${vec3}(0.);\n`; + } + if (hslOutput.hasEndpoints) { + state.compilationString += state._declareOutput(hslOutput) + ` = ${vec3}(0.);\n`; + } + } + return this; + } +} +RegisterClass("BABYLON.ColorConverterBlock", ColorConverterBlock); + +/** + * Block used to repeat code + */ +class LoopBlock extends NodeMaterialBlock { + /** + * Creates a new LoopBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + /** + * Gets or sets number of iterations + * Will be ignored if the iterations input is connected + */ + this.iterations = 4; + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this.registerInput("iterations", NodeMaterialBlockConnectionPointTypes.Float, true); + this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); + this.registerOutput("index", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); + this.registerOutput("loopID", NodeMaterialBlockConnectionPointTypes.Object, undefined, new NodeMaterialConnectionPointCustomObject("loopID", this, 1 /* NodeMaterialConnectionPointDirection.Output */, LoopBlock, "LoopBlock")); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._outputs[0]._forPostBuild = true; + this._outputs[2]._redirectedSource = this._inputs[0]; + this._outputs[1]._preventBubbleUp = true; + this._outputs[2]._preventBubbleUp = true; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "LoopBlock"; + } + /** + * Gets the main input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the iterations input component + */ + get iterationsInput() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the index component which will be incremented at each iteration + */ + get index() { + return this._outputs[1]; + } + /** + * Gets the loop ID component + */ + get loopID() { + return this._outputs[2]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const index = this._outputs[1]; + const indexName = state._getFreeVariableName("index"); + const decl = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "var" : "int"; + const castFloat = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "f32" : "float"; + const castInt = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "i32" : "int"; + // Declare storage variable and store initial value + state.compilationString += state._declareOutput(output) + ` = ${this.input.associatedVariableName};\n`; + // Iterations + const iterations = this.iterationsInput.isConnected ? `${castInt}(${this.iterationsInput.associatedVariableName})` : this.iterations; + // Loop + state.compilationString += `for (${decl} ${indexName} = 0; ${indexName} < ${iterations}; ${indexName}++){\n`; + state.compilationString += `${state._declareOutput(index)} = ${castFloat}(${indexName});\n`; + return this; + } + _postBuildBlock(state) { + super._postBuildBlock(state); + state.compilationString += `}\n`; + return this; + } + _dumpPropertiesCode() { + return super._dumpPropertiesCode() + `${this._codeVariableName}.iterations = ${this.iterations};\n`; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.iterations = this.iterations; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.iterations = serializationObject.iterations; + } +} +__decorate([ + editableInPropertyPage("Iterations", 2 /* PropertyTypeForEdition.Int */, undefined, { embedded: true }) +], LoopBlock.prototype, "iterations", void 0); +RegisterClass("BABYLON.LoopBlock", LoopBlock); + +/** + * Block used to read from a variable within a loop + */ +class StorageReadBlock extends NodeMaterialBlock { + /** + * Creates a new StorageReadBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("loopID", NodeMaterialBlockConnectionPointTypes.Object, false, undefined, new NodeMaterialConnectionPointCustomObject("loopID", this, 0 /* NodeMaterialConnectionPointDirection.Input */, LoopBlock, "LoopBlock")); + this.registerOutput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this._outputs[0]._linkedConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "StorageReadBlock"; + } + /** + * Gets the loop link component + */ + get loopID() { + return this._inputs[0]; + } + /** + * Gets the value component + */ + get value() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const value = this.value; + if (!this.loopID.isConnected) { + return this; + } + const loopBlock = this.loopID.connectedPoint.ownerBlock; + state.compilationString += state._declareOutput(value) + ` = ${loopBlock.output.associatedVariableName};\n`; + return this; + } +} +RegisterClass("BABYLON.StorageReadBlock", StorageReadBlock); + +/** + * Block used to write to a variable within a loop + */ +class StorageWriteBlock extends NodeMaterialBlock { + /** + * Creates a new StorageWriteBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("loopID", NodeMaterialBlockConnectionPointTypes.Object, false, undefined, new NodeMaterialConnectionPointCustomObject("loopID", this, 0 /* NodeMaterialConnectionPointDirection.Input */, LoopBlock, "LoopBlock")); + this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); + this._linkConnectionTypes(0, 1); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "StorageWriteBlock"; + } + /** + * Gets the loop link component + */ + get loopID() { + return this._inputs[0]; + } + /** + * Gets the value component + */ + get value() { + return this._inputs[1]; + } + /** Gets a boolean indicating that this connection will be used in the fragment shader + * @returns true if connected in fragment shader + */ + isConnectedInFragmentShader() { + if (!this.loopID.isConnected) { + return false; + } + const loopBlock = this.loopID.connectedPoint.ownerBlock; + return loopBlock.output.isConnectedInFragmentShader; + } + _buildBlock(state) { + super._buildBlock(state); + const value = this.value; + if (!this.loopID.isConnected) { + return this; + } + const loopBlock = this.loopID.connectedPoint.ownerBlock; + state.compilationString += `${loopBlock.output.associatedVariableName} = ${value.associatedVariableName};\n`; + return this; + } +} +RegisterClass("BABYLON.StorageWriteBlock", StorageWriteBlock); + +/** + * Block used to split a matrix into Vector4 + */ +class MatrixSplitterBlock extends NodeMaterialBlock { + /** + * Creates a new MatrixSplitterBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Neutral); + this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Matrix); + this.registerOutput("row0", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("row1", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("row2", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("row3", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("col0", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("col1", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("col2", NodeMaterialBlockConnectionPointTypes.Vector4); + this.registerOutput("col3", NodeMaterialBlockConnectionPointTypes.Vector4); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MatrixSplitterBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the row0 output vector + */ + get row0() { + return this._outputs[0]; + } + /** + * Gets the row1 output vector + */ + get row1() { + return this._outputs[1]; + } + /** + * Gets the row2 output vector + */ + get row2() { + return this._outputs[2]; + } + /** + * Gets the row3 output vector + */ + get row3() { + return this._outputs[3]; + } + /** + * Gets the col0 output vector + */ + get col0() { + return this._outputs[4]; + } + /** + * Gets the col1 output vector + */ + get col1() { + return this._outputs[5]; + } + /** + * Gets the col2 output vector + */ + get col2() { + return this._outputs[6]; + } + /** + * Gets the col3 output vector + */ + get col3() { + return this._outputs[7]; + } + _exportColumn(state, col, input, columnIndex) { + const vec4 = state.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "vec4f" : "vec4"; + state.compilationString += + state._declareOutput(col) + ` = ${vec4}(${input}[0][${columnIndex}], ${input}[1][${columnIndex}], ${input}[2][${columnIndex}], ${input}[3][${columnIndex}]);\n`; + } + _buildBlock(state) { + super._buildBlock(state); + const input = this._inputs[0].associatedVariableName; + const row0 = this.row0; + const row1 = this.row1; + const row2 = this.row2; + const row3 = this.row3; + const col0 = this.col0; + const col1 = this.col1; + const col2 = this.col2; + const col3 = this.col3; + if (row0.hasEndpoints) { + state.compilationString += state._declareOutput(row0) + ` = ${input}[0];\n`; + } + if (row1.hasEndpoints) { + state.compilationString += state._declareOutput(row1) + ` = ${input}[1];\n`; + } + if (row2.hasEndpoints) { + state.compilationString += state._declareOutput(row2) + ` = ${input}[2];\n`; + } + if (row3.hasEndpoints) { + state.compilationString += state._declareOutput(row3) + ` = ${input}[3];\n`; + } + if (col0.hasEndpoints) { + this._exportColumn(state, col0, input, 0); + } + if (col1.hasEndpoints) { + this._exportColumn(state, col1, input, 1); + } + if (col2.hasEndpoints) { + this._exportColumn(state, col2, input, 2); + } + if (col3.hasEndpoints) { + this._exportColumn(state, col3, input, 3); + } + return this; + } +} +RegisterClass("BABYLON.MatrixSplitterBlock", MatrixSplitterBlock); + +// Do not edit. +const name$3P = "gaussianSplattingVertexDeclaration"; +const shader$3O = `attribute position: vec2f; +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$3P]) { + ShaderStore.IncludesShadersStoreWGSL[name$3P] = shader$3O; +} + +/** + * Block used to render intermediate debug values + * Please note that the node needs to be active to be generated in the shader + * Only one DebugBlock should be active at a time + */ +class NodeMaterialDebugBlock extends NodeMaterialBlock { + /** + * Gets or sets a boolean indicating that the block is active + */ + get isActive() { + return this._isActive && this.debug.isConnected; + } + set isActive(value) { + if (this._isActive === value) { + return; + } + this._isActive = value; + } + /** + * Creates a new NodeMaterialDebugBlock + * @param name defines the block name + */ + constructor(name) { + super(name, NodeMaterialBlockTargets.Fragment, true, true); + this._isActive = false; + /** Gets or sets a boolean indicating if we want to render alpha when using a rgba input*/ + this.renderAlpha = false; + this.registerInput("debug", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); + this.debug.excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); + } + /** @internal */ + get _isFinalOutputAndActive() { + return this.isActive; + } + /** @internal */ + get _hasPrecedence() { + return true; + } + /** + * Gets the rgba input component + */ + get debug() { + return this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NodeMaterialDebugBlock"; + } + _buildBlock(state) { + super._buildBlock(state); + if (!this._isActive) { + return this; + } + let outputString = "gl_FragColor"; + if (state.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + outputString = "fragmentOutputs.color"; + } + const debug = this.debug; + if (!debug.connectedPoint) { + return this; + } + if (debug.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float) { + state.compilationString += `${outputString} = vec4${state.fSuffix}(${debug.associatedVariableName}, ${debug.associatedVariableName}, ${debug.associatedVariableName}, 1.0);\n`; + } + else if (debug.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector2) { + state.compilationString += `${outputString} = vec4${state.fSuffix}(${debug.associatedVariableName}, 0., 1.0);\n`; + } + else if (debug.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Color3 || debug.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector3) { + state.compilationString += `${outputString} = vec4${state.fSuffix}(${debug.associatedVariableName}, 1.0);\n`; + } + else if (this.renderAlpha) { + state.compilationString += `${outputString} =${debug.associatedVariableName};\n`; + } + else { + state.compilationString += `${outputString} = vec4${state.fSuffix}(${debug.associatedVariableName}.rgb, 1.0);\n`; + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.isActive = this._isActive; + serializationObject.renderAlpha = this.renderAlpha; + return serializationObject; + } + _deserialize(serializationObject, scene, rootUrl) { + super._deserialize(serializationObject, scene, rootUrl); + this.isActive = serializationObject.isActive; + this.renderAlpha = serializationObject.renderAlpha; + } +} +__decorate([ + editableInPropertyPage("Render Alpha", 0 /* PropertyTypeForEdition.Boolean */, undefined) +], NodeMaterialDebugBlock.prototype, "renderAlpha", void 0); +RegisterClass("BABYLON.NodeMaterialDebugBlock", NodeMaterialDebugBlock); + +/** + * @internal + */ +var MaterialPluginEvent; +(function (MaterialPluginEvent) { + MaterialPluginEvent[MaterialPluginEvent["Created"] = 1] = "Created"; + MaterialPluginEvent[MaterialPluginEvent["Disposed"] = 2] = "Disposed"; + MaterialPluginEvent[MaterialPluginEvent["GetDefineNames"] = 4] = "GetDefineNames"; + MaterialPluginEvent[MaterialPluginEvent["PrepareUniformBuffer"] = 8] = "PrepareUniformBuffer"; + MaterialPluginEvent[MaterialPluginEvent["IsReadyForSubMesh"] = 16] = "IsReadyForSubMesh"; + MaterialPluginEvent[MaterialPluginEvent["PrepareDefines"] = 32] = "PrepareDefines"; + MaterialPluginEvent[MaterialPluginEvent["BindForSubMesh"] = 64] = "BindForSubMesh"; + MaterialPluginEvent[MaterialPluginEvent["PrepareEffect"] = 128] = "PrepareEffect"; + MaterialPluginEvent[MaterialPluginEvent["GetAnimatables"] = 256] = "GetAnimatables"; + MaterialPluginEvent[MaterialPluginEvent["GetActiveTextures"] = 512] = "GetActiveTextures"; + MaterialPluginEvent[MaterialPluginEvent["HasTexture"] = 1024] = "HasTexture"; + MaterialPluginEvent[MaterialPluginEvent["FillRenderTargetTextures"] = 2048] = "FillRenderTargetTextures"; + MaterialPluginEvent[MaterialPluginEvent["HasRenderTargetTextures"] = 4096] = "HasRenderTargetTextures"; + MaterialPluginEvent[MaterialPluginEvent["HardBindForSubMesh"] = 8192] = "HardBindForSubMesh"; +})(MaterialPluginEvent || (MaterialPluginEvent = {})); + +/** + * @internal + */ +class DecalMapDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.DECAL = false; + this.DECALDIRECTUV = 0; + this.DECAL_SMOOTHALPHA = false; + this.GAMMADECAL = false; + } +} +/** + * Plugin that implements the decal map component of a material + * @since 5.49.1 + */ +class DecalMapConfiguration extends MaterialPluginBase { + /** @internal */ + _markAllSubMeshesAsTexturesDirty() { + this._enable(this._isEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + /** + * Creates a new DecalMapConfiguration + * @param material The material to attach the decal map plugin to + * @param addToPluginList If the plugin should be added to the material plugin list + */ + constructor(material, addToPluginList = true) { + super(material, "DecalMap", 150, new DecalMapDefines(), addToPluginList); + this._isEnabled = false; + /** + * Enables or disables the decal map on this material + */ + this.isEnabled = false; + this._smoothAlpha = false; + /** + * Enables or disables the smooth alpha mode on this material. Default: false. + * When enabled, the alpha value used to blend the decal map will be the squared value and will produce a smoother result. + */ + this.smoothAlpha = false; + this.registerForExtraEvents = true; // because we override the hardBindForSubMesh method + this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; + } + isReadyForSubMesh(defines, scene, engine, subMesh) { + const decalMap = subMesh.getMesh().decalMap; + if (!this._isEnabled || !decalMap?.texture || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) { + return true; + } + return decalMap.isReady(); + } + prepareDefinesBeforeAttributes(defines, scene, mesh) { + const decalMap = mesh.decalMap; + if (!this._isEnabled || !decalMap?.texture || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) { + const isDirty = defines.DECAL; + if (isDirty) { + defines.markAsTexturesDirty(); + } + defines.DECAL = false; + } + else { + const isDirty = !defines.DECAL || defines.GAMMADECAL !== decalMap.texture.gammaSpace; + if (isDirty) { + defines.markAsTexturesDirty(); + } + defines.DECAL = true; + defines.GAMMADECAL = decalMap.texture.gammaSpace; + defines.DECAL_SMOOTHALPHA = this._smoothAlpha; + PrepareDefinesForMergedUV(decalMap.texture, defines, "DECAL"); + } + } + hardBindForSubMesh(uniformBuffer, scene, _engine, subMesh) { + /** + * Note that we override hardBindForSubMesh and not bindForSubMesh because the material can be shared by multiple meshes, + * in which case mustRebind could return false even though the decal map is different for each mesh: that's because the decal map + * is not part of the material but hosted by the decalMap of the mesh instead. + */ + const decalMap = subMesh.getMesh().decalMap; + if (!this._isEnabled || !decalMap?.texture || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) { + return; + } + const isFrozen = this._material.isFrozen; + const texture = decalMap.texture; + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + uniformBuffer.updateFloat4("vDecalInfos", texture.coordinatesIndex, 0, 0, 0); + BindTextureMatrix(texture, uniformBuffer, "decal"); + } + uniformBuffer.setTexture("decalSampler", texture); + } + getClassName() { + return "DecalMapConfiguration"; + } + getSamplers(samplers) { + samplers.push("decalSampler"); + } + getUniforms() { + return { + ubo: [ + { name: "vDecalInfos", size: 4, type: "vec4" }, + { name: "decalMatrix", size: 16, type: "mat4" }, + ], + }; + } +} +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], DecalMapConfiguration.prototype, "isEnabled", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], DecalMapConfiguration.prototype, "smoothAlpha", void 0); +RegisterClass("BABYLON.DecalMapConfiguration", DecalMapConfiguration); + +/** + * Default settings for GreasedLine materials + */ +class GreasedLineMaterialDefaults { +} +/** + * Default line color for newly created lines + */ +GreasedLineMaterialDefaults.DEFAULT_COLOR = Color3.White(); +/** + * Default line width when sizeAttenuation is true + */ +GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED = 1; +/** + * Defaule line width + */ +GreasedLineMaterialDefaults.DEFAULT_WIDTH = 0.1; + +/** + * Tool functions for GreasedLine + */ +class GreasedLineTools { + /** + * Converts GreasedLinePoints to number[][] + * @param points GreasedLinePoints + * @param options GreasedLineToolsConvertPointsOptions + * @returns number[][] with x, y, z coordinates of the points, like [[x, y, z, x, y, z, ...], [x, y, z, ...]] + */ + static ConvertPoints(points, options) { + if (points.length && Array.isArray(points) && typeof points[0] === "number") { + return [points]; + } + else if (points.length && Array.isArray(points[0]) && typeof points[0][0] === "number") { + return points; + } + else if (points.length && !Array.isArray(points[0]) && points[0] instanceof Vector3) { + const positions = []; + for (let j = 0; j < points.length; j++) { + const p = points[j]; + positions.push(p.x, p.y, p.z); + } + return [positions]; + } + else if (points.length > 0 && Array.isArray(points[0]) && points[0].length > 0 && points[0][0] instanceof Vector3) { + const positions = []; + const vectorPoints = points; + vectorPoints.forEach((p) => { + positions.push(p.flatMap((p2) => [p2.x, p2.y, p2.z])); + }); + return positions; + } + else if (points instanceof Float32Array) { + if (options?.floatArrayStride) { + const positions = []; + const stride = options.floatArrayStride * 3; + for (let i = 0; i < points.length; i += stride) { + const linePoints = new Array(stride); // Pre-allocate memory for the line + for (let j = 0; j < stride; j++) { + linePoints[j] = points[i + j]; + } + positions.push(linePoints); + } + return positions; + } + else { + return [Array.from(points)]; + } + } + else if (points.length && points[0] instanceof Float32Array) { + const positions = []; + points.forEach((p) => { + positions.push(Array.from(p)); + }); + return positions; + } + return []; + } + /** + * Omit zero length lines predicate for the MeshesToLines function + * @param p1 point1 position of the face + * @param p2 point2 position of the face + * @param p3 point3 position of the face + * @returns original points or null if any edge length is zero + */ + static OmitZeroLengthPredicate(p1, p2, p3) { + const fileredPoints = []; + // edge1 + if (p2.subtract(p1).lengthSquared() > 0) { + fileredPoints.push([p1, p2]); + } + // edge2 + if (p3.subtract(p2).lengthSquared() > 0) { + fileredPoints.push([p2, p3]); + } + // edge3 + if (p1.subtract(p3).lengthSquared() > 0) { + fileredPoints.push([p3, p1]); + } + return fileredPoints.length === 0 ? null : fileredPoints; + } + /** + * Omit duplicate lines predicate for the MeshesToLines function + * @param p1 point1 position of the face + * @param p2 point2 position of the face + * @param p3 point3 position of the face + * @param points array of points to search in + * @returns original points or null if any edge length is zero + */ + static OmitDuplicatesPredicate(p1, p2, p3, points) { + const fileredPoints = []; + // edge1 + if (!GreasedLineTools._SearchInPoints(p1, p2, points)) { + fileredPoints.push([p1, p2]); + } + // edge2 + if (!GreasedLineTools._SearchInPoints(p2, p3, points)) { + fileredPoints.push([p2, p3]); + } + // edge3 + if (!GreasedLineTools._SearchInPoints(p3, p1, points)) { + fileredPoints.push([p3, p1]); + } + return fileredPoints.length === 0 ? null : fileredPoints; + } + static _SearchInPoints(p1, p2, points) { + for (const ps of points) { + for (let i = 0; i < ps.length; i++) { + if (ps[i]?.equals(p1)) { + // find the first point + // if it has a sibling of p2 the line already exists + if (ps[i + 1]?.equals(p2) || ps[i - 1]?.equals(p2)) { + return true; + } + } + } + } + return false; + } + /** + * Gets mesh triangles as line positions + * @param meshes array of meshes + * @param predicate predicate function which decides whether to include the mesh triangle/face in the ouput + * @returns array of arrays of points + */ + static MeshesToLines(meshes, predicate) { + const points = []; + meshes.forEach((m, meshIndex) => { + const vertices = m.getVerticesData(VertexBuffer.PositionKind); + const indices = m.getIndices(); + if (vertices && indices) { + for (let i = 0, ii = 0; i < indices.length; i++) { + const vi1 = indices[ii++] * 3; + const vi2 = indices[ii++] * 3; + const vi3 = indices[ii++] * 3; + const p1 = new Vector3(vertices[vi1], vertices[vi1 + 1], vertices[vi1 + 2]); + const p2 = new Vector3(vertices[vi2], vertices[vi2 + 1], vertices[vi2 + 2]); + const p3 = new Vector3(vertices[vi3], vertices[vi3 + 1], vertices[vi3 + 2]); + if (predicate) { + const pointsFromPredicate = predicate(p1, p2, p3, points, i, vi1, m, meshIndex, vertices, indices); + if (pointsFromPredicate) { + for (const p of pointsFromPredicate) { + points.push(p); + } + } + } + else { + points.push([p1, p2], [p2, p3], [p3, p1]); + } + } + } + }); + return points; + } + /** + * Converts number coordinates to Vector3s + * @param points number array of x, y, z, x, y z, ... coordinates + * @returns Vector3 array + */ + static ToVector3Array(points) { + if (Array.isArray(points[0])) { + const array = []; + const inputArray = points; + for (const subInputArray of inputArray) { + const subArray = []; + for (let i = 0; i < subInputArray.length; i += 3) { + subArray.push(new Vector3(subInputArray[i], subInputArray[i + 1], subInputArray[i + 2])); + } + array.push(subArray); + } + return array; + } + const inputArray = points; + const array = []; + for (let i = 0; i < inputArray.length; i += 3) { + array.push(new Vector3(inputArray[i], inputArray[i + 1], inputArray[i + 2])); + } + return array; + } + /** + * Gets a number array from a Vector3 array. + * You can you for example to convert your Vector3[] offsets to the required number[] for the offsets option. + * @param points Vector3 array + * @returns an array of x, y, z coordinates as numbers [x, y, z, x, y, z, x, y, z, ....] + */ + static ToNumberArray(points) { + return points.flatMap((v) => [v.x, v.y, v.z]); + } + /** + * Calculates the sum of points of every line and the number of points in each line. + * This function is useful when you are drawing multiple lines in one mesh and you want + * to know the counts. For example for creating an offsets table. + * @param points point array + * @returns points count info + */ + static GetPointsCountInfo(points) { + const counts = new Array(points.length); + let total = 0; + for (let n = points.length; n--;) { + counts[n] = points[n].length / 3; + total += counts[n]; + } + return { total, counts }; + } + /** + * Gets the length of the line counting all it's segments length + * @param data array of line points + * @returns length of the line + */ + static GetLineLength(data) { + if (data.length === 0) { + return 0; + } + let points; + if (typeof data[0] === "number") { + points = GreasedLineTools.ToVector3Array(data); + } + else { + points = data; + } + const tmp = TmpVectors.Vector3[0]; + let length = 0; + for (let index = 0; index < points.length - 1; index++) { + const point1 = points[index]; + const point2 = points[index + 1]; + length += point2.subtractToRef(point1, tmp).length(); + } + return length; + } + /** + * Gets the the length from the beginning to each point of the line as array. + * @param data array of line points + * @returns length array of the line + */ + static GetLineLengthArray(data) { + const out = new Float32Array(data.length / 3); + let length = 0; + for (let index = 0, pointsLength = data.length / 3 - 1; index < pointsLength; index++) { + let x = data[index * 3 + 0]; + let y = data[index * 3 + 1]; + let z = data[index * 3 + 2]; + x -= data[index * 3 + 3]; + y -= data[index * 3 + 4]; + z -= data[index * 3 + 5]; + const currentLength = Math.sqrt(x * x + y * y + z * z); + length += currentLength; + out[index + 1] = length; + } + return out; + } + /** + * Divides a segment into smaller segments. + * A segment is a part of the line between it's two points. + * @param point1 first point of the line + * @param point2 second point of the line + * @param segmentCount number of segments we want to have in the divided line + * @returns + */ + static SegmentizeSegmentByCount(point1, point2, segmentCount) { + const dividedLinePoints = []; + const diff = point2.subtract(point1); + const divisor = TmpVectors.Vector3[0]; + divisor.setAll(segmentCount); + const segmentVector = TmpVectors.Vector3[1]; + diff.divideToRef(divisor, segmentVector); + let nextPoint = point1.clone(); + dividedLinePoints.push(nextPoint); + for (let index = 0; index < segmentCount; index++) { + nextPoint = nextPoint.clone(); + dividedLinePoints.push(nextPoint.addInPlace(segmentVector)); + } + return dividedLinePoints; + } + /** + * Divides a line into segments. + * A segment is a part of the line between it's two points. + * @param what line points + * @param segmentLength length of each segment of the resulting line (distance between two line points) + * @returns line point + */ + static SegmentizeLineBySegmentLength(what, segmentLength) { + const subLines = what[0] instanceof Vector3 + ? GreasedLineTools.GetLineSegments(what) + : typeof what[0] === "number" + ? GreasedLineTools.GetLineSegments(GreasedLineTools.ToVector3Array(what)) + : what; + const points = []; + subLines.forEach((s) => { + if (s.length > segmentLength) { + const segments = GreasedLineTools.SegmentizeSegmentByCount(s.point1, s.point2, Math.ceil(s.length / segmentLength)); + segments.forEach((seg) => { + points.push(seg); + }); + } + else { + points.push(s.point1); + points.push(s.point2); + } + }); + return points; + } + /** + * Divides a line into segments. + * A segment is a part of the line between it's two points. + * @param what line points + * @param segmentCount number of segments + * @returns line point + */ + static SegmentizeLineBySegmentCount(what, segmentCount) { + const points = (typeof what[0] === "number" ? GreasedLineTools.ToVector3Array(what) : what); + const segmentLength = GreasedLineTools.GetLineLength(points) / segmentCount; + return GreasedLineTools.SegmentizeLineBySegmentLength(points, segmentLength); + } + /** + * Gets line segments. + * A segment is a part of the line between it's two points. + * @param points line points + * @returns segments information of the line segment including starting point, ending point and the distance between them + */ + static GetLineSegments(points) { + const segments = []; + for (let index = 0; index < points.length - 1; index++) { + const point1 = points[index]; + const point2 = points[index + 1]; + const length = point2.subtract(point1).length(); + segments.push({ point1, point2, length }); + } + return segments; + } + /** + * Gets the minimum and the maximum length of a line segment in the line. + * A segment is a part of the line between it's two points. + * @param points line points + * @returns + */ + static GetMinMaxSegmentLength(points) { + const subLines = GreasedLineTools.GetLineSegments(points); + const sorted = subLines.sort((s) => s.length); + return { + min: sorted[0].length, + max: sorted[sorted.length - 1].length, + }; + } + /** + * Finds the last visible position in world space of the line according to the visibility parameter + * @param lineSegments segments of the line + * @param lineLength total length of the line + * @param visbility normalized value of visibility + * @param localSpace if true the result will be in local space (default is false) + * @returns world space coordinate of the last visible piece of the line + */ + static GetPositionOnLineByVisibility(lineSegments, lineLength, visbility, localSpace = false) { + const lengthVisibilityRatio = lineLength * visbility; + let sumSegmentLengths = 0; + let segmentIndex = 0; + const lineSegmentsLength = lineSegments.length; + for (let i = 0; i < lineSegmentsLength; i++) { + if (lengthVisibilityRatio <= sumSegmentLengths + lineSegments[i].length) { + segmentIndex = i; + break; + } + sumSegmentLengths += lineSegments[i].length; + } + const s = (lengthVisibilityRatio - sumSegmentLengths) / lineSegments[segmentIndex].length; + lineSegments[segmentIndex].point2.subtractToRef(lineSegments[segmentIndex].point1, TmpVectors.Vector3[0]); + TmpVectors.Vector3[1] = TmpVectors.Vector3[0].multiplyByFloats(s, s, s); + if (!localSpace) { + TmpVectors.Vector3[1].addInPlace(lineSegments[segmentIndex].point1); + } + return TmpVectors.Vector3[1].clone(); + } + /** + * Creates lines in a shape of circle/arc. + * A segment is a part of the line between it's two points. + * @param radiusX radiusX of the circle + * @param segments number of segments in the circle + * @param z z coordinate of the points. Defaults to 0. + * @param radiusY radiusY of the circle - you can draw an oval if using different values + * @param segmentAngle angle offset of the segments. Defaults to Math.PI * 2 / segments. Change this value to draw a part of the circle. + * @returns line points + */ + static GetCircleLinePoints(radiusX, segments, z = 0, radiusY = radiusX, segmentAngle = (Math.PI * 2) / segments) { + const points = []; + for (let i = 0; i <= segments; i++) { + points.push(new Vector3(Math.cos(i * segmentAngle) * radiusX, Math.sin(i * segmentAngle) * radiusY, z)); + } + return points; + } + /** + * Gets line points in a shape of a bezier curve + * @param p0 bezier point0 + * @param p1 bezier point1 + * @param p2 bezier point2 + * @param segments number of segments in the curve + * @returns + */ + static GetBezierLinePoints(p0, p1, p2, segments) { + return Curve3.CreateQuadraticBezier(p0, p1, p2, segments) + .getPoints() + .flatMap((v) => [v.x, v.y, v.z]); + } + /** + * + * @param position position of the arrow cap (mainly you want to create a triangle, set widthUp and widthDown to the same value and omit widthStartUp and widthStartDown) + * @param direction direction which the arrow points to + * @param length length (size) of the arrow cap itself + * @param widthUp the arrow width above the line + * @param widthDown the arrow width belove the line + * @param widthStartUp the arrow width at the start of the arrow above the line. In most scenarios this is 0. + * @param widthStartDown the arrow width at the start of the arrow below the line. In most scenarios this is 0. + * @returns + */ + static GetArrowCap(position, direction, length, widthUp, widthDown, widthStartUp = 0, widthStartDown = 0) { + const points = [position.clone(), position.add(direction.multiplyByFloats(length, length, length))]; + const widths = [widthUp, widthDown, widthStartUp, widthStartDown]; + return { + points, + widths, + }; + } + /** + * Gets 3D positions of points from a text and font + * @param text Text + * @param size Size of the font + * @param resolution Resolution of the font + * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/) + * @param z z coordinate + * @param includeInner include the inner parts of the font in the result. Default true. If false, only the outlines will be returned. + * @returns number[][] of 3D positions + */ + static GetPointsFromText(text, size, resolution, fontData, z = 0, includeInner = true) { + const allPoints = []; + const shapePaths = CreateTextShapePaths(text, size, resolution, fontData); + for (const sp of shapePaths) { + for (const p of sp.paths) { + const points = []; + const points2d = p.getPoints(); + for (const p2d of points2d) { + points.push(p2d.x, p2d.y, z); + } + allPoints.push(points); + } + if (includeInner) { + for (const h of sp.holes) { + const holes = []; + const points2d = h.getPoints(); + for (const p2d of points2d) { + holes.push(p2d.x, p2d.y, z); + } + allPoints.push(holes); + } + } + } + return allPoints; + } + /** + * Converts an array of Color3 to Uint8Array + * @param colors Arrray of Color3 + * @returns Uin8Array of colors [r, g, b, a, r, g, b, a, ...] + */ + static Color3toRGBAUint8(colors) { + const colorTable = new Uint8Array(colors.length * 4); + for (let i = 0, j = 0; i < colors.length; i++) { + colorTable[j++] = colors[i].r * 255; + colorTable[j++] = colors[i].g * 255; + colorTable[j++] = colors[i].b * 255; + colorTable[j++] = 255; + } + return colorTable; + } + /** + * Creates a RawTexture from an RGBA color array and sets it on the plugin material instance. + * @param name name of the texture + * @param colors Uint8Array of colors + * @param colorsSampling sampling mode of the created texture + * @param scene Scene + * @returns the colors texture + */ + static CreateColorsTexture(name, colors, colorsSampling, scene) { + const maxTextureSize = scene.getEngine().getCaps().maxTextureSize ?? 1; + const width = colors.length > maxTextureSize ? maxTextureSize : colors.length; + const height = Math.ceil(colors.length / maxTextureSize); + if (height > 1) { + colors = [...colors, ...Array(width * height - colors.length).fill(colors[0])]; + } + const colorsArray = GreasedLineTools.Color3toRGBAUint8(colors); + const colorsTexture = new RawTexture(colorsArray, width, height, Engine.TEXTUREFORMAT_RGBA, scene, false, true, colorsSampling); + colorsTexture.name = name; + return colorsTexture; + } + /** + * A minimum size texture for the colors sampler2D when there is no colors texture defined yet. + * For fast switching using the useColors property without the need to use defines. + * @param scene Scene + * @returns empty colors texture + */ + static PrepareEmptyColorsTexture(scene) { + if (!GreasedLineMaterialDefaults.EmptyColorsTexture) { + const colorsArray = new Uint8Array(4); + GreasedLineMaterialDefaults.EmptyColorsTexture = new RawTexture(colorsArray, 1, 1, Engine.TEXTUREFORMAT_RGBA, scene, false, false, RawTexture.NEAREST_NEAREST); + GreasedLineMaterialDefaults.EmptyColorsTexture.name = "grlEmptyColorsTexture"; + } + return GreasedLineMaterialDefaults.EmptyColorsTexture; + } + /** + * Diposes the shared empty colors texture + */ + static DisposeEmptyColorsTexture() { + GreasedLineMaterialDefaults.EmptyColorsTexture?.dispose(); + GreasedLineMaterialDefaults.EmptyColorsTexture = null; + } + /** + * Converts boolean to number. + * @param bool the bool value + * @returns 1 if true, 0 if false. + */ + static BooleanToNumber(bool) { + return bool ? 1 : 0; + } +} + +/** + * Returns GLSL custom shader code + * @param shaderType vertex or fragment + * @param cameraFacing is in camera facing mode? + * @returns GLSL custom shader code + */ +/** @internal */ +function GetCustomCode$1(shaderType, cameraFacing) { + if (shaderType === "vertex") { + const obj = { + CUSTOM_VERTEX_DEFINITIONS: ` + attribute float grl_widths; + attribute vec3 grl_offsets; + attribute float grl_colorPointers; + varying float grlCounters; + varying float grlColorPointer; + + #ifdef GREASED_LINE_CAMERA_FACING + attribute vec4 grl_previousAndSide; + attribute vec4 grl_nextAndCounters; + + vec2 grlFix( vec4 i, float aspect ) { + vec2 res = i.xy / i.w; + res.x *= aspect; + return res; + } + #else + attribute vec3 grl_slopes; + attribute float grl_counters; + #endif + `, + CUSTOM_VERTEX_UPDATE_POSITION: ` + #ifdef GREASED_LINE_CAMERA_FACING + vec3 grlPositionOffset = grl_offsets; + positionUpdated += grlPositionOffset; + #else + positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths); + #endif + `, + CUSTOM_VERTEX_MAIN_END: ` + grlColorPointer = grl_colorPointers; + + #ifdef GREASED_LINE_CAMERA_FACING + + float grlAspect = grl_aspect_resolution_lineWidth.x; + float grlBaseWidth = grl_aspect_resolution_lineWidth.w; + + vec3 grlPrevious = grl_previousAndSide.xyz; + float grlSide = grl_previousAndSide.w; + + vec3 grlNext = grl_nextAndCounters.xyz; + grlCounters = grl_nextAndCounters.w; + float grlWidth = grlBaseWidth * grl_widths; + + vec3 worldDir = normalize(grlNext - grlPrevious); + vec3 nearPosition = positionUpdated + (worldDir * 0.001); + mat4 grlMatrix = viewProjection * finalWorld; + vec4 grlFinalPosition = grlMatrix * vec4(positionUpdated , 1.0); + vec4 screenNearPos = grlMatrix * vec4(nearPosition, 1.0); + vec2 grlLinePosition = grlFix(grlFinalPosition, grlAspect); + vec2 grlLineNearPosition = grlFix(screenNearPos, grlAspect); + vec2 grlDir = normalize(grlLineNearPosition - grlLinePosition); + + vec4 grlNormal = vec4(-grlDir.y, grlDir.x, 0., 1.); + + #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM + grlNormal.xy *= -.5 * grlWidth; + #else + grlNormal.xy *= .5 * grlWidth; + #endif + + grlNormal *= grl_projection; + + #ifdef GREASED_LINE_SIZE_ATTENUATION + grlNormal.xy *= grlFinalPosition.w; + grlNormal.xy /= (vec4(grl_aspect_resolution_lineWidth.yz, 0., 1.) * grl_projection).xy; + #endif + + grlFinalPosition.xy += grlNormal.xy * grlSide; + gl_Position = grlFinalPosition; + + vPositionW = vec3(grlFinalPosition); + #else + grlCounters = grl_counters; + #endif + `, + }; + cameraFacing && (obj["!gl_Position\\=viewProjection\\*worldPos;"] = "//"); // not needed for camera facing GRL + return obj; + } + if (shaderType === "fragment") { + return { + CUSTOM_FRAGMENT_DEFINITIONS: ` + #ifdef PBR + #define grlFinalColor finalColor + #else + #define grlFinalColor color + #endif + + varying float grlCounters; + varying float grlColorPointer; + uniform sampler2D grl_colors; + `, + CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: ` + float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; + float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; + float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; + float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; + + float grlUseDash = grl_dashOptions.x; + float grlDashArray = grl_dashOptions.y; + float grlDashOffset = grl_dashOptions.z; + float grlDashRatio = grl_dashOptions.w; + + grlFinalColor.a *= step(grlCounters, grlVisibility); + if(grlFinalColor.a == 0.) discard; + + if(grlUseDash == 1.){ + grlFinalColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); + if (grlFinalColor.a == 0.) discard; + } + + #ifdef GREASED_LINE_HAS_COLOR + if (grlColorMode == ${0 /* GreasedLineMeshColorMode.COLOR_MODE_SET */}.) { + grlFinalColor.rgb = grl_singleColor; + } else if (grlColorMode == ${1 /* GreasedLineMeshColorMode.COLOR_MODE_ADD */}.) { + grlFinalColor.rgb += grl_singleColor; + } else if (grlColorMode == ${2 /* GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY */}.) { + grlFinalColor.rgb *= grl_singleColor; + } + #else + if (grlUseColors == 1.) { + #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE + vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); + #else + vec2 lookup = vec2(fract(grlColorPointer / grl_textureSize.x), 1.0 - floor(grlColorPointer / grl_textureSize.x) / max(grl_textureSize.y - 1.0, 1.0)); + vec4 grlColor = texture2D(grl_colors, lookup, 0.0); + #endif + if (grlColorMode == ${0 /* GreasedLineMeshColorMode.COLOR_MODE_SET */}.) { + grlFinalColor = grlColor; + } else if (grlColorMode == ${1 /* GreasedLineMeshColorMode.COLOR_MODE_ADD */}.) { + grlFinalColor += grlColor; + } else if (grlColorMode == ${2 /* GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY */}.) { + grlFinalColor *= grlColor; + } + } + #endif + `, + }; + } + return null; +} + +/** + * Returns WGSL custom shader code + * @param shaderType vertex or fragment + * @param cameraFacing is in camera facing mode? + * @returns WGSL custom shader code + */ +/** @internal */ +function GetCustomCode(shaderType, cameraFacing) { + if (shaderType === "vertex") { + const obj = { + CUSTOM_VERTEX_DEFINITIONS: ` + attribute grl_widths: f32; + attribute grl_colorPointers: f32; + varying grlCounters: f32; + varying grlColorPointer: f32; + + #ifdef GREASED_LINE_USE_OFFSETS + attribute grl_offsets: vec3f; + #endif + + #ifdef GREASED_LINE_CAMERA_FACING + attribute grl_previousAndSide : vec4f; + attribute grl_nextAndCounters : vec4f; + + fn grlFix(i: vec4f, aspect: f32) -> vec2f { + var res = i.xy / i.w; + res.x *= aspect; + return res; + } + #else + attribute grl_slopes: f32; + attribute grl_counters: f32; + #endif + + + `, + CUSTOM_VERTEX_UPDATE_POSITION: ` + #ifdef GREASED_LINE_USE_OFFSETS + var grlPositionOffset: vec3f = input.grl_offsets; + #else + var grlPositionOffset = vec3f(0.); + #endif + + #ifdef GREASED_LINE_CAMERA_FACING + positionUpdated += grlPositionOffset; + #else + positionUpdated = (positionUpdated + grlPositionOffset) + (input.grl_slopes * input.grl_widths); + #endif + `, + CUSTOM_VERTEX_MAIN_END: ` + vertexOutputs.grlColorPointer = input.grl_colorPointers; + + #ifdef GREASED_LINE_CAMERA_FACING + + let grlAspect: f32 = uniforms.grl_aspect_resolution_lineWidth.x; + let grlBaseWidth: f32 = uniforms.grl_aspect_resolution_lineWidth.w; + + let grlPrevious: vec3f = input.grl_previousAndSide.xyz; + let grlSide: f32 = input.grl_previousAndSide.w; + + let grlNext: vec3f = input.grl_nextAndCounters.xyz; + vertexOutputs.grlCounters = input.grl_nextAndCounters.w; + + let grlWidth: f32 = grlBaseWidth * input.grl_widths; + + let worldDir: vec3f = normalize(grlNext - grlPrevious); + let nearPosition: vec3f = positionUpdated + (worldDir * 0.001); + let grlMatrix: mat4x4f = uniforms.viewProjection * finalWorld; + let grlFinalPosition: vec4f = grlMatrix * vec4f(positionUpdated, 1.0); + let screenNearPos: vec4f = grlMatrix * vec4(nearPosition, 1.0); + let grlLinePosition: vec2f = grlFix(grlFinalPosition, grlAspect); + let grlLineNearPosition: vec2f = grlFix(screenNearPos, grlAspect); + let grlDir: vec2f = normalize(grlLineNearPosition - grlLinePosition); + + var grlNormal: vec4f = vec4f(-grlDir.y, grlDir.x, 0.0, 1.0); + + let grlHalfWidth: f32 = 0.5 * grlWidth; + #if defined(GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM) + grlNormal.x *= -grlHalfWidth; + grlNormal.y *= -grlHalfWidth; + #else + grlNormal.x *= grlHalfWidth; + grlNormal.y *= grlHalfWidth; + #endif + + grlNormal *= uniforms.grl_projection; + + #if defined(GREASED_LINE_SIZE_ATTENUATION) + grlNormal.x *= grlFinalPosition.w; + grlNormal.y *= grlFinalPosition.w; + + let pr = vec4f(uniforms.grl_aspect_resolution_lineWidth.yz, 0.0, 1.0) * uniforms.grl_projection; + grlNormal.x /= pr.x; + grlNormal.y /= pr.y; + #endif + + vertexOutputs.position = vec4f(grlFinalPosition.xy + grlNormal.xy * grlSide, grlFinalPosition.z, grlFinalPosition.w); + vertexOutputs.vPositionW = vertexOutputs.position.xyz; + + #else + vertexOutputs.grlCounters = input.grl_counters; + #endif + `, + }; + cameraFacing && (obj["!vertexOutputs\\.position\\s=\\sscene\\.viewProjection\\s\\*\\sworldPos;"] = "//"); // not needed for camera facing GRL + return obj; + } + if (shaderType === "fragment") { + return { + CUSTOM_FRAGMENT_DEFINITIONS: ` + #ifdef PBR + #define grlFinalColor finalColor + #else + #define grlFinalColor color + #endif + + varying grlCounters: f32; + varying grlColorPointer: 32; + + var grl_colors: texture_2d; + var grl_colorsSampler: sampler; + `, + CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: ` + let grlColorMode: f32 = uniforms.grl_colorMode_visibility_colorsWidth_useColors.x; + let grlVisibility: f32 = uniforms.grl_colorMode_visibility_colorsWidth_useColors.y; + let grlColorsWidth: f32 = uniforms.grl_colorMode_visibility_colorsWidth_useColors.z; + let grlUseColors: f32 = uniforms.grl_colorMode_visibility_colorsWidth_useColors.w; + + let grlUseDash: f32 = uniforms.grl_dashOptions.x; + let grlDashArray: f32 = uniforms.grl_dashOptions.y; + let grlDashOffset: f32 = uniforms.grl_dashOptions.z; + let grlDashRatio: f32 = uniforms.grl_dashOptions.w; + + grlFinalColor.a *= step(fragmentInputs.grlCounters, grlVisibility); + if (grlFinalColor.a == 0.0) { + discard; + } + + if (grlUseDash == 1.0) { + let dashPosition = (fragmentInputs.grlCounters + grlDashOffset) % grlDashArray; + grlFinalColor.a *= ceil(dashPosition - (grlDashArray * grlDashRatio)); + + if (grlFinalColor.a == 0.0) { + discard; + } + } + + #ifdef GREASED_LINE_HAS_COLOR + if (grlColorMode == ${0 /* GreasedLineMeshColorMode.COLOR_MODE_SET */}.) { + grlFinalColor = vec4f(uniforms.grl_singleColor, grlFinalColor.a); + } else if (grlColorMode == ${1 /* GreasedLineMeshColorMode.COLOR_MODE_ADD */}.) { + grlFinalColor += vec4f(uniforms.grl_singleColor, grlFinalColor.a); + } else if (grlColorMode == ${2 /* GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY */}.) { + grlFinalColor *= vec4f(uniforms.grl_singleColor, grlFinalColor.a); + } + #else + if (grlUseColors == 1.) { + #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE + let grlColor: vec4f = textureSample(grl_colors, grl_colorsSampler, vec2f(fragmentInputs.grlCounters, 0.)); + #else + let lookup: vec2f = vec2(fract(fragmentInputs.grlColorPointer / uniforms.grl_textureSize.x), 1.0 - floor(fragmentInputs.grlColorPointer / uniforms.grl_textureSize.x) / max(uniforms.grl_textureSize.y - 1.0, 1.0)); + let grlColor: vec4f = textureSample(grl_colors, grl_colorsSampler, lookup); + #endif + if (grlColorMode == ${0 /* GreasedLineMeshColorMode.COLOR_MODE_SET */}.) { + grlFinalColor = grlColor; + } else if (grlColorMode == ${1 /* GreasedLineMeshColorMode.COLOR_MODE_ADD */}.) { + grlFinalColor += grlColor; + } else if (grlColorMode == ${2 /* GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY */}.) { + grlFinalColor *= grlColor; + } + } + #endif + + + `, + }; + } + return null; +} + +/** + * @internal + */ +class MaterialGreasedLineDefines extends MaterialDefines { + constructor() { + super(...arguments); + /** + * The material has a color option specified + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + this.GREASED_LINE_HAS_COLOR = false; + /** + * The material's size attenuation optiom + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + this.GREASED_LINE_SIZE_ATTENUATION = false; + /** + * The type of color distribution is set to line this value equals to true. + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = false; + /** + * True if scene is in right handed coordinate system. + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + this.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM = false; + /** + * True if the line is in camera facing mode + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + this.GREASED_LINE_CAMERA_FACING = true; + /** + * True if the line uses offsets + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + this.GREASED_LINE_USE_OFFSETS = false; + } +} +/** + * GreasedLinePluginMaterial for GreasedLineMesh/GreasedLineRibbonMesh. + * Use the GreasedLineBuilder.CreateGreasedLineMaterial function to create and instance of this class. + */ +class GreasedLinePluginMaterial extends MaterialPluginBase { + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language + * @param _shaderLanguage The shader language to use + * @returns true if the plugin is compatible with the shader language. Return always true since both GLSL and WGSL are supported + */ + isCompatible(_shaderLanguage) { + return true; + } + /** + * Creates a new instance of the GreasedLinePluginMaterial + * @param material Base material for the plugin + * @param scene The scene + * @param options Plugin options + */ + constructor(material, scene, options) { + options = options || { + color: GreasedLineMaterialDefaults.DEFAULT_COLOR, + }; + const defines = new MaterialGreasedLineDefines(); + defines.GREASED_LINE_HAS_COLOR = !!options.color && !options.useColors; + defines.GREASED_LINE_SIZE_ATTENUATION = options.sizeAttenuation ?? false; + defines.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = options.colorDistributionType === 1 /* GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_LINE */; + defines.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM = (scene ?? material.getScene()).useRightHandedSystem; + defines.GREASED_LINE_CAMERA_FACING = options.cameraFacing ?? true; + super(material, GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME, 200, defines, true, true); + /** + * You can provide a colorsTexture to use instead of one generated from the 'colors' option + */ + this.colorsTexture = null; + this._forceGLSL = false; + this._forceGLSL = options?.forceGLSL || GreasedLinePluginMaterial.ForceGLSL; + this._scene = scene ?? material.getScene(); + this._engine = this._scene.getEngine(); + this._cameraFacing = options.cameraFacing ?? true; + this.visibility = options.visibility ?? 1; + this.useDash = options.useDash ?? false; + this.dashRatio = options.dashRatio ?? 0.5; + this.dashOffset = options.dashOffset ?? 0; + this.width = options.width ? options.width : options.sizeAttenuation ? GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED : GreasedLineMaterialDefaults.DEFAULT_WIDTH; + this._sizeAttenuation = options.sizeAttenuation ?? false; + this.colorMode = options.colorMode ?? 0 /* GreasedLineMeshColorMode.COLOR_MODE_SET */; + this._color = options.color ?? null; + this.useColors = options.useColors ?? false; + this._colorsDistributionType = options.colorDistributionType ?? 0 /* GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_SEGMENT */; + this.colorsSampling = options.colorsSampling ?? RawTexture.NEAREST_NEAREST; + this._colors = options.colors ?? null; + this.dashCount = options.dashCount ?? 1; // calculate the _dashArray value, call the setter + this.resolution = options.resolution ?? new Vector2(this._engine.getRenderWidth(), this._engine.getRenderHeight()); // calculate aspect call the setter + if (options.colorsTexture) { + this.colorsTexture = options.colorsTexture; // colorsTexture from options takes precedence + } + else { + if (this._colors) { + this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${material.name}-colors-texture`, this._colors, this.colorsSampling, this._scene); + } + else { + this._color = this._color ?? GreasedLineMaterialDefaults.DEFAULT_COLOR; + GreasedLineTools.PrepareEmptyColorsTexture(this._scene); + } + } + this._engine.onDisposeObservable.add(() => { + GreasedLineTools.DisposeEmptyColorsTexture(); + }); + } + /** + * Get the shader attributes + * @param attributes array which will be filled with the attributes + */ + getAttributes(attributes) { + attributes.push("grl_offsets"); + attributes.push("grl_widths"); + attributes.push("grl_colorPointers"); + attributes.push("grl_counters"); + if (this._cameraFacing) { + attributes.push("grl_previousAndSide"); + attributes.push("grl_nextAndCounters"); + } + else { + attributes.push("grl_slopes"); + } + } + /** + * Get the shader samplers + * @param samplers + */ + getSamplers(samplers) { + samplers.push("grl_colors"); + } + /** + * Get the shader textures + * @param activeTextures array which will be filled with the textures + */ + getActiveTextures(activeTextures) { + if (this.colorsTexture) { + activeTextures.push(this.colorsTexture); + } + } + /** + * Get the shader uniforms + * @param shaderLanguage The shader language to use + * @returns uniforms + */ + getUniforms(shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + const ubo = [ + { name: "grl_singleColor", size: 3, type: "vec3" }, + { name: "grl_textureSize", size: 2, type: "vec2" }, + { name: "grl_dashOptions", size: 4, type: "vec4" }, + { name: "grl_colorMode_visibility_colorsWidth_useColors", size: 4, type: "vec4" }, + ]; + if (this._cameraFacing) { + ubo.push({ name: "grl_projection", size: 16, type: "mat4" }, { name: "grl_aspect_resolution_lineWidth", size: 4, type: "vec4" }); + } + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + ubo.push({ + name: "viewProjection", + size: 16, + type: "mat4", + }); + } + return { + ubo, + vertex: this._cameraFacing && this._isGLSL(shaderLanguage) + ? ` + uniform vec4 grl_aspect_resolution_lineWidth; + uniform mat4 grl_projection; + ` + : "", + fragment: this._isGLSL(shaderLanguage) + ? ` + uniform vec4 grl_dashOptions; + uniform vec2 grl_textureSize; + uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; + uniform vec3 grl_singleColor; + ` + : "", + }; + } + // only getter, it doesn't make sense to use this plugin on a mesh other than GreasedLineMesh + // and it doesn't make sense to disable it on the mesh + get isEnabled() { + return true; + } + /** + * Bind the uniform buffer + * @param uniformBuffer + */ + bindForSubMesh(uniformBuffer) { + if (this._cameraFacing) { + uniformBuffer.updateMatrix("grl_projection", this._scene.getProjectionMatrix()); + !this._isGLSL(this._material.shaderLanguage) && uniformBuffer.updateMatrix("viewProjection", this._scene.getTransformMatrix()); + const resolutionLineWidth = TmpVectors.Vector4[0]; + resolutionLineWidth.x = this._aspect; + resolutionLineWidth.y = this._resolution.x; + resolutionLineWidth.z = this._resolution.y; + resolutionLineWidth.w = this.width; + uniformBuffer.updateVector4("grl_aspect_resolution_lineWidth", resolutionLineWidth); + } + const dashOptions = TmpVectors.Vector4[0]; + dashOptions.x = GreasedLineTools.BooleanToNumber(this.useDash); + dashOptions.y = this._dashArray; + dashOptions.z = this.dashOffset; + dashOptions.w = this.dashRatio; + uniformBuffer.updateVector4("grl_dashOptions", dashOptions); + const colorModeVisibilityColorsWidthUseColors = TmpVectors.Vector4[1]; + colorModeVisibilityColorsWidthUseColors.x = this.colorMode; + colorModeVisibilityColorsWidthUseColors.y = this.visibility; + colorModeVisibilityColorsWidthUseColors.z = this.colorsTexture ? this.colorsTexture.getSize().width : 0; + colorModeVisibilityColorsWidthUseColors.w = GreasedLineTools.BooleanToNumber(this.useColors); + uniformBuffer.updateVector4("grl_colorMode_visibility_colorsWidth_useColors", colorModeVisibilityColorsWidthUseColors); + if (this._color) { + uniformBuffer.updateColor3("grl_singleColor", this._color); + } + const texture = this.colorsTexture ?? GreasedLineMaterialDefaults.EmptyColorsTexture; + uniformBuffer.setTexture("grl_colors", texture); + uniformBuffer.updateFloat2("grl_textureSize", texture?.getSize().width ?? 1, texture?.getSize().height ?? 1); + } + /** + * Prepare the defines + * @param defines + * @param _scene + * @param mesh + */ + prepareDefines(defines, _scene, mesh) { + defines.GREASED_LINE_HAS_COLOR = !!this.color && !this.useColors; + defines.GREASED_LINE_SIZE_ATTENUATION = this._sizeAttenuation; + defines.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = this._colorsDistributionType === 1 /* GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_LINE */; + defines.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM = _scene.useRightHandedSystem; + defines.GREASED_LINE_CAMERA_FACING = this._cameraFacing; + defines.GREASED_LINE_USE_OFFSETS = !!mesh.offsets; + } + /** + * Get the class name + * @returns class name + */ + getClassName() { + return GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME; + } + /** + * Get shader code + * @param shaderType vertex/fragment + * @param shaderLanguage GLSL or WGSL + * @returns shader code + */ + getCustomCode(shaderType, shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + if (this._isGLSL(shaderLanguage)) { + return GetCustomCode$1(shaderType, this._cameraFacing); + } + return GetCustomCode(shaderType, this._cameraFacing); + } + /** + * Disposes the plugin material. + */ + dispose() { + this.colorsTexture?.dispose(); + super.dispose(); + } + /** + * Returns the colors used to colorize the line + */ + get colors() { + return this._colors; + } + /** + * Sets the colors used to colorize the line + */ + set colors(value) { + this.setColors(value); + } + /** + * Creates or updates the colors texture + * @param colors color table RGBA + * @param lazy if lazy, the colors are not updated + * @param forceNewTexture force creation of a new texture + */ + setColors(colors, lazy = false, forceNewTexture = false) { + const origColorsCount = this._colors?.length ?? 0; + this._colors = colors; + if (colors === null || colors.length === 0) { + this.colorsTexture?.dispose(); + return; + } + if (lazy && !forceNewTexture) { + return; + } + if (this.colorsTexture && origColorsCount === colors.length && !forceNewTexture) { + const colorArray = GreasedLineTools.Color3toRGBAUint8(colors); + this.colorsTexture.update(colorArray); + } + else { + this.colorsTexture?.dispose(); + this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`, colors, this.colorsSampling, this._scene); + } + } + /** + * Updates the material. Use when material created in lazy mode. + */ + updateLazy() { + if (this._colors) { + this.setColors(this._colors, false, true); + } + } + /** + * Gets the number of dashes in the line + */ + get dashCount() { + return this._dashCount; + } + /** + * Sets the number of dashes in the line + * @param value dash + */ + set dashCount(value) { + this._dashCount = value; + this._dashArray = 1 / value; + } + /** + * If set to true the line will be rendered always with the same width regardless how far it is located from the camera. + * Not supported for non camera facing lines. + */ + get sizeAttenuation() { + return this._sizeAttenuation; + } + /** + * Turn on/off size attenuation of the width option and widths array. + * Not supported for non camera facing lines. + * @param value If set to true the line will be rendered always with the same width regardless how far it is located from the camera. + */ + set sizeAttenuation(value) { + this._sizeAttenuation = value; + this.markAllDefinesAsDirty(); + } + /** + * Gets the color of the line + */ + get color() { + return this._color; + } + /** + * Sets the color of the line + * @param value Color3 or null to clear the color. You need to clear the color if you use colors and useColors = true + */ + set color(value) { + this.setColor(value); + } + /** + * Sets the color of the line. If set the whole line will be mixed with this color according to the colorMode option. + * @param value color + * @param doNotMarkDirty if true, the material will not be marked as dirty + */ + setColor(value, doNotMarkDirty = false) { + if ((this._color === null && value !== null) || (this._color !== null && value === null)) { + this._color = value; + !doNotMarkDirty && this.markAllDefinesAsDirty(); + } + else { + this._color = value; + } + } + /** + * Gets the color distributiopn type + */ + get colorsDistributionType() { + return this._colorsDistributionType; + } + /** + * Sets the color distribution type + * @see GreasedLineMeshColorDistributionType + * @param value color distribution type + */ + set colorsDistributionType(value) { + this._colorsDistributionType = value; + this.markAllDefinesAsDirty(); + } + /** + * Gets the resolution + */ + get resolution() { + return this._resolution; + } + /** + * Sets the resolution + * @param value resolution of the screen for GreasedLine + */ + set resolution(value) { + this._aspect = value.x / value.y; + this._resolution = value; + } + /** + * Serializes this plugin material + * @returns serializationObjec + */ + serialize() { + const serializationObject = super.serialize(); + const greasedLineMaterialOptions = { + colorDistributionType: this._colorsDistributionType, + colorsSampling: this.colorsSampling, + colorMode: this.colorMode, + dashCount: this._dashCount, + dashOffset: this.dashOffset, + dashRatio: this.dashRatio, + resolution: this._resolution, + sizeAttenuation: this._sizeAttenuation, + useColors: this.useColors, + useDash: this.useDash, + visibility: this.visibility, + width: this.width, + }; + this._colors && (greasedLineMaterialOptions.colors = this._colors); + this._color && (greasedLineMaterialOptions.color = this._color); + serializationObject.greasedLineMaterialOptions = greasedLineMaterialOptions; + return serializationObject; + } + /** + * Parses a serialized objects + * @param source serialized object + * @param scene scene + * @param rootUrl root url for textures + */ + parse(source, scene, rootUrl) { + super.parse(source, scene, rootUrl); + const greasedLineMaterialOptions = source.greasedLineMaterialOptions; + this.colorsTexture?.dispose(); + greasedLineMaterialOptions.color && this.setColor(greasedLineMaterialOptions.color, true); + greasedLineMaterialOptions.colorDistributionType && (this.colorsDistributionType = greasedLineMaterialOptions.colorDistributionType); + greasedLineMaterialOptions.colors && (this.colors = greasedLineMaterialOptions.colors); + greasedLineMaterialOptions.colorsSampling && (this.colorsSampling = greasedLineMaterialOptions.colorsSampling); + greasedLineMaterialOptions.colorMode && (this.colorMode = greasedLineMaterialOptions.colorMode); + greasedLineMaterialOptions.useColors && (this.useColors = greasedLineMaterialOptions.useColors); + greasedLineMaterialOptions.visibility && (this.visibility = greasedLineMaterialOptions.visibility); + greasedLineMaterialOptions.useDash && (this.useDash = greasedLineMaterialOptions.useDash); + greasedLineMaterialOptions.dashCount && (this.dashCount = greasedLineMaterialOptions.dashCount); + greasedLineMaterialOptions.dashRatio && (this.dashRatio = greasedLineMaterialOptions.dashRatio); + greasedLineMaterialOptions.dashOffset && (this.dashOffset = greasedLineMaterialOptions.dashOffset); + greasedLineMaterialOptions.width && (this.width = greasedLineMaterialOptions.width); + greasedLineMaterialOptions.sizeAttenuation && (this.sizeAttenuation = greasedLineMaterialOptions.sizeAttenuation); + greasedLineMaterialOptions.resolution && (this.resolution = greasedLineMaterialOptions.resolution); + if (this.colors) { + this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`, this.colors, this.colorsSampling, scene); + } + else { + GreasedLineTools.PrepareEmptyColorsTexture(scene); + } + this.markAllDefinesAsDirty(); + } + /** + * Makes a duplicate of the current configuration into another one. + * @param plugin define the config where to copy the info + */ + copyTo(plugin) { + const dest = plugin; + dest.colorsTexture?.dispose(); + if (this._colors) { + dest.colorsTexture = GreasedLineTools.CreateColorsTexture(`${dest._material.name}-colors-texture`, this._colors, dest.colorsSampling, this._scene); + } + dest.setColor(this.color, true); + dest.colorsDistributionType = this.colorsDistributionType; + dest.colorsSampling = this.colorsSampling; + dest.colorMode = this.colorMode; + dest.useColors = this.useColors; + dest.visibility = this.visibility; + dest.useDash = this.useDash; + dest.dashCount = this.dashCount; + dest.dashRatio = this.dashRatio; + dest.dashOffset = this.dashOffset; + dest.width = this.width; + dest.sizeAttenuation = this.sizeAttenuation; + dest.resolution = this.resolution; + dest.markAllDefinesAsDirty(); + } + _isGLSL(shaderLanguage) { + return shaderLanguage === 0 /* ShaderLanguage.GLSL */ || this._forceGLSL; + } +} +/** + * Plugin name + */ +GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME = "GreasedLinePluginMaterial"; +/** + * Force all the greased lines to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +GreasedLinePluginMaterial.ForceGLSL = false; +RegisterClass(`BABYLON.${GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}`, GreasedLinePluginMaterial); + +const GreasedLineUseOffsetsSimpleMaterialDefine = "GREASED_LINE_USE_OFFSETS"; +/** + * GreasedLineSimpleMaterial + */ +class GreasedLineSimpleMaterial extends ShaderMaterial { + /** + * GreasedLineSimple material constructor + * @param name material name + * @param scene the scene + * @param options material options + */ + constructor(name, scene, options) { + const engine = scene.getEngine(); + const isWGSL = engine.isWebGPU && !(options.forceGLSL || GreasedLineSimpleMaterial.ForceGLSL); + const defines = [ + `COLOR_DISTRIBUTION_TYPE_LINE ${1 /* GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_LINE */}.`, + `COLOR_DISTRIBUTION_TYPE_SEGMENT ${0 /* GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_SEGMENT */}.`, + `COLOR_MODE_SET ${0 /* GreasedLineMeshColorMode.COLOR_MODE_SET */}.`, + `COLOR_MODE_ADD ${1 /* GreasedLineMeshColorMode.COLOR_MODE_ADD */}.`, + `COLOR_MODE_MULTIPLY ${2 /* GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY */}.`, + ]; + scene.useRightHandedSystem && defines.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"); + const attributes = ["position", "grl_widths", "grl_offsets", "grl_colorPointers"]; + if (options.cameraFacing) { + defines.push("GREASED_LINE_CAMERA_FACING"); + attributes.push("grl_previousAndSide", "grl_nextAndCounters"); + } + else { + attributes.push("grl_slopes"); + attributes.push("grl_counters"); + } + const uniforms = [ + "grlColorsWidth", + "grlUseColors", + "grlWidth", + "grlColor", + "grl_colorModeAndColorDistributionType", + "grlResolution", + "grlAspect", + "grlAizeAttenuation", + "grlDashArray", + "grlDashOffset", + "grlDashRatio", + "grlUseDash", + "grlVisibility", + "grlColors", + ]; + if (!isWGSL) { + uniforms.push("world", "viewProjection", "view", "projection"); + } + super(name, scene, { + vertex: "greasedLine", + fragment: "greasedLine", + }, { + uniformBuffers: isWGSL ? ["Scene", "Mesh"] : undefined, + attributes, + uniforms, + samplers: isWGSL ? [] : ["grlColors"], + defines, + extraInitializationsAsync: async () => { + if (isWGSL) { + await Promise.all([Promise.resolve().then(() => greasedLine_vertex), Promise.resolve().then(() => greasedLine_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => greasedLine_vertex$1), Promise.resolve().then(() => greasedLine_fragment$1)]); + } + }, + shaderLanguage: isWGSL ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, + }); + this._color = Color3.White(); + this._colorsDistributionType = 0 /* GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_SEGMENT */; + this._colorsTexture = null; + options = options || { + color: GreasedLineMaterialDefaults.DEFAULT_COLOR, + }; + this.visibility = options.visibility ?? 1; + this.useDash = options.useDash ?? false; + this.dashRatio = options.dashRatio ?? 0.5; + this.dashOffset = options.dashOffset ?? 0; + this.dashCount = options.dashCount ?? 1; // calculate the _dashArray value, call the setter + this.width = options.width + ? options.width + : options.sizeAttenuation && options.cameraFacing + ? GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED + : GreasedLineMaterialDefaults.DEFAULT_WIDTH; + this.sizeAttenuation = options.sizeAttenuation ?? false; + this.color = options.color ?? Color3.White(); + this.useColors = options.useColors ?? false; + this.colorsDistributionType = options.colorDistributionType ?? 0 /* GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_SEGMENT */; + this.colorsSampling = options.colorsSampling ?? RawTexture.NEAREST_NEAREST; + this.colorMode = options.colorMode ?? 0 /* GreasedLineMeshColorMode.COLOR_MODE_SET */; + this._colors = options.colors ?? null; + this._cameraFacing = options.cameraFacing ?? true; + this.resolution = options.resolution ?? new Vector2(engine.getRenderWidth(), engine.getRenderHeight()); // calculate aspect call the setter + if (options.colorsTexture) { + this.colorsTexture = options.colorsTexture; + } + else { + if (this._colors) { + this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`, this._colors, this.colorsSampling, scene); + } + else { + this._color = this._color ?? GreasedLineMaterialDefaults.DEFAULT_COLOR; + this.colorsTexture = GreasedLineTools.PrepareEmptyColorsTexture(scene); + } + } + if (isWGSL) { + const sampler = new TextureSampler(); + sampler.setParameters(); // use the default values + sampler.samplingMode = this.colorsSampling; + this.setTextureSampler("grlColorsSampler", sampler); + } + engine.onDisposeObservable.add(() => { + GreasedLineTools.DisposeEmptyColorsTexture(); + }); + } + /** + * Disposes the plugin material. + */ + dispose() { + this._colorsTexture?.dispose(); + super.dispose(); + } + _setColorModeAndColorDistributionType() { + this.setVector2("grl_colorModeAndColorDistributionType", new Vector2(this._colorMode, this._colorsDistributionType)); + } + /** + * Updates the material. Use when material created in lazy mode. + */ + updateLazy() { + if (this._colors) { + this.setColors(this._colors, false, true); + } + } + /** + * Returns the colors used to colorize the line + */ + get colors() { + return this._colors; + } + /** + * Sets the colors used to colorize the line + */ + set colors(value) { + this.setColors(value); + } + /** + * Creates or updates the colors texture + * @param colors color table RGBA + * @param lazy if lazy, the colors are not updated + * @param forceNewTexture force creation of a new texture + */ + setColors(colors, lazy = false, forceNewTexture = false) { + const origColorsCount = this._colors?.length ?? 0; + this._colors = colors; + if (colors === null || colors.length === 0) { + this._colorsTexture?.dispose(); + return; + } + if (lazy && !forceNewTexture) { + return; + } + if (this._colorsTexture && origColorsCount === colors.length && !forceNewTexture) { + const colorArray = GreasedLineTools.Color3toRGBAUint8(colors); + this._colorsTexture.update(colorArray); + } + else { + this._colorsTexture?.dispose(); + this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`, colors, this.colorsSampling, this.getScene()); + } + } + /** + * Gets the colors texture + */ + get colorsTexture() { + return this._colorsTexture ?? null; + } + /** + * Sets the colorsTexture + */ + set colorsTexture(value) { + this._colorsTexture = value; + this.setFloat("grlColorsWidth", this._colorsTexture.getSize().width); + this.setTexture("grlColors", this._colorsTexture); + } + /** + * Line base width. At each point the line width is calculated by widths[pointIndex] * width + */ + get width() { + return this._width; + } + /** + * Line base width. At each point the line width is calculated by widths[pointIndex] * width + */ + set width(value) { + this._width = value; + this.setFloat("grlWidth", value); + } + /** + * Whether to use the colors option to colorize the line + */ + get useColors() { + return this._useColors; + } + set useColors(value) { + this._useColors = value; + this.setFloat("grlUseColors", GreasedLineTools.BooleanToNumber(value)); + } + /** + * The type of sampling of the colors texture. The values are the same when using with textures. + */ + get colorsSampling() { + return this._colorsSampling; + } + /** + * The type of sampling of the colors texture. The values are the same when using with textures. + */ + set colorsSampling(value) { + this._colorsSampling = value; + } + /** + * Normalized value of how much of the line will be visible + * 0 - 0% of the line will be visible + * 1 - 100% of the line will be visible + */ + get visibility() { + return this._visibility; + } + set visibility(value) { + this._visibility = value; + this.setFloat("grlVisibility", value); + } + /** + * Turns on/off dash mode + */ + get useDash() { + return this._useDash; + } + /** + * Turns on/off dash mode + */ + set useDash(value) { + this._useDash = value; + this.setFloat("grlUseDash", GreasedLineTools.BooleanToNumber(value)); + } + /** + * Gets the dash offset + */ + get dashOffset() { + return this._dashOffset; + } + /** + * Sets the dash offset + */ + set dashOffset(value) { + this._dashOffset = value; + this.setFloat("grlDashOffset", value); + } + /** + * Length of the dash. 0 to 1. 0.5 means half empty, half drawn. + */ + get dashRatio() { + return this._dashRatio; + } + /** + * Length of the dash. 0 to 1. 0.5 means half empty, half drawn. + */ + set dashRatio(value) { + this._dashRatio = value; + this.setFloat("grlDashRatio", value); + } + /** + * Gets the number of dashes in the line + */ + get dashCount() { + return this._dashCount; + } + /** + * Sets the number of dashes in the line + * @param value dash + */ + set dashCount(value) { + this._dashCount = value; + this._dashArray = 1 / value; + this.setFloat("grlDashArray", this._dashArray); + } + /** + * False means 1 unit in width = 1 unit on scene, true means 1 unit in width is reduced on the screen to make better looking lines + */ + get sizeAttenuation() { + return this._sizeAttenuation; + } + /** + * Turn on/off attenuation of the width option and widths array. + * @param value false means 1 unit in width = 1 unit on scene, true means 1 unit in width is reduced on the screen to make better looking lines + */ + set sizeAttenuation(value) { + this._sizeAttenuation = value; + this.setFloat("grlSizeAttenuation", GreasedLineTools.BooleanToNumber(value)); + } + /** + * Gets the color of the line + */ + get color() { + return this._color; + } + /** + * Sets the color of the line + * @param value Color3 + */ + set color(value) { + this.setColor(value); + } + /** + * Sets the color of the line. If set the whole line will be mixed with this color according to the colorMode option. + * The simple material always needs a color to be set. If you set it to null it will set the color to the default color (GreasedLineSimpleMaterial.DEFAULT_COLOR). + * @param value color + */ + setColor(value) { + value = value ?? GreasedLineMaterialDefaults.DEFAULT_COLOR; + this._color = value; + this.setColor3("grlColor", value); + } + /** + * Gets the color distributiopn type + */ + get colorsDistributionType() { + return this._colorsDistributionType; + } + /** + * Sets the color distribution type + * @see GreasedLineMeshColorDistributionType + * @param value color distribution type + */ + set colorsDistributionType(value) { + this._colorsDistributionType = value; + this._setColorModeAndColorDistributionType(); + } + /** + * Gets the mixing mode of the color and colors paramaters. Default value is GreasedLineMeshColorMode.SET. + * MATERIAL_TYPE_SIMPLE mixes the color and colors of the greased line material. + * @see GreasedLineMeshColorMode + */ + get colorMode() { + return this._colorMode; + } + /** + * Sets the mixing mode of the color and colors paramaters. Default value is GreasedLineMeshColorMode.SET. + * MATERIAL_TYPE_SIMPLE mixes the color and colors of the greased line material. + * @see GreasedLineMeshColorMode + */ + set colorMode(value) { + this._colorMode = value; + this._setColorModeAndColorDistributionType(); + } + /** + * Gets the resolution + */ + get resolution() { + return this._resolution; + } + /** + * Sets the resolution + * @param value resolution of the screen for GreasedLine + */ + set resolution(value) { + this._resolution = value; + this.setVector2("grlResolution", value); + this.setFloat("grlAspect", value.x / value.y); + } + /** + * Serializes this plugin material + * @returns serializationObjec + */ + serialize() { + const serializationObject = super.serialize(); + const greasedLineMaterialOptions = { + colorDistributionType: this._colorsDistributionType, + colorsSampling: this._colorsSampling, + colorMode: this._colorMode, + color: this._color, + dashCount: this._dashCount, + dashOffset: this._dashOffset, + dashRatio: this._dashRatio, + resolution: this._resolution, + sizeAttenuation: this._sizeAttenuation, + useColors: this._useColors, + useDash: this._useDash, + visibility: this._visibility, + width: this._width, + cameraFacing: this._cameraFacing, + }; + this._colors && (greasedLineMaterialOptions.colors = this._colors); + serializationObject.greasedLineMaterialOptions = greasedLineMaterialOptions; + return serializationObject; + } + /** + * Parses a serialized objects + * @param source serialized object + * @param scene scene + * @param _rootUrl root url for textures + */ + parse(source, scene, _rootUrl) { + const greasedLineMaterialOptions = source.greasedLineMaterialOptions; + this._colorsTexture?.dispose(); + greasedLineMaterialOptions.color && (this.color = greasedLineMaterialOptions.color); + greasedLineMaterialOptions.colorDistributionType && (this.colorsDistributionType = greasedLineMaterialOptions.colorDistributionType); + greasedLineMaterialOptions.colorsSampling && (this.colorsSampling = greasedLineMaterialOptions.colorsSampling); + greasedLineMaterialOptions.colorMode && (this.colorMode = greasedLineMaterialOptions.colorMode); + greasedLineMaterialOptions.useColors && (this.useColors = greasedLineMaterialOptions.useColors); + greasedLineMaterialOptions.visibility && (this.visibility = greasedLineMaterialOptions.visibility); + greasedLineMaterialOptions.useDash && (this.useDash = greasedLineMaterialOptions.useDash); + greasedLineMaterialOptions.dashCount && (this.dashCount = greasedLineMaterialOptions.dashCount); + greasedLineMaterialOptions.dashRatio && (this.dashRatio = greasedLineMaterialOptions.dashRatio); + greasedLineMaterialOptions.dashOffset && (this.dashOffset = greasedLineMaterialOptions.dashOffset); + greasedLineMaterialOptions.width && (this.width = greasedLineMaterialOptions.width); + greasedLineMaterialOptions.sizeAttenuation && (this.sizeAttenuation = greasedLineMaterialOptions.sizeAttenuation); + greasedLineMaterialOptions.resolution && (this.resolution = greasedLineMaterialOptions.resolution); + if (greasedLineMaterialOptions.colors) { + this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`, greasedLineMaterialOptions.colors, this.colorsSampling, this.getScene()); + } + else { + this.colorsTexture = GreasedLineTools.PrepareEmptyColorsTexture(scene); + } + this._cameraFacing = greasedLineMaterialOptions.cameraFacing ?? true; + this.setDefine("GREASED_LINE_CAMERA_FACING", this._cameraFacing); + } +} +/** + * Force to use GLSL in WebGPU + */ +GreasedLineSimpleMaterial.ForceGLSL = false; + +/** + * Material types for GreasedLine + * {@link https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/greased_line#materialtype} + */ +var GreasedLineMeshMaterialType; +(function (GreasedLineMeshMaterialType) { + /** + * StandardMaterial + */ + GreasedLineMeshMaterialType[GreasedLineMeshMaterialType["MATERIAL_TYPE_STANDARD"] = 0] = "MATERIAL_TYPE_STANDARD"; + /** + * PBR Material + */ + GreasedLineMeshMaterialType[GreasedLineMeshMaterialType["MATERIAL_TYPE_PBR"] = 1] = "MATERIAL_TYPE_PBR"; + /** + * Simple and fast shader material without texture, light, fog, instances, ... support. + * Just raw colored lines. + * Dashing and visibility is supported. + */ + GreasedLineMeshMaterialType[GreasedLineMeshMaterialType["MATERIAL_TYPE_SIMPLE"] = 2] = "MATERIAL_TYPE_SIMPLE"; +})(GreasedLineMeshMaterialType || (GreasedLineMeshMaterialType = {})); +/** + * Color blending mode of the @see GreasedLineMaterial and the base material + * {@link https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/greased_line#colormode} + */ +var GreasedLineMeshColorMode; +(function (GreasedLineMeshColorMode) { + /** + * Color blending mode SET + */ + GreasedLineMeshColorMode[GreasedLineMeshColorMode["COLOR_MODE_SET"] = 0] = "COLOR_MODE_SET"; + /** + * Color blending mode ADD + */ + GreasedLineMeshColorMode[GreasedLineMeshColorMode["COLOR_MODE_ADD"] = 1] = "COLOR_MODE_ADD"; + /** + * Color blending mode ADD + */ + GreasedLineMeshColorMode[GreasedLineMeshColorMode["COLOR_MODE_MULTIPLY"] = 2] = "COLOR_MODE_MULTIPLY"; +})(GreasedLineMeshColorMode || (GreasedLineMeshColorMode = {})); +/** + * Color distribution type of the @see colors. + * {@link https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/greased_line#colordistributiontype} + * + */ +var GreasedLineMeshColorDistributionType; +(function (GreasedLineMeshColorDistributionType) { + /** + * Colors distributed between segments of the line + */ + GreasedLineMeshColorDistributionType[GreasedLineMeshColorDistributionType["COLOR_DISTRIBUTION_TYPE_SEGMENT"] = 0] = "COLOR_DISTRIBUTION_TYPE_SEGMENT"; + /** + * Colors distributed along the line ingoring the segments + */ + GreasedLineMeshColorDistributionType[GreasedLineMeshColorDistributionType["COLOR_DISTRIBUTION_TYPE_LINE"] = 1] = "COLOR_DISTRIBUTION_TYPE_LINE"; +})(GreasedLineMeshColorDistributionType || (GreasedLineMeshColorDistributionType = {})); + +const vertexDefinitions = `#if defined(DBG_ENABLED) +attribute float dbg_initialPass; +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; +#endif`; +const vertexDefinitionsWebGPU = `#if defined(DBG_ENABLED) +attribute dbg_initialPass: f32; +varying dbg_vBarycentric: vec3f; +varying dbg_vVertexWorldPos: vec3f; +varying dbg_vPass: f32; +#endif`; +const vertexMainEnd = `#if defined(DBG_ENABLED) +float dbg_vertexIndex = mod(float(gl_VertexID), 3.); +if (dbg_vertexIndex == 0.0) { + dbg_vBarycentric = vec3(1.,0.,0.); +} +else if (dbg_vertexIndex == 1.0) { + dbg_vBarycentric = vec3(0.,1.,0.); +} +else { + dbg_vBarycentric = vec3(0.,0.,1.); +} + +dbg_vVertexWorldPos = vPositionW; +dbg_vPass = dbg_initialPass; +#endif`; +const vertexMainEndWebGPU = `#if defined(DBG_ENABLED) +var dbg_vertexIndex = f32(input.vertexIndex) % 3.; +if (dbg_vertexIndex == 0.0) { + vertexOutputs.dbg_vBarycentric = vec3f(1.,0.,0.); +} +else if (dbg_vertexIndex == 1.0) { + vertexOutputs.dbg_vBarycentric = vec3f(0.,1.,0.); +} +else { + vertexOutputs.dbg_vBarycentric = vec3f(0.,0.,1.); +} + +vertexOutputs.dbg_vVertexWorldPos = vertexOutputs.vPositionW; +vertexOutputs.dbg_vPass = input.dbg_initialPass; +#endif`; +const fragmentUniforms = `#if defined(DBG_ENABLED) +uniform vec3 dbg_shadedDiffuseColor; +uniform vec4 dbg_shadedSpecularColorPower; +uniform vec3 dbg_thicknessRadiusScale; + +#if DBG_MODE == 2 || DBG_MODE == 3 + uniform vec3 dbg_vertexColor; +#endif + +#if DBG_MODE == 1 + uniform vec3 dbg_wireframeTrianglesColor; +#elif DBG_MODE == 3 + uniform vec3 dbg_wireframeVerticesColor; +#elif DBG_MODE == 4 || DBG_MODE == 5 + uniform vec3 dbg_uvPrimaryColor; + uniform vec3 dbg_uvSecondaryColor; +#elif DBG_MODE == 7 + uniform vec3 dbg_materialColor; +#endif +#endif`; +const fragmentUniformsWebGPU = `#if defined(DBG_ENABLED) +uniform dbg_shadedDiffuseColor: vec3f; +uniform dbg_shadedSpecularColorPower: vec4f; +uniform dbg_thicknessRadiusScale: vec3f; + +#if DBG_MODE == 2 || DBG_MODE == 3 + uniform dbg_vertexColor: vec3f; +#endif + +#if DBG_MODE == 1 + uniform dbg_wireframeTrianglesColor: vec3f; +#elif DBG_MODE == 3 + uniform dbg_wireframeVerticesColor: vec3f; +#elif DBG_MODE == 4 || DBG_MODE == 5 + uniform dbg_uvPrimaryColor: vec3f; + uniform dbg_uvSecondaryColor: vec3f; +#elif DBG_MODE == 7 + uniform dbg_materialColor: vec3f; +#endif +#endif`; +const fragmentDefinitions = `#if defined(DBG_ENABLED) +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; + +#if !defined(DBG_MULTIPLY) + vec3 dbg_applyShading(vec3 color) { + vec3 N = vNormalW.xyz; + vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); + vec3 H = normalize(L + L); + float LdotN = clamp(dot(L,N), 0., 1.); + float HdotN = clamp(dot(H,N), 0., 1.); + float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); + color *= (LdotN / PI); + color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); + return color; + } +#endif + +#if DBG_MODE == 1 || DBG_MODE == 3 + float dbg_edgeFactor() { + vec3 d = fwidth(dbg_vBarycentric); + vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); + return min(min(a3.x, a3.y), a3.z); + } +#endif + +#if DBG_MODE == 2 || DBG_MODE == 3 + float dbg_cornerFactor() { + vec3 worldPos = vPositionW; + float dist = length(worldPos - dbg_vVertexWorldPos); + float camDist = length(worldPos - vEyePosition.xyz); + float d = sqrt(camDist) * .001; + return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); + } +#endif + +#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) + float dbg_checkerboardFactor(vec2 uv) { + vec2 f = fract(uv * dbg_thicknessRadiusScale.z); + f -= .5; + return (f.x * f.y) > 0. ? 1. : 0.; + } +#endif +#endif`; +const fragmentDefinitionsWebGPU = `#if defined(DBG_ENABLED) +varying dbg_vBarycentric: vec3f; +varying dbg_vVertexWorldPos: vec3f; +varying dbg_vPass: f32; + +#if !defined(DBG_MULTIPLY) + fn dbg_applyShading(color: vec3f) -> vec3f { + var N = fragmentInputs.vNormalW.xyz; + var L = normalize(scene.vEyePosition.xyz - fragmentInputs.vPositionW.xyz); + var H = normalize(L + L); + var LdotN = clamp(dot(L,N), 0., 1.); + var HdotN = clamp(dot(H,N), 0., 1.); + var specTerm = pow(HdotN, uniforms.dbg_shadedSpecularColorPower.w); + var result = color * (LdotN / PI); + result += uniforms.dbg_shadedSpecularColorPower.rgb * (specTerm / PI); + return result; + } +#endif + +#if DBG_MODE == 1 || DBG_MODE == 3 + fn dbg_edgeFactor() -> f32 { + var d = fwidth(fragmentInputs.dbg_vBarycentric); + var a3 = smoothstep(vec3f(0.), d * uniforms.dbg_thicknessRadiusScale.x, fragmentInputs.dbg_vBarycentric); + return min(min(a3.x, a3.y), a3.z); + } +#endif + +#if DBG_MODE == 2 || DBG_MODE == 3 + fn dbg_cornerFactor() -> f32 { + var worldPos = fragmentInputs.vPositionW; + float dist = length(worldPos - fragmentInputs.dbg_vVertexWorldPos); + float camDist = length(worldPos - scene.vEyePosition.xyz); + float d = sqrt(camDist) * .001; + return smoothstep((uniforms.dbg_thicknessRadiusScale.y * d), ((uniforms.dbg_thicknessRadiusScale.y * 1.01) * d), dist); + } +#endif + +#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) + fn dbg_checkerboardFactor(uv: vec2f) -> f32 { + var f = fract(uv * uniforms.dbg_thicknessRadiusScale.z); + f -= .5; + return (f.x * f.y) > 0. ? 1. : 0.; + } +#endif +#endif`; +const fragmentMainEnd = `#if defined(DBG_ENABLED) +vec3 dbg_color = vec3(1.); +#if DBG_MODE == 1 + dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); +#elif DBG_MODE == 2 || DBG_MODE == 3 + float dbg_cornerFactor = dbg_cornerFactor(); + if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; + dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); + #if DBG_MODE == 3 + dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); + #endif +#elif DBG_MODE == 4 && defined(MAINUV1) + dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); +#elif DBG_MODE == 5 && defined(MAINUV2) + dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); +#elif DBG_MODE == 6 && defined(VERTEXCOLOR) + dbg_color = vColor.rgb; +#elif DBG_MODE == 7 + dbg_color = dbg_materialColor; +#endif + +#if defined(DBG_MULTIPLY) + gl_FragColor *= vec4(dbg_color, 1.); +#else + #if DBG_MODE != 6 + gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); + #else + gl_FragColor = vec4(dbg_color, 1.); + #endif +#endif +#endif`; +const fragmentMainEndWebGPU = `#if defined(DBG_ENABLED) +var dbg_color = vec3f(1.); +#if DBG_MODE == 1 + dbg_color = mix(uniforms.dbg_wireframeTrianglesColor, vec3f(1.), dbg_edgeFactor()); +#elif DBG_MODE == 2 || DBG_MODE == 3 + var dbg_cornerFactor = dbg_cornerFactor(); + if (fragmentInputs.dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; + dbg_color = mix(uniforms.dbg_vertexColor, vec3(1.), dbg_cornerFactor); + #if DBG_MODE == 3 + dbg_color *= mix(uniforms.dbg_wireframeVerticesColor, vec3f(1.), dbg_edgeFactor()); + #endif +#elif DBG_MODE == 4 && defined(MAINUV1) + dbg_color = mix(uniforms.dbg_uvPrimaryColor, uniforms.dbg_uvSecondaryColor, dbg_checkerboardFactor(fragmentInputs.vMainUV1)); +#elif DBG_MODE == 5 && defined(MAINUV2) + dbg_color = mix(uniforms.dbg_uvPrimaryColor, uniforms.dbg_uvSecondaryColor, dbg_checkerboardFactor(fragmentInputs.vMainUV2)); +#elif DBG_MODE == 6 && defined(VERTEXCOLOR) + dbg_color = fragmentInputs.vColor.rgb; +#elif DBG_MODE == 7 + dbg_color = uniforms.dbg_materialColor; +#endif + +#if defined(DBG_MULTIPLY) + fragmentOutputs.color *= vec4f(dbg_color, 1.); +#else + #if DBG_MODE != 6 + fragmentOutputs.color = vec4f(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); + #else + fragmentOutputs.color = vec4f(dbg_color, 1.); + #endif +#endif +#endif`; +const defaultMaterialColors = [ + new Color3(0.98, 0.26, 0.38), + new Color3(0.47, 0.75, 0.3), + new Color3(0, 0.26, 0.77), + new Color3(0.97, 0.6, 0.76), + new Color3(0.19, 0.63, 0.78), + new Color3(0.98, 0.8, 0.6), + new Color3(0.65, 0.43, 0.15), + new Color3(0.15, 0.47, 0.22), + new Color3(0.67, 0.71, 0.86), + new Color3(0.09, 0.46, 0.56), + new Color3(0.8, 0.98, 0.02), + new Color3(0.39, 0.29, 0.13), + new Color3(0.53, 0.63, 0.06), + new Color3(0.95, 0.96, 0.41), + new Color3(1, 0.72, 0.94), + new Color3(0.63, 0.08, 0.31), + new Color3(0.66, 0.96, 0.95), + new Color3(0.22, 0.14, 0.19), + new Color3(0.14, 0.65, 0.59), + new Color3(0.93, 1, 0.68), + new Color3(0.93, 0.14, 0.44), + new Color3(0.47, 0.86, 0.67), + new Color3(0.85, 0.07, 0.78), + new Color3(0.53, 0.64, 0.98), + new Color3(0.43, 0.37, 0.56), + new Color3(0.71, 0.65, 0.25), + new Color3(0.66, 0.19, 0.01), + new Color3(0.94, 0.53, 0.12), + new Color3(0.41, 0.44, 0.44), + new Color3(0.24, 0.71, 0.96), + new Color3(0.57, 0.28, 0.56), + new Color3(0.44, 0.98, 0.42), +]; +/** + * Supported visualizations of MeshDebugPluginMaterial + */ +var MeshDebugMode; +(function (MeshDebugMode) { + /** + * Material without any mesh debug visualization + */ + MeshDebugMode[MeshDebugMode["NONE"] = 0] = "NONE"; + /** + * A wireframe of the mesh + * NOTE: For this mode to work correctly, convertToUnIndexedMesh() or MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() must first be called on mesh. + */ + MeshDebugMode[MeshDebugMode["TRIANGLES"] = 1] = "TRIANGLES"; + /** + * Points drawn over vertices of mesh + * NOTE: For this mode to work correctly, MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() must first be called on mesh. + */ + MeshDebugMode[MeshDebugMode["VERTICES"] = 2] = "VERTICES"; + /** + * A wireframe of the mesh, with points drawn over vertices + * NOTE: For this mode to work correctly, MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() must first be called on mesh. + */ + MeshDebugMode[MeshDebugMode["TRIANGLES_VERTICES"] = 3] = "TRIANGLES_VERTICES"; + /** + * A checkerboard grid of the mesh's UV set 0 + */ + MeshDebugMode[MeshDebugMode["UV0"] = 4] = "UV0"; + /** + * A checkerboard grid of the mesh's UV set 1 + */ + MeshDebugMode[MeshDebugMode["UV1"] = 5] = "UV1"; + /** + * The mesh's vertex colors displayed as the primary texture + */ + MeshDebugMode[MeshDebugMode["VERTEXCOLORS"] = 6] = "VERTEXCOLORS"; + /** + * An arbitrary, distinguishable color to identify the material + */ + MeshDebugMode[MeshDebugMode["MATERIALIDS"] = 7] = "MATERIALIDS"; +})(MeshDebugMode || (MeshDebugMode = {})); +/** @internal */ +class MeshDebugDefines extends MaterialDefines { + constructor() { + super(...arguments); + /** + * Current mesh debug visualization. + * Defaults to NONE. + */ + this.DBG_MODE = 0 /* MeshDebugMode.NONE */; + /** + * Whether the mesh debug visualization multiplies with colors underneath. + * Defaults to true. + */ + this.DBG_MULTIPLY = true; + /** + * Whether the mesh debug plugin is enabled in the material. + * Defaults to true. + */ + this.DBG_ENABLED = true; + } +} +/** + * Plugin that implements various mesh debug visualizations, + * List of available visualizations can be found in MeshDebugMode enum. + */ +class MeshDebugPluginMaterial extends MaterialPluginBase { + /** @internal */ + _markAllDefinesAsDirty() { + this._enable(this._isEnabled); + this.markAllDefinesAsDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @param shaderLanguage The shader language to use. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible(shaderLanguage) { + switch (shaderLanguage) { + case 0 /* ShaderLanguage.GLSL */: + case 1 /* ShaderLanguage.WGSL */: + return true; + default: + return false; + } + } + /** + * Creates a new MeshDebugPluginMaterial + * @param material Material to attach the mesh debug plugin to + * @param options Options for the mesh debug plugin + */ + constructor(material, options = {}) { + const defines = new MeshDebugDefines(); + defines.DBG_MODE = options.mode ?? defines.DBG_MODE; + defines.DBG_MULTIPLY = options.multiply ?? defines.DBG_MULTIPLY; + super(material, "MeshDebug", 200, defines, true, true); + this._mode = defines.DBG_MODE; + this._multiply = defines.DBG_MULTIPLY; + this.shadedDiffuseColor = options.shadedDiffuseColor ?? new Color3(1, 1, 1); + this.shadedSpecularColor = options.shadedSpecularColor ?? new Color3(0.8, 0.8, 0.8); + this.shadedSpecularPower = options.shadedSpecularPower ?? 10; + this.wireframeThickness = options.wireframeThickness ?? 0.7; + this.wireframeTrianglesColor = options.wireframeTrianglesColor ?? new Color3(0, 0, 0); + this.wireframeVerticesColor = options.wireframeVerticesColor ?? new Color3(0.8, 0.8, 0.8); + this.vertexColor = options.vertexColor ?? new Color3(0, 0, 0); + this.vertexRadius = options.vertexRadius ?? 1.2; + this.uvScale = options.uvScale ?? 20; + this.uvPrimaryColor = options.uvPrimaryColor ?? new Color3(1, 1, 1); + this.uvSecondaryColor = options.uvSecondaryColor ?? new Color3(0.5, 0.5, 0.5); + this._materialColor = MeshDebugPluginMaterial.MaterialColors[MeshDebugPluginMaterial._PluginCount++ % MeshDebugPluginMaterial.MaterialColors.length]; + this.isEnabled = true; + } + /** + * Get the class name + * @returns Class name + */ + getClassName() { + return "MeshDebugPluginMaterial"; + } + /** + * Gets whether the mesh debug plugin is enabled in the material. + */ + get isEnabled() { + return this._isEnabled; + } + /** + * Sets whether the mesh debug plugin is enabled in the material. + * @param value enabled + */ + set isEnabled(value) { + if (this._isEnabled === value) { + return; + } + if (!this._material.getScene().getEngine().isWebGPU && this._material.getScene().getEngine().version == 1) { + Logger.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."); + this._isEnabled = false; + return; + } + this._isEnabled = value; + this._markAllDefinesAsDirty(); + } + /** + * Prepare the defines + * @param defines Mesh debug defines + * @param scene Scene + * @param mesh Mesh associated with material + */ + prepareDefines(defines, scene, mesh) { + if ((this._mode == 2 /* MeshDebugMode.VERTICES */ || this._mode == 1 /* MeshDebugMode.TRIANGLES */ || this._mode == 3 /* MeshDebugMode.TRIANGLES_VERTICES */) && + !mesh.isVerticesDataPresent("dbg_initialPass")) { + Logger.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.", 1); + } + defines.DBG_MODE = this._mode; + defines.DBG_MULTIPLY = this._multiply; + defines.DBG_ENABLED = this._isEnabled; + } + /** + * Get the shader attributes + * @param attributes Array of attributes + */ + getAttributes(attributes) { + attributes.push("dbg_initialPass"); + } + /** + * Get the shader uniforms + * @param shaderLanguage The shader language to use. + * @returns Uniforms + */ + getUniforms(shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + return { + ubo: [ + { name: "dbg_shadedDiffuseColor", size: 3, type: "vec3" }, + { name: "dbg_shadedSpecularColorPower", size: 4, type: "vec4" }, // shadedSpecularColor, shadedSpecularPower + { name: "dbg_thicknessRadiusScale", size: 3, type: "vec3" }, // wireframeThickness, vertexRadius, uvScale + { name: "dbg_wireframeTrianglesColor", size: 3, type: "vec3" }, + { name: "dbg_wireframeVerticesColor", size: 3, type: "vec3" }, + { name: "dbg_vertexColor", size: 3, type: "vec3" }, + { name: "dbg_uvPrimaryColor", size: 3, type: "vec3" }, + { name: "dbg_uvSecondaryColor", size: 3, type: "vec3" }, + { name: "dbg_materialColor", size: 3, type: "vec3" }, + ], + fragment: shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? fragmentUniforms : fragmentUniformsWebGPU, + }; + } + /** + * Bind the uniform buffer + * @param uniformBuffer Uniform buffer + */ + bindForSubMesh(uniformBuffer) { + if (!this._isEnabled) { + return; + } + uniformBuffer.updateFloat3("dbg_shadedDiffuseColor", this.shadedDiffuseColor.r, this.shadedDiffuseColor.g, this.shadedDiffuseColor.b); + uniformBuffer.updateFloat4("dbg_shadedSpecularColorPower", this.shadedSpecularColor.r, this.shadedSpecularColor.g, this.shadedSpecularColor.b, this.shadedSpecularPower); + uniformBuffer.updateFloat3("dbg_thicknessRadiusScale", this.wireframeThickness, this.vertexRadius, this.uvScale); + uniformBuffer.updateColor3("dbg_wireframeTrianglesColor", this.wireframeTrianglesColor); + uniformBuffer.updateColor3("dbg_wireframeVerticesColor", this.wireframeVerticesColor); + uniformBuffer.updateColor3("dbg_vertexColor", this.vertexColor); + uniformBuffer.updateColor3("dbg_uvPrimaryColor", this.uvPrimaryColor); + uniformBuffer.updateColor3("dbg_uvSecondaryColor", this.uvSecondaryColor); + uniformBuffer.updateColor3("dbg_materialColor", this._materialColor); + } + /** + * Get shader code + * @param shaderType "vertex" or "fragment" + * @param shaderLanguage The shader language to use. + * @returns Shader code + */ + getCustomCode(shaderType, shaderLanguage = 0 /* ShaderLanguage.GLSL */) { + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return shaderType === "vertex" + ? { + CUSTOM_VERTEX_DEFINITIONS: vertexDefinitionsWebGPU, + CUSTOM_VERTEX_MAIN_END: vertexMainEndWebGPU, + } + : { + CUSTOM_FRAGMENT_DEFINITIONS: fragmentDefinitionsWebGPU, + CUSTOM_FRAGMENT_MAIN_END: fragmentMainEndWebGPU, + }; + } + return shaderType === "vertex" + ? { + CUSTOM_VERTEX_DEFINITIONS: vertexDefinitions, + CUSTOM_VERTEX_MAIN_END: vertexMainEnd, + } + : { + CUSTOM_FRAGMENT_DEFINITIONS: fragmentDefinitions, + CUSTOM_FRAGMENT_MAIN_END: fragmentMainEnd, + }; + } + /** + * Resets static variables of the plugin to their original state + */ + static Reset() { + this._PluginCount = 0; + this.MaterialColors = defaultMaterialColors; + } + /** + * Renders triangles in a mesh 3 times by tripling the indices in the index buffer. + * Used to prepare a mesh to be rendered in `TRIANGLES`, `VERTICES`, or `TRIANGLES_VERTICES` modes. + * NOTE: This is a destructive operation. The mesh's index buffer and vertex buffers are modified, and a new vertex buffer is allocated. + * If you'd like the ability to revert these changes, toggle the optional `returnRollback` flag. + * @param mesh the mesh to target + * @param returnRollback whether or not to return a function that reverts mesh to its initial state. Default: false. + * @returns a rollback function if `returnRollback` is true, otherwise an empty function. + */ + static PrepareMeshForTrianglesAndVerticesMode(mesh, returnRollback = false) { + let rollback = () => { }; + if (mesh.getTotalIndices() == 0) + return rollback; + if (returnRollback) { + const kinds = mesh.getVerticesDataKinds(); + const indices = mesh.getIndices(); + const data = {}; + for (const kind of kinds) { + data[kind] = mesh.getVerticesData(kind); + } + rollback = function () { + mesh.setIndices(indices); + for (const kind of kinds) { + const stride = mesh.getVertexBuffer(kind).getStrideSize(); + mesh.setVerticesData(kind, data[kind], undefined, stride); + } + mesh.removeVerticesData("dbg_initialPass"); + }; + } + let indices = Array.from(mesh.getIndices()); + const newIndices1 = []; + for (let i = 0; i < indices.length; i += 3) { + newIndices1.push(indices[i + 1], indices[i + 2], indices[i + 0]); + } + mesh.setIndices(indices.concat(newIndices1)); + mesh.convertToUnIndexedMesh(); + mesh.isUnIndexed = false; + indices = Array.from(mesh.getIndices()); + const newIndices2 = []; + for (let i = indices.length / 2; i < indices.length; i += 3) { + newIndices2.push(indices[i + 1], indices[i + 2], indices[i + 0]); + } + mesh.setIndices(indices.concat(newIndices2)); + const num = mesh.getTotalVertices(); + const mid = num / 2; + const pass = new Array(num).fill(1, 0, mid).fill(0, mid, num); + mesh.setVerticesData("dbg_initialPass", pass, false, 1); + return rollback; + } +} +/** + * Total number of instances of the plugin. + * Starts at 0. + */ +MeshDebugPluginMaterial._PluginCount = 0; +/** + * Color palette used for MATERIALIDS mode. + * Defaults to `defaultMaterialColors` + */ +MeshDebugPluginMaterial.MaterialColors = defaultMaterialColors; +__decorate([ + serializeAsColor3() +], MeshDebugPluginMaterial.prototype, "_materialColor", void 0); +__decorate([ + serialize() +], MeshDebugPluginMaterial.prototype, "_isEnabled", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllDefinesAsDirty") +], MeshDebugPluginMaterial.prototype, "mode", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllDefinesAsDirty") +], MeshDebugPluginMaterial.prototype, "multiply", void 0); +__decorate([ + serializeAsColor3() +], MeshDebugPluginMaterial.prototype, "shadedDiffuseColor", void 0); +__decorate([ + serializeAsColor3() +], MeshDebugPluginMaterial.prototype, "shadedSpecularColor", void 0); +__decorate([ + serialize() +], MeshDebugPluginMaterial.prototype, "shadedSpecularPower", void 0); +__decorate([ + serialize() +], MeshDebugPluginMaterial.prototype, "wireframeThickness", void 0); +__decorate([ + serializeAsColor3() +], MeshDebugPluginMaterial.prototype, "wireframeTrianglesColor", void 0); +__decorate([ + serializeAsColor3() +], MeshDebugPluginMaterial.prototype, "wireframeVerticesColor", void 0); +__decorate([ + serializeAsColor3() +], MeshDebugPluginMaterial.prototype, "vertexColor", void 0); +__decorate([ + serialize() +], MeshDebugPluginMaterial.prototype, "vertexRadius", void 0); +__decorate([ + serialize() +], MeshDebugPluginMaterial.prototype, "uvScale", void 0); +__decorate([ + serializeAsColor3() +], MeshDebugPluginMaterial.prototype, "uvPrimaryColor", void 0); +__decorate([ + serializeAsColor3() +], MeshDebugPluginMaterial.prototype, "uvSecondaryColor", void 0); +RegisterClass("BABYLON.MeshDebugPluginMaterial", MeshDebugPluginMaterial); + +Object.defineProperty(StandardMaterial.prototype, "decalMap", { + get: function () { + if (!this._decalMap) { + if (this._uniformBufferLayoutBuilt) { + // Material already used to display a mesh, so it's invalid to add the decal map plugin at that point + // Returns null instead of having new DecalMapConfiguration throws an exception + return null; + } + this._decalMap = new DecalMapConfiguration(this); + } + return this._decalMap; + }, + enumerable: true, + configurable: true, +}); + +Object.defineProperty(PBRBaseMaterial.prototype, "decalMap", { + get: function () { + if (!this._decalMap) { + if (this._uniformBufferLayoutBuilt) { + // Material already used to display a mesh, so it's invalid to add the decal map plugin at that point + // Returns null instead of having new DecalMapConfiguration throws an exception + return null; + } + this._decalMap = new DecalMapConfiguration(this); + } + return this._decalMap; + }, + enumerable: true, + configurable: true, +}); + +Object.defineProperty(AbstractMesh.prototype, "decalMap", { + get: function () { + return this._decalMap; + }, + set: function (decalMap) { + this._decalMap = decalMap; + }, + enumerable: true, + configurable: true, +}); + +// Do not edit. +const name$3O = "defaultFragmentDeclaration"; +const shader$3N = `uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 vSpecularColor;uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; +#ifdef DIFFUSE +uniform vec2 vDiffuseInfos; +#endif +#ifdef AMBIENT +uniform vec2 vAmbientInfos; +#endif +#ifdef OPACITY +uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#ifdef ALPHATEST +uniform float alphaCutOff; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) +uniform mat4 view; +#endif +#ifdef REFRACTION +uniform vec4 vRefractionInfos; +#ifndef REFRACTIONMAP_3D +uniform mat4 refractionMatrix; +#endif +#ifdef REFRACTIONFRESNEL +uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; +#endif +#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) +uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; +#endif +#endif +#if defined(SPECULAR) && defined(SPECULARTERM) +uniform vec2 vSpecularInfos; +#endif +#ifdef DIFFUSEFRESNEL +uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; +#endif +#ifdef OPACITYFRESNEL +uniform vec4 opacityParts; +#endif +#ifdef EMISSIVEFRESNEL +uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; +#endif +#if defined(REFLECTION) || (defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)) +uniform vec2 vReflectionInfos; +#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) +uniform mat4 reflectionMatrix; +#endif +#ifndef REFLECTIONMAP_SKYBOX +#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; +#endif +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos; +#endif +#include +#define ADDITIONAL_FRAGMENT_DECLARATION +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$3O]) { + ShaderStore.IncludesShadersStore[name$3O] = shader$3N; +} + +// Do not edit. +const name$3N = "defaultUboDeclaration"; +const shader$3M = `layout(std140,column_major) uniform;uniform Material +{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; +#define ADDITIONAL_UBO_DECLARATION +}; +#include +#include +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$3N]) { + ShaderStore.IncludesShadersStore[name$3N] = shader$3M; +} + +// Do not edit. +const name$3M = "defaultPixelShader"; +const shader$3L = `#define CUSTOM_FRAGMENT_EXTENSION +#include<__decl__defaultFragment> +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +#include[SCENE_MRT_COUNT] +#include +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include[1..7] +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef REFRACTION +#ifdef REFRACTIONMAP_3D +uniform samplerCube refractionCubeSampler; +#else +uniform sampler2D refraction2DSampler; +#endif +#endif +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) +#endif +#include +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +uniform samplerCube reflectionCubeSampler; +#else +uniform sampler2D reflection2DSampler; +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); +#endif +#include +#ifdef TWOSIDEDLIGHTING +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +#ifdef DIFFUSE +baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); +#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) +if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#include +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor.rgb*=vColor.rgb; +#endif +#ifdef DETAIL +baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); +#endif +#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE +vec3 baseAmbientColor=vec3(1.,1.,1.); +#ifdef AMBIENT +baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; +#endif +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; +#ifdef SPECULARTERM +#ifdef SPECULAR +vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; +#ifdef GLOSSINESS +glossiness=glossiness*specularMapColor.a; +#endif +#endif +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +float shadow=1.;float aggShadow=0.;float numLights=0.; +#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +#include[0..maxSimultaneousLights] +aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); +#ifdef REFRACTION +vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); +#ifdef REFRACTIONMAP_3D +#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); +#endif +#ifdef RGBDREFRACTION +refractionColor.rgb=fromRGBD(refractionColor); +#endif +#ifdef IS_REFRACTION_LINEAR +refractionColor.rgb=toGammaSpace(refractionColor.rgb); +#endif +refractionColor.rgb*=vRefractionInfos.x; +#endif +vec4 reflectionColor=vec4(0.,0.,0.,1.); +#ifdef REFLECTION +vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +vReflectionUVW.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +#ifdef ROUGHNESS +float bias=vReflectionInfos.y; +#ifdef SPECULARTERM +#ifdef SPECULAR +#ifdef GLOSSINESS +bias*=(1.0-specularMapColor.a); +#endif +#endif +#endif +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); +#else +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); +#endif +#else +vec2 coords=vReflectionUVW.xy; +#ifdef REFLECTIONMAP_PROJECTION +coords/=vReflectionUVW.z; +#endif +coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef IS_REFLECTION_LINEAR +reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#ifdef REFLECTIONFRESNEL +float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); +#ifdef REFLECTIONFRESNELFROMSPECULAR +#ifdef SPECULARTERM +reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#endif +#endif +#ifdef REFRACTIONFRESNEL +float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#ifdef OPACITYRGB +opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; +#else +alpha*=opacityMap.a*vOpacityInfos.y; +#endif +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef OPACITYFRESNEL +float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; +#endif +#ifdef ALPHATEST +#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS +if (alpha +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +color.rgb=toLinearSpace(color.rgb); +#else +#ifdef IMAGEPROCESSING +color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); +#endif +#endif +color.a*=visibility; +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0; +#ifdef PREPASS_COLOR +gl_FragData[PREPASS_COLOR_INDEX]=color; +#endif +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_LOCAL_POSITION +gl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition,writeGeometryInfo); +#endif +#if defined(PREPASS_VELOCITY) +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#elif defined(PREPASS_VELOCITY_LINEAR) +vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w)-(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_IRRADIANCE +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_SCREENSPACE_DEPTH +gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_WORLD_NORMAL +gl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO +gl_FragData[PREPASS_ALBEDO_INDEX]=vec4(baseColor.rgb,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqrt(baseColor.rgb),writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#if defined(SPECULAR) +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=color; +#endif +#include +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} +#endif +#define CUSTOM_FRAGMENT_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3M]) { + ShaderStore.ShadersStore[name$3M] = shader$3L; +} +/** @internal */ +const defaultPixelShader = { name: name$3M, shader: shader$3L }; + +const default_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + defaultPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3L = "defaultVertexDeclaration"; +const shader$3K = `uniform mat4 viewProjection; +#ifdef MULTIVIEW +mat4 viewProjectionR; +#endif +uniform mat4 view; +#ifdef DIFFUSE +uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef AMBIENT +uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; +#endif +#ifdef OPACITY +uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; +#endif +#if defined(SPECULAR) && defined(SPECULARTERM) +uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; +#endif +#ifdef REFLECTION +uniform mat4 reflectionMatrix; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos;uniform mat4 detailMatrix; +#endif +#include +#define ADDITIONAL_VERTEX_DECLARATION +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$3L]) { + ShaderStore.IncludesShadersStore[name$3L] = shader$3K; +} + +// Do not edit. +const name$3K = "defaultVertexShader"; +const shader$3J = `#define CUSTOM_VERTEX_EXTENSION +#include<__decl__defaultVertex> +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include[2..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +#include +#include[1..7] +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) +#endif +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef UV2 +vec2 uv2Updated=uv2; +#endif +#ifdef VERTEXCOLOR +vec4 colorUpdated=color; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include +#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +vPositionW=vec3(worldPos); +#ifdef PREPASS +#include +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2Updated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#ifdef MAINUV2 +vMainUV2=uv2Updated; +#endif +#include[3..7] +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) +#endif +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#include +#include +#define CUSTOM_VERTEX_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3K]) { + ShaderStore.ShadersStore[name$3K] = shader$3J; +} +/** @internal */ +const defaultVertexShader = { name: name$3K, shader: shader$3J }; + +const default_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + defaultVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3J = "defaultUboDeclaration"; +const shader$3I = `uniform diffuseLeftColor: vec4f;uniform diffuseRightColor: vec4f;uniform opacityParts: vec4f;uniform reflectionLeftColor: vec4f;uniform reflectionRightColor: vec4f;uniform refractionLeftColor: vec4f;uniform refractionRightColor: vec4f;uniform emissiveLeftColor: vec4f;uniform emissiveRightColor: vec4f;uniform vDiffuseInfos: vec2f;uniform vAmbientInfos: vec2f;uniform vOpacityInfos: vec2f;uniform vReflectionInfos: vec2f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vSpecularInfos: vec2f;uniform vBumpInfos: vec3f;uniform diffuseMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform reflectionMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform specularMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform pointSize: f32;uniform alphaCutOff: f32;uniform refractionMatrix: mat4x4f;uniform vRefractionInfos: vec4f;uniform vRefractionPosition: vec3f;uniform vRefractionSize: vec3f;uniform vSpecularColor: vec4f;uniform vEmissiveColor: vec3f;uniform vDiffuseColor: vec4f;uniform vAmbientColor: vec3f; +#define ADDITIONAL_UBO_DECLARATION +#include +#include +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$3J]) { + ShaderStore.IncludesShadersStoreWGSL[name$3J] = shader$3I; +} + +// Do not edit. +const name$3I = "defaultPixelShader"; +const shader$3H = `#include +#include[SCENE_MRT_COUNT] +#include +#define CUSTOM_FRAGMENT_BEGIN +varying vPositionW: vec3f; +#ifdef NORMAL +varying vNormalW: vec3f; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vColor: vec4f; +#endif +#include[1..7] +#include +#include[0..maxSimultaneousLights] +#include +#include +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef REFRACTION +#ifdef REFRACTIONMAP_3D +var refractionCubeSamplerSampler: sampler;var refractionCubeSampler: texture_cube; +#else +var refraction2DSamplerSampler: sampler;var refraction2DSampler: texture_2d; +#endif +#endif +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) +#endif +#include +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +var reflectionCubeSamplerSampler: sampler;var reflectionCubeSampler: texture_cube; +#else +var reflection2DSamplerSampler: sampler;var reflection2DSampler: texture_2d; +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vPositionUVW: vec3f; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vDirectionW: vec3f; +#endif +#endif +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-fragmentInputs.vPositionW);var baseColor: vec4f= vec4f(1.,1.,1.,1.);var diffuseColor: vec3f=uniforms.vDiffuseColor.rgb;var alpha: f32=uniforms.vDiffuseColor.a; +#ifdef NORMAL +var normalW: vec3f=normalize(fragmentInputs.vNormalW); +#else +var normalW: vec3f=normalize(-cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW))); +#endif +#include +#ifdef TWOSIDEDLIGHTING +normalW=select(-normalW,normalW,fragmentInputs.frontFacing); +#endif +#ifdef DIFFUSE +baseColor=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vDiffuseUV+uvOffset); +#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) +if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#include +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor=vec4f(baseColor.rgb*fragmentInputs.vColor.rgb,baseColor.a); +#endif +#ifdef DETAIL +baseColor=vec4f(baseColor.rgb*2.0*mix(0.5,detailColor.r,uniforms.vDetailInfos.y),baseColor.a); +#endif +#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) +var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset); +#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE +var baseAmbientColor: vec3f= vec3f(1.,1.,1.); +#ifdef AMBIENT +baseAmbientColor=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb*uniforms.vAmbientInfos.y; +#endif +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +var glossiness: f32=uniforms.vSpecularColor.a;var specularColor: vec3f=uniforms.vSpecularColor.rgb; +#ifdef SPECULARTERM +#ifdef SPECULAR +var specularMapColor: vec4f=textureSample(specularSampler,specularSamplerSampler,fragmentInputs.vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; +#ifdef GLOSSINESS +glossiness=glossiness*specularMapColor.a; +#endif +#endif +#endif +var diffuseBase: vec3f= vec3f(0.,0.,0.);var info: lightingInfo; +#ifdef SPECULARTERM +var specularBase: vec3f= vec3f(0.,0.,0.); +#endif +var shadow: f32=1.;var aggShadow: f32=0.;var numLights: f32=0.; +#ifdef LIGHTMAP +var lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a); +#endif +lightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a); +#endif +#include[0..maxSimultaneousLights] +aggShadow=aggShadow/numLights;var refractionColor: vec4f= vec4f(0.,0.,0.,1.); +#ifdef REFRACTION +var refractionVector: vec3f=normalize(refract(-viewDirectionW,normalW,uniforms.vRefractionInfos.y)); +#ifdef REFRACTIONMAP_3D +#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(fragmentInputs.vPositionW,refractionVector,uniforms.vRefractionSize,uniforms.vRefractionPosition); +#endif +refractionVector.y=refractionVector.y*uniforms.vRefractionInfos.w;var refractionLookup: vec4f=textureSample(refractionCubeSampler,refractionCubeSamplerSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} +#else +var vRefractionUVW: vec3f= (uniforms.refractionMatrix*(scene.view* vec4f(fragmentInputs.vPositionW+refractionVector*uniforms.vRefractionInfos.z,1.0))).xyz;var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=textureSample(refraction2DSampler,refraction2DSamplerSampler,refractionCoords); +#endif +#ifdef RGBDREFRACTION +refractionColor=vec4f(fromRGBD(refractionColor),refractionColor.a); +#endif +#ifdef IS_REFRACTION_LINEAR +refractionColor=vec4f(toGammaSpaceVec3(refractionColor.rgb),refractionColor.a); +#endif +refractionColor=vec4f(refractionColor.rgb*uniforms.vRefractionInfos.x,refractionColor.a); +#endif +var reflectionColor: vec4f= vec4f(0.,0.,0.,1.); +#ifdef REFLECTION +var vReflectionUVW: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +vReflectionUVW=vec3f(vReflectionUVW.x,vReflectionUVW.y,vReflectionUVW.z*-1.0); +#endif +#ifdef REFLECTIONMAP_3D +#ifdef ROUGHNESS +var bias: f32=uniforms.vReflectionInfos.y; +#ifdef SPECULARTERM +#ifdef SPECULAR +#ifdef GLOSSINESS +bias*=(1.0-specularMapColor.a); +#endif +#endif +#endif +reflectionColor=textureSampleLevel(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW,bias); +#else +reflectionColor=textureSample(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW); +#endif +#else +var coords: vec2f=vReflectionUVW.xy; +#ifdef REFLECTIONMAP_PROJECTION +coords/=vReflectionUVW.z; +#endif +coords.y=1.0-coords.y;reflectionColor=textureSample(reflection2DSampler,reflection2DSamplerSampler,coords); +#endif +#ifdef RGBDREFLECTION +reflectionColor=vec4f(fromRGBD(reflectionColor),reflectionColor.a); +#endif +#ifdef IS_REFLECTION_LINEAR +reflectionColor=vec4f(toGammaSpaceVec3(reflectionColor.rgb),reflectionColor.a); +#endif +reflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a); +#ifdef REFLECTIONFRESNEL +var reflectionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.reflectionRightColor.a,uniforms.reflectionLeftColor.a); +#ifdef REFLECTIONFRESNELFROMSPECULAR +#ifdef SPECULARTERM +reflectionColor=vec4f(reflectionColor.rgb*specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a); +#else +reflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a); +#endif +#else +reflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a); +#endif +#endif +#endif +#ifdef REFRACTIONFRESNEL +var refractionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.refractionRightColor.a,uniforms.refractionLeftColor.a);refractionColor=vec4f(refractionColor.rgb*uniforms.refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*uniforms.refractionRightColor.rgb,refractionColor.a); +#endif +#ifdef OPACITY +var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset); +#ifdef OPACITYRGB +opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* uniforms.vOpacityInfos.y; +#else +alpha*=opacityMap.a*uniforms.vOpacityInfos.y; +#endif +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=fragmentInputs.vColor.a; +#endif +#ifdef OPACITYFRESNEL +var opacityFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.opacityParts.z,uniforms.opacityParts.w);alpha+=uniforms.opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*uniforms.opacityParts.y; +#endif +#ifdef ALPHATEST +#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS +if (alpha +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +color=vec4f(toLinearSpaceVec3(color.rgb),color.a); +#else +#ifdef IMAGEPROCESSING +color=vec4f(toLinearSpaceVec3(color.rgb),color.a);color=applyImageProcessing(color); +#endif +#endif +color=vec4f(color.rgb,color.a*mesh.visibility); +#ifdef PREMULTIPLYALPHA +color=vec4f(color.rgb*color.a, color.a); +#endif +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +var writeGeometryInfo: f32=select(0.0,1.0,color.a>0.4);var fragData: array,SCENE_MRT_COUNT>; +#ifdef PREPASS_COLOR +fragData[PREPASS_COLOR_INDEX]=color; +#endif +#ifdef PREPASS_POSITION +fragData[PREPASS_POSITION_INDEX]=vec4f(fragmentInputs.vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_LOCAL_POSITION +fragData[PREPASS_LOCAL_POSITION_INDEX]=vec4f(fragmentInputs.vPosition,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +var a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo); +#elif defined(PREPASS_VELOCITY_LINEAR) +var velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w) - +(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_IRRADIANCE +fragData[PREPASS_IRRADIANCE_INDEX]=vec4f(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_DEPTH +fragData[PREPASS_DEPTH_INDEX]=vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_SCREENSPACE_DEPTH +fragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +fragData[PREPASS_NORMAL_INDEX]=vec4f(normalW,writeGeometryInfo); +#else +fragData[PREPASS_NORMAL_INDEX]=vec4f(normalize((scene.view*vec4f(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_WORLD_NORMAL +fragData[PREPASS_WORLD_NORMAL_INDEX]=vec4f(normalW*0.5+0.5,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO +fragData[PREPASS_ALBEDO_INDEX]=vec4f(baseColor.rgb,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +fragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4f(sqrt(baseColor.rgb),writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#if defined(SPECULAR) +fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec4(specularMapColor))*writeGeometryInfo; +#else +fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec3(specularColor),1.0)*writeGeometryInfo; +#endif +#endif +#if SCENE_MRT_COUNT>0 +fragmentOutputs.fragData0=fragData[0]; +#endif +#if SCENE_MRT_COUNT>1 +fragmentOutputs.fragData1=fragData[1]; +#endif +#if SCENE_MRT_COUNT>2 +fragmentOutputs.fragData2=fragData[2]; +#endif +#if SCENE_MRT_COUNT>3 +fragmentOutputs.fragData3=fragData[3]; +#endif +#if SCENE_MRT_COUNT>4 +fragmentOutputs.fragData4=fragData[4]; +#endif +#if SCENE_MRT_COUNT>5 +fragmentOutputs.fragData5=fragData[5]; +#endif +#if SCENE_MRT_COUNT>6 +fragmentOutputs.fragData6=fragData[6]; +#endif +#if SCENE_MRT_COUNT>7 +fragmentOutputs.fragData7=fragData[7]; +#endif +#endif +#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY) +fragmentOutputs.color=color; +#endif +#include +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+color.rgb*color.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-color.a));} else {fragmentOutputs.backColor+=color;} +#endif +#define CUSTOM_FRAGMENT_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3I]) { + ShaderStore.ShadersStoreWGSL[name$3I] = shader$3H; +} +/** @internal */ +const defaultPixelShaderWGSL = { name: name$3I, shader: shader$3H }; + +const default_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + defaultPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3H = "lightVxFragmentDeclaration"; +const shader$3G = `#ifdef LIGHT{X} +uniform vLightData{X}: vec4f;uniform vLightDiffuse{X}: vec4f; +#ifdef SPECULARTERM +uniform vLightSpecular{X}: vec4f; +#else +var vLightSpecular{X}: vec4f= vec4f(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform lightMatrix{X}: mat4x4f[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromLight{X}: vec4f[SHADOWCSMNUM_CASCADES{X}];varying var vDepthMetric{X}: f32[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromCamera{X}: vec4f; +#elif defined(SHADOWCUBE{X}) +#else +varying var vPositionFromLight{X}: vec4f;varying var vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f; +#endif +uniform shadowsInfo{X}: vec4f;uniform depthValues{X}: vec2f; +#endif +#ifdef SPOTLIGHT{X} +uniform vLightDirection{X}: vec4f;uniform vLightFalloff{X}: vec4f; +#elif defined(POINTLIGHT{X}) +uniform vLightFalloff{X}: vec4f; +#elif defined(HEMILIGHT{X}) +uniform vLightGround{X}: vec3f; +#endif +#if defined(AREALIGHT{X}) +uniform vLightWidth{X}: vec4f;uniform vLightHeight{X}: vec4f; +#endif +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$3H]) { + ShaderStore.IncludesShadersStoreWGSL[name$3H] = shader$3G; +} + +// Do not edit. +const name$3G = "defaultVertexShader"; +const shader$3F = `#include +#define CUSTOM_VERTEX_BEGIN +attribute position: vec3f; +#ifdef NORMAL +attribute normal: vec3f; +#endif +#ifdef TANGENT +attribute tangent: vec4f; +#endif +#ifdef UV1 +attribute uv: vec2f; +#endif +#include[2..7] +#ifdef VERTEXCOLOR +attribute color: vec4f; +#endif +#include +#include +#include +#include +#include +#include[1..7] +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) +#endif +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +varying vPositionW: vec3f; +#ifdef NORMAL +varying vNormalW: vec3f; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vColor: vec4f; +#endif +#include +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vPositionUVW: vec3f; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vDirectionW: vec3f; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +var positionUpdated: vec3f=vertexInputs.position; +#ifdef NORMAL +var normalUpdated: vec3f=vertexInputs.normal; +#endif +#ifdef TANGENT +var tangentUpdated: vec4f=vertexInputs.tangent; +#endif +#ifdef UV1 +var uvUpdated: vec2f=vertexInputs.uv; +#endif +#ifdef UV2 +var uv2Updated: vec2f=vertexInputs.uv2; +#endif +#ifdef VERTEXCOLOR +var colorUpdated: vec4f=vertexInputs.color; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vertexOutputs.vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include +#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED) +vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0); +#endif +#include +#include +var worldPos: vec4f=finalWorld*vec4f(positionUpdated,1.0); +#ifdef NORMAL +var normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;} +#else +vertexOutputs.position=scene.viewProjection*worldPos; +#endif +vertexOutputs.vPositionW= worldPos.xyz; +#ifdef PREPASS +#include +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vertexOutputs.vDirectionW=normalize((finalWorld* vec4f(positionUpdated,0.0)).xyz); +#endif +#ifndef UV1 +var uvUpdated: vec2f=vec2f(0.,0.); +#endif +#ifdef MAINUV1 +vertexOutputs.vMainUV1=uvUpdated; +#endif +#ifndef UV2 +var uv2Updated: vec2f=vec2f(0.,0.); +#endif +#ifdef MAINUV2 +vertexOutputs.vMainUV2=uv2Updated; +#endif +#include[3..7] +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) +#endif +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#include +#define CUSTOM_VERTEX_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3G]) { + ShaderStore.ShadersStoreWGSL[name$3G] = shader$3F; +} +/** @internal */ +const defaultVertexShaderWGSL = { name: name$3G, shader: shader$3F }; + +const default_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + defaultVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3F = "greasedLinePixelShader"; +const shader$3E = `precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} +if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { +textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} +if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3F]) { + ShaderStore.ShadersStore[name$3F] = shader$3E; +} +/** @internal */ +const greasedLinePixelShader = { name: name$3F, shader: shader$3E }; + +const greasedLine_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + greasedLinePixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3E = "greasedLineVertexShader"; +const shader$3D = `precision highp float; +#include +attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer; +#ifdef GREASED_LINE_CAMERA_FACING +attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} +#else +attribute vec3 grl_slopes;attribute float grl_counters; +#endif +void main() { +#include +grlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ; +#ifdef GREASED_LINE_CAMERA_FACING +float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;float grlWidth=grlBaseWidth*grl_widths;vec3 positionUpdated=position+grl_offsets;vec3 worldDir=normalize(grlNext-grlPrevious);vec3 nearPosition=positionUpdated+(worldDir*0.001);vec4 grlFinalPosition=grlMatrix*vec4( positionUpdated ,1.0);vec4 screenNearPos=grlMatrix*vec4(nearPosition,1.0);vec2 grlLinePosition=grlFix(grlFinalPosition,grlAspect);vec2 grlLineNearPosition=grlFix(screenNearPos,grlAspect);vec2 grlDir=normalize(grlLineNearPosition-grlLinePosition);vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); +#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM +grlNormal.xy*=-.5*grlWidth; +#else +grlNormal.xy*=.5*grlWidth; +#endif +grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} +grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition; +#else +grlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition; +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3E]) { + ShaderStore.ShadersStore[name$3E] = shader$3D; +} +/** @internal */ +const greasedLineVertexShader = { name: name$3E, shader: shader$3D }; + +const greasedLine_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + greasedLineVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3D = "greasedLinePixelShader"; +const shader$3C = `var grlColors: texture_2d;var grlColorsSampler: sampler;uniform grlUseColors: f32;uniform grlUseDash: f32;uniform grlDashArray: f32;uniform grlDashOffset: f32;uniform grlDashRatio: f32;uniform grlVisibility: f32;uniform grlColorsWidth: f32;uniform grl_colorModeAndColorDistributionType: vec2f;uniform grlColor: vec3f;varying grlCounters: f32;varying grlColorPointer: f32; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +let grlColorMode: f32=uniforms.grl_colorModeAndColorDistributionType.x;let grlColorDistributionType: f32=uniforms.grl_colorModeAndColorDistributionType.y;var outColor=vec4(uniforms.grlColor,1.);outColor.a=step(fragmentInputs.grlCounters,uniforms.grlVisibility);if (outColor.a==0.0) {discard;} +if (uniforms.grlUseDash==1.0) {let dashPosition=(fragmentInputs.grlCounters+uniforms.grlDashOffset) % uniforms.grlDashArray;outColor.a*=ceil(dashPosition-(uniforms.grlDashArray*uniforms.grlDashRatio));if (outColor.a==0.0) {discard;}} +if (uniforms.grlUseColors==1.) { +#ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE +let grlColor: vec4f=textureSample(grlColors,grlColorsSampler,vec2f(fragmentInputs.grlCounters,0.)); +#else +let lookup: vec2f=vec2(fract(fragmentInputs.grlColorPointer/uniforms.grlColorsWidth),1.0-floor(fragmentInputs.grlColorPointer/uniforms.grlColorsWidth));let grlColor: vec4f=textureSample(grlColors,grlColorsSampler,lookup); +#endif +if (grlColorMode==COLOR_MODE_SET) {outColor=grlColor;} else if (grlColorMode==COLOR_MODE_ADD) {outColor+=grlColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {outColor*=grlColor;}} +#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY) +fragmentOutputs.color=outColor; +#endif +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+outColor.rgb*outColor.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-outColor.a));} else {fragmentOutputs.backColor+=outColor;} +#endif +#define CUSTOM_FRAGMENT_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3D]) { + ShaderStore.ShadersStoreWGSL[name$3D] = shader$3C; +} +/** @internal */ +const greasedLinePixelShaderWGSL = { name: name$3D, shader: shader$3C }; + +const greasedLine_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + greasedLinePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3C = "greasedLineVertexShader"; +const shader$3B = `#include +#include +#include +attribute grl_widths: f32; +#ifdef GREASED_LINE_USE_OFFSETS +attribute grl_offsets: vec3f; +#endif +attribute grl_colorPointers: f32;attribute position: vec3f;varying grlCounters: f32;varying grlColorPointer: f32; +#ifdef GREASED_LINE_CAMERA_FACING +attribute grl_nextAndCounters: vec4f;attribute grl_previousAndSide: vec4f;uniform grlResolution: vec2f;uniform grlAspect: f32;uniform grlWidth: f32;uniform grlSizeAttenuation: f32;fn grlFix(i: vec4f,aspect: f32)->vec2f {var res=i.xy/i.w;res.x*=aspect;return res;} +#else +attribute grl_slopes: vec3f;attribute grl_counters: f32; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +vertexOutputs.grlColorPointer=input.grl_colorPointers;let grlMatrix: mat4x4f=scene.viewProjection*mesh.world ; +#ifdef GREASED_LINE_CAMERA_FACING +let grlBaseWidth: f32=uniforms.grlWidth;let grlPrevious: vec3f=input.grl_previousAndSide.xyz;let grlSide: f32=input.grl_previousAndSide.w;let grlNext: vec3f=input.grl_nextAndCounters.xyz;vertexOutputs.grlCounters=input.grl_nextAndCounters.w;let grlWidth:f32=grlBaseWidth*input.grl_widths; +#ifdef GREASED_LINE_USE_OFFSETS +var grlPositionOffset: vec3f=input.grl_offsets; +#else +var grlPositionOffset=vec3f(0.); +#endif +let positionUpdated: vec3f=vertexInputs.position+grlPositionOffset;let worldDir: vec3f=normalize(grlNext-grlPrevious);let nearPosition: vec3f=positionUpdated+(worldDir*0.001);let grlFinalPosition: vec4f=grlMatrix*vec4f(positionUpdated,1.0);let screenNearPos: vec4f=grlMatrix*vec4(nearPosition,1.0);let grlLinePosition: vec2f=grlFix(grlFinalPosition,uniforms.grlAspect);let grlLineNearPosition: vec2f=grlFix(screenNearPos,uniforms.grlAspect);let grlDir: vec2f=normalize(grlLineNearPosition-grlLinePosition);var grlNormal: vec4f=vec4f(-grlDir.y,grlDir.x,0.0,1.0);let grlHalfWidth: f32=0.5*grlWidth; +#if defined(GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM) +grlNormal.x*=-grlHalfWidth;grlNormal.y*=-grlHalfWidth; +#else +grlNormal.x*=grlHalfWidth;grlNormal.y*=grlHalfWidth; +#endif +grlNormal*=scene.projection;if (uniforms.grlSizeAttenuation==1.) {grlNormal.x*=grlFinalPosition.w;grlNormal.y*=grlFinalPosition.w;let pr=vec4f(uniforms.grlResolution,0.0,1.0)*scene.projection;grlNormal.x/=pr.x;grlNormal.y/=pr.y;} +vertexOutputs.position=vec4f(grlFinalPosition.xy+grlNormal.xy*grlSide,grlFinalPosition.z,grlFinalPosition.w); +#else +vertexOutputs.grlCounters=input.grl_counters;vertexOutputs.position=grlMatrix*vec4f((vertexInputs.position+input.grl_offsets)+input.grl_slopes*input.grl_widths,1.0) ; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3C]) { + ShaderStore.ShadersStoreWGSL[name$3C] = shader$3B; +} +/** @internal */ +const greasedLineVertexShaderWGSL = { name: name$3C, shader: shader$3B }; + +const greasedLine_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + greasedLineVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +/* eslint-disable @typescript-eslint/naming-convention */ +const HCF = HighestCommonFactor; +/** + * Scalar computation library + */ +const Scalar = { + ...functions, + /** + * Two pi constants convenient for computation. + */ + TwoPi: Math.PI * 2, + /** + * Returns -1 if value is negative and +1 is value is positive. + * @param value the value + * @returns the value itself if it's equal to zero. + */ + Sign: Math.sign, + /** + * the log2 of value. + * @param value the value to compute log2 of + * @returns the log2 of value. + */ + Log2: Math.log2, + /** + * Returns the highest common factor of two integers. + * @param a first parameter + * @param b second parameter + * @returns HCF of a and b + */ + HCF, +}; +/* eslint-enable @typescript-eslint/naming-convention */ + +/** + * Creates a string representation of the Vector2 + * @param vector defines the Vector2 to stringify + * @param decimalCount defines the number of decimals to use + * @returns a string with the Vector2 coordinates. + */ +function Vector2ToFixed(vector, decimalCount) { + return `{X: ${vector.x.toFixed(decimalCount)} Y: ${vector.y.toFixed(decimalCount)}}`; +} +/** + * Creates a string representation of the Vector3 + * @param vector defines the Vector3 to stringify + * @param decimalCount defines the number of decimals to use + * @returns a string with the Vector3 coordinates. + */ +function Vector3ToFixed(vector, decimalCount) { + return `{X: ${vector._x.toFixed(decimalCount)} Y: ${vector._y.toFixed(decimalCount)} Z: ${vector._z.toFixed(decimalCount)}}`; +} +/** + * Creates a string representation of the Vector4 + * @param vector defines the Vector4 to stringify + * @param decimalCount defines the number of decimals to use + * @returns a string with the Vector4 coordinates. + */ +function Vector4ToFixed(vector, decimalCount) { + return `{X: ${vector.x.toFixed(decimalCount)} Y: ${vector.y.toFixed(decimalCount)} Z: ${vector.z.toFixed(decimalCount)} W: ${vector.w.toFixed(decimalCount)}}`; +} + +/** + * Map the Babylon.js attribute kind to the Draco attribute kind, defined by the `GeometryAttributeType` enum. + * @internal + */ +function GetDracoAttributeName(kind) { + if (kind === VertexBuffer.PositionKind) { + return "POSITION"; + } + else if (kind === VertexBuffer.NormalKind) { + return "NORMAL"; + } + else if (kind === VertexBuffer.ColorKind) { + return "COLOR"; + } + else if (kind.startsWith(VertexBuffer.UVKind)) { + return "TEX_COORD"; + } + return "GENERIC"; +} +/** + * Get the indices for the geometry, if present. Eventually used as + * `AddFacesToMesh(mesh: Mesh, numFaces: number, faces: Uint16Array | Uint32Array)`; + * where `numFaces = indices.length / 3` and `faces = indices`. + * @internal + */ +function PrepareIndicesForDraco(input) { + let indices = input.getIndices(undefined, true); + // Convert number[] and Int32Array types, if needed + if (indices && !(indices instanceof Uint32Array) && !(indices instanceof Uint16Array)) { + indices = (AreIndices32Bits(indices, indices.length) ? Uint32Array : Uint16Array).from(indices); + } + return indices; +} +/** + * Get relevant information about the geometry's vertex attributes for Draco encoding. Eventually used for each attribute as + * `AddFloatAttribute(mesh: Mesh, attribute: number, count: number, itemSize: number, array: TypedArray)` + * where `attribute = EncoderModule[]`, `itemSize = `, `array = `, and count is the number of position vertices. + * @internal + */ +function PrepareAttributesForDraco(input, excludedAttributes) { + const attributes = []; + for (const kind of input.getVerticesDataKinds()) { + if (excludedAttributes?.includes(kind)) { + if (kind === VertexBuffer.PositionKind) { + throw new Error("Cannot exclude position attribute from Draco encoding."); + } + continue; + } + // Convert number[] to typed array, if needed. + const vertexBuffer = input.getVertexBuffer(kind); + const size = vertexBuffer.getSize(); + const data = GetTypedArrayData(vertexBuffer.getData(), size, vertexBuffer.type, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.normalized, input.getTotalVertices(), true); + attributes.push({ kind: kind, dracoName: GetDracoAttributeName(kind), size: size, data: data }); + } + return attributes; +} +const DefaultEncoderOptions = { + decodeSpeed: 5, + encodeSpeed: 5, + method: "MESH_EDGEBREAKER_ENCODING", + quantizationBits: { + POSITION: 14, + NORMAL: 10, + COLOR: 8, + TEX_COORD: 12, + GENERIC: 12, + }, +}; +/** + * @experimental This class is subject to change. + * + * Draco Encoder (https://google.github.io/draco/) + * + * This class wraps the Draco encoder module. + * + * By default, the configuration points to a copy of the Draco encoder files from the Babylon.js cdn https://cdn.babylonjs.com/draco_encoder_wasm_wrapper.js. + * + * To update the configuration, use the following code: + * ```javascript + * DracoEncoder.DefaultConfiguration = { + * wasmUrl: "", + * wasmBinaryUrl: "", + * fallbackUrl: "", + * }; + * ``` + * + * Draco has two versions, one for WebAssembly and one for JavaScript. The encoder configuration can be set to only support WebAssembly or only support the JavaScript version. + * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser. + * Use `DracoEncoder.DefaultAvailable` to determine if the encoder configuration is available for the current context. + * + * To encode Draco compressed data, get the default DracoEncoder object and call encodeMeshAsync: + * ```javascript + * var dracoData = await DracoEncoder.Default.encodeMeshAsync(mesh); + * ``` + * + * Currently, DracoEncoder only encodes to meshes. Encoding to point clouds is not yet supported. + * + * Only position, normal, color, and UV attributes are supported natively by the encoder. All other attributes are treated as generic. This means that, + * when decoding these generic attributes later, additional information about their original Babylon types will be needed to interpret the data correctly. + * You can use the return value of `encodeMeshAsync` to source this information, specifically the `attributes` field. E.g., + * ```javascript + * var dracoData = await DracoEncoder.Default.encodeMeshAsync(mesh); + * var meshData = await DracoDecoder.Default.decodeMeshToMeshDataAsync(dracoData.data, dracoData.attributes); + * ``` + * + * By default, DracoEncoder will encode all available attributes of the mesh. To exclude specific attributes, use the following code: + * ```javascript + * var options = { excludedAttributes: [VertexBuffer.MatricesIndicesKind, VertexBuffer.MatricesWeightsKind] }; + * var dracoData = await DracoDecoder.Default.encodeMeshAsync(mesh, options); + * ``` + */ +class DracoEncoder extends DracoCodec { + /** + * Returns true if the encoder's `DefaultConfiguration` is available. + */ + static get DefaultAvailable() { + return _IsConfigurationAvailable(DracoEncoder.DefaultConfiguration); + } + /** + * Default instance for the DracoEncoder. + */ + static get Default() { + DracoEncoder._Default ?? (DracoEncoder._Default = new DracoEncoder()); + return DracoEncoder._Default; + } + /** + * Reset the default DracoEncoder object to null and disposing the removed default instance. + * Note that if the workerPool is a member of the static DefaultConfiguration object it is recommended not to run dispose, + * unless the static worker pool is no longer needed. + * @param skipDispose set to true to not dispose the removed default instance + */ + static ResetDefault(skipDispose) { + if (DracoEncoder._Default) { + if (!skipDispose) { + DracoEncoder._Default.dispose(); + } + DracoEncoder._Default = null; + } + } + _isModuleAvailable() { + return typeof DracoEncoderModule !== "undefined"; + } + async _createModuleAsync(wasmBinary, jsModule /** DracoEncoderModule */) { + const module = await (jsModule || DracoEncoderModule)({ wasmBinary }); + return { module }; + } + _getWorkerContent() { + return `${EncodeMesh}(${EncoderWorkerFunction})()`; + } + /** + * Creates a new Draco encoder. + * @param configuration Optional override of the configuration for the DracoEncoder. If not provided, defaults to {@link DracoEncoder.DefaultConfiguration}. + */ + constructor(configuration = DracoEncoder.DefaultConfiguration) { + super(configuration); + } + /** + * @internal + */ + async _encodeAsync(attributes, indices, options) { + const mergedOptions = options ? deepMerge(DefaultEncoderOptions, options) : DefaultEncoderOptions; + if (this._workerPoolPromise) { + const workerPool = await this._workerPoolPromise; + return new Promise((resolve, reject) => { + workerPool.push((worker, onComplete) => { + const onError = (error) => { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + reject(error); + onComplete(); + }; + const onMessage = (message) => { + if (message.data.id === "encodeMeshDone") { + worker.removeEventListener("error", onError); + worker.removeEventListener("message", onMessage); + resolve(message.data.encodedMeshData); + onComplete(); + } + }; + worker.addEventListener("error", onError); + worker.addEventListener("message", onMessage); + // Build the transfer list. No need to copy, as the data was copied in previous steps. + const transferList = []; + attributes.forEach((attribute) => { + transferList.push(attribute.data.buffer); + }); + if (indices) { + transferList.push(indices.buffer); + } + worker.postMessage({ id: "encodeMesh", attributes: attributes, indices: indices, options: mergedOptions }, transferList); + }); + }); + } + if (this._modulePromise) { + const encoder = await this._modulePromise; + return EncodeMesh(encoder.module, attributes, indices, mergedOptions); + } + throw new Error("Draco encoder module is not available"); + } + /** + * Encodes a mesh or geometry into a Draco-encoded mesh data. + * @param input the mesh or geometry to encode + * @param options options for the encoding + * @returns a promise that resolves to the newly-encoded data + */ + async encodeMeshAsync(input, options) { + const verticesCount = input.getTotalVertices(); + if (verticesCount == 0) { + throw new Error("Cannot compress geometry with Draco. There are no vertices."); + } + // Prepare parameters for encoding + if (input instanceof Mesh && input.morphTargetManager && options?.method === "MESH_EDGEBREAKER_ENCODING") { + Logger.Warn("Cannot use Draco EDGEBREAKER method with morph targets. Falling back to SEQUENTIAL method."); + options.method = "MESH_SEQUENTIAL_ENCODING"; + } + const indices = PrepareIndicesForDraco(input); + const attributes = PrepareAttributesForDraco(input, options?.excludedAttributes); + return this._encodeAsync(attributes, indices, options); + } +} +/** + * Default configuration for the DracoEncoder. Defaults to the following: + * - numWorkers: 50% of the available logical processors, capped to 4. If no logical processors are available, defaults to 1. + * - wasmUrl: `"https://cdn.babylonjs.com/draco_encoder_wasm_wrapper.js"` + * - wasmBinaryUrl: `"https://cdn.babylonjs.com/draco_encoder.wasm"` + * - fallbackUrl: `"https://cdn.babylonjs.com/draco_encoder.js"` + */ +DracoEncoder.DefaultConfiguration = { + wasmUrl: `${Tools._DefaultCdnUrl}/draco_encoder_wasm_wrapper.js`, + wasmBinaryUrl: `${Tools._DefaultCdnUrl}/draco_encoder.wasm`, + fallbackUrl: `${Tools._DefaultCdnUrl}/draco_encoder.js`, +}; +DracoEncoder._Default = null; + +/** + * Unique ID when we import meshes from Babylon to CSG + */ +let currentCSGMeshId = 0; +/** + * Represents a vertex of a polygon. Use your own vertex class instead of this + * one to provide additional features like texture coordinates and vertex + * colors. Custom vertex classes need to provide a `pos` property and `clone()`, + * `flip()`, and `interpolate()` methods that behave analogous to the ones + * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience + * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal` + * is not used anywhere else. + * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes + */ +class Vertex { + /** + * Initializes the vertex + * @param pos The position of the vertex + * @param normal The normal of the vertex + * @param uv The texture coordinate of the vertex + * @param vertColor The RGBA color of the vertex + */ + constructor( + /** + * The position of the vertex + */ + pos, + /** + * The normal of the vertex + */ + normal, + /** + * The texture coordinate of the vertex + */ + uv, + /** + * The texture coordinate of the vertex + */ + vertColor) { + this.pos = pos; + this.normal = normal; + this.uv = uv; + this.vertColor = vertColor; + } + /** + * Make a clone, or deep copy, of the vertex + * @returns A new Vertex + */ + clone() { + return new Vertex(this.pos.clone(), this.normal.clone(), this.uv?.clone(), this.vertColor?.clone()); + } + /** + * Invert all orientation-specific data (e.g. vertex normal). Called when the + * orientation of a polygon is flipped. + */ + flip() { + this.normal = this.normal.scale(-1); + } + /** + * Create a new vertex between this vertex and `other` by linearly + * interpolating all properties using a parameter of `t`. Subclasses should + * override this to interpolate additional properties. + * @param other the vertex to interpolate against + * @param t The factor used to linearly interpolate between the vertices + * @returns The new interpolated vertex + */ + interpolate(other, t) { + return new Vertex(Vector3.Lerp(this.pos, other.pos, t), Vector3.Lerp(this.normal, other.normal, t), this.uv && other.uv ? Vector2.Lerp(this.uv, other.uv, t) : undefined, this.vertColor && other.vertColor ? Color4.Lerp(this.vertColor, other.vertColor, t) : undefined); + } +} +/** + * Represents a plane in 3D space. + */ +class CSGPlane { + /** + * Initializes the plane + * @param normal The normal for the plane + * @param w + */ + constructor(normal, w) { + this.normal = normal; + this.w = w; + } + /** + * Construct a plane from three points + * @param a Point a + * @param b Point b + * @param c Point c + * @returns A new plane + */ + static FromPoints(a, b, c) { + const v0 = c.subtract(a); + const v1 = b.subtract(a); + if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) { + return null; + } + const n = Vector3.Normalize(Vector3.Cross(v0, v1)); + return new CSGPlane(n, Vector3.Dot(n, a)); + } + /** + * Clone, or make a deep copy of the plane + * @returns a new Plane + */ + clone() { + return new CSGPlane(this.normal.clone(), this.w); + } + /** + * Flip the face of the plane + */ + flip() { + this.normal.scaleInPlace(-1); + this.w = -this.w; + } + /** + * Split `polygon` by this plane if needed, then put the polygon or polygon + * fragments in the appropriate lists. Coplanar polygons go into either + `* coplanarFront` or `coplanarBack` depending on their orientation with + * respect to this plane. Polygons in front or in back of this plane go into + * either `front` or `back` + * @param polygon The polygon to be split + * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane + * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane + * @param front Will contain the polygons in front of the plane + * @param back Will contain the polygons begind the plane + */ + splitPolygon(polygon, coplanarFront, coplanarBack, front, back) { + const COPLANAR = 0; + const FRONT = 1; + const BACK = 2; + const SPANNING = 3; + // Classify each point as well as the entire polygon into one of the above + // four classes. + let polygonType = 0; + const types = []; + let i; + let t; + for (i = 0; i < polygon.vertices.length; i++) { + t = Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w; + const type = t < -CSGPlane.EPSILON ? BACK : t > CSGPlane.EPSILON ? FRONT : COPLANAR; + polygonType |= type; + types.push(type); + } + // Put the polygon in the correct list, splitting it when necessary + switch (polygonType) { + case COPLANAR: + (Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon); + break; + case FRONT: + front.push(polygon); + break; + case BACK: + back.push(polygon); + break; + case SPANNING: { + const f = [], b = []; + for (i = 0; i < polygon.vertices.length; i++) { + const j = (i + 1) % polygon.vertices.length; + const ti = types[i], tj = types[j]; + const vi = polygon.vertices[i], vj = polygon.vertices[j]; + if (ti !== BACK) { + f.push(vi); + } + if (ti !== FRONT) { + b.push(ti !== BACK ? vi.clone() : vi); + } + if ((ti | tj) === SPANNING) { + t = (this.w - Vector3.Dot(this.normal, vi.pos)) / Vector3.Dot(this.normal, vj.pos.subtract(vi.pos)); + const v = vi.interpolate(vj, t); + f.push(v); + b.push(v.clone()); + } + } + let poly; + if (f.length >= 3) { + poly = new CSGPolygon(f, polygon.shared); + if (poly.plane) { + front.push(poly); + } + } + if (b.length >= 3) { + poly = new CSGPolygon(b, polygon.shared); + if (poly.plane) { + back.push(poly); + } + } + break; + } + } + } +} +/** + * `CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a + * point is on the plane + */ +CSGPlane.EPSILON = 1e-5; +/** + * Represents a convex polygon. The vertices used to initialize a polygon must + * be coplanar and form a convex loop. + * + * Each convex polygon has a `shared` property, which is shared between all + * polygons that are clones of each other or were split from the same polygon. + * This can be used to define per-polygon properties (such as surface color) + */ +class CSGPolygon { + /** + * Initializes the polygon + * @param vertices The vertices of the polygon + * @param shared The properties shared across all polygons + */ + constructor(vertices, shared) { + this.vertices = vertices; + this.shared = shared; + this.plane = CSGPlane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos); + } + /** + * Clones, or makes a deep copy, or the polygon + * @returns A new CSGPolygon + */ + clone() { + const vertices = this.vertices.map((v) => v.clone()); + return new CSGPolygon(vertices, this.shared); + } + /** + * Flips the faces of the polygon + */ + flip() { + this.vertices.reverse().map((v) => { + v.flip(); + }); + this.plane.flip(); + } +} +/** + * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons + * by picking a polygon to split along. That polygon (and all other coplanar + * polygons) are added directly to that node and the other polygons are added to + * the front and/or back subtrees. This is not a leafy BSP tree since there is + * no distinction between internal and leaf nodes + */ +let Node$1 = class Node { + /** + * Initializes the node + * @param polygons A collection of polygons held in the node + */ + constructor(polygons) { + this._plane = null; + this._front = null; + this._back = null; + this._polygons = new Array(); + if (polygons) { + this.build(polygons); + } + } + /** + * Clones, or makes a deep copy, of the node + * @returns The cloned node + */ + clone() { + const node = new Node(); + node._plane = this._plane && this._plane.clone(); + node._front = this._front && this._front.clone(); + node._back = this._back && this._back.clone(); + node._polygons = this._polygons.map((p) => p.clone()); + return node; + } + /** + * Convert solid space to empty space and empty space to solid space + */ + invert() { + for (let i = 0; i < this._polygons.length; i++) { + this._polygons[i].flip(); + } + if (this._plane) { + this._plane.flip(); + } + if (this._front) { + this._front.invert(); + } + if (this._back) { + this._back.invert(); + } + const temp = this._front; + this._front = this._back; + this._back = temp; + } + /** + * Recursively remove all polygons in `polygons` that are inside this BSP + * tree. + * @param polygons Polygons to remove from the BSP + * @returns Polygons clipped from the BSP + */ + clipPolygons(polygons) { + if (!this._plane) { + return polygons.slice(); + } + let front = [], back = []; + for (let i = 0; i < polygons.length; i++) { + this._plane.splitPolygon(polygons[i], front, back, front, back); + } + if (this._front) { + front = this._front.clipPolygons(front); + } + if (this._back) { + back = this._back.clipPolygons(back); + } + else { + back = []; + } + return front.concat(back); + } + /** + * Remove all polygons in this BSP tree that are inside the other BSP tree + * `bsp`. + * @param bsp BSP containing polygons to remove from this BSP + */ + clipTo(bsp) { + this._polygons = bsp.clipPolygons(this._polygons); + if (this._front) { + this._front.clipTo(bsp); + } + if (this._back) { + this._back.clipTo(bsp); + } + } + /** + * Return a list of all polygons in this BSP tree + * @returns List of all polygons in this BSP tree + */ + allPolygons() { + let polygons = this._polygons.slice(); + if (this._front) { + polygons = polygons.concat(this._front.allPolygons()); + } + if (this._back) { + polygons = polygons.concat(this._back.allPolygons()); + } + return polygons; + } + /** + * Build a BSP tree out of `polygons`. When called on an existing tree, the + * new polygons are filtered down to the bottom of the tree and become new + * nodes there. Each set of polygons is partitioned using the first polygon + * (no heuristic is used to pick a good split) + * @param polygons Polygons used to construct the BSP tree + */ + build(polygons) { + if (!polygons.length) { + return; + } + if (!this._plane) { + this._plane = polygons[0].plane.clone(); + } + const front = [], back = []; + for (let i = 0; i < polygons.length; i++) { + this._plane.splitPolygon(polygons[i], this._polygons, this._polygons, front, back); + } + if (front.length) { + if (!this._front) { + this._front = new Node(); + } + this._front.build(front); + } + if (back.length) { + if (!this._back) { + this._back = new Node(); + } + this._back.build(back); + } + } +}; +/** + * Class for building Constructive Solid Geometry + * @deprecated Please use CSG2 instead + */ +class CSG { + constructor() { + this._polygons = new Array(); + } + /** + * Convert a VertexData to CSG + * @param data defines the VertexData to convert to CSG + * @returns the new CSG + */ + static FromVertexData(data) { + let vertex, polygon, vertices; + const polygons = []; + const indices = data.indices; + const positions = data.positions; + const normals = data.normals; + const uvs = data.uvs; + const vertColors = data.colors; + if (!indices || !positions) { + // eslint-disable-next-line no-throw-literal + throw "BABYLON.CSG: VertexData must at least contain positions and indices"; + } + for (let i = 0; i < indices.length; i += 3) { + vertices = []; + for (let j = 0; j < 3; j++) { + const indexIndices = i + j; + const offset = indices[indexIndices]; + const normal = normals ? Vector3.FromArray(normals, offset * 3) : Vector3.Zero(); + const uv = uvs ? Vector2.FromArray(uvs, offset * 2) : undefined; + const vertColor = vertColors ? Color4.FromArray(vertColors, offset * 4) : undefined; + const position = Vector3.FromArray(positions, offset * 3); + vertex = new Vertex(position, normal, uv, vertColor); + vertices.push(vertex); + } + polygon = new CSGPolygon(vertices, { subMeshId: 0, meshId: currentCSGMeshId, materialIndex: 0 }); + // To handle the case of degenerated triangle + // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated + if (polygon.plane) { + polygons.push(polygon); + } + } + const csg = CSG._FromPolygons(polygons); + csg.matrix = Matrix.Identity(); + csg.position = Vector3.Zero(); + csg.rotation = Vector3.Zero(); + csg.scaling = Vector3.One(); + csg.rotationQuaternion = Quaternion.Identity(); + currentCSGMeshId++; + return csg; + } + /** + * Convert the Mesh to CSG + * @param mesh The Mesh to convert to CSG + * @param absolute If true, the final (local) matrix transformation is set to the identity and not to that of `mesh`. It can help when dealing with right-handed meshes (default: false) + * @returns A new CSG from the Mesh + */ + static FromMesh(mesh, absolute = false) { + let vertex, normal, uv = undefined, position, vertColor = undefined, polygon, vertices; + const polygons = []; + let matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling; + let invertWinding = false; + if (mesh instanceof Mesh) { + mesh.computeWorldMatrix(true); + matrix = mesh.getWorldMatrix(); + meshPosition = mesh.position.clone(); + meshRotation = mesh.rotation.clone(); + if (mesh.rotationQuaternion) { + meshRotationQuaternion = mesh.rotationQuaternion.clone(); + } + meshScaling = mesh.scaling.clone(); + if (mesh.material && absolute) { + invertWinding = mesh.material.sideOrientation === 0; + } + } + else { + // eslint-disable-next-line no-throw-literal + throw "BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh"; + } + const indices = mesh.getIndices(), positions = mesh.getVerticesData(VertexBuffer.PositionKind), normals = mesh.getVerticesData(VertexBuffer.NormalKind), uvs = mesh.getVerticesData(VertexBuffer.UVKind), vertColors = mesh.getVerticesData(VertexBuffer.ColorKind); + if (indices === null) { + // eslint-disable-next-line no-throw-literal + throw "BABYLON.CSG: Mesh has no indices"; + } + if (positions === null) { + // eslint-disable-next-line no-throw-literal + throw "BABYLON.CSG: Mesh has no positions"; + } + if (normals === null) { + // eslint-disable-next-line no-throw-literal + throw "BABYLON.CSG: Mesh has no normals"; + } + const subMeshes = mesh.subMeshes; + if (!subMeshes) { + // eslint-disable-next-line no-throw-literal + throw "BABYLON.CSG: Mesh has no submeshes"; + } + for (let sm = 0, sml = subMeshes.length; sm < sml; sm++) { + for (let i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) { + vertices = []; + for (let j = 0; j < 3; j++) { + const indexIndices = j === 0 ? i + j : invertWinding ? i + 3 - j : i + j; + const sourceNormal = new Vector3(normals[indices[indexIndices] * 3], normals[indices[indexIndices] * 3 + 1], normals[indices[indexIndices] * 3 + 2]); + if (uvs) { + uv = new Vector2(uvs[indices[indexIndices] * 2], uvs[indices[indexIndices] * 2 + 1]); + } + if (vertColors) { + vertColor = new Color4(vertColors[indices[indexIndices] * 4], vertColors[indices[indexIndices] * 4 + 1], vertColors[indices[indexIndices] * 4 + 2], vertColors[indices[indexIndices] * 4 + 3]); + } + const sourcePosition = new Vector3(positions[indices[indexIndices] * 3], positions[indices[indexIndices] * 3 + 1], positions[indices[indexIndices] * 3 + 2]); + position = Vector3.TransformCoordinates(sourcePosition, matrix); + normal = Vector3.TransformNormal(sourceNormal, matrix); + vertex = new Vertex(position, normal, uv, vertColor); + vertices.push(vertex); + } + polygon = new CSGPolygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex }); + // To handle the case of degenerated triangle + // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated + if (polygon.plane) { + polygons.push(polygon); + } + } + } + const csg = CSG._FromPolygons(polygons); + csg.matrix = absolute ? Matrix.Identity() : matrix; + csg.position = absolute ? Vector3.Zero() : meshPosition; + csg.rotation = absolute ? Vector3.Zero() : meshRotation; + csg.scaling = absolute ? Vector3.One() : meshScaling; + csg.rotationQuaternion = absolute && meshRotationQuaternion ? Quaternion.Identity() : meshRotationQuaternion; + currentCSGMeshId++; + return csg; + } + /** + * Construct a CSG solid from a list of `CSG.Polygon` instances. + * @param polygons Polygons used to construct a CSG solid + * @returns A new CSG solid + */ + static _FromPolygons(polygons) { + const csg = new CSG(); + csg._polygons = polygons; + return csg; + } + /** + * Clones, or makes a deep copy, of the CSG + * @returns A new CSG + */ + clone() { + const csg = new CSG(); + csg._polygons = this._polygons.map((p) => p.clone()); + csg.copyTransformAttributes(this); + return csg; + } + /** + * Unions this CSG with another CSG + * @param csg The CSG to union against this CSG + * @returns The unioned CSG + */ + union(csg) { + const a = new Node$1(this.clone()._polygons); + const b = new Node$1(csg.clone()._polygons); + a.clipTo(b); + b.clipTo(a); + b.invert(); + b.clipTo(a); + b.invert(); + a.build(b.allPolygons()); + return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this); + } + /** + * Unions this CSG with another CSG in place + * @param csg The CSG to union against this CSG + */ + unionInPlace(csg) { + const a = new Node$1(this._polygons); + const b = new Node$1(csg._polygons); + a.clipTo(b); + b.clipTo(a); + b.invert(); + b.clipTo(a); + b.invert(); + a.build(b.allPolygons()); + this._polygons = a.allPolygons(); + } + /** + * Subtracts this CSG with another CSG + * @param csg The CSG to subtract against this CSG + * @returns A new CSG + */ + subtract(csg) { + const a = new Node$1(this.clone()._polygons); + const b = new Node$1(csg.clone()._polygons); + a.invert(); + a.clipTo(b); + b.clipTo(a); + b.invert(); + b.clipTo(a); + b.invert(); + a.build(b.allPolygons()); + a.invert(); + return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this); + } + /** + * Subtracts this CSG with another CSG in place + * @param csg The CSG to subtract against this CSG + */ + subtractInPlace(csg) { + const a = new Node$1(this._polygons); + const b = new Node$1(csg._polygons); + a.invert(); + a.clipTo(b); + b.clipTo(a); + b.invert(); + b.clipTo(a); + b.invert(); + a.build(b.allPolygons()); + a.invert(); + this._polygons = a.allPolygons(); + } + /** + * Intersect this CSG with another CSG + * @param csg The CSG to intersect against this CSG + * @returns A new CSG + */ + intersect(csg) { + const a = new Node$1(this.clone()._polygons); + const b = new Node$1(csg.clone()._polygons); + a.invert(); + b.clipTo(a); + b.invert(); + a.clipTo(b); + b.clipTo(a); + a.build(b.allPolygons()); + a.invert(); + return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this); + } + /** + * Intersects this CSG with another CSG in place + * @param csg The CSG to intersect against this CSG + */ + intersectInPlace(csg) { + const a = new Node$1(this._polygons); + const b = new Node$1(csg._polygons); + a.invert(); + b.clipTo(a); + b.invert(); + a.clipTo(b); + b.clipTo(a); + a.build(b.allPolygons()); + a.invert(); + this._polygons = a.allPolygons(); + } + /** + * Return a new CSG solid with solid and empty space switched. This solid is + * not modified. + * @returns A new CSG solid with solid and empty space switched + */ + inverse() { + const csg = this.clone(); + csg.inverseInPlace(); + return csg; + } + /** + * Inverses the CSG in place + */ + inverseInPlace() { + this._polygons.map((p) => { + p.flip(); + }); + } + /** + * This is used to keep meshes transformations so they can be restored + * when we build back a Babylon Mesh + * NB : All CSG operations are performed in world coordinates + * @param csg The CSG to copy the transform attributes from + * @returns This CSG + */ + copyTransformAttributes(csg) { + this.matrix = csg.matrix; + this.position = csg.position; + this.rotation = csg.rotation; + this.scaling = csg.scaling; + this.rotationQuaternion = csg.rotationQuaternion; + return this; + } + /** + * Build vertex data from CSG + * Coordinates here are in world space + * @param onBeforePolygonProcessing called before each polygon is being processed + * @param onAfterPolygonProcessing called after each polygon has been processed + * @returns the final vertex data + */ + toVertexData(onBeforePolygonProcessing = null, onAfterPolygonProcessing = null) { + const matrix = this.matrix.clone(); + matrix.invert(); + const polygons = this._polygons; + const vertices = []; + const indices = []; + const normals = []; + let uvs = null; + let vertColors = null; + const vertex = Vector3.Zero(); + const normal = Vector3.Zero(); + const uv = Vector2.Zero(); + const vertColor = new Color4(0, 0, 0, 0); + const polygonIndices = [0, 0, 0]; + const vertice_dict = {}; + let vertex_idx; + for (let i = 0, il = polygons.length; i < il; i++) { + const polygon = polygons[i]; + if (onBeforePolygonProcessing) { + onBeforePolygonProcessing(polygon); + } + for (let j = 2, jl = polygon.vertices.length; j < jl; j++) { + polygonIndices[0] = 0; + polygonIndices[1] = j - 1; + polygonIndices[2] = j; + for (let k = 0; k < 3; k++) { + vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos); + normal.copyFrom(polygon.vertices[polygonIndices[k]].normal); + if (polygon.vertices[polygonIndices[k]].uv) { + if (!uvs) { + uvs = []; + } + uv.copyFrom(polygon.vertices[polygonIndices[k]].uv); + } + if (polygon.vertices[polygonIndices[k]].vertColor) { + if (!vertColors) { + vertColors = []; + } + vertColor.copyFrom(polygon.vertices[polygonIndices[k]].vertColor); + } + const localVertex = Vector3.TransformCoordinates(vertex, matrix); + const localNormal = Vector3.TransformNormal(normal, matrix); + vertex_idx = vertice_dict[localVertex.x + "," + localVertex.y + "," + localVertex.z]; + let areUvsDifferent = false; + if (uvs && !(uvs[vertex_idx * 2] === uv.x || uvs[vertex_idx * 2 + 1] === uv.y)) { + areUvsDifferent = true; + } + let areColorsDifferent = false; + if (vertColors && + !(vertColors[vertex_idx * 4] === vertColor.r || + vertColors[vertex_idx * 4 + 1] === vertColor.g || + vertColors[vertex_idx * 4 + 2] === vertColor.b || + vertColors[vertex_idx * 4 + 3] === vertColor.a)) { + areColorsDifferent = true; + } + // Check if 2 points can be merged + if (!(typeof vertex_idx !== "undefined" && + normals[vertex_idx * 3] === localNormal.x && + normals[vertex_idx * 3 + 1] === localNormal.y && + normals[vertex_idx * 3 + 2] === localNormal.z) || + areUvsDifferent || + areColorsDifferent) { + vertices.push(localVertex.x, localVertex.y, localVertex.z); + if (uvs) { + uvs.push(uv.x, uv.y); + } + normals.push(normal.x, normal.y, normal.z); + if (vertColors) { + vertColors.push(vertColor.r, vertColor.g, vertColor.b, vertColor.a); + } + vertex_idx = vertice_dict[localVertex.x + "," + localVertex.y + "," + localVertex.z] = vertices.length / 3 - 1; + } + indices.push(vertex_idx); + if (onAfterPolygonProcessing) { + onAfterPolygonProcessing(); + } + } + } + } + const result = new VertexData(); + result.positions = vertices; + result.normals = normals; + if (uvs) { + result.uvs = uvs; + } + if (vertColors) { + result.colors = vertColors; + } + result.indices = indices; + return result; + } + /** + * Build Raw mesh from CSG + * Coordinates here are in world space + * @param name The name of the mesh geometry + * @param scene The Scene + * @param keepSubMeshes Specifies if the submeshes should be kept + * @returns A new Mesh + */ + buildMeshGeometry(name, scene, keepSubMeshes) { + const mesh = new Mesh(name, scene); + const polygons = this._polygons; + let currentIndex = 0; + const subMeshDict = {}; + let subMeshObj; + if (keepSubMeshes) { + // Sort Polygons, since subMeshes are indices range + polygons.sort((a, b) => { + if (a.shared.meshId === b.shared.meshId) { + return a.shared.subMeshId - b.shared.subMeshId; + } + else { + return a.shared.meshId - b.shared.meshId; + } + }); + } + const vertexData = this.toVertexData((polygon) => { + // Building SubMeshes + if (!subMeshDict[polygon.shared.meshId]) { + subMeshDict[polygon.shared.meshId] = {}; + } + if (!subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId]) { + subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId] = { + indexStart: +Infinity, + indexEnd: -Infinity, + materialIndex: polygon.shared.materialIndex, + }; + } + subMeshObj = subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId]; + }, () => { + subMeshObj.indexStart = Math.min(currentIndex, subMeshObj.indexStart); + subMeshObj.indexEnd = Math.max(currentIndex, subMeshObj.indexEnd); + currentIndex++; + }); + vertexData.applyToMesh(mesh); + if (keepSubMeshes) { + // We offset the materialIndex by the previous number of materials in the CSG mixed meshes + let materialIndexOffset = 0, materialMaxIndex; + mesh.subMeshes = []; + for (const m in subMeshDict) { + materialMaxIndex = -1; + for (const sm in subMeshDict[m]) { + subMeshObj = subMeshDict[m][sm]; + SubMesh.CreateFromIndices(subMeshObj.materialIndex + materialIndexOffset, subMeshObj.indexStart, subMeshObj.indexEnd - subMeshObj.indexStart + 1, mesh); + materialMaxIndex = Math.max(subMeshObj.materialIndex, materialMaxIndex); + } + materialIndexOffset += ++materialMaxIndex; + } + } + return mesh; + } + /** + * Build Mesh from CSG taking material and transforms into account + * @param name The name of the Mesh + * @param material The material of the Mesh + * @param scene The Scene + * @param keepSubMeshes Specifies if submeshes should be kept + * @returns The new Mesh + */ + toMesh(name, material = null, scene, keepSubMeshes) { + const mesh = this.buildMeshGeometry(name, scene, keepSubMeshes); + mesh.material = material; + mesh.position.copyFrom(this.position); + mesh.rotation.copyFrom(this.rotation); + if (this.rotationQuaternion) { + mesh.rotationQuaternion = this.rotationQuaternion.clone(); + } + mesh.scaling.copyFrom(this.scaling); + mesh.computeWorldMatrix(true); + return mesh; + } +} + +Mesh._TrailMeshParser = (parsedMesh, scene) => { + return TrailMesh.Parse(parsedMesh, scene); +}; +/** + * Class used to create a trail following a mesh + */ +class TrailMesh extends Mesh { + /** @internal */ + constructor(name, generator, scene, diameterOrOptions, length = 60, autoStart = true) { + super(name, scene); + this._sectionPolygonPointsCount = 4; + this._running = false; + this._generator = generator; + if (typeof diameterOrOptions === "object" && diameterOrOptions !== null) { + this.diameter = diameterOrOptions.diameter || 1; + this._length = diameterOrOptions.length || 60; + this._segments = diameterOrOptions.segments ? (diameterOrOptions.segments > this._length ? this._length : diameterOrOptions.segments) : this._length; + this._sectionPolygonPointsCount = diameterOrOptions.sections || 4; + this._doNotTaper = diameterOrOptions.doNotTaper || false; + this._autoStart = diameterOrOptions.autoStart || true; + } + else { + this.diameter = diameterOrOptions || 1; + this._length = length; + this._segments = this._length; + this._doNotTaper = false; + this._autoStart = autoStart; + } + this._sectionVectors = []; + this._sectionNormalVectors = []; + for (let i = 0; i <= this._sectionPolygonPointsCount; i++) { + this._sectionVectors[i] = Vector3.Zero(); + this._sectionNormalVectors[i] = Vector3.Zero(); + } + this._createMesh(); + } + /** + * "TrailMesh" + * @returns "TrailMesh" + */ + getClassName() { + return "TrailMesh"; + } + _createMesh() { + const data = new VertexData(); + const positions = []; + const normals = []; + const indices = []; + const uvs = []; + let meshCenter = Vector3.Zero(); + if (this._generator instanceof AbstractMesh && this._generator.hasBoundingInfo) { + meshCenter = this._generator.getBoundingInfo().boundingBox.centerWorld; + } + else { + meshCenter = this._generator.absolutePosition; + } + const alpha = (2 * Math.PI) / this._sectionPolygonPointsCount; + for (let i = 0; i <= this._sectionPolygonPointsCount; i++) { + const angle = i !== this._sectionPolygonPointsCount ? i * alpha : 0; + positions.push(meshCenter.x + Math.cos(angle) * this.diameter, meshCenter.y + Math.sin(angle) * this.diameter, meshCenter.z); + uvs.push(i / this._sectionPolygonPointsCount, 0); + } + for (let i = 1; i <= this._segments; i++) { + for (let j = 0; j <= this._sectionPolygonPointsCount; j++) { + const angle = j !== this._sectionPolygonPointsCount ? j * alpha : 0; + positions.push(meshCenter.x + Math.cos(angle) * this.diameter, meshCenter.y + Math.sin(angle) * this.diameter, meshCenter.z); + uvs.push(j / this._sectionPolygonPointsCount, i / this._segments); + } + const l = positions.length / 3 - 2 * (this._sectionPolygonPointsCount + 1); + for (let j = 0; j <= this._sectionPolygonPointsCount; j++) { + indices.push(l + j, l + j + this._sectionPolygonPointsCount, l + j + this._sectionPolygonPointsCount + 1); + indices.push(l + j, l + j + this._sectionPolygonPointsCount + 1, l + j + 1); + } + } + VertexData.ComputeNormals(positions, indices, normals); + data.positions = positions; + data.normals = normals; + data.indices = indices; + data.uvs = uvs; + data.applyToMesh(this, true); + if (this._autoStart) { + this.start(); + } + } + _updateSectionVectors() { + const wm = this._generator.getWorldMatrix(); + const alpha = (2 * Math.PI) / this._sectionPolygonPointsCount; + for (let i = 0; i <= this._sectionPolygonPointsCount; i++) { + const angle = i !== this._sectionPolygonPointsCount ? i * alpha : 0; + this._sectionVectors[i].copyFromFloats(Math.cos(angle) * this.diameter, Math.sin(angle) * this.diameter, 0); + this._sectionNormalVectors[i].copyFromFloats(Math.cos(angle), Math.sin(angle), 0); + Vector3.TransformCoordinatesToRef(this._sectionVectors[i], wm, this._sectionVectors[i]); + Vector3.TransformNormalToRef(this._sectionNormalVectors[i], wm, this._sectionNormalVectors[i]); + } + } + /** + * Start trailing mesh. + */ + start() { + if (!this._running) { + this._running = true; + this._beforeRenderObserver = this.getScene().onBeforeRenderObservable.add(() => { + this.update(); + }); + } + } + /** + * Stop trailing mesh. + */ + stop() { + if (this._beforeRenderObserver && this._running) { + this._running = false; + this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver); + } + } + /** + * Update trailing mesh geometry. + */ + update() { + const positions = this.getVerticesData(VertexBuffer.PositionKind); + const normals = this.getVerticesData(VertexBuffer.NormalKind); + const index = 3 * (this._sectionPolygonPointsCount + 1); + if (positions && normals) { + if (this._doNotTaper) { + for (let i = index; i < positions.length; i++) { + positions[i - index] = Lerp(positions[i - index], positions[i], this._segments / this._length); + } + } + else { + for (let i = index; i < positions.length; i++) { + positions[i - index] = Lerp(positions[i - index], positions[i], this._segments / this._length) - (normals[i] / this._length) * this.diameter; + } + } + for (let i = index; i < normals.length; i++) { + normals[i - index] = Lerp(normals[i - index], normals[i], this._segments / this._length); + } + this._updateSectionVectors(); + const l = positions.length - 3 * (this._sectionPolygonPointsCount + 1); + for (let i = 0; i <= this._sectionPolygonPointsCount; i++) { + positions[l + 3 * i] = this._sectionVectors[i].x; + positions[l + 3 * i + 1] = this._sectionVectors[i].y; + positions[l + 3 * i + 2] = this._sectionVectors[i].z; + normals[l + 3 * i] = this._sectionNormalVectors[i].x; + normals[l + 3 * i + 1] = this._sectionNormalVectors[i].y; + normals[l + 3 * i + 2] = this._sectionNormalVectors[i].z; + } + this.updateVerticesData(VertexBuffer.PositionKind, positions, true, false); + this.updateVerticesData(VertexBuffer.NormalKind, normals, true, false); + } + } + /** + * Reset trailing mesh geometry. + */ + reset() { + const positions = this.getVerticesData(VertexBuffer.PositionKind); + const normals = this.getVerticesData(VertexBuffer.NormalKind); + if (positions && normals) { + this._updateSectionVectors(); + for (let i = 0; i <= this._segments; i++) { + const l = 3 * i * (this._sectionPolygonPointsCount + 1); + for (let j = 0; j <= this._sectionPolygonPointsCount; j++) { + positions[l + 3 * j] = this._sectionVectors[j].x; + positions[l + 3 * j + 1] = this._sectionVectors[j].y; + positions[l + 3 * j + 2] = this._sectionVectors[j].z; + normals[l + 3 * j] = this._sectionNormalVectors[j].x; + normals[l + 3 * j + 1] = this._sectionNormalVectors[j].y; + normals[l + 3 * j + 2] = this._sectionNormalVectors[j].z; + } + } + this.updateVerticesData(VertexBuffer.PositionKind, positions, true, false); + this.updateVerticesData(VertexBuffer.NormalKind, normals, true, false); + } + } + /** + * Returns a new TrailMesh object. + * @param name is a string, the name given to the new mesh + * @param newGenerator use new generator object for cloned trail mesh + * @returns a new mesh + */ + clone(name = "", newGenerator) { + const options = { + diameter: this.diameter, + length: this._length, + segments: this._segments, + sections: this._sectionPolygonPointsCount, + doNotTaper: this._doNotTaper, + autoStart: this._autoStart, + }; + return new TrailMesh(name, newGenerator ?? this._generator, this.getScene(), options); + } + /** + * Serializes this trail mesh + * @param serializationObject object to write serialization to + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.generatorId = this._generator.id; + } + /** + * Parses a serialized trail mesh + * @param parsedMesh the serialized mesh + * @param scene the scene to create the trail mesh in + * @returns the created trail mesh + */ + static Parse(parsedMesh, scene) { + const generator = scene.getLastMeshById(parsedMesh.generatorId) ?? scene.getLastTransformNodeById(parsedMesh.generatorId); + if (!generator) { + throw new Error("TrailMesh: generator not found with ID " + parsedMesh.generatorId); + } + const options = { + diameter: parsedMesh.diameter ?? parsedMesh._diameter, + length: parsedMesh._length, + segments: parsedMesh._segments, + sections: parsedMesh._sectionPolygonPointsCount, + doNotTaper: parsedMesh._doNotTaper, + autoStart: parsedMesh._autoStart, + }; + return new TrailMesh(parsedMesh.name, generator, scene, options); + } +} + +/** + * Queue used to order the simplification tasks + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes + */ +class SimplificationQueue { + /** + * Creates a new queue + */ + constructor() { + this.running = false; + this._simplificationArray = []; + } + /** + * Adds a new simplification task + * @param task defines a task to add + */ + addTask(task) { + this._simplificationArray.push(task); + } + /** + * Execute next task + */ + executeNext() { + const task = this._simplificationArray.pop(); + if (task) { + this.running = true; + this.runSimplification(task); + } + else { + this.running = false; + } + } + /** + * Execute a simplification task + * @param task defines the task to run + */ + runSimplification(task) { + if (task.parallelProcessing) { + //parallel simplifier + task.settings.forEach((setting) => { + const simplifier = this._getSimplifier(task); + simplifier.simplify(setting, (newMesh) => { + if (setting.distance !== undefined) { + task.mesh.addLODLevel(setting.distance, newMesh); + } + newMesh.isVisible = true; + //check if it is the last + if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) { + //all done, run the success callback. + task.successCallback(); + } + this.executeNext(); + }); + }); + } + else { + //single simplifier. + const simplifier = this._getSimplifier(task); + const runDecimation = (setting, callback) => { + simplifier.simplify(setting, (newMesh) => { + if (setting.distance !== undefined) { + task.mesh.addLODLevel(setting.distance, newMesh); + } + newMesh.isVisible = true; + //run the next quality level + callback(); + }); + }; + AsyncLoop.Run(task.settings.length, (loop) => { + runDecimation(task.settings[loop.index], () => { + loop.executeNext(); + }); + }, () => { + //execution ended, run the success callback. + if (task.successCallback) { + task.successCallback(); + } + this.executeNext(); + }); + } + } + _getSimplifier(task) { + switch (task.simplificationType) { + case 0 /* SimplificationType.QUADRATIC */: + default: + return new QuadraticErrorSimplification(task.mesh); + } + } +} +/** + * The implemented types of simplification + * At the moment only Quadratic Error Decimation is implemented + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes + */ +var SimplificationType; +(function (SimplificationType) { + /** Quadratic error decimation */ + SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC"; +})(SimplificationType || (SimplificationType = {})); +class DecimationTriangle { + constructor(_vertices) { + this._vertices = _vertices; + this.error = new Array(4); + this.deleted = false; + this.isDirty = false; + this.deletePending = false; + this.borderFactor = 0; + } +} +class DecimationVertex { + constructor(position, id) { + this.position = position; + this.id = id; + this.isBorder = true; + this.q = new QuadraticMatrix(); + this.triangleCount = 0; + this.triangleStart = 0; + this.originalOffsets = []; + } + updatePosition(newPosition) { + this.position.copyFrom(newPosition); + } +} +class QuadraticMatrix { + constructor(data) { + this.data = new Array(10); + for (let i = 0; i < 10; ++i) { + if (data && data[i]) { + this.data[i] = data[i]; + } + else { + this.data[i] = 0; + } + } + } + det(a11, a12, a13, a21, a22, a23, a31, a32, a33) { + const det = this.data[a11] * this.data[a22] * this.data[a33] + + this.data[a13] * this.data[a21] * this.data[a32] + + this.data[a12] * this.data[a23] * this.data[a31] - + this.data[a13] * this.data[a22] * this.data[a31] - + this.data[a11] * this.data[a23] * this.data[a32] - + this.data[a12] * this.data[a21] * this.data[a33]; + return det; + } + addInPlace(matrix) { + for (let i = 0; i < 10; ++i) { + this.data[i] += matrix.data[i]; + } + } + addArrayInPlace(data) { + for (let i = 0; i < 10; ++i) { + this.data[i] += data[i]; + } + } + add(matrix) { + const m = new QuadraticMatrix(); + for (let i = 0; i < 10; ++i) { + m.data[i] = this.data[i] + matrix.data[i]; + } + return m; + } + static FromData(a, b, c, d) { + return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d)); + } + //returning an array to avoid garbage collection + static DataFromNumbers(a, b, c, d) { + return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d]; + } +} +class Reference { + constructor(vertexId, triangleId) { + this.vertexId = vertexId; + this.triangleId = triangleId; + } +} +/** + * An implementation of the Quadratic Error simplification algorithm. + * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf + * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS + * @author RaananW + * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes + */ +class QuadraticErrorSimplification { + /** + * Creates a new QuadraticErrorSimplification + * @param _mesh defines the target mesh + */ + constructor(_mesh) { + this._mesh = _mesh; + /** Gets or sets the number pf sync iterations */ + this.syncIterations = 5000; + this.aggressiveness = 7; + this.decimationIterations = 100; + this.boundingBoxEpsilon = Epsilon; + } + /** + * Simplification of a given mesh according to the given settings. + * Since this requires computation, it is assumed that the function runs async. + * @param settings The settings of the simplification, including quality and distance + * @param successCallback A callback that will be called after the mesh was simplified. + */ + simplify(settings, successCallback) { + this._initDecimatedMesh(); + //iterating through the submeshes array, one after the other. + AsyncLoop.Run(this._mesh.subMeshes.length, (loop) => { + this._initWithMesh(loop.index, () => { + this._runDecimation(settings, loop.index, () => { + loop.executeNext(); + }); + }, settings.optimizeMesh); + }, () => { + setTimeout(() => { + successCallback(this._reconstructedMesh); + }, 0); + }); + } + _runDecimation(settings, submeshIndex, successCallback) { + const targetCount = ~~(this._triangles.length * settings.quality); + let deletedTriangles = 0; + const triangleCount = this._triangles.length; + const iterationFunction = (iteration, callback) => { + setTimeout(() => { + if (iteration % 5 === 0) { + this._updateMesh(iteration === 0); + } + for (let i = 0; i < this._triangles.length; ++i) { + this._triangles[i].isDirty = false; + } + const threshold = 0.000000001 * Math.pow(iteration + 3, this.aggressiveness); + const trianglesIterator = (i) => { + const tIdx = ~~((this._triangles.length / 2 + i) % this._triangles.length); + const t = this._triangles[tIdx]; + if (!t) { + return; + } + if (t.error[3] > threshold || t.deleted || t.isDirty) { + return; + } + for (let j = 0; j < 3; ++j) { + if (t.error[j] < threshold) { + const deleted0 = []; + const deleted1 = []; + const v0 = t._vertices[j]; + const v1 = t._vertices[(j + 1) % 3]; + if (v0.isBorder || v1.isBorder) { + continue; + } + const p = Vector3.Zero(); + // var n = Vector3.Zero(); + // var uv = Vector2.Zero(); + // var color = new Color4(0, 0, 0, 1); + this._calculateError(v0, v1, p); + const delTr = []; + if (this._isFlipped(v0, v1, p, deleted0, delTr)) { + continue; + } + if (this._isFlipped(v1, v0, p, deleted1, delTr)) { + continue; + } + if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) { + continue; + } + const uniqueArray = []; + delTr.forEach((deletedT) => { + if (uniqueArray.indexOf(deletedT) === -1) { + deletedT.deletePending = true; + uniqueArray.push(deletedT); + } + }); + if (uniqueArray.length % 2 !== 0) { + continue; + } + v0.q = v1.q.add(v0.q); + v0.updatePosition(p); + const tStart = this._references.length; + deletedTriangles = this._updateTriangles(v0, v0, deleted0, deletedTriangles); + deletedTriangles = this._updateTriangles(v0, v1, deleted1, deletedTriangles); + const tCount = this._references.length - tStart; + if (tCount <= v0.triangleCount) { + if (tCount) { + for (let c = 0; c < tCount; c++) { + this._references[v0.triangleStart + c] = this._references[tStart + c]; + } + } + } + else { + v0.triangleStart = tStart; + } + v0.triangleCount = tCount; + break; + } + } + }; + AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, trianglesIterator, callback, () => { + return triangleCount - deletedTriangles <= targetCount; + }); + }, 0); + }; + AsyncLoop.Run(this.decimationIterations, (loop) => { + if (triangleCount - deletedTriangles <= targetCount) { + loop.breakLoop(); + } + else { + iterationFunction(loop.index, () => { + loop.executeNext(); + }); + } + }, () => { + setTimeout(() => { + //reconstruct this part of the mesh + this._reconstructMesh(submeshIndex); + successCallback(); + }, 0); + }); + } + _initWithMesh(submeshIndex, callback, optimizeMesh) { + this._vertices = []; + this._triangles = []; + const positionData = this._mesh.getVerticesData(VertexBuffer.PositionKind); + const indices = this._mesh.getIndices(); + const submesh = this._mesh.subMeshes[submeshIndex]; + const findInVertices = (positionToSearch) => { + if (optimizeMesh) { + for (let ii = 0; ii < this._vertices.length; ++ii) { + if (this._vertices[ii].position.equalsWithEpsilon(positionToSearch, 0.0001)) { + return this._vertices[ii]; + } + } + } + return null; + }; + const vertexReferences = []; + const vertexInit = (i) => { + if (!positionData) { + return; + } + const offset = i + submesh.verticesStart; + const position = Vector3.FromArray(positionData, offset * 3); + const vertex = findInVertices(position) || new DecimationVertex(position, this._vertices.length); + vertex.originalOffsets.push(offset); + if (vertex.id === this._vertices.length) { + this._vertices.push(vertex); + } + vertexReferences.push(vertex.id); + }; + //var totalVertices = mesh.getTotalVertices(); + const totalVertices = submesh.verticesCount; + AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, () => { + const indicesInit = (i) => { + if (!indices) { + return; + } + const offset = submesh.indexStart / 3 + i; + const pos = offset * 3; + const i0 = indices[pos + 0]; + const i1 = indices[pos + 1]; + const i2 = indices[pos + 2]; + const v0 = this._vertices[vertexReferences[i0 - submesh.verticesStart]]; + const v1 = this._vertices[vertexReferences[i1 - submesh.verticesStart]]; + const v2 = this._vertices[vertexReferences[i2 - submesh.verticesStart]]; + const triangle = new DecimationTriangle([v0, v1, v2]); + triangle.originalOffset = pos; + this._triangles.push(triangle); + }; + AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, this.syncIterations, indicesInit, () => { + this._init(callback); + }); + }); + } + _init(callback) { + const triangleInit1 = (i) => { + const t = this._triangles[i]; + t.normal = Vector3.Cross(t._vertices[1].position.subtract(t._vertices[0].position), t._vertices[2].position.subtract(t._vertices[0].position)).normalize(); + for (let j = 0; j < 3; j++) { + t._vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -Vector3.Dot(t.normal, t._vertices[0].position))); + } + }; + AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, triangleInit1, () => { + const triangleInit2 = (i) => { + const t = this._triangles[i]; + for (let j = 0; j < 3; ++j) { + t.error[j] = this._calculateError(t._vertices[j], t._vertices[(j + 1) % 3]); + } + t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]); + }; + AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, triangleInit2, () => { + callback(); + }); + }); + } + _reconstructMesh(submeshIndex) { + const newTriangles = []; + let i; + for (i = 0; i < this._vertices.length; ++i) { + this._vertices[i].triangleCount = 0; + } + let t; + let j; + for (i = 0; i < this._triangles.length; ++i) { + if (!this._triangles[i].deleted) { + t = this._triangles[i]; + for (j = 0; j < 3; ++j) { + t._vertices[j].triangleCount = 1; + } + newTriangles.push(t); + } + } + const newPositionData = (this._reconstructedMesh.getVerticesData(VertexBuffer.PositionKind) || []); + const newNormalData = (this._reconstructedMesh.getVerticesData(VertexBuffer.NormalKind) || []); + const newUVsData = (this._reconstructedMesh.getVerticesData(VertexBuffer.UVKind) || []); + const newColorsData = (this._reconstructedMesh.getVerticesData(VertexBuffer.ColorKind) || []); + const normalData = this._mesh.getVerticesData(VertexBuffer.NormalKind); + const uvs = this._mesh.getVerticesData(VertexBuffer.UVKind); + const colorsData = this._mesh.getVerticesData(VertexBuffer.ColorKind); + let vertexCount = 0; + for (i = 0; i < this._vertices.length; ++i) { + const vertex = this._vertices[i]; + vertex.id = vertexCount; + if (vertex.triangleCount) { + vertex.originalOffsets.forEach((originalOffset) => { + newPositionData.push(vertex.position.x); + newPositionData.push(vertex.position.y); + newPositionData.push(vertex.position.z); + if (normalData && normalData.length) { + newNormalData.push(normalData[originalOffset * 3]); + newNormalData.push(normalData[originalOffset * 3 + 1]); + newNormalData.push(normalData[originalOffset * 3 + 2]); + } + if (uvs && uvs.length) { + newUVsData.push(uvs[originalOffset * 2]); + newUVsData.push(uvs[originalOffset * 2 + 1]); + } + if (colorsData && colorsData.length) { + newColorsData.push(colorsData[originalOffset * 4]); + newColorsData.push(colorsData[originalOffset * 4 + 1]); + newColorsData.push(colorsData[originalOffset * 4 + 2]); + newColorsData.push(colorsData[originalOffset * 4 + 3]); + } + ++vertexCount; + }); + } + } + const startingIndex = this._reconstructedMesh.getTotalIndices(); + const startingVertex = this._reconstructedMesh.getTotalVertices(); + const submeshesArray = this._reconstructedMesh.subMeshes; + this._reconstructedMesh.subMeshes = []; + const newIndicesArray = this._reconstructedMesh.getIndices(); //[]; + const originalIndices = this._mesh.getIndices(); + for (i = 0; i < newTriangles.length; ++i) { + t = newTriangles[i]; //now get the new referencing point for each vertex + [0, 1, 2].forEach((idx) => { + const id = originalIndices[t.originalOffset + idx]; + let offset = t._vertices[idx].originalOffsets.indexOf(id); + if (offset < 0) { + offset = 0; + } + newIndicesArray.push(t._vertices[idx].id + offset + startingVertex); + }); + } + //overwriting the old vertex buffers and indices. + this._reconstructedMesh.setIndices(newIndicesArray); + this._reconstructedMesh.setVerticesData(VertexBuffer.PositionKind, newPositionData); + if (newNormalData.length > 0) { + this._reconstructedMesh.setVerticesData(VertexBuffer.NormalKind, newNormalData); + } + if (newUVsData.length > 0) { + this._reconstructedMesh.setVerticesData(VertexBuffer.UVKind, newUVsData); + } + if (newColorsData.length > 0) { + this._reconstructedMesh.setVerticesData(VertexBuffer.ColorKind, newColorsData); + } + //create submesh + const originalSubmesh = this._mesh.subMeshes[submeshIndex]; + if (submeshIndex > 0) { + this._reconstructedMesh.subMeshes = []; + submeshesArray.forEach((submesh) => { + SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, + /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh()); + }); + SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, + /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh); + } + } + _initDecimatedMesh() { + this._reconstructedMesh = new Mesh(this._mesh.name + "Decimated", this._mesh.getScene()); + this._reconstructedMesh.material = this._mesh.material; + this._reconstructedMesh.parent = this._mesh.parent; + this._reconstructedMesh.isVisible = false; + this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId; + } + _isFlipped(vertex1, vertex2, point, deletedArray, delTr) { + for (let i = 0; i < vertex1.triangleCount; ++i) { + const t = this._triangles[this._references[vertex1.triangleStart + i].triangleId]; + if (t.deleted) { + continue; + } + const s = this._references[vertex1.triangleStart + i].vertexId; + const v1 = t._vertices[(s + 1) % 3]; + const v2 = t._vertices[(s + 2) % 3]; + if (v1 === vertex2 || v2 === vertex2) { + deletedArray[i] = true; + delTr.push(t); + continue; + } + let d1 = v1.position.subtract(point); + d1 = d1.normalize(); + let d2 = v2.position.subtract(point); + d2 = d2.normalize(); + if (Math.abs(Vector3.Dot(d1, d2)) > 0.999) { + return true; + } + const normal = Vector3.Cross(d1, d2).normalize(); + deletedArray[i] = false; + if (Vector3.Dot(normal, t.normal) < 0.2) { + return true; + } + } + return false; + } + _updateTriangles(origVertex, vertex, deletedArray, deletedTriangles) { + let newDeleted = deletedTriangles; + for (let i = 0; i < vertex.triangleCount; ++i) { + const ref = this._references[vertex.triangleStart + i]; + const t = this._triangles[ref.triangleId]; + if (t.deleted) { + continue; + } + if (deletedArray[i] && t.deletePending) { + t.deleted = true; + newDeleted++; + continue; + } + t._vertices[ref.vertexId] = origVertex; + t.isDirty = true; + t.error[0] = this._calculateError(t._vertices[0], t._vertices[1]) + t.borderFactor / 2; + t.error[1] = this._calculateError(t._vertices[1], t._vertices[2]) + t.borderFactor / 2; + t.error[2] = this._calculateError(t._vertices[2], t._vertices[0]) + t.borderFactor / 2; + t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]); + this._references.push(ref); + } + return newDeleted; + } + _identifyBorder() { + for (let i = 0; i < this._vertices.length; ++i) { + const vCount = []; + const vId = []; + const v = this._vertices[i]; + let j; + for (j = 0; j < v.triangleCount; ++j) { + const triangle = this._triangles[this._references[v.triangleStart + j].triangleId]; + for (let ii = 0; ii < 3; ii++) { + let ofs = 0; + const vv = triangle._vertices[ii]; + while (ofs < vCount.length) { + if (vId[ofs] === vv.id) { + break; + } + ++ofs; + } + if (ofs === vCount.length) { + vCount.push(1); + vId.push(vv.id); + } + else { + vCount[ofs]++; + } + } + } + for (j = 0; j < vCount.length; ++j) { + if (vCount[j] === 1) { + this._vertices[vId[j]].isBorder = true; + } + else { + this._vertices[vId[j]].isBorder = false; + } + } + } + } + _updateMesh(identifyBorders = false) { + let i; + if (!identifyBorders) { + const newTrianglesVector = []; + for (i = 0; i < this._triangles.length; ++i) { + if (!this._triangles[i].deleted) { + newTrianglesVector.push(this._triangles[i]); + } + } + this._triangles = newTrianglesVector; + } + for (i = 0; i < this._vertices.length; ++i) { + this._vertices[i].triangleCount = 0; + this._vertices[i].triangleStart = 0; + } + let t; + let j; + let v; + for (i = 0; i < this._triangles.length; ++i) { + t = this._triangles[i]; + for (j = 0; j < 3; ++j) { + v = t._vertices[j]; + v.triangleCount++; + } + } + let tStart = 0; + for (i = 0; i < this._vertices.length; ++i) { + this._vertices[i].triangleStart = tStart; + tStart += this._vertices[i].triangleCount; + this._vertices[i].triangleCount = 0; + } + const newReferences = new Array(this._triangles.length * 3); + for (i = 0; i < this._triangles.length; ++i) { + t = this._triangles[i]; + for (j = 0; j < 3; ++j) { + v = t._vertices[j]; + newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i); + v.triangleCount++; + } + } + this._references = newReferences; + if (identifyBorders) { + this._identifyBorder(); + } + } + _vertexError(q, point) { + const x = point.x; + const y = point.y; + const z = point.z; + return (q.data[0] * x * x + + 2 * q.data[1] * x * y + + 2 * q.data[2] * x * z + + 2 * q.data[3] * x + + q.data[4] * y * y + + 2 * q.data[5] * y * z + + 2 * q.data[6] * y + + q.data[7] * z * z + + 2 * q.data[8] * z + + q.data[9]); + } + _calculateError(vertex1, vertex2, pointResult) { + const q = vertex1.q.add(vertex2.q); + const border = vertex1.isBorder && vertex2.isBorder; + let error = 0; + const qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7); + if (qDet !== 0 && !border) { + if (!pointResult) { + pointResult = Vector3.Zero(); + } + pointResult.x = (-1 / qDet) * q.det(1, 2, 3, 4, 5, 6, 5, 7, 8); + pointResult.y = (1 / qDet) * q.det(0, 2, 3, 1, 5, 6, 2, 7, 8); + pointResult.z = (-1 / qDet) * q.det(0, 1, 3, 1, 4, 6, 2, 5, 8); + error = this._vertexError(q, pointResult); + } + else { + const p3 = vertex1.position.add(vertex2.position).divide(new Vector3(2, 2, 2)); + //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize(); + const error1 = this._vertexError(q, vertex1.position); + const error2 = this._vertexError(q, vertex2.position); + const error3 = this._vertexError(q, p3); + error = Math.min(error1, error2, error3); + if (error === error1) { + if (pointResult) { + pointResult.copyFrom(vertex1.position); + } + } + else if (error === error2) { + if (pointResult) { + pointResult.copyFrom(vertex2.position); + } + } + else { + if (pointResult) { + pointResult.copyFrom(p3); + } + } + } + return error; + } +} + +Object.defineProperty(Scene.prototype, "simplificationQueue", { + get: function () { + if (!this._simplificationQueue) { + this._simplificationQueue = new SimplificationQueue(); + let component = this._getComponent(SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE); + if (!component) { + component = new SimplicationQueueSceneComponent(this); + this._addComponent(component); + } + } + return this._simplificationQueue; + }, + set: function (value) { + this._simplificationQueue = value; + }, + enumerable: true, + configurable: true, +}); +Mesh.prototype.simplify = function (settings, parallelProcessing = true, simplificationType = 0 /* SimplificationType.QUADRATIC */, successCallback) { + this.getScene().simplificationQueue.addTask({ + settings: settings, + parallelProcessing: parallelProcessing, + mesh: this, + simplificationType: simplificationType, + successCallback: successCallback, + }); + return this; +}; +/** + * Defines the simplification queue scene component responsible to help scheduling the various simplification task + * created in a scene + */ +class SimplicationQueueSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpfull to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._beforeCameraUpdateStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do for this component + } + /** + * Disposes the component and the associated resources + */ + dispose() { + // Nothing to do for this component + } + _beforeCameraUpdate() { + if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) { + this.scene._simplificationQueue.executeNext(); + } + } +} + +/** + * Class used to represent a lattice + * @see [Moving lattice bounds](https://playground.babylonjs.com/#MDVD75#18) + * @see [Twist](https://playground.babylonjs.com/#MDVD75#23) + */ +class Lattice { + /** + * @returns the string "Lattice" + */ + getClassName() { + return "Lattice"; + } + /** + * Gets the resolution on x axis + */ + get resolutionX() { + return this._resolutionX; + } + /** + * Gets the resolution on y axis + */ + get resolutionY() { + return this._resolutionY; + } + /** + * Gets the resolution on z axis + */ + get resolutionZ() { + return this._resolutionZ; + } + /** + * Gets the size of the lattice along each axis in object space + * Updating the size requires you to call update afterwards + */ + get size() { + return this._size; + } + /** + * Gets the lattice position in object space + */ + get position() { + return this._position; + } + /** + * Gets the data of the lattice + */ + get data() { + return this._data; + } + /** + * Gets the size of each cell in the lattice + */ + get cellSize() { + return this._cellSize; + } + /** + * Gets the min bounds of the lattice + */ + get min() { + return this._min; + } + /** + * Gets the max bounds of the lattice + */ + get max() { + return this._max; + } + /** + * Creates a new Lattice + * @param options options for creating + */ + constructor(options) { + this._cellSize = new Vector3(); + // Cache + this._min = new Vector3(-0.5, -0.5, -0.5); + this._max = new Vector3(0.5, 0.5, 0.5); + this._localPos = new Vector3(); + this._tmpVector = new Vector3(); + this._lerpVector0 = new Vector3(); + this._lerpVector1 = new Vector3(); + this._lerpVector2 = new Vector3(); + this._lerpVector3 = new Vector3(); + this._lerpVector4 = new Vector3(); + this._lerpVector5 = new Vector3(); + const localOptions = { + resolutionX: 3, + resolutionY: 3, + resolutionZ: 3, + position: Vector3.Zero(), + size: Vector3.One(), + ...options, + }; + this._resolutionX = localOptions.resolutionX; + this._resolutionY = localOptions.resolutionY; + this._resolutionZ = localOptions.resolutionZ; + this._position = localOptions.position; + this._size = localOptions.autoAdaptToMesh ? localOptions.autoAdaptToMesh.getBoundingInfo().boundingBox.extendSize.scale(2) : localOptions.size; + // Allocate data + this._allocateData(); + this.update(); + } + _allocateData() { + this._data = new Array(this.resolutionX); + for (let i = 0; i < this.resolutionX; i++) { + this._data[i] = new Array(this.resolutionY); + for (let j = 0; j < this.resolutionY; j++) { + this._data[i][j] = new Array(this.resolutionZ); + for (let k = 0; k < this.resolutionZ; k++) { + this._data[i][j][k] = Vector3.Zero(); + } + } + } + } + /** + * Update of the lattice data + */ + update() { + for (let i = 0; i < this.resolutionX; i++) { + for (let j = 0; j < this.resolutionY; j++) { + for (let k = 0; k < this.resolutionZ; k++) { + const x = -this.size.x / 2 + this.size.x * (i / (this.resolutionX - 1)); + const y = -this.size.y / 2 + this.size.y * (j / (this.resolutionY - 1)); + const z = -this.size.z / 2 + this.size.z * (k / (this.resolutionZ - 1)); + this._data[i][j][k].set(x, y, z); + } + } + } + } + /** + * Apply the lattice to a mesh + * @param mesh mesh to deform + */ + deformMesh(mesh) { + const positions = mesh.getVerticesData(VertexBuffer.PositionKind); + if (!positions) { + return; + } + // Apply the lattice + this.deform(positions); + // Update back the mesh + mesh.setVerticesData(VertexBuffer.PositionKind, positions, true); + } + /** + * Update the lattice internals (like min, max and cell size) + */ + updateInternals() { + const nx = this._resolutionX; + const ny = this._resolutionY; + const nz = this._resolutionZ; + // Calculate the size of each cell in the lattice + this._cellSize.set(this.size.x / (nx - 1), this.size.y / (ny - 1), this.size.z / (nz - 1)); + // Calculate the lattice bounds + this._min.set(this.position.x - this.size.x / 2, this.position.y - this.size.y / 2, this.position.z - this.size.z / 2); + this._min.addToRef(this._size, this._max); + } + /** + * Apply the lattice to a set of points + * @param positions vertex data to deform + * @param target optional target array to store the result (operation will be done in place in not defined) + */ + deform(positions, target) { + const nx = this._resolutionX; + const ny = this._resolutionY; + const nz = this._resolutionZ; + this.updateInternals(); + const min = this._min; + const max = this._max; + // Loop over each vertex + for (let i = 0; i < positions.length; i += 3) { + const vertex = this._tmpVector.fromArray(positions, i); + // Check we are inside + if (OutsideRange(vertex.x, min.x, max.x, Epsilon) || OutsideRange(vertex.y, min.y, max.y, Epsilon) || OutsideRange(vertex.z, min.z, max.z, Epsilon)) { + if (target) { + vertex.toArray(target, i); + } + continue; + } + // Map vertex position to lattice local coordinates + const localPos = this._localPos.set((vertex.x - min.x) / this._cellSize.x, (vertex.y - min.y) / this._cellSize.y, (vertex.z - min.z) / this._cellSize.z); + // Get integer lattice indices + const i0 = Math.floor(localPos.x); + const j0 = Math.floor(localPos.y); + const k0 = Math.floor(localPos.z); + const i1 = Math.min(i0 + 1, nx - 1); + const j1 = Math.min(j0 + 1, ny - 1); + const k1 = Math.min(k0 + 1, nz - 1); + // Compute interpolation weights + const tx = localPos.x - i0; + const ty = localPos.y - j0; + const tz = localPos.z - k0; + // Ensure indices are within bounds + const ii0 = Clamp(i0, 0, nx - 1); + const jj0 = Clamp(j0, 0, ny - 1); + const kk0 = Clamp(k0, 0, nz - 1); + const ii1 = Clamp(i1, 0, nx - 1); + const jj1 = Clamp(j1, 0, ny - 1); + const kk1 = Clamp(k1, 0, nz - 1); + // Get lattice control points + const p000 = this._data[ii0][jj0][kk0]; + const p100 = this._data[ii1][jj0][kk0]; + const p010 = this._data[ii0][jj1][kk0]; + const p110 = this._data[ii1][jj1][kk0]; + const p001 = this._data[ii0][jj0][kk1]; + const p101 = this._data[ii1][jj0][kk1]; + const p011 = this._data[ii0][jj1][kk1]; + const p111 = this._data[ii1][jj1][kk1]; + // Trilinear interpolation + const p00 = Vector3.LerpToRef(p000, p100, tx, this._lerpVector0); + const p01 = Vector3.LerpToRef(p001, p101, tx, this._lerpVector1); + const p10 = Vector3.LerpToRef(p010, p110, tx, this._lerpVector2); + const p11 = Vector3.LerpToRef(p011, p111, tx, this._lerpVector3); + const p0 = Vector3.LerpToRef(p00, p10, ty, this._lerpVector4); + const p1 = Vector3.LerpToRef(p01, p11, ty, this._lerpVector5); + const deformedPos = Vector3.LerpToRef(p0, p1, tz, this._lerpVector0); + deformedPos.addInPlace(this.position); + // Apply deformation to the vertex + deformedPos.toArray(target || positions, i); + } + } +} + +/** + * In POINTS_MODE_POINTS every array of points will become the center (backbone) of the ribbon. The ribbon will be expanded by `width / 2` to `+direction` and `-direction` as well. + * In POINTS_MODE_PATHS every array of points specifies an edge. These will be used to build one ribbon. + */ +var GreasedLineRibbonPointsMode; +(function (GreasedLineRibbonPointsMode) { + GreasedLineRibbonPointsMode[GreasedLineRibbonPointsMode["POINTS_MODE_POINTS"] = 0] = "POINTS_MODE_POINTS"; + GreasedLineRibbonPointsMode[GreasedLineRibbonPointsMode["POINTS_MODE_PATHS"] = 1] = "POINTS_MODE_PATHS"; +})(GreasedLineRibbonPointsMode || (GreasedLineRibbonPointsMode = {})); +/** + * FACES_MODE_SINGLE_SIDED single sided with back face culling. Default value. + * FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING single sided without back face culling. Sets backFaceCulling = false on the material so it affects all line ribbons added to the line ribbon instance. + * FACES_MODE_DOUBLE_SIDED extra back faces are created. This doubles the amount of faces of the mesh. + */ +var GreasedLineRibbonFacesMode; +(function (GreasedLineRibbonFacesMode) { + GreasedLineRibbonFacesMode[GreasedLineRibbonFacesMode["FACES_MODE_SINGLE_SIDED"] = 0] = "FACES_MODE_SINGLE_SIDED"; + GreasedLineRibbonFacesMode[GreasedLineRibbonFacesMode["FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING"] = 1] = "FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING"; + GreasedLineRibbonFacesMode[GreasedLineRibbonFacesMode["FACES_MODE_DOUBLE_SIDED"] = 2] = "FACES_MODE_DOUBLE_SIDED"; +})(GreasedLineRibbonFacesMode || (GreasedLineRibbonFacesMode = {})); +/** + * Only with POINTS_MODE_PATHS. + * AUTO_DIRECTIONS_FROM_FIRST_SEGMENT sets the direction (slope) of the ribbon from the direction of the first line segment. Recommended. + * AUTO_DIRECTIONS_FROM_ALL_SEGMENTS in this mode the direction (slope) will be calculated for each line segment according to the direction vector between each point of the line segments. Slow method. + * AUTO_DIRECTIONS_ENHANCED in this mode the direction (slope) will be calculated for each line segment according to the direction vector between each point of the line segments using a more sophisitcaed algorithm. Slowest method. + * AUTO_DIRECTIONS_FACE_TO in this mode the direction (slope) will be calculated for each line segment according to the direction vector between each point of the line segments and a direction (face-to) vector specified in direction. The resulting line will face to the direction of this face-to vector. + * AUTO_DIRECTIONS_NONE you have to set the direction (slope) manually. Recommended. + */ +var GreasedLineRibbonAutoDirectionMode; +(function (GreasedLineRibbonAutoDirectionMode) { + GreasedLineRibbonAutoDirectionMode[GreasedLineRibbonAutoDirectionMode["AUTO_DIRECTIONS_FROM_FIRST_SEGMENT"] = 0] = "AUTO_DIRECTIONS_FROM_FIRST_SEGMENT"; + GreasedLineRibbonAutoDirectionMode[GreasedLineRibbonAutoDirectionMode["AUTO_DIRECTIONS_FROM_ALL_SEGMENTS"] = 1] = "AUTO_DIRECTIONS_FROM_ALL_SEGMENTS"; + GreasedLineRibbonAutoDirectionMode[GreasedLineRibbonAutoDirectionMode["AUTO_DIRECTIONS_ENHANCED"] = 2] = "AUTO_DIRECTIONS_ENHANCED"; + GreasedLineRibbonAutoDirectionMode[GreasedLineRibbonAutoDirectionMode["AUTO_DIRECTIONS_FACE_TO"] = 3] = "AUTO_DIRECTIONS_FACE_TO"; + GreasedLineRibbonAutoDirectionMode[GreasedLineRibbonAutoDirectionMode["AUTO_DIRECTIONS_NONE"] = 99] = "AUTO_DIRECTIONS_NONE"; +})(GreasedLineRibbonAutoDirectionMode || (GreasedLineRibbonAutoDirectionMode = {})); +/** + * GreasedLineBaseMesh + */ +class GreasedLineBaseMesh extends Mesh { + constructor(name, scene, _options) { + super(name, scene, null, null, false, false); + this.name = name; + this._options = _options; + this._lazy = false; + this._updatable = false; + this._engine = scene.getEngine(); + this._lazy = _options.lazy ?? false; + this._updatable = _options.updatable ?? false; + this._vertexPositions = []; + this._indices = []; + this._uvs = []; + this._points = []; + this._colorPointers = _options.colorPointers ?? []; + this._widths = _options.widths ?? new Array(_options.points.length).fill(1); + } + /** + * "GreasedLineMesh" + * @returns "GreasedLineMesh" + */ + getClassName() { + return "GreasedLineMesh"; + } + _updateWidthsWithValue(defaulValue) { + let pointCount = 0; + for (const points of this._points) { + pointCount += points.length; + } + const countDiff = (pointCount / 3) * 2 - this._widths.length; + for (let i = 0; i < countDiff; i++) { + this._widths.push(defaulValue); + } + } + /** + * Updated a lazy line. Rerenders the line and updates boundinfo as well. + */ + updateLazy() { + this._setPoints(this._points); + if (!this._options.colorPointers) { + this._updateColorPointers(); + } + this._createVertexBuffers(this._options.ribbonOptions?.smoothShading); + !this.doNotSyncBoundingInfo && this.refreshBoundingInfo(); + this.greasedLineMaterial?.updateLazy(); + } + /** + * Adds new points to the line. It doesn't rerenders the line if in lazy mode. + * @param points points table + * @param options optional options + */ + addPoints(points, options) { + for (const p of points) { + this._points.push(p); + } + if (!this._lazy) { + this.setPoints(this._points, options); + } + } + /** + * Dispose the line and it's resources + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + dispose(doNotRecurse, disposeMaterialAndTextures = false) { + super.dispose(doNotRecurse, disposeMaterialAndTextures); + } + /** + * @returns true if the mesh was created in lazy mode + */ + isLazy() { + return this._lazy; + } + /** + * Returns the UVs + */ + get uvs() { + return this._uvs; + } + /** + * Sets the UVs + * @param uvs the UVs + */ + set uvs(uvs) { + this._uvs = uvs instanceof Float32Array ? uvs : new Float32Array(uvs); + this._createVertexBuffers(); + } + /** + * Returns the points offsets + * Return the points offsets + */ + get offsets() { + return this._offsets; + } + /** + * Sets point offests + * @param offsets offset table [x,y,z, x,y,z, ....] + */ + set offsets(offsets) { + if (this.material instanceof GreasedLineSimpleMaterial) { + this.material.setDefine(GreasedLineUseOffsetsSimpleMaterialDefine, offsets?.length > 0); + } + this._offsets = offsets; + if (!this._offsetsBuffer) { + this._createOffsetsBuffer(offsets); + } + else { + this._offsetsBuffer.update(offsets); + } + } + /** + * Gets widths at each line point like [widthLower, widthUpper, widthLower, widthUpper, ...] + */ + get widths() { + return this._widths; + } + /** + * Sets widths at each line point + * @param widths width table [widthLower, widthUpper, widthLower, widthUpper ...] + */ + set widths(widths) { + this._widths = widths; + if (!this._lazy) { + this._widthsBuffer && this._widthsBuffer.update(widths); + } + } + /** + * Gets the color pointer. Each vertex need a color pointer. These color pointers points to the colors in the color table @see colors + */ + get colorPointers() { + return this._colorPointers; + } + /** + * Sets the color pointer + * @param colorPointers array of color pointer in the colors array. One pointer for every vertex is needed. + */ + set colorPointers(colorPointers) { + this._colorPointers = colorPointers; + if (!this._lazy) { + this._colorPointersBuffer && this._colorPointersBuffer.update(colorPointers); + } + } + /** + * Gets the pluginMaterial associated with line + */ + get greasedLineMaterial() { + if (this.material && this.material instanceof GreasedLineSimpleMaterial) { + return this.material; + } + const materialPlugin = this.material?.pluginManager?.getPlugin(GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME); + if (materialPlugin) { + return materialPlugin; + } + return; + } + /** + * Return copy the points. + */ + get points() { + const pointsCopy = []; + DeepCopier.DeepCopy(this._points, pointsCopy); + return pointsCopy; + } + /** + * Sets line points and rerenders the line. + * @param points points table + * @param options optional options + */ + setPoints(points, options) { + this._points = GreasedLineTools.ConvertPoints(points, options?.pointsOptions ?? this._options.pointsOptions); + this._updateWidths(); + if (!options?.colorPointers) { + this._updateColorPointers(); + } + this._setPoints(this._points, options); + } + _initGreasedLine() { + this._vertexPositions = []; + this._indices = []; + this._uvs = []; + } + _createLineOptions() { + const lineOptions = { + points: this._points, + colorPointers: this._colorPointers, + lazy: this._lazy, + updatable: this._updatable, + uvs: this._uvs, + widths: this._widths, + ribbonOptions: this._options.ribbonOptions, + }; + return lineOptions; + } + /** + * Serializes this GreasedLineMesh + * @param serializationObject object to write serialization to + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.type = this.getClassName(); + serializationObject.lineOptions = this._createLineOptions(); + } + _createVertexBuffers(computeNormals = false) { + const vertexData = new VertexData(); + vertexData.positions = this._vertexPositions; + vertexData.indices = this._indices; + vertexData.uvs = this._uvs; + if (computeNormals) { + vertexData.normals = []; + VertexData.ComputeNormals(this._vertexPositions, this._indices, vertexData.normals); + } + vertexData.applyToMesh(this, this._options.updatable); + return vertexData; + } + _createOffsetsBuffer(offsets) { + const engine = this._scene.getEngine(); + const offsetBuffer = new Buffer(engine, offsets, this._updatable, 3); + this.setVerticesBuffer(offsetBuffer.createVertexBuffer("grl_offsets", 0, 3)); + this._offsetsBuffer = offsetBuffer; + } +} + +Mesh._GreasedLineMeshParser = (parsedMesh, scene) => { + return GreasedLineMesh.Parse(parsedMesh, scene); +}; +/** + * GreasedLineMesh + * Use the GreasedLineBuilder.CreateGreasedLine function to create an instance of this class. + */ +class GreasedLineMesh extends GreasedLineBaseMesh { + /** + * GreasedLineMesh + * @param name name of the mesh + * @param scene the scene + * @param _options mesh options + */ + constructor(name, scene, _options) { + super(name, scene, _options); + this.name = name; + /** + * Treshold used to pick the mesh + */ + this.intersectionThreshold = 0.1; + this._previousAndSide = []; + this._nextAndCounters = []; + if (_options.points) { + this.addPoints(GreasedLineTools.ConvertPoints(_options.points)); + } + } + /** + * "GreasedLineMesh" + * @returns "GreasedLineMesh" + */ + getClassName() { + return "GreasedLineMesh"; + } + _updateColorPointers() { + if (this._options.colorPointers) { + return; + } + let colorPointer = 0; + this._colorPointers = []; + this._points.forEach((p) => { + for (let jj = 0; jj < p.length; jj += 3) { + this._colorPointers.push(colorPointer); + this._colorPointers.push(colorPointer++); + } + }); + } + _updateWidths() { + // intentionally left blank + } + _setPoints(points) { + this._points = points; + this._options.points = points; + this._initGreasedLine(); + let indiceOffset = 0; + let vertexPositionsLen = 0, indicesLength = 0, uvLength = 0, previousAndSideLength = 0; + points.forEach((p) => { + vertexPositionsLen += p.length * 2; + indicesLength += (p.length - 3) * 2; + uvLength += (p.length * 4) / 3; + previousAndSideLength += (p.length * 8) / 3; + }); + const vertexPositionsArr = new Float32Array(vertexPositionsLen); + const indicesArr = vertexPositionsLen > 65535 ? new Uint32Array(indicesLength) : new Uint16Array(indicesLength); + const uvArr = new Float32Array(uvLength); + const previousAndSide = new Float32Array(previousAndSideLength); + // it's the same length here + const nextAndCounters = new Float32Array(previousAndSideLength); + let vertexPositionsOffset = 0, indicesOffset = 0, uvOffset = 0, previousAndSideOffset = 0, nextAndCountersOffset = 0; + points.forEach((p) => { + const lengthArray = GreasedLineTools.GetLineLengthArray(p); + const totalLength = lengthArray[lengthArray.length - 1]; + for (let j = 0, jj = 0; jj < p.length; j++, jj += 3) { + const baseOffset = vertexPositionsOffset + jj * 2; + vertexPositionsArr[baseOffset + 0] = p[jj + 0]; + vertexPositionsArr[baseOffset + 1] = p[jj + 1]; + vertexPositionsArr[baseOffset + 2] = p[jj + 2]; + vertexPositionsArr[baseOffset + 3] = p[jj + 0]; + vertexPositionsArr[baseOffset + 4] = p[jj + 1]; + vertexPositionsArr[baseOffset + 5] = p[jj + 2]; + if (jj < p.length - 3) { + const n = j * 2 + indiceOffset; + const baseIndicesOffset = indicesOffset + jj * 2; + indicesArr[baseIndicesOffset + 0] = n; + indicesArr[baseIndicesOffset + 1] = n + 1; + indicesArr[baseIndicesOffset + 2] = n + 2; + indicesArr[baseIndicesOffset + 3] = n + 2; + indicesArr[baseIndicesOffset + 4] = n + 1; + indicesArr[baseIndicesOffset + 5] = n + 3; + } + } + indiceOffset += (p.length / 3) * 2; + const currVertexPositionsOffsetLength = p.length * 2; + const positions = vertexPositionsArr.subarray(vertexPositionsOffset, vertexPositionsOffset + currVertexPositionsOffsetLength); + vertexPositionsOffset += currVertexPositionsOffsetLength; + indicesOffset += (p.length - 3) * 2; + const previous = new Float32Array(positions.length); + const next = new Float32Array(positions.length); + const l = positions.length / 6; + let v; + if (GreasedLineMesh._CompareV3(0, l - 1, positions)) { + v = positions.subarray((l - 2) * 6, (l - 1) * 6); + } + else { + v = positions.subarray(0, 6); + } + previous.set(v); + previous.set(positions.subarray(0, positions.length - 6), 6); + next.set(positions.subarray(6)); + if (GreasedLineMesh._CompareV3(l - 1, 0, positions)) { + v = positions.subarray(6, 12); + } + else { + v = positions.subarray((l - 1) * 6, l * 6); + } + next.set(v, next.length - 6); + for (let i = 0, sidesLength = positions.length / 3; i < sidesLength; i++) { + previousAndSide[previousAndSideOffset++] = previous[i * 3]; + previousAndSide[previousAndSideOffset++] = previous[i * 3 + 1]; + previousAndSide[previousAndSideOffset++] = previous[i * 3 + 2]; + // side[i] = i % 2 ? -1 : 1; + // side[i] = 1 - ((i & 1) << 1); + previousAndSide[previousAndSideOffset++] = 1 - ((i & 1) << 1); + nextAndCounters[nextAndCountersOffset++] = next[i * 3]; + nextAndCounters[nextAndCountersOffset++] = next[i * 3 + 1]; + nextAndCounters[nextAndCountersOffset++] = next[i * 3 + 2]; + // counters[i] = lengthArray[i >> 1] / totalLength; + nextAndCounters[nextAndCountersOffset++] = lengthArray[i >> 1] / totalLength; + } + if (this._options.uvs) { + for (let i = 0; i < this._options.uvs.length; i++) { + uvArr[uvOffset++] = this._options.uvs[i]; + } + } + else { + for (let j = 0; j < l; j++) { + // uvs + const lengthRatio = lengthArray[j] / totalLength; + const uvOffsetBase = uvOffset + j * 4; + uvArr[uvOffsetBase + 0] = lengthRatio; + uvArr[uvOffsetBase + 1] = 0; + uvArr[uvOffsetBase + 2] = lengthRatio; + uvArr[uvOffsetBase + 3] = 1; + } + } + }); + this._vertexPositions = vertexPositionsArr; + this._indices = indicesArr; + this._uvs = uvArr; + this._previousAndSide = previousAndSide; + this._nextAndCounters = nextAndCounters; + if (!this._lazy) { + if (!this._options.colorPointers) { + this._updateColorPointers(); + } + this._createVertexBuffers(); + !this.doNotSyncBoundingInfo && this.refreshBoundingInfo(); + } + } + /** + * Clones the GreasedLineMesh. + * @param name new line name + * @param newParent new parent node + * @returns cloned line + */ + clone(name = `${this.name}-cloned`, newParent) { + const lineOptions = this._createLineOptions(); + const deepCopiedLineOptions = {}; + DeepCopier.DeepCopy(lineOptions, deepCopiedLineOptions, ["instance"], undefined, true); + const cloned = new GreasedLineMesh(name, this._scene, deepCopiedLineOptions); + if (newParent) { + cloned.parent = newParent; + } + cloned.material = this.material; + return cloned; + } + /** + * Serializes this GreasedLineMesh + * @param serializationObject object to write serialization to + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.type = this.getClassName(); + serializationObject.lineOptions = this._createLineOptions(); + } + /** + * Parses a serialized GreasedLineMesh + * @param parsedMesh the serialized GreasedLineMesh + * @param scene the scene to create the GreasedLineMesh in + * @returns the created GreasedLineMesh + */ + static Parse(parsedMesh, scene) { + const lineOptions = parsedMesh.lineOptions; + const name = parsedMesh.name; + const result = new GreasedLineMesh(name, scene, lineOptions); + return result; + } + _initGreasedLine() { + super._initGreasedLine(); + this._previousAndSide = []; + this._nextAndCounters = []; + } + /** + * Checks whether a ray is intersecting this GreasedLineMesh + * @param ray ray to check the intersection of this mesh with + * @param fastCheck not supported + * @param trianglePredicate not supported + * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default) + * @param worldToUse not supported + * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check + * @returns the picking info + */ + intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) { + const pickingInfo = new PickingInfo(); + const intersections = this.findAllIntersections(ray, fastCheck, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo, true); + if (intersections?.length === 1) { + const intersection = intersections[0]; + pickingInfo.hit = true; + pickingInfo.distance = intersection.distance; + pickingInfo.ray = ray; + pickingInfo.pickedMesh = this; + pickingInfo.pickedPoint = intersection.point; + } + return pickingInfo; + } + /** + * Gets all intersections of a ray and the line + * @param ray Ray to check the intersection of this mesh with + * @param _fastCheck not supported + * @param _trianglePredicate not supported + * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default) + * @param _worldToUse not supported + * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check + * @param firstOnly If true, the first and only intersection is immediatelly returned if found + * @returns intersection(s) + */ + findAllIntersections(ray, _fastCheck, _trianglePredicate, onlyBoundingInfo = false, _worldToUse, skipBoundingInfo = false, firstOnly = false) { + if (onlyBoundingInfo && !skipBoundingInfo && ray.intersectsSphere(this._boundingSphere, this.intersectionThreshold) === false) { + return; + } + const indices = this.getIndices(); + const positions = this.getVerticesData(VertexBuffer.PositionKind); + const widths = this._widths; + const lineWidth = this.greasedLineMaterial?.width ?? 1; + const intersects = []; + if (indices && positions && widths) { + let i = 0, l = 0; + for (i = 0, l = indices.length - 1; i < l; i += 3) { + const a = indices[i]; + const b = indices[i + 1]; + GreasedLineMesh._V_START.fromArray(positions, a * 3); + GreasedLineMesh._V_END.fromArray(positions, b * 3); + if (this._offsets) { + GreasedLineMesh._V_OFFSET_START.fromArray(this._offsets, a * 3); + GreasedLineMesh._V_OFFSET_END.fromArray(this._offsets, b * 3); + GreasedLineMesh._V_START.addInPlace(GreasedLineMesh._V_OFFSET_START); + GreasedLineMesh._V_END.addInPlace(GreasedLineMesh._V_OFFSET_END); + } + const iFloored = Math.floor(i / 3); + const width = widths[iFloored] !== undefined ? widths[iFloored] : 1; + const precision = (this.intersectionThreshold * (lineWidth * width)) / 2; + const distance = ray.intersectionSegment(GreasedLineMesh._V_START, GreasedLineMesh._V_END, precision); + if (distance !== -1) { + intersects.push({ + distance: distance, + point: ray.direction.normalize().multiplyByFloats(distance, distance, distance).add(ray.origin), + }); + if (firstOnly) { + return intersects; + } + } + } + i = l; + } + return intersects; + } + get _boundingSphere() { + return this.getBoundingInfo().boundingSphere; + } + static _CompareV3(positionIdx1, positionIdx2, positions) { + const arrayIdx1 = positionIdx1 * 6; + const arrayIdx2 = positionIdx2 * 6; + return positions[arrayIdx1] === positions[arrayIdx2] && positions[arrayIdx1 + 1] === positions[arrayIdx2 + 1] && positions[arrayIdx1 + 2] === positions[arrayIdx2 + 2]; + } + _createVertexBuffers() { + const vertexData = super._createVertexBuffers(); + const engine = this._scene.getEngine(); + const previousAndSideBuffer = new Buffer(engine, this._previousAndSide, false, 4); + this.setVerticesBuffer(previousAndSideBuffer.createVertexBuffer("grl_previousAndSide", 0, 4)); + const nextAndCountersBuffer = new Buffer(engine, this._nextAndCounters, false, 4); + this.setVerticesBuffer(nextAndCountersBuffer.createVertexBuffer("grl_nextAndCounters", 0, 4)); + const widthBuffer = new Buffer(engine, this._widths, this._updatable, 1); + this.setVerticesBuffer(widthBuffer.createVertexBuffer("grl_widths", 0, 1)); + this._widthsBuffer = widthBuffer; + const colorPointersBuffer = new Buffer(engine, this._colorPointers, this._updatable, 1); + this.setVerticesBuffer(colorPointersBuffer.createVertexBuffer("grl_colorPointers", 0, 1)); + this._colorPointersBuffer = colorPointersBuffer; + return vertexData; + } +} +GreasedLineMesh._V_START = new Vector3(); +GreasedLineMesh._V_END = new Vector3(); +GreasedLineMesh._V_OFFSET_START = new Vector3(); +GreasedLineMesh._V_OFFSET_END = new Vector3(); + +Mesh._GreasedLineRibbonMeshParser = (parsedMesh, scene) => { + return GreasedLineRibbonMesh.Parse(parsedMesh, scene); +}; +/** + * GreasedLineRibbonMesh + * Use the GreasedLineBuilder.CreateGreasedLine function to create an instance of this class. + */ +class GreasedLineRibbonMesh extends GreasedLineBaseMesh { + /** + * GreasedLineRibbonMesh + * @param name name of the mesh + * @param scene the scene + * @param _options mesh options + * @param _pathOptions used internaly when parsing a serialized GreasedLineRibbonMesh + */ + constructor(name, scene, _options, _pathOptions) { + super(name, scene, _options); + this.name = name; + if (!_options.ribbonOptions) { + // eslint-disable-next-line no-throw-literal + throw "'GreasedLineMeshOptions.ribbonOptions' is not set."; + } + this._paths = []; + this._counters = []; + this._slopes = []; + this._widths = _options.widths ?? []; + this._ribbonWidths = []; + this._pathsOptions = _pathOptions ?? []; + if (_options.points) { + this.addPoints(GreasedLineTools.ConvertPoints(_options.points), _options, !!_pathOptions); + } + } + /** + * Adds new points to the line. It doesn't rerenders the line if in lazy mode. + * @param points points table + * @param options mesh options + * @param hasPathOptions defaults to false + */ + addPoints(points, options, hasPathOptions = false) { + if (!options.ribbonOptions) { + // eslint-disable-next-line no-throw-literal + throw "addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'."; + } + if (!hasPathOptions) { + this._pathsOptions.push({ options, pathCount: points.length }); + } + super.addPoints(points, options); + } + /** + * "GreasedLineRibbonMesh" + * @returns "GreasedLineRibbonMesh" + */ + getClassName() { + return "GreasedLineRibbonMesh"; + } + /** + * Return true if the line was created from two edge paths or one points path. + * In this case the line is always flat. + */ + get isFlatLine() { + return this._paths.length < 3; + } + /** + * Returns the slopes of the line at each point relative to the center of the line + */ + get slopes() { + return this._slopes; + } + /** + * Set the slopes of the line at each point relative to the center of the line + */ + set slopes(slopes) { + this._slopes = slopes; + } + _updateColorPointers() { + if (this._options.colorPointers) { + return; + } + let colorPointer = 0; + this._colorPointers = []; + for (let i = 0; i < this._pathsOptions.length; i++) { + const { options: pathOptions, pathCount } = this._pathsOptions[i]; + const points = this._points[i]; + if (pathOptions.ribbonOptions.pointsMode === 0 /* GreasedLineRibbonPointsMode.POINTS_MODE_POINTS */) { + for (let k = 0; k < pathCount; k++) { + for (let j = 0; j < points.length; j += 3) { + this._colorPointers.push(colorPointer); + this._colorPointers.push(colorPointer++); + } + } + } + else { + for (let j = 0; j < points.length; j += 3) { + for (let k = 0; k < pathCount; k++) { + this._colorPointers.push(colorPointer); + } + colorPointer++; + } + } + } + } + _updateWidths() { + super._updateWidthsWithValue(1); + } + _setPoints(points, _options) { + if (!this._options.ribbonOptions) { + // eslint-disable-next-line no-throw-literal + throw "No 'GreasedLineMeshOptions.ribbonOptions' provided."; + } + this._points = points; + this._options.points = points; + this._initGreasedLine(); + let indiceOffset = 0; + let directionPlanes; + for (let i = 0, c = 0; i < this._pathsOptions.length; i++) { + const { options: pathOptions, pathCount } = this._pathsOptions[i]; + const subPoints = points.slice(c, c + pathCount); + c += pathCount; + if (pathOptions.ribbonOptions?.pointsMode === 1 /* GreasedLineRibbonPointsMode.POINTS_MODE_PATHS */) { + indiceOffset = this._preprocess(GreasedLineTools.ToVector3Array(subPoints), indiceOffset, pathOptions); + } + else { + if (pathOptions.ribbonOptions?.directionsAutoMode === 99 /* GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_NONE */) { + if (!pathOptions.ribbonOptions.directions) { + // eslint-disable-next-line no-throw-literal + throw "In GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_NONE 'GreasedLineMeshOptions.ribbonOptions.directions' must be defined."; + } + directionPlanes = GreasedLineRibbonMesh._GetDirectionPlanesFromDirectionsOption(subPoints.length, pathOptions.ribbonOptions.directions); + } + subPoints.forEach((p, idx) => { + const pathArray = GreasedLineRibbonMesh._ConvertToRibbonPath(p, pathOptions.ribbonOptions, this._scene.useRightHandedSystem, directionPlanes ? directionPlanes[idx] : directionPlanes); + indiceOffset = this._preprocess(pathArray, indiceOffset, pathOptions); + }); + } + } + if (!this._lazy) { + this._createVertexBuffers(); + !this.doNotSyncBoundingInfo && this.refreshBoundingInfo(); + } + } + static _GetDirectionPlanesFromDirectionsOption(count, directions) { + if (Array.isArray(directions)) { + return directions; + } + return new Array(count).fill(directions); + } + static _CreateRibbonVertexData(pathArray, options) { + const numOfPaths = pathArray.length; + if (numOfPaths < 2) { + // eslint-disable-next-line no-throw-literal + throw "Minimum of two paths are required to create a GreasedLineRibbonMesh."; + } + const positions = []; + const indices = []; + const path = pathArray[0]; + for (let i = 0; i < path.length; i++) { + for (let pi = 0; pi < pathArray.length; pi++) { + const v = pathArray[pi][i]; + positions.push(v.x, v.y, v.z); + } + } + const v = [1, 0, numOfPaths]; + const doubleSided = options.ribbonOptions?.facesMode === 2 /* GreasedLineRibbonFacesMode.FACES_MODE_DOUBLE_SIDED */; + const closePath = options.ribbonOptions?.pointsMode === 1 /* GreasedLineRibbonPointsMode.POINTS_MODE_PATHS */ && options.ribbonOptions.closePath; + if (numOfPaths > 2) { + for (let i = 0; i < path.length - 1; i++) { + v[0] = 1 + numOfPaths * i; + v[1] = numOfPaths * i; + v[2] = (i + 1) * numOfPaths; + for (let pi = 0; pi < (numOfPaths - 1) * 2; pi++) { + if (pi % 2 !== 0) { + v[2] += 1; + } + if (pi % 2 === 0 && pi > 0) { + v[0] += 1; + v[1] += 1; + } + indices.push(v[1] + (pi % 2 !== 0 ? numOfPaths : 0), v[0], v[2]); + if (doubleSided) { + indices.push(v[0], v[1] + (pi % 2 !== 0 ? numOfPaths : 0), v[2]); + } + } + } + } + else { + for (let i = 0; i < positions.length / 3 - 3; i += 2) { + indices.push(i, i + 1, i + 2); + indices.push(i + 2, i + 1, i + 3); + if (doubleSided) { + indices.push(i + 1, i, i + 2); + indices.push(i + 1, i + 2, i + 3); + } + } + } + if (closePath) { + let lastIndice = numOfPaths * (path.length - 1); + for (let pi = 0; pi < numOfPaths - 1; pi++) { + indices.push(lastIndice, pi + 1, pi); + indices.push(lastIndice + 1, pi + 1, lastIndice); + if (doubleSided) { + indices.push(pi, pi + 1, lastIndice); + indices.push(lastIndice, pi + 1, lastIndice + 1); + } + lastIndice++; + } + } + return { + positions, + indices, + }; + } + _preprocess(pathArray, indiceOffset, options) { + this._paths = pathArray; + const ribbonVertexData = GreasedLineRibbonMesh._CreateRibbonVertexData(pathArray, options); + const positions = ribbonVertexData.positions; + if (!this._options.widths) { + // eslint-disable-next-line no-throw-literal + throw "No 'GreasedLineMeshOptions.widths' table is specified."; + } + const vertexPositions = Array.isArray(this._vertexPositions) ? this._vertexPositions : Array.from(this._vertexPositions); + this._vertexPositions = vertexPositions; + const uvs = Array.isArray(this._uvs) ? this._uvs : Array.from(this._uvs); + this._uvs = uvs; + const indices = Array.isArray(this._indices) ? this._indices : Array.from(this._indices); + this._indices = indices; + for (const p of positions) { + vertexPositions.push(p); + } + let pathArrayCopy = pathArray; + if (options.ribbonOptions?.pointsMode === 1 /* GreasedLineRibbonPointsMode.POINTS_MODE_PATHS */ && options.ribbonOptions.closePath) { + pathArrayCopy = []; + for (let i = 0; i < pathArray.length; i++) { + const pathCopy = pathArray[i].slice(); + pathCopy.push(pathArray[i][0].clone()); + pathArrayCopy.push(pathCopy); + } + } + this._calculateSegmentLengths(pathArrayCopy); + const pathArrayLength = pathArrayCopy.length; + const previousCounters = new Array(pathArrayLength).fill(0); + for (let i = 0; i < pathArrayCopy[0].length; i++) { + let v = 0; + for (let pi = 0; pi < pathArrayLength; pi++) { + const counter = previousCounters[pi] + this._vSegmentLengths[pi][i] / this._vTotalLengths[pi]; + this._counters.push(counter); + uvs.push(counter, v); + previousCounters[pi] = counter; + v += this._uSegmentLengths[i][pi] / this._uTotalLengths[i]; + } + } + for (let i = 0, c = 0; i < pathArrayCopy[0].length; i++) { + const widthLower = this._uSegmentLengths[i][0] / 2; + const widthUpper = this._uSegmentLengths[i][pathArrayLength - 1] / 2; + this._ribbonWidths.push(((this._widths[c++] ?? 1) - 1) * widthLower); + for (let pi = 0; pi < pathArrayLength - 2; pi++) { + this._ribbonWidths.push(0); + } + this._ribbonWidths.push(((this._widths[c++] ?? 1) - 1) * widthUpper); + } + const slopes = options.ribbonOptions?.pointsMode === 1 /* GreasedLineRibbonPointsMode.POINTS_MODE_PATHS */ + ? new Array(pathArrayCopy[0].length * pathArrayCopy.length * 6).fill(0) + : GreasedLineRibbonMesh._CalculateSlopes(pathArrayCopy); + for (const s of slopes) { + this._slopes.push(s); + } + if (ribbonVertexData.indices) { + for (let i = 0; i < ribbonVertexData.indices.length; i++) { + indices.push(ribbonVertexData.indices[i] + indiceOffset); + } + } + indiceOffset += positions.length / 3; + return indiceOffset; + } + static _ConvertToRibbonPath(points, ribbonInfo, rightHandedSystem, directionPlane) { + if (ribbonInfo.pointsMode === 0 /* GreasedLineRibbonPointsMode.POINTS_MODE_POINTS */ && !ribbonInfo.width) { + // eslint-disable-next-line no-throw-literal + throw "'GreasedLineMeshOptions.ribbonOptiosn.width' must be specified in GreasedLineRibbonPointsMode.POINTS_MODE_POINTS."; + } + const path1 = []; + const path2 = []; + if (ribbonInfo.pointsMode === 0 /* GreasedLineRibbonPointsMode.POINTS_MODE_POINTS */) { + const width = ribbonInfo.width / 2; + const pointVectors = GreasedLineTools.ToVector3Array(points); + let direction = null; + let fatDirection = null; + if (ribbonInfo.directionsAutoMode === 0 /* GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT */) { + // set the direction plane from the first line segment for the whole line + directionPlane = GreasedLineRibbonMesh._GetDirectionFromPoints(pointVectors[0], pointVectors[1], null); + } + if (ribbonInfo.directionsAutoMode === 3 /* GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_FACE_TO */ && !(ribbonInfo.directions instanceof Vector3)) { + // eslint-disable-next-line no-throw-literal + throw "In GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_FACE_TO 'GreasedLineMeshOptions.ribbonOptions.directions' must be a Vector3."; + } + TmpVectors.Vector3[1] = ribbonInfo.directions instanceof Vector3 ? ribbonInfo.directions : GreasedLineRibbonMesh.DIRECTION_XZ; + for (let i = 0; i < pointVectors.length - (directionPlane ? 0 : 1); i++) { + const p1 = pointVectors[i]; + const p2 = pointVectors[i + 1]; + if (directionPlane) { + direction = directionPlane; + } + else if (ribbonInfo.directionsAutoMode === 3 /* GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_FACE_TO */) { + p2.subtractToRef(p1, TmpVectors.Vector3[0]); + direction = Vector3.CrossToRef(TmpVectors.Vector3[0], TmpVectors.Vector3[1], TmpVectors.Vector3[2]).normalize(); + } + else if (ribbonInfo.directionsAutoMode === 1 /* GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS */) { + direction = GreasedLineRibbonMesh._GetDirectionFromPoints(p1, p2, direction); + } + else { + // GreasedLineRibbonAutoDirectionMode.DIRECTION_ENHANCED + const directionTemp = p2.subtract(p1); + directionTemp.applyRotationQuaternionInPlace(directionTemp.x > directionTemp.y && directionTemp.x > directionTemp.z + ? rightHandedSystem + ? GreasedLineRibbonMesh._RightHandedForwardReadOnlyQuaternion + : GreasedLineRibbonMesh._LeftHandedForwardReadOnlyQuaternion + : GreasedLineRibbonMesh._LeftReadOnlyQuaternion); + direction = directionTemp.normalize(); + } + fatDirection = direction.multiplyByFloats(width, width, width); + path1.push(p1.add(fatDirection)); + path2.push(p1.subtract(fatDirection)); + } + if (!directionPlane) { + path1.push(pointVectors[pointVectors.length - 1].add(fatDirection)); + path2.push(pointVectors[pointVectors.length - 1].subtract(fatDirection)); + } + } + return [path1, path2]; + } + static _GetDirectionFromPoints(p1, p2, previousDirection) { + // handle straight lines + if (p1.x === p2.x && (!previousDirection || previousDirection?.x === 1)) { + return GreasedLineRibbonMesh.DIRECTION_YZ; + } + if (p1.y === p2.y) { + return GreasedLineRibbonMesh.DIRECTION_XZ; + } + if (p1.z === p2.z) { + return GreasedLineRibbonMesh.DIRECTION_XY; + } + return GreasedLineRibbonMesh.DIRECTION_XZ; + } + /** + * Clones the GreasedLineRibbonMesh. + * @param name new line name + * @param newParent new parent node + * @returns cloned line + */ + clone(name = `${this.name}-cloned`, newParent) { + const lineOptions = this._createLineOptions(); + const deepCopiedLineOptions = {}; + const pathOptionsCloned = []; + DeepCopier.DeepCopy(this._pathsOptions, pathOptionsCloned, undefined, undefined, true); + DeepCopier.DeepCopy(lineOptions, deepCopiedLineOptions, ["instance"], undefined, true); + const cloned = new GreasedLineRibbonMesh(name, this._scene, deepCopiedLineOptions, pathOptionsCloned); + if (newParent) { + cloned.parent = newParent; + } + cloned.material = this.material; + return cloned; + } + /** + * Serializes this GreasedLineRibbonMesh + * @param serializationObject object to write serialization to + */ + serialize(serializationObject) { + super.serialize(serializationObject); + serializationObject.type = this.getClassName(); + serializationObject.lineOptions = this._createLineOptions(); + serializationObject.pathsOptions = this._pathsOptions; + } + /** + * Parses a serialized GreasedLineRibbonMesh + * @param parsedMesh the serialized GreasedLineRibbonMesh + * @param scene the scene to create the GreasedLineRibbonMesh in + * @returns the created GreasedLineRibbonMesh + */ + static Parse(parsedMesh, scene) { + const lineOptions = parsedMesh.lineOptions; + const name = parsedMesh.name; + const pathOptions = parsedMesh.pathOptions; + const result = new GreasedLineRibbonMesh(name, scene, lineOptions, pathOptions); + return result; + } + _initGreasedLine() { + super._initGreasedLine(); + this._paths = []; + this._counters = []; + this._slopes = []; + this._ribbonWidths = []; + } + _calculateSegmentLengths(pathArray) { + const pathArrayLength = pathArray.length; + this._vSegmentLengths = new Array(pathArrayLength); + this._vTotalLengths = new Array(pathArrayLength); + let length = 0; + for (let pi = 0; pi < pathArrayLength; pi++) { + const points = pathArray[pi]; + this._vSegmentLengths[pi] = [0]; // first point has 0 distance + length = 0; + for (let i = 0; i < points.length - 1; i++) { + const l = Math.abs(points[i].subtract(points[i + 1]).lengthSquared()); // it's ok to have lengthSquared() here + length += l; + this._vSegmentLengths[pi].push(l); + } + this._vTotalLengths[pi] = length; + } + const positionsLength = pathArray[0].length; + this._uSegmentLengths = new Array(positionsLength).fill([]); + this._uTotalLengths = new Array(positionsLength).fill([]); + const uLength = new Vector3(); + for (let i = 0; i < positionsLength; i++) { + length = 0; + for (let pi = 1; pi < pathArrayLength; pi++) { + pathArray[pi][i].subtractToRef(pathArray[pi - 1][i], uLength); + const l = uLength.length(); // must be length() + length += l; + this._uSegmentLengths[i].push(l); + } + this._uTotalLengths[i] = length; + } + } + static _CalculateSlopes(paths) { + const points1 = paths[0]; + const points2 = paths.length === 2 ? paths[1] : paths[paths.length - 1]; + const slopes = []; + const slope = new Vector3(); + for (let i = 0; i < points1.length; i++) { + for (let pi = 0; pi < paths.length; pi++) { + if (pi === 0 || pi === paths.length - 1) { + points1[i].subtract(points2[i]).normalizeToRef(slope); + slopes.push(slope.x, slope.y, slope.z); + slopes.push(-slope.x, -slope.y, -slope.z); + } + else { + slopes.push(0, 0, 0, 0, 0, 0); + } + } + } + return slopes; + } + _createVertexBuffers() { + this._uvs = this._options.uvs ?? this._uvs; + const vertexData = super._createVertexBuffers(this._options.ribbonOptions?.smoothShading); + const countersBuffer = new Buffer(this._engine, this._counters, this._updatable, 1); + this.setVerticesBuffer(countersBuffer.createVertexBuffer("grl_counters", 0, 1)); + const colorPointersBuffer = new Buffer(this._engine, this._colorPointers, this._updatable, 1); + this.setVerticesBuffer(colorPointersBuffer.createVertexBuffer("grl_colorPointers", 0, 1)); + const slopesBuffer = new Buffer(this._engine, this._slopes, this._updatable, 3); + this.setVerticesBuffer(slopesBuffer.createVertexBuffer("grl_slopes", 0, 3)); + const widthsBuffer = new Buffer(this._engine, this._ribbonWidths, this._updatable, 1); + this.setVerticesBuffer(widthsBuffer.createVertexBuffer("grl_widths", 0, 1)); + this._widthsBuffer = widthsBuffer; + return vertexData; + } +} +/** + * Default line width + */ +GreasedLineRibbonMesh.DEFAULT_WIDTH = 0.1; +GreasedLineRibbonMesh._RightHandedForwardReadOnlyQuaternion = Quaternion.RotationAxis(Vector3.RightHandedForwardReadOnly, Math.PI / 2); +GreasedLineRibbonMesh._LeftHandedForwardReadOnlyQuaternion = Quaternion.RotationAxis(Vector3.LeftHandedForwardReadOnly, Math.PI / 2); +GreasedLineRibbonMesh._LeftReadOnlyQuaternion = Quaternion.RotationAxis(Vector3.LeftReadOnly, Math.PI / 2); +/** + * Direction which the line segment will be thickened if drawn on the XY plane + */ +GreasedLineRibbonMesh.DIRECTION_XY = Vector3.LeftHandedForwardReadOnly; // doesn't matter in which handed system the scene operates +/** + * Direction which the line segment will be thickened if drawn on the XZ plane + */ +GreasedLineRibbonMesh.DIRECTION_XZ = Vector3.UpReadOnly; +/** + * Direction which the line segment will be thickened if drawn on the YZ plane + */ +GreasedLineRibbonMesh.DIRECTION_YZ = Vector3.LeftReadOnly; + +/** + * How are the colors distributed along the color table + * {@link https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/greased_line#colors-and-colordistribution} + */ +var GreasedLineMeshColorDistribution; +(function (GreasedLineMeshColorDistribution) { + /** + * Do no modify the color table + */ + GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_NONE"] = 0] = "COLOR_DISTRIBUTION_NONE"; + /** + * Repeat the colors until the color table is full + */ + GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_REPEAT"] = 1] = "COLOR_DISTRIBUTION_REPEAT"; + /** + * Distribute the colors evenly through the color table + */ + GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_EVEN"] = 2] = "COLOR_DISTRIBUTION_EVEN"; + /** + * Put the colors to start of the color table a fill the rest with the default color + */ + GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_START"] = 3] = "COLOR_DISTRIBUTION_START"; + /** + * Put the colors to the end of the color table and fill the rest with the default color + */ + GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_END"] = 4] = "COLOR_DISTRIBUTION_END"; + /** + * Put the colors to start and to the end of the color table and fill the gap between with the default color + */ + GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_START_END"] = 5] = "COLOR_DISTRIBUTION_START_END"; +})(GreasedLineMeshColorDistribution || (GreasedLineMeshColorDistribution = {})); +/** + * How are the widths distributed along the width table + * {@link https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/greased_line#widths-and-widthdistribution} + */ +var GreasedLineMeshWidthDistribution; +(function (GreasedLineMeshWidthDistribution) { + /** + * Do no modify the width table + */ + GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_NONE"] = 0] = "WIDTH_DISTRIBUTION_NONE"; + /** + * Repeat the widths until the width table is full + */ + GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_REPEAT"] = 1] = "WIDTH_DISTRIBUTION_REPEAT"; + /** + * Distribute the widths evenly through the width table + */ + GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_EVEN"] = 2] = "WIDTH_DISTRIBUTION_EVEN"; + /** + * Put the widths to start of the width table a fill the rest with the default width + */ + GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_START"] = 3] = "WIDTH_DISTRIBUTION_START"; + /** + * Put the widths to the end of the width table and fill the rest with the default width + */ + GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_END"] = 4] = "WIDTH_DISTRIBUTION_END"; + /** + * Put the widths to start and to the end of the width table and fill the gap between with the default width + */ + GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_START_END"] = 5] = "WIDTH_DISTRIBUTION_START_END"; +})(GreasedLineMeshWidthDistribution || (GreasedLineMeshWidthDistribution = {})); + +/* eslint-disable @typescript-eslint/naming-convention */ +/** + * This file is only for internal use only and should not be used in your code + */ +let _UniqueResolveID = 0; +/** + * Load an asynchronous script (identified by an url) in a module way. When the url returns, the + * content of this file is added into a new script element, attached to the DOM (body element) + * @param scriptUrl defines the url of the script to load + * @param scriptId defines the id of the script element + * @returns a promise request object + * It is up to the caller to provide a script that will do the import and prepare a "returnedValue" variable + * @internal DO NOT USE outside of Babylon.js core + */ +function _LoadScriptModuleAsync(scriptUrl, scriptId) { + return new Promise((resolve, reject) => { + // Need a relay + let windowAsAny; + let windowString; + if (IsWindowObjectExist()) { + windowAsAny = window; + windowString = "window"; + } + else if (typeof self !== "undefined") { + windowAsAny = self; + windowString = "self"; + } + else { + reject(new Error("Cannot load script module outside of a window or a worker")); + return; + } + if (!windowAsAny._LoadScriptModuleResolve) { + windowAsAny._LoadScriptModuleResolve = {}; + } + windowAsAny._LoadScriptModuleResolve[_UniqueResolveID] = resolve; + scriptUrl += ` + ${windowString}._LoadScriptModuleResolve[${_UniqueResolveID}](returnedValue); + ${windowString}._LoadScriptModuleResolve[${_UniqueResolveID}] = undefined; + `; + _UniqueResolveID++; + Tools.LoadScript(scriptUrl, undefined, (message, exception) => { + reject(exception || new Error(message)); + }, scriptId, true); + }); +} + +/** + * Main manifold library + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +let Manifold; +/** + * Promise to wait for the manifold library to be ready + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +let ManifoldPromise; +/** + * Manifold mesh + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +let ManifoldMesh; +/** + * First ID to use for materials indexing + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +let FirstID; +/** + * Wrapper around the Manifold library + * https://manifoldcad.org/ + * Use this class to perform fast boolean operations on meshes + * @see [basic operations](https://playground.babylonjs.com/#IW43EB#15) + * @see [skull vs box](https://playground.babylonjs.com/#JUKXQD#6218) + * @see [skull vs vertex data](https://playground.babylonjs.com/#JUKXQD#6219) + */ +class CSG2 { + /** + * Return the size of a vertex (at least 3 for the position) + */ + get numProp() { + return this._numProp; + } + constructor(manifold, numProp, vertexStructure) { + this._manifold = manifold; + this._numProp = numProp; + this._vertexStructure = vertexStructure; + } + _process(operation, csg) { + if (this.numProp !== csg.numProp) { + throw new Error("CSG must be used with geometries having the same number of properties"); + } + return new CSG2(Manifold[operation](this._manifold, csg._manifold), this.numProp, this._vertexStructure); + } + /** + * Run a difference operation between two CSG + * @param csg defines the CSG to use to create the difference + * @returns a new csg + */ + subtract(csg) { + return this._process("difference", csg); + } + /** + * Run an intersection operation between two CSG + * @param csg defines the CSG to use to create the intersection + * @returns a new csg + */ + intersect(csg) { + return this._process("intersection", csg); + } + /** + * Run an union operation between two CSG + * @param csg defines the CSG to use to create the union + * @returns a new csg + */ + add(csg) { + return this._process("union", csg); + } + /** + * Print debug information about the CSG + */ + printDebug() { + Logger.Log("Genus:" + this._manifold.genus()); + const properties = this._manifold.getProperties(); + Logger.Log("Volume:" + properties.volume); + Logger.Log("surface area:" + properties.surfaceArea); + } + /** + * Generate a vertex data from the CSG + * @param options defines the options to use to rebuild the vertex data + * @returns a new vertex data + */ + toVertexData(options) { + const localOptions = { + rebuildNormals: false, + ...options, + }; + const vertexData = new VertexData(); + const normalComponent = this._vertexStructure.find((c) => c.kind === VertexBuffer.NormalKind); + const manifoldMesh = this._manifold.getMesh(localOptions.rebuildNormals && normalComponent ? [3, 4, 5] : undefined); + vertexData.indices = manifoldMesh.triVerts.length > 65535 ? new Uint32Array(manifoldMesh.triVerts) : new Uint16Array(manifoldMesh.triVerts); + for (let i = 0; i < manifoldMesh.triVerts.length; i += 3) { + vertexData.indices[i] = manifoldMesh.triVerts[i + 2]; + vertexData.indices[i + 1] = manifoldMesh.triVerts[i + 1]; + vertexData.indices[i + 2] = manifoldMesh.triVerts[i]; + } + const vertexCount = manifoldMesh.vertProperties.length / manifoldMesh.numProp; + // Attributes + let offset = 0; + for (let componentIndex = 0; componentIndex < this._vertexStructure.length; componentIndex++) { + const component = this._vertexStructure[componentIndex]; + const data = new Float32Array(vertexCount * component.stride); + for (let i = 0; i < vertexCount; i++) { + for (let strideIndex = 0; strideIndex < component.stride; strideIndex++) { + data[i * component.stride + strideIndex] = manifoldMesh.vertProperties[i * manifoldMesh.numProp + offset + strideIndex]; + } + } + vertexData.set(data, component.kind); + offset += component.stride; + } + // Rebuild mesh from vertex data + return vertexData; + } + /** + * Generate a mesh from the CSG + * @param name defines the name of the mesh + * @param scene defines the scene to use to create the mesh + * @param options defines the options to use to rebuild the mesh + * @returns a new Mesh + */ + toMesh(name, scene, options) { + const localOptions = { + rebuildNormals: false, + centerMesh: true, + ...options, + }; + const vertexData = this.toVertexData({ rebuildNormals: localOptions.rebuildNormals }); + const normalComponent = this._vertexStructure.find((c) => c.kind === VertexBuffer.NormalKind); + const manifoldMesh = this._manifold.getMesh(localOptions.rebuildNormals && normalComponent ? [3, 4, 5] : undefined); + const vertexCount = manifoldMesh.vertProperties.length / manifoldMesh.numProp; + // Rebuild mesh from vertex data + const output = new Mesh(name, scene); + vertexData.applyToMesh(output); + // Center mesh + if (localOptions.centerMesh) { + const extents = output.getBoundingInfo().boundingSphere.center; + output.position.set(-extents.x, -extents.y, -extents.z); + output.bakeCurrentTransformIntoVertices(); + } + // Submeshes + let id = manifoldMesh.runOriginalID[0]; + let start = manifoldMesh.runIndex[0]; + let materialIndex = 0; + const materials = []; + scene = output.getScene(); + for (let run = 0; run < manifoldMesh.numRun; ++run) { + const nextID = manifoldMesh.runOriginalID[run + 1]; + if (nextID !== id) { + const end = manifoldMesh.runIndex[run + 1]; + new SubMesh(materialIndex, 0, vertexCount, start, end - start, output); + materials.push(scene.getMaterialByUniqueID(id - FirstID) || scene.defaultMaterial); + id = nextID; + start = end; + materialIndex++; + } + } + if (localOptions.materialToUse) { + output.material = localOptions.materialToUse; + } + else { + if (materials.length > 1) { + const multiMaterial = new MultiMaterial(name, scene); + multiMaterial.subMaterials = materials; + output.material = multiMaterial; + } + else { + if (output.subMeshes.length > 1) { + // Remove the submeshes as they are not needed + output._createGlobalSubMesh(true); + } + output.material = materials[0]; + } + } + return output; + } + /** + * Dispose the CSG resources + */ + dispose() { + if (this._manifold) { + this._manifold.delete(); + this._manifold = null; + } + } + static _ProcessData(vertexCount, triVerts, structure, numProp, runIndex, runOriginalID) { + const vertProperties = new Float32Array(vertexCount * structure.reduce((acc, cur) => acc + cur.stride, 0)); + for (let i = 0; i < vertexCount; i++) { + let offset = 0; + for (let idx = 0; idx < structure.length; idx++) { + const component = structure[idx]; + for (let strideIndex = 0; strideIndex < component.stride; strideIndex++) { + vertProperties[i * numProp + offset + strideIndex] = component.data[i * component.stride + strideIndex]; + } + offset += component.stride; + } + } + const manifoldMesh = new ManifoldMesh({ numProp: numProp, vertProperties, triVerts, runIndex, runOriginalID }); + manifoldMesh.merge(); + let returnValue; + try { + returnValue = new CSG2(new Manifold(manifoldMesh), numProp, structure); + } + catch (e) { + throw new Error("Error while creating the CSG: " + e.message); + } + return returnValue; + } + static _Construct(data, worldMatrix, runIndex, runOriginalID) { + // Create the MeshGL for I/O with Manifold library. + const triVerts = new Uint32Array(data.indices.length); + // Revert order + for (let i = 0; i < data.indices.length; i += 3) { + triVerts[i] = data.indices[i + 2]; + triVerts[i + 1] = data.indices[i + 1]; + triVerts[i + 2] = data.indices[i]; + } + const tempVector3 = new Vector3(); + let numProp = 3; + const structure = [{ stride: 3, kind: VertexBuffer.PositionKind }]; + if (!worldMatrix) { + structure[0].data = data.positions; + } + else { + const positions = new Float32Array(data.positions.length); + for (let i = 0; i < data.positions.length; i += 3) { + Vector3.TransformCoordinatesFromFloatsToRef(data.positions[i], data.positions[i + 1], data.positions[i + 2], worldMatrix, tempVector3); + tempVector3.toArray(positions, i); + } + structure[0].data = positions; + } + // Normals + const sourceNormals = data.normals; + if (sourceNormals) { + numProp += 3; + structure.push({ stride: 3, kind: VertexBuffer.NormalKind }); + if (!worldMatrix) { + structure[1].data = sourceNormals; + } + else { + const normals = new Float32Array(sourceNormals.length); + for (let i = 0; i < sourceNormals.length; i += 3) { + Vector3.TransformNormalFromFloatsToRef(sourceNormals[i], sourceNormals[i + 1], sourceNormals[i + 2], worldMatrix, tempVector3); + tempVector3.toArray(normals, i); + } + structure[1].data = normals; + } + } + // UVs + for (const kind of [VertexBuffer.UVKind, VertexBuffer.UV2Kind, VertexBuffer.UV3Kind, VertexBuffer.UV4Kind, VertexBuffer.UV5Kind, VertexBuffer.UV6Kind]) { + const sourceUV = data[kind === VertexBuffer.UVKind ? "uvs" : kind]; + if (sourceUV) { + numProp += 2; + structure.push({ stride: 2, kind: kind, data: sourceUV }); + } + } + // Colors + const sourceColors = data.colors; + if (sourceColors) { + numProp += 4; + structure.push({ stride: 4, kind: VertexBuffer.ColorKind, data: sourceColors }); + } + return this._ProcessData(data.positions.length / 3, triVerts, structure, numProp, runIndex, runOriginalID); + } + /** + * Create a new Constructive Solid Geometry from a vertexData + * @param vertexData defines the vertexData to use to create the CSG + * @returns a new CSG2 class + */ + static FromVertexData(vertexData) { + const sourceVertices = vertexData.positions; + const sourceIndices = vertexData.indices; + if (!sourceVertices || !sourceIndices) { + throw new Error("The vertexData must at least have positions and indices"); + } + return this._Construct(vertexData, null); + } + /** + * Create a new Constructive Solid Geometry from a mesh + * @param mesh defines the mesh to use to create the CSG + * @param ignoreWorldMatrix defines if the world matrix should be ignored + * @returns a new CSG2 class + */ + static FromMesh(mesh, ignoreWorldMatrix = false) { + const sourceVertices = mesh.getVerticesData(VertexBuffer.PositionKind); + const sourceIndices = mesh.getIndices(); + const worldMatrix = mesh.computeWorldMatrix(true); + if (!sourceVertices || !sourceIndices) { + throw new Error("The mesh must at least have positions and indices"); + } + // Create a triangle run for each submesh (material) + const starts = [...Array(mesh.subMeshes.length)].map((_, idx) => mesh.subMeshes[idx].indexStart); + // Map the materials to ID. + const sourceMaterial = mesh.material || mesh.getScene().defaultMaterial; + const isMultiMaterial = sourceMaterial.getClassName() === "MultiMaterial"; + const originalIDs = [...Array(mesh.subMeshes.length)].map((_, idx) => { + if (isMultiMaterial) { + return FirstID + sourceMaterial.subMaterials[mesh.subMeshes[idx].materialIndex].uniqueId; + } + return FirstID + sourceMaterial.uniqueId; + }); + // List the runs in sequence. + const indices = Array.from(starts.keys()); + indices.sort((a, b) => starts[a] - starts[b]); + const runIndex = new Uint32Array(indices.map((i) => starts[i])); + const runOriginalID = new Uint32Array(indices.map((i) => originalIDs[i])); + // Process + const data = { + positions: sourceVertices, + indices: sourceIndices, + normals: mesh.getVerticesData(VertexBuffer.NormalKind), + colors: mesh.getVerticesData(VertexBuffer.ColorKind), + uvs: mesh.getVerticesData(VertexBuffer.UVKind), + uvs2: mesh.getVerticesData(VertexBuffer.UV2Kind), + uvs3: mesh.getVerticesData(VertexBuffer.UV3Kind), + uvs4: mesh.getVerticesData(VertexBuffer.UV4Kind), + uvs5: mesh.getVerticesData(VertexBuffer.UV5Kind), + uvs6: mesh.getVerticesData(VertexBuffer.UV6Kind), + }; + return this._Construct(data, ignoreWorldMatrix ? null : worldMatrix, runIndex, runOriginalID); + } +} +/** + * Checks if the Manifold library is ready + * @returns true if the Manifold library is ready + */ +function IsCSG2Ready() { + return Manifold !== undefined; +} +/** + * Initialize the Manifold library + * @param options defines the options to use to initialize the library + */ +async function InitializeCSG2Async(options) { + const localOptions = { + manifoldUrl: "https://unpkg.com/manifold-3d@3.0.1", + ...options, + }; + if (Manifold) { + return; // Already initialized + } + if (ManifoldPromise) { + await ManifoldPromise; + return; + } + if (localOptions.manifoldInstance) { + Manifold = localOptions.manifoldInstance; + ManifoldMesh = localOptions.manifoldMeshInstance; + } + else { + ManifoldPromise = _LoadScriptModuleAsync(` + import Module from '${localOptions.manifoldUrl}/manifold.js'; + const wasm = await Module(); + wasm.setup(); + const {Manifold, Mesh} = wasm; + const returnedValue = {Manifold, Mesh}; + `); + const result = await ManifoldPromise; + Manifold = result.Manifold; + ManifoldMesh = result.Mesh; + } + // Reserve IDs for materials (we consider that there will be no more than 65536 materials) + FirstID = Manifold.reserveIDs(65536); +} + +function getByteIndex(bitIndex) { + return Math.floor(bitIndex / 8); +} +function getBitMask(bitIndex) { + return 1 << bitIndex % 8; +} +/** + * An fixed size array that effectively stores boolean values where each value is a single bit of backing data. + * @remarks + * All bits are initialized to false. + */ +class BitArray { + /** + * Creates a new bit array with a fixed size. + * @param size The number of bits to store. + */ + constructor(size) { + this.size = size; + this._byteArray = new Uint8Array(Math.ceil(this.size / 8)); + } + /** + * Gets the current value at the specified index. + * @param bitIndex The index to get the value from. + * @returns The value at the specified index. + */ + get(bitIndex) { + if (bitIndex >= this.size) { + throw new RangeError("Bit index out of range"); + } + const byteIndex = getByteIndex(bitIndex); + const bitMask = getBitMask(bitIndex); + return (this._byteArray[byteIndex] & bitMask) !== 0; + } + /** + * Sets the value at the specified index. + * @param bitIndex The index to set the value at. + * @param value The value to set. + */ + set(bitIndex, value) { + if (bitIndex >= this.size) { + throw new RangeError("Bit index out of range"); + } + const byteIndex = getByteIndex(bitIndex); + const bitMask = getBitMask(bitIndex); + if (value) { + this._byteArray[byteIndex] |= bitMask; + } + else { + this._byteArray[byteIndex] &= ~bitMask; + } + } +} + +/** + * Sort (in place) the index array so that faces with common indices are close + * @param indices the array of indices to sort + */ +function OptimizeIndices(indices) { + const faces = []; + const faceCount = indices.length / 3; + // Step 1: Break the indices array into faces + for (let i = 0; i < faceCount; i++) { + faces.push([indices[i * 3], indices[i * 3 + 1], indices[i * 3 + 2]]); + } + // Step 2: Build a graph connecting faces sharing a vertex + const vertexToFaceMap = new Map(); + faces.forEach((face, faceIndex) => { + face.forEach((vertex) => { + let face = vertexToFaceMap.get(vertex); + if (!face) { + vertexToFaceMap.set(vertex, (face = [])); + } + face.push(faceIndex); + }); + }); + // Step 3: Traverse faces using DFS to ensure connected faces are close + const visited = new BitArray(faceCount); + const sortedFaces = []; + // Using a stack and not a recursive version to avoid call stack overflow + const deepFirstSearchStack = (startFaceIndex) => { + const stack = [startFaceIndex]; + while (stack.length > 0) { + const currentFaceIndex = stack.pop(); + if (visited.get(currentFaceIndex)) { + continue; + } + visited.set(currentFaceIndex, true); + sortedFaces.push(faces[currentFaceIndex]); + // Push unvisited neighbors (faces sharing a vertex) onto the stack + faces[currentFaceIndex].forEach((vertex) => { + const neighbors = vertexToFaceMap.get(vertex); + if (!neighbors) { + return; + } + neighbors.forEach((neighborFaceIndex) => { + if (!visited.get(neighborFaceIndex)) { + stack.push(neighborFaceIndex); + } + }); + }); + } + }; + // Start DFS from the first face + for (let i = 0; i < faceCount; i++) { + if (!visited.get(i)) { + deepFirstSearchStack(i); + } + } + // Step 4: Flatten the sorted faces back into an array + let index = 0; + sortedFaces.forEach((face) => { + indices[index++] = face[0]; + indices[index++] = face[1]; + indices[index++] = face[2]; + }); +} + +const mesh_vertexData_functions = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + OptimizeIndices +}, Symbol.toStringTag, { value: 'Module' })); + +const _positionShift = Math.pow(10, 4); +/** + * Rounds a number (simulate integer rounding) + * @internal + */ +function round(x) { + return (x + (x > 0 ? 0.5 : -0.5)) << 0; +} +/** + * Generates a hash string from a number + * @internal + */ +function hashFromNumber(num, shift = _positionShift) { + let roundedNumber = round(num * shift); + if (roundedNumber === 0) { + roundedNumber = 0; // prevent -0 + } + return `${roundedNumber}`; +} +/** + * Generates a hash string from a Vector3 + * @internal + */ +function hashFromVector(v, shift = _positionShift) { + return `${hashFromNumber(v.x, shift)},${hashFromNumber(v.y, shift)},${hashFromNumber(v.z, shift)}`; +} +/** + * Gathers attribute names from a VertexData object + * @internal + */ +function gatherAttributes(vertexData) { + const desired = ["positions", "normals", "uvs"]; + const available = Object.keys(vertexData).filter((k) => Array.isArray(vertexData[k])); + return Array.from(new Set([...desired, ...available])); +} +/** + * Sets triangle data into an attribute array + * @internal + */ +function setTriangle(arr, index, itemSize, vec0, vec1, vec2) { + for (let i = 0; i < itemSize; i++) { + arr[index + i] = vec0[i]; + arr[index + itemSize + i] = vec1[i]; + arr[index + 2 * itemSize + i] = vec2[i]; + } +} +/** + * Converts indexed VertexData to a non-indexed form + * @internal + */ +function toNonIndexed(vertexData) { + if (!vertexData.indices || vertexData.indices.length === 0) { + return vertexData; // already non-indexed + } + const newPositions = []; + const newNormals = []; + const newUVs = []; + const indices = vertexData.indices; + const pos = vertexData.positions; + const norm = vertexData.normals; + const uv = vertexData.uvs; + for (let i = 0; i < indices.length; i++) { + const idx = indices[i]; + newPositions.push(pos[3 * idx], pos[3 * idx + 1], pos[3 * idx + 2]); + if (norm) { + newNormals.push(norm[3 * idx], norm[3 * idx + 1], norm[3 * idx + 2]); + } + if (uv) { + newUVs.push(uv[2 * idx], uv[2 * idx + 1]); + } + } + const newVertexData = new VertexData(); + newVertexData.positions = newPositions; + if (newNormals.length) { + newVertexData.normals = newNormals; + } + if (newUVs.length) { + newVertexData.uvs = newUVs; + } + return newVertexData; +} +/** Helper to read a Vector3 from an attribute array + * @internal + */ +function readVector(destination, attribute, index, itemSize) { + if (itemSize === 3) { + destination.fromArray(attribute, index * 3); + return; + } + // For uvs (itemSize 2), return a Vector3 with z = 0. + destination.set(attribute[index * 2], attribute[index * 2 + 1], 0); +} +function processFlatAttribute(source, vertexCount, output) { + const v0 = new Vector3(); + const v1 = new Vector3(); + const v2 = new Vector3(); + const m01 = new Vector3(); + const m12 = new Vector3(); + const m20 = new Vector3(); + for (let i = 0; i < vertexCount; i += 3) { + const j = i * 3; + v0.set(source[j], source[j + 1], source[j + 2]); + v1.set(source[j + 3], source[j + 4], source[j + 5]); + v2.set(source[j + 6], source[j + 7], source[j + 8]); + v0.addToRef(v1, m01); + m01.scaleInPlace(0.5); + v1.addToRef(v2, m12); + m12.scaleInPlace(0.5); + v2.addToRef(v0, m20); + m20.scaleInPlace(0.5); + // Positions + output.push(v0.x, v0.y, v0.z, m01.x, m01.y, m01.z, m20.x, m20.y, m20.z); + output.push(v1.x, v1.y, v1.z, m12.x, m12.y, m12.z, m01.x, m01.y, m01.z); + output.push(v2.x, v2.y, v2.z, m20.x, m20.y, m20.z, m12.x, m12.y, m12.z); + output.push(m01.x, m01.y, m01.z, m12.x, m12.y, m12.z, m20.x, m20.y, m20.z); + } +} +/** + * Applies one iteration of flat subdivision (each triangle becomes 4). + * @internal + */ +function flat(vertexData) { + const data = toNonIndexed(vertexData); + const positions = data.positions; + const normals = data.normals; + const uvs = data.uvs; + const vertexCount = positions.length / 3; + const newPositions = []; + const newNormals = []; + const newUVs = []; + processFlatAttribute(positions, vertexCount, newPositions); + if (normals && normals.length) { + processFlatAttribute(normals, vertexCount, newNormals); + } + if (uvs && uvs.length) { + for (let i = 0; i < vertexCount; i += 3) { + const j = i * 2; + const uv0 = [uvs[j], uvs[j + 1]]; + const uv1 = [uvs[j + 2], uvs[j + 3]]; + const uv2 = [uvs[j + 4], uvs[j + 5]]; + const uv01 = [(uv0[0] + uv1[0]) / 2, (uv0[1] + uv1[1]) / 2]; + const uv12 = [(uv1[0] + uv2[0]) / 2, (uv1[1] + uv2[1]) / 2]; + const uv20 = [(uv2[0] + uv0[0]) / 2, (uv2[1] + uv0[1]) / 2]; + newUVs.push(...uv0, ...uv01, ...uv20); + newUVs.push(...uv1, ...uv12, ...uv01); + newUVs.push(...uv2, ...uv20, ...uv12); + newUVs.push(...uv01, ...uv12, ...uv20); + } + } + const newVertexCount = newPositions.length / 3; + const newIndices = []; + for (let i = 0; i < newVertexCount; i++) { + newIndices.push(i); + } + const newVertexData = new VertexData(); + newVertexData.positions = newPositions; + if (newNormals.length) { + newVertexData.normals = newNormals; + } + if (newUVs.length) { + newVertexData.uvs = newUVs; + } + newVertexData.indices = newIndices; + return newVertexData; +} +/** + * Applies one iteration of smooth subdivision with vertex averaging. + * This function uses the subdivideAttribute routine to adjust vertex data. + * @internal + */ +function smooth(vertexData, options) { + // Convert to non-indexed and apply flat subdivision first. + const sourceData = toNonIndexed(vertexData); + const flatData = flat(sourceData); + const attributeList = gatherAttributes(sourceData); + const origPositions = sourceData.positions; + const flatPositions = flatData.positions; + const vertexCount = origPositions.length / 3; + // Build connectivity maps from the original geometry. + const hashToIndex = {}; + const existingNeighbors = {}; + const flatOpposites = {}; + const existingEdges = {}; + function addNeighbor(posHash, neighborHash, index) { + if (!existingNeighbors[posHash]) { + existingNeighbors[posHash] = {}; + } + if (!existingNeighbors[posHash][neighborHash]) { + existingNeighbors[posHash][neighborHash] = []; + } + existingNeighbors[posHash][neighborHash].push(index); + } + function addOpposite(posHash, index) { + if (!flatOpposites[posHash]) { + flatOpposites[posHash] = []; + } + flatOpposites[posHash].push(index); + } + function addEdgePoint(posHash, edgeHash) { + if (!existingEdges[posHash]) { + existingEdges[posHash] = new Set(); + } + existingEdges[posHash].add(edgeHash); + } + const temp = new Vector3(); + const v0 = new Vector3(); + const v1 = new Vector3(); + const v2 = new Vector3(); + const m01 = new Vector3(); + const m12 = new Vector3(); + const m20 = new Vector3(); + // Process original positions + for (let i = 0; i < vertexCount; i += 3) { + readVector(v0, origPositions, i, 3); + readVector(v1, origPositions, i + 1, 3); + readVector(v2, origPositions, i + 2, 3); + const h0 = hashFromVector(v0); + const h1 = hashFromVector(v1); + const h2 = hashFromVector(v2); + addNeighbor(h0, h1, i + 1); + addNeighbor(h0, h2, i + 2); + addNeighbor(h1, h0, i); + addNeighbor(h1, h2, i + 2); + addNeighbor(h2, h0, i); + addNeighbor(h2, h1, i + 1); + // Opposites from flat subdivision: calculate midpoints. + v0.addToRef(v1, m01); + m01.scaleInPlace(0.5); + v1.addToRef(v2, m12); + m12.scaleInPlace(0.5); + v2.addToRef(v0, m20); + m20.scaleInPlace(0.5); + addOpposite(hashFromVector(m01), i + 2); + addOpposite(hashFromVector(m12), i); + addOpposite(hashFromVector(m20), i + 1); + // Track edges for preserveEdges. + addEdgePoint(h0, hashFromVector(m01)); + addEdgePoint(h0, hashFromVector(m20)); + addEdgePoint(h1, hashFromVector(m01)); + addEdgePoint(h1, hashFromVector(m12)); + addEdgePoint(h2, hashFromVector(m12)); + addEdgePoint(h2, hashFromVector(m20)); + } + // Build map from flat positions to indices. + for (let i = 0; i < flatPositions.length / 3; i++) { + readVector(temp, flatPositions, i, 3); + const h = hashFromVector(temp); + if (!hashToIndex[h]) { + hashToIndex[h] = []; + } + hashToIndex[h].push(i); + } + // Prepare temporary vectors for subdivideAttribute. + const _vertex = [new Vector3(), new Vector3(), new Vector3()]; + const _position = [new Vector3(), new Vector3(), new Vector3()]; + const _average = new Vector3(); + const _temp = new Vector3(); + // subdivideAttribute: adjusts vertex attributes using Loop’s averaging rules. + function subdivideAttribute(attributeName, existingAttribute, flattenedAttribute) { + const itemSize = attributeName === "uvs" ? 2 : 3; + const flatVertexCount = flatPositions.length / 3; + const floatArray = new Array(flatVertexCount * itemSize); + let index = 0; + for (let i = 0; i < flatVertexCount; i += 3) { + for (let v = 0; v < 3; v++) { + if (attributeName === "uvs" && !options.uvSmooth) { + // Simply copy UVs. + readVector(_vertex[v], flattenedAttribute, i + v, 2); + } + else if (attributeName === "normals") { + readVector(_position[v], flatPositions, i + v, 3); + const positionHash = hashFromVector(_position[v]); + const positionsArr = hashToIndex[positionHash] || []; + const k = positionsArr.length; + const beta = 0.75 / k; + const startWeight = 1.0 - beta * k; + readVector(_vertex[v], flattenedAttribute, i + v, 3); + _vertex[v].scaleInPlace(startWeight); + positionsArr.forEach((positionIndex) => { + readVector(_average, flattenedAttribute, positionIndex, 3); + _average.scaleInPlace(beta); + _vertex[v].addInPlace(_average); + }); + } + else { + // 'positions', 'colors', etc. + readVector(_vertex[v], flattenedAttribute, i + v, itemSize); + readVector(_position[v], flatPositions, i + v, 3); + const positionHash = hashFromVector(_position[v]); + const neighbors = existingNeighbors[positionHash]; + const opposites = flatOpposites[positionHash]; + if (neighbors) { + if (options.preserveEdges) { + const edgeSet = existingEdges[positionHash]; + let hasPair = true; + edgeSet.forEach((edgeHash) => { + if (flatOpposites[edgeHash] && flatOpposites[edgeHash].length % 2 !== 0) { + hasPair = false; + } + }); + if (!hasPair) { + // If edges aren't paired, skip adjustment. + continue; + } + } + const neighborKeys = Object.keys(neighbors); + const k = neighborKeys.length; + const beta = (1 / k) * (5 / 8 - Math.pow(3 / 8 + (1 / 4) * Math.cos((2 * Math.PI) / k), 2)); + const heavy = 1 / k / k; + const weight = Scalar.Lerp(heavy, beta, options.weight); + const startWeight = 1.0 - weight * k; + _vertex[v].scaleInPlace(startWeight); + for (const neighborHash in neighbors) { + const neighborIndices = neighbors[neighborHash]; + _average.set(0, 0, 0); + neighborIndices.forEach((neighborIndex) => { + readVector(_temp, existingAttribute, neighborIndex, itemSize); + _average.addInPlace(_temp); + }); + _average.scaleInPlace(1 / neighborIndices.length); + _average.scaleInPlace(weight); + _vertex[v].addInPlace(_average); + } + } + else if (opposites && opposites.length === 2) { + const k = opposites.length; + const beta = 0.125; // 1/8 + const startWeight = 1.0 - beta * k; + _vertex[v].scaleInPlace(startWeight); + opposites.forEach((oppositeIndex) => { + readVector(_average, existingAttribute, oppositeIndex, itemSize); + _average.scaleInPlace(beta); + _vertex[v].addInPlace(_average); + }); + } + } + } + // Write out new triangle vertices. + setTriangle(floatArray, index, itemSize, _vertex[0].asArray(), _vertex[1].asArray(), _vertex[2].asArray()); + index += itemSize * 3; + } + return floatArray; + } + // Build new attributes for the smoothed geometry. + const smoothData = new VertexData(); + attributeList.forEach((attributeName) => { + if (attributeName === "indices") { + return; + } + const existingAttribute = sourceData[attributeName]; + const flattenedAttribute = flatData[attributeName]; + if (!existingAttribute || !flattenedAttribute) { + return; + } + const newArray = subdivideAttribute(attributeName, existingAttribute, flattenedAttribute); + smoothData[attributeName] = newArray; + }); + // Rebuild indices sequentially. + const newPositions = smoothData.positions; + const newIndices = []; + for (let i = 0; i < newPositions.length / 3; i++) { + newIndices.push(i); + } + smoothData.indices = newIndices; + return smoothData; +} +/** + * Subdivide a vertexData using Loop algorithm + * @param vertexData The vertexData to subdivide + * @param level The number of times to subdivide + * @param options The options to use when subdividing + * @returns The subdivided vertexData + */ +function Subdivide(vertexData, level, options) { + options = { + flatOnly: false, + uvSmooth: false, + preserveEdges: false, + weight: 1, + ...options, + }; + if (!vertexData.positions || vertexData.positions.length === 0 || level <= 0) { + return vertexData; + } + // Clone the input + let modified = vertexData.clone(); + for (let i = 0; i < level; i++) { + if (options.flatOnly) { + modified = flat(modified); + } + else { + modified = smooth(modified, options); + } + } + return modified; +} + +/** + * Defines the kind of connection point for node geometry + */ +var NodeGeometryBlockConnectionPointTypes; +(function (NodeGeometryBlockConnectionPointTypes) { + /** Int */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Int"] = 1] = "Int"; + /** Float */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Float"] = 2] = "Float"; + /** Vector2 */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Vector2"] = 4] = "Vector2"; + /** Vector3 */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Vector3"] = 8] = "Vector3"; + /** Vector4 */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Vector4"] = 16] = "Vector4"; + /** Matrix */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Matrix"] = 32] = "Matrix"; + /** Geometry */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Geometry"] = 64] = "Geometry"; + /** Texture */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Texture"] = 128] = "Texture"; + /** Detect type based on connection */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["AutoDetect"] = 1024] = "AutoDetect"; + /** Output type that will be defined by input type */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["BasedOnInput"] = 2048] = "BasedOnInput"; + /** Undefined */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Undefined"] = 4096] = "Undefined"; + /** Bitmask of all types */ + NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["All"] = 4095] = "All"; +})(NodeGeometryBlockConnectionPointTypes || (NodeGeometryBlockConnectionPointTypes = {})); + +/** + * Enum used to define the compatibility state between two connection points + */ +var NodeGeometryConnectionPointCompatibilityStates; +(function (NodeGeometryConnectionPointCompatibilityStates) { + /** Points are compatibles */ + NodeGeometryConnectionPointCompatibilityStates[NodeGeometryConnectionPointCompatibilityStates["Compatible"] = 0] = "Compatible"; + /** Points are incompatible because of their types */ + NodeGeometryConnectionPointCompatibilityStates[NodeGeometryConnectionPointCompatibilityStates["TypeIncompatible"] = 1] = "TypeIncompatible"; + /** Points are incompatible because they are in the same hierarchy **/ + NodeGeometryConnectionPointCompatibilityStates[NodeGeometryConnectionPointCompatibilityStates["HierarchyIssue"] = 2] = "HierarchyIssue"; +})(NodeGeometryConnectionPointCompatibilityStates || (NodeGeometryConnectionPointCompatibilityStates = {})); +/** + * Defines the direction of a connection point + */ +var NodeGeometryConnectionPointDirection; +(function (NodeGeometryConnectionPointDirection) { + /** Input */ + NodeGeometryConnectionPointDirection[NodeGeometryConnectionPointDirection["Input"] = 0] = "Input"; + /** Output */ + NodeGeometryConnectionPointDirection[NodeGeometryConnectionPointDirection["Output"] = 1] = "Output"; +})(NodeGeometryConnectionPointDirection || (NodeGeometryConnectionPointDirection = {})); +/** + * Defines a connection point for a block + */ +class NodeGeometryConnectionPoint { + /** Gets the direction of the point */ + get direction() { + return this._direction; + } + /** + * Gets or sets the connection point type (default is float) + */ + get type() { + if (this._type === NodeGeometryBlockConnectionPointTypes.AutoDetect) { + if (this._ownerBlock.isInput) { + return this._ownerBlock.type; + } + if (this._connectedPoint) { + return this._connectedPoint.type; + } + if (this._linkedConnectionSource) { + if (this._linkedConnectionSource.isConnected) { + return this._linkedConnectionSource.type; + } + if (this._linkedConnectionSource._defaultConnectionPointType) { + return this._linkedConnectionSource._defaultConnectionPointType; + } + } + if (this._defaultConnectionPointType) { + return this._defaultConnectionPointType; + } + } + if (this._type === NodeGeometryBlockConnectionPointTypes.BasedOnInput) { + if (this._typeConnectionSource) { + if (!this._typeConnectionSource.isConnected && this._defaultConnectionPointType) { + return this._defaultConnectionPointType; + } + return this._typeConnectionSource.type; + } + else if (this._defaultConnectionPointType) { + return this._defaultConnectionPointType; + } + } + return this._type; + } + set type(value) { + this._type = value; + } + /** + * Gets a boolean indicating that the current point is connected to another NodeMaterialBlock + */ + get isConnected() { + return this.connectedPoint !== null || this.hasEndpoints; + } + /** Get the other side of the connection (if any) */ + get connectedPoint() { + return this._connectedPoint; + } + /** Get the block that owns this connection point */ + get ownerBlock() { + return this._ownerBlock; + } + /** Get the block connected on the other side of this connection (if any) */ + get sourceBlock() { + if (!this._connectedPoint) { + return null; + } + return this._connectedPoint.ownerBlock; + } + /** Get the block connected on the endpoints of this connection (if any) */ + get connectedBlocks() { + if (this._endpoints.length === 0) { + return []; + } + return this._endpoints.map((e) => e.ownerBlock); + } + /** Gets the list of connected endpoints */ + get endpoints() { + return this._endpoints; + } + /** Gets a boolean indicating if that output point is connected to at least one input */ + get hasEndpoints() { + return this._endpoints && this._endpoints.length > 0; + } + /** Get the inner type (ie AutoDetect for instance instead of the inferred one) */ + get innerType() { + if (this._linkedConnectionSource && !this._isMainLinkSource && this._linkedConnectionSource.isConnected) { + return this.type; + } + return this._type; + } + /** @internal */ + _resetCounters() { + this._callCount = 0; + this._executionCount = 0; + } + /** + * Gets the number of times this point was called + */ + get callCount() { + return this._callCount; + } + /** + * Gets the number of times this point was executed + */ + get executionCount() { + return this._executionCount; + } + /** + * Gets the value represented by this connection point + * @param state current evaluation state + * @returns the connected value or the value if nothing is connected + */ + getConnectedValue(state) { + if (this.isConnected) { + if (this._connectedPoint?._storedFunction) { + this._connectedPoint._callCount++; + this._connectedPoint._executionCount++; + return this._connectedPoint._storedFunction(state); + } + this._connectedPoint._callCount++; + this._connectedPoint._executionCount = 1; + return this._connectedPoint._storedValue; + } + this._callCount++; + this._executionCount = 1; + return this.value; + } + /** + * Creates a new connection point + * @param name defines the connection point name + * @param ownerBlock defines the block hosting this connection point + * @param direction defines the direction of the connection point + */ + constructor(name, ownerBlock, direction) { + /** @internal */ + this._connectedPoint = null; + /** @internal */ + this._storedValue = null; + /** @internal */ + this._storedFunction = null; + /** @internal */ + this._acceptedConnectionPointType = null; + this._endpoints = new Array(); + this._type = NodeGeometryBlockConnectionPointTypes.Geometry; + /** @internal */ + this._linkedConnectionSource = null; + /** @internal */ + this._typeConnectionSource = null; + /** @internal */ + this._defaultConnectionPointType = null; + /** @internal */ + this._isMainLinkSource = false; + /** + * Gets or sets the additional types supported by this connection point + */ + this.acceptedConnectionPointTypes = []; + /** + * Gets or sets the additional types excluded by this connection point + */ + this.excludedConnectionPointTypes = []; + /** + * Observable triggered when this point is connected + */ + this.onConnectionObservable = new Observable(); + /** + * Observable triggered when this point is disconnected + */ + this.onDisconnectionObservable = new Observable(); + /** + * Gets or sets a boolean indicating that this connection point is exposed on a frame + */ + this.isExposedOnFrame = false; + /** + * Gets or sets number indicating the position that the port is exposed to on a frame + */ + this.exposedPortPosition = -1; + /** + * Gets the default value used for this point at creation time + */ + this.defaultValue = null; + /** + * Gets or sets the default value used for this point if nothing is connected + */ + this.value = null; + /** + * Gets or sets the min value accepted for this point if nothing is connected + */ + this.valueMin = null; + /** + * Gets or sets the max value accepted for this point if nothing is connected + */ + this.valueMax = null; + /** @internal */ + this._callCount = 0; + /** @internal */ + this._executionCount = 0; + this._ownerBlock = ownerBlock; + this.name = name; + this._direction = direction; + } + /** + * Gets the current class name e.g. "NodeMaterialConnectionPoint" + * @returns the class name + */ + getClassName() { + return "NodeGeometryConnectionPoint"; + } + /** + * Gets a boolean indicating if the current point can be connected to another point + * @param connectionPoint defines the other connection point + * @returns a boolean + */ + canConnectTo(connectionPoint) { + return this.checkCompatibilityState(connectionPoint) === 0 /* NodeGeometryConnectionPointCompatibilityStates.Compatible */; + } + /** + * Gets a number indicating if the current point can be connected to another point + * @param connectionPoint defines the other connection point + * @returns a number defining the compatibility state + */ + checkCompatibilityState(connectionPoint) { + const ownerBlock = this._ownerBlock; + const otherBlock = connectionPoint.ownerBlock; + if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeGeometryBlockConnectionPointTypes.AutoDetect) { + // Accepted types + if (connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) { + return 0 /* NodeGeometryConnectionPointCompatibilityStates.Compatible */; + } + else { + return 1 /* NodeGeometryConnectionPointCompatibilityStates.TypeIncompatible */; + } + } + // Excluded + if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) { + return 1 /* NodeGeometryConnectionPointCompatibilityStates.TypeIncompatible */; + } + // Check hierarchy + let targetBlock = otherBlock; + let sourceBlock = ownerBlock; + if (this.direction === 0 /* NodeGeometryConnectionPointDirection.Input */) { + targetBlock = ownerBlock; + sourceBlock = otherBlock; + } + if (targetBlock.isAnAncestorOf(sourceBlock)) { + return 2 /* NodeGeometryConnectionPointCompatibilityStates.HierarchyIssue */; + } + return 0 /* NodeGeometryConnectionPointCompatibilityStates.Compatible */; + } + /** + * Connect this point to another connection point + * @param connectionPoint defines the other connection point + * @param ignoreConstraints defines if the system will ignore connection type constraints (default is false) + * @returns the current connection point + */ + connectTo(connectionPoint, ignoreConstraints = false) { + if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) { + // eslint-disable-next-line no-throw-literal + throw "Cannot connect these two connectors."; + } + this._endpoints.push(connectionPoint); + connectionPoint._connectedPoint = this; + this.onConnectionObservable.notifyObservers(connectionPoint); + connectionPoint.onConnectionObservable.notifyObservers(this); + return this; + } + /** + * Disconnect this point from one of his endpoint + * @param endpoint defines the other connection point + * @returns the current connection point + */ + disconnectFrom(endpoint) { + const index = this._endpoints.indexOf(endpoint); + if (index === -1) { + return this; + } + this._endpoints.splice(index, 1); + endpoint._connectedPoint = null; + this.onDisconnectionObservable.notifyObservers(endpoint); + endpoint.onDisconnectionObservable.notifyObservers(this); + return this; + } + /** + * Fill the list of excluded connection point types with all types other than those passed in the parameter + * @param mask Types (ORed values of NodeMaterialBlockConnectionPointTypes) that are allowed, and thus will not be pushed to the excluded list + */ + addExcludedConnectionPointFromAllowedTypes(mask) { + let bitmask = 1; + while (bitmask < NodeGeometryBlockConnectionPointTypes.All) { + if (!(mask & bitmask)) { + this.excludedConnectionPointTypes.push(bitmask); + } + bitmask = bitmask << 1; + } + } + /** + * Serializes this point in a JSON representation + * @param isInput defines if the connection point is an input (default is true) + * @returns the serialized point object + */ + serialize(isInput = true) { + const serializationObject = {}; + serializationObject.name = this.name; + serializationObject.displayName = this.displayName; + if (this.value !== undefined && this.value !== null) { + if (this.value.asArray) { + serializationObject.valueType = "BABYLON." + this.value.getClassName(); + serializationObject.value = this.value.asArray(); + } + else { + serializationObject.valueType = "number"; + serializationObject.value = this.value; + } + } + if (isInput && this.connectedPoint) { + serializationObject.inputName = this.name; + serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId; + serializationObject.targetConnectionName = this.connectedPoint.name; + serializationObject.isExposedOnFrame = true; + serializationObject.exposedPortPosition = this.exposedPortPosition; + } + if (this.isExposedOnFrame || this.exposedPortPosition >= 0) { + serializationObject.isExposedOnFrame = true; + serializationObject.exposedPortPosition = this.exposedPortPosition; + } + return serializationObject; + } + /** + * Release resources + */ + dispose() { + this.onConnectionObservable.clear(); + this.onDisconnectionObservable.clear(); + } +} + +/** + * Defines a block that can be used inside a node based geometry + */ +class NodeGeometryBlock { + /** + * Gets the time spent to build this block (in ms) + */ + get buildExecutionTime() { + return this._buildExecutionTime; + } + /** + * Gets the list of input points + */ + get inputs() { + return this._inputs; + } + /** Gets the list of output points */ + get outputs() { + return this._outputs; + } + /** + * Gets or set the name of the block + */ + get name() { + return this._name; + } + set name(value) { + this._name = value; + } + /** + * Gets a boolean indicating if this block is an input + */ + get isInput() { + return this._isInput; + } + /** + * Gets a boolean indicating if this block is a teleport out + */ + get isTeleportOut() { + return this._isTeleportOut; + } + /** + * Gets a boolean indicating if this block is a teleport in + */ + get isTeleportIn() { + return this._isTeleportIn; + } + /** + * Gets a boolean indicating if this block is a debug block + */ + get isDebug() { + return this._isDebug; + } + /** + * Gets a boolean indicating that this block can only be used once per NodeGeometry + */ + get isUnique() { + return this._isUnique; + } + /** + * Gets the current class name e.g. "NodeGeometryBlock" + * @returns the class name + */ + getClassName() { + return "NodeGeometryBlock"; + } + _inputRename(name) { + return name; + } + _outputRename(name) { + return name; + } + /** + * Checks if the current block is an ancestor of a given block + * @param block defines the potential descendant block to check + * @returns true if block is a descendant + */ + isAnAncestorOf(block) { + for (const output of this._outputs) { + if (!output.hasEndpoints) { + continue; + } + for (const endpoint of output.endpoints) { + if (endpoint.ownerBlock === block) { + return true; + } + if (endpoint.ownerBlock.isAnAncestorOf(block)) { + return true; + } + } + } + return false; + } + /** + * Checks if the current block is an ancestor of a given type + * @param type defines the potential type to check + * @returns true if block is a descendant + */ + isAnAncestorOfType(type) { + if (this.getClassName() === type) { + return true; + } + for (const output of this._outputs) { + if (!output.hasEndpoints) { + continue; + } + for (const endpoint of output.endpoints) { + if (endpoint.ownerBlock.isAnAncestorOfType(type)) { + return true; + } + } + } + return false; + } + /** + * Get the first descendant using a predicate + * @param predicate defines the predicate to check + * @returns descendant or null if none found + */ + getDescendantOfPredicate(predicate) { + if (predicate(this)) { + return this; + } + for (const output of this._outputs) { + if (!output.hasEndpoints) { + continue; + } + for (const endpoint of output.endpoints) { + const descendant = endpoint.ownerBlock.getDescendantOfPredicate(predicate); + if (descendant) { + return descendant; + } + } + } + return null; + } + /** + * @internal + */ + get _isReadyState() { + return null; + } + /** + * Creates a new NodeGeometryBlock + * @param name defines the block name + */ + constructor(name) { + this._name = ""; + this._isInput = false; + this._isTeleportOut = false; + this._isTeleportIn = false; + this._isDebug = false; + this._isUnique = false; + this._buildExecutionTime = 0; + /** + * Gets an observable raised when the block is built + */ + this.onBuildObservable = new Observable(); + /** @internal */ + this._inputs = new Array(); + /** @internal */ + this._outputs = new Array(); + /** @internal */ + this._codeVariableName = ""; + /** Gets or sets a boolean indicating that this input can be edited from a collapsed frame */ + this.visibleOnFrame = false; + this._name = name; + this.uniqueId = UniqueIdGenerator.UniqueId; + } + /** + * Register a new input. Must be called inside a block constructor + * @param name defines the connection point name + * @param type defines the connection point type + * @param isOptional defines a boolean indicating that this input can be omitted + * @param value value to return if there is no connection + * @param valueMin min value accepted for value + * @param valueMax max value accepted for value + * @returns the current block + */ + registerInput(name, type, isOptional = false, value, valueMin, valueMax) { + const point = new NodeGeometryConnectionPoint(name, this, 0 /* NodeGeometryConnectionPointDirection.Input */); + point.type = type; + point.isOptional = isOptional; + point.defaultValue = value; + point.value = value; + point.valueMin = valueMin; + point.valueMax = valueMax; + this._inputs.push(point); + return this; + } + /** + * Register a new output. Must be called inside a block constructor + * @param name defines the connection point name + * @param type defines the connection point type + * @param point an already created connection point. If not provided, create a new one + * @returns the current block + */ + registerOutput(name, type, point) { + point = point ?? new NodeGeometryConnectionPoint(name, this, 1 /* NodeGeometryConnectionPointDirection.Output */); + point.type = type; + this._outputs.push(point); + return this; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _buildBlock(state) { + // Empty. Must be defined by child nodes + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _customBuildStep(state) { + // Must be implemented by children + } + /** + * Build the current node and generate the vertex data + * @param state defines the current generation state + * @returns true if already built + */ + build(state) { + if (this._buildId === state.buildId) { + return true; + } + if (this._outputs.length > 0) { + if (!this._outputs.some((o) => o.hasEndpoints) && !this.isDebug) { + return false; + } + this.outputs.forEach((o) => o._resetCounters()); + } + this._buildId = state.buildId; + // Check if "parent" blocks are compiled + for (const input of this._inputs) { + if (!input.connectedPoint) { + if (!input.isOptional) { + // Emit a warning + state.notConnectedNonOptionalInputs.push(input); + } + continue; + } + const block = input.connectedPoint.ownerBlock; + if (block && block !== this) { + block.build(state); + } + } + this._customBuildStep(state); + // Logs + if (state.verbose) { + Logger.Log(`Building ${this.name} [${this.getClassName()}]`); + } + const now = PrecisionDate.Now; + this._buildBlock(state); + this._buildExecutionTime = PrecisionDate.Now - now; + this.onBuildObservable.notifyObservers(this); + return false; + } + _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) { + if (looseCoupling) { + this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0]; + } + else { + this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1]; + this._inputs[inputIndex0]._isMainLinkSource = true; + } + this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0]; + } + /** + * Initialize the block and prepare the context for build + */ + initialize() { + // Do nothing + } + /** + * Lets the block try to connect some inputs automatically + * @param _nodeGeometry defines the node geometry to use for auto connection + */ + autoConfigure(_nodeGeometry) { + // Do nothing + } + /** + * Find an input by its name + * @param name defines the name of the input to look for + * @returns the input or null if not found + */ + getInputByName(name) { + const filter = this._inputs.filter((e) => e.name === name); + if (filter.length) { + return filter[0]; + } + return null; + } + /** + * Find an output by its name + * @param name defines the name of the output to look for + * @returns the output or null if not found + */ + getOutputByName(name) { + const filter = this._outputs.filter((e) => e.name === name); + if (filter.length) { + return filter[0]; + } + return null; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = {}; + serializationObject.customType = "BABYLON." + this.getClassName(); + serializationObject.id = this.uniqueId; + serializationObject.name = this.name; + serializationObject.visibleOnFrame = this.visibleOnFrame; + serializationObject.inputs = []; + serializationObject.outputs = []; + for (const input of this.inputs) { + serializationObject.inputs.push(input.serialize()); + } + for (const output of this.outputs) { + serializationObject.outputs.push(output.serialize(false)); + } + return serializationObject; + } + /** + * @internal + */ + _deserialize(serializationObject) { + this._name = serializationObject.name; + this.comments = serializationObject.comments; + this.visibleOnFrame = !!serializationObject.visibleOnFrame; + this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject); + } + _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) { + const serializedInputs = serializationObject.inputs; + const serializedOutputs = serializationObject.outputs; + if (serializedInputs) { + serializedInputs.forEach((port) => { + const input = this.inputs.find((i) => i.name === port.name); + if (!input) { + return; + } + if (port.displayName) { + input.displayName = port.displayName; + } + if (port.isExposedOnFrame) { + input.isExposedOnFrame = port.isExposedOnFrame; + input.exposedPortPosition = port.exposedPortPosition; + } + if (port.value !== undefined && port.value !== null) { + if (port.valueType === "number") { + input.value = port.value; + } + else { + const valueType = GetClass(port.valueType); + if (valueType) { + input.value = valueType.FromArray(port.value); + } + } + } + }); + } + if (serializedOutputs) { + serializedOutputs.forEach((port, i) => { + if (port.displayName) { + this.outputs[i].displayName = port.displayName; + } + if (port.isExposedOnFrame) { + this.outputs[i].isExposedOnFrame = port.isExposedOnFrame; + this.outputs[i].exposedPortPosition = port.exposedPortPosition; + } + }); + } + } + _dumpPropertiesCode() { + const variableName = this._codeVariableName; + return `${variableName}.visibleOnFrame = ${this.visibleOnFrame};\n`; + } + /** + * @internal + */ + _dumpCodeForOutputConnections(alreadyDumped) { + let codeString = ""; + if (alreadyDumped.indexOf(this) !== -1) { + return codeString; + } + alreadyDumped.push(this); + for (const input of this.inputs) { + if (!input.isConnected) { + continue; + } + const connectedOutput = input.connectedPoint; + const connectedBlock = connectedOutput.ownerBlock; + codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped); + codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});\n`; + } + return codeString; + } + /** + * @internal + */ + _dumpCode(uniqueNames, alreadyDumped) { + alreadyDumped.push(this); + // Get unique name + const nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, ""); + this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`; + if (uniqueNames.indexOf(this._codeVariableName) !== -1) { + let index = 0; + do { + index++; + this._codeVariableName = nameAsVariableName + index; + } while (uniqueNames.indexOf(this._codeVariableName) !== -1); + } + uniqueNames.push(this._codeVariableName); + // Declaration + let codeString = `\n// ${this.getClassName()}\n`; + if (this.comments) { + codeString += `// ${this.comments}\n`; + } + const className = this.getClassName(); + if (className === "GeometryInputBlock") { + const block = this; + const blockType = block.type; + codeString += `var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${blockType});\n`; + } + else { + codeString += `var ${this._codeVariableName} = new BABYLON.${className}("${this.name}");\n`; + } + // Properties + codeString += this._dumpPropertiesCode(); + // Inputs + for (const input of this.inputs) { + if (!input.isConnected) { + continue; + } + const connectedOutput = input.connectedPoint; + const connectedBlock = connectedOutput.ownerBlock; + if (alreadyDumped.indexOf(connectedBlock) === -1) { + codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped); + } + } + // Outputs + for (const output of this.outputs) { + if (!output.hasEndpoints) { + continue; + } + for (const endpoint of output.endpoints) { + const connectedBlock = endpoint.ownerBlock; + if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) { + codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped); + } + } + } + return codeString; + } + /** + * Clone the current block to a new identical block + * @returns a copy of the current block + */ + clone() { + const serializationObject = this.serialize(); + const blockType = GetClass(serializationObject.customType); + if (blockType) { + const block = new blockType(); + block._deserialize(serializationObject); + return block; + } + return null; + } + /** + * Release resources + */ + dispose() { + for (const input of this.inputs) { + input.dispose(); + } + for (const output of this.outputs) { + output.dispose(); + } + this.onBuildObservable.clear(); + } +} +__decorate([ + serialize("comment") +], NodeGeometryBlock.prototype, "comments", void 0); + +/** + * Block used to generate the final geometry + */ +class GeometryOutputBlock extends NodeGeometryBlock { + /** + * Gets the current vertex data if the graph was successfully built + */ + get currentVertexData() { + return this._vertexData; + } + /** + * Create a new GeometryOutputBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._vertexData = null; + this._isUnique = true; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryOutputBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + _buildBlock(state) { + state.vertexData = this.geometry.getConnectedValue(state); + this._vertexData = state.vertexData; + } +} +RegisterClass("BABYLON.GeometryOutputBlock", GeometryOutputBlock); + +/** + * Defines the kind of contextual sources for node geometry + */ +var NodeGeometryContextualSources; +(function (NodeGeometryContextualSources) { + /** None */ + NodeGeometryContextualSources[NodeGeometryContextualSources["None"] = 0] = "None"; + /** Positions */ + NodeGeometryContextualSources[NodeGeometryContextualSources["Positions"] = 1] = "Positions"; + /** Normals */ + NodeGeometryContextualSources[NodeGeometryContextualSources["Normals"] = 2] = "Normals"; + /** Tangents */ + NodeGeometryContextualSources[NodeGeometryContextualSources["Tangents"] = 3] = "Tangents"; + /** UV */ + NodeGeometryContextualSources[NodeGeometryContextualSources["UV"] = 4] = "UV"; + /** UV2 */ + NodeGeometryContextualSources[NodeGeometryContextualSources["UV2"] = 5] = "UV2"; + /** UV3 */ + NodeGeometryContextualSources[NodeGeometryContextualSources["UV3"] = 6] = "UV3"; + /** UV4 */ + NodeGeometryContextualSources[NodeGeometryContextualSources["UV4"] = 7] = "UV4"; + /** UV5 */ + NodeGeometryContextualSources[NodeGeometryContextualSources["UV5"] = 8] = "UV5"; + /** UV6 */ + NodeGeometryContextualSources[NodeGeometryContextualSources["UV6"] = 9] = "UV6"; + /** Colors */ + NodeGeometryContextualSources[NodeGeometryContextualSources["Colors"] = 10] = "Colors"; + /** VertexID */ + NodeGeometryContextualSources[NodeGeometryContextualSources["VertexID"] = 11] = "VertexID"; + /** FaceID */ + NodeGeometryContextualSources[NodeGeometryContextualSources["FaceID"] = 12] = "FaceID"; + /** GeometryID */ + NodeGeometryContextualSources[NodeGeometryContextualSources["GeometryID"] = 13] = "GeometryID"; + /** CollectionID */ + NodeGeometryContextualSources[NodeGeometryContextualSources["CollectionID"] = 14] = "CollectionID"; + /** LoopID */ + NodeGeometryContextualSources[NodeGeometryContextualSources["LoopID"] = 15] = "LoopID"; + /** InstanceID */ + NodeGeometryContextualSources[NodeGeometryContextualSources["InstanceID"] = 16] = "InstanceID"; + /** LatticeID */ + NodeGeometryContextualSources[NodeGeometryContextualSources["LatticeID"] = 17] = "LatticeID"; + /** LatticeControl */ + NodeGeometryContextualSources[NodeGeometryContextualSources["LatticeControl"] = 18] = "LatticeControl"; +})(NodeGeometryContextualSources || (NodeGeometryContextualSources = {})); + +/** + * Class used to store node based geometry build state + */ +class NodeGeometryBuildState { + constructor() { + this._rotationMatrix = new Matrix(); + this._scalingMatrix = new Matrix(); + this._positionMatrix = new Matrix(); + this._scalingRotationMatrix = new Matrix(); + this._transformMatrix = new Matrix(); + this._tempVector3 = new Vector3(); + /** Gets or sets the list of non connected mandatory inputs */ + this.notConnectedNonOptionalInputs = []; + /** Gets or sets the list of non contextual inputs having no contextudal data */ + this.noContextualData = []; + /** Gets or sets the vertex data */ + this.vertexData = null; + this._geometryContext = null; + this._executionContext = null; + this._instancingContext = null; + this._geometryContextStack = []; + this._executionContextStack = []; + this._instancingContextStack = []; + } + /** Gets or sets the geometry context */ + get geometryContext() { + return this._geometryContext; + } + /** Gets or sets the execution context */ + get executionContext() { + return this._executionContext; + } + /** Gets or sets the instancing context */ + get instancingContext() { + return this._instancingContext; + } + /** + * Push the new active geometry context + * @param geometryContext defines the geometry context + */ + pushGeometryContext(geometryContext) { + this._geometryContext = geometryContext; + this._geometryContextStack.push(this._geometryContext); + } + /** + * Push the new active execution context + * @param executionContext defines the execution context + */ + pushExecutionContext(executionContext) { + this._executionContext = executionContext; + this._executionContextStack.push(this._executionContext); + } + /** + * Push the new active instancing context + * @param instancingContext defines the instancing context + */ + pushInstancingContext(instancingContext) { + this._instancingContext = instancingContext; + this._instancingContextStack.push(this._instancingContext); + } + /** + * Remove current geometry context and restore the previous one + */ + restoreGeometryContext() { + this._geometryContextStack.pop(); + this._geometryContext = this._geometryContextStack.length > 0 ? this._geometryContextStack[this._geometryContextStack.length - 1] : null; + } + /** + * Remove current execution context and restore the previous one + */ + restoreExecutionContext() { + this._executionContextStack.pop(); + this._executionContext = this._executionContextStack.length > 0 ? this._executionContextStack[this._executionContextStack.length - 1] : null; + } + /** + * Remove current isntancing context and restore the previous one + */ + restoreInstancingContext() { + this._instancingContextStack.pop(); + this._instancingContext = this._instancingContextStack.length > 0 ? this._instancingContextStack[this._instancingContextStack.length - 1] : null; + } + /** + * Gets the value associated with a contextual source + * @param source Source of the contextual value + * @param skipWarning Do not store the warning for reporting if true + * @returns the value associated with the source + */ + getContextualValue(source, skipWarning = false) { + if (!this.executionContext) { + if (!skipWarning) { + this.noContextualData.push(source); + } + return null; + } + const index = this.executionContext.getExecutionIndex(); + switch (source) { + case NodeGeometryContextualSources.Positions: + if (this.executionContext.getOverridePositionsContextualValue) { + return this.executionContext.getOverridePositionsContextualValue(); + } + if (!this.geometryContext || !this.geometryContext.positions) { + return Vector3.Zero(); + } + return Vector3.FromArray(this.geometryContext.positions, index * 3); + case NodeGeometryContextualSources.Normals: + if (this.executionContext.getOverrideNormalsContextualValue) { + return this.executionContext.getOverrideNormalsContextualValue(); + } + if (!this.geometryContext || !this.geometryContext.normals) { + return Vector3.Zero(); + } + return Vector3.FromArray(this.geometryContext.normals, index * 3); + case NodeGeometryContextualSources.Colors: + if (!this.geometryContext || !this.geometryContext.colors) { + return Vector4.Zero(); + } + return Vector4.FromArray(this.geometryContext.colors, index * 4); + case NodeGeometryContextualSources.Tangents: + if (!this.geometryContext || !this.geometryContext.tangents) { + return Vector4.Zero(); + } + return Vector4.FromArray(this.geometryContext.tangents, index * 4); + case NodeGeometryContextualSources.UV: + if (this.executionContext.getOverrideUVs1ContextualValue) { + return this.executionContext.getOverrideUVs1ContextualValue(); + } + if (!this.geometryContext || !this.geometryContext.uvs) { + return Vector2.Zero(); + } + return Vector2.FromArray(this.geometryContext.uvs, index * 2); + case NodeGeometryContextualSources.UV2: + if (!this.geometryContext || !this.geometryContext.uvs2) { + return Vector2.Zero(); + } + return Vector2.FromArray(this.geometryContext.uvs2, index * 2); + case NodeGeometryContextualSources.UV3: + if (!this.geometryContext || !this.geometryContext.uvs3) { + return Vector2.Zero(); + } + return Vector2.FromArray(this.geometryContext.uvs3, index * 2); + case NodeGeometryContextualSources.UV4: + if (!this.geometryContext || !this.geometryContext.uvs4) { + return Vector2.Zero(); + } + return Vector2.FromArray(this.geometryContext.uvs4, index * 2); + case NodeGeometryContextualSources.UV5: + if (!this.geometryContext || !this.geometryContext.uvs5) { + return Vector2.Zero(); + } + return Vector2.FromArray(this.geometryContext.uvs5, index * 2); + case NodeGeometryContextualSources.UV6: + if (!this.geometryContext || !this.geometryContext.uvs6) { + return Vector2.Zero(); + } + return Vector2.FromArray(this.geometryContext.uvs6, index * 2); + case NodeGeometryContextualSources.VertexID: + return index; + case NodeGeometryContextualSources.FaceID: + return this.executionContext.getExecutionFaceIndex(); + case NodeGeometryContextualSources.LoopID: + return this.executionContext.getExecutionLoopIndex(); + case NodeGeometryContextualSources.InstanceID: + return this.instancingContext ? this.instancingContext.getInstanceIndex() : 0; + case NodeGeometryContextualSources.GeometryID: + return !this.geometryContext ? 0 : this.geometryContext.uniqueId; + case NodeGeometryContextualSources.CollectionID: { + if (!this.geometryContext || !this.geometryContext.metadata) { + return 0; + } + return this.geometryContext.metadata.collectionId || 0; + } + case NodeGeometryContextualSources.LatticeID: { + if (this.executionContext.getOverridePositionsContextualValue) { + return this.executionContext.getOverridePositionsContextualValue(); + } + return Vector3.Zero(); + } + case NodeGeometryContextualSources.LatticeControl: { + if (this.executionContext.getOverrideNormalsContextualValue) { + return this.executionContext.getOverrideNormalsContextualValue(); + } + return Vector3.Zero(); + } + } + return null; + } + /** + * Adapt a value to a target type + * @param source defines the value to adapt + * @param targetType defines the target type + * @returns the adapted value + */ + adapt(source, targetType) { + const value = source.getConnectedValue(this) || 0; + if (source.type === targetType) { + return value; + } + switch (targetType) { + case NodeGeometryBlockConnectionPointTypes.Vector2: + return new Vector2(value, value); + case NodeGeometryBlockConnectionPointTypes.Vector3: + return new Vector3(value, value, value); + case NodeGeometryBlockConnectionPointTypes.Vector4: + return new Vector4(value, value, value, value); + } + return null; + } + /** + * Adapt an input value to a target type + * @param source defines the value to adapt + * @param targetType defines the target type + * @param defaultValue defines the default value to use if not connected + * @returns the adapted value + */ + adaptInput(source, targetType, defaultValue) { + if (!source.isConnected) { + return source.value || defaultValue; + } + const value = source.getConnectedValue(this); + if (source._connectedPoint?.type === targetType) { + return value; + } + switch (targetType) { + case NodeGeometryBlockConnectionPointTypes.Vector2: + return new Vector2(value, value); + case NodeGeometryBlockConnectionPointTypes.Vector3: + return new Vector3(value, value, value); + case NodeGeometryBlockConnectionPointTypes.Vector4: + return new Vector4(value, value, value, value); + } + return null; + } + /** + * Emits console errors and exceptions if there is a failing check + */ + emitErrors() { + let errorMessage = ""; + for (const notConnectedInput of this.notConnectedNonOptionalInputs) { + errorMessage += `input ${notConnectedInput.name} from block ${notConnectedInput.ownerBlock.name}[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional.\n`; + } + for (const source of this.noContextualData) { + errorMessage += `Contextual input ${NodeGeometryContextualSources[source]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).\n`; + } + if (errorMessage) { + // eslint-disable-next-line no-throw-literal + throw "Build of NodeGeometry failed:\n" + errorMessage; + } + } + /** @internal */ + _instantiate(clone, currentPosition, rotation, scaling, additionalVertexData) { + // Transform + Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, this._scalingMatrix); + Matrix.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, this._rotationMatrix); + Matrix.TranslationToRef(currentPosition.x, currentPosition.y, currentPosition.z, this._positionMatrix); + this._scalingMatrix.multiplyToRef(this._rotationMatrix, this._scalingRotationMatrix); + this._scalingRotationMatrix.multiplyToRef(this._positionMatrix, this._transformMatrix); + for (let clonePositionIndex = 0; clonePositionIndex < clone.positions.length; clonePositionIndex += 3) { + this._tempVector3.fromArray(clone.positions, clonePositionIndex); + Vector3.TransformCoordinatesToRef(this._tempVector3, this._transformMatrix, this._tempVector3); + this._tempVector3.toArray(clone.positions, clonePositionIndex); + if (clone.normals) { + this._tempVector3.fromArray(clone.normals, clonePositionIndex); + Vector3.TransformNormalToRef(this._tempVector3, this._scalingRotationMatrix, this._tempVector3); + this._tempVector3.toArray(clone.normals, clonePositionIndex); + } + } + additionalVertexData.push(clone); + } + /** @internal */ + _instantiateWithMatrix(clone, transform, additionalVertexData) { + for (let clonePositionIndex = 0; clonePositionIndex < clone.positions.length; clonePositionIndex += 3) { + this._tempVector3.fromArray(clone.positions, clonePositionIndex); + Vector3.TransformCoordinatesToRef(this._tempVector3, transform, this._tempVector3); + this._tempVector3.toArray(clone.positions, clonePositionIndex); + if (clone.normals) { + this._tempVector3.fromArray(clone.normals, clonePositionIndex); + Vector3.TransformNormalToRef(this._tempVector3, transform, this._tempVector3); + this._tempVector3.toArray(clone.normals, clonePositionIndex); + } + } + additionalVertexData.push(clone); + } + /** @internal */ + _instantiateWithPositionAndMatrix(clone, currentPosition, transform, additionalVertexData) { + Matrix.TranslationToRef(currentPosition.x, currentPosition.y, currentPosition.z, this._positionMatrix); + transform.multiplyToRef(this._positionMatrix, this._transformMatrix); + for (let clonePositionIndex = 0; clonePositionIndex < clone.positions.length; clonePositionIndex += 3) { + this._tempVector3.fromArray(clone.positions, clonePositionIndex); + Vector3.TransformCoordinatesToRef(this._tempVector3, this._transformMatrix, this._tempVector3); + this._tempVector3.toArray(clone.positions, clonePositionIndex); + if (clone.normals) { + this._tempVector3.fromArray(clone.normals, clonePositionIndex); + Vector3.TransformNormalToRef(this._tempVector3, this._transformMatrix, this._tempVector3); + this._tempVector3.toArray(clone.normals, clonePositionIndex); + } + } + additionalVertexData.push(clone); + } +} + +/** + * Block used to expose an input value + */ +class GeometryInputBlock extends NodeGeometryBlock { + /** + * Gets or sets the connection point type (default is float) + */ + get type() { + if (this._type === NodeGeometryBlockConnectionPointTypes.AutoDetect) { + if (this.value != null) { + if (!isNaN(this.value)) { + this._type = NodeGeometryBlockConnectionPointTypes.Float; + return this._type; + } + switch (this.value.getClassName()) { + case "Vector2": + this._type = NodeGeometryBlockConnectionPointTypes.Vector2; + return this._type; + case "Vector3": + this._type = NodeGeometryBlockConnectionPointTypes.Vector3; + return this._type; + case "Vector4": + this._type = NodeGeometryBlockConnectionPointTypes.Vector4; + return this._type; + case "Matrix": + this._type = NodeGeometryBlockConnectionPointTypes.Matrix; + return this._type; + } + } + } + return this._type; + } + /** + * Gets a boolean indicating that the current connection point is a contextual value + */ + get isContextual() { + return this._contextualSource !== NodeGeometryContextualSources.None; + } + /** + * Gets or sets the current contextual value + */ + get contextualValue() { + return this._contextualSource; + } + set contextualValue(value) { + this._contextualSource = value; + switch (value) { + case NodeGeometryContextualSources.Positions: + case NodeGeometryContextualSources.Normals: + case NodeGeometryContextualSources.LatticeID: + case NodeGeometryContextualSources.LatticeControl: + this._type = NodeGeometryBlockConnectionPointTypes.Vector3; + break; + case NodeGeometryContextualSources.Colors: + case NodeGeometryContextualSources.Tangents: + this._type = NodeGeometryBlockConnectionPointTypes.Vector4; + break; + case NodeGeometryContextualSources.UV: + case NodeGeometryContextualSources.UV2: + case NodeGeometryContextualSources.UV3: + case NodeGeometryContextualSources.UV4: + case NodeGeometryContextualSources.UV5: + case NodeGeometryContextualSources.UV6: + this._type = NodeGeometryBlockConnectionPointTypes.Vector2; + break; + case NodeGeometryContextualSources.VertexID: + case NodeGeometryContextualSources.GeometryID: + case NodeGeometryContextualSources.CollectionID: + case NodeGeometryContextualSources.FaceID: + case NodeGeometryContextualSources.LoopID: + case NodeGeometryContextualSources.InstanceID: + this._type = NodeGeometryBlockConnectionPointTypes.Int; + break; + } + if (this.output) { + this.output.type = this._type; + } + } + /** + * Creates a new InputBlock + * @param name defines the block name + * @param type defines the type of the input (can be set to NodeGeometryBlockConnectionPointTypes.AutoDetect) + */ + constructor(name, type = NodeGeometryBlockConnectionPointTypes.AutoDetect) { + super(name); + this._type = NodeGeometryBlockConnectionPointTypes.Undefined; + this._contextualSource = NodeGeometryContextualSources.None; + /** Gets or set a value used to limit the range of float values */ + this.min = 0; + /** Gets or set a value used to limit the range of float values */ + this.max = 0; + /** Gets or sets the group to use to display this block in the Inspector */ + this.groupInInspector = ""; + /** + * Gets or sets a boolean indicating that this input is displayed in the Inspector + */ + this.displayInInspector = true; + /** Gets an observable raised when the value is changed */ + this.onValueChangedObservable = new Observable(); + this._type = type; + this._isInput = true; + this.setDefaultValue(); + this.registerOutput("output", type); + } + /** + * Gets or sets the value of that point. + * Please note that this value will be ignored if valueCallback is defined + */ + get value() { + return this._storedValue; + } + set value(value) { + if (this.type === NodeGeometryBlockConnectionPointTypes.Float) { + if (this.min !== this.max) { + value = Math.max(this.min, value); + value = Math.min(this.max, value); + } + } + this._storedValue = value; + this.onValueChangedObservable.notifyObservers(this); + } + /** + * Gets or sets a callback used to get the value of that point. + * Please note that setting this value will force the connection point to ignore the value property + */ + get valueCallback() { + return this._valueCallback; + } + set valueCallback(value) { + this._valueCallback = value; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryInputBlock"; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + /** + * Set the input block to its default value (based on its type) + */ + setDefaultValue() { + this.contextualValue = NodeGeometryContextualSources.None; + switch (this.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: + this.value = 0; + break; + case NodeGeometryBlockConnectionPointTypes.Vector2: + this.value = Vector2.Zero(); + break; + case NodeGeometryBlockConnectionPointTypes.Vector3: + this.value = Vector3.Zero(); + break; + case NodeGeometryBlockConnectionPointTypes.Vector4: + this.value = Vector4.Zero(); + break; + case NodeGeometryBlockConnectionPointTypes.Matrix: + this.value = Matrix.Identity(); + break; + } + } + _buildBlock(state) { + super._buildBlock(state); + if (this.isContextual) { + this.output._storedValue = null; + this.output._storedFunction = (state) => { + return state.getContextualValue(this._contextualSource); + }; + } + else { + this.output._storedFunction = null; + this.output._storedValue = this.value; + } + } + dispose() { + this.onValueChangedObservable.clear(); + super.dispose(); + } + _dumpPropertiesCode() { + const variableName = this._codeVariableName; + if (this.isContextual) { + return (super._dumpPropertiesCode() + `${variableName}.contextualValue = BABYLON.NodeGeometryContextualSources.${NodeGeometryContextualSources[this._contextualSource]};\n`); + } + const codes = []; + let valueString = ""; + switch (this.type) { + case NodeGeometryBlockConnectionPointTypes.Float: + case NodeGeometryBlockConnectionPointTypes.Int: + valueString = `${this.value}`; + break; + case NodeGeometryBlockConnectionPointTypes.Vector2: + valueString = `new BABYLON.Vector2(${this.value.x}, ${this.value.y})`; + break; + case NodeGeometryBlockConnectionPointTypes.Vector3: + valueString = `new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`; + break; + case NodeGeometryBlockConnectionPointTypes.Vector4: + valueString = `new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`; + break; + } + // Common Property "Value" + codes.push(`${variableName}.value = ${valueString}`); + // Float-Value-Specific Properties + if (this.type === NodeGeometryBlockConnectionPointTypes.Float || this.type === NodeGeometryBlockConnectionPointTypes.Int) { + codes.push(`${variableName}.min = ${this.min}`, `${variableName}.max = ${this.max}`); + } + codes.push(""); + return super._dumpPropertiesCode() + codes.join(";\n"); + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.type = this.type; + serializationObject.contextualValue = this.contextualValue; + serializationObject.min = this.min; + serializationObject.max = this.max; + serializationObject.groupInInspector = this.groupInInspector; + serializationObject.displayInInspector = this.displayInInspector; + if (this._storedValue !== null && !this.isContextual) { + if (this._storedValue.asArray) { + serializationObject.valueType = "BABYLON." + this._storedValue.getClassName(); + serializationObject.value = this._storedValue.asArray(); + } + else { + serializationObject.valueType = "number"; + serializationObject.value = this._storedValue; + } + } + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this._type = serializationObject.type; + this.contextualValue = serializationObject.contextualValue; + this.min = serializationObject.min || 0; + this.max = serializationObject.max || 0; + this.groupInInspector = serializationObject.groupInInspector || ""; + if (serializationObject.displayInInspector !== undefined) { + this.displayInInspector = serializationObject.displayInInspector; + } + if (!serializationObject.valueType) { + return; + } + if (serializationObject.valueType === "number") { + this._storedValue = serializationObject.value; + } + else { + const valueType = GetClass(serializationObject.valueType); + if (valueType) { + this._storedValue = valueType.FromArray(serializationObject.value); + } + } + } +} +RegisterClass("BABYLON.GeometryInputBlock", GeometryInputBlock); + +/** + * Defines a block used to generate box geometry data + */ +class BoxBlock extends NodeGeometryBlock { + /** + * Create a new BoxBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + this.registerInput("size", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("width", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("depth", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1, 0); + this.registerInput("subdivisionsX", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0); + this.registerInput("subdivisionsY", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0); + this.registerInput("subdivisionsZ", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0); + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "BoxBlock"; + } + /** + * Gets the size input component + */ + get size() { + return this._inputs[0]; + } + /** + * Gets the width input component + */ + get width() { + return this._inputs[1]; + } + /** + * Gets the height input component + */ + get height() { + return this._inputs[2]; + } + /** + * Gets the depth input component + */ + get depth() { + return this._inputs[3]; + } + /** + * Gets the subdivisions input component + */ + get subdivisions() { + return this._inputs[4]; + } + /** + * Gets the subdivisionsX input component + */ + get subdivisionsX() { + return this._inputs[5]; + } + /** + * Gets the subdivisionsY input component + */ + get subdivisionsY() { + return this._inputs[6]; + } + /** + * Gets the subdivisionsZ input component + */ + get subdivisionsZ() { + return this._inputs[7]; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + autoConfigure() { + if (this.size.isConnected) { + return; + } + if (!this.width.isConnected && !this.height.isConnected && !this.depth.isConnected) { + const sizeInput = new GeometryInputBlock("Size"); + sizeInput.value = 1; + sizeInput.output.connectTo(this.size); + return; + } + if (!this.width.isConnected) { + const widthInput = new GeometryInputBlock("Width"); + widthInput.value = 1; + widthInput.output.connectTo(this.width); + } + if (!this.height.isConnected) { + const heightInput = new GeometryInputBlock("Height"); + heightInput.value = 1; + heightInput.output.connectTo(this.height); + } + if (!this.depth.isConnected) { + const depthInput = new GeometryInputBlock("Depth"); + depthInput.value = 1; + depthInput.output.connectTo(this.depth); + } + } + _buildBlock(state) { + const options = {}; + const func = (state) => { + options.size = this.size.getConnectedValue(state); + options.width = this.width.getConnectedValue(state); + options.height = this.height.getConnectedValue(state); + options.depth = this.depth.getConnectedValue(state); + const subdivisions = this.subdivisions.getConnectedValue(state); + const subdivisionsX = this.subdivisionsX.getConnectedValue(state); + const subdivisionsY = this.subdivisionsY.getConnectedValue(state); + const subdivisionsZ = this.subdivisionsZ.getConnectedValue(state); + if (subdivisions) { + options.segments = subdivisions; + } + if (subdivisionsX) { + options.widthSegments = subdivisionsX; + } + if (subdivisionsY) { + options.heightSegments = subdivisionsY; + } + if (subdivisionsZ) { + options.depthSegments = subdivisionsZ; + } + // Append vertex data from the plane builder + return CreateSegmentedBoxVertexData(options); + }; + if (this.evaluateContext) { + this.geometry._storedFunction = func; + } + else { + const value = func(state); + this.geometry._storedFunction = () => { + this.geometry._executionCount = 1; + return value.clone(); + }; + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], BoxBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.BoxBlock", BoxBlock); + +/** + * Defines a node based geometry + * @see demo at https://playground.babylonjs.com#PYY6XE#69 + */ +class NodeGeometry { + /** @returns the inspector from bundle or global */ + _getGlobalNodeGeometryEditor() { + // UMD Global name detection from Webpack Bundle UMD Name. + if (typeof NODEGEOMETRYEDITOR !== "undefined") { + return NODEGEOMETRYEDITOR; + } + // In case of module let's check the global emitted from the editor entry point. + if (typeof BABYLON !== "undefined" && typeof BABYLON.NodeGeometryEditor !== "undefined") { + return BABYLON; + } + return undefined; + } + /** + * Gets the time spent to build this block (in ms) + */ + get buildExecutionTime() { + return this._buildExecutionTime; + } + /** + * Creates a new geometry + * @param name defines the name of the geometry + */ + constructor(name) { + this._buildId = NodeGeometry._BuildIdGenerator++; + this._buildWasSuccessful = false; + this._vertexData = null; + this._buildExecutionTime = 0; + // eslint-disable-next-line @typescript-eslint/naming-convention + this.BJSNODEGEOMETRYEDITOR = this._getGlobalNodeGeometryEditor(); + /** + * Gets or sets data used by visual editor + * @see https://nge.babylonjs.com + */ + this.editorData = null; + /** + * Gets an array of blocks that needs to be serialized even if they are not yet connected + */ + this.attachedBlocks = []; + /** + * Observable raised when the geometry is built + */ + this.onBuildObservable = new Observable(); + /** Gets or sets the GeometryOutputBlock used to gather the final geometry data */ + this.outputBlock = null; + this.name = name; + } + /** + * Gets the current class name of the geometry e.g. "NodeGeometry" + * @returns the class name + */ + getClassName() { + return "NodeGeometry"; + } + /** + * Gets the vertex data. This needs to be done after build() was called. + * This is used to access vertexData when creating a mesh is not required. + */ + get vertexData() { + return this._vertexData; + } + /** + * Get a block by its name + * @param name defines the name of the block to retrieve + * @returns the required block or null if not found + */ + getBlockByName(name) { + let result = null; + for (const block of this.attachedBlocks) { + if (block.name === name) { + if (!result) { + result = block; + } + else { + Tools.Warn("More than one block was found with the name `" + name + "`"); + return result; + } + } + } + return result; + } + /** + * Get a block using a predicate + * @param predicate defines the predicate used to find the good candidate + * @returns the required block or null if not found + */ + getBlockByPredicate(predicate) { + for (const block of this.attachedBlocks) { + if (predicate(block)) { + return block; + } + } + return null; + } + /** + * Gets the list of input blocks attached to this material + * @returns an array of InputBlocks + */ + getInputBlocks() { + const blocks = []; + for (const block of this.attachedBlocks) { + if (block.isInput) { + blocks.push(block); + } + } + return blocks; + } + /** + * Launch the node geometry editor + * @param config Define the configuration of the editor + * @returns a promise fulfilled when the node editor is visible + */ + edit(config) { + return new Promise((resolve) => { + this.BJSNODEGEOMETRYEDITOR = this.BJSNODEGEOMETRYEDITOR || this._getGlobalNodeGeometryEditor(); + if (typeof this.BJSNODEGEOMETRYEDITOR == "undefined") { + const editorUrl = config && config.editorURL ? config.editorURL : NodeGeometry.EditorURL; + // Load editor and add it to the DOM + Tools.LoadBabylonScript(editorUrl, () => { + this.BJSNODEGEOMETRYEDITOR = this.BJSNODEGEOMETRYEDITOR || this._getGlobalNodeGeometryEditor(); + this._createNodeEditor(config?.nodeGeometryEditorConfig); + resolve(); + }); + } + else { + // Otherwise creates the editor + this._createNodeEditor(config?.nodeGeometryEditorConfig); + resolve(); + } + }); + } + /** + * Creates the node editor window. + * @param additionalConfig Additional configuration for the NGE + */ + _createNodeEditor(additionalConfig) { + const nodeEditorConfig = { + nodeGeometry: this, + ...additionalConfig, + }; + this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(nodeEditorConfig); + } + /** + * Build the final geometry. Please note that the geometry MAY not be ready until the onBuildObservable is raised. + * @param verbose defines if the build should log activity + * @param updateBuildId defines if the internal build Id should be updated (default is true) + * @param autoConfigure defines if the autoConfigure method should be called when initializing blocks (default is false) + */ + build(verbose = false, updateBuildId = true, autoConfigure = false) { + this._buildWasSuccessful = false; + if (!this.outputBlock) { + // eslint-disable-next-line no-throw-literal + throw "You must define the outputBlock property before building the geometry"; + } + const now = PrecisionDate.Now; + // Initialize blocks + this._initializeBlock(this.outputBlock, autoConfigure); + // Check async states + const promises = []; + for (const block of this.attachedBlocks) { + if (block._isReadyState) { + promises.push(block._isReadyState); + } + } + if (promises.length) { + Promise.all(promises).then(() => { + this.build(verbose, updateBuildId, autoConfigure); + }); + return; + } + // Build + const state = new NodeGeometryBuildState(); + state.buildId = this._buildId; + state.verbose = verbose; + try { + this.outputBlock.build(state); + } + finally { + if (updateBuildId) { + this._buildId = NodeGeometry._BuildIdGenerator++; + } + } + this._buildExecutionTime = PrecisionDate.Now - now; + // Errors + state.emitErrors(); + this._buildWasSuccessful = true; + this._vertexData = state.vertexData; + this.onBuildObservable.notifyObservers(this); + } + /** + * Creates a mesh from the geometry blocks + * @param name defines the name of the mesh + * @param scene The scene the mesh is scoped to + * @returns The new mesh + */ + createMesh(name, scene = null) { + if (!this._buildWasSuccessful) { + this.build(); + } + if (!this._vertexData) { + return null; + } + const mesh = new Mesh(name, scene); + this._vertexData.applyToMesh(mesh); + mesh._internalMetadata = mesh._internalMetadata || {}; + mesh._internalMetadata.nodeGeometry = this; + return mesh; + } + /** + * Creates a mesh from the geometry blocks + * @param mesh the mesh to update + * @returns True if successfully updated + */ + updateMesh(mesh) { + if (!this._buildWasSuccessful) { + this.build(); + } + if (!this._vertexData) { + return false; + } + this._vertexData.applyToMesh(mesh); + mesh._internalMetadata = mesh._internalMetadata || {}; + mesh._internalMetadata.nodeGeometry = this; + return mesh; + } + _initializeBlock(node, autoConfigure = true) { + node.initialize(); + if (autoConfigure) { + node.autoConfigure(this); + } + node._preparationId = this._buildId; + if (this.attachedBlocks.indexOf(node) === -1) { + this.attachedBlocks.push(node); + } + for (const input of node.inputs) { + const connectedPoint = input.connectedPoint; + if (connectedPoint) { + const block = connectedPoint.ownerBlock; + if (block !== node) { + this._initializeBlock(block, autoConfigure); + } + } + } + } + /** + * Clear the current geometry + */ + clear() { + this.outputBlock = null; + this.attachedBlocks.length = 0; + } + /** + * Remove a block from the current geometry + * @param block defines the block to remove + */ + removeBlock(block) { + const attachedBlockIndex = this.attachedBlocks.indexOf(block); + if (attachedBlockIndex > -1) { + this.attachedBlocks.splice(attachedBlockIndex, 1); + } + if (block === this.outputBlock) { + this.outputBlock = null; + } + } + /** + * Clear the current graph and load a new one from a serialization object + * @param source defines the JSON representation of the geometry + * @param merge defines whether or not the source must be merged or replace the current content + */ + parseSerializedObject(source, merge = false) { + if (!merge) { + this.clear(); + } + const map = {}; + // Create blocks + for (const parsedBlock of source.blocks) { + const blockType = GetClass(parsedBlock.customType); + if (blockType) { + const block = new blockType(); + block._deserialize(parsedBlock); + map[parsedBlock.id] = block; + this.attachedBlocks.push(block); + } + } + // Reconnect teleportation + for (const block of this.attachedBlocks) { + if (block.isTeleportOut) { + const teleportOut = block; + const id = teleportOut._tempEntryPointUniqueId; + if (id) { + const source = map[id]; + if (source) { + source.attachToEndpoint(teleportOut); + } + } + } + } + // Connections - Starts with input blocks only (except if in "merge" mode where we scan all blocks) + for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) { + const parsedBlock = source.blocks[blockIndex]; + const block = map[parsedBlock.id]; + if (!block) { + continue; + } + if (block.inputs.length && parsedBlock.inputs.some((i) => i.targetConnectionName) && !merge) { + continue; + } + this._restoreConnections(block, source, map); + } + // Outputs + if (source.outputNodeId) { + this.outputBlock = map[source.outputNodeId]; + } + // UI related info + if (source.locations || (source.editorData && source.editorData.locations)) { + const locations = source.locations || source.editorData.locations; + for (const location of locations) { + if (map[location.blockId]) { + location.blockId = map[location.blockId].uniqueId; + } + } + if (merge && this.editorData && this.editorData.locations) { + locations.concat(this.editorData.locations); + } + if (source.locations) { + this.editorData = { + locations: locations, + }; + } + else { + this.editorData = source.editorData; + this.editorData.locations = locations; + } + const blockMap = []; + for (const key in map) { + blockMap[key] = map[key].uniqueId; + } + this.editorData.map = blockMap; + } + this.comment = source.comment; + } + _restoreConnections(block, source, map) { + for (const outputPoint of block.outputs) { + for (const candidate of source.blocks) { + const target = map[candidate.id]; + if (!target) { + continue; + } + for (const input of candidate.inputs) { + if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) { + const inputPoint = target.getInputByName(input.inputName); + if (!inputPoint || inputPoint.isConnected) { + continue; + } + outputPoint.connectTo(inputPoint, true); + this._restoreConnections(target, source, map); + continue; + } + } + } + } + } + /** + * Generate a string containing the code declaration required to create an equivalent of this geometry + * @returns a string + */ + generateCode() { + let alreadyDumped = []; + const blocks = []; + const uniqueNames = ["const", "var", "let"]; + // Gets active blocks + if (this.outputBlock) { + this._gatherBlocks(this.outputBlock, blocks); + } + // Generate + let codeString = `let nodeGeometry = new BABYLON.NodeGeometry("${this.name || "node geometry"}");\n`; + for (const node of blocks) { + if (node.isInput && alreadyDumped.indexOf(node) === -1) { + codeString += node._dumpCode(uniqueNames, alreadyDumped); + } + } + if (this.outputBlock) { + // Connections + alreadyDumped = []; + codeString += "// Connections\n"; + codeString += this.outputBlock._dumpCodeForOutputConnections(alreadyDumped); + // Output nodes + codeString += "// Output nodes\n"; + codeString += `nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`; + codeString += `nodeGeometry.build();\n`; + } + return codeString; + } + _gatherBlocks(rootNode, list) { + if (list.indexOf(rootNode) !== -1) { + return; + } + list.push(rootNode); + for (const input of rootNode.inputs) { + const connectedPoint = input.connectedPoint; + if (connectedPoint) { + const block = connectedPoint.ownerBlock; + if (block !== rootNode) { + this._gatherBlocks(block, list); + } + } + } + // Teleportation + if (rootNode.isTeleportOut) { + const block = rootNode; + if (block.entryPoint) { + this._gatherBlocks(block.entryPoint, list); + } + } + } + /** + * Clear the current geometry and set it to a default state + */ + setToDefault() { + this.clear(); + this.editorData = null; + // Source + const dataBlock = new BoxBlock("Box"); + dataBlock.autoConfigure(); + // Final output + const output = new GeometryOutputBlock("Geometry Output"); + dataBlock.geometry.connectTo(output.geometry); + this.outputBlock = output; + } + /** + * Makes a duplicate of the current geometry. + * @param name defines the name to use for the new geometry + * @returns the new geometry + */ + clone(name) { + const serializationObject = this.serialize(); + const clone = SerializationHelper.Clone(() => new NodeGeometry(name), this); + clone.name = name; + clone.parseSerializedObject(serializationObject); + clone._buildId = this._buildId; + clone.build(false); + return clone; + } + /** + * Serializes this geometry in a JSON representation + * @param selectedBlocks defines the list of blocks to save (if null the whole geometry will be saved) + * @returns the serialized geometry object + */ + serialize(selectedBlocks) { + const serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this); + serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy + let blocks = []; + if (selectedBlocks) { + blocks = selectedBlocks; + } + else { + serializationObject.customType = "BABYLON.NodeGeometry"; + if (this.outputBlock) { + serializationObject.outputNodeId = this.outputBlock.uniqueId; + } + } + // Blocks + serializationObject.blocks = []; + for (const block of blocks) { + serializationObject.blocks.push(block.serialize()); + } + if (!selectedBlocks) { + for (const block of this.attachedBlocks) { + if (blocks.indexOf(block) !== -1) { + continue; + } + serializationObject.blocks.push(block.serialize()); + } + } + return serializationObject; + } + /** + * Disposes the ressources + */ + dispose() { + for (const block of this.attachedBlocks) { + block.dispose(); + } + this.attachedBlocks.length = 0; + this.onBuildObservable.clear(); + } + /** + * Creates a new node geometry set to default basic configuration + * @param name defines the name of the geometry + * @returns a new NodeGeometry + */ + static CreateDefault(name) { + const nodeGeometry = new NodeGeometry(name); + nodeGeometry.setToDefault(); + nodeGeometry.build(); + return nodeGeometry; + } + /** + * Creates a node geometry from parsed geometry data + * @param source defines the JSON representation of the geometry + * @returns a new node geometry + */ + static Parse(source) { + const nodeGeometry = SerializationHelper.Parse(() => new NodeGeometry(source.name), source, null); + nodeGeometry.parseSerializedObject(source); + nodeGeometry.build(); + return nodeGeometry; + } + /** + * Creates a node geometry from a snippet saved by the node geometry editor + * @param snippetId defines the snippet to load + * @param nodeGeometry defines a node geometry to update (instead of creating a new one) + * @param skipBuild defines whether to build the node geometry + * @returns a promise that will resolve to the new node geometry + */ + static ParseFromSnippetAsync(snippetId, nodeGeometry, skipBuild = false) { + if (snippetId === "_BLANK") { + return Promise.resolve(NodeGeometry.CreateDefault("blank")); + } + return new Promise((resolve, reject) => { + const request = new WebRequest(); + request.addEventListener("readystatechange", () => { + if (request.readyState == 4) { + if (request.status == 200) { + const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); + const serializationObject = JSON.parse(snippet.nodeGeometry); + if (!nodeGeometry) { + nodeGeometry = SerializationHelper.Parse(() => new NodeGeometry(snippetId), serializationObject, null); + } + nodeGeometry.parseSerializedObject(serializationObject); + nodeGeometry.snippetId = snippetId; + try { + if (!skipBuild) { + nodeGeometry.build(); + } + resolve(nodeGeometry); + } + catch (err) { + reject(err); + } + } + else { + reject("Unable to load the snippet " + snippetId); + } + } + }); + request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); + request.send(); + }); + } +} +NodeGeometry._BuildIdGenerator = 0; +/** Define the Url to load node editor script */ +NodeGeometry.EditorURL = `${Tools._DefaultCdnUrl}/v${AbstractEngine.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`; +/** Define the Url to load snippets */ +NodeGeometry.SnippetUrl = `https://snippet.babylonjs.com`; +__decorate([ + serialize() +], NodeGeometry.prototype, "name", void 0); +__decorate([ + serialize("comment") +], NodeGeometry.prototype, "comment", void 0); + +/** + * Block used to extract unique positions from a geometry + */ +class GeometryOptimizeBlock extends NodeGeometryBlock { + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._currentIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentIndex; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Creates a new GeometryOptimizeBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + /** + * Define the epsilon used to compare similar positions + */ + this.epsilon = Epsilon; + /** + * Optimize faces (by removing duplicates) + */ + this.optimizeFaces = false; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("selector", NodeGeometryBlockConnectionPointTypes.Int, true); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryOptimizeBlock"; + } + /** + * Gets the geometry component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the selector component + */ + get selector() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + if (!this.geometry.isConnected) { + return null; + } + const vertexData = this.geometry.getConnectedValue(state); + const newPositions = []; + const newIndicesMap = {}; + state.pushExecutionContext(this); + state.pushGeometryContext(vertexData); + // Optimize positions + for (let index = 0; index < vertexData.positions.length; index += 3) { + this._currentIndex = index / 3; + if (this.selector.isConnected) { + const selector = this.selector.getConnectedValue(state); + if (!selector) { + continue; + } + } + const x = vertexData.positions[index]; + const y = vertexData.positions[index + 1]; + const z = vertexData.positions[index + 2]; + // check if we already have it + let found = false; + for (let checkIndex = 0; checkIndex < newPositions.length; checkIndex += 3) { + if (WithinEpsilon(x, newPositions[checkIndex], this.epsilon) && + WithinEpsilon(y, newPositions[checkIndex + 1], this.epsilon) && + WithinEpsilon(z, newPositions[checkIndex + 2], this.epsilon)) { + newIndicesMap[index / 3] = checkIndex / 3; + found = true; + continue; + } + } + if (!found) { + newIndicesMap[index / 3] = newPositions.length / 3; + newPositions.push(x, y, z); + } + } + const newVertexData = new VertexData(); + newVertexData.positions = newPositions; + const indices = vertexData.indices.map((index) => newIndicesMap[index]); + const newIndices = []; + if (this.optimizeFaces) { + // Optimize indices + for (let index = 0; index < indices.length; index += 3) { + const a = indices[index]; + const b = indices[index + 1]; + const c = indices[index + 2]; + if (a === b || b == c || c === a) { + continue; + } + // check if we already have it + let found = false; + for (let checkIndex = 0; checkIndex < newIndices.length; checkIndex += 3) { + if (a === newIndices[checkIndex] && b === newIndices[checkIndex + 1] && c === newIndices[checkIndex + 2]) { + found = true; + continue; + } + if (a === newIndices[checkIndex + 1] && b === newIndices[checkIndex + 2] && c === newIndices[checkIndex]) { + found = true; + continue; + } + if (a === newIndices[checkIndex + 2] && b === newIndices[checkIndex] && c === newIndices[checkIndex + 1]) { + found = true; + continue; + } + } + if (!found) { + newIndices.push(a, b, c); + } + } + newVertexData.indices = newIndices; + } + else { + newVertexData.indices = indices; + } + return newVertexData; + }; + state.restoreGeometryContext(); + state.restoreExecutionContext(); + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + codeString += `${this._codeVariableName}.epsilon = ${this.epsilon};\n`; + codeString += `${this._codeVariableName}.optimizeFaces = ${this.optimizeFaces ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + serializationObject.epsilon = this.epsilon; + serializationObject.optimizeFaces = this.optimizeFaces; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + this.epsilon = serializationObject.epsilon; + this.optimizeFaces = serializationObject.optimizeFaces; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], GeometryOptimizeBlock.prototype, "evaluateContext", void 0); +__decorate([ + editableInPropertyPage("Epsilon", 1 /* PropertyTypeForEdition.Float */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], GeometryOptimizeBlock.prototype, "epsilon", void 0); +__decorate([ + editableInPropertyPage("Optimize faces", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], GeometryOptimizeBlock.prototype, "optimizeFaces", void 0); +RegisterClass("BABYLON.GeometryOptimizeBlock", GeometryOptimizeBlock); + +/** + * Defines a block used to generate plane geometry data + */ +class PlaneBlock extends NodeGeometryBlock { + /** + * Create a new PlaneBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._rotationMatrix = new Matrix(); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + this.registerInput("size", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("width", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1, 0); + this.registerInput("subdivisionsX", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0); + this.registerInput("subdivisionsY", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0); + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "PlaneBlock"; + } + /** + * Gets the size input component + */ + get size() { + return this._inputs[0]; + } + /** + * Gets the width input component + */ + get width() { + return this._inputs[1]; + } + /** + * Gets the height input component + */ + get height() { + return this._inputs[2]; + } + /** + * Gets the subdivisions input component + */ + get subdivisions() { + return this._inputs[3]; + } + /** + * Gets the subdivisionsX input component + */ + get subdivisionsX() { + return this._inputs[4]; + } + /** + * Gets the subdivisionsY input component + */ + get subdivisionsY() { + return this._inputs[5]; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + autoConfigure() { + if (this.size.isConnected) { + return; + } + if (!this.width.isConnected && !this.height.isConnected) { + const sizeInput = new GeometryInputBlock("Size"); + sizeInput.value = 1; + sizeInput.output.connectTo(this.size); + return; + } + if (!this.width.isConnected) { + const widthInput = new GeometryInputBlock("Width"); + widthInput.value = 1; + widthInput.output.connectTo(this.width); + } + if (!this.height.isConnected) { + const heightInput = new GeometryInputBlock("Height"); + heightInput.value = 1; + heightInput.output.connectTo(this.height); + } + } + _buildBlock(state) { + const options = {}; + const func = (state) => { + options.size = this.size.getConnectedValue(state); + options.width = this.width.getConnectedValue(state); + options.height = this.height.getConnectedValue(state); + const subdivisions = this.subdivisions.getConnectedValue(state); + const subdivisionsX = this.subdivisionsX.getConnectedValue(state); + const subdivisionsY = this.subdivisionsY.getConnectedValue(state); + if (subdivisions) { + options.subdivisions = subdivisions; + } + if (subdivisionsX) { + options.subdivisionsX = subdivisionsX; + } + if (subdivisionsY) { + options.subdivisionsY = subdivisionsY; + } + // Append vertex data from the ground builder (to get access to subdivisions) + const vertexData = CreateGroundVertexData(options); + Matrix.RotationYawPitchRollToRef(-Math.PI / 2, 0, Math.PI / 2, this._rotationMatrix); + vertexData.transform(this._rotationMatrix); + return vertexData; + }; + if (this.evaluateContext) { + this.geometry._storedFunction = func; + } + else { + const value = func(state); + this.geometry._storedFunction = () => { + this.geometry._executionCount = 1; + return value.clone(); + }; + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], PlaneBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.PlaneBlock", PlaneBlock); + +/** + * Defines a block used to generate a user defined mesh geometry data + */ +class MeshBlock extends NodeGeometryBlock { + /** + * Gets or sets the mesh to use to get vertex data + */ + get mesh() { + return this._mesh; + } + set mesh(value) { + this._mesh = value; + } + /** + * Create a new MeshBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._cachedVertexData = null; + /** + * Gets or sets a boolean indicating that winding order needs to be reserved + */ + this.reverseWindingOrder = false; + /** + * Gets or sets a boolean indicating that this block should serialize its cached data + */ + this.serializedCachedData = false; + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MeshBlock"; + } + /** + * Gets a boolean indicating if the block is using cached data + */ + get isUsingCachedData() { + return !this.mesh && !!this._cachedVertexData; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + /** + * Remove stored data + */ + cleanData() { + this._mesh = null; + this._cachedVertexData = null; + } + _buildBlock() { + if (!this._mesh) { + if (this._cachedVertexData) { + this.geometry._storedValue = this._cachedVertexData.clone(); + } + else { + this.geometry._storedValue = null; + } + return; + } + const vertexData = VertexData.ExtractFromMesh(this._mesh, false, true); + this._cachedVertexData = null; + if (this.reverseWindingOrder && vertexData.indices) { + for (let index = 0; index < vertexData.indices.length; index += 3) { + const tmp = vertexData.indices[index]; + vertexData.indices[index] = vertexData.indices[index + 2]; + vertexData.indices[index + 2] = tmp; + } + } + this.geometry._storedFunction = () => { + return vertexData.clone(); + }; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.serializedCachedData = this.serializedCachedData; + if (this.serializedCachedData) { + if (this._mesh) { + serializationObject.cachedVertexData = VertexData.ExtractFromMesh(this._mesh, false, true).serialize(); + } + else if (this._cachedVertexData) { + serializationObject.cachedVertexData = this._cachedVertexData.serialize(); + } + } + serializationObject.reverseWindingOrder = this.reverseWindingOrder; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.cachedVertexData) { + this._cachedVertexData = VertexData.Parse(serializationObject.cachedVertexData); + } + this.serializedCachedData = !!serializationObject.serializedCachedData; + this.reverseWindingOrder = serializationObject.reverseWindingOrder; + } +} +__decorate([ + editableInPropertyPage("Serialize cached data", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], MeshBlock.prototype, "serializedCachedData", void 0); +RegisterClass("BABYLON.MeshBlock", MeshBlock); + +/** + * Defines a block used to generate icosphere geometry data + */ +class IcoSphereBlock extends NodeGeometryBlock { + /** + * Create a new IcoSphereBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("radiusX", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("radiusY", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("radiusZ", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 4); + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "IcoSphereBlock"; + } + /** + * Gets the radius input component + */ + get radius() { + return this._inputs[0]; + } + /** + * Gets the radiusX input component + */ + get radiusX() { + return this._inputs[1]; + } + /** + * Gets the radiusY input component + */ + get radiusY() { + return this._inputs[2]; + } + /** + * Gets the radiusZ input component + */ + get radiusZ() { + return this._inputs[3]; + } + /** + * Gets the subdivisions input component + */ + get subdivisions() { + return this._inputs[4]; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.radius.isConnected) { + const radiusInput = new GeometryInputBlock("Radius"); + radiusInput.value = 0.2; + radiusInput.output.connectTo(this.radius); + } + } + _buildBlock(state) { + const options = {}; + const func = (state) => { + options.radius = this.radius.getConnectedValue(state); + options.subdivisions = this.subdivisions.getConnectedValue(state); + options.radiusX = this.radiusX.getConnectedValue(state); + options.radiusY = this.radiusY.getConnectedValue(state); + options.radiusZ = this.radiusZ.getConnectedValue(state); + // Append vertex data from the plane builder + return CreateIcoSphereVertexData(options); + }; + if (this.evaluateContext) { + this.geometry._storedFunction = func; + } + else { + const value = func(state); + this.geometry._storedFunction = () => { + this.geometry._executionCount = 1; + return value.clone(); + }; + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], IcoSphereBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.IcoSphereBlock", IcoSphereBlock); + +/** + * Defines a block used to generate sphere geometry data + */ +class SphereBlock extends NodeGeometryBlock { + /** + * Create a new SphereBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + this.registerInput("segments", NodeGeometryBlockConnectionPointTypes.Int, true, 32); + this.registerInput("diameter", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("diameterX", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("diameterY", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("diameterZ", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("arc", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("slice", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SphereBlock"; + } + /** + * Gets the segments input component + */ + get segments() { + return this._inputs[0]; + } + /** + * Gets the diameter input component + */ + get diameter() { + return this._inputs[1]; + } + /** + * Gets the diameterX input component + */ + get diameterX() { + return this._inputs[2]; + } + /** + * Gets the diameterY input component + */ + get diameterY() { + return this._inputs[3]; + } + /** + * Gets the diameterZ input component + */ + get diameterZ() { + return this._inputs[4]; + } + /** + * Gets the arc input component + */ + get arc() { + return this._inputs[5]; + } + /** + * Gets the slice input component + */ + get slice() { + return this._inputs[6]; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.diameter.isConnected) { + const diameterInput = new GeometryInputBlock("Diameter"); + diameterInput.value = 1; + diameterInput.output.connectTo(this.diameter); + } + } + _buildBlock(state) { + const options = {}; + const func = (state) => { + options.segments = this.segments.getConnectedValue(state); + options.diameter = this.diameter.getConnectedValue(state); + options.diameterX = this.diameterX.getConnectedValue(state); + options.diameterY = this.diameterY.getConnectedValue(state); + options.diameterZ = this.diameterZ.getConnectedValue(state); + options.arc = this.arc.getConnectedValue(state); + options.slice = this.slice.getConnectedValue(state); + // Append vertex data from the plane builder + return CreateSphereVertexData(options); + }; + if (this.evaluateContext) { + this.geometry._storedFunction = func; + } + else { + const value = func(state); + this.geometry._storedFunction = () => { + this.geometry._executionCount = 1; + return value.clone(); + }; + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], SphereBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.SphereBlock", SphereBlock); + +/** + * Defines a block used to generate grid geometry data + */ +class GridBlock extends NodeGeometryBlock { + /** + * Create a new GridBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + this.registerInput("width", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1, 0); + this.registerInput("subdivisionsX", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0); + this.registerInput("subdivisionsY", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0); + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GridBlock"; + } + /** + * Gets the width input component + */ + get width() { + return this._inputs[0]; + } + /** + * Gets the height input component + */ + get height() { + return this._inputs[1]; + } + /** + * Gets the subdivisions input component + */ + get subdivisions() { + return this._inputs[2]; + } + /** + * Gets the subdivisionsX input component + */ + get subdivisionsX() { + return this._inputs[3]; + } + /** + * Gets the subdivisionsY input component + */ + get subdivisionsY() { + return this._inputs[4]; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.width.isConnected) { + const widthInput = new GeometryInputBlock("Width"); + widthInput.value = 1; + widthInput.output.connectTo(this.width); + } + if (!this.height.isConnected) { + const heightInput = new GeometryInputBlock("Height"); + heightInput.value = 1; + heightInput.output.connectTo(this.height); + } + } + _buildBlock(state) { + const options = {}; + const func = (state) => { + options.width = this.width.getConnectedValue(state); + options.height = this.height.getConnectedValue(state); + options.subdivisions = this.subdivisions.getConnectedValue(state); + options.subdivisionsX = this.subdivisionsX.getConnectedValue(state); + options.subdivisionsY = this.subdivisionsY.getConnectedValue(state); + // Append vertex data from the plane builder + return CreateGroundVertexData(options); + }; + if (this.evaluateContext) { + this.geometry._storedFunction = func; + } + else { + const value = func(state); + this.geometry._storedFunction = () => { + this.geometry._executionCount = 1; + return value.clone(); + }; + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], GridBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.GridBlock", GridBlock); + +/** + * Defines a block used to generate torus geometry data + */ +class TorusBlock extends NodeGeometryBlock { + /** + * Create a new TorusBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + this.registerInput("diameter", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("thickness", NodeGeometryBlockConnectionPointTypes.Float, true, 0.5); + this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 16); + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "TorusBlock"; + } + /** + * Gets the diameter input component + */ + get diameter() { + return this._inputs[0]; + } + /** + * Gets the thickness input component + */ + get thickness() { + return this._inputs[1]; + } + /** + * Gets the tessellation input component + */ + get tessellation() { + return this._inputs[2]; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.diameter.isConnected) { + const diameterInput = new GeometryInputBlock("Diameter"); + diameterInput.value = 1; + diameterInput.output.connectTo(this.diameter); + } + } + _buildBlock(state) { + const options = {}; + const func = (state) => { + options.thickness = this.thickness.getConnectedValue(state); + options.diameter = this.diameter.getConnectedValue(state); + options.tessellation = this.tessellation.getConnectedValue(state); + // Append vertex data from the plane builder + return CreateTorusVertexData(options); + }; + if (this.evaluateContext) { + this.geometry._storedFunction = func; + } + else { + const value = func(state); + this.geometry._storedFunction = () => { + this.geometry._executionCount = 1; + return value.clone(); + }; + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], TorusBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.TorusBlock", TorusBlock); + +/** + * Defines a block used to generate cylinder geometry data + */ +class CylinderBlock extends NodeGeometryBlock { + /** + * Create a new SphereBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 25); + this.registerInput("diameter", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("diameterTop", NodeGeometryBlockConnectionPointTypes.Float, true, -1); + this.registerInput("diameterBottom", NodeGeometryBlockConnectionPointTypes.Float, true, -1); + this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1); + this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 24); + this.registerInput("arc", NodeGeometryBlockConnectionPointTypes.Float, true, 1.0); + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "CylinderBlock"; + } + /** + * Gets the height input component + */ + get height() { + return this._inputs[0]; + } + /** + * Gets the diameter input component + */ + get diameter() { + return this._inputs[1]; + } + /** + * Gets the diameterTop input component + */ + get diameterTop() { + return this._inputs[2]; + } + /** + * Gets the diameterBottom input component + */ + get diameterBottom() { + return this._inputs[3]; + } + /** + * Gets the subdivisions input component + */ + get subdivisions() { + return this._inputs[4]; + } + /** + * Gets the tessellation input component + */ + get tessellation() { + return this._inputs[5]; + } + /** + * Gets the arc input component + */ + get arc() { + return this._inputs[6]; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.diameter.isConnected) { + const diameterInput = new GeometryInputBlock("Diameter"); + diameterInput.value = 1; + diameterInput.output.connectTo(this.diameter); + } + if (!this.height.isConnected) { + const heightInput = new GeometryInputBlock("Height"); + heightInput.value = 1; + heightInput.output.connectTo(this.height); + } + } + _buildBlock(state) { + const options = {}; + const func = (state) => { + options.height = this.height.getConnectedValue(state); + options.diameter = this.diameter.getConnectedValue(state); + options.diameterTop = this.diameterTop.getConnectedValue(state); + options.diameterBottom = this.diameterBottom.getConnectedValue(state); + if (options.diameterTop === -1) { + options.diameterTop = options.diameter; + } + if (options.diameterBottom === -1) { + options.diameterBottom = options.diameter; + } + options.tessellation = this.tessellation.getConnectedValue(state); + options.subdivisions = this.subdivisions.getConnectedValue(state); + options.arc = this.arc.getConnectedValue(state); + // Append vertex data from the plane builder + return CreateCylinderVertexData(options); + }; + if (this.evaluateContext) { + this.geometry._storedFunction = func; + } + else { + const value = func(state); + this.geometry._storedFunction = () => { + this.geometry._executionCount = 1; + return value.clone(); + }; + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], CylinderBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.CylinderBlock", CylinderBlock); + +/** + * Defines a block used to generate capsule geometry data + */ +class CapsuleBlock extends NodeGeometryBlock { + /** + * Create a new CapsuleBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Float, true, 0.25); + this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 16); + this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 2); + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "CapsuleBlock"; + } + /** + * Gets the height input component + */ + get height() { + return this._inputs[0]; + } + /** + * Gets the radius input component + */ + get radius() { + return this._inputs[1]; + } + /** + * Gets the tessellation input component + */ + get tessellation() { + return this._inputs[2]; + } + /** + * Gets the subdivisions input component + */ + get subdivisions() { + return this._inputs[3]; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.height.isConnected) { + const heightInput = new GeometryInputBlock("Height"); + heightInput.value = 1; + heightInput.output.connectTo(this.height); + } + if (!this.radius.isConnected) { + const radiusInput = new GeometryInputBlock("Radius"); + radiusInput.value = 0.2; + radiusInput.output.connectTo(this.radius); + } + } + _buildBlock(state) { + const options = {}; + const func = (state) => { + options.height = this.height.getConnectedValue(state); + options.radius = this.radius.getConnectedValue(state); + options.tessellation = this.tessellation.getConnectedValue(state); + options.subdivisions = this.subdivisions.getConnectedValue(state); + // Append vertex data from the plane builder + return CreateCapsuleVertexData(options); + }; + if (this.evaluateContext) { + this.geometry._storedFunction = func; + } + else { + const value = func(state); + this.geometry._storedFunction = () => { + this.geometry._executionCount = 1; + return value.clone(); + }; + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], CapsuleBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.CapsuleBlock", CapsuleBlock); + +/** + * Defines a block used to generate disc geometry data + */ +class DiscBlock extends NodeGeometryBlock { + /** + * Create a new DiscBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Float, true, 0.5); + this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 64); + this.registerInput("arc", NodeGeometryBlockConnectionPointTypes.Float, true, 1.0); + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "DiscBlock"; + } + /** + * Gets the radius input component + */ + get radius() { + return this._inputs[0]; + } + /** + * Gets the tessellation input component + */ + get tessellation() { + return this._inputs[1]; + } + /** + * Gets the arc input component + */ + get arc() { + return this._inputs[2]; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.radius.isConnected) { + const radiusInput = new GeometryInputBlock("Radius"); + radiusInput.value = 0.2; + radiusInput.output.connectTo(this.radius); + } + } + _buildBlock(state) { + const options = {}; + const func = (state) => { + options.radius = this.radius.getConnectedValue(state); + options.tessellation = this.tessellation.getConnectedValue(state); + options.arc = this.arc.getConnectedValue(state); + // Append vertex data from the plane builder + return CreateDiscVertexData(options); + }; + if (this.evaluateContext) { + this.geometry._storedFunction = func; + } + else { + const value = func(state); + this.geometry._storedFunction = () => { + this.geometry._executionCount = 1; + return value.clone(); + }; + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], DiscBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.DiscBlock", DiscBlock); + +/** + * Defines a block used to generate a null geometry data + */ +class NullBlock extends NodeGeometryBlock { + /** + * Create a new NullBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerOutput("vector", NodeGeometryBlockConnectionPointTypes.Vector3); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NullBlock"; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + /** + * Gets the vector output component + */ + get vector() { + return this._outputs[1]; + } + _buildBlock() { + this.geometry._storedValue = null; + this.vector._storedValue = null; + } +} +RegisterClass("BABYLON.NullBlock", NullBlock); + +/** + * Defines a block used to generate a geometry data from a list of points + */ +class PointListBlock extends NodeGeometryBlock { + /** + * Create a new PointListBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a list of points used to generate the geometry + */ + this.points = []; + this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "PointListBlock"; + } + /** + * Gets the geometry output component + */ + get geometry() { + return this._outputs[0]; + } + _buildBlock(state) { + this.geometry._storedFunction = () => { + this.geometry._executionCount = 1; + if (this.points.length === 0) { + return null; + } + const vertexData = new VertexData(); + vertexData.positions = this.points.reduce((acc, point) => { + acc.push(point.x, point.y, point.z); + return acc; + }, []); + return vertexData; + }; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.points = [];\n`; + for (let i = 0; i < this.points.length; i++) { + const point = this.points[i]; + codeString += `${this._codeVariableName}.points.push(new BABYLON.Vector3(${point.x}, ${point.y}, ${point.z}));\n`; + } + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.points = this.points.map((point) => { + return point.asArray(); + }); + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.points = serializationObject.points.map((point) => { + return Vector3.FromArray(point); + }); + } +} +RegisterClass("BABYLON.PointListBlock", PointListBlock); + +/** + * Block used to set positions for a geometry + */ +class SetPositionsBlock extends NodeGeometryBlock { + /** + * Create a new SetPositionsBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("positions", NodeGeometryBlockConnectionPointTypes.Vector3); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._currentIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentIndex; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SetPositionsBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the positions input component + */ + get positions() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _remapVector3Data(source, remap) { + const newData = []; + for (let index = 0; index < source.length; index += 3) { + const remappedIndex = remap[index / 3]; + if (remappedIndex !== undefined) { + newData.push(source[index], source[index + 1], source[index + 2]); + } + } + return newData; + } + _remapVector4Data(source, remap) { + const newData = []; + for (let index = 0; index < source.length; index += 4) { + const remappedIndex = remap[index / 4]; + if (remappedIndex !== undefined) { + newData.push(source[index], source[index + 1], source[index + 2], source[index + 3]); + } + } + return newData; + } + _remapVector2Data(source, remap) { + const newData = []; + for (let index = 0; index < source.length; index += 2) { + const remappedIndex = remap[index / 2]; + if (remappedIndex !== undefined) { + newData.push(source[index], source[index + 1]); + } + } + return newData; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + this._vertexData = this.geometry.getConnectedValue(state); + if (this._vertexData) { + this._vertexData = this._vertexData.clone(); // Preserve source data + } + state.pushGeometryContext(this._vertexData); + if (!this._vertexData || !this._vertexData.positions || !this.positions.isConnected) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedValue = null; + return; + } + // Processing + const remap = {}; + const vertexCount = this._vertexData.positions.length / 3; + const newPositions = []; + let activeIndex = 0; + let resize = false; + for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { + const tempVector3 = this.positions.getConnectedValue(state); + if (tempVector3) { + tempVector3.toArray(newPositions, activeIndex * 3); + remap[this._currentIndex] = activeIndex; + activeIndex++; + } + else { + resize = true; + } + } + if (resize) { + // Indices remap + if (this._vertexData.indices) { + const newIndices = []; + for (let index = 0; index < this._vertexData.indices.length; index += 3) { + const a = this._vertexData.indices[index]; + const b = this._vertexData.indices[index + 1]; + const c = this._vertexData.indices[index + 2]; + const remappedA = remap[a]; + const remappedB = remap[b]; + const remappedC = remap[c]; + if (remappedA !== undefined && remappedB !== undefined && remappedC !== undefined) { + newIndices.push(remappedA); + newIndices.push(remappedB); + newIndices.push(remappedC); + } + } + this._vertexData.indices = newIndices; + } + // Normals remap + if (this._vertexData.normals) { + this._vertexData.normals = this._remapVector3Data(this._vertexData.normals, remap); + } + // Tangents remap + if (this._vertexData.tangents) { + this._vertexData.tangents = this._remapVector4Data(this._vertexData.tangents, remap); + } + // Colors remap + if (this._vertexData.colors) { + this._vertexData.colors = this._remapVector4Data(this._vertexData.colors, remap); + } + // UVs remap + if (this._vertexData.uvs) { + this._vertexData.uvs = this._remapVector2Data(this._vertexData.uvs, remap); + } + if (this._vertexData.uvs2) { + this._vertexData.uvs2 = this._remapVector2Data(this._vertexData.uvs2, remap); + } + if (this._vertexData.uvs3) { + this._vertexData.uvs3 = this._remapVector2Data(this._vertexData.uvs3, remap); + } + if (this._vertexData.uvs4) { + this._vertexData.uvs4 = this._remapVector2Data(this._vertexData.uvs4, remap); + } + if (this._vertexData.uvs5) { + this._vertexData.uvs5 = this._remapVector2Data(this._vertexData.uvs5, remap); + } + if (this._vertexData.uvs6) { + this._vertexData.uvs6 = this._remapVector2Data(this._vertexData.uvs6, remap); + } + } + // Update positions + this._vertexData.positions = newPositions; + // Storage + state.restoreGeometryContext(); + state.restoreExecutionContext(); + return this._vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], SetPositionsBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.SetPositionsBlock", SetPositionsBlock); + +/** + * Block used to set normals for a geometry + */ +class SetNormalsBlock extends NodeGeometryBlock { + /** + * Create a new SetNormalsBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("normals", NodeGeometryBlockConnectionPointTypes.Vector3); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._currentIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentIndex; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SetNormalsBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the normals input component + */ + get normals() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + this._vertexData = this.geometry.getConnectedValue(state); + if (this._vertexData) { + this._vertexData = this._vertexData.clone(); // Preserve source data + } + state.pushGeometryContext(this._vertexData); + if (!this._vertexData || !this._vertexData.positions) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedValue = null; + return; + } + if (!this.normals.isConnected) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedValue = this._vertexData; + return; + } + if (!this._vertexData.normals) { + this._vertexData.normals = []; + } + // Processing + const vertexCount = this._vertexData.positions.length / 3; + for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { + const tempVector3 = this.normals.getConnectedValue(state); + if (tempVector3) { + tempVector3.toArray(this._vertexData.normals, this._currentIndex * 3); + } + } + // Storage + state.restoreGeometryContext(); + state.restoreExecutionContext(); + return this._vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], SetNormalsBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.SetNormalsBlock", SetNormalsBlock); + +/** + * Block used to set texture coordinates for a geometry + */ +class SetUVsBlock extends NodeGeometryBlock { + /** + * Create a new SetUVsBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + /** + * Gets or sets a value indicating which UV to set + */ + this.textureCoordinateIndex = 0; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("uvs", NodeGeometryBlockConnectionPointTypes.Vector2); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._currentIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentIndex; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SetUVsBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the uvs input component + */ + get uvs() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + this._vertexData = this.geometry.getConnectedValue(state); + if (this._vertexData) { + this._vertexData = this._vertexData.clone(); // Preserve source data + } + state.pushGeometryContext(this._vertexData); + if (!this._vertexData || !this._vertexData.positions) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedValue = null; + return; + } + if (!this.uvs.isConnected) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedValue = this._vertexData; + return; + } + const uvs = []; + // Processing + const vertexCount = this._vertexData.positions.length / 3; + for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { + const tempVector2 = this.uvs.getConnectedValue(state); + if (tempVector2) { + tempVector2.toArray(uvs, this._currentIndex * 2); + } + } + switch (this.textureCoordinateIndex) { + case 0: + this._vertexData.uvs = uvs; + break; + case 1: + this._vertexData.uvs2 = uvs; + break; + case 2: + this._vertexData.uvs3 = uvs; + break; + case 3: + this._vertexData.uvs4 = uvs; + break; + case 4: + this._vertexData.uvs5 = uvs; + break; + case 5: + this._vertexData.uvs6 = uvs; + break; + } + // Storage + state.restoreGeometryContext(); + state.restoreExecutionContext(); + return this._vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.textureCoordinateIndex};\n`; + codeString += `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + serializationObject.textureCoordinateIndex = this.textureCoordinateIndex; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.textureCoordinateIndex = serializationObject.textureCoordinateIndex; + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], SetUVsBlock.prototype, "evaluateContext", void 0); +__decorate([ + editableInPropertyPage("Texture coordinates index", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { update: true }, + embedded: true, + options: [ + { label: "UV1", value: 0 }, + { label: "UV2", value: 1 }, + { label: "UV3", value: 2 }, + { label: "UV4", value: 3 }, + { label: "UV5", value: 4 }, + { label: "UV6", value: 5 }, + ], + }) +], SetUVsBlock.prototype, "textureCoordinateIndex", void 0); +RegisterClass("BABYLON.SetUVsBlock", SetUVsBlock); + +/** + * Block used to set colors for a geometry + */ +class SetColorsBlock extends NodeGeometryBlock { + /** + * Create a new SetColorsBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("colors", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector2); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._currentIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentIndex; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SetColorsBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the colors input component + */ + get colors() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + this._vertexData = this.geometry.getConnectedValue(state); + if (this._vertexData) { + this._vertexData = this._vertexData.clone(); // Preserve source data + } + state.pushGeometryContext(this._vertexData); + if (!this._vertexData || !this._vertexData.positions) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedValue = null; + return; + } + if (!this.colors.isConnected) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedValue = this._vertexData; + return; + } + if (!this._vertexData.colors) { + this._vertexData.colors = []; + } + // Processing + const vertexCount = this._vertexData.positions.length / 3; + for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { + if (this.colors.connectedPoint?.type === NodeGeometryBlockConnectionPointTypes.Vector3) { + const tempVector3 = this.colors.getConnectedValue(state); + if (tempVector3) { + tempVector3.toArray(this._vertexData.colors, this._currentIndex * 4); + this._vertexData.colors[this._currentIndex * 4 + 3] = 1; // Alpha + this._vertexData.hasVertexAlpha = false; + } + } + else { + const tempVector4 = this.colors.getConnectedValue(state); + if (tempVector4) { + tempVector4.toArray(this._vertexData.colors, this._currentIndex * 4); + this._vertexData.hasVertexAlpha = true; + } + } + } + // Storage + state.restoreGeometryContext(); + state.restoreExecutionContext(); + return this._vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], SetColorsBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.SetColorsBlock", SetColorsBlock); + +/** + * Block used to set tangents for a geometry + */ +class SetTangentsBlock extends NodeGeometryBlock { + /** + * Create a new SetTangentsBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("tangents", NodeGeometryBlockConnectionPointTypes.Vector4); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._currentIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentIndex; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SetTangentsBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the tangents input component + */ + get tangents() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + this._vertexData = this.geometry.getConnectedValue(state); + if (this._vertexData) { + this._vertexData = this._vertexData.clone(); // Preserve source data + } + state.pushGeometryContext(this._vertexData); + if (!this._vertexData || !this._vertexData.positions) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedValue = null; + return; + } + if (!this.tangents.isConnected) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedValue = this._vertexData; + return; + } + if (!this._vertexData.tangents) { + this._vertexData.tangents = []; + } + // Processing + const vertexCount = this._vertexData.positions.length / 3; + for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { + const tempVector4 = this.tangents.getConnectedValue(state); + if (tempVector4) { + tempVector4.toArray(this._vertexData.tangents, this._currentIndex * 4); + } + } + // Storage + state.restoreGeometryContext(); + state.restoreExecutionContext(); + return this._vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], SetTangentsBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.SetTangentsBlock", SetTangentsBlock); + +/** + * Operations supported by the Math block + */ +var MathBlockOperations; +(function (MathBlockOperations) { + /** Add */ + MathBlockOperations[MathBlockOperations["Add"] = 0] = "Add"; + /** Subtract */ + MathBlockOperations[MathBlockOperations["Subtract"] = 1] = "Subtract"; + /** Multiply */ + MathBlockOperations[MathBlockOperations["Multiply"] = 2] = "Multiply"; + /** Divide */ + MathBlockOperations[MathBlockOperations["Divide"] = 3] = "Divide"; + /** Max */ + MathBlockOperations[MathBlockOperations["Max"] = 4] = "Max"; + /** Min */ + MathBlockOperations[MathBlockOperations["Min"] = 5] = "Min"; +})(MathBlockOperations || (MathBlockOperations = {})); +/** + * Block used to apply math functions + */ +class MathBlock extends NodeGeometryBlock { + /** + * Create a new MathBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets the operation applied by the block + */ + this.operation = MathBlockOperations.Add; + this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this.output._typeConnectionSource = this.left; + const excludedConnectionPointTypes = [ + NodeGeometryBlockConnectionPointTypes.Matrix, + NodeGeometryBlockConnectionPointTypes.Geometry, + NodeGeometryBlockConnectionPointTypes.Texture, + ]; + this.left.excludedConnectionPointTypes.push(...excludedConnectionPointTypes); + this.right.excludedConnectionPointTypes.push(...excludedConnectionPointTypes); + this._linkConnectionTypes(0, 1); + this._connectionObservers = [ + this.left.onConnectionObservable.add(() => this._updateInputOutputTypes()), + this.left.onDisconnectionObservable.add(() => this._updateInputOutputTypes()), + this.right.onConnectionObservable.add(() => this._updateInputOutputTypes()), + this.right.onDisconnectionObservable.add(() => this._updateInputOutputTypes()), + ]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MathBlock"; + } + /** + * Gets the left input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + let func; + const left = this.left; + const right = this.right; + if (!left.isConnected || !right.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const leftIsScalar = left.type === NodeGeometryBlockConnectionPointTypes.Float || left.type === NodeGeometryBlockConnectionPointTypes.Int; + const rightIsScalar = right.type === NodeGeometryBlockConnectionPointTypes.Float || right.type === NodeGeometryBlockConnectionPointTypes.Int; + // If both input types are scalars, then this is a scalar operation. + const isScalar = leftIsScalar && rightIsScalar; + switch (this.operation) { + case MathBlockOperations.Add: { + if (isScalar) { + func = (state) => { + return left.getConnectedValue(state) + right.getConnectedValue(state); + }; + } + else if (leftIsScalar) { + func = (state) => { + return state.adapt(left, right.type).add(right.getConnectedValue(state)); + }; + } + else { + func = (state) => { + return left.getConnectedValue(state).add(state.adapt(right, left.type)); + }; + } + break; + } + case MathBlockOperations.Subtract: { + if (isScalar) { + func = (state) => { + return left.getConnectedValue(state) - right.getConnectedValue(state); + }; + } + else if (leftIsScalar) { + func = (state) => { + return state.adapt(left, right.type).subtract(right.getConnectedValue(state)); + }; + } + else { + func = (state) => { + return left.getConnectedValue(state).subtract(state.adapt(right, left.type)); + }; + } + break; + } + case MathBlockOperations.Multiply: { + if (isScalar) { + func = (state) => { + return left.getConnectedValue(state) * right.getConnectedValue(state); + }; + } + else if (leftIsScalar) { + func = (state) => { + return state.adapt(left, right.type).multiply(right.getConnectedValue(state)); + }; + } + else { + func = (state) => { + return left.getConnectedValue(state).multiply(state.adapt(right, left.type)); + }; + } + break; + } + case MathBlockOperations.Divide: { + if (isScalar) { + func = (state) => { + return left.getConnectedValue(state) / right.getConnectedValue(state); + }; + } + else if (leftIsScalar) { + func = (state) => { + return state.adapt(left, right.type).divide(right.getConnectedValue(state)); + }; + } + else { + func = (state) => { + return left.getConnectedValue(state).divide(state.adapt(right, left.type)); + }; + } + break; + } + case MathBlockOperations.Min: { + if (isScalar) { + func = (state) => { + return Math.min(left.getConnectedValue(state), right.getConnectedValue(state)); + }; + } + else { + const [vector, scalar] = leftIsScalar ? [right, left] : [left, right]; + switch (vector.type) { + case NodeGeometryBlockConnectionPointTypes.Vector2: { + func = (state) => { + return Vector2.Minimize(vector.getConnectedValue(state), state.adapt(scalar, vector.type)); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + func = (state) => { + return Vector3.Minimize(vector.getConnectedValue(state), state.adapt(scalar, vector.type)); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + func = (state) => { + return Vector4.Minimize(vector.getConnectedValue(state), state.adapt(scalar, vector.type)); + }; + break; + } + } + } + break; + } + case MathBlockOperations.Max: { + if (isScalar) { + func = (state) => { + return Math.max(left.getConnectedValue(state), right.getConnectedValue(state)); + }; + } + else { + const [vector, scalar] = leftIsScalar ? [right, left] : [left, right]; + switch (vector.type) { + case NodeGeometryBlockConnectionPointTypes.Vector2: { + func = (state) => { + return Vector2.Maximize(vector.getConnectedValue(state), state.adapt(scalar, vector.type)); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + func = (state) => { + return Vector3.Maximize(vector.getConnectedValue(state), state.adapt(scalar, vector.type)); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + func = (state) => { + return Vector4.Maximize(vector.getConnectedValue(state), state.adapt(scalar, vector.type)); + }; + break; + } + } + break; + } + } + } + this.output._storedFunction = (state) => { + if (left.type === NodeGeometryBlockConnectionPointTypes.Int) { + return func(state) | 0; + } + return func(state); + }; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${MathBlockOperations[this.operation]};\n`; + return codeString; + } + _updateInputOutputTypes() { + // First update the output type with the initial assumption that we'll base it on the left input. + this.output._typeConnectionSource = this.left; + if (this.left.isConnected && this.right.isConnected) { + // Both inputs are connected, so we need to determine the output type based on the input types. + if (this.left.type === NodeGeometryBlockConnectionPointTypes.Int || + (this.left.type === NodeGeometryBlockConnectionPointTypes.Float && this.right.type !== NodeGeometryBlockConnectionPointTypes.Int)) { + this.output._typeConnectionSource = this.right; + } + } + else if (this.left.isConnected !== this.right.isConnected) { + // Only one input is connected, so we need to determine the output type based on the connected input. + this.output._typeConnectionSource = this.left.isConnected ? this.left : this.right; + } + // Next update the accepted connection point types for the inputs based on the current input connection state. + if (this.left.isConnected || this.right.isConnected) { + for (const [first, second] of [ + [this.left, this.right], + [this.right, this.left], + ]) { + // Always allow Ints and Floats. + first.acceptedConnectionPointTypes = [NodeGeometryBlockConnectionPointTypes.Int, NodeGeometryBlockConnectionPointTypes.Float]; + if (second.isConnected) { + // The same types as the connected input are always allowed. + first.acceptedConnectionPointTypes.push(second.type); + // If the other input is a scalar, then we also allow Vector types. + if (second.type === NodeGeometryBlockConnectionPointTypes.Int || second.type === NodeGeometryBlockConnectionPointTypes.Float) { + first.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector2, NodeGeometryBlockConnectionPointTypes.Vector3, NodeGeometryBlockConnectionPointTypes.Vector4); + } + } + } + } + } + /** + * Release resources + */ + dispose() { + super.dispose(); + this._connectionObservers.forEach((observer) => observer.remove()); + this._connectionObservers.length = 0; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.operation = this.operation; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.operation = serializationObject.operation; + } +} +__decorate([ + editableInPropertyPage("Operation", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "Add", value: MathBlockOperations.Add }, + { label: "Subtract", value: MathBlockOperations.Subtract }, + { label: "Multiply", value: MathBlockOperations.Multiply }, + { label: "Divide", value: MathBlockOperations.Divide }, + { label: "Max", value: MathBlockOperations.Max }, + { label: "Min", value: MathBlockOperations.Min }, + ], + }) +], MathBlock.prototype, "operation", void 0); +RegisterClass("BABYLON.MathBlock", MathBlock); + +/** + * Defines a block used to move a value from a range to another + */ +class MapRangeBlock extends NodeGeometryBlock { + /** + * Create a new MapRangeBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("fromMin", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("fromMax", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("toMin", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("toMax", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector2); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector3); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector4); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MapRangeBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the fromMin input component + */ + get fromMin() { + return this._inputs[1]; + } + /** + * Gets the fromMax input component + */ + get fromMax() { + return this._inputs[2]; + } + /** + * Gets the toMin input component + */ + get toMin() { + return this._inputs[3]; + } + /** + * Gets the toMax input component + */ + get toMax() { + return this._inputs[4]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.value.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + this.output._storedFunction = (state) => { + const value = this.value.getConnectedValue(state); + const fromMin = this.fromMin.getConnectedValue(state); + const fromMax = this.fromMax.getConnectedValue(state); + const toMin = this.toMin.getConnectedValue(state); + const toMax = this.toMax.getConnectedValue(state); + const result = ((value - fromMin) / (fromMax - fromMin)) * (toMax - toMin) + toMin; + if (this.output.type === NodeGeometryBlockConnectionPointTypes.Int) { + return Math.floor(result); + } + return result; + }; + } +} +RegisterClass("BABYLON.MapRangeBlock", MapRangeBlock); + +/** + * Conditions supported by the condition block + */ +var ConditionBlockTests; +(function (ConditionBlockTests) { + /** Equal */ + ConditionBlockTests[ConditionBlockTests["Equal"] = 0] = "Equal"; + /** NotEqual */ + ConditionBlockTests[ConditionBlockTests["NotEqual"] = 1] = "NotEqual"; + /** LessThan */ + ConditionBlockTests[ConditionBlockTests["LessThan"] = 2] = "LessThan"; + /** GreaterThan */ + ConditionBlockTests[ConditionBlockTests["GreaterThan"] = 3] = "GreaterThan"; + /** LessOrEqual */ + ConditionBlockTests[ConditionBlockTests["LessOrEqual"] = 4] = "LessOrEqual"; + /** GreaterOrEqual */ + ConditionBlockTests[ConditionBlockTests["GreaterOrEqual"] = 5] = "GreaterOrEqual"; + /** Logical Exclusive OR */ + ConditionBlockTests[ConditionBlockTests["Xor"] = 6] = "Xor"; + /** Logical Or */ + ConditionBlockTests[ConditionBlockTests["Or"] = 7] = "Or"; + /** Logical And */ + ConditionBlockTests[ConditionBlockTests["And"] = 8] = "And"; +})(ConditionBlockTests || (ConditionBlockTests = {})); +/** + * Block used to evaluate a condition and return a true or false value + */ +class ConditionBlock extends NodeGeometryBlock { + /** + * Create a new ConditionBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets the test used by the block + */ + this.test = ConditionBlockTests.Equal; + /** + * Gets or sets the epsilon value used for comparison + */ + this.epsilon = 0; + this.registerInput("left", NodeGeometryBlockConnectionPointTypes.Float); + this.registerInput("right", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("ifTrue", NodeGeometryBlockConnectionPointTypes.AutoDetect, true, 1); + this.registerInput("ifFalse", NodeGeometryBlockConnectionPointTypes.AutoDetect, true, 0); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[2]; + this._outputs[0]._defaultConnectionPointType = NodeGeometryBlockConnectionPointTypes.Float; + this._inputs[0].acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); + this._inputs[1].acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); + this._linkConnectionTypes(2, 3); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ConditionBlock"; + } + /** + * Gets the left input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the ifTrue input component + */ + get ifTrue() { + return this._inputs[2]; + } + /** + * Gets the ifFalse input component + */ + get ifFalse() { + return this._inputs[3]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + autoConfigure(nodeGeometry) { + if (!this.ifTrue.isConnected) { + const minInput = nodeGeometry.getBlockByPredicate((b) => b.isInput && b.value === 1 && b.name === "True") || + new GeometryInputBlock("True"); + minInput.value = 1; + minInput.output.connectTo(this.ifTrue); + } + if (!this.ifFalse.isConnected) { + const maxInput = nodeGeometry.getBlockByPredicate((b) => b.isInput && b.value === 0 && b.name === "False") || + new GeometryInputBlock("False"); + maxInput.value = 0; + maxInput.output.connectTo(this.ifFalse); + } + } + _buildBlock() { + if (!this.left.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (state) => { + const left = this.left.getConnectedValue(state); + const right = this.right.getConnectedValue(state); + let condition = false; + switch (this.test) { + case ConditionBlockTests.Equal: + condition = WithinEpsilon(left, right, this.epsilon); + break; + case ConditionBlockTests.NotEqual: + condition = !WithinEpsilon(left, right, this.epsilon); + break; + case ConditionBlockTests.LessThan: + condition = left < right + this.epsilon; + break; + case ConditionBlockTests.GreaterThan: + condition = left > right - this.epsilon; + break; + case ConditionBlockTests.LessOrEqual: + condition = left <= right + this.epsilon; + break; + case ConditionBlockTests.GreaterOrEqual: + condition = left >= right - this.epsilon; + break; + case ConditionBlockTests.Xor: + condition = (!!left && !right) || (!left && !!right); + break; + case ConditionBlockTests.Or: + condition = !!left || !!right; + break; + case ConditionBlockTests.And: + condition = !!left && !!right; + break; + } + return condition; + }; + this.output._storedFunction = (state) => { + if (func(state)) { + return this.ifTrue.getConnectedValue(state); + } + return this.ifFalse.getConnectedValue(state); + }; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${ConditionBlockTests[this.test]};\n`; + codeString += `${this._codeVariableName}.epsilon = ${this.epsilon};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.test = this.test; + serializationObject.epsilon = this.epsilon; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.test = serializationObject.test; + if (serializationObject.epsilon !== undefined) { + this.epsilon = serializationObject.epsilon; + } + } +} +__decorate([ + editableInPropertyPage("Test", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "Equal", value: ConditionBlockTests.Equal }, + { label: "NotEqual", value: ConditionBlockTests.NotEqual }, + { label: "LessThan", value: ConditionBlockTests.LessThan }, + { label: "GreaterThan", value: ConditionBlockTests.GreaterThan }, + { label: "LessOrEqual", value: ConditionBlockTests.LessOrEqual }, + { label: "GreaterOrEqual", value: ConditionBlockTests.GreaterOrEqual }, + { label: "Xor", value: ConditionBlockTests.Xor }, + { label: "Or", value: ConditionBlockTests.Or }, + { label: "And", value: ConditionBlockTests.And }, + ], + }) +], ConditionBlock.prototype, "test", void 0); +__decorate([ + editableInPropertyPage("Epsilon", 1 /* PropertyTypeForEdition.Float */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], ConditionBlock.prototype, "epsilon", void 0); +RegisterClass("BABYLON.ConditionBlock", ConditionBlock); + +/** + * Locks supported by the random block + */ +var RandomBlockLocks; +(function (RandomBlockLocks) { + /** None */ + RandomBlockLocks[RandomBlockLocks["None"] = 0] = "None"; + /** LoopID */ + RandomBlockLocks[RandomBlockLocks["LoopID"] = 1] = "LoopID"; + /** InstanceID */ + RandomBlockLocks[RandomBlockLocks["InstanceID"] = 2] = "InstanceID"; + /** Once */ + RandomBlockLocks[RandomBlockLocks["Once"] = 3] = "Once"; +})(RandomBlockLocks || (RandomBlockLocks = {})); +/** + * Block used to get a random number + */ +class RandomBlock extends NodeGeometryBlock { + /** + * Create a new RandomBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._currentLockId = -1; + /** + * Gets or sets a value indicating if that block will lock its value for a specific duration + */ + this.lockMode = RandomBlockLocks.None; + this.registerInput("min", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("max", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "RandomBlock"; + } + /** + * Gets the min input component + */ + get min() { + return this._inputs[0]; + } + /** + * Gets the max input component + */ + get max() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.min.isConnected) { + const minInput = new GeometryInputBlock("Min"); + minInput.value = 0; + minInput.output.connectTo(this.min); + } + if (!this.max.isConnected) { + const maxInput = new GeometryInputBlock("Max"); + maxInput.value = 1; + maxInput.output.connectTo(this.max); + } + } + _buildBlock() { + let func = null; + this._currentLockId = -1; + switch (this.min.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + func = (state) => { + const min = this.min.getConnectedValue(state) || 0; + const max = this.max.getConnectedValue(state) || 0; + return min + Math.random() * (max - min); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + func = (state) => { + const min = this.min.getConnectedValue(state) || Vector2.Zero(); + const max = this.max.getConnectedValue(state) || Vector2.Zero(); + return new Vector2(min.x + Math.random() * (max.x - min.x), min.y + Math.random() * (max.y - min.y)); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + func = (state) => { + const min = this.min.getConnectedValue(state) || Vector3.Zero(); + const max = this.max.getConnectedValue(state) || Vector3.Zero(); + return new Vector3(min.x + Math.random() * (max.x - min.x), min.y + Math.random() * (max.y - min.y), min.z + Math.random() * (max.z - min.z)); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + func = (state) => { + const min = this.min.getConnectedValue(state) || Vector4.Zero(); + const max = this.max.getConnectedValue(state) || Vector4.Zero(); + return new Vector4(min.x + Math.random() * (max.x - min.x), min.y + Math.random() * (max.y - min.y), min.z + Math.random() * (max.z - min.z), min.w + Math.random() * (max.w - min.w)); + }; + break; + } + } + if (this.lockMode === RandomBlockLocks.None || !func) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = (state) => { + let lockId = 0; + switch (this.lockMode) { + case RandomBlockLocks.InstanceID: + lockId = state.getContextualValue(NodeGeometryContextualSources.InstanceID, true) || 0; + break; + case RandomBlockLocks.LoopID: + lockId = state.getContextualValue(NodeGeometryContextualSources.LoopID, true) || 0; + break; + case RandomBlockLocks.Once: + lockId = state.buildId || 0; + break; + } + if (this._currentLockId !== lockId || this.lockMode === RandomBlockLocks.None) { + this._currentLockId = lockId; + this.output._storedValue = func(state); + } + return this.output._storedValue; + }; + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${RandomBlockLocks[this.lockMode]};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.lockMode = this.lockMode; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.lockMode = serializationObject.lockMode; + } +} +__decorate([ + editableInPropertyPage("LockMode", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "None", value: RandomBlockLocks.None }, + { label: "LoopID", value: RandomBlockLocks.LoopID }, + { label: "InstanceID", value: RandomBlockLocks.InstanceID }, + { label: "Once", value: RandomBlockLocks.Once }, + ], + }) +], RandomBlock.prototype, "lockMode", void 0); +RegisterClass("BABYLON.RandomBlock", RandomBlock); + +/** + * Block used to get a noise value + */ +class NoiseBlock extends NodeGeometryBlock { + /** + * Create a new NoiseBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("offset", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("scale", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerInput("octaves", NodeGeometryBlockConnectionPointTypes.Float, true, 2, 0, 16); + this.registerInput("roughness", NodeGeometryBlockConnectionPointTypes.Float, true, 0.5, 0, 1); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NoiseBlock"; + } + /** + * Gets the offset input component + */ + get offset() { + return this._inputs[0]; + } + /** + * Gets the scale input component + */ + get scale() { + return this._inputs[1]; + } + /** + * Gets the octaves input component + */ + get octaves() { + return this._inputs[2]; + } + /** + * Gets the roughtness input component + */ + get roughness() { + return this._inputs[3]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _negateIf(value, condition) { + return condition !== 0 ? -value : value; + } + _noiseGrad(hash, x, y, z) { + const h = hash & 15; + const u = h < 8 ? x : y; + const vt = h === 12 || h == 14 ? x : z; + const v = h < 4 ? y : vt; + return this._negateIf(u, h & u) + this._negateIf(v, h & 2); + } + _fade(t) { + return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); + } + _hashBitRotate(x, k) { + return (x << k) | (x >> (32 - k)); + } + _hash(kx, ky, kz) { + let a, b, c; + a = b = c = 0xdeadbeef + (3 << 2) + 13; + c += kz; + b += ky; + a += kx; + c ^= b; + c -= this._hashBitRotate(b, 14); + a ^= c; + a -= this._hashBitRotate(c, 11); + b ^= a; + b -= this._hashBitRotate(a, 25); + c ^= b; + c -= this._hashBitRotate(b, 16); + a ^= c; + a -= this._hashBitRotate(c, 4); + b ^= a; + b -= this._hashBitRotate(a, 14); + c ^= b; + c -= this._hashBitRotate(b, 24); + return c; + } + _mix(v0, v1, v2, v3, v4, v5, v6, v7, x, y, z) { + const x1 = 1.0 - x; + const y1 = 1.0 - y; + const z1 = 1.0 - z; + return z1 * (y1 * (v0 * x1 + v1 * x) + y * (v2 * x1 + v3 * x)) + z * (y1 * (v4 * x1 + v5 * x) + y * (v6 * x1 + v7 * x)); + } + _perlinNoise(position) { + const X = (position.x | 0) - (position.x < 0 ? 1 : 0); + const Y = (position.y | 0) - (position.y < 0 ? 1 : 0); + const Z = (position.z | 0) - (position.z < 0 ? 1 : 0); + const fx = position.x - X; + const fy = position.y - Y; + const fz = position.z - Z; + const u = this._fade(fx); + const v = this._fade(fy); + const w = this._fade(fz); + return this._mix(this._noiseGrad(this._hash(X, Y, Z), fx, fy, fz), this._noiseGrad(this._hash(X + 1, Y, Z), fx - 1, fy, fz), this._noiseGrad(this._hash(X, Y + 1, Z), fx, fy - 1, fz), this._noiseGrad(this._hash(X + 1, Y + 1, Z), fx - 1, fy - 1, fz), this._noiseGrad(this._hash(X, Y, Z + 1), fx, fy, fz - 1), this._noiseGrad(this._hash(X + 1, Y, Z + 1), fx - 1, fy, fz - 1), this._noiseGrad(this._hash(X, Y + 1, Z + 1), fx, fy - 1, fz - 1), this._noiseGrad(this._hash(X + 1, Y + 1, Z + 1), fx - 1, fy - 1, fz - 1), u, v, w); + } + _perlinSigned(position) { + return this._perlinNoise(position) * 0.982; + } + _perlin(position) { + return this._perlinSigned(position) / 2.0 + 0.5; + } + /** + * Gets a perlin noise value + * @param octaves number of octaves + * @param roughness roughness + * @param _position position vector + * @param offset offset vector + * @param scale scale value + * @returns a value between 0 and 1 + * @see Based on https://github.com/blender/blender/blob/main/source/blender/blenlib/intern/noise.cc#L533 + */ + noise(octaves, roughness, _position, offset, scale) { + const position = new Vector3(_position.x * scale + offset.x, _position.y * scale + offset.y, _position.z * scale + offset.z); + let fscale = 1.0; + let amp = 1.0; + let maxamp = 0.0; + let sum = 0.0; + octaves = Clamp(octaves, 0, 15.0); + const step = octaves | 0; + for (let i = 0; i <= step; i++) { + const t = this._perlin(position.scale(fscale)); + sum += t * amp; + maxamp += amp; + amp *= Clamp(roughness, 0.0, 1.0); + fscale *= 2.0; + } + const rmd = octaves - Math.floor(octaves); + if (rmd == 0.0) { + return sum / maxamp; + } + const t = this._perlin(position.scale(fscale)); + let sum2 = sum + t * amp; + sum /= maxamp; + sum2 /= maxamp + amp; + return (1.0 - rmd) * sum + rmd * sum2; + } + _buildBlock() { + this.output._storedFunction = (state) => { + const position = state.getContextualValue(NodeGeometryContextualSources.Positions); + const octaves = this.octaves.getConnectedValue(state); + const roughness = this.roughness.getConnectedValue(state); + const offset = this.offset.getConnectedValue(state); + const scale = this.scale.getConnectedValue(state); + return this.noise(octaves, roughness, position, offset, scale); + }; + } +} +RegisterClass("BABYLON.NoiseBlock", NoiseBlock); + +/** + * Block used to merge several geometries + */ +class MergeGeometryBlock extends NodeGeometryBlock { + /** + * Create a new MergeGeometryBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + this.registerInput("geometry0", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("geometry1", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry2", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry3", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry4", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MergeGeometryBlock"; + } + /** + * Gets the geometry0 input component + */ + get geometry0() { + return this._inputs[0]; + } + /** + * Gets the geometry1 input component + */ + get geometry1() { + return this._inputs[1]; + } + /** + * Gets the geometry2 input component + */ + get geometry2() { + return this._inputs[2]; + } + /** + * Gets the geometry3 input component + */ + get geometry3() { + return this._inputs[3]; + } + /** + * Gets the geometry4 input component + */ + get geometry4() { + return this._inputs[4]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + const vertexDataSource = []; + if (this.geometry0.isConnected) { + const data = this.geometry0.getConnectedValue(state); + if (data) { + vertexDataSource.push(data); + } + } + if (this.geometry1.isConnected) { + const data = this.geometry1.getConnectedValue(state); + if (data) { + vertexDataSource.push(data); + } + } + if (this.geometry2.isConnected) { + const data = this.geometry2.getConnectedValue(state); + if (data) { + vertexDataSource.push(data); + } + } + if (this.geometry3.isConnected) { + const data = this.geometry3.getConnectedValue(state); + if (data) { + vertexDataSource.push(data); + } + } + if (this.geometry4.isConnected) { + const data = this.geometry4.getConnectedValue(state); + if (data) { + vertexDataSource.push(data); + } + } + if (vertexDataSource.length === 0) { + return null; + } + let vertexData = vertexDataSource[0].clone(); // Preserve source data + const additionalVertexData = vertexDataSource.slice(1); + if (additionalVertexData.length && vertexData) { + vertexData = vertexData.merge(additionalVertexData, true, false, true, true); + } + return vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], MergeGeometryBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.MergeGeometryBlock", MergeGeometryBlock); + +/** + * Block used to randomly pick a geometry from a collection + */ +class GeometryCollectionBlock extends NodeGeometryBlock { + /** + * Create a new GeometryCollectionBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("geometry0", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry1", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry2", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry3", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry4", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry5", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry6", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry7", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry8", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("geometry9", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryCollectionBlock"; + } + /** + * Gets the geometry0 input component + */ + get geometry0() { + return this._inputs[0]; + } + /** + * Gets the geometry1 input component + */ + get geometry1() { + return this._inputs[1]; + } + /** + * Gets the geometry2 input component + */ + get geometry2() { + return this._inputs[2]; + } + /** + * Gets the geometry3 input component + */ + get geometry3() { + return this._inputs[3]; + } + /** + * Gets the geometry4 input component + */ + get geometry4() { + return this._inputs[4]; + } + /** + * Gets the geometry5 input component + */ + get geometry5() { + return this._inputs[5]; + } + /** + * Gets the geometry6 input component + */ + get geometry6() { + return this._inputs[6]; + } + /** + * Gets the geometry7 input component + */ + get geometry7() { + return this._inputs[7]; + } + /** + * Gets the geometry8 input component + */ + get geometry8() { + return this._inputs[8]; + } + /** + * Gets the geometry9 input component + */ + get geometry9() { + return this._inputs[9]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _storeGeometry(input, state, index, availables) { + if (input.isConnected) { + const vertexData = input.getConnectedValue(state); + if (!vertexData) { + return; + } + vertexData.metadata = vertexData.metadata || {}; + vertexData.metadata.collectionId = index; + availables.push(vertexData); + } + } + _buildBlock(state) { + const func = (state) => { + const availables = []; + this._storeGeometry(this.geometry0, state, 0, availables); + this._storeGeometry(this.geometry1, state, 1, availables); + this._storeGeometry(this.geometry2, state, 2, availables); + this._storeGeometry(this.geometry3, state, 3, availables); + this._storeGeometry(this.geometry4, state, 4, availables); + this._storeGeometry(this.geometry5, state, 5, availables); + this._storeGeometry(this.geometry6, state, 6, availables); + this._storeGeometry(this.geometry7, state, 7, availables); + this._storeGeometry(this.geometry8, state, 8, availables); + this._storeGeometry(this.geometry9, state, 9, availables); + if (!availables.length) { + return null; + } + return availables[Math.round(Math.random() * (availables.length - 1))]; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], GeometryCollectionBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.GeometryCollectionBlock", GeometryCollectionBlock); + +/** + * Block used to clean a geometry + */ +class CleanGeometryBlock extends NodeGeometryBlock { + /** + * Creates a new CleanGeometryBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "CleanGeometryBlock"; + } + /** + * Gets the geometry component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + if (!this.geometry.isConnected) { + return null; + } + const vertexData = this.geometry.getConnectedValue(state).clone(); + if (!vertexData.positions || !vertexData.indices || !vertexData.normals) { + return vertexData; + } + const indices = vertexData.indices; + const positions = vertexData.positions; + FixFlippedFaces(positions, indices); + return vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + return super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], CleanGeometryBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.CleanGeometryBlock", CleanGeometryBlock); + +/** + * Block used as a pass through + */ +class GeometryElbowBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryElbowBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the time spent to build this block (in ms) + */ + get buildExecutionTime() { + return -1; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryElbowBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const input = this._inputs[0]; + output._storedFunction = (state) => { + return input.getConnectedValue(state); + }; + } +} +RegisterClass("BABYLON.GeometryElbowBlock", GeometryElbowBlock); + +/** + * Block used to recompute normals for a geometry + */ +class ComputeNormalsBlock extends NodeGeometryBlock { + /** + * Creates a new ComputeNormalsBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ComputeNormalsBlock"; + } + /** + * Gets the geometry component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + this.output._storedFunction = (state) => { + if (!this.geometry.isConnected) { + return null; + } + const vertexData = this.geometry.getConnectedValue(state); + if (!vertexData) { + return null; + } + if (!vertexData.normals) { + vertexData.normals = []; + } + VertexData.ComputeNormals(vertexData.positions, vertexData.indices, vertexData.normals); + return vertexData; + }; + } +} +RegisterClass("BABYLON.ComputeNormalsBlock", ComputeNormalsBlock); + +/** + * Block used to create a Vector2/3/4 out of individual or partial inputs + */ +class VectorConverterBlock extends NodeGeometryBlock { + /** + * Create a new VectorConverterBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("xyzw ", NodeGeometryBlockConnectionPointTypes.Vector4, true); + this.registerInput("xyz ", NodeGeometryBlockConnectionPointTypes.Vector3, true); + this.registerInput("xy ", NodeGeometryBlockConnectionPointTypes.Vector2, true); + this.registerInput("zw ", NodeGeometryBlockConnectionPointTypes.Vector2, true); + this.registerInput("x ", NodeGeometryBlockConnectionPointTypes.Float, true); + this.registerInput("y ", NodeGeometryBlockConnectionPointTypes.Float, true); + this.registerInput("z ", NodeGeometryBlockConnectionPointTypes.Float, true); + this.registerInput("w ", NodeGeometryBlockConnectionPointTypes.Float, true); + this.registerOutput("xyzw", NodeGeometryBlockConnectionPointTypes.Vector4); + this.registerOutput("xyz", NodeGeometryBlockConnectionPointTypes.Vector3); + this.registerOutput("xy", NodeGeometryBlockConnectionPointTypes.Vector2); + this.registerOutput("zw", NodeGeometryBlockConnectionPointTypes.Vector2); + this.registerOutput("x", NodeGeometryBlockConnectionPointTypes.Float); + this.registerOutput("y", NodeGeometryBlockConnectionPointTypes.Float); + this.registerOutput("z", NodeGeometryBlockConnectionPointTypes.Float); + this.registerOutput("w", NodeGeometryBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "VectorConverterBlock"; + } + /** + * Gets the xyzw component (input) + */ + get xyzwIn() { + return this._inputs[0]; + } + /** + * Gets the xyz component (input) + */ + get xyzIn() { + return this._inputs[1]; + } + /** + * Gets the xy component (input) + */ + get xyIn() { + return this._inputs[2]; + } + /** + * Gets the zw component (input) + */ + get zwIn() { + return this._inputs[3]; + } + /** + * Gets the x component (input) + */ + get xIn() { + return this._inputs[4]; + } + /** + * Gets the y component (input) + */ + get yIn() { + return this._inputs[5]; + } + /** + * Gets the z component (input) + */ + get zIn() { + return this._inputs[6]; + } + /** + * Gets the w component (input) + */ + get wIn() { + return this._inputs[7]; + } + /** + * Gets the xyzw component (output) + */ + get xyzwOut() { + return this._outputs[0]; + } + /** + * Gets the xyz component (output) + */ + get xyzOut() { + return this._outputs[1]; + } + /** + * Gets the xy component (output) + */ + get xyOut() { + return this._outputs[2]; + } + /** + * Gets the zw component (output) + */ + get zwOut() { + return this._outputs[3]; + } + /** + * Gets the x component (output) + */ + get xOut() { + return this._outputs[4]; + } + /** + * Gets the y component (output) + */ + get yOut() { + return this._outputs[5]; + } + /** + * Gets the z component (output) + */ + get zOut() { + return this._outputs[6]; + } + /** + * Gets the w component (output) + */ + get wOut() { + return this._outputs[7]; + } + _inputRename(name) { + if (name === "xyzw ") { + return "xyzwIn"; + } + if (name === "xyz ") { + return "xyzIn"; + } + if (name === "xy ") { + return "xyIn"; + } + if (name === "zw ") { + return "zwIn"; + } + if (name === "x ") { + return "xIn"; + } + if (name === "y ") { + return "yIn"; + } + if (name === "z ") { + return "zIn"; + } + if (name === "w ") { + return "wIn"; + } + return name; + } + _outputRename(name) { + switch (name) { + case "x": + return "xOut"; + case "y": + return "yOut"; + case "z": + return "zOut"; + case "w": + return "wOut"; + case "xy": + return "xyOut"; + case "zw": + return "zwOut"; + case "xyz": + return "xyzOut"; + case "xyzw": + return "xyzwOut"; + default: + return name; + } + } + _buildBlock(state) { + super._buildBlock(state); + const xInput = this.xIn; + const yInput = this.yIn; + const zInput = this.zIn; + const wInput = this.wIn; + const xyInput = this.xyIn; + const zwInput = this.zwIn; + const xyzInput = this.xyzIn; + const xyzwInput = this.xyzwIn; + const xyzwOutput = this.xyzwOut; + const xyzOutput = this.xyzOut; + const xyOutput = this.xyOut; + const zwOutput = this.zwOut; + const xOutput = this.xOut; + const yOutput = this.yOut; + const zOutput = this.zOut; + const wOutput = this.wOut; + const getData = (state) => { + if (xyzwInput.isConnected) { + return xyzwInput.getConnectedValue(state); + } + let x = 0; + let y = 0; + let z = 0; + let w = 0; + if (xInput.isConnected) { + x = xInput.getConnectedValue(state); + } + if (yInput.isConnected) { + y = yInput.getConnectedValue(state); + } + if (zInput.isConnected) { + z = zInput.getConnectedValue(state); + } + if (wInput.isConnected) { + w = wInput.getConnectedValue(state); + } + if (xyInput.isConnected) { + const temp = xyInput.getConnectedValue(state); + if (temp) { + x = temp.x; + y = temp.y; + } + } + if (zwInput.isConnected) { + const temp = zwInput.getConnectedValue(state); + if (temp) { + z = temp.x; + w = temp.y; + } + } + if (xyzInput.isConnected) { + const temp = xyzInput.getConnectedValue(state); + if (temp) { + x = temp.x; + y = temp.y; + z = temp.z; + } + } + return new Vector4(x, y, z, w); + }; + xyzwOutput._storedFunction = (state) => getData(state); + xyzOutput._storedFunction = (state) => { + const data = getData(state); + return new Vector3(data.x, data.y, data.z); + }; + xyOutput._storedFunction = (state) => { + const data = getData(state); + return new Vector2(data.x, data.y); + }; + zwOutput._storedFunction = (state) => { + const data = getData(state); + return new Vector2(data.z, data.w); + }; + xOutput._storedFunction = (state) => getData(state).x; + yOutput._storedFunction = (state) => getData(state).y; + zOutput._storedFunction = (state) => getData(state).z; + wOutput._storedFunction = (state) => getData(state).w; + } +} +RegisterClass("BABYLON.VectorConverterBlock", VectorConverterBlock); + +/** + * Block used to normalize vectors + */ +class NormalizeVectorBlock extends NodeGeometryBlock { + /** + * Creates a new NormalizeVectorBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "NormalizeVectorBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.output._storedFunction = null; + if (!this.input.isConnected) { + this.output._storedValue = null; + return; + } + this.output._storedFunction = (state) => this.input.getConnectedValue(state).normalize(); + } +} +RegisterClass("BABYLON.NormalizeVectorBlock", NormalizeVectorBlock); + +/** + * Block used to affect a material ID to a geometry + */ +class SetMaterialIDBlock extends NodeGeometryBlock { + /** + * Create a new SetMaterialIDBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("id", NodeGeometryBlockConnectionPointTypes.Int, true, 0); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + this.id.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SetMaterialIDBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the id input component + */ + get id() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + if (!this.geometry.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (state) => { + const vertexData = this.geometry.getConnectedValue(state); + if (!vertexData || !vertexData.indices || !vertexData.positions) { + return vertexData; + } + const materialInfo = new VertexDataMaterialInfo(); + materialInfo.materialIndex = this.id.getConnectedValue(state) | 0; + materialInfo.indexStart = 0; + materialInfo.indexCount = vertexData.indices.length; + materialInfo.verticesStart = 0; + materialInfo.verticesCount = vertexData.positions.length / 3; + vertexData.materialInfos = [materialInfo]; + return vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], SetMaterialIDBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.SetMaterialIDBlock", SetMaterialIDBlock); + +/** + * Block used to apply Lattice on geometry + */ +class LatticeBlock extends NodeGeometryBlock { + /** + * Create a new LatticeBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._indexVector3 = new Vector3(); + this._currentControl = new Vector3(); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + /** + * Resolution on x axis + */ + this.resolutionX = 3; + /** + * Resolution on y axis + */ + this.resolutionY = 3; + /** + * Resolution on z axis + */ + this.resolutionZ = 3; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("controls", NodeGeometryBlockConnectionPointTypes.Vector3); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._currentIndexX + this.resolutionX * (this._currentIndexY + this.resolutionY * this._currentIndexZ); + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this.getExecutionIndex(); + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "LatticeBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the controls input component + */ + get controls() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the value associated with a contextual positions + * In this case it will be the current position in the lattice + * @returns the current position in the lattice + */ + getOverridePositionsContextualValue() { + return this._indexVector3; + } + /** + * Gets the value associated with a contextual normals + * In this case it will be the current control point being processed + * @returns the current control point being processed + */ + getOverrideNormalsContextualValue() { + return this._currentControl; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + this._vertexData = this.geometry.getConnectedValue(state); + if (this._vertexData) { + this._vertexData = this._vertexData.clone(); // Preserve source data + } + if (!this._vertexData || !this._vertexData.positions) { + state.restoreExecutionContext(); + this.output._storedValue = null; + return; + } + const positions = this._vertexData.positions; + const boundingInfo = extractMinAndMax(positions, 0, positions.length / 3); + // Building the lattice + const size = boundingInfo.maximum.subtract(boundingInfo.minimum); + this._lattice = new Lattice({ + resolutionX: this.resolutionX, + resolutionY: this.resolutionY, + resolutionZ: this.resolutionZ, + size: size, + position: boundingInfo.minimum.add(size.scale(0.5)), + }); + for (this._currentIndexX = 0; this._currentIndexX < this.resolutionX; this._currentIndexX++) { + for (this._currentIndexY = 0; this._currentIndexY < this.resolutionY; this._currentIndexY++) { + for (this._currentIndexZ = 0; this._currentIndexZ < this.resolutionZ; this._currentIndexZ++) { + this._indexVector3.set(this._currentIndexX, this._currentIndexY, this._currentIndexZ); + const latticeControl = this._lattice.data[this._currentIndexX][this._currentIndexY][this._currentIndexZ]; + this._currentControl.copyFrom(latticeControl); + const tempVector3 = this.controls.getConnectedValue(state); + if (tempVector3) { + latticeControl.set(tempVector3.x, tempVector3.y, tempVector3.z); + } + } + } + } + // Apply lattice + this._lattice.deform(positions); + // Storage + state.restoreExecutionContext(); + return this._vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + codeString += `${this._codeVariableName}.resolutionX = ${this.resolutionX};\n`; + codeString += `${this._codeVariableName}.resolutionY = ${this.resolutionY};\n`; + codeString += `${this._codeVariableName}.resolutionZ = ${this.resolutionZ};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + serializationObject.resolutionX = this.resolutionX; + serializationObject.resolutionY = this.resolutionY; + serializationObject.resolutionZ = this.resolutionZ; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + this.resolutionX = serializationObject.resolutionX; + this.resolutionY = serializationObject.resolutionY; + this.resolutionZ = serializationObject.resolutionZ; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], LatticeBlock.prototype, "evaluateContext", void 0); +__decorate([ + editableInPropertyPage("resolutionX", 2 /* PropertyTypeForEdition.Int */, "ADVANCED", { embedded: true, notifiers: { rebuild: true }, min: 1, max: 10 }) +], LatticeBlock.prototype, "resolutionX", void 0); +__decorate([ + editableInPropertyPage("resolutionY", 2 /* PropertyTypeForEdition.Int */, "ADVANCED", { embedded: true, notifiers: { rebuild: true }, min: 1, max: 10 }) +], LatticeBlock.prototype, "resolutionY", void 0); +__decorate([ + editableInPropertyPage("resolutionZ", 2 /* PropertyTypeForEdition.Int */, "ADVANCED", { embedded: true, notifiers: { rebuild: true }, min: 1, max: 10 }) +], LatticeBlock.prototype, "resolutionZ", void 0); +RegisterClass("BABYLON.LatticeBlock", LatticeBlock); + +/** + * Operations supported by the Trigonometry block + */ +var GeometryTrigonometryBlockOperations; +(function (GeometryTrigonometryBlockOperations) { + /** Cos */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Cos"] = 0] = "Cos"; + /** Sin */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Sin"] = 1] = "Sin"; + /** Abs */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Abs"] = 2] = "Abs"; + /** Exp */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Exp"] = 3] = "Exp"; + /** Round */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Round"] = 4] = "Round"; + /** Floor */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Floor"] = 5] = "Floor"; + /** Ceiling */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Ceiling"] = 6] = "Ceiling"; + /** Square root */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Sqrt"] = 7] = "Sqrt"; + /** Log */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Log"] = 8] = "Log"; + /** Tangent */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Tan"] = 9] = "Tan"; + /** Arc tangent */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["ArcTan"] = 10] = "ArcTan"; + /** Arc cosinus */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["ArcCos"] = 11] = "ArcCos"; + /** Arc sinus */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["ArcSin"] = 12] = "ArcSin"; + /** Sign */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Sign"] = 13] = "Sign"; + /** Negate */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Negate"] = 14] = "Negate"; + /** OneMinus */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["OneMinus"] = 15] = "OneMinus"; + /** Reciprocal */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Reciprocal"] = 16] = "Reciprocal"; + /** ToDegrees */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["ToDegrees"] = 17] = "ToDegrees"; + /** ToRadians */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["ToRadians"] = 18] = "ToRadians"; + /** Fract */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Fract"] = 19] = "Fract"; + /** Exp2 */ + GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Exp2"] = 20] = "Exp2"; +})(GeometryTrigonometryBlockOperations || (GeometryTrigonometryBlockOperations = {})); +/** + * Block used to apply trigonometry operation to floats + */ +class GeometryTrigonometryBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryTrigonometryBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets the operation applied by the block + */ + this.operation = GeometryTrigonometryBlockOperations.Cos; + this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryTrigonometryBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + let func = null; + switch (this.operation) { + case GeometryTrigonometryBlockOperations.Cos: { + func = (value) => Math.cos(value); + break; + } + case GeometryTrigonometryBlockOperations.Sin: { + func = (value) => Math.sin(value); + break; + } + case GeometryTrigonometryBlockOperations.Abs: { + func = (value) => Math.abs(value); + break; + } + case GeometryTrigonometryBlockOperations.Exp: { + func = (value) => Math.exp(value); + break; + } + case GeometryTrigonometryBlockOperations.Exp2: { + func = (value) => Math.pow(2, value); + break; + } + case GeometryTrigonometryBlockOperations.Round: { + func = (value) => Math.round(value); + break; + } + case GeometryTrigonometryBlockOperations.Floor: { + func = (value) => Math.floor(value); + break; + } + case GeometryTrigonometryBlockOperations.Ceiling: { + func = (value) => Math.ceil(value); + break; + } + case GeometryTrigonometryBlockOperations.Sqrt: { + func = (value) => Math.sqrt(value); + break; + } + case GeometryTrigonometryBlockOperations.Log: { + func = (value) => Math.log(value); + break; + } + case GeometryTrigonometryBlockOperations.Tan: { + func = (value) => Math.tan(value); + break; + } + case GeometryTrigonometryBlockOperations.ArcTan: { + func = (value) => Math.atan(value); + break; + } + case GeometryTrigonometryBlockOperations.ArcCos: { + func = (value) => Math.acos(value); + break; + } + case GeometryTrigonometryBlockOperations.ArcSin: { + func = (value) => Math.asin(value); + break; + } + case GeometryTrigonometryBlockOperations.Sign: { + func = (value) => Math.sign(value); + break; + } + case GeometryTrigonometryBlockOperations.Negate: { + func = (value) => -value; + break; + } + case GeometryTrigonometryBlockOperations.OneMinus: { + func = (value) => 1 - value; + break; + } + case GeometryTrigonometryBlockOperations.Reciprocal: { + func = (value) => 1 / value; + break; + } + case GeometryTrigonometryBlockOperations.ToRadians: { + func = (value) => (value * Math.PI) / 180; + break; + } + case GeometryTrigonometryBlockOperations.ToDegrees: { + func = (value) => (value * 180) / Math.PI; + break; + } + case GeometryTrigonometryBlockOperations.Fract: { + func = (value) => { + if (value >= 0) { + return value - Math.floor(value); + } + else { + return value - Math.ceil(value); + } + }; + break; + } + } + if (!func) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + switch (this.input.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + this.output._storedFunction = (state) => { + const source = this.input.getConnectedValue(state); + return func(source); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + this.output._storedFunction = (state) => { + const source = this.input.getConnectedValue(state); + return new Vector2(func(source.x), func(source.y)); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + this.output._storedFunction = (state) => { + const source = this.input.getConnectedValue(state); + return new Vector3(func(source.x), func(source.y), func(source.z)); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + this.output._storedFunction = (state) => { + const source = this.input.getConnectedValue(state); + return new Vector4(func(source.x), func(source.y), func(source.z), func(source.w)); + }; + break; + } + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.operation = this.operation; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.operation = serializationObject.operation; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + + `${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${GeometryTrigonometryBlockOperations[this.operation]};\n`; + return codeString; + } +} +__decorate([ + editableInPropertyPage("Operation", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + embedded: true, + notifiers: { rebuild: true }, + options: [ + { label: "Cos", value: GeometryTrigonometryBlockOperations.Cos }, + { label: "Sin", value: GeometryTrigonometryBlockOperations.Sin }, + { label: "Abs", value: GeometryTrigonometryBlockOperations.Abs }, + { label: "Exp", value: GeometryTrigonometryBlockOperations.Exp }, + { label: "Exp2", value: GeometryTrigonometryBlockOperations.Exp2 }, + { label: "Round", value: GeometryTrigonometryBlockOperations.Round }, + { label: "Floor", value: GeometryTrigonometryBlockOperations.Floor }, + { label: "Ceiling", value: GeometryTrigonometryBlockOperations.Ceiling }, + { label: "Sqrt", value: GeometryTrigonometryBlockOperations.Sqrt }, + { label: "Log", value: GeometryTrigonometryBlockOperations.Log }, + { label: "Tan", value: GeometryTrigonometryBlockOperations.Tan }, + { label: "ArcTan", value: GeometryTrigonometryBlockOperations.ArcTan }, + { label: "ArcCos", value: GeometryTrigonometryBlockOperations.ArcCos }, + { label: "ArcSin", value: GeometryTrigonometryBlockOperations.ArcSin }, + { label: "Sign", value: GeometryTrigonometryBlockOperations.Sign }, + { label: "Negate", value: GeometryTrigonometryBlockOperations.Negate }, + { label: "OneMinus", value: GeometryTrigonometryBlockOperations.OneMinus }, + { label: "Reciprocal", value: GeometryTrigonometryBlockOperations.Reciprocal }, + { label: "ToDegrees", value: GeometryTrigonometryBlockOperations.ToDegrees }, + { label: "ToRadians", value: GeometryTrigonometryBlockOperations.ToRadians }, + { label: "Fract", value: GeometryTrigonometryBlockOperations.Fract }, + ], + }) +], GeometryTrigonometryBlock.prototype, "operation", void 0); +RegisterClass("BABYLON.GeometryTrigonometryBlock", GeometryTrigonometryBlock); + +/** + * Block used to apply a transform to a vector / geometry + */ +class GeometryTransformBlock extends NodeGeometryBlock { + /** + * Create a new GeometryTransformBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._rotationMatrix = new Matrix(); + this._scalingMatrix = new Matrix(); + this._translationMatrix = new Matrix(); + this._scalingRotationMatrix = new Matrix(); + this._pivotMatrix = new Matrix(); + this._backPivotMatrix = new Matrix(); + this._transformMatrix = new Matrix(); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true); + this.registerInput("translation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.One()); + this.registerInput("pivot", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryTransformBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the matrix input component + */ + get matrix() { + return this._inputs[1]; + } + /** + * Gets the translation input component + */ + get translation() { + return this._inputs[2]; + } + /** + * Gets the rotation input component + */ + get rotation() { + return this._inputs[3]; + } + /** + * Gets the scaling input component + */ + get scaling() { + return this._inputs[4]; + } + /** + * Gets the pivot input component + */ + get pivot() { + return this._inputs[5]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + if (!this.value.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (state) => { + const value = this.value.getConnectedValue(state); + if (!value) { + return null; + } + let matrix; + if (this.matrix.isConnected) { + matrix = this.matrix.getConnectedValue(state); + } + else { + const scaling = this.scaling.getConnectedValue(state) || Vector3.OneReadOnly; + const rotation = this.rotation.getConnectedValue(state) || Vector3.ZeroReadOnly; + const translation = this.translation.getConnectedValue(state) || Vector3.ZeroReadOnly; + const pivot = this.pivot.getConnectedValue(state) || Vector3.ZeroReadOnly; + // Transform + Matrix.TranslationToRef(-pivot.x, -pivot.y, -pivot.z, this._pivotMatrix); + Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, this._scalingMatrix); + Matrix.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, this._rotationMatrix); + Matrix.TranslationToRef(translation.x + pivot.x, translation.y + pivot.y, translation.z + pivot.z, this._translationMatrix); + this._pivotMatrix.multiplyToRef(this._scalingMatrix, this._backPivotMatrix); + this._backPivotMatrix.multiplyToRef(this._rotationMatrix, this._scalingRotationMatrix); + this._scalingRotationMatrix.multiplyToRef(this._translationMatrix, this._transformMatrix); + matrix = this._transformMatrix; + } + switch (this.value.type) { + case NodeGeometryBlockConnectionPointTypes.Geometry: { + const geometry = value.clone(); + geometry.transform(matrix); + return geometry; + } + case NodeGeometryBlockConnectionPointTypes.Vector2: + return Vector2.Transform(value, matrix); + case NodeGeometryBlockConnectionPointTypes.Vector3: + return Vector3.TransformCoordinates(value, matrix); + case NodeGeometryBlockConnectionPointTypes.Vector4: + return Vector4.TransformCoordinates(value, matrix); + } + return null; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], GeometryTransformBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.GeometryTransformBlock", GeometryTransformBlock); + +/** + * Block used to get a rotation matrix on X Axis + */ +class RotationXBlock extends NodeGeometryBlock { + /** + * Create a new RotationXBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "RotationXBlock"; + } + /** + * Gets the angle input component + */ + get angle() { + return this._inputs[0]; + } + /** + * Gets the matrix output component + */ + get matrix() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.matrix._storedFunction = (state) => { + return Matrix.RotationX(this.angle.getConnectedValue(state)); + }; + } +} +RegisterClass("BABYLON.RotationXBlock", RotationXBlock); + +/** + * Block used to get a rotation matrix on Y Axis + */ +class RotationYBlock extends NodeGeometryBlock { + /** + * Create a new RotationYBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "RotationYBlock"; + } + /** + * Gets the angle input component + */ + get angle() { + return this._inputs[0]; + } + /** + * Gets the matrix output component + */ + get matrix() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.matrix._storedFunction = (state) => { + return Matrix.RotationY(this.angle.getConnectedValue(state)); + }; + } +} +RegisterClass("BABYLON.RotationYBlock", RotationYBlock); + +/** + * Block used to get a rotation matrix on Z Axis + */ +class RotationZBlock extends NodeGeometryBlock { + /** + * Create a new RotationZBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "RotationZBlock"; + } + /** + * Gets the angle input component + */ + get angle() { + return this._inputs[0]; + } + /** + * Gets the matrix output component + */ + get matrix() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.matrix._storedFunction = (state) => { + return Matrix.RotationZ(this.angle.getConnectedValue(state)); + }; + } +} +RegisterClass("BABYLON.RotationZBlock", RotationZBlock); + +/** + * Block used to get a scaling matrix + */ +class ScalingBlock extends NodeGeometryBlock { + /** + * Create a new ScalingBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("scale", NodeGeometryBlockConnectionPointTypes.Vector3, false, Vector3.One()); + this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "ScalingBlock"; + } + /** + * Gets the scale input component + */ + get scale() { + return this._inputs[0]; + } + /** + * Gets the matrix output component + */ + get matrix() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.scale.isConnected) { + const scaleInput = new GeometryInputBlock("Scale"); + scaleInput.value = new Vector3(1, 1, 1); + scaleInput.output.connectTo(this.scale); + } + } + _buildBlock(state) { + super._buildBlock(state); + this.matrix._storedFunction = (state) => { + const value = this.scale.getConnectedValue(state); + return Matrix.Scaling(value.x, value.y, value.z); + }; + } +} +RegisterClass("BABYLON.ScalingBlock", ScalingBlock); + +/** + * Block used to get a align matrix + */ +class AlignBlock extends NodeGeometryBlock { + /** + * Create a new AlignBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("source", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Up()); + this.registerInput("target", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Left()); + this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "AlignBlock"; + } + /** + * Gets the source input component + */ + get source() { + return this._inputs[0]; + } + /** + * Gets the target input component + */ + get target() { + return this._inputs[1]; + } + /** + * Gets the matrix output component + */ + get matrix() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + this.matrix._storedFunction = (state) => { + const source = this.source.getConnectedValue(state).clone(); + const target = this.target.getConnectedValue(state).clone(); + const result = new Matrix(); + source.normalize(); + target.normalize(); + Matrix.RotationAlignToRef(source, target, result, true); + return result; + }; + } +} +RegisterClass("BABYLON.AlignBlock", AlignBlock); + +/** + * Block used to get a translation matrix + */ +class TranslationBlock extends NodeGeometryBlock { + /** + * Create a new TranslationBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("translation", NodeGeometryBlockConnectionPointTypes.Vector3, false, Vector3.Zero()); + this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "TranslationBlock"; + } + /** + * Gets the translation input component + */ + get translation() { + return this._inputs[0]; + } + /** + * Gets the matrix output component + */ + get matrix() { + return this._outputs[0]; + } + autoConfigure() { + if (!this.translation.isConnected) { + const translationInput = new GeometryInputBlock("Translation"); + translationInput.value = new Vector3(0, 0, 0); + translationInput.output.connectTo(this.translation); + } + } + _buildBlock(state) { + super._buildBlock(state); + this.matrix._storedFunction = (state) => { + const value = this.translation.getConnectedValue(state); + return Matrix.Translation(value.x, value.y, value.z); + }; + } +} +RegisterClass("BABYLON.TranslationBlock", TranslationBlock); + +/** + * Block used to instance geometry on every vertex of a geometry + */ +class InstantiateOnVerticesBlock extends NodeGeometryBlock { + /** + * Create a new InstantiateOnVerticesBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._indexTranslation = null; + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + /** + * Gets or sets a boolean indicating if the block should remove duplicated positions + */ + this.removeDuplicatedPositions = true; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("density", NodeGeometryBlockConnectionPointTypes.Float, true, 1, 0, 1); + this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true); + this.registerInput("offset", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.One()); + this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current instance index in the current flow + * @returns the current index + */ + getInstanceIndex() { + return this._currentLoopIndex; + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._indexTranslation ? this._indexTranslation[this._currentIndex] : this._currentIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentLoopIndex; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "InstantiateOnVerticesBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the instance input component + */ + get instance() { + return this._inputs[1]; + } + /** + * Gets the density input component + */ + get density() { + return this._inputs[2]; + } + /** + * Gets the matrix input component + */ + get matrix() { + return this._inputs[3]; + } + /** + * Gets the offset input component + */ + get offset() { + return this._inputs[4]; + } + /** + * Gets the rotation input component + */ + get rotation() { + return this._inputs[5]; + } + /** + * Gets the scaling input component + */ + get scaling() { + return this._inputs[6]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + state.pushInstancingContext(this); + this._vertexData = this.geometry.getConnectedValue(state); + state.pushGeometryContext(this._vertexData); + if (!this._vertexData || !this._vertexData.positions || !this.instance.isConnected) { + state.restoreExecutionContext(); + state.restoreInstancingContext(); + state.restoreGeometryContext(); + this.output._storedValue = null; + return; + } + // Processing + let vertexCount = this._vertexData.positions.length / 3; + const additionalVertexData = []; + const currentPosition = new Vector3(); + const alreadyDone = []; + let vertices = this._vertexData.positions; + this._currentLoopIndex = 0; + if (this.removeDuplicatedPositions) { + this._indexTranslation = {}; + for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { + const x = vertices[this._currentIndex * 3]; + const y = vertices[this._currentIndex * 3 + 1]; + const z = vertices[this._currentIndex * 3 + 2]; + let found = false; + for (let index = 0; index < alreadyDone.length; index += 3) { + if (Math.abs(alreadyDone[index] - x) < Epsilon && Math.abs(alreadyDone[index + 1] - y) < Epsilon && Math.abs(alreadyDone[index + 2] - z) < Epsilon) { + found = true; + break; + } + } + if (found) { + continue; + } + this._indexTranslation[alreadyDone.length / 3] = this._currentIndex; + alreadyDone.push(x, y, z); + } + vertices = alreadyDone; + vertexCount = vertices.length / 3; + } + else { + this._indexTranslation = null; + } + for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { + const instanceGeometry = this.instance.getConnectedValue(state); + if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) { + continue; + } + const density = this.density.getConnectedValue(state); + if (density < 1) { + if (Math.random() > density) { + continue; + } + } + currentPosition.fromArray(vertices, this._currentIndex * 3); + // Clone the instance + const clone = instanceGeometry.clone(); + // Transform + if (this.matrix.isConnected) { + const transform = this.matrix.getConnectedValue(state); + state._instantiateWithPositionAndMatrix(clone, currentPosition, transform, additionalVertexData); + } + else { + const offset = state.adaptInput(this.offset, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.ZeroReadOnly); + const scaling = state.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly); + const rotation = this.rotation.getConnectedValue(state) || Vector3.ZeroReadOnly; + currentPosition.addInPlace(offset); + state._instantiate(clone, currentPosition, rotation, scaling, additionalVertexData); + } + this._currentLoopIndex++; + } + // Restore + state.restoreGeometryContext(); + state.restoreExecutionContext(); + state.restoreInstancingContext(); + // Merge + if (additionalVertexData.length) { + if (additionalVertexData.length === 1) { + this._vertexData = additionalVertexData[0]; + } + else { + // We do not merge the main one as user can use a merge node if wanted + const main = additionalVertexData.splice(0, 1)[0]; + this._vertexData = main.merge(additionalVertexData, true, false, true, true); + } + } + else { + return null; + } + return this._vertexData; + }; + // Storage + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions ? "true" : "false"};\n`; + codeString += `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.removeDuplicatedPositions = this.removeDuplicatedPositions; + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.removeDuplicatedPositions = serializationObject.removeDuplicatedPositions; + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { notifiers: { rebuild: true } }) +], InstantiateOnVerticesBlock.prototype, "evaluateContext", void 0); +__decorate([ + editableInPropertyPage("Remove duplicated positions", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { notifiers: { update: true } }) +], InstantiateOnVerticesBlock.prototype, "removeDuplicatedPositions", void 0); +RegisterClass("BABYLON.InstantiateOnVerticesBlock", InstantiateOnVerticesBlock); + +/** + * Block used to instance geometry on every face of a geometry + */ +class InstantiateOnFacesBlock extends NodeGeometryBlock { + /** + * Create a new InstantiateOnFacesBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._currentPosition = new Vector3(); + this._currentUV = new Vector2(); + this._vertex0 = new Vector3(); + this._vertex1 = new Vector3(); + this._vertex2 = new Vector3(); + this._tempVector0 = new Vector3(); + this._tempVector1 = new Vector3(); + this._uv0 = new Vector2(); + this._uv1 = new Vector2(); + this._uv2 = new Vector2(); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("count", NodeGeometryBlockConnectionPointTypes.Int, true, 256); + this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true); + this.registerInput("offset", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.One()); + this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current instance index in the current flow + * @returns the current index + */ + getInstanceIndex() { + return this._currentLoopIndex; + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return 0; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return this._currentFaceIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentLoopIndex; + } + /** + * Gets the value associated with a contextual positions + * @returns the value associated with the source + */ + getOverridePositionsContextualValue() { + return this._currentPosition; + } + /** + * Gets the value associated with a contextual normals + * @returns the value associated with the source + */ + getOverrideNormalsContextualValue() { + this._vertex1.subtractToRef(this._vertex0, this._tempVector0); + this._vertex2.subtractToRef(this._vertex1, this._tempVector1); + this._tempVector0.normalize(); + this._tempVector1.normalize(); + return Vector3.Cross(this._tempVector1, this._tempVector0); + } + /** + * Gets the value associated with a contextual UV1 se + * @returns the value associated with the source + */ + getOverrideUVs1ContextualValue() { + return this._currentUV; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "InstantiateOnFacesBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the instance input component + */ + get instance() { + return this._inputs[1]; + } + /** + * Gets the count input component + */ + get count() { + return this._inputs[2]; + } + /** + * Gets the matrix input component + */ + get matrix() { + return this._inputs[3]; + } + /** + * Gets the offset input component + */ + get offset() { + return this._inputs[4]; + } + /** + * Gets the rotation input component + */ + get rotation() { + return this._inputs[5]; + } + /** + * Gets the scaling input component + */ + get scaling() { + return this._inputs[6]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + state.pushInstancingContext(this); + this._vertexData = this.geometry.getConnectedValue(state); + state.pushGeometryContext(this._vertexData); + if (!this._vertexData || !this._vertexData.positions || !this._vertexData.indices || !this.instance.isConnected) { + state.restoreExecutionContext(); + state.restoreInstancingContext(); + state.restoreGeometryContext(); + this.output._storedValue = null; + return; + } + // Processing + let instanceGeometry = null; + const instanceCount = this.count.getConnectedValue(state); + const faceCount = this._vertexData.indices.length / 3; + const instancePerFace = instanceCount / faceCount; + let accumulatedCount = 0; + const additionalVertexData = []; + let totalDone = 0; + this._currentLoopIndex = 0; + for (this._currentFaceIndex = 0; this._currentFaceIndex < faceCount; this._currentFaceIndex++) { + accumulatedCount += instancePerFace; + const countPerFace = (accumulatedCount | 0) - totalDone; + if (countPerFace < 1) { + continue; + } + const faceID0 = this._vertexData.indices[this._currentFaceIndex * 3]; + const faceID1 = this._vertexData.indices[this._currentFaceIndex * 3 + 1]; + const faceID2 = this._vertexData.indices[this._currentFaceIndex * 3 + 2]; + // Extract face vertices + this._vertex0.fromArray(this._vertexData.positions, faceID0 * 3); + this._vertex1.fromArray(this._vertexData.positions, faceID1 * 3); + this._vertex2.fromArray(this._vertexData.positions, faceID2 * 3); + if (this._vertexData.uvs) { + this._uv0.fromArray(this._vertexData.uvs, faceID0 * 2); + this._uv1.fromArray(this._vertexData.uvs, faceID1 * 2); + this._uv2.fromArray(this._vertexData.uvs, faceID2 * 2); + } + for (let faceDispatchCount = 0; faceDispatchCount < countPerFace; faceDispatchCount++) { + if (totalDone >= instanceCount) { + break; + } + // Get random point on face + let x = Math.random(); + let y = Math.random(); + if (x > y) { + const temp = x; + x = y; + y = temp; + } + const s = x; + const t = y - x; + const u = 1 - s - t; + this._currentPosition.set(s * this._vertex0.x + t * this._vertex1.x + u * this._vertex2.x, s * this._vertex0.y + t * this._vertex1.y + u * this._vertex2.y, s * this._vertex0.z + t * this._vertex1.z + u * this._vertex2.z); + if (this._vertexData.uvs) { + this._currentUV.set(s * this._uv0.x + t * this._uv1.x + u * this._uv2.x, s * this._uv0.y + t * this._uv1.y + u * this._uv2.y); + } + // Clone the instance + instanceGeometry = this.instance.getConnectedValue(state); + if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) { + accumulatedCount -= instancePerFace; + continue; + } + const clone = instanceGeometry.clone(); + if (this.matrix.isConnected) { + const transform = this.matrix.getConnectedValue(state); + state._instantiateWithPositionAndMatrix(clone, this._currentPosition, transform, additionalVertexData); + } + else { + const offset = state.adaptInput(this.offset, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.ZeroReadOnly); + const scaling = state.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly); + const rotation = this.rotation.getConnectedValue(state) || Vector3.ZeroReadOnly; + this._currentPosition.addInPlace(offset); + state._instantiate(clone, this._currentPosition, rotation, scaling, additionalVertexData); + } + totalDone++; + this._currentLoopIndex++; + } + } + // Merge + if (additionalVertexData.length) { + if (additionalVertexData.length === 1) { + this._vertexData = additionalVertexData[0]; + } + else { + // We do not merge the main one as user can use a merge node if wanted + const main = additionalVertexData.splice(0, 1)[0]; + this._vertexData = main.merge(additionalVertexData, true, false, true, true); + } + } + state.restoreExecutionContext(); + state.restoreInstancingContext(); + state.restoreGeometryContext(); + return this._vertexData; + }; + // Storage + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { notifiers: { rebuild: true } }) +], InstantiateOnFacesBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.InstantiateOnFacesBlock", InstantiateOnFacesBlock); + +/** + * Block used to instance geometry inside a geometry + */ +class InstantiateOnVolumeBlock extends NodeGeometryBlock { + /** + * Create a new InstantiateOnVolumeBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._currentPosition = new Vector3(); + this._vertex0 = new Vector3(); + this._vertex1 = new Vector3(); + this._vertex2 = new Vector3(); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + /** + * Gets or sets a boolean indicating that a grid pattern should be used + */ + this.gridMode = false; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("count", NodeGeometryBlockConnectionPointTypes.Int, true, 256); + this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true); + this.registerInput("offset", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.One()); + this.registerInput("gridSize", NodeGeometryBlockConnectionPointTypes.Int, true, 10); + this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current instance index in the current flow + * @returns the current index + */ + getInstanceIndex() { + return this._currentLoopIndex; + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return 0; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentLoopIndex; + } + /** + * Gets the value associated with a contextual positions + * @returns the value associated with the source + */ + getOverridePositionsContextualValue() { + return this._currentPosition; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "InstantiateOnVolumeBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the instance input component + */ + get instance() { + return this._inputs[1]; + } + /** + * Gets the count input component + */ + get count() { + return this._inputs[2]; + } + /** + * Gets the matrix input component + */ + get matrix() { + return this._inputs[3]; + } + /** + * Gets the offset input component + */ + get offset() { + return this._inputs[4]; + } + /** + * Gets the rotation input component + */ + get rotation() { + return this._inputs[5]; + } + /** + * Gets the scaling input component + */ + get scaling() { + return this._inputs[6]; + } + /** + * Gets the grid size input component + */ + get gridSize() { + return this._inputs[6]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _getValueOnGrid(step, size, min, max) { + const cellSize = (max - min) / size; + return min + cellSize / 2 + step * cellSize; + } + _getIndexinGrid(x, y, z, size) { + return x + y * size + z * size * size; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + state.pushInstancingContext(this); + this._vertexData = this.geometry.getConnectedValue(state); + state.pushGeometryContext(this._vertexData); + if (!this._vertexData || !this._vertexData.positions || !this._vertexData.indices || !this.instance.isConnected) { + state.restoreExecutionContext(); + state.restoreInstancingContext(); + state.restoreGeometryContext(); + this.output._storedValue = null; + return; + } + // Processing + let instanceGeometry = null; + const instanceCount = this.count.getConnectedValue(state); + const additionalVertexData = []; + const boundingInfo = extractMinAndMax(this._vertexData.positions, 0, this._vertexData.positions.length / 3); + const min = boundingInfo.minimum; + const max = boundingInfo.maximum; + const direction = new Vector3(0.5, 0.8, 0.2); + const faceCount = this._vertexData.indices.length / 3; + const gridSize = this.gridSize.getConnectedValue(state); + this._currentLoopIndex = 0; + let candidatesCells; + if (this.gridMode) { + candidatesCells = []; + // Generates the list of candidates cells + for (let index = 0; index < gridSize * gridSize * gridSize; index++) { + candidatesCells[index] = false; + } + } + for (let index = 0; index < instanceCount; index++) { + if (this.gridMode) { + // Get a random cell + let cellX = Math.floor(Math.random() * gridSize); + let cellY = Math.floor(Math.random() * gridSize); + let cellZ = Math.floor(Math.random() * gridSize); + let cellIndex = this._getIndexinGrid(cellX, cellY, cellZ, gridSize); + if (candidatesCells[cellIndex]) { + // Find the first one that is free + let found = false; + for (let candidateIndex = 0; candidateIndex < gridSize * gridSize * gridSize; candidateIndex++) { + if (!candidatesCells[candidateIndex]) { + cellZ = Math.floor(candidateIndex / (gridSize * gridSize)); + cellY = Math.floor((candidateIndex - cellZ * gridSize * gridSize) / gridSize); + cellX = candidateIndex - cellZ * gridSize * gridSize - cellY * gridSize; + cellIndex = this._getIndexinGrid(cellX, cellY, cellZ, gridSize); + found = true; + break; + } + } + if (!found) { + // No more free cells + break; + } + } + if (!candidatesCells[cellIndex]) { + // Cell is free + const x = this._getValueOnGrid(cellX, gridSize, min.x, max.x); + const y = this._getValueOnGrid(cellY, gridSize, min.y, max.y); + const z = this._getValueOnGrid(cellZ, gridSize, min.z, max.z); + this._currentPosition.set(x, y, z); + candidatesCells[cellIndex] = true; + } + } + else { + this._currentPosition.set(Math.random() * (max.x - min.x) + min.x, Math.random() * (max.y - min.y) + min.y, Math.random() * (max.z - min.z) + min.z); + } + // Cast a ray from the random point in an arbitrary direction + const ray = new Ray(this._currentPosition, direction); + let intersectionCount = 0; + for (let currentFaceIndex = 0; currentFaceIndex < faceCount; currentFaceIndex++) { + // Extract face vertices + this._vertex0.fromArray(this._vertexData.positions, this._vertexData.indices[currentFaceIndex * 3] * 3); + this._vertex1.fromArray(this._vertexData.positions, this._vertexData.indices[currentFaceIndex * 3 + 1] * 3); + this._vertex2.fromArray(this._vertexData.positions, this._vertexData.indices[currentFaceIndex * 3 + 2] * 3); + const currentIntersectInfo = ray.intersectsTriangle(this._vertex0, this._vertex1, this._vertex2); + if (currentIntersectInfo && currentIntersectInfo.distance > 0) { + intersectionCount++; + } + } + if (intersectionCount % 2 === 0) { + // We are outside, try again + index--; + continue; + } + // Clone the instance + instanceGeometry = this.instance.getConnectedValue(state); + if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) { + continue; + } + const clone = instanceGeometry.clone(); + if (this.matrix.isConnected) { + const transform = this.matrix.getConnectedValue(state); + state._instantiateWithPositionAndMatrix(clone, this._currentPosition, transform, additionalVertexData); + } + else { + const offset = state.adaptInput(this.offset, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.ZeroReadOnly); + const scaling = state.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly); + const rotation = this.rotation.getConnectedValue(state) || Vector3.ZeroReadOnly; + this._currentPosition.addInPlace(offset); + state._instantiate(clone, this._currentPosition, rotation, scaling, additionalVertexData); + } + this._currentLoopIndex++; + } + // Merge + if (additionalVertexData.length) { + if (additionalVertexData.length === 1) { + this._vertexData = additionalVertexData[0]; + } + else { + // We do not merge the main one as user can use a merge node if wanted + const main = additionalVertexData.splice(0, 1)[0]; + this._vertexData = main.merge(additionalVertexData, true, false, true, true); + } + } + state.restoreGeometryContext(); + state.restoreExecutionContext(); + state.restoreInstancingContext(); + return this._vertexData; + }; + // Storage + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + codeString += `${this._codeVariableName}.gridMode = ${this.gridMode ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + serializationObject.gridMode = this.gridMode; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + if (serializationObject.gridMode !== undefined) { + this.gridMode = serializationObject.gridMode; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { notifiers: { rebuild: true } }) +], InstantiateOnVolumeBlock.prototype, "evaluateContext", void 0); +__decorate([ + editableInPropertyPage("Grid mode", 0 /* PropertyTypeForEdition.Boolean */, "MODES", { notifiers: { rebuild: true } }) +], InstantiateOnVolumeBlock.prototype, "gridMode", void 0); +RegisterClass("BABYLON.InstantiateOnVolumeBlock", InstantiateOnVolumeBlock); + +/** + * Block used as a base for InstantiateXXX blocks + */ +class InstantiateBaseBlock extends NodeGeometryBlock { + /** + * Create a new InstantiateBaseBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true); + this.registerInput("count", NodeGeometryBlockConnectionPointTypes.Int, true, 1); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current instance index in the current flow + * @returns the current index + */ + getInstanceIndex() { + return this._currentIndex; + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._currentIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentIndex; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "InstantiateBaseBlock"; + } + /** + * Gets the instance input component + */ + get instance() { + return this._inputs[0]; + } + /** + * Gets the count input component + */ + get count() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], InstantiateBaseBlock.prototype, "evaluateContext", void 0); + +/** + * Block used to instantiate a geometry inside a loop + */ +class InstantiateBlock extends InstantiateBaseBlock { + /** + * Create a new InstantiateBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true); + this.registerInput("position", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.One()); + this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + } + /** + * Gets the current instance index in the current flow + * @returns the current index + */ + getInstanceIndex() { + return this._currentIndex; + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._currentIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentIndex; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "InstantiateBlock"; + } + /** + * Gets the matrix input component + */ + get matrix() { + return this._inputs[2]; + } + /** + * Gets the position input component + */ + get position() { + return this._inputs[3]; + } + /** + * Gets the rotation input component + */ + get rotation() { + return this._inputs[4]; + } + /** + * Gets the scaling input component + */ + get scaling() { + return this._inputs[5]; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + state.pushInstancingContext(this); + // Processing + const iterationCount = this.count.getConnectedValue(state); + const additionalVertexData = []; + for (this._currentIndex = 0; this._currentIndex < iterationCount; this._currentIndex++) { + const instanceGeometry = this.instance.getConnectedValue(state); + if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) { + continue; + } + // Clone the instance + const clone = instanceGeometry.clone(); + // Transform + if (this.matrix.isConnected) { + const transform = this.matrix.getConnectedValue(state); + state._instantiateWithMatrix(clone, transform, additionalVertexData); + } + else { + const position = this.position.getConnectedValue(state) || Vector3.ZeroReadOnly; + const scaling = state.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly); + const rotation = this.rotation.getConnectedValue(state) || Vector3.ZeroReadOnly; + state._instantiate(clone, position, rotation, scaling, additionalVertexData); + } + } + // Merge + if (additionalVertexData.length) { + if (additionalVertexData.length === 1) { + this._vertexData = additionalVertexData[0]; + } + else { + // We do not merge the main one as user can use a merge node if wanted + const main = additionalVertexData.splice(0, 1)[0]; + this._vertexData = main.merge(additionalVertexData, true, false, true, true); + } + } + state.restoreExecutionContext(); + state.restoreInstancingContext(); + return this._vertexData; + }; + // Storage + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } +} +RegisterClass("BABYLON.InstantiateBlock", InstantiateBlock); + +/** + * Block used to clone geometry along a line + */ +class InstantiateLinearBlock extends InstantiateBaseBlock { + /** + * Create a new Instantiate Linear Block + * @param name defines the block name + */ + constructor(name) { + super(name); + // Direction is magnitude per step + this.registerInput("direction", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(1, 0, 0)); + // Rotation is magnitude per step + this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(0, 0, 0)); + // Scaling is magnitude per step + this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(0, 0, 0)); + this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "InstantiateLinearBlock"; + } + /** + * Gets the direction input component + */ + get direction() { + return this._inputs[2]; + } + /** + * Gets the rotation input component + */ + get rotation() { + return this._inputs[3]; + } + /** + * Gets the scaling input component + */ + get scaling() { + return this._inputs[4]; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + state.pushInstancingContext(this); + const iterationCount = this.count.getConnectedValue(state); + const additionalVertexData = []; + const transformMatrix = Matrix.Identity(); + const transformOffset = Vector3.Zero(); + const rotationOffset = Vector3.Zero(); + const scaleOffset = Vector3.Zero(); + for (this._currentIndex = 0; this._currentIndex < iterationCount; this._currentIndex++) { + const instanceGeometry = this.instance.getConnectedValue(state); + if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) { + continue; + } + // Clone the instance + const clone = instanceGeometry.clone(); + const direction = this.direction.getConnectedValue(state); + const rotation = this.rotation.getConnectedValue(state); + const scale = state.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly); + transformOffset.copyFrom(direction.clone().scale(this._currentIndex)); + rotationOffset.copyFrom(rotation.clone().scale(this._currentIndex)); + scaleOffset.copyFrom(scale.clone().scale(this._currentIndex)); + scaleOffset.addInPlaceFromFloats(1, 1, 1); + Matrix.ComposeToRef(scaleOffset, Quaternion.FromEulerAngles(rotationOffset.x, rotationOffset.y, rotationOffset.z), transformOffset, transformMatrix); + state._instantiateWithMatrix(clone, transformMatrix, additionalVertexData); + } + // Merge + if (additionalVertexData.length) { + if (additionalVertexData.length === 1) { + this._vertexData = additionalVertexData[0]; + } + else { + // We do not merge the main one as user can use a merge node if wanted + const main = additionalVertexData.splice(0, 1)[0]; + this._vertexData = main.merge(additionalVertexData, true, false, true, true); + } + } + state.restoreExecutionContext(); + state.restoreInstancingContext(); + // Storage + return this._vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } +} +RegisterClass("BABYLON.InstantiateLinearBlock", InstantiateLinearBlock); + +/** + * Block used to clone geometry in a radial shape + */ +class InstantiateRadialBlock extends InstantiateBaseBlock { + /** + * Create a new InstantiateRadialBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0); + // Angle start and end + this.registerInput("angleStart", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("angleEnd", NodeGeometryBlockConnectionPointTypes.Float, true, Math.PI * 2); + // Transform offset + this.registerInput("transform", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(0, 0, 0)); + // Rotation is magnitude per step + this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(0, 0, 0)); + // Scale is magnitude per step + this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(0, 0, 0)); + this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "InstantiateRadialBlock"; + } + /** + * Gets the direction input component + */ + get radius() { + return this._inputs[2]; + } + /** + * Gets the direction input component + */ + get angleStart() { + return this._inputs[3]; + } + /** + * Gets the direction input component + */ + get angleEnd() { + return this._inputs[4]; + } + /** + * Gets the transform input component + */ + get transform() { + return this._inputs[5]; + } + /** + * Gets the rotation input component + */ + get rotation() { + return this._inputs[6]; + } + /** + * Gets the scaling input component + */ + get scaling() { + return this._inputs[7]; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + state.pushInstancingContext(this); + const iterationCount = this.count.getConnectedValue(state); + const additionalVertexData = []; + const rotMatrix = Matrix.Identity(); + const radiusMatrix = Matrix.Identity(); + const transformMatrix = Matrix.Identity(); + const transformOffset = Vector3.Zero(); + const rotationOffset = Vector3.Zero(); + const scaleOffset = Vector3.Zero(); + for (this._currentIndex = 0; this._currentIndex < iterationCount; this._currentIndex++) { + const instanceGeometry = this.instance.getConnectedValue(state); + if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) { + continue; + } + // Clone the instance + const clone = instanceGeometry.clone(); + const radius = this.radius.getConnectedValue(state); + const angleStart = this.angleStart.getConnectedValue(state); + const angleEnd = this.angleEnd.getConnectedValue(state); + const transform = this.transform.getConnectedValue(state); + const rotation = this.rotation.getConnectedValue(state); + const scale = state.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly); + // Define arc size + const pieSlice = angleEnd - angleStart; + const rStep = pieSlice / iterationCount; + const angle = angleStart + rStep * this._currentIndex; + const angleQuat = Quaternion.FromEulerAngles(0, angle, 0); + // Get local transforms + transformOffset.copyFrom(transform.clone().scale(this._currentIndex)); + rotationOffset.copyFrom(rotation.clone().scale(this._currentIndex)); + scaleOffset.copyFrom(scale.clone().scale(this._currentIndex)); + scaleOffset.addInPlaceFromFloats(1, 1, 1); + // Compose (rotMatrix x radius x scale x angle x user transform) + Matrix.RotationYawPitchRollToRef(rotationOffset.y, rotationOffset.x, rotationOffset.z, rotMatrix); + radiusMatrix.setTranslationFromFloats(0, 0, radius); + Matrix.ComposeToRef(scaleOffset, angleQuat, transformOffset, transformMatrix); + rotMatrix.multiplyToRef(radiusMatrix, radiusMatrix); + radiusMatrix.multiplyToRef(transformMatrix, transformMatrix); + state._instantiateWithMatrix(clone, transformMatrix, additionalVertexData); + } + // Merge + if (additionalVertexData.length) { + if (additionalVertexData.length === 1) { + this._vertexData = additionalVertexData[0]; + } + else { + // We do not merge the main one as user can use a merge node if wanted + const main = additionalVertexData.splice(0, 1)[0]; + this._vertexData = main.merge(additionalVertexData, true, false, true, true); + } + } + // Storage + state.restoreExecutionContext(); + state.restoreInstancingContext(); + return this._vertexData; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } +} +RegisterClass("BABYLON.InstantiateRadialBlock", InstantiateRadialBlock); + +/** + * Defines a block used to convert from int to float + */ +class IntFloatConverterBlock extends NodeGeometryBlock { + /** + * Create a new IntFloatConverterBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("float ", NodeGeometryBlockConnectionPointTypes.Float, true); + this.registerInput("int ", NodeGeometryBlockConnectionPointTypes.Int, true); + this.registerOutput("float", NodeGeometryBlockConnectionPointTypes.Float); + this.registerOutput("int", NodeGeometryBlockConnectionPointTypes.Int); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "IntFloatConverterBlock"; + } + /** + * Gets the float input component + */ + get floatIn() { + return this._inputs[0]; + } + /** + * Gets the int input component + */ + get intIn() { + return this._inputs[1]; + } + /** + * Gets the float output component + */ + get floatOut() { + return this._outputs[0]; + } + /** + * Gets the int output component + */ + get intOut() { + return this._outputs[1]; + } + _inputRename(name) { + if (name === "float ") { + return "floatIn"; + } + if (name === "int ") { + return "intIn"; + } + return name; + } + _buildBlock() { + this.floatOut._storedFunction = (state) => { + if (this.floatIn.isConnected) { + return this.floatIn.getConnectedValue(state); + } + if (this.intIn.isConnected) { + return this.intIn.getConnectedValue(state); + } + return 0; + }; + this.intOut._storedFunction = (state) => { + if (this.floatIn.isConnected) { + return Math.floor(this.floatIn.getConnectedValue(state)); + } + if (this.intIn.isConnected) { + return Math.floor(this.intIn.getConnectedValue(state)); + } + return 0; + }; + } +} +RegisterClass("BABYLON.IntFloatConverterBlock", IntFloatConverterBlock); + +/** + * Defines a block used to debug values going through it + */ +class DebugBlock extends NodeGeometryBlock { + /** + * Create a new DebugBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets the log entries + */ + this.log = []; + this._isDebug = true; + this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the time spent to build this block (in ms) + */ + get buildExecutionTime() { + return -1; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "DebugBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + if (!this.input.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + this.log = []; + const func = (state) => { + const input = this.input.getConnectedValue(state); + if (input === null || input === undefined) { + this.log.push(["null", ""]); + return input; + } + switch (this.input.type) { + case NodeGeometryBlockConnectionPointTypes.Vector2: + this.log.push([Vector2ToFixed(input, 4), input.toString()]); + break; + case NodeGeometryBlockConnectionPointTypes.Vector3: + this.log.push([Vector3ToFixed(input, 4), input.toString()]); + break; + case NodeGeometryBlockConnectionPointTypes.Vector4: + this.log.push([Vector4ToFixed(input, 4), input.toString()]); + break; + default: + this.log.push([input.toString(), input.toString()]); + break; + } + return input; + }; + if (this.output.isConnected) { + this.output._storedFunction = func; + } + else { + this.output._storedValue = func(state); + } + } +} +RegisterClass("BABYLON.DebugBlock", DebugBlock); + +/** + * Block used to get information about a geometry + */ +class GeometryInfoBlock extends NodeGeometryBlock { + /** + * Create a new GeometryInfoBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerOutput("id", NodeGeometryBlockConnectionPointTypes.Int); + this.registerOutput("collectionId", NodeGeometryBlockConnectionPointTypes.Int); + this.registerOutput("verticesCount", NodeGeometryBlockConnectionPointTypes.Int); + this.registerOutput("facesCount", NodeGeometryBlockConnectionPointTypes.Int); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryInfoBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + /** + * Gets the id output component + */ + get id() { + return this._outputs[1]; + } + /** + * Gets the collectionId output component + */ + get collectionId() { + return this._outputs[2]; + } + /** + * Gets the verticesCount output component + */ + get verticesCount() { + return this._outputs[3]; + } + /** + * Gets the facesCount output component + */ + get facesCount() { + return this._outputs[4]; + } + _buildBlock() { + if (!this.geometry.isConnected) { + this.id._storedValue = 0; + this.collectionId._storedValue = 0; + this.verticesCount._storedValue = 0; + this.facesCount._storedValue = 0; + this.output._storedValue = 0; + this.id._storedFunction = null; + this.collectionId._storedFunction = null; + this.verticesCount._storedFunction = null; + this.facesCount._storedFunction = null; + this.output._storedFunction = null; + return; + } + this.output._storedFunction = (state) => { + this._currentVertexData = this.geometry.getConnectedValue(state); + return this._currentVertexData; + }; + this.id._storedFunction = (state) => { + this._currentVertexData = this._currentVertexData || this.geometry.getConnectedValue(state); + return this._currentVertexData.uniqueId; + }; + this.collectionId._storedFunction = (state) => { + this._currentVertexData = this._currentVertexData || this.geometry.getConnectedValue(state); + return this._currentVertexData.metadata ? this._currentVertexData.metadata.collectionId : 0; + }; + this.verticesCount._storedFunction = (state) => { + this._currentVertexData = this._currentVertexData || this.geometry.getConnectedValue(state); + return this._currentVertexData.positions ? this._currentVertexData.positions.length / 3 : 0; + }; + this.facesCount._storedFunction = (state) => { + this._currentVertexData = this._currentVertexData || this.geometry.getConnectedValue(state); + return this._currentVertexData.indices ? this._currentVertexData.indices.length / 3 : 0; + }; + } +} +RegisterClass("BABYLON.GeometryInfoBlock", GeometryInfoBlock); + +/** + * Type of mappings supported by the mapping block + */ +var MappingTypes; +(function (MappingTypes) { + /** Spherical */ + MappingTypes[MappingTypes["Spherical"] = 0] = "Spherical"; + /** Cylindrical */ + MappingTypes[MappingTypes["Cylindrical"] = 1] = "Cylindrical"; + /** Cubic */ + MappingTypes[MappingTypes["Cubic"] = 2] = "Cubic"; +})(MappingTypes || (MappingTypes = {})); +/** + * Block used to generate UV coordinates + */ +class MappingBlock extends NodeGeometryBlock { + /** + * Create a new MappingBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets the mapping type used by the block + */ + this.mapping = MappingTypes.Spherical; + this.registerInput("position", NodeGeometryBlockConnectionPointTypes.Vector3); + this.registerInput("normal", NodeGeometryBlockConnectionPointTypes.Vector3); + this.registerInput("center", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero()); + this.registerOutput("uv", NodeGeometryBlockConnectionPointTypes.Vector2); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MappingBlock"; + } + /** + * Gets the position input component + */ + get position() { + return this._inputs[0]; + } + /** + * Gets the normal input component + */ + get normal() { + return this._inputs[1]; + } + /** + * Gets the center input component + */ + get center() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get uv() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.position.isConnected) { + this.uv._storedFunction = null; + this.uv._storedValue = null; + return; + } + const tempDirection = Vector3.Zero(); + const func = (state) => { + const position = this.position.getConnectedValue(state) || Vector3.Zero(); + const normal = this.normal.getConnectedValue(state) || Vector3.Zero(); + const center = this.center.getConnectedValue(state); + const uv = Vector2.Zero(); + switch (this.mapping) { + case MappingTypes.Spherical: { + position.subtractToRef(center, tempDirection); + const len = tempDirection.length(); + if (len > 0) { + uv.x = Math.acos(tempDirection.y / len) / Math.PI; + if (tempDirection.x !== 0 || tempDirection.z !== 0) { + uv.y = Math.atan2(tempDirection.x, tempDirection.z) / (Math.PI * 2); + } + } + break; + } + case MappingTypes.Cylindrical: { + position.subtractToRef(center, tempDirection); + const len = tempDirection.length(); + if (len > 0) { + uv.x = Math.atan2(tempDirection.x / len, tempDirection.z / len) / (Math.PI * 2); + uv.y = (tempDirection.y + 1.0) / 2.0; + } + break; + } + case MappingTypes.Cubic: { + // Find the largest component of the normal vector + const absX = Math.abs(normal.x); + const absY = Math.abs(normal.y); + const absZ = Math.abs(normal.z); + const maxDim = Math.max(Math.abs(position.x), Math.abs(position.y), Math.abs(position.z)); + let u = 0, v = 0; + if (absX >= absY && absX >= absZ) { + u = position.y / maxDim - center.y; + v = position.z / maxDim - center.z; + } + else if (absY >= absX && absY >= absZ) { + u = position.x / maxDim - center.x; + v = position.z / maxDim - center.z; + } + else { + u = position.x / maxDim - center.x; + v = position.y / maxDim - center.y; + } + uv.x = (u + 1) / 2; + uv.y = (v + 1) / 2; + } + } + return uv; + }; + this.uv._storedFunction = (state) => { + return func(state); + }; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.mapping = BABYLON.MappingTypes.${MappingTypes[this.mapping]};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.mapping = this.mapping; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.mapping = serializationObject.mapping; + } +} +__decorate([ + editableInPropertyPage("Mapping", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "Spherical", value: MappingTypes.Spherical }, + { label: "Cylindrical", value: MappingTypes.Cylindrical }, + { label: "Cubic", value: MappingTypes.Cubic }, + ], + }) +], MappingBlock.prototype, "mapping", void 0); +RegisterClass("BABYLON.MappingBlock", MappingBlock); + +/** + * Block used to compose two matrices + */ +class MatrixComposeBlock extends NodeGeometryBlock { + /** + * Create a new MatrixComposeBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("matrix0", NodeGeometryBlockConnectionPointTypes.Matrix); + this.registerInput("matrix1", NodeGeometryBlockConnectionPointTypes.Matrix); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "MatrixComposeBlock"; + } + /** + * Gets the matrix0 input component + */ + get matrix0() { + return this._inputs[0]; + } + /** + * Gets the matrix1 input component + */ + get matrix1() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + this.output._storedFunction = (state) => { + if (!this.matrix0.isConnected || !this.matrix1.isConnected) { + return null; + } + const matrix0 = this.matrix0.getConnectedValue(state); + const matrix1 = this.matrix1.getConnectedValue(state); + if (!matrix0 || !matrix1) { + return null; + } + return matrix0.multiply(matrix1); + }; + } +} +RegisterClass("BABYLON.MatrixComposeBlock", MatrixComposeBlock); + +/** + * Defines a block used to teleport a value to an endpoint + */ +class TeleportInBlock extends NodeGeometryBlock { + /** Gets the list of attached endpoints */ + get endpoints() { + return this._endpoints; + } + /** + * Create a new TeleportInBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._endpoints = []; + this._isTeleportIn = true; + this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "TeleportInBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + _dumpCode(uniqueNames, alreadyDumped) { + let codeString = super._dumpCode(uniqueNames, alreadyDumped); + for (const endpoint of this.endpoints) { + if (alreadyDumped.indexOf(endpoint) === -1) { + codeString += endpoint._dumpCode(uniqueNames, alreadyDumped); + } + } + return codeString; + } + /** + * Checks if the current block is an ancestor of a given type + * @param type defines the potential type to check + * @returns true if block is a descendant + */ + isAnAncestorOfType(type) { + if (this.getClassName() === type) { + return true; + } + for (const endpoint of this.endpoints) { + if (endpoint.isAnAncestorOfType(type)) { + return true; + } + } + return false; + } + /** + * Checks if the current block is an ancestor of a given block + * @param block defines the potential descendant block to check + * @returns true if block is a descendant + */ + isAnAncestorOf(block) { + for (const endpoint of this.endpoints) { + if (endpoint === block) { + return true; + } + if (endpoint.isAnAncestorOf(block)) { + return true; + } + } + return false; + } + /** + * Get the first descendant using a predicate + * @param predicate defines the predicate to check + * @returns descendant or null if none found + */ + getDescendantOfPredicate(predicate) { + if (predicate(this)) { + return this; + } + for (const endpoint of this.endpoints) { + const descendant = endpoint.getDescendantOfPredicate(predicate); + if (descendant) { + return descendant; + } + } + return null; + } + /** + * Add an enpoint to this block + * @param endpoint define the endpoint to attach to + */ + attachToEndpoint(endpoint) { + endpoint.detach(); + this._endpoints.push(endpoint); + endpoint._entryPoint = this; + endpoint._outputs[0]._typeConnectionSource = this._inputs[0]; + endpoint._tempEntryPointUniqueId = null; + endpoint.name = "> " + this.name; + } + /** + * Remove enpoint from this block + * @param endpoint define the endpoint to remove + */ + detachFromEndpoint(endpoint) { + const index = this._endpoints.indexOf(endpoint); + if (index !== -1) { + this._endpoints.splice(index, 1); + endpoint._outputs[0]._typeConnectionSource = null; + endpoint._entryPoint = null; + } + } + _buildBlock() { + for (const endpoint of this._endpoints) { + endpoint.output._storedFunction = (state) => { + return this.input.getConnectedValue(state); + }; + } + } +} +RegisterClass("BABYLON.TeleportInBlock", TeleportInBlock); + +/** + * Defines a block used to receive a value from a teleport entry point + */ +class TeleportOutBlock extends NodeGeometryBlock { + /** + * Create a new TeleportOutBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** @internal */ + this._entryPoint = null; + /** @internal */ + this._tempEntryPointUniqueId = null; + this._isTeleportOut = true; + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + } + /** + * Gets the entry point + */ + get entryPoint() { + return this._entryPoint; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "TeleportOutBlock"; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + /** Detach from entry point */ + detach() { + if (!this._entryPoint) { + return; + } + this._entryPoint.detachFromEndpoint(this); + } + _buildBlock() { + // Do nothing + // All work done by the emitter + } + _customBuildStep(state) { + if (this.entryPoint) { + this.entryPoint.build(state); + } + } + _dumpCode(uniqueNames, alreadyDumped) { + let codeString = ""; + if (this.entryPoint) { + if (alreadyDumped.indexOf(this.entryPoint) === -1) { + codeString += this.entryPoint._dumpCode(uniqueNames, alreadyDumped); + } + } + return codeString + super._dumpCode(uniqueNames, alreadyDumped); + } + _dumpCodeForOutputConnections(alreadyDumped) { + let codeString = super._dumpCodeForOutputConnections(alreadyDumped); + if (this.entryPoint) { + codeString += this.entryPoint._dumpCodeForOutputConnections(alreadyDumped); + } + return codeString; + } + /** + * Clone the current block to a new identical block + * @returns a copy of the current block + */ + clone() { + const clone = super.clone(); + if (this.entryPoint) { + this.entryPoint.attachToEndpoint(clone); + } + return clone; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode(); + if (this.entryPoint) { + codeString += `${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`; + } + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.entryPoint = this.entryPoint?.uniqueId ?? ""; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this._tempEntryPointUniqueId = serializationObject.entryPoint; + } +} +RegisterClass("BABYLON.TeleportOutBlock", TeleportOutBlock); + +/** + * Block used to load texture data + */ +class GeometryTextureBlock extends NodeGeometryBlock { + /** + * Gets the texture data + */ + get textureData() { + return this._data; + } + /** + * Gets the texture width + */ + get textureWidth() { + return this._width; + } + /** + * Gets the texture height + */ + get textureHeight() { + return this._height; + } + /** + * Creates a new GeometryTextureBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._data = null; + /** + * Gets or sets a boolean indicating that this block should serialize its cached data + */ + this.serializedCachedData = false; + this.registerOutput("texture", NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryTextureBlock"; + } + /** + * Gets the texture component + */ + get texture() { + return this._outputs[0]; + } + _prepareImgToLoadAsync(url) { + return new Promise((resolve, reject) => { + const img = new Image(); + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + img.onload = () => { + canvas.width = img.width; + canvas.height = img.height; + ctx.drawImage(img, 0, 0); + const imageData = ctx.getImageData(0, 0, img.width, img.height); + const pixels = imageData.data; + const floatArray = new Float32Array(pixels.length); + for (let i = 0; i < pixels.length; i++) { + floatArray[i] = pixels[i] / 255.0; + } + this._data = floatArray; + this._width = img.width; + this._height = img.height; + resolve(); + }; + img.onerror = () => { + this._data = null; + reject(); + }; + img.src = url; + }); + } + /** + * Remove stored data + */ + cleanData() { + this._data = null; + } + /** + * Load the texture data + * @param imageFile defines the file to load data from + * @returns a promise fulfilled when image data is loaded + */ + loadTextureFromFileAsync(imageFile) { + return this._prepareImgToLoadAsync(URL.createObjectURL(imageFile)); + } + /** + * Load the texture data + * @param url defines the url to load data from + * @returns a promise fulfilled when image data is loaded + */ + loadTextureFromUrlAsync(url) { + return this._prepareImgToLoadAsync(url); + } + /** + * Load the texture data + * @param texture defines the source texture + * @returns a promise fulfilled when image data is loaded + */ + extractFromTextureAsync(texture) { + return new Promise((resolve, reject) => { + if (!texture.isReady()) { + texture.onLoadObservable.addOnce(() => { + return this.extractFromTextureAsync(texture).then(resolve).catch(reject); + }); + return; + } + const size = texture.getSize(); + TextureTools.GetTextureDataAsync(texture, size.width, size.height) + .then(async (data) => { + const floatArray = new Float32Array(data.length); + for (let i = 0; i < data.length; i++) { + floatArray[i] = data[i] / 255.0; + } + this._data = floatArray; + this._width = size.width; + this._height = size.height; + resolve(); + }) + .catch(reject); + }); + } + _buildBlock() { + if (!this._data) { + this.texture._storedValue = null; + return; + } + const textureData = { + data: this._data, + width: this._width, + height: this._height, + }; + this.texture._storedValue = textureData; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.width = this._width; + serializationObject.height = this._height; + serializationObject.serializedCachedData = this.serializedCachedData; + if (this._data && this.serializedCachedData) { + serializationObject.data = Array.from(this._data); + } + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this._width = serializationObject.width; + this._height = serializationObject.height; + if (serializationObject.data) { + this._data = new Float32Array(serializationObject.data); + this.serializedCachedData = true; + } + else { + this.serializedCachedData = !!serializationObject.serializedCachedData; + } + } +} +__decorate([ + editableInPropertyPage("Serialize cached data", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], GeometryTextureBlock.prototype, "serializedCachedData", void 0); +RegisterClass("BABYLON.GeometryTextureBlock", GeometryTextureBlock); + +/** + * Block used to fetch a color from texture data + */ +class GeometryTextureFetchBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryTextureFetchBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating if coordinates should be clamped between 0 and 1 + */ + this.clampCoordinates = true; + this.registerInput("texture", NodeGeometryBlockConnectionPointTypes.Texture); + this.registerInput("coordinates", NodeGeometryBlockConnectionPointTypes.Vector2); + this.registerOutput("rgba", NodeGeometryBlockConnectionPointTypes.Vector4); + this.registerOutput("rgb", NodeGeometryBlockConnectionPointTypes.Vector3); + this.registerOutput("r", NodeGeometryBlockConnectionPointTypes.Float); + this.registerOutput("g", NodeGeometryBlockConnectionPointTypes.Float); + this.registerOutput("b", NodeGeometryBlockConnectionPointTypes.Float); + this.registerOutput("a", NodeGeometryBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryTextureFetchBlock"; + } + /** + * Gets the texture component + */ + get texture() { + return this.inputs[0]; + } + /** + * Gets the coordinates component + */ + get coordinates() { + return this.inputs[1]; + } + /** + * Gets the rgba component + */ + get rgba() { + return this._outputs[0]; + } + /** + * Gets the rgb component + */ + get rgb() { + return this._outputs[1]; + } + /** + * Gets the r component + */ + get r() { + return this._outputs[2]; + } + /** + * Gets the g component + */ + get g() { + return this._outputs[3]; + } + /** + * Gets the b component + */ + get b() { + return this._outputs[4]; + } + /** + * Gets the a component + */ + get a() { + return this._outputs[5]; + } + _repeatClamp(num) { + if (num >= 0) { + return num % 1; + } + else { + return 1 - (Math.abs(num) % 1); + } + } + _buildBlock() { + const func = (state) => { + const textureData = this.texture.getConnectedValue(state); + if (!textureData || !textureData.data) { + return null; + } + const uv = this.coordinates.getConnectedValue(state); + if (!uv) { + return null; + } + const u = this.clampCoordinates ? Math.max(0, Math.min(uv.x, 1.0)) : this._repeatClamp(uv.x); + const v = this.clampCoordinates ? Math.max(0, Math.min(uv.y, 1.0)) : this._repeatClamp(uv.y); + const x = Math.floor(u * (textureData.width - 1)); + const y = Math.floor(v * (textureData.height - 1)); + const index = x + textureData.width * y; + return Vector4.FromArray(textureData.data, index * 4); + }; + this.rgba._storedFunction = (state) => { + return func(state); + }; + this.rgb._storedFunction = (state) => { + const color = func(state); + return color ? color.toVector3() : null; + }; + this.r._storedFunction = (state) => { + const color = func(state); + return color ? color.x : null; + }; + this.g._storedFunction = (state) => { + const color = func(state); + return color ? color.y : null; + }; + this.b._storedFunction = (state) => { + const color = func(state); + return color ? color.z : null; + }; + this.a._storedFunction = (state) => { + const color = func(state); + return color ? color.w : null; + }; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.clampCoordinates = this.clampCoordinates; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.clampCoordinates = serializationObject.clampCoordinates; + } +} +__decorate([ + editableInPropertyPage("Clamp Coordinates", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], GeometryTextureFetchBlock.prototype, "clampCoordinates", void 0); +RegisterClass("BABYLON.GeometryTextureFetchBlock", GeometryTextureFetchBlock); + +/** + * Block used to get the bounding info of a geometry + */ +class BoundingBlock extends NodeGeometryBlock { + /** + * Create a new BoundingBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerOutput("min", NodeGeometryBlockConnectionPointTypes.Vector3); + this.registerOutput("max", NodeGeometryBlockConnectionPointTypes.Vector3); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "BoundingBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the min output component + */ + get min() { + return this._outputs[0]; + } + /** + * Gets the max output component + */ + get max() { + return this._outputs[1]; + } + _buildBlock() { + this.min._storedFunction = (state) => { + const geometry = this.geometry.getConnectedValue(state); + if (!geometry) { + return null; + } + const boundingInfo = extractMinAndMax(geometry.positions, 0, geometry.positions.length / 3); + return boundingInfo.minimum; + }; + this.max._storedFunction = (state) => { + const geometry = this.geometry.getConnectedValue(state); + if (!geometry) { + return null; + } + const boundingInfo = extractMinAndMax(geometry.positions, 0, geometry.positions.length / 3); + return boundingInfo.maximum; + }; + } +} +RegisterClass("BABYLON.BoundingBlock", BoundingBlock); + +/** + * Operations supported by the boolean block + */ +var BooleanGeometryOperations; +(function (BooleanGeometryOperations) { + /** Intersect */ + BooleanGeometryOperations[BooleanGeometryOperations["Intersect"] = 0] = "Intersect"; + /** Subtract */ + BooleanGeometryOperations[BooleanGeometryOperations["Subtract"] = 1] = "Subtract"; + /** Union */ + BooleanGeometryOperations[BooleanGeometryOperations["Union"] = 2] = "Union"; +})(BooleanGeometryOperations || (BooleanGeometryOperations = {})); +/** + * Block used to apply a boolean operation between 2 geometries + */ +class BooleanGeometryBlock extends NodeGeometryBlock { + /** + * @internal + */ + get _isReadyState() { + if (IsCSG2Ready()) { + return null; + } + if (!this._csg2LoadingPromise) { + this._csg2LoadingPromise = InitializeCSG2Async(); + } + return this._csg2LoadingPromise; + } + /** + * Create a new BooleanGeometryBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = false; + /** + * Gets or sets the operation applied by the block + */ + this.operation = BooleanGeometryOperations.Intersect; + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.useOldCSGEngine = false; + this.registerInput("geometry0", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("geometry1", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "BooleanGeometryBlock"; + } + /** + * Gets the geometry0 input component + */ + get geometry0() { + return this._inputs[0]; + } + /** + * Gets the geometry1 input component + */ + get geometry1() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + const vertexData0 = this.geometry0.getConnectedValue(state); + const vertexData1 = this.geometry1.getConnectedValue(state); + if (!vertexData0 || !vertexData1) { + return null; + } + const vertexCount = vertexData0.positions.length / 3; + // Ensure that all the fields are filled to avoid problems later on in the graph + if (!vertexData0.normals && vertexData1.normals) { + vertexData0.normals = new Array(vertexData0.positions.length); + } + if (!vertexData1.normals && vertexData0.normals) { + vertexData1.normals = new Array(vertexData1.positions.length); + } + if (!vertexData0.uvs && vertexData1.uvs) { + vertexData0.uvs = new Array(vertexCount * 2); + } + if (!vertexData1.uvs && vertexData0.uvs) { + vertexData1.uvs = new Array(vertexCount * 2); + } + if (!vertexData0.colors && vertexData1.colors) { + vertexData0.colors = new Array(vertexCount * 4); + } + if (!vertexData1.colors && vertexData0.colors) { + vertexData1.colors = new Array(vertexCount * 4); + } + let boolCSG; + if (this.useOldCSGEngine) { + const CSG0 = CSG.FromVertexData(vertexData0); + const CSG1 = CSG.FromVertexData(vertexData1); + switch (this.operation) { + case BooleanGeometryOperations.Intersect: + boolCSG = CSG0.intersect(CSG1); + break; + case BooleanGeometryOperations.Subtract: + boolCSG = CSG0.subtract(CSG1); + break; + case BooleanGeometryOperations.Union: + boolCSG = CSG0.union(CSG1); + break; + } + } + else { + const CSG0 = CSG2.FromVertexData(vertexData0); + const CSG1 = CSG2.FromVertexData(vertexData1); + switch (this.operation) { + case BooleanGeometryOperations.Intersect: + boolCSG = CSG0.intersect(CSG1); + break; + case BooleanGeometryOperations.Subtract: + boolCSG = CSG0.subtract(CSG1); + break; + case BooleanGeometryOperations.Union: + boolCSG = CSG0.add(CSG1); + break; + } + } + return boolCSG.toVertexData(); + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + codeString += `${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${BooleanGeometryOperations[this.operation]};\n`; + codeString += `${this._codeVariableName}.useOldCSGEngine = ${this.useOldCSGEngine ? "true" : "false"};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + serializationObject.operation = this.operation; + serializationObject.useOldCSGEngine = this.useOldCSGEngine; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.evaluateContext = serializationObject.evaluateContext; + if (serializationObject.operation) { + this.operation = serializationObject.operation; + } + this.useOldCSGEngine = !!serializationObject.useOldCSGEngine; + } +} +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], BooleanGeometryBlock.prototype, "evaluateContext", void 0); +__decorate([ + editableInPropertyPage("Operation", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "Intersect", value: BooleanGeometryOperations.Intersect }, + { label: "Subtract", value: BooleanGeometryOperations.Subtract }, + { label: "Union", value: BooleanGeometryOperations.Union }, + ], + }) +], BooleanGeometryBlock.prototype, "operation", void 0); +__decorate([ + editableInPropertyPage("Use old CSG engine", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], BooleanGeometryBlock.prototype, "useOldCSGEngine", void 0); +RegisterClass("BABYLON.BooleanGeometryBlock", BooleanGeometryBlock); + +/** + * Block used to compute arc tangent of 2 values + */ +class GeometryArcTan2Block extends NodeGeometryBlock { + /** + * Creates a new GeometryArcTan2Block + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("x", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("y", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryArcTan2Block"; + } + /** + * Gets the x operand input component + */ + get x() { + return this._inputs[0]; + } + /** + * Gets the y operand input component + */ + get y() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.x.isConnected || !this.y.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (x, y) => { + return Math.atan2(x, y); + }; + this.output._storedFunction = (state) => { + const x = this.x.getConnectedValue(state); + const y = this.y.getConnectedValue(state); + switch (this.x.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + return func(x, y); + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + return new Vector2(func(x.x, y.x), func(x.y, y.y)); + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + return new Vector3(func(x.x, y.x), func(x.y, y.y), func(x.z, y.z)); + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + return new Vector4(func(x.x, y.x), func(x.y, y.y), func(x.z, y.z), func(x.w, y.w)); + } + } + return 0; + }; + } +} +RegisterClass("BABYLON.GeometryArcTan2Block", GeometryArcTan2Block); + +/** + * Block used to lerp between 2 values + */ +class GeometryLerpBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryLerpBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("gradient", NodeGeometryBlockConnectionPointTypes.Float, true, 0, 0, 1); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryLerpBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the gradient operand input component + */ + get gradient() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.left.isConnected || !this.right.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (gradient, left, right) => { + return (1 - gradient) * left + gradient * right; + }; + this.output._storedFunction = (state) => { + const left = this.left.getConnectedValue(state); + const right = this.right.getConnectedValue(state); + const gradient = this.gradient.getConnectedValue(state); + switch (this.left.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + return func(gradient, left, right); + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + return new Vector2(func(gradient, left.x, right.x), func(gradient, left.y, right.y)); + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + return new Vector3(func(gradient, left.x, right.x), func(gradient, left.y, right.y), func(gradient, left.z, right.z)); + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + return new Vector4(func(gradient, left.x, right.x), func(gradient, left.y, right.y), func(gradient, left.z, right.z), func(gradient, left.w, right.w)); + } + } + return 0; + }; + return this; + } +} +RegisterClass("BABYLON.GeometryLerpBlock", GeometryLerpBlock); + +/** + * Block used to normalize lerp between 2 values + */ +class GeometryNLerpBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryNLerpBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("gradient", NodeGeometryBlockConnectionPointTypes.Float, true, 0, 0, 1); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryNLerpBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the gradient operand input component + */ + get gradient() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.left.isConnected || !this.right.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (gradient, left, right) => { + return (1 - gradient) * left + gradient * right; + }; + this.output._storedFunction = (state) => { + const left = this.left.getConnectedValue(state); + const right = this.right.getConnectedValue(state); + const gradient = this.gradient.getConnectedValue(state); + switch (this.left.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + return func(gradient, left, right); // NLerp is really lerp in that case + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + const result = new Vector2(func(gradient, left.x, right.x), func(gradient, left.y, right.y)); + result.normalize(); + return result; + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + const result = new Vector3(func(gradient, left.x, right.x), func(gradient, left.y, right.y), func(gradient, left.z, right.z)); + result.normalize(); + return result; + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + const result = new Vector4(func(gradient, left.x, right.x), func(gradient, left.y, right.y), func(gradient, left.z, right.z), func(gradient, left.w, right.w)); + result.normalize(); + return result; + } + } + return 0; + }; + return this; + } +} +RegisterClass("BABYLON.GeometryNLerpBlock", GeometryNLerpBlock); + +/** + * Block used to step a value + */ +class GeometryStepBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryStepBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("edge", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryStepBlock"; + } + /** + * Gets the value operand input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the edge operand input component + */ + get edge() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.value.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (value, edge) => { + if (value < edge) { + return 0; + } + return 1; + }; + this.output._storedFunction = (state) => { + const source = this.value.getConnectedValue(state); + const edge = this.edge.getConnectedValue(state); + switch (this.value.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + return func(source, edge); + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + return new Vector2(func(source.x, edge), func(source.y, edge)); + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + return new Vector3(func(source.x, edge), func(source.y, edge), func(source.z, edge)); + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + return new Vector4(func(source.x, edge), func(source.y, edge), func(source.z, edge), func(source.w, edge)); + } + } + return 0; + }; + return this; + } +} +RegisterClass("BABYLON.GeometryStepBlock", GeometryStepBlock); + +/** + * Block used to smooth step a value + */ +class GeometrySmoothStepBlock extends NodeGeometryBlock { + /** + * Creates a new GeometrySmoothStepBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("edge0", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("edge1", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometrySmoothStepBlock"; + } + /** + * Gets the value operand input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the first edge operand input component + */ + get edge0() { + return this._inputs[1]; + } + /** + * Gets the second edge operand input component + */ + get edge1() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.value.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (value, edge0, edge1) => { + const x = Math.max(0, Math.min((value - edge0) / (edge1 - edge0), 1)); + // Smoothstep formula: 3x^2 - 2x^3 + return x * x * (3 - 2 * x); + }; + this.output._storedFunction = (state) => { + const source = this.value.getConnectedValue(state); + const edge0 = this.edge0.getConnectedValue(state); + const edge1 = this.edge1.getConnectedValue(state); + switch (this.value.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + return func(source, edge0, edge1); + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + return new Vector2(func(source.x, edge0, edge1), func(source.y, edge0, edge1)); + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + return new Vector3(func(source.x, edge0, edge1), func(source.y, edge0, edge1), func(source.z, edge0, edge1)); + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + return new Vector4(func(source.x, edge0, edge1), func(source.y, edge0, edge1), func(source.z, edge0, edge1), func(source.w, edge0, edge1)); + } + } + return 0; + }; + return this; + } +} +RegisterClass("BABYLON.GeometrySmoothStepBlock", GeometrySmoothStepBlock); + +/** + * Block used to compute value of one parameter modulo another + */ +class GeometryModBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryModBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryModBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.left.isConnected || !this.right.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (left, right) => { + return left - Math.floor(left / right) * right; + }; + this.output._storedFunction = (state) => { + const left = this.left.getConnectedValue(state); + const right = this.right.getConnectedValue(state); + switch (this.left.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + return func(left, right); + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + return new Vector2(func(left.x, right.x), func(left.y, right.y)); + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + return new Vector3(func(left.x, right.x), func(left.y, right.y), func(left.z, right.z)); + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + return new Vector4(func(left.x, right.x), func(left.y, right.y), func(left.z, right.z), func(left.w, right.w)); + } + } + return 0; + }; + return this; + } +} +RegisterClass("BABYLON.GeometryModBlock", GeometryModBlock); + +/** + * Block used to get the value of the first parameter raised to the power of the second + */ +class GeometryPowBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryPowBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("power", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryPowBlock"; + } + /** + * Gets the value operand input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the power operand input component + */ + get power() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.value.isConnected || !this.power.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (value, power) => { + return Math.pow(value, power); + }; + this.output._storedFunction = (state) => { + const source = this.value.getConnectedValue(state); + const power = this.power.getConnectedValue(state); + switch (this.value.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + return func(source, power); + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + return new Vector2(func(source.x, power), func(source.y, power)); + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + return new Vector3(func(source.x, power), func(source.y, power), func(source.z, power)); + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + return new Vector4(func(source.x, power), func(source.y, power), func(source.z, power), func(source.w, power)); + } + } + return 0; + }; + return this; + } +} +RegisterClass("BABYLON.GeometryPowBlock", GeometryPowBlock); + +/** + * Block used to clamp a float + */ +class GeometryClampBlock extends NodeGeometryBlock { + /** Gets or sets the minimum range */ + get minimum() { + return this.min.value; + } + set minimum(value) { + this.min.value = value; + } + /** Gets or sets the maximum range */ + get maximum() { + return this.max.value; + } + set maximum(value) { + this.max.value = value; + } + /** + * Creates a new GeometryClampBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("min", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("max", NodeGeometryBlockConnectionPointTypes.Float, true, 1); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryClampBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the min input component + */ + get min() { + return this._inputs[1]; + } + /** + * Gets the max input component + */ + get max() { + return this._inputs[2]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.value.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + const func = (value, min, max) => { + return Math.max(min, Math.min(value, max)); + }; + this.output._storedFunction = (state) => { + const value = this.value.getConnectedValue(state); + const min = this.min.isConnected ? this.min.getConnectedValue(state) : this.minimum; + const max = this.max.isConnected ? this.max.getConnectedValue(state) : this.maximum; + switch (this.value.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + return func(value, min, max); + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + return new Vector2(func(value.x, min, max), func(value.y, min, max)); + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + return new Vector3(func(value.x, min, max), func(value.y, min, max), func(value.z, min, max)); + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + return new Vector4(func(value.x, min, max), func(value.y, min, max), func(value.z, min, max), func(value.w, min, max)); + } + } + return 0; + }; + return this; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.minimum = serializationObject.minimum; + this.maximum = serializationObject.maximum; + } +} +RegisterClass("BABYLON.GeometryClampBlock", GeometryClampBlock); + +/** + * Block used to apply a cross product between 2 vectors + */ +class GeometryCrossBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryCrossBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Vector3); + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector2); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector2); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryCrossBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.left.isConnected || !this.right.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + this.output._storedFunction = (state) => { + const left = this.left.getConnectedValue(state); + const right = this.right.getConnectedValue(state); + switch (this.left.type) { + case NodeGeometryBlockConnectionPointTypes.Vector3: { + return Vector3.Cross(left, right); + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + return Vector3.Cross(left.toVector3(), right.toVector3()); + } + } + return 0; + }; + return this; + } +} +RegisterClass("BABYLON.GeometryCrossBlock", GeometryCrossBlock); + +/** + * Types of curves supported by the Curve block + */ +var GeometryCurveBlockTypes; +(function (GeometryCurveBlockTypes) { + /** EaseInSine */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInSine"] = 0] = "EaseInSine"; + /** EaseOutSine */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseOutSine"] = 1] = "EaseOutSine"; + /** EaseInOutSine */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInOutSine"] = 2] = "EaseInOutSine"; + /** EaseInQuad */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInQuad"] = 3] = "EaseInQuad"; + /** EaseOutQuad */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseOutQuad"] = 4] = "EaseOutQuad"; + /** EaseInOutQuad */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInOutQuad"] = 5] = "EaseInOutQuad"; + /** EaseInCubic */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInCubic"] = 6] = "EaseInCubic"; + /** EaseOutCubic */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseOutCubic"] = 7] = "EaseOutCubic"; + /** EaseInOutCubic */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInOutCubic"] = 8] = "EaseInOutCubic"; + /** EaseInQuart */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInQuart"] = 9] = "EaseInQuart"; + /** EaseOutQuart */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseOutQuart"] = 10] = "EaseOutQuart"; + /** EaseInOutQuart */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInOutQuart"] = 11] = "EaseInOutQuart"; + /** EaseInQuint */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInQuint"] = 12] = "EaseInQuint"; + /** EaseOutQuint */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseOutQuint"] = 13] = "EaseOutQuint"; + /** EaseInOutQuint */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInOutQuint"] = 14] = "EaseInOutQuint"; + /** EaseInExpo */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInExpo"] = 15] = "EaseInExpo"; + /** EaseOutExpo */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseOutExpo"] = 16] = "EaseOutExpo"; + /** EaseInOutExpo */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInOutExpo"] = 17] = "EaseInOutExpo"; + /** EaseInCirc */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInCirc"] = 18] = "EaseInCirc"; + /** EaseOutCirc */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseOutCirc"] = 19] = "EaseOutCirc"; + /** EaseInOutCirc */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInOutCirc"] = 20] = "EaseInOutCirc"; + /** EaseInBack */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInBack"] = 21] = "EaseInBack"; + /** EaseOutBack */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseOutBack"] = 22] = "EaseOutBack"; + /** EaseInOutBack */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInOutBack"] = 23] = "EaseInOutBack"; + /** EaseInElastic */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInElastic"] = 24] = "EaseInElastic"; + /** EaseOutElastic */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseOutElastic"] = 25] = "EaseOutElastic"; + /** EaseInOutElastic */ + GeometryCurveBlockTypes[GeometryCurveBlockTypes["EaseInOutElastic"] = 26] = "EaseInOutElastic"; +})(GeometryCurveBlockTypes || (GeometryCurveBlockTypes = {})); +/** + * Block used to apply curve operation + */ +class GeometryCurveBlock extends NodeGeometryBlock { + /** + * Creates a new CurveBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets the type of the curve applied by the block + */ + this.type = GeometryCurveBlockTypes.EaseInOutSine; + this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryCurveBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.input.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + let func; + switch (this.type) { + case GeometryCurveBlockTypes.EaseInSine: + func = (v) => 1.0 - Math.cos((v * 3.1415) / 2.0); + break; + case GeometryCurveBlockTypes.EaseOutSine: + func = (v) => Math.sin((v * 3.1415) / 2.0); + break; + case GeometryCurveBlockTypes.EaseInOutSine: + func = (v) => -(Math.cos(v * 3.1415) - 1.0) / 2.0; + break; + case GeometryCurveBlockTypes.EaseInQuad: + func = (v) => v * v; + break; + case GeometryCurveBlockTypes.EaseOutQuad: + func = (v) => (1.0 - v) * (1.0 - v); + break; + case GeometryCurveBlockTypes.EaseInOutQuad: { + func = (v) => (v < 0.5 ? 2.0 * v * v : 1.0 - Math.pow(-2 * v + 2.0, 2.0) / 2.0); + break; + } + case GeometryCurveBlockTypes.EaseInCubic: + func = (v) => v * v * v; + break; + case GeometryCurveBlockTypes.EaseOutCubic: { + func = (v) => 1.0 - Math.pow(1.0 - v, 3.0); + break; + } + case GeometryCurveBlockTypes.EaseInOutCubic: { + func = (v) => (v < 0.5 ? 4.0 * v * v * v : 1.0 - Math.pow(-2 * v + 2.0, 3.0) / 2.0); + break; + } + case GeometryCurveBlockTypes.EaseInQuart: + func = (v) => v * v * v * v; + break; + case GeometryCurveBlockTypes.EaseOutQuart: { + func = (v) => 1.0 - Math.pow(1.0 - v, 4.0); + break; + } + case GeometryCurveBlockTypes.EaseInOutQuart: { + func = (v) => (v < 0.5 ? 8.0 * v * v * v * v : 1.0 - Math.pow(-2 * v + 2.0, 4.0) / 2.0); + break; + } + case GeometryCurveBlockTypes.EaseInQuint: + func = (v) => v * v * v * v * v; + break; + case GeometryCurveBlockTypes.EaseOutQuint: { + func = (v) => 1.0 - Math.pow(1.0 - v, 5.0); + break; + } + case GeometryCurveBlockTypes.EaseInOutQuint: { + func = (v) => (v < 0.5 ? 16.0 * v * v * v * v * v : 1.0 - Math.pow(-2 * v + 2.0, 5.0) / 2.0); + break; + } + case GeometryCurveBlockTypes.EaseInExpo: { + func = (v) => (v === 0.0 ? 0.0 : Math.pow(2.0, 10.0 * v - 10.0)); + break; + } + case GeometryCurveBlockTypes.EaseOutExpo: { + func = (v) => (v === 1.0 ? 1.0 : 1.0 - Math.pow(2.0, -10 * v)); + break; + } + case GeometryCurveBlockTypes.EaseInOutExpo: { + func = (v) => (v === 0.0 ? 0.0 : v === 1.0 ? 1.0 : v < 0.5 ? Math.pow(2.0, 20.0 * v - 10.0) / 2.0 : (2.0 - Math.pow(2.0, -20 * v + 10.0)) / 2.0); + break; + } + case GeometryCurveBlockTypes.EaseInCirc: { + func = (v) => 1.0 - Math.sqrt(1.0 - Math.pow(v, 2.0)); + break; + } + case GeometryCurveBlockTypes.EaseOutCirc: { + func = (v) => Math.sqrt(1.0 - Math.pow(v - 1.0, 2.0)); + break; + } + case GeometryCurveBlockTypes.EaseInOutCirc: { + func = (v) => (v < 0.5 ? (1.0 - Math.sqrt(1.0 - Math.pow(2.0 * v, 2.0))) / 2.0 : (Math.sqrt(1.0 - Math.pow(-2 * v + 2.0, 2.0)) + 1.0) / 2.0); + break; + } + case GeometryCurveBlockTypes.EaseInBack: { + func = (v) => 2.70158 * v * v * v - 1.70158 * v * v; + break; + } + case GeometryCurveBlockTypes.EaseOutBack: { + func = (v) => 2.70158 * Math.pow(v - 1.0, 3.0) + 1.70158 * Math.pow(v - 1.0, 2.0); + break; + } + case GeometryCurveBlockTypes.EaseInOutBack: { + func = (v) => v < 0.5 + ? (Math.pow(2.0 * v, 2.0) * (3.5949095 * 2.0 * v - 2.5949095)) / 2.0 + : (Math.pow(2.0 * v - 2.0, 2.0) * (3.5949095 * (v * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0; + break; + } + case GeometryCurveBlockTypes.EaseInElastic: { + func = (v) => (v === 0.0 ? 0.0 : v === 1.0 ? 1.0 : -Math.pow(2.0, 10.0 * v - 10.0) * Math.sin((v * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))); + break; + } + case GeometryCurveBlockTypes.EaseOutElastic: { + func = (v) => (v === 0.0 ? 0.0 : v === 1.0 ? 1.0 : Math.pow(2.0, -10 * v) * Math.sin((v * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0); + break; + } + case GeometryCurveBlockTypes.EaseInOutElastic: { + func = (v) => v === 0.0 + ? 0.0 + : v == 1.0 + ? 1.0 + : v < 0.5 + ? -(Math.pow(2.0, 20.0 * v - 10.0) * Math.sin((20.0 * v - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + : (Math.pow(2.0, -20 * v + 10.0) * Math.sin((20.0 * v - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0; + break; + } + } + this.output._storedFunction = (state) => { + const input = this.input.getConnectedValue(state); + switch (this.input.type) { + case NodeGeometryBlockConnectionPointTypes.Float: { + return func(input); + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + return new Vector2(func(input.x), func(input.y)); + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + return new Vector3(func(input.x), func(input.y), func(input.z)); + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + return new Vector4(func(input.x), func(input.y), func(input.z), func(input.w)); + } + } + return 0; + }; + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.curveType = this.type; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.type = serializationObject.curveType; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${GeometryCurveBlockTypes[this.type]};\n`; + return codeString; + } +} +__decorate([ + editableInPropertyPage("Type", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "EaseInSine", value: GeometryCurveBlockTypes.EaseInSine }, + { label: "EaseOutSine", value: GeometryCurveBlockTypes.EaseOutSine }, + { label: "EaseInOutSine", value: GeometryCurveBlockTypes.EaseInOutSine }, + { label: "EaseInQuad", value: GeometryCurveBlockTypes.EaseInQuad }, + { label: "EaseOutQuad", value: GeometryCurveBlockTypes.EaseOutQuad }, + { label: "EaseInOutQuad", value: GeometryCurveBlockTypes.EaseInOutQuad }, + { label: "EaseInCubic", value: GeometryCurveBlockTypes.EaseInCubic }, + { label: "EaseOutCubic", value: GeometryCurveBlockTypes.EaseOutCubic }, + { label: "EaseInOutCubic", value: GeometryCurveBlockTypes.EaseInOutCubic }, + { label: "EaseInQuart", value: GeometryCurveBlockTypes.EaseInQuart }, + { label: "EaseOutQuart", value: GeometryCurveBlockTypes.EaseOutQuart }, + { label: "EaseInOutQuart", value: GeometryCurveBlockTypes.EaseInOutQuart }, + { label: "EaseInQuint", value: GeometryCurveBlockTypes.EaseInQuint }, + { label: "EaseOutQuint", value: GeometryCurveBlockTypes.EaseOutQuint }, + { label: "EaseInOutQuint", value: GeometryCurveBlockTypes.EaseInOutQuint }, + { label: "EaseInExpo", value: GeometryCurveBlockTypes.EaseInExpo }, + { label: "EaseOutExpo", value: GeometryCurveBlockTypes.EaseOutExpo }, + { label: "EaseInOutExpo", value: GeometryCurveBlockTypes.EaseInOutExpo }, + { label: "EaseInCirc", value: GeometryCurveBlockTypes.EaseInCirc }, + { label: "EaseOutCirc", value: GeometryCurveBlockTypes.EaseOutCirc }, + { label: "EaseInOutCirc", value: GeometryCurveBlockTypes.EaseInOutCirc }, + { label: "EaseInBack", value: GeometryCurveBlockTypes.EaseInBack }, + { label: "EaseOutBack", value: GeometryCurveBlockTypes.EaseOutBack }, + { label: "EaseInOutBack", value: GeometryCurveBlockTypes.EaseInOutBack }, + { label: "EaseInElastic", value: GeometryCurveBlockTypes.EaseInElastic }, + { label: "EaseOutElastic", value: GeometryCurveBlockTypes.EaseOutElastic }, + { label: "EaseInOutElastic", value: GeometryCurveBlockTypes.EaseInOutElastic }, + ], + }) +], GeometryCurveBlock.prototype, "type", void 0); +RegisterClass("BABYLON.GeometryCurveBlock", GeometryCurveBlock); + +/** + * Block used to desaturate a color + */ +class GeometryDesaturateBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryDesaturateBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("color", NodeGeometryBlockConnectionPointTypes.Vector3); + this.registerInput("level", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Vector3); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryDesaturateBlock"; + } + /** + * Gets the color operand input component + */ + get color() { + return this._inputs[0]; + } + /** + * Gets the level operand input component + */ + get level() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.color.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + this.output._storedFunction = (state) => { + const color = this.color.getConnectedValue(state); + const level = this.level.getConnectedValue(state); + const tempMin = Math.min(color.x, color.y, color.z); + const tempMax = Math.max(color.x, color.y, color.z); + const tempMerge = 0.5 * (tempMin + tempMax); + return new Vector3(color.x * (1 - level) + tempMerge * level, color.y * (1 - level) + tempMerge * level, color.z * (1 - level) + tempMerge * level); + }; + return this; + } +} +RegisterClass("BABYLON.GeometryDesaturateBlock", GeometryDesaturateBlock); + +/** + * Block used to posterize a value + * @see https://en.wikipedia.org/wiki/Posterization + */ +class GeometryPosterizeBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryPosterizeBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("steps", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[1].acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryPosterizeBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the steps input component + */ + get steps() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.value.isConnected || !this.steps.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + this.output._storedFunction = (state) => { + const source = this.value.getConnectedValue(state); + const steps = this.steps.getConnectedValue(state); + let stepVector = steps; + if (this.steps.type === NodeGeometryBlockConnectionPointTypes.Float) { + switch (this.value.type) { + case NodeGeometryBlockConnectionPointTypes.Vector2: + stepVector = new Vector2(steps, steps); + break; + case NodeGeometryBlockConnectionPointTypes.Vector3: + stepVector = new Vector3(steps, steps, steps); + break; + case NodeGeometryBlockConnectionPointTypes.Vector4: + stepVector = new Vector4(steps, steps, steps, steps); + break; + } + } + switch (this.value.type) { + case NodeGeometryBlockConnectionPointTypes.Vector2: + return new Vector2((source.x / (1.0 / stepVector.x)) * (1.0 / stepVector.x), (source.y / (1.0 / stepVector.y)) * (1.0 / stepVector.y)); + case NodeGeometryBlockConnectionPointTypes.Vector3: + return new Vector3((source.x / (1.0 / stepVector.x)) * (1.0 / stepVector.x), (source.y / (1.0 / stepVector.y)) * (1.0 / stepVector.y), (source.z / (1.0 / stepVector.z)) * (1.0 / stepVector.z)); + case NodeGeometryBlockConnectionPointTypes.Vector4: + return new Vector4((source.x / (1.0 / stepVector.x)) * (1.0 / stepVector.x), (source.y / (1.0 / stepVector.y)) * (1.0 / stepVector.y), (source.z / (1.0 / stepVector.z)) * (1.0 / stepVector.z), (source.w / (1.0 / stepVector.w)) * (1.0 / stepVector.w)); + default: + return Math.floor((source / (1.0 / steps)) * (1.0 / steps)); + } + }; + return this; + } +} +RegisterClass("BABYLON.GeometryPosterizeBlock", GeometryPosterizeBlock); + +/** + * Block used to replace a color by another one + */ +class GeometryReplaceColorBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryReplaceColorBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("reference", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("distance", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerInput("replacement", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._linkConnectionTypes(0, 1); + this._linkConnectionTypes(0, 3); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[3].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[3].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryReplaceColorBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the reference input component + */ + get reference() { + return this._inputs[1]; + } + /** + * Gets the distance input component + */ + get distance() { + return this._inputs[2]; + } + /** + * Gets the replacement input component + */ + get replacement() { + return this._inputs[3]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.value.isConnected || !this.reference.isConnected || !this.replacement.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + this.output._storedFunction = (state) => { + const value = this.value.getConnectedValue(state); + const reference = this.reference.getConnectedValue(state); + const distance = this.distance.getConnectedValue(state); + const replacement = this.replacement.getConnectedValue(state); + if (value.subtract(reference).length() < distance) { + return replacement; + } + else { + return value; + } + }; + return this; + } +} +RegisterClass("BABYLON.GeometryReplaceColorBlock", GeometryReplaceColorBlock); + +/** + * Block used to get the distance between 2 values + */ +class GeometryDistanceBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryDistanceBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Float); + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryDistanceBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.left.isConnected || !this.right.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + this.output._storedFunction = (state) => { + const left = this.left.getConnectedValue(state); + const right = this.right.getConnectedValue(state); + return left.subtract(right).length(); + }; + return this; + } +} +RegisterClass("BABYLON.GeometryDistanceBlock", GeometryDistanceBlock); + +/** + * Block used to apply a dot product between 2 vectors + */ +class GeometryDotBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryDotBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Float); + this._linkConnectionTypes(0, 1); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryDotBlock"; + } + /** + * Gets the left operand input component + */ + get left() { + return this._inputs[0]; + } + /** + * Gets the right operand input component + */ + get right() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.left.isConnected || !this.right.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + this.output._storedFunction = (state) => { + const left = this.left.getConnectedValue(state); + const right = this.right.getConnectedValue(state); + return left.dot(right); + }; + return this; + } +} +RegisterClass("BABYLON.GeometryDotBlock", GeometryDotBlock); + +/** + * Block used to get the length of a vector + */ +class GeometryLengthBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryLengthBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryLengthBlock"; + } + /** + * Gets the value input component + */ + get value() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.value.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + this.output._storedFunction = (state) => { + const value = this.value.getConnectedValue(state); + return value.length(); + }; + return this; + } +} +RegisterClass("BABYLON.GeometryLengthBlock", GeometryLengthBlock); + +/** + * Block used to rotate a 2d vector by a given angle + */ +class GeometryRotate2dBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryRotate2dBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this.registerInput("input", NodeGeometryBlockConnectionPointTypes.Vector2); + this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, true, 0); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Vector2); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryRotate2dBlock"; + } + /** + * Gets the input vector + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the input angle + */ + get angle() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + if (!this.input.isConnected) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + this.output._storedFunction = (state) => { + const input = this.input.getConnectedValue(state); + const angle = this.angle.getConnectedValue(state); + return new Vector2(Math.cos(angle) * input.x - Math.sin(angle) * input.y, Math.sin(angle) * input.x + Math.cos(angle) * input.y); + }; + return this; + } +} +RegisterClass("BABYLON.GeometryRotate2dBlock", GeometryRotate2dBlock); + +/** + * Block used to trigger an observable when traversed + * It can also be used to execute a function when traversed + */ +class GeometryInterceptorBlock extends NodeGeometryBlock { + /** + * Creates a new GeometryInterceptorBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Observable triggered when the block is traversed + */ + this.onInterceptionObservable = new Observable(undefined, true); + this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + } + /** + * Gets the time spent to build this block (in ms) + */ + get buildExecutionTime() { + return -1; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryInterceptorBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + const output = this._outputs[0]; + const input = this._inputs[0]; + output._storedFunction = (state) => { + let value = input.getConnectedValue(state); + if (this.customFunction) { + value = this.customFunction(value, state); + } + this.onInterceptionObservable.notifyObservers(value); + return value; + }; + } +} +RegisterClass("BABYLON.GeometryInterceptorBlock", GeometryInterceptorBlock); + +/** + * Types of easing function supported by the Ease block + */ +var GeometryEaseBlockTypes; +(function (GeometryEaseBlockTypes) { + /** EaseInSine */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInSine"] = 0] = "EaseInSine"; + /** EaseOutSine */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseOutSine"] = 1] = "EaseOutSine"; + /** EaseInOutSine */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInOutSine"] = 2] = "EaseInOutSine"; + /** EaseInQuad */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInQuad"] = 3] = "EaseInQuad"; + /** EaseOutQuad */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseOutQuad"] = 4] = "EaseOutQuad"; + /** EaseInOutQuad */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInOutQuad"] = 5] = "EaseInOutQuad"; + /** EaseInCubic */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInCubic"] = 6] = "EaseInCubic"; + /** EaseOutCubic */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseOutCubic"] = 7] = "EaseOutCubic"; + /** EaseInOutCubic */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInOutCubic"] = 8] = "EaseInOutCubic"; + /** EaseInQuart */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInQuart"] = 9] = "EaseInQuart"; + /** EaseOutQuart */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseOutQuart"] = 10] = "EaseOutQuart"; + /** EaseInOutQuart */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInOutQuart"] = 11] = "EaseInOutQuart"; + /** EaseInQuint */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInQuint"] = 12] = "EaseInQuint"; + /** EaseOutQuint */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseOutQuint"] = 13] = "EaseOutQuint"; + /** EaseInOutQuint */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInOutQuint"] = 14] = "EaseInOutQuint"; + /** EaseInExpo */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInExpo"] = 15] = "EaseInExpo"; + /** EaseOutExpo */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseOutExpo"] = 16] = "EaseOutExpo"; + /** EaseInOutExpo */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInOutExpo"] = 17] = "EaseInOutExpo"; + /** EaseInCirc */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInCirc"] = 18] = "EaseInCirc"; + /** EaseOutCirc */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseOutCirc"] = 19] = "EaseOutCirc"; + /** EaseInOutCirc */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInOutCirc"] = 20] = "EaseInOutCirc"; + /** EaseInBack */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInBack"] = 21] = "EaseInBack"; + /** EaseOutBack */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseOutBack"] = 22] = "EaseOutBack"; + /** EaseInOutBack */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInOutBack"] = 23] = "EaseInOutBack"; + /** EaseInElastic */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInElastic"] = 24] = "EaseInElastic"; + /** EaseOutElastic */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseOutElastic"] = 25] = "EaseOutElastic"; + /** EaseInOutElastic */ + GeometryEaseBlockTypes[GeometryEaseBlockTypes["EaseInOutElastic"] = 26] = "EaseInOutElastic"; +})(GeometryEaseBlockTypes || (GeometryEaseBlockTypes = {})); +/** + * Block used to apply an easing function to floats + */ +class GeometryEaseBlock extends NodeGeometryBlock { + /** + * Gets or sets the type of the easing functions applied by the block + */ + get type() { + return this._type; + } + set type(value) { + if (this._type === value) { + return; + } + this._type = value; + switch (this._type) { + case GeometryEaseBlockTypes.EaseInSine: + this._easingFunction = new SineEase(); + this._easingFunction.setEasingMode(SineEase.EASINGMODE_EASEIN); + break; + case GeometryEaseBlockTypes.EaseOutSine: + this._easingFunction = new SineEase(); + this._easingFunction.setEasingMode(SineEase.EASINGMODE_EASEOUT); + break; + case GeometryEaseBlockTypes.EaseInOutSine: + this._easingFunction = new SineEase(); + this._easingFunction.setEasingMode(SineEase.EASINGMODE_EASEINOUT); + break; + case GeometryEaseBlockTypes.EaseInQuad: + this._easingFunction = new QuadraticEase(); + this._easingFunction.setEasingMode(QuadraticEase.EASINGMODE_EASEIN); + break; + case GeometryEaseBlockTypes.EaseOutQuad: + this._easingFunction = new QuadraticEase(); + this._easingFunction.setEasingMode(QuadraticEase.EASINGMODE_EASEOUT); + break; + case GeometryEaseBlockTypes.EaseInOutQuad: + this._easingFunction = new QuadraticEase(); + this._easingFunction.setEasingMode(QuadraticEase.EASINGMODE_EASEINOUT); + break; + case GeometryEaseBlockTypes.EaseInCubic: + this._easingFunction = new CubicEase(); + this._easingFunction.setEasingMode(CubicEase.EASINGMODE_EASEIN); + break; + case GeometryEaseBlockTypes.EaseOutCubic: + this._easingFunction = new CubicEase(); + this._easingFunction.setEasingMode(CubicEase.EASINGMODE_EASEOUT); + break; + case GeometryEaseBlockTypes.EaseInOutCubic: + this._easingFunction = new CubicEase(); + this._easingFunction.setEasingMode(CubicEase.EASINGMODE_EASEINOUT); + break; + case GeometryEaseBlockTypes.EaseInQuart: + this._easingFunction = new QuarticEase(); + this._easingFunction.setEasingMode(QuarticEase.EASINGMODE_EASEIN); + break; + case GeometryEaseBlockTypes.EaseOutQuart: + this._easingFunction = new QuarticEase(); + this._easingFunction.setEasingMode(QuarticEase.EASINGMODE_EASEOUT); + break; + case GeometryEaseBlockTypes.EaseInOutQuart: + this._easingFunction = new QuarticEase(); + this._easingFunction.setEasingMode(QuarticEase.EASINGMODE_EASEINOUT); + break; + case GeometryEaseBlockTypes.EaseInQuint: + this._easingFunction = new QuinticEase(); + this._easingFunction.setEasingMode(QuinticEase.EASINGMODE_EASEIN); + break; + case GeometryEaseBlockTypes.EaseOutQuint: + this._easingFunction = new QuinticEase(); + this._easingFunction.setEasingMode(QuinticEase.EASINGMODE_EASEOUT); + break; + case GeometryEaseBlockTypes.EaseInOutQuint: + this._easingFunction = new QuinticEase(); + this._easingFunction.setEasingMode(QuinticEase.EASINGMODE_EASEINOUT); + break; + case GeometryEaseBlockTypes.EaseInExpo: + this._easingFunction = new ExponentialEase(); + this._easingFunction.setEasingMode(ExponentialEase.EASINGMODE_EASEIN); + break; + case GeometryEaseBlockTypes.EaseOutExpo: + this._easingFunction = new ExponentialEase(); + this._easingFunction.setEasingMode(ExponentialEase.EASINGMODE_EASEOUT); + break; + case GeometryEaseBlockTypes.EaseInOutExpo: + this._easingFunction = new ExponentialEase(); + this._easingFunction.setEasingMode(ExponentialEase.EASINGMODE_EASEINOUT); + break; + case GeometryEaseBlockTypes.EaseInCirc: + this._easingFunction = new CircleEase(); + this._easingFunction.setEasingMode(CircleEase.EASINGMODE_EASEIN); + break; + case GeometryEaseBlockTypes.EaseOutCirc: + this._easingFunction = new CircleEase(); + this._easingFunction.setEasingMode(CircleEase.EASINGMODE_EASEOUT); + break; + case GeometryEaseBlockTypes.EaseInOutCirc: + this._easingFunction = new CircleEase(); + this._easingFunction.setEasingMode(CircleEase.EASINGMODE_EASEINOUT); + break; + case GeometryEaseBlockTypes.EaseInBack: + this._easingFunction = new BackEase(); + this._easingFunction.setEasingMode(BackEase.EASINGMODE_EASEIN); + break; + case GeometryEaseBlockTypes.EaseOutBack: + this._easingFunction = new BackEase(); + this._easingFunction.setEasingMode(BackEase.EASINGMODE_EASEOUT); + break; + case GeometryEaseBlockTypes.EaseInOutBack: + this._easingFunction = new BackEase(); + this._easingFunction.setEasingMode(BackEase.EASINGMODE_EASEINOUT); + break; + case GeometryEaseBlockTypes.EaseInElastic: + this._easingFunction = new ElasticEase(); + this._easingFunction.setEasingMode(ElasticEase.EASINGMODE_EASEIN); + break; + case GeometryEaseBlockTypes.EaseOutElastic: + this._easingFunction = new ElasticEase(); + this._easingFunction.setEasingMode(ElasticEase.EASINGMODE_EASEOUT); + break; + case GeometryEaseBlockTypes.EaseInOutElastic: + this._easingFunction = new ElasticEase(); + this._easingFunction.setEasingMode(ElasticEase.EASINGMODE_EASEINOUT); + break; + } + } + /** + * Creates a new GeometryEaseBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + this._easingFunction = new SineEase(); + this._type = GeometryEaseBlockTypes.EaseInOutSine; + this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[0]; + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); + this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "GeometryEaseBlock"; + } + /** + * Gets the input component + */ + get input() { + return this._inputs[0]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + super._buildBlock(state); + if (!this._easingFunction) { + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + switch (this.input.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + this.output._storedFunction = (state) => { + const source = this.input.getConnectedValue(state); + return this._easingFunction.ease(source); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + this.output._storedFunction = (state) => { + const source = this.input.getConnectedValue(state); + return new Vector2(this._easingFunction.ease(source.x), this._easingFunction.ease(source.y)); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + this.output._storedFunction = (state) => { + const source = this.input.getConnectedValue(state); + return new Vector3(this._easingFunction.ease(source.x), this._easingFunction.ease(source.y), this._easingFunction.ease(source.z)); + }; + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + this.output._storedFunction = (state) => { + const source = this.input.getConnectedValue(state); + return new Vector4(this._easingFunction.ease(source.x), this._easingFunction.ease(source.y), this._easingFunction.ease(source.z), this._easingFunction.ease(source.w)); + }; + break; + } + } + return this; + } + serialize() { + const serializationObject = super.serialize(); + serializationObject.type = this.type; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.type = serializationObject.type; + } + _dumpPropertiesCode() { + const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.type = BABYLON.GeometryEaseBlockTypes.${GeometryEaseBlockTypes[this.type]};\n`; + return codeString; + } +} +__decorate([ + editableInPropertyPage("Type", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "EaseInSine", value: GeometryEaseBlockTypes.EaseInSine }, + { label: "EaseOutSine", value: GeometryEaseBlockTypes.EaseOutSine }, + { label: "EaseInOutSine", value: GeometryEaseBlockTypes.EaseInOutSine }, + { label: "EaseInQuad", value: GeometryEaseBlockTypes.EaseInQuad }, + { label: "EaseOutQuad", value: GeometryEaseBlockTypes.EaseOutQuad }, + { label: "EaseInOutQuad", value: GeometryEaseBlockTypes.EaseInOutQuad }, + { label: "EaseInCubic", value: GeometryEaseBlockTypes.EaseInCubic }, + { label: "EaseOutCubic", value: GeometryEaseBlockTypes.EaseOutCubic }, + { label: "EaseInOutCubic", value: GeometryEaseBlockTypes.EaseInOutCubic }, + { label: "EaseInQuart", value: GeometryEaseBlockTypes.EaseInQuart }, + { label: "EaseOutQuart", value: GeometryEaseBlockTypes.EaseOutQuart }, + { label: "EaseInOutQuart", value: GeometryEaseBlockTypes.EaseInOutQuart }, + { label: "EaseInQuint", value: GeometryEaseBlockTypes.EaseInQuint }, + { label: "EaseOutQuint", value: GeometryEaseBlockTypes.EaseOutQuint }, + { label: "EaseInOutQuint", value: GeometryEaseBlockTypes.EaseInOutQuint }, + { label: "EaseInExpo", value: GeometryEaseBlockTypes.EaseInExpo }, + { label: "EaseOutExpo", value: GeometryEaseBlockTypes.EaseOutExpo }, + { label: "EaseInOutExpo", value: GeometryEaseBlockTypes.EaseInOutExpo }, + { label: "EaseInCirc", value: GeometryEaseBlockTypes.EaseInCirc }, + { label: "EaseOutCirc", value: GeometryEaseBlockTypes.EaseOutCirc }, + { label: "EaseInOutCirc", value: GeometryEaseBlockTypes.EaseInOutCirc }, + { label: "EaseInBack", value: GeometryEaseBlockTypes.EaseInBack }, + { label: "EaseOutBack", value: GeometryEaseBlockTypes.EaseOutBack }, + { label: "EaseInOutBack", value: GeometryEaseBlockTypes.EaseInOutBack }, + { label: "EaseInElastic", value: GeometryEaseBlockTypes.EaseInElastic }, + { label: "EaseOutElastic", value: GeometryEaseBlockTypes.EaseOutElastic }, + { label: "EaseInOutElastic", value: GeometryEaseBlockTypes.EaseInOutElastic }, + ], + }) +], GeometryEaseBlock.prototype, "type", null); +RegisterClass("BABYLON.GeometryEaseBlock", GeometryEaseBlock); + +/** + * Conditions supported by the condition block + */ +var Aggregations; +(function (Aggregations) { + /** Max */ + Aggregations[Aggregations["Max"] = 0] = "Max"; + /** Min */ + Aggregations[Aggregations["Min"] = 1] = "Min"; + /** Sum */ + Aggregations[Aggregations["Sum"] = 2] = "Sum"; +})(Aggregations || (Aggregations = {})); +/** + * Block used to extract a valuefrom a geometry + */ +class AggregatorBlock extends NodeGeometryBlock { + /** + * Create a new SetPositionsBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets the test used by the block + */ + this.aggregation = Aggregations.Sum; + /** + * Gets or sets a boolean indicating that this block can evaluate context + * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change + */ + this.evaluateContext = true; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("source", NodeGeometryBlockConnectionPointTypes.AutoDetect); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); + this._outputs[0]._typeConnectionSource = this._inputs[1]; + } + /** + * Gets the current index in the current flow + * @returns the current index + */ + getExecutionIndex() { + return this._currentIndex; + } + /** + * Gets the current loop index in the current flow + * @returns the current loop index + */ + getExecutionLoopIndex() { + return this._currentIndex; + } + /** + * Gets the current face index in the current flow + * @returns the current face index + */ + getExecutionFaceIndex() { + return 0; + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "AggregatorBlock"; + } + /** + * Gets the geometry input component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the source input component + */ + get source() { + return this._inputs[1]; + } + /** + * Gets the geometry output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock(state) { + const func = (state) => { + state.pushExecutionContext(this); + this._vertexData = this.geometry.getConnectedValue(state); + state.pushGeometryContext(this._vertexData); + if (!this._vertexData || !this._vertexData.positions || !this.source.isConnected) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedValue = null; + return; + } + // Processing + const vertexCount = this._vertexData.positions.length / 3; + const context = []; + for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { + context.push(this.source.getConnectedValue(state)); + } + // Aggregation + let func = null; + switch (this.aggregation) { + case Aggregations.Max: { + func = (a, b) => Math.max(a, b); + break; + } + case Aggregations.Min: { + func = (a, b) => Math.min(a, b); + break; + } + case Aggregations.Sum: { + func = (a, b) => a + b; + break; + } + } + if (!func) { + state.restoreGeometryContext(); + state.restoreExecutionContext(); + this.output._storedFunction = null; + this.output._storedValue = null; + return; + } + let returnValue; + switch (this.source.type) { + case NodeGeometryBlockConnectionPointTypes.Int: + case NodeGeometryBlockConnectionPointTypes.Float: { + returnValue = context.reduce(func); + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector2: { + const x = context.map((v) => v.x).reduce(func); + const y = context.map((v) => v.y).reduce(func); + returnValue = new Vector2(x, y); + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector3: { + const x = context.map((v) => v.x).reduce(func); + const y = context.map((v) => v.y).reduce(func); + const z = context.map((v) => v.z).reduce(func); + returnValue = new Vector3(x, y, z); + break; + } + case NodeGeometryBlockConnectionPointTypes.Vector4: { + const x = context.map((v) => v.x).reduce(func); + const y = context.map((v) => v.y).reduce(func); + const z = context.map((v) => v.z).reduce(func); + const w = context.map((v) => v.w).reduce(func); + returnValue = new Vector4(x, y, z, w); + break; + } + } + // Storage + state.restoreGeometryContext(); + state.restoreExecutionContext(); + return returnValue; + }; + if (this.evaluateContext) { + this.output._storedFunction = func; + } + else { + this.output._storedFunction = null; + this.output._storedValue = func(state); + } + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; + codeString += `${this._codeVariableName}.aggregation = BABYLON.Aggregations.${Aggregations[this.aggregation]};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.evaluateContext = this.evaluateContext; + serializationObject.aggregation = this.aggregation; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + if (serializationObject.evaluateContext !== undefined) { + this.evaluateContext = serializationObject.evaluateContext; + } + if (serializationObject.aggregation !== undefined) { + this.aggregation = serializationObject.aggregation; + } + } +} +__decorate([ + editableInPropertyPage("Aggregation", 4 /* PropertyTypeForEdition.List */, "ADVANCED", { + notifiers: { rebuild: true }, + embedded: true, + options: [ + { label: "Max", value: Aggregations.Max }, + { label: "Min", value: Aggregations.Min }, + { label: "Sum", value: Aggregations.Sum }, + ], + }) +], AggregatorBlock.prototype, "aggregation", void 0); +__decorate([ + editableInPropertyPage("Evaluate context", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { notifiers: { rebuild: true } }) +], AggregatorBlock.prototype, "evaluateContext", void 0); +RegisterClass("BABYLON.AggregatorBlock", AggregatorBlock); + +/** + * Block used to subdivide for a geometry using Catmull-Clark algorithm + */ +class SubdivideBlock extends NodeGeometryBlock { + /** + * Creates a new ComputeNormalsBlock + * @param name defines the block name + */ + constructor(name) { + super(name); + /** + * Gets or sets a boolean indicating that this block can evaluate context + */ + this.flatOnly = false; + /** + * Gets or sets a float defining the loop weight. i.e how much to weigh favoring heavy corners vs favoring Loop's formula + */ + this.loopWeight = 1.0; + this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); + this.registerInput("level", NodeGeometryBlockConnectionPointTypes.Int, true, 1, 0, 8); + this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); + } + /** + * Gets the current class name + * @returns the class name + */ + getClassName() { + return "SubdivideBlock"; + } + /** + * Gets the geometry component + */ + get geometry() { + return this._inputs[0]; + } + /** + * Gets the level component + */ + get level() { + return this._inputs[1]; + } + /** + * Gets the output component + */ + get output() { + return this._outputs[0]; + } + _buildBlock() { + this.output._storedFunction = (state) => { + if (!this.geometry.isConnected) { + return null; + } + const vertexData = this.geometry.getConnectedValue(state); + if (!vertexData) { + return null; + } + const level = this.level.getConnectedValue(state); + return Subdivide(vertexData, level, { + flatOnly: this.flatOnly, + weight: this.loopWeight, + }); + }; + } + _dumpPropertiesCode() { + let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.flatOnly = ${this.flatOnly ? "true" : "false"};\n`; + codeString += `${this._codeVariableName}.loopWeight = ${this.loopWeight};\n`; + return codeString; + } + /** + * Serializes this block in a JSON representation + * @returns the serialized block object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.flatOnly = this.flatOnly; + serializationObject.loopWeight = this.loopWeight; + return serializationObject; + } + _deserialize(serializationObject) { + super._deserialize(serializationObject); + this.flatOnly = serializationObject.flatOnly; + this.loopWeight = serializationObject.loopWeight; + } +} +__decorate([ + editableInPropertyPage("Flat Only", 0 /* PropertyTypeForEdition.Boolean */, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) +], SubdivideBlock.prototype, "flatOnly", void 0); +__decorate([ + editableInPropertyPage("Loop weight", 1 /* PropertyTypeForEdition.Float */, "ADVANCED", { embedded: true, min: 0, max: 1, notifiers: { rebuild: true } }) +], SubdivideBlock.prototype, "loopWeight", void 0); +RegisterClass("BABYLON.SubdivideBlock", SubdivideBlock); + +// @internal +const unpackUnorm = (value, bits) => { + const t = (1 << bits) - 1; + return (value & t) / t; +}; +// @internal +const unpack111011 = (value, result) => { + result.x = unpackUnorm(value >>> 21, 11); + result.y = unpackUnorm(value >>> 11, 10); + result.z = unpackUnorm(value, 11); +}; +// @internal +const unpack8888 = (value, result) => { + result[0] = unpackUnorm(value >>> 24, 8) * 255; + result[1] = unpackUnorm(value >>> 16, 8) * 255; + result[2] = unpackUnorm(value >>> 8, 8) * 255; + result[3] = unpackUnorm(value, 8) * 255; +}; +// @internal +// unpack quaternion with 2,10,10,10 format (largest element, 3x10bit element) +const unpackRot = (value, result) => { + const norm = 1.0 / (Math.sqrt(2) * 0.5); + const a = (unpackUnorm(value >>> 20, 10) - 0.5) * norm; + const b = (unpackUnorm(value >>> 10, 10) - 0.5) * norm; + const c = (unpackUnorm(value, 10) - 0.5) * norm; + const m = Math.sqrt(1.0 - (a * a + b * b + c * c)); + switch (value >>> 30) { + case 0: + result.set(m, a, b, c); + break; + case 1: + result.set(a, m, b, c); + break; + case 2: + result.set(a, b, m, c); + break; + case 3: + result.set(a, b, c, m); + break; + } +}; +/** + * Representation of the types + */ +var PLYType; +(function (PLYType) { + PLYType[PLYType["FLOAT"] = 0] = "FLOAT"; + PLYType[PLYType["INT"] = 1] = "INT"; + PLYType[PLYType["UINT"] = 2] = "UINT"; + PLYType[PLYType["DOUBLE"] = 3] = "DOUBLE"; + PLYType[PLYType["UCHAR"] = 4] = "UCHAR"; + PLYType[PLYType["UNDEFINED"] = 5] = "UNDEFINED"; +})(PLYType || (PLYType = {})); +/** + * Usage types of the PLY values + */ +var PLYValue; +(function (PLYValue) { + PLYValue[PLYValue["MIN_X"] = 0] = "MIN_X"; + PLYValue[PLYValue["MIN_Y"] = 1] = "MIN_Y"; + PLYValue[PLYValue["MIN_Z"] = 2] = "MIN_Z"; + PLYValue[PLYValue["MAX_X"] = 3] = "MAX_X"; + PLYValue[PLYValue["MAX_Y"] = 4] = "MAX_Y"; + PLYValue[PLYValue["MAX_Z"] = 5] = "MAX_Z"; + PLYValue[PLYValue["MIN_SCALE_X"] = 6] = "MIN_SCALE_X"; + PLYValue[PLYValue["MIN_SCALE_Y"] = 7] = "MIN_SCALE_Y"; + PLYValue[PLYValue["MIN_SCALE_Z"] = 8] = "MIN_SCALE_Z"; + PLYValue[PLYValue["MAX_SCALE_X"] = 9] = "MAX_SCALE_X"; + PLYValue[PLYValue["MAX_SCALE_Y"] = 10] = "MAX_SCALE_Y"; + PLYValue[PLYValue["MAX_SCALE_Z"] = 11] = "MAX_SCALE_Z"; + PLYValue[PLYValue["PACKED_POSITION"] = 12] = "PACKED_POSITION"; + PLYValue[PLYValue["PACKED_ROTATION"] = 13] = "PACKED_ROTATION"; + PLYValue[PLYValue["PACKED_SCALE"] = 14] = "PACKED_SCALE"; + PLYValue[PLYValue["PACKED_COLOR"] = 15] = "PACKED_COLOR"; + PLYValue[PLYValue["X"] = 16] = "X"; + PLYValue[PLYValue["Y"] = 17] = "Y"; + PLYValue[PLYValue["Z"] = 18] = "Z"; + PLYValue[PLYValue["SCALE_0"] = 19] = "SCALE_0"; + PLYValue[PLYValue["SCALE_1"] = 20] = "SCALE_1"; + PLYValue[PLYValue["SCALE_2"] = 21] = "SCALE_2"; + PLYValue[PLYValue["DIFFUSE_RED"] = 22] = "DIFFUSE_RED"; + PLYValue[PLYValue["DIFFUSE_GREEN"] = 23] = "DIFFUSE_GREEN"; + PLYValue[PLYValue["DIFFUSE_BLUE"] = 24] = "DIFFUSE_BLUE"; + PLYValue[PLYValue["OPACITY"] = 25] = "OPACITY"; + PLYValue[PLYValue["F_DC_0"] = 26] = "F_DC_0"; + PLYValue[PLYValue["F_DC_1"] = 27] = "F_DC_1"; + PLYValue[PLYValue["F_DC_2"] = 28] = "F_DC_2"; + PLYValue[PLYValue["F_DC_3"] = 29] = "F_DC_3"; + PLYValue[PLYValue["ROT_0"] = 30] = "ROT_0"; + PLYValue[PLYValue["ROT_1"] = 31] = "ROT_1"; + PLYValue[PLYValue["ROT_2"] = 32] = "ROT_2"; + PLYValue[PLYValue["ROT_3"] = 33] = "ROT_3"; + PLYValue[PLYValue["MIN_COLOR_R"] = 34] = "MIN_COLOR_R"; + PLYValue[PLYValue["MIN_COLOR_G"] = 35] = "MIN_COLOR_G"; + PLYValue[PLYValue["MIN_COLOR_B"] = 36] = "MIN_COLOR_B"; + PLYValue[PLYValue["MAX_COLOR_R"] = 37] = "MAX_COLOR_R"; + PLYValue[PLYValue["MAX_COLOR_G"] = 38] = "MAX_COLOR_G"; + PLYValue[PLYValue["MAX_COLOR_B"] = 39] = "MAX_COLOR_B"; + PLYValue[PLYValue["SH_0"] = 40] = "SH_0"; + PLYValue[PLYValue["SH_1"] = 41] = "SH_1"; + PLYValue[PLYValue["SH_2"] = 42] = "SH_2"; + PLYValue[PLYValue["SH_3"] = 43] = "SH_3"; + PLYValue[PLYValue["SH_4"] = 44] = "SH_4"; + PLYValue[PLYValue["SH_5"] = 45] = "SH_5"; + PLYValue[PLYValue["SH_6"] = 46] = "SH_6"; + PLYValue[PLYValue["SH_7"] = 47] = "SH_7"; + PLYValue[PLYValue["SH_8"] = 48] = "SH_8"; + PLYValue[PLYValue["SH_9"] = 49] = "SH_9"; + PLYValue[PLYValue["SH_10"] = 50] = "SH_10"; + PLYValue[PLYValue["SH_11"] = 51] = "SH_11"; + PLYValue[PLYValue["SH_12"] = 52] = "SH_12"; + PLYValue[PLYValue["SH_13"] = 53] = "SH_13"; + PLYValue[PLYValue["SH_14"] = 54] = "SH_14"; + PLYValue[PLYValue["SH_15"] = 55] = "SH_15"; + PLYValue[PLYValue["SH_16"] = 56] = "SH_16"; + PLYValue[PLYValue["SH_17"] = 57] = "SH_17"; + PLYValue[PLYValue["SH_18"] = 58] = "SH_18"; + PLYValue[PLYValue["SH_19"] = 59] = "SH_19"; + PLYValue[PLYValue["SH_20"] = 60] = "SH_20"; + PLYValue[PLYValue["SH_21"] = 61] = "SH_21"; + PLYValue[PLYValue["SH_22"] = 62] = "SH_22"; + PLYValue[PLYValue["SH_23"] = 63] = "SH_23"; + PLYValue[PLYValue["SH_24"] = 64] = "SH_24"; + PLYValue[PLYValue["SH_25"] = 65] = "SH_25"; + PLYValue[PLYValue["SH_26"] = 66] = "SH_26"; + PLYValue[PLYValue["SH_27"] = 67] = "SH_27"; + PLYValue[PLYValue["SH_28"] = 68] = "SH_28"; + PLYValue[PLYValue["SH_29"] = 69] = "SH_29"; + PLYValue[PLYValue["SH_30"] = 70] = "SH_30"; + PLYValue[PLYValue["SH_31"] = 71] = "SH_31"; + PLYValue[PLYValue["SH_32"] = 72] = "SH_32"; + PLYValue[PLYValue["SH_33"] = 73] = "SH_33"; + PLYValue[PLYValue["SH_34"] = 74] = "SH_34"; + PLYValue[PLYValue["SH_35"] = 75] = "SH_35"; + PLYValue[PLYValue["SH_36"] = 76] = "SH_36"; + PLYValue[PLYValue["SH_37"] = 77] = "SH_37"; + PLYValue[PLYValue["SH_38"] = 78] = "SH_38"; + PLYValue[PLYValue["SH_39"] = 79] = "SH_39"; + PLYValue[PLYValue["SH_40"] = 80] = "SH_40"; + PLYValue[PLYValue["SH_41"] = 81] = "SH_41"; + PLYValue[PLYValue["SH_42"] = 82] = "SH_42"; + PLYValue[PLYValue["SH_43"] = 83] = "SH_43"; + PLYValue[PLYValue["SH_44"] = 84] = "SH_44"; + PLYValue[PLYValue["UNDEFINED"] = 85] = "UNDEFINED"; +})(PLYValue || (PLYValue = {})); +/** + * Class used to render a gaussian splatting mesh + */ +class GaussianSplattingMesh extends Mesh { + /** + * SH degree. 0 = no sh (default). 1 = 3 parameters. 2 = 8 parameters. 3 = 15 parameters. + */ + get shDegree() { + return this._shDegree; + } + /** + * returns the splats data array buffer that contains in order : postions (3 floats), size (3 floats), color (4 bytes), orientation quaternion (4 bytes) + */ + get splatsData() { + return this._splatsData; + } + /** + * Gets the covariancesA texture + */ + get covariancesATexture() { + return this._covariancesATexture; + } + /** + * Gets the covariancesB texture + */ + get covariancesBTexture() { + return this._covariancesBTexture; + } + /** + * Gets the centers texture + */ + get centersTexture() { + return this._centersTexture; + } + /** + * Gets the colors texture + */ + get colorsTexture() { + return this._colorsTexture; + } + /** + * Gets the SH textures + */ + get shTextures() { + return this._shTextures; + } + /** + * set rendering material + */ + set material(value) { + this._material = value; + this._material.backFaceCulling = true; + this._material.cullBackFaces = false; + value.resetDrawCache(); + } + /** + * get rendering material + */ + get material() { + return this._material; + } + /** + * Creates a new gaussian splatting mesh + * @param name defines the name of the mesh + * @param url defines the url to load from (optional) + * @param scene defines the hosting scene (optional) + * @param keepInRam keep datas in ram for editing purpose + */ + constructor(name, url = null, scene = null, keepInRam = false) { + super(name, scene); + this._vertexCount = 0; + this._worker = null; + this._frameIdLastUpdate = -1; + this._modelViewMatrix = Matrix.Identity(); + this._canPostToWorker = true; + this._readyToDisplay = false; + this._covariancesATexture = null; + this._covariancesBTexture = null; + this._centersTexture = null; + this._colorsTexture = null; + this._splatPositions = null; + this._splatIndex = null; + this._shTextures = null; + this._splatsData = null; + this._sh = null; + this._keepInRam = false; + this._delayedTextureUpdate = null; + this._oldDirection = new Vector3(); + this._useRGBACovariants = false; + this._material = null; + this._tmpCovariances = [0, 0, 0, 0, 0, 0]; + this._sortIsDirty = false; + this._shDegree = 0; + const vertexData = new VertexData(); + // Use an intanced quad or triangle. Triangle might be a bit faster because of less shader invocation but I didn't see any difference. + // Keeping both and use triangle for now. + // for quad, use following lines + //vertexData.positions = [-2, -2, 0, 2, -2, 0, 2, 2, 0, -2, 2, 0]; + //vertexData.indices = [0, 1, 2, 0, 2, 3]; + vertexData.positions = [-3, -2, 0, 3, -2, 0, 0, 4, 0]; + vertexData.indices = [0, 1, 2]; + vertexData.applyToMesh(this); + this.subMeshes = []; + // for quad, use following line + //new SubMesh(0, 0, 4, 0, 6, this); + new SubMesh(0, 0, 3, 0, 3, this); + this.setEnabled(false); + // webGL2 and webGPU support for RG texture with float16 is fine. not webGL1 + this._useRGBACovariants = !this.getEngine().isWebGPU && this.getEngine().version === 1.0; + this._keepInRam = keepInRam; + if (url) { + this.loadFileAsync(url); + } + this._material = new GaussianSplattingMaterial(this.name + "_material", this._scene); + } + /** + * Returns the class name + * @returns "GaussianSplattingMesh" + */ + getClassName() { + return "GaussianSplattingMesh"; + } + /** + * Returns the total number of vertices (splats) within the mesh + * @returns the total number of vertices + */ + getTotalVertices() { + return this._vertexCount; + } + /** + * Is this node ready to be used/rendered + * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) + * @returns true when ready + */ + isReady(completeCheck = false) { + if (!super.isReady(completeCheck, true)) { + return false; + } + if (!this._readyToDisplay) { + // mesh is ready when worker has done at least 1 sorting + this._postToWorker(true); + return false; + } + return true; + } + /** @internal */ + _postToWorker(forced = false) { + const frameId = this.getScene().getFrameId(); + if ((forced || frameId !== this._frameIdLastUpdate) && this._worker && this._scene.activeCamera && this._canPostToWorker) { + const cameraMatrix = this._scene.activeCamera.getViewMatrix(); + this.getWorldMatrix().multiplyToRef(cameraMatrix, this._modelViewMatrix); + cameraMatrix.invertToRef(TmpVectors.Matrix[0]); + this.getWorldMatrix().multiplyToRef(TmpVectors.Matrix[0], TmpVectors.Matrix[1]); + Vector3.TransformNormalToRef(Vector3.Forward(this._scene.useRightHandedSystem), TmpVectors.Matrix[1], TmpVectors.Vector3[2]); + TmpVectors.Vector3[2].normalize(); + const dot = Vector3.Dot(TmpVectors.Vector3[2], this._oldDirection); + if (forced || Math.abs(dot - 1) >= 0.01) { + this._oldDirection.copyFrom(TmpVectors.Vector3[2]); + this._frameIdLastUpdate = frameId; + this._canPostToWorker = false; + this._worker.postMessage({ view: this._modelViewMatrix.m, depthMix: this._depthMix, useRightHandedSystem: this._scene.useRightHandedSystem }, [ + this._depthMix.buffer, + ]); + } + } + } + /** + * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager + * @param subMesh defines the subMesh to render + * @param enableAlphaMode defines if alpha mode can be changed + * @param effectiveMeshReplacement defines an optional mesh used to provide info for the rendering + * @returns the current mesh + */ + render(subMesh, enableAlphaMode, effectiveMeshReplacement) { + this._postToWorker(); + return super.render(subMesh, enableAlphaMode, effectiveMeshReplacement); + } + static _TypeNameToEnum(name) { + switch (name) { + case "float": + return 0 /* PLYType.FLOAT */; + case "int": + return 1 /* PLYType.INT */; + case "uint": + return 2 /* PLYType.UINT */; + case "double": + return 3 /* PLYType.DOUBLE */; + case "uchar": + return 4 /* PLYType.UCHAR */; + } + return 5 /* PLYType.UNDEFINED */; + } + static _ValueNameToEnum(name) { + switch (name) { + case "min_x": + return 0 /* PLYValue.MIN_X */; + case "min_y": + return 1 /* PLYValue.MIN_Y */; + case "min_z": + return 2 /* PLYValue.MIN_Z */; + case "max_x": + return 3 /* PLYValue.MAX_X */; + case "max_y": + return 4 /* PLYValue.MAX_Y */; + case "max_z": + return 5 /* PLYValue.MAX_Z */; + case "min_scale_x": + return 6 /* PLYValue.MIN_SCALE_X */; + case "min_scale_y": + return 7 /* PLYValue.MIN_SCALE_Y */; + case "min_scale_z": + return 8 /* PLYValue.MIN_SCALE_Z */; + case "max_scale_x": + return 9 /* PLYValue.MAX_SCALE_X */; + case "max_scale_y": + return 10 /* PLYValue.MAX_SCALE_Y */; + case "max_scale_z": + return 11 /* PLYValue.MAX_SCALE_Z */; + case "packed_position": + return 12 /* PLYValue.PACKED_POSITION */; + case "packed_rotation": + return 13 /* PLYValue.PACKED_ROTATION */; + case "packed_scale": + return 14 /* PLYValue.PACKED_SCALE */; + case "packed_color": + return 15 /* PLYValue.PACKED_COLOR */; + case "x": + return 16 /* PLYValue.X */; + case "y": + return 17 /* PLYValue.Y */; + case "z": + return 18 /* PLYValue.Z */; + case "scale_0": + return 19 /* PLYValue.SCALE_0 */; + case "scale_1": + return 20 /* PLYValue.SCALE_1 */; + case "scale_2": + return 21 /* PLYValue.SCALE_2 */; + case "diffuse_red": + case "red": + return 22 /* PLYValue.DIFFUSE_RED */; + case "diffuse_green": + case "green": + return 23 /* PLYValue.DIFFUSE_GREEN */; + case "diffuse_blue": + case "blue": + return 24 /* PLYValue.DIFFUSE_BLUE */; + case "f_dc_0": + return 26 /* PLYValue.F_DC_0 */; + case "f_dc_1": + return 27 /* PLYValue.F_DC_1 */; + case "f_dc_2": + return 28 /* PLYValue.F_DC_2 */; + case "f_dc_3": + return 29 /* PLYValue.F_DC_3 */; + case "opacity": + return 25 /* PLYValue.OPACITY */; + case "rot_0": + return 30 /* PLYValue.ROT_0 */; + case "rot_1": + return 31 /* PLYValue.ROT_1 */; + case "rot_2": + return 32 /* PLYValue.ROT_2 */; + case "rot_3": + return 33 /* PLYValue.ROT_3 */; + case "min_r": + return 34 /* PLYValue.MIN_COLOR_R */; + case "min_g": + return 35 /* PLYValue.MIN_COLOR_G */; + case "min_b": + return 36 /* PLYValue.MIN_COLOR_B */; + case "max_r": + return 37 /* PLYValue.MAX_COLOR_R */; + case "max_g": + return 38 /* PLYValue.MAX_COLOR_G */; + case "max_b": + return 39 /* PLYValue.MAX_COLOR_B */; + case "f_rest_0": + return 40 /* PLYValue.SH_0 */; + case "f_rest_1": + return 41 /* PLYValue.SH_1 */; + case "f_rest_2": + return 42 /* PLYValue.SH_2 */; + case "f_rest_3": + return 43 /* PLYValue.SH_3 */; + case "f_rest_4": + return 44 /* PLYValue.SH_4 */; + case "f_rest_5": + return 45 /* PLYValue.SH_5 */; + case "f_rest_6": + return 46 /* PLYValue.SH_6 */; + case "f_rest_7": + return 47 /* PLYValue.SH_7 */; + case "f_rest_8": + return 48 /* PLYValue.SH_8 */; + case "f_rest_9": + return 49 /* PLYValue.SH_9 */; + case "f_rest_10": + return 50 /* PLYValue.SH_10 */; + case "f_rest_11": + return 51 /* PLYValue.SH_11 */; + case "f_rest_12": + return 52 /* PLYValue.SH_12 */; + case "f_rest_13": + return 53 /* PLYValue.SH_13 */; + case "f_rest_14": + return 54 /* PLYValue.SH_14 */; + case "f_rest_15": + return 55 /* PLYValue.SH_15 */; + case "f_rest_16": + return 56 /* PLYValue.SH_16 */; + case "f_rest_17": + return 57 /* PLYValue.SH_17 */; + case "f_rest_18": + return 58 /* PLYValue.SH_18 */; + case "f_rest_19": + return 59 /* PLYValue.SH_19 */; + case "f_rest_20": + return 60 /* PLYValue.SH_20 */; + case "f_rest_21": + return 61 /* PLYValue.SH_21 */; + case "f_rest_22": + return 62 /* PLYValue.SH_22 */; + case "f_rest_23": + return 63 /* PLYValue.SH_23 */; + case "f_rest_24": + return 64 /* PLYValue.SH_24 */; + case "f_rest_25": + return 65 /* PLYValue.SH_25 */; + case "f_rest_26": + return 66 /* PLYValue.SH_26 */; + case "f_rest_27": + return 67 /* PLYValue.SH_27 */; + case "f_rest_28": + return 68 /* PLYValue.SH_28 */; + case "f_rest_29": + return 69 /* PLYValue.SH_29 */; + case "f_rest_30": + return 70 /* PLYValue.SH_30 */; + case "f_rest_31": + return 71 /* PLYValue.SH_31 */; + case "f_rest_32": + return 72 /* PLYValue.SH_32 */; + case "f_rest_33": + return 73 /* PLYValue.SH_33 */; + case "f_rest_34": + return 74 /* PLYValue.SH_34 */; + case "f_rest_35": + return 75 /* PLYValue.SH_35 */; + case "f_rest_36": + return 76 /* PLYValue.SH_36 */; + case "f_rest_37": + return 77 /* PLYValue.SH_37 */; + case "f_rest_38": + return 78 /* PLYValue.SH_38 */; + case "f_rest_39": + return 79 /* PLYValue.SH_39 */; + case "f_rest_40": + return 80 /* PLYValue.SH_40 */; + case "f_rest_41": + return 81 /* PLYValue.SH_41 */; + case "f_rest_42": + return 82 /* PLYValue.SH_42 */; + case "f_rest_43": + return 83 /* PLYValue.SH_43 */; + case "f_rest_44": + return 84 /* PLYValue.SH_44 */; + } + return 85 /* PLYValue.UNDEFINED */; + } + /** + * Parse a PLY file header and returns metas infos on splats and chunks + * @param data the loaded buffer + * @returns a PLYHeader + */ + static ParseHeader(data) { + const ubuf = new Uint8Array(data); + const header = new TextDecoder().decode(ubuf.slice(0, 1024 * 10)); + const headerEnd = "end_header\n"; + const headerEndIndex = header.indexOf(headerEnd); + if (headerEndIndex < 0 || !header) { + // standard splat + return null; + } + const vertexCount = parseInt(/element vertex (\d+)\n/.exec(header)[1]); + const chunkElement = /element chunk (\d+)\n/.exec(header); + let chunkCount = 0; + if (chunkElement) { + chunkCount = parseInt(chunkElement[1]); + } + let rowVertexOffset = 0; + let rowChunkOffset = 0; + const offsets = { + double: 8, + int: 4, + uint: 4, + float: 4, + short: 2, + ushort: 2, + uchar: 1, + list: 0, + }; + let ElementMode; + (function (ElementMode) { + ElementMode[ElementMode["Vertex"] = 0] = "Vertex"; + ElementMode[ElementMode["Chunk"] = 1] = "Chunk"; + })(ElementMode || (ElementMode = {})); + let chunkMode = 1 /* ElementMode.Chunk */; + const vertexProperties = []; + const chunkProperties = []; + const filtered = header.slice(0, headerEndIndex).split("\n"); + let shDegree = 0; + for (const prop of filtered) { + if (prop.startsWith("property ")) { + const [, typeName, name] = prop.split(" "); + const value = GaussianSplattingMesh._ValueNameToEnum(name); + // SH degree 1,2 or 3 for 9, 24 or 45 values + if (value >= 84 /* PLYValue.SH_44 */) { + shDegree = 3; + } + else if (value >= 64 /* PLYValue.SH_24 */) { + shDegree = 2; + } + else if (value >= 48 /* PLYValue.SH_8 */) { + shDegree = 1; + } + const type = GaussianSplattingMesh._TypeNameToEnum(typeName); + if (chunkMode == 1 /* ElementMode.Chunk */) { + chunkProperties.push({ value, type, offset: rowChunkOffset }); + rowChunkOffset += offsets[typeName]; + } + else if (chunkMode == 0 /* ElementMode.Vertex */) { + vertexProperties.push({ value, type, offset: rowVertexOffset }); + rowVertexOffset += offsets[typeName]; + } + if (!offsets[typeName]) { + Logger.Warn(`Unsupported property type: ${typeName}.`); + } + } + else if (prop.startsWith("element ")) { + const [, type] = prop.split(" "); + if (type == "chunk") { + chunkMode = 1 /* ElementMode.Chunk */; + } + else if (type == "vertex") { + chunkMode = 0 /* ElementMode.Vertex */; + } + } + } + const dataView = new DataView(data, headerEndIndex + headerEnd.length); + const buffer = new ArrayBuffer(GaussianSplattingMesh._RowOutputLength * vertexCount); + let shBuffer = null; + let shCoefficientCount = 0; + if (shDegree) { + const shVectorCount = (shDegree + 1) * (shDegree + 1) - 1; + shCoefficientCount = shVectorCount * 3; + shBuffer = new ArrayBuffer(shCoefficientCount * vertexCount); + } + return { + vertexCount: vertexCount, + chunkCount: chunkCount, + rowVertexLength: rowVertexOffset, + rowChunkLength: rowChunkOffset, + vertexProperties: vertexProperties, + chunkProperties: chunkProperties, + dataView: dataView, + buffer: buffer, + shDegree: shDegree, + shCoefficientCount: shCoefficientCount, + shBuffer: shBuffer, + }; + } + static _GetCompressedChunks(header, offset) { + if (!header.chunkCount) { + return null; + } + const dataView = header.dataView; + const compressedChunks = new Array(header.chunkCount); + for (let i = 0; i < header.chunkCount; i++) { + const currentChunk = { + min: new Vector3(), + max: new Vector3(), + minScale: new Vector3(), + maxScale: new Vector3(), + minColor: new Vector3(0, 0, 0), + maxColor: new Vector3(1, 1, 1), + }; + compressedChunks[i] = currentChunk; + for (let propertyIndex = 0; propertyIndex < header.chunkProperties.length; propertyIndex++) { + const property = header.chunkProperties[propertyIndex]; + let value; + switch (property.type) { + case 0 /* PLYType.FLOAT */: + value = dataView.getFloat32(property.offset + offset.value, true); + break; + default: + continue; + } + switch (property.value) { + case 0 /* PLYValue.MIN_X */: + currentChunk.min.x = value; + break; + case 1 /* PLYValue.MIN_Y */: + currentChunk.min.y = value; + break; + case 2 /* PLYValue.MIN_Z */: + currentChunk.min.z = value; + break; + case 3 /* PLYValue.MAX_X */: + currentChunk.max.x = value; + break; + case 4 /* PLYValue.MAX_Y */: + currentChunk.max.y = value; + break; + case 5 /* PLYValue.MAX_Z */: + currentChunk.max.z = value; + break; + case 6 /* PLYValue.MIN_SCALE_X */: + currentChunk.minScale.x = value; + break; + case 7 /* PLYValue.MIN_SCALE_Y */: + currentChunk.minScale.y = value; + break; + case 8 /* PLYValue.MIN_SCALE_Z */: + currentChunk.minScale.z = value; + break; + case 9 /* PLYValue.MAX_SCALE_X */: + currentChunk.maxScale.x = value; + break; + case 10 /* PLYValue.MAX_SCALE_Y */: + currentChunk.maxScale.y = value; + break; + case 11 /* PLYValue.MAX_SCALE_Z */: + currentChunk.maxScale.z = value; + break; + case 34 /* PLYValue.MIN_COLOR_R */: + currentChunk.minColor.x = value; + break; + case 35 /* PLYValue.MIN_COLOR_G */: + currentChunk.minColor.y = value; + break; + case 36 /* PLYValue.MIN_COLOR_B */: + currentChunk.minColor.z = value; + break; + case 37 /* PLYValue.MAX_COLOR_R */: + currentChunk.maxColor.x = value; + break; + case 38 /* PLYValue.MAX_COLOR_G */: + currentChunk.maxColor.y = value; + break; + case 39 /* PLYValue.MAX_COLOR_B */: + currentChunk.maxColor.z = value; + break; + } + } + offset.value += header.rowChunkLength; + } + return compressedChunks; + } + static _GetSplat(header, index, compressedChunks, offset) { + const q = TmpVectors.Quaternion[0]; + const temp3 = TmpVectors.Vector3[0]; + const rowOutputLength = GaussianSplattingMesh._RowOutputLength; + const buffer = header.buffer; + const dataView = header.dataView; + const position = new Float32Array(buffer, index * rowOutputLength, 3); + const scale = new Float32Array(buffer, index * rowOutputLength + 12, 3); + const rgba = new Uint8ClampedArray(buffer, index * rowOutputLength + 24, 4); + const rot = new Uint8ClampedArray(buffer, index * rowOutputLength + 28, 4); + let sh = null; + if (header.shBuffer) { + sh = new Uint8ClampedArray(header.shBuffer, index * header.shCoefficientCount, header.shCoefficientCount); + } + const chunkIndex = index >> 8; + let r0 = 255; + let r1 = 0; + let r2 = 0; + let r3 = 0; + for (let propertyIndex = 0; propertyIndex < header.vertexProperties.length; propertyIndex++) { + const property = header.vertexProperties[propertyIndex]; + let value; + switch (property.type) { + case 0 /* PLYType.FLOAT */: + value = dataView.getFloat32(offset.value + property.offset, true); + break; + case 1 /* PLYType.INT */: + value = dataView.getInt32(offset.value + property.offset, true); + break; + case 2 /* PLYType.UINT */: + value = dataView.getUint32(offset.value + property.offset, true); + break; + case 3 /* PLYType.DOUBLE */: + value = dataView.getFloat64(offset.value + property.offset, true); + break; + case 4 /* PLYType.UCHAR */: + value = dataView.getUint8(offset.value + property.offset); + break; + default: + continue; + } + switch (property.value) { + case 12 /* PLYValue.PACKED_POSITION */: + { + const compressedChunk = compressedChunks[chunkIndex]; + unpack111011(value, temp3); + position[0] = Scalar.Lerp(compressedChunk.min.x, compressedChunk.max.x, temp3.x); + position[1] = Scalar.Lerp(compressedChunk.min.y, compressedChunk.max.y, temp3.y); + position[2] = Scalar.Lerp(compressedChunk.min.z, compressedChunk.max.z, temp3.z); + } + break; + case 13 /* PLYValue.PACKED_ROTATION */: + { + unpackRot(value, q); + r0 = q.w; + r1 = -q.z; + r2 = q.y; + r3 = -q.x; + } + break; + case 14 /* PLYValue.PACKED_SCALE */: + { + const compressedChunk = compressedChunks[chunkIndex]; + unpack111011(value, temp3); + scale[0] = Math.exp(Scalar.Lerp(compressedChunk.minScale.x, compressedChunk.maxScale.x, temp3.x)); + scale[1] = Math.exp(Scalar.Lerp(compressedChunk.minScale.y, compressedChunk.maxScale.y, temp3.y)); + scale[2] = Math.exp(Scalar.Lerp(compressedChunk.minScale.z, compressedChunk.maxScale.z, temp3.z)); + } + break; + case 15 /* PLYValue.PACKED_COLOR */: + { + const compressedChunk = compressedChunks[chunkIndex]; + unpack8888(value, rgba); + rgba[0] = Scalar.Lerp(compressedChunk.minColor.x, compressedChunk.maxColor.x, rgba[0] / 255) * 255; + rgba[1] = Scalar.Lerp(compressedChunk.minColor.y, compressedChunk.maxColor.y, rgba[1] / 255) * 255; + rgba[2] = Scalar.Lerp(compressedChunk.minColor.z, compressedChunk.maxColor.z, rgba[2] / 255) * 255; + } + break; + case 16 /* PLYValue.X */: + position[0] = value; + break; + case 17 /* PLYValue.Y */: + position[1] = value; + break; + case 18 /* PLYValue.Z */: + position[2] = value; + break; + case 19 /* PLYValue.SCALE_0 */: + scale[0] = Math.exp(value); + break; + case 20 /* PLYValue.SCALE_1 */: + scale[1] = Math.exp(value); + break; + case 21 /* PLYValue.SCALE_2 */: + scale[2] = Math.exp(value); + break; + case 22 /* PLYValue.DIFFUSE_RED */: + rgba[0] = value; + break; + case 23 /* PLYValue.DIFFUSE_GREEN */: + rgba[1] = value; + break; + case 24 /* PLYValue.DIFFUSE_BLUE */: + rgba[2] = value; + break; + case 26 /* PLYValue.F_DC_0 */: + rgba[0] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255; + break; + case 27 /* PLYValue.F_DC_1 */: + rgba[1] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255; + break; + case 28 /* PLYValue.F_DC_2 */: + rgba[2] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255; + break; + case 29 /* PLYValue.F_DC_3 */: + rgba[3] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255; + break; + case 25 /* PLYValue.OPACITY */: + rgba[3] = (1 / (1 + Math.exp(-value))) * 255; + break; + case 30 /* PLYValue.ROT_0 */: + r0 = value; + break; + case 31 /* PLYValue.ROT_1 */: + r1 = value; + break; + case 32 /* PLYValue.ROT_2 */: + r2 = value; + break; + case 33 /* PLYValue.ROT_3 */: + r3 = value; + break; + } + if (sh && property.value >= 40 /* PLYValue.SH_0 */ && property.value <= 84 /* PLYValue.SH_44 */) { + const clampedValue = Scalar.Clamp(value * 127.5 + 127.5, 0, 255); + const shIndex = property.value - 40 /* PLYValue.SH_0 */; + sh[shIndex] = clampedValue; + } + } + q.set(r1, r2, r3, r0); + q.normalize(); + rot[0] = q.w * 128 + 128; + rot[1] = q.x * 128 + 128; + rot[2] = q.y * 128 + 128; + rot[3] = q.z * 128 + 128; + offset.value += header.rowVertexLength; + } + /** + * Converts a .ply data with SH coefficients splat + * if data array buffer is not ply, returns the original buffer + * @param data the .ply data to load + * @param useCoroutine use coroutine and yield + * @returns the loaded splat buffer and optional array of sh coefficients + */ + static *ConvertPLYWithSHToSplat(data, useCoroutine = false) { + const header = GaussianSplattingMesh.ParseHeader(data); + if (!header) { + return { buffer: data }; + } + const offset = { value: 0 }; + const compressedChunks = GaussianSplattingMesh._GetCompressedChunks(header, offset); + for (let i = 0; i < header.vertexCount; i++) { + GaussianSplattingMesh._GetSplat(header, i, compressedChunks, offset); + if (i % GaussianSplattingMesh._PlyConversionBatchSize === 0 && useCoroutine) { + yield; + } + } + let sh = null; + // make SH texture buffers + if (header.shDegree && header.shBuffer) { + const textureCount = Math.ceil(header.shCoefficientCount / 16); // 4 components can be stored per texture, 4 sh per component + let shIndexRead = 0; + const ubuf = new Uint8Array(header.shBuffer); + // sh is an array of uint8array that will be used to create sh textures + sh = []; + const splatCount = header.vertexCount; + const engine = EngineStore.LastCreatedEngine; + if (engine) { + const width = engine.getCaps().maxTextureSize; + const height = Math.ceil(splatCount / width); + // create array for the number of textures needed. + for (let textureIndex = 0; textureIndex < textureCount; textureIndex++) { + const texture = new Uint8Array(height * width * 4 * 4); // 4 components per texture, 4 sh per component + sh.push(texture); + } + for (let i = 0; i < splatCount; i++) { + for (let shIndexWrite = 0; shIndexWrite < header.shCoefficientCount; shIndexWrite++) { + const shValue = ubuf[shIndexRead++]; + const textureIndex = Math.floor(shIndexWrite / 16); + const shArray = sh[textureIndex]; + const byteIndexInTexture = shIndexWrite % 16; // [0..15] + const offsetPerSplat = i * 16; // 16 sh values per texture per splat. + shArray[byteIndexInTexture + offsetPerSplat] = shValue; + } + } + } + } + return { buffer: header.buffer, sh: sh }; + } + /** + * Converts a .ply data array buffer to splat + * if data array buffer is not ply, returns the original buffer + * @param data the .ply data to load + * @param useCoroutine use coroutine and yield + * @returns the loaded splat buffer without SH coefficient, whether ply contains or not SH. + */ + static *ConvertPLYToSplat(data, useCoroutine = false) { + const header = GaussianSplattingMesh.ParseHeader(data); + if (!header) { + return data; + } + const offset = { value: 0 }; + const compressedChunks = GaussianSplattingMesh._GetCompressedChunks(header, offset); + for (let i = 0; i < header.vertexCount; i++) { + GaussianSplattingMesh._GetSplat(header, i, compressedChunks, offset); + if (i % GaussianSplattingMesh._PlyConversionBatchSize === 0 && useCoroutine) { + yield; + } + } + return header.buffer; + } + /** + * Converts a .ply data array buffer to splat + * if data array buffer is not ply, returns the original buffer + * @param data the .ply data to load + * @returns the loaded splat buffer + */ + static async ConvertPLYToSplatAsync(data) { + return runCoroutineAsync(GaussianSplattingMesh.ConvertPLYToSplat(data, true), createYieldingScheduler()); + } + /** + * Converts a .ply with SH data array buffer to splat + * if data array buffer is not ply, returns the original buffer + * @param data the .ply data to load + * @returns the loaded splat buffer with SH + */ + static async ConvertPLYWithSHToSplatAsync(data) { + return runCoroutineAsync(GaussianSplattingMesh.ConvertPLYWithSHToSplat(data, true), createYieldingScheduler()); + } + /** + * Loads a .splat Gaussian Splatting array buffer asynchronously + * @param data arraybuffer containing splat file + * @returns a promise that resolves when the operation is complete + */ + loadDataAsync(data) { + return this.updateDataAsync(data); + } + /** + * Loads a .splat Gaussian or .ply Splatting file asynchronously + * @param url path to the splat file to load + * @returns a promise that resolves when the operation is complete + * @deprecated Please use SceneLoader.ImportMeshAsync instead + */ + loadFileAsync(url) { + return Tools.LoadFileAsync(url, true).then(async (plyBuffer) => { + GaussianSplattingMesh.ConvertPLYWithSHToSplatAsync(plyBuffer).then((splatsData) => { + this.updateDataAsync(splatsData.buffer, splatsData.sh); + }); + }); + } + /** + * Releases resources associated with this mesh. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + */ + dispose(doNotRecurse) { + this._covariancesATexture?.dispose(); + this._covariancesBTexture?.dispose(); + this._centersTexture?.dispose(); + this._colorsTexture?.dispose(); + if (this._shTextures) { + this._shTextures.forEach((shTexture) => { + shTexture.dispose(); + }); + } + this._covariancesATexture = null; + this._covariancesBTexture = null; + this._centersTexture = null; + this._colorsTexture = null; + this._shTextures = null; + this._worker?.terminate(); + this._worker = null; + super.dispose(doNotRecurse, true); + } + _copyTextures(source) { + this._covariancesATexture = source.covariancesATexture?.clone(); + this._covariancesBTexture = source.covariancesBTexture?.clone(); + this._centersTexture = source.centersTexture?.clone(); + this._colorsTexture = source.colorsTexture?.clone(); + if (source._shTextures) { + this._shTextures = []; + this._shTextures.forEach((shTexture) => { + this._shTextures?.push(shTexture.clone()); + }); + } + } + /** + * Returns a new Mesh object generated from the current mesh properties. + * @param name is a string, the name given to the new mesh + * @returns a new Gaussian Splatting Mesh + */ + clone(name = "") { + const newGS = new GaussianSplattingMesh(name, undefined, this.getScene()); + newGS._copySource(this); + newGS.makeGeometryUnique(); + newGS._vertexCount = this._vertexCount; + newGS._copyTextures(this); + newGS._modelViewMatrix = Matrix.Identity(); + newGS._splatPositions = this._splatPositions; + newGS._readyToDisplay = false; + newGS._instanciateWorker(); + const binfo = this.getBoundingInfo(); + newGS.getBoundingInfo().reConstruct(binfo.minimum, binfo.maximum, this.getWorldMatrix()); + newGS.forcedInstanceCount = newGS._vertexCount; + newGS.setEnabled(true); + return newGS; + } + _makeSplat(index, fBuffer, uBuffer, covA, covB, colorArray, minimum, maximum) { + const matrixRotation = TmpVectors.Matrix[0]; + const matrixScale = TmpVectors.Matrix[1]; + const quaternion = TmpVectors.Quaternion[0]; + const covBSItemSize = this._useRGBACovariants ? 4 : 2; + const x = fBuffer[8 * index + 0]; + const y = -fBuffer[8 * index + 1]; + const z = fBuffer[8 * index + 2]; + this._splatPositions[4 * index + 0] = x; + this._splatPositions[4 * index + 1] = y; + this._splatPositions[4 * index + 2] = z; + minimum.minimizeInPlaceFromFloats(x, y, z); + maximum.maximizeInPlaceFromFloats(x, y, z); + quaternion.set((uBuffer[32 * index + 28 + 1] - 127.5) / 127.5, (uBuffer[32 * index + 28 + 2] - 127.5) / 127.5, (uBuffer[32 * index + 28 + 3] - 127.5) / 127.5, -(uBuffer[32 * index + 28 + 0] - 127.5) / 127.5); + quaternion.toRotationMatrix(matrixRotation); + Matrix.ScalingToRef(fBuffer[8 * index + 3 + 0] * 2, fBuffer[8 * index + 3 + 1] * 2, fBuffer[8 * index + 3 + 2] * 2, matrixScale); + const M = matrixRotation.multiplyToRef(matrixScale, TmpVectors.Matrix[0]).m; + const covariances = this._tmpCovariances; + covariances[0] = M[0] * M[0] + M[1] * M[1] + M[2] * M[2]; + covariances[1] = M[0] * M[4] + M[1] * M[5] + M[2] * M[6]; + covariances[2] = M[0] * M[8] + M[1] * M[9] + M[2] * M[10]; + covariances[3] = M[4] * M[4] + M[5] * M[5] + M[6] * M[6]; + covariances[4] = M[4] * M[8] + M[5] * M[9] + M[6] * M[10]; + covariances[5] = M[8] * M[8] + M[9] * M[9] + M[10] * M[10]; + // normalize covA, covB + let factor = -1e4; + for (let covIndex = 0; covIndex < 6; covIndex++) { + factor = Math.max(factor, Math.abs(covariances[covIndex])); + } + this._splatPositions[4 * index + 3] = factor; + const transform = factor; + covA[index * 4 + 0] = ToHalfFloat$1(covariances[0] / transform); + covA[index * 4 + 1] = ToHalfFloat$1(covariances[1] / transform); + covA[index * 4 + 2] = ToHalfFloat$1(covariances[2] / transform); + covA[index * 4 + 3] = ToHalfFloat$1(covariances[3] / transform); + covB[index * covBSItemSize + 0] = ToHalfFloat$1(covariances[4] / transform); + covB[index * covBSItemSize + 1] = ToHalfFloat$1(covariances[5] / transform); + // colors + colorArray[index * 4 + 0] = uBuffer[32 * index + 24 + 0]; + colorArray[index * 4 + 1] = uBuffer[32 * index + 24 + 1]; + colorArray[index * 4 + 2] = uBuffer[32 * index + 24 + 2]; + colorArray[index * 4 + 3] = uBuffer[32 * index + 24 + 3]; + } + _updateTextures(covA, covB, colorArray, sh) { + const textureSize = this._getTextureSize(this._vertexCount); + // Update the textures + const createTextureFromData = (data, width, height, format) => { + return new RawTexture(data, width, height, format, this._scene, false, false, 2, 1); + }; + const createTextureFromDataU8 = (data, width, height, format) => { + return new RawTexture(data, width, height, format, this._scene, false, false, 2, 0); + }; + const createTextureFromDataU32 = (data, width, height, format) => { + return new RawTexture(data, width, height, format, this._scene, false, false, 1, 7); + }; + const createTextureFromDataF16 = (data, width, height, format) => { + return new RawTexture(data, width, height, format, this._scene, false, false, 2, 2); + }; + if (this._covariancesATexture) { + this._delayedTextureUpdate = { covA: covA, covB: covB, colors: colorArray, centers: this._splatPositions, sh: sh }; + const positions = Float32Array.from(this._splatPositions); + const vertexCount = this._vertexCount; + this._worker.postMessage({ positions, vertexCount }, [positions.buffer]); + this._postToWorker(true); + } + else { + this._covariancesATexture = createTextureFromDataF16(covA, textureSize.x, textureSize.y, 5); + this._covariancesBTexture = createTextureFromDataF16(covB, textureSize.x, textureSize.y, this._useRGBACovariants ? 5 : 7); + this._centersTexture = createTextureFromData(this._splatPositions, textureSize.x, textureSize.y, 5); + this._colorsTexture = createTextureFromDataU8(colorArray, textureSize.x, textureSize.y, 5); + if (sh) { + this._shTextures = []; + sh.forEach((shData) => { + const buffer = new Uint32Array(shData.buffer); + const shTexture = createTextureFromDataU32(buffer, textureSize.x, textureSize.y, 11); + shTexture.wrapU = 0; + shTexture.wrapV = 0; + this._shTextures.push(shTexture); + }); + } + this._instanciateWorker(); + } + } + *_updateData(data, isAsync, sh) { + // if a covariance texture is present, then it's not a creation but an update + if (!this._covariancesATexture) { + this._readyToDisplay = false; + } + // Parse the data + const uBuffer = new Uint8Array(data); + const fBuffer = new Float32Array(uBuffer.buffer); + if (this._keepInRam) { + this._splatsData = data; + if (sh) { + this._sh = sh; + } + } + const vertexCount = uBuffer.length / GaussianSplattingMesh._RowOutputLength; + if (vertexCount != this._vertexCount) { + this._updateSplatIndexBuffer(vertexCount); + } + this._vertexCount = vertexCount; + // degree == 1 for 1 texture (3 terms), 2 for 2 textures(8 terms) and 3 for 3 textures (15 terms) + this._shDegree = sh ? sh.length : 0; + const textureSize = this._getTextureSize(vertexCount); + const textureLength = textureSize.x * textureSize.y; + const lineCountUpdate = GaussianSplattingMesh.ProgressiveUpdateAmount ?? textureSize.y; + const textureLengthPerUpdate = textureSize.x * lineCountUpdate; + this._splatPositions = new Float32Array(4 * textureLength); + const covA = new Uint16Array(textureLength * 4); + const covB = new Uint16Array((this._useRGBACovariants ? 4 : 2) * textureLength); + const colorArray = new Uint8Array(textureLength * 4); + const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + if (GaussianSplattingMesh.ProgressiveUpdateAmount) { + // create textures with not filled-yet array, then update directly portions of it + this._updateTextures(covA, covB, colorArray, sh); + this.setEnabled(true); + const partCount = Math.ceil(textureSize.y / lineCountUpdate); + for (let partIndex = 0; partIndex < partCount; partIndex++) { + const updateLine = partIndex * lineCountUpdate; + const splatIndexBase = updateLine * textureSize.x; + for (let i = 0; i < textureLengthPerUpdate; i++) { + this._makeSplat(splatIndexBase + i, fBuffer, uBuffer, covA, covB, colorArray, minimum, maximum); + } + this._updateSubTextures(this._splatPositions, covA, covB, colorArray, updateLine, Math.min(lineCountUpdate, textureSize.y - updateLine)); + // Update the binfo + this.getBoundingInfo().reConstruct(minimum, maximum, this.getWorldMatrix()); + if (isAsync) { + yield; + } + } + // sort will be dirty here as just finished filled positions will not be sorted + const positions = Float32Array.from(this._splatPositions); + const vertexCount = this._vertexCount; + this._worker.postMessage({ positions, vertexCount }, [positions.buffer]); + this._sortIsDirty = true; + } + else { + for (let i = 0; i < vertexCount; i++) { + this._makeSplat(i, fBuffer, uBuffer, covA, covB, colorArray, minimum, maximum); + if (isAsync && i % GaussianSplattingMesh._SplatBatchSize === 0) { + yield; + } + } + // textures + this._updateTextures(covA, covB, colorArray, sh); + // Update the binfo + this.getBoundingInfo().reConstruct(minimum, maximum, this.getWorldMatrix()); + this.setEnabled(true); + } + this._postToWorker(true); + } + /** + * Update asynchronously the buffer + * @param data array buffer containing center, color, orientation and scale of splats + * @param sh optional array of uint8 array for SH data + * @returns a promise + */ + async updateDataAsync(data, sh) { + return runCoroutineAsync(this._updateData(data, true, sh), createYieldingScheduler()); + } + /** + * @experimental + * Update data from GS (position, orientation, color, scaling) + * @param data array that contain all the datas + * @param sh optional array of uint8 array for SH data + */ + updateData(data, sh) { + runCoroutineSync(this._updateData(data, false, sh)); + } + /** + * Refreshes the bounding info, taking into account all the thin instances defined + * @returns the current Gaussian Splatting + */ + refreshBoundingInfo() { + this.thinInstanceRefreshBoundingInfo(false); + return this; + } + // in case size is different + _updateSplatIndexBuffer(vertexCount) { + if (!this._splatIndex || vertexCount > this._splatIndex.length) { + this._splatIndex = new Float32Array(vertexCount); + this.thinInstanceSetBuffer("splatIndex", this._splatIndex, 1, false); + } + this.forcedInstanceCount = vertexCount; + } + _updateSubTextures(centers, covA, covB, colors, lineStart, lineCount, sh) { + const updateTextureFromData = (texture, data, width, lineStart, lineCount) => { + this.getEngine().updateTextureData(texture.getInternalTexture(), data, 0, lineStart, width, lineCount, 0, 0, false); + }; + const textureSize = this._getTextureSize(this._vertexCount); + const covBSItemSize = this._useRGBACovariants ? 4 : 2; + const texelStart = lineStart * textureSize.x; + const texelCount = lineCount * textureSize.x; + const covAView = new Uint16Array(covA.buffer, texelStart * 4 * Uint16Array.BYTES_PER_ELEMENT, texelCount * 4); + const covBView = new Uint16Array(covB.buffer, texelStart * covBSItemSize * Uint16Array.BYTES_PER_ELEMENT, texelCount * covBSItemSize); + const colorsView = new Uint8Array(colors.buffer, texelStart * 4, texelCount * 4); + const centersView = new Float32Array(centers.buffer, texelStart * 4 * Float32Array.BYTES_PER_ELEMENT, texelCount * 4); + updateTextureFromData(this._covariancesATexture, covAView, textureSize.x, lineStart, lineCount); + updateTextureFromData(this._covariancesBTexture, covBView, textureSize.x, lineStart, lineCount); + updateTextureFromData(this._centersTexture, centersView, textureSize.x, lineStart, lineCount); + updateTextureFromData(this._colorsTexture, colorsView, textureSize.x, lineStart, lineCount); + if (sh) { + for (let i = 0; i < sh.length; i++) { + const componentCount = 4; + const shView = new Uint8Array(this._sh[i].buffer, texelStart * componentCount, texelCount * componentCount); + updateTextureFromData(this._shTextures[i], shView, textureSize.x, lineStart, lineCount); + } + } + } + _instanciateWorker() { + if (!this._vertexCount) { + return; + } + this._updateSplatIndexBuffer(this._vertexCount); + // Start the worker thread + this._worker?.terminate(); + this._worker = new Worker(URL.createObjectURL(new Blob(["(", GaussianSplattingMesh._CreateWorker.toString(), ")(self)"], { + type: "application/javascript", + }))); + this._depthMix = new BigInt64Array(this._vertexCount); + const positions = Float32Array.from(this._splatPositions); + const vertexCount = this._vertexCount; + this._worker.postMessage({ positions, vertexCount }, [positions.buffer]); + this._worker.onmessage = (e) => { + this._depthMix = e.data.depthMix; + const indexMix = new Uint32Array(e.data.depthMix.buffer); + if (this._splatIndex) { + for (let j = 0; j < this._vertexCount; j++) { + this._splatIndex[j] = indexMix[2 * j]; + } + } + if (this._delayedTextureUpdate) { + const textureSize = this._getTextureSize(vertexCount); + this._updateSubTextures(this._delayedTextureUpdate.centers, this._delayedTextureUpdate.covA, this._delayedTextureUpdate.covB, this._delayedTextureUpdate.colors, 0, textureSize.y, this._delayedTextureUpdate.sh); + this._delayedTextureUpdate = null; + } + this.thinInstanceBufferUpdated("splatIndex"); + this._canPostToWorker = true; + this._readyToDisplay = true; + // sort is dirty when GS is visible for progressive update with a this message arriving but positions were partially filled + // another update needs to be kicked. The kick can't happen just when the position buffer is ready because _canPostToWorker might be false. + if (this._sortIsDirty) { + this._postToWorker(true); + this._sortIsDirty = false; + } + }; + } + _getTextureSize(length) { + const engine = this._scene.getEngine(); + const width = engine.getCaps().maxTextureSize; + let height = 1; + if (engine.version === 1 && !engine.isWebGPU) { + while (width * height < length) { + height *= 2; + } + } + else { + height = Math.ceil(length / width); + } + if (height > width) { + Logger.Error("GaussianSplatting texture size: (" + width + ", " + height + "), maxTextureSize: " + width); + height = width; + } + return new Vector2(width, height); + } +} +GaussianSplattingMesh._RowOutputLength = 3 * 4 + 3 * 4 + 4 + 4; // Vector3 position, Vector3 scale, 1 u8 quaternion, 1 color with alpha +GaussianSplattingMesh._SH_C0 = 0.28209479177387814; +// batch size between 2 yield calls. This value is a tradeoff between updates overhead and framerate hiccups +// This step is faster the PLY conversion. So batch size can be bigger +GaussianSplattingMesh._SplatBatchSize = 327680; +// batch size between 2 yield calls during the PLY to splat conversion. +GaussianSplattingMesh._PlyConversionBatchSize = 32768; +/** + * Set the number of batch (a batch is 16384 splats) after which a display update is performed + * A value of 0 (default) means display update will not happens before splat is ready. + */ +GaussianSplattingMesh.ProgressiveUpdateAmount = 0; +GaussianSplattingMesh._CreateWorker = function (self) { + let vertexCount = 0; + let positions; + let depthMix; + let indices; + let floatMix; + self.onmessage = (e) => { + // updated on init + if (e.data.positions) { + positions = e.data.positions; + vertexCount = e.data.vertexCount; + } + // udpate on view changed + else { + const viewProj = e.data.view; + if (!positions || !viewProj) { + // Sanity check, it shouldn't happen! + throw new Error("positions or view is not defined!"); + } + depthMix = e.data.depthMix; + indices = new Uint32Array(depthMix.buffer); + floatMix = new Float32Array(depthMix.buffer); + // Sort + for (let j = 0; j < vertexCount; j++) { + indices[2 * j] = j; + } + let depthFactor = -1; + if (e.data.useRightHandedSystem) { + depthFactor = 1; + } + for (let j = 0; j < vertexCount; j++) { + floatMix[2 * j + 1] = 10000 + (viewProj[2] * positions[4 * j + 0] + viewProj[6] * positions[4 * j + 1] + viewProj[10] * positions[4 * j + 2]) * depthFactor; + } + depthMix.sort(); + self.postMessage({ depthMix }, [depthMix.buffer]); + } + }; +}; + +// Do not edit. +const name$3B = "colorPixelShader"; +const shader$3A = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +#define VERTEXCOLOR +varying vColor: vec4f; +#else +uniform color: vec4f; +#endif +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +fragmentOutputs.color=input.vColor; +#else +fragmentOutputs.color=uniforms.color; +#endif +#include(color,fragmentOutputs.color) +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3B]) { + ShaderStore.ShadersStoreWGSL[name$3B] = shader$3A; +} +/** @internal */ +const colorPixelShaderWGSL = { name: name$3B, shader: shader$3A }; + +const color_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + colorPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3A = "colorVertexShader"; +const shader$3z = `attribute position: vec3f; +#ifdef VERTEXCOLOR +attribute color: vec4f; +#endif +#include +#include +#include +#include +#ifdef FOG +uniform view: mat4x4f; +#endif +#include +uniform viewProjection: mat4x4f; +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vColor: vec4f; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +#ifdef VERTEXCOLOR +var colorUpdated: vec4f=vertexInputs.color; +#endif +#include +#include +#include +var worldPos: vec4f=finalWorld* vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos; +#include +#include +#include +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3A]) { + ShaderStore.ShadersStoreWGSL[name$3A] = shader$3z; +} +/** @internal */ +const colorVertexShaderWGSL = { name: name$3A, shader: shader$3z }; + +const color_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + colorVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3z = "meshUVSpaceRendererVertexShader"; +const shader$3y = `precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vNormalW=normalize(normWorldSM*normalUpdated); +#endif +vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3z]) { + ShaderStore.ShadersStore[name$3z] = shader$3y; +} + +// Do not edit. +const name$3y = "meshUVSpaceRendererPixelShader"; +const shader$3x = `precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} +gl_FragColor=texture2D(textureSampler,vDecalTC);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3y]) { + ShaderStore.ShadersStore[name$3y] = shader$3x; +} + +// Do not edit. +const name$3x = "meshUVSpaceRendererMaskerVertexShader"; +const shader$3w = `attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3x]) { + ShaderStore.ShadersStore[name$3x] = shader$3w; +} + +// Do not edit. +const name$3w = "meshUVSpaceRendererMaskerPixelShader"; +const shader$3v = `varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3w]) { + ShaderStore.ShadersStore[name$3w] = shader$3v; +} + +// Do not edit. +const name$3v = "meshUVSpaceRendererFinaliserPixelShader"; +const shader$3u = `precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;} +if (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;} +if (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;} +if (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;} +if (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3v]) { + ShaderStore.ShadersStore[name$3v] = shader$3u; +} + +// Do not edit. +const name$3u = "meshUVSpaceRendererFinaliserVertexShader"; +const shader$3t = `precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3u]) { + ShaderStore.ShadersStore[name$3u] = shader$3t; +} + +// Do not edit. +const name$3t = "meshUVSpaceRendererVertexShader"; +const shader$3s = `attribute position: vec3f;attribute normal: vec3f;attribute uv: vec2f;uniform projMatrix: mat4x4f;varying vDecalTC: vec2f; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +@vertex +fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;var normalUpdated: vec3f=input.normal; +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);var vNormalW: vec3f; +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vNormalW=normalize(normWorldSM*normalUpdated); +#endif +var normalView: vec3f=normalize((uniforms.projMatrix* vec4f(vNormalW,0.0)).xyz);var decalTC: vec3f=(uniforms.projMatrix*worldPos).xyz;vertexOutputs.vDecalTC=decalTC.xy;vertexOutputs.position=vec4f(input.uv*2.0-1.0,select(decalTC.z,2.,normalView.z>0.0),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3t]) { + ShaderStore.ShadersStoreWGSL[name$3t] = shader$3s; +} + +// Do not edit. +const name$3s = "meshUVSpaceRendererPixelShader"; +const shader$3r = `varying vDecalTC: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {if (input.vDecalTC.x<0. || input.vDecalTC.x>1. || input.vDecalTC.y<0. || input.vDecalTC.y>1.) {discard;} +fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vDecalTC);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3s]) { + ShaderStore.ShadersStoreWGSL[name$3s] = shader$3r; +} + +// Do not edit. +const name$3r = "meshUVSpaceRendererMaskerVertexShader"; +const shader$3q = `attribute uv: vec2f;varying vUV: vec2f;@vertex +fn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position= vec4f( vec2f(input.uv.x,input.uv.y)*2.0-1.0,0.,1.0);vertexOutputs.vUV=input.uv;}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3r]) { + ShaderStore.ShadersStoreWGSL[name$3r] = shader$3q; +} + +// Do not edit. +const name$3q = "meshUVSpaceRendererMaskerPixelShader"; +const shader$3p = `varying vUV: vec2f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color= vec4f(1.0,1.0,1.0,1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3q]) { + ShaderStore.ShadersStoreWGSL[name$3q] = shader$3p; +} + +// Do not edit. +const name$3p = "meshUVSpaceRendererFinaliserPixelShader"; +const shader$3o = `#define DISABLE_UNIFORMITY_ANALYSIS +varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var maskTextureSamplerSampler: sampler;var maskTextureSampler: texture_2d;uniform textureSize: vec2f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var mask: vec4f=textureSample(maskTextureSampler,maskTextureSamplerSampler,input.vUV).rgba;if (mask.r>0.5) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);} else {var texelSize: vec2f=4.0/uniforms.textureSize;var uv_p01: vec2f=input.vUV+ vec2f(-1.0,0.0)*texelSize;var uv_p21: vec2f=input.vUV+ vec2f(1.0,0.0)*texelSize;var uv_p10: vec2f=input.vUV+ vec2f(0.0,-1.0)*texelSize;var uv_p12: vec2f=input.vUV+ vec2f(0.0,1.0)*texelSize;var mask_p01: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p01).r;var mask_p21: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p21).r;var mask_p10: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p10).r;var mask_p12: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p12).r;var col: vec4f= vec4f(0.0,0.0,0.0,0.0);var total_weight: f32=0.0;if (mask_p01>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p01);total_weight+=1.0;} +if (mask_p21>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p21);total_weight+=1.0;} +if (mask_p10>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p10);total_weight+=1.0;} +if (mask_p12>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p12);total_weight+=1.0;} +if (total_weight>0.0) {fragmentOutputs.color=col/total_weight;} else {fragmentOutputs.color=col;}}} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3p]) { + ShaderStore.ShadersStoreWGSL[name$3p] = shader$3o; +} + +// Do not edit. +const name$3o = "meshUVSpaceRendererFinaliserVertexShader"; +const shader$3n = `attribute position: vec3f;attribute uv: vec2f;uniform worldViewProjection: mat4x4f;varying vUV: vec2f;@vertex +fn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position=uniforms.worldViewProjection* vec4f(input.position,1.0);vertexOutputs.positionvUV=input.uv;} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3o]) { + ShaderStore.ShadersStoreWGSL[name$3o] = shader$3n; +} + +/** + * Defines the list of states available for a task inside a AssetsManager + */ +var AssetTaskState; +(function (AssetTaskState) { + /** + * Initialization + */ + AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT"; + /** + * Running + */ + AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING"; + /** + * Done + */ + AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE"; + /** + * Error + */ + AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR"; +})(AssetTaskState || (AssetTaskState = {})); + +Observable.prototype.notifyObserversWithPromise = async function (eventData, mask = -1, target, currentTarget, userInfo) { + // create an empty promise + let p = Promise.resolve(eventData); + // no observers? return this promise. + if (!this.observers.length) { + return p; + } + const state = this._eventState; + state.mask = mask; + state.target = target; + state.currentTarget = currentTarget; + state.skipNextObservers = false; + state.userInfo = userInfo; + // execute one callback after another (not using Promise.all, the order is important) + this.observers.forEach((obs) => { + if (state.skipNextObservers) { + return; + } + if (obs._willBeUnregistered) { + return; + } + if (obs.mask & mask) { + if (obs.scope) { + p = p.then((lastReturnedValue) => { + state.lastReturnValue = lastReturnedValue; + return obs.callback.apply(obs.scope, [eventData, state]); + }); + } + else { + p = p.then((lastReturnedValue) => { + state.lastReturnValue = lastReturnedValue; + return obs.callback(eventData, state); + }); + } + if (obs.unregisterOnNextCall) { + this._deferUnregister(obs); + } + } + }); + // return the eventData + await p; + return eventData; +}; + +// Do not edit. +const name$3n = "lodCubePixelShader"; +const shader$3m = `precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform int gamma;void main(void) +{vec2 uv=vUV*2.0-1.0; +#ifdef POSITIVEX +gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod); +#endif +#ifdef NEGATIVEX +gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod); +#endif +#ifdef POSITIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod); +#endif +#ifdef NEGATIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod); +#endif +#ifdef POSITIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod); +#endif +#ifdef NEGATIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod); +#endif +if (gamma==0) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3n]) { + ShaderStore.ShadersStore[name$3n] = shader$3m; +} + +const lodCube_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3m = "lodPixelShader"; +const shader$3l = `#extension GL_EXT_shader_texture_lod : enable +precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform int gamma;void main(void) +{gl_FragColor=texture2DLodEXT(textureSampler,vUV,lod);if (gamma==0) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3m]) { + ShaderStore.ShadersStore[name$3m] = shader$3l; +} + +const lod_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3l = "lodCubePixelShader"; +const shader$3k = `const GammaEncodePowerApprox=1.0/2.2;varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube;uniform lod: f32;uniform gamma: i32;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {let uv=fragmentInputs.vUV*2.0-1.0; +#ifdef POSITIVEX +fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x),uniforms.lod); +#endif +#ifdef NEGATIVEX +fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x),uniforms.lod); +#endif +#ifdef POSITIVEY +fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x),uniforms.lod); +#endif +#ifdef NEGATIVEY +fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x),uniforms.lod); +#endif +#ifdef POSITIVEZ +fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv,1.001),uniforms.lod); +#endif +#ifdef NEGATIVEZ +fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv,-1.001),uniforms.lod); +#endif +if (uniforms.gamma==0) {fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb,vec3f(GammaEncodePowerApprox)),fragmentOutputs.color.a);}} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3l]) { + ShaderStore.ShadersStoreWGSL[name$3l] = shader$3k; +} + +const lodCube_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3k = "lodPixelShader"; +const shader$3j = `const GammaEncodePowerApprox=1.0/2.2;varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform lod: f32;uniform gamma: i32;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,fragmentInputs.vUV,uniforms.lod);if (uniforms.gamma==0) {fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb,vec3f(GammaEncodePowerApprox)),fragmentOutputs.color.a);}} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3k]) { + ShaderStore.ShadersStoreWGSL[name$3k] = shader$3j; +} + +const lod_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * Fxaa post process + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#fxaa + */ +class FxaaPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "FxaaPostProcess" string + */ + getClassName() { + return "FxaaPostProcess"; + } + constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0) { + super(name, "fxaa", ["texelSize"], null, options, camera, samplingMode || Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true); + const defines = this._getDefines(); + this.updateEffect(defines); + this.onApplyObservable.add((effect) => { + const texelSize = this.texelSize; + effect.setFloat2("texelSize", texelSize.x, texelSize.y); + }); + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => fxaa_fragment), Promise.resolve().then(() => fxaa_vertex)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => fxaa_fragment$1), Promise.resolve().then(() => fxaa_vertex$1)])); + } + super._gatherImports(useWebGPU, list); + } + _getDefines() { + const engine = this.getEngine(); + if (!engine) { + return null; + } + const driverInfo = engine.extractDriverInfo(); + if (driverInfo.toLowerCase().indexOf("mali") > -1) { + return "#define MALI 1\n"; + } + return null; + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new FxaaPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +RegisterClass("BABYLON.FxaaPostProcess", FxaaPostProcess); + +let screenshotCanvas = null; +/** + * Captures a screenshot of the current rendering + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG + * @param engine defines the rendering engine + * @param camera defines the source camera. If the camera is not the scene's active camera, {@link CreateScreenshotUsingRenderTarget} will be used instead, and `useFill` will be ignored + * @param size This parameter can be set to a single number or to an object with the + * following (optional) properties: precision, width, height. If a single number is passed, + * it will be used for both width and height. If an object is passed, the screenshot size + * will be derived from the parameters. The precision property is a multiplier allowing + * rendering at a higher or lower resolution + * @param successCallback defines the callback receives a single parameter which contains the + * screenshot as a string of base64-encoded characters. This string can be assigned to the + * src parameter of an to display it + * @param mimeType defines the MIME type of the screenshot image (default: image/png). + * Check your browser for supported MIME types + * @param forceDownload force the system to download the image even if a successCallback is provided + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @param useFill fill the screenshot dimensions with the render canvas and clip any overflow. If false, fit the canvas within the screenshot, as in letterboxing. + */ +function CreateScreenshot(engine, camera, size, successCallback, mimeType = "image/png", forceDownload = false, quality, useFill = false) { + const { height, width } = _GetScreenshotSize(engine, camera, size); + if (!(height && width)) { + Logger.Error("Invalid 'size' parameter !"); + return; + } + const scene = camera.getScene(); + if (scene.activeCamera !== camera) { + CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => { + if (forceDownload) { + const blob = new Blob([data]); + Tools.DownloadBlob(blob); + if (successCallback) { + successCallback(""); + } + } + else if (successCallback) { + successCallback(data); + } + }, mimeType, 1.0, engine.getCreationOptions().antialias, undefined, undefined, undefined, undefined, quality); + return; + } + engine.onEndFrameObservable.addOnce(() => { + if (!screenshotCanvas) { + screenshotCanvas = document.createElement("canvas"); + } + screenshotCanvas.width = width; + screenshotCanvas.height = height; + const renderContext = screenshotCanvas.getContext("2d"); + const renderingCanvas = engine.getRenderingCanvas(); + if (!renderContext || !renderingCanvas) { + Logger.Error("Failed to create screenshot. Rendering context or rendering canvas is not available."); + return; + } + const srcWidth = renderingCanvas.width; + const srcHeight = renderingCanvas.height; + const destWidth = screenshotCanvas.width; + const destHeight = screenshotCanvas.height; + // Calculate scale factors for width and height. + const scaleX = destWidth / srcWidth; + const scaleY = destHeight / srcHeight; + // Use the larger of the two scales to fill the screenshot dimensions, else use the smaller to fit. + const scale = useFill ? Math.max(scaleX, scaleY) : Math.min(scaleX, scaleY); + const newWidth = srcWidth * scale; + const newHeight = srcHeight * scale; + // Center the image in the screenshot canvas + const offsetX = (destWidth - newWidth) / 2; + const offsetY = (destHeight - newHeight) / 2; + renderContext.drawImage(renderingCanvas, 0, 0, srcWidth, srcHeight, offsetX, offsetY, newWidth, newHeight); + if (forceDownload) { + Tools.EncodeScreenshotCanvasData(screenshotCanvas, undefined, mimeType, undefined, quality); + if (successCallback) { + successCallback(""); + } + } + else { + Tools.EncodeScreenshotCanvasData(screenshotCanvas, successCallback, mimeType, undefined, quality); + } + }); +} +/** + * Captures a screenshot of the current rendering + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG + * @param engine defines the rendering engine + * @param camera defines the source camera. If the camera is not the scene's active camera, {@link CreateScreenshotUsingRenderTarget} will be used instead, and `useFill` will be ignored + * @param size This parameter can be set to a single number or to an object with the + * following (optional) properties: precision, width, height. If a single number is passed, + * it will be used for both width and height. If an object is passed, the screenshot size + * will be derived from the parameters. The precision property is a multiplier allowing + * rendering at a higher or lower resolution + * @param mimeType defines the MIME type of the screenshot image (default: image/png). + * Check your browser for supported MIME types + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @param useFill fill the screenshot dimensions with the render canvas and clip any overflow. If false, fit the canvas within the screenshot, as in letterboxing. + * @returns screenshot as a string of base64-encoded characters. This string can be assigned + * to the src parameter of an to display it + */ +function CreateScreenshotAsync(engine, camera, size, mimeType = "image/png", quality, useFill = false) { + return new Promise((resolve, reject) => { + CreateScreenshot(engine, camera, size, (data) => { + if (typeof data !== "undefined") { + resolve(data); + } + else { + reject(new Error("Data is undefined")); + } + }, mimeType, undefined, quality, useFill); + }); +} +/** + * Generates an image screenshot from the specified camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG + * @param engine The engine to use for rendering + * @param camera The camera to use for rendering + * @param size This parameter can be set to a single number or to an object with the + * following (optional) properties: precision, width, height, finalWidth, finalHeight. If a single number is passed, + * it will be used for both width and height, as well as finalWidth, finalHeight. If an object is passed, the screenshot size + * will be derived from the parameters. The precision property is a multiplier allowing + * rendering at a higher or lower resolution + * @param successCallback The callback receives a single parameter which contains the + * screenshot as a string of base64-encoded characters. This string can be assigned to the + * src parameter of an to display it + * @param mimeType The MIME type of the screenshot image (default: image/png). + * Check your browser for supported MIME types + * @param samples Texture samples (default: 1) + * @param antialiasing Whether antialiasing should be turned on or not (default: false) + * @param fileName A name for for the downloaded file. + * @param renderSprites Whether the sprites should be rendered or not (default: false) + * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) + * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true) + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @param customizeTexture An optional callback that can be used to modify the render target texture before taking the screenshot. This can be used, for instance, to enable camera post-processes before taking the screenshot. + * @param customDumpData The function to use to dump the data. If not provided, the default DumpData function will be used. + */ +function CreateScreenshotUsingRenderTarget(engine, camera, size, successCallback, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture, customDumpData) { + const { height, width, finalWidth, finalHeight } = _GetScreenshotSize(engine, camera, size); + const targetTextureSize = { width, height }; + if (!(height && width)) { + Logger.Error("Invalid 'size' parameter !"); + return; + } + // Prevent engine to render on screen while we do the screenshot + engine.skipFrameRender = true; + const originalGetRenderWidth = engine.getRenderWidth; + const originalGetRenderHeight = engine.getRenderHeight; + // Override getRenderWidth and getRenderHeight to return the desired size of the render + // A few internal methods are relying on the canvas size to compute the render size + // so we need to override these methods to ensure the correct size is used during the preparation of the render + // as well as the screenshot + engine.getRenderWidth = (useScreen = false) => { + if (!useScreen && engine._currentRenderTarget) { + return engine._currentRenderTarget.width; + } + return width; + }; + engine.getRenderHeight = (useScreen = false) => { + if (!useScreen && engine._currentRenderTarget) { + return engine._currentRenderTarget.height; + } + return height; + }; + // Trigger a resize event to ensure the intermediate renders have the correct size + if (engine.onResizeObservable.hasObservers()) { + engine.onResizeObservable.notifyObservers(engine); + } + const scene = camera.getScene(); + // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method) + const texture = new RenderTargetTexture("screenShot", targetTextureSize, scene, false, false, 0, false, Texture.BILINEAR_SAMPLINGMODE, undefined, enableStencilBuffer, undefined, undefined, undefined, samples); + texture.renderList = scene.meshes.slice(); + texture.samples = samples; + texture.renderSprites = renderSprites; + texture.activeCamera = camera; + texture.forceLayerMaskCheck = useLayerMask; + customizeTexture?.(texture); + const dumpDataFunc = customDumpData || DumpData; + const renderWhenReady = () => { + _retryWithInterval(() => texture.isReadyForRendering() && camera.isReady(true), () => { + engine.onEndFrameObservable.addOnce(() => { + if (finalWidth === width && finalHeight === height) { + texture.readPixels(undefined, undefined, undefined, false).then((data) => { + dumpDataFunc(width, height, data, successCallback, mimeType, fileName, true, undefined, quality); + texture.dispose(); + }); + } + else { + const importPromise = engine.isWebGPU ? Promise.resolve().then(() => pass_fragment) : Promise.resolve().then(() => pass_fragment$1); + importPromise.then(() => ApplyPostProcess("pass", texture.getInternalTexture(), scene, undefined, undefined, undefined, finalWidth, finalHeight).then((texture) => { + engine._readTexturePixels(texture, finalWidth, finalHeight, -1, 0, null, true, false, 0, 0).then((data) => { + dumpDataFunc(finalWidth, finalHeight, data, successCallback, mimeType, fileName, true, undefined, quality); + texture.dispose(); + }); + })); + } + }); + scene.incrementRenderId(); + scene.resetCachedMaterial(); + // Record the original scene setup + const originalCamera = scene.activeCamera; + const originalCameras = scene.activeCameras; + const originalOutputRenderTarget = camera.outputRenderTarget; + const originalSpritesEnabled = scene.spritesEnabled; + // Swap with the requested one + scene.activeCamera = camera; + scene.activeCameras = null; + camera.outputRenderTarget = texture; + scene.spritesEnabled = renderSprites; + const currentMeshList = scene.meshes; + scene.meshes = texture.renderList || scene.meshes; + // render the scene on the RTT + try { + scene.render(); + } + finally { + // Restore the original scene camera setup + scene.activeCamera = originalCamera; + scene.activeCameras = originalCameras; + camera.outputRenderTarget = originalOutputRenderTarget; + scene.spritesEnabled = originalSpritesEnabled; + scene.meshes = currentMeshList; + engine.getRenderWidth = originalGetRenderWidth; + engine.getRenderHeight = originalGetRenderHeight; + // Trigger a resize event to ensure the intermediate renders have the correct size + if (engine.onResizeObservable.hasObservers()) { + engine.onResizeObservable.notifyObservers(engine); + } + camera.getProjectionMatrix(true); // Force cache refresh; + engine.skipFrameRender = false; + } + }, () => { + // Restore engine frame rendering on error + engine.skipFrameRender = false; + engine.getRenderWidth = originalGetRenderWidth; + engine.getRenderHeight = originalGetRenderHeight; + }); + }; + const renderToTexture = () => { + // render the RTT + scene.incrementRenderId(); + scene.resetCachedMaterial(); + renderWhenReady(); + }; + if (antialiasing) { + const fxaaPostProcess = new FxaaPostProcess("antialiasing", 1.0, scene.activeCamera); + texture.addPostProcess(fxaaPostProcess); + // Async Shader Compilation can lead to none ready effects in synchronous code + fxaaPostProcess.onEffectCreatedObservable.addOnce((e) => { + if (!e.isReady()) { + e.onCompiled = () => { + renderToTexture(); + }; + } + // The effect is ready we can render + else { + renderToTexture(); + } + }); + } + else { + // No need to wait for extra resources to be ready + renderToTexture(); + } +} +/** + * Generates an image screenshot from the specified camera. + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG + * @param engine The engine to use for rendering + * @param camera The camera to use for rendering + * @param size This parameter can be set to a single number or to an object with the + * following (optional) properties: precision, width, height. If a single number is passed, + * it will be used for both width and height. If an object is passed, the screenshot size + * will be derived from the parameters. The precision property is a multiplier allowing + * rendering at a higher or lower resolution + * @param mimeType The MIME type of the screenshot image (default: image/png). + * Check your browser for supported MIME types + * @param samples Texture samples (default: 1) + * @param antialiasing Whether antialiasing should be turned on or not (default: false) + * @param fileName A name for for the downloaded file. + * @param renderSprites Whether the sprites should be rendered or not (default: false) + * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) + * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true) + * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. + * @param customizeTexture An optional callback that can be used to modify the render target texture before taking the screenshot. This can be used, for instance, to enable camera post-processes before taking the screenshot. + * @param customDumpData The function to use to dump the data. If not provided, the default DumpData function will be used. + * @returns screenshot as a string of base64-encoded characters. This string can be assigned + * to the src parameter of an to display it + */ +function CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture, customDumpData) { + return new Promise((resolve, reject) => { + CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => { + if (typeof data !== "undefined") { + resolve(data); + } + else { + reject(new Error("Data is undefined")); + } + }, mimeType, samples, antialiasing, fileName, renderSprites, enableStencilBuffer, useLayerMask, quality, customizeTexture, customDumpData); + }); +} +/** + * Gets height and width for screenshot size + * @param engine The engine to use for rendering + * @param camera The camera to use for rendering + * @param size This size of the screenshot. can be a number or an object implementing IScreenshotSize + * @returns height and width for screenshot size + */ +function _GetScreenshotSize(engine, camera, size) { + let height = 0; + let width = 0; + let finalWidth = 0; + let finalHeight = 0; + //If a size value defined as object + if (typeof size === "object") { + const precision = size.precision + ? Math.abs(size.precision) // prevent GL_INVALID_VALUE : glViewport: negative width/height + : 1; + //If a width and height values is specified + if (size.width && size.height) { + height = size.height * precision; + width = size.width * precision; + } + //If passing only width, computing height to keep display canvas ratio. + else if (size.width && !size.height) { + width = size.width * precision; + height = Math.round(width / engine.getAspectRatio(camera)); + } + //If passing only height, computing width to keep display canvas ratio. + else if (size.height && !size.width) { + height = size.height * precision; + width = Math.round(height * engine.getAspectRatio(camera)); + } + else { + width = Math.round(engine.getRenderWidth() * precision); + height = Math.round(width / engine.getAspectRatio(camera)); + } + //If a finalWidth and finalHeight values is specified + if (size.finalWidth && size.finalHeight) { + finalHeight = size.finalHeight; + finalWidth = size.finalWidth; + } + //If passing only finalWidth, computing finalHeight to keep display canvas ratio. + else if (size.finalWidth && !size.finalHeight) { + finalWidth = size.finalWidth; + finalHeight = Math.round(finalWidth / engine.getAspectRatio(camera)); + } + //If passing only finalHeight, computing finalWidth to keep display canvas ratio. + else if (size.finalHeight && !size.finalWidth) { + finalHeight = size.finalHeight; + finalWidth = Math.round(finalHeight * engine.getAspectRatio(camera)); + } + else { + finalWidth = width; + finalHeight = height; + } + } + //Assuming here that "size" parameter is a number + else if (!isNaN(size)) { + height = size; + width = size; + finalWidth = size; + finalHeight = size; + } + // When creating the image data from the CanvasRenderingContext2D, the width and height is clamped to the size of the _gl context + // On certain GPUs, it seems as if the _gl context truncates to an integer automatically. Therefore, if a user tries to pass the width of their canvas element + // and it happens to be a float (1000.5 x 600.5 px), the engine.readPixels will return a different size array than context.createImageData + // to resolve this, we truncate the floats here to ensure the same size + if (width) { + width = Math.floor(width); + } + if (height) { + height = Math.floor(height); + } + if (finalWidth) { + finalWidth = Math.floor(finalWidth); + } + if (finalHeight) { + finalHeight = Math.floor(finalHeight); + } + return { height: height | 0, width: width | 0, finalWidth: finalWidth | 0, finalHeight: finalHeight | 0 }; +} +/** + * This will be executed automatically for UMD and es5. + * If esm dev wants the side effects to execute they will have to run it manually + * Once we build native modules those need to be exported. + * @internal + */ +const initSideEffects = () => { + // References the dependencies. + Tools.CreateScreenshot = CreateScreenshot; + Tools.CreateScreenshotAsync = CreateScreenshotAsync; + Tools.CreateScreenshotUsingRenderTarget = CreateScreenshotUsingRenderTarget; + Tools.CreateScreenshotUsingRenderTargetAsync = CreateScreenshotUsingRenderTargetAsync; +}; +initSideEffects(); + +/** + * Enum that determines the text-wrapping mode to use. + */ +var InspectableType; +(function (InspectableType) { + /** + * Checkbox for booleans + */ + InspectableType[InspectableType["Checkbox"] = 0] = "Checkbox"; + /** + * Sliders for numbers + */ + InspectableType[InspectableType["Slider"] = 1] = "Slider"; + /** + * Vector3 + */ + InspectableType[InspectableType["Vector3"] = 2] = "Vector3"; + /** + * Quaternions + */ + InspectableType[InspectableType["Quaternion"] = 3] = "Quaternion"; + /** + * Color3 + */ + InspectableType[InspectableType["Color3"] = 4] = "Color3"; + /** + * String + */ + InspectableType[InspectableType["String"] = 5] = "String"; + /** + * Button + */ + InspectableType[InspectableType["Button"] = 6] = "Button"; + /** + * Options + */ + InspectableType[InspectableType["Options"] = 7] = "Options"; + /** + * Tab + */ + InspectableType[InspectableType["Tab"] = 8] = "Tab"; + /** + * File button + */ + InspectableType[InspectableType["FileButton"] = 9] = "FileButton"; + /** + * Vector2 + */ + InspectableType[InspectableType["Vector2"] = 10] = "Vector2"; +})(InspectableType || (InspectableType = {})); + +/** Class used to store color4 gradient */ +class ColorGradient { + /** + * Creates a new color4 gradient + * @param gradient gets or sets the gradient value (between 0 and 1) + * @param color1 gets or sets first associated color + * @param color2 gets or sets first second color + */ + constructor( + /** + * Gets or sets the gradient value (between 0 and 1) + */ + gradient, + /** + * Gets or sets first associated color + */ + color1, + /** + * Gets or sets second associated color + */ + color2) { + this.gradient = gradient; + this.color1 = color1; + this.color2 = color2; + } + /** + * Will get a color picked randomly between color1 and color2. + * If color2 is undefined then color1 will be used + * @param result defines the target Color4 to store the result in + */ + getColorToRef(result) { + if (!this.color2) { + result.copyFrom(this.color1); + return; + } + Color4.LerpToRef(this.color1, this.color2, Math.random(), result); + } +} +/** Class used to store color 3 gradient */ +class Color3Gradient { + /** + * Creates a new color3 gradient + * @param gradient gets or sets the gradient value (between 0 and 1) + * @param color gets or sets associated color + */ + constructor( + /** + * Gets or sets the gradient value (between 0 and 1) + */ + gradient, + /** + * Gets or sets the associated color + */ + color) { + this.gradient = gradient; + this.color = color; + } +} +/** Class used to store factor gradient */ +class FactorGradient { + /** + * Creates a new factor gradient + * @param gradient gets or sets the gradient value (between 0 and 1) + * @param factor1 gets or sets first associated factor + * @param factor2 gets or sets second associated factor + */ + constructor( + /** + * Gets or sets the gradient value (between 0 and 1) + */ + gradient, + /** + * Gets or sets first associated factor + */ + factor1, + /** + * Gets or sets second associated factor + */ + factor2) { + this.gradient = gradient; + this.factor1 = factor1; + this.factor2 = factor2; + } + /** + * Will get a number picked randomly between factor1 and factor2. + * If factor2 is undefined then factor1 will be used + * @returns the picked number + */ + getFactor() { + if (this.factor2 === undefined || this.factor2 === this.factor1) { + return this.factor1; + } + return this.factor1 + (this.factor2 - this.factor1) * Math.random(); + } +} +/** + * Helper used to simplify some generic gradient tasks + */ +class GradientHelper { + /** + * Gets the current gradient from an array of IValueGradient + * @param ratio defines the current ratio to get + * @param gradients defines the array of IValueGradient + * @param updateFunc defines the callback function used to get the final value from the selected gradients + */ + static GetCurrentGradient(ratio, gradients, updateFunc) { + // Use last index if over + if (gradients[0].gradient > ratio) { + updateFunc(gradients[0], gradients[0], 1.0); + return; + } + for (let gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) { + const currentGradient = gradients[gradientIndex]; + const nextGradient = gradients[gradientIndex + 1]; + if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) { + const scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient); + updateFunc(currentGradient, nextGradient, scale); + return; + } + } + // Use last index if over + const lastIndex = gradients.length - 1; + updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0); + } +} + +/** + * Class for storing data to local storage if available or in-memory storage otherwise + */ +class DataStorage { + static _GetStorage() { + try { + localStorage.setItem("test", ""); + localStorage.removeItem("test"); + return localStorage; + } + catch { + const inMemoryStorage = {}; + return { + getItem: (key) => { + const value = inMemoryStorage[key]; + return value === undefined ? null : value; + }, + setItem: (key, value) => { + inMemoryStorage[key] = value; + }, + }; + } + } + /** + * Reads a string from the data storage + * @param key The key to read + * @param defaultValue The value if the key doesn't exist + * @returns The string value + */ + static ReadString(key, defaultValue) { + const value = this._Storage.getItem(key); + return value !== null ? value : defaultValue; + } + /** + * Writes a string to the data storage + * @param key The key to write + * @param value The value to write + */ + static WriteString(key, value) { + this._Storage.setItem(key, value); + } + /** + * Reads a boolean from the data storage + * @param key The key to read + * @param defaultValue The value if the key doesn't exist + * @returns The boolean value + */ + static ReadBoolean(key, defaultValue) { + const value = this._Storage.getItem(key); + return value !== null ? value === "true" : defaultValue; + } + /** + * Writes a boolean to the data storage + * @param key The key to write + * @param value The value to write + */ + static WriteBoolean(key, value) { + this._Storage.setItem(key, value ? "true" : "false"); + } + /** + * Reads a number from the data storage + * @param key The key to read + * @param defaultValue The value if the key doesn't exist + * @returns The number value + */ + static ReadNumber(key, defaultValue) { + const value = this._Storage.getItem(key); + return value !== null ? parseFloat(value) : defaultValue; + } + /** + * Writes a number to the data storage + * @param key The key to write + * @param value The value to write + */ + static WriteNumber(key, value) { + this._Storage.setItem(key, value.toString()); + } +} +DataStorage._Storage = DataStorage._GetStorage(); + +/** + * A particle represents one of the element emitted by a particle system. + * This is mainly define by its coordinates, direction, velocity and age. + */ +class Particle { + /** + * Creates a new instance Particle + * @param particleSystem the particle system the particle belongs to + */ + constructor( + /** + * The particle system the particle belongs to. + */ + particleSystem) { + this.particleSystem = particleSystem; + /** + * The world position of the particle in the scene. + */ + this.position = Vector3.Zero(); + /** + * The world direction of the particle in the scene. + */ + this.direction = Vector3.Zero(); + /** + * The color of the particle. + */ + this.color = new Color4(0, 0, 0, 0); + /** + * The color change of the particle per step. + */ + this.colorStep = new Color4(0, 0, 0, 0); + /** + * Defines how long will the life of the particle be. + */ + this.lifeTime = 1.0; + /** + * The current age of the particle. + */ + this.age = 0; + /** + * The current size of the particle. + */ + this.size = 0; + /** + * The current scale of the particle. + */ + this.scale = new Vector2(1, 1); + /** + * The current angle of the particle. + */ + this.angle = 0; + /** + * Defines how fast is the angle changing. + */ + this.angularSpeed = 0; + /** + * Defines the cell index used by the particle to be rendered from a sprite. + */ + this.cellIndex = 0; + /** @internal */ + this._attachedSubEmitters = null; + /** @internal */ + this._currentColor1 = new Color4(0, 0, 0, 0); + /** @internal */ + this._currentColor2 = new Color4(0, 0, 0, 0); + /** @internal */ + this._currentSize1 = 0; + /** @internal */ + this._currentSize2 = 0; + /** @internal */ + this._currentAngularSpeed1 = 0; + /** @internal */ + this._currentAngularSpeed2 = 0; + /** @internal */ + this._currentVelocity1 = 0; + /** @internal */ + this._currentVelocity2 = 0; + /** @internal */ + this._currentLimitVelocity1 = 0; + /** @internal */ + this._currentLimitVelocity2 = 0; + /** @internal */ + this._currentDrag1 = 0; + /** @internal */ + this._currentDrag2 = 0; + this.id = Particle._Count++; + if (!this.particleSystem.isAnimationSheetEnabled) { + return; + } + this._updateCellInfoFromSystem(); + } + _updateCellInfoFromSystem() { + this.cellIndex = this.particleSystem.startSpriteCellID; + } + /** + * Defines how the sprite cell index is updated for the particle + */ + updateCellIndex() { + let offsetAge = this.age; + let changeSpeed = this.particleSystem.spriteCellChangeSpeed; + if (this.particleSystem.spriteRandomStartCell) { + if (this._randomCellOffset === undefined) { + this._randomCellOffset = Math.random() * this.lifeTime; + } + if (changeSpeed === 0) { + // Special case when speed = 0 meaning we want to stay on initial cell + changeSpeed = 1; + offsetAge = this._randomCellOffset; + } + else { + offsetAge += this._randomCellOffset; + } + } + const dist = this._initialEndSpriteCellID - this._initialStartSpriteCellID + 1; + let ratio; + if (this._initialSpriteCellLoop) { + ratio = Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime); + } + else { + ratio = Clamp((offsetAge * changeSpeed) / this.lifeTime); + } + this.cellIndex = (this._initialStartSpriteCellID + ratio * dist) | 0; + } + /** + * @internal + */ + _inheritParticleInfoToSubEmitter(subEmitter) { + if (subEmitter.particleSystem.emitter.position) { + const emitterMesh = subEmitter.particleSystem.emitter; + emitterMesh.position.copyFrom(this.position); + if (subEmitter.inheritDirection) { + const temp = TmpVectors.Vector3[0]; + this.direction.normalizeToRef(temp); + emitterMesh.setDirection(temp, 0, Math.PI / 2); + } + } + else { + const emitterPosition = subEmitter.particleSystem.emitter; + emitterPosition.copyFrom(this.position); + } + // Set inheritedVelocityOffset to be used when new particles are created + this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, TmpVectors.Vector3[0]); + subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(TmpVectors.Vector3[0]); + } + /** @internal */ + _inheritParticleInfoToSubEmitters() { + if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) { + this._attachedSubEmitters.forEach((subEmitter) => { + this._inheritParticleInfoToSubEmitter(subEmitter); + }); + } + } + /** @internal */ + _reset() { + this.age = 0; + this.id = Particle._Count++; + this._currentColorGradient = null; + this._currentSizeGradient = null; + this._currentAngularSpeedGradient = null; + this._currentVelocityGradient = null; + this._currentLimitVelocityGradient = null; + this._currentDragGradient = null; + this.cellIndex = this.particleSystem.startSpriteCellID; + this._randomCellOffset = undefined; + } + /** + * Copy the properties of particle to another one. + * @param other the particle to copy the information to. + */ + copyTo(other) { + other.position.copyFrom(this.position); + if (this._initialDirection) { + if (other._initialDirection) { + other._initialDirection.copyFrom(this._initialDirection); + } + else { + other._initialDirection = this._initialDirection.clone(); + } + } + else { + other._initialDirection = null; + } + other.direction.copyFrom(this.direction); + if (this._localPosition) { + if (other._localPosition) { + other._localPosition.copyFrom(this._localPosition); + } + else { + other._localPosition = this._localPosition.clone(); + } + } + other.color.copyFrom(this.color); + other.colorStep.copyFrom(this.colorStep); + other.lifeTime = this.lifeTime; + other.age = this.age; + other._randomCellOffset = this._randomCellOffset; + other.size = this.size; + other.scale.copyFrom(this.scale); + other.angle = this.angle; + other.angularSpeed = this.angularSpeed; + other.particleSystem = this.particleSystem; + other.cellIndex = this.cellIndex; + other.id = this.id; + other._attachedSubEmitters = this._attachedSubEmitters; + if (this._currentColorGradient) { + other._currentColorGradient = this._currentColorGradient; + other._currentColor1.copyFrom(this._currentColor1); + other._currentColor2.copyFrom(this._currentColor2); + } + if (this._currentSizeGradient) { + other._currentSizeGradient = this._currentSizeGradient; + other._currentSize1 = this._currentSize1; + other._currentSize2 = this._currentSize2; + } + if (this._currentAngularSpeedGradient) { + other._currentAngularSpeedGradient = this._currentAngularSpeedGradient; + other._currentAngularSpeed1 = this._currentAngularSpeed1; + other._currentAngularSpeed2 = this._currentAngularSpeed2; + } + if (this._currentVelocityGradient) { + other._currentVelocityGradient = this._currentVelocityGradient; + other._currentVelocity1 = this._currentVelocity1; + other._currentVelocity2 = this._currentVelocity2; + } + if (this._currentLimitVelocityGradient) { + other._currentLimitVelocityGradient = this._currentLimitVelocityGradient; + other._currentLimitVelocity1 = this._currentLimitVelocity1; + other._currentLimitVelocity2 = this._currentLimitVelocity2; + } + if (this._currentDragGradient) { + other._currentDragGradient = this._currentDragGradient; + other._currentDrag1 = this._currentDrag1; + other._currentDrag2 = this._currentDrag2; + } + if (this.particleSystem.isAnimationSheetEnabled) { + other._initialStartSpriteCellID = this._initialStartSpriteCellID; + other._initialEndSpriteCellID = this._initialEndSpriteCellID; + other._initialSpriteCellLoop = this._initialSpriteCellLoop; + } + if (this.particleSystem.useRampGradients) { + if (other.remapData && this.remapData) { + other.remapData.copyFrom(this.remapData); + } + else { + other.remapData = new Vector4(0, 0, 0, 0); + } + } + if (this._randomNoiseCoordinates1) { + if (other._randomNoiseCoordinates1) { + other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1); + other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2); + } + else { + other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone(); + other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone(); + } + } + } +} +Particle._Count = 0; + +/** + * Particle emitter emitting particles from the inside of a box. + * It emits the particles randomly between 2 given directions. + */ +class BoxParticleEmitter { + /** + * Creates a new instance BoxParticleEmitter + */ + constructor() { + /** + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + */ + this.direction1 = new Vector3(0, 1.0, 0); + /** + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + */ + this.direction2 = new Vector3(0, 1.0, 0); + /** + * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + */ + this.minEmitBox = new Vector3(-0.5, -0.5, -0.5); + /** + * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. + */ + this.maxEmitBox = new Vector3(0.5, 0.5, 0.5); + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + * @param particle is the particle we are computed the direction for + * @param isLocal defines if the direction should be set in local space + */ + startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { + const randX = RandomRange(this.direction1.x, this.direction2.x); + const randY = RandomRange(this.direction1.y, this.direction2.y); + const randZ = RandomRange(this.direction1.z, this.direction2.z); + if (isLocal) { + directionToUpdate.x = randX; + directionToUpdate.y = randY; + directionToUpdate.z = randZ; + return; + } + Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); + } + /** + * Called by the particle System when the position is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param positionToUpdate is the position vector to update with the result + * @param particle is the particle we are computed the position for + * @param isLocal defines if the position should be set in local space + */ + startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { + const randX = RandomRange(this.minEmitBox.x, this.maxEmitBox.x); + const randY = RandomRange(this.minEmitBox.y, this.maxEmitBox.y); + const randZ = RandomRange(this.minEmitBox.z, this.maxEmitBox.z); + if (isLocal) { + positionToUpdate.x = randX; + positionToUpdate.y = randY; + positionToUpdate.z = randZ; + return; + } + Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate); + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new BoxParticleEmitter(); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + applyToShader(uboOrEffect) { + uboOrEffect.setVector3("direction1", this.direction1); + uboOrEffect.setVector3("direction2", this.direction2); + uboOrEffect.setVector3("minEmitBox", this.minEmitBox); + uboOrEffect.setVector3("maxEmitBox", this.maxEmitBox); + } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + buildUniformLayout(ubo) { + ubo.addUniform("direction1", 3); + ubo.addUniform("direction2", 3); + ubo.addUniform("minEmitBox", 3); + ubo.addUniform("maxEmitBox", 3); + } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + return "#define BOXEMITTER"; + } + /** + * Returns the string "BoxParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "BoxParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = {}; + serializationObject.type = this.getClassName(); + serializationObject.direction1 = this.direction1.asArray(); + serializationObject.direction2 = this.direction2.asArray(); + serializationObject.minEmitBox = this.minEmitBox.asArray(); + serializationObject.maxEmitBox = this.maxEmitBox.asArray(); + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + */ + parse(serializationObject) { + Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); + Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); + Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox); + Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox); + } +} + +/** + * This represents a thin particle system in Babylon. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function. + * This thin version contains a limited subset of the total features in order to provide users with a way to get particles but with a smaller footprint + * @example https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro + */ +class ThinParticleSystem extends BaseParticleSystem { + /** + * Sets a callback that will be triggered when the system is disposed + */ + set onDispose(callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + } + /** Gets or sets a boolean indicating that ramp gradients must be used + * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients + */ + get useRampGradients() { + return this._useRampGradients; + } + set useRampGradients(value) { + if (this._useRampGradients === value) { + return; + } + this._useRampGradients = value; + this._resetEffect(); + } + /** + * Gets the current list of active particles + */ + get particles() { + return this._particles; + } + /** + * Gets the shader language used in this material. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Gets the number of particles active at the same time. + * @returns The number of active particles. + */ + getActiveCount() { + return this._particles.length; + } + /** + * Returns the string "ParticleSystem" + * @returns a string containing the class name + */ + getClassName() { + return "ParticleSystem"; + } + /** + * Gets a boolean indicating that the system is stopping + * @returns true if the system is currently stopping + */ + isStopping() { + return this._stopped && this.isAlive(); + } + /** + * Gets the custom effect used to render the particles + * @param blendMode Blend mode for which the effect should be retrieved + * @returns The effect + */ + getCustomEffect(blendMode = 0) { + return this._customWrappers[blendMode]?.effect ?? this._customWrappers[0].effect; + } + _getCustomDrawWrapper(blendMode = 0) { + return this._customWrappers[blendMode] ?? this._customWrappers[0]; + } + /** + * Sets the custom effect used to render the particles + * @param effect The effect to set + * @param blendMode Blend mode for which the effect should be set + */ + setCustomEffect(effect, blendMode = 0) { + this._customWrappers[blendMode] = new DrawWrapper(this._engine); + this._customWrappers[blendMode].effect = effect; + if (this._customWrappers[blendMode].drawContext) { + this._customWrappers[blendMode].drawContext.useInstancing = this._useInstancing; + } + } + /** + * Observable that will be called just before the particles are drawn + */ + get onBeforeDrawParticlesObservable() { + if (!this._onBeforeDrawParticlesObservable) { + this._onBeforeDrawParticlesObservable = new Observable(); + } + return this._onBeforeDrawParticlesObservable; + } + /** + * Gets the name of the particle vertex shader + */ + get vertexShaderName() { + return "particles"; + } + /** + * Gets the vertex buffers used by the particle system + */ + get vertexBuffers() { + return this._vertexBuffers; + } + /** + * Gets the index buffer used by the particle system (or null if no index buffer is used (if _useInstancing=true)) + */ + get indexBuffer() { + return this._indexBuffer; + } + /** + * Instantiates a particle system. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * @param name The name of the particle system + * @param capacity The max number of particles alive at the same time + * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene + * @param customEffect a custom effect used to change the way particles are rendered by default + * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture + * @param epsilon Offset used to render the particles + */ + constructor(name, capacity, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false, epsilon = 0.01) { + super(name); + this._emitterInverseWorldMatrix = Matrix.Identity(); + /** + * @internal + */ + this._inheritedVelocityOffset = new Vector3(); + /** + * An event triggered when the system is disposed + */ + this.onDisposeObservable = new Observable(); + /** + * An event triggered when the system is stopped + */ + this.onStoppedObservable = new Observable(); + this._particles = new Array(); + this._stockParticles = new Array(); + this._newPartsExcess = 0; + this._vertexBuffers = {}; + this._scaledColorStep = new Color4(0, 0, 0, 0); + this._colorDiff = new Color4(0, 0, 0, 0); + this._scaledDirection = Vector3.Zero(); + this._scaledGravity = Vector3.Zero(); + this._currentRenderId = -1; + this._useInstancing = false; + this._started = false; + this._stopped = false; + this._actualFrame = 0; + /** @internal */ + this._currentEmitRate1 = 0; + /** @internal */ + this._currentEmitRate2 = 0; + /** @internal */ + this._currentStartSize1 = 0; + /** @internal */ + this._currentStartSize2 = 0; + /** Indicates that the update of particles is done in the animate function */ + this.updateInAnimate = true; + this._rawTextureWidth = 256; + this._useRampGradients = false; + /** + * Specifies if the particles are updated in emitter local space or world space + */ + this.isLocal = false; + /** Indicates that the particle system is CPU based */ + this.isGPU = false; + /** Shader language used by the material */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + /** @internal */ + this._onBeforeDrawParticlesObservable = null; + /** @internal */ + this._emitFromParticle = (particle) => { + // Do nothing + }; + // start of sub system methods + /** + * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list. + * Its lifetime will start back at 0. + * @param particle + */ + this.recycleParticle = (particle) => { + // move particle from activeParticle list to stock particles + const lastParticle = this._particles.pop(); + if (lastParticle !== particle) { + lastParticle.copyTo(particle); + } + this._stockParticles.push(lastParticle); + }; + this._createParticle = () => { + let particle; + if (this._stockParticles.length !== 0) { + particle = this._stockParticles.pop(); + particle._reset(); + } + else { + particle = new Particle(this); + } + this._prepareParticle(particle); + return particle; + }; + this._shadersLoaded = false; + this._capacity = capacity; + this._epsilon = epsilon; + this._isAnimationSheetEnabled = isAnimationSheetEnabled; + if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") { + this._scene = sceneOrEngine || EngineStore.LastCreatedScene; + this._engine = this._scene.getEngine(); + this.uniqueId = this._scene.getUniqueId(); + this._scene.particleSystems.push(this); + } + else { + this._engine = sceneOrEngine; + this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange); + } + if (this._engine.getCaps().vertexArrayObject) { + this._vertexArrayObject = null; + } + this._initShaderSourceAsync(); + // Setup the default processing configuration to the scene. + this._attachImageProcessingConfiguration(null); + // eslint-disable-next-line @typescript-eslint/naming-convention + this._customWrappers = { 0: new DrawWrapper(this._engine) }; + this._customWrappers[0].effect = customEffect; + this._drawWrappers = []; + this._useInstancing = this._engine.getCaps().instancedArrays; + this._createIndexBuffer(); + this._createVertexBuffers(); + // Default emitter type + this.particleEmitterType = new BoxParticleEmitter(); + let noiseTextureData = null; + // Update + this.updateFunction = (particles) => { + let noiseTextureSize = null; + if (this.noiseTexture) { + // We need to get texture data back to CPU + noiseTextureSize = this.noiseTexture.getSize(); + this.noiseTexture.getContent()?.then((data) => { + noiseTextureData = data; + }); + } + const sameParticleArray = particles === this._particles; + for (let index = 0; index < particles.length; index++) { + const particle = particles[index]; + let scaledUpdateSpeed = this._scaledUpdateSpeed; + const previousAge = particle.age; + particle.age += scaledUpdateSpeed; + // Evaluate step to death + if (particle.age > particle.lifeTime) { + const diff = particle.age - previousAge; + const oldDiff = particle.lifeTime - previousAge; + scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff; + particle.age = particle.lifeTime; + } + const ratio = particle.age / particle.lifeTime; + // Color + if (this._colorGradients && this._colorGradients.length > 0) { + GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => { + if (currentGradient !== particle._currentColorGradient) { + particle._currentColor1.copyFrom(particle._currentColor2); + nextGradient.getColorToRef(particle._currentColor2); + particle._currentColorGradient = currentGradient; + } + Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color); + }); + } + else { + particle.colorStep.scaleToRef(scaledUpdateSpeed, this._scaledColorStep); + particle.color.addInPlace(this._scaledColorStep); + if (particle.color.a < 0) { + particle.color.a = 0; + } + } + // Angular speed + if (this._angularSpeedGradients && this._angularSpeedGradients.length > 0) { + GradientHelper.GetCurrentGradient(ratio, this._angularSpeedGradients, (currentGradient, nextGradient, scale) => { + if (currentGradient !== particle._currentAngularSpeedGradient) { + particle._currentAngularSpeed1 = particle._currentAngularSpeed2; + particle._currentAngularSpeed2 = nextGradient.getFactor(); + particle._currentAngularSpeedGradient = currentGradient; + } + particle.angularSpeed = Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale); + }); + } + particle.angle += particle.angularSpeed * scaledUpdateSpeed; + // Direction + let directionScale = scaledUpdateSpeed; + /// Velocity + if (this._velocityGradients && this._velocityGradients.length > 0) { + GradientHelper.GetCurrentGradient(ratio, this._velocityGradients, (currentGradient, nextGradient, scale) => { + if (currentGradient !== particle._currentVelocityGradient) { + particle._currentVelocity1 = particle._currentVelocity2; + particle._currentVelocity2 = nextGradient.getFactor(); + particle._currentVelocityGradient = currentGradient; + } + directionScale *= Lerp(particle._currentVelocity1, particle._currentVelocity2, scale); + }); + } + particle.direction.scaleToRef(directionScale, this._scaledDirection); + /// Limit velocity + if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) { + GradientHelper.GetCurrentGradient(ratio, this._limitVelocityGradients, (currentGradient, nextGradient, scale) => { + if (currentGradient !== particle._currentLimitVelocityGradient) { + particle._currentLimitVelocity1 = particle._currentLimitVelocity2; + particle._currentLimitVelocity2 = nextGradient.getFactor(); + particle._currentLimitVelocityGradient = currentGradient; + } + const limitVelocity = Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale); + const currentVelocity = particle.direction.length(); + if (currentVelocity > limitVelocity) { + particle.direction.scaleInPlace(this.limitVelocityDamping); + } + }); + } + /// Drag + if (this._dragGradients && this._dragGradients.length > 0) { + GradientHelper.GetCurrentGradient(ratio, this._dragGradients, (currentGradient, nextGradient, scale) => { + if (currentGradient !== particle._currentDragGradient) { + particle._currentDrag1 = particle._currentDrag2; + particle._currentDrag2 = nextGradient.getFactor(); + particle._currentDragGradient = currentGradient; + } + const drag = Lerp(particle._currentDrag1, particle._currentDrag2, scale); + this._scaledDirection.scaleInPlace(1.0 - drag); + }); + } + if (this.isLocal && particle._localPosition) { + particle._localPosition.addInPlace(this._scaledDirection); + Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position); + } + else { + particle.position.addInPlace(this._scaledDirection); + } + // Noise + if (noiseTextureData && noiseTextureSize && particle._randomNoiseCoordinates1) { + const fetchedColorR = this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData); + const fetchedColorG = this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData); + const fetchedColorB = this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData); + const force = TmpVectors.Vector3[0]; + const scaledForce = TmpVectors.Vector3[1]; + force.copyFromFloats((2 * fetchedColorR - 1) * this.noiseStrength.x, (2 * fetchedColorG - 1) * this.noiseStrength.y, (2 * fetchedColorB - 1) * this.noiseStrength.z); + force.scaleToRef(scaledUpdateSpeed, scaledForce); + particle.direction.addInPlace(scaledForce); + } + // Gravity + this.gravity.scaleToRef(scaledUpdateSpeed, this._scaledGravity); + particle.direction.addInPlace(this._scaledGravity); + // Size + if (this._sizeGradients && this._sizeGradients.length > 0) { + GradientHelper.GetCurrentGradient(ratio, this._sizeGradients, (currentGradient, nextGradient, scale) => { + if (currentGradient !== particle._currentSizeGradient) { + particle._currentSize1 = particle._currentSize2; + particle._currentSize2 = nextGradient.getFactor(); + particle._currentSizeGradient = currentGradient; + } + particle.size = Lerp(particle._currentSize1, particle._currentSize2, scale); + }); + } + // Remap data + if (this._useRampGradients) { + if (this._colorRemapGradients && this._colorRemapGradients.length > 0) { + GradientHelper.GetCurrentGradient(ratio, this._colorRemapGradients, (currentGradient, nextGradient, scale) => { + const min = Lerp(currentGradient.factor1, nextGradient.factor1, scale); + const max = Lerp(currentGradient.factor2, nextGradient.factor2, scale); + particle.remapData.x = min; + particle.remapData.y = max - min; + }); + } + if (this._alphaRemapGradients && this._alphaRemapGradients.length > 0) { + GradientHelper.GetCurrentGradient(ratio, this._alphaRemapGradients, (currentGradient, nextGradient, scale) => { + const min = Lerp(currentGradient.factor1, nextGradient.factor1, scale); + const max = Lerp(currentGradient.factor2, nextGradient.factor2, scale); + particle.remapData.z = min; + particle.remapData.w = max - min; + }); + } + } + if (this._isAnimationSheetEnabled) { + particle.updateCellIndex(); + } + // Update the position of the attached sub-emitters to match their attached particle + particle._inheritParticleInfoToSubEmitters(); + if (particle.age >= particle.lifeTime) { + // Recycle by swapping with last particle + this._emitFromParticle(particle); + if (particle._attachedSubEmitters) { + particle._attachedSubEmitters.forEach((subEmitter) => { + subEmitter.particleSystem.disposeOnStop = true; + subEmitter.particleSystem.stop(); + }); + particle._attachedSubEmitters = null; + } + this.recycleParticle(particle); + if (sameParticleArray) { + index--; + } + continue; + } + } + }; + } + serialize(serializeTexture) { + throw new Error("Method not implemented."); + } + /** + * Clones the particle system. + * @param name The name of the cloned object + * @param newEmitter The new emitter to use + * @param cloneTexture Also clone the textures if true + */ + clone(name, newEmitter, cloneTexture = false) { + throw new Error("Method not implemented."); + } + _addFactorGradient(factorGradients, gradient, factor, factor2) { + const newGradient = new FactorGradient(gradient, factor, factor2); + factorGradients.push(newGradient); + factorGradients.sort((a, b) => { + if (a.gradient < b.gradient) { + return -1; + } + else if (a.gradient > b.gradient) { + return 1; + } + return 0; + }); + } + _removeFactorGradient(factorGradients, gradient) { + if (!factorGradients) { + return; + } + let index = 0; + for (const factorGradient of factorGradients) { + if (factorGradient.gradient === gradient) { + factorGradients.splice(index, 1); + break; + } + index++; + } + } + /** + * Adds a new life time gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the life time factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addLifeTimeGradient(gradient, factor, factor2) { + if (!this._lifeTimeGradients) { + this._lifeTimeGradients = []; + } + this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2); + return this; + } + /** + * Remove a specific life time gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeLifeTimeGradient(gradient) { + this._removeFactorGradient(this._lifeTimeGradients, gradient); + return this; + } + /** + * Adds a new size gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addSizeGradient(gradient, factor, factor2) { + if (!this._sizeGradients) { + this._sizeGradients = []; + } + this._addFactorGradient(this._sizeGradients, gradient, factor, factor2); + return this; + } + /** + * Remove a specific size gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeSizeGradient(gradient) { + this._removeFactorGradient(this._sizeGradients, gradient); + return this; + } + /** + * Adds a new color remap gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param min defines the color remap minimal range + * @param max defines the color remap maximal range + * @returns the current particle system + */ + addColorRemapGradient(gradient, min, max) { + if (!this._colorRemapGradients) { + this._colorRemapGradients = []; + } + this._addFactorGradient(this._colorRemapGradients, gradient, min, max); + return this; + } + /** + * Remove a specific color remap gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeColorRemapGradient(gradient) { + this._removeFactorGradient(this._colorRemapGradients, gradient); + return this; + } + /** + * Adds a new alpha remap gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param min defines the alpha remap minimal range + * @param max defines the alpha remap maximal range + * @returns the current particle system + */ + addAlphaRemapGradient(gradient, min, max) { + if (!this._alphaRemapGradients) { + this._alphaRemapGradients = []; + } + this._addFactorGradient(this._alphaRemapGradients, gradient, min, max); + return this; + } + /** + * Remove a specific alpha remap gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeAlphaRemapGradient(gradient) { + this._removeFactorGradient(this._alphaRemapGradients, gradient); + return this; + } + /** + * Adds a new angular speed gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the angular speed to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addAngularSpeedGradient(gradient, factor, factor2) { + if (!this._angularSpeedGradients) { + this._angularSpeedGradients = []; + } + this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2); + return this; + } + /** + * Remove a specific angular speed gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeAngularSpeedGradient(gradient) { + this._removeFactorGradient(this._angularSpeedGradients, gradient); + return this; + } + /** + * Adds a new velocity gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the velocity to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addVelocityGradient(gradient, factor, factor2) { + if (!this._velocityGradients) { + this._velocityGradients = []; + } + this._addFactorGradient(this._velocityGradients, gradient, factor, factor2); + return this; + } + /** + * Remove a specific velocity gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeVelocityGradient(gradient) { + this._removeFactorGradient(this._velocityGradients, gradient); + return this; + } + /** + * Adds a new limit velocity gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the limit velocity value to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addLimitVelocityGradient(gradient, factor, factor2) { + if (!this._limitVelocityGradients) { + this._limitVelocityGradients = []; + } + this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2); + return this; + } + /** + * Remove a specific limit velocity gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeLimitVelocityGradient(gradient) { + this._removeFactorGradient(this._limitVelocityGradients, gradient); + return this; + } + /** + * Adds a new drag gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the drag value to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addDragGradient(gradient, factor, factor2) { + if (!this._dragGradients) { + this._dragGradients = []; + } + this._addFactorGradient(this._dragGradients, gradient, factor, factor2); + return this; + } + /** + * Remove a specific drag gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeDragGradient(gradient) { + this._removeFactorGradient(this._dragGradients, gradient); + return this; + } + /** + * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property) + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the emit rate value to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addEmitRateGradient(gradient, factor, factor2) { + if (!this._emitRateGradients) { + this._emitRateGradients = []; + } + this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2); + return this; + } + /** + * Remove a specific emit rate gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeEmitRateGradient(gradient) { + this._removeFactorGradient(this._emitRateGradients, gradient); + return this; + } + /** + * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property) + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the start size value to affect to the specified gradient + * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from + * @returns the current particle system + */ + addStartSizeGradient(gradient, factor, factor2) { + if (!this._startSizeGradients) { + this._startSizeGradients = []; + } + this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2); + return this; + } + /** + * Remove a specific start size gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeStartSizeGradient(gradient) { + this._removeFactorGradient(this._startSizeGradients, gradient); + return this; + } + _createRampGradientTexture() { + if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture || !this._scene) { + return; + } + const data = new Uint8Array(this._rawTextureWidth * 4); + const tmpColor = TmpColors.Color3[0]; + for (let x = 0; x < this._rawTextureWidth; x++) { + const ratio = x / this._rawTextureWidth; + GradientHelper.GetCurrentGradient(ratio, this._rampGradients, (currentGradient, nextGradient, scale) => { + Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor); + data[x * 4] = tmpColor.r * 255; + data[x * 4 + 1] = tmpColor.g * 255; + data[x * 4 + 2] = tmpColor.b * 255; + data[x * 4 + 3] = 255; + }); + } + this._rampGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1); + } + /** + * Gets the current list of ramp gradients. + * You must use addRampGradient and removeRampGradient to update this list + * @returns the list of ramp gradients + */ + getRampGradients() { + return this._rampGradients; + } + /** Force the system to rebuild all gradients that need to be resync */ + forceRefreshGradients() { + this._syncRampGradientTexture(); + } + _syncRampGradientTexture() { + if (!this._rampGradients) { + return; + } + this._rampGradients.sort((a, b) => { + if (a.gradient < b.gradient) { + return -1; + } + else if (a.gradient > b.gradient) { + return 1; + } + return 0; + }); + if (this._rampGradientsTexture) { + this._rampGradientsTexture.dispose(); + this._rampGradientsTexture = null; + } + this._createRampGradientTexture(); + } + /** + * Adds a new ramp gradient used to remap particle colors + * @param gradient defines the gradient to use (between 0 and 1) + * @param color defines the color to affect to the specified gradient + * @returns the current particle system + */ + addRampGradient(gradient, color) { + if (!this._rampGradients) { + this._rampGradients = []; + } + const rampGradient = new Color3Gradient(gradient, color); + this._rampGradients.push(rampGradient); + this._syncRampGradientTexture(); + return this; + } + /** + * Remove a specific ramp gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeRampGradient(gradient) { + this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture); + this._rampGradientsTexture = null; + if (this._rampGradients && this._rampGradients.length > 0) { + this._createRampGradientTexture(); + } + return this; + } + /** + * Adds a new color gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param color1 defines the color to affect to the specified gradient + * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from + * @returns this particle system + */ + addColorGradient(gradient, color1, color2) { + if (!this._colorGradients) { + this._colorGradients = []; + } + const colorGradient = new ColorGradient(gradient, color1, color2); + this._colorGradients.push(colorGradient); + this._colorGradients.sort((a, b) => { + if (a.gradient < b.gradient) { + return -1; + } + else if (a.gradient > b.gradient) { + return 1; + } + return 0; + }); + return this; + } + /** + * Remove a specific color gradient + * @param gradient defines the gradient to remove + * @returns this particle system + */ + removeColorGradient(gradient) { + if (!this._colorGradients) { + return this; + } + let index = 0; + for (const colorGradient of this._colorGradients) { + if (colorGradient.gradient === gradient) { + this._colorGradients.splice(index, 1); + break; + } + index++; + } + return this; + } + /** + * Resets the draw wrappers cache + */ + resetDrawCache() { + for (const drawWrappers of this._drawWrappers) { + if (drawWrappers) { + for (const drawWrapper of drawWrappers) { + drawWrapper?.dispose(); + } + } + } + this._drawWrappers = []; + } + _fetchR(u, v, width, height, pixels) { + u = Math.abs(u) * 0.5 + 0.5; + v = Math.abs(v) * 0.5 + 0.5; + const wrappedU = (u * width) % width | 0; + const wrappedV = (v * height) % height | 0; + const position = (wrappedU + wrappedV * width) * 4; + return pixels[position] / 255; + } + _reset() { + this._resetEffect(); + } + _resetEffect() { + if (this._vertexBuffer) { + this._vertexBuffer.dispose(); + this._vertexBuffer = null; + } + if (this._spriteBuffer) { + this._spriteBuffer.dispose(); + this._spriteBuffer = null; + } + if (this._vertexArrayObject) { + this._engine.releaseVertexArrayObject(this._vertexArrayObject); + this._vertexArrayObject = null; + } + this._createVertexBuffers(); + } + _createVertexBuffers() { + this._vertexBufferSize = this._useInstancing ? 10 : 12; + if (this._isAnimationSheetEnabled) { + this._vertexBufferSize += 1; + } + if (!this._isBillboardBased || + this.billboardMode === 8 || + this.billboardMode === 9) { + this._vertexBufferSize += 3; + } + if (this._useRampGradients) { + this._vertexBufferSize += 4; + } + const engine = this._engine; + const vertexSize = this._vertexBufferSize * (this._useInstancing ? 1 : 4); + this._vertexData = new Float32Array(this._capacity * vertexSize); + this._vertexBuffer = new Buffer(engine, this._vertexData, true, vertexSize); + let dataOffset = 0; + const positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing); + this._vertexBuffers[VertexBuffer.PositionKind] = positions; + dataOffset += 3; + const colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing); + this._vertexBuffers[VertexBuffer.ColorKind] = colors; + dataOffset += 4; + const options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing); + this._vertexBuffers["angle"] = options; + dataOffset += 1; + const size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing); + this._vertexBuffers["size"] = size; + dataOffset += 2; + if (this._isAnimationSheetEnabled) { + const cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing); + this._vertexBuffers["cellIndex"] = cellIndexBuffer; + dataOffset += 1; + } + if (!this._isBillboardBased || + this.billboardMode === 8 || + this.billboardMode === 9) { + const directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing); + this._vertexBuffers["direction"] = directionBuffer; + dataOffset += 3; + } + if (this._useRampGradients) { + const rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing); + this._vertexBuffers["remapData"] = rampDataBuffer; + dataOffset += 4; + } + let offsets; + if (this._useInstancing) { + const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]); + this._spriteBuffer = new Buffer(engine, spriteData, false, 2); + offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2); + } + else { + offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing); + dataOffset += 2; + } + this._vertexBuffers["offset"] = offsets; + this.resetDrawCache(); + } + _createIndexBuffer() { + if (this._useInstancing) { + this._linesIndexBufferUseInstancing = this._engine.createIndexBuffer(new Uint32Array([0, 1, 1, 3, 3, 2, 2, 0, 0, 3])); + return; + } + const indices = []; + const indicesWireframe = []; + let index = 0; + for (let count = 0; count < this._capacity; count++) { + indices.push(index); + indices.push(index + 1); + indices.push(index + 2); + indices.push(index); + indices.push(index + 2); + indices.push(index + 3); + indicesWireframe.push(index, index + 1, index + 1, index + 2, index + 2, index + 3, index + 3, index, index, index + 3); + index += 4; + } + this._indexBuffer = this._engine.createIndexBuffer(indices); + this._linesIndexBuffer = this._engine.createIndexBuffer(indicesWireframe); + } + /** + * Gets the maximum number of particles active at the same time. + * @returns The max number of active particles. + */ + getCapacity() { + return this._capacity; + } + /** + * Gets whether there are still active particles in the system. + * @returns True if it is alive, otherwise false. + */ + isAlive() { + return this._alive; + } + /** + * Gets if the system has been started. (Note: this will still be true after stop is called) + * @returns True if it has been started, otherwise false. + */ + isStarted() { + return this._started; + } + /** @internal */ + _preStart() { + // Do nothing + } + /** + * Starts the particle system and begins to emit + * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default) + */ + start(delay = this.startDelay) { + if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) { + // eslint-disable-next-line no-throw-literal + throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set"; + } + if (delay) { + setTimeout(() => { + this.start(0); + }, delay); + return; + } + this._started = true; + this._stopped = false; + this._actualFrame = 0; + this._preStart(); + // Reset emit gradient so it acts the same on every start + if (this._emitRateGradients) { + if (this._emitRateGradients.length > 0) { + this._currentEmitRateGradient = this._emitRateGradients[0]; + this._currentEmitRate1 = this._currentEmitRateGradient.getFactor(); + this._currentEmitRate2 = this._currentEmitRate1; + } + if (this._emitRateGradients.length > 1) { + this._currentEmitRate2 = this._emitRateGradients[1].getFactor(); + } + } + // Reset start size gradient so it acts the same on every start + if (this._startSizeGradients) { + if (this._startSizeGradients.length > 0) { + this._currentStartSizeGradient = this._startSizeGradients[0]; + this._currentStartSize1 = this._currentStartSizeGradient.getFactor(); + this._currentStartSize2 = this._currentStartSize1; + } + if (this._startSizeGradients.length > 1) { + this._currentStartSize2 = this._startSizeGradients[1].getFactor(); + } + } + if (this.preWarmCycles) { + if (this.emitter?.getClassName().indexOf("Mesh") !== -1) { + this.emitter.computeWorldMatrix(true); + } + const noiseTextureAsProcedural = this.noiseTexture; + if (noiseTextureAsProcedural && noiseTextureAsProcedural.onGeneratedObservable) { + noiseTextureAsProcedural.onGeneratedObservable.addOnce(() => { + setTimeout(() => { + for (let index = 0; index < this.preWarmCycles; index++) { + this.animate(true); + noiseTextureAsProcedural.render(); + } + }); + }); + } + else { + for (let index = 0; index < this.preWarmCycles; index++) { + this.animate(true); + } + } + } + // Animations + if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) { + this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop); + } + } + /** + * Stops the particle system. + * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. The default value is true. + */ + stop(stopSubEmitters = true) { + if (this._stopped) { + return; + } + this.onStoppedObservable.notifyObservers(this); + this._stopped = true; + this._postStop(stopSubEmitters); + } + /** @internal */ + _postStop(stopSubEmitters) { + // Do nothing + } + // Animation sheet + /** + * Remove all active particles + */ + reset() { + this._stockParticles.length = 0; + this._particles.length = 0; + } + /** + * @internal (for internal use only) + */ + _appendParticleVertex(index, particle, offsetX, offsetY) { + let offset = index * this._vertexBufferSize; + this._vertexData[offset++] = particle.position.x + this.worldOffset.x; + this._vertexData[offset++] = particle.position.y + this.worldOffset.y; + this._vertexData[offset++] = particle.position.z + this.worldOffset.z; + this._vertexData[offset++] = particle.color.r; + this._vertexData[offset++] = particle.color.g; + this._vertexData[offset++] = particle.color.b; + this._vertexData[offset++] = particle.color.a; + this._vertexData[offset++] = particle.angle; + this._vertexData[offset++] = particle.scale.x * particle.size; + this._vertexData[offset++] = particle.scale.y * particle.size; + if (this._isAnimationSheetEnabled) { + this._vertexData[offset++] = particle.cellIndex; + } + if (!this._isBillboardBased) { + if (particle._initialDirection) { + let initialDirection = particle._initialDirection; + if (this.isLocal) { + Vector3.TransformNormalToRef(initialDirection, this._emitterWorldMatrix, TmpVectors.Vector3[0]); + initialDirection = TmpVectors.Vector3[0]; + } + if (initialDirection.x === 0 && initialDirection.z === 0) { + initialDirection.x = 0.001; + } + this._vertexData[offset++] = initialDirection.x; + this._vertexData[offset++] = initialDirection.y; + this._vertexData[offset++] = initialDirection.z; + } + else { + let direction = particle.direction; + if (this.isLocal) { + Vector3.TransformNormalToRef(direction, this._emitterWorldMatrix, TmpVectors.Vector3[0]); + direction = TmpVectors.Vector3[0]; + } + if (direction.x === 0 && direction.z === 0) { + direction.x = 0.001; + } + this._vertexData[offset++] = direction.x; + this._vertexData[offset++] = direction.y; + this._vertexData[offset++] = direction.z; + } + } + else if (this.billboardMode === 8 || this.billboardMode === 9) { + this._vertexData[offset++] = particle.direction.x; + this._vertexData[offset++] = particle.direction.y; + this._vertexData[offset++] = particle.direction.z; + } + if (this._useRampGradients && particle.remapData) { + this._vertexData[offset++] = particle.remapData.x; + this._vertexData[offset++] = particle.remapData.y; + this._vertexData[offset++] = particle.remapData.z; + this._vertexData[offset++] = particle.remapData.w; + } + if (!this._useInstancing) { + if (this._isAnimationSheetEnabled) { + if (offsetX === 0) { + offsetX = this._epsilon; + } + else if (offsetX === 1) { + offsetX = 1 - this._epsilon; + } + if (offsetY === 0) { + offsetY = this._epsilon; + } + else if (offsetY === 1) { + offsetY = 1 - this._epsilon; + } + } + this._vertexData[offset++] = offsetX; + this._vertexData[offset++] = offsetY; + } + } + /** @internal */ + _prepareParticle(particle) { + //Do nothing + } + _update(newParticles) { + // Update current + this._alive = this._particles.length > 0; + if (this.emitter.position) { + const emitterMesh = this.emitter; + this._emitterWorldMatrix = emitterMesh.getWorldMatrix(); + } + else { + const emitterPosition = this.emitter; + this._emitterWorldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z); + } + this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix); + this.updateFunction(this._particles); + // Add new ones + let particle; + for (let index = 0; index < newParticles; index++) { + if (this._particles.length === this._capacity) { + break; + } + particle = this._createParticle(); + this._particles.push(particle); + // Life time + if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) { + const ratio = Clamp(this._actualFrame / this.targetStopDuration); + GradientHelper.GetCurrentGradient(ratio, this._lifeTimeGradients, (currentGradient, nextGradient) => { + const factorGradient1 = currentGradient; + const factorGradient2 = nextGradient; + const lifeTime1 = factorGradient1.getFactor(); + const lifeTime2 = factorGradient2.getFactor(); + const gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient); + particle.lifeTime = Lerp(lifeTime1, lifeTime2, gradient); + }); + } + else { + particle.lifeTime = RandomRange(this.minLifeTime, this.maxLifeTime); + } + // Emitter + const emitPower = RandomRange(this.minEmitPower, this.maxEmitPower); + if (this.startPositionFunction) { + this.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal); + } + else { + this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal); + } + if (this.isLocal) { + if (!particle._localPosition) { + particle._localPosition = particle.position.clone(); + } + else { + particle._localPosition.copyFrom(particle.position); + } + Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position); + } + if (this.startDirectionFunction) { + this.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal); + } + else { + this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal, this._emitterInverseWorldMatrix); + } + if (emitPower === 0) { + if (!particle._initialDirection) { + particle._initialDirection = particle.direction.clone(); + } + else { + particle._initialDirection.copyFrom(particle.direction); + } + } + else { + particle._initialDirection = null; + } + particle.direction.scaleInPlace(emitPower); + // Size + if (!this._sizeGradients || this._sizeGradients.length === 0) { + particle.size = RandomRange(this.minSize, this.maxSize); + } + else { + particle._currentSizeGradient = this._sizeGradients[0]; + particle._currentSize1 = particle._currentSizeGradient.getFactor(); + particle.size = particle._currentSize1; + if (this._sizeGradients.length > 1) { + particle._currentSize2 = this._sizeGradients[1].getFactor(); + } + else { + particle._currentSize2 = particle._currentSize1; + } + } + // Size and scale + particle.scale.copyFromFloats(RandomRange(this.minScaleX, this.maxScaleX), RandomRange(this.minScaleY, this.maxScaleY)); + // Adjust scale by start size + if (this._startSizeGradients && this._startSizeGradients[0] && this.targetStopDuration) { + const ratio = this._actualFrame / this.targetStopDuration; + GradientHelper.GetCurrentGradient(ratio, this._startSizeGradients, (currentGradient, nextGradient, scale) => { + if (currentGradient !== this._currentStartSizeGradient) { + this._currentStartSize1 = this._currentStartSize2; + this._currentStartSize2 = nextGradient.getFactor(); + this._currentStartSizeGradient = currentGradient; + } + const value = Lerp(this._currentStartSize1, this._currentStartSize2, scale); + particle.scale.scaleInPlace(value); + }); + } + // Angle + if (!this._angularSpeedGradients || this._angularSpeedGradients.length === 0) { + particle.angularSpeed = RandomRange(this.minAngularSpeed, this.maxAngularSpeed); + } + else { + particle._currentAngularSpeedGradient = this._angularSpeedGradients[0]; + particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor(); + particle._currentAngularSpeed1 = particle.angularSpeed; + if (this._angularSpeedGradients.length > 1) { + particle._currentAngularSpeed2 = this._angularSpeedGradients[1].getFactor(); + } + else { + particle._currentAngularSpeed2 = particle._currentAngularSpeed1; + } + } + particle.angle = RandomRange(this.minInitialRotation, this.maxInitialRotation); + // Velocity + if (this._velocityGradients && this._velocityGradients.length > 0) { + particle._currentVelocityGradient = this._velocityGradients[0]; + particle._currentVelocity1 = particle._currentVelocityGradient.getFactor(); + if (this._velocityGradients.length > 1) { + particle._currentVelocity2 = this._velocityGradients[1].getFactor(); + } + else { + particle._currentVelocity2 = particle._currentVelocity1; + } + } + // Limit velocity + if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) { + particle._currentLimitVelocityGradient = this._limitVelocityGradients[0]; + particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor(); + if (this._limitVelocityGradients.length > 1) { + particle._currentLimitVelocity2 = this._limitVelocityGradients[1].getFactor(); + } + else { + particle._currentLimitVelocity2 = particle._currentLimitVelocity1; + } + } + // Drag + if (this._dragGradients && this._dragGradients.length > 0) { + particle._currentDragGradient = this._dragGradients[0]; + particle._currentDrag1 = particle._currentDragGradient.getFactor(); + if (this._dragGradients.length > 1) { + particle._currentDrag2 = this._dragGradients[1].getFactor(); + } + else { + particle._currentDrag2 = particle._currentDrag1; + } + } + // Color + if (!this._colorGradients || this._colorGradients.length === 0) { + const step = RandomRange(0, 1.0); + Color4.LerpToRef(this.color1, this.color2, step, particle.color); + this.colorDead.subtractToRef(particle.color, this._colorDiff); + this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep); + } + else { + particle._currentColorGradient = this._colorGradients[0]; + particle._currentColorGradient.getColorToRef(particle.color); + particle._currentColor1.copyFrom(particle.color); + if (this._colorGradients.length > 1) { + this._colorGradients[1].getColorToRef(particle._currentColor2); + } + else { + particle._currentColor2.copyFrom(particle.color); + } + } + // Sheet + if (this._isAnimationSheetEnabled) { + particle._initialStartSpriteCellID = this.startSpriteCellID; + particle._initialEndSpriteCellID = this.endSpriteCellID; + particle._initialSpriteCellLoop = this.spriteCellLoop; + } + // Inherited Velocity + particle.direction.addInPlace(this._inheritedVelocityOffset); + // Ramp + if (this._useRampGradients) { + particle.remapData = new Vector4(0, 1, 0, 1); + } + // Noise texture coordinates + if (this.noiseTexture) { + if (particle._randomNoiseCoordinates1) { + particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random()); + particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random()); + } + else { + particle._randomNoiseCoordinates1 = new Vector3(Math.random(), Math.random(), Math.random()); + particle._randomNoiseCoordinates2 = new Vector3(Math.random(), Math.random(), Math.random()); + } + } + // Update the position of the attached sub-emitters to match their attached particle + particle._inheritParticleInfoToSubEmitters(); + } + } + /** + * @internal + */ + static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false, useRampGradients = false) { + const attributeNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"]; + if (isAnimationSheetEnabled) { + attributeNamesOrOptions.push("cellIndex"); + } + if (!isBillboardBased) { + attributeNamesOrOptions.push("direction"); + } + if (useRampGradients) { + attributeNamesOrOptions.push("remapData"); + } + return attributeNamesOrOptions; + } + /** + * @internal + */ + static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false, applyFog = false) { + const effectCreationOption = ["invView", "view", "projection", "textureMask", "translationPivot", "eyePosition"]; + addClipPlaneUniforms(effectCreationOption); + if (isAnimationSheetEnabled) { + effectCreationOption.push("particlesInfos"); + } + if (useLogarithmicDepth) { + effectCreationOption.push("logarithmicDepthConstant"); + } + if (applyFog) { + effectCreationOption.push("vFogInfos"); + effectCreationOption.push("vFogColor"); + } + return effectCreationOption; + } + /** + * Fill the defines array according to the current settings of the particle system + * @param defines Array to be updated + * @param blendMode blend mode to take into account when updating the array + * @param fillImageProcessing fills the image processing defines + */ + fillDefines(defines, blendMode, fillImageProcessing = true) { + if (this._scene) { + prepareStringDefinesForClipPlanes(this, this._scene, defines); + if (this.applyFog && this._scene.fogEnabled && this._scene.fogMode !== 0) { + defines.push("#define FOG"); + } + } + if (this._isAnimationSheetEnabled) { + defines.push("#define ANIMATESHEET"); + } + if (this.useLogarithmicDepth) { + defines.push("#define LOGARITHMICDEPTH"); + } + if (blendMode === BaseParticleSystem.BLENDMODE_MULTIPLY) { + defines.push("#define BLENDMULTIPLYMODE"); + } + if (this._useRampGradients) { + defines.push("#define RAMPGRADIENT"); + } + if (this._isBillboardBased) { + defines.push("#define BILLBOARD"); + switch (this.billboardMode) { + case 2: + defines.push("#define BILLBOARDY"); + break; + case 8: + case 9: + defines.push("#define BILLBOARDSTRETCHED"); + if (this.billboardMode === 9) { + defines.push("#define BILLBOARDSTRETCHED_LOCAL"); + } + break; + case 7: + defines.push("#define BILLBOARDMODE_ALL"); + break; + } + } + if (fillImageProcessing && this._imageProcessingConfiguration) { + this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines); + defines.push(this._imageProcessingConfigurationDefines.toString()); + } + } + /** + * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system + * @param uniforms Uniforms array to fill + * @param attributes Attributes array to fill + * @param samplers Samplers array to fill + */ + fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) { + attributes.push(...ThinParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && + this.billboardMode !== 8 && + this.billboardMode !== 9, this._useRampGradients)); + uniforms.push(...ThinParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth, this.applyFog)); + samplers.push("diffuseSampler", "rampSampler"); + if (this._imageProcessingConfiguration) { + PrepareUniformsForImageProcessing(uniforms, this._imageProcessingConfigurationDefines); + PrepareSamplersForImageProcessing(samplers, this._imageProcessingConfigurationDefines); + } + } + /** + * @internal + */ + _getWrapper(blendMode) { + const customWrapper = this._getCustomDrawWrapper(blendMode); + if (customWrapper?.effect) { + return customWrapper; + } + const defines = []; + this.fillDefines(defines, blendMode); + // Effect + const currentRenderPassId = this._engine._features.supportRenderPasses ? this._engine.currentRenderPassId : 0; + let drawWrappers = this._drawWrappers[currentRenderPassId]; + if (!drawWrappers) { + drawWrappers = this._drawWrappers[currentRenderPassId] = []; + } + let drawWrapper = drawWrappers[blendMode]; + if (!drawWrapper) { + drawWrapper = new DrawWrapper(this._engine); + if (drawWrapper.drawContext) { + drawWrapper.drawContext.useInstancing = this._useInstancing; + } + drawWrappers[blendMode] = drawWrapper; + } + const join = defines.join("\n"); + if (drawWrapper.defines !== join) { + const attributesNamesOrOptions = []; + const effectCreationOption = []; + const samplers = []; + this.fillUniformsAttributesAndSamplerNames(effectCreationOption, attributesNamesOrOptions, samplers); + drawWrapper.setEffect(this._engine.createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join, undefined, undefined, undefined, undefined, this._shaderLanguage), join); + } + return drawWrapper; + } + /** + * Animates the particle system for the current frame by emitting new particles and or animating the living ones. + * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false) + */ + animate(preWarmOnly = false) { + if (!this._started) { + return; + } + if (!preWarmOnly && this._scene) { + // Check + if (!this.isReady()) { + return; + } + if (this._currentRenderId === this._scene.getFrameId()) { + return; + } + this._currentRenderId = this._scene.getFrameId(); + } + this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene?.getAnimationRatio() || 1); + // Determine the number of particles we need to create + let newParticles; + if (this.manualEmitCount > -1) { + newParticles = this.manualEmitCount; + this._newPartsExcess = 0; + this.manualEmitCount = 0; + } + else { + let rate = this.emitRate; + if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) { + const ratio = this._actualFrame / this.targetStopDuration; + GradientHelper.GetCurrentGradient(ratio, this._emitRateGradients, (currentGradient, nextGradient, scale) => { + if (currentGradient !== this._currentEmitRateGradient) { + this._currentEmitRate1 = this._currentEmitRate2; + this._currentEmitRate2 = nextGradient.getFactor(); + this._currentEmitRateGradient = currentGradient; + } + rate = Lerp(this._currentEmitRate1, this._currentEmitRate2, scale); + }); + } + newParticles = (rate * this._scaledUpdateSpeed) >> 0; + this._newPartsExcess += rate * this._scaledUpdateSpeed - newParticles; + } + if (this._newPartsExcess > 1.0) { + newParticles += this._newPartsExcess >> 0; + this._newPartsExcess -= this._newPartsExcess >> 0; + } + this._alive = false; + if (!this._stopped) { + this._actualFrame += this._scaledUpdateSpeed; + if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) { + this.stop(); + } + } + else { + newParticles = 0; + } + this._update(newParticles); + // Stopped? + if (this._stopped) { + if (!this._alive) { + this._started = false; + if (this.onAnimationEnd) { + this.onAnimationEnd(); + } + if (this.disposeOnStop && this._scene) { + this._scene._toBeDisposed.push(this); + } + } + } + if (!preWarmOnly) { + // Update VBO + let offset = 0; + for (let index = 0; index < this._particles.length; index++) { + const particle = this._particles[index]; + this._appendParticleVertices(offset, particle); + offset += this._useInstancing ? 1 : 4; + } + if (this._vertexBuffer) { + this._vertexBuffer.updateDirectly(this._vertexData, 0, this._particles.length); + } + } + if (this.manualEmitCount === 0 && this.disposeOnStop) { + this.stop(); + } + } + _appendParticleVertices(offset, particle) { + this._appendParticleVertex(offset++, particle, 0, 0); + if (!this._useInstancing) { + this._appendParticleVertex(offset++, particle, 1, 0); + this._appendParticleVertex(offset++, particle, 1, 1); + this._appendParticleVertex(offset++, particle, 0, 1); + } + } + /** + * Rebuilds the particle system. + */ + rebuild() { + if (this._engine.getCaps().vertexArrayObject) { + this._vertexArrayObject = null; + } + this._createIndexBuffer(); + this._spriteBuffer?._rebuild(); + this._createVertexBuffers(); + this.resetDrawCache(); + } + async _initShaderSourceAsync() { + const engine = this._engine; + if (engine.isWebGPU && !ThinParticleSystem.ForceGLSL) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + await Promise.all([Promise.resolve().then(() => particles_vertex), Promise.resolve().then(() => particles_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => particles_vertex$1), Promise.resolve().then(() => particles_fragment$1)]); + } + this._shadersLoaded = true; + } + /** + * Is this system ready to be used/rendered + * @returns true if the system is ready + */ + isReady() { + if (!this._shadersLoaded) { + return false; + } + if (!this.emitter || (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady()) || !this.particleTexture || !this.particleTexture.isReady()) { + return false; + } + if (this.blendMode !== BaseParticleSystem.BLENDMODE_MULTIPLYADD) { + if (!this._getWrapper(this.blendMode).effect.isReady()) { + return false; + } + } + else { + if (!this._getWrapper(BaseParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) { + return false; + } + if (!this._getWrapper(BaseParticleSystem.BLENDMODE_ADD).effect.isReady()) { + return false; + } + } + return true; + } + _render(blendMode) { + const drawWrapper = this._getWrapper(blendMode); + const effect = drawWrapper.effect; + const engine = this._engine; + // Render + engine.enableEffect(drawWrapper); + const viewMatrix = this.defaultViewMatrix ?? this._scene.getViewMatrix(); + effect.setTexture("diffuseSampler", this.particleTexture); + effect.setMatrix("view", viewMatrix); + effect.setMatrix("projection", this.defaultProjectionMatrix ?? this._scene.getProjectionMatrix()); + if (this._isAnimationSheetEnabled && this.particleTexture) { + const baseSize = this.particleTexture.getBaseSize(); + effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, this.spriteCellWidth / baseSize.width); + } + effect.setVector2("translationPivot", this.translationPivot); + effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a); + if (this._isBillboardBased && this._scene) { + const camera = this._scene.activeCamera; + effect.setVector3("eyePosition", camera.globalPosition); + } + if (this._rampGradientsTexture) { + if (!this._rampGradients || !this._rampGradients.length) { + this._rampGradientsTexture.dispose(); + this._rampGradientsTexture = null; + } + effect.setTexture("rampSampler", this._rampGradientsTexture); + } + const defines = effect.defines; + if (this._scene) { + bindClipPlane(effect, this, this._scene); + if (this.applyFog) { + BindFogParameters(this._scene, undefined, effect); + } + } + if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) { + viewMatrix.invertToRef(TmpVectors.Matrix[0]); + effect.setMatrix("invView", TmpVectors.Matrix[0]); + } + if (this._vertexArrayObject !== undefined) { + if (this._scene?.forceWireframe) { + engine.bindBuffers(this._vertexBuffers, this._linesIndexBufferUseInstancing, effect); + } + else { + if (!this._vertexArrayObject) { + this._vertexArrayObject = this._engine.recordVertexArrayObject(this._vertexBuffers, null, effect); + } + this._engine.bindVertexArrayObject(this._vertexArrayObject, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : this._indexBuffer); + } + } + else { + if (!this._indexBuffer) { + // Use instancing mode + engine.bindBuffers(this._vertexBuffers, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : null, effect); + } + else { + engine.bindBuffers(this._vertexBuffers, this._scene?.forceWireframe ? this._linesIndexBuffer : this._indexBuffer, effect); + } + } + // Log. depth + if (this.useLogarithmicDepth && this._scene) { + BindLogDepth(defines, effect, this._scene); + } + // image processing + if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) { + this._imageProcessingConfiguration.bind(effect); + } + // Draw order + switch (blendMode) { + case BaseParticleSystem.BLENDMODE_ADD: + engine.setAlphaMode(1); + break; + case BaseParticleSystem.BLENDMODE_ONEONE: + engine.setAlphaMode(6); + break; + case BaseParticleSystem.BLENDMODE_STANDARD: + engine.setAlphaMode(2); + break; + case BaseParticleSystem.BLENDMODE_MULTIPLY: + engine.setAlphaMode(4); + break; + } + if (this._onBeforeDrawParticlesObservable) { + this._onBeforeDrawParticlesObservable.notifyObservers(effect); + } + if (this._useInstancing) { + if (this._scene?.forceWireframe) { + engine.drawElementsType(6, 0, 10, this._particles.length); + } + else { + engine.drawArraysType(7, 0, 4, this._particles.length); + } + } + else { + if (this._scene?.forceWireframe) { + engine.drawElementsType(1, 0, this._particles.length * 10); + } + else { + engine.drawElementsType(0, 0, this._particles.length * 6); + } + } + return this._particles.length; + } + /** + * Renders the particle system in its current state. + * @returns the current number of particles + */ + render() { + // Check + if (!this.isReady() || !this._particles.length) { + return 0; + } + const engine = this._engine; + if (engine.setState) { + engine.setState(false); + if (this.forceDepthWrite) { + engine.setDepthWrite(true); + } + } + let outparticles = 0; + if (this.blendMode === BaseParticleSystem.BLENDMODE_MULTIPLYADD) { + outparticles = this._render(BaseParticleSystem.BLENDMODE_MULTIPLY) + this._render(BaseParticleSystem.BLENDMODE_ADD); + } + else { + outparticles = this._render(this.blendMode); + } + this._engine.unbindInstanceAttributes(); + this._engine.setAlphaMode(0); + return outparticles; + } + /** @internal */ + _onDispose(disposeAttachedSubEmitters = false, disposeEndSubEmitters = false) { + // Do Nothing + } + /** + * Disposes the particle system and free the associated resources + * @param disposeTexture defines if the particle texture must be disposed as well (true by default) + * @param disposeAttachedSubEmitters defines if the attached sub-emitters must be disposed as well (false by default) + * @param disposeEndSubEmitters defines if the end type sub-emitters must be disposed as well (false by default) + */ + dispose(disposeTexture = true, disposeAttachedSubEmitters = false, disposeEndSubEmitters = false) { + this.resetDrawCache(); + if (this._vertexBuffer) { + this._vertexBuffer.dispose(); + this._vertexBuffer = null; + } + if (this._spriteBuffer) { + this._spriteBuffer.dispose(); + this._spriteBuffer = null; + } + if (this._indexBuffer) { + this._engine._releaseBuffer(this._indexBuffer); + this._indexBuffer = null; + } + if (this._linesIndexBuffer) { + this._engine._releaseBuffer(this._linesIndexBuffer); + this._linesIndexBuffer = null; + } + if (this._linesIndexBufferUseInstancing) { + this._engine._releaseBuffer(this._linesIndexBufferUseInstancing); + this._linesIndexBufferUseInstancing = null; + } + if (this._vertexArrayObject) { + this._engine.releaseVertexArrayObject(this._vertexArrayObject); + this._vertexArrayObject = null; + } + if (disposeTexture && this.particleTexture) { + this.particleTexture.dispose(); + this.particleTexture = null; + } + if (disposeTexture && this.noiseTexture) { + this.noiseTexture.dispose(); + this.noiseTexture = null; + } + if (this._rampGradientsTexture) { + this._rampGradientsTexture.dispose(); + this._rampGradientsTexture = null; + } + this._onDispose(disposeAttachedSubEmitters, disposeEndSubEmitters); + if (this._onBeforeDrawParticlesObservable) { + this._onBeforeDrawParticlesObservable.clear(); + } + // Remove from scene + if (this._scene) { + const index = this._scene.particleSystems.indexOf(this); + if (index > -1) { + this._scene.particleSystems.splice(index, 1); + } + this._scene._activeParticleSystems.dispose(); + } + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + this.onStoppedObservable.clear(); + this.reset(); + } +} +/** + * Force all the particle systems to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +ThinParticleSystem.ForceGLSL = false; + +/** + * Type of sub emitter + */ +var SubEmitterType; +(function (SubEmitterType) { + /** + * Attached to the particle over it's lifetime + */ + SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED"; + /** + * Created when the particle dies + */ + SubEmitterType[SubEmitterType["END"] = 1] = "END"; +})(SubEmitterType || (SubEmitterType = {})); +/** + * Sub emitter class used to emit particles from an existing particle + */ +class SubEmitter { + /** + * Creates a sub emitter + * @param particleSystem the particle system to be used by the sub emitter + */ + constructor( + /** + * the particle system to be used by the sub emitter + */ + particleSystem) { + this.particleSystem = particleSystem; + /** + * Type of the submitter (Default: END) + */ + this.type = 1 /* SubEmitterType.END */; + /** + * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false) + * Note: This only is supported when using an emitter of type Mesh + */ + this.inheritDirection = false; + /** + * How much of the attached particles speed should be added to the sub emitted particle (default: 0) + */ + this.inheritedVelocityAmount = 0; + // Create mesh as emitter to support rotation + if (!particleSystem.emitter || !particleSystem.emitter.dispose) { + const internalClass = GetClass("BABYLON.AbstractMesh"); + particleSystem.emitter = new internalClass("SubemitterSystemEmitter", particleSystem.getScene()); + particleSystem._disposeEmitterOnDispose = true; + } + } + /** + * Clones the sub emitter + * @returns the cloned sub emitter + */ + clone() { + // Clone particle system + let emitter = this.particleSystem.emitter; + if (!emitter) { + emitter = new Vector3(); + } + else if (emitter instanceof Vector3) { + emitter = emitter.clone(); + } + else if (emitter.getClassName().indexOf("Mesh") !== -1) { + const internalClass = GetClass("BABYLON.Mesh"); + emitter = new internalClass("", emitter.getScene()); + emitter.isVisible = false; + } + const clone = new SubEmitter(this.particleSystem.clone(this.particleSystem.name, emitter)); + // Clone properties + clone.particleSystem.name += "Clone"; + clone.type = this.type; + clone.inheritDirection = this.inheritDirection; + clone.inheritedVelocityAmount = this.inheritedVelocityAmount; + clone.particleSystem._disposeEmitterOnDispose = true; + clone.particleSystem.disposeOnStop = true; + return clone; + } + /** + * Serialize current object to a JSON object + * @param serializeTexture defines if the texture must be serialized as well + * @returns the serialized object + */ + serialize(serializeTexture = false) { + const serializationObject = {}; + serializationObject.type = this.type; + serializationObject.inheritDirection = this.inheritDirection; + serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount; + serializationObject.particleSystem = this.particleSystem.serialize(serializeTexture); + return serializationObject; + } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static _ParseParticleSystem(system, sceneOrEngine, rootUrl, doNotStart = false) { + throw _WarnImport("ParseParticle"); + } + /** + * Creates a new SubEmitter from a serialized JSON version + * @param serializationObject defines the JSON object to read from + * @param sceneOrEngine defines the hosting scene or the hosting engine + * @param rootUrl defines the rootUrl for data loading + * @returns a new SubEmitter + */ + static Parse(serializationObject, sceneOrEngine, rootUrl) { + const system = serializationObject.particleSystem; + const subEmitter = new SubEmitter(SubEmitter._ParseParticleSystem(system, sceneOrEngine, rootUrl, true)); + subEmitter.type = serializationObject.type; + subEmitter.inheritDirection = serializationObject.inheritDirection; + subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount; + subEmitter.particleSystem._isSubEmitter = true; + return subEmitter; + } + /** Release associated resources */ + dispose() { + this.particleSystem.dispose(); + } +} + +/** + * Particle emitter emitting particles from the inside of a box. + * It emits the particles randomly between 2 given directions. + */ +class MeshParticleEmitter { + /** Defines the mesh to use as source */ + get mesh() { + return this._mesh; + } + set mesh(value) { + if (this._mesh === value) { + return; + } + this._mesh = value; + if (value) { + this._indices = value.getIndices(); + this._positions = value.getVerticesData(VertexBuffer.PositionKind); + this._normals = value.getVerticesData(VertexBuffer.NormalKind); + } + else { + this._indices = null; + this._positions = null; + this._normals = null; + } + } + /** + * Creates a new instance MeshParticleEmitter + * @param mesh defines the mesh to use as source + */ + constructor(mesh = null) { + this._indices = null; + this._positions = null; + this._normals = null; + this._storedNormal = Vector3.Zero(); + this._mesh = null; + /** + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + */ + this.direction1 = new Vector3(0, 1.0, 0); + /** + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + */ + this.direction2 = new Vector3(0, 1.0, 0); + /** + * Gets or sets a boolean indicating that particle directions must be built from mesh face normals + */ + this.useMeshNormalsForDirection = true; + this.mesh = mesh; + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + * @param particle is the particle we are computed the direction for + * @param isLocal defines if the direction should be set in local space + */ + startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { + if (this.useMeshNormalsForDirection && this._normals) { + Vector3.TransformNormalToRef(this._storedNormal, worldMatrix, directionToUpdate); + return; + } + const randX = RandomRange(this.direction1.x, this.direction2.x); + const randY = RandomRange(this.direction1.y, this.direction2.y); + const randZ = RandomRange(this.direction1.z, this.direction2.z); + if (isLocal) { + directionToUpdate.copyFromFloats(randX, randY, randZ); + return; + } + Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); + } + /** + * Called by the particle System when the position is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param positionToUpdate is the position vector to update with the result + * @param particle is the particle we are computed the position for + * @param isLocal defines if the position should be set in local space + */ + startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { + if (!this._indices || !this._positions) { + return; + } + const randomFaceIndex = (3 * Math.random() * (this._indices.length / 3)) | 0; + const bu = Math.random(); + const bv = Math.random() * (1.0 - bu); + const bw = 1.0 - bu - bv; + const faceIndexA = this._indices[randomFaceIndex]; + const faceIndexB = this._indices[randomFaceIndex + 1]; + const faceIndexC = this._indices[randomFaceIndex + 2]; + const vertexA = TmpVectors.Vector3[0]; + const vertexB = TmpVectors.Vector3[1]; + const vertexC = TmpVectors.Vector3[2]; + const randomVertex = TmpVectors.Vector3[3]; + Vector3.FromArrayToRef(this._positions, faceIndexA * 3, vertexA); + Vector3.FromArrayToRef(this._positions, faceIndexB * 3, vertexB); + Vector3.FromArrayToRef(this._positions, faceIndexC * 3, vertexC); + randomVertex.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x; + randomVertex.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y; + randomVertex.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z; + if (isLocal) { + positionToUpdate.copyFromFloats(randomVertex.x, randomVertex.y, randomVertex.z); + } + else { + Vector3.TransformCoordinatesFromFloatsToRef(randomVertex.x, randomVertex.y, randomVertex.z, worldMatrix, positionToUpdate); + } + if (this.useMeshNormalsForDirection && this._normals) { + Vector3.FromArrayToRef(this._normals, faceIndexA * 3, vertexA); + Vector3.FromArrayToRef(this._normals, faceIndexB * 3, vertexB); + Vector3.FromArrayToRef(this._normals, faceIndexC * 3, vertexC); + this._storedNormal.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x; + this._storedNormal.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y; + this._storedNormal.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z; + } + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new MeshParticleEmitter(this.mesh); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + applyToShader(uboOrEffect) { + uboOrEffect.setVector3("direction1", this.direction1); + uboOrEffect.setVector3("direction2", this.direction2); + } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + buildUniformLayout(ubo) { + ubo.addUniform("direction1", 3); + ubo.addUniform("direction2", 3); + } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + return ""; + } + /** + * Returns the string "BoxParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "MeshParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = {}; + serializationObject.type = this.getClassName(); + serializationObject.direction1 = this.direction1.asArray(); + serializationObject.direction2 = this.direction2.asArray(); + serializationObject.meshId = this.mesh?.id; + serializationObject.useMeshNormalsForDirection = this.useMeshNormalsForDirection; + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + * @param scene defines the hosting scene + */ + parse(serializationObject, scene) { + Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); + Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); + if (serializationObject.meshId && scene) { + this.mesh = scene.getLastMeshById(serializationObject.meshId); + } + this.useMeshNormalsForDirection = serializationObject.useMeshNormalsForDirection; + } +} + +/** + * Particle emitter emitting particles from a custom list of positions. + */ +class CustomParticleEmitter { + /** + * Creates a new instance CustomParticleEmitter + */ + constructor() { + /** + * Gets or sets the position generator that will create the initial position of each particle. + * Index will be provided when used with GPU particle. Particle will be provided when used with CPU particles + */ + this.particlePositionGenerator = () => { }; + /** + * Gets or sets the destination generator that will create the final destination of each particle. + * * Index will be provided when used with GPU particle. Particle will be provided when used with CPU particles + */ + this.particleDestinationGenerator = () => { }; + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + * @param particle is the particle we are computed the direction for + * @param isLocal defines if the direction should be set in local space + */ + startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { + const tmpVector = TmpVectors.Vector3[0]; + if (this.particleDestinationGenerator) { + this.particleDestinationGenerator(-1, particle, tmpVector); + // Get direction + const diffVector = TmpVectors.Vector3[1]; + tmpVector.subtractToRef(particle.position, diffVector); + diffVector.scaleToRef(1 / particle.lifeTime, tmpVector); + } + else { + tmpVector.set(0, 0, 0); + } + if (isLocal) { + directionToUpdate.copyFrom(tmpVector); + return; + } + Vector3.TransformNormalToRef(tmpVector, worldMatrix, directionToUpdate); + } + /** + * Called by the particle System when the position is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param positionToUpdate is the position vector to update with the result + * @param particle is the particle we are computed the position for + * @param isLocal defines if the position should be set in local space + */ + startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { + const tmpVector = TmpVectors.Vector3[0]; + if (this.particlePositionGenerator) { + this.particlePositionGenerator(-1, particle, tmpVector); + } + else { + tmpVector.set(0, 0, 0); + } + if (isLocal) { + positionToUpdate.copyFrom(tmpVector); + return; + } + Vector3.TransformCoordinatesToRef(tmpVector, worldMatrix, positionToUpdate); + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new CustomParticleEmitter(); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + applyToShader(uboOrEffect) { } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + buildUniformLayout(ubo) { } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + return "#define CUSTOMEMITTER"; + } + /** + * Returns the string "PointParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "CustomParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = {}; + serializationObject.type = this.getClassName(); + serializationObject.particlePositionGenerator = this.particlePositionGenerator; + serializationObject.particleDestinationGenerator = this.particleDestinationGenerator; + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + */ + parse(serializationObject) { + if (serializationObject.particlePositionGenerator) { + this.particlePositionGenerator = serializationObject.particlePositionGenerator; + } + if (serializationObject.particleDestinationGenerator) { + this.particleDestinationGenerator = serializationObject.particleDestinationGenerator; + } + } +} + +/** + * Particle emitter emitting particles from a point. + * It emits the particles randomly between 2 given directions. + */ +class PointParticleEmitter { + /** + * Creates a new instance PointParticleEmitter + */ + constructor() { + /** + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + */ + this.direction1 = new Vector3(0, 1.0, 0); + /** + * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. + */ + this.direction2 = new Vector3(0, 1.0, 0); + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + * @param particle is the particle we are computed the direction for + * @param isLocal defines if the direction should be set in local space + */ + startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { + const randX = RandomRange(this.direction1.x, this.direction2.x); + const randY = RandomRange(this.direction1.y, this.direction2.y); + const randZ = RandomRange(this.direction1.z, this.direction2.z); + if (isLocal) { + directionToUpdate.copyFromFloats(randX, randY, randZ); + return; + } + Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); + } + /** + * Called by the particle System when the position is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param positionToUpdate is the position vector to update with the result + * @param particle is the particle we are computed the position for + * @param isLocal defines if the position should be set in local space + */ + startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { + if (isLocal) { + positionToUpdate.copyFromFloats(0, 0, 0); + return; + } + Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate); + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new PointParticleEmitter(); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + applyToShader(uboOrEffect) { + uboOrEffect.setVector3("direction1", this.direction1); + uboOrEffect.setVector3("direction2", this.direction2); + } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + buildUniformLayout(ubo) { + ubo.addUniform("direction1", 3); + ubo.addUniform("direction2", 3); + } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + return "#define POINTEMITTER"; + } + /** + * Returns the string "PointParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "PointParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = {}; + serializationObject.type = this.getClassName(); + serializationObject.direction1 = this.direction1.asArray(); + serializationObject.direction2 = this.direction2.asArray(); + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + */ + parse(serializationObject) { + Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); + Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); + } +} + +/** + * Particle emitter emitting particles from the inside of a hemisphere. + * It emits the particles alongside the hemisphere radius. The emission direction might be randomized. + */ +class HemisphericParticleEmitter { + /** + * Creates a new instance HemisphericParticleEmitter + * @param radius the radius of the emission hemisphere (1 by default) + * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default) + * @param directionRandomizer defines how much to randomize the particle direction [0-1] + */ + constructor( + /** + * [1] The radius of the emission hemisphere. + */ + radius = 1, + /** + * [1] The range of emission [0-1] 0 Surface only, 1 Entire Radius. + */ + radiusRange = 1, + /** + * [0] How much to randomize the particle direction [0-1]. + */ + directionRandomizer = 0) { + this.radius = radius; + this.radiusRange = radiusRange; + this.directionRandomizer = directionRandomizer; + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + * @param particle is the particle we are computed the direction for + * @param isLocal defines if the direction should be set in local space + */ + startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { + const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize(); + const randX = RandomRange(0, this.directionRandomizer); + const randY = RandomRange(0, this.directionRandomizer); + const randZ = RandomRange(0, this.directionRandomizer); + direction.x += randX; + direction.y += randY; + direction.z += randZ; + direction.normalize(); + if (isLocal) { + directionToUpdate.copyFrom(direction); + return; + } + Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate); + } + /** + * Called by the particle System when the position is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param positionToUpdate is the position vector to update with the result + * @param particle is the particle we are computed the position for + * @param isLocal defines if the position should be set in local space + */ + startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { + const randRadius = this.radius - RandomRange(0, this.radius * this.radiusRange); + const v = RandomRange(0, 1.0); + const phi = RandomRange(0, 2 * Math.PI); + const theta = Math.acos(2 * v - 1); + const randX = randRadius * Math.cos(phi) * Math.sin(theta); + const randY = randRadius * Math.cos(theta); + const randZ = randRadius * Math.sin(phi) * Math.sin(theta); + if (isLocal) { + positionToUpdate.copyFromFloats(randX, Math.abs(randY), randZ); + return; + } + Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate); + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + applyToShader(uboOrEffect) { + uboOrEffect.setFloat("radius", this.radius); + uboOrEffect.setFloat("radiusRange", this.radiusRange); + uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); + } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + buildUniformLayout(ubo) { + ubo.addUniform("radius", 1); + ubo.addUniform("radiusRange", 1); + ubo.addUniform("directionRandomizer", 1); + } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + return "#define HEMISPHERICEMITTER"; + } + /** + * Returns the string "HemisphericParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "HemisphericParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = {}; + serializationObject.type = this.getClassName(); + serializationObject.radius = this.radius; + serializationObject.radiusRange = this.radiusRange; + serializationObject.directionRandomizer = this.directionRandomizer; + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + */ + parse(serializationObject) { + this.radius = serializationObject.radius; + this.radiusRange = serializationObject.radiusRange; + this.directionRandomizer = serializationObject.directionRandomizer; + } +} + +/** + * Particle emitter emitting particles from the inside of a sphere. + * It emits the particles alongside the sphere radius. The emission direction might be randomized. + */ +class SphereParticleEmitter { + /** + * Creates a new instance SphereParticleEmitter + * @param radius the radius of the emission sphere (1 by default) + * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default) + * @param directionRandomizer defines how much to randomize the particle direction [0-1] + */ + constructor( + /** + * [1] The radius of the emission sphere. + */ + radius = 1, + /** + * [1] The range of emission [0-1] 0 Surface only, 1 Entire Radius. + */ + radiusRange = 1, + /** + * [0] How much to randomize the particle direction [0-1]. + */ + directionRandomizer = 0) { + this.radius = radius; + this.radiusRange = radiusRange; + this.directionRandomizer = directionRandomizer; + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + * @param particle is the particle we are computed the direction for + * @param isLocal defines if the direction should be set in local space + */ + startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { + const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize(); + const randX = RandomRange(0, this.directionRandomizer); + const randY = RandomRange(0, this.directionRandomizer); + const randZ = RandomRange(0, this.directionRandomizer); + direction.x += randX; + direction.y += randY; + direction.z += randZ; + direction.normalize(); + if (isLocal) { + directionToUpdate.copyFrom(direction); + return; + } + Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate); + } + /** + * Called by the particle System when the position is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param positionToUpdate is the position vector to update with the result + * @param particle is the particle we are computed the position for + * @param isLocal defines if the position should be set in local space + */ + startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { + const randRadius = this.radius - RandomRange(0, this.radius * this.radiusRange); + const v = RandomRange(0, 1.0); + const phi = RandomRange(0, 2 * Math.PI); + const theta = Math.acos(2 * v - 1); + const randX = randRadius * Math.cos(phi) * Math.sin(theta); + const randY = randRadius * Math.cos(theta); + const randZ = randRadius * Math.sin(phi) * Math.sin(theta); + if (isLocal) { + positionToUpdate.copyFromFloats(randX, randY, randZ); + return; + } + Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate); + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + applyToShader(uboOrEffect) { + uboOrEffect.setFloat("radius", this.radius); + uboOrEffect.setFloat("radiusRange", this.radiusRange); + uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); + } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + buildUniformLayout(ubo) { + ubo.addUniform("radius", 1); + ubo.addUniform("radiusRange", 1); + ubo.addUniform("directionRandomizer", 1); + } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + return "#define SPHEREEMITTER"; + } + /** + * Returns the string "SphereParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "SphereParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = {}; + serializationObject.type = this.getClassName(); + serializationObject.radius = this.radius; + serializationObject.radiusRange = this.radiusRange; + serializationObject.directionRandomizer = this.directionRandomizer; + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + */ + parse(serializationObject) { + this.radius = serializationObject.radius; + this.radiusRange = serializationObject.radiusRange; + this.directionRandomizer = serializationObject.directionRandomizer; + } +} +/** + * Particle emitter emitting particles from the inside of a sphere. + * It emits the particles randomly between two vectors. + */ +class SphereDirectedParticleEmitter extends SphereParticleEmitter { + /** + * Creates a new instance SphereDirectedParticleEmitter + * @param radius the radius of the emission sphere (1 by default) + * @param direction1 the min limit of the emission direction (up vector by default) + * @param direction2 the max limit of the emission direction (up vector by default) + */ + constructor(radius = 1, + /** + * [Up vector] The min limit of the emission direction. + */ + direction1 = new Vector3(0, 1, 0), + /** + * [Up vector] The max limit of the emission direction. + */ + direction2 = new Vector3(0, 1, 0)) { + super(radius); + this.direction1 = direction1; + this.direction2 = direction2; + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + */ + startDirectionFunction(worldMatrix, directionToUpdate) { + const randX = RandomRange(this.direction1.x, this.direction2.x); + const randY = RandomRange(this.direction1.y, this.direction2.y); + const randZ = RandomRange(this.direction1.z, this.direction2.z); + Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + applyToShader(uboOrEffect) { + uboOrEffect.setFloat("radius", this.radius); + uboOrEffect.setFloat("radiusRange", this.radiusRange); + uboOrEffect.setVector3("direction1", this.direction1); + uboOrEffect.setVector3("direction2", this.direction2); + } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + buildUniformLayout(ubo) { + ubo.addUniform("radius", 1); + ubo.addUniform("radiusRange", 1); + ubo.addUniform("direction1", 3); + ubo.addUniform("direction2", 3); + } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"; + } + /** + * Returns the string "SphereDirectedParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "SphereDirectedParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.direction1 = this.direction1.asArray(); + serializationObject.direction2 = this.direction2.asArray(); + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + */ + parse(serializationObject) { + super.parse(serializationObject); + this.direction1.copyFrom(serializationObject.direction1); + this.direction2.copyFrom(serializationObject.direction2); + } +} + +/** + * Particle emitter emitting particles from the inside of a cylinder. + * It emits the particles alongside the cylinder radius. The emission direction might be randomized. + */ +class CylinderParticleEmitter { + /** + * Creates a new instance CylinderParticleEmitter + * @param radius the radius of the emission cylinder (1 by default) + * @param height the height of the emission cylinder (1 by default) + * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) + * @param directionRandomizer defines how much to randomize the particle direction [0-1] + */ + constructor( + /** + * [1] The radius of the emission cylinder. + */ + radius = 1, + /** + * [1] The height of the emission cylinder. + */ + height = 1, + /** + * [1] The range of emission [0-1] 0 Surface only, 1 Entire Radius. + */ + radiusRange = 1, + /** + * [0] How much to randomize the particle direction [0-1]. + */ + directionRandomizer = 0) { + this.radius = radius; + this.height = height; + this.radiusRange = radiusRange; + this.directionRandomizer = directionRandomizer; + this._tempVector = Vector3.Zero(); + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + * @param particle is the particle we are computed the direction for + * @param isLocal defines if the direction should be set in local space + * @param inverseWorldMatrix defines the inverted world matrix to use if isLocal is false + */ + startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal, inverseWorldMatrix) { + particle.position.subtractToRef(worldMatrix.getTranslation(), this._tempVector); + this._tempVector.normalize(); + Vector3.TransformNormalToRef(this._tempVector, inverseWorldMatrix, this._tempVector); + const randY = RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2); + let angle = Math.atan2(this._tempVector.x, this._tempVector.z); + angle += RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer; + this._tempVector.y = randY; // set direction y to rand y to mirror normal of cylinder surface + this._tempVector.x = Math.sin(angle); + this._tempVector.z = Math.cos(angle); + this._tempVector.normalize(); + if (isLocal) { + directionToUpdate.copyFrom(this._tempVector); + return; + } + Vector3.TransformNormalFromFloatsToRef(this._tempVector.x, this._tempVector.y, this._tempVector.z, worldMatrix, directionToUpdate); + } + /** + * Called by the particle System when the position is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param positionToUpdate is the position vector to update with the result + * @param particle is the particle we are computed the position for + * @param isLocal defines if the position should be set in local space + */ + startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { + const yPos = RandomRange(-this.height / 2, this.height / 2); + const angle = RandomRange(0, 2 * Math.PI); + // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html + const radiusDistribution = RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1); + const positionRadius = Math.sqrt(radiusDistribution) * this.radius; + const xPos = positionRadius * Math.cos(angle); + const zPos = positionRadius * Math.sin(angle); + if (isLocal) { + positionToUpdate.copyFromFloats(xPos, yPos, zPos); + return; + } + Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate); + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + applyToShader(uboOrEffect) { + uboOrEffect.setFloat("radius", this.radius); + uboOrEffect.setFloat("height", this.height); + uboOrEffect.setFloat("radiusRange", this.radiusRange); + uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); + } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + buildUniformLayout(ubo) { + ubo.addUniform("radius", 1); + ubo.addUniform("height", 1); + ubo.addUniform("radiusRange", 1); + ubo.addUniform("directionRandomizer", 1); + } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + return "#define CYLINDEREMITTER"; + } + /** + * Returns the string "CylinderParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "CylinderParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = {}; + serializationObject.type = this.getClassName(); + serializationObject.radius = this.radius; + serializationObject.height = this.height; + serializationObject.radiusRange = this.radiusRange; + serializationObject.directionRandomizer = this.directionRandomizer; + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + */ + parse(serializationObject) { + this.radius = serializationObject.radius; + this.height = serializationObject.height; + this.radiusRange = serializationObject.radiusRange; + this.directionRandomizer = serializationObject.directionRandomizer; + } +} +/** + * Particle emitter emitting particles from the inside of a cylinder. + * It emits the particles randomly between two vectors. + */ +class CylinderDirectedParticleEmitter extends CylinderParticleEmitter { + /** + * Creates a new instance CylinderDirectedParticleEmitter + * @param radius the radius of the emission cylinder (1 by default) + * @param height the height of the emission cylinder (1 by default) + * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) + * @param direction1 the min limit of the emission direction (up vector by default) + * @param direction2 the max limit of the emission direction (up vector by default) + */ + constructor(radius = 1, height = 1, radiusRange = 1, + /** + * [Up vector] The min limit of the emission direction. + */ + direction1 = new Vector3(0, 1, 0), + /** + * [Up vector] The max limit of the emission direction. + */ + direction2 = new Vector3(0, 1, 0)) { + super(radius, height, radiusRange); + this.direction1 = direction1; + this.direction2 = direction2; + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + * @param _particle is the particle we are computed the direction for + * @param isLocal defines if the direction should be set in local space + */ + startDirectionFunction(worldMatrix, directionToUpdate, _particle, isLocal) { + const randX = RandomRange(this.direction1.x, this.direction2.x); + const randY = RandomRange(this.direction1.y, this.direction2.y); + const randZ = RandomRange(this.direction1.z, this.direction2.z); + if (isLocal) { + directionToUpdate.copyFromFloats(randX, randY, randZ); + return; + } + Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + applyToShader(uboOrEffect) { + uboOrEffect.setFloat("radius", this.radius); + uboOrEffect.setFloat("height", this.height); + uboOrEffect.setFloat("radiusRange", this.radiusRange); + uboOrEffect.setVector3("direction1", this.direction1); + uboOrEffect.setVector3("direction2", this.direction2); + } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + buildUniformLayout(ubo) { + ubo.addUniform("radius", 1); + ubo.addUniform("height", 1); + ubo.addUniform("radiusRange", 1); + ubo.addUniform("direction1", 3); + ubo.addUniform("direction2", 3); + } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"; + } + /** + * Returns the string "CylinderDirectedParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "CylinderDirectedParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.direction1 = this.direction1.asArray(); + serializationObject.direction2 = this.direction2.asArray(); + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + */ + parse(serializationObject) { + super.parse(serializationObject); + Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); + Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); + } +} + +/** + * Particle emitter emitting particles from the inside of a cone. + * It emits the particles alongside the cone volume from the base to the particle. + * The emission direction might be randomized. + */ +class ConeParticleEmitter { + /** + * Gets or sets the radius of the emission cone + */ + get radius() { + return this._radius; + } + set radius(value) { + this._radius = value; + this._buildHeight(); + } + /** + * Gets or sets the angle of the emission cone + */ + get angle() { + return this._angle; + } + set angle(value) { + this._angle = value; + this._buildHeight(); + } + _buildHeight() { + if (this._angle !== 0) { + this._height = this._radius / Math.tan(this._angle / 2); + } + else { + this._height = 1; + } + } + /** + * Creates a new instance ConeParticleEmitter + * @param radius the radius of the emission cone (1 by default) + * @param angle the cone base angle (PI by default) + * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0) + */ + constructor(radius = 1, angle = Math.PI, + /** [0] defines how much to randomize the particle direction [0-1] (default is 0) */ + directionRandomizer = 0) { + this.directionRandomizer = directionRandomizer; + /** + * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface) + */ + this.radiusRange = 1; + /** + * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface) + */ + this.heightRange = 1; + /** + * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone) + */ + this.emitFromSpawnPointOnly = false; + this.angle = angle; + this.radius = radius; + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + * @param particle is the particle we are computed the direction for + * @param isLocal defines if the direction should be set in local space + */ + startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { + if (isLocal) { + TmpVectors.Vector3[0].copyFrom(particle._localPosition).normalize(); + } + else { + particle.position.subtractToRef(worldMatrix.getTranslation(), TmpVectors.Vector3[0]).normalize(); + } + const randX = RandomRange(0, this.directionRandomizer); + const randY = RandomRange(0, this.directionRandomizer); + const randZ = RandomRange(0, this.directionRandomizer); + directionToUpdate.x = TmpVectors.Vector3[0].x + randX; + directionToUpdate.y = TmpVectors.Vector3[0].y + randY; + directionToUpdate.z = TmpVectors.Vector3[0].z + randZ; + directionToUpdate.normalize(); + } + /** + * Called by the particle System when the position is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param positionToUpdate is the position vector to update with the result + * @param particle is the particle we are computed the position for + * @param isLocal defines if the position should be set in local space + */ + startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { + const s = RandomRange(0, Math.PI * 2); + let h; + if (!this.emitFromSpawnPointOnly) { + h = RandomRange(0, this.heightRange); + // Better distribution in a cone at normal angles. + h = 1 - h * h; + } + else { + h = 0.0001; + } + let radius = this._radius - RandomRange(0, this._radius * this.radiusRange); + radius = radius * h; + const randX = radius * Math.sin(s); + const randZ = radius * Math.cos(s); + const randY = h * this._height; + if (isLocal) { + positionToUpdate.x = randX; + positionToUpdate.y = randY; + positionToUpdate.z = randZ; + return; + } + Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate); + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + applyToShader(uboOrEffect) { + uboOrEffect.setFloat2("radius", this._radius, this.radiusRange); + uboOrEffect.setFloat("coneAngle", this._angle); + uboOrEffect.setFloat2("height", this._height, this.heightRange); + uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); + } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + buildUniformLayout(ubo) { + ubo.addUniform("radius", 2); + ubo.addUniform("coneAngle", 1); + ubo.addUniform("height", 2); + ubo.addUniform("directionRandomizer", 1); + } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + let defines = "#define CONEEMITTER"; + if (this.emitFromSpawnPointOnly) { + defines += "\n#define CONEEMITTERSPAWNPOINT"; + } + return defines; + } + /** + * Returns the string "ConeParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "ConeParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = {}; + serializationObject.type = this.getClassName(); + serializationObject.radius = this._radius; + serializationObject.angle = this._angle; + serializationObject.directionRandomizer = this.directionRandomizer; + serializationObject.radiusRange = this.radiusRange; + serializationObject.heightRange = this.heightRange; + serializationObject.emitFromSpawnPointOnly = this.emitFromSpawnPointOnly; + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + */ + parse(serializationObject) { + this.radius = serializationObject.radius; + this.angle = serializationObject.angle; + this.directionRandomizer = serializationObject.directionRandomizer; + this.radiusRange = serializationObject.radiusRange !== undefined ? serializationObject.radiusRange : 1; + this.heightRange = serializationObject.radiusRange !== undefined ? serializationObject.heightRange : 1; + this.emitFromSpawnPointOnly = serializationObject.emitFromSpawnPointOnly !== undefined ? serializationObject.emitFromSpawnPointOnly : false; + } +} +class ConeDirectedParticleEmitter extends ConeParticleEmitter { + constructor(radius = 1, angle = Math.PI, + /** + * [Up vector] The min limit of the emission direction. + */ + direction1 = new Vector3(0, 1, 0), + /** + * [Up vector] The max limit of the emission direction. + */ + direction2 = new Vector3(0, 1, 0)) { + super(radius, angle); + this.direction1 = direction1; + this.direction2 = direction2; + } + /** + * Called by the particle System when the direction is computed for the created particle. + * @param worldMatrix is the world matrix of the particle system + * @param directionToUpdate is the direction vector to update with the result + */ + startDirectionFunction(worldMatrix, directionToUpdate) { + const randX = RandomRange(this.direction1.x, this.direction2.x); + const randY = RandomRange(this.direction1.y, this.direction2.y); + const randZ = RandomRange(this.direction1.z, this.direction2.z); + Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); + } + /** + * Clones the current emitter and returns a copy of it + * @returns the new emitter + */ + clone() { + const newOne = new ConeDirectedParticleEmitter(this.radius, this.angle, this.direction1, this.direction2); + DeepCopier.DeepCopy(this, newOne); + return newOne; + } + /** + * Called by the GPUParticleSystem to setup the update shader + * @param uboOrEffect defines the update shader + */ + applyToShader(uboOrEffect) { + uboOrEffect.setFloat("radius", this.radius); + uboOrEffect.setFloat("radiusRange", this.radiusRange); + uboOrEffect.setVector3("direction1", this.direction1); + uboOrEffect.setVector3("direction2", this.direction2); + } + /** + * Creates the structure of the ubo for this particle emitter + * @param ubo ubo to create the structure for + */ + buildUniformLayout(ubo) { + ubo.addUniform("radius", 1); + ubo.addUniform("radiusRange", 1); + ubo.addUniform("direction1", 3); + ubo.addUniform("direction2", 3); + } + /** + * Returns a string to use to update the GPU particles update shader + * @returns a string containing the defines string + */ + getEffectDefines() { + return "#define CONEEMITTER\n#define DIRECTEDCONEEMITTER"; + } + /** + * Returns the string "ConeDirectedParticleEmitter" + * @returns a string containing the class name + */ + getClassName() { + return "ConeDirectedParticleEmitter"; + } + /** + * Serializes the particle system to a JSON object. + * @returns the JSON object + */ + serialize() { + const serializationObject = super.serialize(); + serializationObject.direction1 = this.direction1.asArray(); + serializationObject.direction2 = this.direction2.asArray(); + return serializationObject; + } + /** + * Parse properties from a JSON object + * @param serializationObject defines the JSON object + */ + parse(serializationObject) { + super.parse(serializationObject); + this.direction1.copyFrom(serializationObject.direction1); + this.direction2.copyFrom(serializationObject.direction2); + } +} + +/** + * Creates a Point Emitter for the particle system (emits directly from the emitter position) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + * @returns the emitter + */ +function CreatePointEmitter(direction1, direction2) { + const particleEmitter = new PointParticleEmitter(); + particleEmitter.direction1 = direction1; + particleEmitter.direction2 = direction2; + return particleEmitter; +} +/** + * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) + * @param radius The radius of the hemisphere to emit from + * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + * @returns the emitter + */ +function CreateHemisphericEmitter(radius = 1, radiusRange = 1) { + return new HemisphericParticleEmitter(radius, radiusRange); +} +/** + * Creates a Sphere Emitter for the particle system (emits along the sphere radius) + * @param radius The radius of the sphere to emit from + * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + * @returns the emitter + */ +function CreateSphereEmitter(radius = 1, radiusRange = 1) { + return new SphereParticleEmitter(radius, radiusRange); +} +/** + * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) + * @param radius The radius of the sphere to emit from + * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere + * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere + * @returns the emitter + */ +function CreateDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + return new SphereDirectedParticleEmitter(radius, direction1, direction2); +} +/** + * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position) + * @param radius The radius of the emission cylinder + * @param height The height of the emission cylinder + * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius + * @param directionRandomizer How much to randomize the particle direction [0-1] + * @returns the emitter + */ +function CreateCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) { + return new CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer); +} +/** + * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2) + * @param radius The radius of the cylinder to emit from + * @param height The height of the emission cylinder + * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder + * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder + * @returns the emitter + */ +function CreateDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + return new CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2); +} +/** + * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) + * @param radius The radius of the cone to emit from + * @param angle The base angle of the cone + * @returns the emitter + */ +function CreateConeEmitter(radius = 1, angle = Math.PI / 4) { + return new ConeParticleEmitter(radius, angle); +} +function CreateDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + return new ConeDirectedParticleEmitter(radius, angle, direction1, direction2); +} + +/** + * This represents a particle system in Babylon. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function. + * @example https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro + */ +class ParticleSystem extends ThinParticleSystem { + constructor() { + super(...arguments); + /** + * @internal + * If the particle systems emitter should be disposed when the particle system is disposed + */ + this._disposeEmitterOnDispose = false; + this._emitFromParticle = (particle) => { + if (!this._subEmitters || this._subEmitters.length === 0) { + return; + } + const templateIndex = Math.floor(Math.random() * this._subEmitters.length); + this._subEmitters[templateIndex].forEach((subEmitter) => { + if (subEmitter.type === 1 /* SubEmitterType.END */) { + const subSystem = subEmitter.clone(); + particle._inheritParticleInfoToSubEmitter(subSystem); + subSystem.particleSystem._rootParticleSystem = this; + this.activeSubSystems.push(subSystem.particleSystem); + subSystem.particleSystem.start(); + } + }); + }; + } + /** + * Creates a Point Emitter for the particle system (emits directly from the emitter position) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + * @returns the emitter + */ + createPointEmitter(direction1, direction2) { + const particleEmitter = CreatePointEmitter(direction1, direction2); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) + * @param radius The radius of the hemisphere to emit from + * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + * @returns the emitter + */ + createHemisphericEmitter(radius = 1, radiusRange = 1) { + const particleEmitter = CreateHemisphericEmitter(radius, radiusRange); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Sphere Emitter for the particle system (emits along the sphere radius) + * @param radius The radius of the sphere to emit from + * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + * @returns the emitter + */ + createSphereEmitter(radius = 1, radiusRange = 1) { + const particleEmitter = CreateSphereEmitter(radius, radiusRange); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) + * @param radius The radius of the sphere to emit from + * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere + * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere + * @returns the emitter + */ + createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + const particleEmitter = CreateDirectedSphereEmitter(radius, direction1, direction2); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position) + * @param radius The radius of the emission cylinder + * @param height The height of the emission cylinder + * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius + * @param directionRandomizer How much to randomize the particle direction [0-1] + * @returns the emitter + */ + createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) { + const particleEmitter = CreateCylinderEmitter(radius, height, radiusRange, directionRandomizer); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2) + * @param radius The radius of the cylinder to emit from + * @param height The height of the emission cylinder + * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder + * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder + * @returns the emitter + */ + createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + const particleEmitter = CreateDirectedCylinderEmitter(radius, height, radiusRange, direction1, direction2); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) + * @param radius The radius of the cone to emit from + * @param angle The base angle of the cone + * @returns the emitter + */ + createConeEmitter(radius = 1, angle = Math.PI / 4) { + const particleEmitter = CreateConeEmitter(radius, angle); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + createDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + const particleEmitter = CreateDirectedConeEmitter(radius, angle, direction1, direction2); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox + * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox + * @returns the emitter + */ + createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) { + const particleEmitter = new BoxParticleEmitter(); + this.particleEmitterType = particleEmitter; + this.direction1 = direction1; + this.direction2 = direction2; + this.minEmitBox = minEmitBox; + this.maxEmitBox = maxEmitBox; + return particleEmitter; + } + _prepareSubEmitterInternalArray() { + this._subEmitters = new Array(); + if (this.subEmitters) { + this.subEmitters.forEach((subEmitter) => { + if (subEmitter instanceof ParticleSystem) { + this._subEmitters.push([new SubEmitter(subEmitter)]); + } + else if (subEmitter instanceof SubEmitter) { + this._subEmitters.push([subEmitter]); + } + else if (subEmitter instanceof Array) { + this._subEmitters.push(subEmitter); + } + }); + } + } + _stopSubEmitters() { + if (!this.activeSubSystems) { + return; + } + this.activeSubSystems.forEach((subSystem) => { + subSystem.stop(true); + }); + this.activeSubSystems = []; + } + _removeFromRoot() { + if (!this._rootParticleSystem) { + return; + } + const index = this._rootParticleSystem.activeSubSystems.indexOf(this); + if (index !== -1) { + this._rootParticleSystem.activeSubSystems.splice(index, 1); + } + this._rootParticleSystem = null; + } + _preStart() { + // Convert the subEmitters field to the constant type field _subEmitters + this._prepareSubEmitterInternalArray(); + if (this._subEmitters && this._subEmitters.length != 0) { + this.activeSubSystems = []; + } + } + _postStop(stopSubEmitters) { + if (stopSubEmitters) { + this._stopSubEmitters(); + } + } + _prepareParticle(particle) { + // Attach emitters + if (this._subEmitters && this._subEmitters.length > 0) { + const subEmitters = this._subEmitters[Math.floor(Math.random() * this._subEmitters.length)]; + particle._attachedSubEmitters = []; + subEmitters.forEach((subEmitter) => { + if (subEmitter.type === 0 /* SubEmitterType.ATTACHED */) { + const newEmitter = subEmitter.clone(); + particle._attachedSubEmitters.push(newEmitter); + newEmitter.particleSystem.start(); + } + }); + } + } + /** @internal */ + _onDispose(disposeAttachedSubEmitters = false, disposeEndSubEmitters = false) { + this._removeFromRoot(); + if (this.subEmitters && !this._subEmitters) { + this._prepareSubEmitterInternalArray(); + } + if (disposeAttachedSubEmitters) { + this.particles?.forEach((particle) => { + if (particle._attachedSubEmitters) { + for (let i = particle._attachedSubEmitters.length - 1; i >= 0; i -= 1) { + particle._attachedSubEmitters[i].dispose(); + } + } + }); + } + if (disposeEndSubEmitters) { + if (this.activeSubSystems) { + for (let i = this.activeSubSystems.length - 1; i >= 0; i -= 1) { + this.activeSubSystems[i].dispose(); + } + } + } + if (this._subEmitters && this._subEmitters.length) { + for (let index = 0; index < this._subEmitters.length; index++) { + for (const subEmitter of this._subEmitters[index]) { + subEmitter.dispose(); + } + } + this._subEmitters = []; + this.subEmitters = []; + } + if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) { + this.emitter.dispose(true); + } + } + /** + * @internal + */ + static _Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl) { + let scene; + if (sceneOrEngine instanceof AbstractEngine) { + scene = null; + } + else { + scene = sceneOrEngine; + } + const internalClass = GetClass("BABYLON.Texture"); + if (internalClass && scene) { + // Texture + if (parsedParticleSystem.texture) { + particleSystem.particleTexture = internalClass.Parse(parsedParticleSystem.texture, scene, rootUrl); + } + else if (parsedParticleSystem.textureName) { + particleSystem.particleTexture = new internalClass(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true); + particleSystem.particleTexture.name = parsedParticleSystem.textureName; + } + } + // Emitter + if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) { + particleSystem.emitter = Vector3.Zero(); + } + else if (parsedParticleSystem.emitterId && scene) { + particleSystem.emitter = scene.getLastMeshById(parsedParticleSystem.emitterId); + } + else { + particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter); + } + particleSystem.isLocal = !!parsedParticleSystem.isLocal; + // Misc. + if (parsedParticleSystem.renderingGroupId !== undefined) { + particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId; + } + if (parsedParticleSystem.isBillboardBased !== undefined) { + particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased; + } + if (parsedParticleSystem.billboardMode !== undefined) { + particleSystem.billboardMode = parsedParticleSystem.billboardMode; + } + if (parsedParticleSystem.useLogarithmicDepth !== undefined) { + particleSystem.useLogarithmicDepth = parsedParticleSystem.useLogarithmicDepth; + } + // Animations + if (parsedParticleSystem.animations) { + for (let animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) { + const parsedAnimation = parsedParticleSystem.animations[animationIndex]; + const internalClass = GetClass("BABYLON.Animation"); + if (internalClass) { + particleSystem.animations.push(internalClass.Parse(parsedAnimation)); + } + } + particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart; + particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom; + particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo; + particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop; + } + if (parsedParticleSystem.autoAnimate && scene) { + scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0); + } + // Particle system + particleSystem.startDelay = parsedParticleSystem.startDelay | 0; + particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed; + particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed; + particleSystem.minSize = parsedParticleSystem.minSize; + particleSystem.maxSize = parsedParticleSystem.maxSize; + if (parsedParticleSystem.minScaleX) { + particleSystem.minScaleX = parsedParticleSystem.minScaleX; + particleSystem.maxScaleX = parsedParticleSystem.maxScaleX; + particleSystem.minScaleY = parsedParticleSystem.minScaleY; + particleSystem.maxScaleY = parsedParticleSystem.maxScaleY; + } + if (parsedParticleSystem.preWarmCycles !== undefined) { + particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles; + particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset; + } + if (parsedParticleSystem.minInitialRotation !== undefined) { + particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation; + particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation; + } + particleSystem.minLifeTime = parsedParticleSystem.minLifeTime; + particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime; + particleSystem.minEmitPower = parsedParticleSystem.minEmitPower; + particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower; + particleSystem.emitRate = parsedParticleSystem.emitRate; + particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity); + if (parsedParticleSystem.noiseStrength) { + particleSystem.noiseStrength = Vector3.FromArray(parsedParticleSystem.noiseStrength); + } + particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1); + particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2); + particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead); + particleSystem.updateSpeed = parsedParticleSystem.updateSpeed; + particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration; + particleSystem.blendMode = parsedParticleSystem.blendMode; + if (parsedParticleSystem.colorGradients) { + for (const colorGradient of parsedParticleSystem.colorGradients) { + particleSystem.addColorGradient(colorGradient.gradient, Color4.FromArray(colorGradient.color1), colorGradient.color2 ? Color4.FromArray(colorGradient.color2) : undefined); + } + } + if (parsedParticleSystem.rampGradients) { + for (const rampGradient of parsedParticleSystem.rampGradients) { + particleSystem.addRampGradient(rampGradient.gradient, Color3.FromArray(rampGradient.color)); + } + particleSystem.useRampGradients = parsedParticleSystem.useRampGradients; + } + if (parsedParticleSystem.colorRemapGradients) { + for (const colorRemapGradient of parsedParticleSystem.colorRemapGradients) { + particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2); + } + } + if (parsedParticleSystem.alphaRemapGradients) { + for (const alphaRemapGradient of parsedParticleSystem.alphaRemapGradients) { + particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2); + } + } + if (parsedParticleSystem.sizeGradients) { + for (const sizeGradient of parsedParticleSystem.sizeGradients) { + particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2); + } + } + if (parsedParticleSystem.angularSpeedGradients) { + for (const angularSpeedGradient of parsedParticleSystem.angularSpeedGradients) { + particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2); + } + } + if (parsedParticleSystem.velocityGradients) { + for (const velocityGradient of parsedParticleSystem.velocityGradients) { + particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2); + } + } + if (parsedParticleSystem.dragGradients) { + for (const dragGradient of parsedParticleSystem.dragGradients) { + particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2); + } + } + if (parsedParticleSystem.emitRateGradients) { + for (const emitRateGradient of parsedParticleSystem.emitRateGradients) { + particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2); + } + } + if (parsedParticleSystem.startSizeGradients) { + for (const startSizeGradient of parsedParticleSystem.startSizeGradients) { + particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2); + } + } + if (parsedParticleSystem.lifeTimeGradients) { + for (const lifeTimeGradient of parsedParticleSystem.lifeTimeGradients) { + particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2); + } + } + if (parsedParticleSystem.limitVelocityGradients) { + for (const limitVelocityGradient of parsedParticleSystem.limitVelocityGradients) { + particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2); + } + particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping; + } + if (parsedParticleSystem.noiseTexture && scene) { + const internalClass = GetClass("BABYLON.ProceduralTexture"); + particleSystem.noiseTexture = internalClass.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl); + } + // Emitter + let emitterType; + if (parsedParticleSystem.particleEmitterType) { + switch (parsedParticleSystem.particleEmitterType.type) { + case "SphereParticleEmitter": + emitterType = new SphereParticleEmitter(); + break; + case "SphereDirectedParticleEmitter": + emitterType = new SphereDirectedParticleEmitter(); + break; + case "ConeEmitter": + case "ConeParticleEmitter": + emitterType = new ConeParticleEmitter(); + break; + case "ConeDirectedParticleEmitter": + emitterType = new ConeDirectedParticleEmitter(); + break; + case "CylinderParticleEmitter": + emitterType = new CylinderParticleEmitter(); + break; + case "CylinderDirectedParticleEmitter": + emitterType = new CylinderDirectedParticleEmitter(); + break; + case "HemisphericParticleEmitter": + emitterType = new HemisphericParticleEmitter(); + break; + case "PointParticleEmitter": + emitterType = new PointParticleEmitter(); + break; + case "MeshParticleEmitter": + emitterType = new MeshParticleEmitter(); + break; + case "CustomParticleEmitter": + emitterType = new CustomParticleEmitter(); + break; + case "BoxEmitter": + case "BoxParticleEmitter": + default: + emitterType = new BoxParticleEmitter(); + break; + } + emitterType.parse(parsedParticleSystem.particleEmitterType, scene); + } + else { + emitterType = new BoxParticleEmitter(); + emitterType.parse(parsedParticleSystem, scene); + } + particleSystem.particleEmitterType = emitterType; + // Animation sheet + particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID; + particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID; + particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop ?? true; + particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth; + particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight; + particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed; + particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell; + particleSystem.disposeOnStop = parsedParticleSystem.disposeOnStop ?? false; + particleSystem.manualEmitCount = parsedParticleSystem.manualEmitCount ?? -1; + } + /** + * Parses a JSON object to create a particle system. + * @param parsedParticleSystem The JSON object to parse + * @param sceneOrEngine The scene or the engine to create the particle system in + * @param rootUrl The root url to use to load external dependencies like texture + * @param doNotStart Ignore the preventAutoStart attribute and does not start + * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) + * @returns the Parsed particle system + */ + static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) { + const name = parsedParticleSystem.name; + let custom = null; + let program = null; + let engine; + let scene; + if (sceneOrEngine instanceof AbstractEngine) { + engine = sceneOrEngine; + } + else { + scene = sceneOrEngine; + engine = scene.getEngine(); + } + if (parsedParticleSystem.customShader && engine.createEffectForParticles) { + program = parsedParticleSystem.customShader; + const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; + custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines); + } + const particleSystem = new ParticleSystem(name, capacity || parsedParticleSystem.capacity, sceneOrEngine, custom, parsedParticleSystem.isAnimationSheetEnabled); + particleSystem.customShader = program; + particleSystem._rootUrl = rootUrl; + if (parsedParticleSystem.id) { + particleSystem.id = parsedParticleSystem.id; + } + // SubEmitters + if (parsedParticleSystem.subEmitters) { + particleSystem.subEmitters = []; + for (const cell of parsedParticleSystem.subEmitters) { + const cellArray = []; + for (const sub of cell) { + cellArray.push(SubEmitter.Parse(sub, sceneOrEngine, rootUrl)); + } + particleSystem.subEmitters.push(cellArray); + } + } + ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl); + if (parsedParticleSystem.textureMask) { + particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask); + } + if (parsedParticleSystem.worldOffset) { + particleSystem.worldOffset = Vector3.FromArray(parsedParticleSystem.worldOffset); + } + // Auto start + if (parsedParticleSystem.preventAutoStart) { + particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart; + } + if (!doNotStart && !particleSystem.preventAutoStart) { + particleSystem.start(); + } + return particleSystem; + } + /** + * Serializes the particle system to a JSON object + * @param serializeTexture defines if the texture must be serialized as well + * @returns the JSON object + */ + serialize(serializeTexture = false) { + const serializationObject = {}; + ParticleSystem._Serialize(serializationObject, this, serializeTexture); + serializationObject.textureMask = this.textureMask.asArray(); + serializationObject.customShader = this.customShader; + serializationObject.preventAutoStart = this.preventAutoStart; + serializationObject.worldOffset = this.worldOffset.asArray(); + // SubEmitters + if (this.subEmitters) { + serializationObject.subEmitters = []; + if (!this._subEmitters) { + this._prepareSubEmitterInternalArray(); + } + for (const subs of this._subEmitters) { + const cell = []; + for (const sub of subs) { + cell.push(sub.serialize(serializeTexture)); + } + serializationObject.subEmitters.push(cell); + } + } + return serializationObject; + } + /** + * @internal + */ + static _Serialize(serializationObject, particleSystem, serializeTexture) { + serializationObject.name = particleSystem.name; + serializationObject.id = particleSystem.id; + serializationObject.capacity = particleSystem.getCapacity(); + serializationObject.disposeOnStop = particleSystem.disposeOnStop; + serializationObject.manualEmitCount = particleSystem.manualEmitCount; + // Emitter + if (particleSystem.emitter.position) { + const emitterMesh = particleSystem.emitter; + serializationObject.emitterId = emitterMesh.id; + } + else { + const emitterPosition = particleSystem.emitter; + serializationObject.emitter = emitterPosition.asArray(); + } + // Emitter + if (particleSystem.particleEmitterType) { + serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize(); + } + if (particleSystem.particleTexture) { + if (serializeTexture) { + serializationObject.texture = particleSystem.particleTexture.serialize(); + } + else { + serializationObject.textureName = particleSystem.particleTexture.name; + serializationObject.invertY = !!particleSystem.particleTexture._invertY; + } + } + serializationObject.isLocal = particleSystem.isLocal; + // Animations + SerializationHelper.AppendSerializedAnimations(particleSystem, serializationObject); + serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart; + serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom; + serializationObject.beginAnimationTo = particleSystem.beginAnimationTo; + serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop; + // Particle system + serializationObject.startDelay = particleSystem.startDelay; + serializationObject.renderingGroupId = particleSystem.renderingGroupId; + serializationObject.isBillboardBased = particleSystem.isBillboardBased; + serializationObject.billboardMode = particleSystem.billboardMode; + serializationObject.minAngularSpeed = particleSystem.minAngularSpeed; + serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed; + serializationObject.minSize = particleSystem.minSize; + serializationObject.maxSize = particleSystem.maxSize; + serializationObject.minScaleX = particleSystem.minScaleX; + serializationObject.maxScaleX = particleSystem.maxScaleX; + serializationObject.minScaleY = particleSystem.minScaleY; + serializationObject.maxScaleY = particleSystem.maxScaleY; + serializationObject.minEmitPower = particleSystem.minEmitPower; + serializationObject.maxEmitPower = particleSystem.maxEmitPower; + serializationObject.minLifeTime = particleSystem.minLifeTime; + serializationObject.maxLifeTime = particleSystem.maxLifeTime; + serializationObject.emitRate = particleSystem.emitRate; + serializationObject.gravity = particleSystem.gravity.asArray(); + serializationObject.noiseStrength = particleSystem.noiseStrength.asArray(); + serializationObject.color1 = particleSystem.color1.asArray(); + serializationObject.color2 = particleSystem.color2.asArray(); + serializationObject.colorDead = particleSystem.colorDead.asArray(); + serializationObject.updateSpeed = particleSystem.updateSpeed; + serializationObject.targetStopDuration = particleSystem.targetStopDuration; + serializationObject.blendMode = particleSystem.blendMode; + serializationObject.preWarmCycles = particleSystem.preWarmCycles; + serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset; + serializationObject.minInitialRotation = particleSystem.minInitialRotation; + serializationObject.maxInitialRotation = particleSystem.maxInitialRotation; + serializationObject.startSpriteCellID = particleSystem.startSpriteCellID; + serializationObject.spriteCellLoop = particleSystem.spriteCellLoop; + serializationObject.endSpriteCellID = particleSystem.endSpriteCellID; + serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed; + serializationObject.spriteCellWidth = particleSystem.spriteCellWidth; + serializationObject.spriteCellHeight = particleSystem.spriteCellHeight; + serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell; + serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled; + serializationObject.useLogarithmicDepth = particleSystem.useLogarithmicDepth; + const colorGradients = particleSystem.getColorGradients(); + if (colorGradients) { + serializationObject.colorGradients = []; + for (const colorGradient of colorGradients) { + const serializedGradient = { + gradient: colorGradient.gradient, + color1: colorGradient.color1.asArray(), + }; + if (colorGradient.color2) { + serializedGradient.color2 = colorGradient.color2.asArray(); + } + else { + serializedGradient.color2 = colorGradient.color1.asArray(); + } + serializationObject.colorGradients.push(serializedGradient); + } + } + const rampGradients = particleSystem.getRampGradients(); + if (rampGradients) { + serializationObject.rampGradients = []; + for (const rampGradient of rampGradients) { + const serializedGradient = { + gradient: rampGradient.gradient, + color: rampGradient.color.asArray(), + }; + serializationObject.rampGradients.push(serializedGradient); + } + serializationObject.useRampGradients = particleSystem.useRampGradients; + } + const colorRemapGradients = particleSystem.getColorRemapGradients(); + if (colorRemapGradients) { + serializationObject.colorRemapGradients = []; + for (const colorRemapGradient of colorRemapGradients) { + const serializedGradient = { + gradient: colorRemapGradient.gradient, + factor1: colorRemapGradient.factor1, + }; + if (colorRemapGradient.factor2 !== undefined) { + serializedGradient.factor2 = colorRemapGradient.factor2; + } + else { + serializedGradient.factor2 = colorRemapGradient.factor1; + } + serializationObject.colorRemapGradients.push(serializedGradient); + } + } + const alphaRemapGradients = particleSystem.getAlphaRemapGradients(); + if (alphaRemapGradients) { + serializationObject.alphaRemapGradients = []; + for (const alphaRemapGradient of alphaRemapGradients) { + const serializedGradient = { + gradient: alphaRemapGradient.gradient, + factor1: alphaRemapGradient.factor1, + }; + if (alphaRemapGradient.factor2 !== undefined) { + serializedGradient.factor2 = alphaRemapGradient.factor2; + } + else { + serializedGradient.factor2 = alphaRemapGradient.factor1; + } + serializationObject.alphaRemapGradients.push(serializedGradient); + } + } + const sizeGradients = particleSystem.getSizeGradients(); + if (sizeGradients) { + serializationObject.sizeGradients = []; + for (const sizeGradient of sizeGradients) { + const serializedGradient = { + gradient: sizeGradient.gradient, + factor1: sizeGradient.factor1, + }; + if (sizeGradient.factor2 !== undefined) { + serializedGradient.factor2 = sizeGradient.factor2; + } + else { + serializedGradient.factor2 = sizeGradient.factor1; + } + serializationObject.sizeGradients.push(serializedGradient); + } + } + const angularSpeedGradients = particleSystem.getAngularSpeedGradients(); + if (angularSpeedGradients) { + serializationObject.angularSpeedGradients = []; + for (const angularSpeedGradient of angularSpeedGradients) { + const serializedGradient = { + gradient: angularSpeedGradient.gradient, + factor1: angularSpeedGradient.factor1, + }; + if (angularSpeedGradient.factor2 !== undefined) { + serializedGradient.factor2 = angularSpeedGradient.factor2; + } + else { + serializedGradient.factor2 = angularSpeedGradient.factor1; + } + serializationObject.angularSpeedGradients.push(serializedGradient); + } + } + const velocityGradients = particleSystem.getVelocityGradients(); + if (velocityGradients) { + serializationObject.velocityGradients = []; + for (const velocityGradient of velocityGradients) { + const serializedGradient = { + gradient: velocityGradient.gradient, + factor1: velocityGradient.factor1, + }; + if (velocityGradient.factor2 !== undefined) { + serializedGradient.factor2 = velocityGradient.factor2; + } + else { + serializedGradient.factor2 = velocityGradient.factor1; + } + serializationObject.velocityGradients.push(serializedGradient); + } + } + const dragGradients = particleSystem.getDragGradients(); + if (dragGradients) { + serializationObject.dragGradients = []; + for (const dragGradient of dragGradients) { + const serializedGradient = { + gradient: dragGradient.gradient, + factor1: dragGradient.factor1, + }; + if (dragGradient.factor2 !== undefined) { + serializedGradient.factor2 = dragGradient.factor2; + } + else { + serializedGradient.factor2 = dragGradient.factor1; + } + serializationObject.dragGradients.push(serializedGradient); + } + } + const emitRateGradients = particleSystem.getEmitRateGradients(); + if (emitRateGradients) { + serializationObject.emitRateGradients = []; + for (const emitRateGradient of emitRateGradients) { + const serializedGradient = { + gradient: emitRateGradient.gradient, + factor1: emitRateGradient.factor1, + }; + if (emitRateGradient.factor2 !== undefined) { + serializedGradient.factor2 = emitRateGradient.factor2; + } + else { + serializedGradient.factor2 = emitRateGradient.factor1; + } + serializationObject.emitRateGradients.push(serializedGradient); + } + } + const startSizeGradients = particleSystem.getStartSizeGradients(); + if (startSizeGradients) { + serializationObject.startSizeGradients = []; + for (const startSizeGradient of startSizeGradients) { + const serializedGradient = { + gradient: startSizeGradient.gradient, + factor1: startSizeGradient.factor1, + }; + if (startSizeGradient.factor2 !== undefined) { + serializedGradient.factor2 = startSizeGradient.factor2; + } + else { + serializedGradient.factor2 = startSizeGradient.factor1; + } + serializationObject.startSizeGradients.push(serializedGradient); + } + } + const lifeTimeGradients = particleSystem.getLifeTimeGradients(); + if (lifeTimeGradients) { + serializationObject.lifeTimeGradients = []; + for (const lifeTimeGradient of lifeTimeGradients) { + const serializedGradient = { + gradient: lifeTimeGradient.gradient, + factor1: lifeTimeGradient.factor1, + }; + if (lifeTimeGradient.factor2 !== undefined) { + serializedGradient.factor2 = lifeTimeGradient.factor2; + } + else { + serializedGradient.factor2 = lifeTimeGradient.factor1; + } + serializationObject.lifeTimeGradients.push(serializedGradient); + } + } + const limitVelocityGradients = particleSystem.getLimitVelocityGradients(); + if (limitVelocityGradients) { + serializationObject.limitVelocityGradients = []; + for (const limitVelocityGradient of limitVelocityGradients) { + const serializedGradient = { + gradient: limitVelocityGradient.gradient, + factor1: limitVelocityGradient.factor1, + }; + if (limitVelocityGradient.factor2 !== undefined) { + serializedGradient.factor2 = limitVelocityGradient.factor2; + } + else { + serializedGradient.factor2 = limitVelocityGradient.factor1; + } + serializationObject.limitVelocityGradients.push(serializedGradient); + } + serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping; + } + if (particleSystem.noiseTexture) { + serializationObject.noiseTexture = particleSystem.noiseTexture.serialize(); + } + } + // Clone + /** + * Clones the particle system. + * @param name The name of the cloned object + * @param newEmitter The new emitter to use + * @param cloneTexture Also clone the textures if true + * @returns the cloned particle system + */ + clone(name, newEmitter, cloneTexture = false) { + const custom = { ...this._customWrappers }; + let program = null; + const engine = this._engine; + if (engine.createEffectForParticles) { + if (this.customShader != null) { + program = this.customShader; + const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; + const effect = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines); + if (!custom[0]) { + this.setCustomEffect(effect, 0); + } + else { + custom[0].effect = effect; + } + } + } + const serialization = this.serialize(cloneTexture); + const result = ParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl); + result.name = name; + result.customShader = program; + result._customWrappers = custom; + if (newEmitter === undefined) { + newEmitter = this.emitter; + } + if (this.noiseTexture) { + result.noiseTexture = this.noiseTexture.clone(); + } + result.emitter = newEmitter; + if (!this.preventAutoStart) { + result.start(); + } + return result; + } +} +/** + * Billboard mode will only apply to Y axis + */ +ParticleSystem.BILLBOARDMODE_Y = 2; +/** + * Billboard mode will apply to all axes + */ +ParticleSystem.BILLBOARDMODE_ALL = 7; +/** + * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction + */ +ParticleSystem.BILLBOARDMODE_STRETCHED = 8; +/** + * Special billboard mode where the particle will be billboard to the camera but only around the axis of the direction of particle emission + */ +ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL = 9; +SubEmitter._ParseParticleSystem = ParticleSystem.Parse; + +// This implementation was based on the original MIT-licensed TRACE repository +// from https://github.com/septagon/TRACE. +/** + * Generic implementation of Levenshtein distance. + */ +var Levenshtein; +(function (Levenshtein) { + /** + * Alphabet from which to construct sequences to be compared using Levenshtein + * distance. + */ + class Alphabet { + /** + * Serialize the Alphabet to JSON string. + * @returns JSON serialization + */ + serialize() { + const jsonObject = {}; + const characters = new Array(this._characterToIdx.size); + this._characterToIdx.forEach((v, k) => { + characters[v] = k; + }); + jsonObject["characters"] = characters; + jsonObject["insertionCosts"] = this._insertionCosts; + jsonObject["deletionCosts"] = this._deletionCosts; + jsonObject["substitutionCosts"] = this._substitutionCosts; + return JSON.stringify(jsonObject); + } + /** + * Parse an Alphabet from a JSON serialization. + * @param json JSON string to deserialize + * @returns deserialized Alphabet + */ + static Deserialize(json) { + const jsonObject = JSON.parse(json); + const alphabet = new Alphabet(jsonObject["characters"]); + alphabet._insertionCosts = jsonObject["insertionCosts"]; + alphabet._deletionCosts = jsonObject["deletionCosts"]; + alphabet._substitutionCosts = jsonObject["substitutionCosts"]; + return alphabet; + } + /** + * Create a new Alphabet. + * @param characters characters of the alphabet + * @param charToInsertionCost function mapping characters to insertion costs + * @param charToDeletionCost function mapping characters to deletion costs + * @param charsToSubstitutionCost function mapping character pairs to substitution costs + */ + constructor(characters, charToInsertionCost = null, charToDeletionCost = null, charsToSubstitutionCost = null) { + charToInsertionCost = charToInsertionCost ?? (() => 1); + charToDeletionCost = charToDeletionCost ?? (() => 1); + charsToSubstitutionCost = charsToSubstitutionCost ?? ((a, b) => (a === b ? 0 : 1)); + this._characterToIdx = new Map(); + this._insertionCosts = new Array(characters.length); + this._deletionCosts = new Array(characters.length); + this._substitutionCosts = new Array(characters.length); + let c; + for (let outerIdx = 0; outerIdx < characters.length; ++outerIdx) { + c = characters[outerIdx]; + this._characterToIdx.set(c, outerIdx); + this._insertionCosts[outerIdx] = charToInsertionCost(c); + this._deletionCosts[outerIdx] = charToDeletionCost(c); + this._substitutionCosts[outerIdx] = new Array(characters.length); + for (let innerIdx = outerIdx; innerIdx < characters.length; ++innerIdx) { + this._substitutionCosts[outerIdx][innerIdx] = charsToSubstitutionCost(c, characters[innerIdx]); + } + } + } + /** + * Get the index (internally-assigned number) for a character. + * @param char character + * @returns index + */ + getCharacterIdx(char) { + return this._characterToIdx.get(char); + } + /** + * Get the insertion cost of a character from its index. + * @param idx character index + * @returns insertion cost + */ + getInsertionCost(idx) { + return this._insertionCosts[idx]; + } + /** + * Get the deletion cost of a character from its index. + * @param idx character index + * @returns deletion cost + */ + getDeletionCost(idx) { + return this._deletionCosts[idx]; + } + /** + * Gets the cost to substitute two characters. NOTE: this cost is + * required to be bi-directional, meaning it cannot matter which of + * the provided characters is being removed and which is being inserted. + * @param idx1 the first character index + * @param idx2 the second character index + * @returns substitution cost + */ + getSubstitutionCost(idx1, idx2) { + const min = Math.min(idx1, idx2); + const max = Math.max(idx1, idx2); + return this._substitutionCosts[min][max]; + } + } + Levenshtein.Alphabet = Alphabet; + /** + * Character sequence intended to be compared against other Sequences created + * with the same Alphabet in order to compute Levenshtein distance. + */ + class Sequence { + /** + * Serialize to JSON string. JSON representation does NOT include the Alphabet + * from which this Sequence was created; Alphabet must be independently + * serialized. + * @returns JSON string + */ + serialize() { + return JSON.stringify(this._characters); + } + /** + * Deserialize from JSON string and Alphabet. This should be the same Alphabet + * from which the Sequence was originally created, which must be serialized and + * deserialized independently so that it can be passed in here. + * @param json JSON string representation of Sequence + * @param alphabet Alphabet from which Sequence was originally created + * @returns Sequence + */ + static Deserialize(json, alphabet) { + const sequence = new Sequence([], alphabet); + sequence._characters = JSON.parse(json); + return sequence; + } + /** + * Create a new Sequence. + * @param characters characters in the new Sequence + * @param alphabet Alphabet, which must include all used characters + */ + constructor(characters, alphabet) { + if (characters.length > Sequence._MAX_SEQUENCE_LENGTH) { + throw new Error("Sequences longer than " + Sequence._MAX_SEQUENCE_LENGTH + " not supported."); + } + this._alphabet = alphabet; + this._characters = characters.map((c) => this._alphabet.getCharacterIdx(c)); + } + /** + * Get the distance between this Sequence and another. + * @param other sequence to compare to + * @returns Levenshtein distance + */ + distance(other) { + return Sequence._Distance(this, other); + } + /** + * Compute the Levenshtein distance between two Sequences. + * @param a first Sequence + * @param b second Sequence + * @returns Levenshtein distance + */ + static _Distance(a, b) { + const alphabet = a._alphabet; + if (alphabet !== b._alphabet) { + throw new Error("Cannot Levenshtein compare Sequences built from different alphabets."); + } + const aChars = a._characters; + const bChars = b._characters; + const aLength = aChars.length; + const bLength = bChars.length; + const costMatrix = Sequence._CostMatrix; + costMatrix[0][0] = 0; + for (let idx = 0; idx < aLength; ++idx) { + costMatrix[idx + 1][0] = costMatrix[idx][0] + alphabet.getInsertionCost(aChars[idx]); + } + for (let idx = 0; idx < bLength; ++idx) { + costMatrix[0][idx + 1] = costMatrix[0][idx] + alphabet.getInsertionCost(bChars[idx]); + } + for (let aIdx = 0; aIdx < aLength; ++aIdx) { + for (let bIdx = 0; bIdx < bLength; ++bIdx) { + Sequence._InsertionCost = costMatrix[aIdx + 1][bIdx] + alphabet.getInsertionCost(bChars[bIdx]); + Sequence._DeletionCost = costMatrix[aIdx][bIdx + 1] + alphabet.getDeletionCost(aChars[aIdx]); + Sequence._SubstitutionCost = costMatrix[aIdx][bIdx] + alphabet.getSubstitutionCost(aChars[aIdx], bChars[bIdx]); + costMatrix[aIdx + 1][bIdx + 1] = Math.min(Sequence._InsertionCost, Sequence._DeletionCost, Sequence._SubstitutionCost); + } + } + return costMatrix[aLength][bLength]; + } + } + // Scratch values + Sequence._MAX_SEQUENCE_LENGTH = 256; + Sequence._CostMatrix = [...Array(Sequence._MAX_SEQUENCE_LENGTH + 1)].map(() => new Array(Sequence._MAX_SEQUENCE_LENGTH + 1)); + Levenshtein.Sequence = Sequence; +})(Levenshtein || (Levenshtein = {})); +new Matrix(); + +const growthFactor = 1.5; +/** + * A class acting as a dynamic float32array used in the performance viewer + */ +class DynamicFloat32Array { + /** + * Creates a new DynamicFloat32Array with the desired item capacity. + * @param itemCapacity The initial item capacity you would like to set for the array. + */ + constructor(itemCapacity) { + this._view = new Float32Array(itemCapacity); + this._itemLength = 0; + } + /** + * The number of items currently in the array. + */ + get itemLength() { + return this._itemLength; + } + /** + * Gets value at index, NaN if no such index exists. + * @param index the index to get the value at. + * @returns the value at the index provided. + */ + at(index) { + if (index < 0 || index >= this._itemLength) { + return NaN; + } + return this._view[index]; + } + /** + * Gets a view of the original array from start to end (exclusive of end). + * @param start starting index. + * @param end ending index. + * @returns a subarray of the original array. + */ + subarray(start, end) { + if (start >= end || start < 0) { + return new Float32Array(0); + } + if (end > this._itemLength) { + end = this._itemLength; + } + return this._view.subarray(start, end); + } + /** + * Pushes items to the end of the array. + * @param item The item to push into the array. + */ + push(item) { + this._view[this._itemLength] = item; + this._itemLength++; + if (this._itemLength >= this._view.length) { + this._growArray(); + } + } + /** + * Grows the array by the growth factor when necessary. + */ + _growArray() { + const newCapacity = Math.floor(this._view.length * growthFactor); + const view = new Float32Array(newCapacity); + view.set(this._view); + this._view = view; + } +} + +// the initial size of our array, should be a multiple of two! +const InitialArraySize = 1800; +// three octets in a hexcode. #[AA][BB][CC], i.e. 24 bits of data. +const NumberOfBitsInHexcode = 24; +// Allows single numeral hex numbers to be appended by a 0. +const HexPadding = "0"; +// header for the timestamp column +const TimestampColHeader = "timestamp"; +// header for the numPoints column +const NumPointsColHeader = "numPoints"; +// regex to capture all carriage returns in the string. +const CarriageReturnRegex = /\r/g; +// string to use as separator when exporting extra information along with the dataset id +const ExportedDataSeparator = "@"; +/** + * The collector class handles the collection and storage of data into the appropriate array. + * The collector also handles notifying any observers of any updates. + */ +class PerformanceViewerCollector { + /** + * The offset for when actual data values start appearing inside a slice. + */ + static get SliceDataOffset() { + return 2; + } + /** + * The offset for the value of the number of points inside a slice. + */ + static get NumberOfPointsOffset() { + return 1; + } + /** + * Handles the creation of a performance viewer collector. + * @param _scene the scene to collect on. + * @param _enabledStrategyCallbacks the list of data to collect with callbacks for initialization purposes. + */ + constructor(_scene, _enabledStrategyCallbacks) { + this._scene = _scene; + /** + * Collects data for every dataset by using the appropriate strategy. This is called every frame. + * This method will then notify all observers with the latest slice. + */ + this._collectDataAtFrame = () => { + const timestamp = PrecisionDate.Now - this._startingTimestamp; + const numPoints = this.datasets.ids.length; + // add the starting index for the slice + const numberOfIndices = this.datasets.startingIndices.itemLength; + let startingIndex = 0; + if (numberOfIndices > 0) { + const previousStartingIndex = this.datasets.startingIndices.at(numberOfIndices - 1); + startingIndex = + previousStartingIndex + this.datasets.data.at(previousStartingIndex + PerformanceViewerCollector.NumberOfPointsOffset) + PerformanceViewerCollector.SliceDataOffset; + } + this.datasets.startingIndices.push(startingIndex); + // add the first 2 items in our slice. + this.datasets.data.push(timestamp); + this.datasets.data.push(numPoints); + // add the values inside the slice. + this.datasets.ids.forEach((id) => { + const strategy = this._strategies.get(id); + if (!strategy) { + return; + } + this.datasets.data.push(strategy.getData()); + }); + if (this.datasetObservable.hasObservers()) { + const slice = [timestamp, numPoints]; + for (let i = 0; i < numPoints; i++) { + slice.push(this.datasets.data.at(startingIndex + PerformanceViewerCollector.SliceDataOffset + i)); + } + this.datasetObservable.notifyObservers(slice); + } + }; + this.datasets = { + ids: [], + data: new DynamicFloat32Array(InitialArraySize), + startingIndices: new DynamicFloat32Array(InitialArraySize), + }; + this._strategies = new Map(); + this._datasetMeta = new Map(); + this._eventRestoreSet = new Set(); + this._customEventObservable = new Observable(); + this.datasetObservable = new Observable(); + this.metadataObservable = new Observable((observer) => observer.callback(this._datasetMeta, new EventState(0))); + if (_enabledStrategyCallbacks) { + this.addCollectionStrategies(..._enabledStrategyCallbacks); + } + } + /** + * Registers a custom string event which will be callable via sendEvent. This method returns an event object which will contain the id of the event. + * The user can set a value optionally, which will be used in the sendEvent method. If the value is set, we will record this value at the end of each frame, + * if not we will increment our counter and record the value of the counter at the end of each frame. The value recorded is 0 if no sendEvent method is called, within a frame. + * @param name The name of the event to register + * @param forceUpdate if the code should force add an event, and replace the last one. + * @param category the category for that event + * @returns The event registered, used in sendEvent + */ + registerEvent(name, forceUpdate, category) { + if (this._strategies.has(name) && !forceUpdate) { + return; + } + if (this._strategies.has(name) && forceUpdate) { + this._strategies.get(name)?.dispose(); + this._strategies.delete(name); + } + const strategy = (scene) => { + let counter = 0; + let value = 0; + const afterRenderObserver = scene.onAfterRenderObservable.add(() => { + value = counter; + counter = 0; + }); + const stringObserver = this._customEventObservable.add((eventVal) => { + if (name !== eventVal.name) { + return; + } + if (eventVal.value !== undefined) { + counter = eventVal.value; + } + else { + counter++; + } + }); + return { + id: name, + getData: () => value, + dispose: () => { + scene.onAfterRenderObservable.remove(afterRenderObserver); + this._customEventObservable.remove(stringObserver); + }, + }; + }; + const event = { + name, + }; + this._eventRestoreSet.add(name); + this.addCollectionStrategies({ strategyCallback: strategy, category }); + return event; + } + /** + * Lets the perf collector handle an event, occurences or event value depending on if the event.value params is set. + * @param event the event to handle an occurence for + */ + sendEvent(event) { + this._customEventObservable.notifyObservers(event); + } + /** + * This event restores all custom string events if necessary. + */ + _restoreStringEvents() { + if (this._eventRestoreSet.size !== this._customEventObservable.observers.length) { + this._eventRestoreSet.forEach((event) => { + this.registerEvent(event, true); + }); + } + } + /** + * This method adds additional collection strategies for data collection purposes. + * @param strategyCallbacks the list of data to collect with callbacks. + */ + addCollectionStrategies(...strategyCallbacks) { + // eslint-disable-next-line prefer-const + for (let { strategyCallback, category, hidden } of strategyCallbacks) { + const strategy = strategyCallback(this._scene); + if (this._strategies.has(strategy.id)) { + strategy.dispose(); + continue; + } + this.datasets.ids.push(strategy.id); + if (category) { + category = category.replace(new RegExp(ExportedDataSeparator, "g"), ""); + } + this._datasetMeta.set(strategy.id, { + color: this._getHexColorFromId(strategy.id), + category, + hidden, + }); + this._strategies.set(strategy.id, strategy); + } + this.metadataObservable.notifyObservers(this._datasetMeta); + } + /** + * Gets a 6 character hexcode representing the colour from a passed in string. + * @param id the string to get a hex code for. + * @returns a hexcode hashed from the id. + */ + _getHexColorFromId(id) { + // this first bit is just a known way of hashing a string. + let hash = 0; + for (let i = 0; i < id.length; i++) { + // (hash << 5) - hash is the same as hash * 31 + hash = id.charCodeAt(i) + ((hash << 5) - hash); + } + // then we build the string octet by octet. + let hex = "#"; + for (let i = 0; i < NumberOfBitsInHexcode; i += 8) { + const octet = (hash >> i) & 0xff; + const toStr = HexPadding + octet.toString(16); + hex += toStr.substring(toStr.length - 2); + } + return hex; + } + /** + * Collects and then sends the latest slice to any observers by using the appropriate strategy when the user wants. + * The slice will be of the form [timestamp, numberOfPoints, value1, value2...] + * This method does not add onto the collected data accessible via the datasets variable. + */ + getCurrentSlice() { + const timestamp = PrecisionDate.Now - this._startingTimestamp; + const numPoints = this.datasets.ids.length; + const slice = [timestamp, numPoints]; + // add the values inside the slice. + this.datasets.ids.forEach((id) => { + const strategy = this._strategies.get(id); + if (!strategy) { + return; + } + if (this.datasetObservable.hasObservers()) { + slice.push(strategy.getData()); + } + }); + if (this.datasetObservable.hasObservers()) { + this.datasetObservable.notifyObservers(slice); + } + } + /** + * Updates a property for a dataset's metadata with the value provided. + * @param id the id of the dataset which needs its metadata updated. + * @param prop the property to update. + * @param value the value to update the property with. + */ + updateMetadata(id, prop, value) { + const meta = this._datasetMeta.get(id); + if (!meta) { + return; + } + meta[prop] = value; + this.metadataObservable.notifyObservers(this._datasetMeta); + } + /** + * Completely clear, data, ids, and strategies saved to this performance collector. + * @param preserveStringEventsRestore if it should preserve the string events, by default will clear string events registered when called. + */ + clear(preserveStringEventsRestore) { + this.datasets.data = new DynamicFloat32Array(InitialArraySize); + this.datasets.ids.length = 0; + this.datasets.startingIndices = new DynamicFloat32Array(InitialArraySize); + this._datasetMeta.clear(); + this._strategies.forEach((strategy) => strategy.dispose()); + this._strategies.clear(); + if (!preserveStringEventsRestore) { + this._eventRestoreSet.clear(); + } + this._hasLoadedData = false; + } + /** + * Accessor which lets the caller know if the performance collector has data loaded from a file or not! + * Call clear() to reset this value. + * @returns true if the data is loaded from a file, false otherwise. + */ + get hasLoadedData() { + return this._hasLoadedData; + } + /** + * Given a string containing file data, this function parses the file data into the datasets object. + * It returns a boolean to indicate if this object was successfully loaded with the data. + * @param data string content representing the file data. + * @param keepDatasetMeta if it should use reuse the existing dataset metadata + * @returns true if the data was successfully loaded, false otherwise. + */ + loadFromFileData(data, keepDatasetMeta) { + const lines = data + .replace(CarriageReturnRegex, "") + .split("\n") + .map((line) => line.split(",").filter((s) => s.length > 0)) + .filter((line) => line.length > 0); + const timestampIndex = 0; + const numPointsIndex = PerformanceViewerCollector.NumberOfPointsOffset; + if (lines.length < 2) { + return false; + } + const parsedDatasets = { + ids: [], + data: new DynamicFloat32Array(InitialArraySize), + startingIndices: new DynamicFloat32Array(InitialArraySize), + }; + // parse first line separately to populate ids! + const [firstLine, ...dataLines] = lines; + // make sure we have the correct beginning headers + if (firstLine.length < 2 || firstLine[timestampIndex] !== TimestampColHeader || firstLine[numPointsIndex] !== NumPointsColHeader) { + return false; + } + const idCategoryMap = new Map(); + // populate the ids. + for (let i = PerformanceViewerCollector.SliceDataOffset; i < firstLine.length; i++) { + const [id, category] = firstLine[i].split(ExportedDataSeparator); + parsedDatasets.ids.push(id); + idCategoryMap.set(id, category); + } + let startingIndex = 0; + for (const line of dataLines) { + if (line.length < 2) { + return false; + } + const timestamp = parseFloat(line[timestampIndex]); + const numPoints = parseInt(line[numPointsIndex]); + if (isNaN(numPoints) || isNaN(timestamp)) { + return false; + } + parsedDatasets.data.push(timestamp); + parsedDatasets.data.push(numPoints); + if (numPoints + PerformanceViewerCollector.SliceDataOffset !== line.length) { + return false; + } + for (let i = PerformanceViewerCollector.SliceDataOffset; i < line.length; i++) { + const val = parseFloat(line[i]); + if (isNaN(val)) { + return false; + } + parsedDatasets.data.push(val); + } + parsedDatasets.startingIndices.push(startingIndex); + startingIndex += line.length; + } + this.datasets.ids = parsedDatasets.ids; + this.datasets.data = parsedDatasets.data; + this.datasets.startingIndices = parsedDatasets.startingIndices; + if (!keepDatasetMeta) { + this._datasetMeta.clear(); + } + this._strategies.forEach((strategy) => strategy.dispose()); + this._strategies.clear(); + // populate metadata. + if (!keepDatasetMeta) { + for (const id of this.datasets.ids) { + const category = idCategoryMap.get(id); + this._datasetMeta.set(id, { category, color: this._getHexColorFromId(id) }); + } + } + this.metadataObservable.notifyObservers(this._datasetMeta); + this._hasLoadedData = true; + return true; + } + /** + * Exports the datasets inside of the collector to a csv. + */ + exportDataToCsv() { + let csvContent = ""; + // create the header line. + csvContent += `${TimestampColHeader},${NumPointsColHeader}`; + for (let i = 0; i < this.datasets.ids.length; i++) { + csvContent += `,${this.datasets.ids[i]}`; + if (this._datasetMeta) { + const meta = this._datasetMeta.get(this.datasets.ids[i]); + if (meta?.category) { + csvContent += `${ExportedDataSeparator}${meta.category}`; + } + } + } + csvContent += "\n"; + // create the data lines + for (let i = 0; i < this.datasets.startingIndices.itemLength; i++) { + const startingIndex = this.datasets.startingIndices.at(i); + const timestamp = this.datasets.data.at(startingIndex); + const numPoints = this.datasets.data.at(startingIndex + PerformanceViewerCollector.NumberOfPointsOffset); + csvContent += `${timestamp},${numPoints}`; + for (let offset = 0; offset < numPoints; offset++) { + csvContent += `,${this.datasets.data.at(startingIndex + PerformanceViewerCollector.SliceDataOffset + offset)}`; + } + // add extra commas. + for (let diff = 0; diff < this.datasets.ids.length - numPoints; diff++) { + csvContent += ","; + } + csvContent += "\n"; + } + const fileName = `${new Date().toISOString()}-perfdata.csv`; + Tools.Download(new Blob([csvContent], { type: "text/csv" }), fileName); + } + /** + * Starts the realtime collection of data. + * @param shouldPreserve optional boolean param, if set will preserve the dataset between calls of start. + */ + start(shouldPreserve) { + if (!shouldPreserve) { + this.datasets.data = new DynamicFloat32Array(InitialArraySize); + this.datasets.startingIndices = new DynamicFloat32Array(InitialArraySize); + this._startingTimestamp = PrecisionDate.Now; + } + else if (this._startingTimestamp === undefined) { + this._startingTimestamp = PrecisionDate.Now; + } + this._scene.onAfterRenderObservable.add(this._collectDataAtFrame); + this._restoreStringEvents(); + this._isStarted = true; + } + /** + * Stops the collection of data. + */ + stop() { + this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame); + this._isStarted = false; + } + /** + * Returns if the perf collector has been started or not. + */ + get isStarted() { + return this._isStarted; + } + /** + * Disposes of the object + */ + dispose() { + this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame); + this._datasetMeta.clear(); + this._strategies.forEach((strategy) => { + strategy.dispose(); + }); + this.datasetObservable.clear(); + this.metadataObservable.clear(); + this._isStarted = false; + this.datasets = null; + } +} + +Scene.prototype.getPerfCollector = function () { + if (!this._perfCollector) { + this._perfCollector = new PerformanceViewerCollector(this); + } + return this._perfCollector; +}; + +function CreateObservableScheduler(observable) { + const coroutines = new Array(); + const onSteps = new Array(); + const onErrors = new Array(); + const observer = observable.add(() => { + const count = coroutines.length; + for (let i = 0; i < count; i++) { + inlineScheduler(coroutines.shift(), onSteps.shift(), onErrors.shift()); + } + }); + const scheduler = (coroutine, onStep, onError) => { + coroutines.push(coroutine); + onSteps.push(onStep); + onErrors.push(onError); + }; + return { + scheduler: scheduler, + dispose: () => { + observable.remove(observer); + }, + }; +} +Observable.prototype.runCoroutineAsync = function (coroutine) { + if (!this._coroutineScheduler) { + const schedulerAndDispose = CreateObservableScheduler(this); + this._coroutineScheduler = schedulerAndDispose.scheduler; + this._coroutineSchedulerDispose = schedulerAndDispose.dispose; + } + return runCoroutineAsync(coroutine, this._coroutineScheduler); +}; +Observable.prototype.cancelAllCoroutines = function () { + if (this._coroutineSchedulerDispose) { + this._coroutineSchedulerDispose(); + } + this._coroutineScheduler = undefined; + this._coroutineSchedulerDispose = undefined; +}; + +// Do not edit. +const name$3j = "equirectangularPanoramaPixelShader"; +const shader$3i = `#ifdef GL_ES +precision highp float; +#endif +#define M_PI 3.1415926535897932384626433832795 +varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3( +- sin( longitude )*sin( latitude ), +cos( latitude ), +- cos( longitude )*sin( latitude ) +);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3j]) { + ShaderStore.ShadersStore[name$3j] = shader$3i; +} + +// Do not edit. +const name$3i = "rgbdDecodePixelShader"; +const shader$3h = `varying vec2 vUV;uniform sampler2D textureSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3i]) { + ShaderStore.ShadersStore[name$3i] = shader$3h; +} + +const rgbdDecode_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3h = "rgbdEncodePixelShader"; +const shader$3g = `varying vec2 vUV;uniform sampler2D textureSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3h]) { + ShaderStore.ShadersStore[name$3h] = shader$3g; +} + +const rgbdEncode_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3g = "rgbdDecodePixelShader"; +const shader$3f = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(fromRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV)),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3g]) { + ShaderStore.ShadersStoreWGSL[name$3g] = shader$3f; +} + +const rgbdDecode_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3f = "rgbdEncodePixelShader"; +const shader$3e = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=toRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3f]) { + ShaderStore.ShadersStoreWGSL[name$3f] = shader$3e; +} + +const rgbdEncode_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3e = "copyTextureToTexturePixelShader"; +const shader$3d = `uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; +#include +void main(void) +{vec4 color=texture2D(textureSampler,vUV); +#ifdef DEPTH_TEXTURE +gl_FragDepth=color.r; +#else +if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} +gl_FragColor=color; +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3e]) { + ShaderStore.ShadersStore[name$3e] = shader$3d; +} + +const copyTextureToTexture_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3d = "copyTextureToTexturePixelShader"; +const shader$3c = `uniform conversion: f32;var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f; +#include +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV); +#ifdef DEPTH_TEXTURE +fragmentOutputs.fragDepth=color.r; +#else +if (uniforms.conversion==1.) {color=toLinearSpaceVec4(color);} else if (uniforms.conversion==2.) {color=toGammaSpace(color);} +fragmentOutputs.color=color; +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3d]) { + ShaderStore.ShadersStoreWGSL[name$3d] = shader$3c; +} + +const copyTextureToTexture_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Sets the default offline provider to Babylon.js +AbstractEngine.OfflineProviderFactory = (urlToScene, callbackManifestChecked, disableManifestCheck = false) => { + return new Database(urlToScene, callbackManifestChecked, disableManifestCheck); +}; +/** + * Class used to enable access to IndexedDB + * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeCached + */ +class Database { + /** + * Gets a boolean indicating if scene must be saved in the database + */ + get enableSceneOffline() { + return this._enableSceneOffline; + } + /** + * Gets a boolean indicating if textures must be saved in the database + */ + get enableTexturesOffline() { + return this._enableTexturesOffline; + } + /** + * Creates a new Database + * @param urlToScene defines the url to load the scene + * @param callbackManifestChecked defines the callback to use when manifest is checked + * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date) + */ + constructor(urlToScene, callbackManifestChecked, disableManifestCheck = false) { + // Handling various flavors of prefixed version of IndexedDB + this._idbFactory = (typeof indexedDB !== "undefined" ? indexedDB : undefined); + this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene); + this._db = null; + this._enableSceneOffline = false; + this._enableTexturesOffline = false; + this._manifestVersionFound = 0; + this._mustUpdateRessources = false; + this._hasReachedQuota = false; + if (!Database.IDBStorageEnabled) { + callbackManifestChecked(true); + } + else { + if (disableManifestCheck) { + this._enableSceneOffline = true; + this._enableTexturesOffline = true; + this._manifestVersionFound = 1; + Tools.SetImmediate(() => { + callbackManifestChecked(true); + }); + } + else { + this._checkManifestFile(callbackManifestChecked); + } + } + } + _checkManifestFile(callbackManifestChecked) { + const noManifestFile = () => { + this._enableSceneOffline = false; + this._enableTexturesOffline = false; + callbackManifestChecked(false); + }; + const createManifestURL = () => { + try { + // make sure we have a valid URL. + if (typeof URL === "function" && this._currentSceneUrl.indexOf("http") === 0) { + // we don't have the base url, so the URL string must have a protocol + const url = new URL(this._currentSceneUrl); + url.pathname += ".manifest"; + return url.toString(); + } + } + catch (e) { + // defensive - if this fails for any reason, fall back to the older method + } + return `${this._currentSceneUrl}.manifest`; + }; + let timeStampUsed = false; + let manifestURL = createManifestURL(); + const xhr = new WebRequest(); + if (navigator.onLine) { + // Adding a timestamp to by-pass browsers' cache + timeStampUsed = true; + manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now(); + } + xhr.open("GET", manifestURL); + xhr.addEventListener("load", () => { + if (xhr.status === 200 || Database._ValidateXHRData(xhr, 1)) { + try { + const manifestFile = JSON.parse(xhr.response); + this._enableSceneOffline = manifestFile.enableSceneOffline; + this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database._IsUASupportingBlobStorage; + if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) { + this._manifestVersionFound = manifestFile.version; + } + callbackManifestChecked(true); + } + catch (ex) { + noManifestFile(); + } + } + else { + noManifestFile(); + } + }, false); + xhr.addEventListener("error", () => { + if (timeStampUsed) { + timeStampUsed = false; + // Let's retry without the timeStamp + // It could fail when coupled with HTML5 Offline API + const retryManifestURL = createManifestURL(); + xhr.open("GET", retryManifestURL); + xhr.send(); + } + else { + noManifestFile(); + } + }, false); + try { + xhr.send(); + } + catch (ex) { + Logger.Error("Error on XHR send request."); + callbackManifestChecked(false); + } + } + /** + * Open the database and make it available + * @param successCallback defines the callback to call on success + * @param errorCallback defines the callback to call on error + */ + open(successCallback, errorCallback) { + const handleError = () => { + this._isSupported = false; + if (errorCallback) { + errorCallback(); + } + }; + if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) { + // Your browser doesn't support IndexedDB + this._isSupported = false; + if (errorCallback) { + errorCallback(); + } + } + else { + // If the DB hasn't been opened or created yet + if (!this._db) { + this._hasReachedQuota = false; + this._isSupported = true; + const request = this._idbFactory.open("babylonjs", 1); + // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB + request.onerror = () => { + handleError(); + }; + // executes when a version change transaction cannot complete due to other active transactions + request.onblocked = () => { + Logger.Error("IDB request blocked. Please reload the page."); + handleError(); + }; + // DB has been opened successfully + request.onsuccess = () => { + this._db = request.result; + successCallback(); + }; + // Initialization of the DB. Creating Scenes & Textures stores + request.onupgradeneeded = (event) => { + this._db = event.target.result; + if (this._db) { + try { + this._db.createObjectStore("scenes", { keyPath: "sceneUrl" }); + this._db.createObjectStore("versions", { keyPath: "sceneUrl" }); + this._db.createObjectStore("textures", { keyPath: "textureUrl" }); + } + catch (ex) { + Logger.Error("Error while creating object stores. Exception: " + ex.message); + handleError(); + } + } + }; + } + // DB has already been created and opened + else { + if (successCallback) { + successCallback(); + } + } + } + } + /** + * Loads an image from the database + * @param url defines the url to load from + * @param image defines the target DOM image + */ + loadImage(url, image) { + const completeURL = Database._ReturnFullUrlLocation(url); + const saveAndLoadImage = () => { + if (!this._hasReachedQuota && this._db !== null) { + // the texture is not yet in the DB, let's try to save it + this._saveImageIntoDBAsync(completeURL, image); + } + // If the texture is not in the DB and we've reached the DB quota limit + // let's load it directly from the web + else { + image.src = url; + } + }; + if (!this._mustUpdateRessources) { + this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage); + } + // First time we're download the images or update requested in the manifest file by a version change + else { + saveAndLoadImage(); + } + } + _loadImageFromDBAsync(url, image, notInDBCallback) { + if (this._isSupported && this._db !== null) { + let texture; + const transaction = this._db.transaction(["textures"]); + transaction.onabort = () => { + image.src = url; + }; + transaction.oncomplete = () => { + let blobTextureURL; + if (texture && typeof URL === "function") { + blobTextureURL = URL.createObjectURL(texture.data); + image.onerror = () => { + Logger.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url); + image.src = url; + }; + image.src = blobTextureURL; + } + else { + notInDBCallback(); + } + }; + const getRequest = transaction.objectStore("textures").get(url); + getRequest.onsuccess = (event) => { + texture = event.target.result; + }; + getRequest.onerror = () => { + Logger.Error("Error loading texture " + url + " from DB."); + image.src = url; + }; + } + else { + Logger.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."); + image.src = url; + } + } + _saveImageIntoDBAsync(url, image) { + let blob; + if (this._isSupported) { + // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on + const generateBlobUrl = () => { + let blobTextureURL; + if (blob && typeof URL === "function") { + try { + blobTextureURL = URL.createObjectURL(blob); + } + catch (ex) { + // Chrome is raising a type error if we're setting the oneTimeOnly parameter + blobTextureURL = URL.createObjectURL(blob); + } + } + if (blobTextureURL) { + image.src = blobTextureURL; + } + }; + if (Database._IsUASupportingBlobStorage) { + // Create XHR + const xhr = new WebRequest(); + xhr.open("GET", url); + xhr.responseType = "blob"; + xhr.addEventListener("load", () => { + if (xhr.status === 200 && this._db) { + // Blob as response + blob = xhr.response; + const transaction = this._db.transaction(["textures"], "readwrite"); + // the transaction could abort because of a QuotaExceededError error + transaction.onabort = (event) => { + try { + //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3 + const srcElement = event.target; + const error = srcElement.error; + if (error && error.name === "QuotaExceededError") { + this._hasReachedQuota = true; + } + } + catch (ex) { } + generateBlobUrl(); + }; + transaction.oncomplete = () => { + generateBlobUrl(); + }; + const newTexture = { textureUrl: url, data: blob }; + try { + // Put the blob into the dabase + const addRequest = transaction.objectStore("textures").put(newTexture); + addRequest.onsuccess = () => { }; + addRequest.onerror = () => { + generateBlobUrl(); + }; + } + catch (ex) { + // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB + if (ex.code === 25) { + Database._IsUASupportingBlobStorage = false; + this._enableTexturesOffline = false; + } + image.src = url; + } + } + else { + image.src = url; + } + }, false); + xhr.addEventListener("error", () => { + Logger.Error("Error in XHR request in BABYLON.Database."); + image.src = url; + }, false); + xhr.send(); + } + else { + image.src = url; + } + } + else { + Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."); + image.src = url; + } + } + _checkVersionFromDB(url, versionLoaded) { + const updateVersion = () => { + // the version is not yet in the DB or we need to update it + this._saveVersionIntoDBAsync(url, versionLoaded); + }; + this._loadVersionFromDBAsync(url, versionLoaded, updateVersion); + } + _loadVersionFromDBAsync(url, callback, updateInDBCallback) { + if (this._isSupported && this._db) { + let version; + try { + const transaction = this._db.transaction(["versions"]); + transaction.oncomplete = () => { + if (version) { + // If the version in the JSON file is different from the version in DB + if (this._manifestVersionFound !== version.data) { + this._mustUpdateRessources = true; + updateInDBCallback(); + } + else { + callback(version.data); + } + } + // version was not found in DB + else { + this._mustUpdateRessources = true; + updateInDBCallback(); + } + }; + transaction.onabort = () => { + callback(-1); + }; + const getRequest = transaction.objectStore("versions").get(url); + getRequest.onsuccess = (event) => { + version = event.target.result; + }; + getRequest.onerror = () => { + Logger.Error("Error loading version for scene " + url + " from DB."); + callback(-1); + }; + } + catch (ex) { + Logger.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message); + callback(-1); + } + } + else { + Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."); + callback(-1); + } + } + _saveVersionIntoDBAsync(url, callback) { + if (this._isSupported && !this._hasReachedQuota && this._db) { + try { + // Open a transaction to the database + const transaction = this._db.transaction(["versions"], "readwrite"); + // the transaction could abort because of a QuotaExceededError error + transaction.onabort = (event) => { + try { + //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3 + const error = event.target["error"]; + if (error && error.name === "QuotaExceededError") { + this._hasReachedQuota = true; + } + } + catch (ex) { } + callback(-1); + }; + transaction.oncomplete = () => { + callback(this._manifestVersionFound); + }; + const newVersion = { sceneUrl: url, data: this._manifestVersionFound }; + // Put the scene into the database + const addRequest = transaction.objectStore("versions").put(newVersion); + addRequest.onsuccess = () => { }; + addRequest.onerror = () => { + Logger.Error("Error in DB add version request in BABYLON.Database."); + }; + } + catch (ex) { + Logger.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message); + callback(-1); + } + } + else { + callback(-1); + } + } + /** + * Loads a file from database + * @param url defines the URL to load from + * @param sceneLoaded defines a callback to call on success + * @param progressCallBack defines a callback to call when progress changed + * @param errorCallback defines a callback to call on error + * @param useArrayBuffer defines a boolean to use array buffer instead of text string + */ + loadFile(url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) { + const completeUrl = Database._ReturnFullUrlLocation(url); + const saveAndLoadFile = () => { + // the scene is not yet in the DB, let's try to save it + this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback); + }; + this._checkVersionFromDB(completeUrl, (version) => { + if (version !== -1) { + if (!this._mustUpdateRessources) { + this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile, progressCallBack); + } + else { + this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback); + } + } + else { + if (errorCallback) { + errorCallback(); + } + } + }); + } + _loadFileAsync(url, callback, notInDBCallback, progressCallBack) { + if (this._isSupported && this._db) { + let targetStore; + if (url.indexOf(".babylon") !== -1) { + targetStore = "scenes"; + } + else { + targetStore = "textures"; + } + let file; + const transaction = this._db.transaction([targetStore]); + transaction.oncomplete = () => { + if (file) { + if (progressCallBack) { + const numberToLoad = file.data?.byteLength || 0; + progressCallBack({ + total: numberToLoad, + loaded: numberToLoad, + lengthComputable: true, + }); + } + callback(file.data); + } + // file was not found in DB + else { + notInDBCallback(); + } + }; + transaction.onabort = () => { + notInDBCallback(); + }; + const getRequest = transaction.objectStore(targetStore).get(url); + getRequest.onsuccess = (event) => { + file = event.target.result; + }; + getRequest.onerror = () => { + Logger.Error("Error loading file " + url + " from DB."); + notInDBCallback(); + }; + } + else { + Logger.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."); + callback(); + } + } + _saveFileAsync(url, callback, progressCallback, useArrayBuffer, errorCallback) { + if (this._isSupported) { + let targetStore; + if (url.indexOf(".babylon") !== -1) { + targetStore = "scenes"; + } + else { + targetStore = "textures"; + } + // Create XHR + const xhr = new WebRequest(); + let fileData; + xhr.open("GET", url + (url.match(/\?/) == null ? "?" : "&") + Date.now()); + if (useArrayBuffer) { + xhr.responseType = "arraybuffer"; + } + if (progressCallback) { + xhr.onprogress = progressCallback; + } + xhr.addEventListener("load", () => { + if (xhr.status === 200 || (xhr.status < 400 && Database._ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) { + // Blob as response + fileData = !useArrayBuffer ? xhr.responseText : xhr.response; + if (!this._hasReachedQuota && this._db) { + // Open a transaction to the database + const transaction = this._db.transaction([targetStore], "readwrite"); + // the transaction could abort because of a QuotaExceededError error + transaction.onabort = (event) => { + try { + //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3 + const error = event.target["error"]; + if (error && error.name === "QuotaExceededError") { + this._hasReachedQuota = true; + } + } + catch (ex) { } + callback(fileData); + }; + transaction.oncomplete = () => { + callback(fileData); + }; + let newFile; + if (targetStore === "scenes") { + newFile = { sceneUrl: url, data: fileData, version: this._manifestVersionFound }; + } + else { + newFile = { textureUrl: url, data: fileData }; + } + try { + // Put the scene into the database + const addRequest = transaction.objectStore(targetStore).put(newFile); + addRequest.onsuccess = () => { }; + addRequest.onerror = () => { + Logger.Error("Error in DB add file request in BABYLON.Database."); + }; + } + catch (ex) { + callback(fileData); + } + } + else { + callback(fileData); + } + } + else { + if (xhr.status >= 400 && errorCallback) { + errorCallback(xhr); + } + else { + callback(); + } + } + }, false); + xhr.addEventListener("error", () => { + Logger.Error("error on XHR request."); + errorCallback && errorCallback(); + }, false); + xhr.send(); + } + else { + Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."); + errorCallback && errorCallback(); + } + } + /** + * Validates if xhr data is correct + * @param xhr defines the request to validate + * @param dataType defines the expected data type + * @returns true if data is correct + */ + static _ValidateXHRData(xhr, dataType = 7) { + // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all + try { + if (dataType & 1) { + if (xhr.responseText && xhr.responseText.length > 0) { + return true; + } + else if (dataType === 1) { + return false; + } + } + if (dataType & 2) { + // Check header width and height since there is no "TGA" magic number + const tgaHeader = GetTGAHeader(xhr.response); + if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) { + return true; + } + else if (dataType === 2) { + return false; + } + } + if (dataType & 4) { + // Check for the "DDS" magic number + const ddsHeader = new Uint8Array(xhr.response, 0, 3); + if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) { + return true; + } + else { + return false; + } + } + } + catch (e) { + // Global protection + } + return false; + } +} +/** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */ +Database._IsUASupportingBlobStorage = true; +/** + * Gets a boolean indicating if Database storage is enabled (off by default) + */ +Database.IDBStorageEnabled = false; +Database._ParseURL = (url) => { + const a = document.createElement("a"); + a.href = url; + const urlWithoutHash = url.substring(0, url.lastIndexOf("#")); + const fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length); + const absLocation = url.substring(0, url.indexOf(fileName, 0)); + return absLocation; +}; +Database._ReturnFullUrlLocation = (url) => { + if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1 && typeof window !== "undefined") { + return Database._ParseURL(window.location.href) + url; + } + else { + return url; + } +}; + +/** @internal */ +class UniformBufferEffectCommonAccessor { + _isUbo(uboOrEffect) { + return uboOrEffect.addUniform !== undefined; + } + constructor(uboOrEffect) { + if (this._isUbo(uboOrEffect)) { + this.setMatrix3x3 = uboOrEffect.updateMatrix3x3.bind(uboOrEffect); + this.setMatrix2x2 = uboOrEffect.updateMatrix2x2.bind(uboOrEffect); + this.setFloat = uboOrEffect.updateFloat.bind(uboOrEffect); + this.setFloat2 = uboOrEffect.updateFloat2.bind(uboOrEffect); + this.setFloat3 = uboOrEffect.updateFloat3.bind(uboOrEffect); + this.setFloat4 = uboOrEffect.updateFloat4.bind(uboOrEffect); + this.setFloatArray = uboOrEffect.updateFloatArray.bind(uboOrEffect); + this.setArray = uboOrEffect.updateArray.bind(uboOrEffect); + this.setIntArray = uboOrEffect.updateIntArray.bind(uboOrEffect); + this.setMatrix = uboOrEffect.updateMatrix.bind(uboOrEffect); + this.setMatrices = uboOrEffect.updateMatrices.bind(uboOrEffect); + this.setVector3 = uboOrEffect.updateVector3.bind(uboOrEffect); + this.setVector4 = uboOrEffect.updateVector4.bind(uboOrEffect); + this.setColor3 = uboOrEffect.updateColor3.bind(uboOrEffect); + this.setColor4 = uboOrEffect.updateColor4.bind(uboOrEffect); + this.setDirectColor4 = uboOrEffect.updateDirectColor4.bind(uboOrEffect); + this.setInt = uboOrEffect.updateInt.bind(uboOrEffect); + this.setInt2 = uboOrEffect.updateInt2.bind(uboOrEffect); + this.setInt3 = uboOrEffect.updateInt3.bind(uboOrEffect); + this.setInt4 = uboOrEffect.updateInt4.bind(uboOrEffect); + } + else { + this.setMatrix3x3 = uboOrEffect.setMatrix3x3.bind(uboOrEffect); + this.setMatrix2x2 = uboOrEffect.setMatrix2x2.bind(uboOrEffect); + this.setFloat = uboOrEffect.setFloat.bind(uboOrEffect); + this.setFloat2 = uboOrEffect.setFloat2.bind(uboOrEffect); + this.setFloat3 = uboOrEffect.setFloat3.bind(uboOrEffect); + this.setFloat4 = uboOrEffect.setFloat4.bind(uboOrEffect); + this.setFloatArray = uboOrEffect.setFloatArray.bind(uboOrEffect); + this.setArray = uboOrEffect.setArray.bind(uboOrEffect); + this.setIntArray = uboOrEffect.setIntArray.bind(uboOrEffect); + this.setMatrix = uboOrEffect.setMatrix.bind(uboOrEffect); + this.setMatrices = uboOrEffect.setMatrices.bind(uboOrEffect); + this.setVector3 = uboOrEffect.setVector3.bind(uboOrEffect); + this.setVector4 = uboOrEffect.setVector4.bind(uboOrEffect); + this.setColor3 = uboOrEffect.setColor3.bind(uboOrEffect); + this.setColor4 = uboOrEffect.setColor4.bind(uboOrEffect); + this.setDirectColor4 = uboOrEffect.setDirectColor4.bind(uboOrEffect); + this.setInt = uboOrEffect.setInt.bind(uboOrEffect); + this.setInt2 = uboOrEffect.setInt2.bind(uboOrEffect); + this.setInt3 = uboOrEffect.setInt3.bind(uboOrEffect); + this.setInt4 = uboOrEffect.setInt4.bind(uboOrEffect); + } + } +} + +// Do not edit. +const name$3c = "gpuUpdateParticlesPixelShader"; +const shader$3b = `#version 300 es +void main() {discard;} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3c]) { + ShaderStore.ShadersStore[name$3c] = shader$3b; +} + +// Do not edit. +const name$3b = "gpuUpdateParticlesVertexShader"; +const shader$3a = `#version 300 es +#define PI 3.14159 +uniform float currentCount;uniform float timeDelta;uniform float stopFactor; +#ifndef LOCAL +uniform mat4 emitterWM; +#endif +uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; +#ifndef COLORGRADIENTS +uniform vec4 color1;uniform vec4 color2; +#endif +uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; +#ifdef BOXEMITTER +uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; +#endif +#ifdef POINTEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#endif +#ifdef HEMISPHERICEMITTER +uniform float radius;uniform float radiusRange;uniform float directionRandomizer; +#endif +#ifdef SPHEREEMITTER +uniform float radius;uniform float radiusRange; +#ifdef DIRECTEDSPHEREEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +#ifdef CYLINDEREMITTER +uniform float radius;uniform float height;uniform float radiusRange; +#ifdef DIRECTEDCYLINDEREMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +#ifdef CONEEMITTER +uniform vec2 radius;uniform float coneAngle;uniform vec2 height; +#ifdef DIRECTEDCONEEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +in vec3 position; +#ifdef CUSTOMEMITTER +in vec3 initialPosition; +#endif +in float age;in float life;in vec4 seed;in vec3 size; +#ifndef COLORGRADIENTS +in vec4 color; +#endif +in vec3 direction; +#ifndef BILLBOARD +in vec3 initialDirection; +#endif +#ifdef ANGULARSPEEDGRADIENTS +in float angle; +#else +in vec2 angle; +#endif +#ifdef ANIMATESHEET +in float cellIndex; +#ifdef ANIMATESHEETRANDOMSTART +in float cellStartOffset; +#endif +#endif +#ifdef NOISE +in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; +#endif +out vec3 outPosition; +#ifdef CUSTOMEMITTER +out vec3 outInitialPosition; +#endif +out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; +#ifndef COLORGRADIENTS +out vec4 outColor; +#endif +out vec3 outDirection; +#ifndef BILLBOARD +out vec3 outInitialDirection; +#endif +#ifdef ANGULARSPEEDGRADIENTS +out float outAngle; +#else +out vec2 outAngle; +#endif +#ifdef ANIMATESHEET +out float outCellIndex; +#ifdef ANIMATESHEETRANDOMSTART +out float outCellStartOffset; +#endif +#endif +#ifdef NOISE +out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; +#endif +#ifdef SIZEGRADIENTS +uniform sampler2D sizeGradientSampler; +#endif +#ifdef ANGULARSPEEDGRADIENTS +uniform sampler2D angularSpeedGradientSampler; +#endif +#ifdef VELOCITYGRADIENTS +uniform sampler2D velocityGradientSampler; +#endif +#ifdef LIMITVELOCITYGRADIENTS +uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; +#endif +#ifdef DRAGGRADIENTS +uniform sampler2D dragGradientSampler; +#endif +#ifdef NOISE +uniform vec3 noiseStrength;uniform sampler2D noiseSampler; +#endif +#ifdef ANIMATESHEET +uniform vec4 cellInfos; +#endif +vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} +vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} +void main() {float newAge=age+timeDelta; +if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; +#ifdef SIZEGRADIENTS +outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; +#else +outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; +#endif +outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; +#ifndef COLORGRADIENTS +outColor=color1+(color2-color1)*randoms.b; +#endif +#ifndef ANGULARSPEEDGRADIENTS +outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; +#else +outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; +#endif +#ifdef POINTEMITTER +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; +#elif defined(BOXEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; +#elif defined(HEMISPHERICEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; +#elif defined(SPHEREEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); +#ifdef DIRECTEDSPHEREEMITTER +newDirection=normalize(direction1+(direction2-direction1)*randoms3); +#else +newDirection=normalize(newPosition+directionRandomizer*randoms3); +#endif +#elif defined(CYLINDEREMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); +#ifdef DIRECTEDCYLINDEREMITTER +newDirection=direction1+(direction2-direction1)*randoms3; +#else +angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); +#endif +#elif defined(CONEEMITTER) +vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; +#ifdef CONEEMITTERSPAWNPOINT +float h=0.0001; +#else +float h=randoms2.y*height.y;h=1.-h*h; +#endif +float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); +vec3 randoms3=getRandomVec3(seed.z); +#ifdef DIRECTEDCONEEMITTER +newDirection=direction1+(direction2-direction1)*randoms3; +#else +if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {newDirection=normalize(newPosition+directionRandomizer*randoms3); } +#endif +#elif defined(CUSTOMEMITTER) +newPosition=initialPosition;outInitialPosition=initialPosition; +#else +newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); +#endif +float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; +#ifdef LOCAL +outPosition=newPosition; +#else +outPosition=(emitterWM*vec4(newPosition,1.)).xyz; +#endif +#ifdef CUSTOMEMITTER +outDirection=direction; +#ifndef BILLBOARD +outInitialDirection=direction; +#endif +#else +#ifdef LOCAL +vec3 initial=newDirection; +#else +vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; +#endif +outDirection=initial*power; +#ifndef BILLBOARD +outInitialDirection=initial; +#endif +#endif +#ifdef ANIMATESHEET +outCellIndex=cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +outCellStartOffset=randoms.a*outLife; +#endif +#endif +#ifdef NOISE +outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; +#endif +} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; +#ifdef VELOCITYGRADIENTS +directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; +#endif +#ifdef DRAGGRADIENTS +directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; +#endif +#if defined(CUSTOMEMITTER) +outPosition=position+(direction-position)*ageGradient; +outInitialPosition=initialPosition; +#else +outPosition=position+direction*directionScale; +#endif +outLife=life;outSeed=seed; +#ifndef COLORGRADIENTS +outColor=color; +#endif +#ifdef SIZEGRADIENTS +outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; +#else +outSize=size; +#endif +#ifndef BILLBOARD +outInitialDirection=initialDirection; +#endif +#ifdef CUSTOMEMITTER +outDirection=direction; +#else +vec3 updatedDirection=direction+gravity*timeDelta; +#ifdef LIMITVELOCITYGRADIENTS +float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} +#endif +outDirection=updatedDirection; +#ifdef NOISE +float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; +#endif +#endif +#ifdef ANGULARSPEEDGRADIENTS +float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; +#else +outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); +#endif +#ifdef ANIMATESHEET +float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; +#else +float cellStartOffset=0.; +#endif +float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} +else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} +outCellIndex=float(int(cellInfos.x+ratio*dist)); +#endif +}}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$3b]) { + ShaderStore.ShadersStore[name$3b] = shader$3a; +} + +/** @internal */ +class WebGL2ParticleSystem { + constructor(parent, engine) { + this._renderVAO = []; + this._updateVAO = []; + this.alignDataInBuffer = false; + this._parent = parent; + this._engine = engine; + this._updateEffectOptions = { + attributes: [ + "position", + "initialPosition", + "age", + "life", + "seed", + "size", + "color", + "direction", + "initialDirection", + "angle", + "cellIndex", + "cellStartOffset", + "noiseCoordinates1", + "noiseCoordinates2", + ], + uniformsNames: [ + "currentCount", + "timeDelta", + "emitterWM", + "lifeTime", + "color1", + "color2", + "sizeRange", + "scaleRange", + "gravity", + "emitPower", + "direction1", + "direction2", + "minEmitBox", + "maxEmitBox", + "radius", + "directionRandomizer", + "height", + "coneAngle", + "stopFactor", + "angleRange", + "radiusRange", + "cellInfos", + "noiseStrength", + "limitVelocityDamping", + ], + uniformBuffersNames: [], + samplers: [ + "randomSampler", + "randomSampler2", + "sizeGradientSampler", + "angularSpeedGradientSampler", + "velocityGradientSampler", + "limitVelocityGradientSampler", + "noiseSampler", + "dragGradientSampler", + ], + defines: "", + fallbacks: null, + onCompiled: null, + onError: null, + indexParameters: null, + maxSimultaneousLights: 0, + transformFeedbackVaryings: [], + }; + } + contextLost() { + this._updateEffect = undefined; + this._renderVAO.length = 0; + this._updateVAO.length = 0; + } + isUpdateBufferCreated() { + return !!this._updateEffect; + } + isUpdateBufferReady() { + return this._updateEffect?.isReady() ?? false; + } + createUpdateBuffer(defines) { + this._updateEffectOptions.transformFeedbackVaryings = ["outPosition"]; + this._updateEffectOptions.transformFeedbackVaryings.push("outAge"); + this._updateEffectOptions.transformFeedbackVaryings.push("outSize"); + this._updateEffectOptions.transformFeedbackVaryings.push("outLife"); + this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"); + this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"); + if (this._parent.particleEmitterType instanceof CustomParticleEmitter) { + this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"); + } + if (!this._parent._colorGradientsTexture) { + this._updateEffectOptions.transformFeedbackVaryings.push("outColor"); + } + if (!this._parent._isBillboardBased) { + this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"); + } + if (this._parent.noiseTexture) { + this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"); + this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2"); + } + this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"); + if (this._parent.isAnimationSheetEnabled) { + this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"); + if (this._parent.spriteRandomStartCell) { + this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset"); + } + } + this._updateEffectOptions.defines = defines; + this._updateEffect = this._engine.createEffect("gpuUpdateParticles", this._updateEffectOptions, this._engine); + return new UniformBufferEffectCommonAccessor(this._updateEffect); + } + createVertexBuffers(updateBuffer, renderVertexBuffers) { + this._updateVAO.push(this._createUpdateVAO(updateBuffer)); + this._renderVAO.push(this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._parent._getWrapper(this._parent.blendMode).effect)); + this._engine.bindArrayBuffer(null); + this._renderVertexBuffers = renderVertexBuffers; + } + createParticleBuffer(data) { + return data; + } + bindDrawBuffers(index, effect, indexBuffer) { + if (indexBuffer) { + this._engine.bindBuffers(this._renderVertexBuffers, indexBuffer, effect); + } + else { + this._engine.bindVertexArrayObject(this._renderVAO[index], null); + } + } + preUpdateParticleBuffer() { + const engine = this._engine; + this._engine.enableEffect(this._updateEffect); + if (!engine.setState) { + throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported"); + } + } + updateParticleBuffer(index, targetBuffer, currentActiveCount) { + this._updateEffect.setTexture("randomSampler", this._parent._randomTexture); + this._updateEffect.setTexture("randomSampler2", this._parent._randomTexture2); + if (this._parent._sizeGradientsTexture) { + this._updateEffect.setTexture("sizeGradientSampler", this._parent._sizeGradientsTexture); + } + if (this._parent._angularSpeedGradientsTexture) { + this._updateEffect.setTexture("angularSpeedGradientSampler", this._parent._angularSpeedGradientsTexture); + } + if (this._parent._velocityGradientsTexture) { + this._updateEffect.setTexture("velocityGradientSampler", this._parent._velocityGradientsTexture); + } + if (this._parent._limitVelocityGradientsTexture) { + this._updateEffect.setTexture("limitVelocityGradientSampler", this._parent._limitVelocityGradientsTexture); + } + if (this._parent._dragGradientsTexture) { + this._updateEffect.setTexture("dragGradientSampler", this._parent._dragGradientsTexture); + } + if (this._parent.noiseTexture) { + this._updateEffect.setTexture("noiseSampler", this._parent.noiseTexture); + } + // Bind source VAO + this._engine.bindVertexArrayObject(this._updateVAO[index], null); + // Update + const engine = this._engine; + engine.bindTransformFeedbackBuffer(targetBuffer.getBuffer()); + engine.setRasterizerState(false); + engine.beginTransformFeedback(true); + engine.drawArraysType(3, 0, currentActiveCount); + engine.endTransformFeedback(); + engine.setRasterizerState(true); + engine.bindTransformFeedbackBuffer(null); + } + releaseBuffers() { } + releaseVertexBuffers() { + for (let index = 0; index < this._updateVAO.length; index++) { + this._engine.releaseVertexArrayObject(this._updateVAO[index]); + } + this._updateVAO.length = 0; + for (let index = 0; index < this._renderVAO.length; index++) { + this._engine.releaseVertexArrayObject(this._renderVAO[index]); + } + this._renderVAO.length = 0; + } + _createUpdateVAO(source) { + const updateVertexBuffers = {}; + updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3); + let offset = 3; + updateVertexBuffers["age"] = source.createVertexBuffer("age", offset, 1); + offset += 1; + updateVertexBuffers["size"] = source.createVertexBuffer("size", offset, 3); + offset += 3; + updateVertexBuffers["life"] = source.createVertexBuffer("life", offset, 1); + offset += 1; + updateVertexBuffers["seed"] = source.createVertexBuffer("seed", offset, 4); + offset += 4; + updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3); + offset += 3; + if (this._parent.particleEmitterType instanceof CustomParticleEmitter) { + updateVertexBuffers["initialPosition"] = source.createVertexBuffer("initialPosition", offset, 3); + offset += 3; + } + if (!this._parent._colorGradientsTexture) { + updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4); + offset += 4; + } + if (!this._parent._isBillboardBased) { + updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3); + offset += 3; + } + if (this._parent.noiseTexture) { + updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3); + offset += 3; + updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3); + offset += 3; + } + if (this._parent._angularSpeedGradientsTexture) { + updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1); + offset += 1; + } + else { + updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2); + offset += 2; + } + if (this._parent._isAnimationSheetEnabled) { + updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1); + offset += 1; + if (this._parent.spriteRandomStartCell) { + updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1); + offset += 1; + } + } + const vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect); + this._engine.bindArrayBuffer(null); + return vao; + } +} +RegisterClass("BABYLON.WebGL2ParticleSystem", WebGL2ParticleSystem); + +// Do not edit. +const name$3a = "gpuUpdateParticlesComputeShader"; +const shader$39 = `struct Particle {position : vec3, +age : f32, +size : vec3, +life : f32, +seed : vec4, +direction : vec3, +dummy0: f32, +#ifdef CUSTOMEMITTER +initialPosition : vec3, +dummy1: f32, +#endif +#ifndef COLORGRADIENTS +color : vec4, +#endif +#ifndef BILLBOARD +initialDirection : vec3, +dummy2: f32, +#endif +#ifdef NOISE +noiseCoordinates1 : vec3, +dummy3: f32, +noiseCoordinates2 : vec3, +dummy4: f32, +#endif +#ifdef ANGULARSPEEDGRADIENTS +angle : f32, +#else +angle : vec2, +#endif +#ifdef ANIMATESHEET +cellIndex : f32, +#ifdef ANIMATESHEETRANDOMSTART +cellStartOffset : f32, +#endif +#endif +};struct Particles {particles : array,};struct SimParams {currentCount : f32, +timeDelta : f32, +stopFactor : f32, +randomTextureSize: i32, +lifeTime : vec2, +emitPower : vec2, +#ifndef COLORGRADIENTS +color1 : vec4, +color2 : vec4, +#endif +sizeRange : vec2, +scaleRange : vec4, +angleRange : vec4, +gravity : vec3, +#ifdef LIMITVELOCITYGRADIENTS +limitVelocityDamping : f32, +#endif +#ifdef ANIMATESHEET +cellInfos : vec4, +#endif +#ifdef NOISE +noiseStrength : vec3, +#endif +#ifndef LOCAL +emitterWM : mat4x4, +#endif +#ifdef BOXEMITTER +direction1 : vec3, +direction2 : vec3, +minEmitBox : vec3, +maxEmitBox : vec3, +#endif +#ifdef CONEEMITTER +radius : vec2, +coneAngle : f32, +height : vec2, +#ifdef DIRECTEDCONEEMITTER +direction1 : vec3, +direction2 : vec3, +#else +directionRandomizer : f32, +#endif +#endif +#ifdef CYLINDEREMITTER +radius : f32, +height : f32, +radiusRange : f32, +#ifdef DIRECTEDCYLINDEREMITTER +direction1 : vec3, +direction2 : vec3, +#else +directionRandomizer : f32, +#endif +#endif +#ifdef HEMISPHERICEMITTER +radius : f32, +radiusRange : f32, +directionRandomizer : f32, +#endif +#ifdef POINTEMITTER +direction1 : vec3, +direction2 : vec3, +#endif +#ifdef SPHEREEMITTER +radius : f32, +radiusRange : f32, +#ifdef DIRECTEDSPHEREEMITTER +direction1 : vec3, +direction2 : vec3, +#else +directionRandomizer : f32, +#endif +#endif +};@binding(0) @group(0) var params : SimParams;@binding(1) @group(0) var particlesIn : Particles;@binding(2) @group(0) var particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d;@binding(4) @group(0) var randomTexture2 : texture_2d; +#ifdef SIZEGRADIENTS +@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d; +#endif +#ifdef ANGULARSPEEDGRADIENTS +@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d; +#endif +#ifdef VELOCITYGRADIENTS +@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d; +#endif +#ifdef LIMITVELOCITYGRADIENTS +@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d; +#endif +#ifdef DRAGGRADIENTS +@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d; +#endif +#ifdef NOISE +@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d; +#endif +fn getRandomVec3(offset : f32,vertexID : f32)->vec3 {return textureLoad(randomTexture2,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} +fn getRandomVec4(offset : f32,vertexID : f32)->vec4 {return textureLoad(randomTexture,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} +let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4=particlesIn.particles[index].seed;let direction : vec3=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3;var newDirection : vec3;let randoms : vec4=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; +#ifdef SIZEGRADIENTS +sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(0.,0.),0.).r; +#else +sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; +#endif +particlesOut.particles[index].size=vec3( +sizex, +params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, +params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); +#ifndef COLORGRADIENTS +particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; +#endif +#ifndef ANGULARSPEEDGRADIENTS +particlesOut.particles[index].angle=vec2( +params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, +params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); +#else +particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; +#endif +#if defined(POINTEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=vec3(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#elif defined(BOXEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#elif defined(HEMISPHERICEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); +#elif defined(SPHEREEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,randY,randZ); +#ifdef DIRECTEDSPHEREEMITTER +newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); +#else +newDirection=normalize(newPosition+params.directionRandomizer*randoms3); +#endif +#elif defined(CYLINDEREMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); +#ifdef DIRECTEDCYLINDEREMITTER +newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#else +angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); +#endif +#elif defined(CONEEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; +#ifdef CONEEMITTERSPAWNPOINT +let h : f32=0.0001; +#else +var h : f32=randoms2.y*params.height.y;h=1.-h*h; +#endif +var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3(randX,randY,randZ); +let randoms3 : vec3=getRandomVec3(seed.z,vertexID); +#ifdef DIRECTEDCONEEMITTER +newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#else +if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } +#endif +#elif defined(CUSTOMEMITTER) +newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; +#else +newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3(0.5,0.5,0.5)); +#endif +let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; +#ifdef LOCAL +particlesOut.particles[index].position=newPosition; +#else +particlesOut.particles[index].position=(params.emitterWM*vec4(newPosition,1.)).xyz; +#endif +#ifdef CUSTOMEMITTER +particlesOut.particles[index].direction=direction; +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=direction; +#endif +#else +#ifdef LOCAL +let initial : vec3=newDirection; +#else +let initial : vec3=(params.emitterWM*vec4(newDirection,0.)).xyz; +#endif +particlesOut.particles[index].direction=initial*power; +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=initial; +#endif +#endif +#ifdef ANIMATESHEET +particlesOut.particles[index].cellIndex=params.cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +particlesOut.particles[index].cellStartOffset=randoms.a*outLife; +#endif +#endif +#ifdef NOISE +particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; +#endif +} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; +#ifdef VELOCITYGRADIENTS +directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2(ageGradient,0.),0.).r; +#endif +#ifdef DRAGGRADIENTS +directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2(ageGradient,0.),0.).r); +#endif +let position : vec3=particlesIn.particles[index].position; +#if defined(CUSTOMEMITTER) +particlesOut.particles[index].position=position+(direction-position)*ageGradient; +particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; +#else +particlesOut.particles[index].position=position+direction*directionScale; +#endif +particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; +#ifndef COLORGRADIENTS +particlesOut.particles[index].color=particlesIn.particles[index].color; +#endif +#ifdef SIZEGRADIENTS +particlesOut.particles[index].size=vec3( +textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(ageGradient,0.),0.).r, +particlesIn.particles[index].size.yz); +#else +particlesOut.particles[index].size=particlesIn.particles[index].size; +#endif +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; +#endif +#ifdef CUSTOMEMITTER +particlesOut.particles[index].direction=direction; +#else +var updatedDirection : vec3=direction+params.gravity*timeDelta; +#ifdef LIMITVELOCITYGRADIENTS +let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} +#endif +particlesOut.particles[index].direction=updatedDirection; +#ifdef NOISE +let noiseCoordinates1 : vec3=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let force : vec3=vec3(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; +#endif +#endif +#ifdef ANGULARSPEEDGRADIENTS +let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; +#else +let angle : vec2=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2(angle.x+angle.y*timeDelta,angle.y); +#endif +#ifdef ANIMATESHEET +var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; +#else +let cellStartOffset : f32=0.; +#endif +var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} +else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} +particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); +#endif +}} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3a]) { + ShaderStore.ShadersStoreWGSL[name$3a] = shader$39; +} + +/** @internal */ +class ComputeShaderParticleSystem { + constructor(parent, engine) { + this._bufferComputeShader = []; + this._renderVertexBuffers = []; + this.alignDataInBuffer = true; + this._parent = parent; + this._engine = engine; + } + contextLost() { + this._updateComputeShader = undefined; + this._bufferComputeShader.length = 0; + this._renderVertexBuffers.length = 0; + } + isUpdateBufferCreated() { + return !!this._updateComputeShader; + } + isUpdateBufferReady() { + return this._updateComputeShader?.isReady() ?? false; + } + createUpdateBuffer(defines) { + const bindingsMapping = { + params: { group: 0, binding: 0 }, + particlesIn: { group: 0, binding: 1 }, + particlesOut: { group: 0, binding: 2 }, + randomTexture: { group: 0, binding: 3 }, + randomTexture2: { group: 0, binding: 4 }, + }; + if (this._parent._sizeGradientsTexture) { + bindingsMapping["sizeGradientTexture"] = { group: 1, binding: 1 }; + } + if (this._parent._angularSpeedGradientsTexture) { + bindingsMapping["angularSpeedGradientTexture"] = { group: 1, binding: 3 }; + } + if (this._parent._velocityGradientsTexture) { + bindingsMapping["velocityGradientTexture"] = { group: 1, binding: 5 }; + } + if (this._parent._limitVelocityGradientsTexture) { + bindingsMapping["limitVelocityGradientTexture"] = { group: 1, binding: 7 }; + } + if (this._parent._dragGradientsTexture) { + bindingsMapping["dragGradientTexture"] = { group: 1, binding: 9 }; + } + if (this._parent.noiseTexture) { + bindingsMapping["noiseTexture"] = { group: 1, binding: 11 }; + } + this._updateComputeShader = new ComputeShader("updateParticles", this._engine, "gpuUpdateParticles", { bindingsMapping, defines: defines.split("\n") }); + this._simParamsComputeShader?.dispose(); + this._simParamsComputeShader = new UniformBuffer(this._engine, undefined, undefined, "ComputeShaderParticleSystemUBO"); + this._simParamsComputeShader.addUniform("currentCount", 1); + this._simParamsComputeShader.addUniform("timeDelta", 1); + this._simParamsComputeShader.addUniform("stopFactor", 1); + this._simParamsComputeShader.addUniform("randomTextureSize", 1); + this._simParamsComputeShader.addUniform("lifeTime", 2); + this._simParamsComputeShader.addUniform("emitPower", 2); + if (!this._parent._colorGradientsTexture) { + this._simParamsComputeShader.addUniform("color1", 4); + this._simParamsComputeShader.addUniform("color2", 4); + } + this._simParamsComputeShader.addUniform("sizeRange", 2); + this._simParamsComputeShader.addUniform("scaleRange", 4); + this._simParamsComputeShader.addUniform("angleRange", 4); + this._simParamsComputeShader.addUniform("gravity", 3); + if (this._parent._limitVelocityGradientsTexture) { + this._simParamsComputeShader.addUniform("limitVelocityDamping", 1); + } + if (this._parent.isAnimationSheetEnabled) { + this._simParamsComputeShader.addUniform("cellInfos", 4); + } + if (this._parent.noiseTexture) { + this._simParamsComputeShader.addUniform("noiseStrength", 3); + } + if (!this._parent.isLocal) { + this._simParamsComputeShader.addUniform("emitterWM", 16); + } + if (this._parent.particleEmitterType) { + this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader); + } + this._updateComputeShader.setUniformBuffer("params", this._simParamsComputeShader); + return new UniformBufferEffectCommonAccessor(this._simParamsComputeShader); + } + createVertexBuffers(updateBuffer, renderVertexBuffers) { + this._renderVertexBuffers.push(renderVertexBuffers); + } + createParticleBuffer(data) { + const buffer = new StorageBuffer(this._engine, data.length * 4, 3 | 8, "ComputeShaderParticleSystemBuffer"); + buffer.update(data); + this._bufferComputeShader.push(buffer); + return buffer.getBuffer(); + } + bindDrawBuffers(index, effect, indexBuffer) { + this._engine.bindBuffers(this._renderVertexBuffers[index], indexBuffer, effect); + } + preUpdateParticleBuffer() { } + updateParticleBuffer(index, targetBuffer, currentActiveCount) { + this._simParamsComputeShader.update(); + this._updateComputeShader.setTexture("randomTexture", this._parent._randomTexture, false); + this._updateComputeShader.setTexture("randomTexture2", this._parent._randomTexture2, false); + if (this._parent._sizeGradientsTexture) { + this._updateComputeShader.setTexture("sizeGradientTexture", this._parent._sizeGradientsTexture); + } + if (this._parent._angularSpeedGradientsTexture) { + this._updateComputeShader.setTexture("angularSpeedGradientTexture", this._parent._angularSpeedGradientsTexture); + } + if (this._parent._velocityGradientsTexture) { + this._updateComputeShader.setTexture("velocityGradientTexture", this._parent._velocityGradientsTexture); + } + if (this._parent._limitVelocityGradientsTexture) { + this._updateComputeShader.setTexture("limitVelocityGradientTexture", this._parent._limitVelocityGradientsTexture); + } + if (this._parent._dragGradientsTexture) { + this._updateComputeShader.setTexture("dragGradientTexture", this._parent._dragGradientsTexture); + } + if (this._parent.noiseTexture) { + this._updateComputeShader.setTexture("noiseTexture", this._parent.noiseTexture); + } + this._updateComputeShader.setStorageBuffer("particlesIn", this._bufferComputeShader[index]); + this._updateComputeShader.setStorageBuffer("particlesOut", this._bufferComputeShader[index ^ 1]); + this._updateComputeShader.dispatch(Math.ceil(currentActiveCount / 64)); + } + releaseBuffers() { + for (let i = 0; i < this._bufferComputeShader.length; ++i) { + this._bufferComputeShader[i].dispose(); + } + this._bufferComputeShader.length = 0; + this._simParamsComputeShader?.dispose(); + this._simParamsComputeShader = null; + this._updateComputeShader = null; + } + releaseVertexBuffers() { + this._renderVertexBuffers.length = 0; + } +} +RegisterClass("BABYLON.ComputeShaderParticleSystem", ComputeShaderParticleSystem); + +// Do not edit. +const name$39 = "clipPlaneFragmentDeclaration2"; +const shader$38 = `#ifdef CLIPPLANE +in float fClipDistance; +#endif +#ifdef CLIPPLANE2 +in float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +in float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +in float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +in float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +in float fClipDistance6; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$39]) { + ShaderStore.IncludesShadersStore[name$39] = shader$38; +} + +// Do not edit. +const name$38 = "gpuRenderParticlesPixelShader"; +const shader$37 = `precision highp float; +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; +#include +#include +#include +#include +#include +#include +void main() { +#include +vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; +#ifdef BLENDMULTIPLYMODE +float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); +#endif +#include +#include(color,gl_FragColor) +#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); +#else +#ifdef IMAGEPROCESSING +gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); +#endif +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$38]) { + ShaderStore.ShadersStore[name$38] = shader$37; +} + +// Do not edit. +const name$37 = "clipPlaneVertexDeclaration2"; +const shader$36 = `#ifdef CLIPPLANE +uniform vec4 vClipPlane;out float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;out float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;out float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;out float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;out float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;out float fClipDistance6; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$37]) { + ShaderStore.IncludesShadersStore[name$37] = shader$36; +} + +// Do not edit. +const name$36 = "gpuRenderParticlesVertexShader"; +const shader$35 = `precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; +#ifdef LOCAL +uniform mat4 emitterWM; +#endif +attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; +#ifndef BILLBOARD +attribute vec3 initialDirection; +#endif +#ifdef BILLBOARDSTRETCHED +attribute vec3 direction; +#endif +attribute float angle; +#ifdef ANIMATESHEET +attribute float cellIndex; +#endif +attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform mat4 invView; +#endif +#include +#include +#include +#ifdef COLORGRADIENTS +uniform sampler2D colorGradientSampler; +#else +uniform vec4 colorDead;attribute vec4 color; +#endif +#ifdef ANIMATESHEET +uniform vec3 sheetInfos; +#endif +#ifdef BILLBOARD +uniform vec3 eyePosition; +#endif +vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; +#ifdef LOCAL +return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; +#else +return (position+worldOffset)+alignedCorner; +#endif +} +#ifdef BILLBOARDSTRETCHED +vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; +#ifdef LOCAL +return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; +#else +return (position+worldOffset)+alignedCorner; +#endif +} +#endif +void main() { +#ifdef ANIMATESHEET +float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; +#else +vUV=uv; +#endif +float ratio=min(1.0,age/life); +#ifdef COLORGRADIENTS +vColor=texture2D(colorGradientSampler,vec2(ratio,0)); +#else +vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); +#endif +vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; +#ifdef BILLBOARD +vec4 rotatedCorner;rotatedCorner.w=0.; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); +#else +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; +#ifdef LOCAL +vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; +#else +vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; +#endif +vPositionW=(invView*viewPosition).xyz; +#endif +#else +vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); +#endif +gl_Position=projection*viewPosition; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include +#include +#include +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$36]) { + ShaderStore.ShadersStore[name$36] = shader$35; +} + +/** + * This represents a GPU particle system in Babylon + * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data + * @see https://www.babylonjs-playground.com/#PU4WYI#4 + */ +class GPUParticleSystem extends BaseParticleSystem { + /** + * Gets a boolean indicating if the GPU particles can be rendered on current browser + */ + static get IsSupported() { + if (!EngineStore.LastCreatedEngine) { + return false; + } + const caps = EngineStore.LastCreatedEngine.getCaps(); + return caps.supportTransformFeedbacks || caps.supportComputeShaders; + } + _createIndexBuffer() { + this._linesIndexBufferUseInstancing = this._engine.createIndexBuffer(new Uint32Array([0, 1, 1, 3, 3, 2, 2, 0, 0, 3]), undefined, "GPUParticleSystemLinesIndexBuffer"); + } + /** + * Gets the maximum number of particles active at the same time. + * @returns The max number of active particles. + */ + getCapacity() { + return this._capacity; + } + /** + * Gets or set the number of active particles + * The value cannot be greater than "capacity" (if it is, it will be limited to "capacity"). + */ + get maxActiveParticleCount() { + return this._maxActiveParticleCount; + } + set maxActiveParticleCount(value) { + this._maxActiveParticleCount = Math.min(value, this._capacity); + } + /** + * Gets or set the number of active particles + * @deprecated Please use maxActiveParticleCount instead. + */ + get activeParticleCount() { + return this.maxActiveParticleCount; + } + set activeParticleCount(value) { + this.maxActiveParticleCount = value; + } + /** + * Creates a Point Emitter for the particle system (emits directly from the emitter position) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + * @returns the emitter + */ + createPointEmitter(direction1, direction2) { + const particleEmitter = CreatePointEmitter(direction1, direction2); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) + * @param radius The radius of the hemisphere to emit from + * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + * @returns the emitter + */ + createHemisphericEmitter(radius = 1, radiusRange = 1) { + const particleEmitter = CreateHemisphericEmitter(radius, radiusRange); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Sphere Emitter for the particle system (emits along the sphere radius) + * @param radius The radius of the sphere to emit from + * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius + * @returns the emitter + */ + createSphereEmitter(radius = 1, radiusRange = 1) { + const particleEmitter = CreateSphereEmitter(radius, radiusRange); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) + * @param radius The radius of the sphere to emit from + * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere + * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere + * @returns the emitter + */ + createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + const particleEmitter = CreateDirectedSphereEmitter(radius, direction1, direction2); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position) + * @param radius The radius of the emission cylinder + * @param height The height of the emission cylinder + * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius + * @param directionRandomizer How much to randomize the particle direction [0-1] + * @returns the emitter + */ + createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) { + const particleEmitter = CreateCylinderEmitter(radius, height, radiusRange, directionRandomizer); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2) + * @param radius The radius of the cylinder to emit from + * @param height The height of the emission cylinder + * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder + * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder + * @returns the emitter + */ + createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + const particleEmitter = CreateDirectedCylinderEmitter(radius, height, radiusRange, direction1, direction2); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) + * @param radius The radius of the cone to emit from + * @param angle The base angle of the cone + * @returns the emitter + */ + createConeEmitter(radius = 1, angle = Math.PI / 4) { + const particleEmitter = CreateConeEmitter(radius, angle); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + createDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) { + const particleEmitter = CreateDirectedConeEmitter(radius, angle, direction1, direction2); + this.particleEmitterType = particleEmitter; + return particleEmitter; + } + /** + * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) + * @param direction1 Particles are emitted between the direction1 and direction2 from within the box + * @param direction2 Particles are emitted between the direction1 and direction2 from within the box + * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox + * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox + * @returns the emitter + */ + createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) { + const particleEmitter = new BoxParticleEmitter(); + this.particleEmitterType = particleEmitter; + this.direction1 = direction1; + this.direction2 = direction2; + this.minEmitBox = minEmitBox; + this.maxEmitBox = maxEmitBox; + return particleEmitter; + } + /** + * Is this system ready to be used/rendered + * @returns true if the system is ready + */ + isReady() { + if (!this.emitter || + (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady()) || + !this.particleTexture || + !this.particleTexture.isReady() || + this._rebuildingAfterContextLost) { + return false; + } + if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) { + if (!this._getWrapper(this.blendMode).effect.isReady()) { + return false; + } + } + else { + if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) { + return false; + } + if (!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady()) { + return false; + } + } + if (!this._platform.isUpdateBufferCreated()) { + this._recreateUpdateEffect(); + return false; + } + return this._platform.isUpdateBufferReady(); + } + /** + * Gets if the system has been started. (Note: this will still be true after stop is called) + * @returns True if it has been started, otherwise false. + */ + isStarted() { + return this._started; + } + /** + * Gets if the system has been stopped. (Note: rendering is still happening but the system is frozen) + * @returns True if it has been stopped, otherwise false. + */ + isStopped() { + return this._stopped; + } + /** + * Gets a boolean indicating that the system is stopping + * @returns true if the system is currently stopping + */ + isStopping() { + return false; // Stop is immediate on GPU + } + /** + * Gets the number of particles active at the same time. + * @returns The number of active particles. + */ + getActiveCount() { + return this._currentActiveCount; + } + /** + * Starts the particle system and begins to emit + * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default) + */ + start(delay = this.startDelay) { + if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) { + // eslint-disable-next-line no-throw-literal + throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set"; + } + if (delay) { + setTimeout(() => { + this.start(0); + }, delay); + return; + } + this._started = true; + this._stopped = false; + this._preWarmDone = false; + // Animations + if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) { + this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop); + } + } + /** + * Stops the particle system. + */ + stop() { + if (this._stopped) { + return; + } + this.onStoppedObservable.notifyObservers(this); + this._stopped = true; + } + /** + * Remove all active particles + */ + reset() { + this._releaseBuffers(); + this._platform.releaseVertexBuffers(); + this._currentActiveCount = 0; + this._targetIndex = 0; + } + /** + * Returns the string "GPUParticleSystem" + * @returns a string containing the class name + */ + getClassName() { + return "GPUParticleSystem"; + } + /** + * Gets the custom effect used to render the particles + * @param blendMode Blend mode for which the effect should be retrieved + * @returns The effect + */ + getCustomEffect(blendMode = 0) { + return this._customWrappers[blendMode]?.effect ?? this._customWrappers[0].effect; + } + _getCustomDrawWrapper(blendMode = 0) { + return this._customWrappers[blendMode] ?? this._customWrappers[0]; + } + /** + * Sets the custom effect used to render the particles + * @param effect The effect to set + * @param blendMode Blend mode for which the effect should be set + */ + setCustomEffect(effect, blendMode = 0) { + this._customWrappers[blendMode] = new DrawWrapper(this._engine); + this._customWrappers[blendMode].effect = effect; + } + /** + * Observable that will be called just before the particles are drawn + */ + get onBeforeDrawParticlesObservable() { + if (!this._onBeforeDrawParticlesObservable) { + this._onBeforeDrawParticlesObservable = new Observable(); + } + return this._onBeforeDrawParticlesObservable; + } + /** + * Gets the name of the particle vertex shader + */ + get vertexShaderName() { + return "gpuRenderParticles"; + } + /** + * Gets the vertex buffers used by the particle system + * Should be called after render() has been called for the current frame so that the buffers returned are the ones that have been updated + * in the current frame (there's a ping-pong between two sets of buffers - for a given frame, one set is used as the source and the other as the destination) + */ + get vertexBuffers() { + // We return the other buffers than those corresponding to this._targetIndex because it is assumed vertexBuffers will be called in the current frame + // after render() has been called, meaning that the buffers have already been swapped and this._targetIndex points to the buffers that will be updated + // in the next frame (and which are the sources in this frame) and (this._targetIndex ^ 1) points to the buffers that have been updated this frame + // (and that will be the source buffers in the next frame) + return this._renderVertexBuffers[this._targetIndex ^ 1]; + } + /** + * Gets the index buffer used by the particle system (null for GPU particle systems) + */ + get indexBuffer() { + return null; + } + _removeGradientAndTexture(gradient, gradients, texture) { + super._removeGradientAndTexture(gradient, gradients, texture); + this._releaseBuffers(); + return this; + } + /** + * Adds a new color gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param color1 defines the color to affect to the specified gradient + * @returns the current particle system + */ + addColorGradient(gradient, color1) { + if (!this._colorGradients) { + this._colorGradients = []; + } + const colorGradient = new ColorGradient(gradient, color1); + this._colorGradients.push(colorGradient); + this._refreshColorGradient(true); + this._releaseBuffers(); + return this; + } + _refreshColorGradient(reorder = false) { + if (this._colorGradients) { + if (reorder) { + this._colorGradients.sort((a, b) => { + if (a.gradient < b.gradient) { + return -1; + } + else if (a.gradient > b.gradient) { + return 1; + } + return 0; + }); + } + if (this._colorGradientsTexture) { + this._colorGradientsTexture.dispose(); + this._colorGradientsTexture = null; + } + } + } + /** Force the system to rebuild all gradients that need to be resync */ + forceRefreshGradients() { + this._refreshColorGradient(); + this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture"); + this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture"); + this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture"); + this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture"); + this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture"); + this.reset(); + } + /** + * Remove a specific color gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeColorGradient(gradient) { + this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture); + this._colorGradientsTexture = null; + return this; + } + /** + * Resets the draw wrappers cache + */ + resetDrawCache() { + for (const blendMode in this._drawWrappers) { + const drawWrapper = this._drawWrappers[blendMode]; + drawWrapper.drawContext?.reset(); + } + } + _addFactorGradient(factorGradients, gradient, factor) { + const valueGradient = new FactorGradient(gradient, factor); + factorGradients.push(valueGradient); + this._releaseBuffers(); + } + /** + * Adds a new size gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the size factor to affect to the specified gradient + * @returns the current particle system + */ + addSizeGradient(gradient, factor) { + if (!this._sizeGradients) { + this._sizeGradients = []; + } + this._addFactorGradient(this._sizeGradients, gradient, factor); + this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture", true); + this._releaseBuffers(); + return this; + } + /** + * Remove a specific size gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeSizeGradient(gradient) { + this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture); + this._sizeGradientsTexture = null; + return this; + } + _refreshFactorGradient(factorGradients, textureName, reorder = false) { + if (!factorGradients) { + return; + } + if (reorder) { + factorGradients.sort((a, b) => { + if (a.gradient < b.gradient) { + return -1; + } + else if (a.gradient > b.gradient) { + return 1; + } + return 0; + }); + } + const that = this; + if (that[textureName]) { + that[textureName].dispose(); + that[textureName] = null; + } + } + /** + * Adds a new angular speed gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the angular speed to affect to the specified gradient + * @returns the current particle system + */ + addAngularSpeedGradient(gradient, factor) { + if (!this._angularSpeedGradients) { + this._angularSpeedGradients = []; + } + this._addFactorGradient(this._angularSpeedGradients, gradient, factor); + this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture", true); + this._releaseBuffers(); + return this; + } + /** + * Remove a specific angular speed gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeAngularSpeedGradient(gradient) { + this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture); + this._angularSpeedGradientsTexture = null; + return this; + } + /** + * Adds a new velocity gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the velocity to affect to the specified gradient + * @returns the current particle system + */ + addVelocityGradient(gradient, factor) { + if (!this._velocityGradients) { + this._velocityGradients = []; + } + this._addFactorGradient(this._velocityGradients, gradient, factor); + this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture", true); + this._releaseBuffers(); + return this; + } + /** + * Remove a specific velocity gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeVelocityGradient(gradient) { + this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture); + this._velocityGradientsTexture = null; + return this; + } + /** + * Adds a new limit velocity gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the limit velocity value to affect to the specified gradient + * @returns the current particle system + */ + addLimitVelocityGradient(gradient, factor) { + if (!this._limitVelocityGradients) { + this._limitVelocityGradients = []; + } + this._addFactorGradient(this._limitVelocityGradients, gradient, factor); + this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture", true); + this._releaseBuffers(); + return this; + } + /** + * Remove a specific limit velocity gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeLimitVelocityGradient(gradient) { + this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture); + this._limitVelocityGradientsTexture = null; + return this; + } + /** + * Adds a new drag gradient + * @param gradient defines the gradient to use (between 0 and 1) + * @param factor defines the drag value to affect to the specified gradient + * @returns the current particle system + */ + addDragGradient(gradient, factor) { + if (!this._dragGradients) { + this._dragGradients = []; + } + this._addFactorGradient(this._dragGradients, gradient, factor); + this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture", true); + this._releaseBuffers(); + return this; + } + /** + * Remove a specific drag gradient + * @param gradient defines the gradient to remove + * @returns the current particle system + */ + removeDragGradient(gradient) { + this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture); + this._dragGradientsTexture = null; + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + addEmitRateGradient() { + // Do nothing as emit rate is not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + removeEmitRateGradient() { + // Do nothing as emit rate is not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + addStartSizeGradient() { + // Do nothing as start size is not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + removeStartSizeGradient() { + // Do nothing as start size is not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + addColorRemapGradient() { + // Do nothing as start size is not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + removeColorRemapGradient() { + // Do nothing as start size is not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + addAlphaRemapGradient() { + // Do nothing as start size is not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + removeAlphaRemapGradient() { + // Do nothing as start size is not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + addRampGradient() { + //Not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + removeRampGradient() { + //Not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the list of ramp gradients + */ + getRampGradients() { + return null; + } + /** + * Not supported by GPUParticleSystem + * Gets or sets a boolean indicating that ramp gradients must be used + * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients + */ + get useRampGradients() { + //Not supported by GPUParticleSystem + return false; + } + set useRampGradients(value) { + //Not supported by GPUParticleSystem + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + addLifeTimeGradient() { + //Not supported by GPUParticleSystem + return this; + } + /** + * Not supported by GPUParticleSystem + * @returns the current particle system + */ + removeLifeTimeGradient() { + //Not supported by GPUParticleSystem + return this; + } + /** + * Instantiates a GPU particle system. + * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. + * @param name The name of the particle system + * @param options The options used to create the system + * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene + * @param customEffect a custom effect used to change the way particles are rendered by default + * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture + */ + constructor(name, options, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false) { + super(name); + /** + * The layer mask we are rendering the particles through. + */ + this.layerMask = 0x0fffffff; + this._accumulatedCount = 0; + this._renderVertexBuffers = []; + this._targetIndex = 0; + this._currentRenderId = -1; + this._currentRenderingCameraUniqueId = -1; + this._started = false; + this._stopped = false; + this._timeDelta = 0; + /** Indicates that the update of particles is done in the animate function (and not in render). Default: false */ + this.updateInAnimate = false; + this._actualFrame = 0; + this._rawTextureWidth = 256; + this._rebuildingAfterContextLost = false; + /** + * An event triggered when the system is disposed. + */ + this.onDisposeObservable = new Observable(); + /** + * An event triggered when the system is stopped + */ + this.onStoppedObservable = new Observable(); + /** + * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls + * to override the particles. + */ + this.forceDepthWrite = false; + this._preWarmDone = false; + /** + * Specifies if the particles are updated in emitter local space or world space. + */ + this.isLocal = false; + /** Indicates that the particle system is GPU based */ + this.isGPU = true; + /** @internal */ + this._onBeforeDrawParticlesObservable = null; + if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") { + this._scene = sceneOrEngine || EngineStore.LastCreatedScene; + this._engine = this._scene.getEngine(); + this.uniqueId = this._scene.getUniqueId(); + this._scene.particleSystems.push(this); + } + else { + this._engine = sceneOrEngine; + this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange); + } + if (this._engine.getCaps().supportComputeShaders) { + if (!GetClass("BABYLON.ComputeShaderParticleSystem")) { + throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it."); + } + this._platform = new (GetClass("BABYLON.ComputeShaderParticleSystem"))(this, this._engine); + } + else { + if (!GetClass("BABYLON.WebGL2ParticleSystem")) { + throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it."); + } + this._platform = new (GetClass("BABYLON.WebGL2ParticleSystem"))(this, this._engine); + } + this._customWrappers = { 0: new DrawWrapper(this._engine) }; + this._customWrappers[0].effect = customEffect; + this._drawWrappers = { 0: new DrawWrapper(this._engine) }; + if (this._drawWrappers[0].drawContext) { + this._drawWrappers[0].drawContext.useInstancing = true; + } + this._createIndexBuffer(); + // Setup the default processing configuration to the scene. + this._attachImageProcessingConfiguration(null); + options = options ?? {}; + if (!options.randomTextureSize) { + delete options.randomTextureSize; + } + const fullOptions = { + capacity: 50000, + randomTextureSize: this._engine.getCaps().maxTextureSize, + ...options, + }; + const optionsAsNumber = options; + if (isFinite(optionsAsNumber)) { + fullOptions.capacity = optionsAsNumber; + } + this._capacity = fullOptions.capacity; + this._maxActiveParticleCount = fullOptions.capacity; + this._currentActiveCount = 0; + this._isAnimationSheetEnabled = isAnimationSheetEnabled; + this.particleEmitterType = new BoxParticleEmitter(); + // Random data + const maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize); + let d = []; + for (let i = 0; i < maxTextureSize; ++i) { + d.push(Math.random()); + d.push(Math.random()); + d.push(Math.random()); + d.push(Math.random()); + } + this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1); + this._randomTexture.name = "GPUParticleSystem_random1"; + this._randomTexture.wrapU = 1; + this._randomTexture.wrapV = 1; + d = []; + for (let i = 0; i < maxTextureSize; ++i) { + d.push(Math.random()); + d.push(Math.random()); + d.push(Math.random()); + d.push(Math.random()); + } + this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1); + this._randomTexture2.name = "GPUParticleSystem_random2"; + this._randomTexture2.wrapU = 1; + this._randomTexture2.wrapV = 1; + this._randomTextureSize = maxTextureSize; + } + _reset() { + this._releaseBuffers(); + } + _createVertexBuffers(updateBuffer, renderBuffer, spriteSource) { + const renderVertexBuffers = {}; + renderVertexBuffers["position"] = renderBuffer.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true); + let offset = 3; + renderVertexBuffers["age"] = renderBuffer.createVertexBuffer("age", offset, 1, this._attributesStrideSize, true); + offset += 1; + renderVertexBuffers["size"] = renderBuffer.createVertexBuffer("size", offset, 3, this._attributesStrideSize, true); + offset += 3; + renderVertexBuffers["life"] = renderBuffer.createVertexBuffer("life", offset, 1, this._attributesStrideSize, true); + offset += 1; + offset += 4; // seed + if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) { + renderVertexBuffers["direction"] = renderBuffer.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true); + } + offset += 3; // direction + if (this._platform.alignDataInBuffer) { + offset += 1; + } + if (this.particleEmitterType instanceof CustomParticleEmitter) { + offset += 3; + if (this._platform.alignDataInBuffer) { + offset += 1; + } + } + if (!this._colorGradientsTexture) { + renderVertexBuffers["color"] = renderBuffer.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true); + offset += 4; + } + if (!this._isBillboardBased) { + renderVertexBuffers["initialDirection"] = renderBuffer.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true); + offset += 3; + if (this._platform.alignDataInBuffer) { + offset += 1; + } + } + if (this.noiseTexture) { + renderVertexBuffers["noiseCoordinates1"] = renderBuffer.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true); + offset += 3; + if (this._platform.alignDataInBuffer) { + offset += 1; + } + renderVertexBuffers["noiseCoordinates2"] = renderBuffer.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true); + offset += 3; + if (this._platform.alignDataInBuffer) { + offset += 1; + } + } + renderVertexBuffers["angle"] = renderBuffer.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true); + if (this._angularSpeedGradientsTexture) { + offset++; + } + else { + offset += 2; + } + if (this._isAnimationSheetEnabled) { + renderVertexBuffers["cellIndex"] = renderBuffer.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true); + offset += 1; + if (this.spriteRandomStartCell) { + renderVertexBuffers["cellStartOffset"] = renderBuffer.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true); + offset += 1; + } + } + renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2); + renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2); + this._renderVertexBuffers.push(renderVertexBuffers); + this._platform.createVertexBuffers(updateBuffer, renderVertexBuffers); + this.resetDrawCache(); + } + _initialize(force = false) { + if (this._buffer0 && !force) { + return; + } + const engine = this._engine; + const data = []; + this._attributesStrideSize = 21; + this._targetIndex = 0; + if (this._platform.alignDataInBuffer) { + this._attributesStrideSize += 1; + } + if (this.particleEmitterType instanceof CustomParticleEmitter) { + this._attributesStrideSize += 3; + if (this._platform.alignDataInBuffer) { + this._attributesStrideSize += 1; + } + } + if (!this.isBillboardBased) { + this._attributesStrideSize += 3; + if (this._platform.alignDataInBuffer) { + this._attributesStrideSize += 1; + } + } + if (this._colorGradientsTexture) { + this._attributesStrideSize -= 4; + } + if (this._angularSpeedGradientsTexture) { + this._attributesStrideSize -= 1; + } + if (this._isAnimationSheetEnabled) { + this._attributesStrideSize += 1; + if (this.spriteRandomStartCell) { + this._attributesStrideSize += 1; + } + } + if (this.noiseTexture) { + this._attributesStrideSize += 6; + if (this._platform.alignDataInBuffer) { + this._attributesStrideSize += 2; + } + } + if (this._platform.alignDataInBuffer) { + this._attributesStrideSize += 3 - ((this._attributesStrideSize + 3) & 3); // round to multiple of 4 + } + const usingCustomEmitter = this.particleEmitterType instanceof CustomParticleEmitter; + const tmpVector = TmpVectors.Vector3[0]; + let offset = 0; + for (let particleIndex = 0; particleIndex < this._capacity; particleIndex++) { + // position + data.push(0.0); + data.push(0.0); + data.push(0.0); + // Age + data.push(0.0); // create the particle as a dead one to create a new one at start + // Size + data.push(0.0); + data.push(0.0); + data.push(0.0); + // life + data.push(0.0); + // Seed + data.push(Math.random()); + data.push(Math.random()); + data.push(Math.random()); + data.push(Math.random()); + // direction + if (usingCustomEmitter) { + this.particleEmitterType.particleDestinationGenerator(particleIndex, null, tmpVector); + data.push(tmpVector.x); + data.push(tmpVector.y); + data.push(tmpVector.z); + } + else { + data.push(0.0); + data.push(0.0); + data.push(0.0); + } + if (this._platform.alignDataInBuffer) { + data.push(0.0); // dummy0 + } + offset += 16; // position, age, size, life, seed, direction, dummy0 + if (usingCustomEmitter) { + this.particleEmitterType.particlePositionGenerator(particleIndex, null, tmpVector); + data.push(tmpVector.x); + data.push(tmpVector.y); + data.push(tmpVector.z); + if (this._platform.alignDataInBuffer) { + data.push(0.0); // dummy1 + } + offset += 4; + } + if (!this._colorGradientsTexture) { + // color + data.push(0.0); + data.push(0.0); + data.push(0.0); + data.push(0.0); + offset += 4; + } + if (!this.isBillboardBased) { + // initialDirection + data.push(0.0); + data.push(0.0); + data.push(0.0); + if (this._platform.alignDataInBuffer) { + data.push(0.0); // dummy2 + } + offset += 4; + } + if (this.noiseTexture) { + // Random coordinates for reading into noise texture + data.push(Math.random()); + data.push(Math.random()); + data.push(Math.random()); + if (this._platform.alignDataInBuffer) { + data.push(0.0); // dummy3 + } + data.push(Math.random()); + data.push(Math.random()); + data.push(Math.random()); + if (this._platform.alignDataInBuffer) { + data.push(0.0); // dummy4 + } + offset += 8; + } + // angle + data.push(0.0); + offset += 1; + if (!this._angularSpeedGradientsTexture) { + data.push(0.0); + offset += 1; + } + if (this._isAnimationSheetEnabled) { + data.push(0.0); + offset += 1; + if (this.spriteRandomStartCell) { + data.push(0.0); + offset += 1; + } + } + if (this._platform.alignDataInBuffer) { + let numDummies = 3 - ((offset + 3) & 3); + offset += numDummies; + while (numDummies-- > 0) { + data.push(0.0); + } + } + } + // Sprite data + const spriteData = new Float32Array([0.5, 0.5, 1, 1, -0.5, 0.5, 0, 1, 0.5, -0.5, 1, 0, -0.5, -0.5, 0, 0]); + const bufferData1 = this._platform.createParticleBuffer(data); + const bufferData2 = this._platform.createParticleBuffer(data); + // Buffers + this._buffer0 = new Buffer(engine, bufferData1, false, this._attributesStrideSize); + this._buffer1 = new Buffer(engine, bufferData2, false, this._attributesStrideSize); + this._spriteBuffer = new Buffer(engine, spriteData, false, 4); + // Update & Render vertex buffers + this._renderVertexBuffers = []; + this._createVertexBuffers(this._buffer0, this._buffer1, this._spriteBuffer); + this._createVertexBuffers(this._buffer1, this._buffer0, this._spriteBuffer); + // Links + this._sourceBuffer = this._buffer0; + this._targetBuffer = this._buffer1; + } + /** @internal */ + _recreateUpdateEffect() { + this._createColorGradientTexture(); + this._createSizeGradientTexture(); + this._createAngularSpeedGradientTexture(); + this._createVelocityGradientTexture(); + this._createLimitVelocityGradientTexture(); + this._createDragGradientTexture(); + let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : ""; + if (this._isBillboardBased) { + defines += "\n#define BILLBOARD"; + } + if (this._colorGradientsTexture) { + defines += "\n#define COLORGRADIENTS"; + } + if (this._sizeGradientsTexture) { + defines += "\n#define SIZEGRADIENTS"; + } + if (this._angularSpeedGradientsTexture) { + defines += "\n#define ANGULARSPEEDGRADIENTS"; + } + if (this._velocityGradientsTexture) { + defines += "\n#define VELOCITYGRADIENTS"; + } + if (this._limitVelocityGradientsTexture) { + defines += "\n#define LIMITVELOCITYGRADIENTS"; + } + if (this._dragGradientsTexture) { + defines += "\n#define DRAGGRADIENTS"; + } + if (this.isAnimationSheetEnabled) { + defines += "\n#define ANIMATESHEET"; + if (this.spriteRandomStartCell) { + defines += "\n#define ANIMATESHEETRANDOMSTART"; + } + } + if (this.noiseTexture) { + defines += "\n#define NOISE"; + } + if (this.isLocal) { + defines += "\n#define LOCAL"; + } + if (this._platform.isUpdateBufferCreated() && this._cachedUpdateDefines === defines) { + return this._platform.isUpdateBufferReady(); + } + this._cachedUpdateDefines = defines; + this._updateBuffer = this._platform.createUpdateBuffer(defines); + return this._platform.isUpdateBufferReady(); + } + /** + * @internal + */ + _getWrapper(blendMode) { + const customWrapper = this._getCustomDrawWrapper(blendMode); + if (customWrapper?.effect) { + return customWrapper; + } + const defines = []; + this.fillDefines(defines, blendMode); + // Effect + let drawWrapper = this._drawWrappers[blendMode]; + if (!drawWrapper) { + drawWrapper = new DrawWrapper(this._engine); + if (drawWrapper.drawContext) { + drawWrapper.drawContext.useInstancing = true; + } + this._drawWrappers[blendMode] = drawWrapper; + } + const join = defines.join("\n"); + if (drawWrapper.defines !== join) { + const attributes = []; + const uniforms = []; + const samplers = []; + this.fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers); + drawWrapper.setEffect(this._engine.createEffect("gpuRenderParticles", attributes, uniforms, samplers, join), join); + } + return drawWrapper; + } + /** + * @internal + */ + static _GetAttributeNamesOrOptions(hasColorGradients = false, isAnimationSheetEnabled = false, isBillboardBased = false, isBillboardStretched = false) { + const attributeNamesOrOptions = [VertexBuffer.PositionKind, "age", "life", "size", "angle"]; + if (!hasColorGradients) { + attributeNamesOrOptions.push(VertexBuffer.ColorKind); + } + if (isAnimationSheetEnabled) { + attributeNamesOrOptions.push("cellIndex"); + } + if (!isBillboardBased) { + attributeNamesOrOptions.push("initialDirection"); + } + if (isBillboardStretched) { + attributeNamesOrOptions.push("direction"); + } + attributeNamesOrOptions.push("offset", VertexBuffer.UVKind); + return attributeNamesOrOptions; + } + /** + * @internal + */ + static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false, applyFog = false) { + const effectCreationOption = ["emitterWM", "worldOffset", "view", "projection", "colorDead", "invView", "translationPivot", "eyePosition"]; + addClipPlaneUniforms(effectCreationOption); + if (isAnimationSheetEnabled) { + effectCreationOption.push("sheetInfos"); + } + if (useLogarithmicDepth) { + effectCreationOption.push("logarithmicDepthConstant"); + } + if (applyFog) { + effectCreationOption.push("vFogInfos"); + effectCreationOption.push("vFogColor"); + } + return effectCreationOption; + } + /** + * Fill the defines array according to the current settings of the particle system + * @param defines Array to be updated + * @param blendMode blend mode to take into account when updating the array + * @param fillImageProcessing fills the image processing defines + */ + fillDefines(defines, blendMode = 0, fillImageProcessing = true) { + if (this._scene) { + prepareStringDefinesForClipPlanes(this, this._scene, defines); + if (this.applyFog && this._scene.fogEnabled && this._scene.fogMode !== Scene.FOGMODE_NONE) { + defines.push("#define FOG"); + } + } + if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) { + defines.push("#define BLENDMULTIPLYMODE"); + } + if (this.isLocal) { + defines.push("#define LOCAL"); + } + if (this.useLogarithmicDepth) { + defines.push("#define LOGARITHMICDEPTH"); + } + if (this._isBillboardBased) { + defines.push("#define BILLBOARD"); + switch (this.billboardMode) { + case ParticleSystem.BILLBOARDMODE_Y: + defines.push("#define BILLBOARDY"); + break; + case ParticleSystem.BILLBOARDMODE_STRETCHED: + defines.push("#define BILLBOARDSTRETCHED"); + break; + case ParticleSystem.BILLBOARDMODE_ALL: + defines.push("#define BILLBOARDMODE_ALL"); + break; + } + } + if (this._colorGradientsTexture) { + defines.push("#define COLORGRADIENTS"); + } + if (this.isAnimationSheetEnabled) { + defines.push("#define ANIMATESHEET"); + } + if (fillImageProcessing && this._imageProcessingConfiguration) { + this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines); + defines.push("" + this._imageProcessingConfigurationDefines.toString()); + } + } + /** + * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system + * @param uniforms Uniforms array to fill + * @param attributes Attributes array to fill + * @param samplers Samplers array to fill + */ + fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) { + attributes.push(...GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture, this._isAnimationSheetEnabled, this._isBillboardBased, this._isBillboardBased && this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED)); + uniforms.push(...GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth, this.applyFog)); + samplers.push("diffuseSampler", "colorGradientSampler"); + if (this._imageProcessingConfiguration) { + ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines); + ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines); + } + } + /** + * Animates the particle system for the current frame by emitting new particles and or animating the living ones. + * @param preWarm defines if we are in the pre-warmimg phase + */ + animate(preWarm = false) { + this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene?.getAnimationRatio() || 1); + this._actualFrame += this._timeDelta; + if (!this._stopped) { + if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) { + this.stop(); + } + } + if (this.updateInAnimate) { + this._update(); + } + } + _createFactorGradientTexture(factorGradients, textureName) { + const texture = this[textureName]; + if (!factorGradients || !factorGradients.length || texture) { + return; + } + const data = new Float32Array(this._rawTextureWidth); + for (let x = 0; x < this._rawTextureWidth; x++) { + const ratio = x / this._rawTextureWidth; + GradientHelper.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => { + data[x] = Lerp(currentGradient.factor1, nextGradient.factor1, scale); + }); + } + this[textureName] = RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene || this._engine, false, false, 1); + this[textureName].name = textureName.substring(1); + } + _createSizeGradientTexture() { + this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture"); + } + _createAngularSpeedGradientTexture() { + this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture"); + } + _createVelocityGradientTexture() { + this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture"); + } + _createLimitVelocityGradientTexture() { + this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture"); + } + _createDragGradientTexture() { + this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture"); + } + _createColorGradientTexture() { + if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) { + return; + } + const data = new Uint8Array(this._rawTextureWidth * 4); + const tmpColor = TmpColors.Color4[0]; + for (let x = 0; x < this._rawTextureWidth; x++) { + const ratio = x / this._rawTextureWidth; + GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => { + Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor); + data[x * 4] = tmpColor.r * 255; + data[x * 4 + 1] = tmpColor.g * 255; + data[x * 4 + 2] = tmpColor.b * 255; + data[x * 4 + 3] = tmpColor.a * 255; + }); + } + this._colorGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1); + this._colorGradientsTexture.name = "colorGradients"; + } + _render(blendMode, emitterWM) { + // Enable render effect + const drawWrapper = this._getWrapper(blendMode); + const effect = drawWrapper.effect; + this._engine.enableEffect(drawWrapper); + const viewMatrix = this._scene?.getViewMatrix() || Matrix.IdentityReadOnly; + effect.setMatrix("view", viewMatrix); + effect.setMatrix("projection", this.defaultProjectionMatrix ?? this._scene.getProjectionMatrix()); + effect.setTexture("diffuseSampler", this.particleTexture); + effect.setVector2("translationPivot", this.translationPivot); + effect.setVector3("worldOffset", this.worldOffset); + if (this.isLocal) { + effect.setMatrix("emitterWM", emitterWM); + } + if (this._colorGradientsTexture) { + effect.setTexture("colorGradientSampler", this._colorGradientsTexture); + } + else { + effect.setDirectColor4("colorDead", this.colorDead); + } + if (this._isAnimationSheetEnabled && this.particleTexture) { + const baseSize = this.particleTexture.getBaseSize(); + effect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth); + } + if (this._isBillboardBased && this._scene) { + const camera = this._scene.activeCamera; + effect.setVector3("eyePosition", camera.globalPosition); + } + const defines = effect.defines; + if (this._scene) { + bindClipPlane(effect, this, this._scene); + if (this.applyFog) { + BindFogParameters(this._scene, undefined, effect); + } + } + if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) { + const invView = viewMatrix.clone(); + invView.invert(); + effect.setMatrix("invView", invView); + } + // Log. depth + if (this.useLogarithmicDepth && this._scene) { + BindLogDepth(defines, effect, this._scene); + } + // image processing + if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) { + this._imageProcessingConfiguration.bind(effect); + } + // Draw order + switch (blendMode) { + case ParticleSystem.BLENDMODE_ADD: + this._engine.setAlphaMode(1); + break; + case ParticleSystem.BLENDMODE_ONEONE: + this._engine.setAlphaMode(6); + break; + case ParticleSystem.BLENDMODE_STANDARD: + this._engine.setAlphaMode(2); + break; + case ParticleSystem.BLENDMODE_MULTIPLY: + this._engine.setAlphaMode(4); + break; + } + // Bind source VAO + this._platform.bindDrawBuffers(this._targetIndex, effect, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : null); + if (this._onBeforeDrawParticlesObservable) { + this._onBeforeDrawParticlesObservable.notifyObservers(effect); + } + // Render + if (this._scene?.forceWireframe) { + this._engine.drawElementsType(6, 0, 10, this._currentActiveCount); + } + else { + this._engine.drawArraysType(7, 0, 4, this._currentActiveCount); + } + this._engine.setAlphaMode(0); + if (this._scene?.forceWireframe) { + this._engine.unbindInstanceAttributes(); + } + return this._currentActiveCount; + } + /** @internal */ + _update(emitterWM) { + if (!this.emitter || !this._targetBuffer) { + return; + } + if (!this._recreateUpdateEffect() || this._rebuildingAfterContextLost) { + return; + } + if (!emitterWM) { + if (this.emitter.position) { + const emitterMesh = this.emitter; + emitterWM = emitterMesh.getWorldMatrix(); + } + else { + const emitterPosition = this.emitter; + emitterWM = TmpVectors.Matrix[0]; + Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM); + } + } + const engine = this._engine; + const depthWriteState = engine.getDepthWrite(); + engine.setDepthWrite(false); + this._platform.preUpdateParticleBuffer(); + this._updateBuffer.setFloat("currentCount", this._currentActiveCount); + this._updateBuffer.setFloat("timeDelta", this._timeDelta); + this._updateBuffer.setFloat("stopFactor", this._stopped ? 0 : 1); + this._updateBuffer.setInt("randomTextureSize", this._randomTextureSize); + this._updateBuffer.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime); + this._updateBuffer.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower); + if (!this._colorGradientsTexture) { + this._updateBuffer.setDirectColor4("color1", this.color1); + this._updateBuffer.setDirectColor4("color2", this.color2); + } + this._updateBuffer.setFloat2("sizeRange", this.minSize, this.maxSize); + this._updateBuffer.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY); + this._updateBuffer.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation); + this._updateBuffer.setVector3("gravity", this.gravity); + if (this._limitVelocityGradientsTexture) { + this._updateBuffer.setFloat("limitVelocityDamping", this.limitVelocityDamping); + } + if (this.particleEmitterType) { + this.particleEmitterType.applyToShader(this._updateBuffer); + } + if (this._isAnimationSheetEnabled) { + this._updateBuffer.setFloat4("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed, this.spriteCellLoop ? 1 : 0); + } + if (this.noiseTexture) { + this._updateBuffer.setVector3("noiseStrength", this.noiseStrength); + } + if (!this.isLocal) { + this._updateBuffer.setMatrix("emitterWM", emitterWM); + } + this._platform.updateParticleBuffer(this._targetIndex, this._targetBuffer, this._currentActiveCount); + // Switch VAOs + this._targetIndex++; + if (this._targetIndex === 2) { + this._targetIndex = 0; + } + // Switch buffers + const tmpBuffer = this._sourceBuffer; + this._sourceBuffer = this._targetBuffer; + this._targetBuffer = tmpBuffer; + engine.setDepthWrite(depthWriteState); + } + /** + * Renders the particle system in its current state + * @param preWarm defines if the system should only update the particles but not render them + * @param forceUpdateOnly if true, force to only update the particles and never display them (meaning, even if preWarm=false, when forceUpdateOnly=true the particles won't be displayed) + * @returns the current number of particles + */ + render(preWarm = false, forceUpdateOnly = false) { + if (!this._started) { + return 0; + } + if (!this.isReady()) { + return 0; + } + if (!preWarm && this._scene) { + if (!this._preWarmDone && this.preWarmCycles) { + for (let index = 0; index < this.preWarmCycles; index++) { + this.animate(true); + this.render(true, true); + } + this._preWarmDone = true; + } + if (this._currentRenderId === this._scene.getRenderId() && + (!this._scene.activeCamera || (this._scene.activeCamera && this._currentRenderingCameraUniqueId === this._scene.activeCamera.uniqueId))) { + return 0; + } + this._currentRenderId = this._scene.getRenderId(); + if (this._scene.activeCamera) { + this._currentRenderingCameraUniqueId = this._scene.activeCamera.uniqueId; + } + } + // Get everything ready to render + this._initialize(); + if (this.manualEmitCount > -1) { + this._accumulatedCount += this.manualEmitCount; + this.manualEmitCount = 0; + } + else { + this._accumulatedCount += this.emitRate * this._timeDelta; + } + if (this._accumulatedCount >= 1) { + const intPart = this._accumulatedCount | 0; + this._accumulatedCount -= intPart; + this._currentActiveCount += intPart; + } + this._currentActiveCount = Math.min(this._maxActiveParticleCount, this._currentActiveCount); + if (!this._currentActiveCount) { + return 0; + } + // Enable update effect + let emitterWM; + if (this.emitter.position) { + const emitterMesh = this.emitter; + emitterWM = emitterMesh.getWorldMatrix(); + } + else { + const emitterPosition = this.emitter; + emitterWM = TmpVectors.Matrix[0]; + Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM); + } + const engine = this._engine; + if (!this.updateInAnimate) { + this._update(emitterWM); + } + let outparticles = 0; + if (!preWarm && !forceUpdateOnly) { + engine.setState(false); + if (this.forceDepthWrite) { + engine.setDepthWrite(true); + } + if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) { + outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY, emitterWM) + this._render(ParticleSystem.BLENDMODE_ADD, emitterWM); + } + else { + outparticles = this._render(this.blendMode, emitterWM); + } + this._engine.setAlphaMode(0); + } + return outparticles; + } + /** + * Rebuilds the particle system + */ + rebuild() { + const checkUpdateEffect = () => { + if (!this._recreateUpdateEffect() || !this._platform.isUpdateBufferReady()) { + setTimeout(checkUpdateEffect, 10); + } + else { + this._initialize(true); + this._rebuildingAfterContextLost = false; + } + }; + this._createIndexBuffer(); + this._cachedUpdateDefines = ""; + this._platform.contextLost(); + this._rebuildingAfterContextLost = true; + checkUpdateEffect(); + } + _releaseBuffers() { + if (this._buffer0) { + this._buffer0.dispose(); + this._buffer0 = null; + } + if (this._buffer1) { + this._buffer1.dispose(); + this._buffer1 = null; + } + if (this._spriteBuffer) { + this._spriteBuffer.dispose(); + this._spriteBuffer = null; + } + this._platform.releaseBuffers(); + } + /** + * Disposes the particle system and free the associated resources + * @param disposeTexture defines if the particule texture must be disposed as well (true by default) + */ + dispose(disposeTexture = true) { + for (const blendMode in this._drawWrappers) { + const drawWrapper = this._drawWrappers[blendMode]; + drawWrapper.dispose(); + } + this._drawWrappers = {}; + if (this._scene) { + const index = this._scene.particleSystems.indexOf(this); + if (index > -1) { + this._scene.particleSystems.splice(index, 1); + } + } + this._releaseBuffers(); + this._platform.releaseVertexBuffers(); + for (let i = 0; i < this._renderVertexBuffers.length; ++i) { + const rvb = this._renderVertexBuffers[i]; + for (const key in rvb) { + rvb[key].dispose(); + } + } + this._renderVertexBuffers = []; + if (this._colorGradientsTexture) { + this._colorGradientsTexture.dispose(); + this._colorGradientsTexture = null; + } + if (this._sizeGradientsTexture) { + this._sizeGradientsTexture.dispose(); + this._sizeGradientsTexture = null; + } + if (this._angularSpeedGradientsTexture) { + this._angularSpeedGradientsTexture.dispose(); + this._angularSpeedGradientsTexture = null; + } + if (this._velocityGradientsTexture) { + this._velocityGradientsTexture.dispose(); + this._velocityGradientsTexture = null; + } + if (this._limitVelocityGradientsTexture) { + this._limitVelocityGradientsTexture.dispose(); + this._limitVelocityGradientsTexture = null; + } + if (this._dragGradientsTexture) { + this._dragGradientsTexture.dispose(); + this._dragGradientsTexture = null; + } + if (this._randomTexture) { + this._randomTexture.dispose(); + this._randomTexture = null; + } + if (this._randomTexture2) { + this._randomTexture2.dispose(); + this._randomTexture2 = null; + } + if (disposeTexture && this.particleTexture) { + this.particleTexture.dispose(); + this.particleTexture = null; + } + if (disposeTexture && this.noiseTexture) { + this.noiseTexture.dispose(); + this.noiseTexture = null; + } + // Callback + this.onStoppedObservable.clear(); + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + } + /** + * Clones the particle system. + * @param name The name of the cloned object + * @param newEmitter The new emitter to use + * @param cloneTexture Also clone the textures if true + * @returns the cloned particle system + */ + clone(name, newEmitter, cloneTexture = false) { + const custom = { ...this._customWrappers }; + let program = null; + const engine = this._engine; + if (engine.createEffectForParticles) { + if (this.customShader != null) { + program = this.customShader; + const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; + custom[0] = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, this); + } + } + const serialization = this.serialize(cloneTexture); + const result = GPUParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl); + result.name = name; + result.customShader = program; + result._customWrappers = custom; + if (newEmitter === undefined) { + newEmitter = this.emitter; + } + if (this.noiseTexture) { + result.noiseTexture = this.noiseTexture.clone(); + } + result.emitter = newEmitter; + return result; + } + /** + * Serializes the particle system to a JSON object + * @param serializeTexture defines if the texture must be serialized as well + * @returns the JSON object + */ + serialize(serializeTexture = false) { + const serializationObject = {}; + ParticleSystem._Serialize(serializationObject, this, serializeTexture); + serializationObject.activeParticleCount = this.activeParticleCount; + serializationObject.randomTextureSize = this._randomTextureSize; + serializationObject.customShader = this.customShader; + return serializationObject; + } + /** + * Parses a JSON object to create a GPU particle system. + * @param parsedParticleSystem The JSON object to parse + * @param sceneOrEngine The scene or the engine to create the particle system in + * @param rootUrl The root url to use to load external dependencies like texture + * @param doNotStart Ignore the preventAutoStart attribute and does not start + * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) + * @returns the parsed GPU particle system + */ + static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) { + const name = parsedParticleSystem.name; + let engine; + let scene; + if (sceneOrEngine instanceof AbstractEngine) { + engine = sceneOrEngine; + } + else { + scene = sceneOrEngine; + engine = scene.getEngine(); + } + const particleSystem = new GPUParticleSystem(name, { capacity: capacity || parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, sceneOrEngine, null, parsedParticleSystem.isAnimationSheetEnabled); + particleSystem._rootUrl = rootUrl; + if (parsedParticleSystem.customShader && engine.createEffectForParticles) { + const program = parsedParticleSystem.customShader; + const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; + const custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, particleSystem); + particleSystem.setCustomEffect(custom, 0); + particleSystem.customShader = program; + } + if (parsedParticleSystem.id) { + particleSystem.id = parsedParticleSystem.id; + } + if (parsedParticleSystem.activeParticleCount) { + particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount; + } + ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl); + // Auto start + if (parsedParticleSystem.preventAutoStart) { + particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart; + } + if (!doNotStart && !particleSystem.preventAutoStart) { + particleSystem.start(); + } + return particleSystem; + } +} + +// Adds the parsers to the scene parsers. +AddParser(SceneComponentConstants.NAME_PARTICLESYSTEM, (parsedData, scene, container, rootUrl) => { + const individualParser = GetIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM); + if (!individualParser) { + return; + } + // Particles Systems + if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) { + for (let index = 0, cache = parsedData.particleSystems.length; index < cache; index++) { + const parsedParticleSystem = parsedData.particleSystems[index]; + container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl)); + } + } +}); +AddIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM, (parsedParticleSystem, scene, rootUrl) => { + if (parsedParticleSystem.activeParticleCount) { + const ps = GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl); + return ps; + } + else { + const ps = ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl); + return ps; + } +}); +AbstractEngine.prototype.createEffectForParticles = function (fragmentName, uniformsNames = [], samplers = [], defines = "", fallbacks, onCompiled, onError, particleSystem, shaderLanguage = 0 /* ShaderLanguage.GLSL */, vertexName) { + let attributesNamesOrOptions = []; + let effectCreationOption = []; + const allSamplers = []; + if (particleSystem) { + particleSystem.fillUniformsAttributesAndSamplerNames(effectCreationOption, attributesNamesOrOptions, allSamplers); + } + else { + attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(); + effectCreationOption = ParticleSystem._GetEffectCreationOptions(); + } + if (defines.indexOf(" BILLBOARD") === -1) { + defines += "\n#define BILLBOARD\n"; + } + if (particleSystem?.isAnimationSheetEnabled) { + if (defines.indexOf(" ANIMATESHEET") === -1) { + defines += "\n#define ANIMATESHEET\n"; + } + } + if (samplers.indexOf("diffuseSampler") === -1) { + samplers.push("diffuseSampler"); + } + return this.createEffect({ + vertex: vertexName ?? particleSystem?.vertexShaderName ?? "particles", + fragmentElement: fragmentName, + }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), allSamplers.concat(samplers), defines, fallbacks, onCompiled, onError, undefined, shaderLanguage, async () => { + if (shaderLanguage === 0 /* ShaderLanguage.GLSL */) { + await Promise.resolve().then(() => particles_vertex$1); + } + else { + await Promise.resolve().then(() => particles_vertex); + } + }); +}; +Mesh.prototype.getEmittedParticleSystems = function () { + const results = []; + for (let index = 0; index < this.getScene().particleSystems.length; index++) { + const particleSystem = this.getScene().particleSystems[index]; + if (particleSystem.emitter === this) { + results.push(particleSystem); + } + } + return results; +}; +Mesh.prototype.getHierarchyEmittedParticleSystems = function () { + const results = []; + const descendants = this.getDescendants(); + descendants.push(this); + for (let index = 0; index < this.getScene().particleSystems.length; index++) { + const particleSystem = this.getScene().particleSystems[index]; + const emitter = particleSystem.emitter; + if (emitter.position && descendants.indexOf(emitter) !== -1) { + results.push(particleSystem); + } + } + return results; +}; + +/** Defines the 4 color options */ +var PointColor; +(function (PointColor) { + /** color value */ + PointColor[PointColor["Color"] = 2] = "Color"; + /** uv value */ + PointColor[PointColor["UV"] = 1] = "UV"; + /** random value */ + PointColor[PointColor["Random"] = 0] = "Random"; + /** stated value */ + PointColor[PointColor["Stated"] = 3] = "Stated"; +})(PointColor || (PointColor = {})); + +// Do not edit. +const name$35 = "particlesPixelShader"; +const shader$34 = `#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; +#include +#include +#include +#include +#include +#ifdef RAMPGRADIENT +varying vec4 remapRanges;uniform sampler2D rampSampler; +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; +#ifdef RAMPGRADIENT +float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); +#endif +#ifdef BLENDMULTIPLYMODE +float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); +#endif +#include +#include(color,baseColor) +#ifdef IMAGEPROCESSINGPOSTPROCESS +baseColor.rgb=toLinearSpace(baseColor.rgb); +#else +#ifdef IMAGEPROCESSING +baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); +#endif +#endif +gl_FragColor=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$35]) { + ShaderStore.ShadersStore[name$35] = shader$34; +} +/** @internal */ +const particlesPixelShader = { name: name$35, shader: shader$34 }; + +const particles_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + particlesPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$34 = "particlesVertexShader"; +const shader$33 = `attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; +#ifdef ANIMATESHEET +attribute float cellIndex; +#endif +#ifndef BILLBOARD +attribute vec3 direction; +#endif +#ifdef BILLBOARDSTRETCHED +attribute vec3 direction; +#endif +#ifdef RAMPGRADIENT +attribute vec4 remapData; +#endif +attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; +#ifdef ANIMATESHEET +uniform vec3 particlesInfos; +#endif +varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; +#ifdef RAMPGRADIENT +varying vec4 remapRanges; +#endif +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform mat4 invView; +#endif +#include +#include +#include +#ifdef BILLBOARD +uniform vec3 eyePosition; +#endif +vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} +#ifdef BILLBOARDSTRETCHED +vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); +#ifdef BILLBOARDSTRETCHED_LOCAL +vec3 row1=direction; +#else +vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); +#endif +mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; +#ifdef BILLBOARD +vec3 rotatedCorner; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; +#else +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; +#endif +#ifdef RAMPGRADIENT +remapRanges=remapData; +#endif +gl_Position=projection*vec4(viewPos,1.0); +#else +vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); +#endif +vColor=color; +#ifdef ANIMATESHEET +float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; +#else +vUV=offset; +#endif +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include +#include +#include +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$34]) { + ShaderStore.ShadersStore[name$34] = shader$33; +} +/** @internal */ +const particlesVertexShader = { name: name$34, shader: shader$33 }; + +const particles_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + particlesVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$33 = "particlesPixelShader"; +const shader$32 = `varying vUV: vec2f;varying vColor: vec4f;uniform textureMask: vec4f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; +#include +#include +#include +#include +#include +#ifdef RAMPGRADIENT +varying remapRanges: vec4f;var rampSamplerSampler: sampler;var rampSampler: texture_2d; +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +var textureColor: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV);var baseColor: vec4f=(textureColor*uniforms.textureMask+( vec4f(1.,1.,1.,1.)-uniforms.textureMask))*input.vColor; +#ifdef RAMPGRADIENT +var alpha: f32=baseColor.a;var remappedColorIndex: f32=clamp((alpha-input.remapRanges.x)/input.remapRanges.y,0.0,1.0);var rampColor: vec4f=textureSample(rampSampler,rampSamplerSampler,vec2f(1.0-remappedColorIndex,0.));baseColor=vec4f(baseColor.rgb*rampColor.rgb,baseColor.a);var finalAlpha: f32=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-input.remapRanges.z)/input.remapRanges.w,0.0,1.0); +#endif +#ifdef BLENDMULTIPLYMODE +var sourceAlpha: f32=input.vColor.a*textureColor.a;baseColor=vec4f(baseColor.rgb*sourceAlpha+ vec3f(1.0)*(1.0-sourceAlpha),baseColor.a); +#endif +#include +#include(color,baseColor) +#ifdef IMAGEPROCESSINGPOSTPROCESS +baseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a); +#else +#ifdef IMAGEPROCESSING +baseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a);baseColor=applyImageProcessing(baseColor); +#endif +#endif +fragmentOutputs.color=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$33]) { + ShaderStore.ShadersStoreWGSL[name$33] = shader$32; +} +/** @internal */ +const particlesPixelShaderWGSL = { name: name$33, shader: shader$32 }; + +const particles_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + particlesPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$32 = "particlesVertexShader"; +const shader$31 = `attribute position: vec3f;attribute color: vec4f;attribute angle: f32;attribute size: vec2f; +#ifdef ANIMATESHEET +attribute cellIndex: f32; +#endif +#ifndef BILLBOARD +attribute direction: vec3f; +#endif +#ifdef BILLBOARDSTRETCHED +attribute direction: vec3f; +#endif +#ifdef RAMPGRADIENT +attribute remapData: vec4f; +#endif +attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform translationPivot: vec2f; +#ifdef ANIMATESHEET +uniform particlesInfos: vec3f; +#endif +varying vUV: vec2f;varying vColor: vec4f;varying vPositionW: vec3f; +#ifdef RAMPGRADIENT +varying remapRanges: vec4f; +#endif +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform invView: mat4x4f; +#endif +#include +#include +#include +#ifdef BILLBOARD +uniform eyePosition: vec3f; +#endif +fn rotate(yaxis: vec3f,rotatedCorner: vec3f)->vec3f {var xaxis: vec3f=normalize(cross( vec3f(0.,1.0,0.),yaxis));var zaxis: vec3f=normalize(cross(yaxis,xaxis));var row0: vec3f= vec3f(xaxis.x,xaxis.y,xaxis.z);var row1: vec3f= vec3f(yaxis.x,yaxis.y,yaxis.z);var row2: vec3f= vec3f(zaxis.x,zaxis.y,zaxis.z);var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;} +#ifdef BILLBOARDSTRETCHED +fn rotateAlign(toCamera: vec3f,rotatedCorner: vec3f)->vec3f {var normalizedToCamera: vec3f=normalize(toCamera);var normalizedCrossDirToCamera: vec3f=normalize(cross(normalize(vertexInputs.direction),normalizedToCamera));var row0: vec3f= vec3f(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);var row2: vec3f= vec3f(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); +#ifdef BILLBOARDSTRETCHED_LOCAL +var row1: vec3f=vertexInputs.direction; +#else +var crossProduct: vec3f=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));var row1: vec3f= vec3f(crossProduct.x,crossProduct.y,crossProduct.z); +#endif +var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;} +#endif +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +var cornerPos: vec2f;cornerPos=( vec2f(input.offset.x-0.5,input.offset.y -0.5)-uniforms.translationPivot)*input.size; +#ifdef BILLBOARD +var rotatedCorner: vec3f; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=input.position-uniforms.eyePosition;yaxis.y=0.;vertexOutputs.vPositionW=rotate(normalize(yaxis),rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz; +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var toCamera: vec3f=input.position-uniforms.eyePosition;vertexOutputs.vPositionW=rotateAlign(toCamera,rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz; +#else +rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var viewPos: vec3f=(uniforms.view* vec4f(input.position,1.0)).xyz+rotatedCorner;vertexOutputs.vPositionW=(uniforms.invView* vec4f(viewPos,1)).xyz; +#endif +#ifdef RAMPGRADIENT +vertexOutputs.remapRanges=input.remapData; +#endif +vertexOutputs.position=uniforms.projection* vec4f(viewPos,1.0); +#else +var rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=normalize(vertexInputs.direction);vertexOutputs.vPositionW=rotate(yaxis,rotatedCorner);vertexOutputs.position=uniforms.projection*uniforms.view* vec4f(vertexOutputs.vPositionW,1.0); +#endif +vertexOutputs.vColor=input.color; +#ifdef ANIMATESHEET +var rowOffset: f32=floor(input.cellIndex*uniforms.particlesInfos.z);var columnOffset: f32=input.cellIndex-rowOffset/uniforms.particlesInfos.z;var uvScale: vec2f=uniforms.particlesInfos.xy;var uvOffset: vec2f= vec2f(input.offset.x ,1.0-input.offset.y);vertexOutputs.vUV=(uvOffset+ vec2f(columnOffset,rowOffset))*uvScale; +#else +vertexOutputs.vUV=input.offset; +#endif +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) +var worldPos: vec4f= vec4f(vertexOutputs.vPositionW,1.0); +#endif +#include +#include +#include +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$32]) { + ShaderStore.ShadersStoreWGSL[name$32] = shader$31; +} +/** @internal */ +const particlesVertexShaderWGSL = { name: name$32, shader: shader$31 }; + +const particles_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + particlesVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +Object.defineProperty(AbstractMesh.prototype, "physicsImpostor", { + get: function () { + return this._physicsImpostor; + }, + set: function (value) { + if (this._physicsImpostor === value) { + return; + } + if (this._disposePhysicsObserver) { + this.onDisposeObservable.remove(this._disposePhysicsObserver); + } + this._physicsImpostor = value; + if (value) { + this._disposePhysicsObserver = this.onDisposeObservable.add(() => { + // Physics + if (this.physicsImpostor) { + this.physicsImpostor.dispose( /*!doNotRecurse*/); + this.physicsImpostor = null; + } + }); + } + }, + enumerable: true, + configurable: true, +}); +/** + * Gets the current physics impostor + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics + * @returns a physics impostor or null + */ +AbstractMesh.prototype.getPhysicsImpostor = function () { + return this.physicsImpostor; +}; +/** + * Apply a physic impulse to the mesh + * @param force defines the force to apply + * @param contactPoint defines where to apply the force + * @returns the current mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine + */ +AbstractMesh.prototype.applyImpulse = function (force, contactPoint) { + if (!this.physicsImpostor) { + return this; + } + this.physicsImpostor.applyImpulse(force, contactPoint); + return this; +}; +/** + * Creates a physic joint between two meshes + * @param otherMesh defines the other mesh to use + * @param pivot1 defines the pivot to use on this mesh + * @param pivot2 defines the pivot to use on the other mesh + * @param options defines additional options (can be plugin dependent) + * @returns the current mesh + * @see https://www.babylonjs-playground.com/#0BS5U0#0 + */ +AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) { + if (!this.physicsImpostor || !otherMesh.physicsImpostor) { + return this; + } + this.physicsImpostor.createJoint(otherMesh.physicsImpostor, PhysicsJoint.HingeJoint, { + mainPivot: pivot1, + connectedPivot: pivot2, + nativeParams: options, + }); + return this; +}; + +/** + * Class used to control physics engine + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine + */ +class PhysicsEngine { + /** + * + * @returns physics plugin version + */ + getPluginVersion() { + return this._physicsPlugin.getPluginVersion(); + } + // eslint-disable-next-line jsdoc/require-returns-check + /** + * Factory used to create the default physics plugin. + * @returns The default physics plugin + */ + static DefaultPluginFactory() { + throw _WarnImport(""); + } + /** + * Creates a new Physics Engine + * @param gravity defines the gravity vector used by the simulation + * @param _physicsPlugin defines the plugin to use (CannonJS by default) + */ + constructor(gravity, _physicsPlugin = PhysicsEngine.DefaultPluginFactory()) { + this._physicsPlugin = _physicsPlugin; + /** @internal */ + this._physicsBodies = []; + this._subTimeStep = 0; + gravity = gravity || new Vector3(0, -9.807, 0); + this.setGravity(gravity); + this.setTimeStep(); + } + /** + * Sets the gravity vector used by the simulation + * @param gravity defines the gravity vector to use + */ + setGravity(gravity) { + this.gravity = gravity; + this._physicsPlugin.setGravity(this.gravity); + } + /** + * Set the time step of the physics engine. + * Default is 1/60. + * To slow it down, enter 1/600 for example. + * To speed it up, 1/30 + * Unit is seconds. + * @param newTimeStep defines the new timestep to apply to this world. + */ + setTimeStep(newTimeStep = 1 / 60) { + this._physicsPlugin.setTimeStep(newTimeStep); + } + /** + * Get the time step of the physics engine. + * @returns the current time step + */ + getTimeStep() { + return this._physicsPlugin.getTimeStep(); + } + /** + * Set the sub time step of the physics engine. + * Default is 0 meaning there is no sub steps + * To increase physics resolution precision, set a small value (like 1 ms) + * @param subTimeStep defines the new sub timestep used for physics resolution. + */ + setSubTimeStep(subTimeStep = 0) { + this._subTimeStep = subTimeStep; + } + /** + * Get the sub time step of the physics engine. + * @returns the current sub time step + */ + getSubTimeStep() { + return this._subTimeStep; + } + /** + * Release all resources + */ + dispose() { + this._physicsPlugin.dispose(); + } + /** + * Gets the name of the current physics plugin + * @returns the name of the plugin + */ + getPhysicsPluginName() { + return this._physicsPlugin.name; + } + /** + * Set the maximum allowed linear and angular velocities + * @param maxLinearVelocity maximum allowed linear velocity + * @param maxAngularVelocity maximum allowed angular velocity + */ + setVelocityLimits(maxLinearVelocity, maxAngularVelocity) { + this._physicsPlugin.setVelocityLimits(maxLinearVelocity, maxAngularVelocity); + } + /** + * @returns maximum allowed linear velocity + */ + getMaxLinearVelocity() { + return this._physicsPlugin.getMaxLinearVelocity(); + } + /** + * @returns maximum allowed angular velocity + */ + getMaxAngularVelocity() { + return this._physicsPlugin.getMaxAngularVelocity(); + } + /** + * Adding a new impostor for the impostor tracking. + * This will be done by the impostor itself. + * @param impostor the impostor to add + */ + /** + * Called by the scene. No need to call it. + * @param delta defines the timespan between frames + */ + _step(delta) { + if (delta > 0.1) { + delta = 0.1; + } + else if (delta <= 0) { + delta = 1.0 / 60.0; + } + this._physicsPlugin.executeStep(delta, this._physicsBodies); + } + /** + * Add a body as an active component of this engine + * @param physicsBody The body to add + */ + addBody(physicsBody) { + this._physicsBodies.push(physicsBody); + } + /** + * Removes a particular body from this engine + * @param physicsBody The body to remove from the simulation + */ + removeBody(physicsBody) { + const index = this._physicsBodies.indexOf(physicsBody); + if (index > -1) { + /*const removed =*/ this._physicsBodies.splice(index, 1); + } + } + /** + * @returns an array of bodies added to this engine + */ + getBodies() { + return this._physicsBodies; + } + /** + * Gets the current plugin used to run the simulation + * @returns current plugin + */ + getPhysicsPlugin() { + return this._physicsPlugin; + } + /** + * Does a raycast in the physics world + * @param from when should the ray start? + * @param to when should the ray end? + * @param result resulting PhysicsRaycastResult + * @param query raycast query object + */ + raycastToRef(from, to, result, query) { + this._physicsPlugin.raycast(from, to, result, query); + } + /** + * Does a raycast in the physics world + * @param from when should the ray start? + * @param to when should the ray end? + * @param query raycast query object + * @returns PhysicsRaycastResult + */ + raycast(from, to, query) { + const result = new PhysicsRaycastResult(); + this._physicsPlugin.raycast(from, to, result, query); + return result; + } +} + +/** How a specific axis can be constrained */ +var PhysicsConstraintAxisLimitMode; +(function (PhysicsConstraintAxisLimitMode) { + /* + * The axis is not restricted at all + */ + PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode["FREE"] = 0] = "FREE"; + /* + * The axis has a minimum/maximum limit + */ + PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode["LIMITED"] = 1] = "LIMITED"; + /* + * The axis allows no relative movement of the pivots + */ + PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode["LOCKED"] = 2] = "LOCKED"; +})(PhysicsConstraintAxisLimitMode || (PhysicsConstraintAxisLimitMode = {})); +/** The constraint specific axis to use when setting Friction, `ConstraintAxisLimitMode`, max force, ... */ +var PhysicsConstraintAxis; +(function (PhysicsConstraintAxis) { + /* + * Translation along the primary axis of the constraint (i.e. the + * direction specified by PhysicsConstraintParameters.axisA/axisB) + */ + PhysicsConstraintAxis[PhysicsConstraintAxis["LINEAR_X"] = 0] = "LINEAR_X"; + /* + * Translation along the second axis of the constraint (i.e. the + * direction specified by PhysicsConstraintParameters.perpAxisA/perpAxisB) + */ + PhysicsConstraintAxis[PhysicsConstraintAxis["LINEAR_Y"] = 1] = "LINEAR_Y"; + /* + * Translation along the third axis of the constraint. This axis is + * computed from the cross product of axisA/axisB and perpAxisA/perpAxisB) + */ + PhysicsConstraintAxis[PhysicsConstraintAxis["LINEAR_Z"] = 2] = "LINEAR_Z"; + /* + * Rotation around the primary axis of the constraint (i.e. the + * axis specified by PhysicsConstraintParameters.axisA/axisB) + */ + PhysicsConstraintAxis[PhysicsConstraintAxis["ANGULAR_X"] = 3] = "ANGULAR_X"; + /* + * Rotation around the second axis of the constraint (i.e. the + * axis specified by PhysicsConstraintParameters.perpAxisA/perpAxisB) + */ + PhysicsConstraintAxis[PhysicsConstraintAxis["ANGULAR_Y"] = 4] = "ANGULAR_Y"; + /* + * Rotation around the third axis of the constraint. This axis is + * computed from the cross product of axisA/axisB and perpAxisA/perpAxisB) + */ + PhysicsConstraintAxis[PhysicsConstraintAxis["ANGULAR_Z"] = 5] = "ANGULAR_Z"; + /* + * A 3D distance limit; similar to specifying the LINEAR_X/Y/Z axes + * individually, but the distance calculation uses all three axes + * simultaneously, instead of individually. + */ + PhysicsConstraintAxis[PhysicsConstraintAxis["LINEAR_DISTANCE"] = 6] = "LINEAR_DISTANCE"; +})(PhysicsConstraintAxis || (PhysicsConstraintAxis = {})); +/** Type of Constraint */ +var PhysicsConstraintType; +(function (PhysicsConstraintType) { + /** + * A ball and socket constraint will attempt to line up the pivot + * positions in each body, and have no restrictions on rotation + */ + PhysicsConstraintType[PhysicsConstraintType["BALL_AND_SOCKET"] = 1] = "BALL_AND_SOCKET"; + /** + * A distance constraint will attempt to keep the pivot locations + * within a specified distance. + */ + PhysicsConstraintType[PhysicsConstraintType["DISTANCE"] = 2] = "DISTANCE"; + /** + * A hinge constraint will keep the pivot positions aligned as well + * as two angular axes. The remaining angular axis will be free to rotate. + */ + PhysicsConstraintType[PhysicsConstraintType["HINGE"] = 3] = "HINGE"; + /** + * A slider constraint allows bodies to translate along one axis and + * rotate about the same axis. The remaining two axes are locked in + * place + */ + PhysicsConstraintType[PhysicsConstraintType["SLIDER"] = 4] = "SLIDER"; + /** + * A lock constraint will attempt to keep the pivots completely lined + * up between both bodies, allowing no relative movement. + */ + PhysicsConstraintType[PhysicsConstraintType["LOCK"] = 5] = "LOCK"; + /* + * A prismatic will lock the rotations of the bodies, and allow translation + * only along one axis + */ + PhysicsConstraintType[PhysicsConstraintType["PRISMATIC"] = 6] = "PRISMATIC"; + /* + * A generic constraint; this starts with no limits on how the bodies can + * move relative to each other, but limits can be added via the PhysicsConstraint + * interfaces. This can be used to specify a large variety of constraints + */ + PhysicsConstraintType[PhysicsConstraintType["SIX_DOF"] = 7] = "SIX_DOF"; +})(PhysicsConstraintType || (PhysicsConstraintType = {})); +/** Type of Shape */ +var PhysicsShapeType; +(function (PhysicsShapeType) { + PhysicsShapeType[PhysicsShapeType["SPHERE"] = 0] = "SPHERE"; + PhysicsShapeType[PhysicsShapeType["CAPSULE"] = 1] = "CAPSULE"; + PhysicsShapeType[PhysicsShapeType["CYLINDER"] = 2] = "CYLINDER"; + PhysicsShapeType[PhysicsShapeType["BOX"] = 3] = "BOX"; + PhysicsShapeType[PhysicsShapeType["CONVEX_HULL"] = 4] = "CONVEX_HULL"; + PhysicsShapeType[PhysicsShapeType["CONTAINER"] = 5] = "CONTAINER"; + PhysicsShapeType[PhysicsShapeType["MESH"] = 6] = "MESH"; + PhysicsShapeType[PhysicsShapeType["HEIGHTFIELD"] = 7] = "HEIGHTFIELD"; +})(PhysicsShapeType || (PhysicsShapeType = {})); +/** Optional motor which attempts to move a body at a specific velocity, or at a specific position */ +var PhysicsConstraintMotorType; +(function (PhysicsConstraintMotorType) { + PhysicsConstraintMotorType[PhysicsConstraintMotorType["NONE"] = 0] = "NONE"; + PhysicsConstraintMotorType[PhysicsConstraintMotorType["VELOCITY"] = 1] = "VELOCITY"; + PhysicsConstraintMotorType[PhysicsConstraintMotorType["POSITION"] = 2] = "POSITION"; +})(PhysicsConstraintMotorType || (PhysicsConstraintMotorType = {})); +var PhysicsEventType; +(function (PhysicsEventType) { + PhysicsEventType["COLLISION_STARTED"] = "COLLISION_STARTED"; + PhysicsEventType["COLLISION_CONTINUED"] = "COLLISION_CONTINUED"; + PhysicsEventType["COLLISION_FINISHED"] = "COLLISION_FINISHED"; + PhysicsEventType["TRIGGER_ENTERED"] = "TRIGGER_ENTERED"; + PhysicsEventType["TRIGGER_EXITED"] = "TRIGGER_EXITED"; +})(PhysicsEventType || (PhysicsEventType = {})); +/** + * Indicates how the body will behave. + */ +var PhysicsMotionType; +(function (PhysicsMotionType) { + PhysicsMotionType[PhysicsMotionType["STATIC"] = 0] = "STATIC"; + PhysicsMotionType[PhysicsMotionType["ANIMATED"] = 1] = "ANIMATED"; + PhysicsMotionType[PhysicsMotionType["DYNAMIC"] = 2] = "DYNAMIC"; +})(PhysicsMotionType || (PhysicsMotionType = {})); +/** + * Indicates how to handle position/rotation change of transform node attached to a physics body + */ +var PhysicsPrestepType; +(function (PhysicsPrestepType) { + PhysicsPrestepType[PhysicsPrestepType["DISABLED"] = 0] = "DISABLED"; + PhysicsPrestepType[PhysicsPrestepType["TELEPORT"] = 1] = "TELEPORT"; + PhysicsPrestepType[PhysicsPrestepType["ACTION"] = 2] = "ACTION"; +})(PhysicsPrestepType || (PhysicsPrestepType = {})); +/** + * Controls the body sleep mode. + */ +var PhysicsActivationControl; +(function (PhysicsActivationControl) { + PhysicsActivationControl[PhysicsActivationControl["SIMULATION_CONTROLLED"] = 0] = "SIMULATION_CONTROLLED"; + PhysicsActivationControl[PhysicsActivationControl["ALWAYS_ACTIVE"] = 1] = "ALWAYS_ACTIVE"; + PhysicsActivationControl[PhysicsActivationControl["ALWAYS_INACTIVE"] = 2] = "ALWAYS_INACTIVE"; +})(PhysicsActivationControl || (PhysicsActivationControl = {})); + +/** + * Determines how values from the PhysicsMaterial are combined when + * two objects are in contact. When each PhysicsMaterial specifies + * a different combine mode for some property, the combine mode which + * is used will be selected based on their order in this enum - i.e. + * a value later in this list will be preferentially used. + */ +var PhysicsMaterialCombineMode; +(function (PhysicsMaterialCombineMode) { + /** + * The final value will be the geometric mean of the two values: + * sqrt( valueA * valueB ) + */ + PhysicsMaterialCombineMode[PhysicsMaterialCombineMode["GEOMETRIC_MEAN"] = 0] = "GEOMETRIC_MEAN"; + /** + * The final value will be the smaller of the two: + * min( valueA , valueB ) + */ + PhysicsMaterialCombineMode[PhysicsMaterialCombineMode["MINIMUM"] = 1] = "MINIMUM"; + /* The final value will be the larger of the two: + * max( valueA , valueB ) + */ + PhysicsMaterialCombineMode[PhysicsMaterialCombineMode["MAXIMUM"] = 2] = "MAXIMUM"; + /* The final value will be the arithmetic mean of the two values: + * (valueA + valueB) / 2 + */ + PhysicsMaterialCombineMode[PhysicsMaterialCombineMode["ARITHMETIC_MEAN"] = 3] = "ARITHMETIC_MEAN"; + /** + * The final value will be the product of the two values: + * valueA * valueB + */ + PhysicsMaterialCombineMode[PhysicsMaterialCombineMode["MULTIPLY"] = 4] = "MULTIPLY"; +})(PhysicsMaterialCombineMode || (PhysicsMaterialCombineMode = {})); + +/** + * State of the character on the surface + */ +var CharacterSupportedState; +(function (CharacterSupportedState) { + CharacterSupportedState[CharacterSupportedState["UNSUPPORTED"] = 0] = "UNSUPPORTED"; + CharacterSupportedState[CharacterSupportedState["SLIDING"] = 1] = "SLIDING"; + CharacterSupportedState[CharacterSupportedState["SUPPORTED"] = 2] = "SUPPORTED"; +})(CharacterSupportedState || (CharacterSupportedState = {})); +/** @internal */ +var SurfaceConstraintInteractionStatus; +(function (SurfaceConstraintInteractionStatus) { + SurfaceConstraintInteractionStatus[SurfaceConstraintInteractionStatus["OK"] = 0] = "OK"; + SurfaceConstraintInteractionStatus[SurfaceConstraintInteractionStatus["FAILURE_3D"] = 1] = "FAILURE_3D"; + SurfaceConstraintInteractionStatus[SurfaceConstraintInteractionStatus["FAILURE_2D"] = 2] = "FAILURE_2D"; +})(SurfaceConstraintInteractionStatus || (SurfaceConstraintInteractionStatus = {})); + +/** + * Gets the current physics engine + * @returns a IPhysicsEngine or null if none attached + */ +Scene.prototype.getPhysicsEngine = function () { + return this._physicsEngine; +}; +/** + * Enables physics to the current scene + * @param gravity defines the scene's gravity for the physics engine + * @param plugin defines the physics engine to be used. defaults to CannonJS. + * @returns a boolean indicating if the physics engine was initialized + */ +Scene.prototype.enablePhysics = function (gravity = null, plugin) { + if (this._physicsEngine) { + return true; + } + // Register the component to the scene + let component = this._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE); + if (!component) { + component = new PhysicsEngineSceneComponent(this); + this._addComponent(component); + } + try { + if (!plugin || plugin?.getPluginVersion() === 1) { + this._physicsEngine = new PhysicsEngine$1(gravity, plugin); + } + else if (plugin?.getPluginVersion() === 2) { + this._physicsEngine = new PhysicsEngine(gravity, plugin); + } + else { + throw new Error("Unsupported Physics plugin version."); + } + this._physicsTimeAccumulator = 0; + return true; + } + catch (e) { + Logger.Error(e.message); + return false; + } +}; +/** + * Disables and disposes the physics engine associated with the scene + */ +Scene.prototype.disablePhysicsEngine = function () { + if (!this._physicsEngine) { + return; + } + this._physicsEngine.dispose(); + this._physicsEngine = null; +}; +/** + * Gets a boolean indicating if there is an active physics engine + * @returns a boolean indicating if there is an active physics engine + */ +Scene.prototype.isPhysicsEnabled = function () { + return this._physicsEngine !== undefined; +}; +/** + * Deletes a physics compound impostor + * @param compound defines the compound to delete + */ +Scene.prototype.deleteCompoundImpostor = function (compound) { + const mesh = compound.parts[0].mesh; + if (mesh.physicsImpostor) { + mesh.physicsImpostor.dispose( /*true*/); + mesh.physicsImpostor = null; + } +}; +/** + * @internal + */ +Scene.prototype._advancePhysicsEngineStep = function (step) { + if (this._physicsEngine) { + const subTime = this._physicsEngine.getSubTimeStep(); + if (subTime > 0) { + this._physicsTimeAccumulator += step; + while (this._physicsTimeAccumulator > subTime) { + this.onBeforePhysicsObservable.notifyObservers(this); + this._physicsEngine._step(subTime / 1000); + this.onAfterPhysicsObservable.notifyObservers(this); + this._physicsTimeAccumulator -= subTime; + } + } + else { + this.onBeforePhysicsObservable.notifyObservers(this); + this._physicsEngine._step(step / 1000); + this.onAfterPhysicsObservable.notifyObservers(this); + } + } +}; +/** + * Defines the physics engine scene component responsible to manage a physics engine + */ +class PhysicsEngineSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_PHYSICSENGINE; + this.scene = scene; + this.scene.onBeforePhysicsObservable = new Observable(); + this.scene.onAfterPhysicsObservable = new Observable(); + // Replace the function used to get the deterministic frame time + this.scene.getDeterministicFrameTime = () => { + if (this.scene._physicsEngine) { + return this.scene._physicsEngine.getTimeStep() * 1000; + } + return 1000.0 / 60.0; + }; + } + /** + * Registers the component in a given scene + */ + register() { } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do for this component + } + /** + * Disposes the component and the associated resources + */ + dispose() { + this.scene.onBeforePhysicsObservable.clear(); + this.scene.onAfterPhysicsObservable.clear(); + if (this.scene._physicsEngine) { + this.scene.disablePhysicsEngine(); + } + } +} + +Object.defineProperty(TransformNode.prototype, "physicsBody", { + get: function () { + return this._physicsBody; + }, + set: function (value) { + if (this._physicsBody === value) { + return; + } + if (this._disposePhysicsObserver) { + this.onDisposeObservable.remove(this._disposePhysicsObserver); + } + this._physicsBody = value; + if (value) { + this._disposePhysicsObserver = this.onDisposeObservable.add(() => { + // Physics + if (this.physicsBody) { + this.physicsBody.dispose( /*!doNotRecurse*/); + this.physicsBody = null; + } + }); + } + }, + enumerable: true, + configurable: true, +}); +/** + * Gets the current physics body + * @returns a physics body or null + */ +TransformNode.prototype.getPhysicsBody = function () { + return this.physicsBody; +}; +/** + * Apply a physic impulse to the mesh + * @param force defines the force to apply + * @param contactPoint defines where to apply the force + * @returns the current mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine + */ +TransformNode.prototype.applyImpulse = function (force, contactPoint) { + if (!this.physicsBody) { + throw new Error("No Physics Body for TransformNode"); + } + this.physicsBody.applyImpulse(force, contactPoint); + return this; +}; +/** + * Apply a physic angular impulse to the mesh + * @param angularImpulse defines the torque to apply + * @returns the current mesh + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine + */ +TransformNode.prototype.applyAngularImpulse = function (angularImpulse) { + if (!this.physicsBody) { + throw new Error("No Physics Body for TransformNode"); + } + this.physicsBody.applyAngularImpulse(angularImpulse); + return this; +}; + +Vector3.Zero(); +/** + * The strength of the force in correspondence to the distance of the affected object + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine#further-functionality-of-the-impostor-class + */ +var PhysicsRadialImpulseFalloff; +(function (PhysicsRadialImpulseFalloff) { + /** Defines that impulse is constant in strength across it's whole radius */ + PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant"; + /** Defines that impulse gets weaker if it's further from the origin */ + PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; +})(PhysicsRadialImpulseFalloff || (PhysicsRadialImpulseFalloff = {})); +/** + * The strength of the force in correspondence to the distance of the affected object + * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine#further-functionality-of-the-impostor-class + */ +var PhysicsUpdraftMode; +(function (PhysicsUpdraftMode) { + /** Defines that the upstream forces will pull towards the top center of the cylinder */ + PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center"; + /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */ + PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; +})(PhysicsUpdraftMode || (PhysicsUpdraftMode = {})); + +/** + * Post process used to render in black and white + */ +class BlackAndWhitePostProcess extends PostProcess { + /** + * Linear about to convert he result to black and white (default: 1) + */ + get degree() { + return this._effectWrapper.degree; + } + set degree(value) { + this._effectWrapper.degree = value; + } + /** + * Gets a string identifying the name of the class + * @returns "BlackAndWhitePostProcess" string + */ + getClassName() { + return "BlackAndWhitePostProcess"; + } + /** + * Creates a black and white post process + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#black-and-white + * @param name The name of the effect. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + */ + constructor(name, options, camera = null, samplingMode, engine, reusable) { + const localOptions = { + uniforms: ThinBlackAndWhitePostProcess.Uniforms, + size: typeof options === "number" ? options : undefined, + camera, + samplingMode, + engine, + reusable, + ...options, + }; + super(name, ThinBlackAndWhitePostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBlackAndWhitePostProcess(name, engine, localOptions) : undefined, + ...localOptions, + }); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new BlackAndWhitePostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], BlackAndWhitePostProcess.prototype, "degree", null); +RegisterClass("BABYLON.BlackAndWhitePostProcess", BlackAndWhitePostProcess); + +/** + * This represents a set of one or more post processes in Babylon. + * A post process can be used to apply a shader to a texture after it is rendered. + * @example https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/postProcessRenderPipeline + */ +class PostProcessRenderEffect { + /** + * Instantiates a post process render effect. + * A post process can be used to apply a shader to a texture after it is rendered. + * @param engine The engine the effect is tied to + * @param name The name of the effect + * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run. + * @param singleInstance False if this post process can be run on multiple cameras. (default: true) + */ + constructor(engine, name, getPostProcesses, singleInstance) { + this._name = name; + this._singleInstance = singleInstance || true; + this._getPostProcesses = getPostProcesses; + this._cameras = {}; + this._indicesForCamera = {}; + this._postProcesses = {}; + } + /** + * Checks if all the post processes in the effect are supported. + */ + get isSupported() { + for (const index in this._postProcesses) { + if (Object.prototype.hasOwnProperty.call(this._postProcesses, index)) { + const pps = this._postProcesses[index]; + for (let ppIndex = 0; ppIndex < pps.length; ppIndex++) { + if (!pps[ppIndex].isSupported) { + return false; + } + } + } + } + return true; + } + /** + * Updates the current state of the effect + * @internal + */ + _update() { } + /** + * Attaches the effect on cameras + * @param cameras The camera to attach to. + * @internal + */ + _attachCameras(cameras) { + let cameraKey; + const cams = Tools.MakeArray(cameras || this._cameras); + if (!cams) { + return; + } + for (let i = 0; i < cams.length; i++) { + const camera = cams[i]; + if (!camera) { + continue; + } + const cameraName = camera.name; + if (this._singleInstance) { + cameraKey = 0; + } + else { + cameraKey = cameraName; + } + if (!this._postProcesses[cameraKey]) { + const postProcess = this._getPostProcesses(); + if (postProcess) { + this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess]; + } + } + if (!this._indicesForCamera[cameraName]) { + this._indicesForCamera[cameraName] = []; + } + this._postProcesses[cameraKey].forEach((postProcess) => { + const index = camera.attachPostProcess(postProcess); + this._indicesForCamera[cameraName].push(index); + }); + if (!this._cameras[cameraName]) { + this._cameras[cameraName] = camera; + } + } + } + /** + * Detaches the effect on cameras + * @param cameras The camera to detach from. + * @internal + */ + _detachCameras(cameras) { + const cams = Tools.MakeArray(cameras || this._cameras); + if (!cams) { + return; + } + for (let i = 0; i < cams.length; i++) { + const camera = cams[i]; + const cameraName = camera.name; + const postProcesses = this._postProcesses[this._singleInstance ? 0 : cameraName]; + if (postProcesses) { + postProcesses.forEach((postProcess) => { + camera.detachPostProcess(postProcess); + }); + } + if (this._cameras[cameraName]) { + this._cameras[cameraName] = null; + } + delete this._indicesForCamera[cameraName]; + } + } + /** + * Enables the effect on given cameras + * @param cameras The camera to enable. + * @internal + */ + _enable(cameras) { + const cams = Tools.MakeArray(cameras || this._cameras); + if (!cams) { + return; + } + for (let i = 0; i < cams.length; i++) { + const camera = cams[i]; + const cameraName = camera.name; + const cameraKey = this._singleInstance ? 0 : cameraName; + for (let j = 0; j < this._indicesForCamera[cameraName].length; j++) { + const index = this._indicesForCamera[cameraName][j]; + const postProcess = camera._postProcesses[index]; + if (postProcess === undefined || postProcess === null) { + cams[i].attachPostProcess(this._postProcesses[cameraKey][j], index); + } + } + } + } + /** + * Disables the effect on the given cameras + * @param cameras The camera to disable. + * @internal + */ + _disable(cameras) { + const cams = Tools.MakeArray(cameras || this._cameras); + if (!cams) { + return; + } + for (let i = 0; i < cams.length; i++) { + const camera = cams[i]; + const cameraName = camera.name; + this._postProcesses[this._singleInstance ? 0 : cameraName].forEach((postProcess) => { + camera.detachPostProcess(postProcess); + }); + } + } + /** + * Gets a list of the post processes contained in the effect. + * @param camera The camera to get the post processes on. + * @returns The list of the post processes in the effect. + */ + getPostProcesses(camera) { + if (this._singleInstance) { + return this._postProcesses[0]; + } + else { + if (!camera) { + return null; + } + return this._postProcesses[camera.name]; + } + } +} + +/** + * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect. + */ +class ExtractHighlightsPostProcess extends PostProcess { + /** + * The luminance threshold, pixels below this value will be set to black. + */ + get threshold() { + return this._effectWrapper.threshold; + } + set threshold(value) { + this._effectWrapper.threshold = value; + } + /** @internal */ + get _exposure() { + return this._effectWrapper._exposure; + } + /** @internal */ + set _exposure(value) { + this._effectWrapper._exposure = value; + } + /** + * Gets a string identifying the name of the class + * @returns "ExtractHighlightsPostProcess" string + */ + getClassName() { + return "ExtractHighlightsPostProcess"; + } + constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { + const localOptions = { + uniforms: ThinExtractHighlightsPostProcess.Uniforms, + size: typeof options === "number" ? options : undefined, + camera, + samplingMode, + engine, + reusable, + textureType, + blockCompilation, + ...options, + }; + super(name, ThinExtractHighlightsPostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinExtractHighlightsPostProcess(name, engine, localOptions) : undefined, + ...localOptions, + }); + /** + * Post process which has the input texture to be used when performing highlight extraction + * @internal + */ + this._inputPostProcess = null; + this.onApplyObservable.add((effect) => { + this.externalTextureSamplerBinding = !!this._inputPostProcess; + if (this._inputPostProcess) { + effect.setTextureFromPostProcess("textureSampler", this._inputPostProcess); + } + }); + } +} +__decorate([ + serialize() +], ExtractHighlightsPostProcess.prototype, "threshold", null); +RegisterClass("BABYLON.ExtractHighlightsPostProcess", ExtractHighlightsPostProcess); + +/** + * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion. + */ +class BloomMergePostProcess extends PostProcess { + /** Weight of the bloom to be added to the original input. */ + get weight() { + return this._effectWrapper.weight; + } + set weight(value) { + this._effectWrapper.weight = value; + } + /** + * Gets a string identifying the name of the class + * @returns "BloomMergePostProcess" string + */ + getClassName() { + return "BloomMergePostProcess"; + } + /** + * Creates a new instance of @see BloomMergePostProcess + * @param name The name of the effect. + * @param originalFromInput Post process which's input will be used for the merge. + * @param blurred Blurred highlights post process which's output will be used. + * @param weight Weight of the bloom to be added to the original input. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(name, originalFromInput, blurred, weight, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { + const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation; + const localOptions = { + uniforms: ThinBloomMergePostProcess.Uniforms, + samplers: ThinBloomMergePostProcess.Samplers, + size: typeof options === "number" ? options : undefined, + camera, + samplingMode, + engine, + reusable, + textureType, + ...options, + blockCompilation: true, + }; + super(name, ThinBloomMergePostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBloomMergePostProcess(name, engine, localOptions) : undefined, + ...localOptions, + }); + this.weight = weight; + this.externalTextureSamplerBinding = true; + this.onApplyObservable.add((effect) => { + effect.setTextureFromPostProcess("textureSampler", originalFromInput); + effect.setTextureFromPostProcessOutput("bloomBlur", blurred); + }); + if (!blockCompilationFinal) { + this.updateEffect(); + } + } +} +__decorate([ + serialize() +], BloomMergePostProcess.prototype, "weight", null); +RegisterClass("BABYLON.BloomMergePostProcess", BloomMergePostProcess); + +/** + * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras + */ +class BloomEffect extends PostProcessRenderEffect { + /** + * The luminance threshold to find bright areas of the image to bloom. + */ + get threshold() { + return this._thinBloomEffect.threshold; + } + set threshold(value) { + this._thinBloomEffect.threshold = value; + } + /** + * The strength of the bloom. + */ + get weight() { + return this._thinBloomEffect.weight; + } + set weight(value) { + this._thinBloomEffect.weight = value; + } + /** + * Specifies the size of the bloom blur kernel, relative to the final output size + */ + get kernel() { + return this._thinBloomEffect.kernel; + } + set kernel(value) { + this._thinBloomEffect.kernel = value; + } + get bloomScale() { + return this._thinBloomEffect.scale; + } + /** + * Creates a new instance of @see BloomEffect + * @param sceneOrEngine The scene or engine the effect belongs to. + * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom. + * @param bloomWeight The strength of bloom. + * @param bloomKernel The size of the kernel to be used when applying the blur. + * @param pipelineTextureType The type of texture to be used when performing the post processing. + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(sceneOrEngine, bloomScale, bloomWeight, bloomKernel, pipelineTextureType = 0, blockCompilation = false) { + const engine = sceneOrEngine._renderForCamera ? sceneOrEngine.getEngine() : sceneOrEngine; + super(engine, "bloom", () => { + return this._effects; + }, true); + /** + * @internal Internal + */ + this._effects = []; + this._thinBloomEffect = new ThinBloomEffect("bloom", engine, bloomScale, blockCompilation); + this._downscale = new ExtractHighlightsPostProcess("highlights", { + size: 1.0, + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine, + textureType: pipelineTextureType, + blockCompilation, + effectWrapper: this._thinBloomEffect._downscale, + }); + this._blurX = new BlurPostProcess("horizontal blur", this._thinBloomEffect._blurX.direction, this._thinBloomEffect._blurX.kernel, { + size: bloomScale, + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine, + textureType: pipelineTextureType, + blockCompilation, + effectWrapper: this._thinBloomEffect._blurX, + }); + this._blurX.alwaysForcePOT = true; + this._blurX.autoClear = false; + this._blurY = new BlurPostProcess("vertical blur", this._thinBloomEffect._blurY.direction, this._thinBloomEffect._blurY.kernel, { + size: bloomScale, + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine, + textureType: pipelineTextureType, + blockCompilation, + effectWrapper: this._thinBloomEffect._blurY, + }); + this._blurY.alwaysForcePOT = true; + this._blurY.autoClear = false; + this.kernel = bloomKernel; + this._effects = [this._downscale, this._blurX, this._blurY]; + this._merge = new BloomMergePostProcess("bloomMerge", this._downscale, this._blurY, bloomWeight, { + size: bloomScale, + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine, + textureType: pipelineTextureType, + blockCompilation, + effectWrapper: this._thinBloomEffect._merge, + }); + this._merge.autoClear = false; + this._effects.push(this._merge); + } + /** + * Disposes each of the internal effects for a given camera. + * @param camera The camera to dispose the effect on. + */ + disposeEffects(camera) { + for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { + this._effects[effectIndex].dispose(camera); + } + } + /** + * @internal Internal + */ + _updateEffects() { + for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { + this._effects[effectIndex].updateEffect(); + } + } + /** + * Internal + * @returns if all the contained post processes are ready. + * @internal + */ + _isReady() { + return this._thinBloomEffect.isReady(); + } +} + +/** + * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen + */ +class ChromaticAberrationPostProcess extends PostProcess { + /** + * The amount of separation of rgb channels (default: 30) + */ + get aberrationAmount() { + return this._effectWrapper.aberrationAmount; + } + set aberrationAmount(value) { + this._effectWrapper.aberrationAmount = value; + } + /** + * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0) + */ + get radialIntensity() { + return this._effectWrapper.radialIntensity; + } + set radialIntensity(value) { + this._effectWrapper.radialIntensity = value; + } + /** + * The normalized direction in which the rgb channels should be separated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707)) + */ + get direction() { + return this._effectWrapper.direction; + } + set direction(value) { + this._effectWrapper.direction = value; + } + /** + * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corner] (default: Vector2(0.5 ,0.5)) + */ + get centerPosition() { + return this._effectWrapper.centerPosition; + } + set centerPosition(value) { + this._effectWrapper.centerPosition = value; + } + /** The width of the screen to apply the effect on */ + get screenWidth() { + return this._effectWrapper.screenWidth; + } + set screenWidth(value) { + this._effectWrapper.screenWidth = value; + } + /** The height of the screen to apply the effect on */ + get screenHeight() { + return this._effectWrapper.screenHeight; + } + set screenHeight(value) { + this._effectWrapper.screenHeight = value; + } + /** + * Gets a string identifying the name of the class + * @returns "ChromaticAberrationPostProcess" string + */ + getClassName() { + return "ChromaticAberrationPostProcess"; + } + /** + * Creates a new instance ChromaticAberrationPostProcess + * @param name The name of the effect. + * @param screenWidth The width of the screen to apply the effect on. + * @param screenHeight The height of the screen to apply the effect on. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { + const localOptions = { + uniforms: ThinChromaticAberrationPostProcess.Uniforms, + size: typeof options === "number" ? options : undefined, + camera, + samplingMode, + engine, + reusable, + textureType, + blockCompilation, + ...options, + }; + super(name, ThinChromaticAberrationPostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinChromaticAberrationPostProcess(name, engine, localOptions) : undefined, + ...localOptions, + }); + this.screenWidth = screenWidth; + this.screenHeight = screenHeight; + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new ChromaticAberrationPostProcess(parsedPostProcess.name, parsedPostProcess.screenWidth, parsedPostProcess.screenHeight, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, false); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], ChromaticAberrationPostProcess.prototype, "aberrationAmount", null); +__decorate([ + serialize() +], ChromaticAberrationPostProcess.prototype, "radialIntensity", null); +__decorate([ + serialize() +], ChromaticAberrationPostProcess.prototype, "direction", null); +__decorate([ + serialize() +], ChromaticAberrationPostProcess.prototype, "centerPosition", null); +__decorate([ + serialize() +], ChromaticAberrationPostProcess.prototype, "screenWidth", null); +__decorate([ + serialize() +], ChromaticAberrationPostProcess.prototype, "screenHeight", null); +RegisterClass("BABYLON.ChromaticAberrationPostProcess", ChromaticAberrationPostProcess); + +/** + * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion + */ +class CircleOfConfusionPostProcess extends PostProcess { + /** + * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diameter of the resulting aperture can be computed by lensSize/fStop. + */ + get lensSize() { + return this._effectWrapper.lensSize; + } + set lensSize(value) { + this._effectWrapper.lensSize = value; + } + /** + * F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop. (default: 1.4) + */ + get fStop() { + return this._effectWrapper.fStop; + } + set fStop(value) { + this._effectWrapper.fStop = value; + } + /** + * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000) + */ + get focusDistance() { + return this._effectWrapper.focusDistance; + } + set focusDistance(value) { + this._effectWrapper.focusDistance = value; + } + /** + * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50) + */ + get focalLength() { + return this._effectWrapper.focalLength; + } + set focalLength(value) { + this._effectWrapper.focalLength = value; + } + /** + * Gets a string identifying the name of the class + * @returns "CircleOfConfusionPostProcess" string + */ + getClassName() { + return "CircleOfConfusionPostProcess"; + } + /** + * Creates a new instance CircleOfConfusionPostProcess + * @param name The name of the effect. + * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { + const localOptions = { + uniforms: ThinCircleOfConfusionPostProcess.Uniforms, + samplers: ThinCircleOfConfusionPostProcess.Samplers, + defines: typeof options === "object" && options.depthNotNormalized ? ThinCircleOfConfusionPostProcess.DefinesDepthNotNormalized : undefined, + size: typeof options === "number" ? options : undefined, + camera, + samplingMode, + engine, + reusable, + textureType, + blockCompilation, + ...options, + }; + super(name, ThinCircleOfConfusionPostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinCircleOfConfusionPostProcess(name, engine, localOptions) : undefined, + ...localOptions, + }); + this._depthTexture = null; + this._depthTexture = depthTexture; + this.onApplyObservable.add((effect) => { + if (!this._depthTexture) { + Logger.Warn("No depth texture set on CircleOfConfusionPostProcess"); + return; + } + effect.setTexture("depthSampler", this._depthTexture); + this._effectWrapper.camera = this._depthTexture.activeCamera; + }); + } + /** + * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function. + */ + set depthTexture(value) { + this._depthTexture = value; + } +} +__decorate([ + serialize() +], CircleOfConfusionPostProcess.prototype, "lensSize", null); +__decorate([ + serialize() +], CircleOfConfusionPostProcess.prototype, "fStop", null); +__decorate([ + serialize() +], CircleOfConfusionPostProcess.prototype, "focusDistance", null); +__decorate([ + serialize() +], CircleOfConfusionPostProcess.prototype, "focalLength", null); +RegisterClass("BABYLON.CircleOfConfusionPostProcess", CircleOfConfusionPostProcess); + +/** + * + * This post-process allows the modification of rendered colors by using + * a 'look-up table' (LUT). This effect is also called Color Grading. + * + * The object needs to be provided an url to a texture containing the color + * look-up table: the texture must be 256 pixels wide and 16 pixels high. + * Use an image editing software to tweak the LUT to match your needs. + * + * For an example of a color LUT, see here: + * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png + * For explanations on color grading, see here: + * @see http://udn.epicgames.com/Three/ColorGrading.html + * + */ +class ColorCorrectionPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "ColorCorrectionPostProcess" string + */ + getClassName() { + return "ColorCorrectionPostProcess"; + } + constructor(name, colorTableUrl, options, camera, samplingMode, engine, reusable) { + super(name, "colorCorrection", null, ["colorTable"], options, camera, samplingMode, engine, reusable); + const scene = camera?.getScene() || null; + this._colorTableTexture = new Texture(colorTableUrl, scene, true, false, Texture.TRILINEAR_SAMPLINGMODE); + this._colorTableTexture.anisotropicFilteringLevel = 1; + this._colorTableTexture.wrapU = Texture.CLAMP_ADDRESSMODE; + this._colorTableTexture.wrapV = Texture.CLAMP_ADDRESSMODE; + this.colorTableUrl = colorTableUrl; + this.onApply = (effect) => { + effect.setTexture("colorTable", this._colorTableTexture); + }; + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => colorCorrection_fragment)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => colorCorrection_fragment$1)])); + } + super._gatherImports(useWebGPU, list); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new ColorCorrectionPostProcess(parsedPostProcess.name, parsedPostProcess.colorTableUrl, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], ColorCorrectionPostProcess.prototype, "colorTableUrl", void 0); +RegisterClass("BABYLON.ColorCorrectionPostProcess", ColorCorrectionPostProcess); + +/** + * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the + * input texture to perform effects such as edge detection or sharpening + * See http://en.wikipedia.org/wiki/Kernel_(image_processing) + */ +class ConvolutionPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "ConvolutionPostProcess" string + */ + getClassName() { + return "ConvolutionPostProcess"; + } + /** + * Creates a new instance ConvolutionPostProcess + * @param name The name of the effect. + * @param kernel Array of 9 values corresponding to the 3x3 kernel to be applied + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + */ + constructor(name, kernel, options, camera, samplingMode, engine, reusable, textureType = 0) { + super(name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType); + this.kernel = kernel; + this.onApply = (effect) => { + effect.setFloat2("screenSize", this.width, this.height); + effect.setArray("kernel", this.kernel); + }; + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => convolution_fragment)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => convolution_fragment$1)])); + } + super._gatherImports(useWebGPU, list); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new ConvolutionPostProcess(parsedPostProcess.name, parsedPostProcess.kernel, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType); + }, parsedPostProcess, scene, rootUrl); + } +} +// Statics +/** + * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing) + */ +ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1]; +/** + * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing) + */ +ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0]; +/** + * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing) + */ +ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1]; +/** + * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing) + */ +ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0]; +/** + * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing) + */ +ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2]; +/** + * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing) + */ +ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0]; +__decorate([ + serialize() +], ConvolutionPostProcess.prototype, "kernel", void 0); +RegisterClass("BABYLON.ConvolutionPostProcess", ConvolutionPostProcess); + +/** + * The DepthOfFieldBlurPostProcess applied a blur in a give direction. + * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels + * based on samples that have a large difference in distance than the center pixel. + * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf + */ +class DepthOfFieldBlurPostProcess extends BlurPostProcess { + /** + * Gets a string identifying the name of the class + * @returns "DepthOfFieldBlurPostProcess" string + */ + getClassName() { + return "DepthOfFieldBlurPostProcess"; + } + /** + * Creates a new instance DepthOfFieldBlurPostProcess + * @param name The name of the effect. + * @param _scene The scene the effect belongs to (not used, you can pass null) + * @param direction The direction the blur should be applied. + * @param kernel The size of the kernel used to blur. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring across edges + * @param imageToBlur The image to apply the blur to (default: Current rendered frame) + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA) + */ + constructor(name, _scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur = null, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = 0, blockCompilation = false, textureFormat = 5) { + super(name, direction, kernel, { + camera, + engine, + reusable, + textureType, + defines: `#define DOF 1\n`, + blockCompilation, + textureFormat, + ...options, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + samplingMode: (samplingMode = 2), + }); + this.externalTextureSamplerBinding = !!imageToBlur; + this.onApplyObservable.add((effect) => { + if (imageToBlur != null) { + effect.setTextureFromPostProcess("textureSampler", imageToBlur); + } + effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion); + }); + } +} +RegisterClass("BABYLON.DepthOfFieldBlurPostProcess", DepthOfFieldBlurPostProcess); + +/** + * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion. + */ +class DepthOfFieldMergePostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "DepthOfFieldMergePostProcess" string + */ + getClassName() { + return "DepthOfFieldMergePostProcess"; + } + /** + * Creates a new instance of DepthOfFieldMergePostProcess + * @param name The name of the effect. + * @param originalFromInput Post process which's input will be used for the merge. + * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel. + * @param _blurSteps Blur post processes from low to high which will be mixed with the original image. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(name, originalFromInput, circleOfConfusion, _blurSteps, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { + const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation; + const localOptions = { + samplers: ThinDepthOfFieldMergePostProcess.Samplers, + size: typeof options === "number" ? options : undefined, + camera, + samplingMode, + engine, + reusable, + textureType, + ...options, + blockCompilation: true, + }; + super(name, ThinDepthOfFieldMergePostProcess.FragmentUrl, { + effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinDepthOfFieldMergePostProcess(name, engine, localOptions) : undefined, + ...localOptions, + }); + this._blurSteps = _blurSteps; + this.externalTextureSamplerBinding = true; + this.onApplyObservable.add((effect) => { + effect.setTextureFromPostProcess("textureSampler", originalFromInput); + effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion); + _blurSteps.forEach((step, index) => { + effect.setTextureFromPostProcessOutput("blurStep" + (_blurSteps.length - index - 1), step); + }); + }); + if (!blockCompilationFinal) { + this.updateEffect(); + } + } + /** + * Updates the effect with the current post process compile time values and recompiles the shader. + * @param defines Define statements that should be added at the beginning of the shader. (default: null) + * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) + * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) + * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx + * @param onCompiled Called when the shader has been compiled. + * @param onError Called if there is an error when compiling a shader. + */ + updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError) { + if (!defines) { + defines = ""; + defines += "#define BLUR_LEVEL " + (this._blurSteps.length - 1) + "\n"; + } + super.updateEffect(defines, uniforms, samplers, indexParameters, onCompiled, onError); + } +} + +/** + * Specifies the level of max blur that should be applied when using the depth of field effect + */ +var DepthOfFieldEffectBlurLevel; +(function (DepthOfFieldEffectBlurLevel) { + /** + * Subtle blur + */ + DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low"; + /** + * Medium blur + */ + DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium"; + /** + * Large blur + */ + DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High"; +})(DepthOfFieldEffectBlurLevel || (DepthOfFieldEffectBlurLevel = {})); +/** + * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing. + */ +class DepthOfFieldEffect extends PostProcessRenderEffect { + /** + * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter) + */ + set focalLength(value) { + this._thinDepthOfFieldEffect.focalLength = value; + } + get focalLength() { + return this._thinDepthOfFieldEffect.focalLength; + } + /** + * F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop. (default: 1.4) + */ + set fStop(value) { + this._thinDepthOfFieldEffect.fStop = value; + } + get fStop() { + return this._thinDepthOfFieldEffect.fStop; + } + /** + * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000) + */ + set focusDistance(value) { + this._thinDepthOfFieldEffect.focusDistance = value; + } + get focusDistance() { + return this._thinDepthOfFieldEffect.focusDistance; + } + /** + * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diameter of the resulting aperture can be computed by lensSize/fStop. + */ + set lensSize(value) { + this._thinDepthOfFieldEffect.lensSize = value; + } + get lensSize() { + return this._thinDepthOfFieldEffect.lensSize; + } + /** + * Creates a new instance DepthOfFieldEffect + * @param sceneOrEngine The scene or engine the effect belongs to. + * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed. + * @param blurLevel + * @param pipelineTextureType The type of texture to be used when performing the post processing. + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + * @param depthNotNormalized If the depth from the depth texture is already normalized or if the normalization should be done at runtime in the shader (default: false) + */ + constructor(sceneOrEngine, depthTexture, blurLevel = 0 /* DepthOfFieldEffectBlurLevel.Low */, pipelineTextureType = 0, blockCompilation = false, depthNotNormalized = false) { + const engine = sceneOrEngine._renderForCamera ? sceneOrEngine.getEngine() : sceneOrEngine; + super(engine, "depth of field", () => { + return this._effects; + }, true); + /** + * @internal Internal post processes in depth of field effect + */ + this._effects = []; + this._thinDepthOfFieldEffect = new ThinDepthOfFieldEffect("Depth of Field", engine, blurLevel, false, blockCompilation); + // Use R-only formats if supported to store the circle of confusion values. + // This should be more space and bandwidth efficient than using RGBA. + const circleOfConfusionTextureFormat = engine.isWebGPU || engine.version > 1 ? 6 : 5; + // Circle of confusion value for each pixel is used to determine how much to blur that pixel + this._circleOfConfusion = new CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, { + size: 1, + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine, + textureType: pipelineTextureType, + blockCompilation, + depthNotNormalized, + effectWrapper: this._thinDepthOfFieldEffect._circleOfConfusion, + }, null); + // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur) + // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts + // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf + this._depthOfFieldBlurY = []; + this._depthOfFieldBlurX = []; + const blurCount = this._thinDepthOfFieldEffect._depthOfFieldBlurX.length; + for (let i = 0; i < blurCount; i++) { + const [thinBlurY, ratioY] = this._thinDepthOfFieldEffect._depthOfFieldBlurY[i]; + const blurY = new DepthOfFieldBlurPostProcess("vertical blur", null, thinBlurY.direction, thinBlurY.kernel, { + size: ratioY, + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine, + textureType: pipelineTextureType, + blockCompilation, + textureFormat: i == 0 ? circleOfConfusionTextureFormat : 5, + effectWrapper: thinBlurY, + }, null, this._circleOfConfusion, i == 0 ? this._circleOfConfusion : null); + blurY.autoClear = false; + const [thinBlurX, ratioX] = this._thinDepthOfFieldEffect._depthOfFieldBlurX[i]; + const blurX = new DepthOfFieldBlurPostProcess("horizontal blur", null, thinBlurX.direction, thinBlurX.kernel, { + size: ratioX, + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine, + textureType: pipelineTextureType, + blockCompilation, + effectWrapper: thinBlurX, + }, null, this._circleOfConfusion, null); + blurX.autoClear = false; + this._depthOfFieldBlurY.push(blurY); + this._depthOfFieldBlurX.push(blurX); + } + // Set all post processes on the effect. + this._effects = [this._circleOfConfusion]; + for (let i = 0; i < this._depthOfFieldBlurX.length; i++) { + this._effects.push(this._depthOfFieldBlurY[i]); + this._effects.push(this._depthOfFieldBlurX[i]); + } + // Merge blurred images with original image based on circleOfConfusion + this._dofMerge = new DepthOfFieldMergePostProcess("dofMerge", this._circleOfConfusion, this._circleOfConfusion, this._depthOfFieldBlurX, { + size: this._thinDepthOfFieldEffect._depthOfFieldBlurX[blurCount - 1][1], + samplingMode: Texture.BILINEAR_SAMPLINGMODE, + engine, + textureType: pipelineTextureType, + blockCompilation, + effectWrapper: this._thinDepthOfFieldEffect._dofMerge, + }, null); + this._dofMerge.autoClear = false; + this._effects.push(this._dofMerge); + } + /** + * Get the current class name of the current effect + * @returns "DepthOfFieldEffect" + */ + getClassName() { + return "DepthOfFieldEffect"; + } + /** + * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function. + */ + set depthTexture(value) { + this._circleOfConfusion.depthTexture = value; + } + /** + * Disposes each of the internal effects for a given camera. + * @param camera The camera to dispose the effect on. + */ + disposeEffects(camera) { + for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { + this._effects[effectIndex].dispose(camera); + } + } + /** + * @internal Internal + */ + _updateEffects() { + for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { + this._effects[effectIndex].updateEffect(); + } + } + /** + * Internal + * @returns if all the contained post processes are ready. + * @internal + */ + _isReady() { + return this._thinDepthOfFieldEffect.isReady(); + } +} + +/** + * DisplayPassPostProcess which produces an output the same as it's input + */ +class DisplayPassPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "DisplayPassPostProcess" string + */ + getClassName() { + return "DisplayPassPostProcess"; + } + /** + * Creates the DisplayPassPostProcess + * @param name The name of the effect. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + */ + constructor(name, options, camera, samplingMode, engine, reusable) { + super(name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable); + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => displayPass_fragment)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => displayPass_fragment$1)])); + } + super._gatherImports(useWebGPU, list); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new DisplayPassPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +RegisterClass("BABYLON.DisplayPassPostProcess", DisplayPassPostProcess); + +/** + * Applies a kernel filter to the image + */ +class FilterPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "FilterPostProcess" string + */ + getClassName() { + return "FilterPostProcess"; + } + /** + * + * @param name The name of the effect. + * @param kernelMatrix The matrix to be applied to the image + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + */ + constructor(name, kernelMatrix, options, camera, samplingMode, engine, reusable) { + super(name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable); + this.kernelMatrix = kernelMatrix; + this.onApply = (effect) => { + effect.setMatrix("kernelMatrix", this.kernelMatrix); + }; + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => filter_fragment)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => filter_fragment$1)])); + } + super._gatherImports(useWebGPU, list); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new FilterPostProcess(parsedPostProcess.name, parsedPostProcess.kernelMatrix, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serializeAsMatrix() +], FilterPostProcess.prototype, "kernelMatrix", void 0); +RegisterClass("BABYLON.FilterPostProcess", FilterPostProcess); + +/** + * The GrainPostProcess adds noise to the image at mid luminance levels + */ +class GrainPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "GrainPostProcess" string + */ + getClassName() { + return "GrainPostProcess"; + } + /** + * Creates a new instance of @see GrainPostProcess + * @param name The name of the effect. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(name, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { + super(name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation); + /** + * The intensity of the grain added (default: 30) + */ + this.intensity = 30; + /** + * If the grain should be randomized on every frame + */ + this.animated = false; + this.onApplyObservable.add((effect) => { + effect.setFloat("intensity", this.intensity); + effect.setFloat("animatedSeed", this.animated ? Math.random() + 1 : 1); + }); + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => grain_fragment)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => grain_fragment$1)])); + } + super._gatherImports(useWebGPU, list); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new GrainPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], GrainPostProcess.prototype, "intensity", void 0); +__decorate([ + serialize() +], GrainPostProcess.prototype, "animated", void 0); +RegisterClass("BABYLON.GrainPostProcess", GrainPostProcess); + +/** + * ImageProcessingPostProcess + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#imageprocessing + */ +class ImageProcessingPostProcess extends PostProcess { + /** + * Gets the image processing configuration used either in this material. + */ + get imageProcessingConfiguration() { + return this._imageProcessingConfiguration; + } + /** + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ + set imageProcessingConfiguration(value) { + // We are almost sure it is applied by post process as + // We are in the post process :-) + value.applyByPostProcess = true; + this._attachImageProcessingConfiguration(value); + } + /** + * Attaches a new image processing configuration to the PBR Material. + * @param configuration + * @param doNotBuild + */ + _attachImageProcessingConfiguration(configuration, doNotBuild = false) { + if (configuration === this._imageProcessingConfiguration) { + return; + } + // Detaches observer. + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + // Pick the scene configuration if needed. + if (!configuration) { + let scene = null; + const engine = this.getEngine(); + const camera = this.getCamera(); + if (camera) { + scene = camera.getScene(); + } + else if (engine && engine.scenes) { + const scenes = engine.scenes; + scene = scenes[scenes.length - 1]; + } + else { + scene = EngineStore.LastCreatedScene; + } + if (scene) { + this._imageProcessingConfiguration = scene.imageProcessingConfiguration; + } + else { + this._imageProcessingConfiguration = new ImageProcessingConfiguration(); + } + } + else { + this._imageProcessingConfiguration = configuration; + } + // Attaches observer. + if (this._imageProcessingConfiguration) { + this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { + this._updateParameters(); + }); + } + // Ensure the effect will be rebuilt. + if (!doNotBuild) { + this._updateParameters(); + } + } + /** + * If the post process is supported. + */ + get isSupported() { + const effect = this.getEffect(); + return !effect || effect.isSupported; + } + /** + * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true . + */ + get colorCurves() { + return this.imageProcessingConfiguration.colorCurves; + } + /** + * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true . + */ + set colorCurves(value) { + this.imageProcessingConfiguration.colorCurves = value; + } + /** + * Gets whether the color curves effect is enabled. + */ + get colorCurvesEnabled() { + return this.imageProcessingConfiguration.colorCurvesEnabled; + } + /** + * Sets whether the color curves effect is enabled. + */ + set colorCurvesEnabled(value) { + this.imageProcessingConfiguration.colorCurvesEnabled = value; + } + /** + * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. + */ + get colorGradingTexture() { + return this.imageProcessingConfiguration.colorGradingTexture; + } + /** + * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. + */ + set colorGradingTexture(value) { + this.imageProcessingConfiguration.colorGradingTexture = value; + } + /** + * Gets whether the color grading effect is enabled. + */ + get colorGradingEnabled() { + return this.imageProcessingConfiguration.colorGradingEnabled; + } + /** + * Gets whether the color grading effect is enabled. + */ + set colorGradingEnabled(value) { + this.imageProcessingConfiguration.colorGradingEnabled = value; + } + /** + * Gets exposure used in the effect. + */ + get exposure() { + return this.imageProcessingConfiguration.exposure; + } + /** + * Sets exposure used in the effect. + */ + set exposure(value) { + this.imageProcessingConfiguration.exposure = value; + } + /** + * Gets whether tonemapping is enabled or not. + */ + get toneMappingEnabled() { + return this._imageProcessingConfiguration.toneMappingEnabled; + } + /** + * Sets whether tonemapping is enabled or not + */ + set toneMappingEnabled(value) { + this._imageProcessingConfiguration.toneMappingEnabled = value; + } + /** + * Gets the type of tone mapping effect. + */ + get toneMappingType() { + return this._imageProcessingConfiguration.toneMappingType; + } + /** + * Sets the type of tone mapping effect. + */ + set toneMappingType(value) { + this._imageProcessingConfiguration.toneMappingType = value; + } + /** + * Gets contrast used in the effect. + */ + get contrast() { + return this.imageProcessingConfiguration.contrast; + } + /** + * Sets contrast used in the effect. + */ + set contrast(value) { + this.imageProcessingConfiguration.contrast = value; + } + /** + * Gets Vignette stretch size. + */ + get vignetteStretch() { + return this.imageProcessingConfiguration.vignetteStretch; + } + /** + * Sets Vignette stretch size. + */ + set vignetteStretch(value) { + this.imageProcessingConfiguration.vignetteStretch = value; + } + /** + * Gets Vignette center X Offset. + * @deprecated use vignetteCenterX instead + */ + get vignetteCentreX() { + return this.imageProcessingConfiguration.vignetteCenterX; + } + /** + * Sets Vignette center X Offset. + * @deprecated use vignetteCenterX instead + */ + set vignetteCentreX(value) { + this.imageProcessingConfiguration.vignetteCenterX = value; + } + /** + * Gets Vignette center Y Offset. + * @deprecated use vignetteCenterY instead + */ + get vignetteCentreY() { + return this.imageProcessingConfiguration.vignetteCenterY; + } + /** + * Sets Vignette center Y Offset. + * @deprecated use vignetteCenterY instead + */ + set vignetteCentreY(value) { + this.imageProcessingConfiguration.vignetteCenterY = value; + } + /** + * Vignette center Y Offset. + */ + get vignetteCenterY() { + return this.imageProcessingConfiguration.vignetteCenterY; + } + set vignetteCenterY(value) { + this.imageProcessingConfiguration.vignetteCenterY = value; + } + /** + * Vignette center X Offset. + */ + get vignetteCenterX() { + return this.imageProcessingConfiguration.vignetteCenterX; + } + set vignetteCenterX(value) { + this.imageProcessingConfiguration.vignetteCenterX = value; + } + /** + * Gets Vignette weight or intensity of the vignette effect. + */ + get vignetteWeight() { + return this.imageProcessingConfiguration.vignetteWeight; + } + /** + * Sets Vignette weight or intensity of the vignette effect. + */ + set vignetteWeight(value) { + this.imageProcessingConfiguration.vignetteWeight = value; + } + /** + * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) + * if vignetteEnabled is set to true. + */ + get vignetteColor() { + return this.imageProcessingConfiguration.vignetteColor; + } + /** + * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) + * if vignetteEnabled is set to true. + */ + set vignetteColor(value) { + this.imageProcessingConfiguration.vignetteColor = value; + } + /** + * Gets Camera field of view used by the Vignette effect. + */ + get vignetteCameraFov() { + return this.imageProcessingConfiguration.vignetteCameraFov; + } + /** + * Sets Camera field of view used by the Vignette effect. + */ + set vignetteCameraFov(value) { + this.imageProcessingConfiguration.vignetteCameraFov = value; + } + /** + * Gets the vignette blend mode allowing different kind of effect. + */ + get vignetteBlendMode() { + return this.imageProcessingConfiguration.vignetteBlendMode; + } + /** + * Sets the vignette blend mode allowing different kind of effect. + */ + set vignetteBlendMode(value) { + this.imageProcessingConfiguration.vignetteBlendMode = value; + } + /** + * Gets whether the vignette effect is enabled. + */ + get vignetteEnabled() { + return this.imageProcessingConfiguration.vignetteEnabled; + } + /** + * Sets whether the vignette effect is enabled. + */ + set vignetteEnabled(value) { + this.imageProcessingConfiguration.vignetteEnabled = value; + } + /** + * Gets intensity of the dithering effect. + */ + get ditheringIntensity() { + return this.imageProcessingConfiguration.ditheringIntensity; + } + /** + * Sets intensity of the dithering effect. + */ + set ditheringIntensity(value) { + this.imageProcessingConfiguration.ditheringIntensity = value; + } + /** + * Gets whether the dithering effect is enabled. + */ + get ditheringEnabled() { + return this.imageProcessingConfiguration.ditheringEnabled; + } + /** + * Sets whether the dithering effect is enabled. + */ + set ditheringEnabled(value) { + this.imageProcessingConfiguration.ditheringEnabled = value; + } + /** + * Gets whether the input of the processing is in Gamma or Linear Space. + */ + get fromLinearSpace() { + return this._fromLinearSpace; + } + /** + * Sets whether the input of the processing is in Gamma or Linear Space. + */ + set fromLinearSpace(value) { + if (this._fromLinearSpace === value) { + return; + } + this._fromLinearSpace = value; + this._updateParameters(); + } + constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, imageProcessingConfiguration) { + super(name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true); + this._fromLinearSpace = true; + /** + * Defines cache preventing GC. + */ + this._defines = { + IMAGEPROCESSING: false, + VIGNETTE: false, + VIGNETTEBLENDMODEMULTIPLY: false, + VIGNETTEBLENDMODEOPAQUE: false, + TONEMAPPING: 0, + CONTRAST: false, + COLORCURVES: false, + COLORGRADING: false, + COLORGRADING3D: false, + FROMLINEARSPACE: false, + SAMPLER3DGREENDEPTH: false, + SAMPLER3DBGRMAP: false, + DITHER: false, + IMAGEPROCESSINGPOSTPROCESS: false, + EXPOSURE: false, + SKIPFINALCOLORCLAMP: false, + }; + // Setup the configuration as forced by the constructor. This would then not force the + // scene materials output in linear space and let untouched the default forward pass. + if (imageProcessingConfiguration) { + imageProcessingConfiguration.applyByPostProcess = true; + this._attachImageProcessingConfiguration(imageProcessingConfiguration, true); + // This will cause the shader to be compiled + this._updateParameters(); + } + // Setup the default processing configuration to the scene. + else { + this._attachImageProcessingConfiguration(null, true); + this.imageProcessingConfiguration.applyByPostProcess = true; + } + this.onApply = (effect) => { + this.imageProcessingConfiguration.bind(effect, this.aspectRatio); + }; + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.resolve().then(() => imageProcessing_fragment$1)); + } + else { + list.push(Promise.resolve().then(() => imageProcessing_fragment)); + } + super._gatherImports(useWebGPU, list); + } + /** + * "ImageProcessingPostProcess" + * @returns "ImageProcessingPostProcess" + */ + getClassName() { + return "ImageProcessingPostProcess"; + } + /** + * @internal + */ + _updateParameters() { + this._defines.FROMLINEARSPACE = this._fromLinearSpace; + this.imageProcessingConfiguration.prepareDefines(this._defines, true); + let defines = ""; + for (const prop in this._defines) { + const value = this._defines[prop]; + const type = typeof value; + switch (type) { + case "number": + case "string": + defines += `#define ${prop} ${value};\n`; + break; + default: + if (value) { + defines += `#define ${prop};\n`; + } + break; + } + } + const samplers = ["textureSampler"]; + const uniforms = ["scale"]; + if (ImageProcessingConfiguration) { + ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines); + ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines); + } + this.updateEffect(defines, uniforms, samplers); + } + dispose(camera) { + super.dispose(camera); + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + if (this._imageProcessingConfiguration) { + this.imageProcessingConfiguration.applyByPostProcess = false; + } + } +} +__decorate([ + serialize() +], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0); + +// Do not edit. +const name$31 = "mrtFragmentDeclaration"; +const shader$30 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +layout(location=0) out vec4 glFragData[{X}]; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$31]) { + ShaderStore.IncludesShadersStore[name$31] = shader$30; +} + +// Do not edit. +const name$30 = "geometryPixelShader"; +const shader$2$ = `#extension GL_EXT_draw_buffers : require +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +precision highp float; +#ifdef BUMP +varying mat4 vWorldView;varying vec3 vNormalW; +#else +varying vec3 vNormalV; +#endif +varying vec4 vViewPos; +#if defined(POSITION) || defined(BUMP) +varying vec3 vPositionW; +#endif +#if defined(VELOCITY) || defined(VELOCITY_LINEAR) +varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#ifdef NEED_UV +varying vec2 vUV; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#if defined(REFLECTIVITY) +#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; +#endif +#ifdef ALBEDOTEXTURE +varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; +#endif +#ifdef REFLECTIVITYCOLOR +uniform vec3 reflectivityColor; +#endif +#ifdef ALBEDOCOLOR +uniform vec3 albedoColor; +#endif +#ifdef METALLIC +uniform float metallic; +#endif +#if defined(ROUGHNESS) || defined(GLOSSINESS) +uniform float glossiness; +#endif +#endif +#if defined(ALPHATEST) && defined(NEED_UV) +uniform sampler2D diffuseSampler; +#endif +#include +#include[SCENE_MRT_COUNT] +#include +#include +#include +void main() { +#include +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +vec3 normalOutput; +#ifdef BUMP +vec3 normalW=normalize(vNormalW); +#include +#ifdef NORMAL_WORLDSPACE +normalOutput=normalW; +#else +normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); +#endif +#else +normalOutput=normalize(vNormalV); +#endif +#ifdef ENCODE_NORMAL +normalOutput=normalOutput*0.5+0.5; +#endif +#ifdef DEPTH +gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); +#endif +#ifdef NORMAL +gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); +#endif +#ifdef SCREENSPACE_DEPTH +gl_FragData[SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,1.0); +#endif +#ifdef POSITION +gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); +#endif +#ifdef VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); +#endif +#ifdef VELOCITY_LINEAR +vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w) - +(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,1.0); +#endif +#ifdef REFLECTIVITY +vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); +#ifdef METALLICWORKFLOW +float metal=1.0;float roughness=1.0; +#ifdef ORMTEXTURE +metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; +#endif +#ifdef METALLIC +metal*=metallic; +#endif +#ifdef ROUGHNESS +roughness*=(1.0-glossiness); +#endif +reflectivity.a-=roughness;vec3 color=vec3(1.0); +#ifdef ALBEDOTEXTURE +color=texture2D(albedoSampler,vAlbedoUV).rgb; +#ifdef GAMMAALBEDO +color=toLinearSpace(color); +#endif +#endif +#ifdef ALBEDOCOLOR +color*=albedoColor.xyz; +#endif +reflectivity.rgb=mix(vec3(0.04),color,metal); +#else +#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +reflectivity=texture2D(reflectivitySampler,vReflectivityUV); +#ifdef GAMMAREFLECTIVITYTEXTURE +reflectivity.rgb=toLinearSpace(reflectivity.rgb); +#endif +#else +#ifdef REFLECTIVITYCOLOR +reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; +#endif +#endif +#ifdef GLOSSINESSS +reflectivity.a*=glossiness; +#endif +#endif +gl_FragData[REFLECTIVITY_INDEX]=reflectivity; +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$30]) { + ShaderStore.ShadersStore[name$30] = shader$2$; +} +/** @internal */ +const geometryPixelShader = { name: name$30, shader: shader$2$ }; + +const geometry_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + geometryPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2$ = "geometryVertexDeclaration"; +const shader$2_ = `uniform mat4 viewProjection;uniform mat4 view;`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$2$]) { + ShaderStore.IncludesShadersStore[name$2$] = shader$2_; +} + +// Do not edit. +const name$2_ = "geometryUboDeclaration"; +const shader$2Z = `#include +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$2_]) { + ShaderStore.IncludesShadersStore[name$2_] = shader$2Z; +} + +// Do not edit. +const name$2Z = "geometryVertexShader"; +const shader$2Y = `precision highp float; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include<__decl__geometryVertex> +#include +attribute vec3 position;attribute vec3 normal; +#ifdef NEED_UV +varying vec2 vUV; +#ifdef ALPHATEST +uniform mat4 diffuseMatrix; +#endif +#ifdef BUMP +uniform mat4 bumpMatrix;varying vec2 vBumpUV; +#endif +#ifdef REFLECTIVITY +uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#ifdef BUMP +varying mat4 vWorldView; +#endif +#ifdef BUMP +varying vec3 vNormalW; +#else +varying vec3 vNormalV; +#endif +varying vec4 vViewPos; +#if defined(POSITION) || defined(BUMP) +varying vec3 vPositionW; +#endif +#if defined(VELOCITY) || defined(VELOCITY_LINEAR) +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position;vec3 normalUpdated=normal; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef UV2 +vec2 uv2Updated=uv2; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); +#ifdef BUMP +vWorldView=view*finalWorld;mat3 normalWorld=mat3(finalWorld);vNormalW=normalize(normalWorld*normalUpdated); +#else +#ifdef NORMAL_WORLDSPACE +vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0))); +#else +vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); +#endif +#endif +vViewPos=view*worldPos; +#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +#if defined(POSITION) || defined(BUMP) +vPositionW=worldPos.xyz/worldPos.w; +#endif +gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#include +#ifdef NEED_UV +#ifdef UV1 +#if defined(ALPHATEST) && defined(ALPHATEST_UV1) +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#else +vUV=uvUpdated; +#endif +#ifdef BUMP_UV1 +vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef REFLECTIVITY_UV1 +vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef ALBEDO_UV1 +vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#endif +#ifdef UV2 +#if defined(ALPHATEST) && defined(ALPHATEST_UV2) +vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); +#else +vUV=uv2Updated; +#endif +#ifdef BUMP_UV2 +vBumpUV=vec2(bumpMatrix*vec4(uv2Updated,1.0,0.0)); +#endif +#ifdef REFLECTIVITY_UV2 +vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2Updated,1.0,0.0)); +#endif +#ifdef ALBEDO_UV2 +vAlbedoUV=vec2(albedoMatrix*vec4(uv2Updated,1.0,0.0)); +#endif +#endif +#endif +#include +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2Z]) { + ShaderStore.ShadersStore[name$2Z] = shader$2Y; +} +/** @internal */ +const geometryVertexShader = { name: name$2Z, shader: shader$2Y }; + +const geometry_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + geometryVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +/** list the uniforms used by the geometry renderer */ +const uniforms = [ + "world", + "mBones", + "viewProjection", + "diffuseMatrix", + "view", + "previousWorld", + "previousViewProjection", + "mPreviousBones", + "bumpMatrix", + "reflectivityMatrix", + "albedoMatrix", + "reflectivityColor", + "albedoColor", + "metallic", + "glossiness", + "vTangentSpaceParams", + "vBumpInfos", + "morphTargetInfluences", + "morphTargetCount", + "morphTargetTextureInfo", + "morphTargetTextureIndices", + "boneTextureWidth", +]; +addClipPlaneUniforms(uniforms); +/** + * This renderer is helpful to fill one of the render target with a geometry buffer. + */ +class GeometryBufferRenderer { + /** + * Gets a boolean indicating if normals are encoded in the [0,1] range in the render target. If true, you should do `normal = normal_rt * 2.0 - 1.0` to get the right normal + */ + get normalsAreUnsigned() { + return this._normalsAreUnsigned; + } + /** + * @internal + * Sets up internal structures to share outputs with PrePassRenderer + * This method should only be called by the PrePassRenderer itself + */ + _linkPrePassRenderer(prePassRenderer) { + this._linkedWithPrePass = true; + this._prePassRenderer = prePassRenderer; + if (this._multiRenderTarget) { + // prevents clearing of the RT since it's done by prepass + this._multiRenderTarget.onClearObservable.clear(); + this._multiRenderTarget.onClearObservable.add(() => { + // pass + }); + } + } + /** + * @internal + * Separates internal structures from PrePassRenderer so the geometry buffer can now operate by itself. + * This method should only be called by the PrePassRenderer itself + */ + _unlinkPrePassRenderer() { + this._linkedWithPrePass = false; + this._createRenderTargets(); + } + /** + * @internal + * Resets the geometry buffer layout + */ + _resetLayout() { + this._enableDepth = true; + this._enableNormal = true; + this._enablePosition = false; + this._enableReflectivity = false; + this._enableVelocity = false; + this._enableVelocityLinear = false; + this._enableScreenspaceDepth = false; + this._attachmentsFromPrePass = []; + } + /** + * @internal + * Replaces a texture in the geometry buffer renderer + * Useful when linking textures of the prepass renderer + */ + _forceTextureType(geometryBufferType, index) { + if (geometryBufferType === GeometryBufferRenderer.POSITION_TEXTURE_TYPE) { + this._positionIndex = index; + this._enablePosition = true; + } + else if (geometryBufferType === GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE) { + this._velocityIndex = index; + this._enableVelocity = true; + } + else if (geometryBufferType === GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE) { + this._velocityLinearIndex = index; + this._enableVelocityLinear = true; + } + else if (geometryBufferType === GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE) { + this._reflectivityIndex = index; + this._enableReflectivity = true; + } + else if (geometryBufferType === GeometryBufferRenderer.DEPTH_TEXTURE_TYPE) { + this._depthIndex = index; + this._enableDepth = true; + } + else if (geometryBufferType === GeometryBufferRenderer.NORMAL_TEXTURE_TYPE) { + this._normalIndex = index; + this._enableNormal = true; + } + else if (geometryBufferType === GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE) { + this._screenspaceDepthIndex = index; + this._enableScreenspaceDepth = true; + } + } + /** + * @internal + * Sets texture attachments + * Useful when linking textures of the prepass renderer + */ + _setAttachments(attachments) { + this._attachmentsFromPrePass = attachments; + } + /** + * @internal + * Replaces the first texture which is hard coded as a depth texture in the geometry buffer + * Useful when linking textures of the prepass renderer + */ + _linkInternalTexture(internalTexture) { + this._multiRenderTarget.setInternalTexture(internalTexture, 0, false); + } + /** + * Gets the render list (meshes to be rendered) used in the G buffer. + */ + get renderList() { + return this._multiRenderTarget.renderList; + } + /** + * Set the render list (meshes to be rendered) used in the G buffer. + */ + set renderList(meshes) { + this._multiRenderTarget.renderList = meshes; + } + /** + * Gets whether or not G buffer are supported by the running hardware. + * This requires draw buffer supports + */ + get isSupported() { + return this._multiRenderTarget.isSupported; + } + /** + * Returns the index of the given texture type in the G-Buffer textures array + * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX + * @returns the index of the given texture type in the G-Buffer textures array + */ + getTextureIndex(textureType) { + switch (textureType) { + case GeometryBufferRenderer.POSITION_TEXTURE_TYPE: + return this._positionIndex; + case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: + return this._velocityIndex; + case GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE: + return this._velocityLinearIndex; + case GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE: + return this._reflectivityIndex; + case GeometryBufferRenderer.DEPTH_TEXTURE_TYPE: + return this._depthIndex; + case GeometryBufferRenderer.NORMAL_TEXTURE_TYPE: + return this._normalIndex; + case GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE: + return this._screenspaceDepthIndex; + default: + return -1; + } + } + /** + * @returns a boolean indicating if object's depths are enabled for the G buffer. + */ + get enableDepth() { + return this._enableDepth; + } + /** + * Sets whether or not object's depths are enabled for the G buffer. + */ + set enableDepth(enable) { + this._enableDepth = enable; + if (!this._linkedWithPrePass) { + this.dispose(); + this._createRenderTargets(); + } + } + /** + * @returns a boolean indicating if object's normals are enabled for the G buffer. + */ + get enableNormal() { + return this._enableNormal; + } + /** + * Sets whether or not object's normals are enabled for the G buffer. + */ + set enableNormal(enable) { + this._enableNormal = enable; + if (!this._linkedWithPrePass) { + this.dispose(); + this._createRenderTargets(); + } + } + /** + * @returns a boolean indicating if objects positions are enabled for the G buffer. + */ + get enablePosition() { + return this._enablePosition; + } + /** + * Sets whether or not objects positions are enabled for the G buffer. + */ + set enablePosition(enable) { + this._enablePosition = enable; + // PrePass handles index and texture links + if (!this._linkedWithPrePass) { + this.dispose(); + this._createRenderTargets(); + } + } + /** + * @returns a boolean indicating if objects velocities are enabled for the G buffer. + */ + get enableVelocity() { + return this._enableVelocity; + } + /** + * Sets whether or not objects velocities are enabled for the G buffer. + */ + set enableVelocity(enable) { + this._enableVelocity = enable; + if (!enable) { + this._previousTransformationMatrices = {}; + } + if (!this._linkedWithPrePass) { + this.dispose(); + this._createRenderTargets(); + } + this._scene.needsPreviousWorldMatrices = enable; + } + /** + * @returns a boolean indicating if object's linear velocities are enabled for the G buffer. + */ + get enableVelocityLinear() { + return this._enableVelocityLinear; + } + /** + * Sets whether or not object's linear velocities are enabled for the G buffer. + */ + set enableVelocityLinear(enable) { + this._enableVelocityLinear = enable; + if (!this._linkedWithPrePass) { + this.dispose(); + this._createRenderTargets(); + } + } + /** + * Gets a boolean indicating if objects reflectivity are enabled in the G buffer. + */ + get enableReflectivity() { + return this._enableReflectivity; + } + /** + * Sets whether or not objects reflectivity are enabled for the G buffer. + * For Metallic-Roughness workflow with ORM texture, we assume that ORM texture is defined according to the default layout: + * pbr.useRoughnessFromMetallicTextureAlpha = false; + * pbr.useRoughnessFromMetallicTextureGreen = true; + * pbr.useMetallnessFromMetallicTextureBlue = true; + */ + set enableReflectivity(enable) { + this._enableReflectivity = enable; + if (!this._linkedWithPrePass) { + this.dispose(); + this._createRenderTargets(); + } + } + /** + * Sets whether or not objects screenspace depth are enabled for the G buffer. + */ + get enableScreenspaceDepth() { + return this._enableScreenspaceDepth; + } + set enableScreenspaceDepth(enable) { + this._enableScreenspaceDepth = enable; + if (!this._linkedWithPrePass) { + this.dispose(); + this._createRenderTargets(); + } + } + /** + * Gets the scene associated with the buffer. + */ + get scene() { + return this._scene; + } + /** + * Gets the ratio used by the buffer during its creation. + * How big is the buffer related to the main canvas. + */ + get ratio() { + return typeof this._ratioOrDimensions === "object" ? 1 : this._ratioOrDimensions; + } + /** + * Gets the shader language used in this material. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Creates a new G Buffer for the scene + * @param scene The scene the buffer belongs to + * @param ratioOrDimensions How big is the buffer related to the main canvas (default: 1). You can also directly pass a width and height for the generated textures + * @param depthFormat Format of the depth texture (default: 15) + * @param textureTypesAndFormats The types and formats of textures to create as render targets. If not provided, all textures will be RGBA and float or half float, depending on the engine capabilities. + */ + constructor(scene, ratioOrDimensions = 1, depthFormat = 15, textureTypesAndFormats) { + /** + * Dictionary used to store the previous transformation matrices of each rendered mesh + * in order to compute objects velocities when enableVelocity is set to "true" + * @internal + */ + this._previousTransformationMatrices = {}; + /** + * Dictionary used to store the previous bones transformation matrices of each rendered mesh + * in order to compute objects velocities when enableVelocity is set to "true" + * @internal + */ + this._previousBonesTransformationMatrices = {}; + /** + * Array used to store the ignored skinned meshes while computing velocity map (typically used by the motion blur post-process). + * Avoids computing bones velocities and computes only mesh's velocity itself (position, rotation, scaling). + */ + this.excludedSkinnedMeshesFromVelocity = []; + /** Gets or sets a boolean indicating if transparent meshes should be rendered */ + this.renderTransparentMeshes = true; + /** + * Gets or sets a boolean indicating if normals should be generated in world space (default: false, meaning normals are generated in view space) + */ + this.generateNormalsInWorldSpace = false; + this._normalsAreUnsigned = false; + this._resizeObserver = null; + this._enableDepth = true; + this._enableNormal = true; + this._enablePosition = false; + this._enableVelocity = false; + this._enableVelocityLinear = false; + this._enableReflectivity = false; + this._enableScreenspaceDepth = false; + this._clearColor = new Color4(0, 0, 0, 0); + this._clearDepthColor = new Color4(1e8, 0, 0, 1); // "infinity" value - depth in the depth texture is view.z, not a 0..1 value! + this._positionIndex = -1; + this._velocityIndex = -1; + this._velocityLinearIndex = -1; + this._reflectivityIndex = -1; + this._depthIndex = -1; + this._normalIndex = -1; + this._screenspaceDepthIndex = -1; + this._linkedWithPrePass = false; + /** + * If set to true (default: false), the depth texture will be cleared with the depth value corresponding to the far plane (1 in normal mode, 0 in reverse depth buffer mode) + * If set to false, the depth texture is always cleared with 0. + */ + this.useSpecificClearForDepthTexture = false; + /** Shader language used by the material */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._shadersLoaded = false; + this._scene = scene; + this._ratioOrDimensions = ratioOrDimensions; + this._useUbo = scene.getEngine().supportsUniformBuffers; + this._depthFormat = depthFormat; + this._textureTypesAndFormats = textureTypesAndFormats || {}; + this._initShaderSourceAsync(); + GeometryBufferRenderer._SceneComponentInitialization(this._scene); + // Render target + this._createRenderTargets(); + } + async _initShaderSourceAsync() { + const engine = this._scene.getEngine(); + if (engine.isWebGPU && !GeometryBufferRenderer.ForceGLSL) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + await Promise.all([Promise.resolve().then(() => geometry_vertex), Promise.resolve().then(() => geometry_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => geometry_vertex$1), Promise.resolve().then(() => geometry_fragment$1)]); + } + this._shadersLoaded = true; + } + /** + * Checks whether everything is ready to render a submesh to the G buffer. + * @param subMesh the submesh to check readiness for + * @param useInstances is the mesh drawn using instance or not + * @returns true if ready otherwise false + */ + isReady(subMesh, useInstances) { + if (!this._shadersLoaded) { + return false; + } + const material = subMesh.getMaterial(); + if (material && material.disableDepthWrite) { + return false; + } + const defines = []; + const attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind]; + const mesh = subMesh.getMesh(); + let uv1 = false; + let uv2 = false; + const color = false; + if (material) { + let needUv = false; + // Alpha test + if (material.needAlphaTestingForMesh(mesh) && material.getAlphaTestTexture()) { + defines.push("#define ALPHATEST"); + defines.push(`#define ALPHATEST_UV${material.getAlphaTestTexture().coordinatesIndex + 1}`); + needUv = true; + } + // Normal map texture + if ((material.bumpTexture || material.normalTexture) && MaterialFlags.BumpTextureEnabled) { + const texture = material.bumpTexture || material.normalTexture; + defines.push("#define BUMP"); + defines.push(`#define BUMP_UV${texture.coordinatesIndex + 1}`); + needUv = true; + } + if (this._enableReflectivity) { + let metallicWorkflow = false; + // for PBR materials: cf. https://doc.babylonjs.com/features/featuresDeepDive/materials/using/masterPBR + if (material.getClassName() === "PBRMetallicRoughnessMaterial") { + // if it is a PBR material in MetallicRoughness Mode: + if (material.metallicRoughnessTexture) { + defines.push("#define ORMTEXTURE"); + defines.push(`#define REFLECTIVITY_UV${material.metallicRoughnessTexture.coordinatesIndex + 1}`); + defines.push("#define METALLICWORKFLOW"); + needUv = true; + metallicWorkflow = true; + } + // null or undefined + if (material.metallic != null) { + defines.push("#define METALLIC"); + defines.push("#define METALLICWORKFLOW"); + metallicWorkflow = true; + } + // null or undefined + if (material.roughness != null) { + defines.push("#define ROUGHNESS"); + defines.push("#define METALLICWORKFLOW"); + metallicWorkflow = true; + } + if (metallicWorkflow) { + if (material.baseTexture) { + defines.push("#define ALBEDOTEXTURE"); + defines.push(`#define ALBEDO_UV${material.baseTexture.coordinatesIndex + 1}`); + if (material.baseTexture.gammaSpace) { + defines.push("#define GAMMAALBEDO"); + } + needUv = true; + } + if (material.baseColor) { + defines.push("#define ALBEDOCOLOR"); + } + } + } + else if (material.getClassName() === "PBRSpecularGlossinessMaterial") { + // if it is a PBR material in Specular/Glossiness Mode: + if (material.specularGlossinessTexture) { + defines.push("#define SPECULARGLOSSINESSTEXTURE"); + defines.push(`#define REFLECTIVITY_UV${material.specularGlossinessTexture.coordinatesIndex + 1}`); + needUv = true; + if (material.specularGlossinessTexture.gammaSpace) { + defines.push("#define GAMMAREFLECTIVITYTEXTURE"); + } + } + else { + if (material.specularColor) { + defines.push("#define REFLECTIVITYCOLOR"); + } + } + // null or undefined + if (material.glossiness != null) { + defines.push("#define GLOSSINESS"); + } + } + else if (material.getClassName() === "PBRMaterial") { + // if it is the bigger PBRMaterial + if (material.metallicTexture) { + defines.push("#define ORMTEXTURE"); + defines.push(`#define REFLECTIVITY_UV${material.metallicTexture.coordinatesIndex + 1}`); + defines.push("#define METALLICWORKFLOW"); + needUv = true; + metallicWorkflow = true; + } + // null or undefined + if (material.metallic != null) { + defines.push("#define METALLIC"); + defines.push("#define METALLICWORKFLOW"); + metallicWorkflow = true; + } + // null or undefined + if (material.roughness != null) { + defines.push("#define ROUGHNESS"); + defines.push("#define METALLICWORKFLOW"); + metallicWorkflow = true; + } + if (metallicWorkflow) { + if (material.albedoTexture) { + defines.push("#define ALBEDOTEXTURE"); + defines.push(`#define ALBEDO_UV${material.albedoTexture.coordinatesIndex + 1}`); + if (material.albedoTexture.gammaSpace) { + defines.push("#define GAMMAALBEDO"); + } + needUv = true; + } + if (material.albedoColor) { + defines.push("#define ALBEDOCOLOR"); + } + } + else { + // SpecularGlossiness Model + if (material.reflectivityTexture) { + defines.push("#define SPECULARGLOSSINESSTEXTURE"); + defines.push(`#define REFLECTIVITY_UV${material.reflectivityTexture.coordinatesIndex + 1}`); + if (material.reflectivityTexture.gammaSpace) { + defines.push("#define GAMMAREFLECTIVITYTEXTURE"); + } + needUv = true; + } + else if (material.reflectivityColor) { + defines.push("#define REFLECTIVITYCOLOR"); + } + // null or undefined + if (material.microSurface != null) { + defines.push("#define GLOSSINESS"); + } + } + } + else if (material.getClassName() === "StandardMaterial") { + // if StandardMaterial: + if (material.specularTexture) { + defines.push("#define REFLECTIVITYTEXTURE"); + defines.push(`#define REFLECTIVITY_UV${material.specularTexture.coordinatesIndex + 1}`); + if (material.specularTexture.gammaSpace) { + defines.push("#define GAMMAREFLECTIVITYTEXTURE"); + } + needUv = true; + } + if (material.specularColor) { + defines.push("#define REFLECTIVITYCOLOR"); + } + } + } + if (needUv) { + defines.push("#define NEED_UV"); + if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { + attribs.push(VertexBuffer.UVKind); + defines.push("#define UV1"); + uv1 = true; + } + if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) { + attribs.push(VertexBuffer.UV2Kind); + defines.push("#define UV2"); + uv2 = true; + } + } + } + // Buffers + if (this._enableDepth) { + defines.push("#define DEPTH"); + defines.push("#define DEPTH_INDEX " + this._depthIndex); + } + if (this._enableNormal) { + defines.push("#define NORMAL"); + defines.push("#define NORMAL_INDEX " + this._normalIndex); + } + if (this._enablePosition) { + defines.push("#define POSITION"); + defines.push("#define POSITION_INDEX " + this._positionIndex); + } + if (this._enableVelocity) { + defines.push("#define VELOCITY"); + defines.push("#define VELOCITY_INDEX " + this._velocityIndex); + if (this.excludedSkinnedMeshesFromVelocity.indexOf(mesh) === -1) { + defines.push("#define BONES_VELOCITY_ENABLED"); + } + } + if (this._enableVelocityLinear) { + defines.push("#define VELOCITY_LINEAR"); + defines.push("#define VELOCITY_LINEAR_INDEX " + this._velocityLinearIndex); + if (this.excludedSkinnedMeshesFromVelocity.indexOf(mesh) === -1) { + defines.push("#define BONES_VELOCITY_ENABLED"); + } + } + if (this._enableReflectivity) { + defines.push("#define REFLECTIVITY"); + defines.push("#define REFLECTIVITY_INDEX " + this._reflectivityIndex); + } + if (this._enableScreenspaceDepth) { + if (this._screenspaceDepthIndex !== -1) { + defines.push("#define SCREENSPACE_DEPTH_INDEX " + this._screenspaceDepthIndex); + defines.push("#define SCREENSPACE_DEPTH"); + } + } + if (this.generateNormalsInWorldSpace) { + defines.push("#define NORMAL_WORLDSPACE"); + } + if (this._normalsAreUnsigned) { + defines.push("#define ENCODE_NORMAL"); + } + // Bones + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + attribs.push(VertexBuffer.MatricesIndicesKind); + attribs.push(VertexBuffer.MatricesWeightsKind); + if (mesh.numBoneInfluencers > 4) { + attribs.push(VertexBuffer.MatricesIndicesExtraKind); + attribs.push(VertexBuffer.MatricesWeightsExtraKind); + } + defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); + defines.push("#define BONETEXTURE " + mesh.skeleton.isUsingTextureForMatrices); + defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1)); + } + else { + defines.push("#define NUM_BONE_INFLUENCERS 0"); + defines.push("#define BONETEXTURE false"); + defines.push("#define BonesPerMesh 0"); + } + // Morph targets + const numMorphInfluencers = mesh.morphTargetManager + ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph + true, // useNormalMorph + false, // useTangentMorph + uv1, // useUVMorph + uv2, // useUV2Morph + color // useColorMorph + ) + : 0; + // Instances + if (useInstances) { + defines.push("#define INSTANCES"); + PushAttributesForInstances(attribs, this._enableVelocity || this._enableVelocityLinear); + if (subMesh.getRenderingMesh().hasThinInstances) { + defines.push("#define THIN_INSTANCES"); + } + } + // Setup textures count + if (this._linkedWithPrePass) { + defines.push("#define SCENE_MRT_COUNT " + this._attachmentsFromPrePass.length); + } + else { + defines.push("#define SCENE_MRT_COUNT " + this._multiRenderTarget.textures.length); + } + prepareStringDefinesForClipPlanes(material, this._scene, defines); + // Get correct effect + const engine = this._scene.getEngine(); + const drawWrapper = subMesh._getDrawWrapper(undefined, true); + const cachedDefines = drawWrapper.defines; + const join = defines.join("\n"); + if (cachedDefines !== join) { + drawWrapper.setEffect(engine.createEffect("geometry", { + attributes: attribs, + uniformsNames: uniforms, + samplers: ["diffuseSampler", "bumpSampler", "reflectivitySampler", "albedoSampler", "morphTargets", "boneSampler"], + defines: join, + onCompiled: null, + fallbacks: null, + onError: null, + uniformBuffersNames: ["Scene"], + indexParameters: { buffersCount: this._multiRenderTarget.textures.length - 1, maxSimultaneousMorphTargets: numMorphInfluencers }, + shaderLanguage: this.shaderLanguage, + }, engine), join); + } + return drawWrapper.effect.isReady(); + } + /** + * Gets the current underlying G Buffer. + * @returns the buffer + */ + getGBuffer() { + return this._multiRenderTarget; + } + /** + * Gets the number of samples used to render the buffer (anti aliasing). + */ + get samples() { + return this._multiRenderTarget.samples; + } + /** + * Sets the number of samples used to render the buffer (anti aliasing). + */ + set samples(value) { + this._multiRenderTarget.samples = value; + } + /** + * Disposes the renderer and frees up associated resources. + */ + dispose() { + if (this._resizeObserver) { + const engine = this._scene.getEngine(); + engine.onResizeObservable.remove(this._resizeObserver); + this._resizeObserver = null; + } + this.getGBuffer().dispose(); + } + _assignRenderTargetIndices() { + const textureNames = []; + const textureTypesAndFormats = []; + let count = 0; + if (this._enableDepth) { + this._depthIndex = count; + count++; + textureNames.push("gBuffer_Depth"); + textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.DEPTH_TEXTURE_TYPE]); + } + if (this._enableNormal) { + this._normalIndex = count; + count++; + textureNames.push("gBuffer_Normal"); + textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.NORMAL_TEXTURE_TYPE]); + } + if (this._enablePosition) { + this._positionIndex = count; + count++; + textureNames.push("gBuffer_Position"); + textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.POSITION_TEXTURE_TYPE]); + } + if (this._enableVelocity) { + this._velocityIndex = count; + count++; + textureNames.push("gBuffer_Velocity"); + textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE]); + } + if (this._enableVelocityLinear) { + this._velocityLinearIndex = count; + count++; + textureNames.push("gBuffer_VelocityLinear"); + textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE]); + } + if (this._enableReflectivity) { + this._reflectivityIndex = count; + count++; + textureNames.push("gBuffer_Reflectivity"); + textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE]); + } + if (this._enableScreenspaceDepth) { + this._screenspaceDepthIndex = count; + count++; + textureNames.push("gBuffer_ScreenspaceDepth"); + textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE]); + } + return [count, textureNames, textureTypesAndFormats]; + } + _createRenderTargets() { + const engine = this._scene.getEngine(); + const [count, textureNames, textureTypesAndFormat] = this._assignRenderTargetIndices(); + let type = 0; + if (engine._caps.textureFloat && engine._caps.textureFloatLinearFiltering) { + type = 1; + } + else if (engine._caps.textureHalfFloat && engine._caps.textureHalfFloatLinearFiltering) { + type = 2; + } + const dimensions = this._ratioOrDimensions.width !== undefined + ? this._ratioOrDimensions + : { width: engine.getRenderWidth() * this._ratioOrDimensions, height: engine.getRenderHeight() * this._ratioOrDimensions }; + const textureTypes = []; + const textureFormats = []; + for (const typeAndFormat of textureTypesAndFormat) { + if (typeAndFormat) { + textureTypes.push(typeAndFormat.textureType); + textureFormats.push(typeAndFormat.textureFormat); + } + else { + textureTypes.push(type); + textureFormats.push(5); + } + } + this._normalsAreUnsigned = + textureTypes[GeometryBufferRenderer.NORMAL_TEXTURE_TYPE] === 11 || + textureTypes[GeometryBufferRenderer.NORMAL_TEXTURE_TYPE] === 13; + this._multiRenderTarget = new MultiRenderTarget("gBuffer", dimensions, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, types: textureTypes, formats: textureFormats, depthTextureFormat: this._depthFormat }, textureNames.concat("gBuffer_DepthBuffer")); + if (!this.isSupported) { + return; + } + this._multiRenderTarget.wrapU = Texture.CLAMP_ADDRESSMODE; + this._multiRenderTarget.wrapV = Texture.CLAMP_ADDRESSMODE; + this._multiRenderTarget.refreshRate = 1; + this._multiRenderTarget.renderParticles = false; + this._multiRenderTarget.renderList = null; + // Depth is always the first texture in the geometry buffer renderer! + const layoutAttachmentsAll = [true]; + const layoutAttachmentsAllButDepth = [false]; + const layoutAttachmentsDepthOnly = [true]; + for (let i = 1; i < count; ++i) { + layoutAttachmentsAll.push(true); + layoutAttachmentsDepthOnly.push(false); + layoutAttachmentsAllButDepth.push(true); + } + const attachmentsAll = engine.buildTextureLayout(layoutAttachmentsAll); + const attachmentsAllButDepth = engine.buildTextureLayout(layoutAttachmentsAllButDepth); + const attachmentsDepthOnly = engine.buildTextureLayout(layoutAttachmentsDepthOnly); + this._multiRenderTarget.onClearObservable.add((engine) => { + engine.bindAttachments(this.useSpecificClearForDepthTexture ? attachmentsAllButDepth : attachmentsAll); + engine.clear(this._clearColor, true, true, true); + if (this.useSpecificClearForDepthTexture) { + engine.bindAttachments(attachmentsDepthOnly); + engine.clear(this._clearDepthColor, true, true, true); + } + engine.bindAttachments(attachmentsAll); + }); + this._resizeObserver = engine.onResizeObservable.add(() => { + if (this._multiRenderTarget) { + const dimensions = this._ratioOrDimensions.width !== undefined + ? this._ratioOrDimensions + : { width: engine.getRenderWidth() * this._ratioOrDimensions, height: engine.getRenderHeight() * this._ratioOrDimensions }; + this._multiRenderTarget.resize(dimensions); + } + }); + // Custom render function + const renderSubMesh = (subMesh) => { + const renderingMesh = subMesh.getRenderingMesh(); + const effectiveMesh = subMesh.getEffectiveMesh(); + const scene = this._scene; + const engine = scene.getEngine(); + const material = subMesh.getMaterial(); + if (!material) { + return; + } + effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; + // Velocity + if ((this._enableVelocity || this._enableVelocityLinear) && !this._previousTransformationMatrices[effectiveMesh.uniqueId]) { + this._previousTransformationMatrices[effectiveMesh.uniqueId] = { + world: Matrix.Identity(), + viewProjection: scene.getTransformMatrix(), + }; + if (renderingMesh.skeleton) { + const bonesTransformations = renderingMesh.skeleton.getTransformMatrices(renderingMesh); + this._previousBonesTransformationMatrices[renderingMesh.uniqueId] = this._copyBonesTransformationMatrices(bonesTransformations, new Float32Array(bonesTransformations.length)); + } + } + // Managing instances + const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); + if (batch.mustReturn) { + return; + } + const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); + const world = effectiveMesh.getWorldMatrix(); + if (this.isReady(subMesh, hardwareInstancedRendering)) { + const drawWrapper = subMesh._getDrawWrapper(); + if (!drawWrapper) { + return; + } + const effect = drawWrapper.effect; + engine.enableEffect(drawWrapper); + if (!hardwareInstancedRendering) { + renderingMesh._bind(subMesh, effect, material.fillMode); + } + if (!this._useUbo) { + effect.setMatrix("viewProjection", scene.getTransformMatrix()); + effect.setMatrix("view", scene.getViewMatrix()); + } + else { + BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer()); + this._scene.finalizeSceneUbo(); + } + let sideOrientation; + const instanceDataStorage = renderingMesh._instanceDataStorage; + if (!instanceDataStorage.isFrozen && (material.backFaceCulling || material.sideOrientation !== null)) { + const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant(); + sideOrientation = material._getEffectiveOrientation(renderingMesh); + if (mainDeterminant < 0) { + sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation; + } + } + else { + sideOrientation = instanceDataStorage.sideOrientation; + } + material._preBind(drawWrapper, sideOrientation); + // Alpha test + if (material.needAlphaTestingForMesh(effectiveMesh)) { + const alphaTexture = material.getAlphaTestTexture(); + if (alphaTexture) { + effect.setTexture("diffuseSampler", alphaTexture); + effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); + } + } + // Bump + if ((material.bumpTexture || material.normalTexture) && scene.getEngine().getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled) { + const texture = material.bumpTexture || material.normalTexture; + effect.setFloat3("vBumpInfos", texture.coordinatesIndex, 1.0 / texture.level, material.parallaxScaleBias); + effect.setMatrix("bumpMatrix", texture.getTextureMatrix()); + effect.setTexture("bumpSampler", texture); + effect.setFloat2("vTangentSpaceParams", material.invertNormalMapX ? -1 : 1.0, material.invertNormalMapY ? -1 : 1.0); + } + // Reflectivity + if (this._enableReflectivity) { + // for PBR materials: cf. https://doc.babylonjs.com/features/featuresDeepDive/materials/using/masterPBR + if (material.getClassName() === "PBRMetallicRoughnessMaterial") { + // if it is a PBR material in MetallicRoughness Mode: + if (material.metallicRoughnessTexture !== null) { + effect.setTexture("reflectivitySampler", material.metallicRoughnessTexture); + effect.setMatrix("reflectivityMatrix", material.metallicRoughnessTexture.getTextureMatrix()); + } + if (material.metallic !== null) { + effect.setFloat("metallic", material.metallic); + } + if (material.roughness !== null) { + effect.setFloat("glossiness", 1.0 - material.roughness); + } + if (material.baseTexture !== null) { + effect.setTexture("albedoSampler", material.baseTexture); + effect.setMatrix("albedoMatrix", material.baseTexture.getTextureMatrix()); + } + if (material.baseColor !== null) { + effect.setColor3("albedoColor", material.baseColor); + } + } + else if (material.getClassName() === "PBRSpecularGlossinessMaterial") { + // if it is a PBR material in Specular/Glossiness Mode: + if (material.specularGlossinessTexture !== null) { + effect.setTexture("reflectivitySampler", material.specularGlossinessTexture); + effect.setMatrix("reflectivityMatrix", material.specularGlossinessTexture.getTextureMatrix()); + } + else { + if (material.specularColor !== null) { + effect.setColor3("reflectivityColor", material.specularColor); + } + } + if (material.glossiness !== null) { + effect.setFloat("glossiness", material.glossiness); + } + } + else if (material.getClassName() === "PBRMaterial") { + // if it is the bigger PBRMaterial + if (material.metallicTexture !== null) { + effect.setTexture("reflectivitySampler", material.metallicTexture); + effect.setMatrix("reflectivityMatrix", material.metallicTexture.getTextureMatrix()); + } + if (material.metallic !== null) { + effect.setFloat("metallic", material.metallic); + } + if (material.roughness !== null) { + effect.setFloat("glossiness", 1.0 - material.roughness); + } + if (material.roughness !== null || material.metallic !== null || material.metallicTexture !== null) { + // MetallicRoughness Model + if (material.albedoTexture !== null) { + effect.setTexture("albedoSampler", material.albedoTexture); + effect.setMatrix("albedoMatrix", material.albedoTexture.getTextureMatrix()); + } + if (material.albedoColor !== null) { + effect.setColor3("albedoColor", material.albedoColor); + } + } + else { + // SpecularGlossiness Model + if (material.reflectivityTexture !== null) { + effect.setTexture("reflectivitySampler", material.reflectivityTexture); + effect.setMatrix("reflectivityMatrix", material.reflectivityTexture.getTextureMatrix()); + } + else if (material.reflectivityColor !== null) { + effect.setColor3("reflectivityColor", material.reflectivityColor); + } + if (material.microSurface !== null) { + effect.setFloat("glossiness", material.microSurface); + } + } + } + else if (material.getClassName() === "StandardMaterial") { + // if StandardMaterial: + if (material.specularTexture !== null) { + effect.setTexture("reflectivitySampler", material.specularTexture); + effect.setMatrix("reflectivityMatrix", material.specularTexture.getTextureMatrix()); + } + if (material.specularColor !== null) { + effect.setColor3("reflectivityColor", material.specularColor); + } + } + } + // Clip plane + bindClipPlane(effect, material, this._scene); + // Bones + if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { + const skeleton = renderingMesh.skeleton; + if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) { + const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh); + effect.setTexture("boneSampler", boneTexture); + effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); + } + else { + effect.setMatrices("mBones", renderingMesh.skeleton.getTransformMatrices(renderingMesh)); + } + if (this._enableVelocity || this._enableVelocityLinear) { + effect.setMatrices("mPreviousBones", this._previousBonesTransformationMatrices[renderingMesh.uniqueId]); + } + } + // Morph targets + BindMorphTargetParameters(renderingMesh, effect); + if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { + renderingMesh.morphTargetManager._bind(effect); + } + // Velocity + if (this._enableVelocity || this._enableVelocityLinear) { + effect.setMatrix("previousWorld", this._previousTransformationMatrices[effectiveMesh.uniqueId].world); + effect.setMatrix("previousViewProjection", this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection); + } + if (hardwareInstancedRendering && renderingMesh.hasThinInstances) { + effect.setMatrix("world", world); + } + // Draw + renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, w) => { + if (!isInstance) { + effect.setMatrix("world", w); + } + }); + } + // Velocity + if (this._enableVelocity || this._enableVelocityLinear) { + this._previousTransformationMatrices[effectiveMesh.uniqueId].world = world.clone(); + this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection = this._scene.getTransformMatrix().clone(); + if (renderingMesh.skeleton) { + this._copyBonesTransformationMatrices(renderingMesh.skeleton.getTransformMatrices(renderingMesh), this._previousBonesTransformationMatrices[effectiveMesh.uniqueId]); + } + } + }; + this._multiRenderTarget.customIsReadyFunction = (mesh, refreshRate, preWarm) => { + if ((preWarm || refreshRate === 0) && mesh.subMeshes) { + for (let i = 0; i < mesh.subMeshes.length; ++i) { + const subMesh = mesh.subMeshes[i]; + const material = subMesh.getMaterial(); + const renderingMesh = subMesh.getRenderingMesh(); + if (!material) { + continue; + } + const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); + const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); + if (!this.isReady(subMesh, hardwareInstancedRendering)) { + return false; + } + } + } + return true; + }; + this._multiRenderTarget.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { + let index; + if (this._linkedWithPrePass) { + if (!this._prePassRenderer.enabled) { + return; + } + this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass); + } + if (depthOnlySubMeshes.length) { + engine.setColorWrite(false); + for (index = 0; index < depthOnlySubMeshes.length; index++) { + renderSubMesh(depthOnlySubMeshes.data[index]); + } + engine.setColorWrite(true); + } + for (index = 0; index < opaqueSubMeshes.length; index++) { + renderSubMesh(opaqueSubMeshes.data[index]); + } + engine.setDepthWrite(false); + for (index = 0; index < alphaTestSubMeshes.length; index++) { + renderSubMesh(alphaTestSubMeshes.data[index]); + } + if (this.renderTransparentMeshes) { + for (index = 0; index < transparentSubMeshes.length; index++) { + renderSubMesh(transparentSubMeshes.data[index]); + } + } + engine.setDepthWrite(true); + }; + } + // Copies the bones transformation matrices into the target array and returns the target's reference + _copyBonesTransformationMatrices(source, target) { + for (let i = 0; i < source.length; i++) { + target[i] = source[i]; + } + return target; + } +} +/** + * Force all the standard materials to compile to glsl even on WebGPU engines. + * False by default. This is mostly meant for backward compatibility. + */ +GeometryBufferRenderer.ForceGLSL = false; +/** + * Constant used to retrieve the depth texture index in the G-Buffer textures array + * using getIndex(GeometryBufferRenderer.DEPTH_TEXTURE_INDEX) + */ +GeometryBufferRenderer.DEPTH_TEXTURE_TYPE = 0; +/** + * Constant used to retrieve the normal texture index in the G-Buffer textures array + * using getIndex(GeometryBufferRenderer.NORMAL_TEXTURE_INDEX) + */ +GeometryBufferRenderer.NORMAL_TEXTURE_TYPE = 1; +/** + * Constant used to retrieve the position texture index in the G-Buffer textures array + * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX) + */ +GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 2; +/** + * Constant used to retrieve the velocity texture index in the G-Buffer textures array + * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX) + */ +GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 3; +/** + * Constant used to retrieve the reflectivity texture index in the G-Buffer textures array + * using the getIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE) + */ +GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE = 4; +/** + * Constant used to retrieve the screen-space depth texture index in the G-Buffer textures array + * using getIndex(GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE) + */ +GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE = 5; +/** + * Constant used to retrieve the linear velocity texture index in the G-Buffer textures array + * using getIndex(GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE) + */ +GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE = 6; +/** + * @internal + */ +GeometryBufferRenderer._SceneComponentInitialization = (_) => { + throw _WarnImport("GeometryBufferRendererSceneComponent"); +}; + +/** + * Contains all parameters needed for the prepass to perform + * motion blur + */ +class MotionBlurConfiguration { + constructor() { + /** + * Is motion blur enabled + */ + this.enabled = false; + /** + * Name of the configuration + */ + this.name = "motionBlur"; + /** + * Textures that should be present in the MRT for this effect to work + */ + this.texturesRequired = [2]; + } +} + +Object.defineProperty(Scene.prototype, "geometryBufferRenderer", { + get: function () { + return this._geometryBufferRenderer; + }, + set: function (value) { + if (value && value.isSupported) { + this._geometryBufferRenderer = value; + } + }, + enumerable: true, + configurable: true, +}); +Scene.prototype.enableGeometryBufferRenderer = function (ratio = 1, depthFormat = 15, textureTypesAndFormats) { + if (this._geometryBufferRenderer) { + return this._geometryBufferRenderer; + } + this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio, depthFormat, textureTypesAndFormats); + if (!this._geometryBufferRenderer.isSupported) { + this._geometryBufferRenderer = null; + } + return this._geometryBufferRenderer; +}; +Scene.prototype.disableGeometryBufferRenderer = function () { + if (!this._geometryBufferRenderer) { + return; + } + this._geometryBufferRenderer.dispose(); + this._geometryBufferRenderer = null; +}; +/** + * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful + * in several rendering techniques. + */ +class GeometryBufferRendererSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do for this component + } + /** + * Disposes the component and the associated resources + */ + dispose() { + // Nothing to do for this component + } + _gatherRenderTargets(renderTargets) { + if (this.scene._geometryBufferRenderer) { + renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer()); + } + } +} +GeometryBufferRenderer._SceneComponentInitialization = (scene) => { + // Register the G Buffer component to the scene. + let component = scene._getComponent(SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER); + if (!component) { + component = new GeometryBufferRendererSceneComponent(scene); + scene._addComponent(component); + } +}; + +/** + * The Motion Blur Post Process which blurs an image based on the objects velocity in scene. + * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed. + * As an example, all you have to do is to create the post-process: + * var mb = new BABYLON.MotionBlurPostProcess( + * 'mb', // The name of the effect. + * scene, // The scene containing the objects to blur according to their velocity. + * 1.0, // The required width/height ratio to downsize to before computing the render pass. + * camera // The camera to apply the render pass to. + * ); + * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed. + */ +class MotionBlurPostProcess extends PostProcess { + /** + * Gets the number of iterations are used for motion blur quality. Default value is equal to 32 + */ + get motionBlurSamples() { + return this._motionBlurSamples; + } + /** + * Sets the number of iterations to be used for motion blur quality + */ + set motionBlurSamples(samples) { + this._motionBlurSamples = samples; + this._updateEffect(); + } + /** + * Gets whether or not the motion blur post-process is in object based mode. + */ + get isObjectBased() { + return this._isObjectBased; + } + /** + * Sets whether or not the motion blur post-process is in object based mode. + */ + set isObjectBased(value) { + if (this._isObjectBased === value) { + return; + } + this._isObjectBased = value; + this._applyMode(); + } + get _geometryBufferRenderer() { + if (!this._forceGeometryBuffer) { + return null; + } + return this._scene.geometryBufferRenderer; + } + get _prePassRenderer() { + if (this._forceGeometryBuffer) { + return null; + } + return this._scene.prePassRenderer; + } + /** + * Gets a string identifying the name of the class + * @returns "MotionBlurPostProcess" string + */ + getClassName() { + return "MotionBlurPostProcess"; + } + /** + * Creates a new instance MotionBlurPostProcess + * @param name The name of the effect. + * @param scene The scene containing the objects to blur according to their velocity. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: true) + * @param forceGeometryBuffer If this post process should use geometry buffer instead of prepass (default: false) + */ + constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false, forceGeometryBuffer = false) { + super(name, "motionBlur", ["motionStrength", "motionScale", "screenSize", "inverseViewProjection", "prevViewProjection", "projection"], ["velocitySampler", "depthSampler"], options, camera, samplingMode, engine, reusable, "#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED", textureType, undefined, null, blockCompilation); + /** + * Defines how much the image is blurred by the movement. Default value is equal to 1 + */ + this.motionStrength = 1; + this._motionBlurSamples = 32; + this._isObjectBased = true; + this._forceGeometryBuffer = false; + this._invViewProjection = null; + this._previousViewProjection = null; + this._forceGeometryBuffer = forceGeometryBuffer; + // Set up assets + if (this._forceGeometryBuffer) { + scene.enableGeometryBufferRenderer(); + if (this._geometryBufferRenderer) { + this._geometryBufferRenderer.enableVelocity = this._isObjectBased; + } + } + else { + scene.enablePrePassRenderer(); + if (this._prePassRenderer) { + this._prePassRenderer.markAsDirty(); + this._prePassEffectConfiguration = new MotionBlurConfiguration(); + } + } + this._applyMode(); + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => motionBlur_fragment)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => motionBlur_fragment$1)])); + } + super._gatherImports(useWebGPU, list); + } + /** + * Excludes the given skinned mesh from computing bones velocities. + * Computing bones velocities can have a cost and that cost. The cost can be saved by calling this function and by passing the skinned mesh reference to ignore. + * @param skinnedMesh The mesh containing the skeleton to ignore when computing the velocity map. + */ + excludeSkinnedMesh(skinnedMesh) { + if (skinnedMesh.skeleton) { + let list; + if (this._geometryBufferRenderer) { + list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity; + } + else if (this._prePassRenderer) { + list = this._prePassRenderer.excludedSkinnedMesh; + } + else { + return; + } + list.push(skinnedMesh); + } + } + /** + * Removes the given skinned mesh from the excluded meshes to integrate bones velocities while rendering the velocity map. + * @param skinnedMesh The mesh containing the skeleton that has been ignored previously. + * @see excludeSkinnedMesh to exclude a skinned mesh from bones velocity computation. + */ + removeExcludedSkinnedMesh(skinnedMesh) { + if (skinnedMesh.skeleton) { + let list; + if (this._geometryBufferRenderer) { + list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity; + } + else if (this._prePassRenderer) { + list = this._prePassRenderer.excludedSkinnedMesh; + } + else { + return; + } + const index = list.indexOf(skinnedMesh); + if (index !== -1) { + list.splice(index, 1); + } + } + } + /** + * Disposes the post process. + * @param camera The camera to dispose the post process on. + */ + dispose(camera) { + if (this._geometryBufferRenderer) { + // Clear previous transformation matrices dictionary used to compute objects velocities + this._geometryBufferRenderer._previousTransformationMatrices = {}; + this._geometryBufferRenderer._previousBonesTransformationMatrices = {}; + this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity = []; + } + super.dispose(camera); + } + /** + * Called on the mode changed (object based or screen based). + * @returns void + */ + _applyMode() { + if (!this._geometryBufferRenderer && !this._prePassRenderer) { + // We can't get a velocity or depth texture. So, work as a passthrough. + Logger.Warn("Multiple Render Target support needed to compute object based motion blur"); + return this.updateEffect(); + } + if (this._geometryBufferRenderer) { + this._geometryBufferRenderer.enableVelocity = this._isObjectBased; + } + this._updateEffect(); + this._invViewProjection = null; + this._previousViewProjection = null; + if (this.isObjectBased) { + if (this._prePassRenderer && this._prePassEffectConfiguration) { + this._prePassEffectConfiguration.texturesRequired[0] = 2; + } + this.onApply = (effect) => this._onApplyObjectBased(effect); + } + else { + this._invViewProjection = Matrix.Identity(); + this._previousViewProjection = this._scene.getTransformMatrix().clone(); + if (this._prePassRenderer && this._prePassEffectConfiguration) { + this._prePassEffectConfiguration.texturesRequired[0] = 5; + } + this.onApply = (effect) => this._onApplyScreenBased(effect); + } + } + /** + * Called on the effect is applied when the motion blur post-process is in object based mode. + * @param effect + */ + _onApplyObjectBased(effect) { + effect.setVector2("screenSize", new Vector2(this.width, this.height)); + effect.setFloat("motionScale", this._scene.getAnimationRatio()); + effect.setFloat("motionStrength", this.motionStrength); + if (this._geometryBufferRenderer) { + const velocityIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE); + effect.setTexture("velocitySampler", this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]); + } + else if (this._prePassRenderer) { + const velocityIndex = this._prePassRenderer.getIndex(2); + effect.setTexture("velocitySampler", this._prePassRenderer.getRenderTarget().textures[velocityIndex]); + } + } + /** + * Called on the effect is applied when the motion blur post-process is in screen based mode. + * @param effect + */ + _onApplyScreenBased(effect) { + const viewProjection = TmpVectors.Matrix[0]; + viewProjection.copyFrom(this._scene.getTransformMatrix()); + viewProjection.invertToRef(this._invViewProjection); + effect.setMatrix("inverseViewProjection", this._invViewProjection); + effect.setMatrix("prevViewProjection", this._previousViewProjection); + this._previousViewProjection.copyFrom(viewProjection); + effect.setMatrix("projection", this._scene.getProjectionMatrix()); + effect.setVector2("screenSize", new Vector2(this.width, this.height)); + effect.setFloat("motionScale", this._scene.getAnimationRatio()); + effect.setFloat("motionStrength", this.motionStrength); + if (this._geometryBufferRenderer) { + const depthIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE); + effect.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[depthIndex]); + } + else if (this._prePassRenderer) { + const depthIndex = this._prePassRenderer.getIndex(5); + effect.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[depthIndex]); + } + } + /** + * Called on the effect must be updated (changed mode, samples count, etc.). + */ + _updateEffect() { + if (this._geometryBufferRenderer || this._prePassRenderer) { + const defines = [ + "#define GEOMETRY_SUPPORTED", + "#define SAMPLES " + this._motionBlurSamples.toFixed(1), + this._isObjectBased ? "#define OBJECT_BASED" : "#define SCREEN_BASED", + ]; + this.updateEffect(defines.join("\n")); + } + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new MotionBlurPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, false); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], MotionBlurPostProcess.prototype, "motionStrength", void 0); +__decorate([ + serialize() +], MotionBlurPostProcess.prototype, "motionBlurSamples", null); +__decorate([ + serialize() +], MotionBlurPostProcess.prototype, "isObjectBased", null); +RegisterClass("BABYLON.MotionBlurPostProcess", MotionBlurPostProcess); + +// Do not edit. +const name$2Y = "refractionPixelShader"; +const shader$2X = `varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2Y]) { + ShaderStore.ShadersStore[name$2Y] = shader$2X; +} + +/** + * Post process which applies a refraction texture + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#refraction + */ +class RefractionPostProcess extends PostProcess { + /** + * Gets or sets the refraction texture + * Please note that you are responsible for disposing the texture if you set it manually + */ + get refractionTexture() { + return this._refTexture; + } + set refractionTexture(value) { + if (this._refTexture && this._ownRefractionTexture) { + this._refTexture.dispose(); + } + this._refTexture = value; + this._ownRefractionTexture = false; + } + /** + * Gets a string identifying the name of the class + * @returns "RefractionPostProcess" string + */ + getClassName() { + return "RefractionPostProcess"; + } + /** + * Initializes the RefractionPostProcess + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#refraction + * @param name The name of the effect. + * @param refractionTextureUrl Url of the refraction texture to use + * @param color the base color of the refraction (used to taint the rendering) + * @param depth simulated refraction depth + * @param colorLevel the coefficient of the base color (0 to remove base color tainting) + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + */ + constructor(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) { + super(name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable); + this._ownRefractionTexture = true; + this.color = color; + this.depth = depth; + this.colorLevel = colorLevel; + this.refractionTextureUrl = refractionTextureUrl; + this.onActivateObservable.add((cam) => { + this._refTexture = this._refTexture || new Texture(refractionTextureUrl, cam.getScene()); + }); + this.onApplyObservable.add((effect) => { + effect.setColor3("baseColor", this.color); + effect.setFloat("depth", this.depth); + effect.setFloat("colorLevel", this.colorLevel); + effect.setTexture("refractionSampler", this._refTexture); + }); + } + // Methods + /** + * Disposes of the post process + * @param camera Camera to dispose post process on + */ + dispose(camera) { + if (this._refTexture && this._ownRefractionTexture) { + this._refTexture.dispose(); + this._refTexture = null; + } + super.dispose(camera); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new RefractionPostProcess(parsedPostProcess.name, parsedPostProcess.refractionTextureUrl, parsedPostProcess.color, parsedPostProcess.depth, parsedPostProcess.colorLevel, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], RefractionPostProcess.prototype, "color", void 0); +__decorate([ + serialize() +], RefractionPostProcess.prototype, "depth", void 0); +__decorate([ + serialize() +], RefractionPostProcess.prototype, "colorLevel", void 0); +__decorate([ + serialize() +], RefractionPostProcess.prototype, "refractionTextureUrl", void 0); +RegisterClass("BABYLON.RefractionPostProcess", RefractionPostProcess); + +// Do not edit. +const name$2X = "sharpenPixelShader"; +const shader$2W = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + +texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + +texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + +texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - +color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2X]) { + ShaderStore.ShadersStore[name$2X] = shader$2W; +} +/** @internal */ +const sharpenPixelShader = { name: name$2X, shader: shader$2W }; + +const sharpen_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + sharpenPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * The SharpenPostProcess applies a sharpen kernel to every pixel + * See http://en.wikipedia.org/wiki/Kernel_(image_processing) + */ +class SharpenPostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "SharpenPostProcess" string + */ + getClassName() { + return "SharpenPostProcess"; + } + /** + * Creates a new instance ConvolutionPostProcess + * @param name The name of the effect. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(name, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { + super(name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation); + /** + * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1) + */ + this.colorAmount = 1.0; + /** + * How much sharpness should be applied (default: 0.3) + */ + this.edgeAmount = 0.3; + this.onApply = (effect) => { + effect.setFloat2("screenSize", this.width, this.height); + effect.setFloat2("sharpnessAmounts", this.edgeAmount, this.colorAmount); + }; + } + _gatherImports(useWebGPU, list) { + if (useWebGPU) { + this._webGPUReady = true; + list.push(Promise.all([Promise.resolve().then(() => sharpen_fragment)])); + } + else { + list.push(Promise.all([Promise.resolve().then(() => sharpen_fragment$1)])); + } + super._gatherImports(useWebGPU, list); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new SharpenPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], SharpenPostProcess.prototype, "colorAmount", void 0); +__decorate([ + serialize() +], SharpenPostProcess.prototype, "edgeAmount", void 0); +RegisterClass("BABYLON.SharpenPostProcess", SharpenPostProcess); + +/** + * PostProcessRenderPipeline + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/postProcessRenderPipeline + */ +class PostProcessRenderPipeline { + /** + * Gets pipeline name + */ + get name() { + return this._name; + } + /** Gets the list of attached cameras */ + get cameras() { + return this._cameras; + } + /** + * Gets the active engine + */ + get engine() { + return this._engine; + } + /** + * Initializes a PostProcessRenderPipeline + * @param _engine engine to add the pipeline to + * @param name name of the pipeline + */ + constructor(_engine, name) { + this._engine = _engine; + this._name = name; + this._renderEffects = {}; + this._renderEffectsForIsolatedPass = new Array(); + this._cameras = []; + } + /** + * Gets the class name + * @returns "PostProcessRenderPipeline" + */ + getClassName() { + return "PostProcessRenderPipeline"; + } + /** + * If all the render effects in the pipeline are supported + */ + get isSupported() { + for (const renderEffectName in this._renderEffects) { + if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { + if (!this._renderEffects[renderEffectName].isSupported) { + return false; + } + } + } + return true; + } + /** + * Adds an effect to the pipeline + * @param renderEffect the effect to add + */ + addEffect(renderEffect) { + this._renderEffects[renderEffect._name] = renderEffect; + } + // private + /** @internal */ + _rebuild() { } + /** + * @internal + */ + _enableEffect(renderEffectName, cameras) { + const renderEffects = this._renderEffects[renderEffectName]; + if (!renderEffects) { + return; + } + renderEffects._enable(Tools.MakeArray(cameras || this._cameras)); + } + /** + * @internal + */ + _disableEffect(renderEffectName, cameras) { + const renderEffects = this._renderEffects[renderEffectName]; + if (!renderEffects) { + return; + } + renderEffects._disable(Tools.MakeArray(cameras || this._cameras)); + } + /** + * @internal + */ + _attachCameras(cameras, unique) { + const cams = Tools.MakeArray(cameras || this._cameras); + if (!cams) { + return; + } + const indicesToDelete = []; + let i; + for (i = 0; i < cams.length; i++) { + const camera = cams[i]; + if (!camera) { + continue; + } + if (this._cameras.indexOf(camera) === -1) { + this._cameras.push(camera); + } + else if (unique) { + indicesToDelete.push(i); + } + } + for (i = 0; i < indicesToDelete.length; i++) { + cams.splice(indicesToDelete[i], 1); + } + for (const renderEffectName in this._renderEffects) { + if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { + this._renderEffects[renderEffectName]._attachCameras(cams); + } + } + } + /** + * @internal + */ + _detachCameras(cameras) { + const cams = Tools.MakeArray(cameras || this._cameras); + if (!cams) { + return; + } + for (const renderEffectName in this._renderEffects) { + if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { + this._renderEffects[renderEffectName]._detachCameras(cams); + } + } + for (let i = 0; i < cams.length; i++) { + this._cameras.splice(this._cameras.indexOf(cams[i]), 1); + } + } + /** @internal */ + _update() { + for (const renderEffectName in this._renderEffects) { + if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { + this._renderEffects[renderEffectName]._update(); + } + } + for (let i = 0; i < this._cameras.length; i++) { + if (!this._cameras[i]) { + continue; + } + const cameraName = this._cameras[i].name; + if (this._renderEffectsForIsolatedPass[cameraName]) { + this._renderEffectsForIsolatedPass[cameraName]._update(); + } + } + } + /** @internal */ + _reset() { + this._renderEffects = {}; + this._renderEffectsForIsolatedPass = new Array(); + } + _enableMSAAOnFirstPostProcess(sampleCount) { + if (!this._engine._features.supportMSAA) { + return false; + } + // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754) + const effectKeys = Object.keys(this._renderEffects); + if (effectKeys.length > 0) { + const postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses(); + if (postProcesses) { + postProcesses[0].samples = sampleCount; + } + } + return true; + } + /** + * Ensures that all post processes in the pipeline are the correct size according to the + * the viewport's required size + */ + _adaptPostProcessesToViewPort() { + const effectKeys = Object.keys(this._renderEffects); + for (const effectKey of effectKeys) { + const postProcesses = this._renderEffects[effectKey].getPostProcesses(); + if (postProcesses) { + for (const postProcess of postProcesses) { + postProcess.adaptScaleToCurrentViewport = true; + } + } + } + } + /** + * Sets the required values to the prepass renderer. + * @param prePassRenderer defines the prepass renderer to setup. + * @returns true if the pre pass is needed. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + setPrePassRenderer(prePassRenderer) { + // Do Nothing by default + return false; + } + /** + * Disposes of the pipeline + */ + dispose() { + // Must be implemented by children + } +} +__decorate([ + serialize() +], PostProcessRenderPipeline.prototype, "_name", void 0); + +/** + * PostProcessRenderPipelineManager class + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/postProcessRenderPipeline + */ +class PostProcessRenderPipelineManager { + /** + * Initializes a PostProcessRenderPipelineManager + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/postProcessRenderPipeline + */ + constructor() { + this._renderPipelines = {}; + } + /** + * Gets the list of supported render pipelines + */ + get supportedPipelines() { + const result = []; + for (const renderPipelineName in this._renderPipelines) { + if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { + const pipeline = this._renderPipelines[renderPipelineName]; + if (pipeline.isSupported) { + result.push(pipeline); + } + } + } + return result; + } + /** + * Adds a pipeline to the manager + * @param renderPipeline The pipeline to add + */ + addPipeline(renderPipeline) { + this._renderPipelines[renderPipeline._name] = renderPipeline; + } + /** + * Remove the pipeline from the manager + * @param renderPipelineName the name of the pipeline to remove + */ + removePipeline(renderPipelineName) { + delete this._renderPipelines[renderPipelineName]; + } + /** + * Attaches a camera to the pipeline + * @param renderPipelineName The name of the pipeline to attach to + * @param cameras the camera to attach + * @param unique if the camera can be attached multiple times to the pipeline + */ + attachCamerasToRenderPipeline(renderPipelineName, cameras, unique = false) { + const renderPipeline = this._renderPipelines[renderPipelineName]; + if (!renderPipeline) { + return; + } + renderPipeline._attachCameras(cameras, unique); + } + /** + * Detaches a camera from the pipeline + * @param renderPipelineName The name of the pipeline to detach from + * @param cameras the camera to detach + */ + detachCamerasFromRenderPipeline(renderPipelineName, cameras) { + const renderPipeline = this._renderPipelines[renderPipelineName]; + if (!renderPipeline) { + return; + } + renderPipeline._detachCameras(cameras); + } + /** + * Enables an effect by name on a pipeline + * @param renderPipelineName the name of the pipeline to enable the effect in + * @param renderEffectName the name of the effect to enable + * @param cameras the cameras that the effect should be enabled on + */ + enableEffectInPipeline(renderPipelineName, renderEffectName, cameras) { + const renderPipeline = this._renderPipelines[renderPipelineName]; + if (!renderPipeline) { + return; + } + renderPipeline._enableEffect(renderEffectName, cameras); + } + /** + * Disables an effect by name on a pipeline + * @param renderPipelineName the name of the pipeline to disable the effect in + * @param renderEffectName the name of the effect to disable + * @param cameras the cameras that the effect should be disabled on + */ + disableEffectInPipeline(renderPipelineName, renderEffectName, cameras) { + const renderPipeline = this._renderPipelines[renderPipelineName]; + if (!renderPipeline) { + return; + } + renderPipeline._disableEffect(renderEffectName, cameras); + } + /** + * Updates the state of all contained render pipelines and disposes of any non supported pipelines + */ + update() { + for (const renderPipelineName in this._renderPipelines) { + if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { + const pipeline = this._renderPipelines[renderPipelineName]; + if (!pipeline.isSupported) { + pipeline.dispose(); + delete this._renderPipelines[renderPipelineName]; + } + else { + pipeline._update(); + } + } + } + } + /** @internal */ + _rebuild() { + for (const renderPipelineName in this._renderPipelines) { + if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { + const pipeline = this._renderPipelines[renderPipelineName]; + pipeline._rebuild(); + } + } + } + /** + * Disposes of the manager and pipelines + */ + dispose() { + for (const renderPipelineName in this._renderPipelines) { + if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { + const pipeline = this._renderPipelines[renderPipelineName]; + pipeline.dispose(); + } + } + } +} + +Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", { + get: function () { + if (!this._postProcessRenderPipelineManager) { + // Register the G Buffer component to the scene. + let component = this._getComponent(SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER); + if (!component) { + component = new PostProcessRenderPipelineManagerSceneComponent(this); + this._addComponent(component); + } + this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager(); + } + return this._postProcessRenderPipelineManager; + }, + enumerable: true, + configurable: true, +}); +/** + * Defines the Render Pipeline scene component responsible to rendering pipelines + */ +class PostProcessRenderPipelineManagerSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + if (this.scene._postProcessRenderPipelineManager) { + this.scene._postProcessRenderPipelineManager._rebuild(); + } + } + /** + * Disposes the component and the associated resources + */ + dispose() { + if (this.scene._postProcessRenderPipelineManager) { + this.scene._postProcessRenderPipelineManager.dispose(); + } + } + _gatherRenderTargets() { + if (this.scene._postProcessRenderPipelineManager) { + this.scene._postProcessRenderPipelineManager.update(); + } + } +} + +/** + * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field. + * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/defaultRenderingPipeline + */ +class DefaultRenderingPipeline extends PostProcessRenderPipeline { + /** + * Enable or disable automatic building of the pipeline when effects are enabled and disabled. + * If false, you will have to manually call prepare() to update the pipeline. + */ + get automaticBuild() { + return this._buildAllowed; + } + set automaticBuild(value) { + this._buildAllowed = value; + } + /** + * Gets active scene + */ + get scene() { + return this._scene; + } + /** + * Enable or disable the sharpen process from the pipeline + */ + set sharpenEnabled(enabled) { + if (this._sharpenEnabled === enabled) { + return; + } + this._sharpenEnabled = enabled; + this._buildPipeline(); + } + get sharpenEnabled() { + return this._sharpenEnabled; + } + /** + * Specifies the size of the bloom blur kernel, relative to the final output size + */ + get bloomKernel() { + return this._bloomKernel; + } + set bloomKernel(value) { + this._bloomKernel = value; + this.bloom.kernel = value / this._hardwareScaleLevel; + } + /** + * The strength of the bloom. + */ + set bloomWeight(value) { + if (this._bloomWeight === value) { + return; + } + this.bloom.weight = value; + this._bloomWeight = value; + } + get bloomWeight() { + return this._bloomWeight; + } + /** + * The luminance threshold to find bright areas of the image to bloom. + */ + set bloomThreshold(value) { + if (this._bloomThreshold === value) { + return; + } + this.bloom.threshold = value; + this._bloomThreshold = value; + } + get bloomThreshold() { + return this._bloomThreshold; + } + /** + * The scale of the bloom, lower value will provide better performance. + */ + set bloomScale(value) { + if (this._bloomScale === value) { + return; + } + this._bloomScale = value; + // recreate bloom and dispose old as this setting is not dynamic + this._rebuildBloom(); + this._buildPipeline(); + } + get bloomScale() { + return this._bloomScale; + } + /** + * Enable or disable the bloom from the pipeline + */ + set bloomEnabled(enabled) { + if (this._bloomEnabled === enabled) { + return; + } + this._bloomEnabled = enabled; + this._buildPipeline(); + } + get bloomEnabled() { + return this._bloomEnabled; + } + _rebuildBloom() { + // recreate bloom and dispose old as this setting is not dynamic + const oldBloom = this.bloom; + this.bloom = new BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel / this._hardwareScaleLevel, this._defaultPipelineTextureType, false); + this.bloom.threshold = oldBloom.threshold; + for (let i = 0; i < this._cameras.length; i++) { + oldBloom.disposeEffects(this._cameras[i]); + } + } + /** + * If the depth of field is enabled. + */ + get depthOfFieldEnabled() { + return this._depthOfFieldEnabled; + } + set depthOfFieldEnabled(enabled) { + if (this._depthOfFieldEnabled === enabled) { + return; + } + this._depthOfFieldEnabled = enabled; + this._buildPipeline(); + } + /** + * Blur level of the depth of field effect. (Higher blur will effect performance) + */ + get depthOfFieldBlurLevel() { + return this._depthOfFieldBlurLevel; + } + set depthOfFieldBlurLevel(value) { + if (this._depthOfFieldBlurLevel === value) { + return; + } + this._depthOfFieldBlurLevel = value; + // recreate dof and dispose old as this setting is not dynamic + const oldDof = this.depthOfField; + this.depthOfField = new DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false); + this.depthOfField.focalLength = oldDof.focalLength; + this.depthOfField.focusDistance = oldDof.focusDistance; + this.depthOfField.fStop = oldDof.fStop; + this.depthOfField.lensSize = oldDof.lensSize; + for (let i = 0; i < this._cameras.length; i++) { + oldDof.disposeEffects(this._cameras[i]); + } + this._buildPipeline(); + } + /** + * If the anti aliasing is enabled. + */ + set fxaaEnabled(enabled) { + if (this._fxaaEnabled === enabled) { + return; + } + this._fxaaEnabled = enabled; + this._buildPipeline(); + } + get fxaaEnabled() { + return this._fxaaEnabled; + } + /** + * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1) + */ + set samples(sampleCount) { + if (this._samples === sampleCount) { + return; + } + this._samples = sampleCount; + this._buildPipeline(); + } + get samples() { + return this._samples; + } + /** + * If image processing is enabled. + */ + set imageProcessingEnabled(enabled) { + if (this._imageProcessingEnabled === enabled) { + return; + } + this._scene.imageProcessingConfiguration.isEnabled = enabled; + } + get imageProcessingEnabled() { + return this._imageProcessingEnabled; + } + /** + * If glow layer is enabled. (Adds a glow effect to emmissive materials) + */ + set glowLayerEnabled(enabled) { + if (enabled && !this._glowLayer) { + this._glowLayer = new GlowLayer("", this._scene); + } + else if (!enabled && this._glowLayer) { + this._glowLayer.dispose(); + this._glowLayer = null; + } + } + get glowLayerEnabled() { + return this._glowLayer != null; + } + /** + * Gets the glow layer (or null if not defined) + */ + get glowLayer() { + return this._glowLayer; + } + /** + * Enable or disable the chromaticAberration process from the pipeline + */ + set chromaticAberrationEnabled(enabled) { + if (this._chromaticAberrationEnabled === enabled) { + return; + } + this._chromaticAberrationEnabled = enabled; + this._buildPipeline(); + } + get chromaticAberrationEnabled() { + return this._chromaticAberrationEnabled; + } + /** + * Enable or disable the grain process from the pipeline + */ + set grainEnabled(enabled) { + if (this._grainEnabled === enabled) { + return; + } + this._grainEnabled = enabled; + this._buildPipeline(); + } + get grainEnabled() { + return this._grainEnabled; + } + /** + * Instantiates a DefaultRenderingPipeline. + * @param name The rendering pipeline name (default: "") + * @param hdr If high dynamic range textures should be used (default: true) + * @param scene The scene linked to this pipeline (default: the last created scene) + * @param cameras The array of cameras that the rendering pipeline will be attached to (default: scene.cameras) + * @param automaticBuild If false, you will have to manually call prepare() to update the pipeline (default: true) + */ + constructor(name = "", hdr = true, scene = EngineStore.LastCreatedScene, cameras, automaticBuild = true) { + super(scene.getEngine(), name); + this._camerasToBeAttached = []; + /** + * ID of the sharpen post process, + */ + this.SharpenPostProcessId = "SharpenPostProcessEffect"; + /** + * @ignore + * ID of the image processing post process; + */ + this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect"; + /** + * @ignore + * ID of the Fast Approximate Anti-Aliasing post process; + */ + this.FxaaPostProcessId = "FxaaPostProcessEffect"; + /** + * ID of the chromatic aberration post process, + */ + this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect"; + /** + * ID of the grain post process + */ + this.GrainPostProcessId = "GrainPostProcessEffect"; + /** + * Glow post process which adds a glow to emissive areas of the image + */ + this._glowLayer = null; + /** + * Animations which can be used to tweak settings over a period of time + */ + this.animations = []; + this._imageProcessingConfigurationObserver = null; + // Values + this._sharpenEnabled = false; + this._bloomEnabled = false; + this._depthOfFieldEnabled = false; + this._depthOfFieldBlurLevel = 0 /* DepthOfFieldEffectBlurLevel.Low */; + this._fxaaEnabled = false; + this._imageProcessingEnabled = true; + this._bloomScale = 0.5; + this._chromaticAberrationEnabled = false; + this._grainEnabled = false; + this._buildAllowed = true; + /** + * This is triggered each time the pipeline has been built. + */ + this.onBuildObservable = new Observable(); + this._resizeObserver = null; + this._hardwareScaleLevel = 1.0; + this._bloomKernel = 64; + /** + * Specifies the weight of the bloom in the final rendering + */ + this._bloomWeight = 0.15; + /** + * Specifies the luma threshold for the area that will be blurred by the bloom + */ + this._bloomThreshold = 0.9; + this._samples = 1; + this._hasCleared = false; + this._prevPostProcess = null; + this._prevPrevPostProcess = null; + this._depthOfFieldSceneObserver = null; + this._activeCameraChangedObserver = null; + this._activeCamerasChangedObserver = null; + this._cameras = cameras || scene.cameras; + this._cameras = this._cameras.slice(); + this._camerasToBeAttached = this._cameras.slice(); + this._buildAllowed = automaticBuild; + // Initialize + this._scene = scene; + const caps = this._scene.getEngine().getCaps(); + this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender); + // Misc + if (this._hdr) { + if (caps.textureHalfFloatRender) { + this._defaultPipelineTextureType = 2; + } + else if (caps.textureFloatRender) { + this._defaultPipelineTextureType = 1; + } + } + else { + this._defaultPipelineTextureType = 0; + } + // Attach + scene.postProcessRenderPipelineManager.addPipeline(this); + const engine = this._scene.getEngine(); + // Create post processes before hand so they can be modified before enabled. + // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline. + this.sharpen = new SharpenPostProcess("sharpen", 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, true); + this._sharpenEffect = new PostProcessRenderEffect(engine, this.SharpenPostProcessId, () => { + return this.sharpen; + }, true); + this.depthOfField = new DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, true); + // To keep the bloom sizes consistent across different display densities, factor in the hardware scaling level. + this._hardwareScaleLevel = engine.getHardwareScalingLevel(); + this._resizeObserver = engine.onResizeObservable.add(() => { + this._hardwareScaleLevel = engine.getHardwareScalingLevel(); + this.bloomKernel = this._bloomKernel; + }); + this.bloom = new BloomEffect(this._scene, this._bloomScale, this._bloomWeight, this.bloomKernel / this._hardwareScaleLevel, this._defaultPipelineTextureType, true); + this.chromaticAberration = new ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, true); + this._chromaticAberrationEffect = new PostProcessRenderEffect(engine, this.ChromaticAberrationPostProcessId, () => { + return this.chromaticAberration; + }, true); + this.grain = new GrainPostProcess("Grain", 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, true); + this._grainEffect = new PostProcessRenderEffect(engine, this.GrainPostProcessId, () => { + return this.grain; + }, true); + let avoidReentrancyAtConstructionTime = true; + this._imageProcessingConfigurationObserver = this._scene.imageProcessingConfiguration.onUpdateParameters.add(() => { + this.bloom._downscale._exposure = this._scene.imageProcessingConfiguration.exposure; + if (this.imageProcessingEnabled !== this._scene.imageProcessingConfiguration.isEnabled) { + this._imageProcessingEnabled = this._scene.imageProcessingConfiguration.isEnabled; + // Avoid re-entrant problems by deferring the call to _buildPipeline because the call to _buildPipeline + // at the end of the constructor could end up triggering imageProcessingConfiguration.onUpdateParameters! + // Note that the pipeline could have been disposed before the deferred call was executed, but in that case + // _buildAllowed will have been set to false, preventing _buildPipeline from being executed. + if (avoidReentrancyAtConstructionTime) { + Tools.SetImmediate(() => { + this._buildPipeline(); + }); + } + else { + this._buildPipeline(); + } + } + }); + this._buildPipeline(); + avoidReentrancyAtConstructionTime = false; + } + /** + * Get the class name + * @returns "DefaultRenderingPipeline" + */ + getClassName() { + return "DefaultRenderingPipeline"; + } + /** + * Force the compilation of the entire pipeline. + */ + prepare() { + const previousState = this._buildAllowed; + this._buildAllowed = true; + this._buildPipeline(); + this._buildAllowed = previousState; + } + _setAutoClearAndTextureSharing(postProcess, skipTextureSharing = false) { + if (this._hasCleared) { + postProcess.autoClear = false; + } + else { + postProcess.autoClear = true; + this._scene.autoClear = false; + this._hasCleared = true; + } + if (!skipTextureSharing) { + if (this._prevPrevPostProcess) { + postProcess.shareOutputWith(this._prevPrevPostProcess); + } + else { + postProcess.useOwnOutput(); + } + if (this._prevPostProcess) { + this._prevPrevPostProcess = this._prevPostProcess; + } + this._prevPostProcess = postProcess; + } + } + _buildPipeline() { + if (!this._buildAllowed) { + return; + } + this._scene.autoClear = true; + const engine = this._scene.getEngine(); + this._disposePostProcesses(); + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); + // get back cameras to be used to reattach pipeline + this._cameras = this._camerasToBeAttached.slice(); + } + this._reset(); + this._prevPostProcess = null; + this._prevPrevPostProcess = null; + this._hasCleared = false; + if (this.depthOfFieldEnabled) { + // Multi camera suport + if (this._cameras.length > 1) { + for (const camera of this._cameras) { + const depthRenderer = this._scene.enableDepthRenderer(camera); + depthRenderer.useOnlyInActiveCamera = true; + } + this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add((scene) => { + if (this._cameras.indexOf(scene.activeCamera) > -1) { + this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap(); + } + }); + } + else { + this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver); + const depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]); + this.depthOfField.depthTexture = depthRenderer.getDepthMap(); + } + if (!this.depthOfField._isReady()) { + this.depthOfField._updateEffects(); + } + this.addEffect(this.depthOfField); + this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true); + } + else { + this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver); + } + if (this.bloomEnabled) { + if (!this.bloom._isReady()) { + this.bloom._updateEffects(); + } + this.addEffect(this.bloom); + this._setAutoClearAndTextureSharing(this.bloom._effects[0], true); + } + if (this._imageProcessingEnabled) { + this.imageProcessing = new ImageProcessingPostProcess("imageProcessing", 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, this.scene.imageProcessingConfiguration); + if (this._hdr) { + this.addEffect(new PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, () => { + return this.imageProcessing; + }, true)); + this._setAutoClearAndTextureSharing(this.imageProcessing); + } + else { + this._scene.imageProcessingConfiguration.applyByPostProcess = false; + } + if (!this._cameras || this._cameras.length === 0) { + this._scene.imageProcessingConfiguration.applyByPostProcess = false; + } + if (!this.imageProcessing.getEffect()) { + this.imageProcessing._updateParameters(); + } + } + if (this.sharpenEnabled) { + if (!this.sharpen.isReady()) { + this.sharpen.updateEffect(); + } + this.addEffect(this._sharpenEffect); + this._setAutoClearAndTextureSharing(this.sharpen); + } + if (this.grainEnabled) { + if (!this.grain.isReady()) { + this.grain.updateEffect(); + } + this.addEffect(this._grainEffect); + this._setAutoClearAndTextureSharing(this.grain); + } + if (this.chromaticAberrationEnabled) { + if (!this.chromaticAberration.isReady()) { + this.chromaticAberration.updateEffect(); + } + this.addEffect(this._chromaticAberrationEffect); + this._setAutoClearAndTextureSharing(this.chromaticAberration); + } + if (this.fxaaEnabled) { + this.fxaa = new FxaaPostProcess("fxaa", 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); + this.addEffect(new PostProcessRenderEffect(engine, this.FxaaPostProcessId, () => { + return this.fxaa; + }, true)); + this._setAutoClearAndTextureSharing(this.fxaa, true); + } + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); + } + // In multicamera mode, the scene needs to autoclear in between cameras. + if ((this._scene.activeCameras && this._scene.activeCameras.length > 1) || (this._scene.activeCamera && this._cameras.indexOf(this._scene.activeCamera) === -1)) { + this._scene.autoClear = true; + } + // The active camera on the scene can be changed anytime + if (!this._activeCameraChangedObserver) { + this._activeCameraChangedObserver = this._scene.onActiveCameraChanged.add(() => { + if (this._scene.activeCamera && this._cameras.indexOf(this._scene.activeCamera) === -1) { + this._scene.autoClear = true; + } + }); + } + if (!this._activeCamerasChangedObserver) { + this._activeCamerasChangedObserver = this._scene.onActiveCamerasChanged.add(() => { + if (this._scene.activeCameras && this._scene.activeCameras.length > 1) { + this._scene.autoClear = true; + } + }); + } + this._adaptPostProcessesToViewPort(); + if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) { + Logger.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"); + } + this.onBuildObservable.notifyObservers(this); + } + _disposePostProcesses(disposeNonRecreated = false) { + for (let i = 0; i < this._cameras.length; i++) { + const camera = this._cameras[i]; + if (this.imageProcessing) { + this.imageProcessing.dispose(camera); + } + if (this.fxaa) { + this.fxaa.dispose(camera); + } + // These are created in the constructor and should not be disposed on every pipeline change + if (disposeNonRecreated) { + if (this.sharpen) { + this.sharpen.dispose(camera); + } + if (this.depthOfField) { + this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver); + this.depthOfField.disposeEffects(camera); + } + if (this.bloom) { + this.bloom.disposeEffects(camera); + } + if (this.chromaticAberration) { + this.chromaticAberration.dispose(camera); + } + if (this.grain) { + this.grain.dispose(camera); + } + if (this._glowLayer) { + this._glowLayer.dispose(); + } + } + } + this.imageProcessing = null; + this.fxaa = null; + if (disposeNonRecreated) { + this.sharpen = null; + this._sharpenEffect = null; + this.depthOfField = null; + this.bloom = null; + this.chromaticAberration = null; + this._chromaticAberrationEffect = null; + this.grain = null; + this._grainEffect = null; + this._glowLayer = null; + } + } + /** + * Adds a camera to the pipeline + * @param camera the camera to be added + */ + addCamera(camera) { + this._camerasToBeAttached.push(camera); + this._buildPipeline(); + } + /** + * Removes a camera from the pipeline + * @param camera the camera to remove + */ + removeCamera(camera) { + const index = this._camerasToBeAttached.indexOf(camera); + this._camerasToBeAttached.splice(index, 1); + this._buildPipeline(); + } + /** + * Dispose of the pipeline and stop all post processes + */ + dispose() { + this._buildAllowed = false; + this.onBuildObservable.clear(); + this._disposePostProcesses(true); + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); + this._scene._postProcessRenderPipelineManager.removePipeline(this.name); + this._scene.autoClear = true; + if (this._resizeObserver) { + this._scene.getEngine().onResizeObservable.remove(this._resizeObserver); + this._resizeObserver = null; + } + this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver); + this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver); + this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver); + super.dispose(); + } + /** + * Serialize the rendering pipeline (Used when exporting) + * @returns the serialized object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.customType = "DefaultRenderingPipeline"; + return serializationObject; + } + /** + * Parse the serialized pipeline + * @param source Source pipeline. + * @param scene The scene to load the pipeline to. + * @param rootUrl The URL of the serialized pipeline. + * @returns An instantiated pipeline from the serialized object. + */ + static Parse(source, scene, rootUrl) { + return SerializationHelper.Parse(() => new DefaultRenderingPipeline(source._name, source._name._hdr, scene), source, scene, rootUrl); + } +} +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "sharpenEnabled", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "bloomKernel", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "_hdr", void 0); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "bloomWeight", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "bloomThreshold", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "bloomScale", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "bloomEnabled", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "fxaaEnabled", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "samples", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null); +__decorate([ + serialize() +], DefaultRenderingPipeline.prototype, "grainEnabled", null); +RegisterClass("BABYLON.DefaultRenderingPipeline", DefaultRenderingPipeline); + +// Do not edit. +const name$2W = "chromaticAberrationPixelShader"; +const shader$2V = `uniform sampler2D textureSampler; +uniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);} +float radius2=centered_screen_pos.x*centered_screen_pos.x ++ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);vec4 r=texture2D(textureSampler,ref_coords_r);vec4 g=texture2D(textureSampler,ref_coords_g);vec4 b=texture2D(textureSampler,ref_coords_b);float a=clamp(r.a+g.a+b.a,0.,1.);gl_FragColor=vec4(r.r,g.g,b.b,a);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2W]) { + ShaderStore.ShadersStore[name$2W] = shader$2V; +} +/** @internal */ +const chromaticAberrationPixelShader = { name: name$2W, shader: shader$2V }; + +const chromaticAberration_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + chromaticAberrationPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2V = "lensHighlightsPixelShader"; +const shader$2U = `uniform sampler2D textureSampler; +uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } +else { lum_threshold=0.5+0.44*threshold; } +luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} +float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); +#ifdef PENTAGON +blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); +#else +blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); +#endif +blurred/=39.0;gl_FragColor=blurred;}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2V]) { + ShaderStore.ShadersStore[name$2V] = shader$2U; +} + +// Do not edit. +const name$2U = "depthOfFieldPixelShader"; +const shader$2T = `uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; +uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; +#define PI 3.14159265 +#define TWOPI 6.28318530 +#define inverse_focal_length 0.1 +vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) +{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} +vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } +vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} +float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} +float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} +vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} +if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} +col/=total_weight; +if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} +return col;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); +vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); +float depth=texture2D(depthSampler,distorted_coords).r; +float distance=near+(far-near)*depth; +vec4 color=texture2D(textureSampler,vUV); +float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } +float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} +float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} +else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} +if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} +if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2U]) { + ShaderStore.ShadersStore[name$2U] = shader$2T; +} + +/** + * Contains all parameters needed for the prepass to perform + * screen space subsurface scattering + */ +class SSAO2Configuration { + constructor() { + /** + * Is subsurface enabled + */ + this.enabled = false; + /** + * Name of the configuration + */ + this.name = "ssao2"; + /** + * Textures that should be present in the MRT for this effect to work + */ + this.texturesRequired = [6, 5]; + } +} + +/** + * Render pipeline to produce ssao effect + */ +class SSAO2RenderingPipeline extends PostProcessRenderPipeline { + /** + * Used in SSAO calculations to compensate for accuracy issues with depth values. Default 0.02. + * + * Normally you do not need to change this value, but you can experiment with it if you get a lot of in false self-occlusion on flat surfaces when using fewer than 16 samples. Useful range is normally [0..0.1] but higher values is allowed. + */ + set epsilon(n) { + this._epsilon = n; + this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO()); + } + get epsilon() { + return this._epsilon; + } + /** + * Number of samples used for the SSAO calculations. Default value is 8. + */ + set samples(n) { + this._samples = n; + this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO()); + this._sampleSphere = this._generateHemisphere(); + } + get samples() { + return this._samples; + } + /** + * Number of samples to use for antialiasing. + */ + set textureSamples(n) { + this._textureSamples = n; + if (this._prePassRenderer) { + this._prePassRenderer.samples = n; + } + else { + this._originalColorPostProcess.samples = n; + } + } + get textureSamples() { + return this._textureSamples; + } + get _geometryBufferRenderer() { + if (!this._forceGeometryBuffer) { + return null; + } + return this._scene.geometryBufferRenderer; + } + get _prePassRenderer() { + if (this._forceGeometryBuffer) { + return null; + } + return this._scene.prePassRenderer; + } + /** + * Skips the denoising (blur) stage of the SSAO calculations. + * + * Useful to temporarily set while experimenting with the other SSAO2 settings. + */ + set bypassBlur(b) { + const defines = this._getDefinesForBlur(this.expensiveBlur, b); + const samplers = this._getSamplersForBlur(b); + this._blurHPostProcess.updateEffect(defines.h, null, samplers); + this._blurVPostProcess.updateEffect(defines.v, null, samplers); + this._bypassBlur = b; + } + get bypassBlur() { + return this._bypassBlur; + } + /** + * Enables the configurable bilateral denoising (blurring) filter. Default is true. + * Set to false to instead use a legacy bilateral filter that can't be configured. + * + * The denoising filter runs after the SSAO calculations and is a very important step. Both options results in a so called bilateral being used, but the "expensive" one can be + * configured in several ways to fit your scene. + */ + set expensiveBlur(b) { + const defines = this._getDefinesForBlur(b, this._bypassBlur); + this._blurHPostProcess.updateEffect(defines.h); + this._blurVPostProcess.updateEffect(defines.v); + this._expensiveBlur = b; + } + get expensiveBlur() { + return this._expensiveBlur; + } + /** + * Support test. + */ + static get IsSupported() { + const engine = EngineStore.LastCreatedEngine; + if (!engine) { + return false; + } + return engine._features.supportSSAO2; + } + /** + * Gets active scene + */ + get scene() { + return this._scene; + } + /** + * @constructor + * @param name The rendering pipeline name + * @param scene The scene linked to this pipeline + * @param ratio The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 } + * @param cameras The array of cameras that the rendering pipeline will be attached to + * @param forceGeometryBuffer Set to true if you want to use the legacy geometry buffer renderer + * @param textureType The texture type used by the different post processes created by SSAO (default: 0) + */ + constructor(name, scene, ratio, cameras, forceGeometryBuffer = false, textureType = 0) { + super(scene.getEngine(), name); + // Members + /** + * @ignore + * The PassPostProcess id in the pipeline that contains the original scene color + */ + this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect"; + /** + * @ignore + * The SSAO PostProcess id in the pipeline + */ + this.SSAORenderEffect = "SSAORenderEffect"; + /** + * @ignore + * The horizontal blur PostProcess id in the pipeline + */ + this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect"; + /** + * @ignore + * The vertical blur PostProcess id in the pipeline + */ + this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect"; + /** + * @ignore + * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect) + */ + this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect"; + /** + * The output strength of the SSAO post-process. Default value is 1.0. + */ + this.totalStrength = 1.0; + /** + * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change. + */ + this.maxZ = 100.0; + /** + * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much. + */ + this.minZAspect = 0.2; + this._epsilon = 0.02; + this._samples = 8; + this._textureSamples = 1; + /** + * Force rendering the geometry through geometry buffer. + */ + this._forceGeometryBuffer = false; + /** + * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0 + */ + this.radius = 2.0; + /** + * The base color of the SSAO post-process + * The final result is "base + ssao" between [0, 1] + */ + this.base = 0; + this._bypassBlur = false; + this._expensiveBlur = true; + /** + * The number of samples the bilateral filter uses in both dimensions when denoising the SSAO calculations. Default value is 16. + * + * A higher value should result in smoother shadows but will use more processing time in the shaders. + * + * A high value can cause the shadows to get to blurry or create visible artifacts (bands) near sharp details in the geometry. The artifacts can sometimes be mitigated by increasing the bilateralSoften setting. + */ + this.bilateralSamples = 16; + /** + * Controls the shape of the denoising kernel used by the bilateral filter. Default value is 0. + * + * By default the bilateral filter acts like a box-filter, treating all samples on the same depth with equal weights. This is effective to maximize the denoising effect given a limited set of samples. However, it also often results in visible ghosting around sharp shadow regions and can spread out lines over large areas so they are no longer visible. + * + * Increasing this setting will make the filter pay less attention to samples further away from the center sample, reducing many artifacts but at the same time increasing noise. + * + * Useful value range is [0..1]. + */ + this.bilateralSoften = 0; + /** + * How forgiving the bilateral denoiser should be when rejecting samples. Default value is 0. + * + * A higher value results in the bilateral filter being more forgiving and thus doing a better job at denoising slanted and curved surfaces, but can lead to shadows spreading out around corners or between objects that are close to each other depth wise. + * + * Useful value range is normally [0..1], but higher values are allowed. + */ + this.bilateralTolerance = 0; + this._bits = new Uint32Array(1); + this._scene = scene; + this._ratio = ratio; + this._textureType = textureType; + this._forceGeometryBuffer = forceGeometryBuffer; + if (!this.isSupported) { + Logger.Error("The current engine does not support SSAO 2."); + return; + } + const ssaoRatio = this._ratio.ssaoRatio || ratio; + const blurRatio = this._ratio.blurRatio || ratio; + // Set up assets + if (this._forceGeometryBuffer) { + scene.enableGeometryBufferRenderer(); + if (scene.geometryBufferRenderer?.generateNormalsInWorldSpace) { + Logger.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"); + } + } + else { + scene.enablePrePassRenderer(); + if (scene.prePassRenderer?.generateNormalsInWorldSpace) { + Logger.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!"); + } + } + this._createRandomTexture(); + this._originalColorPostProcess = new PassPostProcess("SSAOOriginalSceneColor", 1.0, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), undefined, this._textureType); + this._originalColorPostProcess.samples = this.textureSamples; + this._createSSAOPostProcess(1.0, textureType); + this._createBlurPostProcess(ssaoRatio, blurRatio, this._textureType); + this._createSSAOCombinePostProcess(blurRatio, this._textureType); + // Set up pipeline + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, () => { + return this._originalColorPostProcess; + }, true)); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => { + return this._ssaoPostProcess; + }, true)); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => { + return this._blurHPostProcess; + }, true)); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => { + return this._blurVPostProcess; + }, true)); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => { + return this._ssaoCombinePostProcess; + }, true)); + // Finish + scene.postProcessRenderPipelineManager.addPipeline(this); + if (cameras) { + scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras); + } + } + // Public Methods + /** + * Get the class name + * @returns "SSAO2RenderingPipeline" + */ + getClassName() { + return "SSAO2RenderingPipeline"; + } + /** + * Removes the internal pipeline assets and detaches the pipeline from the scene cameras + * @param disableGeometryBufferRenderer Set to true if you want to disable the Geometry Buffer renderer + */ + dispose(disableGeometryBufferRenderer = false) { + for (let i = 0; i < this._scene.cameras.length; i++) { + const camera = this._scene.cameras[i]; + this._originalColorPostProcess.dispose(camera); + this._ssaoPostProcess.dispose(camera); + this._blurHPostProcess.dispose(camera); + this._blurVPostProcess.dispose(camera); + this._ssaoCombinePostProcess.dispose(camera); + } + this._randomTexture.dispose(); + if (disableGeometryBufferRenderer) { + this._scene.disableGeometryBufferRenderer(); + } + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras); + super.dispose(); + } + // Private Methods + /** @internal */ + _rebuild() { + super._rebuild(); + } + _getSamplersForBlur(disabled) { + return disabled ? ["textureSampler"] : ["textureSampler", "depthSampler"]; + } + _getDefinesForBlur(bilateral, disabled) { + let define = "#define BLUR\n"; + if (disabled) { + define += "#define BLUR_BYPASS\n"; + } + if (!bilateral) { + define += "#define BLUR_LEGACY\n"; + } + return { h: define + "#define BLUR_H\n", v: define }; + } + _createBlurPostProcess(ssaoRatio, blurRatio, textureType) { + const defines = this._getDefinesForBlur(this.expensiveBlur, this.bypassBlur); + const samplers = this._getSamplersForBlur(this.bypassBlur); + this._blurHPostProcess = this._createBlurFilter("BlurH", samplers, ssaoRatio, defines.h, textureType, true); + this._blurVPostProcess = this._createBlurFilter("BlurV", samplers, blurRatio, defines.v, textureType, false); + } + _createBlurFilter(name, samplers, ratio, defines, textureType, horizontal) { + const blurFilter = new PostProcess(name, "ssao2", ["outSize", "samples", "soften", "tolerance"], samplers, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, defines, textureType, undefined, undefined, undefined, undefined, this._scene.getEngine().isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, (useWebGPU, list) => { + if (useWebGPU) { + list.push(Promise.resolve().then(() => ssao2_fragment)); + } + else { + list.push(Promise.resolve().then(() => ssao2_fragment$1)); + } + }); + blurFilter.onApply = (effect) => { + if (!this._scene.activeCamera) { + return; + } + const ratio = this._ratio.blurRatio || this._ratio; + const ssaoCombineSize = horizontal ? this._originalColorPostProcess.width * ratio : this._originalColorPostProcess.height * ratio; + const originalColorSize = horizontal ? this._originalColorPostProcess.width : this._originalColorPostProcess.height; + effect.setFloat("outSize", ssaoCombineSize > 0 ? ssaoCombineSize : originalColorSize); + effect.setInt("samples", this.bilateralSamples); + effect.setFloat("soften", this.bilateralSoften); + effect.setFloat("tolerance", this.bilateralTolerance); + if (this._geometryBufferRenderer) { + effect.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[0]); + } + else if (this._prePassRenderer) { + effect.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]); + } + }; + blurFilter.samples = this.textureSamples; + blurFilter.autoClear = false; + return blurFilter; + } + //Van der Corput radical inverse + _radicalInverse_VdC(i) { + this._bits[0] = i; + this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0; + this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | (((this._bits[0] & 0xaaaaaaaa) >>> 1) >>> 0); + this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | (((this._bits[0] & 0xcccccccc) >>> 2) >>> 0); + this._bits[0] = ((this._bits[0] & 0x0f0f0f0f) << 4) | (((this._bits[0] & 0xf0f0f0f0) >>> 4) >>> 0); + this._bits[0] = ((this._bits[0] & 0x00ff00ff) << 8) | (((this._bits[0] & 0xff00ff00) >>> 8) >>> 0); + return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296 + } + _hammersley(i, n) { + return [i / n, this._radicalInverse_VdC(i)]; + } + _hemisphereSample_uniform(u, v) { + const phi = v * 2.0 * Math.PI; + // rejecting samples that are close to tangent plane to avoid z-fighting artifacts + const cosTheta = 1.0 - u * 0.85; + const sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta); + return new Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta); + } + _generateHemisphere() { + const numSamples = this.samples; + const result = []; + let vector; + let i = 0; + while (i < numSamples) { + if (numSamples < 16) { + vector = this._hemisphereSample_uniform(Math.random(), Math.random()); + } + else { + const rand = this._hammersley(i, numSamples); + vector = this._hemisphereSample_uniform(rand[0], rand[1]); + } + result.push(vector.x, vector.y, vector.z); + i++; + } + return result; + } + _getDefinesForSSAO() { + const defines = `#define SSAO\n#define SAMPLES ${this.samples}\n#define EPSILON ${this.epsilon.toFixed(4)}`; + return defines; + } + _createSSAOPostProcess(ratio, textureType) { + this._sampleSphere = this._generateHemisphere(); + const defines = this._getDefinesForSSAO(); + const samplers = ["randomSampler", "depthSampler", "normalSampler"]; + this._ssaoPostProcess = new PostProcess("ssao2", "ssao2", [ + "sampleSphere", + "samplesFactor", + "randTextureTiles", + "totalStrength", + "radius", + "base", + "range", + "projection", + "near", + "texelSize", + "xViewport", + "yViewport", + "maxZ", + "minZAspect", + "depthProjection", + ], samplers, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, defines, textureType, undefined, undefined, undefined, undefined, this._scene.getEngine().isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, (useWebGPU, list) => { + if (useWebGPU) { + list.push(Promise.resolve().then(() => ssao2_fragment)); + } + else { + list.push(Promise.resolve().then(() => ssao2_fragment$1)); + } + }); + this._ssaoPostProcess.autoClear = false; + this._ssaoPostProcess.onApply = (effect) => { + if (!this._scene.activeCamera) { + return; + } + effect.setArray3("sampleSphere", this._sampleSphere); + effect.setFloat("randTextureTiles", 32.0); + effect.setFloat("samplesFactor", 1 / this.samples); + effect.setFloat("totalStrength", this.totalStrength); + effect.setFloat2("texelSize", 1 / this._ssaoPostProcess.width, 1 / this._ssaoPostProcess.height); + effect.setFloat("radius", this.radius); + effect.setFloat("maxZ", this.maxZ); + effect.setFloat("minZAspect", this.minZAspect); + effect.setFloat("base", this.base); + effect.setFloat("near", this._scene.activeCamera.minZ); + if (this._scene.activeCamera.mode === Camera.PERSPECTIVE_CAMERA) { + effect.setMatrix3x3("depthProjection", SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION); + effect.setFloat("xViewport", Math.tan(this._scene.activeCamera.fov / 2) * this._scene.getEngine().getAspectRatio(this._scene.activeCamera, true)); + effect.setFloat("yViewport", Math.tan(this._scene.activeCamera.fov / 2)); + } + else { + const halfWidth = this._scene.getEngine().getRenderWidth() / 2.0; + const halfHeight = this._scene.getEngine().getRenderHeight() / 2.0; + const orthoLeft = this._scene.activeCamera.orthoLeft ?? -halfWidth; + const orthoRight = this._scene.activeCamera.orthoRight ?? halfWidth; + const orthoBottom = this._scene.activeCamera.orthoBottom ?? -halfHeight; + const orthoTop = this._scene.activeCamera.orthoTop ?? halfHeight; + effect.setMatrix3x3("depthProjection", SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION); + effect.setFloat("xViewport", (orthoRight - orthoLeft) * 0.5); + effect.setFloat("yViewport", (orthoTop - orthoBottom) * 0.5); + } + effect.setMatrix("projection", this._scene.getProjectionMatrix()); + if (this._geometryBufferRenderer) { + effect.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[0]); + effect.setTexture("normalSampler", this._geometryBufferRenderer.getGBuffer().textures[1]); + } + else if (this._prePassRenderer) { + effect.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]); + effect.setTexture("normalSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)]); + } + effect.setTexture("randomSampler", this._randomTexture); + }; + this._ssaoPostProcess.samples = this.textureSamples; + if (!this._forceGeometryBuffer) { + this._ssaoPostProcess._prePassEffectConfiguration = new SSAO2Configuration(); + } + } + _createSSAOCombinePostProcess(ratio, textureType) { + this._ssaoCombinePostProcess = new PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, undefined, textureType, undefined, undefined, undefined, undefined, this._scene.getEngine().isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, (useWebGPU, list) => { + if (useWebGPU) { + list.push(Promise.resolve().then(() => ssaoCombine_fragment)); + } + else { + list.push(Promise.resolve().then(() => ssaoCombine_fragment$1)); + } + }); + this._ssaoCombinePostProcess.onApply = (effect) => { + const viewport = this._scene.activeCamera.viewport; + effect.setVector4("viewport", TmpVectors.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height)); + effect.setTextureFromPostProcessOutput("originalColor", this._originalColorPostProcess); + }; + this._ssaoCombinePostProcess.autoClear = false; + this._ssaoCombinePostProcess.samples = this.textureSamples; + } + _createRandomTexture() { + const size = 128; + const data = new Uint8Array(size * size * 4); + const randVector = Vector2.Zero(); + for (let index = 0; index < data.length;) { + randVector.set(RandomRange(0, 1), RandomRange(0, 1)).normalize().scaleInPlace(255); + data[index++] = Math.floor(randVector.x); + data[index++] = Math.floor(randVector.y); + data[index++] = 0; + data[index++] = 255; + } + const texture = RawTexture.CreateRGBATexture(data, size, size, this._scene, false, false, 2); + texture.name = "SSAORandomTexture"; + texture.wrapU = Texture.WRAP_ADDRESSMODE; + texture.wrapV = Texture.WRAP_ADDRESSMODE; + this._randomTexture = texture; + } + /** + * Serialize the rendering pipeline (Used when exporting) + * @returns the serialized object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.customType = "SSAO2RenderingPipeline"; + return serializationObject; + } + /** + * Parse the serialized pipeline + * @param source Source pipeline. + * @param scene The scene to load the pipeline to. + * @param rootUrl The URL of the serialized pipeline. + * @returns An instantiated pipeline from the serialized object. + */ + static Parse(source, scene, rootUrl) { + return SerializationHelper.Parse(() => new SSAO2RenderingPipeline(source._name, scene, source._ratio, undefined, source._forceGeometryBuffer, source._textureType), source, scene, rootUrl); + } +} +SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION = [1, 0, 0, 0, 1, 0, 0, 0, 1]; +SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION = [0, 0, 0, 0, 0, 0, 1, 1, 1]; +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "totalStrength", void 0); +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "maxZ", void 0); +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "minZAspect", void 0); +__decorate([ + serialize("epsilon") +], SSAO2RenderingPipeline.prototype, "_epsilon", void 0); +__decorate([ + serialize("samples") +], SSAO2RenderingPipeline.prototype, "_samples", void 0); +__decorate([ + serialize("textureSamples") +], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0); +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "_forceGeometryBuffer", void 0); +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "_ratio", void 0); +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "_textureType", void 0); +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "radius", void 0); +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "base", void 0); +__decorate([ + serialize("bypassBlur") +], SSAO2RenderingPipeline.prototype, "_bypassBlur", void 0); +__decorate([ + serialize("expensiveBlur") +], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0); +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "bilateralSamples", void 0); +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "bilateralSoften", void 0); +__decorate([ + serialize() +], SSAO2RenderingPipeline.prototype, "bilateralTolerance", void 0); +RegisterClass("BABYLON.SSAO2RenderingPipeline", SSAO2RenderingPipeline); + +// Do not edit. +const name$2T = "ssaoPixelShader"; +const shader$2S = `uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSAO +uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) +{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} +void main() +{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; i { + return this._originalColorPostProcess; + }, true)); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => { + return this._ssaoPostProcess; + }, true)); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => { + return this._blurHPostProcess; + }, true)); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => { + return this._blurVPostProcess; + }, true)); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => { + return this._ssaoCombinePostProcess; + }, true)); + // Finish + scene.postProcessRenderPipelineManager.addPipeline(this); + if (cameras) { + scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras); + } + } + /** + * @internal + */ + _attachCameras(cameras, unique) { + super._attachCameras(cameras, unique); + for (const camera of this._cameras) { + this._scene.enableDepthRenderer(camera).getDepthMap(); // Force depth renderer "on" + } + } + // Public Methods + /** + * Get the class name + * @returns "SSAORenderingPipeline" + */ + getClassName() { + return "SSAORenderingPipeline"; + } + /** + * Removes the internal pipeline assets and detaches the pipeline from the scene cameras + * @param disableDepthRender - If the depth renderer should be disabled on the scene + */ + dispose(disableDepthRender = false) { + for (let i = 0; i < this._scene.cameras.length; i++) { + const camera = this._scene.cameras[i]; + this._originalColorPostProcess.dispose(camera); + this._ssaoPostProcess.dispose(camera); + this._blurHPostProcess.dispose(camera); + this._blurVPostProcess.dispose(camera); + this._ssaoCombinePostProcess.dispose(camera); + } + this._randomTexture.dispose(); + if (disableDepthRender) { + this._scene.disableDepthRenderer(); + } + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras); + super.dispose(); + } + // Private Methods + _createBlurPostProcess(ratio) { + const size = 16; + this._blurHPostProcess = new BlurPostProcess("BlurH", new Vector2(1, 0), size, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, 0); + this._blurVPostProcess = new BlurPostProcess("BlurV", new Vector2(0, 1), size, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, 0); + this._blurHPostProcess.onActivateObservable.add(() => { + const dw = this._blurHPostProcess.width / this._scene.getEngine().getRenderWidth(); + this._blurHPostProcess.kernel = size * dw; + }); + this._blurVPostProcess.onActivateObservable.add(() => { + const dw = this._blurVPostProcess.height / this._scene.getEngine().getRenderHeight(); + this._blurVPostProcess.kernel = size * dw; + }); + } + /** @internal */ + _rebuild() { + this._firstUpdate = true; + super._rebuild(); + } + _createSSAOPostProcess(ratio) { + const numSamples = 16; + const sampleSphere = [ + 0.5381, 0.1856, -0.4319, 0.1379, 0.2486, 0.443, 0.3371, 0.5679, -57e-4, -0.6999, -0.0451, -19e-4, 0.0689, -0.1598, -0.8547, 0.056, 0.0069, -0.1843, -0.0146, 0.1402, + 0.0762, 0.01, -0.1924, -0.0344, -0.3577, -0.5301, -0.4358, -0.3169, 0.1063, 0.0158, 0.0103, -0.5869, 0.0046, -0.0897, -0.494, 0.3287, 0.7119, -0.0154, -0.0918, -0.0533, + 0.0596, -0.5411, 0.0352, -0.0631, 0.546, -0.4776, 0.2847, -0.0271, + ]; + const samplesFactor = 1.0 / numSamples; + this._ssaoPostProcess = new PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff", "base", "range", "viewport"], ["randomSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO"); + this._ssaoPostProcess.externalTextureSamplerBinding = true; + this._ssaoPostProcess.onApply = (effect) => { + if (this._firstUpdate) { + effect.setArray3("sampleSphere", sampleSphere); + effect.setFloat("samplesFactor", samplesFactor); + effect.setFloat("randTextureTiles", 4.0); + } + effect.setFloat("totalStrength", this.totalStrength); + effect.setFloat("radius", this.radius); + effect.setFloat("area", this.area); + effect.setFloat("fallOff", this.fallOff); + effect.setFloat("base", this.base); + effect.setTexture("textureSampler", this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()); + effect.setTexture("randomSampler", this._randomTexture); + }; + } + _createSSAOCombinePostProcess(ratio) { + this._ssaoCombinePostProcess = new PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false); + this._ssaoCombinePostProcess.onApply = (effect) => { + effect.setVector4("viewport", TmpVectors.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0)); + effect.setTextureFromPostProcess("originalColor", this._originalColorPostProcess); + }; + } + _createRandomTexture() { + const size = 512; + const data = new Uint8Array(size * size * 4); + for (let index = 0; index < data.length;) { + data[index++] = Math.floor(Math.max(0.0, RandomRange(-1, 1.0)) * 255); + data[index++] = Math.floor(Math.max(0.0, RandomRange(-1, 1.0)) * 255); + data[index++] = Math.floor(Math.max(0.0, RandomRange(-1, 1.0)) * 255); + data[index++] = 255; + } + const texture = RawTexture.CreateRGBATexture(data, size, size, this._scene, false, false, 2); + texture.name = "SSAORandomTexture"; + texture.wrapU = Texture.WRAP_ADDRESSMODE; + texture.wrapV = Texture.WRAP_ADDRESSMODE; + this._randomTexture = texture; + } +} +__decorate([ + serialize() +], SSAORenderingPipeline.prototype, "totalStrength", void 0); +__decorate([ + serialize() +], SSAORenderingPipeline.prototype, "radius", void 0); +__decorate([ + serialize() +], SSAORenderingPipeline.prototype, "area", void 0); +__decorate([ + serialize() +], SSAORenderingPipeline.prototype, "fallOff", void 0); +__decorate([ + serialize() +], SSAORenderingPipeline.prototype, "base", void 0); + +/** + * Contains all parameters needed for the prepass to perform + * screen space reflections + */ +class ScreenSpaceReflectionsConfiguration { + constructor() { + /** + * Is ssr enabled + */ + this.enabled = false; + /** + * Name of the configuration + */ + this.name = "screenSpaceReflections"; + /** + * Textures that should be present in the MRT for this effect to work + */ + this.texturesRequired = [6, 3, 1]; + } +} + +// Do not edit. +const name$2R = "screenSpaceReflectionPixelShader"; +const shader$2Q = `uniform sampler2D textureSampler; +#ifdef SSR_SUPPORTED +uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler; +#endif +uniform mat4 view;uniform mat4 projection;uniform float stepSize;uniform float strength;uniform float threshold;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;varying vec2 vUV; +#ifdef SSR_SUPPORTED +struct ReflectionInfo {vec3 color;vec4 coords;};/** +* According to specular,see https: +*/ +vec3 fresnelSchlick(float cosTheta,vec3 F0) +{return F0+(1.0-F0)*pow(1.0-cosTheta,5.0);} +/** +* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit +* by sampling multiple reflection pixels. +*/ +ReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord) +{ReflectionInfo info;info.color=vec3(0.0);vec4 projectedCoord;float sampledDepth;for(int i=0; i0.0) +hitCoord-=dir;else +hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} +projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} +/** +* Tests the given world position (hitCoord) according to the given reflection vector (dir) +* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). +*/ +ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) +{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i { + const geometryBufferRenderer = this._geometryBufferRenderer; + const prePassRenderer = this._prePassRenderer; + if (!prePassRenderer && !geometryBufferRenderer) { + return; + } + if (geometryBufferRenderer) { + // Samplers + const positionIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.POSITION_TEXTURE_TYPE); + const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE); + effect.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[1]); + effect.setTexture("positionSampler", geometryBufferRenderer.getGBuffer().textures[positionIndex]); + effect.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]); + } + else if (prePassRenderer) { + // Samplers + const positionIndex = prePassRenderer.getIndex(1); + const roughnessIndex = prePassRenderer.getIndex(3); + const normalIndex = prePassRenderer.getIndex(6); + effect.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]); + effect.setTexture("positionSampler", prePassRenderer.getRenderTarget().textures[positionIndex]); + effect.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]); + } + // Uniforms + const camera = scene.activeCamera; + if (!camera) { + return; + } + const viewMatrix = camera.getViewMatrix(true); + const projectionMatrix = camera.getProjectionMatrix(true); + effect.setMatrix("projection", projectionMatrix); + effect.setMatrix("view", viewMatrix); + effect.setFloat("threshold", this.threshold); + effect.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent); + effect.setFloat("strength", this.strength); + effect.setFloat("stepSize", this.step); + effect.setFloat("roughnessFactor", this.roughnessFactor); + }; + this._isSceneRightHanded = scene.useRightHandedSystem; + } + /** + * Gets whether or not smoothing reflections is enabled. + * Enabling smoothing will require more GPU power and can generate a drop in FPS. + */ + get enableSmoothReflections() { + return this._enableSmoothReflections; + } + /** + * Sets whether or not smoothing reflections is enabled. + * Enabling smoothing will require more GPU power and can generate a drop in FPS. + */ + set enableSmoothReflections(enabled) { + if (enabled === this._enableSmoothReflections) { + return; + } + this._enableSmoothReflections = enabled; + this._updateEffectDefines(); + } + /** + * Gets the number of samples taken while computing reflections. More samples count is high, + * more the post-process wil require GPU power and can generate a drop in FPS. Basically in interval [25, 100]. + */ + get reflectionSamples() { + return this._reflectionSamples; + } + /** + * Sets the number of samples taken while computing reflections. More samples count is high, + * more the post-process wil require GPU power and can generate a drop in FPS. Basically in interval [25, 100]. + */ + set reflectionSamples(samples) { + if (samples === this._reflectionSamples) { + return; + } + this._reflectionSamples = samples; + this._updateEffectDefines(); + } + /** + * Gets the number of samples taken while smoothing reflections. More samples count is high, + * more the post-process will require GPU power and can generate a drop in FPS. + * Default value (5.0) work pretty well in all cases but can be adjusted. + */ + get smoothSteps() { + return this._smoothSteps; + } + /* + * Sets the number of samples taken while smoothing reflections. More samples count is high, + * more the post-process will require GPU power and can generate a drop in FPS. + * Default value (5.0) work pretty well in all cases but can be adjusted. + */ + set smoothSteps(steps) { + if (steps === this._smoothSteps) { + return; + } + this._smoothSteps = steps; + this._updateEffectDefines(); + } + _updateEffectDefines() { + const defines = []; + if (this._geometryBufferRenderer || this._prePassRenderer) { + defines.push("#define SSR_SUPPORTED"); + } + if (this._enableSmoothReflections) { + defines.push("#define ENABLE_SMOOTH_REFLECTIONS"); + } + if (this._isSceneRightHanded) { + defines.push("#define RIGHT_HANDED_SCENE"); + } + defines.push("#define REFLECTION_SAMPLES " + (this._reflectionSamples >> 0)); + defines.push("#define SMOOTH_STEPS " + (this._smoothSteps >> 0)); + this.updateEffect(defines.join("\n")); + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new ScreenSpaceReflectionPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], ScreenSpaceReflectionPostProcess.prototype, "threshold", void 0); +__decorate([ + serialize() +], ScreenSpaceReflectionPostProcess.prototype, "strength", void 0); +__decorate([ + serialize() +], ScreenSpaceReflectionPostProcess.prototype, "reflectionSpecularFalloffExponent", void 0); +__decorate([ + serialize() +], ScreenSpaceReflectionPostProcess.prototype, "step", void 0); +__decorate([ + serialize() +], ScreenSpaceReflectionPostProcess.prototype, "roughnessFactor", void 0); +__decorate([ + serialize() +], ScreenSpaceReflectionPostProcess.prototype, "enableSmoothReflections", null); +__decorate([ + serialize() +], ScreenSpaceReflectionPostProcess.prototype, "reflectionSamples", null); +__decorate([ + serialize() +], ScreenSpaceReflectionPostProcess.prototype, "smoothSteps", null); +RegisterClass("BABYLON.ScreenSpaceReflectionPostProcess", ScreenSpaceReflectionPostProcess); + +// Do not edit. +const name$2Q = "standardPixelShader"; +const shader$2P = `uniform sampler2D textureSampler;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +#if defined(PASS_POST_PROCESS) +void main(void) +{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} +#endif +#if defined(DOWN_SAMPLE_X4) +uniform vec2 dsOffsets[16];void main(void) +{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} +#endif +#if defined(BRIGHT_PASS) +uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) +{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth) +accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} +accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} +#endif +#if defined(VLSMERGE) +uniform sampler2D originalSampler;void main(void) +{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} +#endif +#if defined(LUMINANCE) +uniform vec2 lumOffsets[4];void main() +{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) +{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); +#ifdef WEIGHTED_AVERAGE +float GreyValue=dot(color.rgb,weight); +#endif +#ifdef BRIGHTNESS +float GreyValue=max(color.r,max(color.g,color.b)); +#endif +#ifdef HSL_COMPONENT +float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); +#endif +#ifdef MAGNITUDE +float GreyValue=length(color.rgb); +#endif +maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} +average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} +#endif +#if defined(LUMINANCE_DOWN_SAMPLE) +uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; +#ifdef FINAL_DOWN_SAMPLER +#include +#endif +void main() +{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) +{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} +average/=9.0; +#ifdef FINAL_DOWN_SAMPLER +gl_FragColor=pack(average); +#else +gl_FragColor=vec4(average,average,0.0,1.0); +#endif +} +#endif +#if defined(HDR) +uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() +{vec4 color=texture2D(textureAdderSampler,vUV); +#ifndef AUTO_EXPOSURE +vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; +#endif +gl_FragColor=color;} +#endif +#if defined(LENS_FLARE) +#define GHOSTS 3 +uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) +{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} +float noise(in vec2 p) +{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), +hash(i+vec2(1.0,0.0)),u.x), +mix(hash(i+vec2(0.0,1.0)), +hash(i+vec2(1.0,1.0)),u.x),u.y);} +float fbm(vec2 p) +{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} +vec3 pattern(vec2 uv) +{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} +float luminance(vec3 color) +{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} +vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) +{return vec4( +texture2D(tex,texcoord+direction*distortion.r).r, +texture2D(tex,texcoord+direction*distortion.g).g, +texture2D(tex,texcoord+direction*distortion.b).b, +1.0 +);} +void main(void) +{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples) +break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} +gl_FragColor=result/float(nSamples);} +#endif +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2Q]) { + ShaderStore.ShadersStore[name$2Q] = shader$2P; +} + +/** + * Standard rendering pipeline + * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility. + * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/standardRenderingPipeline + */ +class StandardRenderingPipeline extends PostProcessRenderPipeline { + /** + * Gets the overall exposure used by the pipeline + */ + get exposure() { + return this._fixedExposure; + } + /** + * Sets the overall exposure used by the pipeline + */ + set exposure(value) { + this._fixedExposure = value; + this._currentExposure = value; + } + /** + * Gets whether or not the exposure of the overall pipeline should be automatically adjusted by the HDR post-process + */ + get hdrAutoExposure() { + return this._hdrAutoExposure; + } + /** + * Sets whether or not the exposure of the overall pipeline should be automatically adjusted by the HDR post-process + */ + set hdrAutoExposure(value) { + this._hdrAutoExposure = value; + if (this.hdrPostProcess) { + const defines = ["#define HDR"]; + if (value) { + defines.push("#define AUTO_EXPOSURE"); + } + this.hdrPostProcess.updateEffect(defines.join("\n")); + } + } + /** + * Gets how much the image is blurred by the movement while using the motion blur post-process + */ + get motionStrength() { + return this._motionStrength; + } + /** + * Sets how much the image is blurred by the movement while using the motion blur post-process + */ + set motionStrength(strength) { + this._motionStrength = strength; + if (this._isObjectBasedMotionBlur && this.motionBlurPostProcess) { + this.motionBlurPostProcess.motionStrength = strength; + } + } + /** + * Gets whether or not the motion blur post-process is object based or screen based. + */ + get objectBasedMotionBlur() { + return this._isObjectBasedMotionBlur; + } + /** + * Sets whether or not the motion blur post-process should be object based or screen based + */ + set objectBasedMotionBlur(value) { + const shouldRebuild = this._isObjectBasedMotionBlur !== value; + this._isObjectBasedMotionBlur = value; + if (shouldRebuild) { + this._buildPipeline(); + } + } + /** + * @ignore + * Specifies if the bloom pipeline is enabled + */ + get BloomEnabled() { + return this._bloomEnabled; + } + set BloomEnabled(enabled) { + if (this._bloomEnabled === enabled) { + return; + } + this._bloomEnabled = enabled; + this._buildPipeline(); + } + /** + * @ignore + * Specifies if the depth of field pipeline is enabled + */ + get DepthOfFieldEnabled() { + return this._depthOfFieldEnabled; + } + set DepthOfFieldEnabled(enabled) { + if (this._depthOfFieldEnabled === enabled) { + return; + } + this._depthOfFieldEnabled = enabled; + this._buildPipeline(); + } + /** + * @ignore + * Specifies if the lens flare pipeline is enabled + */ + get LensFlareEnabled() { + return this._lensFlareEnabled; + } + set LensFlareEnabled(enabled) { + if (this._lensFlareEnabled === enabled) { + return; + } + this._lensFlareEnabled = enabled; + this._buildPipeline(); + } + /** + * @ignore + * Specifies if the HDR pipeline is enabled + */ + get HDREnabled() { + return this._hdrEnabled; + } + set HDREnabled(enabled) { + if (this._hdrEnabled === enabled) { + return; + } + this._hdrEnabled = enabled; + this._buildPipeline(); + } + /** + * @ignore + * Specifies if the volumetric lights scattering effect is enabled + */ + get VLSEnabled() { + return this._vlsEnabled; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + set VLSEnabled(enabled) { + if (this._vlsEnabled === enabled) { + return; + } + if (enabled) { + const geometry = this._scene.enableGeometryBufferRenderer(); + if (!geometry) { + Logger.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline"); + return; + } + } + this._vlsEnabled = enabled; + this._buildPipeline(); + } + /** + * @ignore + * Specifies if the motion blur effect is enabled + */ + get MotionBlurEnabled() { + return this._motionBlurEnabled; + } + set MotionBlurEnabled(enabled) { + if (this._motionBlurEnabled === enabled) { + return; + } + this._motionBlurEnabled = enabled; + this._buildPipeline(); + } + /** + * Specifies if anti-aliasing is enabled + */ + get fxaaEnabled() { + return this._fxaaEnabled; + } + set fxaaEnabled(enabled) { + if (this._fxaaEnabled === enabled) { + return; + } + this._fxaaEnabled = enabled; + this._buildPipeline(); + } + /** + * Specifies if screen space reflections are enabled. + */ + get screenSpaceReflectionsEnabled() { + return this._screenSpaceReflectionsEnabled; + } + set screenSpaceReflectionsEnabled(enabled) { + if (this._screenSpaceReflectionsEnabled === enabled) { + return; + } + this._screenSpaceReflectionsEnabled = enabled; + this._buildPipeline(); + } + /** + * Specifies the number of steps used to calculate the volumetric lights + * Typically in interval [50, 200] + */ + get volumetricLightStepsCount() { + return this._volumetricLightStepsCount; + } + set volumetricLightStepsCount(count) { + if (this.volumetricLightPostProcess) { + this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1)); + } + this._volumetricLightStepsCount = count; + } + /** + * Specifies the number of samples used for the motion blur effect + * Typically in interval [16, 64] + */ + get motionBlurSamples() { + return this._motionBlurSamples; + } + set motionBlurSamples(samples) { + if (this.motionBlurPostProcess) { + if (this._isObjectBasedMotionBlur) { + this.motionBlurPostProcess.motionBlurSamples = samples; + } + else { + this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1)); + } + } + this._motionBlurSamples = samples; + } + /** + * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1) + */ + get samples() { + return this._samples; + } + set samples(sampleCount) { + if (this._samples === sampleCount) { + return; + } + this._samples = sampleCount; + this._buildPipeline(); + } + /** + * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility. + * @constructor + * @param name The rendering pipeline name + * @param scene The scene linked to this pipeline + * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) + * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null. + * @param cameras The array of cameras that the rendering pipeline will be attached to + */ + constructor(name, scene, ratio, originalPostProcess = null, cameras) { + super(scene.getEngine(), name); + /** + * Post-process used to down scale an image x4 + */ + this.downSampleX4PostProcess = null; + /** + * Post-process used to calculate the illuminated surfaces controlled by a threshold + */ + this.brightPassPostProcess = null; + /** + * Post-process array storing all the horizontal blur post-processes used by the pipeline + */ + this.blurHPostProcesses = []; + /** + * Post-process array storing all the vertical blur post-processes used by the pipeline + */ + this.blurVPostProcesses = []; + /** + * Post-process used to add colors of 2 textures (typically brightness + real scene color) + */ + this.textureAdderPostProcess = null; + /** + * Post-process used to create volumetric lighting effect + */ + this.volumetricLightPostProcess = null; + /** + * Post-process used to smooth the previous volumetric light post-process on the X axis + */ + this.volumetricLightSmoothXPostProcess = null; + /** + * Post-process used to smooth the previous volumetric light post-process on the Y axis + */ + this.volumetricLightSmoothYPostProcess = null; + /** + * Post-process used to merge the volumetric light effect and the real scene color + */ + this.volumetricLightMergePostProces = null; + /** + * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose) + */ + this.volumetricLightFinalPostProcess = null; + /** + * Base post-process used to calculate the average luminance of the final image for HDR + */ + this.luminancePostProcess = null; + /** + * Post-processes used to create down sample post-processes in order to get + * the average luminance of the final image for HDR + * Array of length "StandardRenderingPipeline.LuminanceSteps" + */ + this.luminanceDownSamplePostProcesses = []; + /** + * Post-process used to create a HDR effect (light adaptation) + */ + this.hdrPostProcess = null; + /** + * Post-process used to store the final texture adder post-process (attach/detach for debug purpose) + */ + this.textureAdderFinalPostProcess = null; + /** + * Post-process used to store the final lens flare post-process (attach/detach for debug purpose) + */ + this.lensFlareFinalPostProcess = null; + /** + * Post-process used to merge the final HDR post-process and the real scene color + */ + this.hdrFinalPostProcess = null; + /** + * Post-process used to create a lens flare effect + */ + this.lensFlarePostProcess = null; + /** + * Post-process that merges the result of the lens flare post-process and the real scene color + */ + this.lensFlareComposePostProcess = null; + /** + * Post-process used to create a motion blur effect + */ + this.motionBlurPostProcess = null; + /** + * Post-process used to create a depth of field effect + */ + this.depthOfFieldPostProcess = null; + /** + * The Fast Approximate Anti-Aliasing post process which attempts to remove aliasing from an image. + */ + this.fxaaPostProcess = null; + /** + * Post-process used to simulate realtime reflections using the screen space and geometry renderer. + */ + this.screenSpaceReflectionPostProcess = null; + // Values + /** + * Represents the brightness threshold in order to configure the illuminated surfaces + */ + this.brightThreshold = 1.0; + /** + * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo) + */ + this.blurWidth = 512.0; + /** + * Sets if the blur for highlighted surfaces must be only horizontal + */ + this.horizontalBlur = false; + /** + * Texture used typically to simulate "dirty" on camera lens + */ + this.lensTexture = null; + /** + * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2] + */ + this.volumetricLightCoefficient = 0.2; + /** + * The overall power of volumetric lights, typically in interval [0, 10] maximum + */ + this.volumetricLightPower = 4.0; + /** + * Used the set the blur intensity to smooth the volumetric lights + */ + this.volumetricLightBlurScale = 64.0; + /** + * Light (spot or directional) used to generate the volumetric lights rays + * The source light must have a shadow generate so the pipeline can get its + * depth map + */ + this.sourceLight = null; + /** + * For eye adaptation, represents the minimum luminance the eye can see + */ + this.hdrMinimumLuminance = 1.0; + /** + * For eye adaptation, represents the decrease luminance speed + */ + this.hdrDecreaseRate = 0.5; + /** + * For eye adaptation, represents the increase luminance speed + */ + this.hdrIncreaseRate = 0.5; + /** + * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled + */ + this.lensColorTexture = null; + /** + * The overall strength for the lens flare effect + */ + this.lensFlareStrength = 20.0; + /** + * Dispersion coefficient for lens flare ghosts + */ + this.lensFlareGhostDispersal = 1.4; + /** + * Main lens flare halo width + */ + this.lensFlareHaloWidth = 0.7; + /** + * Based on the lens distortion effect, defines how much the lens flare result + * is distorted + */ + this.lensFlareDistortionStrength = 16.0; + /** + * Configures the blur intensity used for for lens flare (halo) + */ + this.lensFlareBlurWidth = 512.0; + /** + * Lens star texture must be used to simulate rays on the flares and is available + * in the documentation + */ + this.lensStarTexture = null; + /** + * As the "lensTexture" (can be the same texture or different), it is used to apply the lens + * flare effect by taking account of the dirt texture + */ + this.lensFlareDirtTexture = null; + /** + * Represents the focal length for the depth of field effect + */ + this.depthOfFieldDistance = 10.0; + /** + * Represents the blur intensity for the blurred part of the depth of field effect + */ + this.depthOfFieldBlurWidth = 64.0; + /** + * List of animations for the pipeline (IAnimatable implementation) + */ + this.animations = []; + this._currentDepthOfFieldSource = null; + this._fixedExposure = 1.0; + this._currentExposure = 1.0; + this._hdrAutoExposure = false; + this._hdrCurrentLuminance = 1.0; + this._motionStrength = 1.0; + this._isObjectBasedMotionBlur = false; + this._camerasToBeAttached = []; + // Getters and setters + this._bloomEnabled = false; + this._depthOfFieldEnabled = false; + this._vlsEnabled = false; + this._lensFlareEnabled = false; + this._hdrEnabled = false; + this._motionBlurEnabled = false; + this._fxaaEnabled = false; + this._screenSpaceReflectionsEnabled = false; + this._motionBlurSamples = 64.0; + this._volumetricLightStepsCount = 50.0; + this._samples = 1; + this._cameras = cameras || scene.cameras; + this._cameras = this._cameras.slice(); + this._camerasToBeAttached = this._cameras.slice(); + // Initialize + this._scene = scene; + this._basePostProcess = originalPostProcess; + this._ratio = ratio; + // Misc + this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? 1 : 2; + // Finish + scene.postProcessRenderPipelineManager.addPipeline(this); + this._buildPipeline(); + } + _buildPipeline() { + const ratio = this._ratio; + const scene = this._scene; + this._disposePostProcesses(); + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); + // get back cameras to be used to reattach pipeline + this._cameras = this._camerasToBeAttached.slice(); + } + this._reset(); + // Create pass post-process + if (this._screenSpaceReflectionsEnabled) { + this.screenSpaceReflectionPostProcess = new ScreenSpaceReflectionPostProcess("HDRPass", scene, ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType); + this.screenSpaceReflectionPostProcess.onApplyObservable.add(() => { + this._currentDepthOfFieldSource = this.screenSpaceReflectionPostProcess; + }); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRScreenSpaceReflections", () => this.screenSpaceReflectionPostProcess, true)); + } + if (!this._basePostProcess) { + this.originalPostProcess = new PostProcess("HDRPass", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType); + } + else { + this.originalPostProcess = this._basePostProcess; + } + this.originalPostProcess.autoClear = !this.screenSpaceReflectionPostProcess; + this.originalPostProcess.onApplyObservable.add(() => { + this._currentDepthOfFieldSource = this.originalPostProcess; + }); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", () => this.originalPostProcess, true)); + if (this._bloomEnabled) { + // Create down sample X4 post-process + this._createDownSampleX4PostProcess(scene, ratio / 4); + // Create bright pass post-process + this._createBrightPassPostProcess(scene, ratio / 4); + // Create gaussian blur post-processes (down sampling blurs) + this._createBlurPostProcesses(scene, ratio / 4, 1); + // Create texture adder post-process + this._createTextureAdderPostProcess(scene, ratio); + // Create depth-of-field source post-process + this.textureAdderFinalPostProcess = new PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", () => { + return this.textureAdderFinalPostProcess; + }, true)); + } + if (this._vlsEnabled) { + // Create volumetric light + this._createVolumetricLightPostProcess(scene, ratio); + // Create volumetric light final post-process + this.volumetricLightFinalPostProcess = new PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", () => { + return this.volumetricLightFinalPostProcess; + }, true)); + } + if (this._lensFlareEnabled) { + // Create lens flare post-process + this._createLensFlarePostProcess(scene, ratio); + // Create depth-of-field source post-process post lens-flare and disable it now + this.lensFlareFinalPostProcess = new PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", () => { + return this.lensFlareFinalPostProcess; + }, true)); + } + if (this._hdrEnabled) { + // Create luminance + this._createLuminancePostProcesses(scene, this._floatTextureType); + // Create HDR + this._createHdrPostProcess(scene, ratio); + // Create depth-of-field source post-process post hdr and disable it now + this.hdrFinalPostProcess = new PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", () => { + return this.hdrFinalPostProcess; + }, true)); + } + if (this._depthOfFieldEnabled) { + // Create gaussian blur used by depth-of-field + this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth"); + // Create depth-of-field post-process + this._createDepthOfFieldPostProcess(scene, ratio); + } + if (this._motionBlurEnabled) { + // Create motion blur post-process + this._createMotionBlurPostProcess(scene, ratio); + } + if (this._fxaaEnabled) { + // Create fxaa post-process + this.fxaaPostProcess = new FxaaPostProcess("fxaa", 1.0, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, 0); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", () => { + return this.fxaaPostProcess; + }, true)); + } + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); + } + if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) { + Logger.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"); + } + } + // Down Sample X4 Post-Process + _createDownSampleX4PostProcess(scene, ratio) { + const downSampleX4Offsets = new Array(32); + this.downSampleX4PostProcess = new PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", this._floatTextureType); + this.downSampleX4PostProcess.onApply = (effect) => { + let id = 0; + const width = this.downSampleX4PostProcess.width; + const height = this.downSampleX4PostProcess.height; + for (let i = -2; i < 2; i++) { + for (let j = -2; j < 2; j++) { + downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width); + downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height); + id += 2; + } + } + effect.setArray2("dsOffsets", downSampleX4Offsets); + }; + // Add to pipeline + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", () => { + return this.downSampleX4PostProcess; + }, true)); + } + // Brightpass Post-Process + _createBrightPassPostProcess(scene, ratio) { + const brightOffsets = new Array(8); + this.brightPassPostProcess = new PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", this._floatTextureType); + this.brightPassPostProcess.onApply = (effect) => { + const sU = 1.0 / this.brightPassPostProcess.width; + const sV = 1.0 / this.brightPassPostProcess.height; + brightOffsets[0] = -0.5 * sU; + brightOffsets[1] = 0.5 * sV; + brightOffsets[2] = 0.5 * sU; + brightOffsets[3] = 0.5 * sV; + brightOffsets[4] = -0.5 * sU; + brightOffsets[5] = -0.5 * sV; + brightOffsets[6] = 0.5 * sU; + brightOffsets[7] = -0.5 * sV; + effect.setArray2("dsOffsets", brightOffsets); + effect.setFloat("brightThreshold", this.brightThreshold); + }; + // Add to pipeline + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", () => { + return this.brightPassPostProcess; + }, true)); + } + // Create blur H&V post-processes + _createBlurPostProcesses(scene, ratio, indice, blurWidthKey = "blurWidth") { + const engine = scene.getEngine(); + const blurX = new BlurPostProcess("HDRBlurH" + "_" + indice, new Vector2(1, 0), this[blurWidthKey], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType); + const blurY = new BlurPostProcess("HDRBlurV" + "_" + indice, new Vector2(0, 1), this[blurWidthKey], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType); + blurX.onActivateObservable.add(() => { + const dw = blurX.width / engine.getRenderWidth(); + blurX.kernel = this[blurWidthKey] * dw; + }); + blurY.onActivateObservable.add(() => { + const dw = blurY.height / engine.getRenderHeight(); + blurY.kernel = this.horizontalBlur ? 64 * dw : this[blurWidthKey] * dw; + }); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, () => { + return blurX; + }, true)); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, () => { + return blurY; + }, true)); + this.blurHPostProcesses.push(blurX); + this.blurVPostProcesses.push(blurY); + } + // Create texture adder post-process + _createTextureAdderPostProcess(scene, ratio) { + this.textureAdderPostProcess = new PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", this._floatTextureType); + this.textureAdderPostProcess.onApply = (effect) => { + effect.setTextureFromPostProcess("otherSampler", this._vlsEnabled ? this._currentDepthOfFieldSource : this.originalPostProcess); + effect.setTexture("lensSampler", this.lensTexture); + effect.setFloat("exposure", this._currentExposure); + this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess; + }; + // Add to pipeline + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", () => { + return this.textureAdderPostProcess; + }, true)); + } + _createVolumetricLightPostProcess(scene, ratio) { + const geometryRenderer = scene.enableGeometryBufferRenderer(); + geometryRenderer.enablePosition = true; + const geometry = geometryRenderer.getGBuffer(); + // Base post-process + this.volumetricLightPostProcess = new PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1)); + const depthValues = Vector2.Zero(); + this.volumetricLightPostProcess.onApply = (effect) => { + if (this.sourceLight && this.sourceLight.getShadowGenerator() && this._scene.activeCamera) { + const generator = this.sourceLight.getShadowGenerator(); + effect.setTexture("shadowMapSampler", generator.getShadowMap()); + effect.setTexture("positionSampler", geometry.textures[2]); + effect.setColor3("sunColor", this.sourceLight.diffuse); + effect.setVector3("sunDirection", this.sourceLight.getShadowDirection()); + effect.setVector3("cameraPosition", this._scene.activeCamera.globalPosition); + effect.setMatrix("shadowViewProjection", generator.getTransformMatrix()); + effect.setFloat("scatteringCoefficient", this.volumetricLightCoefficient); + effect.setFloat("scatteringPower", this.volumetricLightPower); + depthValues.x = this.sourceLight.getDepthMinZ(this._scene.activeCamera); + depthValues.y = this.sourceLight.getDepthMaxZ(this._scene.activeCamera); + effect.setVector2("depthValues", depthValues); + } + }; + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRVLS", () => { + return this.volumetricLightPostProcess; + }, true)); + // Smooth + this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale"); + // Merge + this.volumetricLightMergePostProces = new PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE"); + this.volumetricLightMergePostProces.onApply = (effect) => { + effect.setTextureFromPostProcess("originalSampler", this._bloomEnabled ? this.textureAdderFinalPostProcess : this.originalPostProcess); + this._currentDepthOfFieldSource = this.volumetricLightFinalPostProcess; + }; + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", () => { + return this.volumetricLightMergePostProces; + }, true)); + } + // Create luminance + _createLuminancePostProcesses(scene, textureType) { + // Create luminance + let size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps); + this.luminancePostProcess = new PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType); + const offsets = []; + this.luminancePostProcess.onApply = (effect) => { + const sU = 1.0 / this.luminancePostProcess.width; + const sV = 1.0 / this.luminancePostProcess.height; + offsets[0] = -0.5 * sU; + offsets[1] = 0.5 * sV; + offsets[2] = 0.5 * sU; + offsets[3] = 0.5 * sV; + offsets[4] = -0.5 * sU; + offsets[5] = -0.5 * sV; + offsets[6] = 0.5 * sU; + offsets[7] = -0.5 * sV; + effect.setArray2("lumOffsets", offsets); + }; + // Add to pipeline + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", () => { + return this.luminancePostProcess; + }, true)); + // Create down sample luminance + for (let i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) { + size = Math.pow(3, i); + let defines = "#define LUMINANCE_DOWN_SAMPLE\n"; + if (i === 0) { + defines += "#define FINAL_DOWN_SAMPLER"; + } + const postProcess = new PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType); + this.luminanceDownSamplePostProcesses.push(postProcess); + } + // Create callbacks and add effects + let lastLuminance = this.luminancePostProcess; + this.luminanceDownSamplePostProcesses.forEach((pp, index) => { + const downSampleOffsets = new Array(18); + pp.onApply = (effect) => { + if (!lastLuminance) { + return; + } + let id = 0; + for (let x = -1; x < 2; x++) { + for (let y = -1; y < 2; y++) { + downSampleOffsets[id] = x / lastLuminance.width; + downSampleOffsets[id + 1] = y / lastLuminance.height; + id += 2; + } + } + effect.setArray2("dsOffsets", downSampleOffsets); + effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width); + if (index === this.luminanceDownSamplePostProcesses.length - 1) { + lastLuminance = this.luminancePostProcess; + } + else { + lastLuminance = pp; + } + }; + if (index === this.luminanceDownSamplePostProcesses.length - 1) { + pp.onAfterRender = () => { + const pixel = scene.getEngine().readPixels(0, 0, 1, 1); + const bit_shift = new Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0); + pixel.then((pixel) => { + const data = new Uint8Array(pixel.buffer); + this._hdrCurrentLuminance = (data[0] * bit_shift.x + data[1] * bit_shift.y + data[2] * bit_shift.z + data[3] * bit_shift.w) / 100.0; + }); + }; + } + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, () => { + return pp; + }, true)); + }); + } + // Create HDR post-process + _createHdrPostProcess(scene, ratio) { + const defines = ["#define HDR"]; + if (this._hdrAutoExposure) { + defines.push("#define AUTO_EXPOSURE"); + } + this.hdrPostProcess = new PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines.join("\n"), 0); + let outputLiminance = 1; + let time = 0; + let lastTime = 0; + this.hdrPostProcess.onApply = (effect) => { + effect.setTextureFromPostProcess("textureAdderSampler", this._currentDepthOfFieldSource); + time += scene.getEngine().getDeltaTime(); + if (outputLiminance < 0) { + outputLiminance = this._hdrCurrentLuminance; + } + else { + const dt = (lastTime - time) / 1000.0; + if (this._hdrCurrentLuminance < outputLiminance + this.hdrDecreaseRate * dt) { + outputLiminance += this.hdrDecreaseRate * dt; + } + else if (this._hdrCurrentLuminance > outputLiminance - this.hdrIncreaseRate * dt) { + outputLiminance -= this.hdrIncreaseRate * dt; + } + else { + outputLiminance = this._hdrCurrentLuminance; + } + } + if (this.hdrAutoExposure) { + this._currentExposure = this._fixedExposure / outputLiminance; + } + else { + outputLiminance = Clamp(outputLiminance, this.hdrMinimumLuminance, 1e20); + effect.setFloat("averageLuminance", outputLiminance); + } + lastTime = time; + this._currentDepthOfFieldSource = this.hdrFinalPostProcess; + }; + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDR", () => { + return this.hdrPostProcess; + }, true)); + } + // Create lens flare post-process + _createLensFlarePostProcess(scene, ratio) { + this.lensFlarePostProcess = new PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", 0); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", () => { + return this.lensFlarePostProcess; + }, true)); + this._createBlurPostProcesses(scene, ratio / 4, 2, "lensFlareBlurWidth"); + this.lensFlareComposePostProcess = new PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", 0); + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", () => { + return this.lensFlareComposePostProcess; + }, true)); + const resolution = new Vector2(0, 0); + // Lens flare + this.lensFlarePostProcess.externalTextureSamplerBinding = true; + this.lensFlarePostProcess.onApply = (effect) => { + effect.setTextureFromPostProcess("textureSampler", this._bloomEnabled ? this.blurHPostProcesses[0] : this.originalPostProcess); + effect.setTexture("lensColorSampler", this.lensColorTexture); + effect.setFloat("strength", this.lensFlareStrength); + effect.setFloat("ghostDispersal", this.lensFlareGhostDispersal); + effect.setFloat("haloWidth", this.lensFlareHaloWidth); + // Shift + resolution.x = this.lensFlarePostProcess.width; + resolution.y = this.lensFlarePostProcess.height; + effect.setVector2("resolution", resolution); + effect.setFloat("distortionStrength", this.lensFlareDistortionStrength); + }; + // Compose + const scaleBias1 = Matrix.FromValues(2.0, 0.0, -1, 0.0, 0.0, 2.0, -1, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); + const scaleBias2 = Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); + this.lensFlareComposePostProcess.onApply = (effect) => { + if (!this._scene.activeCamera) { + return; + } + effect.setTextureFromPostProcess("otherSampler", this.lensFlarePostProcess); + effect.setTexture("lensDirtSampler", this.lensFlareDirtTexture); + effect.setTexture("lensStarSampler", this.lensStarTexture); + // Lens start rotation matrix + const camerax = this._scene.activeCamera.getViewMatrix().getRow(0); + const cameraz = this._scene.activeCamera.getViewMatrix().getRow(2); + let camRot = Vector3.Dot(camerax.toVector3(), new Vector3(1.0, 0.0, 0.0)) + Vector3.Dot(cameraz.toVector3(), new Vector3(0.0, 0.0, 1.0)); + camRot *= 4.0; + const starRotation = Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); + const lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1); + effect.setMatrix("lensStarMatrix", lensStarMatrix); + this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess; + }; + } + // Create depth-of-field post-process + _createDepthOfFieldPostProcess(scene, ratio) { + this.depthOfFieldPostProcess = new PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", 0); + this.depthOfFieldPostProcess.onApply = (effect) => { + effect.setTextureFromPostProcess("otherSampler", this._currentDepthOfFieldSource); + effect.setTexture("depthSampler", this._getDepthTexture()); + effect.setFloat("distance", this.depthOfFieldDistance); + }; + // Add to pipeline + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", () => { + return this.depthOfFieldPostProcess; + }, true)); + } + // Create motion blur post-process + _createMotionBlurPostProcess(scene, ratio) { + if (this._isObjectBasedMotionBlur) { + const mb = new MotionBlurPostProcess("HDRMotionBlur", scene, ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, 0); + mb.motionStrength = this.motionStrength; + mb.motionBlurSamples = this.motionBlurSamples; + this.motionBlurPostProcess = mb; + } + else { + this.motionBlurPostProcess = new PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), 0); + let motionScale = 0; + let prevViewProjection = Matrix.Identity(); + const invViewProjection = Matrix.Identity(); + let viewProjection = Matrix.Identity(); + const screenSize = Vector2.Zero(); + this.motionBlurPostProcess.onApply = (effect) => { + viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix()); + viewProjection.invertToRef(invViewProjection); + effect.setMatrix("inverseViewProjection", invViewProjection); + effect.setMatrix("prevViewProjection", prevViewProjection); + prevViewProjection = viewProjection; + screenSize.x = this.motionBlurPostProcess.width; + screenSize.y = this.motionBlurPostProcess.height; + effect.setVector2("screenSize", screenSize); + motionScale = scene.getEngine().getFps() / 60.0; + effect.setFloat("motionScale", motionScale); + effect.setFloat("motionStrength", this.motionStrength); + effect.setTexture("depthSampler", this._getDepthTexture()); + }; + } + this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", () => { + return this.motionBlurPostProcess; + }, true)); + } + _getDepthTexture() { + if (this._scene.getEngine().getCaps().drawBuffersExtension) { + const renderer = this._scene.enableGeometryBufferRenderer(); + return renderer.getGBuffer().textures[0]; + } + return this._scene.enableDepthRenderer().getDepthMap(); + } + _disposePostProcesses() { + for (let i = 0; i < this._cameras.length; i++) { + const camera = this._cameras[i]; + if (this.originalPostProcess) { + this.originalPostProcess.dispose(camera); + } + if (this.screenSpaceReflectionPostProcess) { + this.screenSpaceReflectionPostProcess.dispose(camera); + } + if (this.downSampleX4PostProcess) { + this.downSampleX4PostProcess.dispose(camera); + } + if (this.brightPassPostProcess) { + this.brightPassPostProcess.dispose(camera); + } + if (this.textureAdderPostProcess) { + this.textureAdderPostProcess.dispose(camera); + } + if (this.volumetricLightPostProcess) { + this.volumetricLightPostProcess.dispose(camera); + } + if (this.volumetricLightSmoothXPostProcess) { + this.volumetricLightSmoothXPostProcess.dispose(camera); + } + if (this.volumetricLightSmoothYPostProcess) { + this.volumetricLightSmoothYPostProcess.dispose(camera); + } + if (this.volumetricLightMergePostProces) { + this.volumetricLightMergePostProces.dispose(camera); + } + if (this.volumetricLightFinalPostProcess) { + this.volumetricLightFinalPostProcess.dispose(camera); + } + if (this.lensFlarePostProcess) { + this.lensFlarePostProcess.dispose(camera); + } + if (this.lensFlareComposePostProcess) { + this.lensFlareComposePostProcess.dispose(camera); + } + for (let j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) { + this.luminanceDownSamplePostProcesses[j].dispose(camera); + } + if (this.luminancePostProcess) { + this.luminancePostProcess.dispose(camera); + } + if (this.hdrPostProcess) { + this.hdrPostProcess.dispose(camera); + } + if (this.hdrFinalPostProcess) { + this.hdrFinalPostProcess.dispose(camera); + } + if (this.depthOfFieldPostProcess) { + this.depthOfFieldPostProcess.dispose(camera); + } + if (this.motionBlurPostProcess) { + this.motionBlurPostProcess.dispose(camera); + } + if (this.fxaaPostProcess) { + this.fxaaPostProcess.dispose(camera); + } + for (let j = 0; j < this.blurHPostProcesses.length; j++) { + this.blurHPostProcesses[j].dispose(camera); + } + for (let j = 0; j < this.blurVPostProcesses.length; j++) { + this.blurVPostProcesses[j].dispose(camera); + } + } + this.originalPostProcess = null; + this.downSampleX4PostProcess = null; + this.brightPassPostProcess = null; + this.textureAdderPostProcess = null; + this.textureAdderFinalPostProcess = null; + this.volumetricLightPostProcess = null; + this.volumetricLightSmoothXPostProcess = null; + this.volumetricLightSmoothYPostProcess = null; + this.volumetricLightMergePostProces = null; + this.volumetricLightFinalPostProcess = null; + this.lensFlarePostProcess = null; + this.lensFlareComposePostProcess = null; + this.luminancePostProcess = null; + this.hdrPostProcess = null; + this.hdrFinalPostProcess = null; + this.depthOfFieldPostProcess = null; + this.motionBlurPostProcess = null; + this.fxaaPostProcess = null; + this.screenSpaceReflectionPostProcess = null; + this.luminanceDownSamplePostProcesses.length = 0; + this.blurHPostProcesses.length = 0; + this.blurVPostProcesses.length = 0; + } + /** + * Dispose of the pipeline and stop all post processes + */ + dispose() { + this._disposePostProcesses(); + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); + super.dispose(); + } + /** + * Serialize the rendering pipeline (Used when exporting) + * @returns the serialized object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + if (this.sourceLight) { + serializationObject.sourceLightId = this.sourceLight.id; + } + if (this.screenSpaceReflectionPostProcess) { + serializationObject.screenSpaceReflectionPostProcess = SerializationHelper.Serialize(this.screenSpaceReflectionPostProcess); + } + serializationObject.customType = "StandardRenderingPipeline"; + return serializationObject; + } + /** + * Parse the serialized pipeline + * @param source Source pipeline. + * @param scene The scene to load the pipeline to. + * @param rootUrl The URL of the serialized pipeline. + * @returns An instantiated pipeline from the serialized object. + */ + static Parse(source, scene, rootUrl) { + const p = SerializationHelper.Parse(() => new StandardRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl); + if (source.sourceLightId) { + p.sourceLight = scene.getLightById(source.sourceLightId); + } + if (source.screenSpaceReflectionPostProcess) { + SerializationHelper.Parse(() => p.screenSpaceReflectionPostProcess, source.screenSpaceReflectionPostProcess, scene, rootUrl); + } + return p; + } +} +/** + * Luminance steps + */ +StandardRenderingPipeline.LuminanceSteps = 6; +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "brightThreshold", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "blurWidth", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "horizontalBlur", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "exposure", null); +__decorate([ + serializeAsTexture("lensTexture") +], StandardRenderingPipeline.prototype, "lensTexture", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "hdrAutoExposure", null); +__decorate([ + serializeAsTexture("lensColorTexture") +], StandardRenderingPipeline.prototype, "lensColorTexture", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "lensFlareBlurWidth", void 0); +__decorate([ + serializeAsTexture("lensStarTexture") +], StandardRenderingPipeline.prototype, "lensStarTexture", void 0); +__decorate([ + serializeAsTexture("lensFlareDirtTexture") +], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "motionStrength", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "objectBasedMotionBlur", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "_ratio", void 0); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "BloomEnabled", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "LensFlareEnabled", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "HDREnabled", null); +__decorate([ + serialize() + // eslint-disable-next-line @typescript-eslint/naming-convention +], StandardRenderingPipeline.prototype, "VLSEnabled", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "fxaaEnabled", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "screenSpaceReflectionsEnabled", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "motionBlurSamples", null); +__decorate([ + serialize() +], StandardRenderingPipeline.prototype, "samples", null); +RegisterClass("BABYLON.StandardRenderingPipeline", StandardRenderingPipeline); + +/** + * Contains all parameters needed for the prepass to perform + * screen space reflections + */ +class ScreenSpaceReflections2Configuration { + /** + * @param useScreenspaceDepth If the effect should use the screenspace depth texture instead of a linear one + */ + constructor(useScreenspaceDepth = false) { + /** + * Is ssr enabled + */ + this.enabled = false; + /** + * Name of the configuration + */ + this.name = "screenSpaceReflections2"; + /** + * Textures that should be present in the MRT for this effect to work + */ + this.texturesRequired = [6, 3]; + this.texturesRequired.push(useScreenspaceDepth ? 10 : 5); + } +} + +/** + * Render pipeline to produce Screen Space Reflections (SSR) effect + * + * References: + * Screen Space Ray Tracing: + * - http://casual-effects.blogspot.com/2014/08/screen-space-ray-tracing.html + * - https://sourceforge.net/p/g3d/code/HEAD/tree/G3D10/data-files/shader/screenSpaceRayTrace.glsl + * - https://github.com/kode80/kode80SSR + * SSR: + * - general tips: https://sakibsaikia.github.io/graphics/2016/12/26/Screen-Space-Reflection-in-Killing-Floor-2.html + * - computation of blur radius from roughness and distance: https://github.com/godotengine/godot/blob/master/servers/rendering/renderer_rd/shaders/effects/screen_space_reflection.glsl + * - blur and usage of back depth buffer: https://github.com/kode80/kode80SSR + */ +class SSRRenderingPipeline extends PostProcessRenderPipeline { + /** + * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1) + */ + set samples(sampleCount) { + if (this._samples === sampleCount) { + return; + } + this._samples = sampleCount; + if (this._ssrPostProcess) { + this._ssrPostProcess.samples = this.samples; + } + } + get samples() { + return this._samples; + } + /** + * Gets or sets the maxDistance used to define how far we look for reflection during the ray-marching on the reflected ray (default: 1000). + * Note that this value is a view (camera) space distance (not pixels!). + */ + get maxDistance() { + return this._thinSSRRenderingPipeline.maxDistance; + } + set maxDistance(distance) { + this._thinSSRRenderingPipeline.maxDistance = distance; + } + /** + * Gets or sets the step size used to iterate until the effect finds the color of the reflection's pixel. Should be an integer \>= 1 as it is the number of pixels we advance at each step (default: 1). + * Use higher values to improve performances (but at the expense of quality). + */ + get step() { + return this._thinSSRRenderingPipeline.step; + } + set step(step) { + this._thinSSRRenderingPipeline.step = step; + } + /** + * Gets or sets the thickness value used as tolerance when computing the intersection between the reflected ray and the scene (default: 0.5). + * If setting "enableAutomaticThicknessComputation" to true, you can use lower values for "thickness" (even 0), as the geometry thickness + * is automatically computed thank to the regular depth buffer + the backface depth buffer + */ + get thickness() { + return this._thinSSRRenderingPipeline.thickness; + } + set thickness(thickness) { + this._thinSSRRenderingPipeline.thickness = thickness; + } + /** + * Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results (default: 1). + */ + get strength() { + return this._thinSSRRenderingPipeline.strength; + } + set strength(strength) { + this._thinSSRRenderingPipeline.strength = strength; + } + /** + * Gets or sets the falloff exponent used to compute the reflection strength. Higher values lead to fainter reflections (default: 1). + */ + get reflectionSpecularFalloffExponent() { + return this._thinSSRRenderingPipeline.reflectionSpecularFalloffExponent; + } + set reflectionSpecularFalloffExponent(exponent) { + this._thinSSRRenderingPipeline.reflectionSpecularFalloffExponent = exponent; + } + /** + * Maximum number of steps during the ray marching process after which we consider an intersection could not be found (default: 1000). + * Should be an integer value. + */ + get maxSteps() { + return this._thinSSRRenderingPipeline.maxSteps; + } + set maxSteps(steps) { + this._thinSSRRenderingPipeline.maxSteps = steps; + } + /** + * Gets or sets the factor applied when computing roughness. Default value is 0.2. + * When blurring based on roughness is enabled (meaning blurDispersionStrength \> 0), roughnessFactor is used as a global roughness factor applied on all objects. + * If you want to disable this global roughness set it to 0. + */ + get roughnessFactor() { + return this._thinSSRRenderingPipeline.roughnessFactor; + } + set roughnessFactor(factor) { + this._thinSSRRenderingPipeline.roughnessFactor = factor; + } + /** + * Number of steps to skip at start when marching the ray to avoid self collisions (default: 1) + * 1 should normally be a good value, depending on the scene you may need to use a higher value (2 or 3) + */ + get selfCollisionNumSkip() { + return this._thinSSRRenderingPipeline.selfCollisionNumSkip; + } + set selfCollisionNumSkip(skip) { + this._thinSSRRenderingPipeline.selfCollisionNumSkip = skip; + } + /** + * Gets or sets the minimum value for one of the reflectivity component of the material to consider it for SSR (default: 0.04). + * If all r/g/b components of the reflectivity is below or equal this value, the pixel will not be considered reflective and SSR won't be applied. + */ + get reflectivityThreshold() { + return this._thinSSRRenderingPipeline.reflectivityThreshold; + } + set reflectivityThreshold(threshold) { + const currentThreshold = this.reflectivityThreshold; + if (threshold === currentThreshold) { + return; + } + this._thinSSRRenderingPipeline.reflectivityThreshold = threshold; + if ((threshold === 0 && currentThreshold !== 0) || (threshold !== 0 && currentThreshold === 0)) { + this._buildPipeline(); + } + } + /** + * Gets or sets the downsample factor used to reduce the size of the texture used to compute the SSR contribution (default: 0). + * Use 0 to render the SSR contribution at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc. + * Note that it is used only when blurring is enabled (blurDispersionStrength \> 0), because in that mode the SSR contribution is generated in a separate texture. + */ + get ssrDownsample() { + return this._thinSSRRenderingPipeline.ssrDownsample; + } + set ssrDownsample(downsample) { + this._thinSSRRenderingPipeline.ssrDownsample = downsample; + this._buildPipeline(); + } + /** + * Gets or sets the blur dispersion strength. Set this value to 0 to disable blurring (default: 0.03) + * The reflections are blurred based on the roughness of the surface and the distance between the pixel shaded and the reflected pixel: the higher the distance the more blurry the reflection is. + * blurDispersionStrength allows to increase or decrease this effect. + */ + get blurDispersionStrength() { + return this._thinSSRRenderingPipeline.blurDispersionStrength; + } + set blurDispersionStrength(strength) { + const currentStrength = this.blurDispersionStrength; + if (strength === currentStrength) { + return; + } + this._thinSSRRenderingPipeline.blurDispersionStrength = strength; + if ((strength === 0 && currentStrength !== 0) || (strength !== 0 && currentStrength === 0)) { + this._buildPipeline(); + } + } + _useBlur() { + return this.blurDispersionStrength > 0; + } + /** + * Gets or sets the downsample factor used to reduce the size of the textures used to blur the reflection effect (default: 0). + * Use 0 to blur at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc. + */ + get blurDownsample() { + return this._thinSSRRenderingPipeline.blurDownsample; + } + set blurDownsample(downsample) { + this._thinSSRRenderingPipeline.blurDownsample = downsample; + this._buildPipeline(); + } + /** + * Gets or sets whether or not smoothing reflections is enabled (default: false) + * Enabling smoothing will require more GPU power. + * Note that this setting has no effect if step = 1: it's only used if step \> 1. + */ + get enableSmoothReflections() { + return this._thinSSRRenderingPipeline.enableSmoothReflections; + } + set enableSmoothReflections(enabled) { + this._thinSSRRenderingPipeline.enableSmoothReflections = enabled; + } + get _useScreenspaceDepth() { + return this._thinSSRRenderingPipeline.useScreenspaceDepth; + } + /** + * Gets or sets the environment cube texture used to define the reflection when the reflected rays of SSR leave the view space or when the maxDistance/maxSteps is reached. + */ + get environmentTexture() { + return this._thinSSRRenderingPipeline.environmentTexture; + } + set environmentTexture(texture) { + this._thinSSRRenderingPipeline.environmentTexture = texture; + } + /** + * Gets or sets the boolean defining if the environment texture is a standard cubemap (false) or a probe (true). Default value is false. + * Note: a probe cube texture is treated differently than an ordinary cube texture because the Y axis is reversed. + */ + get environmentTextureIsProbe() { + return this._thinSSRRenderingPipeline.environmentTextureIsProbe; + } + set environmentTextureIsProbe(isProbe) { + this._thinSSRRenderingPipeline.environmentTextureIsProbe = isProbe; + } + /** + * Gets or sets a boolean indicating if the reflections should be attenuated at the screen borders (default: true). + */ + get attenuateScreenBorders() { + return this._thinSSRRenderingPipeline.attenuateScreenBorders; + } + set attenuateScreenBorders(attenuate) { + this._thinSSRRenderingPipeline.attenuateScreenBorders = attenuate; + } + /** + * Gets or sets a boolean indicating if the reflections should be attenuated according to the distance of the intersection (default: true). + */ + get attenuateIntersectionDistance() { + return this._thinSSRRenderingPipeline.attenuateIntersectionDistance; + } + set attenuateIntersectionDistance(attenuate) { + this._thinSSRRenderingPipeline.attenuateIntersectionDistance = attenuate; + } + /** + * Gets or sets a boolean indicating if the reflections should be attenuated according to the number of iterations performed to find the intersection (default: true). + */ + get attenuateIntersectionIterations() { + return this._thinSSRRenderingPipeline.attenuateIntersectionIterations; + } + set attenuateIntersectionIterations(attenuate) { + this._thinSSRRenderingPipeline.attenuateIntersectionIterations = attenuate; + } + /** + * Gets or sets a boolean indicating if the reflections should be attenuated when the reflection ray is facing the camera (the view direction) (default: false). + */ + get attenuateFacingCamera() { + return this._thinSSRRenderingPipeline.attenuateFacingCamera; + } + set attenuateFacingCamera(attenuate) { + this._thinSSRRenderingPipeline.attenuateFacingCamera = attenuate; + } + /** + * Gets or sets a boolean indicating if the backface reflections should be attenuated (default: false). + */ + get attenuateBackfaceReflection() { + return this._thinSSRRenderingPipeline.attenuateBackfaceReflection; + } + set attenuateBackfaceReflection(attenuate) { + this._thinSSRRenderingPipeline.attenuateBackfaceReflection = attenuate; + } + /** + * Gets or sets a boolean indicating if the ray should be clipped to the frustum (default: true). + * You can try to set this parameter to false to save some performances: it may produce some artefacts in some cases, but generally they won't really be visible + */ + get clipToFrustum() { + return this._thinSSRRenderingPipeline.clipToFrustum; + } + set clipToFrustum(clip) { + this._thinSSRRenderingPipeline.clipToFrustum = clip; + } + /** + * Gets or sets a boolean indicating whether the blending between the current color pixel and the reflection color should be done with a Fresnel coefficient (default: false). + * It is more physically accurate to use the Fresnel coefficient (otherwise it uses the reflectivity of the material for blending), but it is also more expensive when you use blur (when blurDispersionStrength \> 0). + */ + get useFresnel() { + return this._thinSSRRenderingPipeline.useFresnel; + } + set useFresnel(fresnel) { + this._thinSSRRenderingPipeline.useFresnel = fresnel; + this._buildPipeline(); + } + /** + * Gets or sets a boolean defining if geometry thickness should be computed automatically (default: false). + * When enabled, a depth renderer is created which will render the back faces of the scene to a depth texture (meaning additional work for the GPU). + * In that mode, the "thickness" property is still used as an offset to compute the ray intersection, but you can typically use a much lower + * value than when enableAutomaticThicknessComputation is false (it's even possible to use a value of 0 when using low values for "step") + * Note that for performance reasons, this option will only apply to the first camera to which the rendering pipeline is attached! + */ + get enableAutomaticThicknessComputation() { + return this._thinSSRRenderingPipeline.enableAutomaticThicknessComputation; + } + set enableAutomaticThicknessComputation(automatic) { + this._thinSSRRenderingPipeline.enableAutomaticThicknessComputation = automatic; + this._buildPipeline(); + } + /** + * Gets the depth renderer used to render the back faces of the scene to a depth texture. + */ + get backfaceDepthRenderer() { + return this._depthRenderer; + } + /** + * Gets or sets the downsample factor (default: 0) used to create the backface depth texture - used only if enableAutomaticThicknessComputation = true. + * Use 0 to render the depth at full resolution, 1 to render at half resolution, 2 to render at 1/4 resolution, etc. + * Note that you will get rendering artefacts when using a value different from 0: it's a tradeoff between image quality and performances. + */ + get backfaceDepthTextureDownsample() { + return this._backfaceDepthTextureDownsample; + } + set backfaceDepthTextureDownsample(factor) { + if (this._backfaceDepthTextureDownsample === factor) { + return; + } + this._backfaceDepthTextureDownsample = factor; + this._resizeDepthRenderer(); + } + /** + * Gets or sets a boolean (default: true) indicating if the depth of transparent meshes should be written to the backface depth texture (when automatic thickness computation is enabled). + */ + get backfaceForceDepthWriteTransparentMeshes() { + return this._backfaceForceDepthWriteTransparentMeshes; + } + set backfaceForceDepthWriteTransparentMeshes(force) { + if (this._backfaceForceDepthWriteTransparentMeshes === force) { + return; + } + this._backfaceForceDepthWriteTransparentMeshes = force; + if (this._depthRenderer) { + this._depthRenderer.forceDepthWriteTransparentMeshes = force; + } + } + /** + * Gets or sets a boolean indicating if the effect is enabled (default: true). + */ + get isEnabled() { + return this._isEnabled; + } + set isEnabled(value) { + if (this._isEnabled === value) { + return; + } + this._isEnabled = value; + if (!value) { + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); + this._cameras = this._camerasToBeAttached.slice(); + } + } + else if (value) { + if (!this._isDirty) { + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); + } + } + else { + this._buildPipeline(); + } + } + } + /** + * Gets or sets a boolean defining if the input color texture is in gamma space (default: true) + * The SSR effect works in linear space, so if the input texture is in gamma space, we must convert the texture to linear space before applying the effect + */ + get inputTextureColorIsInGammaSpace() { + return this._thinSSRRenderingPipeline.inputTextureColorIsInGammaSpace; + } + set inputTextureColorIsInGammaSpace(gammaSpace) { + this._thinSSRRenderingPipeline.inputTextureColorIsInGammaSpace = gammaSpace; + this._buildPipeline(); + } + /** + * Gets or sets a boolean defining if the output color texture generated by the SSR pipeline should be in gamma space (default: true) + * If you have a post-process that comes after the SSR and that post-process needs the input to be in a linear space, you must disable generateOutputInGammaSpace + */ + get generateOutputInGammaSpace() { + return this._thinSSRRenderingPipeline.generateOutputInGammaSpace; + } + set generateOutputInGammaSpace(gammaSpace) { + this._thinSSRRenderingPipeline.generateOutputInGammaSpace = gammaSpace; + this._buildPipeline(); + } + /** + * Gets or sets a boolean indicating if the effect should be rendered in debug mode (default: false). + * In this mode, colors have this meaning: + * - blue: the ray hit the max distance (we reached maxDistance) + * - red: the ray ran out of steps (we reached maxSteps) + * - yellow: the ray went off screen + * - green: the ray hit a surface. The brightness of the green color is proportional to the distance between the ray origin and the intersection point: A brighter green means more computation than a darker green. + * In the first 3 cases, the final color is calculated by mixing the skybox color with the pixel color (if environmentTexture is defined), otherwise the pixel color is not modified + * You should try to get as few blue/red/yellow pixels as possible, as this means that the ray has gone further than if it had hit a surface. + */ + get debug() { + return this._thinSSRRenderingPipeline.debug; + } + set debug(value) { + this._thinSSRRenderingPipeline.debug = value; + this._buildPipeline(); + } + /** + * Gets the scene the effect belongs to. + * @returns the scene the effect belongs to. + */ + getScene() { + return this._scene; + } + get _geometryBufferRenderer() { + if (!this._forceGeometryBuffer) { + return null; + } + return this._scene.geometryBufferRenderer; + } + get _prePassRenderer() { + if (this._forceGeometryBuffer) { + return null; + } + return this._scene.prePassRenderer; + } + /** + * Gets active scene + */ + get scene() { + return this._scene; + } + /** + * Returns true if SSR is supported by the running hardware + */ + get isSupported() { + const caps = this._scene.getEngine().getCaps(); + return caps.drawBuffersExtension && caps.texelFetch; + } + /** + * Constructor of the SSR rendering pipeline + * @param name The rendering pipeline name + * @param scene The scene linked to this pipeline + * @param cameras The array of cameras that the rendering pipeline will be attached to (default: scene.cameras) + * @param forceGeometryBuffer Set to true if you want to use the legacy geometry buffer renderer (default: false) + * @param textureType The texture type used by the different post processes created by SSR (default: 0) + * @param useScreenspaceDepth Indicates if the depth buffer should be linear or screenspace (default: false). This allows sharing the buffer with other effect pipelines that may require the depth to be in screenspace. + */ + constructor(name, scene, cameras, forceGeometryBuffer = false, textureType = 0, useScreenspaceDepth = false) { + super(scene.getEngine(), name); + /** + * The SSR PostProcess effect id in the pipeline + */ + this.SSRRenderEffect = "SSRRenderEffect"; + /** + * The blur PostProcess effect id in the pipeline + */ + this.SSRBlurRenderEffect = "SSRBlurRenderEffect"; + /** + * The PostProcess effect id in the pipeline that combines the SSR-Blur output with the original scene color + */ + this.SSRCombineRenderEffect = "SSRCombineRenderEffect"; + this._samples = 1; + this._backfaceDepthTextureDownsample = 0; + this._backfaceForceDepthWriteTransparentMeshes = true; + this._isEnabled = true; + this._forceGeometryBuffer = false; + this._isDirty = false; + this._camerasToBeAttached = []; + this._thinSSRRenderingPipeline = new ThinSSRRenderingPipeline(name, scene); + this._thinSSRRenderingPipeline.isSSRSupported = false; + this._thinSSRRenderingPipeline.useScreenspaceDepth = useScreenspaceDepth; + this._cameras = cameras || scene.cameras; + this._cameras = this._cameras.slice(); + this._camerasToBeAttached = this._cameras.slice(); + this._scene = scene; + this._textureType = textureType; + this._forceGeometryBuffer = forceGeometryBuffer; + if (this.isSupported) { + this._createSSRPostProcess(); + scene.postProcessRenderPipelineManager.addPipeline(this); + if (this._forceGeometryBuffer) { + const geometryBufferRenderer = scene.enableGeometryBufferRenderer(); + if (geometryBufferRenderer) { + geometryBufferRenderer.enableReflectivity = true; + geometryBufferRenderer.useSpecificClearForDepthTexture = true; + geometryBufferRenderer.enableScreenspaceDepth = this._useScreenspaceDepth; + geometryBufferRenderer.enableDepth = !this._useScreenspaceDepth; + } + } + else { + const prePassRenderer = scene.enablePrePassRenderer(); + if (prePassRenderer) { + prePassRenderer.useSpecificClearForDepthTexture = true; + prePassRenderer.markAsDirty(); + } + } + this._thinSSRRenderingPipeline.isSSRSupported = !!this._geometryBufferRenderer || !!this._prePassRenderer; + this._buildPipeline(); + } + } + /** + * Get the class name + * @returns "SSRRenderingPipeline" + */ + getClassName() { + return "SSRRenderingPipeline"; + } + /** + * Adds a camera to the pipeline + * @param camera the camera to be added + */ + addCamera(camera) { + this._camerasToBeAttached.push(camera); + this._buildPipeline(); + } + /** + * Removes a camera from the pipeline + * @param camera the camera to remove + */ + removeCamera(camera) { + const index = this._camerasToBeAttached.indexOf(camera); + this._camerasToBeAttached.splice(index, 1); + this._buildPipeline(); + } + /** + * Removes the internal pipeline assets and detaches the pipeline from the scene cameras + * @param disableGeometryBufferRenderer if the geometry buffer renderer should be disabled + */ + dispose(disableGeometryBufferRenderer = false) { + this._disposeDepthRenderer(); + this._disposeSSRPostProcess(); + this._disposeBlurPostProcesses(); + if (disableGeometryBufferRenderer) { + this._scene.disableGeometryBufferRenderer(); + } + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); + this._thinSSRRenderingPipeline.dispose(); + super.dispose(); + } + _getTextureSize() { + const engine = this._scene.getEngine(); + const prePassRenderer = this._prePassRenderer; + let textureSize = { width: engine.getRenderWidth(), height: engine.getRenderHeight() }; + if (prePassRenderer && this._scene.activeCamera?._getFirstPostProcess() === this._ssrPostProcess) { + const renderTarget = prePassRenderer.getRenderTarget(); + if (renderTarget && renderTarget.textures) { + textureSize = renderTarget.textures[prePassRenderer.getIndex(4)].getSize(); + } + } + else if (this._ssrPostProcess?.inputTexture) { + textureSize.width = this._ssrPostProcess.inputTexture.width; + textureSize.height = this._ssrPostProcess.inputTexture.height; + } + return textureSize; + } + _buildPipeline() { + if (!this.isSupported) { + return; + } + if (!this._isEnabled) { + this._isDirty = true; + return; + } + this._isDirty = false; + const engine = this._scene.getEngine(); + this._disposeDepthRenderer(); + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); + // get back cameras to be used to reattach pipeline + this._cameras = this._camerasToBeAttached.slice(); + if (this._cameras.length > 0) { + this._thinSSRRenderingPipeline.camera = this._cameras[0]; + } + } + this._reset(); + this._thinSSRRenderingPipeline.normalsAreInWorldSpace = !!(this._geometryBufferRenderer?.generateNormalsInWorldSpace ?? this._prePassRenderer?.generateNormalsInWorldSpace); + if (this.enableAutomaticThicknessComputation) { + const camera = this._cameras?.[0]; + if (camera) { + this._depthRendererCamera = camera; + this._depthRenderer = new DepthRenderer(this._scene, undefined, undefined, this._useScreenspaceDepth, 1, !this._useScreenspaceDepth, "SSRBackDepth"); + if (!this._useScreenspaceDepth) { + this._depthRenderer.clearColor.r = 1e8; // "infinity": put a big value because we use the storeCameraSpaceZ mode + } + this._depthRenderer.reverseCulling = true; // we generate depth for the back faces + this._depthRenderer.forceDepthWriteTransparentMeshes = this.backfaceForceDepthWriteTransparentMeshes; + this._resizeDepthRenderer(); + camera.customRenderTargets.push(this._depthRenderer.getDepthMap()); + } + } + this.addEffect(new PostProcessRenderEffect(engine, this.SSRRenderEffect, () => { + return this._ssrPostProcess; + }, true)); + this._disposeBlurPostProcesses(); + if (this._useBlur()) { + this._createBlurAndCombinerPostProcesses(); + this.addEffect(new PostProcessRenderEffect(engine, this.SSRBlurRenderEffect, () => { + return [this._blurPostProcessX, this._blurPostProcessY]; + }, true)); + this.addEffect(new PostProcessRenderEffect(engine, this.SSRCombineRenderEffect, () => { + return this._blurCombinerPostProcess; + }, true)); + } + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); + } + } + _resizeDepthRenderer() { + if (!this._depthRenderer) { + return; + } + const textureSize = this._getTextureSize(); + const depthRendererSize = this._depthRenderer.getDepthMap().getSize(); + const width = Math.floor(textureSize.width / (this.backfaceDepthTextureDownsample + 1)); + const height = Math.floor(textureSize.height / (this.backfaceDepthTextureDownsample + 1)); + if (depthRendererSize.width !== width || depthRendererSize.height !== height) { + this._depthRenderer.getDepthMap().resize({ width, height }); + } + } + _disposeDepthRenderer() { + if (this._depthRenderer) { + if (this._depthRendererCamera) { + const idx = this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()) ?? -1; + if (idx !== -1) { + this._depthRendererCamera.customRenderTargets.splice(idx, 1); + } + } + this._depthRendererCamera = null; + this._depthRenderer.getDepthMap().dispose(); + } + this._depthRenderer = null; + } + _disposeBlurPostProcesses() { + for (let i = 0; i < this._cameras.length; i++) { + const camera = this._cameras[i]; + this._blurPostProcessX?.dispose(camera); + this._blurPostProcessY?.dispose(camera); + this._blurCombinerPostProcess?.dispose(camera); + } + this._blurPostProcessX = null; + this._blurPostProcessY = null; + this._blurCombinerPostProcess = null; + } + _disposeSSRPostProcess() { + for (let i = 0; i < this._cameras.length; i++) { + const camera = this._cameras[i]; + this._ssrPostProcess?.dispose(camera); + } + this._ssrPostProcess = null; + } + _createSSRPostProcess() { + this._ssrPostProcess = new PostProcess("ssr", ThinSSRPostProcess.FragmentUrl, { + uniformNames: ThinSSRPostProcess.Uniforms, + samplerNames: ThinSSRPostProcess.Samplers, + size: 1.0, + samplingMode: 2, + engine: this._scene.getEngine(), + textureType: this._textureType, + effectWrapper: this._thinSSRRenderingPipeline._ssrPostProcess, + }); + this._ssrPostProcess.onApply = (effect) => { + this._resizeDepthRenderer(); + const geometryBufferRenderer = this._geometryBufferRenderer; + const prePassRenderer = this._prePassRenderer; + if (!prePassRenderer && !geometryBufferRenderer) { + return; + } + if (geometryBufferRenderer) { + const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE); + const normalIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.NORMAL_TEXTURE_TYPE); + effect.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[normalIndex]); + effect.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]); + if (this._useScreenspaceDepth) { + const depthIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE); + effect.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[depthIndex]); + } + else { + const depthIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE); + effect.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[depthIndex]); + } + } + else if (prePassRenderer) { + const depthIndex = prePassRenderer.getIndex(this._useScreenspaceDepth ? 10 : 5); + const roughnessIndex = prePassRenderer.getIndex(3); + const normalIndex = prePassRenderer.getIndex(6); + effect.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]); + effect.setTexture("depthSampler", prePassRenderer.getRenderTarget().textures[depthIndex]); + effect.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]); + } + if (this.enableAutomaticThicknessComputation && this._depthRenderer) { + effect.setTexture("backDepthSampler", this._depthRenderer.getDepthMap()); + effect.setFloat("backSizeFactor", this.backfaceDepthTextureDownsample + 1); + } + const textureSize = this._getTextureSize(); + this._thinSSRRenderingPipeline._ssrPostProcess.textureWidth = textureSize.width; + this._thinSSRRenderingPipeline._ssrPostProcess.textureHeight = textureSize.height; + }; + this._ssrPostProcess.samples = this.samples; + if (!this._forceGeometryBuffer) { + this._ssrPostProcess._prePassEffectConfiguration = new ScreenSpaceReflections2Configuration(this._useScreenspaceDepth); + } + } + _createBlurAndCombinerPostProcesses() { + const engine = this._scene.getEngine(); + this._blurPostProcessX = new PostProcess("SSRblurX", ThinSSRBlurPostProcess.FragmentUrl, { + uniformNames: ThinSSRBlurPostProcess.Uniforms, + samplerNames: ThinSSRBlurPostProcess.Samplers, + size: 1 / (this.ssrDownsample + 1), + samplingMode: 2, + engine, + textureType: this._textureType, + effectWrapper: this._thinSSRRenderingPipeline._ssrBlurXPostProcess, + }); + this._blurPostProcessX.autoClear = false; + this._blurPostProcessX.onApplyObservable.add(() => { + this._thinSSRRenderingPipeline._ssrBlurXPostProcess.textureWidth = this._blurPostProcessX?.inputTexture.width ?? this._scene.getEngine().getRenderWidth(); + this._thinSSRRenderingPipeline._ssrBlurXPostProcess.textureHeight = 1; // not used + }); + this._blurPostProcessY = new PostProcess("SSRblurY", ThinSSRBlurPostProcess.FragmentUrl, { + uniformNames: ThinSSRBlurPostProcess.Uniforms, + samplerNames: ThinSSRBlurPostProcess.Samplers, + size: 1 / (this.blurDownsample + 1), + samplingMode: 2, + engine, + textureType: this._textureType, + effectWrapper: this._thinSSRRenderingPipeline._ssrBlurYPostProcess, + }); + this._blurPostProcessY.autoClear = false; + this._blurPostProcessY.onApplyObservable.add(() => { + this._thinSSRRenderingPipeline._ssrBlurYPostProcess.textureWidth = 1; // not used + this._thinSSRRenderingPipeline._ssrBlurYPostProcess.textureHeight = this._blurPostProcessY?.inputTexture.height ?? this._scene.getEngine().getRenderHeight(); + }); + this._blurCombinerPostProcess = new PostProcess("SSRblurCombiner", ThinSSRBlurCombinerPostProcess.FragmentUrl, { + uniformNames: ThinSSRBlurCombinerPostProcess.Uniforms, + samplerNames: ThinSSRBlurCombinerPostProcess.Samplers, + size: 1 / (this.blurDownsample + 1), + samplingMode: 1, + engine, + textureType: this._textureType, + effectWrapper: this._thinSSRRenderingPipeline._ssrBlurCombinerPostProcess, + }); + this._blurCombinerPostProcess.autoClear = false; + this._blurCombinerPostProcess.onApplyObservable.add((effect) => { + const geometryBufferRenderer = this._geometryBufferRenderer; + const prePassRenderer = this._prePassRenderer; + if (!prePassRenderer && !geometryBufferRenderer) { + return; + } + if (prePassRenderer && this._scene.activeCamera?._getFirstPostProcess() === this._ssrPostProcess) { + const renderTarget = prePassRenderer.getRenderTarget(); + if (renderTarget && renderTarget.textures) { + effect.setTexture("mainSampler", renderTarget.textures[prePassRenderer.getIndex(4)]); + } + } + else { + effect.setTextureFromPostProcess("mainSampler", this._ssrPostProcess); + } + if (geometryBufferRenderer) { + const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE); + effect.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]); + if (this.useFresnel) { + effect.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[1]); + if (this._useScreenspaceDepth) { + const depthIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE); + effect.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[depthIndex]); + } + else { + effect.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[0]); + } + } + } + else if (prePassRenderer) { + const roughnessIndex = prePassRenderer.getIndex(3); + effect.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]); + if (this.useFresnel) { + const depthIndex = prePassRenderer.getIndex(this._useScreenspaceDepth ? 10 : 5); + const normalIndex = prePassRenderer.getIndex(6); + effect.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]); + effect.setTexture("depthSampler", prePassRenderer.getRenderTarget().textures[depthIndex]); + } + } + }); + } + /** + * Serializes the rendering pipeline (Used when exporting) + * @returns the serialized object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.customType = "SSRRenderingPipeline"; + return serializationObject; + } + /** + * Parse the serialized pipeline + * @param source Source pipeline. + * @param scene The scene to load the pipeline to. + * @param rootUrl The URL of the serialized pipeline. + * @returns An instantiated pipeline from the serialized object. + */ + static Parse(source, scene, rootUrl) { + return SerializationHelper.Parse(() => new SSRRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl); + } +} +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "samples", null); +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "maxDistance", null); +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "step", null); +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "thickness", null); +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "strength", null); +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "reflectionSpecularFalloffExponent", null); +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "maxSteps", null); +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "roughnessFactor", null); +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "selfCollisionNumSkip", null); +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "reflectivityThreshold", null); +__decorate([ + serialize() +], SSRRenderingPipeline.prototype, "ssrDownsample", null); +__decorate([ + serialize("blurDispersionStrength") +], SSRRenderingPipeline.prototype, "blurDispersionStrength", null); +__decorate([ + serialize("blurDownsample") +], SSRRenderingPipeline.prototype, "blurDownsample", null); +__decorate([ + serialize("enableSmoothReflections") +], SSRRenderingPipeline.prototype, "enableSmoothReflections", null); +__decorate([ + serialize("environmentTexture") +], SSRRenderingPipeline.prototype, "environmentTexture", null); +__decorate([ + serialize("environmentTextureIsProbe") +], SSRRenderingPipeline.prototype, "environmentTextureIsProbe", null); +__decorate([ + serialize("attenuateScreenBorders") +], SSRRenderingPipeline.prototype, "attenuateScreenBorders", null); +__decorate([ + serialize("attenuateIntersectionDistance") +], SSRRenderingPipeline.prototype, "attenuateIntersectionDistance", null); +__decorate([ + serialize("attenuateIntersectionIterations") +], SSRRenderingPipeline.prototype, "attenuateIntersectionIterations", null); +__decorate([ + serialize("attenuateFacingCamera") +], SSRRenderingPipeline.prototype, "attenuateFacingCamera", null); +__decorate([ + serialize("attenuateBackfaceReflection") +], SSRRenderingPipeline.prototype, "attenuateBackfaceReflection", null); +__decorate([ + serialize("clipToFrustum") +], SSRRenderingPipeline.prototype, "clipToFrustum", null); +__decorate([ + serialize("useFresnel") +], SSRRenderingPipeline.prototype, "useFresnel", null); +__decorate([ + serialize("enableAutomaticThicknessComputation") +], SSRRenderingPipeline.prototype, "enableAutomaticThicknessComputation", null); +__decorate([ + serialize("backfaceDepthTextureDownsample") +], SSRRenderingPipeline.prototype, "_backfaceDepthTextureDownsample", void 0); +__decorate([ + serialize("backfaceForceDepthWriteTransparentMeshes") +], SSRRenderingPipeline.prototype, "_backfaceForceDepthWriteTransparentMeshes", void 0); +__decorate([ + serialize("isEnabled") +], SSRRenderingPipeline.prototype, "_isEnabled", void 0); +__decorate([ + serialize("inputTextureColorIsInGammaSpace") +], SSRRenderingPipeline.prototype, "inputTextureColorIsInGammaSpace", null); +__decorate([ + serialize("generateOutputInGammaSpace") +], SSRRenderingPipeline.prototype, "generateOutputInGammaSpace", null); +__decorate([ + serialize("debug") +], SSRRenderingPipeline.prototype, "debug", null); +RegisterClass("BABYLON.SSRRenderingPipeline", SSRRenderingPipeline); + +/** + * Simple implementation of Temporal Anti-Aliasing (TAA). + * This can be used to improve image quality for still pictures (screenshots for e.g.). + */ +class TAARenderingPipeline extends PostProcessRenderPipeline { + /** + * Number of accumulated samples (default: 16) + */ + set samples(samples) { + this._taaThinPostProcess.samples = samples; + } + get samples() { + return this._taaThinPostProcess.samples; + } + /** + * MSAA samples (default: 1) + */ + set msaaSamples(samples) { + if (this._msaaSamples === samples) { + return; + } + this._msaaSamples = samples; + if (this._taaPostProcess) { + this._taaPostProcess.samples = samples; + } + } + get msaaSamples() { + return this._msaaSamples; + } + /** + * The factor used to blend the history frame with current frame (default: 0.05) + */ + get factor() { + return this._taaThinPostProcess.factor; + } + set factor(value) { + this._taaThinPostProcess.factor = value; + } + /** + * Disable TAA on camera move (default: true). + * You generally want to keep this enabled, otherwise you will get a ghost effect when the camera moves (but if it's what you want, go for it!) + */ + get disableOnCameraMove() { + return this._taaThinPostProcess.disableOnCameraMove; + } + set disableOnCameraMove(value) { + this._taaThinPostProcess.disableOnCameraMove = value; + } + /** + * Gets or sets a boolean indicating if the render pipeline is enabled (default: true). + */ + get isEnabled() { + return this._isEnabled; + } + set isEnabled(value) { + if (this._isEnabled === value) { + return; + } + this._isEnabled = value; + if (!value) { + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); + this._cameras = this._camerasToBeAttached.slice(); + } + } + else if (value) { + if (!this._isDirty) { + if (this._cameras !== null) { + this._taaThinPostProcess._reset(); + this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); + } + } + else { + this._buildPipeline(); + } + } + } + /** + * Gets active scene + */ + get scene() { + return this._scene; + } + /** + * Returns true if TAA is supported by the running hardware + */ + get isSupported() { + const caps = this._scene.getEngine().getCaps(); + return caps.texelFetch; + } + /** + * Constructor of the TAA rendering pipeline + * @param name The rendering pipeline name + * @param scene The scene linked to this pipeline + * @param cameras The array of cameras that the rendering pipeline will be attached to (default: scene.cameras) + * @param textureType The type of texture where the scene will be rendered (default: 0) + */ + constructor(name, scene, cameras, textureType = 0) { + const engine = scene.getEngine(); + super(engine, name); + /** + * The TAA PostProcess effect id in the pipeline + */ + this.TAARenderEffect = "TAARenderEffect"; + /** + * The pass PostProcess effect id in the pipeline + */ + this.TAAPassEffect = "TAAPassEffect"; + this._msaaSamples = 1; + this._isEnabled = true; + this._isDirty = false; + this._camerasToBeAttached = []; + this._pingpong = 0; + this._cameras = cameras || scene.cameras; + this._cameras = this._cameras.slice(); + this._camerasToBeAttached = this._cameras.slice(); + this._scene = scene; + this._textureType = textureType; + this._taaThinPostProcess = new ThinTAAPostProcess("TAA", this._scene.getEngine()); + if (this.isSupported) { + this._createPingPongTextures(engine.getRenderWidth(), engine.getRenderHeight()); + scene.postProcessRenderPipelineManager.addPipeline(this); + this._buildPipeline(); + } + } + /** + * Get the class name + * @returns "TAARenderingPipeline" + */ + getClassName() { + return "TAARenderingPipeline"; + } + /** + * Adds a camera to the pipeline + * @param camera the camera to be added + */ + addCamera(camera) { + this._camerasToBeAttached.push(camera); + this._buildPipeline(); + } + /** + * Removes a camera from the pipeline + * @param camera the camera to remove + */ + removeCamera(camera) { + const index = this._camerasToBeAttached.indexOf(camera); + this._camerasToBeAttached.splice(index, 1); + this._buildPipeline(); + } + /** + * Removes the internal pipeline assets and detaches the pipeline from the scene cameras + */ + dispose() { + this._disposePostProcesses(); + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); + this._ping.dispose(); + this._pong.dispose(); + super.dispose(); + } + _createPingPongTextures(width, height) { + const engine = this._scene.getEngine(); + this._ping?.dispose(); + this._pong?.dispose(); + this._ping = engine.createRenderTargetTexture({ width, height }, { generateMipMaps: false, generateDepthBuffer: false, type: 2, samplingMode: 1 }); + this._pong = engine.createRenderTargetTexture({ width, height }, { generateMipMaps: false, generateDepthBuffer: false, type: 2, samplingMode: 1 }); + this._taaThinPostProcess.textureWidth = width; + this._taaThinPostProcess.textureHeight = height; + } + _buildPipeline() { + if (!this.isSupported) { + return; + } + if (!this._isEnabled) { + this._isDirty = true; + return; + } + this._isDirty = false; + const engine = this._scene.getEngine(); + this._disposePostProcesses(); + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); + // get back cameras to be used to reattach pipeline + this._cameras = this._camerasToBeAttached.slice(); + } + this._reset(); + this._createTAAPostProcess(); + this.addEffect(new PostProcessRenderEffect(engine, this.TAARenderEffect, () => { + return this._taaPostProcess; + }, true)); + this._createPassPostProcess(); + this.addEffect(new PostProcessRenderEffect(engine, this.TAAPassEffect, () => { + return this._passPostProcess; + }, true)); + if (this._cameras !== null) { + this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); + } + } + _disposePostProcesses() { + for (let i = 0; i < this._cameras.length; i++) { + const camera = this._cameras[i]; + this._taaPostProcess?.dispose(camera); + this._passPostProcess?.dispose(camera); + camera.getProjectionMatrix(true); // recompute the projection matrix + } + this._taaPostProcess = null; + this._passPostProcess = null; + } + _createTAAPostProcess() { + this._taaPostProcess = new PostProcess("TAA", "taa", { + uniforms: ["factor"], + samplers: ["historySampler"], + size: 1.0, + engine: this._scene.getEngine(), + textureType: this._textureType, + effectWrapper: this._taaThinPostProcess, + }); + this._taaPostProcess.samples = this._msaaSamples; + this._taaPostProcess.onActivateObservable.add(() => { + this._taaThinPostProcess.camera = this._scene.activeCamera; + if (this._taaPostProcess?.width !== this._ping.width || this._taaPostProcess?.height !== this._ping.height) { + const engine = this._scene.getEngine(); + this._createPingPongTextures(engine.getRenderWidth(), engine.getRenderHeight()); + } + this._taaThinPostProcess.updateProjectionMatrix(); + if (this._passPostProcess) { + this._passPostProcess.inputTexture = this._pingpong ? this._ping : this._pong; + } + this._pingpong = this._pingpong ^ 1; + }); + this._taaPostProcess.onApplyObservable.add((effect) => { + effect._bindTexture("historySampler", this._pingpong ? this._ping.texture : this._pong.texture); + }); + } + _createPassPostProcess() { + const engine = this._scene.getEngine(); + this._passPostProcess = new PassPostProcess("TAAPass", 1, null, 1, engine); + this._passPostProcess.inputTexture = this._ping; + this._passPostProcess.autoClear = false; + } + /** + * Serializes the rendering pipeline (Used when exporting) + * @returns the serialized object + */ + serialize() { + const serializationObject = SerializationHelper.Serialize(this); + serializationObject.customType = "TAARenderingPipeline"; + return serializationObject; + } + /** + * Parse the serialized pipeline + * @param source Source pipeline. + * @param scene The scene to load the pipeline to. + * @param rootUrl The URL of the serialized pipeline. + * @returns An instantiated pipeline from the serialized object. + */ + static Parse(source, scene, rootUrl) { + return SerializationHelper.Parse(() => new TAARenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl); + } +} +__decorate([ + serialize("samples") +], TAARenderingPipeline.prototype, "samples", null); +__decorate([ + serialize("msaaSamples") +], TAARenderingPipeline.prototype, "_msaaSamples", void 0); +__decorate([ + serialize() +], TAARenderingPipeline.prototype, "factor", null); +__decorate([ + serialize() +], TAARenderingPipeline.prototype, "disableOnCameraMove", null); +__decorate([ + serialize("isEnabled") +], TAARenderingPipeline.prototype, "_isEnabled", void 0); +RegisterClass("BABYLON.TAARenderingPipeline", TAARenderingPipeline); + +// Do not edit. +const name$2P = "ssao2PixelShader"; +const shader$2O = `precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSAO +float scales[16]=float[16]( +0.1, +0.11406250000000001, +0.131640625, +0.15625, +0.187890625, +0.2265625, +0.272265625, +0.325, +0.384765625, +0.4515625, +0.525390625, +0.60625, +0.694140625, +0.7890625, +0.891015625, +1.0 +);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() +{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=sign(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;} +float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} +occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} +#endif +#ifdef BLUR +uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; +#ifndef BLUR_BYPASS +uniform sampler2D depthSampler; +#ifdef BLUR_LEGACY +#define inline +float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} +#endif +#endif +void main() +{float result=0.0; +#ifdef BLUR_BYPASS +result=textureLod(textureSampler,vUV,0.0).r; +#else +#ifdef BLUR_H +vec2 step=vec2(1.0/outSize,0.0); +#else +vec2 step=vec2(0.0,1.0/outSize); +#endif +#ifdef BLUR_LEGACY +result=blur13Bilateral(textureSampler,vUV,step); +#else +float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i; +#ifdef SSAO +const scales: array=array( +0.1, +0.11406250000000001, +0.131640625, +0.15625, +0.187890625, +0.2265625, +0.272265625, +0.325, +0.384765625, +0.4515625, +0.525390625, +0.60625, +0.694140625, +0.7890625, +0.891015625, +1.0 +);uniform near: f32;uniform radius: f32;var depthSamplerSampler: sampler;var depthSampler: texture_2d;var randomSamplerSampler: sampler;var randomSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;uniform randTextureTiles: f32;uniform samplesFactor: f32;uniform sampleSphere: array;uniform totalStrength: f32;uniform base: f32;uniform xViewport: f32;uniform yViewport: f32;uniform depthProjection: mat3x3f;uniform maxZ: f32;uniform minZAspect: f32;uniform texelSize: vec2f;uniform projection: mat4x4f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var random: vec3f=textureSampleLevel(randomSampler,randomSamplerSampler,input.vUV*uniforms.randTextureTiles,0.0).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r;var depthSign: f32=sign(depth);depth=depth*depthSign;var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.0).rgb;var occlusion: f32=0.0;var correctedRadius: f32=min(uniforms.radius,uniforms.minZAspect*depth/uniforms.near);var vViewRay: vec3f= vec3f((input.vUV.x*2.0-1.0)*uniforms.xViewport,(input.vUV.y*2.0-1.0)*uniforms.yViewport,depthSign);var vDepthFactor: vec3f=uniforms.depthProjection* vec3f(1.0,1.0,depth);var origin: vec3f=vViewRay*vDepthFactor;var rvec: vec3f=random*2.0-1.0;rvec.z=0.0;var dotProduct: f32=dot(rvec,normal);rvec=select( vec3f(-rvec.y,0.0,rvec.x),rvec,1.0-abs(dotProduct)>1e-2);var tangent: vec3f=normalize(rvec-normal*dot(rvec,normal));var bitangent: vec3f=cross(normal,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,normal);var difference: f32;for (var i: i32=0; i1.0 || offset.y>1.0) {continue;} +var sampleDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;var rangeCheck: f32=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} +occlusion=occlusion*(1.0-smoothstep(uniforms.maxZ*0.75,uniforms.maxZ,depth));var ao: f32=1.0-uniforms.totalStrength*occlusion*uniforms.samplesFactor;var result: f32=clamp(ao+uniforms.base,0.0,1.0);fragmentOutputs.color= vec4f( vec3f(result),1.0);} +#else +#ifdef BLUR +uniform outSize: f32;uniform soften: f32;uniform tolerance: f32;uniform samples: i32; +#ifndef BLUR_BYPASS +var depthSamplerSampler: sampler;var depthSampler: texture_2d; +#ifdef BLUR_LEGACY +fn blur13Bilateral(image: texture_2d,imageSampler: sampler,uv: vec2f,step: vec2f)->f32 {var result: f32=0.0;var off1: vec2f= vec2f(1.411764705882353)*step;var off2: vec2f= vec2f(3.2941176470588234)*step;var off3: vec2f= vec2f(5.176470588235294)*step;var compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv,0.0).r);var sampleDepth: f32;var weight: f32;var weightSum: f32=30.0;result+=textureSampleLevel(image,imageSampler,uv,0.0).r*30.0;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv+off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv-off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off3,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off3,0.0).r*weight;return result/weightSum;} +#endif +#endif +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var result: f32=0.0; +#ifdef BLUR_BYPASS +result=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0).r; +#else +#ifdef BLUR_H +var step: vec2f= vec2f(1.0/uniforms.outSize,0.0); +#else +var step: vec2f= vec2f(0.0,1.0/uniforms.outSize); +#endif +#ifdef BLUR_LEGACY +result=blur13Bilateral(textureSampler,textureSamplerSampler,input.vUV,step); +#else +var compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r);var weightSum: f32=0.0;for (var i: i32=-uniforms.samples; i;var originalColorSampler: sampler;var originalColor: texture_2d;uniform viewport: vec4f; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +var uv: vec2f=uniforms.viewport.xy+input.vUV*uniforms.viewport.zw;var ssaoColor: vec4f=textureSample(textureSampler,textureSamplerSampler,uv);var sceneColor: vec4f=textureSample(originalColor,originalColorSampler,uv);fragmentOutputs.color=sceneColor*ssaoColor; +#define CUSTOM_FRAGMENT_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2N]) { + ShaderStore.ShadersStoreWGSL[name$2N] = shader$2M; +} +/** @internal */ +const ssaoCombinePixelShaderWGSL = { name: name$2N, shader: shader$2M }; + +const ssaoCombine_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + ssaoCombinePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2M = "screenSpaceRayTrace"; +const shader$2L = `float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +float linearizeDepth(float depth,float near,float far) { +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +return -(near*far)/(far-depth*(far-near)); +#else +return (near*far)/(far-depth*(far-near)); +#endif +} +#endif +/** +\param csOrigin Camera-space ray origin,which must be +within the view volume and must have z>0.01 and project within the valid screen rectangle +\param csDirection Unit length camera-space ray direction +\param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates +(**not** [-1,+1] normalized device coordinates). +\param csZBuffer The camera-space Z buffer +\param csZBufferSize Dimensions of csZBuffer +\param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer +\param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value +for clipping rays headed towards the camera +\param stride Step in horizontal or vertical pixels between samples. This is a float +because integer math is slow on GPUs,but should be set to an integer>=1 +\param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units +to conceal banding artifacts,plus the stride ray offset. +\param maxSteps Maximum number of iterations. Higher gives better images but may be slow +\param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss +\param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. +1 is a reasonable value,depending on the scene you may need to set this value to 2 +\param hitPixel Pixel coordinates of the first intersection with the scene +\param numIterations number of iterations performed +\param csHitPoint Camera space location of the ray hit +*/ +#define inline +bool traceScreenSpaceRay1( +vec3 csOrigin, +vec3 csDirection, +mat4 projectToPixelMatrix, +sampler2D csZBuffer, +vec2 csZBufferSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +sampler2D csZBackBuffer, +float csZBackSizeFactor, +#endif +float csZThickness, +float nearPlaneZ, +float farPlaneZ, +float stride, +float jitterFraction, +float maxSteps, +float maxRayTraceDistance, +float selfCollisionNumSkip, +out vec2 startPixel, +out vec2 hitPixel, +out vec3 csHitPoint, +out float numIterations +#ifdef SSRAYTRACE_DEBUG +,out vec3 debugColor +#endif +) +{ +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; +#else +float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);} +if ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));} +P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); +#endif +P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { +float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} +sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +sceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ); +#endif +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ); +#endif +hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); +#else +hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); +#endif +#else +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ); +#endif +hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); +#else +hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); +#endif +#endif +} +pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} +#ifdef SSRAYTRACE_ENABLE_REFINEMENT +if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || +(refinementStepCount<=stride*1.4) && +(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} +#endif +return hit;} +/** +texCoord: in the [0,1] range +depth: depth in view space (range [znear,zfar]]) +*/ +vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +#ifdef ORTHOGRAPHIC_CAMERA +ndc.z=-projection[2].z*depth+projection[3].z; +#else +ndc.z=-projection[2].z-projection[3].z/depth; +#endif +#else +#ifdef ORTHOGRAPHIC_CAMERA +ndc.z=projection[2].z*depth+projection[3].z; +#else +ndc.z=projection[2].z+projection[3].z/depth; +#endif +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$2M]) { + ShaderStore.IncludesShadersStore[name$2M] = shader$2L; +} + +// Do not edit. +const name$2L = "screenSpaceReflection2PixelShader"; +const shader$2K = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSR_SUPPORTED +uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +uniform sampler2D backDepthSampler;uniform float backSizeFactor; +#endif +#ifdef SSR_USE_ENVIRONMENT_CUBE +uniform samplerCube envCubeSampler; +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float farPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; +#include +#include +#include +vec3 hash(vec3 a) +{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} +float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; +#ifdef SSR_ATTENUATE_SCREEN_BORDERS +vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE +attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS +attenuation*=1.0-(numIterations/maxSteps); +#endif +#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION +vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; +#endif +return attenuation;} +#endif +void main() +{ +#ifdef SSR_SUPPORTED +vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=max(TEXTUREFUNC(reflectivitySampler,vUV,0.0),vec4(0.)); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { +#ifdef SSR_USE_BLUR +gl_FragColor=vec4(0.); +#else +gl_FragColor=colorFull; +#endif +return;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpace(color); +#endif +vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; +#ifdef SSR_DECODE_NORMAL +csNormal=csNormal*2.0-1.0; +#endif +#ifdef SSR_NORMAL_IS_IN_WORLDSPACE +csNormal=(view*vec4(csNormal,0.0)).xyz; +#endif +float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +depth=linearizeDepth(depth,nearPlaneZ,farPlaneZ); +#endif +vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix); +#ifdef ORTHOGRAPHIC_CAMERA +vec3 csViewDirection=vec3(0.,0.,1.); +#else +vec3 csViewDirection=normalize(csPosition); +#endif +vec3 csReflectedVector=reflect(csViewDirection,csNormal); +#ifdef SSR_USE_ENVIRONMENT_CUBE +vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); +#endif +#ifdef SSR_INVERTCUBICMAP +wReflectedVector.y*=-1.0; +#endif +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +wReflectedVector.z*=-1.0; +#endif +vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; +#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE +envColor=toLinearSpace(envColor); +#endif +#else +vec3 envColor=color; +#endif +float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; +#ifdef SSRAYTRACE_DEBUG +vec3 debugColor; +#endif +#ifdef SSR_ATTENUATE_FACING_CAMERA +reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); +#endif +if (reflectionAttenuation>0.0) { +#ifdef SSR_USE_BLUR +vec3 jitt=vec3(0.); +#else +float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; +#endif +vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); +rayHasHit=traceScreenSpaceRay1( +csPosition, +normalize(csReflectedVector+jitt), +projectionPixel, +depthSampler, +texSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +backDepthSampler, +backSizeFactor, +#endif +thickness, +nearPlaneZ, +farPlaneZ, +stepSize, +jitter, +maxSteps, +maxDistance, +selfCollisionNumSkip, +startPixel, +hitPixel, +hitPoint, +numIterations +#ifdef SSRAYTRACE_DEBUG +,debugColor +#endif +);} +#ifdef SSRAYTRACE_DEBUG +gl_FragColor=vec4(debugColor,1.);return; +#endif +vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; +#ifdef SSR_INPUT_IS_GAMMA_SPACE +reflectedColor=toLinearSpace(reflectedColor); +#endif +reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} +#ifndef SSR_BLEND_WITH_FRESNEL +SSR*=fresnel; +#endif +#ifdef SSR_USE_BLUR +float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; +float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} +gl_FragColor=vec4(SSR,blur_radius/255.0); +#else +#ifdef SSR_BLEND_WITH_FRESNEL +vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#else +vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#endif +vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpace(finalColor); +#endif +gl_FragColor=vec4(finalColor,colorFull.a); +#endif +#else +gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2L]) { + ShaderStore.ShadersStore[name$2L] = shader$2K; +} +/** @internal */ +const screenSpaceReflection2PixelShader = { name: name$2L, shader: shader$2K }; + +const screenSpaceReflection2_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + screenSpaceReflection2PixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2K = "screenSpaceReflection2BlurPixelShader"; +const shader$2J = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) +{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} +void main() +{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} +float blurRadius=colorFull.a*255.0; +vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2K]) { + ShaderStore.ShadersStore[name$2K] = shader$2J; +} +/** @internal */ +const screenSpaceReflection2BlurPixelShader = { name: name$2K, shader: shader$2J }; + +const screenSpaceReflection2Blur_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + screenSpaceReflection2BlurPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2J = "screenSpaceReflection2BlurCombinerPixelShader"; +const shader$2I = `uniform sampler2D textureSampler; +uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; +#include +#ifdef SSR_BLEND_WITH_FRESNEL +#include +#include +uniform mat4 projection;uniform mat4 invProjectionMatrix; +#ifdef SSR_NORMAL_IS_IN_WORLDSPACE +uniform mat4 view; +#endif +uniform sampler2D normalSampler;uniform sampler2D depthSampler; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +uniform float nearPlaneZ;uniform float farPlaneZ; +#endif +#endif +void main() +{ +#ifdef SSRAYTRACE_DEBUG +gl_FragColor=texture2D(textureSampler,vUV); +#else +vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpace(color); +#endif +#ifdef SSR_BLEND_WITH_FRESNEL +vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; +#ifdef SSR_DECODE_NORMAL +csNormal=csNormal*2.0-1.0; +#endif +#ifdef SSR_NORMAL_IS_IN_WORLDSPACE +csNormal=(view*vec4(csNormal,0.0)).xyz; +#endif +float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +depth=linearizeDepth(depth,nearPlaneZ,farPlaneZ); +#endif +vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#else +vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#endif +vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpace(finalColor); +#endif +gl_FragColor=vec4(finalColor,color.a); +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2J]) { + ShaderStore.ShadersStore[name$2J] = shader$2I; +} +/** @internal */ +const screenSpaceReflection2BlurCombinerPixelShader = { name: name$2J, shader: shader$2I }; + +const screenSpaceReflection2BlurCombiner_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + screenSpaceReflection2BlurCombinerPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2I = "screenSpaceRayTrace"; +const shader$2H = `fn distanceSquared(a: vec2f,b: vec2f)->f32 { +var temp=a-b; +return dot(temp,temp); } +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +fn linearizeDepth(depth: f32,near: f32,far: f32)->f32 { +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +return -(near*far)/(far-depth*(far-near)); +#else +return (near*far)/(far-depth*(far-near)); +#endif +} +#endif +/** +\param csOrigin Camera-space ray origin,which must be +within the view volume and must have z>0.01 and project within the valid screen rectangle +\param csDirection Unit length camera-space ray direction +\param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates +(**not** [-1,+1] normalized device coordinates). +\param csZBuffer The camera-space Z buffer +\param csZBufferSize Dimensions of csZBuffer +\param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer +\param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value +for clipping rays headed towards the camera. Should be the actual near plane if screen-space depth is enabled. +\param farPlaneZ The far plane for the camera. Used when screen-space depth is enabled. +\param stride Step in horizontal or vertical pixels between samples. This is a var because: f32 integer math is slow on GPUs,but should be set to an integer>=1 +\param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units +to conceal banding artifacts,plus the stride ray offset. +\param maxSteps Maximum number of iterations. Higher gives better images but may be slow +\param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss +\param selfCollisionNumSkip Number of steps to skip at start when raytracing to avar self: voidnull collisions. +1 is a reasonable value,depending on the scene you may need to set this value to 2 +\param hitPixel Pixel coordinates of the first intersection with the scene +\param numIterations number of iterations performed +\param csHitPovar Camera: i32 space location of the ray hit +*/ +fn traceScreenSpaceRay1( +csOrigin: vec3f, +csDirection: vec3f, +projectToPixelMatrix: mat4x4f, +csZBuffer: texture_2d, +csZBufferSize: vec2f, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +csZBackBuffer: texture_2d, +csZBackSizeFactor: f32, +#endif +csZThickness: f32, +nearPlaneZ: f32, +farPlaneZ: f32, +stride: f32, +jitterFraction: f32, +maxSteps: f32, +maxRayTraceDistance: f32, +selfCollisionNumSkip: f32, +startPixel: ptr, +hitPixel: ptr, +csHitPoint: ptr, +numIterations: ptr +#ifdef SSRAYTRACE_DEBUG +,debugColor: ptr +#endif +)->bool +{ +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +var rayLength: f32=select(maxRayTraceDistance,(-nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ); +#else +var rayLength: f32=select(maxRayTraceDistance,(nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax)))/(P1.y-P0.y);} +if ((P1.x>xMax) || (P1.xxMax)))/(P1.x-P0.x));} +P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); +#endif +P1+= vec2f(select(0.0,0.01,distanceSquared(P0,P1)<0.0001));var delta: vec2f=P1-P0;var permute: bool=false;if (abs(delta.x)rayZMax) { +var t: f32=rayZMin; rayZMin=rayZMax; rayZMax=t;} +sceneZMax=textureLoad(csZBuffer,vec2(*hitPixel),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +sceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ); +#endif +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +var sceneBackZ: f32=textureLoad(csZBackBuffer,vec2(*hitPixel/csZBackSizeFactor),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ); +#endif +hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); +#else +hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); +#endif +#else +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +var sceneBackZ: f32=textureLoad(csZBackBuffer,vec2(*hitPixel/csZBackSizeFactor),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ); +#endif +hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); +#else +hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); +#endif +#endif +stepCount+=1.0;} +pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} +#ifdef SSRAYTRACE_ENABLE_REFINEMENT +if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;var invStride: f32=1.0/stride;dPQK*=invStride;var refinementStepCount: f32=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || +((refinementStepCount<=stride*1.4) && +(rayZMax(*hitPixel),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +sceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ); +#endif +refinementStepCount+=1.0;} +pqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;} +#endif +Q0=vec3f(Q0.xy+dQ.xy*stepCount,pqk.z);*csHitPoint=Q0/pqk.w;*numIterations=stepCount+1.0; +#ifdef SSRAYTRACE_DEBUG +if (((pqk.x+dPQK.x)*stepDirection)>end) {*debugColor= vec3f(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {*debugColor= vec3f(1,0,0);} else if (sceneZMax==0.0) {*debugColor= vec3f(1,1,0);} else {*debugColor= vec3f(0,stepCount/maxSteps,0);} +#endif +return hit;} +/** +texCoord: in the [0,1] range +depth: depth in view space (range [znear,zfar]]) +*/ +fn computeViewPosFromUVDepth(texCoord: vec2f,depth: f32,projection: mat4x4f,invProjectionMatrix: mat4x4f)->vec3f {var xy=texCoord*2.0-1.0;var z: f32; +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +#ifdef ORTHOGRAPHIC_CAMERA +z=-projection[2].z*depth+projection[3].z; +#else +z=-projection[2].z-projection[3].z/depth; +#endif +#else +#ifdef ORTHOGRAPHIC_CAMERA +z=projection[2].z*depth+projection[3].z; +#else +z=projection[2].z+projection[3].z/depth; +#endif +#endif +var w=1.0;var ndc=vec4f(xy,z,w);var eyePos: vec4f=invProjectionMatrix*ndc;var result=eyePos.xyz/eyePos.w;return result;} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$2I]) { + ShaderStore.IncludesShadersStoreWGSL[name$2I] = shader$2H; +} + +// Do not edit. +const name$2H = "screenSpaceReflection2PixelShader"; +const shader$2G = `var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f; +#ifdef SSR_SUPPORTED +var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;var normalSampler: texture_2d;var depthSampler: texture_2d; +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +var backDepthSampler: texture_2d;uniform backSizeFactor: f32; +#endif +#ifdef SSR_USE_ENVIRONMENT_CUBE +var envCubeSamplerSampler: sampler;var envCubeSampler: texture_cube; +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f; +#endif +#endif +uniform view: mat4x4f;uniform invView: mat4x4f;uniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f;uniform projectionPixel: mat4x4f;uniform nearPlaneZ: f32;uniform farPlaneZ: f32;uniform stepSize: f32;uniform maxSteps: f32;uniform strength: f32;uniform thickness: f32;uniform roughnessFactor: f32;uniform reflectionSpecularFalloffExponent: f32;uniform maxDistance: f32;uniform selfCollisionNumSkip: f32;uniform reflectivityThreshold: f32; +#include +#include +#include +fn hash(a: vec3f)->vec3f +{var result=fract(a*0.8);result+=dot(result,result.yxz+19.19);return fract((result.xxy+result.yxx)*result.zyx);} +fn computeAttenuationForIntersection(ihitPixel: vec2f,hitUV: vec2f,vsRayOrigin: vec3f,vsHitPoint: vec3f,reflectionVector: vec3f,maxRayDistance: f32,numIterations: f32)->f32 {var attenuation: f32=1.0; +#ifdef SSR_ATTENUATE_SCREEN_BORDERS +var dCoords: vec2f=smoothstep(vec2f(0.2),vec2f(0.6),abs( vec2f(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE +attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS +attenuation*=1.0-(numIterations/uniforms.maxSteps); +#endif +#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION +var reflectionNormal: vec3f=texelFetch(normalSampler,hitPixel,0).xyz;var directionBasedAttenuation: f32=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; +#endif +return attenuation;} +#endif +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#ifdef SSR_SUPPORTED +var colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var color: vec3f=colorFull.rgb;var reflectivity: vec4f=max(textureSampleLevel(reflectivitySampler,reflectivitySamplerSampler,input.vUV,0.0),vec4f(0.0)); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) { +#ifdef SSR_USE_BLUR +fragmentOutputs.color= vec4f(0.); +#else +fragmentOutputs.color=colorFull; +#endif +return fragmentOutputs;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpaceVec3(color); +#endif +var texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2(input.vUV*texSize),0).xyz; +#ifdef SSR_DECODE_NORMAL +csNormal=csNormal*2.0-1.0; +#endif +#ifdef SSR_NORMAL_IS_IN_WORLDSPACE +csNormal=(uniforms.view* vec4f(csNormal,0.0)).xyz; +#endif +var depth: f32=textureLoad(depthSampler,vec2(input.vUV*texSize),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +depth=linearizeDepth(depth,uniforms.nearPlaneZ,uniforms.farPlaneZ); +#endif +var csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix); +#ifdef ORTHOGRAPHIC_CAMERA +var csViewDirection: vec3f= vec3f(0.,0.,1.); +#else +var csViewDirection: vec3f=normalize(csPosition); +#endif +var csReflectedVector: vec3f=reflect(csViewDirection,csNormal); +#ifdef SSR_USE_ENVIRONMENT_CUBE +var wReflectedVector: vec3f=(uniforms.invView* vec4f(csReflectedVector,0.0)).xyz; +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +var worldPos: vec4f=uniforms.invView* vec4f(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),uniforms.vReflectionSize,uniforms.vReflectionPosition); +#endif +#ifdef SSR_INVERTCUBICMAP +wReflectedVector.y*=-1.0; +#endif +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +wReflectedVector.z*=-1.0; +#endif +var envColor: vec3f=textureSampleLevel(envCubeSampler,envCubeSamplerSampler,wReflectedVector,0.0).xyz; +#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE +envColor=toLinearSpaceVec3(envColor); +#endif +#else +var envColor: vec3f=color; +#endif +var reflectionAttenuation: f32=1.0;var rayHasHit: bool=false;var startPixel: vec2f;var hitPixel: vec2f;var hitPoint: vec3f;var numIterations: f32; +#ifdef SSRAYTRACE_DEBUG +var debugColor: vec3f; +#endif +#ifdef SSR_ATTENUATE_FACING_CAMERA +reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); +#endif +if (reflectionAttenuation>0.0) { +#ifdef SSR_USE_BLUR +var jitt: vec3f= vec3f(0.); +#else +var roughness: f32=1.0-reflectivity.a;var jitt: vec3f=mix( vec3f(0.0),hash(csPosition)- vec3f(0.5),roughness)*uniforms.roughnessFactor; +#endif +var uv2: vec2f=input.vUV*texSize;var c: f32=(uv2.x+uv2.y)*0.25;var jitter: f32=((c)%(1.0)); +rayHasHit=traceScreenSpaceRay1( +csPosition, +normalize(csReflectedVector+jitt), +uniforms.projectionPixel, +depthSampler, +texSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +backDepthSampler, +uniforms.backSizeFactor, +#endif +uniforms.thickness, +uniforms.nearPlaneZ, +uniforms.farPlaneZ, +uniforms.stepSize, +jitter, +uniforms.maxSteps, +uniforms.maxDistance, +uniforms.selfCollisionNumSkip, +&startPixel, +&hitPixel, +&hitPoint, +&numIterations +#ifdef SSRAYTRACE_DEBUG +,&debugColor +#endif +);} +#ifdef SSRAYTRACE_DEBUG +fragmentOutputs.color= vec4f(debugColor,1.);return fragmentOutputs; +#endif +var F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var SSR: vec3f=envColor;if (rayHasHit) {var reflectedColor: vec3f=textureLoad(textureSampler,vec2(hitPixel),0).rgb; +#ifdef SSR_INPUT_IS_GAMMA_SPACE +reflectedColor=toLinearSpaceVec3(reflectedColor); +#endif +reflectionAttenuation*=computeAttenuationForIntersection(hitPixel,hitPixel/texSize,csPosition,hitPoint,csReflectedVector,uniforms.maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} +#ifndef SSR_BLEND_WITH_FRESNEL +SSR*=fresnel; +#endif +#ifdef SSR_USE_BLUR +var blur_radius: f32=0.0;var roughness: f32=1.0-reflectivity.a*(1.0-uniforms.roughnessFactor);if (roughness>0.001) {var cone_angle: f32=min(roughness,0.999)*3.14159265*0.5;var cone_len: f32=distance(startPixel,hitPixel);var op_len: f32=2.0*tan(cone_angle)*cone_len; +var a: f32=op_len;var h: f32=cone_len;var a2: f32=a*a;var fh2: f32=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} +fragmentOutputs.color= vec4f(SSR,blur_radius/255.0); +#else +#ifdef SSR_BLEND_WITH_FRESNEL +var reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); +#else +var reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); +#endif +var colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpaceVec3(finalColor); +#endif +fragmentOutputs.color= vec4f(finalColor,colorFull.a); +#endif +#else +fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0); +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2H]) { + ShaderStore.ShadersStoreWGSL[name$2H] = shader$2G; +} +/** @internal */ +const screenSpaceReflection2PixelShaderWGSL = { name: name$2H, shader: shader$2G }; + +const screenSpaceReflection2_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + screenSpaceReflection2PixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2G = "screenSpaceReflection2BlurPixelShader"; +const shader$2F = `var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;uniform texelOffsetScale: vec2f;const weights: array=array(0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);fn processSample(uv: vec2f,i: f32,stepSize: vec2f,accumulator: ptr,denominator: ptr) +{var offsetUV: vec2f=stepSize*i+uv;var coefficient: f32=weights[ i32(2.0-abs(i))];*accumulator+=textureSampleLevel(textureSampler,textureSamplerSampler,offsetUV,0.0)*coefficient;*denominator+=coefficient;} +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);if (dot(colorFull, vec4f(1.0))==0.0) {fragmentOutputs.color=colorFull;return fragmentOutputs;} +var blurRadius: f32=colorFull.a*255.0; +var stepSize: vec2f=uniforms.texelOffsetScale.xy*blurRadius;var accumulator: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0)*0.214607;var denominator: f32=0.214607;processSample(input.vUV,1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*2.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*2.0,stepSize,&accumulator,&denominator);fragmentOutputs.color= vec4f(accumulator.rgb/denominator,colorFull.a);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2G]) { + ShaderStore.ShadersStoreWGSL[name$2G] = shader$2F; +} +/** @internal */ +const screenSpaceReflection2BlurPixelShaderWGSL = { name: name$2G, shader: shader$2F }; + +const screenSpaceReflection2Blur_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + screenSpaceReflection2BlurPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2F = "screenSpaceReflection2BlurCombinerPixelShader"; +const shader$2E = `var textureSamplerSampler: sampler;var textureSampler: texture_2d; +var mainSamplerSampler: sampler;var mainSampler: texture_2d;var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;uniform strength: f32;uniform reflectionSpecularFalloffExponent: f32;uniform reflectivityThreshold: f32;varying vUV: vec2f; +#include +#ifdef SSR_BLEND_WITH_FRESNEL +#include +#include +uniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f; +#ifdef SSR_NORMAL_IS_IN_WORLDSPACE +uniform view: mat4x4f; +#endif +var normalSampler: texture_2d;var depthSampler: texture_2d; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +uniform nearPlaneZ: f32;uniform farPlaneZ: f32; +#endif +#endif +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#ifdef SSRAYTRACE_DEBUG +fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV); +#else +var SSR: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var color: vec4f=textureSample(mainSampler,textureSamplerSampler,input.vUV);var reflectivity: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vUV); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) {fragmentOutputs.color=color;return fragmentOutputs;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpaceVec4(color); +#endif +#ifdef SSR_BLEND_WITH_FRESNEL +var texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2(input.vUV*texSize),0).xyz; +#ifdef SSR_DECODE_NORMAL +csNormal=csNormal*2.0-1.0; +#endif +#ifdef SSR_NORMAL_IS_IN_WORLDSPACE +csNormal=(uniforms.view*vec4f(csNormal,0.0)).xyz; +#endif +var depth: f32=textureLoad(depthSampler,vec2(input.vUV*texSize),0).r; +#ifdef SSRAYTRACE_SCREENSPACE_DEPTH +depth=linearizeDepth(depth,uniforms.nearPlaneZ,uniforms.farPlaneZ); +#endif +var csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix);var csViewDirection: vec3f=normalize(csPosition);var F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); +#else +var reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); +#endif +var colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpaceVec3(finalColor); +#endif +fragmentOutputs.color= vec4f(finalColor,color.a); +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2F]) { + ShaderStore.ShadersStoreWGSL[name$2F] = shader$2E; +} +/** @internal */ +const screenSpaceReflection2BlurCombinerPixelShaderWGSL = { name: name$2F, shader: shader$2E }; + +const screenSpaceReflection2BlurCombiner_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + screenSpaceReflection2BlurCombinerPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2E = "taaPixelShader"; +const shader$2D = `varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2E]) { + ShaderStore.ShadersStore[name$2E] = shader$2D; +} +/** @internal */ +const taaPixelShader = { name: name$2E, shader: shader$2D }; + +const taa_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + taaPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2D = "taaPixelShader"; +const shader$2C = `var textureSampler: texture_2d;var historySampler: texture_2d;uniform factor: f32;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {let c=textureLoad(textureSampler,vec2(fragmentInputs.position.xy),0);let h=textureLoad(historySampler,vec2(fragmentInputs.position.xy),0);fragmentOutputs.color= mix(h,c,uniforms.factor);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2D]) { + ShaderStore.ShadersStoreWGSL[name$2D] = shader$2C; +} +/** @internal */ +const taaPixelShaderWGSL = { name: name$2D, shader: shader$2C }; + +const taa_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + taaPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +/** Defines operator used for tonemapping */ +var TonemappingOperator; +(function (TonemappingOperator) { + /** Hable */ + TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable"; + /** Reinhard */ + TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard"; + /** HejiDawson */ + TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson"; + /** Photographic */ + TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic"; +})(TonemappingOperator || (TonemappingOperator = {})); + +// Do not edit. +const name$2C = "volumetricLightScatteringPixelShader"; +const shader$2B = `uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +uniform mat4 viewProjection;uniform vec2 depthValues; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) +vec2 uvUpdated=uv; +#endif +#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV2) +vec2 uv2Updated=uv2; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); +#endif +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2B]) { + ShaderStore.ShadersStore[name$2B] = shader$2A; +} + +// Do not edit. +const name$2A = "volumetricLightScatteringPassPixelShader"; +const shader$2z = `#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV; +#endif +#if defined(ALPHATEST) +uniform sampler2D diffuseSampler; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#if defined(ALPHATEST) +vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) +discard; +#endif +gl_FragColor=vec4(0.0,0.0,0.0,1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2A]) { + ShaderStore.ShadersStore[name$2A] = shader$2z; +} + +/** + * Inspired by https://developer.nvidia.com/gpugems/gpugems3/part-ii-light-and-shadows/chapter-13-volumetric-light-scattering-post-process + */ +class VolumetricLightScatteringPostProcess extends PostProcess { + /** + * @internal + * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead + */ + get useDiffuseColor() { + Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"); + return false; + } + set useDiffuseColor(useDiffuseColor) { + Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"); + } + /** + * @constructor + * @param name The post-process name + * @param ratio The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) + * @param camera The camera that the post-process will be attached to + * @param mesh The mesh used to create the light scattering + * @param samples The post-process quality, default 100 + * @param samplingMode The post-process filtering mode + * @param engine The babylon engine + * @param reusable If the post-process is reusable + * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided + */ + constructor(name, ratio, camera, mesh, samples = 100, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable, scene) { + super(name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples); + this._screenCoordinates = Vector2.Zero(); + /** + * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true" + */ + this.customMeshPosition = Vector3.Zero(); + /** + * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false) + */ + this.useCustomMeshPosition = false; + /** + * If the post-process should inverse the light scattering direction + */ + this.invert = true; + /** + * Array containing the excluded meshes not rendered in the internal pass + */ + this.excludedMeshes = []; + /** + * Array containing the only meshes rendered in the internal pass. + * If this array is not empty, only the meshes from this array are rendered in the internal pass + */ + this.includedMeshes = []; + /** + * Controls the overall intensity of the post-process + */ + this.exposure = 0.3; + /** + * Dissipates each sample's contribution in range [0, 1] + */ + this.decay = 0.96815; + /** + * Controls the overall intensity of each sample + */ + this.weight = 0.58767; + /** + * Controls the density of each sample + */ + this.density = 0.926; + scene = camera?.getScene() ?? scene ?? this._scene; // parameter "scene" can be null. + engine = scene.getEngine(); + this._viewPort = new Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); + // Configure mesh + this.mesh = mesh ?? VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene); + // Configure + this._createPass(scene, ratio.passRatio || ratio); + this.onActivate = (camera) => { + if (!this.isSupported) { + this.dispose(camera); + } + this.onActivate = null; + }; + this.onApplyObservable.add((effect) => { + this._updateMeshScreenCoordinates(scene); + effect.setTexture("lightScatteringSampler", this._volumetricLightScatteringRTT); + effect.setFloat("exposure", this.exposure); + effect.setFloat("decay", this.decay); + effect.setFloat("weight", this.weight); + effect.setFloat("density", this.density); + effect.setVector2("meshPositionOnScreen", this._screenCoordinates); + }); + } + /** + * Returns the string "VolumetricLightScatteringPostProcess" + * @returns "VolumetricLightScatteringPostProcess" + */ + getClassName() { + return "VolumetricLightScatteringPostProcess"; + } + _isReady(subMesh, useInstances) { + const mesh = subMesh.getMesh(); + // Render this.mesh as default + if (mesh === this.mesh && mesh.material) { + return mesh.material.isReady(mesh); + } + const renderingMaterial = mesh._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId]; + if (renderingMaterial) { + return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances); + } + const defines = []; + const attribs = [VertexBuffer.PositionKind]; + const material = subMesh.getMaterial(); + let uv1 = false; + let uv2 = false; + const color = false; + // Alpha test + if (material) { + const needAlphaTesting = material.needAlphaTestingForMesh(mesh); + if (needAlphaTesting) { + defines.push("#define ALPHATEST"); + } + if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { + attribs.push(VertexBuffer.UVKind); + defines.push("#define UV1"); + uv1 = needAlphaTesting; + } + if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) { + attribs.push(VertexBuffer.UV2Kind); + defines.push("#define UV2"); + uv2 = needAlphaTesting; + } + } + // Bones + const fallbacks = new EffectFallbacks(); + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + attribs.push(VertexBuffer.MatricesIndicesKind); + attribs.push(VertexBuffer.MatricesWeightsKind); + if (mesh.numBoneInfluencers > 4) { + attribs.push(VertexBuffer.MatricesIndicesExtraKind); + attribs.push(VertexBuffer.MatricesWeightsExtraKind); + } + defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); + if (mesh.numBoneInfluencers > 0) { + fallbacks.addCPUSkinningFallback(0, mesh); + } + const skeleton = mesh.skeleton; + if (skeleton.isUsingTextureForMatrices) { + defines.push("#define BONETEXTURE"); + } + else { + defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); + } + } + else { + defines.push("#define NUM_BONE_INFLUENCERS 0"); + } + // Morph targets + const numMorphInfluencers = mesh.morphTargetManager + ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph + false, // useNormalMorph + false, // useTangentMorph + uv1, // useUVMorph + uv2, // useUV2Morph + color // useColorMorph + ) + : 0; + // Instances + if (useInstances) { + defines.push("#define INSTANCES"); + PushAttributesForInstances(attribs); + if (subMesh.getRenderingMesh().hasThinInstances) { + defines.push("#define THIN_INSTANCES"); + } + } + // Baked vertex animations + const bvaManager = mesh.bakedVertexAnimationManager; + if (bvaManager && bvaManager.isEnabled) { + defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"); + if (useInstances) { + attribs.push("bakedVertexAnimationSettingsInstanced"); + } + } + // Get correct effect + const drawWrapper = subMesh._getDrawWrapper(undefined, true); + const cachedDefines = drawWrapper.defines; + const join = defines.join("\n"); + if (cachedDefines !== join) { + const uniforms = [ + "world", + "mBones", + "boneTextureWidth", + "viewProjection", + "diffuseMatrix", + "morphTargetInfluences", + "morphTargetCount", + "morphTargetTextureInfo", + "morphTargetTextureIndices", + "bakedVertexAnimationSettings", + "bakedVertexAnimationTextureSizeInverted", + "bakedVertexAnimationTime", + "bakedVertexAnimationTexture", + ]; + const samplers = ["diffuseSampler", "morphTargets", "boneSampler", "bakedVertexAnimationTexture"]; + drawWrapper.setEffect(mesh + .getScene() + .getEngine() + .createEffect("volumetricLightScatteringPass", { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: [], + samplers: samplers, + defines: join, + fallbacks: fallbacks, + onCompiled: null, + onError: null, + indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers }, + }, mesh.getScene().getEngine()), join); + } + return drawWrapper.effect.isReady(); + } + /** + * Sets the new light position for light scattering effect + * @param position The new custom light position + */ + setCustomMeshPosition(position) { + this.customMeshPosition = position; + } + /** + * Returns the light position for light scattering effect + * @returns Vector3 The custom light position + */ + getCustomMeshPosition() { + return this.customMeshPosition; + } + /** + * Disposes the internal assets and detaches the post-process from the camera + * @param camera The camera from which to detach the post-process + */ + dispose(camera) { + const rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT); + if (rttIndex !== -1) { + camera.getScene().customRenderTargets.splice(rttIndex, 1); + } + this._volumetricLightScatteringRTT.dispose(); + super.dispose(camera); + } + /** + * Returns the render target texture used by the post-process + * @returns the render target texture used by the post-process + */ + getPass() { + return this._volumetricLightScatteringRTT; + } + // Private methods + _meshExcluded(mesh) { + if ((this.includedMeshes.length > 0 && this.includedMeshes.indexOf(mesh) === -1) || (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1)) { + return true; + } + return false; + } + _createPass(scene, ratio) { + const engine = scene.getEngine(); + this._volumetricLightScatteringRTT = new RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, 0); + this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE; + this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE; + this._volumetricLightScatteringRTT.renderList = null; + this._volumetricLightScatteringRTT.renderParticles = false; + this._volumetricLightScatteringRTT.ignoreCameraViewport = true; + const camera = this.getCamera(); + if (camera) { + camera.customRenderTargets.push(this._volumetricLightScatteringRTT); + } + else { + scene.customRenderTargets.push(this._volumetricLightScatteringRTT); + } + // Custom render function for submeshes + const renderSubMesh = (subMesh) => { + const renderingMesh = subMesh.getRenderingMesh(); + const effectiveMesh = subMesh.getEffectiveMesh(); + if (this._meshExcluded(renderingMesh)) { + return; + } + effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; + const material = subMesh.getMaterial(); + if (!material) { + return; + } + const scene = renderingMesh.getScene(); + const engine = scene.getEngine(); + // Culling + engine.setState(material.backFaceCulling, undefined, undefined, undefined, material.cullBackFaces); + // Managing instances + const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); + if (batch.mustReturn) { + return; + } + const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); + if (this._isReady(subMesh, hardwareInstancedRendering)) { + const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine.currentRenderPassId]; + let drawWrapper = subMesh._getDrawWrapper(); + if (renderingMesh === this.mesh && !drawWrapper) { + drawWrapper = material._getDrawWrapper(); + } + if (!drawWrapper) { + return; + } + const effect = drawWrapper.effect; + engine.enableEffect(drawWrapper); + if (!hardwareInstancedRendering) { + renderingMesh._bind(subMesh, effect, material.fillMode); + } + if (renderingMesh === this.mesh) { + material.bind(effectiveMesh.getWorldMatrix(), renderingMesh); + } + else if (renderingMaterial) { + renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh); + } + else { + effect.setMatrix("viewProjection", scene.getTransformMatrix()); + // Alpha test + if (material.needAlphaTestingForMesh(effectiveMesh)) { + const alphaTexture = material.getAlphaTestTexture(); + if (alphaTexture) { + effect.setTexture("diffuseSampler", alphaTexture); + effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); + } + } + // Bones + BindBonesParameters(renderingMesh, effect); + // Morph targets + BindMorphTargetParameters(renderingMesh, effect); + if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { + renderingMesh.morphTargetManager._bind(effect); + } + // Baked vertex animations + const bvaManager = subMesh.getMesh().bakedVertexAnimationManager; + if (bvaManager && bvaManager.isEnabled) { + bvaManager.bind(effect, hardwareInstancedRendering); + } + } + if (hardwareInstancedRendering && renderingMesh.hasThinInstances) { + effect.setMatrix("world", effectiveMesh.getWorldMatrix()); + } + // Draw + renderingMesh._processRendering(effectiveMesh, subMesh, effect, Material.TriangleFillMode, batch, hardwareInstancedRendering, (isInstance, world) => { + if (!isInstance) { + effect.setMatrix("world", world); + } + }); + } + }; + // Render target texture callbacks + let savedSceneClearColor; + const sceneClearColor = new Color4(0.0, 0.0, 0.0, 1.0); + this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(() => { + savedSceneClearColor = scene.clearColor; + scene.clearColor = sceneClearColor; + }); + this._volumetricLightScatteringRTT.onAfterRenderObservable.add(() => { + scene.clearColor = savedSceneClearColor; + }); + this._volumetricLightScatteringRTT.customIsReadyFunction = (mesh, refreshRate, preWarm) => { + if ((preWarm || refreshRate === 0) && mesh.subMeshes) { + for (let i = 0; i < mesh.subMeshes.length; ++i) { + const subMesh = mesh.subMeshes[i]; + const material = subMesh.getMaterial(); + const renderingMesh = subMesh.getRenderingMesh(); + if (!material) { + continue; + } + const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); + const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); + if (!this._isReady(subMesh, hardwareInstancedRendering)) { + return false; + } + } + } + return true; + }; + this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { + const engine = scene.getEngine(); + let index; + if (depthOnlySubMeshes.length) { + engine.setColorWrite(false); + for (index = 0; index < depthOnlySubMeshes.length; index++) { + renderSubMesh(depthOnlySubMeshes.data[index]); + } + engine.setColorWrite(true); + } + for (index = 0; index < opaqueSubMeshes.length; index++) { + renderSubMesh(opaqueSubMeshes.data[index]); + } + for (index = 0; index < alphaTestSubMeshes.length; index++) { + renderSubMesh(alphaTestSubMeshes.data[index]); + } + if (transparentSubMeshes.length) { + // Sort sub meshes + for (index = 0; index < transparentSubMeshes.length; index++) { + const submesh = transparentSubMeshes.data[index]; + const boundingInfo = submesh.getBoundingInfo(); + if (boundingInfo && scene.activeCamera) { + submesh._alphaIndex = submesh.getMesh().alphaIndex; + submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length(); + } + } + const sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length); + sortedArray.sort((a, b) => { + // Alpha index first + if (a._alphaIndex > b._alphaIndex) { + return 1; + } + if (a._alphaIndex < b._alphaIndex) { + return -1; + } + // Then distance to camera + if (a._distanceToCamera < b._distanceToCamera) { + return 1; + } + if (a._distanceToCamera > b._distanceToCamera) { + return -1; + } + return 0; + }); + // Render sub meshes + engine.setAlphaMode(2); + for (index = 0; index < sortedArray.length; index++) { + renderSubMesh(sortedArray[index]); + } + engine.setAlphaMode(0); + } + }; + } + _updateMeshScreenCoordinates(scene) { + const transform = scene.getTransformMatrix(); + let meshPosition; + if (this.useCustomMeshPosition) { + meshPosition = this.customMeshPosition; + } + else if (this.attachedNode) { + meshPosition = this.attachedNode.position; + } + else { + meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position; + } + const pos = Vector3.Project(meshPosition, Matrix.Identity(), transform, this._viewPort); + this._screenCoordinates.x = pos.x / this._viewPort.width; + this._screenCoordinates.y = pos.y / this._viewPort.height; + if (this.invert) { + this._screenCoordinates.y = 1.0 - this._screenCoordinates.y; + } + } + // Static methods + /** + * Creates a default mesh for the Volumeric Light Scattering post-process + * @param name The mesh name + * @param scene The scene where to create the mesh + * @returns the default mesh + */ + static CreateDefaultMesh(name, scene) { + const mesh = CreatePlane(name, { size: 1 }, scene); + mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL; + const material = new StandardMaterial(name + "Material", scene); + material.emissiveColor = new Color3(1, 1, 1); + mesh.material = material; + return mesh; + } +} +__decorate([ + serializeAsVector3() +], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0); +__decorate([ + serialize() +], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0); +__decorate([ + serialize() +], VolumetricLightScatteringPostProcess.prototype, "invert", void 0); +__decorate([ + serializeAsMeshReference() +], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0); +__decorate([ + serialize() +], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0); +__decorate([ + serialize() +], VolumetricLightScatteringPostProcess.prototype, "includedMeshes", void 0); +__decorate([ + serialize() +], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0); +__decorate([ + serialize() +], VolumetricLightScatteringPostProcess.prototype, "decay", void 0); +__decorate([ + serialize() +], VolumetricLightScatteringPostProcess.prototype, "weight", void 0); +__decorate([ + serialize() +], VolumetricLightScatteringPostProcess.prototype, "density", void 0); +RegisterClass("BABYLON.VolumetricLightScatteringPostProcess", VolumetricLightScatteringPostProcess); + +// Do not edit. +const name$2z = "screenSpaceCurvaturePixelShader"; +const shader$2y = `precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform float curvature_ridge;uniform float curvature_valley; +#ifndef CURVATURE_OFFSET +#define CURVATURE_OFFSET 1 +#endif +float curvature_soft_clamp(float curvature,float control) +{if (curvature<0.5/control) +return curvature*(1.0-curvature*control);return 0.25/control;} +float calculate_curvature(ivec2 texel,float ridge,float valley) +{vec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;vec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;vec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;vec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;float normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));if (normal_diff<0.0) +return -2.0*curvature_soft_clamp(-normal_diff,valley);return 2.0*curvature_soft_clamp(normal_diff,ridge);} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ivec2 texel=ivec2(gl_FragCoord.xy);vec4 baseColor=texture2D(textureSampler,vUV);float curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);baseColor.rgb*=curvature+1.0;gl_FragColor=baseColor;}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2z]) { + ShaderStore.ShadersStore[name$2z] = shader$2y; +} + +/** + * The Screen Space curvature effect can help highlighting ridge and valley of a model. + */ +class ScreenSpaceCurvaturePostProcess extends PostProcess { + /** + * Gets a string identifying the name of the class + * @returns "ScreenSpaceCurvaturePostProcess" string + */ + getClassName() { + return "ScreenSpaceCurvaturePostProcess"; + } + /** + * Creates a new instance ScreenSpaceCurvaturePostProcess + * @param name The name of the effect. + * @param scene The scene containing the objects to blur according to their velocity. + * @param options The required width/height ratio to downsize to before computing the render pass. + * @param camera The camera to apply the render pass to. + * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) + * @param engine The engine which the post process will be applied. (default: current engine) + * @param reusable If the post process can be reused on the same frame. (default: false) + * @param textureType Type of textures used when performing the post process. (default: 0) + * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) + */ + constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { + super(name, "screenSpaceCurvature", ["curvature_ridge", "curvature_valley"], ["textureSampler", "normalSampler"], options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation); + /** + * Defines how much ridge the curvature effect displays. + */ + this.ridge = 1; + /** + * Defines how much valley the curvature effect displays. + */ + this.valley = 1; + this._geometryBufferRenderer = scene.enableGeometryBufferRenderer(); + if (!this._geometryBufferRenderer) { + // Geometry buffer renderer is not supported. So, work as a passthrough. + Logger.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first."); + } + else { + if (this._geometryBufferRenderer.generateNormalsInWorldSpace) { + Logger.Error("ScreenSpaceCurvaturePostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"); + } + // Geometry buffer renderer is supported. + this.onApply = (effect) => { + effect.setFloat("curvature_ridge", 0.5 / Math.max(this.ridge * this.ridge, 1e-4)); + effect.setFloat("curvature_valley", 0.7 / Math.max(this.valley * this.valley, 1e-4)); + const normalTexture = this._geometryBufferRenderer.getGBuffer().textures[1]; + effect.setTexture("normalSampler", normalTexture); + }; + } + } + /** + * Support test. + */ + static get IsSupported() { + const engine = EngineStore.LastCreatedEngine; + if (!engine) { + return false; + } + return engine.getCaps().drawBuffersExtension; + } + /** + * @internal + */ + static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { + return SerializationHelper.Parse(() => { + return new ScreenSpaceCurvaturePostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable); + }, parsedPostProcess, scene, rootUrl); + } +} +__decorate([ + serialize() +], ScreenSpaceCurvaturePostProcess.prototype, "ridge", void 0); +__decorate([ + serialize() +], ScreenSpaceCurvaturePostProcess.prototype, "valley", void 0); +RegisterClass("BABYLON.ScreenSpaceCurvaturePostProcess", ScreenSpaceCurvaturePostProcess); + +// Do not edit. +const name$2y = "postprocessVertexShader"; +const shader$2x = `attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2y]) { + ShaderStore.ShadersStoreWGSL[name$2y] = shader$2x; +} +/** @internal */ +const postprocessVertexShaderWGSL = { name: name$2y, shader: shader$2x }; + +const postprocess_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + postprocessVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2x = "kernelBlurVaryingDeclaration"; +const shader$2w = `varying vec2 sampleCoord{X};`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$2x]) { + ShaderStore.IncludesShadersStore[name$2x] = shader$2w; +} + +// Do not edit. +const name$2w = "kernelBlurFragment"; +const shader$2v = `#ifdef DOF +factor=sampleCoC(sampleCoord{X}); +computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; +#else +blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$2w]) { + ShaderStore.IncludesShadersStore[name$2w] = shader$2v; +} + +// Do not edit. +const name$2v = "kernelBlurFragment2"; +const shader$2u = `#ifdef DOF +factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_DEP_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; +#else +blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$2v]) { + ShaderStore.IncludesShadersStore[name$2v] = shader$2u; +} + +// Do not edit. +const name$2u = "kernelBlurPixelShader"; +const shader$2t = `uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; +#ifdef DOF +uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } +#endif +#include[0..varyingCount] +#ifdef PACKEDFLOAT +#include +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float computedWeight=0.0; +#ifdef PACKEDFLOAT +float blend=0.; +#else +vec4 blend=vec4(0.); +#endif +#ifdef DOF +float sumOfWeights=CENTER_WEIGHT; +float factor=0.0; +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; +#else +blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; +#endif +#endif +#include[0..varyingCount] +#include[0..depCount] +#ifdef PACKEDFLOAT +gl_FragColor=pack(blend); +#else +gl_FragColor=blend; +#endif +#ifdef DOF +gl_FragColor/=sumOfWeights; +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2u]) { + ShaderStore.ShadersStore[name$2u] = shader$2t; +} +/** @internal */ +const kernelBlurPixelShader = { name: name$2u, shader: shader$2t }; + +const kernelBlur_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + kernelBlurPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2t = "kernelBlurVertex"; +const shader$2s = `sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$2t]) { + ShaderStore.IncludesShadersStore[name$2t] = shader$2s; +} + +// Do not edit. +const name$2s = "kernelBlurVertexShader"; +const shader$2r = `attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; +#include[0..varyingCount] +const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +sampleCenter=(position*madd+madd); +#include[0..varyingCount] +gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2s]) { + ShaderStore.ShadersStore[name$2s] = shader$2r; +} +/** @internal */ +const kernelBlurVertexShader = { name: name$2s, shader: shader$2r }; + +const kernelBlur_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + kernelBlurVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2r = "kernelBlurVaryingDeclaration"; +const shader$2q = `varying sampleCoord{X}: vec2f;`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$2r]) { + ShaderStore.IncludesShadersStoreWGSL[name$2r] = shader$2q; +} + +// Do not edit. +const name$2q = "kernelBlurFragment"; +const shader$2p = `#ifdef DOF +factor=sampleCoC(fragmentInputs.sampleCoord{X}); +computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X}))*computedWeight; +#else +blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X})*computedWeight; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$2q]) { + ShaderStore.IncludesShadersStoreWGSL[name$2q] = shader$2p; +} + +// Do not edit. +const name$2p = "kernelBlurFragment2"; +const shader$2o = `#ifdef DOF +factor=sampleCoC(fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_DEP_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X}))*computedWeight; +#else +blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X})*computedWeight; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$2p]) { + ShaderStore.IncludesShadersStoreWGSL[name$2p] = shader$2o; +} + +// Do not edit. +const name$2o = "kernelBlurPixelShader"; +const shader$2n = `var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform delta: vec2f;varying sampleCenter: vec2f; +#ifdef DOF +var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;fn sampleCoC(offset: vec2f)->f32 {var coc: f32=textureSample(circleOfConfusionSampler,circleOfConfusionSamplerSampler,offset).r;return coc; } +#endif +#include[0..varyingCount] +#ifdef PACKEDFLOAT +#include +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var computedWeight: f32=0.0; +#ifdef PACKEDFLOAT +var blend: f32=0.; +#else +var blend: vec4f= vec4f(0.); +#endif +#ifdef DOF +var sumOfWeights: f32=CENTER_WEIGHT; +var factor: f32=0.0; +#ifdef PACKEDFLOAT +blend+=unpack(textureSample(textureSampler,textureSamplerSampler,input.sampleCenter))*CENTER_WEIGHT; +#else +blend+=textureSample(textureSampler,textureSamplerSampler,input.sampleCenter)*CENTER_WEIGHT; +#endif +#endif +#include[0..varyingCount] +#include[0..depCount] +#ifdef PACKEDFLOAT +fragmentOutputs.color=pack(blend); +#else +fragmentOutputs.color=blend; +#endif +#ifdef DOF +fragmentOutputs.color/=sumOfWeights; +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2o]) { + ShaderStore.ShadersStoreWGSL[name$2o] = shader$2n; +} +/** @internal */ +const kernelBlurPixelShaderWGSL = { name: name$2o, shader: shader$2n }; + +const kernelBlur_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + kernelBlurPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2n = "kernelBlurVertex"; +const shader$2m = `vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$2n]) { + ShaderStore.IncludesShadersStoreWGSL[name$2n] = shader$2m; +} + +// Do not edit. +const name$2m = "kernelBlurVertexShader"; +const shader$2l = `attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f; +#include[0..varyingCount] +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5); +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.sampleCenter=(input.position*madd+madd); +#include[0..varyingCount] +vertexOutputs.position= vec4f(input.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2m]) { + ShaderStore.ShadersStoreWGSL[name$2m] = shader$2l; +} +/** @internal */ +const kernelBlurVertexShaderWGSL = { name: name$2m, shader: shader$2l }; + +const kernelBlur_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + kernelBlurVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2l = "passPixelShader"; +const shader$2k = `varying vec2 vUV;uniform sampler2D textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2l]) { + ShaderStore.ShadersStore[name$2l] = shader$2k; +} +/** @internal */ +const passPixelShader = { name: name$2l, shader: shader$2k }; + +const pass_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + passPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2k = "passCubePixelShader"; +const shader$2j = `varying vec2 vUV;uniform samplerCube textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 uv=vUV*2.0-1.0; +#ifdef POSITIVEX +gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); +#endif +#ifdef NEGATIVEX +gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); +#endif +#ifdef POSITIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); +#endif +#ifdef NEGATIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); +#endif +#ifdef POSITIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); +#endif +#ifdef NEGATIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2k]) { + ShaderStore.ShadersStore[name$2k] = shader$2j; +} +/** @internal */ +const passCubePixelShader = { name: name$2k, shader: shader$2j }; + +const passCube_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + passCubePixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2j = "passPixelShader"; +const shader$2i = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2j]) { + ShaderStore.ShadersStoreWGSL[name$2j] = shader$2i; +} +/** @internal */ +const passPixelShaderWGSL = { name: name$2j, shader: shader$2i }; + +const pass_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + passPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2i = "passCubePixelShader"; +const shader$2h = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f=input.vUV*2.0-1.0; +#ifdef POSITIVEX +fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x)); +#endif +#ifdef NEGATIVEX +fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x)); +#endif +#ifdef POSITIVEY +fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x)); +#endif +#ifdef NEGATIVEY +fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x)); +#endif +#ifdef POSITIVEZ +fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,1.001)); +#endif +#ifdef NEGATIVEZ +fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,-1.001)); +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2i]) { + ShaderStore.ShadersStoreWGSL[name$2i] = shader$2h; +} +/** @internal */ +const passCubePixelShaderWGSL = { name: name$2i, shader: shader$2h }; + +const passCube_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + passCubePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2h = "vrDistortionCorrectionPixelShader"; +const shader$2g = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; +float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) +gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2h]) { + ShaderStore.ShadersStore[name$2h] = shader$2g; +} +/** @internal */ +const vrDistortionCorrectionPixelShader = { name: name$2h, shader: shader$2g }; + +const vrDistortionCorrection_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + vrDistortionCorrectionPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2g = "vrDistortionCorrectionPixelShader"; +const shader$2f = `#define DISABLE_UNIFORMITY_ANALYSIS +varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform LensCenter: vec2f;uniform Scale: vec2f;uniform ScaleIn: vec2f;uniform HmdWarpParam: vec4f;fn HmdWarp(in01: vec2f)->vec2f {var theta: vec2f=(in01-uniforms.LensCenter)*uniforms.ScaleIn; +var rSq: f32=theta.x*theta.x+theta.y*theta.y;var rvector: vec2f=theta*(uniforms.HmdWarpParam.x+uniforms.HmdWarpParam.y*rSq+uniforms.HmdWarpParam.z*rSq*rSq+uniforms.HmdWarpParam.w*rSq*rSq*rSq);return uniforms.LensCenter+uniforms.Scale*rvector;} +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var tc: vec2f=HmdWarp(input.vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) {fragmentOutputs.color=vec4f(0.0,0.0,0.0,0.0);} +else{fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,tc);}}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2g]) { + ShaderStore.ShadersStoreWGSL[name$2g] = shader$2f; +} +/** @internal */ +const vrDistortionCorrectionPixelShaderWGSL = { name: name$2g, shader: shader$2f }; + +const vrDistortionCorrection_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + vrDistortionCorrectionPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2f = "imageProcessingPixelShader"; +const shader$2e = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var result: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);result=vec4f(max(result.rgb,vec3f(0.)),result.a); +#ifdef IMAGEPROCESSING +#ifndef FROMLINEARSPACE +result=vec4f(toLinearSpaceVec3(result.rgb),result.a); +#endif +result=applyImageProcessing(result); +#else +#ifdef FROMLINEARSPACE +result=applyImageProcessing(result); +#endif +#endif +fragmentOutputs.color=result;}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2f]) { + ShaderStore.ShadersStoreWGSL[name$2f] = shader$2e; +} +/** @internal */ +const imageProcessingPixelShaderWGSL = { name: name$2f, shader: shader$2e }; + +const imageProcessing_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + imageProcessingPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2e = "imageProcessingPixelShader"; +const shader$2d = `varying vec2 vUV;uniform sampler2D textureSampler; +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 result=texture2D(textureSampler,vUV);result.rgb=max(result.rgb,vec3(0.)); +#ifdef IMAGEPROCESSING +#ifndef FROMLINEARSPACE +result.rgb=toLinearSpace(result.rgb); +#endif +result=applyImageProcessing(result); +#else +#ifdef FROMLINEARSPACE +result=applyImageProcessing(result); +#endif +#endif +gl_FragColor=result;}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2e]) { + ShaderStore.ShadersStore[name$2e] = shader$2d; +} +/** @internal */ +const imageProcessingPixelShader = { name: name$2e, shader: shader$2d }; + +const imageProcessing_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + imageProcessingPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2d = "sharpenPixelShader"; +const shader$2c = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform sharpnessAmounts: vec2f; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var edgeDetection: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,-1)) + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(-1,0)) + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(1,0)) + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,1)) - +color*4.0;fragmentOutputs.color=max(vec4f(color.rgb*uniforms.sharpnessAmounts.y,color.a)-(uniforms.sharpnessAmounts.x* vec4f(edgeDetection.rgb,0)),vec4f(0.));}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2d]) { + ShaderStore.ShadersStoreWGSL[name$2d] = shader$2c; +} +/** @internal */ +const sharpenPixelShaderWGSL = { name: name$2d, shader: shader$2c }; + +const sharpen_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + sharpenPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2c = "grainPixelShader"; +const shader$2b = `#include +uniform sampler2D textureSampler; +uniform float intensity;uniform float animatedSeed;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2c]) { + ShaderStore.ShadersStore[name$2c] = shader$2b; +} +/** @internal */ +const grainPixelShader = { name: name$2c, shader: shader$2b }; + +const grain_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + grainPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2b = "grainPixelShader"; +const shader$2a = `#include +varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform intensity: f32;uniform animatedSeed: f32; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var seed: vec2f=input.vUV*uniforms.animatedSeed;var grain: f32=dither(seed,uniforms.intensity);var lum: f32=getLuminance(fragmentOutputs.color.rgb);var grainAmount: f32=(cos(-PI+(lum*PI*2.))+1.)/2.;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+grain*grainAmount,fragmentOutputs.color.a);fragmentOutputs.color=vec4f(max(fragmentOutputs.color.rgb,vec3f(0.0)),fragmentOutputs.color.a);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2b]) { + ShaderStore.ShadersStoreWGSL[name$2b] = shader$2a; +} +/** @internal */ +const grainPixelShaderWGSL = { name: name$2b, shader: shader$2a }; + +const grain_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + grainPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$2a = "chromaticAberrationPixelShader"; +const shader$29 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform chromatic_aberration: f32;uniform radialIntensity: f32;uniform direction: vec2f;uniform centerPosition: vec2f;uniform screen_width: f32;uniform screen_height: f32; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var centered_screen_pos: vec2f= vec2f(input.vUV.x-uniforms.centerPosition.x,input.vUV.y-uniforms.centerPosition.y);var directionOfEffect: vec2f=uniforms.direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);} +var radius2: f32=centered_screen_pos.x*centered_screen_pos.x ++ centered_screen_pos.y*centered_screen_pos.y;var radius: f32=sqrt(radius2);var ref_indices: vec3f= vec3f(-0.3,0.0,0.3);var ref_shiftX: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.x/uniforms.screen_width;var ref_shiftY: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.y/uniforms.screen_height;var ref_coords_r: vec2f=vec2f(input.vUV.x+ref_indices.r*ref_shiftX,input.vUV.y+ref_indices.r*ref_shiftY*0.5);var ref_coords_g: vec2f=vec2f(input.vUV.x+ref_indices.g*ref_shiftX,input.vUV.y+ref_indices.g*ref_shiftY*0.5);var ref_coords_b: vec2f=vec2f(input.vUV.x+ref_indices.b*ref_shiftX,input.vUV.y+ref_indices.b*ref_shiftY*0.5);var r=textureSample(textureSampler,textureSamplerSampler,ref_coords_r);var g=textureSample(textureSampler,textureSamplerSampler,ref_coords_g);var b=textureSample(textureSampler,textureSamplerSampler,ref_coords_b);var a=clamp(r.a+g.a+b.a,0.,1.);fragmentOutputs.color=vec4f(r.r,g.g,b.b,a);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$2a]) { + ShaderStore.ShadersStoreWGSL[name$2a] = shader$29; +} +/** @internal */ +const chromaticAberrationPixelShaderWGSL = { name: name$2a, shader: shader$29 }; + +const chromaticAberration_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + chromaticAberrationPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$29 = "depthOfFieldMergePixelShader"; +const shader$28 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; +#if BLUR_LEVEL>0 +uniform sampler2D blurStep1; +#endif +#if BLUR_LEVEL>1 +uniform sampler2D blurStep2; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; +#if BLUR_LEVEL==0 +vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); +#endif +#if BLUR_LEVEL==1 +if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} +#endif +#if BLUR_LEVEL==2 +if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$29]) { + ShaderStore.ShadersStore[name$29] = shader$28; +} +/** @internal */ +const depthOfFieldMergePixelShader = { name: name$29, shader: shader$28 }; + +const depthOfFieldMerge_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + depthOfFieldMergePixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$28 = "depthOfFieldMergePixelShader"; +const shader$27 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;var blurStep0Sampler: sampler;var blurStep0: texture_2d; +#if BLUR_LEVEL>0 +var blurStep1Sampler: sampler;var blurStep1: texture_2d; +#endif +#if BLUR_LEVEL>1 +var blurStep2Sampler: sampler;var blurStep2: texture_2d; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var coc: f32=textureSampleLevel(circleOfConfusionSampler,circleOfConfusionSamplerSampler,input.vUV,0.0).r; +#if BLUR_LEVEL==0 +var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred0,coc); +#endif +#if BLUR_LEVEL==1 +if(coc<0.5){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred1,coc/0.5);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.5)/0.5);} +#endif +#if BLUR_LEVEL==2 +if(coc<0.33){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred2,coc/0.33);}else if(coc<0.66){var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.66)/0.34);} +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$28]) { + ShaderStore.ShadersStoreWGSL[name$28] = shader$27; +} +/** @internal */ +const depthOfFieldMergePixelShaderWGSL = { name: name$28, shader: shader$27 }; + +const depthOfFieldMerge_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + depthOfFieldMergePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$27 = "circleOfConfusionPixelShader"; +const shader$26 = `uniform sampler2D depthSampler;varying vec2 vUV; +#ifndef COC_DEPTH_NOT_NORMALIZED +uniform vec2 cameraMinMaxZ; +#endif +uniform float focusDistance;uniform float cocPrecalculation; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float depth=texture2D(depthSampler,vUV).r; +#define CUSTOM_COC_DEPTH +#ifdef COC_DEPTH_NOT_NORMALIZED +float pixelDistance=depth*1000.0; +#else +float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; +#endif +#define CUSTOM_COC_PIXELDISTANCE +float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$27]) { + ShaderStore.ShadersStore[name$27] = shader$26; +} +/** @internal */ +const circleOfConfusionPixelShader = { name: name$27, shader: shader$26 }; + +const circleOfConfusion_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + circleOfConfusionPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$26 = "circleOfConfusionPixelShader"; +const shader$25 = `varying vUV: vec2f;var depthSamplerSampler: sampler;var depthSampler: texture_2d; +#ifndef COC_DEPTH_NOT_NORMALIZED +uniform cameraMinMaxZ: vec2f; +#endif +uniform focusDistance: f32;uniform cocPrecalculation: f32; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r; +#define CUSTOM_COC_DEPTH +#ifdef COC_DEPTH_NOT_NORMALIZED +let pixelDistance=depth*1000.0; +#else +let pixelDistance: f32=(uniforms.cameraMinMaxZ.x+uniforms.cameraMinMaxZ.y*depth)*1000.0; +#endif +#define CUSTOM_COC_PIXELDISTANCE +var coc: f32=abs(uniforms.cocPrecalculation*((uniforms.focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);fragmentOutputs.color= vec4f(coc,coc,coc,1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$26]) { + ShaderStore.ShadersStoreWGSL[name$26] = shader$25; +} +/** @internal */ +const circleOfConfusionPixelShaderWGSL = { name: name$26, shader: shader$25 }; + +const circleOfConfusion_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + circleOfConfusionPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$25 = "bloomMergePixelShader"; +const shader$24 = `uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$25]) { + ShaderStore.ShadersStore[name$25] = shader$24; +} +/** @internal */ +const bloomMergePixelShader = { name: name$25, shader: shader$24 }; + +const bloomMerge_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bloomMergePixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$24 = "bloomMergePixelShader"; +const shader$23 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var bloomBlurSampler: sampler;var bloomBlur: texture_2d;uniform bloomWeight: f32; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var blurred: vec3f=textureSample(bloomBlur,bloomBlurSampler,input.vUV).rgb;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+(blurred.rgb*uniforms.bloomWeight),fragmentOutputs.color.a);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$24]) { + ShaderStore.ShadersStoreWGSL[name$24] = shader$23; +} +/** @internal */ +const bloomMergePixelShaderWGSL = { name: name$24, shader: shader$23 }; + +const bloomMerge_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + bloomMergePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$23 = "extractHighlightsPixelShader"; +const shader$22 = `#include +varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$23]) { + ShaderStore.ShadersStore[name$23] = shader$22; +} +/** @internal */ +const extractHighlightsPixelShader = { name: name$23, shader: shader$22 }; + +const extractHighlights_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + extractHighlightsPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$22 = "extractHighlightsPixelShader"; +const shader$21 = `#include +varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform threshold: f32;uniform exposure: f32; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var luma: f32=dot(LuminanceEncodeApprox,fragmentOutputs.color.rgb*uniforms.exposure);fragmentOutputs.color=vec4f(step(uniforms.threshold,luma)*fragmentOutputs.color.rgb,fragmentOutputs.color.a);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$22]) { + ShaderStore.ShadersStoreWGSL[name$22] = shader$21; +} +/** @internal */ +const extractHighlightsPixelShaderWGSL = { name: name$22, shader: shader$21 }; + +const extractHighlights_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + extractHighlightsPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$21 = "fxaaPixelShader"; +const shader$20 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); +#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) +void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); +#ifndef MALI +if(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) +{lumaN=lumaW;} +if (!horzSpan) +{lumaS=lumaE;} +if (horzSpan) +{lengthSign=texelSize.y;} +float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) +{lengthSign=-lengthSign;} +float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) +{posB.x+=lengthSign*0.5;} +if (horzSpan) +{posB.y+=lengthSign*0.5;} +vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) +{lumaNN=lumaSS;} +float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) +{posN.x-=offNP.x*3.0;} +if (!doneN) +{posN.y-=offNP.y*3.0;} +bool doneNP=(!doneN) || (!doneP);if (!doneP) +{posP.x+=offNP.x*3.0;} +if (!doneP) +{posP.y+=offNP.y*3.0;} +if (doneNP) +{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} +float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) +{dstN=posM.y-posN.y;} +if (!horzSpan) +{dstP=posP.y-posM.y;} +bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN;uniform texelSize: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const fxaaQualitySubpix: f32=1.0;const fxaaQualityEdgeThreshold: f32=0.166;const fxaaQualityEdgeThresholdMin: f32=0.0833;const kLumaCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722);fn FxaaLuma(rgba: vec4f)->f32 {return dot(rgba.rgb,kLumaCoefficients);} +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var posM: vec2f;posM.x=input.vUV.x;posM.y=input.vUV.y;var rgbyM: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var lumaM: f32=FxaaLuma(rgbyM);var lumaS: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordS,0.0));var lumaE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordE,0.0));var lumaN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordN,0.0));var lumaW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordW,0.0));var maxSM: f32=max(lumaS,lumaM);var minSM: f32=min(lumaS,lumaM);var maxESM: f32=max(lumaE,maxSM);var minESM: f32=min(lumaE,minSM);var maxWN: f32=max(lumaN,lumaW);var minWN: f32=min(lumaN,lumaW);var rangeMax: f32=max(maxWN,maxESM);var rangeMin: f32=min(minWN,minESM);var rangeMaxScaled: f32=rangeMax*fxaaQualityEdgeThreshold;var range: f32=rangeMax-rangeMin;var rangeMaxClamped: f32=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); +#ifndef MALI +if(range=edgeVert;var subpixA: f32=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) +{lumaN=lumaW;} +if (!horzSpan) +{lumaS=lumaE;} +if (horzSpan) +{lengthSign=uniforms.texelSize.y;} +var subpixB: f32=(subpixA*(1.0/12.0))-lumaM;var gradientN: f32=lumaN-lumaM;var gradientS: f32=lumaS-lumaM;var lumaNN: f32=lumaN+lumaM;var lumaSS: f32=lumaS+lumaM;var pairN: bool=abs(gradientN)>=abs(gradientS);var gradient: f32=max(abs(gradientN),abs(gradientS));if (pairN) +{lengthSign=-lengthSign;} +var subpixC: f32=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);var posB: vec2f;posB.x=posM.x;posB.y=posM.y;var offNP: vec2f;offNP.x=select(uniforms.texelSize.x,0.0,(!horzSpan));offNP.y=select(uniforms.texelSize.y,0.0,(horzSpan));if (!horzSpan) +{posB.x+=lengthSign*0.5;} +if (horzSpan) +{posB.y+=lengthSign*0.5;} +var posN: vec2f;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;var posP: vec2f;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;var subpixD: f32=((-2.0)*subpixC)+3.0;var lumaEndN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN,0.0));var subpixE: f32=subpixC*subpixC;var lumaEndP: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP,0.0));if (!pairN) +{lumaNN=lumaSS;} +var gradientScaled: f32=gradient*1.0/4.0;var lumaMM: f32=lumaM-lumaNN*0.5;var subpixF: f32=subpixD*subpixE;var lumaMLTZero: bool=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;var doneN: bool=abs(lumaEndN)>=gradientScaled;var doneP: bool=abs(lumaEndP)>=gradientScaled;if (!doneN) +{posN.x-=offNP.x*3.0;} +if (!doneN) +{posN.y-=offNP.y*3.0;} +var doneNP: bool=(!doneN) || (!doneP);if (!doneP) +{posP.x+=offNP.x*3.0;} +if (!doneP) +{posP.y+=offNP.y*3.0;} +if (doneNP) +{if (!doneN) {lumaEndN=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN.xy,0.0));} +if (!doneP) {lumaEndP=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP.xy,0.0));} +if (!doneN) {lumaEndN=lumaEndN-lumaNN*0.5;} +if (!doneP) {lumaEndP=lumaEndP-lumaNN*0.5;} +doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*12.0;} +if (!doneN) {posN.y-=offNP.y*12.0;} +doneNP=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*12.0;} +if (!doneP) {posP.y+=offNP.y*12.0;}} +var dstN: f32=posM.x-posN.x;var dstP: f32=posP.x-posM.x;if (!horzSpan) +{dstN=posM.y-posN.y;} +if (!horzSpan) +{dstP=posP.y-posM.y;} +var goodSpanN: bool=(lumaEndN<0.0) != lumaMLTZero;var spanLength: f32=(dstP+dstN);var goodSpanP: bool=(lumaEndP<0.0) != lumaMLTZero;var spanLengthRcp: f32=1.0/spanLength;var directionN: bool=dstNFragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.vUV=(input.position*madd+madd);vertexOutputs.sampleCoordS=vertexOutputs.vUV+ vec2f( 0.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordE=vertexOutputs.vUV+ vec2f( 1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordN=vertexOutputs.vUV+ vec2f( 0.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordW=vertexOutputs.vUV+ vec2f(-1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordNW=vertexOutputs.vUV+ vec2f(-1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSE=vertexOutputs.vUV+ vec2f( 1.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordNE=vertexOutputs.vUV+ vec2f( 1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSW=vertexOutputs.vUV+ vec2f(-1.0,1.0)*uniforms.texelSize;vertexOutputs.position=vec4f(input.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1_]) { + ShaderStore.ShadersStoreWGSL[name$1_] = shader$1Z; +} +/** @internal */ +const fxaaVertexShaderWGSL = { name: name$1_, shader: shader$1Z }; + +const fxaa_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + fxaaVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1Z = "blackAndWhitePixelShader"; +const shader$1Y = `varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); +vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1Z]) { + ShaderStore.ShadersStore[name$1Z] = shader$1Y; +} +/** @internal */ +const blackAndWhitePixelShader = { name: name$1Z, shader: shader$1Y }; + +const blackAndWhite_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + blackAndWhitePixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1Y = "blackAndWhitePixelShader"; +const shader$1X = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform degree: f32; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var luminance: f32=dot(color, vec3f(0.3,0.59,0.11)); +var blackAndWhite: vec3f= vec3f(luminance,luminance,luminance);fragmentOutputs.color= vec4f(color-((color-blackAndWhite)*uniforms.degree),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1Y]) { + ShaderStore.ShadersStoreWGSL[name$1Y] = shader$1X; +} +/** @internal */ +const blackAndWhitePixelShaderWGSL = { name: name$1Y, shader: shader$1X }; + +const blackAndWhite_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + blackAndWhitePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1X = "anaglyphPixelShader"; +const shader$1W = `varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1X]) { + ShaderStore.ShadersStore[name$1X] = shader$1W; +} +/** @internal */ +const anaglyphPixelShader = { name: name$1X, shader: shader$1W }; + +const anaglyph_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + anaglyphPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1W = "anaglyphPixelShader"; +const shader$1V = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var leftSamplerSampler: sampler;var leftSampler: texture_2d; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var leftFrag: vec4f=textureSample(leftSampler,leftSamplerSampler,input.vUV);leftFrag= vec4f(1.0,leftFrag.g,leftFrag.b,1.0);var rightFrag: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);rightFrag= vec4f(rightFrag.r,1.0,1.0,1.0);fragmentOutputs.color= vec4f(rightFrag.rgb*leftFrag.rgb,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1W]) { + ShaderStore.ShadersStoreWGSL[name$1W] = shader$1V; +} +/** @internal */ +const anaglyphPixelShaderWGSL = { name: name$1W, shader: shader$1V }; + +const anaglyph_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + anaglyphPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1V = "convolutionPixelShader"; +const shader$1U = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = +texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + +texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + +texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + +texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + +texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + +texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + +texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + +texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + +texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = +kernel[0] + +kernel[1] + +kernel[2] + +kernel[3] + +kernel[4] + +kernel[5] + +kernel[6] + +kernel[7] + +kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} +gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1V]) { + ShaderStore.ShadersStore[name$1V] = shader$1U; +} +/** @internal */ +const convolutionPixelShader = { name: name$1V, shader: shader$1U }; + +const convolution_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + convolutionPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1U = "convolutionPixelShader"; +const shader$1T = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform kernel: array; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var colorSum: vec4f = +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,-1))*uniforms.kernel[0] + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,-1))*uniforms.kernel[1] + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,-1))*uniforms.kernel[2] + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,0))*uniforms.kernel[3] + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,0))*uniforms.kernel[4] + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,0))*uniforms.kernel[5] + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,1))*uniforms.kernel[6] + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,1))*uniforms.kernel[7] + +textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,1))*uniforms.kernel[8];var kernelWeight: f32 = +uniforms.kernel[0] + +uniforms.kernel[1] + +uniforms.kernel[2] + +uniforms.kernel[3] + +uniforms.kernel[4] + +uniforms.kernel[5] + +uniforms.kernel[6] + +uniforms.kernel[7] + +uniforms.kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} +fragmentOutputs.color= vec4f((colorSum/kernelWeight).rgb,1);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1U]) { + ShaderStore.ShadersStoreWGSL[name$1U] = shader$1T; +} +/** @internal */ +const convolutionPixelShaderWGSL = { name: name$1U, shader: shader$1T }; + +const convolution_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + convolutionPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1T = "colorCorrectionPixelShader"; +const shader$1S = `uniform sampler2D textureSampler; +uniform sampler2D colorTable; +varying vec2 vUV;const float SLICE_COUNT=16.0; +#define inline +vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; +float slicePixelSize=sliceSize/width; +float sliceInnerSize=slicePixelSize*(width-1.0); +float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1T]) { + ShaderStore.ShadersStore[name$1T] = shader$1S; +} +/** @internal */ +const colorCorrectionPixelShader = { name: name$1T, shader: shader$1S }; + +const colorCorrection_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + colorCorrectionPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1S = "colorCorrectionPixelShader"; +const shader$1R = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;var colorTableSampler: sampler;var colorTable: texture_2d;const SLICE_COUNT: f32=16.0; +fn sampleAs3DTexture(uv: vec3f,width: f32)->vec4f {var sliceSize: f32=1.0/width; +var slicePixelSize: f32=sliceSize/width; +var sliceInnerSize: f32=slicePixelSize*(width-1.0); +var zSlice0: f32=min(floor(uv.z*width),width-1.0);var zSlice1: f32=min(zSlice0+1.0,width-1.0);var xOffset: f32=slicePixelSize*0.5+uv.x*sliceInnerSize;var s0: f32=xOffset+(zSlice0*sliceSize);var s1: f32=xOffset+(zSlice1*sliceSize);var slice0Color: vec4f=textureSample(colorTable,colorTableSampler,vec2f(s0,uv.y));var slice1Color: vec4f=textureSample(colorTable,colorTableSampler,vec2f(s1,uv.y));var zOffset: f32=((uv.z*width)%(1.0));return mix(slice0Color,slice1Color,zOffset);} +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var screen_color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);fragmentOutputs.color=sampleAs3DTexture(screen_color.rgb,SLICE_COUNT);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1S]) { + ShaderStore.ShadersStoreWGSL[name$1S] = shader$1R; +} +/** @internal */ +const colorCorrectionPixelShaderWGSL = { name: name$1S, shader: shader$1R }; + +const colorCorrection_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + colorCorrectionPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1R = "motionBlurPixelShader"; +const shader$1Q = `varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; +#ifdef OBJECT_BASED +uniform sampler2D velocitySampler; +#else +uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#ifdef GEOMETRY_SUPPORTED +#ifdef OBJECT_BASED +vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 signs=sign(velocityColor.rg);vec2 velocity=pow(abs(velocityColor.rg),vec2(3.0))*signs*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount) +break;vec2 offset=vUV+velocity*(hlim+float(i)); +#if defined(WEBGPU) +result+=texture2DLodEXT(textureSampler,offset,0.0); +#else +result+=texture2D(textureSampler,offset); +#endif +} +gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; +#else +vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; +vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples) +break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); +#if defined(WEBGPU) +result+=texture2DLodEXT(textureSampler,offset1,0.0); +#else +result+=texture2D(textureSampler,offset1); +#endif +} +gl_FragColor=result/float(nSamples); +#endif +#else +gl_FragColor=texture2D(textureSampler,vUV); +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1R]) { + ShaderStore.ShadersStore[name$1R] = shader$1Q; +} +/** @internal */ +const motionBlurPixelShader = { name: name$1R, shader: shader$1Q }; + +const motionBlur_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + motionBlurPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1Q = "motionBlurPixelShader"; +const shader$1P = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform motionStrength: f32;uniform motionScale: f32;uniform screenSize: vec2f; +#ifdef OBJECT_BASED +var velocitySamplerSampler: sampler;var velocitySampler: texture_2d; +#else +var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform inverseViewProjection: mat4x4f;uniform prevViewProjection: mat4x4f;uniform projection: mat4x4f; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#ifdef GEOMETRY_SUPPORTED +#ifdef OBJECT_BASED +var texelSize: vec2f=1.0/uniforms.screenSize;var velocityColor: vec4f=textureSample(velocitySampler,velocitySamplerSampler,input.vUV);velocityColor=vec4f(velocityColor.rg*2.0- vec2f(1.0),velocityColor.b,velocityColor.a);let signs=sign(velocityColor.rg);var velocity=pow(abs(velocityColor.rg),vec2f(3.0))*signs*velocityColor.a;velocity*=uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var samplesCount: i32= i32(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;var hlim: f32= f32(-samplesCount)*0.5+0.5;var result: vec4f=textureSample(textureSampler,textureSamplerSampler, input.vUV);for (var i: i32=1; i< i32(SAMPLES); i++) +{if (i>=samplesCount) {break;} +var offset: vec2f=input.vUV+velocity*(hlim+ f32(i)); +#if defined(WEBGPU) +result+=textureSampleLevel(textureSampler,textureSamplerSampler, offset,0.0); +#else +result+=textureSample(textureSampler,textureSamplerSampler, offset); +#endif +} +fragmentOutputs.color=vec4f(result.rgb/ f32(samplesCount),1.0); +#else +var texelSize: vec2f=1.0/uniforms.screenSize;var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r;depth=uniforms.projection[2].z+uniforms.projection[3].z/depth; +var cpos: vec4f= vec4f(input.vUV*2.0-1.0,depth,1.0);cpos=uniforms.inverseViewProjection*cpos;cpos/=cpos.w;var ppos: vec4f=uniforms.prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;var velocity: vec2f=(ppos.xy-input.vUV)*uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var nSamples: i32= i32(clamp(speed,1.0,SAMPLES));var result: vec4f=textureSample(textureSampler,textureSamplerSampler, input.vUV);for (var i: i32=1; i< i32(SAMPLES); i++) {if (i>=nSamples) {break;} +var offset1: vec2f=input.vUV+velocity*( f32(i)/ f32(nSamples-1)-0.5); +#if defined(WEBGPU) +result+=textureSampleLevel(textureSampler,textureSamplerSampler, offset1,0.0); +#else +result+=textureSample(textureSampler,textureSamplerSampler, offset1); +#endif +} +fragmentOutputs.color=result/ f32(nSamples); +#endif +#else +fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler, input.vUV); +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1Q]) { + ShaderStore.ShadersStoreWGSL[name$1Q] = shader$1P; +} +/** @internal */ +const motionBlurPixelShaderWGSL = { name: name$1Q, shader: shader$1P }; + +const motionBlur_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + motionBlurPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1P = "filterPixelShader"; +const shader$1O = `varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1P]) { + ShaderStore.ShadersStore[name$1P] = shader$1O; +} +/** @internal */ +const filterPixelShader = { name: name$1P, shader: shader$1O }; + +const filter_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + filterPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1O = "filterPixelShader"; +const shader$1N = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform kernelMatrix: mat4x4f; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var baseColor: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var updatedColor: vec3f=(uniforms.kernelMatrix* vec4f(baseColor,1.0)).rgb;fragmentOutputs.color= vec4f(updatedColor,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1O]) { + ShaderStore.ShadersStoreWGSL[name$1O] = shader$1N; +} +/** @internal */ +const filterPixelShaderWGSL = { name: name$1O, shader: shader$1N }; + +const filter_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + filterPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1N = "highlightsPixelShader"; +const shader$1M = `varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1N]) { + ShaderStore.ShadersStore[name$1N] = shader$1M; +} + +// Do not edit. +const name$1M = "highlightsPixelShader"; +const shader$1L = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;const RGBLuminanceCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722); +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var tex: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var c: vec3f=tex.rgb;var luma: f32=dot(c.rgb,RGBLuminanceCoefficients);fragmentOutputs.color= vec4f(pow(c, vec3f(25.0-luma*15.0)),tex.a); }`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1M]) { + ShaderStore.ShadersStoreWGSL[name$1M] = shader$1L; +} + +// Do not edit. +const name$1L = "displayPassPixelShader"; +const shader$1K = `varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(passSampler,vUV);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1L]) { + ShaderStore.ShadersStore[name$1L] = shader$1K; +} +/** @internal */ +const displayPassPixelShader = { name: name$1L, shader: shader$1K }; + +const displayPass_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + displayPassPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1K = "displayPassPixelShader"; +const shader$1J = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var passSamplerSampler: sampler;var passSampler: texture_2d; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(passSampler,passSamplerSampler,input.vUV);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1K]) { + ShaderStore.ShadersStoreWGSL[name$1K] = shader$1J; +} +/** @internal */ +const displayPassPixelShaderWGSL = { name: name$1K, shader: shader$1J }; + +const displayPass_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + displayPassPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1J = "tonemapPixelShader"; +const shader$1I = `varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; +#if defined(HABLE_TONEMAPPING) +const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2; +#endif +float Luminance(vec3 c) +{return dot(c,vec3(0.22,0.707,0.071));} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 colour=texture2D(textureSampler,vUV).rgb; +#if defined(REINHARD_TONEMAPPING) +float lum=Luminance(colour.rgb); +float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); +colour*=scale/lum; +#elif defined(HABLE_TONEMAPPING) +colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; +#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) +colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; +#elif defined(PHOTOGRAPHIC_TONEMAPPING) +colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); +#endif +gl_FragColor=vec4(colour.rgb,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1J]) { + ShaderStore.ShadersStore[name$1J] = shader$1I; +} + +// Do not edit. +const name$1I = "tonemapPixelShader"; +const shader$1H = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform _ExposureAdjustment: f32; +#if defined(HABLE_TONEMAPPING) +const A: f32=0.15;const B: f32=0.50;const C: f32=0.10;const D: f32=0.20;const E: f32=0.02;const F: f32=0.30;const W: f32=11.2; +#endif +fn Luminance(c: vec3f)->f32 +{return dot(c, vec3f(0.22,0.707,0.071));} +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var colour: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb; +#if defined(REINHARD_TONEMAPPING) +var lum: f32=Luminance(colour.rgb); +var lumTm: f32=lum*uniforms._ExposureAdjustment;var scale: f32=lumTm/(1.0+lumTm); +colour*=scale/lum; +#elif defined(HABLE_TONEMAPPING) +colour*=uniforms._ExposureAdjustment;const ExposureBias: f32=2.0;var x: vec3f=ExposureBias*colour;var curr: vec3f=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x= vec3f(W,W,W);var whiteScale: vec3f=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; +#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) +colour*=uniforms._ExposureAdjustment;var X: vec3f=max( vec3f(0.0,0.0,0.0),colour-0.004);var retColor: vec3f=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; +#elif defined(PHOTOGRAPHIC_TONEMAPPING) +colour= vec3f(1.0,1.0,1.0)-exp2(-uniforms._ExposureAdjustment*colour); +#endif +fragmentOutputs.color= vec4f(colour.rgb,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1I]) { + ShaderStore.ShadersStoreWGSL[name$1I] = shader$1H; +} + +Object.defineProperty(Scene.prototype, "forceShowBoundingBoxes", { + get: function () { + return this._forceShowBoundingBoxes || false; + }, + set: function (value) { + this._forceShowBoundingBoxes = value; + // Lazyly creates a BB renderer if needed. + if (value) { + this.getBoundingBoxRenderer(); + } + }, + enumerable: true, + configurable: true, +}); +Scene.prototype.getBoundingBoxRenderer = function () { + if (!this._boundingBoxRenderer) { + this._boundingBoxRenderer = new BoundingBoxRenderer(this); + } + return this._boundingBoxRenderer; +}; +Object.defineProperty(AbstractMesh.prototype, "showBoundingBox", { + get: function () { + return this._showBoundingBox || false; + }, + set: function (value) { + this._showBoundingBox = value; + // Lazyly creates a BB renderer if needed. + if (value) { + this.getScene().getBoundingBoxRenderer(); + } + }, + enumerable: true, + configurable: true, +}); +const tempMatrix = Matrix.Identity(); +const tempVec1 = new Vector3(), tempVec2 = new Vector3(); +// `Matrix.asArray` returns its internal array, so it can be directly updated +const tempMatrixArray = tempMatrix.asArray(); +// BoundingBox copies from it, so it's safe to reuse vectors here +const dummyBoundingBox = new BoundingBox(tempVec1, tempVec1); +/** + * Component responsible of rendering the bounding box of the meshes in a scene. + * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties + */ +class BoundingBoxRenderer { + /** + * Gets the shader language used in this renderer. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Instantiates a new bounding box renderer in a scene. + * @param scene the scene the renderer renders in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_BOUNDINGBOXRENDERER; + /** + * Color of the bounding box lines placed in front of an object + */ + this.frontColor = new Color3(1, 1, 1); + /** + * Color of the bounding box lines placed behind an object + */ + this.backColor = new Color3(0.1, 0.1, 0.1); + /** + * Defines if the renderer should show the back lines or not + */ + this.showBackLines = true; + /** + * Observable raised before rendering a bounding box + * When {@link BoundingBoxRenderer.useInstances} enabled, + * this would only be triggered once for one rendering, instead of once every bounding box. + * Events would be triggered with a dummy box to keep backwards compatibility, + * the passed bounding box has no meaning and should be ignored. + */ + this.onBeforeBoxRenderingObservable = new Observable(); + /** + * Observable raised after rendering a bounding box + * When {@link BoundingBoxRenderer.useInstances} enabled, + * this would only be triggered once for one rendering, instead of once every bounding box. + * Events would be triggered with a dummy box to keep backwards compatibility, + * the passed bounding box has no meaning and should be ignored. + */ + this.onAfterBoxRenderingObservable = new Observable(); + /** + * Observable raised after resources are created + */ + this.onResourcesReadyObservable = new Observable(); + /** + * When false, no bounding boxes will be rendered + */ + this.enabled = true; + /** Shader language used by the renderer */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + /** + * @internal + */ + this.renderList = new SmartArray(32); + this._vertexBuffers = {}; + this._fillIndexBuffer = null; + this._fillIndexData = null; + /** + * Internal buffer for instanced rendering + */ + this._matrixBuffer = null; + this._matrices = null; + /** + * Internal state of whether instanced rendering enabled + */ + this._useInstances = false; + /** @internal */ + this._drawWrapperFront = null; + /** @internal */ + this._drawWrapperBack = null; + this.scene = scene; + const engine = this.scene.getEngine(); + if (engine.isWebGPU) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + } + scene._addComponent(this); + this._uniformBufferFront = new UniformBuffer(this.scene.getEngine(), undefined, undefined, "BoundingBoxRendererFront", true); + this._buildUniformLayout(this._uniformBufferFront); + this._uniformBufferBack = new UniformBuffer(this.scene.getEngine(), undefined, undefined, "BoundingBoxRendererBack", true); + this._buildUniformLayout(this._uniformBufferBack); + } + _buildUniformLayout(ubo) { + ubo.addUniform("color", 4); + ubo.addUniform("world", 16); + ubo.addUniform("viewProjection", 16); + ubo.addUniform("viewProjectionR", 16); + ubo.create(); + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._beforeEvaluateActiveMeshStage.registerStep(SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset); + this.scene._preActiveMeshStage.registerStep(SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER, this, this._preActiveMesh); + this.scene._evaluateSubMeshStage.registerStep(SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh); + this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render); + } + _evaluateSubMesh(mesh, subMesh) { + if (mesh.showSubMeshesBoundingBox) { + const boundingInfo = subMesh.getBoundingInfo(); + if (boundingInfo !== null && boundingInfo !== undefined) { + boundingInfo.boundingBox._tag = mesh.renderingGroupId; + this.renderList.push(boundingInfo.boundingBox); + } + } + } + _preActiveMesh(mesh) { + if (mesh.showBoundingBox || this.scene.forceShowBoundingBoxes) { + const boundingInfo = mesh.getBoundingInfo(); + boundingInfo.boundingBox._tag = mesh.renderingGroupId; + this.renderList.push(boundingInfo.boundingBox); + } + } + _prepareResources() { + if (this._colorShader) { + return; + } + this._colorShader = new ShaderMaterial("colorShader", this.scene, "boundingBoxRenderer", { + attributes: [VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"], + uniforms: ["world", "viewProjection", "viewProjectionR", "color"], + uniformBuffers: ["BoundingBoxRenderer"], + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => boundingBoxRenderer_vertex), Promise.resolve().then(() => boundingBoxRenderer_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => boundingBoxRenderer_vertex$1), Promise.resolve().then(() => boundingBoxRenderer_fragment$1)]); + } + }, + }, false); + this._colorShader.setDefine("INSTANCES", this._useInstances); + this._colorShader.doNotSerialize = true; + this._colorShader.reservedDataStore = { + hidden: true, + }; + this._colorShaderForOcclusionQuery = new ShaderMaterial("colorShaderOccQuery", this.scene, "boundingBoxRenderer", { + attributes: [VertexBuffer.PositionKind], + uniforms: ["world", "viewProjection", "viewProjectionR", "color"], + uniformBuffers: ["BoundingBoxRenderer"], + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => boundingBoxRenderer_vertex), Promise.resolve().then(() => boundingBoxRenderer_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => boundingBoxRenderer_vertex$1), Promise.resolve().then(() => boundingBoxRenderer_fragment$1)]); + } + }, + }, true); + this._colorShaderForOcclusionQuery.doNotSerialize = true; + this._colorShaderForOcclusionQuery.reservedDataStore = { + hidden: true, + }; + const engine = this.scene.getEngine(); + const boxdata = CreateBoxVertexData({ size: 1.0 }); + this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, boxdata.positions, VertexBuffer.PositionKind, false); + this._createIndexBuffer(); + this._fillIndexData = boxdata.indices; + this.onResourcesReadyObservable.notifyObservers(this); + } + _createIndexBuffer() { + const engine = this.scene.getEngine(); + this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + const vb = this._vertexBuffers[VertexBuffer.PositionKind]; + if (vb) { + vb._rebuild(); + } + this._createIndexBuffer(); + if (this._matrixBuffer) { + this._matrixBuffer._rebuild(); + } + } + /** + * @internal + */ + reset() { + this.renderList.reset(); + } + /** + * Render the bounding boxes of a specific rendering group + * @param renderingGroupId defines the rendering group to render + */ + render(renderingGroupId) { + if (this.renderList.length === 0 || !this.enabled) { + return; + } + if (this._useInstances) { + this._renderInstanced(renderingGroupId); + return; + } + this._prepareResources(); + if (!this._colorShader.isReady()) { + return; + } + const engine = this.scene.getEngine(); + engine.setDepthWrite(false); + const transformMatrix = this.scene.getTransformMatrix(); + for (let boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) { + const boundingBox = this.renderList.data[boundingBoxIndex]; + if (boundingBox._tag !== renderingGroupId) { + continue; + } + this._createWrappersForBoundingBox(boundingBox); + this.onBeforeBoxRenderingObservable.notifyObservers(boundingBox); + const min = boundingBox.minimum; + const max = boundingBox.maximum; + const diff = max.subtract(min); + const median = min.add(diff.scale(0.5)); + const worldMatrix = Matrix.Scaling(diff.x, diff.y, diff.z) + .multiply(Matrix.Translation(median.x, median.y, median.z)) + .multiply(boundingBox.getWorldMatrix()); + const useReverseDepthBuffer = engine.useReverseDepthBuffer; + if (this.showBackLines) { + const drawWrapperBack = boundingBox._drawWrapperBack ?? this._colorShader._getDrawWrapper(); + this._colorShader._preBind(drawWrapperBack); + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect()); + // Back + if (useReverseDepthBuffer) { + engine.setDepthFunctionToLessOrEqual(); + } + else { + engine.setDepthFunctionToGreaterOrEqual(); + } + this._uniformBufferBack.bindToEffect(drawWrapperBack.effect, "BoundingBoxRenderer"); + this._uniformBufferBack.updateColor4("color", this.backColor, 1); + this._uniformBufferBack.updateMatrix("world", worldMatrix); + this._uniformBufferBack.updateMatrix("viewProjection", transformMatrix); + this._uniformBufferBack.update(); + // Draw order + engine.drawElementsType(Material.LineListDrawMode, 0, 24); + } + const drawWrapperFront = boundingBox._drawWrapperFront ?? this._colorShader._getDrawWrapper(); + this._colorShader._preBind(drawWrapperFront); + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect()); + // Front + if (useReverseDepthBuffer) { + engine.setDepthFunctionToGreater(); + } + else { + engine.setDepthFunctionToLess(); + } + this._uniformBufferFront.bindToEffect(drawWrapperFront.effect, "BoundingBoxRenderer"); + this._uniformBufferFront.updateColor4("color", this.frontColor, 1); + this._uniformBufferFront.updateMatrix("world", worldMatrix); + this._uniformBufferFront.updateMatrix("viewProjection", transformMatrix); + this._uniformBufferFront.update(); + // Draw order + engine.drawElementsType(Material.LineListDrawMode, 0, 24); + this.onAfterBoxRenderingObservable.notifyObservers(boundingBox); + } + this._colorShader.unbind(); + engine.setDepthFunctionToLessOrEqual(); + engine.setDepthWrite(true); + } + _createWrappersForBoundingBox(boundingBox) { + if (!boundingBox._drawWrapperFront) { + const engine = this.scene.getEngine(); + boundingBox._drawWrapperFront = new DrawWrapper(engine); + boundingBox._drawWrapperBack = new DrawWrapper(engine); + boundingBox._drawWrapperFront.setEffect(this._colorShader.getEffect()); + boundingBox._drawWrapperBack.setEffect(this._colorShader.getEffect()); + } + } + /** + * In case of occlusion queries, we can render the occlusion bounding box through this method + * @param mesh Define the mesh to render the occlusion bounding box for + */ + renderOcclusionBoundingBox(mesh) { + const engine = this.scene.getEngine(); + if (this._renderPassIdForOcclusionQuery === undefined) { + this._renderPassIdForOcclusionQuery = engine.createRenderPassId(`Render pass for occlusion query`); + } + const currentRenderPassId = engine.currentRenderPassId; + engine.currentRenderPassId = this._renderPassIdForOcclusionQuery; + this._prepareResources(); + const subMesh = mesh.subMeshes[0]; + if (!this._colorShaderForOcclusionQuery.isReady(mesh, undefined, subMesh) || !mesh.hasBoundingInfo) { + engine.currentRenderPassId = currentRenderPassId; + return; + } + if (!this._fillIndexBuffer) { + this._fillIndexBuffer = engine.createIndexBuffer(this._fillIndexData); + } + const useReverseDepthBuffer = engine.useReverseDepthBuffer; + engine.setDepthWrite(false); + engine.setColorWrite(false); + const boundingBox = mesh.getBoundingInfo().boundingBox; + const min = boundingBox.minimum; + const max = boundingBox.maximum; + const diff = max.subtract(min); + const median = min.add(diff.scale(0.5)); + const worldMatrix = Matrix.Scaling(diff.x, diff.y, diff.z) + .multiply(Matrix.Translation(median.x, median.y, median.z)) + .multiply(boundingBox.getWorldMatrix()); + const drawWrapper = subMesh._drawWrapper; + this._colorShaderForOcclusionQuery._preBind(drawWrapper); + engine.bindBuffers(this._vertexBuffers, this._fillIndexBuffer, drawWrapper.effect); + if (useReverseDepthBuffer) { + engine.setDepthFunctionToGreater(); + } + else { + engine.setDepthFunctionToLess(); + } + this.scene.resetCachedMaterial(); + this._uniformBufferFront.bindToEffect(drawWrapper.effect, "BoundingBoxRenderer"); + this._uniformBufferFront.updateMatrix("world", worldMatrix); + this._uniformBufferFront.updateMatrix("viewProjection", this.scene.getTransformMatrix()); + this._uniformBufferFront.update(); + engine.drawElementsType(Material.TriangleFillMode, 0, 36); + this._colorShaderForOcclusionQuery.unbind(); + engine.setDepthFunctionToLessOrEqual(); + engine.setDepthWrite(true); + engine.setColorWrite(true); + engine.currentRenderPassId = currentRenderPassId; + } + /** + * Sets whether to use instanced rendering. + * When not enabled, BoundingBoxRenderer renders in a loop, + * calling engine.drawElementsType for each bounding box in renderList, + * making every bounding box 1 or 2 draw call. + * When enabled, it collects bounding boxes to render, + * and render all boxes in 1 or 2 draw call. + * This could make the rendering with many bounding boxes much faster than not enabled, + * but could result in a difference in rendering result if + * {@link BoundingBoxRenderer.showBackLines} enabled, + * because drawing the black/white part of each box one after the other + * can be different from drawing the black part of all boxes and then the white part. + * Also, when enabled, events of {@link BoundingBoxRenderer.onBeforeBoxRenderingObservable} + * and {@link BoundingBoxRenderer.onAfterBoxRenderingObservable} would only be triggered once + * for one rendering, instead of once every bounding box. + * Events would be triggered with a dummy box to keep backwards compatibility, + * the passed bounding box has no meaning and should be ignored. + * @param val whether to use instanced rendering + */ + set useInstances(val) { + this._useInstances = val; + if (this._colorShader) { + this._colorShader.setDefine("INSTANCES", val); + } + if (!val) { + this._cleanupInstances(); + } + } + get useInstances() { + return this._useInstances; + } + /** + * Instanced render the bounding boxes of a specific rendering group + * @param renderingGroupId defines the rendering group to render + */ + _renderInstanced(renderingGroupId) { + if (this.renderList.length === 0 || !this.enabled) { + return; + } + this._prepareResources(); + if (!this._colorShader.isReady()) { + return; + } + const colorShader = this._colorShader; + let matrices = this._matrices; + const expectedLength = this.renderList.length * 16; + if (!matrices || matrices.length < expectedLength || matrices.length > expectedLength * 2) { + matrices = new Float32Array(expectedLength); + this._matrices = matrices; + } + this.onBeforeBoxRenderingObservable.notifyObservers(dummyBoundingBox); + let instancesCount = 0; + for (let boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) { + const boundingBox = this.renderList.data[boundingBoxIndex]; + if (boundingBox._tag !== renderingGroupId) { + continue; + } + const min = boundingBox.minimum; + const max = boundingBox.maximum; + const diff = max.subtractToRef(min, tempVec2); + const median = min.addToRef(diff.scaleToRef(0.5, tempVec1), tempVec1); + const m = tempMatrixArray; + // Directly update the matrix values in column-major order + m[0] = diff._x; // Scale X + m[3] = median._x; // Translate X + m[5] = diff._y; // Scale Y + m[7] = median._y; // Translate Y + m[10] = diff._z; // Scale Z + m[11] = median._z; // Translate Z + tempMatrix.multiplyToArray(boundingBox.getWorldMatrix(), matrices, instancesCount * 16); + instancesCount++; + } + const engine = this.scene.getEngine(); + // keeps the original depth function and depth write + const depthFunction = engine.getDepthFunction() ?? 515; + const depthWrite = engine.getDepthWrite(); + engine.setDepthWrite(false); + const matrixBuffer = this._matrixBuffer; + if (matrixBuffer?.isUpdatable() && matrixBuffer.getData() === matrices) { + matrixBuffer.update(matrices); + } + else { + this._createInstanceBuffer(matrices); + } + this._createWrappersForBoundingBox(this); + const useReverseDepthBuffer = engine.useReverseDepthBuffer; + const transformMatrix = this.scene.getTransformMatrix(); + if (this.showBackLines) { + const drawWrapperBack = this._drawWrapperBack ?? colorShader._getDrawWrapper(); + colorShader._preBind(drawWrapperBack); + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, colorShader.getEffect()); + // Back + if (useReverseDepthBuffer) { + engine.setDepthFunctionToLessOrEqual(); + } + else { + engine.setDepthFunctionToGreaterOrEqual(); + } + const _uniformBufferBack = this._uniformBufferBack; + _uniformBufferBack.bindToEffect(drawWrapperBack.effect, "BoundingBoxRenderer"); + _uniformBufferBack.updateColor4("color", this.backColor, 1); + _uniformBufferBack.updateMatrix("viewProjection", transformMatrix); + _uniformBufferBack.update(); + // Draw order + engine.drawElementsType(Material.LineListDrawMode, 0, 24, instancesCount); + } + const drawWrapperFront = colorShader._getDrawWrapper(); + colorShader._preBind(drawWrapperFront); + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, colorShader.getEffect()); + // Front + if (useReverseDepthBuffer) { + engine.setDepthFunctionToGreater(); + } + else { + engine.setDepthFunctionToLess(); + } + const _uniformBufferFront = this._uniformBufferFront; + _uniformBufferFront.bindToEffect(drawWrapperFront.effect, "BoundingBoxRenderer"); + _uniformBufferFront.updateColor4("color", this.frontColor, 1); + _uniformBufferFront.updateMatrix("viewProjection", transformMatrix); + _uniformBufferFront.update(); + // Draw order + engine.drawElementsType(Material.LineListDrawMode, 0, 24, instancesCount); + this.onAfterBoxRenderingObservable.notifyObservers(dummyBoundingBox); + colorShader.unbind(); + engine.setDepthFunction(depthFunction); + engine.setDepthWrite(depthWrite); + } + /** + * Creates buffer for instanced rendering + * @param buffer buffer to set + */ + _createInstanceBuffer(buffer) { + const vertexBuffers = this._vertexBuffers; + this._cleanupInstanceBuffer(); + const matrixBuffer = new Buffer(this.scene.getEngine(), buffer, true, 16, false, true); + vertexBuffers.world0 = matrixBuffer.createVertexBuffer("world0", 0, 4); + vertexBuffers.world1 = matrixBuffer.createVertexBuffer("world1", 4, 4); + vertexBuffers.world2 = matrixBuffer.createVertexBuffer("world2", 8, 4); + vertexBuffers.world3 = matrixBuffer.createVertexBuffer("world3", 12, 4); + this._matrixBuffer = matrixBuffer; + } + /** + * Clean up buffers for instanced rendering + */ + _cleanupInstanceBuffer() { + const vertexBuffers = this._vertexBuffers; + if (vertexBuffers.world0) { + vertexBuffers.world0.dispose(); + delete vertexBuffers.world0; + } + if (vertexBuffers.world1) { + vertexBuffers.world1.dispose(); + delete vertexBuffers.world1; + } + if (vertexBuffers.world2) { + vertexBuffers.world2.dispose(); + delete vertexBuffers.world2; + } + if (vertexBuffers.world3) { + vertexBuffers.world3.dispose(); + delete vertexBuffers.world3; + } + this._matrices = null; + if (this._matrixBuffer) { + this._matrixBuffer.dispose(); + this._matrixBuffer = null; + } + } + /** + * Clean up resources for instanced rendering + */ + _cleanupInstances() { + this._cleanupInstanceBuffer(); + if (this._drawWrapperFront) { + this._drawWrapperFront.dispose(); + this._drawWrapperFront = null; + } + if (this._drawWrapperBack) { + this._drawWrapperBack.dispose(); + this._drawWrapperBack = null; + } + } + /** + * Dispose and release the resources attached to this renderer. + */ + dispose() { + if (this._renderPassIdForOcclusionQuery !== undefined) { + this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery); + this._renderPassIdForOcclusionQuery = undefined; + } + if (!this._colorShader) { + return; + } + this.onBeforeBoxRenderingObservable.clear(); + this.onAfterBoxRenderingObservable.clear(); + this.onResourcesReadyObservable.clear(); + this.renderList.dispose(); + this._colorShader.dispose(); + this._colorShaderForOcclusionQuery.dispose(); + this._uniformBufferFront.dispose(); + this._uniformBufferBack.dispose(); + const buffer = this._vertexBuffers[VertexBuffer.PositionKind]; + if (buffer) { + buffer.dispose(); + this._vertexBuffers[VertexBuffer.PositionKind] = null; + } + this.scene.getEngine()._releaseBuffer(this._indexBuffer); + if (this._fillIndexBuffer) { + this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer); + this._fillIndexBuffer = null; + } + this._cleanupInstances(); + } +} + +Scene.prototype.enableDepthRenderer = function (camera, storeNonLinearDepth = false, force32bitsFloat = false, samplingMode = 3, storeCameraSpaceZ = false) { + camera = camera || this.activeCamera; + if (!camera) { + // eslint-disable-next-line no-throw-literal + throw "No camera available to enable depth renderer"; + } + if (!this._depthRenderer) { + this._depthRenderer = {}; + } + if (!this._depthRenderer[camera.id]) { + const supportFullfloat = !!this.getEngine().getCaps().textureFloatRender; + let textureType = 0; + if (this.getEngine().getCaps().textureHalfFloatRender && (!force32bitsFloat || !supportFullfloat)) { + textureType = 2; + } + else if (supportFullfloat) { + textureType = 1; + } + else { + textureType = 0; + } + this._depthRenderer[camera.id] = new DepthRenderer(this, textureType, camera, storeNonLinearDepth, samplingMode, storeCameraSpaceZ); + } + return this._depthRenderer[camera.id]; +}; +Scene.prototype.disableDepthRenderer = function (camera) { + camera = camera || this.activeCamera; + if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) { + return; + } + this._depthRenderer[camera.id].dispose(); +}; +/** + * Defines the Depth Renderer scene component responsible to manage a depth buffer useful + * in several rendering techniques. + */ +class DepthRendererSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_DEPTHRENDERER; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets); + this.scene._gatherActiveCameraRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do for this component + } + /** + * Disposes the component and the associated resources + */ + dispose() { + for (const key in this.scene._depthRenderer) { + this.scene._depthRenderer[key].dispose(); + } + } + _gatherRenderTargets(renderTargets) { + if (this.scene._depthRenderer) { + for (const key in this.scene._depthRenderer) { + const depthRenderer = this.scene._depthRenderer[key]; + if (depthRenderer.enabled && !depthRenderer.useOnlyInActiveCamera) { + renderTargets.push(depthRenderer.getDepthMap()); + } + } + } + } + _gatherActiveCameraRenderTargets(renderTargets) { + if (this.scene._depthRenderer) { + for (const key in this.scene._depthRenderer) { + const depthRenderer = this.scene._depthRenderer[key]; + if (depthRenderer.enabled && depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) { + renderTargets.push(depthRenderer.getDepthMap()); + } + } + } + } +} +DepthRenderer._SceneComponentInitialization = (scene) => { + // Register the G Buffer component to the scene. + let component = scene._getComponent(SceneComponentConstants.NAME_DEPTHRENDERER); + if (!component) { + component = new DepthRendererSceneComponent(scene); + scene._addComponent(component); + } +}; + +/** + * Implementation based on https://medium.com/@shrekshao_71662/dual-depth-peeling-implementation-in-webgl-11baa061ba4b + */ + +class DepthPeelingEffectConfiguration { + constructor() { + /** + * Is this effect enabled + */ + this.enabled = true; + /** + * Name of the configuration + */ + this.name = "depthPeeling"; + /** + * Textures that should be present in the MRT for this effect to work + */ + this.texturesRequired = [4]; + } +} +/** + * The depth peeling renderer that performs + * Order independant transparency (OIT). + * This should not be instanciated directly, as it is part of a scene component + */ +class DepthPeelingRenderer { + /** + * Number of depth peeling passes. As we are using dual depth peeling, each pass two levels of transparency are processed. + */ + get passCount() { + return this._passCount; + } + set passCount(count) { + if (this._passCount === count) { + return; + } + this._passCount = count; + this._createRenderPassIds(); + } + /** + * Instructs the renderer to use render passes. It is an optimization that makes the rendering faster for some engines (like WebGPU) but that consumes more memory, so it is disabled by default. + */ + get useRenderPasses() { + return this._useRenderPasses; + } + set useRenderPasses(usePasses) { + if (this._useRenderPasses === usePasses) { + return; + } + this._useRenderPasses = usePasses; + this._createRenderPassIds(); + } + /** + * Add a mesh in the exclusion list to prevent it to be handled by the depth peeling renderer + * @param mesh The mesh to exclude from the depth peeling renderer + */ + addExcludedMesh(mesh) { + if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) { + this._excludedMeshes.push(mesh.uniqueId); + } + } + /** + * Remove a mesh from the exclusion list of the depth peeling renderer + * @param mesh The mesh to remove + */ + removeExcludedMesh(mesh) { + const index = this._excludedMeshes.indexOf(mesh.uniqueId); + if (index !== -1) { + this._excludedMeshes.splice(index, 1); + } + } + /** + * Gets the shader language used in this renderer + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Instanciates the depth peeling renderer + * @param scene Scene to attach to + * @param passCount Number of depth layers to peel + * @returns The depth peeling renderer + */ + constructor(scene, passCount = 5) { + this._thinTextures = []; + this._currentPingPongState = 0; + this._layoutCacheFormat = [[true], [true, true], [true, true, true]]; + this._layoutCache = []; + this._candidateSubMeshes = new SmartArray(10); + this._excludedSubMeshes = new SmartArray(10); + this._excludedMeshes = []; + this._colorCache = [ + new Color4(DepthPeelingRenderer._DEPTH_CLEAR_VALUE, DepthPeelingRenderer._DEPTH_CLEAR_VALUE, 0, 0), + new Color4(-DepthPeelingRenderer._MIN_DEPTH, DepthPeelingRenderer._MAX_DEPTH, 0, 0), + new Color4(0, 0, 0, 0), + ]; + /** Shader language used by the renderer */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._scene = scene; + this._engine = scene.getEngine(); + this._passCount = passCount; + // We need a depth texture for opaque + if (!scene.enablePrePassRenderer()) { + Logger.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting."); + return; + } + for (let i = 0; i < this._layoutCacheFormat.length; ++i) { + this._layoutCache[i] = this._engine.buildTextureLayout(this._layoutCacheFormat[i]); + } + this._renderPassIds = []; + this.useRenderPasses = false; + if (this._engine.isWebGPU) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + } + this._prePassEffectConfiguration = new DepthPeelingEffectConfiguration(); + this._createTextures(); + this._createEffects(); + } + _createRenderPassIds() { + this._releaseRenderPassIds(); + if (this._useRenderPasses) { + for (let i = 0; i < this._passCount + 1; ++i) { + if (!this._renderPassIds[i]) { + this._renderPassIds[i] = this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${i}`); + } + } + } + } + _releaseRenderPassIds() { + for (let i = 0; i < this._renderPassIds.length; ++i) { + this._engine.releaseRenderPassId(this._renderPassIds[i]); + } + this._renderPassIds = []; + } + _createTextures() { + const size = { + width: this._engine.getRenderWidth(), + height: this._engine.getRenderHeight(), + }; + // 2 for ping pong + this._depthMrts = [ + new MultiRenderTarget("depthPeelingDepth0MRT", size, 3, this._scene, undefined, [ + "depthPeelingDepth0MRT_depth", + "depthPeelingDepth0MRT_frontColor", + "depthPeelingDepth0MRT_backColor", + ]), + new MultiRenderTarget("depthPeelingDepth1MRT", size, 3, this._scene, undefined, [ + "depthPeelingDepth1MRT_depth", + "depthPeelingDepth1MRT_frontColor", + "depthPeelingDepth1MRT_backColor", + ]), + ]; + this._colorMrts = [ + new MultiRenderTarget("depthPeelingColor0MRT", size, 2, this._scene, { generateDepthBuffer: false }, [ + "depthPeelingColor0MRT_frontColor", + "depthPeelingColor0MRT_backColor", + ]), + new MultiRenderTarget("depthPeelingColor1MRT", size, 2, this._scene, { generateDepthBuffer: false }, [ + "depthPeelingColor1MRT_frontColor", + "depthPeelingColor1MRT_backColor", + ]), + ]; + this._blendBackMrt = new MultiRenderTarget("depthPeelingBackMRT", size, 1, this._scene, { generateDepthBuffer: false }, ["depthPeelingBackMRT_blendBack"]); + this._outputRT = new RenderTargetTexture("depthPeelingOutputRTT", size, this._scene, false); + // 0 is a depth texture + // 1 is a color texture + const optionsArray = [ + { + format: 7, // For MSAA we need RGBA + samplingMode: 1, + type: this._engine.getCaps().textureFloatLinearFiltering ? 1 : 2, + label: "DepthPeelingRenderer-DepthTexture", + }, + { + format: 5, + samplingMode: 1, + type: 2, // For MSAA we need FLOAT + label: "DepthPeelingRenderer-ColorTexture", + }, + ]; + for (let i = 0; i < 2; i++) { + const depthTexture = this._engine._createInternalTexture(size, optionsArray[0], false); + const frontColorTexture = this._engine._createInternalTexture(size, optionsArray[1], false); + const backColorTexture = this._engine._createInternalTexture(size, optionsArray[1], false); + this._depthMrts[i].setInternalTexture(depthTexture, 0); + this._depthMrts[i].setInternalTexture(frontColorTexture, 1); + this._depthMrts[i].setInternalTexture(backColorTexture, 2); + this._colorMrts[i].setInternalTexture(frontColorTexture, 0); + this._colorMrts[i].setInternalTexture(backColorTexture, 1); + this._thinTextures.push(new ThinTexture(depthTexture), new ThinTexture(frontColorTexture), new ThinTexture(backColorTexture)); + } + } + // TODO : explore again MSAA with depth peeling when + // we are able to fetch individual samples in a multisampled renderbuffer + // public set samples(value: number) { + // for (let i = 0; i < 2; i++) { + // this._depthMrts[i].samples = value; + // this._colorMrts[i].samples = value; + // } + // this._scene.prePassRenderer!.samples = value; + // } + _disposeTextures() { + for (let i = 0; i < this._thinTextures.length; i++) { + if (i === 6) { + // Do not dispose the shared texture with the prepass + continue; + } + this._thinTextures[i].dispose(); + } + for (let i = 0; i < 2; i++) { + this._depthMrts[i].dispose(true); + this._colorMrts[i].dispose(true); + this._blendBackMrt.dispose(true); + } + this._outputRT.dispose(); + this._thinTextures = []; + this._colorMrts = []; + this._depthMrts = []; + } + _updateTextures() { + if (this._depthMrts[0].getSize().width !== this._engine.getRenderWidth() || this._depthMrts[0].getSize().height !== this._engine.getRenderHeight()) { + this._disposeTextures(); + this._createTextures(); + } + return this._updateTextureReferences(); + } + _updateTextureReferences() { + const prePassRenderer = this._scene.prePassRenderer; + if (!prePassRenderer) { + return false; + } + // Retrieve opaque color texture + const textureIndex = prePassRenderer.getIndex(4); + const prePassTexture = prePassRenderer.defaultRT.textures?.length ? prePassRenderer.defaultRT.textures[textureIndex].getInternalTexture() : null; + if (!prePassTexture) { + return false; + } + if (this._blendBackTexture !== prePassTexture) { + this._blendBackTexture = prePassTexture; + this._blendBackMrt.setInternalTexture(this._blendBackTexture, 0); + if (this._thinTextures[6]) { + this._thinTextures[6].dispose(); + } + this._thinTextures[6] = new ThinTexture(this._blendBackTexture); + prePassRenderer.defaultRT.renderTarget.shareDepth(this._depthMrts[0].renderTarget); + } + return true; + } + _createEffects() { + this._blendBackEffectWrapper = new EffectWrapper({ + fragmentShader: "oitBackBlend", + useShaderStore: true, + engine: this._engine, + samplerNames: ["uBackColor"], + uniformNames: [], + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => oitBackBlend_fragment); + } + else { + await Promise.resolve().then(() => oitBackBlend_fragment$1); + } + }, + }); + this._blendBackEffectWrapperPingPong = new EffectWrapper({ + fragmentShader: "oitBackBlend", + useShaderStore: true, + engine: this._engine, + samplerNames: ["uBackColor"], + uniformNames: [], + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => oitBackBlend_fragment); + } + else { + await Promise.resolve().then(() => oitBackBlend_fragment$1); + } + }, + }); + this._finalEffectWrapper = new EffectWrapper({ + fragmentShader: "oitFinal", + useShaderStore: true, + engine: this._engine, + samplerNames: ["uFrontColor", "uBackColor"], + uniformNames: [], + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => oitFinal_fragment); + } + else { + await Promise.resolve().then(() => oitFinal_fragment$1); + } + }, + }); + this._effectRenderer = new EffectRenderer(this._engine); + } + /** + * Links to the prepass renderer + * @param prePassRenderer The scene PrePassRenderer + */ + setPrePassRenderer(prePassRenderer) { + prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration); + } + /** + * Binds depth peeling textures on an effect + * @param effect The effect to bind textures on + */ + bind(effect) { + effect.setTexture("oitDepthSampler", this._thinTextures[this._currentPingPongState * 3]); + effect.setTexture("oitFrontColorSampler", this._thinTextures[this._currentPingPongState * 3 + 1]); + } + _renderSubMeshes(transparentSubMeshes) { + let mapMaterialContext; + if (this._useRenderPasses) { + mapMaterialContext = {}; + } + for (let j = 0; j < transparentSubMeshes.length; j++) { + const material = transparentSubMeshes.data[j].getMaterial(); + let previousShaderHotSwapping = true; + let previousBFC = false; + const subMesh = transparentSubMeshes.data[j]; + let drawWrapper; + let firstDraw = false; + if (this._useRenderPasses) { + drawWrapper = subMesh._getDrawWrapper(); + firstDraw = !drawWrapper; + } + if (material) { + previousShaderHotSwapping = material.allowShaderHotSwapping; + previousBFC = material.backFaceCulling; + material.allowShaderHotSwapping = false; + material.backFaceCulling = false; + } + subMesh.render(false); + if (firstDraw) { + // first time we draw this submesh: we replace the material context + drawWrapper = subMesh._getDrawWrapper(); // we are sure it is now non empty as we just rendered the submesh + if (drawWrapper.materialContext) { + let newMaterialContext = mapMaterialContext[drawWrapper.materialContext.uniqueId]; + if (!newMaterialContext) { + newMaterialContext = mapMaterialContext[drawWrapper.materialContext.uniqueId] = this._engine.createMaterialContext(); + } + subMesh._getDrawWrapper().materialContext = newMaterialContext; + } + } + if (material) { + material.allowShaderHotSwapping = previousShaderHotSwapping; + material.backFaceCulling = previousBFC; + } + } + } + _finalCompose(writeId) { + const output = this._scene.prePassRenderer?.setCustomOutput(this._outputRT); + if (output) { + this._engine.bindFramebuffer(this._outputRT.renderTarget); + } + else { + this._engine.restoreDefaultFramebuffer(); + } + this._engine.setAlphaMode(0); + this._engine.applyStates(); + this._engine.enableEffect(this._finalEffectWrapper.drawWrapper); + this._finalEffectWrapper.effect.setTexture("uFrontColor", this._thinTextures[writeId * 3 + 1]); + this._finalEffectWrapper.effect.setTexture("uBackColor", this._thinTextures[6]); + this._effectRenderer.render(this._finalEffectWrapper); + } + /** + * Checks if the depth peeling renderer is ready to render transparent meshes + * @returns true if the depth peeling renderer is ready to render the transparent meshes + */ + isReady() { + return (this._blendBackEffectWrapper.effect.isReady() && + this._blendBackEffectWrapperPingPong.effect.isReady() && + this._finalEffectWrapper.effect.isReady() && + this._updateTextures()); + } + /** + * Renders transparent submeshes with depth peeling + * @param transparentSubMeshes List of transparent meshes to render + * @returns The array of submeshes that could not be handled by this renderer + */ + render(transparentSubMeshes) { + this._candidateSubMeshes.length = 0; + this._excludedSubMeshes.length = 0; + if (!this.isReady()) { + return this._excludedSubMeshes; + } + if (this._scene.activeCamera) { + this._engine.setViewport(this._scene.activeCamera.viewport); + } + for (let i = 0; i < transparentSubMeshes.length; i++) { + const subMesh = transparentSubMeshes.data[i]; + const material = subMesh.getMaterial(); + const fillMode = material && subMesh.getRenderingMesh()._getRenderingFillMode(material.fillMode); + if (material && + (fillMode === Material.TriangleFanDrawMode || fillMode === Material.TriangleFillMode || fillMode === Material.TriangleStripDrawMode) && + this._excludedMeshes.indexOf(subMesh.getMesh().uniqueId) === -1) { + this._candidateSubMeshes.push(subMesh); + } + else { + this._excludedSubMeshes.push(subMesh); + } + } + if (!this._candidateSubMeshes.length) { + this._engine.bindFramebuffer(this._colorMrts[1].renderTarget); + this._engine.bindAttachments(this._layoutCache[1]); + this._engine.clear(this._colorCache[2], true, false, false); + this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget); + this._finalCompose(1); + return this._excludedSubMeshes; + } + const currentRenderPassId = this._engine.currentRenderPassId; + this._scene.prePassRenderer._enabled = false; + if (this._useRenderPasses) { + this._engine.currentRenderPassId = this._renderPassIds[0]; + } + // Clears + this._engine.bindFramebuffer(this._depthMrts[0].renderTarget); + this._engine.bindAttachments(this._layoutCache[0]); + this._engine.clear(this._colorCache[0], true, false, false); + this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget); + this._engine.bindFramebuffer(this._depthMrts[1].renderTarget); + this._engine.bindAttachments(this._layoutCache[0]); + this._engine.clear(this._colorCache[1], true, false, false); + this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget); + this._engine.bindFramebuffer(this._colorMrts[0].renderTarget); + this._engine.bindAttachments(this._layoutCache[1]); + this._engine.clear(this._colorCache[2], true, false, false); + this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget); + this._engine.bindFramebuffer(this._colorMrts[1].renderTarget); + this._engine.bindAttachments(this._layoutCache[1]); + this._engine.clear(this._colorCache[2], true, false, false); + this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget); + // Draw depth for first pass + this._engine.bindFramebuffer(this._depthMrts[0].renderTarget); + this._engine.bindAttachments(this._layoutCache[0]); + this._engine.setAlphaMode(11); // in WebGPU, when using MIN or MAX equation, the src / dst color factors should not use SRC_ALPHA and the src / dst alpha factors must be 1 else WebGPU will throw a validation error + this._engine.setAlphaEquation(3); + this._engine.depthCullingState.depthMask = false; + this._engine.depthCullingState.depthTest = true; + this._engine.applyStates(); + this._currentPingPongState = 1; + // Render + this._renderSubMeshes(this._candidateSubMeshes); + this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget); + this._scene.resetCachedMaterial(); + // depth peeling ping-pong + let readId = 0; + let writeId = 0; + for (let i = 0; i < this._passCount; i++) { + readId = i % 2; + writeId = 1 - readId; + this._currentPingPongState = readId; + if (this._useRenderPasses) { + this._engine.currentRenderPassId = this._renderPassIds[i + 1]; + } + if (this._scene.activeCamera) { + this._engine.setViewport(this._scene.activeCamera.viewport); + } + // Clears + this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget); + this._engine.bindAttachments(this._layoutCache[0]); + this._engine.clear(this._colorCache[0], true, false, false); + this._engine.unBindFramebuffer(this._depthMrts[writeId].renderTarget); + this._engine.bindFramebuffer(this._colorMrts[writeId].renderTarget); + this._engine.bindAttachments(this._layoutCache[1]); + this._engine.clear(this._colorCache[2], true, false, false); + this._engine.unBindFramebuffer(this._colorMrts[writeId].renderTarget); + this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget); + this._engine.bindAttachments(this._layoutCache[2]); + this._engine.setAlphaMode(11); // the value does not matter (as MAX operation does not use them) but the src and dst color factors should not use SRC_ALPHA else WebGPU will throw a validation error + this._engine.setAlphaEquation(3); + this._engine.depthCullingState.depthTest = false; + this._engine.applyStates(); + // Render + this._renderSubMeshes(this._candidateSubMeshes); + this._engine.unBindFramebuffer(this._depthMrts[writeId].renderTarget); + this._scene.resetCachedMaterial(); + // Back color + this._engine.bindFramebuffer(this._blendBackMrt.renderTarget); + this._engine.bindAttachments(this._layoutCache[0]); + this._engine.setAlphaEquation(0); + this._engine.setAlphaMode(17); + this._engine.applyStates(); + const blendBackEffectWrapper = writeId === 0 || !this._useRenderPasses ? this._blendBackEffectWrapper : this._blendBackEffectWrapperPingPong; + this._engine.enableEffect(blendBackEffectWrapper.drawWrapper); + blendBackEffectWrapper.effect.setTexture("uBackColor", this._thinTextures[writeId * 3 + 2]); + this._effectRenderer.render(blendBackEffectWrapper); + this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget); + } + this._engine.currentRenderPassId = currentRenderPassId; + // Final composition on default FB + this._finalCompose(writeId); + this._scene.prePassRenderer._enabled = true; + this._engine.depthCullingState.depthMask = true; + this._engine.depthCullingState.depthTest = true; + return this._excludedSubMeshes; + } + /** + * Disposes the depth peeling renderer and associated ressources + */ + dispose() { + this._disposeTextures(); + this._blendBackEffectWrapper.dispose(); + this._finalEffectWrapper.dispose(); + this._effectRenderer.dispose(); + this._releaseRenderPassIds(); + } +} +DepthPeelingRenderer._DEPTH_CLEAR_VALUE = -99999; +DepthPeelingRenderer._MIN_DEPTH = 0; +DepthPeelingRenderer._MAX_DEPTH = 1; + +Object.defineProperty(Scene.prototype, "depthPeelingRenderer", { + get: function () { + if (!this._depthPeelingRenderer) { + let component = this._getComponent(SceneComponentConstants.NAME_DEPTHPEELINGRENDERER); + if (!component) { + component = new DepthPeelingSceneComponent(this); + this._addComponent(component); + } + } + return this._depthPeelingRenderer; + }, + set: function (value) { + this._depthPeelingRenderer = value; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(Scene.prototype, "useOrderIndependentTransparency", { + get: function () { + return this._useOrderIndependentTransparency; + }, + set: function (value) { + if (this._useOrderIndependentTransparency === value) { + return; + } + this._useOrderIndependentTransparency = value; + this.markAllMaterialsAsDirty(127); + this.prePassRenderer?.markAsDirty(); + }, + enumerable: true, + configurable: true, +}); +/** + * Scene component to render order independent transparency with depth peeling + */ +class DepthPeelingSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_DEPTHPEELINGRENDERER; + this.scene = scene; + scene.depthPeelingRenderer = new DepthPeelingRenderer(scene); + } + /** + * Registers the component in a given scene + */ + register() { } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { } + /** + * Disposes the component and the associated resources. + */ + dispose() { + this.scene.depthPeelingRenderer?.dispose(); + this.scene.depthPeelingRenderer = null; + } +} + +AbstractMesh.prototype.disableEdgesRendering = function () { + if (this._edgesRenderer) { + this._edgesRenderer.dispose(); + this._edgesRenderer = null; + } + return this; +}; +AbstractMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false, options) { + this.disableEdgesRendering(); + this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices, true, options); + return this; +}; +Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", { + get: function () { + return this._edgesRenderer; + }, + enumerable: true, + configurable: true, +}); +LinesMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false) { + this.disableEdgesRendering(); + this._edgesRenderer = new LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices); + return this; +}; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +InstancedLinesMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false) { + LinesMesh.prototype.enableEdgesRendering.apply(this, arguments); + return this; +}; +/** + * FaceAdjacencies Helper class to generate edges + */ +class FaceAdjacencies { + constructor() { + this.edges = []; + this.edgesConnectedCount = 0; + } +} +/** + * This class is used to generate edges of the mesh that could then easily be rendered in a scene. + */ +class EdgesRenderer { + /** Gets the vertices generated by the edge renderer */ + get linesPositions() { + return this._linesPositions; + } + /** Gets the normals generated by the edge renderer */ + get linesNormals() { + return this._linesNormals; + } + /** Gets the indices generated by the edge renderer */ + get linesIndices() { + return this._linesIndices; + } + /** + * Gets or sets the shader used to draw the lines + */ + get lineShader() { + return this._lineShader; + } + set lineShader(shader) { + this._lineShader = shader; + } + static _GetShader(scene, shaderLanguage) { + if (!scene._edgeRenderLineShader) { + const shader = new ShaderMaterial("lineShader", scene, "line", { + attributes: ["position", "normal"], + uniforms: ["world", "viewProjection", "color", "width", "aspectRatio"], + uniformBuffers: ["Scene", "Mesh"], + shaderLanguage: shaderLanguage, + extraInitializationsAsync: async () => { + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => line_vertex), Promise.resolve().then(() => line_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => line_vertex$1), Promise.resolve().then(() => line_fragment$1)]); + } + }, + }, false); + shader.disableDepthWrite = true; + shader.backFaceCulling = false; + shader.checkReadyOnEveryCall = scene.getEngine().isWebGPU; + scene._edgeRenderLineShader = shader; + scene.onDisposeObservable.add(() => { + scene._edgeRenderLineShader.dispose(); + scene._edgeRenderLineShader = null; + }); + } + return scene._edgeRenderLineShader; + } + /** + * Gets the shader language used. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh. + * Beware when you use this class with complex objects as the adjacencies computation can be really long + * @param source Mesh used to create edges + * @param epsilon sum of angles in adjacency to check for edge + * @param checkVerticesInsteadOfIndices bases the edges detection on vertices vs indices. Note that this parameter is not used if options.useAlternateEdgeFinder = true + * @param generateEdgesLines - should generate Lines or only prepare resources. + * @param options The options to apply when generating the edges + */ + constructor(source, epsilon = 0.95, checkVerticesInsteadOfIndices = false, generateEdgesLines = true, options) { + /** + * Define the size of the edges with an orthographic camera + */ + this.edgesWidthScalerForOrthographic = 1000.0; + /** + * Define the size of the edges with a perspective camera + */ + this.edgesWidthScalerForPerspective = 50.0; + this._linesPositions = new Array(); + this._linesNormals = new Array(); + this._linesIndices = new Array(); + this._buffers = {}; + this._buffersForInstances = {}; + this._checkVerticesInsteadOfIndices = false; + /** Gets or sets a boolean indicating if the edgesRenderer is active */ + this.isEnabled = true; + /** + * List of instances to render in case the source mesh has instances + */ + this.customInstances = new SmartArray(32); + /** Shader language used*/ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._source = source; + this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices; + this._options = options ?? null; + this._epsilon = epsilon; + const engine = this._source.getScene().getEngine(); + if (engine.isWebGPU) { + this._drawWrapper = new DrawWrapper(engine); + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + } + this._prepareRessources(); + if (generateEdgesLines) { + if (options?.useAlternateEdgeFinder ?? true) { + this._generateEdgesLinesAlternate(); + } + else { + this._generateEdgesLines(); + } + } + this._meshRebuildObserver = this._source.onRebuildObservable.add(() => { + this._rebuild(); + }); + this._meshDisposeObserver = this._source.onDisposeObservable.add(() => { + this.dispose(); + }); + } + _prepareRessources() { + if (this._lineShader) { + return; + } + this._lineShader = EdgesRenderer._GetShader(this._source.getScene(), this._shaderLanguage); + } + /** @internal */ + _rebuild() { + let buffer = this._buffers[VertexBuffer.PositionKind]; + if (buffer) { + buffer._rebuild(); + } + buffer = this._buffers[VertexBuffer.NormalKind]; + if (buffer) { + buffer._rebuild(); + } + const scene = this._source.getScene(); + const engine = scene.getEngine(); + this._ib = engine.createIndexBuffer(this._linesIndices); + } + /** + * Releases the required resources for the edges renderer + */ + dispose() { + this._source.onRebuildObservable.remove(this._meshRebuildObserver); + this._source.onDisposeObservable.remove(this._meshDisposeObserver); + let buffer = this._buffers[VertexBuffer.PositionKind]; + if (buffer) { + buffer.dispose(); + this._buffers[VertexBuffer.PositionKind] = null; + } + buffer = this._buffers[VertexBuffer.NormalKind]; + if (buffer) { + buffer.dispose(); + this._buffers[VertexBuffer.NormalKind] = null; + } + if (this._ib) { + this._source.getScene().getEngine()._releaseBuffer(this._ib); + } + this._drawWrapper?.dispose(); + } + _processEdgeForAdjacencies(pa, pb, p0, p1, p2) { + if ((pa === p0 && pb === p1) || (pa === p1 && pb === p0)) { + return 0; + } + if ((pa === p1 && pb === p2) || (pa === p2 && pb === p1)) { + return 1; + } + if ((pa === p2 && pb === p0) || (pa === p0 && pb === p2)) { + return 2; + } + return -1; + } + _processEdgeForAdjacenciesWithVertices(pa, pb, p0, p1, p2) { + const eps = 1e-10; + if ((pa.equalsWithEpsilon(p0, eps) && pb.equalsWithEpsilon(p1, eps)) || (pa.equalsWithEpsilon(p1, eps) && pb.equalsWithEpsilon(p0, eps))) { + return 0; + } + if ((pa.equalsWithEpsilon(p1, eps) && pb.equalsWithEpsilon(p2, eps)) || (pa.equalsWithEpsilon(p2, eps) && pb.equalsWithEpsilon(p1, eps))) { + return 1; + } + if ((pa.equalsWithEpsilon(p2, eps) && pb.equalsWithEpsilon(p0, eps)) || (pa.equalsWithEpsilon(p0, eps) && pb.equalsWithEpsilon(p2, eps))) { + return 2; + } + return -1; + } + /** + * Checks if the pair of p0 and p1 is en edge + * @param faceIndex + * @param edge + * @param faceNormals + * @param p0 + * @param p1 + * @private + */ + _checkEdge(faceIndex, edge, faceNormals, p0, p1) { + let needToCreateLine; + if (edge === undefined) { + needToCreateLine = true; + } + else { + const dotProduct = Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]); + needToCreateLine = dotProduct < this._epsilon; + } + if (needToCreateLine) { + this.createLine(p0, p1, this._linesPositions.length / 3); + } + } + /** + * push line into the position, normal and index buffer + * @param p0 + * @param p1 + * @param offset + * @protected + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + createLine(p0, p1, offset) { + // Positions + this._linesPositions.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, p1.x, p1.y, p1.z); + // Normals + this._linesNormals.push(p1.x, p1.y, p1.z, -1, p1.x, p1.y, p1.z, 1, p0.x, p0.y, p0.z, -1, p0.x, p0.y, p0.z, 1); + // Indices + this._linesIndices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3); + } + /** + * See https://playground.babylonjs.com/#R3JR6V#1 for a visual display of the algorithm + * @param edgePoints + * @param indexTriangle + * @param indices + * @param remapVertexIndices + */ + _tessellateTriangle(edgePoints, indexTriangle, indices, remapVertexIndices) { + const makePointList = (edgePoints, pointIndices, firstIndex) => { + if (firstIndex >= 0) { + pointIndices.push(firstIndex); + } + for (let i = 0; i < edgePoints.length; ++i) { + pointIndices.push(edgePoints[i][0]); + } + }; + let startEdge = 0; + if (edgePoints[1].length >= edgePoints[0].length && edgePoints[1].length >= edgePoints[2].length) { + startEdge = 1; + } + else if (edgePoints[2].length >= edgePoints[0].length && edgePoints[2].length >= edgePoints[1].length) { + startEdge = 2; + } + for (let e = 0; e < 3; ++e) { + if (e === startEdge) { + edgePoints[e].sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)); + } + else { + edgePoints[e].sort((a, b) => (a[1] > b[1] ? -1 : a[1] < b[1] ? 1 : 0)); + } + } + const mainPointIndices = [], otherPointIndices = []; + makePointList(edgePoints[startEdge], mainPointIndices, -1); + const numMainPoints = mainPointIndices.length; + for (let i = startEdge + 2; i >= startEdge + 1; --i) { + makePointList(edgePoints[i % 3], otherPointIndices, i !== startEdge + 2 ? remapVertexIndices[indices[indexTriangle + ((i + 1) % 3)]] : -1); + } + const numOtherPoints = otherPointIndices.length; + const idxMain = 0; + const idxOther = 0; + indices.push(remapVertexIndices[indices[indexTriangle + startEdge]], mainPointIndices[0], otherPointIndices[0]); + indices.push(remapVertexIndices[indices[indexTriangle + ((startEdge + 1) % 3)]], otherPointIndices[numOtherPoints - 1], mainPointIndices[numMainPoints - 1]); + const bucketIsMain = numMainPoints <= numOtherPoints; + const bucketStep = bucketIsMain ? numMainPoints : numOtherPoints; + const bucketLimit = bucketIsMain ? numOtherPoints : numMainPoints; + const bucketIdxLimit = bucketIsMain ? numMainPoints - 1 : numOtherPoints - 1; + const winding = bucketIsMain ? 0 : 1; + let numTris = numMainPoints + numOtherPoints - 2; + let bucketIdx = bucketIsMain ? idxMain : idxOther; + let nbucketIdx = bucketIsMain ? idxOther : idxMain; + const bucketPoints = bucketIsMain ? mainPointIndices : otherPointIndices; + const nbucketPoints = bucketIsMain ? otherPointIndices : mainPointIndices; + let bucket = 0; + while (numTris-- > 0) { + if (winding) { + indices.push(bucketPoints[bucketIdx], nbucketPoints[nbucketIdx]); + } + else { + indices.push(nbucketPoints[nbucketIdx], bucketPoints[bucketIdx]); + } + bucket += bucketStep; + let lastIdx; + if (bucket >= bucketLimit && bucketIdx < bucketIdxLimit) { + lastIdx = bucketPoints[++bucketIdx]; + bucket -= bucketLimit; + } + else { + lastIdx = nbucketPoints[++nbucketIdx]; + } + indices.push(lastIdx); + } + indices[indexTriangle + 0] = indices[indices.length - 3]; + indices[indexTriangle + 1] = indices[indices.length - 2]; + indices[indexTriangle + 2] = indices[indices.length - 1]; + indices.length = indices.length - 3; + } + _generateEdgesLinesAlternate() { + const positions = this._source.getVerticesData(VertexBuffer.PositionKind); + let indices = this._source.getIndices(); + if (!indices || !positions) { + return; + } + if (!Array.isArray(indices)) { + indices = Array.from(indices); + } + /** + * Find all vertices that are at the same location (with an epsilon) and remapp them on the same vertex + */ + const useFastVertexMerger = this._options?.useFastVertexMerger ?? true; + const epsVertexMerge = useFastVertexMerger ? Math.round(-Math.log(this._options?.epsilonVertexMerge ?? 1e-6) / Math.log(10)) : (this._options?.epsilonVertexMerge ?? 1e-6); + const remapVertexIndices = []; + const uniquePositions = []; // list of unique index of vertices - needed for tessellation + if (useFastVertexMerger) { + const mapVertices = {}; + for (let v1 = 0; v1 < positions.length; v1 += 3) { + const x1 = positions[v1 + 0], y1 = positions[v1 + 1], z1 = positions[v1 + 2]; + const key = x1.toFixed(epsVertexMerge) + "|" + y1.toFixed(epsVertexMerge) + "|" + z1.toFixed(epsVertexMerge); + if (mapVertices[key] !== undefined) { + remapVertexIndices.push(mapVertices[key]); + } + else { + const idx = v1 / 3; + mapVertices[key] = idx; + remapVertexIndices.push(idx); + uniquePositions.push(idx); + } + } + } + else { + for (let v1 = 0; v1 < positions.length; v1 += 3) { + const x1 = positions[v1 + 0], y1 = positions[v1 + 1], z1 = positions[v1 + 2]; + let found = false; + for (let v2 = 0; v2 < v1 && !found; v2 += 3) { + const x2 = positions[v2 + 0], y2 = positions[v2 + 1], z2 = positions[v2 + 2]; + if (Math.abs(x1 - x2) < epsVertexMerge && Math.abs(y1 - y2) < epsVertexMerge && Math.abs(z1 - z2) < epsVertexMerge) { + remapVertexIndices.push(v2 / 3); + found = true; + break; + } + } + if (!found) { + remapVertexIndices.push(v1 / 3); + uniquePositions.push(v1 / 3); + } + } + } + if (this._options?.applyTessellation) { + /** + * Tessellate triangles if necessary: + * + * A + * + + * |\ + * | \ + * | \ + * E + \ + * /| \ + * / | \ + * / | \ + * +---+-------+ B + * D C + * + * For the edges to be rendered correctly, the ABC triangle has to be split into ABE and BCE, else AC is considered to be an edge, whereas only AE should be. + * + * The tessellation process looks for the vertices like E that are in-between two other vertices making of an edge and create new triangles as necessary + */ + // First step: collect the triangles to tessellate + const epsVertexAligned = this._options?.epsilonVertexAligned ?? 1e-6; + const mustTesselate = []; // liste of triangles that must be tessellated + for (let index = 0; index < indices.length; index += 3) { + // loop over all triangles + let triangleToTessellate; + for (let i = 0; i < 3; ++i) { + // loop over the 3 edges of the triangle + const p0Index = remapVertexIndices[indices[index + i]]; + const p1Index = remapVertexIndices[indices[index + ((i + 1) % 3)]]; + const p2Index = remapVertexIndices[indices[index + ((i + 2) % 3)]]; + if (p0Index === p1Index) { + continue; + } // degenerated triangle - don't process + const p0x = positions[p0Index * 3 + 0], p0y = positions[p0Index * 3 + 1], p0z = positions[p0Index * 3 + 2]; + const p1x = positions[p1Index * 3 + 0], p1y = positions[p1Index * 3 + 1], p1z = positions[p1Index * 3 + 2]; + const p0p1 = Math.sqrt((p1x - p0x) * (p1x - p0x) + (p1y - p0y) * (p1y - p0y) + (p1z - p0z) * (p1z - p0z)); + for (let v = 0; v < uniquePositions.length - 1; v++) { + // loop over all (unique) vertices and look for the ones that would be in-between p0 and p1 + const vIndex = uniquePositions[v]; + if (vIndex === p0Index || vIndex === p1Index || vIndex === p2Index) { + continue; + } // don't handle the vertex if it is a vertex of the current triangle + const x = positions[vIndex * 3 + 0], y = positions[vIndex * 3 + 1], z = positions[vIndex * 3 + 2]; + const p0p = Math.sqrt((x - p0x) * (x - p0x) + (y - p0y) * (y - p0y) + (z - p0z) * (z - p0z)); + const pp1 = Math.sqrt((x - p1x) * (x - p1x) + (y - p1y) * (y - p1y) + (z - p1z) * (z - p1z)); + if (Math.abs(p0p + pp1 - p0p1) < epsVertexAligned) { + // vertices are aligned and p in-between p0 and p1 if distance(p0, p) + distance (p, p1) ~ distance(p0, p1) + if (!triangleToTessellate) { + triangleToTessellate = { + index: index, + edgesPoints: [[], [], []], + }; + mustTesselate.push(triangleToTessellate); + } + triangleToTessellate.edgesPoints[i].push([vIndex, p0p]); + } + } + } + } + // Second step: tesselate the triangles + for (let t = 0; t < mustTesselate.length; ++t) { + const triangle = mustTesselate[t]; + this._tessellateTriangle(triangle.edgesPoints, triangle.index, indices, remapVertexIndices); + } + mustTesselate.length = 0; + } + /** + * Collect the edges to render + */ + const edges = {}; + for (let index = 0; index < indices.length; index += 3) { + let faceNormal; + for (let i = 0; i < 3; ++i) { + let p0Index = remapVertexIndices[indices[index + i]]; + let p1Index = remapVertexIndices[indices[index + ((i + 1) % 3)]]; + const p2Index = remapVertexIndices[indices[index + ((i + 2) % 3)]]; + if (p0Index === p1Index || ((p0Index === p2Index || p1Index === p2Index) && this._options?.removeDegeneratedTriangles)) { + continue; + } + TmpVectors.Vector3[0].copyFromFloats(positions[p0Index * 3 + 0], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]); + TmpVectors.Vector3[1].copyFromFloats(positions[p1Index * 3 + 0], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]); + TmpVectors.Vector3[2].copyFromFloats(positions[p2Index * 3 + 0], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]); + if (!faceNormal) { + TmpVectors.Vector3[1].subtractToRef(TmpVectors.Vector3[0], TmpVectors.Vector3[3]); + TmpVectors.Vector3[2].subtractToRef(TmpVectors.Vector3[1], TmpVectors.Vector3[4]); + faceNormal = Vector3.Cross(TmpVectors.Vector3[3], TmpVectors.Vector3[4]); + faceNormal.normalize(); + } + if (p0Index > p1Index) { + const tmp = p0Index; + p0Index = p1Index; + p1Index = tmp; + } + const key = p0Index + "_" + p1Index; + const ei = edges[key]; + if (ei) { + if (!ei.done) { + const dotProduct = Vector3.Dot(faceNormal, ei.normal); + if (dotProduct < this._epsilon) { + this.createLine(TmpVectors.Vector3[0], TmpVectors.Vector3[1], this._linesPositions.length / 3); + } + ei.done = true; + } + } + else { + edges[key] = { normal: faceNormal, done: false, index: index, i: i }; + } + } + } + for (const key in edges) { + const ei = edges[key]; + if (!ei.done) { + // Orphaned edge - we must display it + const p0Index = remapVertexIndices[indices[ei.index + ei.i]]; + const p1Index = remapVertexIndices[indices[ei.index + ((ei.i + 1) % 3)]]; + TmpVectors.Vector3[0].copyFromFloats(positions[p0Index * 3 + 0], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]); + TmpVectors.Vector3[1].copyFromFloats(positions[p1Index * 3 + 0], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]); + this.createLine(TmpVectors.Vector3[0], TmpVectors.Vector3[1], this._linesPositions.length / 3); + } + } + /** + * Merge into a single mesh + */ + const engine = this._source.getScene().getEngine(); + this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, this._linesPositions, VertexBuffer.PositionKind, false); + this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine, this._linesNormals, VertexBuffer.NormalKind, false, false, 4); + this._buffersForInstances[VertexBuffer.PositionKind] = this._buffers[VertexBuffer.PositionKind]; + this._buffersForInstances[VertexBuffer.NormalKind] = this._buffers[VertexBuffer.NormalKind]; + this._ib = engine.createIndexBuffer(this._linesIndices); + this._indicesCount = this._linesIndices.length; + } + /** + * Generates lines edges from adjacencjes + * @private + */ + _generateEdgesLines() { + const positions = this._source.getVerticesData(VertexBuffer.PositionKind); + const indices = this._source.getIndices(); + if (!indices || !positions) { + return; + } + // First let's find adjacencies + const adjacencies = []; + const faceNormals = []; + let index; + let faceAdjacencies; + // Prepare faces + for (index = 0; index < indices.length; index += 3) { + faceAdjacencies = new FaceAdjacencies(); + const p0Index = indices[index]; + const p1Index = indices[index + 1]; + const p2Index = indices[index + 2]; + faceAdjacencies.p0 = new Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]); + faceAdjacencies.p1 = new Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]); + faceAdjacencies.p2 = new Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]); + const faceNormal = Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1)); + faceNormal.normalize(); + faceNormals.push(faceNormal); + adjacencies.push(faceAdjacencies); + } + // Scan + for (index = 0; index < adjacencies.length; index++) { + faceAdjacencies = adjacencies[index]; + for (let otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) { + const otherFaceAdjacencies = adjacencies[otherIndex]; + if (faceAdjacencies.edgesConnectedCount === 3) { + // Full + break; + } + if (otherFaceAdjacencies.edgesConnectedCount === 3) { + // Full + continue; + } + const otherP0 = indices[otherIndex * 3]; + const otherP1 = indices[otherIndex * 3 + 1]; + const otherP2 = indices[otherIndex * 3 + 2]; + for (let edgeIndex = 0; edgeIndex < 3; edgeIndex++) { + let otherEdgeIndex = 0; + if (faceAdjacencies.edges[edgeIndex] !== undefined) { + continue; + } + switch (edgeIndex) { + case 0: + if (this._checkVerticesInsteadOfIndices) { + otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2); + } + else { + otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2); + } + break; + case 1: + if (this._checkVerticesInsteadOfIndices) { + otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2); + } + else { + otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2); + } + break; + case 2: + if (this._checkVerticesInsteadOfIndices) { + otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2); + } + else { + otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2); + } + break; + } + if (otherEdgeIndex === -1) { + continue; + } + faceAdjacencies.edges[edgeIndex] = otherIndex; + otherFaceAdjacencies.edges[otherEdgeIndex] = index; + faceAdjacencies.edgesConnectedCount++; + otherFaceAdjacencies.edgesConnectedCount++; + if (faceAdjacencies.edgesConnectedCount === 3) { + break; + } + } + } + } + // Create lines + for (index = 0; index < adjacencies.length; index++) { + // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon + const current = adjacencies[index]; + this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1); + this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2); + this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0); + } + // Merge into a single mesh + const engine = this._source.getScene().getEngine(); + this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, this._linesPositions, VertexBuffer.PositionKind, false); + this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine, this._linesNormals, VertexBuffer.NormalKind, false, false, 4); + this._buffersForInstances[VertexBuffer.PositionKind] = this._buffers[VertexBuffer.PositionKind]; + this._buffersForInstances[VertexBuffer.NormalKind] = this._buffers[VertexBuffer.NormalKind]; + this._ib = engine.createIndexBuffer(this._linesIndices); + this._indicesCount = this._linesIndices.length; + } + /** + * Checks whether or not the edges renderer is ready to render. + * @returns true if ready, otherwise false. + */ + isReady() { + return this._lineShader.isReady(this._source, (this._source.hasInstances && this.customInstances.length > 0) || this._source.hasThinInstances); + } + /** + * Renders the edges of the attached mesh, + */ + render() { + const scene = this._source.getScene(); + const currentDrawWrapper = this._lineShader._getDrawWrapper(); + if (this._drawWrapper) { + this._lineShader._setDrawWrapper(this._drawWrapper); + } + if (!this.isReady() || !scene.activeCamera) { + this._lineShader._setDrawWrapper(currentDrawWrapper); + return; + } + const hasInstances = this._source.hasInstances && this.customInstances.length > 0; + const useBuffersWithInstances = hasInstances || this._source.hasThinInstances; + let instanceCount = 0; + if (useBuffersWithInstances) { + this._buffersForInstances["world0"] = this._source.getVertexBuffer("world0"); + this._buffersForInstances["world1"] = this._source.getVertexBuffer("world1"); + this._buffersForInstances["world2"] = this._source.getVertexBuffer("world2"); + this._buffersForInstances["world3"] = this._source.getVertexBuffer("world3"); + if (hasInstances) { + const instanceStorage = this._source._instanceDataStorage; + instanceCount = this.customInstances.length; + if (!instanceStorage.instancesData) { + if (!this._source.getScene()._activeMeshesFrozen) { + this.customInstances.reset(); + } + return; + } + if (!instanceStorage.isFrozen) { + let offset = 0; + for (let i = 0; i < instanceCount; ++i) { + this.customInstances.data[i].copyToArray(instanceStorage.instancesData, offset); + offset += 16; + } + instanceStorage.instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instanceCount); + } + } + else { + instanceCount = this._source.thinInstanceCount; + } + } + const engine = scene.getEngine(); + this._lineShader._preBind(); + if (this._source.edgesColor.a !== 1) { + engine.setAlphaMode(2); + } + else { + engine.setAlphaMode(0); + } + // VBOs + engine.bindBuffers(useBuffersWithInstances ? this._buffersForInstances : this._buffers, this._ib, this._lineShader.getEffect()); + scene.resetCachedMaterial(); + this._lineShader.setColor4("color", this._source.edgesColor); + if (scene.activeCamera.mode === Camera.ORTHOGRAPHIC_CAMERA) { + this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic); + } + else { + this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective); + } + this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera)); + this._lineShader.bind(this._source.getWorldMatrix(), this._source); + // Draw order + engine.drawElementsType(Material.TriangleFillMode, 0, this._indicesCount, instanceCount); + this._lineShader.unbind(); + if (useBuffersWithInstances) { + engine.unbindInstanceAttributes(); + } + if (!this._source.getScene()._activeMeshesFrozen) { + this.customInstances.reset(); + } + this._lineShader._setDrawWrapper(currentDrawWrapper); + } +} +/** + * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation + */ +class LineEdgesRenderer extends EdgesRenderer { + /** + * This constructor turns off auto generating edges line in Edges Renderer to make it here. + * @param source LineMesh used to generate edges + * @param epsilon not important (specified angle for edge detection) + * @param checkVerticesInsteadOfIndices not important for LineMesh + */ + constructor(source, epsilon = 0.95, checkVerticesInsteadOfIndices = false) { + super(source, epsilon, checkVerticesInsteadOfIndices, false); + this._generateEdgesLines(); + } + /** + * Generate edges for each line in LinesMesh. Every Line should be rendered as edge. + */ + _generateEdgesLines() { + const positions = this._source.getVerticesData(VertexBuffer.PositionKind); + const indices = this._source.getIndices(); + if (!indices || !positions) { + return; + } + const p0 = TmpVectors.Vector3[0]; + const p1 = TmpVectors.Vector3[1]; + const len = indices.length - 1; + for (let i = 0, offset = 0; i < len; i += 2, offset += 4) { + Vector3.FromArrayToRef(positions, 3 * indices[i], p0); + Vector3.FromArrayToRef(positions, 3 * indices[i + 1], p1); + this.createLine(p0, p1, offset); + } + // Merge into a single mesh + const engine = this._source.getScene().getEngine(); + this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, this._linesPositions, VertexBuffer.PositionKind, false); + this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine, this._linesNormals, VertexBuffer.NormalKind, false, false, 4); + this._ib = engine.createIndexBuffer(this._linesIndices); + this._indicesCount = this._linesIndices.length; + } +} + +Object.defineProperty(Scene.prototype, "iblCdfGenerator", { + get: function () { + return this._iblCdfGenerator; + }, + set: function (value) { + if (value) { + this._iblCdfGenerator = value; + } + }, + enumerable: true, + configurable: true, +}); +Scene.prototype.enableIblCdfGenerator = function () { + if (this._iblCdfGenerator) { + return this._iblCdfGenerator; + } + this._iblCdfGenerator = new IblCdfGenerator(this); + if (this.environmentTexture) { + this._iblCdfGenerator.iblSource = this.environmentTexture; + } + return this._iblCdfGenerator; +}; +Scene.prototype.disableIblCdfGenerator = function () { + if (!this._iblCdfGenerator) { + return; + } + this._iblCdfGenerator.dispose(); + this._iblCdfGenerator = null; +}; +/** + * Defines the IBL CDF Generator scene component responsible for generating CDF maps for a given IBL. + */ +class IblCdfGeneratorSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_IBLCDFGENERATOR; + this._newIblObserver = null; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + this._updateIblSource(); + this._newIblObserver = this.scene.onEnvironmentTextureChangedObservable.add(this._updateIblSource.bind(this)); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do for this component + } + /** + * Disposes the component and the associated resources + */ + dispose() { + this.scene.onEnvironmentTextureChangedObservable.remove(this._newIblObserver); + } + _updateIblSource() { + if (this.scene.iblCdfGenerator && this.scene.environmentTexture) { + this.scene.iblCdfGenerator.iblSource = this.scene.environmentTexture; + } + } +} +IblCdfGenerator._SceneComponentInitialization = (scene) => { + // Register the CDF generator component to the scene. + let component = scene._getComponent(SceneComponentConstants.NAME_IBLCDFGENERATOR); + if (!component) { + component = new IblCdfGeneratorSceneComponent(scene); + scene._addComponent(component); + } +}; + +/** + * @internal + */ +class MaterialIBLShadowsRenderDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.RENDER_WITH_IBL_SHADOWS = false; + this.COLORED_IBL_SHADOWS = false; + } +} +/** + * Plugin used to render the contribution from IBL shadows. + */ +class IBLShadowsPluginMaterial extends MaterialPluginBase { + get isColored() { + return this._isColored; + } + set isColored(value) { + if (this._isColored === value) { + return; + } + this._isColored = value; + this._markAllSubMeshesAsTexturesDirty(); + } + _markAllSubMeshesAsTexturesDirty() { + this._enable(this._isEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a give shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + constructor(material) { + super(material, IBLShadowsPluginMaterial.Name, 310, new MaterialIBLShadowsRenderDefines()); + /** + * The opacity of the shadows. + */ + this.shadowOpacity = 1.0; + this._isEnabled = false; + this._isColored = false; + /** + * Defines if the plugin is enabled in the material. + */ + this.isEnabled = false; + this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; + } + prepareDefines(defines) { + defines.RENDER_WITH_IBL_SHADOWS = this._isEnabled; + defines.COLORED_IBL_SHADOWS = this.isColored; + } + getClassName() { + return "IBLShadowsPluginMaterial"; + } + getUniforms() { + return { + ubo: [ + { name: "renderTargetSize", size: 2, type: "vec2" }, + { name: "shadowOpacity", size: 1, type: "float" }, + ], + fragment: `#ifdef RENDER_WITH_IBL_SHADOWS + uniform vec2 renderTargetSize; + uniform float shadowOpacity; + #endif`, + }; + } + getSamplers(samplers) { + samplers.push("iblShadowsTexture"); + } + bindForSubMesh(uniformBuffer) { + if (this._isEnabled) { + uniformBuffer.bindTexture("iblShadowsTexture", this.iblShadowsTexture); + uniformBuffer.updateFloat2("renderTargetSize", this._material.getScene().getEngine().getRenderWidth(), this._material.getScene().getEngine().getRenderHeight()); + uniformBuffer.updateFloat("shadowOpacity", this.shadowOpacity); + } + } + getCustomCode(shaderType, shaderLanguage) { + let frag; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + frag = { + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_DEFINITIONS: ` + #ifdef RENDER_WITH_IBL_SHADOWS + var iblShadowsTextureSampler: sampler; + var iblShadowsTexture: texture_2d; + + #ifdef COLORED_IBL_SHADOWS + fn computeIndirectShadow() -> vec3f { + var uv = fragmentInputs.position.xy / uniforms.renderTargetSize; + var shadowValue: vec3f = textureSample(iblShadowsTexture, iblShadowsTextureSampler, uv).rgb; + return mix(shadowValue, vec3f(1.0), 1.0 - uniforms.shadowOpacity); + } + #else + fn computeIndirectShadow() -> vec2f { + var uv = fragmentInputs.position.xy / uniforms.renderTargetSize; + var shadowValue: vec2f = textureSample(iblShadowsTexture, iblShadowsTextureSampler, uv).rg; + return mix(shadowValue, vec2f(1.0), 1.0 - uniforms.shadowOpacity); + } + #endif + #endif + `, + }; + if (this._material instanceof PBRBaseMaterial) { + // eslint-disable-next-line @typescript-eslint/naming-convention + frag["CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION"] = ` + #ifdef RENDER_WITH_IBL_SHADOWS + #ifndef UNLIT + #ifdef REFLECTION + #ifdef COLORED_IBL_SHADOWS + var shadowValue: vec3f = computeIndirectShadow(); + finalIrradiance *= shadowValue; + finalRadianceScaled *= mix(vec3f(1.0), shadowValue, roughness); + #else + var shadowValue: vec2f = computeIndirectShadow(); + finalIrradiance *= vec3f(shadowValue.x); + finalRadianceScaled *= vec3f(mix(pow(shadowValue.y, 4.0), shadowValue.x, roughness)); + #endif + #endif + #else + finalDiffuse *= computeIndirectShadow().x; + #endif + #endif + `; + } + else { + frag["CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR"] = ` + #ifdef RENDER_WITH_IBL_SHADOWS + #ifdef COLORED_IBL_SHADOWS + var shadowValue: vec3f = computeIndirectShadow(); + color *= toGammaSpace(vec4f(shadowValue, 1.0f)); + #else + var shadowValue: vec2f = computeIndirectShadow(); + color *= toGammaSpace(vec4f(shadowValue.x, shadowValue.x, shadowValue.x, 1.0f)); + #endif + #endif + `; + } + } + else { + frag = { + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_DEFINITIONS: ` + #ifdef RENDER_WITH_IBL_SHADOWS + uniform sampler2D iblShadowsTexture; + #ifdef COLORED_IBL_SHADOWS + vec3 computeIndirectShadow() { + vec2 uv = gl_FragCoord.xy / renderTargetSize; + vec3 shadowValue = texture2D(iblShadowsTexture, uv).rgb; + return mix(shadowValue.rgb, vec3(1.0), 1.0 - shadowOpacity); + } + #else + vec2 computeIndirectShadow() { + vec2 uv = gl_FragCoord.xy / renderTargetSize; + vec2 shadowValue = texture2D(iblShadowsTexture, uv).rg; + return mix(shadowValue.rg, vec2(1.0), 1.0 - shadowOpacity); + } + #endif + #endif + `, + }; + if (this._material instanceof PBRBaseMaterial) { + // eslint-disable-next-line @typescript-eslint/naming-convention + frag["CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION"] = ` + #ifdef RENDER_WITH_IBL_SHADOWS + #ifndef UNLIT + #ifdef REFLECTION + #ifdef COLORED_IBL_SHADOWS + vec3 shadowValue = computeIndirectShadow(); + finalIrradiance.rgb *= shadowValue.rgb; + finalRadianceScaled *= mix(vec3(1.0), shadowValue.rgb, roughness); + #else + vec2 shadowValue = computeIndirectShadow(); + finalIrradiance *= shadowValue.x; + finalRadianceScaled *= mix(pow(shadowValue.y, 4.0), shadowValue.x, roughness); + #endif + #endif + #else + finalDiffuse *= computeIndirectShadow().x; + #endif + #endif + `; + } + else { + frag["CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR"] = ` + #ifdef RENDER_WITH_IBL_SHADOWS + #ifdef COLORED_IBL_SHADOWS + vec3 shadowValue = computeIndirectShadow(); + color.rgb *= toGammaSpace(shadowValue.rgb); + #else + vec2 shadowValue = computeIndirectShadow(); + color.rgb *= toGammaSpace(shadowValue.x); + #endif + #endif + `; + } + } + return shaderType === "vertex" ? null : frag; + } +} +/** + * Defines the name of the plugin. + */ +IBLShadowsPluginMaterial.Name = "IBLShadowsPluginMaterial"; +__decorate([ + serialize() +], IBLShadowsPluginMaterial.prototype, "iblShadowsTexture", void 0); +__decorate([ + serialize() +], IBLShadowsPluginMaterial.prototype, "shadowOpacity", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], IBLShadowsPluginMaterial.prototype, "isEnabled", void 0); +RegisterClass(`BABYLON.IBLShadowsPluginMaterial`, IBLShadowsPluginMaterial); + +/** + * A multi render target designed to render the prepass. + * Prepass is a scene component used to render information in multiple textures + * alongside with the scene materials rendering. + * Note : This is an internal class, and you should NOT need to instanciate this. + * Only the `PrePassRenderer` should instanciate this class. + * It is more likely that you need a regular `MultiRenderTarget` + * @internal + */ +class PrePassRenderTarget extends MultiRenderTarget { + constructor(name, renderTargetTexture, size, count, scene, options) { + super(name, size, count, scene, options); + /** + * @internal + */ + this._beforeCompositionPostProcesses = []; + /** + * @internal + */ + this._internalTextureDirty = false; + /** + * Is this render target enabled for prepass rendering + */ + this.enabled = false; + /** + * Render target associated with this prePassRenderTarget + * If this is `null`, it means this prePassRenderTarget is associated with the scene + */ + this.renderTargetTexture = null; + this.renderTargetTexture = renderTargetTexture; + } + /** + * Creates a composition effect for this RT + * @internal + */ + _createCompositionEffect() { + this.imageProcessingPostProcess = new ImageProcessingPostProcess("prePassComposition", 1, null, undefined, this._engine); + this.imageProcessingPostProcess._updateParameters(); + } + /** + * Checks that the size of this RT is still adapted to the desired render size. + * @internal + */ + _checkSize() { + const requiredWidth = this._engine.getRenderWidth(true); + const requiredHeight = this._engine.getRenderHeight(true); + const width = this.getRenderWidth(); + const height = this.getRenderHeight(); + if (width !== requiredWidth || height !== requiredHeight) { + this.resize({ width: requiredWidth, height: requiredHeight }); + this._internalTextureDirty = true; + } + } + /** + * Changes the number of render targets in this MRT + * Be careful as it will recreate all the data in the new texture. + * @param count new texture count + * @param options Specifies texture types and sampling modes for new textures + * @param textureNames Specifies the names of the textures (optional) + */ + updateCount(count, options, textureNames) { + super.updateCount(count, options, textureNames); + this._internalTextureDirty = true; + } + /** + * Resets the post processes chains applied to this RT. + * @internal + */ + _resetPostProcessChain() { + this._beforeCompositionPostProcesses.length = 0; + } + /** + * Diposes this render target + */ + dispose() { + const scene = this._scene; + super.dispose(); + if (scene && scene.prePassRenderer) { + const index = scene.prePassRenderer.renderTargets.indexOf(this); + if (index !== -1) { + scene.prePassRenderer.renderTargets.splice(index, 1); + } + } + if (this.imageProcessingPostProcess) { + this.imageProcessingPostProcess.dispose(); + } + if (this.renderTargetTexture) { + this.renderTargetTexture._prePassRenderTarget = null; + } + if (this._outputPostProcess) { + this._outputPostProcess.autoClear = true; + this._outputPostProcess.restoreDefaultInputTexture(); + } + } +} + +/** + * Renders a pre pass of the scene + * This means every mesh in the scene will be rendered to a render target texture + * And then this texture will be composited to the rendering canvas with post processes + * It is necessary for effects like subsurface scattering or deferred shading + */ +class PrePassRenderer { + /** + * Indicates if the prepass renderer is generating normals in world space or camera space (default: camera space) + */ + get generateNormalsInWorldSpace() { + return this._generateNormalsInWorldSpace; + } + set generateNormalsInWorldSpace(value) { + if (this._generateNormalsInWorldSpace === value) { + return; + } + this._generateNormalsInWorldSpace = value; + this._markAllMaterialsAsPrePassDirty(); + } + /** + * Returns the index of a texture in the multi render target texture array. + * @param type Texture type + * @returns The index + */ + getIndex(type) { + return this._textureIndices[type]; + } + /** + * How many samples are used for MSAA of the scene render target + */ + get samples() { + return this.defaultRT.samples; + } + set samples(n) { + this.defaultRT.samples = n; + } + /** + * If set to true (default: false), the depth texture will be cleared with the depth value corresponding to the far plane (1 in normal mode, 0 in reverse depth buffer mode) + * If set to false, the depth texture is always cleared with 0. + */ + get useSpecificClearForDepthTexture() { + return this._useSpecificClearForDepthTexture; + } + set useSpecificClearForDepthTexture(value) { + if (this._useSpecificClearForDepthTexture === value) { + return; + } + this._useSpecificClearForDepthTexture = value; + this._isDirty = true; + } + /** + * @returns the prepass render target for the rendering pass. + * If we are currently rendering a render target, it returns the PrePassRenderTarget + * associated with that render target. Otherwise, it returns the scene default PrePassRenderTarget + */ + getRenderTarget() { + return this._currentTarget; + } + /** + * @internal + * Managed by the scene component + * @param prePassRenderTarget + */ + _setRenderTarget(prePassRenderTarget) { + if (prePassRenderTarget) { + this._currentTarget = prePassRenderTarget; + } + else { + this._currentTarget = this.defaultRT; + this._engine.currentRenderPassId = this._scene.activeCamera?.renderPassId ?? this._currentTarget.renderPassId; + } + } + /** + * Returns true if the currently rendered prePassRenderTarget is the one + * associated with the scene. + */ + get currentRTisSceneRT() { + return this._currentTarget === this.defaultRT; + } + _refreshGeometryBufferRendererLink() { + if (!this.doNotUseGeometryRendererFallback) { + this._geometryBuffer = this._scene.enableGeometryBufferRenderer(); + if (!this._geometryBuffer) { + // Not supported + this.doNotUseGeometryRendererFallback = true; + return; + } + this._geometryBuffer._linkPrePassRenderer(this); + } + else { + if (this._geometryBuffer) { + this._geometryBuffer._unlinkPrePassRenderer(); + } + this._geometryBuffer = null; + this._scene.disableGeometryBufferRenderer(); + } + } + /** + * Indicates if the prepass is enabled + */ + get enabled() { + return this._enabled; + } + /** + * Instantiates a prepass renderer + * @param scene The scene + */ + constructor(scene) { + /** + * To save performance, we can excluded skinned meshes from the prepass + */ + this.excludedSkinnedMesh = []; + /** + * Force material to be excluded from the prepass + * Can be useful when `useGeometryBufferFallback` is set to `true` + * and you don't want a material to show in the effect. + */ + this.excludedMaterials = []; + /** + * Number of textures in the multi render target texture where the scene is directly rendered + */ + this.mrtCount = 0; + this._mrtTypes = []; + this._mrtFormats = []; + this._mrtLayout = []; + this._mrtNames = []; + this._textureIndices = []; + this._generateNormalsInWorldSpace = false; + this._useSpecificClearForDepthTexture = false; + this._isDirty = true; + /** + * Configuration for prepass effects + */ + this._effectConfigurations = []; + /** + * Prevents the PrePassRenderer from using the GeometryBufferRenderer as a fallback + */ + this.doNotUseGeometryRendererFallback = true; + /** + * All the render targets generated by prepass + */ + this.renderTargets = []; + this._clearColor = new Color4(0, 0, 0, 0); + this._clearDepthColor = new Color4(1e8, 0, 0, 1); // "infinity" value - depth in the depth texture is view.z, not a 0..1 value! + this._enabled = false; + this._needsCompositionForThisPass = false; + /** + * Set to true to disable gamma transform in PrePass. + * Can be useful in case you already proceed to gamma transform on a material level + * and your post processes don't need to be in linear color space. + */ + this.disableGammaTransform = false; + this._scene = scene; + this._engine = scene.getEngine(); + let type = 0; + if (this._engine._caps.textureFloat && this._engine._caps.textureFloatLinearFiltering) { + type = 1; + } + else if (this._engine._caps.textureHalfFloat && this._engine._caps.textureHalfFloatLinearFiltering) { + type = 2; + } + for (let i = 0; i < PrePassRenderer.TextureFormats.length; ++i) { + const format = PrePassRenderer.TextureFormats[i].format; + if (PrePassRenderer.TextureFormats[i].type === 1) { + PrePassRenderer.TextureFormats[i].type = type; + if (type === 1 && + (format === 6 || format === 7 || format === 5) && + !this._engine._caps.supportFloatTexturesResolve) { + // We don't know in advance if the texture will be used as a resolve target, so we revert to half_float if the extension to resolve full float textures is not supported + PrePassRenderer.TextureFormats[i].type = 2; + } + } + } + PrePassRenderer._SceneComponentInitialization(this._scene); + this.defaultRT = this._createRenderTarget("sceneprePassRT", null); + this._currentTarget = this.defaultRT; + } + /** + * Creates a new PrePassRenderTarget + * This should be the only way to instantiate a `PrePassRenderTarget` + * @param name Name of the `PrePassRenderTarget` + * @param renderTargetTexture RenderTarget the `PrePassRenderTarget` will be attached to. + * Can be `null` if the created `PrePassRenderTarget` is attached to the scene (default framebuffer). + * @internal + */ + _createRenderTarget(name, renderTargetTexture) { + const rt = new PrePassRenderTarget(name, renderTargetTexture, { width: this._engine.getRenderWidth(), height: this._engine.getRenderHeight() }, 0, this._scene, { + generateMipMaps: false, + generateStencilBuffer: this._engine.isStencilEnable, + defaultType: 0, + types: [], + drawOnlyOnFirstAttachmentByDefault: true, + }); + this.renderTargets.push(rt); + if (this._enabled) { + // The pre-pass renderer is already enabled, so make sure we create the render target with the correct number of textures + this._update(); + } + return rt; + } + /** + * Indicates if rendering a prepass is supported + */ + get isSupported() { + return this._scene.getEngine().getCaps().drawBuffersExtension; + } + /** + * Sets the proper output textures to draw in the engine. + * @param effect The effect that is drawn. It can be or not be compatible with drawing to several output textures. + * @param subMesh Submesh on which the effect is applied + */ + bindAttachmentsForEffect(effect, subMesh) { + const material = subMesh.getMaterial(); + const isPrePassCapable = material && material.isPrePassCapable; + const excluded = material && this.excludedMaterials.indexOf(material) !== -1; + if (this.enabled && this._currentTarget.enabled) { + if (effect._multiTarget && isPrePassCapable && !excluded) { + this._engine.bindAttachments(this._multiRenderAttachments); + } + else { + if (this._engine._currentRenderTarget) { + this._engine.bindAttachments(this._defaultAttachments); + } + else { + this._engine.restoreSingleAttachment(); + } + if (this._geometryBuffer && this.currentRTisSceneRT && !excluded) { + this._geometryBuffer.renderList.push(subMesh.getRenderingMesh()); + } + } + } + } + _reinitializeAttachments() { + const multiRenderLayout = []; + const clearLayout = [false]; + const clearDepthLayout = [false]; + const defaultLayout = [true]; + for (let i = 0; i < this.mrtCount; i++) { + multiRenderLayout.push(true); + if (i > 0) { + if (this._useSpecificClearForDepthTexture && this._mrtLayout[i] === 5) { + clearLayout.push(false); + clearDepthLayout.push(true); + } + else { + clearLayout.push(true); + clearDepthLayout.push(false); + } + defaultLayout.push(false); + } + } + this._multiRenderAttachments = this._engine.buildTextureLayout(multiRenderLayout); + this._clearAttachments = this._engine.buildTextureLayout(clearLayout); + this._clearDepthAttachments = this._engine.buildTextureLayout(clearDepthLayout); + this._defaultAttachments = this._engine.buildTextureLayout(defaultLayout); + } + _resetLayout() { + for (let i = 0; i < PrePassRenderer.TextureFormats.length; i++) { + this._textureIndices[PrePassRenderer.TextureFormats[i].purpose] = -1; + } + this._textureIndices[4] = 0; + this._mrtLayout = [4]; + this._mrtTypes = [PrePassRenderer.TextureFormats[4].type]; + this._mrtFormats = [PrePassRenderer.TextureFormats[4].format]; + this._mrtNames = [PrePassRenderer.TextureFormats[4].name]; + this.mrtCount = 1; + } + _updateGeometryBufferLayout() { + this._refreshGeometryBufferRendererLink(); + if (this._geometryBuffer) { + this._geometryBuffer._resetLayout(); + const texturesActivated = []; + for (let i = 0; i < this._mrtLayout.length; i++) { + texturesActivated.push(false); + } + this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture()); + const matches = [ + { + prePassConstant: 5, + geometryBufferConstant: GeometryBufferRenderer.DEPTH_TEXTURE_TYPE, + }, + { + prePassConstant: 6, + geometryBufferConstant: GeometryBufferRenderer.NORMAL_TEXTURE_TYPE, + }, + { + prePassConstant: 1, + geometryBufferConstant: GeometryBufferRenderer.POSITION_TEXTURE_TYPE, + }, + { + prePassConstant: 3, + geometryBufferConstant: GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE, + }, + { + prePassConstant: 2, + geometryBufferConstant: GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE, + }, + ]; + // replace textures in the geometryBuffer RT + for (let i = 0; i < matches.length; i++) { + const index = this._mrtLayout.indexOf(matches[i].prePassConstant); + if (index !== -1) { + this._geometryBuffer._forceTextureType(matches[i].geometryBufferConstant, index); + texturesActivated[index] = true; + } + } + this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(texturesActivated)); + } + } + /** + * Restores attachments for single texture draw. + */ + restoreAttachments() { + if (this.enabled && this._currentTarget.enabled && this._defaultAttachments) { + if (this._engine._currentRenderTarget) { + this._engine.bindAttachments(this._defaultAttachments); + } + else { + this._engine.restoreSingleAttachment(); + } + } + } + /** + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _beforeDraw(camera, faceIndex, layer) { + // const previousEnabled = this._enabled && this._currentTarget.enabled; + if (this._isDirty) { + this._update(); + } + if (!this._enabled || !this._currentTarget.enabled) { + return; + } + if (this._geometryBuffer) { + this._geometryBuffer.renderList = []; + } + this._setupOutputForThisPass(this._currentTarget, camera); + } + _prepareFrame(prePassRenderTarget, faceIndex, layer) { + if (prePassRenderTarget.renderTargetTexture) { + prePassRenderTarget.renderTargetTexture._prepareFrame(this._scene, faceIndex, layer, prePassRenderTarget.renderTargetTexture.useCameraPostProcesses); + } + else if (this._postProcessesSourceForThisPass.length) { + this._scene.postProcessManager._prepareFrame(); + } + else { + this._engine.restoreDefaultFramebuffer(); + } + } + /** + * Sets an intermediary texture between prepass and postprocesses. This texture + * will be used as input for post processes + * @param rt The render target texture to use + * @returns true if there are postprocesses that will use this texture, + * false if there is no postprocesses - and the function has no effect + */ + setCustomOutput(rt) { + const firstPP = this._postProcessesSourceForThisPass[0]; + if (!firstPP) { + return false; + } + firstPP.inputTexture = rt.renderTarget; + return true; + } + _renderPostProcesses(prePassRenderTarget, faceIndex) { + const firstPP = this._postProcessesSourceForThisPass[0]; + const outputTexture = firstPP ? firstPP.inputTexture : prePassRenderTarget.renderTargetTexture ? prePassRenderTarget.renderTargetTexture.renderTarget : null; + // Build post process chain for this prepass post draw + let postProcessChain = this._currentTarget._beforeCompositionPostProcesses; + if (this._needsCompositionForThisPass) { + postProcessChain = postProcessChain.concat([this._currentTarget.imageProcessingPostProcess]); + } + // Activates and renders the chain + if (postProcessChain.length) { + this._scene.postProcessManager._prepareFrame(this._currentTarget.renderTarget?.texture, postProcessChain); + this._scene.postProcessManager.directRender(postProcessChain, outputTexture, false, faceIndex); + } + } + /** + * @internal + */ + _afterDraw(faceIndex, layer) { + if (this._enabled && this._currentTarget.enabled) { + this._prepareFrame(this._currentTarget, faceIndex, layer); + this._renderPostProcesses(this._currentTarget, faceIndex); + } + } + /** + * Clears the current prepass render target (in the sense of settings pixels to the scene clear color value) + * @internal + */ + _clear() { + if (this._isDirty) { + this._update(); + } + if (this._enabled && this._currentTarget.enabled) { + this._bindFrameBuffer(); + // Clearing other attachment with 0 on all other attachments + this._engine.bindAttachments(this._clearAttachments); + this._engine.clear(this._clearColor, true, false, false); + if (this._useSpecificClearForDepthTexture) { + this._engine.bindAttachments(this._clearDepthAttachments); + this._engine.clear(this._clearDepthColor, true, false, false); + } + // Regular clear color with the scene clear color of the 1st attachment + this._engine.bindAttachments(this._defaultAttachments); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _bindFrameBuffer() { + if (this._enabled && this._currentTarget.enabled) { + this._currentTarget._checkSize(); + const internalTexture = this._currentTarget.renderTarget; + if (internalTexture) { + this._engine.bindFramebuffer(internalTexture); + } + } + } + _setEnabled(enabled) { + this._enabled = enabled; + } + _setRenderTargetEnabled(prePassRenderTarget, enabled) { + prePassRenderTarget.enabled = enabled; + if (!enabled) { + this._unlinkInternalTexture(prePassRenderTarget); + } + } + /** + * Adds an effect configuration to the prepass render target. + * If an effect has already been added, it won't add it twice and will return the configuration + * already present. + * @param cfg the effect configuration + * @returns the effect configuration now used by the prepass + */ + addEffectConfiguration(cfg) { + // Do not add twice + for (let i = 0; i < this._effectConfigurations.length; i++) { + if (this._effectConfigurations[i].name === cfg.name) { + return this._effectConfigurations[i]; + } + } + this._effectConfigurations.push(cfg); + return cfg; + } + /** + * Retrieves an effect configuration by name + * @param name the name of the effect configuration + * @returns the effect configuration, or null if not present + */ + getEffectConfiguration(name) { + for (let i = 0; i < this._effectConfigurations.length; i++) { + if (this._effectConfigurations[i].name === name) { + return this._effectConfigurations[i]; + } + } + return null; + } + _enable() { + const previousMrtCount = this.mrtCount; + for (let i = 0; i < this._effectConfigurations.length; i++) { + if (this._effectConfigurations[i].enabled) { + this._enableTextures(this._effectConfigurations[i].texturesRequired); + } + } + for (let i = 0; i < this.renderTargets.length; i++) { + if (this.mrtCount !== previousMrtCount || this.renderTargets[i].count !== this.mrtCount) { + this.renderTargets[i].updateCount(this.mrtCount, { types: this._mrtTypes, formats: this._mrtFormats }, this._mrtNames.concat("prePass_DepthBuffer")); + } + this.renderTargets[i]._resetPostProcessChain(); + for (let j = 0; j < this._effectConfigurations.length; j++) { + if (this._effectConfigurations[j].enabled) { + // TODO : subsurface scattering has 1 scene-wide effect configuration + // solution : do not stock postProcess on effectConfiguration, but in the prepassRenderTarget (hashmap configuration => postProcess) + // And call createPostProcess whenever the post process does not exist in the RT + if (!this._effectConfigurations[j].postProcess && this._effectConfigurations[j].createPostProcess) { + this._effectConfigurations[j].createPostProcess(); + } + if (this._effectConfigurations[j].postProcess) { + this.renderTargets[i]._beforeCompositionPostProcesses.push(this._effectConfigurations[j].postProcess); + } + } + } + } + this._reinitializeAttachments(); + this._setEnabled(true); + this._updateGeometryBufferLayout(); + } + _disable() { + this._setEnabled(false); + for (let i = 0; i < this.renderTargets.length; i++) { + this._setRenderTargetEnabled(this.renderTargets[i], false); + } + this._resetLayout(); + for (let i = 0; i < this._effectConfigurations.length; i++) { + this._effectConfigurations[i].enabled = false; + } + } + _getPostProcessesSource(prePassRenderTarget, camera) { + if (camera) { + return camera._postProcesses; + } + else if (prePassRenderTarget.renderTargetTexture) { + if (prePassRenderTarget.renderTargetTexture.useCameraPostProcesses) { + const camera = prePassRenderTarget.renderTargetTexture.activeCamera ? prePassRenderTarget.renderTargetTexture.activeCamera : this._scene.activeCamera; + return camera ? camera._postProcesses : []; + } + else if (prePassRenderTarget.renderTargetTexture.postProcesses) { + return prePassRenderTarget.renderTargetTexture.postProcesses; + } + else { + return []; + } + } + else { + return this._scene.activeCamera ? this._scene.activeCamera._postProcesses : []; + } + } + _setupOutputForThisPass(prePassRenderTarget, camera) { + // Order is : draw ===> prePassRenderTarget._postProcesses ==> ipp ==> camera._postProcesses + const secondaryCamera = camera && this._scene.activeCameras && !!this._scene.activeCameras.length && this._scene.activeCameras.indexOf(camera) !== 0; + this._postProcessesSourceForThisPass = this._getPostProcessesSource(prePassRenderTarget, camera); + this._postProcessesSourceForThisPass = this._postProcessesSourceForThisPass.filter((pp) => { + return pp != null; + }); + this._scene.autoClear = true; + const cameraHasImageProcessing = this._hasImageProcessing(this._postProcessesSourceForThisPass); + this._needsCompositionForThisPass = !cameraHasImageProcessing && !this.disableGammaTransform && this._needsImageProcessing() && !secondaryCamera; + const firstCameraPP = this._getFirstPostProcess(this._postProcessesSourceForThisPass); + const firstPrePassPP = prePassRenderTarget._beforeCompositionPostProcesses && prePassRenderTarget._beforeCompositionPostProcesses[0]; + let firstPP = null; + // Setting the scene-wide post process configuration + this._scene.imageProcessingConfiguration.applyByPostProcess = this._needsCompositionForThisPass || cameraHasImageProcessing; + // Create composition effect if needed + if (this._needsCompositionForThisPass && !prePassRenderTarget.imageProcessingPostProcess) { + prePassRenderTarget._createCompositionEffect(); + } + // Setting the prePassRenderTarget as input texture of the first PP + if (firstPrePassPP) { + firstPP = firstPrePassPP; + } + else if (this._needsCompositionForThisPass) { + firstPP = prePassRenderTarget.imageProcessingPostProcess; + } + else if (firstCameraPP) { + firstPP = firstCameraPP; + } + this._bindFrameBuffer(); + this._linkInternalTexture(prePassRenderTarget, firstPP); + } + _linkInternalTexture(prePassRenderTarget, postProcess) { + if (postProcess) { + postProcess.autoClear = false; + postProcess.inputTexture = prePassRenderTarget.renderTarget; + } + if (prePassRenderTarget._outputPostProcess !== postProcess) { + if (prePassRenderTarget._outputPostProcess) { + this._unlinkInternalTexture(prePassRenderTarget); + } + prePassRenderTarget._outputPostProcess = postProcess; + } + if (prePassRenderTarget._internalTextureDirty) { + this._updateGeometryBufferLayout(); + prePassRenderTarget._internalTextureDirty = false; + } + } + /** + * @internal + */ + _unlinkInternalTexture(prePassRenderTarget) { + if (prePassRenderTarget._outputPostProcess) { + prePassRenderTarget._outputPostProcess.autoClear = true; + prePassRenderTarget._outputPostProcess.restoreDefaultInputTexture(); + prePassRenderTarget._outputPostProcess = null; + } + } + _needsImageProcessing() { + for (let i = 0; i < this._effectConfigurations.length; i++) { + if (this._effectConfigurations[i].enabled && this._effectConfigurations[i].needsImageProcessing) { + return true; + } + } + return false; + } + _hasImageProcessing(postProcesses) { + let isIPPAlreadyPresent = false; + if (postProcesses) { + for (let i = 0; i < postProcesses.length; i++) { + if (postProcesses[i]?.getClassName() === "ImageProcessingPostProcess") { + isIPPAlreadyPresent = true; + break; + } + } + } + return isIPPAlreadyPresent; + } + /** + * Internal, gets the first post proces. + * @param postProcesses + * @returns the first post process to be run on this camera. + */ + _getFirstPostProcess(postProcesses) { + for (let ppIndex = 0; ppIndex < postProcesses.length; ppIndex++) { + if (postProcesses[ppIndex] !== null) { + return postProcesses[ppIndex]; + } + } + return null; + } + /** + * Marks the prepass renderer as dirty, triggering a check if the prepass is necessary for the next rendering. + */ + markAsDirty() { + this._isDirty = true; + } + /** + * Enables a texture on the MultiRenderTarget for prepass + * @param types + */ + _enableTextures(types) { + // For velocity : enable storage of previous matrices for instances + this._scene.needsPreviousWorldMatrices = false; + for (let i = 0; i < types.length; i++) { + const type = types[i]; + if (this._textureIndices[type] === -1) { + this._textureIndices[type] = this._mrtLayout.length; + this._mrtLayout.push(type); + this._mrtTypes.push(PrePassRenderer.TextureFormats[type].type); + this._mrtFormats.push(PrePassRenderer.TextureFormats[type].format); + this._mrtNames.push(PrePassRenderer.TextureFormats[type].name); + this.mrtCount++; + } + if (type === 2 || type === 11) { + this._scene.needsPreviousWorldMatrices = true; + } + } + } + /** + * Makes sure that the prepass renderer is up to date if it has been dirtified. + */ + update() { + if (this._isDirty) { + this._update(); + } + } + _update() { + this._disable(); + let enablePrePass = false; + this._scene.imageProcessingConfiguration.applyByPostProcess = false; + if (this._scene._depthPeelingRenderer && this._scene.useOrderIndependentTransparency) { + this._scene._depthPeelingRenderer.setPrePassRenderer(this); + enablePrePass = true; + } + for (let i = 0; i < this._scene.materials.length; i++) { + if (this._scene.materials[i].setPrePassRenderer(this)) { + enablePrePass = true; + } + } + if (enablePrePass) { + this._setRenderTargetEnabled(this.defaultRT, true); + } + let postProcesses; + for (let i = 0; i < this.renderTargets.length; i++) { + if (this.renderTargets[i].renderTargetTexture) { + postProcesses = this._getPostProcessesSource(this.renderTargets[i]); + } + else { + const camera = this._scene.activeCamera; + if (!camera) { + continue; + } + postProcesses = camera._postProcesses; + } + if (!postProcesses) { + continue; + } + postProcesses = postProcesses.filter((pp) => { + return pp != null; + }); + if (postProcesses) { + for (let j = 0; j < postProcesses.length; j++) { + if (postProcesses[j].setPrePassRenderer(this)) { + this._setRenderTargetEnabled(this.renderTargets[i], true); + enablePrePass = true; + } + } + if (this._hasImageProcessing(postProcesses)) { + this._scene.imageProcessingConfiguration.applyByPostProcess = true; + } + } + } + this._markAllMaterialsAsPrePassDirty(); + this._isDirty = false; + if (enablePrePass) { + this._enable(); + } + } + _markAllMaterialsAsPrePassDirty() { + const materials = this._scene.materials; + for (let i = 0; i < materials.length; i++) { + materials[i].markAsDirty(Material.PrePassDirtyFlag); + } + } + /** + * Disposes the prepass renderer. + */ + dispose() { + for (let i = this.renderTargets.length - 1; i >= 0; i--) { + this.renderTargets[i].dispose(); + } + for (let i = 0; i < this._effectConfigurations.length; i++) { + if (this._effectConfigurations[i].dispose) { + this._effectConfigurations[i].dispose(); + } + } + } +} +/** + * @internal + */ +PrePassRenderer._SceneComponentInitialization = (_) => { + throw _WarnImport("PrePassRendererSceneComponent"); +}; +/** + * Describes the types and formats of the textures used by the pre-pass renderer + */ +PrePassRenderer.TextureFormats = [ + { + purpose: 0, + type: 2, + format: 5, + name: "prePass_Irradiance", + }, + { + purpose: 1, + type: 2, + format: 5, + name: "prePass_Position", + }, + { + purpose: 2, + type: 0, + format: 5, + name: "prePass_Velocity", + }, + { + purpose: 3, + type: 0, + format: 5, + name: "prePass_Reflectivity", + }, + { + purpose: 4, + type: 2, + format: 5, + name: "prePass_Color", + }, + { + purpose: 5, + type: 1, + format: 6, + name: "prePass_Depth", + }, + { + purpose: 6, + type: 2, + format: 5, + name: "prePass_Normal", + }, + { + purpose: 7, + type: 0, + format: 5, + name: "prePass_Albedo", + }, + { + purpose: 8, + type: 0, + format: 5, + name: "prePass_WorldNormal", + }, + { + purpose: 9, + type: 2, + format: 5, + name: "prePass_LocalPosition", + }, + { + purpose: 10, + type: 1, + format: 6, + name: "prePass_ScreenDepth", + }, + { + purpose: 11, + type: 2, + format: 5, + name: "prePass_VelocityLinear", + }, +]; + +Object.defineProperty(Scene.prototype, "prePassRenderer", { + get: function () { + return this._prePassRenderer; + }, + set: function (value) { + if (value && value.isSupported) { + this._prePassRenderer = value; + } + }, + enumerable: true, + configurable: true, +}); +Scene.prototype.enablePrePassRenderer = function () { + if (this._prePassRenderer) { + return this._prePassRenderer; + } + this._prePassRenderer = new PrePassRenderer(this); + if (!this._prePassRenderer.isSupported) { + this._prePassRenderer = null; + Logger.Error("PrePassRenderer needs WebGL 2 support.\n" + "Maybe you tried to use the following features that need the PrePassRenderer :\n" + " + Subsurface Scattering"); + } + return this._prePassRenderer; +}; +Scene.prototype.disablePrePassRenderer = function () { + if (!this._prePassRenderer) { + return; + } + this._prePassRenderer.dispose(); + this._prePassRenderer = null; +}; +/** + * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful + * in several rendering techniques. + */ +class PrePassRendererSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_PREPASSRENDERER; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS, this, this._beforeCameraDraw); + this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS, this, this._afterCameraDraw); + this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS, this, this._beforeRenderTargetDraw); + this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS, this, this._afterRenderTargetDraw); + this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PREPASS, this, this._beforeClearStage); + this.scene._beforeRenderTargetClearStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS, this, this._beforeRenderTargetClearStage); + this.scene._beforeRenderingMeshStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS, this, this._beforeRenderingMeshStage); + this.scene._afterRenderingMeshStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS, this, this._afterRenderingMeshStage); + } + _beforeRenderTargetDraw(renderTarget, faceIndex, layer) { + if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) { + this.scene.prePassRenderer._setRenderTarget(renderTarget._prePassRenderTarget); + this.scene.prePassRenderer._beforeDraw(undefined, faceIndex, layer); + } + } + _afterRenderTargetDraw(renderTarget, faceIndex, layer) { + if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) { + this.scene.prePassRenderer._afterDraw(faceIndex, layer); + } + } + _beforeRenderTargetClearStage(renderTarget) { + if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) { + if (!renderTarget._prePassRenderTarget) { + renderTarget._prePassRenderTarget = this.scene.prePassRenderer._createRenderTarget(renderTarget.name + "_prePassRTT", renderTarget); + } + this.scene.prePassRenderer._setRenderTarget(renderTarget._prePassRenderTarget); + this.scene.prePassRenderer._clear(); + } + } + _beforeCameraDraw(camera) { + if (this.scene.prePassRenderer) { + this.scene.prePassRenderer._setRenderTarget(null); + this.scene.prePassRenderer._beforeDraw(camera); + } + } + _afterCameraDraw() { + if (this.scene.prePassRenderer) { + this.scene.prePassRenderer._afterDraw(); + } + } + _beforeClearStage() { + if (this.scene.prePassRenderer) { + this.scene.prePassRenderer._setRenderTarget(null); + this.scene.prePassRenderer._clear(); + } + } + _beforeRenderingMeshStage(mesh, subMesh, batch, effect) { + if (!effect) { + return; + } + // Render to MRT + const scene = mesh.getScene(); + if (scene.prePassRenderer) { + scene.prePassRenderer.bindAttachmentsForEffect(effect, subMesh); + } + } + _afterRenderingMeshStage(mesh) { + const scene = mesh.getScene(); + if (scene.prePassRenderer) { + scene.prePassRenderer.restoreAttachments(); + } + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do for this component + } + /** + * Disposes the component and the associated resources + */ + dispose() { + this.scene.disablePrePassRenderer(); + } +} +PrePassRenderer._SceneComponentInitialization = (scene) => { + // Register the G Buffer component to the scene. + let component = scene._getComponent(SceneComponentConstants.NAME_PREPASSRENDERER); + if (!component) { + component = new PrePassRendererSceneComponent(scene); + scene._addComponent(component); + } +}; + +// Do not edit. +const name$1H = "fibonacci"; +const shader$1G = `#define rcp(x) 1./x +#define GOLDEN_RATIO 1.618033988749895 +vec2 Golden2dSeq(int i,float n) +{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} +vec2 SampleDiskGolden(int i,int sampleCount) +{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$1H]) { + ShaderStore.IncludesShadersStore[name$1H] = shader$1G; +} + +// Do not edit. +const name$1G = "diffusionProfile"; +const shader$1F = `uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$1G]) { + ShaderStore.IncludesShadersStore[name$1G] = shader$1F; +} + +// Do not edit. +const name$1F = "subSurfaceScatteringPixelShader"; +const shader$1E = `#include +#include +#include +#include +varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; +#define rcp(x) 1./x +#define Sq(x) x*x +#define SSS_BILATERAL_FILTER true +vec3 EvalBurleyDiffusionProfile(float r,vec3 S) +{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); +vec3 expSum=exp_13*(1.+exp_13*exp_13); +return (S*rcp((8.*PI)))*expSum; } +vec2 SampleBurleyDiffusionProfile(float u,float rcpS) +{u=1.-u; +float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); +float p=(g*n)*n; +float c=1.+p+n; +float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); +float x=(3./LOG2_E)*log2(c)-d; +float rcpExp=((c*c)*c)*rcp(((4.*u)*((c*c)+(4.*u)*(4.*u))));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; +return vec2(r,rcpPdf);} +vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) +{ +#ifndef SSS_BILATERAL_FILTER +z=0.; +#endif +float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; +#if SSS_CLAMP_ARTIFACT +return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); +#else +return EvalBurleyDiffusionProfile(r,S)*area; +#endif +} +void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, +float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) +{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; +float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; +vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; +float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) +{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} +else +{}} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) +{centerDepth=texture2D(depthSampler,vUV).r;} +if (!passedStencilTest) { +gl_FragColor=inputColor;return;} +float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; +vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; +float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) +{ +#ifdef DEBUG_SSS_SAMPLES +vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; +#endif +gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} +#ifdef DEBUG_SSS_SAMPLES +vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; +#endif +float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); +vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; if32 +{return 1./x;} +const GOLDEN_RATIO=1.618033988749895;fn Golden2dSeq(i: u32,n: f32)->vec2f +{return vec2f(f32(i)/n+(0.5/n),fract(f32(i)*rcp(GOLDEN_RATIO)));} +fn SampleDiskGolden(i: u32,sampleCount: u32)->vec2f +{let f=Golden2dSeq(i,f32(sampleCount));return vec2f(sqrt(f.x),TWO_PI*f.y);} +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$1E]) { + ShaderStore.IncludesShadersStoreWGSL[name$1E] = shader$1D; +} + +// Do not edit. +const name$1D = "diffusionProfile"; +const shader$1C = `uniform diffusionS: array;uniform diffusionD: array;uniform filterRadii: array; +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$1D]) { + ShaderStore.IncludesShadersStoreWGSL[name$1D] = shader$1C; +} + +// Do not edit. +const name$1C = "subSurfaceScatteringPixelShader"; +const shader$1B = `#include +#include +#include +#include +varying vUV: vec2f;uniform texelSize: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var irradianceSamplerSampler: sampler;var irradianceSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;var albedoSamplerSampler: sampler;var albedoSampler: texture_2d;uniform viewportSize: vec2f;uniform metersPerUnit: f32;const LOG2_E=1.4426950408889634;const SSS_PIXELS_PER_SAMPLE=4.;const _SssSampleBudget=40u; +#define SSS_BILATERAL_FILTER true +fn EvalBurleyDiffusionProfile(r: f32,S: vec3f)->vec3f +{let exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); +let expSum=exp_13*(1.+exp_13*exp_13); +return (S*rcp(8.*PI))*expSum; } +fn SampleBurleyDiffusionProfile(u_: f32,rcpS: f32)->vec2f +{let u=1.-u_; +let g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));let n=exp2(log2(g)*(-1.0/3.0)); +let p=(g*n)*n; +let c=1.+p+n; +let d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); +let x=(3./LOG2_E)*log2(c)-d; +let rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));let r=x*rcpS;let rcpPdf=(8.*PI*rcpS)*rcpExp; +return vec2f(r,rcpPdf);} +fn ComputeBilateralWeight(xy2: f32,z_: f32,mmPerUnit: f32,S: vec3f,rcpPdf: f32)->vec3f +{ +#ifndef SSS_BILATERAL_FILTER +let z=0.; +#else +let z=z_; +#endif +let r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));let area=rcpPdf; +#ifdef SSS_CLAMP_ARTIFACT +return clamp(EvalBurleyDiffusionProfile(r,S)*area,vec3f(0.0),vec3f(1.0)); +#else +return EvalBurleyDiffusionProfile(r,S)*area; +#endif +} +fn EvaluateSample(i: u32,n: u32,S: vec3f,d: f32,centerPosVS: vec3f,mmPerUnit: f32,pixelsPerMm: f32, +phase: f32,totalIrradiance: ptr,totalWeight: ptr) +{let scale =rcp(f32(n));let offset=rcp(f32(n))*0.5;let sinPhase=sin(phase);let cosPhase=cos(phase);let bdp=SampleBurleyDiffusionProfile(f32(i)*scale+offset,d);let r=bdp.x;let rcpPdf=bdp.y;let phi=SampleDiskGolden(i,n).y;let sinPhi=sin(phi);let cosPhi=cos(phi);let sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; +let cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; +let vec=r*vec2f(cosPsi,sinPsi);let position=fragmentInputs.vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*uniforms.texelSize;let xy2 =r*r;let textureRead=textureSampleLevel(irradianceSampler,irradianceSamplerSampler,position,0.);let viewZ=textureSampleLevel(depthSampler,depthSamplerSampler,position,0.).r;let irradiance =textureRead.rgb;if (testLightingForSSS(textureRead.a)) +{let relZ=viewZ-centerPosVS.z;let weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);*totalIrradiance+=weight*irradiance;*totalWeight +=weight;} +else +{}} +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {let irradianceAndDiffusionProfile =textureSampleLevel(irradianceSampler,irradianceSamplerSampler,fragmentInputs.vUV,0.);let centerIrradiance=irradianceAndDiffusionProfile.rgb;let diffusionProfileIndex=u32(round(irradianceAndDiffusionProfile.a*255.));var centerDepth =0.;let inputColor=textureSampleLevel(textureSampler,textureSamplerSampler,fragmentInputs.vUV,0.);let passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) +{centerDepth=textureSampleLevel(depthSampler,depthSamplerSampler,fragmentInputs.vUV,0.).r;} +if (!passedStencilTest) { +fragmentOutputs.color=inputColor;return fragmentOutputs;} +let distScale =1.;let S =uniforms.diffusionS[diffusionProfileIndex];let d =uniforms.diffusionD[diffusionProfileIndex];let filterRadius=uniforms.filterRadii[diffusionProfileIndex];let centerPosNDC=fragmentInputs.vUV;let cornerPosNDC=fragmentInputs.vUV+0.5*uniforms.texelSize;let centerPosVS =vec3f(centerPosNDC*uniforms.viewportSize,1.0)*centerDepth; +let cornerPosVS =vec3f(cornerPosNDC*uniforms.viewportSize,1.0)*centerDepth; +let mmPerUnit =1000.*(uniforms.metersPerUnit*rcp(distScale));let unitsPerMm=rcp(mmPerUnit);let unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);let pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;let filterArea =PI*square(filterRadius*pixelsPerMm);let sampleCount =u32(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));let sampleBudget=_SssSampleBudget;let albedo =textureSampleLevel(albedoSampler,albedoSamplerSampler,fragmentInputs.vUV,0.).rgb;if (distScale==0. || sampleCount<1) +{ +#ifdef DEBUG_SSS_SAMPLES +let green=vec3f(0.,1.,0.);fragmentOutputs.color=vec4f(green,1.0);return fragmentOutputs; +#endif +fragmentOutputs.color=vec4f(inputColor.rgb+albedo*centerIrradiance,1.0);return fragmentOutputs;} +#ifdef DEBUG_SSS_SAMPLES +let red =vec3f(1.,0.,0.);let blue=vec3f(0.,0.,1.);fragmentOutputs.color=vec4f(mix(blue,red,clamp(f32(sampleCount)/f32(sampleBudget),0.0,1.0)),1.0);return fragmentOutputs; +#endif +let phase=0.;let n=min(sampleCount,sampleBudget);var totalIrradiance=vec3f(0.);var totalWeight =vec3f(0.);for (var i=0u; i { + if (!scene.prePassRenderer || !scene.subSurfaceConfiguration) { + Logger.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering."); + return; + } + const texelSize = this.texelSize; + effect.setFloat("metersPerUnit", scene.subSurfaceConfiguration.metersPerUnit); + effect.setFloat2("texelSize", texelSize.x, texelSize.y); + effect.setTexture("irradianceSampler", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(0)]); + effect.setTexture("depthSampler", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(5)]); + effect.setTexture("albedoSampler", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(7)]); + effect.setFloat2("viewportSize", Math.tan(scene.activeCamera.fov / 2) * scene.getEngine().getAspectRatio(scene.activeCamera, true), Math.tan(scene.activeCamera.fov / 2)); + effect.setArray3("diffusionS", scene.subSurfaceConfiguration.ssDiffusionS); + effect.setArray("diffusionD", scene.subSurfaceConfiguration.ssDiffusionD); + effect.setArray("filterRadii", scene.subSurfaceConfiguration.ssFilterRadii); + }); + } +} + +/** + * Contains all parameters needed for the prepass to perform + * screen space subsurface scattering + */ +class SubSurfaceConfiguration { + /** + * Diffusion profile color for subsurface scattering + */ + get ssDiffusionS() { + return this._ssDiffusionS; + } + /** + * Diffusion profile max color channel value for subsurface scattering + */ + get ssDiffusionD() { + return this._ssDiffusionD; + } + /** + * Diffusion profile filter radius for subsurface scattering + */ + get ssFilterRadii() { + return this._ssFilterRadii; + } + /** + * Builds a subsurface configuration object + * @param scene The scene + */ + constructor(scene) { + this._ssDiffusionS = []; + this._ssFilterRadii = []; + this._ssDiffusionD = []; + /** + * Is subsurface enabled + */ + this.enabled = false; + /** + * Does the output of this prepass need to go through imageprocessing + */ + this.needsImageProcessing = true; + /** + * Name of the configuration + */ + this.name = SceneComponentConstants.NAME_SUBSURFACE; + /** + * Diffusion profile colors for subsurface scattering + * You can add one diffusion color using `addDiffusionProfile` on `scene.prePassRenderer` + * See ... + * Note that you can only store up to 5 of them + */ + this.ssDiffusionProfileColors = []; + /** + * Defines the ratio real world => scene units. + * Used for subsurface scattering + */ + this.metersPerUnit = 1; + /** + * Textures that should be present in the MRT for this effect to work + */ + this.texturesRequired = [ + 5, + 7, + 4, + 0, + ]; + // Adding default diffusion profile + this.addDiffusionProfile(new Color3(1, 1, 1)); + this._scene = scene; + SubSurfaceConfiguration._SceneComponentInitialization(this._scene); + } + /** + * Adds a new diffusion profile. + * Useful for more realistic subsurface scattering on diverse materials. + * @param color The color of the diffusion profile. Should be the average color of the material. + * @returns The index of the diffusion profile for the material subsurface configuration + */ + addDiffusionProfile(color) { + if (this.ssDiffusionD.length >= 5) { + // We only suppport 5 diffusion profiles + Logger.Error("You already reached the maximum number of diffusion profiles."); + return 0; // default profile + } + // Do not add doubles + for (let i = 0; i < this._ssDiffusionS.length / 3; i++) { + if (this._ssDiffusionS[i * 3] === color.r && this._ssDiffusionS[i * 3 + 1] === color.g && this._ssDiffusionS[i * 3 + 2] === color.b) { + return i; + } + } + this._ssDiffusionS.push(color.r, color.b, color.g); + this._ssDiffusionD.push(Math.max(Math.max(color.r, color.b), color.g)); + this._ssFilterRadii.push(this.getDiffusionProfileParameters(color)); + this.ssDiffusionProfileColors.push(color); + return this._ssDiffusionD.length - 1; + } + /** + * Creates the sss post process + * @returns The created post process + */ + createPostProcess() { + this.postProcess = new SubSurfaceScatteringPostProcess("subSurfaceScattering", this._scene, { + size: 1, + engine: this._scene.getEngine(), + shaderLanguage: this._scene.getEngine().isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */, + }); + this.postProcess.autoClear = false; + return this.postProcess; + } + /** + * Deletes all diffusion profiles. + * Note that in order to render subsurface scattering, you should have at least 1 diffusion profile. + */ + clearAllDiffusionProfiles() { + this._ssDiffusionD = []; + this._ssDiffusionS = []; + this._ssFilterRadii = []; + this.ssDiffusionProfileColors = []; + } + /** + * Disposes this object + */ + dispose() { + this.clearAllDiffusionProfiles(); + if (this.postProcess) { + this.postProcess.dispose(); + } + } + /** + * @internal + * https://zero-radiance.github.io/post/sampling-diffusion/ + * + * Importance sample the normalized diffuse reflectance profile for the computed value of 's'. + * ------------------------------------------------------------------------------------ + * R[r, phi, s] = s * (Exp[-r * s] + Exp[-r * s / 3]) / (8 * Pi * r) + * PDF[r, phi, s] = r * R[r, phi, s] + * CDF[r, s] = 1 - 1/4 * Exp[-r * s] - 3/4 * Exp[-r * s / 3] + * ------------------------------------------------------------------------------------ + * We importance sample the color channel with the widest scattering distance. + */ + getDiffusionProfileParameters(color) { + const cdf = 0.997; + const maxScatteringDistance = Math.max(color.r, color.g, color.b); + return this._sampleBurleyDiffusionProfile(cdf, maxScatteringDistance); + } + /** + * Performs sampling of a Normalized Burley diffusion profile in polar coordinates. + * 'u' is the random number (the value of the CDF): [0, 1). + * rcp(s) = 1 / ShapeParam = ScatteringDistance. + * Returns the sampled radial distance, s.t. (u = 0 -> r = 0) and (u = 1 -> r = Inf). + * @param u + * @param rcpS + * @returns The sampled radial distance + */ + _sampleBurleyDiffusionProfile(u, rcpS) { + u = 1 - u; // Convert CDF to CCDF + const g = 1 + 4 * u * (2 * u + Math.sqrt(1 + 4 * u * u)); + const n = Math.pow(g, -1 / 3.0); // g^(-1/3) + const p = g * n * n; // g^(+1/3) + const c = 1 + p + n; // 1 + g^(+1/3) + g^(-1/3) + const x = 3 * Math.log(c / (4 * u)); + return x * rcpS; + } +} +/** + * @internal + */ +SubSurfaceConfiguration._SceneComponentInitialization = (_) => { + throw _WarnImport("SubSurfaceSceneComponent"); +}; + +// Adds the parser to the scene parsers. +AddParser(SceneComponentConstants.NAME_SUBSURFACE, (parsedData, scene) => { + // Diffusion profiles + if (parsedData.ssDiffusionProfileColors !== undefined && parsedData.ssDiffusionProfileColors !== null) { + scene.enableSubSurfaceForPrePass(); + if (scene.subSurfaceConfiguration) { + for (let index = 0, cache = parsedData.ssDiffusionProfileColors.length; index < cache; index++) { + const color = parsedData.ssDiffusionProfileColors[index]; + scene.subSurfaceConfiguration.addDiffusionProfile(new Color3(color.r, color.g, color.b)); + } + } + } +}); +Object.defineProperty(Scene.prototype, "subSurfaceConfiguration", { + get: function () { + return this._subSurfaceConfiguration; + }, + set: function (value) { + if (value) { + if (this.enablePrePassRenderer()) { + this._subSurfaceConfiguration = value; + } + } + }, + enumerable: true, + configurable: true, +}); +Scene.prototype.enableSubSurfaceForPrePass = function () { + if (this._subSurfaceConfiguration) { + return this._subSurfaceConfiguration; + } + const prePassRenderer = this.enablePrePassRenderer(); + if (prePassRenderer) { + this._subSurfaceConfiguration = new SubSurfaceConfiguration(this); + prePassRenderer.addEffectConfiguration(this._subSurfaceConfiguration); + return this._subSurfaceConfiguration; + } + return null; +}; +Scene.prototype.disableSubSurfaceForPrePass = function () { + if (!this._subSurfaceConfiguration) { + return; + } + this._subSurfaceConfiguration.dispose(); + this._subSurfaceConfiguration = null; +}; +/** + * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful + * in several rendering techniques. + */ +class SubSurfaceSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_PREPASSRENDERER; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { } + /** + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to + */ + serialize(serializationObject) { + if (!this.scene.subSurfaceConfiguration) { + return; + } + const ssDiffusionProfileColors = this.scene.subSurfaceConfiguration.ssDiffusionProfileColors; + serializationObject.ssDiffusionProfileColors = []; + for (let i = 0; i < ssDiffusionProfileColors.length; i++) { + serializationObject.ssDiffusionProfileColors.push({ + r: ssDiffusionProfileColors[i].r, + g: ssDiffusionProfileColors[i].g, + b: ssDiffusionProfileColors[i].b, + }); + } + } + /** + * Adds all the elements from the container to the scene + */ + addFromContainer() { + // Nothing to do + } + /** + * Removes all the elements in the container from the scene + */ + removeFromContainer() { + // Make sure nothing will be serialized + if (!this.scene.prePassRenderer) { + return; + } + if (this.scene.subSurfaceConfiguration) { + this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles(); + } + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do for this component + } + /** + * Disposes the component and the associated resources + */ + dispose() { + // Nothing to do for this component + } +} +SubSurfaceConfiguration._SceneComponentInitialization = (scene) => { + // Register the G Buffer component to the scene. + let component = scene._getComponent(SceneComponentConstants.NAME_SUBSURFACE); + if (!component) { + component = new SubSurfaceSceneComponent(scene); + scene._addComponent(component); + } +}; + +/** + * Gets the outline renderer associated with the scene + * @returns a OutlineRenderer + */ +Scene.prototype.getOutlineRenderer = function () { + if (!this._outlineRenderer) { + this._outlineRenderer = new OutlineRenderer(this); + } + return this._outlineRenderer; +}; +Object.defineProperty(Mesh.prototype, "renderOutline", { + get: function () { + return this._renderOutline; + }, + set: function (value) { + if (value) { + // Lazy Load the component. + this.getScene().getOutlineRenderer(); + } + this._renderOutline = value; + }, + enumerable: true, + configurable: true, +}); +Object.defineProperty(Mesh.prototype, "renderOverlay", { + get: function () { + return this._renderOverlay; + }, + set: function (value) { + if (value) { + // Lazy Load the component. + this.getScene().getOutlineRenderer(); + } + this._renderOverlay = value; + }, + enumerable: true, + configurable: true, +}); +/** + * This class is responsible to draw the outline/overlay of meshes. + * It should not be used directly but through the available method on mesh. + */ +class OutlineRenderer { + /** + * Gets the shader language used in the Outline renderer. + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Instantiates a new outline renderer. (There could be only one per scene). + * @param scene Defines the scene it belongs to + */ + constructor(scene) { + /** + * The name of the component. Each component must have a unique name. + */ + this.name = SceneComponentConstants.NAME_OUTLINERENDERER; + /** + * Defines a zOffset default Factor to prevent zFighting between the overlay and the mesh. + */ + this.zOffset = 1; + /** + * Defines a zOffset default Unit to prevent zFighting between the overlay and the mesh. + */ + this.zOffsetUnits = 4; // 4 to account for projection a bit by default + /** Shader language used by the Outline renderer. */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this.scene = scene; + this._engine = scene.getEngine(); + this.scene._addComponent(this); + this._passIdForDrawWrapper = []; + for (let i = 0; i < 4; ++i) { + this._passIdForDrawWrapper[i] = this._engine.createRenderPassId(`Outline Renderer (${i})`); + } + const engine = this._engine; + if (engine.isWebGPU) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + } + } + /** + * Register the component to one instance of a scene. + */ + register() { + this.scene._beforeRenderingMeshStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh); + this.scene._afterRenderingMeshStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + // Nothing to do here. + } + /** + * Disposes the component and the associated resources. + */ + dispose() { + for (let i = 0; i < this._passIdForDrawWrapper.length; ++i) { + this._engine.releaseRenderPassId(this._passIdForDrawWrapper[i]); + } + } + /** + * Renders the outline in the canvas. + * @param subMesh Defines the sumesh to render + * @param batch Defines the batch of meshes in case of instances + * @param useOverlay Defines if the rendering is for the overlay or the outline + * @param renderPassId Render pass id to use to render the mesh + */ + render(subMesh, batch, useOverlay = false, renderPassId) { + renderPassId = renderPassId ?? this._passIdForDrawWrapper[0]; + const scene = this.scene; + const engine = scene.getEngine(); + const hardwareInstancedRendering = engine.getCaps().instancedArrays && + ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || subMesh.getRenderingMesh().hasThinInstances); + if (!this.isReady(subMesh, hardwareInstancedRendering, renderPassId)) { + return; + } + const ownerMesh = subMesh.getMesh(); + const replacementMesh = ownerMesh._internalAbstractMeshDataInfo._actAsRegularMesh ? ownerMesh : null; + const renderingMesh = subMesh.getRenderingMesh(); + const effectiveMesh = replacementMesh ? replacementMesh : renderingMesh; + const material = subMesh.getMaterial(); + if (!material || !scene.activeCamera) { + return; + } + const drawWrapper = subMesh._getDrawWrapper(renderPassId); + const effect = DrawWrapper.GetEffect(drawWrapper); + engine.enableEffect(drawWrapper); + // Logarithmic depth + if (material.useLogarithmicDepth) { + effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2)); + } + effect.setFloat("offset", useOverlay ? 0 : renderingMesh.outlineWidth); + effect.setColor4("color", useOverlay ? renderingMesh.overlayColor : renderingMesh.outlineColor, useOverlay ? renderingMesh.overlayAlpha : material.alpha); + effect.setMatrix("viewProjection", scene.getTransformMatrix()); + effect.setMatrix("world", effectiveMesh.getWorldMatrix()); + // Bones + BindBonesParameters(renderingMesh, effect); + // Morph targets + BindMorphTargetParameters(renderingMesh, effect); + if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { + renderingMesh.morphTargetManager._bind(effect); + } + if (!hardwareInstancedRendering) { + renderingMesh._bind(subMesh, effect, material.fillMode); + } + // Baked vertex animations + const bvaManager = subMesh.getMesh().bakedVertexAnimationManager; + if (bvaManager && bvaManager.isEnabled) { + bvaManager.bind(effect, hardwareInstancedRendering); + } + // Alpha test + if (material && material.needAlphaTestingForMesh(effectiveMesh)) { + const alphaTexture = material.getAlphaTestTexture(); + if (alphaTexture) { + effect.setTexture("diffuseSampler", alphaTexture); + effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); + } + } + // Clip plane + bindClipPlane(effect, material, scene); + engine.setZOffset(-this.zOffset); + engine.setZOffsetUnits(-this.zOffsetUnits); + renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => { + effect.setMatrix("world", world); + }); + engine.setZOffset(0); + engine.setZOffsetUnits(0); + } + /** + * Returns whether or not the outline renderer is ready for a given submesh. + * All the dependencies e.g. submeshes, texture, effect... mus be ready + * @param subMesh Defines the submesh to check readiness for + * @param useInstances Defines whether wee are trying to render instances or not + * @param renderPassId Render pass id to use to render the mesh + * @returns true if ready otherwise false + */ + isReady(subMesh, useInstances, renderPassId) { + renderPassId = renderPassId ?? this._passIdForDrawWrapper[0]; + const defines = []; + const attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind]; + const mesh = subMesh.getMesh(); + const material = subMesh.getMaterial(); + if (!material) { + return false; + } + const scene = mesh.getScene(); + let uv1 = false; + let uv2 = false; + const color = false; + // Alpha test + if (material.needAlphaTestingForMesh(mesh)) { + defines.push("#define ALPHATEST"); + if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { + attribs.push(VertexBuffer.UVKind); + defines.push("#define UV1"); + uv1 = true; + } + if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) { + attribs.push(VertexBuffer.UV2Kind); + defines.push("#define UV2"); + uv2 = true; + } + } + //Logarithmic depth + if (material.useLogarithmicDepth) { + defines.push("#define LOGARITHMICDEPTH"); + } + // Clip planes + prepareStringDefinesForClipPlanes(material, scene, defines); + // Bones + const fallbacks = new EffectFallbacks(); + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + attribs.push(VertexBuffer.MatricesIndicesKind); + attribs.push(VertexBuffer.MatricesWeightsKind); + if (mesh.numBoneInfluencers > 4) { + attribs.push(VertexBuffer.MatricesIndicesExtraKind); + attribs.push(VertexBuffer.MatricesWeightsExtraKind); + } + const skeleton = mesh.skeleton; + defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); + if (mesh.numBoneInfluencers > 0) { + fallbacks.addCPUSkinningFallback(0, mesh); + } + if (skeleton.isUsingTextureForMatrices) { + defines.push("#define BONETEXTURE"); + } + else { + defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); + } + } + else { + defines.push("#define NUM_BONE_INFLUENCERS 0"); + } + // Morph targets + const numMorphInfluencers = mesh.morphTargetManager + ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph + true, // useNormalMorph + false, // useTangentMorph + uv1, // useUVMorph + uv2, // useUV2Morph + color // useColorMorph + ) + : 0; + // Instances + if (useInstances) { + defines.push("#define INSTANCES"); + PushAttributesForInstances(attribs); + if (subMesh.getRenderingMesh().hasThinInstances) { + defines.push("#define THIN_INSTANCES"); + } + } + // Baked vertex animations + const bvaManager = mesh.bakedVertexAnimationManager; + if (bvaManager && bvaManager.isEnabled) { + defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"); + if (useInstances) { + attribs.push("bakedVertexAnimationSettingsInstanced"); + } + } + // Get correct effect + const drawWrapper = subMesh._getDrawWrapper(renderPassId, true); + const cachedDefines = drawWrapper.defines; + const join = defines.join("\n"); + if (cachedDefines !== join) { + const uniforms = [ + "world", + "mBones", + "viewProjection", + "diffuseMatrix", + "offset", + "color", + "logarithmicDepthConstant", + "morphTargetInfluences", + "boneTextureWidth", + "morphTargetCount", + "morphTargetTextureInfo", + "morphTargetTextureIndices", + "bakedVertexAnimationSettings", + "bakedVertexAnimationTextureSizeInverted", + "bakedVertexAnimationTime", + "bakedVertexAnimationTexture", + ]; + const samplers = ["diffuseSampler", "boneSampler", "morphTargets", "bakedVertexAnimationTexture"]; + addClipPlaneUniforms(uniforms); + drawWrapper.setEffect(this.scene.getEngine().createEffect("outline", { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: [], + samplers: samplers, + defines: join, + fallbacks: fallbacks, + onCompiled: null, + onError: null, + indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers }, + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => outline_fragment), Promise.resolve().then(() => outline_vertex)]); + } + else { + await Promise.all([Promise.resolve().then(() => outline_fragment$1), Promise.resolve().then(() => outline_vertex$1)]); + } + }, + }, this.scene.getEngine()), join); + } + return drawWrapper.effect.isReady(); + } + _beforeRenderingMesh(mesh, subMesh, batch) { + // Outline - step 1 + this._savedDepthWrite = this._engine.getDepthWrite(); + if (mesh.renderOutline) { + const material = subMesh.getMaterial(); + if (material && material.needAlphaBlendingForMesh(mesh)) { + this._engine.cacheStencilState(); + // Draw only to stencil buffer for the original mesh + // The resulting stencil buffer will be used so the outline is not visible inside the mesh when the mesh is transparent + this._engine.setDepthWrite(false); + this._engine.setColorWrite(false); + this._engine.setStencilBuffer(true); + this._engine.setStencilOperationPass(7681); + this._engine.setStencilFunction(519); + this._engine.setStencilMask(OutlineRenderer._StencilReference); + this._engine.setStencilFunctionReference(OutlineRenderer._StencilReference); + this._engine.stencilStateComposer.useStencilGlobalOnly = true; + this.render(subMesh, batch, /* This sets offset to 0 */ true, this._passIdForDrawWrapper[1]); + this._engine.setColorWrite(true); + this._engine.setStencilFunction(517); + } + // Draw the outline using the above stencil if needed to avoid drawing within the mesh + this._engine.setDepthWrite(false); + this.render(subMesh, batch, false, this._passIdForDrawWrapper[0]); + this._engine.setDepthWrite(this._savedDepthWrite); + if (material && material.needAlphaBlendingForMesh(mesh)) { + this._engine.stencilStateComposer.useStencilGlobalOnly = false; + this._engine.restoreStencilState(); + } + } + } + _afterRenderingMesh(mesh, subMesh, batch) { + // Overlay + if (mesh.renderOverlay) { + const currentMode = this._engine.getAlphaMode(); + const alphaBlendState = this._engine.alphaState.alphaBlend; + this._engine.setAlphaMode(2); + this.render(subMesh, batch, true, this._passIdForDrawWrapper[3]); + this._engine.setAlphaMode(currentMode); + this._engine.setDepthWrite(this._savedDepthWrite); + this._engine.alphaState.alphaBlend = alphaBlendState; + } + // Outline - step 2 + if (mesh.renderOutline && this._savedDepthWrite) { + this._engine.setDepthWrite(true); + this._engine.setColorWrite(false); + this.render(subMesh, batch, false, this._passIdForDrawWrapper[2]); + this._engine.setColorWrite(true); + } + } +} +/** + * Stencil value used to avoid outline being seen within the mesh when the mesh is transparent + */ +OutlineRenderer._StencilReference = 0x04; + +/** + * Defines the base object used for fluid rendering. + * It is based on a list of vertices (particles) + */ +class FluidRenderingObject { + /** Gets or sets the size of the particle */ + get particleSize() { + return this._particleSize; + } + set particleSize(size) { + if (size === this._particleSize) { + return; + } + this._particleSize = size; + this.onParticleSizeChanged.notifyObservers(this); + } + /** Indicates if the object uses instancing or not */ + get useInstancing() { + return !this.indexBuffer; + } + /** Indicates if velocity of particles should be used when rendering the object. The vertex buffer set must contain a "velocity" buffer for this to work! */ + get useVelocity() { + return this._useVelocity; + } + set useVelocity(use) { + if (this._useVelocity === use || !this._hasVelocity()) { + return; + } + this._useVelocity = use; + this._effectsAreDirty = true; + } + _hasVelocity() { + return !!this.vertexBuffers?.velocity; + } + /** + * Gets the index buffer (or null if the object is using instancing) + */ + get indexBuffer() { + return null; + } + /** + * @returns the name of the class + */ + getClassName() { + return "FluidRenderingObject"; + } + /** + * Gets the shader language used in this object + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Instantiates a fluid rendering object + * @param scene The scene the object is part of + * @param shaderLanguage The shader language to use + */ + constructor(scene, shaderLanguage) { + /** Defines the priority of the object. Objects will be rendered in ascending order of priority */ + this.priority = 0; + this._particleSize = 0.1; + /** Observable triggered when the size of the particle is changed */ + this.onParticleSizeChanged = new Observable(); + /** Defines the alpha value of a particle */ + this.particleThicknessAlpha = 0.05; + this._useVelocity = false; + /** Shader language used by the object */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._scene = scene; + this._engine = scene.getEngine(); + this._effectsAreDirty = true; + this._depthEffectWrapper = null; + this._thicknessEffectWrapper = null; + this._shaderLanguage = shaderLanguage ?? (this._engine.isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */); + } + _createEffects() { + const uniformNames = ["view", "projection", "particleRadius", "size"]; + const attributeNames = ["position", "offset"]; + const defines = []; + this._effectsAreDirty = false; + if (this.useVelocity) { + attributeNames.push("velocity"); + defines.push("#define FLUIDRENDERING_VELOCITY"); + } + if (this._scene.useRightHandedSystem) { + defines.push("#define FLUIDRENDERING_RHS"); + } + this._depthEffectWrapper = new EffectWrapper({ + engine: this._engine, + useShaderStore: true, + vertexShader: "fluidRenderingParticleDepth", + fragmentShader: "fluidRenderingParticleDepth", + attributeNames, + uniformNames, + samplerNames: [], + defines, + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => fluidRenderingParticleDepth_vertex), Promise.resolve().then(() => fluidRenderingParticleDepth_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => fluidRenderingParticleDepth_vertex$1), Promise.resolve().then(() => fluidRenderingParticleDepth_fragment$1)]); + } + }, + }); + uniformNames.push("particleAlpha"); + this._thicknessEffectWrapper = new EffectWrapper({ + engine: this._engine, + useShaderStore: true, + vertexShader: "fluidRenderingParticleThickness", + fragmentShader: "fluidRenderingParticleThickness", + attributeNames: ["position", "offset"], + uniformNames, + samplerNames: [], + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.all([Promise.resolve().then(() => fluidRenderingParticleThickness_vertex), Promise.resolve().then(() => fluidRenderingParticleThickness_fragment)]); + } + else { + await Promise.all([Promise.resolve().then(() => fluidRenderingParticleThickness_vertex$1), Promise.resolve().then(() => fluidRenderingParticleThickness_fragment$1)]); + } + }, + }); + } + /** + * Indicates if the object is ready to be rendered + * @returns True if everything is ready for the object to be rendered, otherwise false + */ + isReady() { + if (this._effectsAreDirty) { + this._createEffects(); + } + if (!this._depthEffectWrapper || !this._thicknessEffectWrapper) { + return false; + } + const depthEffect = this._depthEffectWrapper.drawWrapper.effect; + const thicknessEffect = this._thicknessEffectWrapper.drawWrapper.effect; + return depthEffect.isReady() && thicknessEffect.isReady(); + } + /** + * Render the depth texture for this object + */ + renderDepthTexture() { + const numParticles = this.numParticles; + if (!this._depthEffectWrapper || numParticles === 0) { + return; + } + const depthDrawWrapper = this._depthEffectWrapper.drawWrapper; + const depthEffect = depthDrawWrapper.effect; + this._engine.enableEffect(depthDrawWrapper); + this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, depthEffect); + depthEffect.setMatrix("view", this._scene.getViewMatrix()); + depthEffect.setMatrix("projection", this._scene.getProjectionMatrix()); + depthEffect.setFloat2("size", this._particleSize, this._particleSize); + depthEffect.setFloat("particleRadius", this._particleSize / 2); + if (this.useInstancing) { + this._engine.drawArraysType(7, 0, 4, numParticles); + } + else { + this._engine.drawElementsType(0, 0, numParticles); + } + } + /** + * Render the thickness texture for this object + */ + renderThicknessTexture() { + const numParticles = this.numParticles; + if (!this._thicknessEffectWrapper || numParticles === 0) { + return; + } + const thicknessDrawWrapper = this._thicknessEffectWrapper.drawWrapper; + const thicknessEffect = thicknessDrawWrapper.effect; + this._engine.setAlphaMode(6); + this._engine.setDepthWrite(false); + this._engine.enableEffect(thicknessDrawWrapper); + this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, thicknessEffect); + thicknessEffect.setMatrix("view", this._scene.getViewMatrix()); + thicknessEffect.setMatrix("projection", this._scene.getProjectionMatrix()); + thicknessEffect.setFloat("particleAlpha", this.particleThicknessAlpha); + thicknessEffect.setFloat2("size", this._particleSize, this._particleSize); + if (this.useInstancing) { + this._engine.drawArraysType(7, 0, 4, numParticles); + } + else { + this._engine.drawElementsType(0, 0, numParticles); + } + this._engine.setDepthWrite(true); + this._engine.setAlphaMode(0); + } + /** + * Render the diffuse texture for this object + */ + renderDiffuseTexture() { + // do nothing by default + } + /** + * Releases the ressources used by the class + */ + dispose() { + this._depthEffectWrapper?.dispose(false); + this._thicknessEffectWrapper?.dispose(false); + this.onParticleSizeChanged.clear(); + } +} + +/** + * Defines a rendering object based on a particle system + */ +class FluidRenderingObjectParticleSystem extends FluidRenderingObject { + /** Gets the particle system */ + get particleSystem() { + return this._particleSystem; + } + /** + * @returns the name of the class + */ + getClassName() { + return "FluidRenderingObjectParticleSystem"; + } + /** + * Gets or sets a boolean indicating that the diffuse texture should be generated based on the regular rendering of the particle system (default: true). + * Sometimes, generating the diffuse texture this way may be sub-optimal. In that case, you can disable this property, in which case the particle system will be + * rendered using a ALPHA_COMBINE mode instead of the one used by the particle system. + */ + get useTrueRenderingForDiffuseTexture() { + return this._useTrueRenderingForDiffuseTexture; + } + set useTrueRenderingForDiffuseTexture(use) { + if (this._useTrueRenderingForDiffuseTexture === use) { + return; + } + this._useTrueRenderingForDiffuseTexture = use; + if (use) { + this._particleSystem.blendMode = this._blendMode; + this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver); + this._onBeforeDrawParticleObserver = null; + } + else { + this._particleSystem.blendMode = -1; + this._onBeforeDrawParticleObserver = this._particleSystem.onBeforeDrawParticlesObservable.add(() => { + this._engine.setAlphaMode(2); + }); + } + } + /** + * Gets the vertex buffers + */ + get vertexBuffers() { + return this._particleSystem.vertexBuffers; + } + /** + * Gets the index buffer (or null if the object is using instancing) + */ + get indexBuffer() { + return this._particleSystem.indexBuffer; + } + /** + * Creates a new instance of the class + * @param scene The scene the particle system is part of + * @param ps The particle system + * @param shaderLanguage The shader language to use + */ + constructor(scene, ps, shaderLanguage) { + super(scene, shaderLanguage); + this._useTrueRenderingForDiffuseTexture = true; + this._particleSystem = ps; + this._originalRender = ps.render.bind(ps); + this._blendMode = ps.blendMode; + this._onBeforeDrawParticleObserver = null; + this._updateInAnimate = this._particleSystem.updateInAnimate; + this._particleSystem.updateInAnimate = true; + this._particleSystem.render = () => 0; + this.particleSize = (ps.minSize + ps.maxSize) / 2; + this.useTrueRenderingForDiffuseTexture = false; + } + /** + * Indicates if the object is ready to be rendered + * @returns True if everything is ready for the object to be rendered, otherwise false + */ + isReady() { + return super.isReady() && this._particleSystem.isReady(); + } + /** + * Gets the number of particles in this particle system + * @returns The number of particles + */ + get numParticles() { + return this._particleSystem.getActiveCount(); + } + /** + * Render the diffuse texture for this object + */ + renderDiffuseTexture() { + this._originalRender(); + } + /** + * Releases the ressources used by the class + */ + dispose() { + super.dispose(); + this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver); + this._onBeforeDrawParticleObserver = null; + this._particleSystem.render = this._originalRender; + this._particleSystem.blendMode = this._blendMode; + this._particleSystem.updateInAnimate = this._updateInAnimate; + } +} + +/** @internal */ +class FluidRenderingTextures { + get blurNumIterations() { + return this._blurNumIterations; + } + set blurNumIterations(numIterations) { + if (this._blurNumIterations === numIterations) { + return; + } + this._blurNumIterations = numIterations; + if (this._blurPostProcesses !== null) { + const blurX = this._blurPostProcesses[0]; + const blurY = this._blurPostProcesses[1]; + this._blurPostProcesses = []; + for (let i = 0; i < this._blurNumIterations * 2; ++i) { + this._blurPostProcesses[i] = i & 1 ? blurY : blurX; + } + } + } + get renderTarget() { + return this._rt; + } + get renderTargetBlur() { + return this._rtBlur; + } + get texture() { + return this._texture; + } + get textureBlur() { + return this._textureBlurred; + } + /** + * Gets the shader language used in the texture + */ + get shaderLanguage() { + return this._shaderLanguage; + } + constructor(name, scene, width, height, blurTextureSizeX, blurTextureSizeY, textureType = 1, textureFormat = 6, blurTextureType = 1, blurTextureFormat = 6, useStandardBlur = false, camera = null, generateDepthBuffer = true, samples = 1, shaderLanguage) { + this.enableBlur = true; + this.blurSizeDivisor = 1; + this.blurFilterSize = 7; + this._blurNumIterations = 3; + this.blurMaxFilterSize = 100; + this.blurDepthScale = 10; + this.particleSize = 0.02; + this.onDisposeObservable = new Observable(); + /** Shader language used by the texture */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._name = name; + this._scene = scene; + this._camera = camera; + this._engine = scene.getEngine(); + this._width = width; + this._height = height; + this._blurTextureSizeX = blurTextureSizeX; + this._blurTextureSizeY = blurTextureSizeY; + this._textureType = textureType; + this._textureFormat = textureFormat; + this._blurTextureType = blurTextureType; + this._blurTextureFormat = blurTextureFormat; + this._useStandardBlur = useStandardBlur; + this._generateDepthBuffer = generateDepthBuffer; + this._samples = samples; + this._postProcessRunningIndex = 0; + this.enableBlur = blurTextureSizeX !== 0 && blurTextureSizeY !== 0; + this._rt = null; + this._texture = null; + this._rtBlur = null; + this._textureBlurred = null; + this._blurPostProcesses = null; + this._shaderLanguage = shaderLanguage ?? (this._engine.isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */); + } + initialize() { + this.dispose(); + this._createRenderTarget(); + if (this.enableBlur && this._texture) { + const [rtBlur, textureBlurred, blurPostProcesses] = this._createBlurPostProcesses(this._texture, this._blurTextureType, this._blurTextureFormat, this.blurSizeDivisor, this._name, this._useStandardBlur); + this._rtBlur = rtBlur; + this._textureBlurred = textureBlurred; + this._blurPostProcesses = blurPostProcesses; + } + } + applyBlurPostProcesses() { + if (this.enableBlur && this._blurPostProcesses) { + this._postProcessRunningIndex = 0; + this._scene.postProcessManager.directRender(this._blurPostProcesses, this._rtBlur, true); + this._engine.unBindFramebuffer(this._rtBlur); + } + } + _createRenderTarget() { + this._rt = this._engine.createRenderTargetTexture({ width: this._width, height: this._height }, { + generateMipMaps: false, + type: this._textureType, + format: this._textureFormat, + samplingMode: 1, + generateDepthBuffer: this._generateDepthBuffer, + generateStencilBuffer: false, + samples: this._samples, + label: `FluidRenderingRTT-${this._name}`, + }); + const renderTexture = this._rt.texture; + renderTexture.incrementReferences(); + this._texture = new Texture(null, this._scene); + this._texture.name = "rtt" + this._name; + this._texture._texture = renderTexture; + this._texture.wrapU = Texture.CLAMP_ADDRESSMODE; + this._texture.wrapV = Texture.CLAMP_ADDRESSMODE; + this._texture.anisotropicFilteringLevel = 1; + } + _createBlurPostProcesses(textureBlurSource, textureType, textureFormat, blurSizeDivisor, debugName, useStandardBlur = false) { + const engine = this._scene.getEngine(); + const targetSize = new Vector2(Math.floor(this._blurTextureSizeX / blurSizeDivisor), Math.floor(this._blurTextureSizeY / blurSizeDivisor)); + const useBilinearFiltering = (textureType === 1 && engine.getCaps().textureFloatLinearFiltering) || + (textureType === 2 && engine.getCaps().textureHalfFloatLinearFiltering); + const rtBlur = this._engine.createRenderTargetTexture({ width: targetSize.x, height: targetSize.y }, { + generateMipMaps: false, + type: textureType, + format: textureFormat, + samplingMode: useBilinearFiltering ? 2 : 1, + generateDepthBuffer: false, + generateStencilBuffer: false, + samples: this._samples, + label: `FluidRenderingRTTBlur-${debugName}`, + }); + const renderTexture = rtBlur.texture; + renderTexture.incrementReferences(); + const texture = new Texture(null, this._scene); + texture.name = "rttBlurred" + debugName; + texture._texture = renderTexture; + texture.wrapU = Texture.CLAMP_ADDRESSMODE; + texture.wrapV = Texture.CLAMP_ADDRESSMODE; + texture.anisotropicFilteringLevel = 1; + if (useStandardBlur) { + const kernelBlurXPostprocess = new PostProcess("BilateralBlurX", "fluidRenderingStandardBlur", ["filterSize", "blurDir"], null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat, this._shaderLanguage, async () => { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => fluidRenderingStandardBlur_fragment); + } + else { + await Promise.resolve().then(() => fluidRenderingStandardBlur_fragment$1); + } + }); + kernelBlurXPostprocess.samples = this._samples; + kernelBlurXPostprocess.externalTextureSamplerBinding = true; + kernelBlurXPostprocess.onApplyObservable.add((effect) => { + if (this._postProcessRunningIndex === 0) { + effect.setTexture("textureSampler", textureBlurSource); + } + else { + effect._bindTexture("textureSampler", kernelBlurXPostprocess.inputTexture.texture); + } + effect.setInt("filterSize", this.blurFilterSize); + effect.setFloat2("blurDir", 1 / this._blurTextureSizeX, 0); + this._postProcessRunningIndex++; + }); + kernelBlurXPostprocess.onSizeChangedObservable.add(() => { + kernelBlurXPostprocess._textures.forEach((rt) => { + rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE; + rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE; + }); + }); + this._fixReusablePostProcess(kernelBlurXPostprocess); + const kernelBlurYPostprocess = new PostProcess("BilateralBlurY", "fluidRenderingStandardBlur", ["filterSize", "blurDir"], null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat, this._shaderLanguage, async () => { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => fluidRenderingStandardBlur_fragment); + } + else { + await Promise.resolve().then(() => fluidRenderingStandardBlur_fragment$1); + } + }); + kernelBlurYPostprocess.samples = this._samples; + kernelBlurYPostprocess.onApplyObservable.add((effect) => { + effect.setInt("filterSize", this.blurFilterSize); + effect.setFloat2("blurDir", 0, 1 / this._blurTextureSizeY); + this._postProcessRunningIndex++; + }); + kernelBlurYPostprocess.onSizeChangedObservable.add(() => { + kernelBlurYPostprocess._textures.forEach((rt) => { + rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE; + rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE; + }); + }); + this._fixReusablePostProcess(kernelBlurYPostprocess); + kernelBlurXPostprocess.autoClear = false; + kernelBlurYPostprocess.autoClear = false; + const blurList = []; + for (let i = 0; i < this._blurNumIterations * 2; ++i) { + blurList[i] = i & 1 ? kernelBlurYPostprocess : kernelBlurXPostprocess; + } + return [rtBlur, texture, blurList]; + } + else { + const uniforms = ["maxFilterSize", "blurDir", "projectedParticleConstant", "depthThreshold"]; + const kernelBlurXPostprocess = new PostProcess("BilateralBlurX", "fluidRenderingBilateralBlur", uniforms, null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat, this._shaderLanguage, async () => { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => fluidRenderingBilateralBlur_fragment); + } + else { + await Promise.resolve().then(() => fluidRenderingBilateralBlur_fragment$1); + } + }); + kernelBlurXPostprocess.samples = this._samples; + kernelBlurXPostprocess.externalTextureSamplerBinding = true; + kernelBlurXPostprocess.onApplyObservable.add((effect) => { + if (this._postProcessRunningIndex === 0) { + effect.setTexture("textureSampler", textureBlurSource); + } + else { + effect._bindTexture("textureSampler", kernelBlurXPostprocess.inputTexture.texture); + } + effect.setInt("maxFilterSize", this.blurMaxFilterSize); + effect.setFloat2("blurDir", 1 / this._blurTextureSizeX, 0); + effect.setFloat("projectedParticleConstant", this._getProjectedParticleConstant()); + effect.setFloat("depthThreshold", this._getDepthThreshold()); + this._postProcessRunningIndex++; + }); + kernelBlurXPostprocess.onSizeChangedObservable.add(() => { + kernelBlurXPostprocess._textures.forEach((rt) => { + rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE; + rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE; + }); + }); + this._fixReusablePostProcess(kernelBlurXPostprocess); + const kernelBlurYPostprocess = new PostProcess("BilateralBlurY", "fluidRenderingBilateralBlur", uniforms, null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat, this._shaderLanguage, async () => { + if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => fluidRenderingBilateralBlur_fragment); + } + else { + await Promise.resolve().then(() => fluidRenderingBilateralBlur_fragment$1); + } + }); + kernelBlurYPostprocess.samples = this._samples; + kernelBlurYPostprocess.onApplyObservable.add((effect) => { + effect.setInt("maxFilterSize", this.blurMaxFilterSize); + effect.setFloat2("blurDir", 0, 1 / this._blurTextureSizeY); + effect.setFloat("projectedParticleConstant", this._getProjectedParticleConstant()); + effect.setFloat("depthThreshold", this._getDepthThreshold()); + this._postProcessRunningIndex++; + }); + kernelBlurYPostprocess.onSizeChangedObservable.add(() => { + kernelBlurYPostprocess._textures.forEach((rt) => { + rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE; + rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE; + }); + }); + this._fixReusablePostProcess(kernelBlurYPostprocess); + kernelBlurXPostprocess.autoClear = false; + kernelBlurYPostprocess.autoClear = false; + const blurList = []; + for (let i = 0; i < this._blurNumIterations * 2; ++i) { + blurList[i] = i & 1 ? kernelBlurYPostprocess : kernelBlurXPostprocess; + } + return [rtBlur, texture, blurList]; + } + } + _fixReusablePostProcess(pp) { + if (!pp.isReusable()) { + return; + } + pp.onActivateObservable.add(() => { + // undo what calling activate() does which will make sure we will retrieve the right texture when getting the input for the post process + pp._currentRenderTextureInd = (pp._currentRenderTextureInd + 1) % 2; + }); + pp.onApplyObservable.add(() => { + // now we can advance to the next texture + pp._currentRenderTextureInd = (pp._currentRenderTextureInd + 1) % 2; + }); + } + _getProjectedParticleConstant() { + return (this.blurFilterSize * this.particleSize * 0.05 * (this._height / 2)) / Math.tan((this._camera?.fov ?? (45 * Math.PI) / 180) / 2); + } + _getDepthThreshold() { + return (this.particleSize / 2) * this.blurDepthScale; + } + dispose() { + if (this.onDisposeObservable.hasObservers()) { + this.onDisposeObservable.notifyObservers(this); + } + this.onDisposeObservable.clear(); + this._rt?.dispose(); + this._rt = null; + this._texture?.dispose(); + this._texture = null; + this._rtBlur?.dispose(); + this._rtBlur = null; + this._textureBlurred?.dispose(); + this._textureBlurred = null; + if (this._blurPostProcesses) { + this._blurPostProcesses[0].dispose(); + this._blurPostProcesses[1].dispose(); + } + this._blurPostProcesses = null; + } +} + +/** + * Textures that can be displayed as a debugging tool + */ +var FluidRenderingDebug; +(function (FluidRenderingDebug) { + FluidRenderingDebug[FluidRenderingDebug["DepthTexture"] = 0] = "DepthTexture"; + FluidRenderingDebug[FluidRenderingDebug["DepthBlurredTexture"] = 1] = "DepthBlurredTexture"; + FluidRenderingDebug[FluidRenderingDebug["ThicknessTexture"] = 2] = "ThicknessTexture"; + FluidRenderingDebug[FluidRenderingDebug["ThicknessBlurredTexture"] = 3] = "ThicknessBlurredTexture"; + FluidRenderingDebug[FluidRenderingDebug["DiffuseTexture"] = 4] = "DiffuseTexture"; + FluidRenderingDebug[FluidRenderingDebug["Normals"] = 5] = "Normals"; + FluidRenderingDebug[FluidRenderingDebug["DiffuseRendering"] = 6] = "DiffuseRendering"; +})(FluidRenderingDebug || (FluidRenderingDebug = {})); +/** + * Class used to render an object as a fluid thanks to different render target textures (depth, thickness, diffuse) + */ +class FluidRenderingTargetRenderer { + /** + * Returns true if the class needs to be reinitialized (because of changes in parameterization) + */ + get needInitialization() { + return this._needInitialization; + } + /** + * Gets or sets a boolean indicating that the diffuse texture should be generated and used for the rendering + */ + get generateDiffuseTexture() { + return this._generateDiffuseTexture; + } + set generateDiffuseTexture(generate) { + if (this._generateDiffuseTexture === generate) { + return; + } + this._generateDiffuseTexture = generate; + this._needInitialization = true; + } + /** + * Gets or sets the feature (texture) to be debugged. Not used if debug is false + */ + get debugFeature() { + return this._debugFeature; + } + set debugFeature(feature) { + if (this._debugFeature === feature) { + return; + } + this._needInitialization = true; + this._debugFeature = feature; + } + /** + * Gets or sets a boolean indicating if we should display a specific texture (given by debugFeature) for debugging purpose + */ + get debug() { + return this._debug; + } + set debug(debug) { + if (this._debug === debug) { + return; + } + this._debug = debug; + this._needInitialization = true; + } + /** + * Gets or sets the environment map used for the reflection part of the shading + * If null, no map will be used. If undefined, the scene.environmentMap will be used (if defined) + */ + get environmentMap() { + return this._environmentMap; + } + set environmentMap(map) { + if (this._environmentMap === map) { + return; + } + this._needInitialization = true; + this._environmentMap = map; + } + /** + * Gets or sets a boolean indicating that the depth texture should be blurred + */ + get enableBlurDepth() { + return this._enableBlurDepth; + } + set enableBlurDepth(enable) { + if (this._enableBlurDepth === enable) { + return; + } + this._enableBlurDepth = enable; + this._needInitialization = true; + } + /** + * Gets or sets the depth size divisor (positive number, generally between 1 and 4), which is used as a divisor when creating the texture used for blurring the depth + * For eg. if blurDepthSizeDivisor=2, the texture used to blur the depth will be half the size of the depth texture + */ + get blurDepthSizeDivisor() { + return this._blurDepthSizeDivisor; + } + set blurDepthSizeDivisor(scale) { + if (this._blurDepthSizeDivisor === scale) { + return; + } + this._blurDepthSizeDivisor = scale; + this._needInitialization = true; + } + /** + * Size of the kernel used to filter the depth blur texture (positive number, generally between 1 and 20 - higher values will require more processing power from the GPU) + */ + get blurDepthFilterSize() { + return this._blurDepthFilterSize; + } + set blurDepthFilterSize(filterSize) { + if (this._blurDepthFilterSize === filterSize) { + return; + } + this._blurDepthFilterSize = filterSize; + this._setBlurParameters(); + } + /** + * Number of blurring iterations used to generate the depth blur texture (positive number, generally between 1 and 10 - higher values will require more processing power from the GPU) + */ + get blurDepthNumIterations() { + return this._blurDepthNumIterations; + } + set blurDepthNumIterations(numIterations) { + if (this._blurDepthNumIterations === numIterations) { + return; + } + this._blurDepthNumIterations = numIterations; + this._setBlurParameters(); + } + /** + * Maximum size of the kernel used to blur the depth texture (positive number, generally between 1 and 200 - higher values will require more processing power from the GPU when the particles are larger on screen) + */ + get blurDepthMaxFilterSize() { + return this._blurDepthMaxFilterSize; + } + set blurDepthMaxFilterSize(maxFilterSize) { + if (this._blurDepthMaxFilterSize === maxFilterSize) { + return; + } + this._blurDepthMaxFilterSize = maxFilterSize; + this._setBlurParameters(); + } + /** + * Depth weight in the calculation when applying the bilateral blur to generate the depth blur texture (positive number, generally between 0 and 100) + */ + get blurDepthDepthScale() { + return this._blurDepthDepthScale; + } + set blurDepthDepthScale(scale) { + if (this._blurDepthDepthScale === scale) { + return; + } + this._blurDepthDepthScale = scale; + this._setBlurParameters(); + } + /** + * Gets or sets a boolean indicating that the thickness texture should be blurred + */ + get enableBlurThickness() { + return this._enableBlurThickness; + } + set enableBlurThickness(enable) { + if (this._enableBlurThickness === enable) { + return; + } + this._enableBlurThickness = enable; + this._needInitialization = true; + } + /** + * Gets or sets the thickness size divisor (positive number, generally between 1 and 4), which is used as a divisor when creating the texture used for blurring the thickness + * For eg. if blurThicknessSizeDivisor=2, the texture used to blur the thickness will be half the size of the thickness texture + */ + get blurThicknessSizeDivisor() { + return this._blurThicknessSizeDivisor; + } + set blurThicknessSizeDivisor(scale) { + if (this._blurThicknessSizeDivisor === scale) { + return; + } + this._blurThicknessSizeDivisor = scale; + this._needInitialization = true; + } + /** + * Size of the kernel used to filter the thickness blur texture (positive number, generally between 1 and 20 - higher values will require more processing power from the GPU) + */ + get blurThicknessFilterSize() { + return this._blurThicknessFilterSize; + } + set blurThicknessFilterSize(filterSize) { + if (this._blurThicknessFilterSize === filterSize) { + return; + } + this._blurThicknessFilterSize = filterSize; + this._setBlurParameters(); + } + /** + * Number of blurring iterations used to generate the thickness blur texture (positive number, generally between 1 and 10 - higher values will require more processing power from the GPU) + */ + get blurThicknessNumIterations() { + return this._blurThicknessNumIterations; + } + set blurThicknessNumIterations(numIterations) { + if (this._blurThicknessNumIterations === numIterations) { + return; + } + this._blurThicknessNumIterations = numIterations; + this._setBlurParameters(); + } + /** + * Gets or sets a boolean indicating that a fixed thickness should be used instead of generating a thickness texture + */ + get useFixedThickness() { + return this._useFixedThickness; + } + set useFixedThickness(use) { + if (this._useFixedThickness === use) { + return; + } + this._useFixedThickness = use; + this._needInitialization = true; + } + /** + * Gets or sets a boolean indicating that the velocity should be used when rendering the particles as a fluid. + * Note: the vertex buffers must contain a "velocity" buffer for this to work! + */ + get useVelocity() { + return this._useVelocity; + } + set useVelocity(use) { + if (this._useVelocity === use) { + return; + } + this._useVelocity = use; + this._needInitialization = true; + this._onUseVelocityChanged.notifyObservers(this); + } + /** + * Defines the size of the depth texture. + * If null, the texture will have the size of the screen + */ + get depthMapSize() { + return this._depthMapSize; + } + set depthMapSize(size) { + if (this._depthMapSize === size) { + return; + } + this._depthMapSize = size; + this._needInitialization = true; + } + /** + * Defines the size of the thickness texture. + * If null, the texture will have the size of the screen + */ + get thicknessMapSize() { + return this._thicknessMapSize; + } + set thicknessMapSize(size) { + if (this._thicknessMapSize === size) { + return; + } + this._thicknessMapSize = size; + this._needInitialization = true; + } + /** + * Defines the size of the diffuse texture. + * If null, the texture will have the size of the screen + */ + get diffuseMapSize() { + return this._diffuseMapSize; + } + set diffuseMapSize(size) { + if (this._diffuseMapSize === size) { + return; + } + this._diffuseMapSize = size; + this._needInitialization = true; + } + /** + * Gets or sets the number of samples used by MSAA + * Note: changing this value in WebGL does not work because depth/stencil textures can't be created with MSAA (see https://github.com/BabylonJS/Babylon.js/issues/12444) + */ + get samples() { + return this._samples; + } + set samples(samples) { + if (this._samples === samples) { + return; + } + this._samples = samples; + this._needInitialization = true; + } + /** + * If compositeMode is true (default: false), when the alpha value of the background (the scene rendered without the fluid objects) is 0, the final alpha value of the pixel will be set to the thickness value. + * This way, it is possible to composite the fluid rendering on top of the HTML background. + */ + get compositeMode() { + return this._compositeMode; + } + set compositeMode(value) { + if (this._compositeMode === value) { + return; + } + this._compositeMode = value; + this._needInitialization = true; + } + /** + * Gets the camera used for the rendering + */ + get camera() { + return this._camera; + } + /** + * Gets the shader language used in this renderer + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Creates an instance of the class + * @param scene Scene used to render the fluid object into + * @param camera Camera used to render the fluid object. If not provided, use the active camera of the scene instead + * @param shaderLanguage The shader language to use + */ + constructor(scene, camera, shaderLanguage) { + this._generateDiffuseTexture = false; + /** + * Fluid color. Not used if generateDiffuseTexture is true + */ + this.fluidColor = new Color3(0.085, 0.6375, 0.765); + /** + * Density of the fluid (positive number). The higher the value, the more opaque the fluid. + */ + this.density = 2; + /** + * Strength of the refraction (positive number, but generally between 0 and 0.3). + */ + this.refractionStrength = 0.1; + /** + * Strength of the fresnel effect (value between 0 and 1). Lower the value if you want to soften the specular effect + */ + this.fresnelClamp = 1.0; + /** + * Strength of the specular power (positive number). Increase the value to make the specular effect more concentrated + */ + this.specularPower = 250; + /** + * Minimum thickness of the particles (positive number). If useFixedThickness is true, minimumThickness is the thickness used + */ + this.minimumThickness = 0; + /** + * Direction of the light. The fluid is assumed to be lit by a directional light + */ + this.dirLight = new Vector3(-2, -1, 1).normalize(); + this._debugFeature = 1 /* FluidRenderingDebug.DepthBlurredTexture */; + this._debug = false; + this._enableBlurDepth = true; + this._blurDepthSizeDivisor = 1; + this._blurDepthFilterSize = 7; + this._blurDepthNumIterations = 3; + this._blurDepthMaxFilterSize = 100; + this._blurDepthDepthScale = 10; + this._enableBlurThickness = true; + this._blurThicknessSizeDivisor = 1; + this._blurThicknessFilterSize = 5; + this._blurThicknessNumIterations = 1; + this._useFixedThickness = false; + /** @internal */ + this._onUseVelocityChanged = new Observable(); + this._useVelocity = false; + this._depthMapSize = null; + this._thicknessMapSize = null; + this._diffuseMapSize = null; + this._samples = 1; + this._compositeMode = false; + /** Shader language used by the renderer */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._scene = scene; + this._engine = scene.getEngine(); + this._camera = camera ?? scene.activeCamera; + this._needInitialization = true; + this._bgDepthTexture = null; + this._invProjectionMatrix = new Matrix(); + this._depthClearColor = new Color4(1e6, 1e6, 1e6, 1); + this._thicknessClearColor = new Color4(0, 0, 0, 1); + this._depthRenderTarget = null; + this._diffuseRenderTarget = null; + this._thicknessRenderTarget = null; + this._renderPostProcess = null; + this._shaderLanguage = shaderLanguage ?? (this._engine.isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */); + } + /** @internal */ + _initialize() { + this.dispose(); + this._needInitialization = false; + const depthWidth = this._depthMapSize ?? this._engine.getRenderWidth(); + const depthHeight = this._depthMapSize !== null ? Math.round((this._depthMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth()) : this._engine.getRenderHeight(); + this._depthRenderTarget = new FluidRenderingTextures("Depth", this._scene, depthWidth, depthHeight, depthWidth, depthHeight, 1, 7, 1, 7, false, this._camera, true, this._samples, this._shaderLanguage); + this._initializeRenderTarget(this._depthRenderTarget); + if (this.generateDiffuseTexture) { + const diffuseWidth = this._diffuseMapSize ?? this._engine.getRenderWidth(); + const diffuseHeight = this._diffuseMapSize !== null + ? Math.round((this._diffuseMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth()) + : this._engine.getRenderHeight(); + this._diffuseRenderTarget = new FluidRenderingTextures("Diffuse", this._scene, diffuseWidth, diffuseHeight, 0, 0, 0, 5, 0, 5, true, this._camera, true, this._samples, this._shaderLanguage); + this._initializeRenderTarget(this._diffuseRenderTarget); + } + const thicknessWidth = this._thicknessMapSize ?? this._engine.getRenderWidth(); + const thicknessHeight = this._thicknessMapSize !== null + ? Math.round((this._thicknessMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth()) + : this._engine.getRenderHeight(); + if (!this._useFixedThickness) { + this._thicknessRenderTarget = new FluidRenderingTextures("Thickness", this._scene, thicknessWidth, thicknessHeight, thicknessWidth, thicknessHeight, 2, 6, 2, 6, true, this._camera, false, this._samples, this._shaderLanguage); + this._initializeRenderTarget(this._thicknessRenderTarget); + } + this._createLiquidRenderingPostProcess(); + } + _setBlurParameters(renderTarget = null) { + if (renderTarget === null || renderTarget === this._depthRenderTarget) { + this._setBlurDepthParameters(); + } + if (renderTarget === null || renderTarget === this._thicknessRenderTarget) { + this._setBlurThicknessParameters(); + } + } + _setBlurDepthParameters() { + if (!this._depthRenderTarget) { + return; + } + this._depthRenderTarget.blurFilterSize = this.blurDepthFilterSize; + this._depthRenderTarget.blurMaxFilterSize = this.blurDepthMaxFilterSize; + this._depthRenderTarget.blurNumIterations = this.blurDepthNumIterations; + this._depthRenderTarget.blurDepthScale = this.blurDepthDepthScale; + } + _setBlurThicknessParameters() { + if (!this._thicknessRenderTarget) { + return; + } + this._thicknessRenderTarget.blurFilterSize = this.blurThicknessFilterSize; + this._thicknessRenderTarget.blurNumIterations = this.blurThicknessNumIterations; + } + _initializeRenderTarget(renderTarget) { + if (renderTarget !== this._diffuseRenderTarget) { + renderTarget.enableBlur = renderTarget === this._depthRenderTarget ? this.enableBlurDepth : this.enableBlurThickness; + renderTarget.blurSizeDivisor = renderTarget === this._depthRenderTarget ? this.blurDepthSizeDivisor : this.blurThicknessSizeDivisor; + } + this._setBlurParameters(renderTarget); + renderTarget.initialize(); + } + _createLiquidRenderingPostProcess() { + const engine = this._scene.getEngine(); + const uniformNames = [ + "viewMatrix", + "projectionMatrix", + "invProjectionMatrix", + "texelSize", + "dirLight", + "cameraFar", + "density", + "refractionStrength", + "fresnelClamp", + "specularPower", + ]; + const samplerNames = ["depthSampler"]; + const defines = []; + this.dispose(true); + if (!this._camera) { + return; + } + const texture = this._depthRenderTarget.enableBlur ? this._depthRenderTarget.textureBlur : this._depthRenderTarget.texture; + const texelSize = new Vector2(1 / texture.getSize().width, 1 / texture.getSize().height); + if (this._scene.useRightHandedSystem) { + defines.push("#define FLUIDRENDERING_RHS"); + } + if (this._environmentMap !== null) { + const envMap = this._environmentMap ?? this._scene.environmentTexture; + if (envMap) { + samplerNames.push("reflectionSampler"); + defines.push("#define FLUIDRENDERING_ENVIRONMENT"); + } + } + if (this._diffuseRenderTarget) { + samplerNames.push("diffuseSampler"); + defines.push("#define FLUIDRENDERING_DIFFUSETEXTURE"); + } + else { + uniformNames.push("diffuseColor"); + } + if (this._useVelocity) { + samplerNames.push("velocitySampler"); + defines.push("#define FLUIDRENDERING_VELOCITY"); + } + if (this._useFixedThickness) { + uniformNames.push("thickness"); + samplerNames.push("bgDepthSampler"); + defines.push("#define FLUIDRENDERING_FIXED_THICKNESS"); + } + else { + uniformNames.push("minimumThickness"); + samplerNames.push("thicknessSampler"); + } + if (this._compositeMode) { + defines.push("#define FLUIDRENDERING_COMPOSITE_MODE"); + } + if (this._debug) { + defines.push("#define FLUIDRENDERING_DEBUG"); + if (this._debugFeature === 5 /* FluidRenderingDebug.Normals */) { + defines.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"); + } + else if (this._debugFeature === 6 /* FluidRenderingDebug.DiffuseRendering */) { + defines.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"); + } + else { + defines.push("#define FLUIDRENDERING_DEBUG_TEXTURE"); + samplerNames.push("debugSampler"); + if (this._debugFeature === 0 /* FluidRenderingDebug.DepthTexture */ || this._debugFeature === 1 /* FluidRenderingDebug.DepthBlurredTexture */) { + defines.push("#define FLUIDRENDERING_DEBUG_DEPTH"); + } + } + } + this._renderPostProcess = new PostProcess("FluidRendering", "fluidRenderingRender", uniformNames, samplerNames, 1, null, 2, engine, false, null, 0, undefined, undefined, true, undefined, this._shaderLanguage, async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => fluidRenderingRender_fragment); + } + else { + await Promise.resolve().then(() => fluidRenderingRender_fragment$1); + } + }); + this._renderPostProcess.updateEffect(defines.join("\n")); + this._renderPostProcess.samples = this._samples; + const engineWebGPU = engine; + const setTextureSampler = engineWebGPU.setTextureSampler; + this._renderPostProcess.onApplyObservable.add((effect) => { + this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()); + this._invProjectionMatrix.invert(); + if (setTextureSampler) { + setTextureSampler.call(engineWebGPU, "textureSamplerSampler", this._renderPostProcess.inputTexture.texture); + } + if (!this._depthRenderTarget.enableBlur) { + effect.setTexture("depthSampler", this._depthRenderTarget.texture); + if (setTextureSampler) { + setTextureSampler.call(engineWebGPU, "depthSamplerSampler", this._depthRenderTarget.texture?.getInternalTexture() ?? null); + } + } + else { + effect.setTexture("depthSampler", this._depthRenderTarget.textureBlur); + if (setTextureSampler) { + setTextureSampler.call(engineWebGPU, "depthSamplerSampler", this._depthRenderTarget.textureBlur?.getInternalTexture() ?? null); + } + } + if (this._diffuseRenderTarget) { + if (!this._diffuseRenderTarget.enableBlur) { + effect.setTexture("diffuseSampler", this._diffuseRenderTarget.texture); + if (setTextureSampler) { + setTextureSampler.call(engineWebGPU, "diffuseSamplerSampler", this._diffuseRenderTarget.texture?.getInternalTexture() ?? null); + } + } + else { + effect.setTexture("diffuseSampler", this._diffuseRenderTarget.textureBlur); + if (setTextureSampler) { + setTextureSampler.call(engineWebGPU, "diffuseSamplerSampler", this._diffuseRenderTarget.textureBlur?.getInternalTexture() ?? null); + } + } + } + else { + effect.setColor3("diffuseColor", this.fluidColor); + } + if (this._useFixedThickness) { + effect.setFloat("thickness", this.minimumThickness); + effect._bindTexture("bgDepthSampler", this._bgDepthTexture); + if (setTextureSampler) { + setTextureSampler.call(engineWebGPU, "bgDepthSamplerSampler", this._bgDepthTexture ?? null); + } + } + else { + if (!this._thicknessRenderTarget.enableBlur) { + effect.setTexture("thicknessSampler", this._thicknessRenderTarget.texture); + if (setTextureSampler) { + setTextureSampler.call(engineWebGPU, "thicknessSamplerSampler", this._thicknessRenderTarget.texture?.getInternalTexture() ?? null); + } + } + else { + effect.setTexture("thicknessSampler", this._thicknessRenderTarget.textureBlur); + if (setTextureSampler) { + setTextureSampler.call(engineWebGPU, "thicknessSamplerSampler", this._thicknessRenderTarget.textureBlur?.getInternalTexture() ?? null); + } + } + effect.setFloat("minimumThickness", this.minimumThickness); + } + if (this._environmentMap !== null) { + const envMap = this._environmentMap ?? this._scene.environmentTexture; + if (envMap) { + effect.setTexture("reflectionSampler", envMap); + if (setTextureSampler) { + setTextureSampler.call(engineWebGPU, "reflectionSamplerSampler", envMap?.getInternalTexture() ?? null); + } + } + } + effect.setMatrix("viewMatrix", this._scene.getViewMatrix()); + effect.setMatrix("invProjectionMatrix", this._invProjectionMatrix); + effect.setMatrix("projectionMatrix", this._scene.getProjectionMatrix()); + effect.setVector2("texelSize", texelSize); + effect.setFloat("density", this.density); + effect.setFloat("refractionStrength", this.refractionStrength); + effect.setFloat("fresnelClamp", this.fresnelClamp); + effect.setFloat("specularPower", this.specularPower); + effect.setVector3("dirLight", this.dirLight); + effect.setFloat("cameraFar", this._camera.maxZ); + if (this._debug) { + let texture = null; + switch (this._debugFeature) { + case 0 /* FluidRenderingDebug.DepthTexture */: + texture = this._depthRenderTarget.texture; + break; + case 1 /* FluidRenderingDebug.DepthBlurredTexture */: + texture = this._depthRenderTarget.enableBlur ? this._depthRenderTarget.textureBlur : this._depthRenderTarget.texture; + break; + case 2 /* FluidRenderingDebug.ThicknessTexture */: + texture = this._thicknessRenderTarget?.texture ?? null; + break; + case 3 /* FluidRenderingDebug.ThicknessBlurredTexture */: + texture = this._thicknessRenderTarget?.enableBlur ? (this._thicknessRenderTarget?.textureBlur ?? null) : (this._thicknessRenderTarget?.texture ?? null); + break; + case 4 /* FluidRenderingDebug.DiffuseTexture */: + if (this._diffuseRenderTarget) { + texture = this._diffuseRenderTarget.texture; + } + break; + } + if (this._debugFeature !== 5 /* FluidRenderingDebug.Normals */) { + effect.setTexture("debugSampler", texture); + if (setTextureSampler) { + setTextureSampler.call(engineWebGPU, "debugSamplerSampler", texture?.getInternalTexture() ?? null); + } + } + } + }); + } + /** @internal */ + _clearTargets() { + if (this._depthRenderTarget?.renderTarget) { + this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget); + this._engine.clear(this._depthClearColor, true, true, false); + this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget); + } + if (this._diffuseRenderTarget?.renderTarget) { + this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget); + this._engine.clear(this._thicknessClearColor, true, true, false); + this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget); + } + if (this._thicknessRenderTarget?.renderTarget) { + this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget); + // we don't clear the depth buffer because it is the depth buffer that is coming from the scene and that we reuse in the thickness rendering pass + this._engine.clear(this._thicknessClearColor, true, false, false); + this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget); + } + } + /** @internal */ + _render(fluidObject) { + if (this._needInitialization || !fluidObject.isReady()) { + return; + } + const currentRenderTarget = this._engine._currentRenderTarget; + this._engine.setState(false, undefined, undefined, undefined, true); + this._engine.setDepthBuffer(true); + this._engine.setDepthWrite(true); + this._engine.setAlphaMode(0); + // Render the particles in the depth texture + if (this._depthRenderTarget?.renderTarget) { + this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget); + fluidObject.renderDepthTexture(); + this._engine.unbindInstanceAttributes(); + this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget); + } + // Render the particles in the diffuse texture + if (this._diffuseRenderTarget?.renderTarget) { + this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget); + fluidObject.renderDiffuseTexture(); + this._engine.unbindInstanceAttributes(); + this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget); + } + // Render the particles in the thickness texture + if (this._thicknessRenderTarget?.renderTarget) { + this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget); + fluidObject.renderThicknessTexture(); + this._engine.unbindInstanceAttributes(); + this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget); + } + // Run the blur post processes + this._depthRenderTarget?.applyBlurPostProcesses(); + this._diffuseRenderTarget?.applyBlurPostProcesses(); + this._thicknessRenderTarget?.applyBlurPostProcesses(); + if (currentRenderTarget) { + this._engine.bindFramebuffer(currentRenderTarget); + } + } + /** + * Releases all the ressources used by the class + * @param onlyPostProcesses If true, releases only the ressources used by the render post processes + */ + dispose(onlyPostProcesses = false) { + if (!onlyPostProcesses) { + this._depthRenderTarget?.dispose(); + this._depthRenderTarget = null; + this._diffuseRenderTarget?.dispose(); + this._diffuseRenderTarget = null; + this._thicknessRenderTarget?.dispose(); + this._thicknessRenderTarget = null; + } + if (this._renderPostProcess && this._camera) { + this._camera.detachPostProcess(this._renderPostProcess); + } + this._renderPostProcess?.dispose(); + this._renderPostProcess = null; + this._onUseVelocityChanged.clear(); + this._needInitialization = false; + } +} + +/** + * Defines a rendering object based on a list of custom buffers + * The list must contain at least a "position" buffer! + */ +class FluidRenderingObjectCustomParticles extends FluidRenderingObject { + /** + * @returns the name of the class + */ + getClassName() { + return "FluidRenderingObjectCustomParticles"; + } + /** + * Gets the vertex buffers + */ + get vertexBuffers() { + return this._vertexBuffers; + } + /** + * Creates a new instance of the class + * @param scene The scene the particles should be rendered into + * @param buffers The list of buffers (must contain at least one "position" buffer!). Note that you don't have to pass all (or any!) buffers at once in the constructor, you can use the addBuffers method to add more later. + * @param numParticles Number of vertices to take into account from the buffers + * @param shaderLanguage The shader language to use + */ + constructor(scene, buffers, numParticles, shaderLanguage) { + super(scene, shaderLanguage); + this._numParticles = numParticles; + this._diffuseEffectWrapper = null; + this._vertexBuffers = {}; + this.addBuffers(buffers); + } + /** + * Add some new buffers + * @param buffers List of buffers + */ + addBuffers(buffers) { + for (const name in buffers) { + let stride; + let instanced = true; + switch (name) { + case "velocity": + stride = 3; + break; + case "offset": + instanced = false; + break; + } + this._vertexBuffers[name] = new VertexBuffer(this._engine, buffers[name], name, true, false, stride, instanced); + } + } + _createEffects() { + super._createEffects(); + const uniformNames = ["view", "projection", "size"]; + const attributeNames = ["position", "offset", "color"]; + this._diffuseEffectWrapper = new EffectWrapper({ + engine: this._engine, + useShaderStore: true, + vertexShader: "fluidRenderingParticleDiffuse", + fragmentShader: "fluidRenderingParticleDiffuse", + attributeNames, + uniformNames, + samplerNames: [], + shaderLanguage: this._shaderLanguage, + extraInitializationsAsync: async () => { + if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + await Promise.resolve().then(() => fluidRenderingParticleDiffuse_fragment); + } + else { + await Promise.resolve().then(() => fluidRenderingParticleDiffuse_fragment$1); + } + }, + }); + } + /** + * Indicates if the object is ready to be rendered + * @returns True if everything is ready for the object to be rendered, otherwise false + */ + isReady() { + if (!this._vertexBuffers["offset"]) { + this._vertexBuffers["offset"] = new VertexBuffer(this._engine, [0, 0, 1, 0, 0, 1, 1, 1], "offset", false, false, 2); + } + return super.isReady() && (this._diffuseEffectWrapper?.effect.isReady() ?? false); + } + /** + * Gets the number of particles in this object + * @returns The number of particles + */ + get numParticles() { + return this._numParticles; + } + /** + * Sets the number of particles in this object + * @param num The number of particles to take into account + */ + setNumParticles(num) { + this._numParticles = num; + } + /** + * Render the diffuse texture for this object + */ + renderDiffuseTexture() { + const numParticles = this.numParticles; + if (!this._diffuseEffectWrapper || numParticles === 0) { + return; + } + const diffuseDrawWrapper = this._diffuseEffectWrapper.drawWrapper; + const diffuseEffect = diffuseDrawWrapper.effect; + this._engine.enableEffect(diffuseDrawWrapper); + this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, diffuseEffect); + diffuseEffect.setMatrix("view", this._scene.getViewMatrix()); + diffuseEffect.setMatrix("projection", this._scene.getProjectionMatrix()); + if (this._particleSize !== null) { + diffuseEffect.setFloat2("size", this._particleSize, this._particleSize); + } + if (this.useInstancing) { + this._engine.drawArraysType(7, 0, 4, numParticles); + } + else { + this._engine.drawElementsType(0, 0, numParticles); + } + } + /** + * Releases the ressources used by the class + */ + dispose() { + super.dispose(); + this._diffuseEffectWrapper?.dispose(); + for (const name in this._vertexBuffers) { + this._vertexBuffers[name].dispose(); + } + this._vertexBuffers = {}; + } +} + +/** @internal */ +class FluidRenderingDepthTextureCopy { + get depthRTWrapper() { + return this._depthRTWrapper; + } + constructor(engine, width, height, samples = 1) { + this._engine = engine; + this._copyTextureToTexture = new CopyTextureToTexture(engine, true); + this._depthRTWrapper = this._engine.createRenderTargetTexture({ width, height }, { + generateMipMaps: false, + type: 0, + format: 6, + samplingMode: 1, + generateDepthBuffer: true, + generateStencilBuffer: false, + samples, + noColorAttachment: true, + label: "FluidRenderingDepthTextureCopyRTT", + }); + const depthTexture = this._depthRTWrapper.createDepthStencilTexture(0, false, false, 1, undefined, "FluidRenderingDepthTextureCopyRTTDepthStencil"); + depthTexture.label = `FluidDepthTextureCopy${width}x${height}x${samples}`; + } + copy(source) { + return this._copyTextureToTexture.copy(source, this._depthRTWrapper); + } + dispose() { + this._depthRTWrapper.dispose(); + this._copyTextureToTexture.dispose(); + } +} + +Object.defineProperty(Scene.prototype, "fluidRenderer", { + get: function () { + return this._fluidRenderer; + }, + set: function (value) { + this._fluidRenderer = value; + }, + enumerable: true, + configurable: true, +}); +Scene.prototype.enableFluidRenderer = function () { + if (this._fluidRenderer) { + return this._fluidRenderer; + } + this._fluidRenderer = new FluidRenderer(this); + return this._fluidRenderer; +}; +Scene.prototype.disableFluidRenderer = function () { + this._fluidRenderer?.dispose(); + this._fluidRenderer = null; +}; +function IsParticleSystemObject(obj) { + return !!obj.particleSystem; +} +function IsCustomParticlesObject(obj) { + return !!obj.addBuffers; +} +/** + * Defines the fluid renderer scene component responsible to render objects as fluids + */ +class FluidRendererSceneComponent { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + constructor(scene) { + /** + * The component name helpful to identify the component in the list of scene components. + */ + this.name = SceneComponentConstants.NAME_FLUIDRENDERER; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + register() { + this.scene._gatherActiveCameraRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER, this, this._gatherActiveCameraRenderTargets); + this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER, this, this._afterCameraDraw); + } + _gatherActiveCameraRenderTargets(_renderTargets) { + this.scene.fluidRenderer?._prepareRendering(); + } + _afterCameraDraw(camera) { + this.scene.fluidRenderer?._render(camera); + } + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + rebuild() { + const fluidRenderer = this.scene.fluidRenderer; + if (!fluidRenderer) { + return; + } + const buffers = new Set(); + for (let i = 0; i < fluidRenderer.renderObjects.length; ++i) { + const obj = fluidRenderer.renderObjects[i].object; + if (IsCustomParticlesObject(obj)) { + const vbuffers = obj.vertexBuffers; + for (const name in vbuffers) { + buffers.add(vbuffers[name].getWrapperBuffer()); + } + } + } + buffers.forEach((buffer) => { + buffer._rebuild(); + }); + } + /** + * Disposes the component and the associated resources + */ + dispose() { + this.scene.disableFluidRenderer(); + } +} +/** + * Class responsible for fluid rendering. + * It is implementing the method described in https://developer.download.nvidia.com/presentations/2010/gdc/Direct3D_Effects.pdf + */ +class FluidRenderer { + /** @internal */ + static _SceneComponentInitialization(scene) { + let component = scene._getComponent(SceneComponentConstants.NAME_FLUIDRENDERER); + if (!component) { + component = new FluidRendererSceneComponent(scene); + scene._addComponent(component); + } + } + /** + * Gets the shader language used in this renderer + */ + get shaderLanguage() { + return this._shaderLanguage; + } + /** + * Initializes the class + * @param scene Scene in which the objects are part of + */ + constructor(scene) { + /** Shader language used by the renderer */ + this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; + this._scene = scene; + this._engine = scene.getEngine(); + this._onEngineResizeObserver = null; + this.renderObjects = []; + this.targetRenderers = []; + this._cameras = new Map(); + FluidRenderer._SceneComponentInitialization(this._scene); + this._onEngineResizeObserver = this._engine.onResizeObservable.add(() => { + this._initialize(); + }); + const engine = this._engine; + if (engine.isWebGPU) { + this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; + } + } + /** + * Reinitializes the class + * Can be used if you change the object priority (FluidRenderingObject.priority), to make sure the objects are rendered in the right order + */ + recreate() { + this._sortRenderingObjects(); + this._initialize(); + } + /** + * Gets the render object corresponding to a particle system (null if the particle system is not rendered as a fluid) + * @param ps The particle system + * @returns the render object corresponding to this particle system if any, otherwise null + */ + getRenderObjectFromParticleSystem(ps) { + const index = this._getParticleSystemIndex(ps); + return index !== -1 ? this.renderObjects[index] : null; + } + /** + * Adds a particle system to the fluid renderer. + * @param ps particle system + * @param generateDiffuseTexture True if you want to generate a diffuse texture from the particle system and use it as part of the fluid rendering (default: false) + * @param targetRenderer The target renderer used to display the particle system as a fluid. If not provided, the method will create a new one + * @param camera The camera used by the target renderer (if the target renderer is created by the method) + * @returns the render object corresponding to the particle system + */ + addParticleSystem(ps, generateDiffuseTexture, targetRenderer, camera) { + const object = new FluidRenderingObjectParticleSystem(this._scene, ps, this._shaderLanguage); + object.onParticleSizeChanged.add(() => this._setParticleSizeForRenderTargets()); + if (!targetRenderer) { + targetRenderer = new FluidRenderingTargetRenderer(this._scene, camera, this._shaderLanguage); + this.targetRenderers.push(targetRenderer); + } + if (!targetRenderer._onUseVelocityChanged.hasObservers()) { + targetRenderer._onUseVelocityChanged.add(() => this._setUseVelocityForRenderObject()); + } + if (generateDiffuseTexture !== undefined) { + targetRenderer.generateDiffuseTexture = generateDiffuseTexture; + } + const renderObject = { object, targetRenderer }; + this.renderObjects.push(renderObject); + this._sortRenderingObjects(); + this._setParticleSizeForRenderTargets(); + return renderObject; + } + /** + * Adds a custom particle set to the fluid renderer. + * @param buffers The list of buffers (should contain at least a "position" buffer!) + * @param numParticles Number of particles in each buffer + * @param generateDiffuseTexture True if you want to generate a diffuse texture from buffers and use it as part of the fluid rendering (default: false). For the texture to be generated correctly, you need a "color" buffer in the set! + * @param targetRenderer The target renderer used to display the particle system as a fluid. If not provided, the method will create a new one + * @param camera The camera used by the target renderer (if the target renderer is created by the method) + * @returns the render object corresponding to the custom particle set + */ + addCustomParticles(buffers, numParticles, generateDiffuseTexture, targetRenderer, camera) { + const object = new FluidRenderingObjectCustomParticles(this._scene, buffers, numParticles, this._shaderLanguage); + object.onParticleSizeChanged.add(() => this._setParticleSizeForRenderTargets()); + if (!targetRenderer) { + targetRenderer = new FluidRenderingTargetRenderer(this._scene, camera, this._shaderLanguage); + this.targetRenderers.push(targetRenderer); + } + if (!targetRenderer._onUseVelocityChanged.hasObservers()) { + targetRenderer._onUseVelocityChanged.add(() => this._setUseVelocityForRenderObject()); + } + if (generateDiffuseTexture !== undefined) { + targetRenderer.generateDiffuseTexture = generateDiffuseTexture; + } + const renderObject = { object, targetRenderer }; + this.renderObjects.push(renderObject); + this._sortRenderingObjects(); + this._setParticleSizeForRenderTargets(); + return renderObject; + } + /** + * Removes a render object from the fluid renderer + * @param renderObject the render object to remove + * @param removeUnusedTargetRenderer True to remove/dispose of the target renderer if it's not used anymore (default: true) + * @returns True if the render object has been found and released, else false + */ + removeRenderObject(renderObject, removeUnusedTargetRenderer = true) { + const index = this.renderObjects.indexOf(renderObject); + if (index === -1) { + return false; + } + renderObject.object.dispose(); + this.renderObjects.splice(index, 1); + if (removeUnusedTargetRenderer && this._removeUnusedTargetRenderers()) { + this._initialize(); + } + else { + this._setParticleSizeForRenderTargets(); + } + return true; + } + _sortRenderingObjects() { + this.renderObjects.sort((a, b) => { + return a.object.priority < b.object.priority ? -1 : a.object.priority > b.object.priority ? 1 : 0; + }); + } + _removeUnusedTargetRenderers() { + const indexes = {}; + for (let i = 0; i < this.renderObjects.length; ++i) { + const targetRenderer = this.renderObjects[i].targetRenderer; + indexes[this.targetRenderers.indexOf(targetRenderer)] = true; + } + let removed = false; + const newList = []; + for (let i = 0; i < this.targetRenderers.length; ++i) { + if (!indexes[i]) { + this.targetRenderers[i].dispose(); + removed = true; + } + else { + newList.push(this.targetRenderers[i]); + } + } + if (removed) { + this.targetRenderers.length = 0; + this.targetRenderers.push(...newList); + } + return removed; + } + _getParticleSystemIndex(ps) { + for (let i = 0; i < this.renderObjects.length; ++i) { + const obj = this.renderObjects[i].object; + if (IsParticleSystemObject(obj) && obj.particleSystem === ps) { + return i; + } + } + return -1; + } + _initialize() { + for (let i = 0; i < this.targetRenderers.length; ++i) { + this.targetRenderers[i].dispose(); + } + const cameras = new Map(); + for (let i = 0; i < this.targetRenderers.length; ++i) { + const targetRenderer = this.targetRenderers[i]; + targetRenderer._initialize(); + if (targetRenderer.camera && targetRenderer._renderPostProcess) { + let list = cameras.get(targetRenderer.camera); + if (!list) { + list = [[], {}]; + cameras.set(targetRenderer.camera, list); + } + list[0].push(targetRenderer); + targetRenderer.camera.attachPostProcess(targetRenderer._renderPostProcess, i); + } + } + let iterator = cameras.keys(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const camera = key.value; + const list = cameras.get(camera); + const firstPostProcess = camera._getFirstPostProcess(); + if (!firstPostProcess) { + continue; + } + const [targetRenderers, copyDepthTextures] = list; + firstPostProcess.onSizeChangedObservable.add(() => { + if (!firstPostProcess.inputTexture.depthStencilTexture) { + firstPostProcess.inputTexture.createDepthStencilTexture(0, true, this._engine.isStencilEnable, targetRenderers[0].samples, this._engine.isStencilEnable ? 13 : 14, `PostProcessRTTDepthStencil-${firstPostProcess.name}`); + } + for (const targetRenderer of targetRenderers) { + const thicknessRT = targetRenderer._thicknessRenderTarget?.renderTarget; + const thicknessTexture = thicknessRT?.texture; + if (thicknessRT && thicknessTexture) { + const key = thicknessTexture.width + "_" + thicknessTexture.height; + let copyDepthTexture = copyDepthTextures[key]; + if (!copyDepthTexture) { + copyDepthTexture = copyDepthTextures[key] = new FluidRenderingDepthTextureCopy(this._engine, thicknessTexture.width, thicknessTexture.height); + } + copyDepthTexture.depthRTWrapper.shareDepth(thicknessRT); + } + } + }); + } + // Dispose the CopyDepthTexture instances that we don't need anymore + iterator = this._cameras.keys(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const camera = key.value; + const list = this._cameras.get(camera); + const copyDepthTextures = list[1]; + const list2 = cameras.get(camera); + if (!list2) { + for (const key in copyDepthTextures) { + copyDepthTextures[key].dispose(); + } + } + else { + for (const key in copyDepthTextures) { + if (!list2[1][key]) { + copyDepthTextures[key].dispose(); + } + } + } + } + this._cameras.clear(); + this._cameras = cameras; + this._setParticleSizeForRenderTargets(); + } + _setParticleSizeForRenderTargets() { + const particleSizes = new Map(); + for (let i = 0; i < this.renderObjects.length; ++i) { + const renderingObject = this.renderObjects[i]; + let curSize = particleSizes.get(renderingObject.targetRenderer); + if (curSize === undefined) { + curSize = 0; + } + particleSizes.set(renderingObject.targetRenderer, Math.max(curSize, renderingObject.object.particleSize)); + } + particleSizes.forEach((particleSize, targetRenderer) => { + if (targetRenderer._depthRenderTarget) { + targetRenderer._depthRenderTarget.particleSize = particleSize; + } + }); + } + _setUseVelocityForRenderObject() { + for (const renderingObject of this.renderObjects) { + renderingObject.object.useVelocity = renderingObject.targetRenderer.useVelocity; + } + } + /** @internal */ + _prepareRendering() { + for (const renderer of this.targetRenderers) { + if (renderer.needInitialization) { + this._initialize(); + return; + } + } + } + /** @internal */ + _render(forCamera) { + for (let i = 0; i < this.targetRenderers.length; ++i) { + if (!forCamera || this.targetRenderers[i].camera === forCamera) { + this.targetRenderers[i]._clearTargets(); + } + } + const iterator = this._cameras.keys(); + for (let key = iterator.next(); key.done !== true; key = iterator.next()) { + const camera = key.value; + const list = this._cameras.get(camera); + if (forCamera && camera !== forCamera) { + continue; + } + const firstPostProcess = camera._getFirstPostProcess(); + if (!firstPostProcess) { + continue; + } + const sourceCopyDepth = firstPostProcess.inputTexture?.depthStencilTexture; + if (sourceCopyDepth) { + const [targetRenderers, copyDepthTextures] = list; + for (const targetRenderer of targetRenderers) { + targetRenderer._bgDepthTexture = sourceCopyDepth; + } + for (const key in copyDepthTextures) { + copyDepthTextures[key].copy(sourceCopyDepth); + } + } + } + for (let i = 0; i < this.renderObjects.length; ++i) { + const renderingObject = this.renderObjects[i]; + if (!forCamera || renderingObject.targetRenderer.camera === forCamera) { + renderingObject.targetRenderer._render(renderingObject.object); + } + } + } + /** + * Disposes of all the ressources used by the class + */ + dispose() { + this._engine.onResizeObservable.remove(this._onEngineResizeObserver); + this._onEngineResizeObserver = null; + for (let i = 0; i < this.renderObjects.length; ++i) { + this.renderObjects[i].object.dispose(); + } + for (let i = 0; i < this.targetRenderers.length; ++i) { + this.targetRenderers[i].dispose(); + } + this._cameras.forEach((list) => { + const copyDepthTextures = list[1]; + for (const key in copyDepthTextures) { + copyDepthTextures[key].dispose(); + } + }); + this.renderObjects = []; + this.targetRenderers = []; + this._cameras.clear(); + } +} + +// Do not edit. +const name$1B = "fluidRenderingParticleDepthVertexShader"; +const shader$1A = `attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +#ifdef FLUIDRENDERING_VELOCITY +attribute vec3 velocity;varying float velocityNorm; +#endif +void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; +#ifdef FLUIDRENDERING_VELOCITY +velocityNorm=length(velocity); +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1B]) { + ShaderStore.ShadersStore[name$1B] = shader$1A; +} +/** @internal */ +const fluidRenderingParticleDepthVertexShader = { name: name$1B, shader: shader$1A }; + +const fluidRenderingParticleDepth_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + fluidRenderingParticleDepthVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1A = "fluidRenderingParticleDepthPixelShader"; +const shader$1z = `uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +#ifdef FLUIDRENDERING_VELOCITY +varying float velocityNorm; +#endif +void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); +#ifndef FLUIDRENDERING_RHS +normal.z=-normal.z; +#endif +vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; +#ifdef WEBGPU +gl_FragDepth=clipSpacePos.z/clipSpacePos.w; +#else +gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; +#endif +#ifdef FLUIDRENDERING_RHS +realViewPos.z=-realViewPos.z; +#endif +#ifdef FLUIDRENDERING_VELOCITY +glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); +#else +glFragColor=vec4(realViewPos.z,0.,0.,1.); +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1A]) { + ShaderStore.ShadersStore[name$1A] = shader$1z; +} +/** @internal */ +const fluidRenderingParticleDepthPixelShader = { name: name$1A, shader: shader$1z }; + +const fluidRenderingParticleDepth_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + fluidRenderingParticleDepthPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1z = "fluidRenderingParticleThicknessVertexShader"; +const shader$1y = `attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1z]) { + ShaderStore.ShadersStore[name$1z] = shader$1y; +} +/** @internal */ +const fluidRenderingParticleThicknessVertexShader = { name: name$1z, shader: shader$1y }; + +const fluidRenderingParticleThickness_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + fluidRenderingParticleThicknessVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1y = "fluidRenderingParticleThicknessPixelShader"; +const shader$1x = `uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1y]) { + ShaderStore.ShadersStore[name$1y] = shader$1x; +} +/** @internal */ +const fluidRenderingParticleThicknessPixelShader = { name: name$1y, shader: shader$1x }; + +const fluidRenderingParticleThickness_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + fluidRenderingParticleThicknessPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1x = "fluidRenderingParticleDiffuseVertexShader"; +const shader$1w = `attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1x]) { + ShaderStore.ShadersStore[name$1x] = shader$1w; +} + +// Do not edit. +const name$1w = "fluidRenderingParticleDiffusePixelShader"; +const shader$1v = `uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1w]) { + ShaderStore.ShadersStore[name$1w] = shader$1v; +} + +const fluidRenderingParticleDiffuse_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1v = "fluidRenderingBilateralBlurPixelShader"; +const shader$1u = `uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} +int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} +glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1v]) { + ShaderStore.ShadersStore[name$1v] = shader$1u; +} + +const fluidRenderingBilateralBlur_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1u = "fluidRenderingStandardBlurPixelShader"; +const shader$1t = `uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} +float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} +sum/=wsum;glFragColor=vec4(sum.rgb,1.);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1u]) { + ShaderStore.ShadersStore[name$1u] = shader$1t; +} + +const fluidRenderingStandardBlur_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1t = "fluidRenderingRenderPixelShader"; +const shader$1s = `#define DISABLE_UNIFORMITY_ANALYSIS +#define IOR 1.333 +#define ETA 1.0/IOR +#define F0 0.02 +uniform sampler2D textureSampler;uniform sampler2D depthSampler; +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +uniform sampler2D diffuseSampler; +#else +uniform vec3 diffuseColor; +#endif +#ifdef FLUIDRENDERING_FIXED_THICKNESS +uniform float thickness;uniform sampler2D bgDepthSampler; +#else +uniform float minimumThickness;uniform sampler2D thicknessSampler; +#endif +#ifdef FLUIDRENDERING_ENVIRONMENT +uniform samplerCube reflectionSampler; +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +uniform sampler2D debugSampler; +#endif +uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; +#ifdef FLUIDRENDERING_RHS +ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; +#else +ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} +void main(void) {vec2 texCoord=vUV; +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +vec4 color=texture2D(debugSampler,texCoord); +#ifdef FLUIDRENDERING_DEBUG_DEPTH +glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} +#else +glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} +#endif +return; +#endif +vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; +#ifndef FLUIDRENDERING_FIXED_THICKNESS +float thickness=texture2D(thicknessSampler,texCoord).x; +#else +float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; +#endif +vec4 backColor=texture2D(textureSampler,texCoord); +#ifndef FLUIDRENDERING_FIXED_THICKNESS +if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { +#else +if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { +#endif +#ifdef FLUIDRENDERING_COMPOSITE_MODE +glFragColor.rgb=backColor.rgb*backColor.a;glFragColor.a=backColor.a; +#else +glFragColor=backColor; +#endif +return;} +vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} +vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} +vec3 normal=normalize(cross(ddy,ddx)); +#ifdef FLUIDRENDERING_RHS +normal=-normal; +#endif +#ifndef WEBGPU +if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) +glFragColor=vec4(normal*0.5+0.5,1.0);return; +#endif +vec3 rayDir=normalize(viewPos); +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; +#endif +vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); +#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING +float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; +#endif +vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0); +#ifdef FLUIDRENDERING_COMPOSITE_MODE +if (transmitted.a==0.) transmitted.a=thickness; +#endif +vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); +vec3 refractionColor=transmitted.rgb*transmittance; +#ifdef FLUIDRENDERING_ENVIRONMENT +vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; +#else +vec3 finalColor=refractionColor+specular; +#endif +#ifdef FLUIDRENDERING_VELOCITY +float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); +#endif +glFragColor=vec4(finalColor,transmitted.a);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1t]) { + ShaderStore.ShadersStore[name$1t] = shader$1s; +} + +const fluidRenderingRender_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1s = "fluidRenderingParticleDepthVertexShader"; +const shader$1r = `attribute position: vec3f;attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;varying viewPos: vec3f;varying sphereRadius: f32; +#ifdef FLUIDRENDERING_VELOCITY +attribute velocity: vec3f;varying velocityNorm: f32; +#endif +@vertex +fn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f( +vec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size, +0.0 +);vertexOutputs.viewPos=(uniforms.view*vec4f(input.position,1.0)).xyz;vertexOutputs.position=uniforms.projection*vec4f(vertexOutputs.viewPos+cornerPos,1.0);vertexOutputs.uv=input.offset;vertexOutputs.sphereRadius=uniforms.size.x/2.0; +#ifdef FLUIDRENDERING_VELOCITY +vertexOutputs.velocityNorm=length(velocity); +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1s]) { + ShaderStore.ShadersStoreWGSL[name$1s] = shader$1r; +} +/** @internal */ +const fluidRenderingParticleDepthVertexShaderWGSL = { name: name$1s, shader: shader$1r }; + +const fluidRenderingParticleDepth_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + fluidRenderingParticleDepthVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1r = "fluidRenderingParticleDepthPixelShader"; +const shader$1q = `uniform projection: mat4x4f;varying uv: vec2f;varying viewPos: vec3f;varying sphereRadius: f32; +#ifdef FLUIDRENDERING_VELOCITY +varying velocityNorm: f32; +#endif +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;} +var normal: vec3f=vec3f(normalxy,sqrt(1.0-r2)); +#ifndef FLUIDRENDERING_RHS +normal.z=-normal.z; +#endif +var realViewPos: vec4f=vec4f(input.viewPos+normal*input.sphereRadius,1.0);var clipSpacePos: vec4f=uniforms.projection*realViewPos;fragmentOutputs.fragDepth=clipSpacePos.z/clipSpacePos.w; +#ifdef FLUIDRENDERING_RHS +realViewPos.z=-realViewPos.z; +#endif +#ifdef FLUIDRENDERING_VELOCITY +fragmentOutputs.color=vec4f(realViewPos.z,input.velocityNorm,0.,1.); +#else +fragmentOutputs.color=vec4f(realViewPos.z,0.,0.,1.); +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1r]) { + ShaderStore.ShadersStoreWGSL[name$1r] = shader$1q; +} +/** @internal */ +const fluidRenderingParticleDepthPixelShaderWGSL = { name: name$1r, shader: shader$1q }; + +const fluidRenderingParticleDepth_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + fluidRenderingParticleDepthPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1q = "fluidRenderingParticleThicknessVertexShader"; +const shader$1p = `attribute position: vec3f;attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;@vertex +fn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f( +vec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size, +0.0 +);var viewPos: vec3f=(uniforms.view*vec4f(input.position,1.0)).xyz+cornerPos;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0);vertexOutputs.uv=input.offset;} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1q]) { + ShaderStore.ShadersStoreWGSL[name$1q] = shader$1p; +} +/** @internal */ +const fluidRenderingParticleThicknessVertexShaderWGSL = { name: name$1q, shader: shader$1p }; + +const fluidRenderingParticleThickness_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + fluidRenderingParticleThicknessVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1p = "fluidRenderingParticleThicknessPixelShader"; +const shader$1o = `uniform particleAlpha: f32;varying uv: vec2f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;} +var thickness: f32=sqrt(1.0-r2);fragmentOutputs.color=vec4f(vec3f(uniforms.particleAlpha*thickness),1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1p]) { + ShaderStore.ShadersStoreWGSL[name$1p] = shader$1o; +} +/** @internal */ +const fluidRenderingParticleThicknessPixelShaderWGSL = { name: name$1p, shader: shader$1o }; + +const fluidRenderingParticleThickness_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + fluidRenderingParticleThicknessPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1o = "fluidRenderingParticleDiffuseVertexShader"; +const shader$1n = `attribute position: vec3f;attribute offset: vec2f;attribute color: vec4f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;varying diffuseColor: vec3f;@vertex +fn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f( +vec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size, +0.0 +);var viewPos: vec3f=(uniforms.view*vec4f(input.position,1.0)).xyz+cornerPos;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0);vertexOutputs.uv=input.offset;vertexOutputs.diffuseColor=input.color.rgb;} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1o]) { + ShaderStore.ShadersStoreWGSL[name$1o] = shader$1n; +} + +// Do not edit. +const name$1n = "fluidRenderingParticleDiffusePixelShader"; +const shader$1m = `uniform particleAlpha: f32;varying uv: vec2f;varying diffuseColor: vec3f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;} +fragmentOutputs.color=vec4f(input.diffuseColor,1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1n]) { + ShaderStore.ShadersStoreWGSL[name$1n] = shader$1m; +} + +const fluidRenderingParticleDiffuse_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1m = "fluidRenderingBilateralBlurPixelShader"; +const shader$1l = `var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform maxFilterSize: i32;uniform blurDir: vec2f;uniform projectedParticleConstant: f32;uniform depthThreshold: f32;varying vUV: vec2f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var depth: f32=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color=vec4f(vec3f(depth),1.);return fragmentOutputs;} +var filterSize: i32=min(uniforms.maxFilterSize,i32(ceil(uniforms.projectedParticleConstant/depth)));var sigma: f32=f32(filterSize)/3.0;var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold/3.0;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sum: f32=0.;var wsum: f32=0.;var sumVel: f32=0.;for (var x: i32=-filterSize; x<=filterSize; x++) {var coords: vec2f=vec2f(f32(x));var sampleDepthVel: vec2f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rg;var r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var rDepth: f32=sampleDepthVel.r-depth;var wd: f32=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} +fragmentOutputs.color=vec4f(sum/wsum,sumVel/wsum,0.,1.);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1m]) { + ShaderStore.ShadersStoreWGSL[name$1m] = shader$1l; +} + +const fluidRenderingBilateralBlur_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1l = "fluidRenderingStandardBlurPixelShader"; +const shader$1k = `var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;varying vUV: vec2f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var s: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.);if (s.r==0.) {fragmentOutputs.color=vec4f(0.,0.,0.,1.);return fragmentOutputs;} +var sigma: f32=f32(uniforms.filterSize)/3.0;var twoSigma2: f32=2.0*sigma*sigma;var sum: vec4f=vec4f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {var coords: vec2f=vec2f(f32(x));var sampl: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.);var w: f32=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} +sum/=wsum;fragmentOutputs.color=vec4f(sum.rgb,1.);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1l]) { + ShaderStore.ShadersStoreWGSL[name$1l] = shader$1k; +} + +const fluidRenderingStandardBlur_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1k = "fluidRenderingRenderPixelShader"; +const shader$1j = `#define DISABLE_UNIFORMITY_ANALYSIS +#define IOR 1.333 +#define ETA 1.0/IOR +#define F0 0.02 +var textureSamplerSampler: sampler;var textureSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d; +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; +#else +uniform diffuseColor: vec3f; +#endif +#ifdef FLUIDRENDERING_FIXED_THICKNESS +uniform thickness: f32;var bgDepthSamplerSampler: sampler;var bgDepthSampler: texture_2d; +#else +uniform minimumThickness: f32;var thicknessSamplerSampler: sampler;var thicknessSampler: texture_2d; +#endif +#ifdef FLUIDRENDERING_ENVIRONMENT +var reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube; +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +var debugSamplerSampler: sampler;var debugSampler: texture_2d; +#endif +uniform viewMatrix: mat4x4f;uniform projectionMatrix: mat4x4f;uniform invProjectionMatrix: mat4x4f;uniform texelSize: vec2f;uniform dirLight: vec3f;uniform cameraFar: f32;uniform density: f32;uniform refractionStrength: f32;uniform fresnelClamp: f32;uniform specularPower: f32;varying vUV: vec2f;fn computeViewPosFromUVDepth(texCoord: vec2f,depth: f32)->vec3f {var ndc: vec4f=vec4f(texCoord*2.0-1.0,0.0,1.0); +#ifdef FLUIDRENDERING_RHS +ndc.z=-uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth; +#else +ndc.z=uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth; +#endif +ndc.w=1.0;var eyePos: vec4f=uniforms.invProjectionMatrix*ndc;return eyePos.xyz/eyePos.w;} +fn getViewPosFromTexCoord(texCoord: vec2f)->vec3f {var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var texCoord: vec2f=input.vUV; +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +var color: vec4f=textureSample(debugSampler,debugSamplerSampler,texCoord); +#ifdef FLUIDRENDERING_DEBUG_DEPTH +fragmentOutputs.color=vec4f(color.rgb/vec3f(2.0),1.);if (color.r>0.999 && color.g>0.999) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,texCoord);} +#else +fragmentOutputs.color=vec4f(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,texCoord);} +#endif +return fragmentOutputs; +#endif +var depthVel: vec2f=textureSampleLevel(depthSampler,depthSamplerSampler,texCoord,0.).rg;var depth: f32=depthVel.r; +#ifndef FLUIDRENDERING_FIXED_THICKNESS +var thickness: f32=textureSample(thicknessSampler,thicknessSamplerSampler,texCoord).x; +#else +var thickness: f32=uniforms.thickness;var bgDepth: f32=textureSample(bgDepthSampler,bgDepthSamplerSampler,texCoord).x;var depthNonLinear: f32=uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; +#endif +var backColor: vec4f=textureSample(textureSampler,textureSamplerSampler,texCoord); +#ifndef FLUIDRENDERING_FIXED_THICKNESS +if (depth>=uniforms.cameraFar || depth<=0. || thickness<=uniforms.minimumThickness) { +#else +if (depth>=uniforms.cameraFar || depth<=0. || bgDepth<=depthNonLinear) { +#endif +#ifdef FLUIDRENDERING_COMPOSITE_MODE +fragmentOutputs.color=vec4f(backColor.rgb*backColor.a,backColor.a); +#else +fragmentOutputs.color=backColor; +#endif +return fragmentOutputs;} +var viewPos: vec3f=computeViewPosFromUVDepth(texCoord,depth);var ddx: vec3f=getViewPosFromTexCoord(texCoord+vec2f(uniforms.texelSize.x,0.))-viewPos;var ddy: vec3f=getViewPosFromTexCoord(texCoord+vec2f(0.,uniforms.texelSize.y))-viewPos;var ddx2: vec3f=viewPos-getViewPosFromTexCoord(texCoord+vec2f(-uniforms.texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} +var ddy2: vec3f=viewPos-getViewPosFromTexCoord(texCoord+vec2f(0.,-uniforms.texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} +var normal: vec3f=normalize(cross(ddy,ddx)); +#ifdef FLUIDRENDERING_RHS +normal=-normal; +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) +fragmentOutputs.color=vec4f(normal*0.5+0.5,1.0);return fragmentOutputs; +#endif +var rayDir: vec3f=normalize(viewPos); +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +var diffuseColor: vec3f=textureSampleLevel(diffuseSampler,diffuseSamplerSampler,texCoord,0.0).rgb; +#else +var diffuseColor: vec3f=uniforms.diffuseColor; +#endif +var lightDir: vec3f=normalize((uniforms.viewMatrix*vec4f(-uniforms.dirLight,0.)).xyz);var H: vec3f =normalize(lightDir-rayDir);var specular: f32 =pow(max(0.0,dot(H,normal)),uniforms.specularPower); +#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING +var diffuse: f32 =max(0.0,dot(lightDir,normal))*1.0;fragmentOutputs.color=vec4f(vec3f(0.1) /*ambient*/+vec3f(0.42,0.50,1.00)*diffuse+vec3f(0,0,0.2)+specular,1.);return fragmentOutputs; +#endif +var refractionDir: vec3f=refract(rayDir,normal,ETA);var transmitted: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,vec2f(texCoord+refractionDir.xy*thickness*uniforms.refractionStrength),0.0); +#ifdef FLUIDRENDERING_COMPOSITE_MODE +if (transmitted.a==0.) {transmitted.a=thickness;} +#endif +var transmittance: vec3f=exp(-uniforms.density*thickness*(1.0-diffuseColor)); +var refractionColor: vec3f=transmitted.rgb*transmittance; +#ifdef FLUIDRENDERING_ENVIRONMENT +var reflectionDir: vec3f=reflect(rayDir,normal);var reflectionColor: vec3f=(textureSample(reflectionSampler,reflectionSamplerSampler,reflectionDir).rgb);var fresnel: f32=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,uniforms.fresnelClamp);var finalColor: vec3f=mix(refractionColor,reflectionColor,fresnel)+specular; +#else +var finalColor: vec3f=refractionColor+specular; +#endif +#ifdef FLUIDRENDERING_VELOCITY +var velocity: f32=depthVel.g;finalColor=mix(finalColor,vec3f(1.0),smoothstep(0.3,1.0,velocity/6.0)); +#endif +fragmentOutputs.color=vec4f(finalColor,transmitted.a);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1k]) { + ShaderStore.ShadersStoreWGSL[name$1k] = shader$1j; +} + +const fluidRenderingRender_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * @internal + */ +class MaterialRSMCreateDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.RSMCREATE = false; + this.RSMCREATE_PROJTEXTURE = false; + this.RSMCREATE_LIGHT_IS_SPOT = false; + } +} +/** + * Plugin that implements the creation of the RSM textures + */ +class RSMCreatePluginMaterial extends MaterialPluginBase { + _markAllSubMeshesAsTexturesDirty() { + this._enable(this._isEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a give shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + /** + * Create a new RSMCreatePluginMaterial + * @param material Parent material of the plugin + */ + constructor(material) { + super(material, RSMCreatePluginMaterial.Name, 300, new MaterialRSMCreateDefines()); + this._lightColor = new Color3(); + this._hasProjectionTexture = false; + this._isEnabled = false; + /** + * Defines if the plugin is enabled in the material. + */ + this.isEnabled = false; + this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; + this._varAlbedoName = material instanceof PBRBaseMaterial ? "surfaceAlbedo" : "baseColor.rgb"; + } + prepareDefines(defines) { + defines.RSMCREATE = this._isEnabled; + this._hasProjectionTexture = false; + const isSpot = this.light.getTypeID() === Light.LIGHTTYPEID_SPOTLIGHT; + if (isSpot) { + const spot = this.light; + this._hasProjectionTexture = spot.projectionTexture ? spot.projectionTexture.isReady() : false; + } + defines.RSMCREATE_PROJTEXTURE = this._hasProjectionTexture; + defines.RSMCREATE_LIGHT_IS_SPOT = isSpot; + defines.SCENE_MRT_COUNT = 3; + } + getClassName() { + return "RSMCreatePluginMaterial"; + } + getUniforms() { + return { + ubo: [ + { name: "rsmTextureProjectionMatrix", size: 16, type: "mat4" }, + { name: "rsmSpotInfo", size: 4, type: "vec4" }, + { name: "rsmLightColor", size: 3, type: "vec3" }, + { name: "rsmLightPosition", size: 3, type: "vec3" }, + ], + fragment: `#ifdef RSMCREATE + uniform mat4 rsmTextureProjectionMatrix; + uniform vec4 rsmSpotInfo; + uniform vec3 rsmLightColor; + uniform vec3 rsmLightPosition; + #endif`, + }; + } + getSamplers(samplers) { + samplers.push("rsmTextureProjectionSampler"); + } + bindForSubMesh(uniformBuffer) { + if (!this._isEnabled) { + return; + } + this.light.diffuse.scaleToRef(this.light.getScaledIntensity(), this._lightColor); + uniformBuffer.updateColor3("rsmLightColor", this._lightColor); + if (this.light.getTypeID() === Light.LIGHTTYPEID_SPOTLIGHT) { + const spot = this.light; + if (this._hasProjectionTexture) { + uniformBuffer.updateMatrix("rsmTextureProjectionMatrix", spot.projectionTextureMatrix); + uniformBuffer.setTexture("rsmTextureProjectionSampler", spot.projectionTexture); + } + const normalizeDirection = TmpVectors.Vector3[0]; + if (spot.computeTransformedInformation()) { + uniformBuffer.updateFloat3("rsmLightPosition", this.light.transformedPosition.x, this.light.transformedPosition.y, this.light.transformedPosition.z); + spot.transformedDirection.normalizeToRef(normalizeDirection); + } + else { + uniformBuffer.updateFloat3("rsmLightPosition", this.light.position.x, this.light.position.y, this.light.position.z); + spot.direction.normalizeToRef(normalizeDirection); + } + uniformBuffer.updateFloat4("rsmSpotInfo", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(spot.angle * 0.5)); + } + } + getCustomCode(shaderType, shaderLanguage) { + if (shaderType === "vertex") { + return null; + } + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + return { + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_DEFINITIONS: ` + #ifdef RSMCREATE + #ifdef RSMCREATE_PROJTEXTURE + var rsmTextureProjectionSamplerSampler: sampler; + var rsmTextureProjectionSampler: texture_2d; + #endif + #endif + `, + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: ` + #ifdef RSMCREATE + var rsmColor = ${this._varAlbedoName} * uniforms.rsmLightColor; + #ifdef RSMCREATE_PROJTEXTURE + { + var strq = uniforms.rsmTextureProjectionMatrix * vec4f(fragmentInputs.vPositionW, 1.0); + strq /= strq.w; + rsmColor *= textureSample(rsmTextureProjectionSampler, rsmTextureProjectionSamplerSampler, strq.xy).rgb; + } + #endif + #ifdef RSMCREATE_LIGHT_IS_SPOT + { + var cosAngle = max(0., dot(uniforms.rsmSpotInfo.xyz, normalize(fragmentInputs.vPositionW - uniforms.rsmLightPosition))); + rsmColor = sign(cosAngle - uniforms.rsmSpotInfo.w) * rsmColor; + } + #endif + + #define MRT_AND_COLOR + fragmentOutputs.fragData0 = vec4f(fragmentInputs.vPositionW, 1.); + fragmentOutputs.fragData1 = vec4f(normalize(normalW) * 0.5 + 0.5, 1.); + fragmentOutputs.fragData2 = vec4f(rsmColor, 1.); + #endif + `, + }; + } + return { + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_BEGIN: ` + #ifdef RSMCREATE + #extension GL_EXT_draw_buffers : require + #endif + `, + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_DEFINITIONS: ` + #ifdef RSMCREATE + #ifdef RSMCREATE_PROJTEXTURE + uniform highp sampler2D rsmTextureProjectionSampler; + #endif + layout(location = 0) out highp vec4 glFragData[3]; + vec4 glFragColor; + #endif + `, + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: ` + #ifdef RSMCREATE + vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor; + #ifdef RSMCREATE_PROJTEXTURE + { + vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0); + strq /= strq.w; + rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb; + } + #endif + #ifdef RSMCREATE_LIGHT_IS_SPOT + { + float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition))); + rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor; + } + #endif + glFragData[0] = vec4(vPositionW, 1.); + glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.); + glFragData[2] = vec4(rsmColor, 1.); + #endif + `, + }; + } +} +/** + * Defines the name of the plugin. + */ +RSMCreatePluginMaterial.Name = "RSMCreate"; +__decorate([ + serialize() +], RSMCreatePluginMaterial.prototype, "light", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], RSMCreatePluginMaterial.prototype, "isEnabled", void 0); +RegisterClass(`BABYLON.RSMCreatePluginMaterial`, RSMCreatePluginMaterial); + +/** + * @internal + */ +class MaterialGIRSMRenderDefines extends MaterialDefines { + constructor() { + super(...arguments); + this.RENDER_WITH_GIRSM = false; + this.RSMCREATE_PROJTEXTURE = false; + } +} +/** + * Plugin used to render the global illumination contribution. + */ +class GIRSMRenderPluginMaterial extends MaterialPluginBase { + _markAllSubMeshesAsTexturesDirty() { + this._enable(this._isEnabled); + this._internalMarkAllSubMeshesAsTexturesDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a give shader language. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible() { + return true; + } + constructor(material) { + super(material, GIRSMRenderPluginMaterial.Name, 310, new MaterialGIRSMRenderDefines()); + this._isEnabled = false; + /** + * Defines if the plugin is enabled in the material. + */ + this.isEnabled = false; + this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; + this._isPBR = material instanceof PBRBaseMaterial; + } + prepareDefines(defines) { + defines.RENDER_WITH_GIRSM = this._isEnabled; + } + getClassName() { + return "GIRSMRenderPluginMaterial"; + } + getUniforms() { + return { + ubo: [{ name: "girsmTextureOutputSize", size: 2, type: "vec2" }], + fragment: `#ifdef RENDER_WITH_GIRSM + uniform vec2 girsmTextureOutputSize; + #endif`, + }; + } + getSamplers(samplers) { + samplers.push("girsmTextureGIContrib"); + } + bindForSubMesh(uniformBuffer) { + if (this._isEnabled) { + uniformBuffer.bindTexture("girsmTextureGIContrib", this.textureGIContrib); + uniformBuffer.updateFloat2("girsmTextureOutputSize", this.outputTextureWidth, this.outputTextureHeight); + } + } + getCustomCode(shaderType, shaderLanguage) { + let frag; + if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) { + frag = { + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_DEFINITIONS: ` + #ifdef RENDER_WITH_GIRSM + var girsmTextureGIContribSampler: sampler; + var girsmTextureGIContrib: texture_2d; + + fn computeIndirect() -> vec3f { + var uv = fragmentInputs.position.xy / uniforms.girsmTextureOutputSize; + return textureSample(girsmTextureGIContrib, girsmTextureGIContribSampler, uv).rgb; + } + #endif + `, + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: ` + #ifdef RENDER_WITH_GIRSM + finalDiffuse += computeIndirect() * surfaceAlbedo.rgb; + #endif + `, + }; + if (!this._isPBR) { + frag["CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR"] = ` + #ifdef RENDER_WITH_GIRSM + color = vec4f(color.rgb + computeIndirect() * baseColor.rgb, color.a); + #endif + `; + } + } + else { + frag = { + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_DEFINITIONS: ` + #ifdef RENDER_WITH_GIRSM + uniform sampler2D girsmTextureGIContrib; + + vec3 computeIndirect() { + vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize; + return texture2D(girsmTextureGIContrib, uv).rgb; + } + #endif + `, + // eslint-disable-next-line @typescript-eslint/naming-convention + CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: ` + #ifdef RENDER_WITH_GIRSM + finalDiffuse += computeIndirect() * surfaceAlbedo.rgb; + #endif + `, + }; + if (!this._isPBR) { + frag["CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR"] = ` + #ifdef RENDER_WITH_GIRSM + color.rgb += computeIndirect() * baseColor.rgb; + #endif + `; + } + } + return shaderType === "vertex" ? null : frag; + } +} +/** + * Defines the name of the plugin. + */ +GIRSMRenderPluginMaterial.Name = "GIRSMRender"; +__decorate([ + serialize() +], GIRSMRenderPluginMaterial.prototype, "textureGIContrib", void 0); +__decorate([ + serialize() +], GIRSMRenderPluginMaterial.prototype, "outputTextureWidth", void 0); +__decorate([ + serialize() +], GIRSMRenderPluginMaterial.prototype, "outputTextureHeight", void 0); +__decorate([ + serialize(), + expandToProperty("_markAllSubMeshesAsTexturesDirty") +], GIRSMRenderPluginMaterial.prototype, "isEnabled", void 0); +RegisterClass(`BABYLON.GIRSMRenderPluginMaterial`, GIRSMRenderPluginMaterial); + +// Do not edit. +const name$1j = "bilateralBlurPixelShader"; +const shader$1i = `uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;} +vec3 normal=textureLod(normalSampler,vUV,0.).rgb; +#ifdef DECODE_NORMAL +normal=normal*2.0-1.0; +#endif +float sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb; +#ifdef DECODE_NORMAL +sampleNormal=sampleNormal*2.0-1.0; +#endif +float r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;} +glFragColor=vec4(sum/wsum,1.);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1j]) { + ShaderStore.ShadersStore[name$1j] = shader$1i; +} + +// Do not edit. +const name$1i = "bilateralBlurQualityPixelShader"; +const shader$1h = `uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;} +vec3 normal=textureLod(normalSampler,vUV,0.).rgb; +#ifdef DECODE_NORMAL +normal=normal*2.0-1.0; +#endif +float sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb; +#ifdef DECODE_NORMAL +sampleNormal=sampleNormal*2.0-1.0; +#endif +float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}} +glFragColor=vec4(sum/wsum,1.);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1i]) { + ShaderStore.ShadersStore[name$1i] = shader$1h; +} + +// Do not edit. +const name$1h = "rsmGlobalIlluminationPixelShader"; +const shader$1g = `/** +* The implementation is an application of the formula found in http: +* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts). +*/ +precision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples; +#ifdef TRANSFORM_NORMAL +uniform mat4 invView; +#endif +float mod289(float x){return x-floor(x*(1.0/289.0))*289.0;} +vec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;} +vec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);} +float noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);} +vec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; +float dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);} +return clamp(indirectDiffuse*intensity,0.0,1.0);} +void main(void) +{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz; +#ifdef DECODE_NORMAL +normalW=normalW*2.0-1.0; +#endif +#ifdef TRANSFORM_NORMAL +normalW=(invView*vec4(normalW,0.)).xyz; +#endif +gl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1h]) { + ShaderStore.ShadersStore[name$1h] = shader$1g; +} + +// Do not edit. +const name$1g = "rsmFullGlobalIlluminationPixelShader"; +const shader$1f = `/** +* The implementation is a direct application of the formula found in http: +*/ +precision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux; +#ifdef TRANSFORM_NORMAL +uniform mat4 invView; +#endif +vec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;uniform depthThreshold: f32;uniform normalThreshold: f32;varying vUV: vec2f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color= vec4f(color,1.);return fragmentOutputs;} +var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.).rgb; +#ifdef DECODE_NORMAL +normal=normal*2.0-1.0; +#endif +var sigma: f32= f32(uniforms.filterSize);var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sigmaNormal: f32=uniforms.normalThreshold;var two_sigmaNormal2: f32=2.0*sigmaNormal*sigmaNormal;var sum: vec3f= vec3f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {var coords=vec2f(f32(x));var sampleColor: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rgb;var sampleDepth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).r;var sampleNormal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rgb; +#ifdef DECODE_NORMAL +sampleNormal=sampleNormal*2.0-1.0; +#endif +var r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var depthDelta: f32=abs(sampleDepth-depth);var wd: f32=step(depthDelta,uniforms.depthThreshold);var normalDelta: vec3f=abs(sampleNormal-normal);var wn: f32=step(normalDelta.x+normalDelta.y+normalDelta.z,uniforms.normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;} +fragmentOutputs.color= vec4f(sum/wsum,1.);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1f]) { + ShaderStore.ShadersStoreWGSL[name$1f] = shader$1e; +} + +// Do not edit. +const name$1e = "bilateralBlurQualityPixelShader"; +const shader$1d = `var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;uniform depthThreshold: f32;uniform normalThreshold: f32;varying vUV: vec2f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color= vec4f(color,1.);return fragmentOutputs;} +var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.).rgb; +#ifdef DECODE_NORMAL +normal=normal*2.0-1.0; +#endif +var sigma: f32= f32(uniforms.filterSize);var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sigmaNormal: f32=uniforms.normalThreshold;var two_sigmaNormal2: f32=2.0*sigmaNormal*sigmaNormal;var sum: vec3f= vec3f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {for (var y: i32=-uniforms.filterSize; y<=uniforms.filterSize; y++) {var coords: vec2f= vec2f(f32(x),f32(y))*uniforms.blurDir;var sampleColor: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords,0.).rgb;var sampleDepth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV+coords,0.).r;var sampleNormal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV+coords,0.).rgb; +#ifdef DECODE_NORMAL +sampleNormal=sampleNormal*2.0-1.0; +#endif +var r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var rDepth: f32=sampleDepth-depth;var wd: f32=exp(-rDepth*rDepth/two_sigmaDepth2);var rNormal: f32=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);var wn: f32=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}} +fragmentOutputs.color= vec4f(sum/wsum,1.);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1e]) { + ShaderStore.ShadersStoreWGSL[name$1e] = shader$1d; +} + +// Do not edit. +const name$1d = "rsmGlobalIlluminationPixelShader"; +const shader$1c = `/** +* The implementation is an application of the formula found in http: +* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts). +*/ +varying vUV: vec2f;uniform rsmLightMatrix: mat4x4f;uniform rsmInfo: vec4f;uniform rsmInfo2: vec4f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var rsmPositionWSampler: sampler;var rsmPositionW: texture_2d;var rsmNormalWSampler: sampler;var rsmNormalW: texture_2d;var rsmFluxSampler: sampler;var rsmFlux: texture_2d;var rsmSamples: texture_2d; +#ifdef TRANSFORM_NORMAL +uniform invView: mat4x4f; +#endif +fn mod289(x: f32)->f32{return x-floor(x*(1.0/289.0))*289.0;} +fn mod289Vec4(x: vec4f)->vec4f {return x-floor(x*(1.0/289.0))* 289.0;} +fn perm(x: vec4f)->vec4f {return mod289Vec4(((x*34.0)+1.0)*x) ;} +fn noise(p: vec3f)->f32{var a: vec3f=floor(p);var d: vec3f=p-a;d=d*d*(3.0-2.0*d);var b: vec4f=a.xxyy+ vec4f(0.0,1.0,0.0,1.0);var k1: vec4f=perm(b.xyxy);var k2: vec4f=perm(k1.xyxy+b.zzww);var c: vec4f=k2+a.zzzz;var k3: vec4f=perm(c);var k4: vec4f=perm(c+1.0);var o1: vec4f=fract(k3*(1.0/41.0));var o2: vec4f=fract(k4*(1.0/41.0));var o3: vec4f=o2*d.z+o1*(1.0-d.z);var o4: vec2f=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);} +fn computeIndirect(p: vec3f,n: vec3f)->vec3f {var indirectDiffuse: vec3f= vec3f(0.);var numSamples: i32= i32(uniforms.rsmInfo.x);var radius: f32=uniforms.rsmInfo.y;var intensity: f32=uniforms.rsmInfo.z;var edgeArtifactCorrection: f32=uniforms.rsmInfo.w;var texRSM: vec4f=uniforms.rsmLightMatrix* vec4f(p,1.);texRSM=vec4f(texRSM.xy/texRSM.w,texRSM.z,texRSM.w);texRSM=vec4f(texRSM.xy*0.5+0.5,texRSM.z,texRSM.w);var angle: f32=noise(p*uniforms.rsmInfo2.x);var c: f32=cos(angle);var s: f32=sin(angle);for (var i: i32=0; i(i,0),0).xyz;var weightSquare: f32=rsmSample.z;if (uniforms.rsmInfo2.y==1.0){rsmSample=vec3f(rsmSample.x*c+rsmSample.y*s,-rsmSample.x*s+rsmSample.y*c,rsmSample.z);} +var uv: vec2f=texRSM.xy+rsmSample.xy*radius;if (uv.x<0. || uv.x>1. || uv.y<0. || uv.y>1.) {continue;} +var vplPositionW: vec3f=textureSampleLevel(rsmPositionW,rsmPositionWSampler,uv,0.).xyz;var vplNormalW: vec3f=textureSampleLevel(rsmNormalW,rsmNormalWSampler,uv,0.).xyz*2.0-1.0;var vplFlux: vec3f=textureSampleLevel(rsmFlux,rsmFluxSampler,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; +var dist2: f32=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);} +return clamp(indirectDiffuse*intensity,vec3f(0.0),vec3f(1.0));} +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var positionW: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).xyz;var normalW: vec3f=textureSample(normalSampler,normalSamplerSampler,input.vUV).xyz; +#ifdef DECODE_NORMAL +normalW=normalW*2.0-1.0; +#endif +#ifdef TRANSFORM_NORMAL +normalW=(uniforms.invView* vec4f(normalW,0.)).xyz; +#endif +fragmentOutputs.color=vec4f(computeIndirect(positionW,normalW),1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1d]) { + ShaderStore.ShadersStoreWGSL[name$1d] = shader$1c; +} + +// Do not edit. +const name$1c = "rsmFullGlobalIlluminationPixelShader"; +const shader$1b = `/** +* The implementation is a direct application of the formula found in http: +*/ +varying vUV: vec2f;uniform rsmLightMatrix: mat4x4f;uniform rsmInfo: vec4f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var rsmPositionW: texture_2d;var rsmNormalW: texture_2d;var rsmFlux: texture_2d; +#ifdef TRANSFORM_NORMAL +uniform invView: mat4x4f; +#endif +fn computeIndirect(p: vec3f,n: vec3f)->vec3f {var indirectDiffuse: vec3f= vec3f(0.);var intensity: f32=uniforms.rsmInfo.z;var edgeArtifactCorrection: f32=uniforms.rsmInfo.w;var texRSM: vec4f=uniforms.rsmLightMatrix* vec4f(p,1.);texRSM=vec4f(texRSM.xy/texRSM.w,texRSM.z,texRSM.w);texRSM=vec4f(texRSM.xy*0.5+0.5,texRSM.z,texRSM.w);var width: i32= i32(uniforms.rsmInfo.x);var height: i32= i32(uniforms.rsmInfo.y);for (var j: i32=0; j(i,j);var vplPositionW: vec3f=textureLoad(rsmPositionW,uv,0).xyz;var vplNormalW: vec3f=textureLoad(rsmNormalW,uv,0).xyz*2.0-1.0;var vplFlux: vec3f=textureLoad(rsmFlux,uv,0).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; +var dist2: f32=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}} +return clamp(indirectDiffuse*intensity,vec3f(0.0),vec3f(1.0));} +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var positionW: vec3f=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV).xyz;var normalW: vec3f=textureSample(normalSampler,normalSamplerSampler,fragmentInputs.vUV).xyz; +#ifdef DECODE_NORMAL +normalW=normalW*2.0-1.0; +#endif +#ifdef TRANSFORM_NORMAL +normalW=(uniforms.invView* vec4f(normalW,0.)).xyz; +#endif +fragmentOutputs.color=vec4f(computeIndirect(positionW,normalW),1.0);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1c]) { + ShaderStore.ShadersStoreWGSL[name$1c] = shader$1b; +} + +// Do not edit. +const name$1b = "depthPixelShader"; +const shader$1a = `#ifdef ALPHATEST +varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; +#endif +#include +varying vDepthMetric: f32; +#ifdef PACKED +#include +#endif +#ifdef STORE_CAMERASPACE_Z +varying vViewPos: vec4f; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#include +#ifdef ALPHATEST +if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;} +#endif +#ifdef STORE_CAMERASPACE_Z +#ifdef PACKED +fragmentOutputs.color=pack(input.vViewPos.z); +#else +fragmentOutputs.color= vec4f(input.vViewPos.z,0.0,0.0,1.0); +#endif +#else +#ifdef NONLINEARDEPTH +#ifdef PACKED +fragmentOutputs.color=pack(input.position.z); +#else +fragmentOutputs.color= vec4f(input.position.z,0.0,0.0,0.0); +#endif +#else +#ifdef PACKED +fragmentOutputs.color=pack(input.vDepthMetric); +#else +fragmentOutputs.color= vec4f(input.vDepthMetric,0.0,0.0,1.0); +#endif +#endif +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1b]) { + ShaderStore.ShadersStoreWGSL[name$1b] = shader$1a; +} +/** @internal */ +const depthPixelShaderWGSL = { name: name$1b, shader: shader$1a }; + +const depth_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + depthPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$1a = "depthVertexShader"; +const shader$19 = `attribute position: vec3f; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +uniform viewProjection: mat4x4f;uniform depthValues: vec2f; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vUV: vec2f;uniform diffuseMatrix: mat4x4f; +#ifdef UV1 +attribute uv: vec2f; +#endif +#ifdef UV2 +attribute uv2: vec2f; +#endif +#endif +#ifdef STORE_CAMERASPACE_Z +uniform view: mat4x4f;varying vViewPos: vec4f; +#endif +varying vDepthMetric: f32; +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position; +#ifdef UV1 +var uvUpdated: vec2f=input.uv; +#endif +#ifdef UV2 +var uv2Updated: vec2f=input.uv2; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0); +#include +vertexOutputs.position=uniforms.viewProjection*worldPos; +#ifdef STORE_CAMERASPACE_Z +vertexOutputs.vViewPos=uniforms.view*worldPos; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +vertexOutputs.vDepthMetric=((-vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y)); +#else +vertexOutputs.vDepthMetric=((vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y)); +#endif +#endif +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; +#endif +#ifdef UV2 +vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy; +#endif +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$1a]) { + ShaderStore.ShadersStoreWGSL[name$1a] = shader$19; +} +/** @internal */ +const depthVertexShaderWGSL = { name: name$1a, shader: shader$19 }; + +const depth_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + depthVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$19 = "geometryPixelShader"; +const shader$18 = `#ifdef BUMP +varying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;varying vNormalW: vec3f; +#else +varying vNormalV: vec3f; +#endif +varying vViewPos: vec4f; +#if defined(POSITION) || defined(BUMP) +varying vPositionW: vec3f; +#endif +#if defined(VELOCITY) || defined(VELOCITY_LINEAR) +varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; +#endif +#ifdef NEED_UV +varying vUV: vec2f; +#endif +#ifdef BUMP +uniform vBumpInfos: vec3f;uniform vTangentSpaceParams: vec2f; +#endif +#if defined(REFLECTIVITY) +#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;varying vReflectivityUV: vec2f; +#endif +#ifdef ALBEDOTEXTURE +varying vAlbedoUV: vec2f;var albedoSamplerSampler: sampler;var albedoSampler: texture_2d; +#endif +#ifdef REFLECTIVITYCOLOR +uniform reflectivityColor: vec3f; +#endif +#ifdef ALBEDOCOLOR +uniform albedoColor: vec3f; +#endif +#ifdef METALLIC +uniform metallic: f32; +#endif +#if defined(ROUGHNESS) || defined(GLOSSINESS) +uniform glossiness: f32; +#endif +#endif +#if defined(ALPHATEST) && defined(NEED_UV) +var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; +#endif +#include +#include +#include +#include +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#include +#ifdef ALPHATEST +if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;} +#endif +var normalOutput: vec3f; +#ifdef BUMP +var normalW: vec3f=normalize(input.vNormalW); +#include +#ifdef NORMAL_WORLDSPACE +normalOutput=normalW; +#else +normalOutput=normalize( (mat4x4f(input.vWorldView0,input.vWorldView1,input.vWorldView2,input.vWorldView3)* vec4f(normalW,0.0)).xyz); +#endif +#else +normalOutput=normalize(input.vNormalV); +#endif +#ifdef ENCODE_NORMAL +normalOutput=normalOutput*0.5+0.5; +#endif +var fragData: array,SCENE_MRT_COUNT>; +#ifdef DEPTH +fragData[DEPTH_INDEX]=vec4f(input.vViewPos.z/input.vViewPos.w,0.0,0.0,1.0); +#endif +#ifdef NORMAL +fragData[NORMAL_INDEX]=vec4f(normalOutput,1.0); +#endif +#ifdef SCREENSPACE_DEPTH +fragData[SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,1.0); +#endif +#ifdef POSITION +fragData[POSITION_INDEX]= vec4f(input.vPositionW,1.0); +#endif +#ifdef VELOCITY +var a: vec2f=(input.vCurrentPosition.xy/input.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(input.vPreviousPosition.xy/input.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[VELOCITY_INDEX]= vec4f(velocity,0.0,1.0); +#endif +#ifdef VELOCITY_LINEAR +var velocity : vec2f=vec2f(0.5)*((input.vPreviousPosition.xy / +input.vPreviousPosition.w) - +(input.vCurrentPosition.xy / +input.vCurrentPosition.w));fragData[VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,1.0); +#endif +#ifdef REFLECTIVITY +var reflectivity: vec4f= vec4f(0.0,0.0,0.0,1.0); +#ifdef METALLICWORKFLOW +var metal: f32=1.0;var roughness: f32=1.0; +#ifdef ORMTEXTURE +metal*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).b;roughness*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).g; +#endif +#ifdef METALLIC +metal*=uniforms.metallic; +#endif +#ifdef ROUGHNESS +roughness*=(1.0-uniforms.glossiness); +#endif +reflectivity=vec4f(reflectivity.rgb,reflectivity.a-roughness);var color: vec3f= vec3f(1.0); +#ifdef ALBEDOTEXTURE +color=textureSample(albedoSampler,albedoSamplerSampler,input.vAlbedoUV).rgb; +#ifdef GAMMAALBEDO +color=toLinearSpaceVec4(color); +#endif +#endif +#ifdef ALBEDOCOLOR +color*=uniforms.albedoColor.xyz; +#endif +reflectivity=vec4f(mix( vec3f(0.04),color,metal),reflectivity.a); +#else +#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +reflectivity=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV); +#ifdef GAMMAREFLECTIVITYTEXTURE +reflectivity=vec4f(toLinearSpaceVec3(reflectivity.rgb),reflectivity.a); +#endif +#else +#ifdef REFLECTIVITYCOLOR +reflectivity=vec4f(toLinearSpaceVec3(uniforms.reflectivityColor.xyz),1.0); +#endif +#endif +#ifdef GLOSSINESSS +reflectivity=vec4f(reflectivity.rgb,reflectivity.a*glossiness); +#endif +#endif +fragData[REFLECTIVITY_INDEX]=reflectivity; +#endif +#if SCENE_MRT_COUNT>0 +fragmentOutputs.fragData0=fragData[0]; +#endif +#if SCENE_MRT_COUNT>1 +fragmentOutputs.fragData1=fragData[1]; +#endif +#if SCENE_MRT_COUNT>2 +fragmentOutputs.fragData2=fragData[2]; +#endif +#if SCENE_MRT_COUNT>3 +fragmentOutputs.fragData3=fragData[3]; +#endif +#if SCENE_MRT_COUNT>4 +fragmentOutputs.fragData4=fragData[4]; +#endif +#if SCENE_MRT_COUNT>5 +fragmentOutputs.fragData5=fragData[5]; +#endif +#if SCENE_MRT_COUNT>6 +fragmentOutputs.fragData6=fragData[6]; +#endif +#if SCENE_MRT_COUNT>7 +fragmentOutputs.fragData7=fragData[7]; +#endif +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$19]) { + ShaderStore.ShadersStoreWGSL[name$19] = shader$18; +} +/** @internal */ +const geometryPixelShaderWGSL = { name: name$19, shader: shader$18 }; + +const geometry_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + geometryPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$18 = "geometryVertexShader"; +const shader$17 = `#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +attribute position: vec3f;attribute normal: vec3f; +#ifdef NEED_UV +varying vUV: vec2f; +#ifdef ALPHATEST +uniform diffuseMatrix: mat4x4f; +#endif +#ifdef BUMP +uniform bumpMatrix: mat4x4f;varying vBumpUV: vec2f; +#endif +#ifdef REFLECTIVITY +uniform reflectivityMatrix: mat4x4f;uniform albedoMatrix: mat4x4f;varying vReflectivityUV: vec2f;varying vAlbedoUV: vec2f; +#endif +#ifdef UV1 +attribute uv: vec2f; +#endif +#ifdef UV2 +attribute uv2: vec2f; +#endif +#endif +#ifdef BUMP +varying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f; +#endif +#ifdef BUMP +varying vNormalW: vec3f; +#else +varying vNormalV: vec3f; +#endif +varying vViewPos: vec4f; +#if defined(POSITION) || defined(BUMP) +varying vPositionW: vec3f; +#endif +#if defined(VELOCITY) || defined(VELOCITY_LINEAR) +uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;var normalUpdated: vec3f=input.normal; +#ifdef UV1 +var uvUpdated: vec2f=input.uv; +#endif +#ifdef UV2 +var uv2Updated: vec2f=input.uv2; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); +#endif +#include +#include +var worldPos: vec4f= vec4f(finalWorld* vec4f(positionUpdated,1.0)); +#ifdef BUMP +let vWorldView=scene.view*finalWorld;vertexOutputs.vWorldView0=vWorldView[0];vertexOutputs.vWorldView1=vWorldView[1];vertexOutputs.vWorldView2=vWorldView[2];vertexOutputs.vWorldView3=vWorldView[3];let normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated); +#else +#ifdef NORMAL_WORLDSPACE +vertexOutputs.vNormalV=normalize((finalWorld* vec4f(normalUpdated,0.0)).xyz); +#else +vertexOutputs.vNormalV=normalize(((scene.view*finalWorld)* vec4f(normalUpdated,0.0)).xyz); +#endif +#endif +vertexOutputs.vViewPos=scene.view*worldPos; +#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED) +vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0); +#if NUM_BONE_INFLUENCERS>0 +var previousInfluence: mat4x4f;previousInfluence=mPreviousBones[ i32(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[ i32(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[ i32(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[ i32(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0); +#else +vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); +#endif +#endif +#if defined(POSITION) || defined(BUMP) +vertexOutputs.vPositionW=worldPos.xyz/worldPos.w; +#endif +vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0); +#include +#ifdef NEED_UV +#ifdef UV1 +#if defined(ALPHATEST) && defined(ALPHATEST_UV1) +vertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; +#else +vertexOutputs.vUV=uvUpdated; +#endif +#ifdef BUMP_UV1 +vertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uvUpdated,1.0,0.0)).xy; +#endif +#ifdef REFLECTIVITY_UV1 +vertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uvUpdated,1.0,0.0)).xy; +#endif +#ifdef ALBEDO_UV1 +vertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uvUpdated,1.0,0.0)).xy; +#endif +#endif +#ifdef UV2 +#if defined(ALPHATEST) && defined(ALPHATEST_UV2) +vertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy; +#else +vertexOutputs.vUV=uv2Updated; +#endif +#ifdef BUMP_UV2 +vertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uv2Updated,1.0,0.0)).xy; +#endif +#ifdef REFLECTIVITY_UV2 +vertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uv2Updated,1.0,0.0)).xy; +#endif +#ifdef ALBEDO_UV2 +vertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uv2Updated,1.0,0.0)).xy; +#endif +#endif +#endif +#include +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$18]) { + ShaderStore.ShadersStoreWGSL[name$18] = shader$17; +} +/** @internal */ +const geometryVertexShaderWGSL = { name: name$18, shader: shader$17 }; + +const geometry_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + geometryVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$17 = "boundingBoxRendererFragmentDeclaration"; +const shader$16 = `uniform vec4 color; +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$17]) { + ShaderStore.IncludesShadersStore[name$17] = shader$16; +} + +// Do not edit. +const name$16 = "boundingBoxRendererUboDeclaration"; +const shader$15 = `#ifdef WEBGL2 +uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +#else +layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$16]) { + ShaderStore.IncludesShadersStore[name$16] = shader$15; +} + +// Do not edit. +const name$15 = "boundingBoxRendererPixelShader"; +const shader$14 = `#include<__decl__boundingBoxRendererFragment> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$15]) { + ShaderStore.ShadersStore[name$15] = shader$14; +} +/** @internal */ +const boundingBoxRendererPixelShader = { name: name$15, shader: shader$14 }; + +const boundingBoxRenderer_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + boundingBoxRendererPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$14 = "boundingBoxRendererVertexDeclaration"; +const shader$13 = `uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$14]) { + ShaderStore.IncludesShadersStore[name$14] = shader$13; +} + +// Do not edit. +const name$13 = "boundingBoxRendererVertexShader"; +const shader$12 = `attribute vec3 position; +#include<__decl__boundingBoxRendererVertex> +#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#ifdef INSTANCES +mat4 finalWorld=mat4(world0,world1,world2,world3);vec4 worldPos=finalWorld*vec4(position,1.0); +#else +vec4 worldPos=world*vec4(position,1.0); +#endif +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$13]) { + ShaderStore.ShadersStore[name$13] = shader$12; +} +/** @internal */ +const boundingBoxRendererVertexShader = { name: name$13, shader: shader$12 }; + +const boundingBoxRenderer_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + boundingBoxRendererVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$12 = "boundingBoxRendererPixelShader"; +const shader$11 = `uniform color: vec4f; +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +fragmentOutputs.color=uniforms.color; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$12]) { + ShaderStore.ShadersStoreWGSL[name$12] = shader$11; +} +/** @internal */ +const boundingBoxRendererPixelShaderWGSL = { name: name$12, shader: shader$11 }; + +const boundingBoxRenderer_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + boundingBoxRendererPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$11 = "boundingBoxRendererVertexShader"; +const shader$10 = `attribute position: vec3f;uniform world: mat4x4f;uniform viewProjection: mat4x4f; +#ifdef INSTANCES +attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +#ifdef INSTANCES +var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);var worldPos: vec4f=finalWorld* vec4f(input.position,1.0); +#else +var worldPos: vec4f=uniforms.world* vec4f(input.position,1.0); +#endif +vertexOutputs.position=uniforms.viewProjection*worldPos; +#define CUSTOM_VERTEX_MAIN_END +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$11]) { + ShaderStore.ShadersStoreWGSL[name$11] = shader$10; +} +/** @internal */ +const boundingBoxRendererVertexShaderWGSL = { name: name$11, shader: shader$10 }; + +const boundingBoxRenderer_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + boundingBoxRendererVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$10 = "linePixelShader"; +const shader$$ = `#include +uniform vec4 color; +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#include +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$10]) { + ShaderStore.ShadersStore[name$10] = shader$$; +} +/** @internal */ +const linePixelShader = { name: name$10, shader: shader$$ }; + +const line_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + linePixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$$ = "lineVertexDeclaration"; +const shader$_ = `uniform mat4 viewProjection; +#define ADDITIONAL_VERTEX_DECLARATION +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$$]) { + ShaderStore.IncludesShadersStore[name$$] = shader$_; +} + +// Do not edit. +const name$_ = "lineUboDeclaration"; +const shader$Z = `layout(std140,column_major) uniform; +#include +#include +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$_]) { + ShaderStore.IncludesShadersStore[name$_] = shader$Z; +} + +// Do not edit. +const name$Z = "lineVertexShader"; +const shader$Y = `#include<__decl__lineVertex> +#include +#include +attribute vec3 position;attribute vec4 normal;uniform float width;uniform float aspectRatio; +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=finalWorld*vec4(position,1.0); +#include +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$Z]) { + ShaderStore.ShadersStore[name$Z] = shader$Y; +} +/** @internal */ +const lineVertexShader = { name: name$Z, shader: shader$Y }; + +const line_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lineVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$Y = "linePixelShader"; +const shader$X = `#include +uniform color: vec4f; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#include +fragmentOutputs.color=uniforms.color; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$Y]) { + ShaderStore.ShadersStoreWGSL[name$Y] = shader$X; +} +/** @internal */ +const linePixelShaderWGSL = { name: name$Y, shader: shader$X }; + +const line_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + linePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$X = "lineVertexShader"; +const shader$W = `#define ADDITIONAL_VERTEX_DECLARATION +#include +#include +#include +#include +attribute position: vec3f;attribute normal: vec4f;uniform width: f32;uniform aspectRatio: f32; +#include +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +var worldViewProjection: mat4x4f=scene.viewProjection*finalWorld;var viewPosition: vec4f=worldViewProjection* vec4f(input.position,1.0);var viewPositionNext: vec4f=worldViewProjection* vec4f(input.normal.xyz,1.0);var currentScreen: vec2f=viewPosition.xy/viewPosition.w;var nextScreen: vec2f=viewPositionNext.xy/viewPositionNext.w;currentScreen=vec2f(currentScreen.x*uniforms.aspectRatio,currentScreen.y);nextScreen=vec2f(nextScreen.x*uniforms.aspectRatio,nextScreen.y);var dir: vec2f=normalize(nextScreen-currentScreen);var normalDir: vec2f= vec2f(-dir.y,dir.x);normalDir*=uniforms.width/2.0;normalDir=vec2f(normalDir.x/uniforms.aspectRatio,normalDir.y);var offset: vec4f= vec4f(normalDir*input.normal.w,0.0,0.0);vertexOutputs.position=viewPosition+offset; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +var worldPos: vec4f=finalWorld*vec4f(input.position,1.0); +#include +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$X]) { + ShaderStore.ShadersStoreWGSL[name$X] = shader$W; +} +/** @internal */ +const lineVertexShaderWGSL = { name: name$X, shader: shader$W }; + +const line_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + lineVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$W = "outlinePixelShader"; +const shader$V = `#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform vec4 color; +#ifdef ALPHATEST +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +#include +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$W]) { + ShaderStore.ShadersStore[name$W] = shader$V; +} +/** @internal */ +const outlinePixelShader = { name: name$W, shader: shader$V }; + +const outline_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + outlinePixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$V = "outlineVertexShader"; +const shader$U = `attribute vec3 position;attribute vec3 normal; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +uniform float offset; +#include +uniform mat4 viewProjection; +#ifdef ALPHATEST +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position;vec3 normalUpdated=normal; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef UV2 +vec2 uv2Updated=uv2; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +vec3 offsetPosition=positionUpdated+(normalUpdated*offset); +#include +#include +#include +vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; +#ifdef ALPHATEST +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); +#endif +#endif +#include +#include +} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$V]) { + ShaderStore.ShadersStore[name$V] = shader$U; +} +/** @internal */ +const outlineVertexShader = { name: name$V, shader: shader$U }; + +const outline_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + outlineVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$U = "outlinePixelShader"; +const shader$T = `uniform color: vec4f; +#ifdef ALPHATEST +varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; +#endif +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#ifdef ALPHATEST +if (textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV).a<0.4) {discard;} +#endif +#include +fragmentOutputs.color=uniforms.color; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$U]) { + ShaderStore.ShadersStoreWGSL[name$U] = shader$T; +} +/** @internal */ +const outlinePixelShaderWGSL = { name: name$U, shader: shader$T }; + +const outline_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + outlinePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$T = "outlineVertexShader"; +const shader$S = `attribute position: vec3f;attribute normal: vec3f; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +uniform offset: f32; +#include +uniform viewProjection: mat4x4f; +#ifdef ALPHATEST +varying vUV: vec2f;uniform diffuseMatrix: mat4x4f; +#ifdef UV1 +attribute uv: vec2f; +#endif +#ifdef UV2 +attribute uv2: vec2f; +#endif +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input: VertexInputs)->FragmentInputs {var positionUpdated: vec3f=vertexInputs.position;var normalUpdated: vec3f=vertexInputs.normal; +#ifdef UV1 +var uvUpdated: vec2f=vertexInputs.uv; +#endif +#ifdef UV2 +var uv2Updated: vec2f=vertexInputs.uv2; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +var offsetPosition: vec3f=positionUpdated+(normalUpdated*uniforms.offset); +#include +#include +#include +var worldPos: vec4f=finalWorld*vec4f(offsetPosition,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos; +#ifdef ALPHATEST +#ifdef UV1 +vertexOutputs.vUV=(uniforms.diffuseMatrix*vec4f(uvUpdated,1.0,0.0)).xy; +#endif +#ifdef UV2 +vertexOutputs.vUV=(uniforms.diffuseMatrix*vec4f(uv2Updated,1.0,0.0)).xy; +#endif +#endif +#include +#include +} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$T]) { + ShaderStore.ShadersStoreWGSL[name$T] = shader$S; +} +/** @internal */ +const outlineVertexShaderWGSL = { name: name$T, shader: shader$S }; + +const outline_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + outlineVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$S = "copyTexture3DLayerToTexturePixelShader"; +const shader$R = `precision highp sampler3D;uniform sampler3D textureSampler;uniform int layerNum;varying vec2 vUV;void main(void) {vec3 coord=vec3(0.0,0.0,float(layerNum));coord.xy=vec2(vUV.x,vUV.y)*vec2(textureSize(textureSampler,0).xy);vec3 color=texelFetch(textureSampler,ivec3(coord),0).rgb;gl_FragColor=vec4(color,1);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$S]) { + ShaderStore.ShadersStore[name$S] = shader$R; +} + +// Do not edit. +const name$R = "copyTexture3DLayerToTexturePixelShader"; +const shader$Q = `var textureSampler: texture_3d;uniform layerNum: i32;varying vUV: vec2f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec3f(vec2f(input.vUV.x,input.vUV.y)*vec2f(textureDimensions(textureSampler,0).xy),f32(uniforms.layerNum));let color=textureLoad(textureSampler,vec3i(coord),0).rgb;fragmentOutputs.color= vec4f(color,1);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$R]) { + ShaderStore.ShadersStoreWGSL[name$R] = shader$Q; +} + +// Do not edit. +const name$Q = "iblShadowVoxelTracingPixelShader"; +const shader$P = `precision highp sampler2D;precision highp sampler3D; +#define PI 3.1415927 +varying vec2 vUV; +#define DISABLE_UNIFORMITY_ANALYSIS +uniform sampler2D depthSampler;uniform sampler2D worldNormalSampler;uniform sampler2D blueNoiseSampler;uniform sampler2D icdfSampler;uniform sampler3D voxelGridSampler; +#ifdef COLOR_SHADOWS +uniform samplerCube iblSampler; +#endif +uniform vec4 shadowParameters; +#define SHADOWdirs shadowParameters.x +#define SHADOWframe shadowParameters.y +#define SHADOWenvRot shadowParameters.w +uniform vec4 voxelBiasParameters; +#define highestMipLevel voxelBiasParameters.z +uniform vec4 sssParameters; +#define SSSsamples sssParameters.x +#define SSSstride sssParameters.y +#define SSSmaxDistance sssParameters.z +#define SSSthickness sssParameters.w +uniform vec4 shadowOpacity;uniform mat4 projMtx;uniform mat4 viewMtx;uniform mat4 invProjMtx;uniform mat4 invViewMtx;uniform mat4 wsNormalizationMtx;uniform mat4 invVPMtx; +#define PI 3.1415927 +#define GOLD 0.618034 +struct AABB3f {vec3 m_min;vec3 m_max;};struct Ray {vec3 orig;vec3 dir;vec3 dir_rcp;float t_min;float t_max;};Ray make_ray(const vec3 origin,const vec3 direction,const float tmin, +const float tmax) {Ray ray;ray.orig=origin;ray.dir=direction;ray.dir_rcp=1.0f/direction;ray.t_min=tmin;ray.t_max=tmax;return ray;} +bool ray_box_intersection(const in AABB3f aabb,const in Ray ray, +out float distance_near,out float distance_far) {vec3 tbot=ray.dir_rcp*(aabb.m_min-ray.orig);vec3 ttop=ray.dir_rcp*(aabb.m_max-ray.orig);vec3 tmin=min(ttop,tbot);vec3 tmax=max(ttop,tbot);distance_near=max(ray.t_min,max(tmin.x,max(tmin.y,tmin.z)));distance_far=min(ray.t_max,min(tmax.x,min(tmax.y,tmax.z)));return distance_near<=distance_far;} +#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +struct VoxelMarchDiagnosticInfo {float heat;ivec3 voxel_intersect_coords;}; +#endif +uint hash(uint i) {i ^= i>>16u;i*=0x7FEB352Du;i ^= i>>15u;i*=0x846CA68Bu;i ^= i>>16u;return i;} +float uint2float(uint i) {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;} +vec3 uv_to_normal(vec2 uv) {vec3 N;vec2 uvRange=uv;float theta=uvRange.x*2.0*PI;float phi=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;} +vec2 plasticSequence(const uint rstate) {return vec2(uint2float(rstate*3242174889u), +uint2float(rstate*2447445414u));} +float goldenSequence(const uint rstate) {return uint2float(rstate*2654435769u);} +float distanceSquared(vec2 a,vec2 b) {vec2 diff=a-b;return dot(diff,diff);} +void genTB(const vec3 N,out vec3 T,out vec3 B) {float s=N.z<0.0 ? -1.0 : 1.0;float a=-1.0/(s+N.z);float b=N.x*N.y*a;T=vec3(1.0+s*N.x*N.x*a,s*b,-s*N.x);B=vec3(b,s+N.y*N.y*a,-N.y);} +int stack[24]; +#define PUSH(i) stack[stackLevel++]=i; +#define POP() stack[--stackLevel] +#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +bool anyHitVoxels(const Ray ray_vs, +out VoxelMarchDiagnosticInfo voxel_march_diagnostic_info) { +#else +bool anyHitVoxels(const Ray ray_vs) { +#endif +vec3 invD=ray_vs.dir_rcp;vec3 D=ray_vs.dir;vec3 O=ray_vs.orig;ivec3 negD=ivec3(lessThan(D,vec3(0,0,0)));int voxel0=negD.x | negD.y<<1 | negD.z<<2;vec3 t0=-O*invD,t1=(vec3(1.0)-O)*invD;int maxLod=int(highestMipLevel);int stackLevel=0; +#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +uint steps=0u; +#endif +PUSH(maxLod<<24);while (stackLevel>0) {int elem=POP();ivec4 Coords = +ivec4(elem & 0xFF,elem>>8 & 0xFF,elem>>16 & 0xFF,elem>>24);if (Coords.w==0) { +#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +voxel_march_diagnostic_info.heat=float(steps)/24.0; +#endif +return true;} +#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +++steps; +#endif +float invRes=exp2(float(Coords.w-maxLod));vec3 bbmin=invRes*vec3(Coords.xyz+negD);vec3 bbmax=invRes*vec3(Coords.xyz-negD+ivec3(1));vec3 mint=mix(t0,t1,bbmin);vec3 maxt=mix(t0,t1,bbmax);vec3 midt=0.5*(mint+maxt);mint.x=max(0.0,mint.x);midt.x=max(0.0,midt.x);int nodeMask=int( +round(texelFetch(voxelGridSampler,Coords.xyz,Coords.w).x*255.0));Coords.w--;int voxelBit=voxel0;Coords.xyz=(Coords.xyz<<1)+negD;int packedCoords = +Coords.x | Coords.y<<8 | Coords.z<<16 | Coords.w<<24;if (max(mint.x,max(mint.y,mint.z))0.0 && stepCount0.0) {vec4 VP2=VP;VP2.y*=-1.0;vec4 unormWP=invViewMtx*VP2;vec3 WP=(wsNormalizationMtx*unormWP).xyz;vec2 vxNoise=vec2(uint2float(hash(dirId*2u)),uint2float(hash(dirId*2u+1u))); +#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +VoxelMarchDiagnosticInfo voxel_march_diagnostic_info;opacity=max(opacity,shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise,voxel_march_diagnostic_info));heat+=voxel_march_diagnostic_info.heat; +#else +opacity = +max(opacity,shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise)); +#endif +vec3 VL=(viewMtx*L).xyz; +#ifdef RIGHT_HANDED +float nearPlaneZ=-projMtx[3][2]/(projMtx[2][2]-1.0); +float farPlaneZ=-projMtx[3][2]/(projMtx[2][2]+1.0); +#else +float nearPlaneZ=-projMtx[3][2]/(projMtx[2][2]+1.0); +float farPlaneZ=-projMtx[3][2]/(projMtx[2][2]-1.0); +#endif +float ssShadow=shadowOpacity.y * +screenSpaceShadow(VP2.xyz,VL,Resolution,nearPlaneZ,farPlaneZ, +abs(2.0*noise.z-1.0));opacity=max(opacity,ssShadow); +#ifdef COLOR_SHADOWS +vec3 light=pdf<1e-6 ? vec3(0.0) : vec3(cosNL)/vec3(pdf)*ibl;shadowedLight+=light*opacity;totalLight+=light; +#else +float rcos=(1.0-cosNL);shadowAccum+=(1.0-opacity*(1.0-pow(rcos,8.0)));sampleWeight+=1.0;vec3 VR=-(viewMtx*vec4(reflect(-L.xyz,N),0.0)).xyz;specShadowAccum+=max(1.0-(opacity*pow(VR.z,8.0)),0.0); +#endif +} +noise.z=fract(noise.z+GOLD);} +#ifdef COLOR_SHADOWS +vec3 shadow=(totalLight-shadowedLight)/totalLight;float maxShadow=max(max(shadow.x,max(shadow.y,shadow.z)),1.0);glFragColor=vec4(shadow/maxShadow,1.0); +#else +#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +gl_FragColor=vec4(shadowAccum/float(sampleWeight), +specShadowAccum/float(sampleWeight),heat/float(sampleWeight),1.0); +#else +gl_FragColor=vec4(shadowAccum/float(sampleWeight),specShadowAccum/float(sampleWeight),0.0,1.0); +#endif +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$Q]) { + ShaderStore.ShadersStore[name$Q] = shader$P; +} + +// Do not edit. +const name$P = "iblShadowVoxelTracingPixelShader"; +const shader$O = `#define PI 3.1415927 +varying vUV: vec2f; +#define DISABLE_UNIFORMITY_ANALYSIS +var depthSampler: texture_2d;var worldNormalSampler : texture_2d;var blueNoiseSampler: texture_2d;var icdfSamplerSampler: sampler;var icdfSampler: texture_2d;var voxelGridSamplerSampler: sampler;var voxelGridSampler: texture_3d; +#ifdef COLOR_SHADOWS +var iblSamplerSampler: sampler;var iblSampler: texture_cube; +#endif +uniform shadowParameters: vec4f; +#define SHADOWdirs uniforms.shadowParameters.x +#define SHADOWframe uniforms.shadowParameters.y +#define SHADOWenvRot uniforms.shadowParameters.w +uniform voxelBiasParameters : vec4f; +#define highestMipLevel uniforms.voxelBiasParameters.z +uniform sssParameters: vec4f; +#define SSSsamples uniforms.sssParameters.x +#define SSSstride uniforms.sssParameters.y +#define SSSmaxDistance uniforms.sssParameters.z +#define SSSthickness uniforms.sssParameters.w +uniform shadowOpacity: vec4f;uniform projMtx: mat4x4f;uniform viewMtx: mat4x4f;uniform invProjMtx: mat4x4f;uniform invViewMtx: mat4x4f;uniform wsNormalizationMtx: mat4x4f;uniform invVPMtx: mat4x4f; +#define PI 3.1415927 +#define GOLD 0.618034 +struct AABB3f {m_min: vec3f, +m_max: vec3f,};struct Ray {orig: vec3f, +dir: vec3f, +dir_rcp: vec3f, +t_min: f32, +t_max: f32,};fn make_ray(origin: vec3f,direction: vec3f,tmin: f32, +tmax: f32)->Ray {var ray: Ray;ray.orig=origin;ray.dir=direction;ray.dir_rcp=1.0f/direction;ray.t_min=tmin;ray.t_max=tmax;return ray;} +fn ray_box_intersection(aabb: AABB3f,ray: Ray , +distance_near: ptr,distance_far: ptr)->bool{var tbot: vec3f=ray.dir_rcp*(aabb.m_min-ray.orig);var ttop: vec3f=ray.dir_rcp*(aabb.m_max-ray.orig);var tmin: vec3f=min(ttop,tbot);var tmax: vec3f=max(ttop,tbot);*distance_near=max(ray.t_min,max(tmin.x,max(tmin.y,tmin.z)));*distance_far=min(ray.t_max,min(tmax.x,min(tmax.y,tmax.z)));return *distance_near<=*distance_far;} +#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +struct VoxelMarchDiagnosticInfo {heat: f32, +voxel_intersect_coords: vec3i,}; +#endif +fn hash(i: u32)->u32 {var temp=i ^ (i>>16u);temp*=0x7FEB352Du;temp ^= temp>>15u;temp*=0x846CA68Bu;temp ^= temp>>16u;return temp;} +fn uintBitsToFloat(x: u32)->f32 {return bitcast(x);} +fn uint2float(i: u32)->f32 {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;} +fn uv_to_normal(uv: vec2f)->vec3f {var N: vec3f;var uvRange: vec2f=uv;var theta: f32=uvRange.x*2.0*PI;var phi: f32=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;} +fn plasticSequence(rstate: u32)->vec2f {return vec2f(uint2float(rstate*3242174889u), +uint2float(rstate*2447445414u));} +fn goldenSequence(rstate: u32)->f32 {return uint2float(rstate*2654435769u);} +fn distanceSquared(a: vec2f,b: vec2f)->f32 {var diff: vec2f=a-b;return dot(diff,diff);} +fn genTB(N: vec3f,T: ptr,B: ptr) {var s: f32=select(1.0,-1.0,N.z<0.0);var a: f32=-1.0/(s+N.z);var b: f32=N.x*N.y*a;*T= vec3f(1.0+s*N.x*N.x*a,s*b,-s*N.x);*B= vec3f(b,s+N.y*N.y*a,-N.y);} +fn lessThan(x: vec3f,y: vec3f)->vec3 {return x)->bool { +#else +fn anyHitVoxels(ray_vs: Ray)->bool { +#endif +var stack=array(); +var invD: vec3f=ray_vs.dir_rcp;var D: vec3f=ray_vs.dir;var O: vec3f=ray_vs.orig;var negD=vec3i(lessThan(D, vec3f(0,0,0)));var voxel0: i32=negD.x | (negD.y<<1) | (negD.z<<2);var t0: vec3f=-O*invD;var t1=(vec3f(1.0)-O)*invD;var maxLod: i32= i32(highestMipLevel);var stackLevel: i32=0; +#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +var steps: u32=0u; +#endif +stack[stackLevel]=maxLod<<24;stackLevel++;while (stackLevel>0) {stackLevel=stackLevel-1;var elem: i32=stack[stackLevel];var Coords: vec4i = +vec4i(elem & 0xFF,(elem>>8) & 0xFF,(elem>>16) & 0xFF,elem>>24);if (Coords.w==0) { +#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +*voxel_march_diagnostic_info.heat= f32(steps)/24.0; +#endif +return true;} +#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +++steps; +#endif +var invRes: f32=exp2(f32(Coords.w-maxLod));var bbmin: vec3f=invRes*vec3f(Coords.xyz+negD);var bbmax: vec3f=invRes*vec3f(Coords.xyz-negD+vec3i(1));var mint: vec3f=mix(t0,t1,bbmin);var maxt: vec3f=mix(t0,t1,bbmax);var midt: vec3f=0.5*(mint+maxt);mint.x=max(0.0,mint.x);midt.x=max(0.0,midt.x);var nodeMask: u32= u32( +round(textureLoad(voxelGridSampler,Coords.xyz,Coords.w).x*255.0));Coords.w--;var voxelBit: u32=u32(voxel0);Coords=vec4i((Coords.xyz<f32 {return (near*far)/(far-depth*(far-near));} +fn screenSpaceShadow(csOrigin: vec3f,csDirection: vec3f,csZBufferSize: vec2f, +nearPlaneZ: f32,farPlaneZ: f32,noise: f32)->f32 { +#ifdef RIGHT_HANDED +var csZDir : f32=-1.0; +#else +var csZDir : f32=1.0; +#endif +var ssSamples: f32=SSSsamples;var ssMaxDist: f32=SSSmaxDistance;var ssStride: f32=SSSstride;var ssThickness: f32=SSSthickness;var rayLength: f32 = +select(ssMaxDist,(nearPlaneZ-csOrigin.z)/csDirection.z, +csZDir*(csOrigin.z+ssMaxDist*csDirection.z)0.0 && stepCount)->f32 { +#else +fn voxelShadow(wsOrigin: vec3f,wsDirection: vec3f,wsNormal: vec3f, +DitherNoise: vec2f)->f32 { +#endif +var vxResolution: f32=f32(textureDimensions(voxelGridSampler,0).x);var T: vec3f;var B: vec3f;genTB(wsDirection,&T,&B);var DitherXY: vec2f=sqrt(DitherNoise.x)* vec2f(cos(2.0*PI*DitherNoise.y), +sin(2.0*PI*DitherNoise.y));var Dithering : vec3f=(uniforms.voxelBiasParameters.x*wsNormal + +uniforms.voxelBiasParameters.y*wsDirection + +DitherXY.x*T+DitherXY.y*B) / +vxResolution;var O: vec3f=0.5*wsOrigin+0.5+Dithering;var ray_vs=make_ray(O,wsDirection,0.0,10.0);var voxel_aabb: AABB3f;voxel_aabb.m_min=vec3f(0);voxel_aabb.m_max=vec3f(1);var near: f32=0;var far: f32=0;if (!ray_box_intersection(voxel_aabb,ray_vs,&near,&far)) {return 0.0;} +ray_vs.t_min=max(ray_vs.t_min,near);ray_vs.t_max=min(ray_vs.t_max,far); +#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +return select(0.0f,1.0f,anyHitVoxels(ray_vs,voxel_march_diagnostic_info)); +#else +return select(0.0f,1.0f,anyHitVoxels(ray_vs)); +#endif +} +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var nbDirs=u32(SHADOWdirs);var frameId=u32(SHADOWframe);var envRot: f32=SHADOWenvRot;var Resolution: vec2f= vec2f(textureDimensions(depthSampler,0));var currentPixel=vec2i(fragmentInputs.vUV*Resolution);var GlobalIndex = +(frameId*u32(Resolution.y)+u32(currentPixel.y))*u32(Resolution.x) + +u32(currentPixel.x);var N : vec3f=textureLoad(worldNormalSampler,currentPixel,0).xyz;if (length(N)<0.01) {fragmentOutputs.color=vec4f(1.0,1.0,0.0,1.0);return fragmentOutputs;} +var normalizedRotation: f32=envRot/(2.0*PI);var depth : f32=textureLoad(depthSampler,currentPixel,0).x; +#ifndef IS_NDC_HALF_ZRANGE +depth=depth*2.0-1.0; +#endif +var temp : vec2f=(vec2f(currentPixel)+vec2f(0.5))*2.0/Resolution - +vec2f(1.0);var VP : vec4f=uniforms.invProjMtx*vec4f(temp.x,-temp.y,depth,1.0);VP/=VP.w;N=normalize(N);var noise : vec3f=textureLoad(blueNoiseSampler,currentPixel & vec2i(0xFF),0).xyz;noise.z=fract(noise.z+goldenSequence(frameId*nbDirs)); +#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +var heat: f32=0.0f; +#endif +var shadowAccum: f32=0.001;var specShadowAccum: f32=0.001;var sampleWeight : f32=0.001; +#ifdef COLOR_SHADOWS +var totalLight: vec3f=vec3f(0.001);var shadowedLight: vec3f=vec3f(0.0); +#endif +for (var i: u32=0; i0.0) {var VP2: vec4f=VP;VP2.y*=-1.0;var unormWP : vec4f=uniforms.invViewMtx*VP2;var WP: vec3f=(uniforms.wsNormalizationMtx*unormWP).xyz;var vxNoise: vec2f=vec2f(uint2float(hash(dirId*2)),uint2float(hash(dirId*2+1))); +#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +VoxelMarchDiagnosticInfo voxel_march_diagnostic_info;opacity=max(opacity, +uniforms.shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise, +voxel_march_diagnostic_info));heat+=voxel_march_diagnostic_info.heat; +#else +opacity = +max(opacity,uniforms.shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise)); +#endif +var VL : vec3f=(uniforms.viewMtx*L).xyz; +#ifdef RIGHT_HANDED +var nearPlaneZ: f32=-2.0*uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]-1.0); +var farPlaneZ: f32=-uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]+1.0); +#else +var nearPlaneZ: f32=-2.0*uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]+1.0); +var farPlaneZ: f32=-uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]-1.0); +#endif +var ssShadow: f32=uniforms.shadowOpacity.y * +screenSpaceShadow(VP2.xyz,VL,Resolution,nearPlaneZ,farPlaneZ, +abs(2.0*noise.z-1.0));opacity=max(opacity,ssShadow); +#ifdef COLOR_SHADOWS +var light: vec3f=select(vec3f(0.0),vec3f(cosNL)/vec3f(pdf)*ibl,pdf>1e-6);shadowedLight+=light*opacity;totalLight+=light; +#else +var rcos: f32=1.0-cosNL;shadowAccum+=(1.0-opacity*(1.0-pow(rcos,8.0)));sampleWeight+=1.0;var VR : vec3f=abs((uniforms.viewMtx*vec4f(reflect(-L.xyz,N),0.0)).xyz);specShadowAccum+=max(1.0-(opacity*pow(VR.z,8.0)),0.0); +#endif +} +noise.z=fract(noise.z+GOLD);} +#ifdef COLOR_SHADOWS +var shadow: vec3f=(totalLight-shadowedLight)/totalLight;var maxShadow: f32=max(max(shadow.x,max(shadow.y,shadow.z)),1.0);fragmentOutputs.color=vec4f(shadow/maxShadow,1.0); +#else +#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION +fragmentOutputs.color = +vec4f(shadowAccum/sampleWeight,specShadowAccum/sampleWeight,heat/sampleWeight,1.0); +#else +fragmentOutputs.color=vec4f(shadowAccum/sampleWeight,specShadowAccum/sampleWeight,0.0,1.0); +#endif +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$P]) { + ShaderStore.ShadersStoreWGSL[name$P] = shader$O; +} + +// Do not edit. +const name$O = "iblShadowDebugPixelShader"; +const shader$N = `#ifdef GL_ES +precision mediump float; +#endif +varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D debugSampler;uniform vec4 sizeParams; +#define offsetX sizeParams.x +#define offsetY sizeParams.y +#define widthScale sizeParams.z +#define heightScale sizeParams.w +void main(void) {vec2 uv = +vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 background=texture2D(textureSampler,vUV);vec4 debugColour=texture2D(debugSampler,vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=background;} else {gl_FragColor.rgb=mix(debugColour.rgb,background.rgb,0.0);gl_FragColor.a=1.0;}}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$O]) { + ShaderStore.ShadersStore[name$O] = shader$N; +} + +// Do not edit. +const name$N = "iblShadowDebugPixelShader"; +const shader$M = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var debugSamplerSampler: sampler;var debugSampler: texture_2d;uniform sizeParams: vec4f; +#define offsetX uniforms.sizeParams.x +#define offsetY uniforms.sizeParams.y +#define widthScale uniforms.sizeParams.z +#define heightScale uniforms.sizeParams.w +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f = +vec2f((offsetX+fragmentInputs.vUV.x)*widthScale,(offsetY+fragmentInputs.vUV.y)*heightScale);var background: vec4f=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV);var debugColour: vec4f=textureSample(debugSampler,debugSamplerSampler,fragmentInputs.vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=background;} else {fragmentOutputs.color=vec4f(mix(debugColour.rgb,background.rgb,0.0),1.0);}}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$N]) { + ShaderStore.ShadersStoreWGSL[name$N] = shader$M; +} + +// Do not edit. +const name$M = "iblShadowSpatialBlurPixelShader"; +const shader$L = `#define PI 3.1415927 +varying vUV: vec2f;var depthSampler: texture_2d;var worldNormalSampler: texture_2d;var voxelTracingSampler : texture_2d;uniform blurParameters: vec4f; +#define stridef uniforms.blurParameters.x +#define worldScale uniforms.blurParameters.y +const weights=array(0.0625,0.25,0.375,0.25,0.0625);const nbWeights: i32=5;fn max2(v: vec2f,w: vec2f)->vec2f {return vec2f(max(v.x,w.x),max(v.y,w.y));} +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var gbufferRes=vec2f(textureDimensions(depthSampler,0));var gbufferPixelCoord= vec2i(fragmentInputs.vUV*gbufferRes);var shadowRes=vec2f(textureDimensions(voxelTracingSampler,0));var shadowPixelCoord= vec2i(fragmentInputs.vUV*shadowRes);var N: vec3f=textureLoad(worldNormalSampler,gbufferPixelCoord,0).xyz;if (length(N)<0.01) {fragmentOutputs.color=vec4f(1.0,1.0,0.0,1.0);return fragmentOutputs;} +var depth: f32=-textureLoad(depthSampler,gbufferPixelCoord,0).x;var X: vec4f= vec4f(0.0);for(var y: i32=0; y>1),y-(nbWeights>>1));var shadowCoords: vec2i=shadowPixelCoord+i32(stridef)*vec2i(x-(nbWeights>>1),y-(nbWeights>>1));var T : vec3f=textureLoad(voxelTracingSampler,shadowCoords,0).xyz;var ddepth: f32=-textureLoad(depthSampler,gBufferCoords,0).x-depth;var dN: vec3f=textureLoad(worldNormalSampler,gBufferCoords,0).xyz-N;var w: f32=weights[x]*weights[y] * +exp2(max(-1000.0/(worldScale*worldScale),-0.5) * +(ddepth*ddepth) - +1e1*dot(dN,dN));X+= vec4f(w*T.x,w*T.y,w*T.z,w);}} +fragmentOutputs.color= vec4f(X.x/X.w,X.y/X.w,X.z/X.w,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$M]) { + ShaderStore.ShadersStoreWGSL[name$M] = shader$L; +} + +// Do not edit. +const name$L = "iblShadowSpatialBlurPixelShader"; +const shader$K = `precision highp sampler2D; +#define PI 3.1415927 +varying vec2 vUV;uniform sampler2D depthSampler;uniform sampler2D worldNormalSampler;uniform sampler2D voxelTracingSampler;uniform vec4 blurParameters; +#define stridef blurParameters.x +#define worldScale blurParameters.y +const float weights[5]=float[5](0.0625,0.25,0.375,0.25,0.0625);const int nbWeights=5;vec2 max2(vec2 v,vec2 w) {return vec2(max(v.x,w.x),max(v.y,w.y));} +void main(void) +{vec2 gbufferRes=vec2(textureSize(depthSampler,0));ivec2 gbufferPixelCoord=ivec2(vUV*gbufferRes);vec2 shadowRes=vec2(textureSize(voxelTracingSampler,0));ivec2 shadowPixelCoord=ivec2(vUV*shadowRes);vec3 N=texelFetch(worldNormalSampler,gbufferPixelCoord,0).xyz;if (length(N)<0.01) {glFragColor=vec4(1.0,1.0,0.0,1.0);return;} +float depth=-texelFetch(depthSampler,gbufferPixelCoord,0).x;vec4 X=vec4(0.0);for(int y=0; y>1),y-(nbWeights>>1));ivec2 shadowCoords=shadowPixelCoord+int(stridef)*ivec2(x-(nbWeights>>1),y-(nbWeights>>1));vec4 T=texelFetch(voxelTracingSampler,shadowCoords,0);float ddepth=-texelFetch(depthSampler,gBufferCoords,0).x-depth;vec3 dN=texelFetch(worldNormalSampler,gBufferCoords,0).xyz-N;float w=weights[x]*weights[y] * +exp2(max(-1000.0/(worldScale*worldScale),-0.5) * +(ddepth*ddepth) - +1e1*dot(dN,dN));X+=vec4(w*T.x,w*T.y,w*T.z,w);}} +gl_FragColor=vec4(X.x/X.w,X.y/X.w,X.z/X.w,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$L]) { + ShaderStore.ShadersStore[name$L] = shader$K; +} + +// Do not edit. +const name$K = "iblShadowAccumulationPixelShader"; +const shader$J = `varying vUV: vec2f;uniform accumulationParameters: vec4f; +#define remanence uniforms.accumulationParameters.x +#define resetb uniforms.accumulationParameters.y +#define sceneSize uniforms.accumulationParameters.z +var motionSampler: texture_2d;var positionSampler: texture_2d;var spatialBlurSampler : texture_2d;var oldAccumulationSamplerSampler: sampler;var oldAccumulationSampler: texture_2d;var prevPositionSamplerSampler: sampler;var prevPositionSampler: texture_2d;fn max2(v: vec2f,w: vec2f)->vec2f { +return vec2f(max(v.x,w.x),max(v.y,w.y)); } +fn lessThan(x: vec2f,y: vec2f)->vec2 {return xFragmentOutputs {var reset: bool= bool(resetb);var gbufferRes : vec2f=vec2f(textureDimensions(positionSampler,0));var gbufferPixelCoord: vec2i= vec2i(input.vUV*gbufferRes);var shadowRes : vec2f=vec2f(textureDimensions(spatialBlurSampler,0));var shadowPixelCoord: vec2i= vec2i(input.vUV*shadowRes);var LP: vec4f=textureLoad(positionSampler,gbufferPixelCoord,0);if (0.0==LP.w) {fragmentOutputs.color=vec4f(1.0,0.0,0.0,1.0);return fragmentOutputs;} +var velocityColor: vec2f=textureLoad(motionSampler,gbufferPixelCoord,0).xy;var prevCoord: vec2f=input.vUV+velocityColor;var PrevLP: vec3f=textureSampleLevel(prevPositionSampler,prevPositionSamplerSampler,prevCoord,0.0).xyz;var PrevShadows: vec4f=textureSampleLevel(oldAccumulationSampler,oldAccumulationSamplerSampler,prevCoord,0.0);var newShadows : vec3f=textureLoad(spatialBlurSampler,shadowPixelCoord,0).xyz;PrevShadows.a=select(1.0,max(PrevShadows.a/(1.0+PrevShadows.a),1.0-remanence),!reset && all(lessThan(abs(prevCoord- vec2f(0.5)), vec2f(0.5))) && +distance(LP.xyz,PrevLP)<5e-2*sceneSize);PrevShadows=max( vec4f(0.0),PrevShadows);fragmentOutputs.color= vec4f(mix(PrevShadows.x,newShadows.x,PrevShadows.a), +mix(PrevShadows.y,newShadows.y,PrevShadows.a), +mix(PrevShadows.z,newShadows.z,PrevShadows.a),PrevShadows.a);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$K]) { + ShaderStore.ShadersStoreWGSL[name$K] = shader$J; +} + +// Do not edit. +const name$J = "iblShadowAccumulationPixelShader"; +const shader$I = `#ifdef GL_ES +precision mediump float; +#endif +varying vec2 vUV;uniform vec4 accumulationParameters; +#define remanence accumulationParameters.x +#define resetb accumulationParameters.y +#define sceneSize accumulationParameters.z +uniform sampler2D motionSampler;uniform sampler2D positionSampler;uniform sampler2D spatialBlurSampler;uniform sampler2D oldAccumulationSampler;uniform sampler2D prevPositionSampler;vec2 max2(vec2 v,vec2 w) { return vec2(max(v.x,w.x),max(v.y,w.y)); } +void main(void) {bool reset=bool(resetb);vec2 gbufferRes=vec2(textureSize(motionSampler,0));ivec2 gbufferPixelCoord=ivec2(vUV*gbufferRes);vec2 shadowRes=vec2(textureSize(spatialBlurSampler,0));ivec2 shadowPixelCoord=ivec2(vUV*shadowRes);vec4 LP=texelFetch(positionSampler,gbufferPixelCoord,0);if (0.0==LP.w) {gl_FragColor=vec4(1.0,0.0,0.0,1.0);return;} +vec2 velocityColor=texelFetch(motionSampler,gbufferPixelCoord,0).xy;vec2 prevCoord=vUV+velocityColor;vec3 PrevLP=texture(prevPositionSampler,prevCoord).xyz;vec4 PrevShadows=texture(oldAccumulationSampler,prevCoord);vec3 newShadows=texelFetch(spatialBlurSampler,shadowPixelCoord,0).xyz;PrevShadows.a = +!reset && all(lessThan(abs(prevCoord-vec2(0.5)),vec2(0.5))) && +distance(LP.xyz,PrevLP)<5e-2*sceneSize +? max(PrevShadows.a/(1.0+PrevShadows.a),1.0-remanence) +: 1.0;PrevShadows=max(vec4(0.0),PrevShadows);gl_FragColor = +vec4(mix(PrevShadows.x,newShadows.x,PrevShadows.a), +mix(PrevShadows.y,newShadows.y,PrevShadows.a), +mix(PrevShadows.z,newShadows.z,PrevShadows.a),PrevShadows.a);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$J]) { + ShaderStore.ShadersStore[name$J] = shader$I; +} + +// Do not edit. +const name$I = "iblShadowsCombinePixelShader"; +const shader$H = `precision highp float;varying vec2 vUV;uniform sampler2D shadowSampler;uniform sampler2D textureSampler;uniform float shadowOpacity;void main(void) +{vec3 shadow=texture(shadowSampler,vUV).rgb;vec3 sceneColor=texture(textureSampler,vUV).rgb;float shadowValue=mix(1.0,shadow.x,shadowOpacity);gl_FragColor=vec4(sceneColor*shadowValue,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$I]) { + ShaderStore.ShadersStore[name$I] = shader$H; +} + +// Do not edit. +const name$H = "iblShadowsCombinePixelShader"; +const shader$G = `varying vUV: vec2f;var shadowSamplerSampler : sampler;var shadowSampler : texture_2d;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform shadowOpacity: f32;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var shadow +: vec3f = +textureSample(shadowSampler,shadowSamplerSampler,input.vUV).rgb;var color +: vec3f = +textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var shadowValue: f32=mix(1.0,shadow.x,uniforms.shadowOpacity);fragmentOutputs.color=vec4f(color*shadowValue,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$H]) { + ShaderStore.ShadersStoreWGSL[name$H] = shader$G; +} + +// Do not edit. +const name$G = "iblCombineVoxelGridsPixelShader"; +const shader$F = `varying vUV: vec2f;var voxelXaxisSamplerSampler: sampler;var voxelXaxisSampler: texture_3d;var voxelYaxisSamplerSampler: sampler;var voxelYaxisSampler: texture_3d;var voxelZaxisSamplerSampler: sampler;var voxelZaxisSampler: texture_3d;uniform layer: f32;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var coordZ: vec3f= vec3f(fragmentInputs.vUV.x,fragmentInputs.vUV.y,uniforms.layer);var voxelZ: f32=textureSample(voxelZaxisSampler,voxelZaxisSamplerSampler,coordZ).r;var coordX: vec3f= vec3f(1.0-uniforms.layer,fragmentInputs.vUV.y,fragmentInputs.vUV.x);var voxelX: f32=textureSample(voxelXaxisSampler,voxelXaxisSamplerSampler,coordX).r;var coordY: vec3f= vec3f(uniforms.layer,fragmentInputs.vUV.x,fragmentInputs.vUV.y);var voxelY: f32=textureSample(voxelYaxisSampler,voxelYaxisSamplerSampler,coordY).r;var voxel=select(0.0,1.0,(voxelX>0.0 || voxelY>0.0 || voxelZ>0.0));fragmentOutputs.color= vec4f( vec3f(voxel),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$G]) { + ShaderStore.ShadersStoreWGSL[name$G] = shader$F; +} + +// Do not edit. +const name$F = "iblCombineVoxelGridsPixelShader"; +const shader$E = `precision highp float;precision highp sampler3D;varying vec2 vUV;uniform sampler3D voxelXaxisSampler;uniform sampler3D voxelYaxisSampler;uniform sampler3D voxelZaxisSampler;uniform float layer;void main(void) {vec3 coordZ=vec3(vUV.x,vUV.y,layer);float voxelZ=texture(voxelZaxisSampler,coordZ).r;vec3 coordX=vec3(1.0-layer,vUV.y,vUV.x);float voxelX=texture(voxelXaxisSampler,coordX).r;vec3 coordY=vec3(layer,vUV.x,vUV.y);float voxelY=texture(voxelYaxisSampler,coordY).r;float voxel=(voxelX>0.0 || voxelY>0.0 || voxelZ>0.0) ? 1.0 : 0.0;glFragColor=vec4(vec3(voxel),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$F]) { + ShaderStore.ShadersStore[name$F] = shader$E; +} + +// Do not edit. +const name$E = "iblGenerateVoxelMipPixelShader"; +const shader$D = `precision highp float;precision highp sampler3D;varying vec2 vUV;uniform sampler3D srcMip;uniform int layerNum;void main(void) {ivec3 Coords=ivec3(2)*ivec3(gl_FragCoord.x,gl_FragCoord.y,layerNum);uint tex = +uint(texelFetch(srcMip,Coords+ivec3(0,0,0),0).x>0.0f ? 1u : 0u) +<< 0u | +uint(texelFetch(srcMip,Coords+ivec3(1,0,0),0).x>0.0f ? 1u : 0u) +<< 1u | +uint(texelFetch(srcMip,Coords+ivec3(0,1,0),0).x>0.0f ? 1u : 0u) +<< 2u | +uint(texelFetch(srcMip,Coords+ivec3(1,1,0),0).x>0.0f ? 1u : 0u) +<< 3u | +uint(texelFetch(srcMip,Coords+ivec3(0,0,1),0).x>0.0f ? 1u : 0u) +<< 4u | +uint(texelFetch(srcMip,Coords+ivec3(1,0,1),0).x>0.0f ? 1u : 0u) +<< 5u | +uint(texelFetch(srcMip,Coords+ivec3(0,1,1),0).x>0.0f ? 1u : 0u) +<< 6u | +uint(texelFetch(srcMip,Coords+ivec3(1,1,1),0).x>0.0f ? 1u : 0u) +<< 7u;glFragColor.rgb=vec3(float(tex)/255.0f,0.0f,0.0f);glFragColor.a=1.0;}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$E]) { + ShaderStore.ShadersStore[name$E] = shader$D; +} + +// Do not edit. +const name$D = "iblGenerateVoxelMipPixelShader"; +const shader$C = `varying vUV: vec2f;var srcMip: texture_3d;uniform layerNum: i32;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var Coords=vec3i(2)*vec3i(vec2i(fragmentInputs.position.xy),uniforms.layerNum);var tex = +(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,0,0),0).x>0.0f)) +<< 0u) | +(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,0,0),0).x>0.0f)) +<< 1u) | +(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,1,0),0).x>0.0f)) +<< 2u) | +(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,1,0),0).x>0.0f)) +<< 3u) | +(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,0,1),0).x>0.0f)) +<< 4u) | +(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,0,1),0).x>0.0f)) +<< 5u) | +(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,1,1),0).x>0.0f)) +<< 6u) | +(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,1,1),0).x>0.0f)) +<< 7u);fragmentOutputs.color=vec4f( f32(tex)/255.0f,0.0f,0.0f,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$D]) { + ShaderStore.ShadersStoreWGSL[name$D] = shader$C; +} + +// Do not edit. +const name$C = "iblShadowGBufferDebugPixelShader"; +const shader$B = `#ifdef GL_ES +precision mediump float; +#endif +varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler;uniform sampler2D velocitySampler;uniform vec4 sizeParams;uniform float maxDepth; +#define offsetX sizeParams.x +#define offsetY sizeParams.y +#define widthScale sizeParams.z +#define heightScale sizeParams.w +void main(void) {vec2 uv = +vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 backgroundColour=texture2D(textureSampler,vUV).rgba;vec4 depth=texture2D(depthSampler,vUV);vec4 worldNormal=texture2D(normalSampler,vUV);vec4 worldPosition=texture2D(positionSampler,vUV);vec4 velocityLinear=texture2D(velocitySampler,vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=backgroundColour;} else {gl_FragColor.a=1.0;if (uv.x<=0.25) {gl_FragColor.rgb=depth.rgb;gl_FragColor.a=1.0;} else if (uv.x<=0.5) {velocityLinear.rg=velocityLinear.rg*0.5+0.5;gl_FragColor.rgb=velocityLinear.rgb;} else if (uv.x<=0.75) {gl_FragColor.rgb=worldPosition.rgb;} else {gl_FragColor.rgb=worldNormal.rgb;}}}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$C]) { + ShaderStore.ShadersStore[name$C] = shader$B; +} + +// Do not edit. +const name$B = "iblShadowGBufferDebugPixelShader"; +const shader$A = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var depthSampler: sampler;var depthTexture: texture_2d;var normalSampler: sampler;var normalTexture: texture_2d;var positionSampler: sampler;var positionTexture: texture_2d;var velocitySampler: sampler;var velocityTexture: texture_2d;uniform sizeParams: vec4f;uniform maxDepth: f32; +#define offsetX uniforms.sizeParams.x +#define offsetY uniforms.sizeParams.y +#define widthScale uniforms.sizeParams.z +#define heightScale uniforms.sizeParams.w +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f = +vec2f((offsetX+input.vUV.x)*widthScale,(offsetY+input.vUV.y)*heightScale);var backgroundColour: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgba;var depth: vec4f=textureSample(depthTexture,depthSampler,input.vUV);var worldNormal: vec4f=textureSample(normalTexture,normalSampler,input.vUV);var worldPosition: vec4f=textureSample(positionTexture,positionSampler,input.vUV);var velocityLinear: vec4f=textureSample(velocityTexture,velocitySampler,input.vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=backgroundColour;} else {if (uv.x<=0.25) {fragmentOutputs.color=vec4f(depth.rgb,1.0);} else if (uv.x<=0.5) {velocityLinear=vec4f(velocityLinear.r*0.5+0.5,velocityLinear.g*0.5+0.5,velocityLinear.b,velocityLinear.a);fragmentOutputs.color=vec4f(velocityLinear.rgb,1.0);} else if (uv.x<=0.75) {fragmentOutputs.color=vec4f(worldPosition.rgb,1.0);} else {fragmentOutputs.color=vec4f(worldNormal.rgb,1.0);}}}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$B]) { + ShaderStore.ShadersStoreWGSL[name$B] = shader$A; +} + +// Do not edit. +const name$A = "iblCdfxPixelShader"; +const shader$z = `#define PI 3.1415927 +varying vUV: vec2f;var cdfy: texture_2d;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var cdfyRes=textureDimensions(cdfy,0);var currentPixel=vec2u(fragmentInputs.position.xy);var cdfx: f32=0.0;for (var x: u32=1; x<=currentPixel.x; x++) {cdfx+=textureLoad(cdfy, vec2u(x-1,cdfyRes.y-1),0).x;} +fragmentOutputs.color= vec4f( vec3f(cdfx),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$A]) { + ShaderStore.ShadersStoreWGSL[name$A] = shader$z; +} +/** @internal */ +const iblCdfxPixelShaderWGSL = { name: name$A, shader: shader$z }; + +const iblCdfx_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + iblCdfxPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$z = "iblCdfxPixelShader"; +const shader$y = `precision highp sampler2D; +#define PI 3.1415927 +varying vec2 vUV;uniform sampler2D cdfy;void main(void) {ivec2 cdfyRes=textureSize(cdfy,0);ivec2 currentPixel=ivec2(gl_FragCoord.xy);float cdfx=0.0;for (int x=1; x<=currentPixel.x; x++) {cdfx+=texelFetch(cdfy,ivec2(x-1,cdfyRes.y-1),0).x;} +gl_FragColor=vec4(vec3(cdfx),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$z]) { + ShaderStore.ShadersStore[name$z] = shader$y; +} +/** @internal */ +const iblCdfxPixelShader = { name: name$z, shader: shader$y }; + +const iblCdfx_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + iblCdfxPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$y = "iblCdfyPixelShader"; +const shader$x = `varying vUV : vec2f; +#include +#ifdef IBL_USE_CUBE_MAP +var iblSourceSampler: sampler;var iblSource: texture_cube; +#else +var iblSourceSampler: sampler;var iblSource: texture_2d; +#endif +uniform iblHeight: i32; +#ifdef IBL_USE_CUBE_MAP +fn fetchCube(uv: vec2f)->f32 {var direction: vec3f=equirectangularToCubemapDirection(uv);return sin(PI*uv.y) * +dot(textureSampleLevel(iblSource,iblSourceSampler,direction,0.0) +.rgb, +LuminanceEncodeApprox);} +#else +fn fetchPanoramic(Coords: vec2i,envmapHeight: f32)->f32 {return sin(PI*(f32(Coords.y)+0.5)/envmapHeight) * +dot(textureLoad(iblSource,Coords,0).rgb,LuminanceEncodeApprox);} +#endif +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var coords: vec2i= vec2i(fragmentInputs.position.xy);var cdfy: f32=0.0;for (var y: i32=1; y<=coords.y; y++) { +#ifdef IBL_USE_CUBE_MAP +var uv: vec2f= vec2f(input.vUV.x,( f32(y-1)+0.5)/ f32(uniforms.iblHeight));cdfy+=fetchCube(uv); +#else +cdfy+=fetchPanoramic( vec2i(coords.x,y-1), f32(uniforms.iblHeight)); +#endif +} +fragmentOutputs.color= vec4f(cdfy,0.0,0.0,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$y]) { + ShaderStore.ShadersStoreWGSL[name$y] = shader$x; +} +/** @internal */ +const iblCdfyPixelShaderWGSL = { name: name$y, shader: shader$x }; + +const iblCdfy_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + iblCdfyPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$x = "iblCdfyPixelShader"; +const shader$w = `precision highp sampler2D;precision highp samplerCube; +#include +#define PI 3.1415927 +varying vec2 vUV; +#ifdef IBL_USE_CUBE_MAP +uniform samplerCube iblSource; +#else +uniform sampler2D iblSource; +#endif +uniform int iblHeight; +#ifdef IBL_USE_CUBE_MAP +float fetchCube(vec2 uv) {vec3 direction=equirectangularToCubemapDirection(uv);return sin(PI*uv.y)*dot(textureCubeLodEXT(iblSource,direction,0.0).rgb,LuminanceEncodeApprox);} +#else +float fetchPanoramic(ivec2 Coords,float envmapHeight) {return sin(PI*(float(Coords.y)+0.5)/envmapHeight) * +dot(texelFetch(iblSource,Coords,0).rgb,LuminanceEncodeApprox);} +#endif +void main(void) {ivec2 coords=ivec2(gl_FragCoord.x,gl_FragCoord.y);float cdfy=0.0;for (int y=1; y<=coords.y; y++) { +#ifdef IBL_USE_CUBE_MAP +vec2 uv=vec2(vUV.x,(float(y-1)+0.5)/float(iblHeight));cdfy+=fetchCube(uv); +#else +cdfy+=fetchPanoramic(ivec2(coords.x,y-1),float(iblHeight)); +#endif +} +gl_FragColor=vec4(cdfy,0.0,0.0,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$x]) { + ShaderStore.ShadersStore[name$x] = shader$w; +} +/** @internal */ +const iblCdfyPixelShader = { name: name$x, shader: shader$w }; + +const iblCdfy_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + iblCdfyPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$w = "iblIcdfPixelShader"; +const shader$v = `#include +varying vUV: vec2f; +#ifdef IBL_USE_CUBE_MAP +var iblSourceSampler: sampler;var iblSource: texture_cube; +#else +var iblSourceSampler: sampler;var iblSource: texture_2d; +#endif +var scaledLuminanceSamplerSampler : sampler;var scaledLuminanceSampler : texture_2d;var cdfx: texture_2d;var cdfy: texture_2d;fn fetchLuminance(coords: vec2f)->f32 { +#ifdef IBL_USE_CUBE_MAP +var direction: vec3f=equirectangularToCubemapDirection(coords);var color: vec3f=textureSampleLevel(iblSource,iblSourceSampler,direction,0.0).rgb; +#else +var color: vec3f=textureSampleLevel(iblSource,iblSourceSampler,coords,0.0).rgb; +#endif +return dot(color,LuminanceEncodeApprox);} +fn fetchCDFx(x: u32)->f32 {return textureLoad(cdfx, vec2u(x,0),0).x;} +fn bisectx(size: u32,targetValue: f32)->f32 +{var a: u32=0;var b=size-1;while (b-a>1) {var c: u32=(a+b)>>1;if (fetchCDFx(c)f32 {return textureLoad(cdfy, vec2u(invocationId,y),0).x;} +fn bisecty(size: u32,targetValue: f32,invocationId: u32)->f32 +{var a: u32=0;var b=size-1;while (b-a>1) {var c=(a+b)>>1;if (fetchCDFy(c,invocationId)FragmentOutputs {var cdfxSize: vec2u=textureDimensions(cdfx,0);var cdfWidth: u32=cdfxSize.x;var icdfWidth: u32=cdfWidth-1;var currentPixel: vec2u= vec2u(fragmentInputs.position.xy);var outputColor: vec3f=vec3f(1.0);if (currentPixel.x==0) +{outputColor.x= 0.0;} +else if (currentPixel.x==icdfWidth-1) {outputColor.x= 1.0;} else {var targetValue: f32=fetchCDFx(cdfWidth-1)*input.vUV.x;outputColor.x= bisectx(cdfWidth,targetValue);} +var cdfySize: vec2u=textureDimensions(cdfy,0);var cdfHeight: u32=cdfySize.y;if (currentPixel.y==0) {outputColor.y= 0.0;} +else if (currentPixel.y==cdfHeight-2) {outputColor.y= 1.0;} else {var targetValue: f32=fetchCDFy(cdfHeight-1,currentPixel.x)*input.vUV.y;outputColor.y= max(bisecty(cdfHeight,targetValue,currentPixel.x),0.0);} +var size : vec2f=vec2f(textureDimensions(scaledLuminanceSampler,0));var highestMip: f32=floor(log2(size.x));var normalization : f32=textureSampleLevel(scaledLuminanceSampler, +scaledLuminanceSamplerSampler, +input.vUV,highestMip) +.r;var pixelLuminance: f32=fetchLuminance(input.vUV);outputColor.z=pixelLuminance/(2.0*PI*normalization);fragmentOutputs.color=vec4( outputColor,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$w]) { + ShaderStore.ShadersStoreWGSL[name$w] = shader$v; +} +/** @internal */ +const iblIcdfPixelShaderWGSL = { name: name$w, shader: shader$v }; + +const iblIcdf_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + iblIcdfPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$v = "iblIcdfPixelShader"; +const shader$u = `precision highp sampler2D; +#include +varying vec2 vUV; +#ifdef IBL_USE_CUBE_MAP +uniform samplerCube iblSource; +#else +uniform sampler2D iblSource; +#endif +uniform sampler2D scaledLuminanceSampler;uniform int iblWidth;uniform int iblHeight;uniform sampler2D cdfx;uniform sampler2D cdfy;float fetchLuminance(vec2 coords) { +#ifdef IBL_USE_CUBE_MAP +vec3 direction=equirectangularToCubemapDirection(coords);vec3 color=textureCubeLodEXT(iblSource,direction,0.0).rgb; +#else +vec3 color=textureLod(iblSource,coords,0.0).rgb; +#endif +return dot(color,LuminanceEncodeApprox);} +float fetchCDFx(int x) { return texelFetch(cdfx,ivec2(x,0),0).x; } +float bisectx(int size,float targetValue) {int a=0,b=size-1;while (b-a>1) {int c=a+b>>1;if (fetchCDFx(c)1) {int c=a+b>>1;if (fetchCDFy(c,invocationId);var cdfxSampler: sampler;var cdfx: texture_2d;var icdfSampler: sampler;var icdf: texture_2d; +#ifdef IBL_USE_CUBE_MAP +var iblSourceSampler: sampler;var iblSource: texture_cube; +#else +var iblSourceSampler: sampler;var iblSource: texture_2d; +#endif +var textureSamplerSampler: sampler;var textureSampler: texture_2d; +#define cdfyVSize (0.8/3.0) +#define cdfxVSize 0.1 +#define cdfyHSize 0.5 +uniform sizeParams: vec4f; +#ifdef IBL_USE_CUBE_MAP +fn equirectangularToCubemapDirection(uv: vec2f)->vec3f {var longitude: f32=uv.x*2.0*PI-PI;var latitude: f32=PI*0.5-uv.y*PI;var direction: vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;} +#endif +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +var colour: vec3f= vec3f(0.0);var uv: vec2f = +vec2f((uniforms.sizeParams.x+input.vUV.x)*uniforms.sizeParams.z,(uniforms.sizeParams.y+input.vUV.y)*uniforms.sizeParams.w);var backgroundColour: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var cdfxWidth: u32=textureDimensions(cdfx,0).x;var cdfyHeight: u32=textureDimensions(cdfy,0).y;const iblStart: f32=1.0-cdfyVSize;const pdfStart: f32=1.0-2.0*cdfyVSize;const cdfyStart: f32=1.0-3.0*cdfyVSize;const cdfxStart: f32=1.0-3.0*cdfyVSize-cdfxVSize;const icdfxStart: f32=1.0-3.0*cdfyVSize-2.0*cdfxVSize; +#ifdef IBL_USE_CUBE_MAP +var direction: vec3f=equirectangularToCubemapDirection( +(uv- vec2f(0.0,iblStart))* vec2f(1.0,1.0/cdfyVSize));var iblColour: vec3f=textureSampleLevel(iblSource,iblSourceSampler,direction,0.0).rgb; +#else +var iblColour: vec3f=textureSample(iblSource,iblSourceSampler,(uv- vec2f(0.0,iblStart)) * +vec2f(1.0,1.0/cdfyVSize)) +.rgb; +#endif +var pdfColour: vec3f = +textureSample(icdf,icdfSampler,(uv- vec2f(0.0,pdfStart))* vec2f(1.0,1.0/cdfyVSize)).zzz;var cdfyColour: f32 = +textureSample(cdfy,cdfySampler,(uv- vec2f(0.0,cdfyStart))* vec2f(2.0,1.0/cdfyVSize)).r;var icdfyColour: f32 = +textureSample(icdf,icdfSampler,(uv- vec2f(0.5,cdfyStart))* vec2f(2.0,1.0/cdfyVSize)).g;var cdfxColour: f32 = +textureSample(cdfx,cdfxSampler,(uv- vec2f(0.0,cdfxStart))* vec2f(1.0,1.0/cdfxVSize)).r;var icdfxColour: f32=textureSample(icdf,icdfSampler,(uv- vec2f(0.0,icdfxStart)) * +vec2f(1.0,1.0/cdfxVSize)).r;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {colour=backgroundColour;} else if (uv.y>iblStart) {colour+=iblColour;} else if (uv.y>pdfStart) {colour+=pdfColour;} else if (uv.y>cdfyStart && uv.x<0.5) {colour.r+=cdfyColour/f32(cdfyHeight);} else if (uv.y>cdfyStart && uv.x>0.5) {colour.r+=icdfyColour;} else if (uv.y>cdfxStart) {colour.r+=cdfxColour/f32(cdfxWidth);} else if (uv.y>icdfxStart) {colour.r+=icdfxColour;} +fragmentOutputs.color =vec4(mix(colour,backgroundColour,0.5),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$u]) { + ShaderStore.ShadersStoreWGSL[name$u] = shader$t; +} +/** @internal */ +const iblCdfDebugPixelShaderWGSL = { name: name$u, shader: shader$t }; + +const iblCdfDebug_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + iblCdfDebugPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$t = "iblCdfDebugPixelShader"; +const shader$s = `precision highp samplerCube; +#define PI 3.1415927 +varying vec2 vUV;uniform sampler2D cdfy;uniform sampler2D cdfx;uniform sampler2D icdf;uniform sampler2D pdf; +#ifdef IBL_USE_CUBE_MAP +uniform samplerCube iblSource; +#else +uniform sampler2D iblSource; +#endif +uniform sampler2D textureSampler; +#define cdfyVSize (0.8/3.0) +#define cdfxVSize 0.1 +#define cdfyHSize 0.5 +uniform vec4 sizeParams; +#define offsetX sizeParams.x +#define offsetY sizeParams.y +#define widthScale sizeParams.z +#define heightScale sizeParams.w +#ifdef IBL_USE_CUBE_MAP +vec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*2.0*PI-PI;float latitude=PI*0.5-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;} +#endif +void main(void) {vec3 colour=vec3(0.0);vec2 uv = +vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec3 backgroundColour=texture2D(textureSampler,vUV).rgb;int cdfxWidth=textureSize(cdfx,0).x;int cdfyHeight=textureSize(cdfy,0).y;const float iblStart=1.0-cdfyVSize;const float pdfStart=1.0-2.0*cdfyVSize;const float cdfyStart=1.0-3.0*cdfyVSize;const float cdfxStart=1.0-3.0*cdfyVSize-cdfxVSize;const float icdfxStart=1.0-3.0*cdfyVSize-2.0*cdfxVSize; +#ifdef IBL_USE_CUBE_MAP +vec3 direction=equirectangularToCubemapDirection( +(uv-vec2(0.0,iblStart))*vec2(1.0,1.0/cdfyVSize));vec3 iblColour=textureCubeLodEXT(iblSource,direction,0.0).rgb; +#else +vec3 iblColour=texture2D(iblSource,(uv-vec2(0.0,iblStart)) * +vec2(1.0,1.0/cdfyVSize)) +.rgb; +#endif +vec3 pdfColour=texture(icdf,(uv-vec2(0.0,pdfStart)) * +vec2(1.0,1.0/cdfyVSize)).zzz;float cdfyColour = +texture2D(cdfy,(uv-vec2(0.0,cdfyStart))*vec2(2.0,1.0/cdfyVSize)) +.r;float icdfyColour = +texture2D(icdf,(uv-vec2(0.5,cdfyStart))*vec2(2.0,1.0/cdfyVSize)) +.g;float cdfxColour = +texture2D(cdfx,(uv-vec2(0.0,cdfxStart))*vec2(1.0,1.0/cdfxVSize)) +.r;float icdfxColour=texture2D(icdf,(uv-vec2(0.0,icdfxStart)) * +vec2(1.0,1.0/cdfxVSize)) +.r;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {colour=backgroundColour;} else if (uv.y>iblStart) {colour+=iblColour;} else if (uv.y>pdfStart) {colour+=pdfColour;} else if (uv.y>cdfyStart && uv.x<0.5) {colour.r+=cdfyColour/float(cdfyHeight);} else if (uv.y>cdfyStart && uv.x>0.5) {colour.r+=icdfyColour;} else if (uv.y>cdfxStart) {colour.r+=cdfxColour/float(cdfxWidth);} else if (uv.y>icdfxStart) {colour.r+=icdfxColour;} +gl_FragColor=vec4(colour,1.0);glFragColor.rgb=mix(gl_FragColor.rgb,backgroundColour,0.5);} +`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$t]) { + ShaderStore.ShadersStore[name$t] = shader$s; +} +/** @internal */ +const iblCdfDebugPixelShader = { name: name$t, shader: shader$s }; + +const iblCdfDebug_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + iblCdfDebugPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$s = "iblScaledLuminancePixelShader"; +const shader$r = `#include +#ifdef IBL_USE_CUBE_MAP +var iblSourceSampler: sampler;var iblSource: texture_cube; +#else +var iblSourceSampler: sampler;var iblSource: texture_2d; +#endif +uniform iblHeight: i32;uniform iblWidth: i32;fn fetchLuminance(coords: vec2f)->f32 { +#ifdef IBL_USE_CUBE_MAP +var direction: vec3f=equirectangularToCubemapDirection(coords);var color: vec3f=textureSampleLevel(iblSource,iblSourceSampler,direction,0.0).rgb; +#else +var color: vec3f=textureSampleLevel(iblSource,iblSourceSampler,coords,0.0).rgb; +#endif +return dot(color,LuminanceEncodeApprox);} +@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var deform: f32=sin(input.vUV.y*PI);var luminance: f32=fetchLuminance(input.vUV);fragmentOutputs.color=vec4f(vec3f(deform*luminance),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$s]) { + ShaderStore.ShadersStoreWGSL[name$s] = shader$r; +} +/** @internal */ +const iblScaledLuminancePixelShaderWGSL = { name: name$s, shader: shader$r }; + +const iblScaledLuminance_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + iblScaledLuminancePixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$r = "iblScaledLuminancePixelShader"; +const shader$q = `precision highp sampler2D;precision highp samplerCube; +#include +varying vec2 vUV; +#ifdef IBL_USE_CUBE_MAP +uniform samplerCube iblSource; +#else +uniform sampler2D iblSource; +#endif +uniform int iblWidth;uniform int iblHeight;float fetchLuminance(vec2 coords) { +#ifdef IBL_USE_CUBE_MAP +vec3 direction=equirectangularToCubemapDirection(coords);vec3 color=textureCubeLodEXT(iblSource,direction,0.0).rgb; +#else +vec3 color=textureLod(iblSource,coords,0.0).rgb; +#endif +return dot(color,LuminanceEncodeApprox);} +void main(void) {float deform=sin(vUV.y*PI);float luminance=fetchLuminance(vUV);gl_FragColor=vec4(vec3(deform*luminance),1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$r]) { + ShaderStore.ShadersStore[name$r] = shader$q; +} +/** @internal */ +const iblScaledLuminancePixelShader = { name: name$r, shader: shader$q }; + +const iblScaledLuminance_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + iblScaledLuminancePixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$q = "iblVoxelGrid2dArrayDebugPixelShader"; +const shader$p = `precision highp sampler2DArray;varying vec2 vUV;uniform sampler2DArray voxelTexture;uniform sampler2D textureSampler;uniform int slice;void main(void) {ivec3 size=textureSize(voxelTexture,0);float dimension=sqrt(float(size.z));vec2 samplePos=fract(vUV.xy*vec2(dimension));int sampleIndex=int(floor(vUV.x*float(dimension))+floor(vUV.y*float(dimension))*dimension);glFragColor.rgb=texture(voxelTexture,vec3(samplePos.xy,sampleIndex)).rrr;glFragColor.a=1.0;glFragColor.rgb+=texture(textureSampler,vUV.xy).rgb;}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$q]) { + ShaderStore.ShadersStore[name$q] = shader$p; +} + +// Do not edit. +const name$p = "iblVoxelGrid2dArrayDebugPixelShader"; +const shader$o = `varying vUV: vec2f;var voxelTextureSampler: sampler;var voxelTexture: texture_3d;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform slice: i32;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var size: vec3u=textureDimensions(voxelTexture,0);var dimension: f32=sqrt( f32(size.z));var samplePos: vec2f=fract(input.vUV.xy* vec2f(dimension));var sampleIndex: u32= u32(floor(input.vUV.x* f32(dimension))+floor(input.vUV.y* f32(dimension))*dimension);var color=textureSample(voxelTexture,voxelTextureSampler, vec3f(samplePos.xy,sampleIndex)).rrr;color+=textureSample(textureSampler,textureSamplerSampler,input.vUV.xy).rgb;fragmentOutputs.color=vec4f(color,1.0);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$p]) { + ShaderStore.ShadersStoreWGSL[name$p] = shader$o; +} + +// Do not edit. +const name$o = "iblVoxelGridPixelShader"; +const shader$n = `precision highp float;layout(location=0) out highp float glFragData[MAX_DRAW_BUFFERS];varying vec3 vNormalizedPosition;uniform float nearPlane;uniform float farPlane;uniform float stepSize;void main(void) {vec3 normPos=vNormalizedPosition.xyz;if (normPos.zfarPlane) {discard;} +glFragData[0]=normPos.z=nearPlane+stepSize && normPos.z=nearPlane+2.0*stepSize && normPos.z=nearPlane+3.0*stepSize && normPos.z4 +glFragData[4]=normPos.z>=nearPlane+4.0*stepSize && normPos.z=nearPlane+5.0*stepSize && normPos.z=nearPlane+6.0*stepSize && normPos.z=nearPlane+7.0*stepSize && normPos.zFragmentOutputs {var normPos: vec3f=input.vNormalizedPosition.xyz;if (normPos.zuniforms.farPlane) {discard;} +fragmentOutputs.fragData0=select(vec4f(0.0),vec4f(1.0),normPos.z=uniforms.nearPlane+uniforms.stepSize && normPos.z=uniforms.nearPlane+2.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+3.0*uniforms.stepSize && normPos.z4 +fragmentOutputs.fragData4=select(vec4f(0.0),vec4f(1.0),normPos.z>=uniforms.nearPlane+4.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+5.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+6.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+7.0*uniforms.stepSize && normPos.zFragmentInputs {vertexOutputs.position=uniforms.viewMatrix*uniforms.invWorldScale*uniforms.world* vec4f(input.position,1.);vertexOutputs.vNormalizedPosition=vertexOutputs.position.xyz*0.5+0.5; +#ifdef IS_NDC_HALF_ZRANGE +vertexOutputs.position=vec4f(vertexOutputs.position.x,vertexOutputs.position.y,vertexOutputs.position.z*0.5+0.5,vertexOutputs.position.w); +#endif +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$l]) { + ShaderStore.ShadersStoreWGSL[name$l] = shader$k; +} + +// Do not edit. +const name$k = "iblVoxelGrid3dDebugPixelShader"; +const shader$j = `precision highp sampler3D;varying vec2 vUV;uniform sampler3D voxelTexture;uniform sampler2D voxelSlabTexture;uniform sampler2D textureSampler;uniform vec4 sizeParams; +#define offsetX sizeParams.x +#define offsetY sizeParams.y +#define widthScale sizeParams.z +#define heightScale sizeParams.w +uniform float mipNumber;void main(void) {vec2 uv = +vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 background=texture2D(textureSampler,vUV);vec4 voxelSlab=texture2D(voxelSlabTexture,vUV);ivec3 size=textureSize(voxelTexture,int(mipNumber));float dimension=ceil(sqrt(float(size.z)));vec2 samplePos=fract(uv.xy*vec2(dimension));int sampleIndex=int(floor(uv.x*float(dimension)) + +floor(uv.y*float(dimension))*dimension);float mip_separator=0.0;if (samplePos.x<0.01 || samplePos.y<0.01) {mip_separator=1.0;} +bool outBounds=sampleIndex>size.z-1 ? true : false;sampleIndex=clamp(sampleIndex,0,size.z-1);ivec2 samplePosInt=ivec2(samplePos.xy*vec2(size.xy));vec3 voxel=texelFetch(voxelTexture, +ivec3(samplePosInt.x,samplePosInt.y,sampleIndex), +int(mipNumber)) +.rgb;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=background;} else {if (outBounds) {voxel=vec3(0.15,0.0,0.0);} else {if (voxel.r>0.001) {voxel.g=1.0;} +voxel.r+=mip_separator;} +glFragColor.rgb=mix(background.rgb,voxelSlab.rgb,voxelSlab.a)+voxel;glFragColor.a=1.0;}}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$k]) { + ShaderStore.ShadersStore[name$k] = shader$j; +} + +// Do not edit. +const name$j = "iblVoxelGrid3dDebugPixelShader"; +const shader$i = `varying vUV: vec2f;var voxelTextureSampler: sampler;var voxelTexture: texture_3d;var voxelSlabTextureSampler: sampler;var voxelSlabTexture: texture_2d;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform sizeParams: vec4f; +#define offsetX uniforms.sizeParams.x +#define offsetY uniforms.sizeParams.y +#define widthScale uniforms.sizeParams.z +#define heightScale uniforms.sizeParams.w +uniform mipNumber: f32;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f = +vec2f((offsetX+input.vUV.x)*widthScale,(offsetY+input.vUV.y)*heightScale);var background: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var voxelSlab: vec4f=textureSample(voxelSlabTexture,voxelSlabTextureSampler,input.vUV);var size: vec3u=textureDimensions(voxelTexture, i32(uniforms.mipNumber));var dimension: f32=ceil(sqrt( f32(size.z)));var samplePos: vec2f=fract(uv.xy* vec2f(dimension));var sampleIndex: u32= u32(floor(uv.x* f32(dimension)) + +floor(uv.y* f32(dimension))*dimension);var mip_separator: f32=0.0;if (samplePos.x<0.01 || samplePos.y<0.01) {mip_separator=1.0;} +var outBounds: bool=select(false,true,sampleIndex>size.z-1);sampleIndex=clamp(sampleIndex,0,size.z-1);var samplePosInt: vec2i= vec2i(samplePos.xy* vec2f(size.xy));var voxel: vec3f=textureLoad(voxelTexture, +vec3i(i32(samplePosInt.x),i32(samplePosInt.y),i32(sampleIndex)), +i32(uniforms.mipNumber)).rgb;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=background;} else {if (outBounds) {voxel= vec3f(0.15,0.0,0.0);} else {if (voxel.r>0.001) {voxel.g=1.0;} +voxel.r+=mip_separator;} +fragmentOutputs.color=vec4f(mix(background.rgb,voxelSlab.rgb,voxelSlab.a)+voxel,1.0);}}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$j]) { + ShaderStore.ShadersStoreWGSL[name$j] = shader$i; +} + +// Do not edit. +const name$i = "iblVoxelSlabDebugVertexShader"; +const shader$h = `attribute vec3 position;varying vec3 vNormalizedPosition;uniform mat4 world;uniform mat4 invWorldScale;uniform mat4 cameraViewMatrix;uniform mat4 projection;uniform mat4 viewMatrix;void main(void) {vec4 worldPosition=(world*vec4(position,1.));gl_Position=projection*cameraViewMatrix*worldPosition;vNormalizedPosition=(viewMatrix*invWorldScale*worldPosition).rgb;vNormalizedPosition.xyz=vNormalizedPosition.xyz*vec3(0.5)+vec3(0.5);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$i]) { + ShaderStore.ShadersStore[name$i] = shader$h; +} + +// Do not edit. +const name$h = "iblVoxelSlabDebugPixelShader"; +const shader$g = `precision highp float;varying vec3 vNormalizedPosition;uniform float nearPlane;uniform float farPlane;uniform float stepSize;void main(void) {vec3 normPos=vNormalizedPosition.xyz;float chunkSize=stepSize*float(MAX_DRAW_BUFFERS);float numChunks=1.0/chunkSize;float positionInChunk=fract(normPos.z/chunkSize);float slab=floor(positionInChunk*float(MAX_DRAW_BUFFERS)) / +float(MAX_DRAW_BUFFERS);if (normPos.x<0.0 || normPos.y<0.0 || normPos.z<0.0 || +normPos.x>1.0 || normPos.y>1.0 || normPos.z>1.0) {gl_FragColor=vec4(0.0,0.0,0.0,0.0);} else {gl_FragColor=vec4(slab,0.0,0.0,0.75);}}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$h]) { + ShaderStore.ShadersStore[name$h] = shader$g; +} + +// Do not edit. +const name$g = "iblVoxelSlabDebugVertexShader"; +const shader$f = `attribute position: vec3f;varying vNormalizedPosition: vec3f;uniform world: mat4x4f;uniform invWorldScale: mat4x4f;uniform cameraViewMatrix: mat4x4f;uniform projection: mat4x4f;uniform viewMatrix: mat4x4f;@vertex +fn main(input : VertexInputs)->FragmentInputs {var worldPosition: vec4f=(uniforms.world* vec4f(input.position,1.));vertexOutputs.position=uniforms.projection*uniforms.cameraViewMatrix*worldPosition;vertexOutputs.vNormalizedPosition=(uniforms.viewMatrix*uniforms.invWorldScale*worldPosition).rgb;vertexOutputs.vNormalizedPosition=vertexOutputs.vNormalizedPosition* vec3f(0.5)+ vec3f(0.5);}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$g]) { + ShaderStore.ShadersStoreWGSL[name$g] = shader$f; +} + +// Do not edit. +const name$f = "iblVoxelSlabDebugPixelShader"; +const shader$e = `varying vNormalizedPosition: vec3f;uniform nearPlane: f32;uniform farPlane: f32;uniform stepSize: f32;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var normPos: vec3f=input.vNormalizedPosition.xyz;var chunkSize: f32=uniforms.stepSize* f32(MAX_DRAW_BUFFERS);var numChunks: f32=1.0/chunkSize;var positionInChunk: f32=fract(normPos.z/chunkSize);var slab: f32=floor(positionInChunk* f32(MAX_DRAW_BUFFERS)) / +f32(MAX_DRAW_BUFFERS);if (normPos.x<0.0 || normPos.y<0.0 || normPos.z<0.0 || +normPos.x>1.0 || normPos.y>1.0 || normPos.z>1.0) {fragmentOutputs.color= vec4f(0.0,0.0,0.0,0.0);} else {fragmentOutputs.color= vec4f(slab,0.0,0.0,0.75);}}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$f]) { + ShaderStore.ShadersStoreWGSL[name$f] = shader$e; +} + +// Do not edit. +const name$e = "oitBackBlendPixelShader"; +const shader$d = `precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { +discard;}}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$e]) { + ShaderStore.ShadersStore[name$e] = shader$d; +} + +const oitBackBlend_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$d = "oitFinalPixelShader"; +const shader$c = `precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( +frontColor.rgb+alphaMultiplier*backColor.rgb, +frontColor.a+backColor.a +);}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$d]) { + ShaderStore.ShadersStore[name$d] = shader$c; +} + +const oitFinal_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$c = "oitBackBlendPixelShader"; +const shader$b = `var uBackColor: texture_2d;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureLoad(uBackColor,vec2i(fragmentInputs.position.xy),0);if (fragmentOutputs.color.a==0.0) {discard;}} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$c]) { + ShaderStore.ShadersStoreWGSL[name$c] = shader$b; +} + +const oitBackBlend_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$b = "oitFinalPixelShader"; +const shader$a = `var uFrontColor: texture_2d;var uBackColor: texture_2d;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {var fragCoord: vec2i=vec2i(fragmentInputs.position.xy);var frontColor: vec4f=textureLoad(uFrontColor,fragCoord,0);var backColor: vec4f=textureLoad(uBackColor,fragCoord,0);var alphaMultiplier: f32=1.0-frontColor.a;fragmentOutputs.color=vec4f( +frontColor.rgb+alphaMultiplier*backColor.rgb, +frontColor.a+backColor.a +);} +`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$b]) { + ShaderStore.ShadersStoreWGSL[name$b] = shader$a; +} + +const oitFinal_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$a = "spriteMapPixelShader"; +const shader$9 = `#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul; +#include +#include +float mt;const float fdStep=1.0*0.25;const float aFrameSteps=MAX_ANIMATION_FRAMES==0.0 ? 0.0 : 1.0/MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID) {float fX=frameID/spriteCount;return mat4( +TEXTUREFUNC(frameMap,vec2(fX,0.0),0.0), +TEXTUREFUNC(frameMap,vec2(fX,fdStep*1.0),0.0), +TEXTUREFUNC(frameMap,vec2(fX,fdStep*2.0),0.0), +vec4(0.0) +);} +void main() {vec4 color=vec4(0.0);vec2 tileUV=fract(tUV);vec2 tileID=floor(tUV);vec2 sheetUnits=1.0/spriteMapSize;float spriteUnits=1.0/spriteCount;vec2 stageUnits=1.0/stageSize;for(int i=0; i0.0) {mt=mod(time*animationData.z,1.0);for(float f=0.0; fmt) {frameID=animationData.x;break;} +animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.0);}} +mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw; +#ifdef FR_CW +if (frameData[2].z==1.0) {tileUV.xy=tileUV.yx;} else {tileUV.xy=fract(tUV).xy;} +#ifdef FLIPU +tileUV.y=1.0-tileUV.y; +#endif +#else +if (frameData[2].z==1.0) { +#ifdef FLIPU +tileUV.y=1.0-tileUV.y; +#endif +tileUV.xy=tileUV.yx;} else {tileUV.xy=fract(tUV).xy; +#ifdef FLIPU +tileUV.y=1.0-tileUV.y; +#endif +} +#endif +vec4 nc=TEXTUREFUNC(spriteSheet,tileUV*frameSize+offset,0.0);if (i==0) {color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} +color.xyz*=colorMul; +#include +#include +gl_FragColor=color;}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$a]) { + ShaderStore.ShadersStore[name$a] = shader$9; +} + +// Do not edit. +const name$9 = "spriteMapVertexShader"; +const shader$8 = `precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform mat4 world;uniform mat4 view;uniform mat4 projection;uniform vec2 stageSize;uniform float stageScale; +#include +#include +void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; +vec3 viewPos=(view*world*p).xyz; +gl_Position=projection*vec4(viewPos,1.0); +#ifdef FOG +vFogDistance=viewPos; +#endif +#include +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$9]) { + ShaderStore.ShadersStore[name$9] = shader$8; +} + +var SpriteMapFrameRotationDirection; +(function (SpriteMapFrameRotationDirection) { + SpriteMapFrameRotationDirection[SpriteMapFrameRotationDirection["CCW"] = 0] = "CCW"; + SpriteMapFrameRotationDirection[SpriteMapFrameRotationDirection["CW"] = 1] = "CW"; +})(SpriteMapFrameRotationDirection || (SpriteMapFrameRotationDirection = {})); + +// Do not edit. +const name$8 = "imageProcessingCompatibility"; +const shader$7 = `#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStore[name$8]) { + ShaderStore.IncludesShadersStore[name$8] = shader$7; +} + +// Do not edit. +const name$7 = "spritesPixelShader"; +const shader$6 = `#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +#ifdef PIXEL_PERFECT +vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} +#endif +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#ifdef PIXEL_PERFECT +vec2 uv=uvPixelPerfect(vUV); +#else +vec2 uv=vUV; +#endif +vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) +{if (color.a<0.95) +discard;} +color*=vColor; +#include +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$7]) { + ShaderStore.ShadersStore[name$7] = shader$6; +} +/** @internal */ +const spritesPixelShader = { name: name$7, shader: shader$6 }; + +const sprites_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + spritesPixelShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$6 = "spritesVertexShader"; +const shader$5 = `attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; +#include +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; +vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); +vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; +#ifdef FOG +vFogDistance=viewPos; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$6]) { + ShaderStore.ShadersStore[name$6] = shader$5; +} +/** @internal */ +const spritesVertexShader = { name: name$6, shader: shader$5 }; + +const sprites_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + spritesVertexShader +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$5 = "imageProcessingCompatibility"; +const shader$4 = `#ifdef IMAGEPROCESSINGPOSTPROCESS +fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb, vec3f(2.2)),fragmentOutputs.color.a); +#endif +`; +// Sideeffect +if (!ShaderStore.IncludesShadersStoreWGSL[name$5]) { + ShaderStore.IncludesShadersStoreWGSL[name$5] = shader$4; +} + +// Do not edit. +const name$4 = "spritesPixelShader"; +const shader$3 = `uniform alphaTest: i32;varying vColor: vec4f;varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +#ifdef PIXEL_PERFECT +fn uvPixelPerfect(uv: vec2f)->vec2f {var res: vec2f= vec2f(textureDimensions(diffuseSampler,0));var uvTemp=uv*res;var seam: vec2f=floor(uvTemp+0.5);uvTemp=seam+clamp((uvTemp-seam)/fwidth(uvTemp),vec2f(-0.5),vec2f(0.5));return uvTemp/res;} +#endif +@fragment +fn main(input: FragmentInputs)->FragmentOutputs { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#ifdef PIXEL_PERFECT +var uv: vec2f=uvPixelPerfect(input.vUV); +#else +var uv: vec2f=input.vUV; +#endif +var color: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,uv);var fAlphaTest: f32= f32(uniforms.alphaTest);if (fAlphaTest != 0.) +{if (color.a<0.95) {discard;}} +color*=input.vColor; +#include +#include +fragmentOutputs.color=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$4]) { + ShaderStore.ShadersStoreWGSL[name$4] = shader$3; +} +/** @internal */ +const spritesPixelShaderWGSL = { name: name$4, shader: shader$3 }; + +const sprites_fragment = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + spritesPixelShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +// Do not edit. +const name$3 = "spritesVertexShader"; +const shader$2 = `attribute position: vec4f;attribute options: vec2f;attribute offsets: vec2f;attribute inverts: vec2f;attribute cellInfo: vec4f;attribute color: vec4f;uniform view: mat4x4f;uniform projection: mat4x4f;varying vUV: vec2f;varying vColor: vec4f; +#include +#include +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +var viewPos: vec3f=(uniforms.view* vec4f(input.position.xyz,1.0)).xyz; +var cornerPos: vec2f;var angle: f32=input.position.w;var size: vec2f= vec2f(input.options.x,input.options.y);var offset: vec2f=input.offsets.xy;cornerPos= vec2f(offset.x-0.5,offset.y -0.5)*size;var rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0); +vertexOutputs.vColor=input.color;var uvOffset: vec2f= vec2f(abs(offset.x-input.inverts.x),abs(1.0-offset.y-input.inverts.y));var uvPlace: vec2f=input.cellInfo.xy;var uvSize: vec2f=input.cellInfo.zw;vertexOutputs.vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vertexOutputs.vUV.y=uvPlace.y+uvSize.y*uvOffset.y; +#ifdef FOG +vertexOutputs.vFogDistance=viewPos; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStoreWGSL[name$3]) { + ShaderStore.ShadersStoreWGSL[name$3] = shader$2; +} +/** @internal */ +const spritesVertexShaderWGSL = { name: name$3, shader: shader$2 }; + +const sprites_vertex = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ + __proto__: null, + spritesVertexShaderWGSL +}, Symbol.toStringTag, { value: 'Module' })); + +/** + * States of the webXR experience + */ +var WebXRState; +(function (WebXRState) { + /** + * Transitioning to being in XR mode + */ + WebXRState[WebXRState["ENTERING_XR"] = 0] = "ENTERING_XR"; + /** + * Transitioning to non XR mode + */ + WebXRState[WebXRState["EXITING_XR"] = 1] = "EXITING_XR"; + /** + * In XR mode and presenting + */ + WebXRState[WebXRState["IN_XR"] = 2] = "IN_XR"; + /** + * Not entered XR mode + */ + WebXRState[WebXRState["NOT_IN_XR"] = 3] = "NOT_IN_XR"; +})(WebXRState || (WebXRState = {})); +/** + * The state of the XR camera's tracking + */ +var WebXRTrackingState; +(function (WebXRTrackingState) { + /** + * No transformation received, device is not being tracked + */ + WebXRTrackingState[WebXRTrackingState["NOT_TRACKING"] = 0] = "NOT_TRACKING"; + /** + * Tracking lost - using emulated position + */ + WebXRTrackingState[WebXRTrackingState["TRACKING_LOST"] = 1] = "TRACKING_LOST"; + /** + * Transformation tracking works normally + */ + WebXRTrackingState[WebXRTrackingState["TRACKING"] = 2] = "TRACKING"; +})(WebXRTrackingState || (WebXRTrackingState = {})); + +/** + * The currently-working hit-test module. + * Hit test (or Ray-casting) is used to interact with the real world. + * For further information read here - https://github.com/immersive-web/hit-test + */ +class WebXRHitTestLegacy extends WebXRAbstractFeature { + /** + * Creates a new instance of the (legacy version) hit test feature + * @param _xrSessionManager an instance of WebXRSessionManager + * @param options options to use when constructing this feature + */ + constructor(_xrSessionManager, + /** + * [Empty Object] options to use when constructing this feature + */ + options = {}) { + super(_xrSessionManager); + this.options = options; + // in XR space z-forward is negative + this._direction = new Vector3(0, 0, -1); + this._mat = new Matrix(); + this._onSelectEnabled = false; + this._origin = new Vector3(0, 0, 0); + /** + * Populated with the last native XR Hit Results + */ + this.lastNativeXRHitResults = []; + /** + * Triggered when new babylon (transformed) hit test results are available + */ + this.onHitTestResultObservable = new Observable(); + this._onHitTestResults = (xrResults) => { + const mats = xrResults.map((result) => { + const mat = Matrix.FromArray(result.hitMatrix); + if (!this._xrSessionManager.scene.useRightHandedSystem) { + mat.toggleModelMatrixHandInPlace(); + } + // if (this.options.coordinatesSpace === Space.WORLD) { + if (this.options.worldParentNode) { + mat.multiplyToRef(this.options.worldParentNode.getWorldMatrix(), mat); + } + return { + xrHitResult: result, + transformationMatrix: mat, + }; + }); + this.lastNativeXRHitResults = xrResults; + this.onHitTestResultObservable.notifyObservers(mats); + }; + // can be done using pointerdown event, and xrSessionManager.currentFrame + this._onSelect = (event) => { + if (!this._onSelectEnabled) { + return; + } + WebXRHitTestLegacy.XRHitTestWithSelectEvent(event, this._xrSessionManager.referenceSpace); + }; + this.xrNativeFeatureName = "hit-test"; + Tools.Warn("A newer version of this plugin is available"); + } + /** + * execute a hit test with an XR Ray + * + * @param xrSession a native xrSession that will execute this hit test + * @param xrRay the ray (position and direction) to use for ray-casting + * @param referenceSpace native XR reference space to use for the hit-test + * @param filter filter function that will filter the results + * @returns a promise that resolves with an array of native XR hit result in xr coordinates system + */ + static XRHitTestWithRay(xrSession, xrRay, referenceSpace, filter) { + return xrSession.requestHitTest(xrRay, referenceSpace).then((results) => { + const filterFunction = filter || ((result) => !!result.hitMatrix); + return results.filter(filterFunction); + }); + } + /** + * Execute a hit test on the current running session using a select event returned from a transient input (such as touch) + * @param event the (select) event to use to select with + * @param referenceSpace the reference space to use for this hit test + * @returns a promise that resolves with an array of native XR hit result in xr coordinates system + */ + static XRHitTestWithSelectEvent(event, referenceSpace) { + const targetRayPose = event.frame.getPose(event.inputSource.targetRaySpace, referenceSpace); + if (!targetRayPose) { + return Promise.resolve([]); + } + const targetRay = new XRRay(targetRayPose.transform); + return this.XRHitTestWithRay(event.frame.session, targetRay, referenceSpace); + } + /** + * attach this feature + * Will usually be called by the features manager + * + * @returns true if successful. + */ + attach() { + if (!super.attach()) { + return false; + } + if (this.options.testOnPointerDownOnly) { + this._xrSessionManager.session.addEventListener("select", this._onSelect, false); + } + return true; + } + /** + * detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + if (!super.detach()) { + return false; + } + // disable select + this._onSelectEnabled = false; + this._xrSessionManager.session.removeEventListener("select", this._onSelect); + return true; + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + super.dispose(); + this.onHitTestResultObservable.clear(); + } + _onXRFrame(frame) { + // make sure we do nothing if (async) not attached + if (!this.attached || this.options.testOnPointerDownOnly) { + return; + } + const pose = frame.getViewerPose(this._xrSessionManager.referenceSpace); + if (!pose) { + return; + } + Matrix.FromArrayToRef(pose.transform.matrix, 0, this._mat); + Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, this._mat, this._origin); + Vector3.TransformCoordinatesFromFloatsToRef(0, 0, -1, this._mat, this._direction); + this._direction.subtractInPlace(this._origin); + this._direction.normalize(); + const ray = new XRRay({ x: this._origin.x, y: this._origin.y, z: this._origin.z, w: 0 }, { x: this._direction.x, y: this._direction.y, z: this._direction.z, w: 0 }); + WebXRHitTestLegacy.XRHitTestWithRay(this._xrSessionManager.session, ray, this._xrSessionManager.referenceSpace).then(this._onHitTestResults); + } +} +/** + * The module's name + */ +WebXRHitTestLegacy.Name = WebXRFeatureName.HIT_TEST; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRHitTestLegacy.Version = 1; +//register the plugin versions +WebXRFeaturesManager.AddWebXRFeature(WebXRHitTestLegacy.Name, (xrSessionManager, options) => { + return () => new WebXRHitTestLegacy(xrSessionManager, options); +}, WebXRHitTestLegacy.Version, false); + +let anchorIdProvider = 0; +/** + * An implementation of the anchor system for WebXR. + * For further information see https://github.com/immersive-web/anchors/ + */ +class WebXRAnchorSystem extends WebXRAbstractFeature { + /** + * Set the reference space to use for anchor creation, when not using a hit test. + * Will default to the session's reference space if not defined + */ + set referenceSpaceForFrameAnchors(referenceSpace) { + this._referenceSpaceForFrameAnchors = referenceSpace; + } + /** + * constructs a new anchor system + * @param _xrSessionManager an instance of WebXRSessionManager + * @param _options configuration object for this feature + */ + constructor(_xrSessionManager, _options = {}) { + super(_xrSessionManager); + this._options = _options; + this._lastFrameDetected = new Set(); + this._trackedAnchors = []; + this._futureAnchors = []; + /** + * Observers registered here will be executed when a new anchor was added to the session + */ + this.onAnchorAddedObservable = new Observable(); + /** + * Observers registered here will be executed when an anchor was removed from the session + */ + this.onAnchorRemovedObservable = new Observable(); + /** + * Observers registered here will be executed when an existing anchor updates + * This can execute N times every frame + */ + this.onAnchorUpdatedObservable = new Observable(); + this._tmpVector = new Vector3(); + this._tmpQuaternion = new Quaternion(); + this.xrNativeFeatureName = "anchors"; + if (this._options.clearAnchorsOnSessionInit) { + this._xrSessionManager.onXRSessionInit.add(() => { + this._trackedAnchors.length = 0; + this._futureAnchors.length = 0; + this._lastFrameDetected.clear(); + }); + } + } + _populateTmpTransformation(position, rotationQuaternion) { + this._tmpVector.copyFrom(position); + this._tmpQuaternion.copyFrom(rotationQuaternion); + if (!this._xrSessionManager.scene.useRightHandedSystem) { + this._tmpVector.z *= -1; + this._tmpQuaternion.z *= -1; + this._tmpQuaternion.w *= -1; + } + return { + position: this._tmpVector, + rotationQuaternion: this._tmpQuaternion, + }; + } + /** + * Create a new anchor point using a hit test result at a specific point in the scene + * An anchor is tracked only after it is added to the trackerAnchors in xrFrame. The promise returned here does not yet guaranty that. + * Use onAnchorAddedObservable to get newly added anchors if you require tracking guaranty. + * + * @param hitTestResult The hit test result to use for this anchor creation + * @param position an optional position offset for this anchor + * @param rotationQuaternion an optional rotation offset for this anchor + * @returns A promise that fulfills when babylon has created the corresponding WebXRAnchor object and tracking has begun + */ + async addAnchorPointUsingHitTestResultAsync(hitTestResult, position = new Vector3(), rotationQuaternion = new Quaternion()) { + // convert to XR space (right handed) if needed + this._populateTmpTransformation(position, rotationQuaternion); + // the matrix that we'll use + const m = new XRRigidTransform({ x: this._tmpVector.x, y: this._tmpVector.y, z: this._tmpVector.z }, { x: this._tmpQuaternion.x, y: this._tmpQuaternion.y, z: this._tmpQuaternion.z, w: this._tmpQuaternion.w }); + if (!hitTestResult.xrHitResult.createAnchor) { + this.detach(); + throw new Error("Anchors not enabled in this environment/browser"); + } + else { + try { + const nativeAnchor = await hitTestResult.xrHitResult.createAnchor(m); + return new Promise((resolve, reject) => { + this._futureAnchors.push({ + nativeAnchor, + resolved: false, + submitted: true, + xrTransformation: m, + resolve, + reject, + }); + }); + } + catch (error) { + throw new Error(error); + } + } + } + /** + * Add a new anchor at a specific position and rotation + * This function will add a new anchor per default in the next available frame. Unless forced, the createAnchor function + * will be called in the next xrFrame loop to make sure that the anchor can be created correctly. + * An anchor is tracked only after it is added to the trackerAnchors in xrFrame. The promise returned here does not yet guaranty that. + * Use onAnchorAddedObservable to get newly added anchors if you require tracking guaranty. + * + * @param position the position in which to add an anchor + * @param rotationQuaternion an optional rotation for the anchor transformation + * @param forceCreateInCurrentFrame force the creation of this anchor in the current frame. Must be called inside xrFrame loop! + * @returns A promise that fulfills when babylon has created the corresponding WebXRAnchor object and tracking has begun + */ + async addAnchorAtPositionAndRotationAsync(position, rotationQuaternion = new Quaternion(), forceCreateInCurrentFrame = false) { + // convert to XR space (right handed) if needed + this._populateTmpTransformation(position, rotationQuaternion); + // the matrix that we'll use + const xrTransformation = new XRRigidTransform({ x: this._tmpVector.x, y: this._tmpVector.y, z: this._tmpVector.z }, { x: this._tmpQuaternion.x, y: this._tmpQuaternion.y, z: this._tmpQuaternion.z, w: this._tmpQuaternion.w }); + const xrAnchor = forceCreateInCurrentFrame && this.attached && this._xrSessionManager.currentFrame + ? await this._createAnchorAtTransformation(xrTransformation, this._xrSessionManager.currentFrame) + : undefined; + // add the transformation to the future anchors list + return new Promise((resolve, reject) => { + this._futureAnchors.push({ + nativeAnchor: xrAnchor, + resolved: false, + submitted: false, + xrTransformation, + resolve, + reject, + }); + }); + } + /** + * Get the list of anchors currently being tracked by the system + */ + get anchors() { + return this._trackedAnchors; + } + /** + * detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + if (!super.detach()) { + return false; + } + if (!this._options.doNotRemoveAnchorsOnSessionEnded) { + while (this._trackedAnchors.length) { + const toRemove = this._trackedAnchors.pop(); + if (toRemove && !toRemove._removed) { + // as the xr frame loop is removed, we need to notify manually + this.onAnchorRemovedObservable.notifyObservers(toRemove); + toRemove._removed = true; + // no need to call the remove fn as the anchor is already removed from the session + } + } + } + return true; + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + this._futureAnchors.length = 0; + super.dispose(); + this.onAnchorAddedObservable.clear(); + this.onAnchorRemovedObservable.clear(); + this.onAnchorUpdatedObservable.clear(); + } + _onXRFrame(frame) { + if (!this.attached || !frame) { + return; + } + const trackedAnchors = frame.trackedAnchors; + if (trackedAnchors) { + const toRemove = this._trackedAnchors + .filter((anchor) => anchor._removed) + .map((anchor) => { + return this._trackedAnchors.indexOf(anchor); + }); + let idxTracker = 0; + toRemove.forEach((index) => { + const anchor = this._trackedAnchors.splice(index - idxTracker, 1)[0]; + anchor.xrAnchor.delete(); + this.onAnchorRemovedObservable.notifyObservers(anchor); + idxTracker++; + }); + // now check for new ones + trackedAnchors.forEach((xrAnchor) => { + if (!this._lastFrameDetected.has(xrAnchor)) { + const newAnchor = { + id: anchorIdProvider++, + xrAnchor: xrAnchor, + remove: () => { + newAnchor._removed = true; + }, + }; + const anchor = this._updateAnchorWithXRFrame(xrAnchor, newAnchor, frame); + this._trackedAnchors.push(anchor); + this.onAnchorAddedObservable.notifyObservers(anchor); + // search for the future anchor promise that matches this + const results = this._futureAnchors.filter((futureAnchor) => futureAnchor.nativeAnchor === xrAnchor); + const result = results[0]; + if (result) { + result.resolve(anchor); + result.resolved = true; + } + } + else { + const index = this._findIndexInAnchorArray(xrAnchor); + const anchor = this._trackedAnchors[index]; + try { + // anchors update every frame + this._updateAnchorWithXRFrame(xrAnchor, anchor, frame); + if (anchor.attachedNode) { + anchor.attachedNode.rotationQuaternion = anchor.attachedNode.rotationQuaternion || new Quaternion(); + anchor.transformationMatrix.decompose(anchor.attachedNode.scaling, anchor.attachedNode.rotationQuaternion, anchor.attachedNode.position); + } + this.onAnchorUpdatedObservable.notifyObservers(anchor); + } + catch (e) { + Tools.Warn(`Anchor could not be updated`); + } + } + }); + this._lastFrameDetected = trackedAnchors; + } + // process future anchors + this._futureAnchors.forEach((futureAnchor) => { + if (!futureAnchor.resolved && !futureAnchor.submitted) { + this._createAnchorAtTransformation(futureAnchor.xrTransformation, frame).then((nativeAnchor) => { + futureAnchor.nativeAnchor = nativeAnchor; + }, (error) => { + futureAnchor.resolved = true; + futureAnchor.reject(error); + }); + futureAnchor.submitted = true; + } + }); + } + /** + * avoiding using Array.find for global support. + * @param xrAnchor the plane to find in the array + * @returns the index of the anchor in the array or -1 if not found + */ + _findIndexInAnchorArray(xrAnchor) { + for (let i = 0; i < this._trackedAnchors.length; ++i) { + if (this._trackedAnchors[i].xrAnchor === xrAnchor) { + return i; + } + } + return -1; + } + _updateAnchorWithXRFrame(xrAnchor, anchor, xrFrame) { + // matrix + const pose = xrFrame.getPose(xrAnchor.anchorSpace, this._xrSessionManager.referenceSpace); + if (pose) { + const mat = anchor.transformationMatrix || new Matrix(); + Matrix.FromArrayToRef(pose.transform.matrix, 0, mat); + if (!this._xrSessionManager.scene.useRightHandedSystem) { + mat.toggleModelMatrixHandInPlace(); + } + anchor.transformationMatrix = mat; + if (!this._options.worldParentNode) ; + else { + mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat); + } + } + return anchor; + } + async _createAnchorAtTransformation(xrTransformation, xrFrame) { + if (xrFrame.createAnchor) { + try { + return xrFrame.createAnchor(xrTransformation, this._referenceSpaceForFrameAnchors ?? this._xrSessionManager.referenceSpace); + } + catch (error) { + throw new Error(error); + } + } + else { + this.detach(); + throw new Error("Anchors are not enabled in your browser"); + } + } +} +/** + * The module's name + */ +WebXRAnchorSystem.Name = WebXRFeatureName.ANCHOR_SYSTEM; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRAnchorSystem.Version = 1; +// register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRAnchorSystem.Name, (xrSessionManager, options) => { + return () => new WebXRAnchorSystem(xrSessionManager, options); +}, WebXRAnchorSystem.Version); + +let planeIdProvider = 0; +/** + * The plane detector is used to detect planes in the real world when in AR + * For more information see https://github.com/immersive-web/real-world-geometry/ + */ +class WebXRPlaneDetector extends WebXRAbstractFeature { + /** + * construct a new Plane Detector + * @param _xrSessionManager an instance of xr Session manager + * @param _options configuration to use when constructing this feature + */ + constructor(_xrSessionManager, _options = {}) { + super(_xrSessionManager); + this._options = _options; + this._detectedPlanes = []; + this._enabled = false; + this._lastFrameDetected = new Set(); + /** + * Observers registered here will be executed when a new plane was added to the session + */ + this.onPlaneAddedObservable = new Observable(); + /** + * Observers registered here will be executed when a plane is no longer detected in the session + */ + this.onPlaneRemovedObservable = new Observable(); + /** + * Observers registered here will be executed when an existing plane updates (for example - expanded) + * This can execute N times every frame + */ + this.onPlaneUpdatedObservable = new Observable(); + this.xrNativeFeatureName = "plane-detection"; + if (this._xrSessionManager.session) { + this._init(); + } + else { + this._xrSessionManager.onXRSessionInit.addOnce(() => { + this._init(); + }); + } + } + /** + * detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + if (!super.detach()) { + return false; + } + if (!this._options.doNotRemovePlanesOnSessionEnded) { + while (this._detectedPlanes.length) { + const toRemove = this._detectedPlanes.pop(); + if (toRemove) { + this.onPlaneRemovedObservable.notifyObservers(toRemove); + } + } + } + return true; + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + super.dispose(); + this.onPlaneAddedObservable.clear(); + this.onPlaneRemovedObservable.clear(); + this.onPlaneUpdatedObservable.clear(); + } + /** + * Check if the needed objects are defined. + * This does not mean that the feature is enabled, but that the objects needed are well defined. + * @returns true if the initial compatibility test passed + */ + isCompatible() { + return typeof XRPlane !== "undefined"; + } + /** + * Enable room capture mode. + * When enabled and supported by the system, + * the detectedPlanes array will be populated with the detected room boundaries + * @see https://immersive-web.github.io/real-world-geometry/plane-detection.html#dom-xrsession-initiateroomcapture + * @returns true if plane detection is enabled and supported. Will reject if not supported. + */ + async initiateRoomCapture() { + if (this._xrSessionManager.session.initiateRoomCapture) { + return this._xrSessionManager.session.initiateRoomCapture(); + } + return Promise.reject("initiateRoomCapture is not supported on this session"); + } + _onXRFrame(frame) { + if (!this.attached || !this._enabled || !frame) { + return; + } + const detectedPlanes = frame.detectedPlanes || frame.worldInformation?.detectedPlanes; + if (detectedPlanes) { + // remove all planes that are not currently detected in the frame + for (let planeIdx = 0; planeIdx < this._detectedPlanes.length; planeIdx++) { + const plane = this._detectedPlanes[planeIdx]; + if (!detectedPlanes.has(plane.xrPlane)) { + this._detectedPlanes.splice(planeIdx--, 1); + this.onPlaneRemovedObservable.notifyObservers(plane); + } + } + // now check for new ones + detectedPlanes.forEach((xrPlane) => { + if (!this._lastFrameDetected.has(xrPlane)) { + const newPlane = { + id: planeIdProvider++, + xrPlane: xrPlane, + polygonDefinition: [], + }; + const plane = this._updatePlaneWithXRPlane(xrPlane, newPlane, frame); + this._detectedPlanes.push(plane); + this.onPlaneAddedObservable.notifyObservers(plane); + } + else { + // updated? + if (xrPlane.lastChangedTime === this._xrSessionManager.currentTimestamp) { + const index = this._findIndexInPlaneArray(xrPlane); + const plane = this._detectedPlanes[index]; + this._updatePlaneWithXRPlane(xrPlane, plane, frame); + this.onPlaneUpdatedObservable.notifyObservers(plane); + } + } + }); + this._lastFrameDetected = detectedPlanes; + } + } + _init() { + const internalInit = () => { + this._enabled = true; + if (this._detectedPlanes.length) { + this._detectedPlanes.length = 0; + } + }; + // Only supported by BabylonNative + if (!!this._xrSessionManager.isNative && !!this._options.preferredDetectorOptions && !!this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions) { + this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions); + } + if (!this._xrSessionManager.session.updateWorldTrackingState) { + internalInit(); + return; + } + this._xrSessionManager.session.updateWorldTrackingState({ planeDetectionState: { enabled: true } }); + internalInit(); + } + _updatePlaneWithXRPlane(xrPlane, plane, xrFrame) { + plane.polygonDefinition = xrPlane.polygon.map((xrPoint) => { + const rightHandedSystem = this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1; + return new Vector3(xrPoint.x, xrPoint.y, xrPoint.z * rightHandedSystem); + }); + // matrix + const pose = xrFrame.getPose(xrPlane.planeSpace, this._xrSessionManager.referenceSpace); + if (pose) { + const mat = plane.transformationMatrix || new Matrix(); + Matrix.FromArrayToRef(pose.transform.matrix, 0, mat); + if (!this._xrSessionManager.scene.useRightHandedSystem) { + mat.toggleModelMatrixHandInPlace(); + } + plane.transformationMatrix = mat; + if (this._options.worldParentNode) { + mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat); + } + } + return plane; + } + /** + * avoiding using Array.find for global support. + * @param xrPlane the plane to find in the array + * @returns the index of the plane in the array or -1 if not found + */ + _findIndexInPlaneArray(xrPlane) { + for (let i = 0; i < this._detectedPlanes.length; ++i) { + if (this._detectedPlanes[i].xrPlane === xrPlane) { + return i; + } + } + return -1; + } +} +/** + * The module's name + */ +WebXRPlaneDetector.Name = WebXRFeatureName.PLANE_DETECTION; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRPlaneDetector.Version = 1; +//register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRPlaneDetector.Name, (xrSessionManager, options) => { + return () => new WebXRPlaneDetector(xrSessionManager, options); +}, WebXRPlaneDetector.Version); + +/** + * A module that will automatically disable background meshes when entering AR and will enable them when leaving AR. + */ +class WebXRBackgroundRemover extends WebXRAbstractFeature { + /** + * constructs a new background remover module + * @param _xrSessionManager the session manager for this module + * @param options read-only options to be used in this module + */ + constructor(_xrSessionManager, + /** + * [Empty Object] read-only options to be used in this module + */ + options = {}) { + super(_xrSessionManager); + this.options = options; + /** + * registered observers will be triggered when the background state changes + */ + this.onBackgroundStateChangedObservable = new Observable(); + } + /** + * attach this feature + * Will usually be called by the features manager + * + * @returns true if successful. + */ + attach() { + this._setBackgroundState(false); + return super.attach(); + } + /** + * detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + this._setBackgroundState(true); + return super.detach(); + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + super.dispose(); + this.onBackgroundStateChangedObservable.clear(); + } + _onXRFrame(_xrFrame) { + // no-op + } + _setBackgroundState(newState) { + const scene = this._xrSessionManager.scene; + if (!this.options.ignoreEnvironmentHelper) { + if (this.options.environmentHelperRemovalFlags) { + if (this.options.environmentHelperRemovalFlags.skyBox) { + const backgroundSkybox = scene.getMeshByName("BackgroundSkybox"); + if (backgroundSkybox) { + backgroundSkybox.setEnabled(newState); + } + } + if (this.options.environmentHelperRemovalFlags.ground) { + const backgroundPlane = scene.getMeshByName("BackgroundPlane"); + if (backgroundPlane) { + backgroundPlane.setEnabled(newState); + } + } + } + else { + const backgroundHelper = scene.getMeshByName("BackgroundHelper"); + if (backgroundHelper) { + backgroundHelper.setEnabled(newState); + } + } + } + if (this.options.backgroundMeshes) { + this.options.backgroundMeshes.forEach((mesh) => mesh.setEnabled(newState)); + } + this.onBackgroundStateChangedObservable.notifyObservers(newState); + } +} +/** + * The module's name + */ +WebXRBackgroundRemover.Name = WebXRFeatureName.BACKGROUND_REMOVER; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRBackgroundRemover.Version = 1; +//register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRBackgroundRemover.Name, (xrSessionManager, options) => { + return () => new WebXRBackgroundRemover(xrSessionManager, options); +}, WebXRBackgroundRemover.Version, true); + +/** + * Add physics impostor to your webxr controllers, + * including naive calculation of their linear and angular velocity + */ +class WebXRControllerPhysics extends WebXRAbstractFeature { + _createPhysicsImpostor(xrController) { + const impostorType = this._options.physicsProperties.impostorType || PhysicsImpostor.SphereImpostor; + const impostorSize = this._options.physicsProperties.impostorSize || 0.1; + const impostorMesh = CreateSphere("impostor-mesh-" + xrController.uniqueId, { + diameterX: typeof impostorSize === "number" ? impostorSize : impostorSize.width, + diameterY: typeof impostorSize === "number" ? impostorSize : impostorSize.height, + diameterZ: typeof impostorSize === "number" ? impostorSize : impostorSize.depth, + }); + impostorMesh.isVisible = this._debugMode; + impostorMesh.isPickable = false; + impostorMesh.rotationQuaternion = new Quaternion(); + const controllerMesh = xrController.grip || xrController.pointer; + impostorMesh.position.copyFrom(controllerMesh.position); + impostorMesh.rotationQuaternion.copyFrom(controllerMesh.rotationQuaternion); + const impostor = new PhysicsImpostor(impostorMesh, impostorType, { + mass: 0, + ...this._options.physicsProperties, + }); + this._controllers[xrController.uniqueId] = { + xrController, + impostor, + impostorMesh, + }; + } + /** + * Construct a new Controller Physics Feature + * @param _xrSessionManager the corresponding xr session manager + * @param _options options to create this feature with + */ + constructor(_xrSessionManager, _options) { + super(_xrSessionManager); + this._options = _options; + this._attachController = (xrController) => { + if (this._controllers[xrController.uniqueId]) { + // already attached + return; + } + if (!this._xrSessionManager.scene.isPhysicsEnabled()) { + Logger.Warn("physics engine not enabled, skipped. Please add this controller manually."); + } + // if no motion controller available, create impostors! + if (this._options.physicsProperties.useControllerMesh && xrController.inputSource.gamepad) { + xrController.onMotionControllerInitObservable.addOnce((motionController) => { + if (!motionController._doNotLoadControllerMesh) { + motionController.onModelLoadedObservable.addOnce(() => { + const impostor = new PhysicsImpostor(motionController.rootMesh, PhysicsImpostor.MeshImpostor, { + mass: 0, + ...this._options.physicsProperties, + }); + const controllerMesh = xrController.grip || xrController.pointer; + this._controllers[xrController.uniqueId] = { + xrController, + impostor, + oldPos: controllerMesh.position.clone(), + oldRotation: controllerMesh.rotationQuaternion.clone(), + }; + }); + } + else { + // This controller isn't using a model, create impostors instead + this._createPhysicsImpostor(xrController); + } + }); + } + else { + this._createPhysicsImpostor(xrController); + } + }; + this._controllers = {}; + this._debugMode = false; + this._delta = 0; + this._lastTimestamp = 0; + this._tmpQuaternion = new Quaternion(); + this._tmpVector = new Vector3(); + if (!this._options.physicsProperties) { + this._options.physicsProperties = {}; + } + } + /** + * @internal + * enable debugging - will show console outputs and the impostor mesh + */ + _enablePhysicsDebug() { + this._debugMode = true; + Object.keys(this._controllers).forEach((controllerId) => { + const controllerData = this._controllers[controllerId]; + if (controllerData.impostorMesh) { + controllerData.impostorMesh.isVisible = true; + } + }); + } + /** + * Manually add a controller (if no xrInput was provided or physics engine was not enabled) + * @param xrController the controller to add + */ + addController(xrController) { + this._attachController(xrController); + } + /** + * attach this feature + * Will usually be called by the features manager + * + * @returns true if successful. + */ + attach() { + if (!super.attach()) { + return false; + } + if (!this._options.xrInput) { + return true; + } + this._options.xrInput.controllers.forEach(this._attachController); + this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController); + this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => { + // REMOVE the controller + this._detachController(controller.uniqueId); + }); + if (this._options.enableHeadsetImpostor) { + const params = this._options.headsetImpostorParams || { + impostorType: PhysicsImpostor.SphereImpostor, + restitution: 0.8, + impostorSize: 0.3, + }; + const impostorSize = params.impostorSize || 0.3; + this._headsetMesh = CreateSphere("headset-mesh", { + diameterX: typeof impostorSize === "number" ? impostorSize : impostorSize.width, + diameterY: typeof impostorSize === "number" ? impostorSize : impostorSize.height, + diameterZ: typeof impostorSize === "number" ? impostorSize : impostorSize.depth, + }); + this._headsetMesh.rotationQuaternion = new Quaternion(); + this._headsetMesh.isVisible = false; + this._headsetImpostor = new PhysicsImpostor(this._headsetMesh, params.impostorType, { mass: 0, ...params }); + } + return true; + } + /** + * detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + if (!super.detach()) { + return false; + } + Object.keys(this._controllers).forEach((controllerId) => { + this._detachController(controllerId); + }); + if (this._headsetMesh) { + this._headsetMesh.dispose(); + } + return true; + } + /** + * Get the headset impostor, if enabled + * @returns the impostor + */ + getHeadsetImpostor() { + return this._headsetImpostor; + } + /** + * Get the physics impostor of a specific controller. + * The impostor is not attached to a mesh because a mesh for each controller is not obligatory + * @param controller the controller or the controller id of which to get the impostor + * @returns the impostor or null + */ + getImpostorForController(controller) { + const id = typeof controller === "string" ? controller : controller.uniqueId; + if (this._controllers[id]) { + return this._controllers[id].impostor; + } + else { + return null; + } + } + /** + * Update the physics properties provided in the constructor + * @param newProperties the new properties object + * @param newProperties.impostorType + * @param newProperties.impostorSize + * @param newProperties.friction + * @param newProperties.restitution + */ + setPhysicsProperties(newProperties) { + this._options.physicsProperties = { + ...this._options.physicsProperties, + ...newProperties, + }; + } + _onXRFrame(_xrFrame) { + this._delta = this._xrSessionManager.currentTimestamp - this._lastTimestamp; + this._lastTimestamp = this._xrSessionManager.currentTimestamp; + if (this._headsetMesh && this._headsetImpostor) { + this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition); + this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation); + if (this._options.xrInput.xrCamera._lastXRViewerPose?.linearVelocity) { + const lv = this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity; + this._tmpVector.set(lv.x, lv.y, lv.z); + this._headsetImpostor.setLinearVelocity(this._tmpVector); + } + if (this._options.xrInput.xrCamera._lastXRViewerPose?.angularVelocity) { + const av = this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity; + this._tmpVector.set(av.x, av.y, av.z); + this._headsetImpostor.setAngularVelocity(this._tmpVector); + } + } + Object.keys(this._controllers).forEach((controllerId) => { + const controllerData = this._controllers[controllerId]; + const controllerMesh = controllerData.xrController.grip || controllerData.xrController.pointer; + const comparedPosition = controllerData.oldPos || controllerData.impostorMesh.position; + if (controllerData.xrController._lastXRPose?.linearVelocity) { + const lv = controllerData.xrController._lastXRPose.linearVelocity; + this._tmpVector.set(lv.x, lv.y, lv.z); + controllerData.impostor.setLinearVelocity(this._tmpVector); + } + else { + controllerMesh.position.subtractToRef(comparedPosition, this._tmpVector); + this._tmpVector.scaleInPlace(1000 / this._delta); + controllerData.impostor.setLinearVelocity(this._tmpVector); + } + comparedPosition.copyFrom(controllerMesh.position); + if (this._debugMode) { + Logger.Log([this._tmpVector, "linear"]); + } + const comparedQuaternion = controllerData.oldRotation || controllerData.impostorMesh.rotationQuaternion; + if (controllerData.xrController._lastXRPose?.angularVelocity) { + const av = controllerData.xrController._lastXRPose.angularVelocity; + this._tmpVector.set(av.x, av.y, av.z); + controllerData.impostor.setAngularVelocity(this._tmpVector); + } + else { + if (!comparedQuaternion.equalsWithEpsilon(controllerMesh.rotationQuaternion)) { + // roughly based on this - https://www.gamedev.net/forums/topic/347752-quaternion-and-angular-velocity/ + comparedQuaternion.conjugateInPlace().multiplyToRef(controllerMesh.rotationQuaternion, this._tmpQuaternion); + const len = Math.sqrt(this._tmpQuaternion.x * this._tmpQuaternion.x + this._tmpQuaternion.y * this._tmpQuaternion.y + this._tmpQuaternion.z * this._tmpQuaternion.z); + this._tmpVector.set(this._tmpQuaternion.x, this._tmpQuaternion.y, this._tmpQuaternion.z); + // define a better epsilon + if (len < 0.001) { + this._tmpVector.scaleInPlace(2); + } + else { + const angle = 2 * Math.atan2(len, this._tmpQuaternion.w); + this._tmpVector.scaleInPlace(angle / (len * (this._delta / 1000))); + } + controllerData.impostor.setAngularVelocity(this._tmpVector); + } + } + comparedQuaternion.copyFrom(controllerMesh.rotationQuaternion); + if (this._debugMode) { + Logger.Log([this._tmpVector, this._tmpQuaternion, "angular"]); + } + }); + } + _detachController(xrControllerUniqueId) { + const controllerData = this._controllers[xrControllerUniqueId]; + if (!controllerData) { + return; + } + if (controllerData.impostorMesh) { + controllerData.impostorMesh.dispose(); + } + // remove from the map + delete this._controllers[xrControllerUniqueId]; + } +} +/** + * The module's name + */ +WebXRControllerPhysics.Name = WebXRFeatureName.PHYSICS_CONTROLLERS; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the webxr specs version + */ +WebXRControllerPhysics.Version = 1; +//register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPhysics.Name, (xrSessionManager, options) => { + return () => new WebXRControllerPhysics(xrSessionManager, options); +}, WebXRControllerPhysics.Version, true); + +/** + * The currently-working hit-test module. + * Hit test (or Ray-casting) is used to interact with the real world. + * For further information read here - https://github.com/immersive-web/hit-test + * + * Tested on chrome (mobile) 80. + */ +class WebXRHitTest extends WebXRAbstractFeature { + /** + * Creates a new instance of the hit test feature + * @param _xrSessionManager an instance of WebXRSessionManager + * @param options options to use when constructing this feature + */ + constructor(_xrSessionManager, + /** + * [Empty Object] options to use when constructing this feature + */ + options = {}) { + super(_xrSessionManager); + this.options = options; + this._tmpMat = new Matrix(); + this._tmpPos = new Vector3(); + this._tmpQuat = new Quaternion(); + this._initHitTestSource = (referenceSpace) => { + if (!referenceSpace) { + return; + } + const offsetRay = new XRRay(this.options.offsetRay || {}); + const hitTestOptions = { + space: this.options.useReferenceSpace ? referenceSpace : this._xrSessionManager.viewerReferenceSpace, + offsetRay: offsetRay, + }; + if (this.options.entityTypes) { + hitTestOptions.entityTypes = this.options.entityTypes; + } + if (!hitTestOptions.space) { + Tools.Warn("waiting for viewer reference space to initialize"); + return; + } + this._xrSessionManager.session.requestHitTestSource(hitTestOptions).then((hitTestSource) => { + if (this._xrHitTestSource) { + this._xrHitTestSource.cancel(); + } + this._xrHitTestSource = hitTestSource; + }); + }; + /** + * When set to true, each hit test will have its own position/rotation objects + * When set to false, position and rotation objects will be reused for each hit test. It is expected that + * the developers will clone them or copy them as they see fit. + */ + this.autoCloneTransformation = false; + /** + * Triggered when new babylon (transformed) hit test results are available + * Note - this will be called when results come back from the device. It can be an empty array!! + */ + this.onHitTestResultObservable = new Observable(); + /** + * Use this to temporarily pause hit test checks. + */ + this.paused = false; + this.xrNativeFeatureName = "hit-test"; + Tools.Warn("Hit test is an experimental and unstable feature."); + } + /** + * attach this feature + * Will usually be called by the features manager + * + * @returns true if successful. + */ + attach() { + if (!super.attach()) { + return false; + } + // Feature enabled, but not available + if (!this._xrSessionManager.session.requestHitTestSource) { + return false; + } + if (!this.options.disablePermanentHitTest) { + if (this._xrSessionManager.referenceSpace) { + this._initHitTestSource(this._xrSessionManager.referenceSpace); + } + this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource); + } + if (this.options.enableTransientHitTest) { + const offsetRay = new XRRay(this.options.transientOffsetRay || {}); + this._xrSessionManager.session.requestHitTestSourceForTransientInput({ + profile: this.options.transientHitTestProfile || "generic-touchscreen", + offsetRay, + entityTypes: this.options.entityTypes, + }).then((hitSource) => { + this._transientXrHitTestSource = hitSource; + }); + } + return true; + } + /** + * detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + if (!super.detach()) { + return false; + } + if (this._xrHitTestSource) { + this._xrHitTestSource.cancel(); + this._xrHitTestSource = null; + } + this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource); + if (this._transientXrHitTestSource) { + this._transientXrHitTestSource.cancel(); + this._transientXrHitTestSource = null; + } + return true; + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + super.dispose(); + this.onHitTestResultObservable.clear(); + } + _onXRFrame(frame) { + // make sure we do nothing if (async) not attached + if (!this.attached || this.paused) { + return; + } + if (this._xrHitTestSource) { + const results = frame.getHitTestResults(this._xrHitTestSource); + this._processWebXRHitTestResult(results); + } + if (this._transientXrHitTestSource) { + const hitTestResultsPerInputSource = frame.getHitTestResultsForTransientInput(this._transientXrHitTestSource); + hitTestResultsPerInputSource.forEach((resultsPerInputSource) => { + this._processWebXRHitTestResult(resultsPerInputSource.results, resultsPerInputSource.inputSource); + }); + } + } + _processWebXRHitTestResult(hitTestResults, inputSource) { + const results = []; + hitTestResults.forEach((hitTestResult) => { + const pose = hitTestResult.getPose(this._xrSessionManager.referenceSpace); + if (!pose) { + return; + } + const pos = pose.transform.position; + const quat = pose.transform.orientation; + this._tmpPos.set(pos.x, pos.y, pos.z).scaleInPlace(this._xrSessionManager.worldScalingFactor); + this._tmpQuat.set(quat.x, quat.y, quat.z, quat.w); + Matrix.FromFloat32ArrayToRefScaled(pose.transform.matrix, 0, 1, this._tmpMat); + if (!this._xrSessionManager.scene.useRightHandedSystem) { + this._tmpPos.z *= -1; + this._tmpQuat.z *= -1; + this._tmpQuat.w *= -1; + this._tmpMat.toggleModelMatrixHandInPlace(); + } + const result = { + position: this.autoCloneTransformation ? this._tmpPos.clone() : this._tmpPos, + rotationQuaternion: this.autoCloneTransformation ? this._tmpQuat.clone() : this._tmpQuat, + transformationMatrix: this.autoCloneTransformation ? this._tmpMat.clone() : this._tmpMat, + inputSource: inputSource, + isTransient: !!inputSource, + xrHitResult: hitTestResult, + }; + results.push(result); + }); + this.onHitTestResultObservable.notifyObservers(results); + } +} +/** + * The module's name + */ +WebXRHitTest.Name = WebXRFeatureName.HIT_TEST; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRHitTest.Version = 2; +//register the plugin versions +WebXRFeaturesManager.AddWebXRFeature(WebXRHitTest.Name, (xrSessionManager, options) => { + return () => new WebXRHitTest(xrSessionManager, options); +}, WebXRHitTest.Version, false); + +/** + * The feature point system is used to detect feature points from real world geometry. + * This feature is currently experimental and only supported on BabylonNative, and should not be used in the browser. + * The newly introduced API can be seen in webxr.nativeextensions.d.ts and described in FeaturePoints.md. + */ +class WebXRFeaturePointSystem extends WebXRAbstractFeature { + /** + * The current feature point cloud maintained across frames. + */ + get featurePointCloud() { + return this._featurePointCloud; + } + /** + * construct the feature point system + * @param _xrSessionManager an instance of xr Session manager + */ + constructor(_xrSessionManager) { + super(_xrSessionManager); + this._enabled = false; + this._featurePointCloud = []; + /** + * Observers registered here will be executed whenever new feature points are added (on XRFrame while the session is tracking). + * Will notify the observers about which feature points have been added. + */ + this.onFeaturePointsAddedObservable = new Observable(); + /** + * Observers registered here will be executed whenever a feature point has been updated (on XRFrame while the session is tracking). + * Will notify the observers about which feature points have been updated. + */ + this.onFeaturePointsUpdatedObservable = new Observable(); + this.xrNativeFeatureName = "bjsfeature-points"; + if (this._xrSessionManager.session) { + this._init(); + } + else { + this._xrSessionManager.onXRSessionInit.addOnce(() => { + this._init(); + }); + } + } + /** + * Detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + if (!super.detach()) { + return false; + } + this.featurePointCloud.length = 0; + return true; + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + super.dispose(); + this._featurePointCloud.length = 0; + this.onFeaturePointsUpdatedObservable.clear(); + this.onFeaturePointsAddedObservable.clear(); + } + /** + * On receiving a new XR frame if this feature is attached notify observers new feature point data is available. + * @param frame + */ + _onXRFrame(frame) { + if (!this.attached || !this._enabled || !frame) { + return; + } + const featurePointRawData = frame.featurePointCloud; + if (!featurePointRawData || featurePointRawData.length === 0) { + return; + } + else { + if (featurePointRawData.length % 5 !== 0) { + throw new Error("Received malformed feature point cloud of length: " + featurePointRawData.length); + } + const numberOfFeaturePoints = featurePointRawData.length / 5; + const updatedFeaturePoints = []; + const addedFeaturePoints = []; + for (let i = 0; i < numberOfFeaturePoints; i++) { + const rawIndex = i * 5; + const id = featurePointRawData[rawIndex + 4]; + // IDs should be durable across frames and strictly increasing from 0 up, so use them as indexing into the feature point array. + if (!this._featurePointCloud[id]) { + this._featurePointCloud[id] = { position: new Vector3(), confidenceValue: 0 }; + addedFeaturePoints.push(id); + } + else { + updatedFeaturePoints.push(id); + } + // Set the feature point values. + this._featurePointCloud[id].position.x = featurePointRawData[rawIndex]; + this._featurePointCloud[id].position.y = featurePointRawData[rawIndex + 1]; + this._featurePointCloud[id].position.z = featurePointRawData[rawIndex + 2]; + this._featurePointCloud[id].confidenceValue = featurePointRawData[rawIndex + 3]; + } + // Signal observers that feature points have been added if necessary. + if (addedFeaturePoints.length > 0) { + this.onFeaturePointsAddedObservable.notifyObservers(addedFeaturePoints); + } + // Signal observers that feature points have been updated if necessary. + if (updatedFeaturePoints.length > 0) { + this.onFeaturePointsUpdatedObservable.notifyObservers(updatedFeaturePoints); + } + } + } + /** + * Initializes the feature. If the feature point feature is not available for this environment do not mark the feature as enabled. + */ + _init() { + if (!this._xrSessionManager.session.trySetFeaturePointCloudEnabled || !this._xrSessionManager.session.trySetFeaturePointCloudEnabled(true)) { + // fail silently + return; + } + this._enabled = true; + } +} +/** + * The module's name + */ +WebXRFeaturePointSystem.Name = WebXRFeatureName.FEATURE_POINTS; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRFeaturePointSystem.Version = 1; +// register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRFeaturePointSystem.Name, (xrSessionManager) => { + return () => new WebXRFeaturePointSystem(xrSessionManager); +}, WebXRFeaturePointSystem.Version); + +let meshIdProvider = 0; +/** + * The mesh detector is used to detect meshes in the real world when in AR + */ +class WebXRMeshDetector extends WebXRAbstractFeature { + constructor(_xrSessionManager, _options = {}) { + super(_xrSessionManager); + this._options = _options; + this._detectedMeshes = new Map(); + /** + * Observers registered here will be executed when a new mesh was added to the session + */ + this.onMeshAddedObservable = new Observable(); + /** + * Observers registered here will be executed when a mesh is no longer detected in the session + */ + this.onMeshRemovedObservable = new Observable(); + /** + * Observers registered here will be executed when an existing mesh updates + */ + this.onMeshUpdatedObservable = new Observable(); + this.xrNativeFeatureName = "mesh-detection"; + if (this._options.generateMeshes) { + this._options.convertCoordinateSystems = true; + } + if (this._xrSessionManager.session) { + this._init(); + } + else { + this._xrSessionManager.onXRSessionInit.addOnce(() => { + this._init(); + }); + } + } + detach() { + if (!super.detach()) { + return false; + } + // Only supported by BabylonNative + if (!!this._xrSessionManager.isNative && !!this._xrSessionManager.session.trySetMeshDetectorEnabled) { + this._xrSessionManager.session.trySetMeshDetectorEnabled(false); + } + if (!this._options.doNotRemoveMeshesOnSessionEnded) { + this._detectedMeshes.forEach((mesh) => { + this.onMeshRemovedObservable.notifyObservers(mesh); + }); + this._detectedMeshes.clear(); + } + return true; + } + dispose() { + super.dispose(); + this.onMeshAddedObservable.clear(); + this.onMeshRemovedObservable.clear(); + this.onMeshUpdatedObservable.clear(); + } + _onXRFrame(frame) { + // TODO remove try catch + try { + if (!this.attached || !frame) { + return; + } + // babylon native XR and webxr support + const detectedMeshes = frame.detectedMeshes || frame.worldInformation?.detectedMeshes; + if (detectedMeshes) { + const toRemove = new Set(); + this._detectedMeshes.forEach((vertexData, xrMesh) => { + if (!detectedMeshes.has(xrMesh)) { + toRemove.add(xrMesh); + } + }); + toRemove.forEach((xrMesh) => { + const vertexData = this._detectedMeshes.get(xrMesh); + if (vertexData) { + this.onMeshRemovedObservable.notifyObservers(vertexData); + this._detectedMeshes.delete(xrMesh); + } + }); + // now check for new ones + detectedMeshes.forEach((xrMesh) => { + if (!this._detectedMeshes.has(xrMesh)) { + const partialVertexData = { + id: meshIdProvider++, + xrMesh: xrMesh, + }; + const vertexData = this._updateVertexDataWithXRMesh(xrMesh, partialVertexData, frame); + this._detectedMeshes.set(xrMesh, vertexData); + this.onMeshAddedObservable.notifyObservers(vertexData); + } + else { + // updated? + if (xrMesh.lastChangedTime === this._xrSessionManager.currentTimestamp) { + const vertexData = this._detectedMeshes.get(xrMesh); + if (vertexData) { + this._updateVertexDataWithXRMesh(xrMesh, vertexData, frame); + this.onMeshUpdatedObservable.notifyObservers(vertexData); + } + } + } + }); + } + } + catch (error) { + Logger.Log(error.stack); + } + } + _init() { + // Only supported by BabylonNative + if (this._xrSessionManager.isNative) { + if (this._xrSessionManager.session.trySetMeshDetectorEnabled) { + this._xrSessionManager.session.trySetMeshDetectorEnabled(true); + } + if (!!this._options.preferredDetectorOptions && !!this._xrSessionManager.session.trySetPreferredMeshDetectorOptions) { + this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions); + } + } + } + _updateVertexDataWithXRMesh(xrMesh, mesh, xrFrame) { + mesh.xrMesh = xrMesh; + mesh.worldParentNode = this._options.worldParentNode; + const positions = xrMesh.vertices || xrMesh.positions; + if (this._options.convertCoordinateSystems) { + if (!this._xrSessionManager.scene.useRightHandedSystem) { + mesh.positions = new Float32Array(positions.length); + for (let i = 0; i < positions.length; i += 3) { + mesh.positions[i] = positions[i]; + mesh.positions[i + 1] = positions[i + 1]; + mesh.positions[i + 2] = -1 * positions[i + 2]; + } + if (xrMesh.normals) { + mesh.normals = new Float32Array(xrMesh.normals.length); + for (let i = 0; i < xrMesh.normals.length; i += 3) { + mesh.normals[i] = xrMesh.normals[i]; + mesh.normals[i + 1] = xrMesh.normals[i + 1]; + mesh.normals[i + 2] = -1 * xrMesh.normals[i + 2]; + } + } + } + else { + mesh.positions = positions; + mesh.normals = xrMesh.normals; + } + // WebXR should provide indices in a counterclockwise winding order regardless of coordinate system handedness + mesh.indices = xrMesh.indices; + // matrix + const pose = xrFrame.getPose(xrMesh.meshSpace, this._xrSessionManager.referenceSpace); + if (pose) { + const mat = mesh.transformationMatrix || new Matrix(); + Matrix.FromArrayToRef(pose.transform.matrix, 0, mat); + if (!this._xrSessionManager.scene.useRightHandedSystem) { + mat.toggleModelMatrixHandInPlace(); + } + mesh.transformationMatrix = mat; + if (this._options.worldParentNode) { + mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat); + } + } + if (this._options.generateMeshes) { + if (!mesh.mesh) { + const generatedMesh = new Mesh("xr mesh " + mesh.id, this._xrSessionManager.scene); + generatedMesh.rotationQuaternion = new Quaternion(); + generatedMesh.setVerticesData(VertexBuffer.PositionKind, mesh.positions); + if (mesh.normals) { + generatedMesh.setVerticesData(VertexBuffer.NormalKind, mesh.normals); + } + else { + generatedMesh.createNormals(true); + } + generatedMesh.setIndices(mesh.indices, undefined, true); + mesh.mesh = generatedMesh; + } + else { + const generatedMesh = mesh.mesh; + generatedMesh.updateVerticesData(VertexBuffer.PositionKind, mesh.positions); + if (mesh.normals) { + generatedMesh.updateVerticesData(VertexBuffer.NormalKind, mesh.normals); + } + else { + generatedMesh.createNormals(true); + } + generatedMesh.updateIndices(mesh.indices); + } + mesh.transformationMatrix?.decompose(mesh.mesh.scaling, mesh.mesh.rotationQuaternion, mesh.mesh.position); + } + } + return mesh; + } +} +/** + * The module's name + */ +WebXRMeshDetector.Name = WebXRFeatureName.MESH_DETECTION; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRMeshDetector.Version = 1; +WebXRFeaturesManager.AddWebXRFeature(WebXRMeshDetector.Name, (xrSessionManager, options) => { + return () => new WebXRMeshDetector(xrSessionManager, options); +}, WebXRMeshDetector.Version, false); + +/** + * Enum that describes the state of the image trackability score status for this session. + */ +var ImageTrackingScoreStatus; +(function (ImageTrackingScoreStatus) { + // AR Session has not yet assessed image trackability scores. + ImageTrackingScoreStatus[ImageTrackingScoreStatus["NotReceived"] = 0] = "NotReceived"; + // A request to retrieve trackability scores has been sent, but no response has been received. + ImageTrackingScoreStatus[ImageTrackingScoreStatus["Waiting"] = 1] = "Waiting"; + // Image trackability scores have been received for this session + ImageTrackingScoreStatus[ImageTrackingScoreStatus["Received"] = 2] = "Received"; +})(ImageTrackingScoreStatus || (ImageTrackingScoreStatus = {})); +/** + * Image tracking for immersive AR sessions. + * Providing a list of images and their estimated widths will enable tracking those images in the real world. + */ +class WebXRImageTracking extends WebXRAbstractFeature { + /** + * constructs the image tracking feature + * @param _xrSessionManager the session manager for this module + * @param options read-only options to be used in this module + */ + constructor(_xrSessionManager, + /** + * read-only options to be used in this module + */ + options) { + super(_xrSessionManager); + this.options = options; + /** + * This will be triggered if the underlying system deems an image untrackable. + * The index is the index of the image from the array used to initialize the feature. + */ + this.onUntrackableImageFoundObservable = new Observable(); + /** + * An image was deemed trackable, and the system will start tracking it. + */ + this.onTrackableImageFoundObservable = new Observable(); + /** + * The image was found and its state was updated. + */ + this.onTrackedImageUpdatedObservable = new Observable(); + this._trackableScoreStatus = ImageTrackingScoreStatus.NotReceived; + this._trackedImages = []; + this.xrNativeFeatureName = "image-tracking"; + } + /** + * attach this feature + * Will usually be called by the features manager + * + * @returns true if successful. + */ + attach() { + return super.attach(); + } + /** + * detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + return super.detach(); + } + /** + * Get a tracked image by its ID. + * + * @param id the id of the image to load (position in the init array) + * @returns a trackable image, if exists in this location + */ + getTrackedImageById(id) { + return this._trackedImages[id] || null; + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + super.dispose(); + this._trackedImages.forEach((trackedImage) => { + trackedImage.originalBitmap.close(); + }); + this._trackedImages.length = 0; + this.onTrackableImageFoundObservable.clear(); + this.onUntrackableImageFoundObservable.clear(); + this.onTrackedImageUpdatedObservable.clear(); + } + /** + * Extends the session init object if needed + * @returns augmentation object fo the xr session init object. + */ + async getXRSessionInitExtension() { + if (!this.options.images || !this.options.images.length) { + return {}; + } + const promises = this.options.images.map((image) => { + if (typeof image.src === "string") { + return this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(image.src); + } + else { + return Promise.resolve(image.src); // resolve is probably unneeded + } + }); + try { + const images = await Promise.all(promises); + this._originalTrackingRequest = images.map((image, idx) => { + return { + image, + widthInMeters: this.options.images[idx].estimatedRealWorldWidth, + }; + }); + return { + trackedImages: this._originalTrackingRequest, + }; + } + catch (ex) { + Tools.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."); + return {}; + } + } + _onXRFrame(_xrFrame) { + if (!_xrFrame.getImageTrackingResults || this._trackableScoreStatus === ImageTrackingScoreStatus.Waiting) { + return; + } + // Image tracking scores may be generated a few frames after the XR Session initializes. + // If we haven't received scores yet, then kick off the task to check scores and return immediately. + if (this._trackableScoreStatus === ImageTrackingScoreStatus.NotReceived) { + this._checkScoresAsync(); + return; + } + const imageTrackedResults = _xrFrame.getImageTrackingResults(); + for (const result of imageTrackedResults) { + let changed = false; + const imageIndex = result.index; + const imageObject = this._trackedImages[imageIndex]; + if (!imageObject) { + // something went wrong! + continue; + } + imageObject.xrTrackingResult = result; + if (imageObject.realWorldWidth !== result.measuredWidthInMeters) { + imageObject.realWorldWidth = result.measuredWidthInMeters; + changed = true; + } + // Get the pose of the image relative to a reference space. + const pose = _xrFrame.getPose(result.imageSpace, this._xrSessionManager.referenceSpace); + if (pose) { + const mat = imageObject.transformationMatrix; + Matrix.FromArrayToRef(pose.transform.matrix, 0, mat); + if (!this._xrSessionManager.scene.useRightHandedSystem) { + mat.toggleModelMatrixHandInPlace(); + } + changed = true; + } + const state = result.trackingState; + const emulated = state === "emulated"; + if (imageObject.emulated !== emulated) { + imageObject.emulated = emulated; + changed = true; + } + if (changed) { + this.onTrackedImageUpdatedObservable.notifyObservers(imageObject); + } + } + } + async _checkScoresAsync() { + if (!this._xrSessionManager.session.getTrackedImageScores || this._trackableScoreStatus !== ImageTrackingScoreStatus.NotReceived) { + return; + } + this._trackableScoreStatus = ImageTrackingScoreStatus.Waiting; + const imageScores = await this._xrSessionManager.session.getTrackedImageScores(); + if (!imageScores || imageScores.length === 0) { + this._trackableScoreStatus = ImageTrackingScoreStatus.NotReceived; + return; + } + // check the scores for all + for (let idx = 0; idx < imageScores.length; ++idx) { + if (imageScores[idx] == "untrackable") { + this.onUntrackableImageFoundObservable.notifyObservers(idx); + } + else { + const originalBitmap = this._originalTrackingRequest[idx].image; + const imageObject = { + id: idx, + originalBitmap, + transformationMatrix: new Matrix(), + ratio: originalBitmap.width / originalBitmap.height, + }; + this._trackedImages[idx] = imageObject; + this.onTrackableImageFoundObservable.notifyObservers(imageObject); + } + } + this._trackableScoreStatus = imageScores.length > 0 ? ImageTrackingScoreStatus.Received : ImageTrackingScoreStatus.NotReceived; + } +} +/** + * The module's name + */ +WebXRImageTracking.Name = WebXRFeatureName.IMAGE_TRACKING; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRImageTracking.Version = 1; +//register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRImageTracking.Name, (xrSessionManager, options) => { + return () => new WebXRImageTracking(xrSessionManager, options); +}, WebXRImageTracking.Version, false); + +/** + * DOM Overlay Feature + * + * @since 5.0.0 + */ +class WebXRDomOverlay extends WebXRAbstractFeature { + /** + * Creates a new instance of the dom-overlay feature + * @param _xrSessionManager an instance of WebXRSessionManager + * @param options options to use when constructing this feature + */ + constructor(_xrSessionManager, + /** + * options to use when constructing this feature + */ + options) { + super(_xrSessionManager); + this.options = options; + /** + * Type of overlay - non-null when available + */ + this._domOverlayType = null; + /** + * Event Listener to supress "beforexrselect" events. + */ + this._beforeXRSelectListener = null; + /** + * Element used for overlay + */ + this._element = null; + this.xrNativeFeatureName = "dom-overlay"; + // https://immersive-web.github.io/dom-overlays/ + Tools.Warn("dom-overlay is an experimental and unstable feature."); + } + /** + * attach this feature + * Will usually be called by the features manager + * + * @returns true if successful. + */ + attach() { + if (!super.attach()) { + return false; + } + // Feature not available + if (!this._xrSessionManager.session.domOverlayState || this._xrSessionManager.session.domOverlayState.type === null) { + return false; + } + this._domOverlayType = this._xrSessionManager.session.domOverlayState.type; + if (this._element !== null && this.options.supressXRSelectEvents === true) { + this._beforeXRSelectListener = (ev) => { + ev.preventDefault(); + }; + this._element.addEventListener("beforexrselect", this._beforeXRSelectListener); + } + return true; + } + /** + * The type of DOM overlay (null when not supported). Provided by UA and remains unchanged for duration of session. + */ + get domOverlayType() { + return this._domOverlayType; + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + super.dispose(); + if (this._element !== null && this._beforeXRSelectListener) { + this._element.removeEventListener("beforexrselect", this._beforeXRSelectListener); + } + } + _onXRFrame(_xrFrame) { + /* empty */ + } + /** + * Extends the session init object if needed + * @returns augmentation object for the xr session init object. + */ + async getXRSessionInitExtension() { + if (this.options.element === undefined) { + Tools.Warn('"element" option must be provided to attach xr-dom-overlay feature.'); + return {}; + } + else if (typeof this.options.element === "string") { + const selectedElement = document.querySelector(this.options.element); + if (selectedElement === null) { + Tools.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`); + return {}; + } + this._element = selectedElement; + } + else { + this._element = this.options.element; + } + return { + domOverlay: { + root: this._element, + }, + }; + } +} +/** + * The module's name + */ +WebXRDomOverlay.Name = WebXRFeatureName.DOM_OVERLAY; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRDomOverlay.Version = 1; +//register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRDomOverlay.Name, (xrSessionManager, options) => { + return () => new WebXRDomOverlay(xrSessionManager, options); +}, WebXRDomOverlay.Version, false); + +/** + * This is a movement feature to be used with WebXR-enabled motion controllers. + * When enabled and attached, the feature will allow a user to move around and rotate in the scene using + * the input of the attached controllers. + */ +class WebXRControllerMovement extends WebXRAbstractFeature { + /** + * Current movement direction. Will be null before XR Frames have been processed. + */ + get movementDirection() { + return this._movementDirection; + } + /** + * Is movement enabled + */ + get movementEnabled() { + return this._featureContext.movementEnabled; + } + /** + * Sets whether movement is enabled or not + * @param enabled is movement enabled + */ + set movementEnabled(enabled) { + this._featureContext.movementEnabled = enabled; + } + /** + * If movement follows viewer pose + */ + get movementOrientationFollowsViewerPose() { + return this._featureContext.movementOrientationFollowsViewerPose; + } + /** + * Sets whether movement follows viewer pose + * @param followsPose is movement should follow viewer pose + */ + set movementOrientationFollowsViewerPose(followsPose) { + this._featureContext.movementOrientationFollowsViewerPose = followsPose; + } + /** + * Gets movement speed + */ + get movementSpeed() { + return this._featureContext.movementSpeed; + } + /** + * Sets movement speed + * @param movementSpeed movement speed + */ + set movementSpeed(movementSpeed) { + this._featureContext.movementSpeed = movementSpeed; + } + /** + * Gets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for movement (avoids jitter/unintentional movement) + */ + get movementThreshold() { + return this._featureContext.movementThreshold; + } + /** + * Sets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for movement (avoids jitter/unintentional movement) + * @param movementThreshold new threshold + */ + set movementThreshold(movementThreshold) { + this._featureContext.movementThreshold = movementThreshold; + } + /** + * Is rotation enabled + */ + get rotationEnabled() { + return this._featureContext.rotationEnabled; + } + /** + * Sets whether rotation is enabled or not + * @param enabled is rotation enabled + */ + set rotationEnabled(enabled) { + this._featureContext.rotationEnabled = enabled; + } + /** + * Gets rotation speed factor + */ + get rotationSpeed() { + return this._featureContext.rotationSpeed; + } + /** + * Sets rotation speed factor (1.0 is default) + * @param rotationSpeed new rotation speed factor + */ + set rotationSpeed(rotationSpeed) { + this._featureContext.rotationSpeed = rotationSpeed; + } + /** + * Gets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for rotation (avoids jitter/unintentional rotation) + */ + get rotationThreshold() { + return this._featureContext.rotationThreshold; + } + /** + * Sets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for rotation (avoids jitter/unintentional rotation) + * @param threshold new threshold + */ + set rotationThreshold(threshold) { + this._featureContext.rotationThreshold = threshold; + } + /** + * constructs a new movement controller system + * @param _xrSessionManager an instance of WebXRSessionManager + * @param options configuration object for this feature + */ + constructor(_xrSessionManager, options) { + super(_xrSessionManager); + this._controllers = {}; + this._currentRegistrationConfigurations = []; + // forward direction for movement, which may differ from viewer pose. + this._movementDirection = new Quaternion(); + // unused + this._tmpRotationMatrix = Matrix.Identity(); + this._tmpTranslationDirection = new Vector3(); + this._tmpMovementTranslation = new Vector3(); + this._tempCacheQuaternion = new Quaternion(); + this._attachController = (xrController) => { + if (this._controllers[xrController.uniqueId]) { + // already attached + return; + } + this._controllers[xrController.uniqueId] = { + xrController, + registeredComponents: [], + }; + const controllerData = this._controllers[xrController.uniqueId]; + // movement controller only available to gamepad-enabled input sources. + if (controllerData.xrController.inputSource.targetRayMode === "tracked-pointer" && controllerData.xrController.inputSource.gamepad) { + // motion controller support + const initController = () => { + if (xrController.motionController) { + for (const registration of this._currentRegistrationConfigurations) { + let component = null; + if (registration.allowedComponentTypes) { + for (const componentType of registration.allowedComponentTypes) { + const componentOfType = xrController.motionController.getComponentOfType(componentType); + if (componentOfType !== null) { + component = componentOfType; + break; + } + } + } + if (registration.mainComponentOnly) { + const mainComponent = xrController.motionController.getMainComponent(); + if (mainComponent === null) { + continue; + } + component = mainComponent; + } + if (typeof registration.componentSelectionPredicate === "function") { + // if does not match we do want to ignore a previously found component + component = registration.componentSelectionPredicate(xrController); + } + if (component && registration.forceHandedness) { + if (xrController.inputSource.handedness !== registration.forceHandedness) { + continue; // do not register + } + } + if (component === null) { + continue; // do not register + } + const registeredComponent = { + registrationConfiguration: registration, + component, + }; + controllerData.registeredComponents.push(registeredComponent); + if ("axisChangedHandler" in registration) { + registeredComponent.onAxisChangedObserver = component.onAxisValueChangedObservable.add((axesData) => { + registration.axisChangedHandler(axesData, this._movementState, this._featureContext, this._xrInput); + }); + } + if ("buttonChangedHandler" in registration) { + registeredComponent.onButtonChangedObserver = component.onButtonStateChangedObservable.add((component) => { + if (component.changes.pressed) { + registration.buttonChangedHandler(component.changes.pressed, this._movementState, this._featureContext, this._xrInput); + } + }); + } + } + } + }; + if (xrController.motionController) { + initController(); + } + else { + xrController.onMotionControllerInitObservable.addOnce(() => { + initController(); + }); + } + } + }; + if (!options || options.xrInput === undefined) { + Tools.Error('WebXRControllerMovement feature requires "xrInput" option.'); + return; + } + if (Array.isArray(options.customRegistrationConfigurations)) { + this._currentRegistrationConfigurations = options.customRegistrationConfigurations; + } + else { + this._currentRegistrationConfigurations = WebXRControllerMovement.REGISTRATIONS.default; + } + // synchronized from feature setter properties + this._featureContext = { + movementEnabled: options.movementEnabled || true, + movementOrientationFollowsViewerPose: options.movementOrientationFollowsViewerPose ?? true, + movementOrientationFollowsController: options.movementOrientationFollowsController ?? false, + orientationPreferredHandedness: options.orientationPreferredHandedness, + movementSpeed: options.movementSpeed ?? 1, + movementThreshold: options.movementThreshold ?? 0.25, + rotationEnabled: options.rotationEnabled ?? true, + rotationSpeed: options.rotationSpeed ?? 1.0, + rotationThreshold: options.rotationThreshold ?? 0.25, + }; + this._movementState = { + moveX: 0, + moveY: 0, + rotateX: 0, + rotateY: 0, + }; + this._xrInput = options.xrInput; + } + attach() { + if (!super.attach()) { + return false; + } + this._xrInput.controllers.forEach(this._attachController); + this._addNewAttachObserver(this._xrInput.onControllerAddedObservable, this._attachController); + this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable, (controller) => { + // REMOVE the controller + this._detachController(controller.uniqueId); + }); + return true; + } + detach() { + if (!super.detach()) { + return false; + } + Object.keys(this._controllers).forEach((controllerId) => { + this._detachController(controllerId); + }); + this._controllers = {}; + return true; + } + /** + * Occurs on every XR frame. + * @param _xrFrame + */ + _onXRFrame(_xrFrame) { + if (!this.attached) { + return; + } + if (this._movementState.rotateX !== 0 && this._featureContext.rotationEnabled) { + // smooth rotation + const deltaMillis = this._xrSessionManager.scene.getEngine().getDeltaTime(); + const rotationY = deltaMillis * 0.001 * this._featureContext.rotationSpeed * this._movementState.rotateX * (this._xrSessionManager.scene.useRightHandedSystem ? -1 : 1); + if (this._featureContext.movementOrientationFollowsViewerPose) { + this._xrInput.xrCamera.cameraRotation.y += rotationY; + Quaternion.RotationYawPitchRollToRef(rotationY, 0, 0, this._tempCacheQuaternion); + this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion, this._movementDirection); + } + else if (this._featureContext.movementOrientationFollowsController) { + this._xrInput.xrCamera.cameraRotation.y += rotationY; + // get the correct controller + const handedness = this._featureContext.orientationPreferredHandedness || "right"; + const key = Object.keys(this._controllers).find((key) => this._controllers[key]?.xrController?.inputSource.handedness === handedness) || Object.keys(this._controllers)[0]; + const controller = this._controllers[key]; + Quaternion.RotationYawPitchRollToRef(rotationY, 0, 0, this._tempCacheQuaternion); + (controller?.xrController.pointer.rotationQuaternion || Quaternion.Identity()).multiplyToRef(this._tempCacheQuaternion, this._movementDirection); + } + else { + // movement orientation direction does not affect camera. We use rotation speed multiplier + // otherwise need to implement inertia and constraints for same feel as TargetCamera. + Quaternion.RotationYawPitchRollToRef(rotationY * 3.0, 0, 0, this._tempCacheQuaternion); + this._movementDirection.multiplyInPlace(this._tempCacheQuaternion); + } + } + else if (this._featureContext.movementOrientationFollowsViewerPose) { + this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion); + } + else if (this._featureContext.movementOrientationFollowsController) { + // get the correct controller + const handedness = this._featureContext.orientationPreferredHandedness || "right"; + const key = Object.keys(this._controllers).find((key) => this._controllers[key]?.xrController.inputSource.handedness === handedness) || Object.keys(this._controllers)[0]; + const controller = this._controllers[key]; + this._movementDirection.copyFrom(controller?.xrController.pointer.rotationQuaternion || Quaternion.Identity()); + } + if ((this._movementState.moveX || this._movementState.moveY) && this._featureContext.movementEnabled) { + Matrix.FromQuaternionToRef(this._movementDirection, this._tmpRotationMatrix); + this._tmpTranslationDirection.set(this._movementState.moveX, 0, this._movementState.moveY * (this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1)); + // move according to forward direction based on camera speed + Vector3.TransformCoordinatesToRef(this._tmpTranslationDirection, this._tmpRotationMatrix, this._tmpMovementTranslation); + this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed() * this._featureContext.movementSpeed); + this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation); + } + } + _detachController(xrControllerUniqueId) { + const controllerData = this._controllers[xrControllerUniqueId]; + if (!controllerData) { + return; + } + for (const registeredComponent of controllerData.registeredComponents) { + if (registeredComponent.onAxisChangedObserver) { + registeredComponent.component.onAxisValueChangedObservable.remove(registeredComponent.onAxisChangedObserver); + } + if (registeredComponent.onButtonChangedObserver) { + registeredComponent.component.onButtonStateChangedObservable.remove(registeredComponent.onButtonChangedObserver); + } + } + // remove from the map + delete this._controllers[xrControllerUniqueId]; + } +} +/** + * The module's name + */ +WebXRControllerMovement.Name = WebXRFeatureName.MOVEMENT; +/** + * Standard controller configurations. + */ +WebXRControllerMovement.REGISTRATIONS = { + default: [ + { + allowedComponentTypes: [WebXRControllerComponent.THUMBSTICK_TYPE, WebXRControllerComponent.TOUCHPAD_TYPE], + forceHandedness: "left", + axisChangedHandler: (axes, movementState, featureContext) => { + movementState.rotateX = Math.abs(axes.x) > featureContext.rotationThreshold ? axes.x : 0; + movementState.rotateY = Math.abs(axes.y) > featureContext.rotationThreshold ? axes.y : 0; + }, + }, + { + allowedComponentTypes: [WebXRControllerComponent.THUMBSTICK_TYPE, WebXRControllerComponent.TOUCHPAD_TYPE], + forceHandedness: "right", + axisChangedHandler: (axes, movementState, featureContext) => { + movementState.moveX = Math.abs(axes.x) > featureContext.movementThreshold ? axes.x : 0; + movementState.moveY = Math.abs(axes.y) > featureContext.movementThreshold ? axes.y : 0; + }, + }, + ], +}; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the webxr specs version + */ +WebXRControllerMovement.Version = 1; +WebXRFeaturesManager.AddWebXRFeature(WebXRControllerMovement.Name, (xrSessionManager, options) => { + return () => new WebXRControllerMovement(xrSessionManager, options); +}, WebXRControllerMovement.Version, true); + +/** + * Light Estimation Feature + * + * @since 5.0.0 + */ +class WebXRLightEstimation extends WebXRAbstractFeature { + /** + * Creates a new instance of the light estimation feature + * @param _xrSessionManager an instance of WebXRSessionManager + * @param options options to use when constructing this feature + */ + constructor(_xrSessionManager, + /** + * options to use when constructing this feature + */ + options) { + super(_xrSessionManager); + this.options = options; + this._canvasContext = null; + this._reflectionCubeMap = null; + this._xrLightEstimate = null; + this._xrLightProbe = null; + this._xrWebGLBinding = null; + this._lightDirection = Vector3.Up().negateInPlace(); + this._lightColor = Color3.White(); + this._intensity = 1; + this._sphericalHarmonics = new SphericalHarmonics(); + this._cubeMapPollTime = Date.now(); + this._lightEstimationPollTime = Date.now(); + /** + * ARCore's reflection cube map size is 16x16. + * Once other systems support this feature we will need to change this to be dynamic. + * see https://github.com/immersive-web/lighting-estimation/blob/main/lighting-estimation-explainer.md#cube-map-open-questions + */ + this._reflectionCubeMapTextureSize = 16; + /** + * If createDirectionalLightSource is set to true this light source will be created automatically. + * Otherwise this can be set with an external directional light source. + * This light will be updated whenever the light estimation values change. + */ + this.directionalLight = null; + /** + * This observable will notify when the reflection cube map is updated. + */ + this.onReflectionCubeMapUpdatedObservable = new Observable(); + /** + * Event Listener for "reflectionchange" events. + */ + this._updateReflectionCubeMap = () => { + if (!this._xrLightProbe) { + return; + } + // check poll time, do not update if it has not been long enough + if (this.options.cubeMapPollInterval) { + const now = Date.now(); + if (now - this._cubeMapPollTime < this.options.cubeMapPollInterval) { + return; + } + this._cubeMapPollTime = now; + } + const lp = this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe); + if (lp && this._reflectionCubeMap) { + if (!this._reflectionCubeMap._texture) { + const internalTexture = new InternalTexture(this._xrSessionManager.scene.getEngine(), 0 /* InternalTextureSource.Unknown */); + internalTexture.isCube = true; + internalTexture.invertY = false; + internalTexture._useSRGBBuffer = this.options.reflectionFormat === "srgba8"; + internalTexture.format = 5; + internalTexture.generateMipMaps = true; + internalTexture.type = this.options.reflectionFormat !== "srgba8" ? 2 : 0; + internalTexture.samplingMode = 3; + internalTexture.width = this._reflectionCubeMapTextureSize; + internalTexture.height = this._reflectionCubeMapTextureSize; + internalTexture._cachedWrapU = 1; + internalTexture._cachedWrapV = 1; + internalTexture._hardwareTexture = new WebGLHardwareTexture(lp, this._getCanvasContext()); + this._reflectionCubeMap._texture = internalTexture; + } + else { + this._reflectionCubeMap._texture._hardwareTexture?.set(lp); + this._reflectionCubeMap._texture.getEngine().resetTextureCache(); + } + this._reflectionCubeMap._texture.isReady = true; + if (!this.options.disablePreFiltering) { + this._xrLightProbe.removeEventListener("reflectionchange", this._updateReflectionCubeMap); + this._hdrFilter.prefilter(this._reflectionCubeMap).then(() => { + this._xrSessionManager.scene.markAllMaterialsAsDirty(1); + this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap); + this._xrLightProbe.addEventListener("reflectionchange", this._updateReflectionCubeMap); + }); + } + else { + this._xrSessionManager.scene.markAllMaterialsAsDirty(1); + this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap); + } + } + }; + this.xrNativeFeatureName = "light-estimation"; + if (this.options.createDirectionalLightSource) { + this.directionalLight = new DirectionalLight("light estimation directional", this._lightDirection, this._xrSessionManager.scene); + this.directionalLight.position = new Vector3(0, 8, 0); + // intensity will be set later + this.directionalLight.intensity = 0; + this.directionalLight.falloffType = LightConstants.FALLOFF_GLTF; + } + this._hdrFilter = new HDRFiltering(this._xrSessionManager.scene.getEngine()); + // https://immersive-web.github.io/lighting-estimation/ + Tools.Warn("light-estimation is an experimental and unstable feature."); + } + /** + * While the estimated cube map is expected to update over time to better reflect the user's environment as they move around those changes are unlikely to happen with every XRFrame. + * Since creating and processing the cube map is potentially expensive, especially if mip maps are needed, you can listen to the onReflectionCubeMapUpdatedObservable to determine + * when it has been updated. + */ + get reflectionCubeMapTexture() { + return this._reflectionCubeMap; + } + /** + * The most recent light estimate. Available starting on the first frame where the device provides a light probe. + */ + get xrLightingEstimate() { + if (this._xrLightEstimate) { + return { + lightColor: this._lightColor, + lightDirection: this._lightDirection, + lightIntensity: this._intensity, + sphericalHarmonics: this._sphericalHarmonics, + }; + } + return this._xrLightEstimate; + } + _getCanvasContext() { + if (this._canvasContext === null) { + this._canvasContext = this._xrSessionManager.scene.getEngine()._gl; + } + return this._canvasContext; + } + _getXRGLBinding() { + if (this._xrWebGLBinding === null) { + const context = this._getCanvasContext(); + this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, context); + } + return this._xrWebGLBinding; + } + /** + * attach this feature + * Will usually be called by the features manager + * + * @returns true if successful. + */ + attach() { + if (!super.attach()) { + return false; + } + const reflectionFormat = this.options.reflectionFormat ?? (this._xrSessionManager.session.preferredReflectionFormat || "srgba8"); + this.options.reflectionFormat = reflectionFormat; + this._xrSessionManager.session + .requestLightProbe({ + reflectionFormat, + }) + .then((xrLightProbe) => { + this._xrLightProbe = xrLightProbe; + if (!this.options.disableCubeMapReflection) { + if (!this._reflectionCubeMap) { + this._reflectionCubeMap = new BaseTexture(this._xrSessionManager.scene); + this._reflectionCubeMap._isCube = true; + this._reflectionCubeMap.coordinatesMode = 3; + if (this.options.setSceneEnvironmentTexture) { + this._xrSessionManager.scene.environmentTexture = this._reflectionCubeMap; + } + } + this._xrLightProbe.addEventListener("reflectionchange", this._updateReflectionCubeMap); + } + }); + return true; + } + /** + * detach this feature. + * Will usually be called by the features manager + * + * @returns true if successful. + */ + detach() { + const detached = super.detach(); + if (this._xrLightProbe !== null && !this.options.disableCubeMapReflection) { + this._xrLightProbe.removeEventListener("reflectionchange", this._updateReflectionCubeMap); + this._xrLightProbe = null; + } + this._canvasContext = null; + this._xrLightEstimate = null; + // When the session ends (on detach) we must clear our XRWebGLBinging instance, which references the ended session. + this._xrWebGLBinding = null; + return detached; + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + super.dispose(); + this.onReflectionCubeMapUpdatedObservable.clear(); + if (this.directionalLight) { + this.directionalLight.dispose(); + this.directionalLight = null; + } + if (this._reflectionCubeMap !== null) { + if (this._reflectionCubeMap._texture) { + this._reflectionCubeMap._texture.dispose(); + } + this._reflectionCubeMap.dispose(); + this._reflectionCubeMap = null; + } + } + _onXRFrame(_xrFrame) { + if (this._xrLightProbe !== null) { + if (this.options.lightEstimationPollInterval) { + const now = Date.now(); + if (now - this._lightEstimationPollTime < this.options.lightEstimationPollInterval) { + return; + } + this._lightEstimationPollTime = now; + } + this._xrLightEstimate = _xrFrame.getLightEstimate(this._xrLightProbe); + if (this._xrLightEstimate) { + this._intensity = Math.max(1.0, this._xrLightEstimate.primaryLightIntensity.x, this._xrLightEstimate.primaryLightIntensity.y, this._xrLightEstimate.primaryLightIntensity.z); + const rhsFactor = this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1; + // recreate the vector caches, so that the last one provided to the user will persist + if (this.options.disableVectorReuse) { + this._lightDirection = new Vector3(); + this._lightColor = new Color3(); + if (this.directionalLight) { + this.directionalLight.direction = this._lightDirection; + this.directionalLight.diffuse = this._lightColor; + } + } + this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x, this._xrLightEstimate.primaryLightDirection.y, this._xrLightEstimate.primaryLightDirection.z * rhsFactor); + this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x / this._intensity, this._xrLightEstimate.primaryLightIntensity.y / this._intensity, this._xrLightEstimate.primaryLightIntensity.z / this._intensity); + this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients); + if (this._reflectionCubeMap && !this.options.disableSphericalPolynomial) { + this._reflectionCubeMap.sphericalPolynomial = this._reflectionCubeMap.sphericalPolynomial || new SphericalPolynomial(); + this._reflectionCubeMap.sphericalPolynomial?.updateFromHarmonics(this._sphericalHarmonics); + } + // direction from instead of direction to + this._lightDirection.negateInPlace(); + // set the values after calculating them + if (this.directionalLight) { + this.directionalLight.direction.copyFrom(this._lightDirection); + this.directionalLight.intensity = Math.min(this._intensity, 1.0); + this.directionalLight.diffuse.copyFrom(this._lightColor); + } + } + } + } +} +/** + * The module's name + */ +WebXRLightEstimation.Name = WebXRFeatureName.LIGHT_ESTIMATION; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRLightEstimation.Version = 1; +// register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRLightEstimation.Name, (xrSessionManager, options) => { + return () => new WebXRLightEstimation(xrSessionManager, options); +}, WebXRLightEstimation.Version, false); + +/** + * The WebXR Eye Tracking feature grabs eye data from the device and provides it in an easy-access format. + * Currently only enabled for BabylonNative applications. + */ +class WebXREyeTracking extends WebXRAbstractFeature { + /** + * Creates a new instance of the XR eye tracking feature. + * @param _xrSessionManager An instance of WebXRSessionManager. + */ + constructor(_xrSessionManager) { + super(_xrSessionManager); + /** + * This observable will notify registered observers when eye tracking starts + */ + this.onEyeTrackingStartedObservable = new Observable(); + /** + * This observable will notify registered observers when eye tracking ends + */ + this.onEyeTrackingEndedObservable = new Observable(); + /** + * This observable will notify registered observers on each frame that has valid tracking + */ + this.onEyeTrackingFrameUpdateObservable = new Observable(); + this._eyeTrackingStartListener = (event) => { + this._latestEyeSpace = event.gazeSpace; + this._gazeRay = new Ray(Vector3.Zero(), Vector3.Forward()); + this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay); + }; + this._eyeTrackingEndListener = () => { + this._latestEyeSpace = null; + this._gazeRay = null; + this.onEyeTrackingEndedObservable.notifyObservers(); + }; + this.xrNativeFeatureName = "eye-tracking"; + if (this._xrSessionManager.session) { + this._init(); + } + else { + this._xrSessionManager.onXRSessionInit.addOnce(() => { + this._init(); + }); + } + } + /** + * Dispose this feature and all of the resources attached. + */ + dispose() { + super.dispose(); + this._xrSessionManager.session.removeEventListener("eyetrackingstart", this._eyeTrackingStartListener); + this._xrSessionManager.session.removeEventListener("eyetrackingend", this._eyeTrackingEndListener); + this.onEyeTrackingStartedObservable.clear(); + this.onEyeTrackingEndedObservable.clear(); + this.onEyeTrackingFrameUpdateObservable.clear(); + } + /** + * Returns whether the gaze data is valid or not + * @returns true if the data is valid + */ + get isEyeGazeValid() { + return !!this._gazeRay; + } + /** + * Get a reference to the gaze ray. This data is valid while eye tracking persists, and will be set to null when gaze data is no longer available + * @returns a reference to the gaze ray if it exists and is valid, returns null otherwise. + */ + getEyeGaze() { + return this._gazeRay; + } + _onXRFrame(frame) { + if (!this.attached || !frame) { + return; + } + if (this._latestEyeSpace && this._gazeRay) { + const pose = frame.getPose(this._latestEyeSpace, this._xrSessionManager.referenceSpace); + if (pose) { + this._gazeRay.origin.set(pose.transform.position.x, pose.transform.position.y, pose.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor); + const quat = pose.transform.orientation; + TmpVectors.Quaternion[0].set(quat.x, quat.y, quat.z, quat.w); + if (!this._xrSessionManager.scene.useRightHandedSystem) { + this._gazeRay.origin.z *= -1; + TmpVectors.Quaternion[0].z *= -1; + TmpVectors.Quaternion[0].w *= -1; + Vector3.LeftHandedForwardReadOnly.rotateByQuaternionToRef(TmpVectors.Quaternion[0], this._gazeRay.direction); + } + else { + Vector3.RightHandedForwardReadOnly.rotateByQuaternionToRef(TmpVectors.Quaternion[0], this._gazeRay.direction); + } + this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay); + } + } + } + _init() { + // Only supported by BabylonNative + if (this._xrSessionManager.isNative) { + this._xrSessionManager.session.addEventListener("eyetrackingstart", this._eyeTrackingStartListener); + this._xrSessionManager.session.addEventListener("eyetrackingend", this._eyeTrackingEndListener); + } + } +} +/** + * The module's name + */ +WebXREyeTracking.Name = WebXRFeatureName.EYE_TRACKING; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXREyeTracking.Version = 1; +WebXRFeaturesManager.AddWebXRFeature(WebXREyeTracking.Name, (xrSessionManager) => { + return () => new WebXREyeTracking(xrSessionManager); +}, WebXREyeTracking.Version, false); + +class CircleBuffer { + constructor(numSamples, initializer) { + this._samples = []; + this._idx = 0; + for (let idx = 0; idx < numSamples; ++idx) { + this._samples.push(initializer ? initializer() : Vector2.Zero()); + } + } + get length() { + return this._samples.length; + } + push(x, y) { + this._idx = (this._idx + this._samples.length - 1) % this._samples.length; + this.at(0).copyFromFloats(x, y); + } + at(idx) { + if (idx >= this._samples.length) { + throw new Error("Index out of bounds"); + } + return this._samples[(this._idx + idx) % this._samples.length]; + } +} +class FirstStepDetector { + constructor() { + this._samples = new CircleBuffer(20); + this._entropy = 0; + this.onFirstStepDetected = new Observable(); + } + update(posX, posY, forwardX, forwardY) { + this._samples.push(posX, posY); + const origin = this._samples.at(0); + this._entropy *= this._entropyDecayFactor; + this._entropy += Vector2.Distance(origin, this._samples.at(1)); + if (this._entropy > this._entropyThreshold) { + return; + } + let samePointIdx; + for (samePointIdx = this._samePointCheckStartIdx; samePointIdx < this._samples.length; ++samePointIdx) { + if (Vector2.DistanceSquared(origin, this._samples.at(samePointIdx)) < this._samePointSquaredDistanceThreshold) { + break; + } + } + if (samePointIdx === this._samples.length) { + return; + } + let apexDistSquared = -1; + let apexIdx = 0; + for (let distSquared, idx = 1; idx < samePointIdx; ++idx) { + distSquared = Vector2.DistanceSquared(origin, this._samples.at(idx)); + if (distSquared > apexDistSquared) { + apexIdx = idx; + apexDistSquared = distSquared; + } + } + if (apexDistSquared < this._apexSquaredDistanceThreshold) { + return; + } + const apex = this._samples.at(apexIdx); + const axis = apex.subtract(origin); + axis.normalize(); + const vec = TmpVectors.Vector2[0]; + let dot; + let sample; + let sumSquaredProjectionDistances = 0; + for (let idx = 1; idx < samePointIdx; ++idx) { + sample = this._samples.at(idx); + sample.subtractToRef(origin, vec); + dot = Vector2.Dot(axis, vec); + sumSquaredProjectionDistances += vec.lengthSquared() - dot * dot; + } + if (sumSquaredProjectionDistances > samePointIdx * this._squaredProjectionDistanceThreshold) { + return; + } + const forwardVec = TmpVectors.Vector3[0]; + forwardVec.set(forwardX, forwardY, 0); + const axisVec = TmpVectors.Vector3[1]; + axisVec.set(axis.x, axis.y, 0); + const isApexLeft = Vector3.Cross(forwardVec, axisVec).z > 0; + const leftApex = origin.clone(); + const rightApex = origin.clone(); + apex.subtractToRef(origin, axis); + if (isApexLeft) { + axis.scaleAndAddToRef(this._axisToApexShrinkFactor, leftApex); + axis.scaleAndAddToRef(this._axisToApexExtendFactor, rightApex); + } + else { + axis.scaleAndAddToRef(this._axisToApexExtendFactor, leftApex); + axis.scaleAndAddToRef(this._axisToApexShrinkFactor, rightApex); + } + this.onFirstStepDetected.notifyObservers({ + leftApex: leftApex, + rightApex: rightApex, + currentPosition: origin, + currentStepDirection: isApexLeft ? "right" : "left", + }); + } + reset() { + for (let idx = 0; idx < this._samples.length; ++idx) { + this._samples.at(idx).copyFromFloats(0, 0); + } + } + get _samePointCheckStartIdx() { + return Math.floor(this._samples.length / 3); + } + get _samePointSquaredDistanceThreshold() { + return 0.03 * 0.03; + } + get _apexSquaredDistanceThreshold() { + return 0.09 * 0.09; + } + get _squaredProjectionDistanceThreshold() { + return 0.03 * 0.03; + } + get _axisToApexShrinkFactor() { + return 0.8; + } + get _axisToApexExtendFactor() { + return -1.6; + } + get _entropyDecayFactor() { + return 0.93; + } + get _entropyThreshold() { + return 0.4; + } +} +class WalkingTracker { + constructor(leftApex, rightApex, currentPosition, currentStepDirection) { + this._leftApex = new Vector2(); + this._rightApex = new Vector2(); + this._currentPosition = new Vector2(); + this._axis = new Vector2(); + this._axisLength = -1; + this._forward = new Vector2(); + this._steppingLeft = false; + this._t = -1; + this._maxT = -1; + this._maxTPosition = new Vector2(); + this._vitality = 0; + this.onMovement = new Observable(); + this.onFootfall = new Observable(); + this._reset(leftApex, rightApex, currentPosition, currentStepDirection === "left"); + } + _reset(leftApex, rightApex, currentPosition, steppingLeft) { + this._leftApex.copyFrom(leftApex); + this._rightApex.copyFrom(rightApex); + this._steppingLeft = steppingLeft; + if (this._steppingLeft) { + this._leftApex.subtractToRef(this._rightApex, this._axis); + this._forward.copyFromFloats(-this._axis.y, this._axis.x); + } + else { + this._rightApex.subtractToRef(this._leftApex, this._axis); + this._forward.copyFromFloats(this._axis.y, -this._axis.x); + } + this._axisLength = this._axis.length(); + this._forward.scaleInPlace(1 / this._axisLength); + this._updateTAndVitality(currentPosition.x, currentPosition.y); + this._maxT = this._t; + this._maxTPosition.copyFrom(currentPosition); + this._vitality = 1; + } + _updateTAndVitality(x, y) { + this._currentPosition.copyFromFloats(x, y); + if (this._steppingLeft) { + this._currentPosition.subtractInPlace(this._rightApex); + } + else { + this._currentPosition.subtractInPlace(this._leftApex); + } + const priorT = this._t; + const dot = Vector2.Dot(this._currentPosition, this._axis); + this._t = dot / (this._axisLength * this._axisLength); + const projDistSquared = this._currentPosition.lengthSquared() - (dot / this._axisLength) * (dot / this._axisLength); + // TODO: Extricate the magic. + this._vitality *= 0.92 - 100 * Math.max(projDistSquared - 0.0016, 0) + Math.max(this._t - priorT, 0); + } + update(x, y) { + if (this._vitality < this._vitalityThreshold) { + return false; + } + const priorT = this._t; + this._updateTAndVitality(x, y); + if (this._t > this._maxT) { + this._maxT = this._t; + this._maxTPosition.copyFromFloats(x, y); + } + if (this._vitality < this._vitalityThreshold) { + return false; + } + if (this._t > priorT) { + this.onMovement.notifyObservers({ deltaT: this._t - priorT }); + if (priorT < 0.5 && this._t >= 0.5) { + this.onFootfall.notifyObservers({ foot: this._steppingLeft ? "left" : "right" }); + } + } + if (this._t < 0.95 * this._maxT) { + this._currentPosition.copyFromFloats(x, y); + if (this._steppingLeft) { + this._leftApex.copyFrom(this._maxTPosition); + } + else { + this._rightApex.copyFrom(this._maxTPosition); + } + this._reset(this._leftApex, this._rightApex, this._currentPosition, !this._steppingLeft); + } + if (this._axisLength < 0.03) { + return false; + } + return true; + } + get _vitalityThreshold() { + return 0.1; + } + get forward() { + return this._forward; + } +} +class Walker { + static get _MillisecondsPerUpdate() { + // 15 FPS + return 1000 / 15; + } + constructor(engine) { + this._detector = new FirstStepDetector(); + this._walker = null; + this._movement = new Vector2(); + this._millisecondsSinceLastUpdate = Walker._MillisecondsPerUpdate; + this.movementThisFrame = Vector3.Zero(); + this._engine = engine; + this._detector.onFirstStepDetected.add((event) => { + if (!this._walker) { + this._walker = new WalkingTracker(event.leftApex, event.rightApex, event.currentPosition, event.currentStepDirection); + this._walker.onFootfall.add(() => { + Logger.Log("Footfall!"); + }); + this._walker.onMovement.add((event) => { + this._walker.forward.scaleAndAddToRef(0.024 * event.deltaT, this._movement); + }); + } + }); + } + update(position, forward) { + forward.y = 0; + forward.normalize(); + // Enforce reduced framerate + this._millisecondsSinceLastUpdate += this._engine.getDeltaTime(); + if (this._millisecondsSinceLastUpdate >= Walker._MillisecondsPerUpdate) { + this._millisecondsSinceLastUpdate -= Walker._MillisecondsPerUpdate; + this._detector.update(position.x, position.z, forward.x, forward.z); + if (this._walker) { + const updated = this._walker.update(position.x, position.z); + if (!updated) { + this._walker = null; + } + } + this._movement.scaleInPlace(0.85); + } + this.movementThisFrame.set(this._movement.x, 0, this._movement.y); + } +} +/** + * A module that will enable VR locomotion by detecting when the user walks in place. + */ +class WebXRWalkingLocomotion extends WebXRAbstractFeature { + /** + * The module's name. + */ + static get Name() { + return WebXRFeatureName.WALKING_LOCOMOTION; + } + /** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number has no external basis. + */ + static get Version() { + return 1; + } + /** + * The target to be articulated by walking locomotion. + * When the walking locomotion feature detects walking in place, this element's + * X and Z coordinates will be modified to reflect locomotion. This target should + * be either the XR space's origin (i.e., the parent node of the WebXRCamera) or + * the WebXRCamera itself. Note that the WebXRCamera path will modify the position + * of the WebXRCamera directly and is thus discouraged. + */ + get locomotionTarget() { + return this._locomotionTarget; + } + /** + * The target to be articulated by walking locomotion. + * When the walking locomotion feature detects walking in place, this element's + * X and Z coordinates will be modified to reflect locomotion. This target should + * be either the XR space's origin (i.e., the parent node of the WebXRCamera) or + * the WebXRCamera itself. Note that the WebXRCamera path will modify the position + * of the WebXRCamera directly and is thus discouraged. + */ + set locomotionTarget(locomotionTarget) { + this._locomotionTarget = locomotionTarget; + this._isLocomotionTargetWebXRCamera = this._locomotionTarget.getClassName() === "WebXRCamera"; + } + /** + * Construct a new Walking Locomotion feature. + * @param sessionManager manager for the current XR session + * @param options creation options, prominently including the vector target for locomotion + */ + constructor(sessionManager, options) { + super(sessionManager); + this._up = new Vector3(); + this._forward = new Vector3(); + this._position = new Vector3(); + this._movement = new Vector3(); + this._sessionManager = sessionManager; + this.locomotionTarget = options.locomotionTarget; + if (this._isLocomotionTargetWebXRCamera) { + Logger.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended"); + } + } + /** + * Checks whether this feature is compatible with the current WebXR session. + * Walking locomotion is only compatible with "immersive-vr" sessions. + * @returns true if compatible, false otherwise + */ + isCompatible() { + return this._sessionManager.sessionMode === undefined || this._sessionManager.sessionMode === "immersive-vr"; + } + /** + * Attaches the feature. + * Typically called automatically by the features manager. + * @returns true if attach succeeded, false otherwise + */ + attach() { + if (!this.isCompatible || !super.attach()) { + return false; + } + this._walker = new Walker(this._sessionManager.scene.getEngine()); + return true; + } + /** + * Detaches the feature. + * Typically called automatically by the features manager. + * @returns true if detach succeeded, false otherwise + */ + detach() { + if (!super.detach()) { + return false; + } + this._walker = null; + return true; + } + _onXRFrame(frame) { + const pose = frame.getViewerPose(this._sessionManager.baseReferenceSpace); + if (!pose) { + return; + } + const handednessScalar = this.locomotionTarget.getScene().useRightHandedSystem ? 1 : -1; + const m = pose.transform.matrix; + this._up.copyFromFloats(m[4], m[5], handednessScalar * m[6]); + this._forward.copyFromFloats(m[8], m[9], handednessScalar * m[10]); + this._position.copyFromFloats(m[12], m[13], handednessScalar * m[14]); + // Compute the nape position + this._forward.scaleAndAddToRef(0.05, this._position); + this._up.scaleAndAddToRef(-0.05, this._position); + this._walker.update(this._position, this._forward); + this._movement.copyFrom(this._walker.movementThisFrame); + if (!this._isLocomotionTargetWebXRCamera) { + Vector3.TransformNormalToRef(this._movement, this.locomotionTarget.getWorldMatrix(), this._movement); + } + this.locomotionTarget.position.addInPlace(this._movement); + } +} +//register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRWalkingLocomotion.Name, (xrSessionManager, options) => { + return () => new WebXRWalkingLocomotion(xrSessionManager, options); +}, WebXRWalkingLocomotion.Version, false); + +/** + * Wraps xr composition layers. + * @internal + */ +class WebXRCompositionLayerWrapper extends WebXRLayerWrapper { + constructor(getWidth, getHeight, layer, layerType, isMultiview, createRTTProvider, _originalInternalTexture = null) { + super(getWidth, getHeight, layer, layerType, createRTTProvider); + this.getWidth = getWidth; + this.getHeight = getHeight; + this.layer = layer; + this.layerType = layerType; + this.isMultiview = isMultiview; + this.createRTTProvider = createRTTProvider; + this._originalInternalTexture = _originalInternalTexture; + } +} +/** + * Provides render target textures and other important rendering information for a given XRCompositionLayer. + * @internal + */ +class WebXRCompositionLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider { + constructor(_xrSessionManager, _xrWebGLBinding, layerWrapper) { + super(_xrSessionManager.scene, layerWrapper); + this._xrSessionManager = _xrSessionManager; + this._xrWebGLBinding = _xrWebGLBinding; + this.layerWrapper = layerWrapper; + this._lastSubImages = new Map(); + /** + * Fires every time a new render target texture is created (either for eye, for view, or for the entire frame) + */ + this.onRenderTargetTextureCreatedObservable = new Observable(); + this._compositionLayer = layerWrapper.layer; + } + _getRenderTargetForSubImage(subImage, eye = "none") { + const lastSubImage = this._lastSubImages.get(eye); + const eyeIndex = eye == "right" ? 1 : 0; + const colorTextureWidth = subImage.colorTextureWidth ?? subImage.textureWidth; + const colorTextureHeight = subImage.colorTextureHeight ?? subImage.textureHeight; + if (!this._renderTargetTextures[eyeIndex] || lastSubImage?.textureWidth !== colorTextureWidth || lastSubImage?.textureHeight !== colorTextureHeight) { + let depthStencilTexture; + const depthStencilTextureWidth = subImage.depthStencilTextureWidth ?? colorTextureWidth; + const depthStencilTextureHeight = subImage.depthStencilTextureHeight ?? colorTextureHeight; + if (colorTextureWidth === depthStencilTextureWidth || colorTextureHeight === depthStencilTextureHeight) { + depthStencilTexture = subImage.depthStencilTexture; + } + this._renderTargetTextures[eyeIndex] = this._createRenderTargetTexture(colorTextureWidth, colorTextureHeight, null, subImage.colorTexture, depthStencilTexture, this.layerWrapper.isMultiview); + this._framebufferDimensions = { + framebufferWidth: colorTextureWidth, + framebufferHeight: colorTextureHeight, + }; + this.onRenderTargetTextureCreatedObservable.notifyObservers({ texture: this._renderTargetTextures[eyeIndex], eye }); + } + this._lastSubImages.set(eye, subImage); + return this._renderTargetTextures[eyeIndex]; + } + _getSubImageForEye(eye) { + const currentFrame = this._xrSessionManager.currentFrame; + if (currentFrame) { + return this._xrWebGLBinding.getSubImage(this._compositionLayer, currentFrame, eye); + } + return null; + } + getRenderTargetTextureForEye(eye) { + const subImage = this._getSubImageForEye(eye); + if (subImage) { + return this._getRenderTargetForSubImage(subImage, eye); + } + return null; + } + getRenderTargetTextureForView(view) { + return this.getRenderTargetTextureForEye(view?.eye); + } + _setViewportForSubImage(viewport, subImage) { + const textureWidth = subImage.colorTextureWidth ?? subImage.textureWidth; + const textureHeight = subImage.colorTextureHeight ?? subImage.textureHeight; + const xrViewport = subImage.viewport; + viewport.x = xrViewport.x / textureWidth; + viewport.y = xrViewport.y / textureHeight; + viewport.width = xrViewport.width / textureWidth; + viewport.height = xrViewport.height / textureHeight; + } + trySetViewportForView(viewport, view) { + const subImage = this._lastSubImages.get(view.eye) || this._getSubImageForEye(view.eye); + if (subImage) { + this._setViewportForSubImage(viewport, subImage); + return true; + } + return false; + } +} + +/** + * Wraps xr projection layers. + * @internal + */ +class WebXRProjectionLayerWrapper extends WebXRCompositionLayerWrapper { + constructor(layer, isMultiview, xrGLBinding) { + super(() => layer.textureWidth, () => layer.textureHeight, layer, "XRProjectionLayer", isMultiview, (sessionManager) => new WebXRProjectionLayerRenderTargetTextureProvider(sessionManager, xrGLBinding, this)); + this.layer = layer; + } +} +/** + * Provides render target textures and other important rendering information for a given XRProjectionLayer. + * @internal + */ +class WebXRProjectionLayerRenderTargetTextureProvider extends WebXRCompositionLayerRenderTargetTextureProvider { + constructor(_xrSessionManager, _xrWebGLBinding, layerWrapper) { + super(_xrSessionManager, _xrWebGLBinding, layerWrapper); + this.layerWrapper = layerWrapper; + this._projectionLayer = layerWrapper.layer; + } + _getSubImageForView(view) { + return this._xrWebGLBinding.getViewSubImage(this._projectionLayer, view); + } + getRenderTargetTextureForView(view) { + return this._getRenderTargetForSubImage(this._getSubImageForView(view), view.eye); + } + getRenderTargetTextureForEye(eye) { + const lastSubImage = this._lastSubImages.get(eye); + if (lastSubImage) { + return this._getRenderTargetForSubImage(lastSubImage, eye); + } + return null; + } + trySetViewportForView(viewport, view) { + const subImage = this._lastSubImages.get(view.eye) || this._getSubImageForView(view); + if (subImage) { + this._setViewportForSubImage(viewport, subImage); + return true; + } + return false; + } +} +const defaultXRProjectionLayerInit = { + textureType: "texture", + colorFormat: 0x1908 /* WebGLRenderingContext.RGBA */, + depthFormat: 0x88f0 /* WebGLRenderingContext.DEPTH24_STENCIL8 */, + scaleFactor: 1.0, + clearOnAccess: false, +}; + +const defaultXRWebGLLayerInit = {}; +/** + * Exposes the WebXR Layers API. + */ +class WebXRLayers extends WebXRAbstractFeature { + constructor(_xrSessionManager, _options = {}) { + super(_xrSessionManager); + this._options = _options; + /** + * Already-created layers + */ + this._existingLayers = []; + this._isMultiviewEnabled = false; + this._projectionLayerInitialized = false; + this._compositionLayerTextureMapping = new WeakMap(); + this._layerToRTTProviderMapping = new WeakMap(); + this.xrNativeFeatureName = "layers"; + } + /** + * Attach this feature. + * Will usually be called by the features manager. + * + * @returns true if successful. + */ + attach() { + if (!super.attach()) { + return false; + } + const engine = this._xrSessionManager.scene.getEngine(); + this._glContext = engine._gl; + this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, this._glContext); + this._existingLayers.length = 0; + const projectionLayerInit = { ...defaultXRProjectionLayerInit, ...this._options.projectionLayerInit }; + this._isMultiviewEnabled = this._options.preferMultiviewOnInit && engine.getCaps().multiview; + this.createProjectionLayer(projectionLayerInit /*, projectionLayerMultiview*/); + this._projectionLayerInitialized = true; + return true; + } + detach() { + if (!super.detach()) { + return false; + } + this._existingLayers.forEach((layer) => { + layer.dispose(); + }); + this._existingLayers.length = 0; + this._projectionLayerInitialized = false; + return true; + } + /** + * Creates a new XRWebGLLayer. + * @param params an object providing configuration options for the new XRWebGLLayer + * @returns the XRWebGLLayer + */ + createXRWebGLLayer(params = defaultXRWebGLLayerInit) { + const layer = new XRWebGLLayer(this._xrSessionManager.session, this._glContext, params); + return new WebXRWebGLLayerWrapper(layer); + } + _validateLayerInit(params, multiview = this._isMultiviewEnabled) { + // check if we are in session + if (!this._xrSessionManager.inXRSession) { + throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers."); + } + if (multiview && params.textureType !== "texture-array") { + throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'."); + } + // TODO (rgerd): Support RTT's that are bound to sub-images in the texture array. + if (!multiview && params.textureType === "texture-array") { + throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'."); + } + } + _extendXRLayerInit(params, multiview = this._isMultiviewEnabled) { + if (multiview) { + params.textureType = "texture-array"; + } + return params; + } + /** + * Creates a new XRProjectionLayer. + * @param params an object providing configuration options for the new XRProjectionLayer. + * @param multiview whether the projection layer should render with multiview. Will be tru automatically if the extension initialized with multiview. + * @returns the projection layer + */ + createProjectionLayer(params = defaultXRProjectionLayerInit, multiview = this._isMultiviewEnabled) { + this._extendXRLayerInit(params, multiview); + this._validateLayerInit(params, multiview); + const projLayer = this._xrWebGLBinding.createProjectionLayer(params); + const layer = new WebXRProjectionLayerWrapper(projLayer, multiview, this._xrWebGLBinding); + this.addXRSessionLayer(layer); + return layer; + } + /** + * Note about making it private - this function will be exposed once I decide on a proper API to support all of the XR layers' options + * @param options an object providing configuration options for the new XRQuadLayer. + * @param babylonTexture the texture to display in the layer + * @returns the quad layer + */ + _createQuadLayer(options = { params: {} }, babylonTexture) { + this._extendXRLayerInit(options.params, false); + const width = this._existingLayers[0].layer.textureWidth; + const height = this._existingLayers[0].layer.textureHeight; + const populatedParams = { + space: this._xrSessionManager.referenceSpace, + viewPixelWidth: width, + viewPixelHeight: height, + clearOnAccess: true, + ...options.params, + }; + this._validateLayerInit(populatedParams, false); + const quadLayer = this._xrWebGLBinding.createQuadLayer(populatedParams); + quadLayer.width = this._isMultiviewEnabled ? 1 : 2; + quadLayer.height = 1; + // this wrapper is not really needed, but it's here for consistency + const wrapper = new WebXRCompositionLayerWrapper(() => quadLayer.width, () => quadLayer.height, quadLayer, "XRQuadLayer", false, (sessionManager) => new WebXRCompositionLayerRenderTargetTextureProvider(sessionManager, this._xrWebGLBinding, wrapper)); + if (babylonTexture) { + this._compositionLayerTextureMapping.set(quadLayer, babylonTexture); + } + const rtt = wrapper.createRenderTargetTextureProvider(this._xrSessionManager); + this._layerToRTTProviderMapping.set(quadLayer, rtt); + this.addXRSessionLayer(wrapper); + return wrapper; + } + /** + * @experimental + * This will support full screen ADT when used with WebXR Layers. This API might change in the future. + * Note that no interaction will be available with the ADT when using this method + * @param texture the texture to display in the layer + * @param options optional parameters for the layer + * @returns a composition layer containing the texture + */ + addFullscreenAdvancedDynamicTexture(texture, options = { distanceFromHeadset: 1.5 }) { + const wrapper = this._createQuadLayer({ + params: { + space: this._xrSessionManager.viewerReferenceSpace, + textureType: "texture", + layout: "mono", + }, + }, texture); + const layer = wrapper.layer; + const distance = Math.max(0.1, options.distanceFromHeadset); + const pos = { x: 0, y: 0, z: -distance }; + const orient = { x: 0, y: 0, z: 0, w: 1 }; + layer.transform = new XRRigidTransform(pos, orient); + const rttProvider = this._layerToRTTProviderMapping.get(layer); + if (!rttProvider) { + throw new Error("Could not find the RTT provider for the layer"); + } + const babylonLayer = this._xrSessionManager.scene.layers.find((babylonLayer) => { + return babylonLayer.texture === texture; + }); + if (!babylonLayer) { + throw new Error("Could not find the babylon layer for the texture"); + } + rttProvider.onRenderTargetTextureCreatedObservable.add((data) => { + if (data.eye && data.eye === "right") { + return; + } + data.texture.clearColor = new Color4(0, 0, 0, 0); + babylonLayer.renderTargetTextures.push(data.texture); + babylonLayer.renderOnlyInRenderTargetTextures = true; + // for stereo (not for gui) it should be onBeforeCameraRenderObservable + this._xrSessionManager.scene.onBeforeRenderObservable.add(() => { + data.texture.render(); + }); + babylonLayer.renderTargetTextures.push(data.texture); + babylonLayer.renderOnlyInRenderTargetTextures = true; + // add it back when the session ends + this._xrSessionManager.onXRSessionEnded.addOnce(() => { + babylonLayer.renderTargetTextures.splice(babylonLayer.renderTargetTextures.indexOf(data.texture), 1); + babylonLayer.renderOnlyInRenderTargetTextures = false; + }); + }); + return wrapper; + } + /** + * @experimental + * This functions allows you to add a lens flare system to the XR scene. + * Note - this will remove the lens flare system from the scene and add it to the XR scene. + * This feature is experimental and might change in the future. + * @param flareSystem the flare system to add + * @returns a composition layer containing the flare system + */ + _addLensFlareSystem(flareSystem) { + const wrapper = this._createQuadLayer({ + params: { + space: this._xrSessionManager.viewerReferenceSpace, + textureType: "texture", + layout: "mono", + }, + }); + const layer = wrapper.layer; + layer.width = 2; + layer.height = 1; + const pos = { x: 0, y: 0, z: -10 }; + const orient = { x: 0, y: 0, z: 0, w: 1 }; + layer.transform = new XRRigidTransform(pos, orient); + // get the rtt wrapper + const rttProvider = this._layerToRTTProviderMapping.get(layer); + if (!rttProvider) { + throw new Error("Could not find the RTT provider for the layer"); + } + // render the flare system to the rtt + rttProvider.onRenderTargetTextureCreatedObservable.add((data) => { + data.texture.clearColor = new Color4(0, 0, 0, 0); + data.texture.customRenderFunction = () => { + flareSystem.render(); + }; + // add to the scene's render targets + // this._xrSessionManager.scene.onBeforeCameraRenderObservable.add(() => { + // data.texture.render(); + // }); + }); + // remove the lens flare system from the scene + this._xrSessionManager.onXRSessionInit.add(() => { + this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(flareSystem), 1); + }); + // add it back when the session ends + this._xrSessionManager.onXRSessionEnded.add(() => { + this._xrSessionManager.scene.lensFlareSystems.push(flareSystem); + }); + return wrapper; + } + /** + * Add a new layer to the already-existing list of layers + * @param wrappedLayer the new layer to add to the existing ones + */ + addXRSessionLayer(wrappedLayer) { + this._existingLayers.push(wrappedLayer); + this.setXRSessionLayers(this._existingLayers); + } + /** + * Sets the layers to be used by the XR session. + * Note that you must call this function with any layers you wish to render to + * since it adds them to the XR session's render state + * (replacing any layers that were added in a previous call to setXRSessionLayers or updateRenderState). + * This method also sets up the session manager's render target texture provider + * as the first layer in the array, which feeds the WebXR camera(s) attached to the session. + * @param wrappedLayers An array of WebXRLayerWrapper, usually returned from the WebXRLayers createLayer functions. + */ + setXRSessionLayers(wrappedLayers = this._existingLayers) { + // this._existingLayers = wrappedLayers; + const renderStateInit = { ...this._xrSessionManager.session.renderState }; + // Clear out the layer-related fields. + renderStateInit.baseLayer = undefined; + renderStateInit.layers = wrappedLayers.map((wrappedLayer) => wrappedLayer.layer); + this._xrSessionManager.updateRenderState(renderStateInit); + if (!this._projectionLayerInitialized) { + this._xrSessionManager._setBaseLayerWrapper(wrappedLayers.length > 0 ? wrappedLayers.at(0) : null); + } + } + isCompatible() { + // TODO (rgerd): Add native support. + return !this._xrSessionManager.isNative && typeof XRWebGLBinding !== "undefined" && !!XRWebGLBinding.prototype.createProjectionLayer; + } + /** + * Dispose this feature and all of the resources attached. + */ + dispose() { + super.dispose(); + } + _onXRFrame(_xrFrame) { + // Replace once the mapped internal texture of each available composition layer, apart from the last one, which is the projection layer that needs an RTT + const layers = this._existingLayers; + for (let i = 0; i < layers.length; ++i) { + const layer = layers[i]; + if (layer.layerType !== "XRProjectionLayer") { + // get the rtt provider + const rttProvider = this._layerToRTTProviderMapping.get(layer.layer); + if (!rttProvider) { + continue; + } + if (rttProvider.layerWrapper.isMultiview) { + // get the views, if we are in multiview + const pose = _xrFrame.getViewerPose(this._xrSessionManager.referenceSpace); + if (pose) { + const views = pose.views; + for (let j = 0; j < views.length; ++j) { + const view = views[j]; + rttProvider.getRenderTargetTextureForView(view); + } + } + } + else { + rttProvider.getRenderTargetTextureForView(); + } + } + } + } +} +/** + * The module's name + */ +WebXRLayers.Name = WebXRFeatureName.LAYERS; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRLayers.Version = 1; +//register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRLayers.Name, (xrSessionManager, options) => { + return () => new WebXRLayers(xrSessionManager, options); +}, WebXRLayers.Version, false); + +class DepthSensingMaterialDefines extends MaterialDefines { + constructor() { + super(...arguments); + /** + * Is the feature enabled + */ + this.DEPTH_SENSING = false; + /** + * Is the texture type provided as a texture array + */ + this.DEPTH_SENSING_TEXTURE_ARRAY = false; + /** + * Is the texture type provided as Alpha-Luminance (unpacked differently on the shader) + */ + this.DEPTH_SENSING_TEXTURE_AL = false; + /** + * Should the shader discard the pixel if the depth is less than the asset depth + * Will lead to better performance. the other variant is to change the color based on a tolerance factor + */ + this.DEPTH_SENSING_DISCARD = true; + } +} +let isPluginEnabled = false; +let depthTexture = null; +let alphaLuminanceTexture = false; +const screenSize = { width: 512, height: 512 }; +const shaderViewport = { x: 0, y: 0, width: 1, height: 1 }; +let globalRawValueToMeters = 1; +let viewIndex = 0; +let enableDiscard = true; +const uvTransform = Matrix.Identity(); +const managedMaterialPlugins = []; +/** + * @internal + */ +class WebXRDepthSensingMaterialPlugin extends MaterialPluginBase { + /** @internal */ + _markAllDefinesAsDirty() { + this._enable(this._isEnabled); + this.markAllDefinesAsDirty(); + } + /** + * Gets whether the mesh debug plugin is enabled in the material. + */ + get isEnabled() { + return this._isEnabled; + } + /** + * Sets whether the mesh debug plugin is enabled in the material. + * @param value enabled + */ + set isEnabled(value) { + if (this._isEnabled === value) { + return; + } + this._isEnabled = value; + this._markAllDefinesAsDirty(); + } + /** + * Gets a boolean indicating that the plugin is compatible with a given shader language. + * @param shaderLanguage The shader language to use. + * @returns true if the plugin is compatible with the shader language + */ + isCompatible(shaderLanguage) { + switch (shaderLanguage) { + case 0 /* ShaderLanguage.GLSL */: + return true; + default: + // no webgpu for webxr yet, however - if this is not true the plugin fails to load. + // webxr is currently only supported on webgl, and the plugin is disabled per default. + return true; + } + } + constructor(material) { + super(material, "DepthSensing", 222, new DepthSensingMaterialDefines()); + this._isEnabled = false; + this._varColorName = material instanceof PBRBaseMaterial ? "finalColor" : "color"; + managedMaterialPlugins.push(this); + } + /** + * Prepare the defines + * @param defines the defines + */ + prepareDefines(defines) { + defines.DEPTH_SENSING = !!depthTexture && isPluginEnabled; + defines.DEPTH_SENSING_TEXTURE_ARRAY = depthTexture?.is2DArray ?? false; + defines.DEPTH_SENSING_TEXTURE_AL = alphaLuminanceTexture; + defines.DEPTH_SENSING_DISCARD = enableDiscard; + } + getUniforms() { + return { + // first, define the UBO with the correct type and size. + ubo: [ + { name: "ds_invScreenSize", size: 2, type: "vec2" }, + { name: "ds_rawValueToMeters", size: 1, type: "float" }, + { name: "ds_viewIndex", size: 1, type: "float" }, + { name: "ds_shaderViewport", size: 4, type: "vec4" }, + { name: "ds_uvTransform", size: 16, type: "mat4" }, + ], + // now, on the fragment shader, add the uniform itself in case uniform buffers are not supported by the engine + fragment: `#ifdef DEPTH_SENSING + uniform vec2 ds_invScreenSize; + uniform float ds_rawValueToMeters; + uniform float ds_viewIndex; + uniform vec4 ds_shaderViewport; + uniform mat4 ds_uvTransform; + #endif + `, + }; + } + getSamplers(samplers) { + samplers.push("ds_depthSampler"); + } + bindForSubMesh(uniformBuffer) { + if (isPluginEnabled && depthTexture) { + uniformBuffer.updateFloat2("ds_invScreenSize", 1 / screenSize.width, 1 / screenSize.height); + uniformBuffer.updateFloat("ds_rawValueToMeters", globalRawValueToMeters); + uniformBuffer.updateFloat("ds_viewIndex", viewIndex); + uniformBuffer.updateFloat4("ds_shaderViewport", shaderViewport.x, shaderViewport.y, shaderViewport.width, shaderViewport.height); + uniformBuffer.setTexture("ds_depthSampler", depthTexture); + uniformBuffer.updateMatrix("ds_uvTransform", uvTransform); + } + } + getClassName() { + return "DepthSensingMaterialPlugin"; + } + getCustomCode(shaderType) { + return shaderType === "vertex" + ? { + CUSTOM_VERTEX_MAIN_BEGIN: ` + #ifdef DEPTH_SENSING + #ifdef MULTIVIEW + ds_viewIndexMultiview = float(gl_ViewID_OVR); + #endif + #endif + `, + CUSTOM_VERTEX_DEFINITIONS: ` + #ifdef DEPTH_SENSING + #ifdef MULTIVIEW + varying float ds_viewIndexMultiview; + #endif + #endif + `, + } + : { + CUSTOM_FRAGMENT_DEFINITIONS: ` + #ifdef DEPTH_SENSING + #ifdef DEPTH_SENSING_TEXTURE_ARRAY + uniform highp sampler2DArray ds_depthSampler; + #else + uniform sampler2D ds_depthSampler; + #endif + #ifdef MULTIVIEW + varying float ds_viewIndexMultiview; + #endif + #endif + `, + CUSTOM_FRAGMENT_MAIN_BEGIN: ` +#ifdef DEPTH_SENSING + #ifdef MULTIVIEW + float ds_viewIndexSet = ds_viewIndexMultiview; + vec2 ds_compensation = vec2(0.0, 0.0); + #else + float ds_viewIndexSet = ds_viewIndex; + vec2 ds_compensation = vec2(ds_viewIndexSet, 0.0); + #endif + vec2 ds_baseUv = gl_FragCoord.xy * ds_invScreenSize; + #ifdef DEPTH_SENSING_TEXTURE_ARRAY + vec2 ds_uv = ds_baseUv - ds_compensation; + vec3 ds_depthUv = vec3((ds_uvTransform * vec4(ds_uv, 0.0, 1.0)).xy, ds_viewIndexSet); + #else + vec2 ds_depthUv = (ds_uvTransform * vec4(ds_baseUv.x, 1.0 - ds_baseUv.y, 0.0, 1.0)).xy; + #endif + #ifdef DEPTH_SENSING_TEXTURE_AL + // from alpha-luminance - taken from the explainer + vec2 ds_alphaLuminance = texture(ds_depthSampler, ds_depthUv).ra; + float ds_cameraDepth = dot(ds_alphaLuminance, vec2(255.0, 256.0 * 255.0)); + #else + float ds_cameraDepth = texture(ds_depthSampler, ds_depthUv).r; + #endif + + ds_cameraDepth = ds_cameraDepth * ds_rawValueToMeters; + + float ds_assetDepth = gl_FragCoord.z; + #ifdef DEPTH_SENSING_DISCARD + if(ds_cameraDepth < ds_assetDepth) { + discard; + } + #endif +#endif + `, + CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: ` +#ifdef DEPTH_SENSING + #ifndef DEPTH_SENSING_DISCARD + const float ds_depthTolerancePerM = 0.005; + float ds_occlusion = clamp(1.0 - 0.5 * (ds_cameraDepth - ds_assetDepth) / (ds_depthTolerancePerM * ds_assetDepth) + + 0.5, 0.0, 1.0); + ${this._varColorName} *= (1.0 - ds_occlusion); + #endif +#endif + `, + }; + } + dispose(_forceDisposeTextures) { + const index = managedMaterialPlugins.indexOf(this); + if (index !== -1) { + managedMaterialPlugins.splice(index, 1); + } + super.dispose(_forceDisposeTextures); + } +} +/** + * WebXR Feature for WebXR Depth Sensing Module + * @since 5.49.1 + */ +class WebXRDepthSensing extends WebXRAbstractFeature { + /** + * Width of depth data. If depth data is not exist, returns null. + */ + get width() { + return this._width; + } + /** + * Height of depth data. If depth data is not exist, returns null. + */ + get height() { + return this._height; + } + /** + * Scale factor by which the raw depth values must be multiplied in order to get the depths in meters. + */ + get rawValueToMeters() { + return this._rawValueToMeters; + } + /** + * An XRRigidTransform that needs to be applied when indexing into the depth buffer. + */ + get normDepthBufferFromNormView() { + return this._normDepthBufferFromNormView; + } + /** + * Describes which depth-sensing usage ("cpu" or "gpu") is used. + */ + get depthUsage() { + switch (this._xrSessionManager.session.depthUsage) { + case "cpu-optimized": + return "cpu"; + case "gpu-optimized": + return "gpu"; + } + } + /** + * Describes which depth sensing data format ("ushort" or "float") is used. + */ + get depthDataFormat() { + switch (this._xrSessionManager.session.depthDataFormat) { + case "luminance-alpha": + return "ushort"; + case "float32": + return "float"; + case "unsigned-short": + return "ushort"; + } + } + /** + * Latest cached InternalTexture which containing depth buffer information. + * This can be used when the depth usage is "gpu". + * @deprecated This will be removed in the future. Use latestDepthImageTexture + */ + get latestInternalTexture() { + if (!this._cachedWebGLTexture) { + return null; + } + return this._getInternalTextureFromDepthInfo(); + } + /** + * cached depth buffer + */ + get latestDepthBuffer() { + if (!this._cachedDepthBuffer) { + return null; + } + return this.depthDataFormat === "float" ? new Float32Array(this._cachedDepthBuffer) : new Uint16Array(this._cachedDepthBuffer); + } + /** + * Latest cached Texture of depth image which is made from the depth buffer data. + */ + get latestDepthImageTexture() { + return this._cachedDepthImageTexture; + } + /** + * Creates a new instance of the depth sensing feature + * @param _xrSessionManager the WebXRSessionManager + * @param options options for WebXR Depth Sensing Feature + */ + constructor(_xrSessionManager, options) { + super(_xrSessionManager); + this.options = options; + this._width = null; + this._height = null; + this._rawValueToMeters = null; + this._textureType = null; + this._normDepthBufferFromNormView = null; + this._cachedDepthBuffer = null; + this._cachedWebGLTexture = null; + this._cachedDepthImageTexture = null; + this._onCameraObserver = null; + /** + * Event that notify when `DepthInformation.getDepthInMeters` is available. + * `getDepthInMeters` method needs active XRFrame (not available for cached XRFrame) + */ + this.onGetDepthInMetersAvailable = new Observable(); + this.xrNativeFeatureName = "depth-sensing"; + // https://immersive-web.github.io/depth-sensing/ + Tools.Warn("depth-sensing is an experimental and unstable feature."); + enableDiscard = !options.useToleranceFactorForDepthSensing; + } + /** + * attach this feature + * Will usually be called by the features manager + * @param force should attachment be forced (even when already attached) + * @returns true if successful. + */ + attach(force) { + if (!super.attach(force)) { + return false; + } + const isBothDepthUsageAndFormatNull = this._xrSessionManager.session.depthDataFormat == null || this._xrSessionManager.session.depthUsage == null; + if (isBothDepthUsageAndFormatNull) { + return false; + } + this._glBinding = new XRWebGLBinding(this._xrSessionManager.session, this._xrSessionManager.scene.getEngine()._gl); + isPluginEnabled = !this.options.disableDepthSensingOnMaterials; + if (isPluginEnabled) { + managedMaterialPlugins.forEach((plugin) => { + plugin.isEnabled = true; + }); + this._onCameraObserver = this._xrSessionManager.scene.onBeforeCameraRenderObservable.add((camera) => { + if (!isPluginEnabled) { + return; + } + // make sure this is a webxr camera + if (camera.outputRenderTarget) { + const viewport = camera.rigCameras.length > 0 ? camera.rigCameras[0].viewport : camera.viewport; + screenSize.width = camera.outputRenderTarget.getRenderWidth() / (camera.rigParent ? camera.rigParent.rigCameras.length || 1 : 1); + screenSize.height = camera.outputRenderTarget.getRenderHeight(); + shaderViewport.x = viewport.x; + shaderViewport.y = viewport.y; + shaderViewport.width = viewport.width; + shaderViewport.height = viewport.height; + // find the viewIndex + if (camera.rigParent) { + // should use the viewIndexes array! + viewIndex = camera.isLeftCamera ? 0 : 1; + } + } + }); + } + return true; + } + detach() { + isPluginEnabled = false; + depthTexture = null; + this._cachedWebGLTexture = null; + this._cachedDepthBuffer = null; + managedMaterialPlugins.forEach((plugin) => { + plugin.isEnabled = false; + }); + if (this._onCameraObserver) { + this._xrSessionManager.scene.onBeforeCameraRenderObservable.remove(this._onCameraObserver); + } + return super.detach(); + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + this._cachedDepthImageTexture?.dispose(); + this.onGetDepthInMetersAvailable.clear(); + // cleanup + if (this._onCameraObserver) { + this._xrSessionManager.scene.onBeforeCameraRenderObservable.remove(this._onCameraObserver); + } + } + _onXRFrame(_xrFrame) { + const referenceSPace = this._xrSessionManager.referenceSpace; + const pose = _xrFrame.getViewerPose(referenceSPace); + if (pose == null) { + return; + } + for (const view of pose.views) { + switch (this.depthUsage) { + case "cpu": + this._updateDepthInformationAndTextureCPUDepthUsage(_xrFrame, view, this.depthDataFormat); + break; + case "gpu": + if (!this._glBinding) { + break; + } + this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding, view, this.depthDataFormat); + break; + default: + Tools.Error("Unknown depth usage"); + this.detach(); + break; + } + } + } + _updateDepthInformationAndTextureCPUDepthUsage(frame, view, dataFormat) { + const depthInfo = frame.getDepthInformation(view); + if (depthInfo === null) { + return; + } + const { data, width, height, rawValueToMeters, getDepthInMeters, normDepthBufferFromNormView } = depthInfo; + this._width = width; + this._height = height; + this._rawValueToMeters = rawValueToMeters; + this._cachedDepthBuffer = data; + globalRawValueToMeters = rawValueToMeters; + alphaLuminanceTexture = dataFormat === "luminance-alpha"; + uvTransform.fromArray(normDepthBufferFromNormView.matrix); + // to avoid Illegal Invocation error, bind `this` + this.onGetDepthInMetersAvailable.notifyObservers(getDepthInMeters.bind(depthInfo)); + if (!this._cachedDepthImageTexture) { + this._cachedDepthImageTexture = RawTexture.CreateRTexture(null, width, height, this._xrSessionManager.scene, false, false, Texture.NEAREST_SAMPLINGMODE, 1); + depthTexture = this._cachedDepthImageTexture; + } + let float32Array = null; + switch (dataFormat) { + case "ushort": + case "luminance-alpha": + float32Array = Float32Array.from(new Uint16Array(data)); + break; + case "float": + float32Array = new Float32Array(data); + break; + } + if (float32Array) { + if (this.options.prepareTextureForVisualization) { + float32Array = float32Array.map((val) => val * rawValueToMeters); + } + this._cachedDepthImageTexture.update(float32Array); + } + } + _updateDepthInformationAndTextureWebGLDepthUsage(webglBinding, view, dataFormat) { + const depthInfo = webglBinding.getDepthInformation(view); + if (depthInfo === null) { + return; + } + const { texture, width, height, textureType, rawValueToMeters, normDepthBufferFromNormView } = depthInfo; + globalRawValueToMeters = rawValueToMeters; + alphaLuminanceTexture = dataFormat === "luminance-alpha"; + uvTransform.fromArray(normDepthBufferFromNormView.matrix); + if (this._cachedWebGLTexture) { + return; + } + this._width = width; + this._height = height; + this._cachedWebGLTexture = texture; + this._textureType = textureType; + const scene = this._xrSessionManager.scene; + const internalTexture = this._getInternalTextureFromDepthInfo(); + if (!this._cachedDepthImageTexture) { + this._cachedDepthImageTexture = RawTexture.CreateRTexture(null, width, height, scene, false, true, Texture.NEAREST_SAMPLINGMODE, dataFormat === "float" ? 1 : 0); + } + this._cachedDepthImageTexture._texture = internalTexture; + depthTexture = this._cachedDepthImageTexture; + this._xrSessionManager.scene.markAllMaterialsAsDirty(1); + } + /** + * Extends the session init object if needed + * @returns augmentation object for the xr session init object. + */ + getXRSessionInitExtension() { + const isDepthUsageDeclared = this.options.usagePreference != null && this.options.usagePreference.length !== 0; + const isDataFormatDeclared = this.options.dataFormatPreference != null && this.options.dataFormatPreference.length !== 0; + return new Promise((resolve) => { + if (isDepthUsageDeclared && isDataFormatDeclared) { + const usages = this.options.usagePreference.map((usage) => { + switch (usage) { + case "cpu": + return "cpu-optimized"; + case "gpu": + return "gpu-optimized"; + } + }); + const dataFormats = this.options.dataFormatPreference.map((format) => { + switch (format) { + case "luminance-alpha": + return "luminance-alpha"; + case "float": + return "float32"; + case "ushort": + return "unsigned-short"; + } + }); + resolve({ + depthSensing: { + usagePreference: usages, + dataFormatPreference: dataFormats, + }, + }); + } + else { + resolve({}); + } + }); + } + _getInternalTextureFromDepthInfo() { + const engine = this._xrSessionManager.scene.getEngine(); + const dataFormat = this.depthDataFormat; + const textureType = this._textureType; + if (!this._width || !this._height || !this._cachedWebGLTexture) { + throw new Error("Depth information is not available"); + } + const internalTexture = engine.wrapWebGLTexture(this._cachedWebGLTexture, false, 1, this._width || 256, this._height || 256); + internalTexture.isCube = false; + internalTexture.invertY = false; + internalTexture._useSRGBBuffer = false; + internalTexture.format = dataFormat === "luminance-alpha" ? 2 : 5; + internalTexture.generateMipMaps = false; + internalTexture.type = + dataFormat === "float" ? 1 : dataFormat === "ushort" ? 5 : 0; + internalTexture._cachedWrapU = 1; + internalTexture._cachedWrapV = 1; + internalTexture._hardwareTexture = new WebGLHardwareTexture(this._cachedWebGLTexture, engine._gl); + internalTexture.is2DArray = textureType === "texture-array"; + return internalTexture; + } +} +/** + * The module's name + */ +WebXRDepthSensing.Name = WebXRFeatureName.DEPTH_SENSING; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRDepthSensing.Version = 1; +WebXRFeaturesManager.AddWebXRFeature(WebXRDepthSensing.Name, (xrSessionManager, options) => { + return () => new WebXRDepthSensing(xrSessionManager, options); +}, WebXRDepthSensing.Version, false); +RegisterMaterialPlugin("WebXRDepthSensingMaterialPlugin", (material) => new WebXRDepthSensingMaterialPlugin(material)); + +// Do not edit. +const name$2 = "velocityPixelShader"; +const shader$1 = `precision highp float; +#define CUSTOM_FRAGMENT_BEGIN +varying vec4 clipPos;varying vec4 previousClipPos; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; +#define CUSTOM_FRAGMENT_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$2]) { + ShaderStore.ShadersStore[name$2] = shader$1; +} + +// Do not edit. +const name$1 = "velocityVertexShader"; +const shader = `#define CUSTOM_VERTEX_BEGIN +#define VELOCITY +attribute vec3 position; +#include +uniform mat4 viewProjection;uniform mat4 previousViewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; +#endif +varying vec4 clipPos;varying vec4 previousClipPos; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} +#elif +clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +}`; +// Sideeffect +if (!ShaderStore.ShadersStore[name$1]) { + ShaderStore.ShadersStore[name$1] = shader; +} + +/** + * Used for Space Warp render process + */ +class XRSpaceWarpRenderTarget extends RenderTargetTexture { + /** + * Creates a Space Warp render target + * @param motionVectorTexture WebGLTexture provided by WebGLSubImage + * @param depthStencilTexture WebGLTexture provided by WebGLSubImage + * @param scene scene used with the render target + * @param size the size of the render target (used for each view) + */ + constructor(motionVectorTexture, depthStencilTexture, scene, size = 512) { + super("spacewarp rtt", size, scene, false, true, 2, false, undefined, false, false, true, undefined, true); + this._originalPairing = []; + this._previousWorldMatrices = []; + this._previousTransforms = [Matrix.Identity(), Matrix.Identity()]; + this._renderTarget = this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight(), motionVectorTexture, depthStencilTexture); + this._renderTarget._disposeOnlyFramebuffers = true; + this._texture = this._renderTarget.texture; + this._texture.isMultiview = true; + this._texture.format = 5; + if (scene) { + this._velocityMaterial = new ShaderMaterial("velocity shader material", scene, { + vertex: "velocity", + fragment: "velocity", + }, { + uniforms: ["world", "previousWorld", "viewProjection", "viewProjectionR", "previousViewProjection", "previousViewProjectionR"], + }); + this._velocityMaterial._materialHelperNeedsPreviousMatrices = true; + this._velocityMaterial.onBindObservable.add((mesh) => { + // mesh. getWorldMatrix can be incorrect under rare conditions (e.g. when using a effective mesh in the render function). + // If the case arise that will require changing it we will need to change the bind process in the material class to also provide the world matrix as a parameter + this._previousWorldMatrices[mesh.uniqueId] = this._previousWorldMatrices[mesh.uniqueId] || mesh.getWorldMatrix(); + this._velocityMaterial.getEffect().setMatrix("previousWorld", this._previousWorldMatrices[mesh.uniqueId]); + this._previousWorldMatrices[mesh.uniqueId] = mesh.getWorldMatrix(); + // now set the scene's previous matrix + this._velocityMaterial.getEffect().setMatrix("previousViewProjection", this._previousTransforms[0]); + // multiview for sure + this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR", this._previousTransforms[1]); + // store the previous (current, to be exact) transforms + this._previousTransforms[0].copyFrom(scene.getTransformMatrix()); + this._previousTransforms[1].copyFrom(scene._transformMatrixR); + }); + this._velocityMaterial.freeze(); + } + } + render(useCameraPostProcess = false, dumpForDebug = false) { + // Swap to use velocity material + this._originalPairing.length = 0; + const scene = this.getScene(); + // set the velocity material to render the velocity RTT + if (scene && this._velocityMaterial) { + scene.getActiveMeshes().forEach((mesh) => { + this._originalPairing.push([mesh, mesh.material]); + mesh.material = this._velocityMaterial; + }); + } + super.render(useCameraPostProcess, dumpForDebug); + // Restore original materials + this._originalPairing.forEach((tuple) => { + tuple[0].material = tuple[1]; + }); + } + /** + * @internal + */ + _bindFrameBuffer() { + if (!this._renderTarget) { + return; + } + this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget); + } + /** + * Gets the number of views the corresponding to the texture (eg. a SpaceWarpRenderTarget will have > 1) + * @returns the view count + */ + getViewCount() { + return 2; + } + dispose() { + super.dispose(); + this._velocityMaterial.dispose(); + this._previousTransforms.length = 0; + this._previousWorldMatrices.length = 0; + this._originalPairing.length = 0; + } +} +/** + * WebXR Space Warp Render Target Texture Provider + */ +class WebXRSpaceWarpRenderTargetTextureProvider { + constructor(_scene, _xrSessionManager, _xrWebGLBinding) { + this._scene = _scene; + this._xrSessionManager = _xrSessionManager; + this._xrWebGLBinding = _xrWebGLBinding; + this._lastSubImages = new Map(); + this._renderTargetTextures = new Map(); + this._engine = _scene.getEngine(); + } + _getSubImageForView(view) { + const layerWrapper = this._xrSessionManager._getBaseLayerWrapper(); + if (!layerWrapper) { + throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer."); + } + if (layerWrapper.layerType !== "XRProjectionLayer") { + throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".'); + } + const layer = layerWrapper.layer; + return this._xrWebGLBinding.getViewSubImage(layer, view); + } + _setViewportForSubImage(viewport, subImage) { + viewport.x = 0; + viewport.y = 0; + viewport.width = subImage.motionVectorTextureWidth; + viewport.height = subImage.motionVectorTextureHeight; + } + _createRenderTargetTexture(width, height, framebuffer, motionVectorTexture, depthStencilTexture) { + if (!this._engine) { + throw new Error("Engine is disposed"); + } + const textureSize = { width, height }; + // Create render target texture from the internal texture + const renderTargetTexture = new XRSpaceWarpRenderTarget(motionVectorTexture, depthStencilTexture, this._scene, textureSize); + const renderTargetWrapper = renderTargetTexture.renderTarget; + if (framebuffer) { + renderTargetWrapper._framebuffer = framebuffer; + } + // Create internal texture + renderTargetWrapper._colorTextureArray = motionVectorTexture; + renderTargetWrapper._depthStencilTextureArray = depthStencilTexture; + renderTargetTexture.disableRescaling(); + renderTargetTexture.renderListPredicate = () => true; + return renderTargetTexture; + } + _getRenderTargetForSubImage(subImage, view) { + const lastSubImage = this._lastSubImages.get(view); + let renderTargetTexture = this._renderTargetTextures.get(view.eye); + const width = subImage.motionVectorTextureWidth; + const height = subImage.motionVectorTextureHeight; + if (!renderTargetTexture || lastSubImage?.textureWidth !== width || lastSubImage?.textureHeight != height) { + renderTargetTexture = this._createRenderTargetTexture(width, height, null, subImage.motionVectorTexture, subImage.depthStencilTexture); + this._renderTargetTextures.set(view.eye, renderTargetTexture); + this._framebufferDimensions = { + framebufferWidth: width, + framebufferHeight: height, + }; + } + this._lastSubImages.set(view, subImage); + return renderTargetTexture; + } + trySetViewportForView(viewport, view) { + const subImage = this._lastSubImages.get(view) || this._getSubImageForView(view); + if (subImage) { + this._setViewportForSubImage(viewport, subImage); + return true; + } + return false; + } + /** + * Access the motion vector (which will turn on Space Warp) + * @param view the view to access the motion vector texture for + */ + accessMotionVector(view) { + const subImage = this._getSubImageForView(view); + if (subImage) { + // Meta Quest Browser uses accessing these textures as a sign for turning on Space Warp + subImage.motionVectorTexture; + subImage.depthStencilTexture; + } + } + getRenderTargetTextureForEye(_eye) { + return null; + } + getRenderTargetTextureForView(view) { + const subImage = this._getSubImageForView(view); + if (subImage) { + return this._getRenderTargetForSubImage(subImage, view); + } + return null; + } + dispose() { + this._renderTargetTextures.forEach((rtt) => rtt.dispose()); + this._renderTargetTextures.clear(); + } +} +/** + * the WebXR Space Warp feature. + */ +class WebXRSpaceWarp extends WebXRAbstractFeature { + /** + * constructor for the space warp feature + * @param _xrSessionManager the xr session manager for this feature + */ + constructor(_xrSessionManager) { + super(_xrSessionManager); + this._onAfterRenderObserver = null; + this.dependsOn = [WebXRFeatureName.LAYERS]; + this.xrNativeFeatureName = "space-warp"; + this._xrSessionManager.scene.needsPreviousWorldMatrices = true; + } + /** + * Attach this feature. + * Will usually be called by the features manager. + * + * @returns true if successful. + */ + attach() { + if (!super.attach()) { + return false; + } + const engine = this._xrSessionManager.scene.getEngine(); + this._glContext = engine._gl; + this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, this._glContext); + this.spaceWarpRTTProvider = new WebXRSpaceWarpRenderTargetTextureProvider(this._xrSessionManager.scene, this._xrSessionManager, this._xrWebGLBinding); + this._onAfterRenderObserver = this._xrSessionManager.scene.onAfterRenderObservable.add(() => this._onAfterRender()); + return true; + } + detach() { + this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver); + return super.detach(); + } + _onAfterRender() { + if (this.attached && this._renderTargetTexture) { + this._renderTargetTexture.render(false, false); + } + } + isCompatible() { + return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat || false; + } + dispose() { + super.dispose(); + } + _onXRFrame(_xrFrame) { + const pose = _xrFrame.getViewerPose(this._xrSessionManager.referenceSpace); + if (!pose) { + return; + } + // get the first view to which we will create a texture (or update it) + const view = pose.views[0]; + this._renderTargetTexture = this._renderTargetTexture || this.spaceWarpRTTProvider.getRenderTargetTextureForView(view); + this.spaceWarpRTTProvider.accessMotionVector(view); + } +} +/** + * The module's name + */ +WebXRSpaceWarp.Name = WebXRFeatureName.SPACE_WARP; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRSpaceWarp.Version = 1; +//register the plugin +WebXRFeaturesManager.AddWebXRFeature(WebXRSpaceWarp.Name, (xrSessionManager) => { + return () => new WebXRSpaceWarp(xrSessionManager); +}, WebXRSpaceWarp.Version, false); + +/** + * WebXR Feature for WebXR raw camera access + * @since 6.31.0 + * @see https://immersive-web.github.io/raw-camera-access/ + */ +class WebXRRawCameraAccess extends WebXRAbstractFeature { + /** + * Creates a new instance of the feature + * @param _xrSessionManager the WebXRSessionManager + * @param options options for the Feature + */ + constructor(_xrSessionManager, options = {}) { + super(_xrSessionManager); + this.options = options; + this._cachedInternalTextures = []; + /** + * This is an array of camera views + * Note that mostly the array will contain a single view + * If you want to know the order of the views, use the `viewIndex` array + */ + this.texturesData = []; + /** + * If needed, this array will contain the eye definition of each texture in `texturesArray` + */ + this.viewIndex = []; + /** + * If needed, this array will contain the camera's intrinsics + * You can use this data to convert from camera space to screen space and vice versa + */ + this.cameraIntrinsics = []; + /** + * An observable that will notify when the camera's textures are updated + */ + this.onTexturesUpdatedObservable = new Observable(); + this.xrNativeFeatureName = "camera-access"; + } + attach(force) { + if (!super.attach(force)) { + return false; + } + this._glContext = this._xrSessionManager.scene.getEngine()._gl; + this._glBinding = new XRWebGLBinding(this._xrSessionManager.session, this._glContext); + return true; + } + detach() { + if (!super.detach()) { + return false; + } + this._glBinding = undefined; + if (!this.options.doNotDisposeOnDetach) { + this._cachedInternalTextures.forEach((t) => t.dispose()); + this.texturesData.forEach((t) => t.dispose()); + this._cachedInternalTextures.length = 0; + this.texturesData.length = 0; + this.cameraIntrinsics.length = 0; + } + return true; + } + /** + * Dispose this feature and all of the resources attached + */ + dispose() { + super.dispose(); + this.onTexturesUpdatedObservable.clear(); + } + /** + * @see https://github.com/immersive-web/raw-camera-access/blob/main/explainer.md + * @param view the XRView to update + * @param index the index of the view in the views array + */ + _updateCameraIntrinsics(view, index) { + const cameraViewport = { + width: view.camera.width, + height: view.camera.height, + x: 0, + y: 0, + }; + const p = view.projectionMatrix; + // Principal point in pixels (typically at or near the center of the viewport) + const u0 = ((1 - p[8]) * cameraViewport.width) / 2 + cameraViewport.x; + const v0 = ((1 - p[9]) * cameraViewport.height) / 2 + cameraViewport.y; + // Focal lengths in pixels (these are equal for square pixels) + const ax = (cameraViewport.width / 2) * p[0]; + const ay = (cameraViewport.height / 2) * p[5]; + // Skew factor in pixels (nonzero for rhomboid pixels) + const gamma = (cameraViewport.width / 2) * p[4]; + this.cameraIntrinsics[index] = { + u0, + v0, + ax, + ay, + gamma, + width: cameraViewport.width, + height: cameraViewport.height, + viewportX: cameraViewport.x, + viewportY: cameraViewport.y, + }; + } + _updateInternalTextures(view, index = 0) { + if (!view.camera) { + return false; + } + this.viewIndex[index] = view.eye; + const lp = this._glBinding?.getCameraImage(view.camera); + if (!this._cachedInternalTextures[index]) { + const internalTexture = new InternalTexture(this._xrSessionManager.scene.getEngine(), 0 /* InternalTextureSource.Unknown */, true); + internalTexture.invertY = false; + internalTexture.format = 5; + internalTexture.generateMipMaps = true; + internalTexture.type = 0; + internalTexture.samplingMode = 3; + internalTexture.width = view.camera.width; + internalTexture.height = view.camera.height; + internalTexture._cachedWrapU = 1; + internalTexture._cachedWrapV = 1; + internalTexture._hardwareTexture = new WebGLHardwareTexture(lp, this._glContext); + this._cachedInternalTextures[index] = internalTexture; + // create the base texture + const texture = new BaseTexture(this._xrSessionManager.scene); + texture.name = `WebXR Raw Camera Access (${index})`; + texture._texture = this._cachedInternalTextures[index]; + this.texturesData[index] = texture; + // get the camera intrinsics + this._updateCameraIntrinsics(view, index); + } + else { + // make sure the webgl texture is updated. Should happen automatically + this._cachedInternalTextures[index]._hardwareTexture?.set(lp); + } + this._cachedInternalTextures[index].isReady = true; + return true; + } + _onXRFrame(_xrFrame) { + const referenceSPace = this._xrSessionManager.referenceSpace; + const pose = _xrFrame.getViewerPose(referenceSPace); + if (!pose || !pose.views) { + return; + } + let updated = true; + pose.views.forEach((view, index) => { + updated = updated && this._updateInternalTextures(view, index); + }); + if (updated) { + this.onTexturesUpdatedObservable.notifyObservers(this.texturesData); + } + } +} +/** + * The module's name + */ +WebXRRawCameraAccess.Name = WebXRFeatureName.RAW_CAMERA_ACCESS; +/** + * The (Babylon) version of this module. + * This is an integer representing the implementation version. + * This number does not correspond to the WebXR specs version + */ +WebXRRawCameraAccess.Version = 1; +WebXRFeaturesManager.AddWebXRFeature(WebXRRawCameraAccess.Name, (xrSessionManager, options) => { + return () => new WebXRRawCameraAccess(xrSessionManager, options); +}, WebXRRawCameraAccess.Version, false); + +/** + * A generic hand controller class that supports select and a secondary grasp + */ +class WebXRGenericHandController extends WebXRAbstractMotionController { + /** + * Create a new hand controller object, without loading a controller model + * @param scene the scene to use to create this controller + * @param gamepadObject the corresponding gamepad object + * @param handedness the handedness of the controller + */ + constructor(scene, gamepadObject, handedness) { + // Don't load the controller model - for now, hands have no real model. + super(scene, GenericHandSelectGraspProfile[handedness], gamepadObject, handedness, true); + this.profileId = "generic-hand-select-grasp"; + } + _getFilenameAndPath() { + return { + filename: "generic.babylon", + path: "https://controllers.babylonjs.com/generic/", + }; + } + _getModelLoadingConstraints() { + return true; + } + _processLoadedModel(_meshes) { + // no-op + } + _setRootMesh(meshes) { + // no-op + } + _updateModel() { + // no-op + } +} +// register the profiles +WebXRMotionControllerManager.RegisterController("generic-hand-select-grasp", (xrInput, scene) => { + return new WebXRGenericHandController(scene, xrInput.gamepad, xrInput.handedness); +}); +// https://github.com/immersive-web/webxr-input-profiles/blob/main/packages/registry/profiles/generic/generic-hand-select-grasp.json +const GenericHandSelectGraspProfile = { + left: { + selectComponentId: "xr-standard-trigger", + components: { + // eslint-disable-next-line @typescript-eslint/naming-convention + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr-standard-trigger", + visualResponses: {}, + }, + grasp: { + type: "trigger", + gamepadIndices: { + button: 4, + }, + rootNodeName: "grasp", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "generic-hand-select-grasp-left", + assetPath: "left.glb", + }, + right: { + selectComponentId: "xr-standard-trigger", + components: { + // eslint-disable-next-line @typescript-eslint/naming-convention + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr-standard-trigger", + visualResponses: {}, + }, + grasp: { + type: "trigger", + gamepadIndices: { + button: 4, + }, + rootNodeName: "grasp", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "generic-hand-select-grasp-right", + assetPath: "right.glb", + }, + none: { + selectComponentId: "xr-standard-trigger", + components: { + // eslint-disable-next-line @typescript-eslint/naming-convention + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr-standard-trigger", + visualResponses: {}, + }, + grasp: { + type: "trigger", + gamepadIndices: { + button: 4, + }, + rootNodeName: "grasp", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "generic-hand-select-grasp-none", + assetPath: "none.glb", + }, +}; + +/** + * The motion controller class for all microsoft mixed reality controllers + */ +class WebXRMicrosoftMixedRealityController extends WebXRAbstractMotionController { + constructor(scene, gamepadObject, handedness) { + super(scene, MixedRealityProfile["left-right"], gamepadObject, handedness); + // use this in the future - https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/assets/profiles/microsoft + this._mapping = { + defaultButton: { + valueNodeName: "VALUE", + unpressedNodeName: "UNPRESSED", + pressedNodeName: "PRESSED", + }, + defaultAxis: { + valueNodeName: "VALUE", + minNodeName: "MIN", + maxNodeName: "MAX", + }, + buttons: { + "xr-standard-trigger": { + rootNodeName: "SELECT", + componentProperty: "button", + states: ["default", "touched", "pressed"], + }, + "xr-standard-squeeze": { + rootNodeName: "GRASP", + componentProperty: "state", + states: ["pressed"], + }, + "xr-standard-touchpad": { + rootNodeName: "TOUCHPAD_PRESS", + labelAnchorNodeName: "squeeze-label", + touchPointNodeName: "TOUCH", // TODO - use this for visual feedback + }, + "xr-standard-thumbstick": { + rootNodeName: "THUMBSTICK_PRESS", + componentProperty: "state", + states: ["pressed"], + }, + }, + axes: { + "xr-standard-touchpad": { + "x-axis": { + rootNodeName: "TOUCHPAD_TOUCH_X", + }, + "y-axis": { + rootNodeName: "TOUCHPAD_TOUCH_Y", + }, + }, + "xr-standard-thumbstick": { + "x-axis": { + rootNodeName: "THUMBSTICK_X", + }, + "y-axis": { + rootNodeName: "THUMBSTICK_Y", + }, + }, + }, + }; + this.profileId = "microsoft-mixed-reality"; + } + _getFilenameAndPath() { + let filename = ""; + if (this.handedness === "left") { + filename = WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME; + } + else { + // Right is the default if no hand is specified + filename = WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME; + } + const device = "default"; + const path = WebXRMicrosoftMixedRealityController.MODEL_BASE_URL + device + "/"; + return { + filename, + path, + }; + } + _getModelLoadingConstraints() { + const glbLoaded = SceneLoader.IsPluginForExtensionAvailable(".glb"); + if (!glbLoaded) { + Logger.Warn("glTF / glb loaded was not registered, using generic controller instead"); + } + return glbLoaded; + } + _processLoadedModel(_meshes) { + if (!this.rootMesh) { + return; + } + // Button Meshes + this.getComponentIds().forEach((id, i) => { + if (this.disableAnimation) { + return; + } + if (id && this.rootMesh) { + const buttonMap = this._mapping.buttons[id]; + const buttonMeshName = buttonMap.rootNodeName; + if (!buttonMeshName) { + Logger.Log("Skipping unknown button at index: " + i + " with mapped name: " + id); + return; + } + const buttonMesh = this._getChildByName(this.rootMesh, buttonMeshName); + if (!buttonMesh) { + Logger.Warn("Missing button mesh with name: " + buttonMeshName); + return; + } + buttonMap.valueMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.valueNodeName); + buttonMap.pressedMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.pressedNodeName); + buttonMap.unpressedMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.unpressedNodeName); + if (buttonMap.valueMesh && buttonMap.pressedMesh && buttonMap.unpressedMesh) { + const comp = this.getComponent(id); + if (comp) { + comp.onButtonStateChangedObservable.add((component) => { + this._lerpTransform(buttonMap, component.value); + }, undefined, true); + } + } + else { + // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes. + Logger.Warn("Missing button submesh under mesh with name: " + buttonMeshName); + } + } + }); + // Axis Meshes + this.getComponentIds().forEach((id) => { + const comp = this.getComponent(id); + if (!comp.isAxes()) { + return; + } + ["x-axis", "y-axis"].forEach((axis) => { + if (!this.rootMesh) { + return; + } + const axisMap = this._mapping.axes[id][axis]; + const axisMesh = this._getChildByName(this.rootMesh, axisMap.rootNodeName); + if (!axisMesh) { + Logger.Warn("Missing axis mesh with name: " + axisMap.rootNodeName); + return; + } + axisMap.valueMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.valueNodeName); + axisMap.minMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.minNodeName); + axisMap.maxMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.maxNodeName); + if (axisMap.valueMesh && axisMap.minMesh && axisMap.maxMesh) { + if (comp) { + comp.onAxisValueChangedObservable.add((axisValues) => { + const value = axis === "x-axis" ? axisValues.x : axisValues.y; + this._lerpTransform(axisMap, value, true); + }, undefined, true); + } + } + else { + // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes. + Logger.Warn("Missing axis submesh under mesh with name: " + axisMap.rootNodeName); + } + }); + }); + } + _setRootMesh(meshes) { + this.rootMesh = new Mesh(this.profileId + " " + this.handedness, this.scene); + this.rootMesh.isPickable = false; + let rootMesh; + // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh' + for (let i = 0; i < meshes.length; i++) { + const mesh = meshes[i]; + mesh.isPickable = false; + if (!mesh.parent) { + // Handle root node, attach to the new parentMesh + rootMesh = mesh; + } + } + if (rootMesh) { + rootMesh.setParent(this.rootMesh); + } + if (!this.scene.useRightHandedSystem) { + this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0); + } + } + _updateModel() { + // no-op. model is updated using observables. + } +} +/** + * The base url used to load the left and right controller models + */ +WebXRMicrosoftMixedRealityController.MODEL_BASE_URL = "https://controllers.babylonjs.com/microsoft/"; +/** + * The name of the left controller model file + */ +WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME = "left.glb"; +/** + * The name of the right controller model file + */ +WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME = "right.glb"; +// register the profile +WebXRMotionControllerManager.RegisterController("windows-mixed-reality", (xrInput, scene) => { + return new WebXRMicrosoftMixedRealityController(scene, xrInput.gamepad, xrInput.handedness); +}); +// https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/microsoft/microsoft-mixed-reality.json +const MixedRealityProfile = { + }; + +/** + * The motion controller class for oculus touch (quest, rift). + * This class supports legacy mapping as well the standard xr mapping + */ +class WebXROculusTouchMotionController extends WebXRAbstractMotionController { + constructor(scene, gamepadObject, handedness, _legacyMapping = false, _forceLegacyControllers = false) { + super(scene, OculusTouchLayouts[handedness], gamepadObject, handedness); + this._forceLegacyControllers = _forceLegacyControllers; + this.profileId = "oculus-touch"; + } + _getFilenameAndPath() { + let filename = ""; + if (this.handedness === "left") { + filename = WebXROculusTouchMotionController.MODEL_LEFT_FILENAME; + } + else { + // Right is the default if no hand is specified + filename = WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME; + } + const path = this._isQuest() ? WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL : WebXROculusTouchMotionController.MODEL_BASE_URL; + return { + filename, + path, + }; + } + _getModelLoadingConstraints() { + return true; + } + _processLoadedModel(_meshes) { + const isQuest = this._isQuest(); + const triggerDirection = this.handedness === "right" ? -1 : 1; + this.getComponentIds().forEach((id) => { + const comp = id && this.getComponent(id); + if (comp) { + comp.onButtonStateChangedObservable.add((component) => { + if (!this.rootMesh || this.disableAnimation) { + return; + } + switch (id) { + case "xr-standard-trigger": // index trigger + if (!isQuest) { + this._modelRootNode.getChildren()[3].rotation.x = -component.value * 0.2; + this._modelRootNode.getChildren()[3].position.y = -component.value * 0.005; + this._modelRootNode.getChildren()[3].position.z = -component.value * 0.005; + } + return; + case "xr-standard-squeeze": // secondary trigger + if (!isQuest) { + this._modelRootNode.getChildren()[4].position.x = triggerDirection * component.value * 0.0035; + } + return; + case "xr-standard-thumbstick": // thumbstick + return; + case "a-button": + case "x-button": + if (!isQuest) { + if (component.pressed) { + this._modelRootNode.getChildren()[1].position.y = -1e-3; + } + else { + this._modelRootNode.getChildren()[1].position.y = 0; + } + } + return; + case "b-button": + case "y-button": + if (!isQuest) { + if (component.pressed) { + this._modelRootNode.getChildren()[2].position.y = -1e-3; + } + else { + this._modelRootNode.getChildren()[2].position.y = 0; + } + } + return; + } + }, undefined, true); + } + }); + } + _setRootMesh(meshes) { + this.rootMesh = new Mesh(this.profileId + " " + this.handedness, this.scene); + if (!this.scene.useRightHandedSystem) { + this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0); + } + meshes.forEach((mesh) => { + mesh.isPickable = false; + }); + if (this._isQuest()) { + this._modelRootNode = meshes[0]; + } + else { + this._modelRootNode = meshes[1]; + this.rootMesh.position.y = 0.034; + this.rootMesh.position.z = 0.052; + } + this._modelRootNode.parent = this.rootMesh; + } + _updateModel() { + // no-op. model is updated using observables. + } + /** + * Is this the new type of oculus touch. At the moment both have the same profile and it is impossible to differentiate + * between the touch and touch 2. + * @returns true if this is the new type of oculus touch controllers. + */ + _isQuest() { + // this is SADLY the only way to currently check. Until proper profiles will be available. + return !!navigator.userAgent.match(/Quest/gi) && !this._forceLegacyControllers; + } +} +/** + * The base url used to load the left and right controller models + */ +WebXROculusTouchMotionController.MODEL_BASE_URL = "https://controllers.babylonjs.com/oculus/"; +/** + * The name of the left controller model file + */ +WebXROculusTouchMotionController.MODEL_LEFT_FILENAME = "left.babylon"; +/** + * The name of the right controller model file + */ +WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME = "right.babylon"; +/** + * Base Url for the Quest controller model. + */ +WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL = "https://controllers.babylonjs.com/oculusQuest/"; +// register the profile +WebXRMotionControllerManager.RegisterController("oculus-touch", (xrInput, scene) => { + return new WebXROculusTouchMotionController(scene, xrInput.gamepad, xrInput.handedness); +}); +WebXRMotionControllerManager.RegisterController("oculus-touch-legacy", (xrInput, scene) => { + return new WebXROculusTouchMotionController(scene, xrInput.gamepad, xrInput.handedness, true); +}); +const OculusTouchLayouts = { + left: { + selectComponentId: "xr-standard-trigger", + components: { + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr_standard_trigger", + visualResponses: {}, + }, + "xr-standard-squeeze": { + type: "squeeze", + gamepadIndices: { + button: 1, + }, + rootNodeName: "xr_standard_squeeze", + visualResponses: {}, + }, + "xr-standard-thumbstick": { + type: "thumbstick", + gamepadIndices: { + button: 3, + xAxis: 2, + yAxis: 3, + }, + rootNodeName: "xr_standard_thumbstick", + visualResponses: {}, + }, + "x-button": { + type: "button", + gamepadIndices: { + button: 4, + }, + rootNodeName: "x_button", + visualResponses: {}, + }, + "y-button": { + type: "button", + gamepadIndices: { + button: 5, + }, + rootNodeName: "y_button", + visualResponses: {}, + }, + thumbrest: { + type: "button", + gamepadIndices: { + button: 6, + }, + rootNodeName: "thumbrest", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "oculus-touch-v2-left", + assetPath: "left.glb", + }, + right: { + selectComponentId: "xr-standard-trigger", + components: { + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr_standard_trigger", + visualResponses: {}, + }, + "xr-standard-squeeze": { + type: "squeeze", + gamepadIndices: { + button: 1, + }, + rootNodeName: "xr_standard_squeeze", + visualResponses: {}, + }, + "xr-standard-thumbstick": { + type: "thumbstick", + gamepadIndices: { + button: 3, + xAxis: 2, + yAxis: 3, + }, + rootNodeName: "xr_standard_thumbstick", + visualResponses: {}, + }, + "a-button": { + type: "button", + gamepadIndices: { + button: 4, + }, + rootNodeName: "a_button", + visualResponses: {}, + }, + "b-button": { + type: "button", + gamepadIndices: { + button: 5, + }, + rootNodeName: "b_button", + visualResponses: {}, + }, + thumbrest: { + type: "button", + gamepadIndices: { + button: 6, + }, + rootNodeName: "thumbrest", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "oculus-touch-v2-right", + assetPath: "right.glb", + }, +}; + +/** + * The motion controller class for the standard HTC-Vive controllers + */ +class WebXRHTCViveMotionController extends WebXRAbstractMotionController { + /** + * Create a new Vive motion controller object + * @param scene the scene to use to create this controller + * @param gamepadObject the corresponding gamepad object + * @param handedness the handedness of the controller + */ + constructor(scene, gamepadObject, handedness) { + super(scene, HTCViveLayout[handedness], gamepadObject, handedness); + this.profileId = "htc-vive"; + } + _getFilenameAndPath() { + const filename = WebXRHTCViveMotionController.MODEL_FILENAME; + const path = WebXRHTCViveMotionController.MODEL_BASE_URL; + return { + filename, + path, + }; + } + _getModelLoadingConstraints() { + return true; + } + _processLoadedModel(_meshes) { + this.getComponentIds().forEach((id) => { + const comp = id && this.getComponent(id); + if (comp) { + comp.onButtonStateChangedObservable.add((component) => { + if (!this.rootMesh || this.disableAnimation) { + return; + } + switch (id) { + case "xr-standard-trigger": + this._modelRootNode.getChildren()[6].rotation.x = -component.value * 0.15; + return; + case "xr-standard-touchpad": + return; + case "xr-standard-squeeze": + return; + } + }, undefined, true); + } + }); + } + _setRootMesh(meshes) { + this.rootMesh = new Mesh(this.profileId + " " + this.handedness, this.scene); + meshes.forEach((mesh) => { + mesh.isPickable = false; + }); + this._modelRootNode = meshes[1]; + this._modelRootNode.parent = this.rootMesh; + if (!this.scene.useRightHandedSystem) { + this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0); + } + } + _updateModel() { + // no-op. model is updated using observables. + } +} +/** + * The base url used to load the left and right controller models + */ +WebXRHTCViveMotionController.MODEL_BASE_URL = "https://controllers.babylonjs.com/vive/"; +/** + * File name for the controller model. + */ +WebXRHTCViveMotionController.MODEL_FILENAME = "wand.babylon"; +// register the profile +WebXRMotionControllerManager.RegisterController("htc-vive", (xrInput, scene) => { + return new WebXRHTCViveMotionController(scene, xrInput.gamepad, xrInput.handedness); +}); +// WebXRMotionControllerManager.RegisterController("htc-vive-legacy", (xrInput: XRInputSource, scene: Scene) => { +// return new WebXRHTCViveMotionController(scene, (xrInput.gamepad), xrInput.handedness, true); +// }); +const HTCViveLayout = { + left: { + selectComponentId: "xr-standard-trigger", + components: { + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr_standard_trigger", + visualResponses: {}, + }, + "xr-standard-squeeze": { + type: "squeeze", + gamepadIndices: { + button: 1, + }, + rootNodeName: "xr_standard_squeeze", + visualResponses: {}, + }, + "xr-standard-touchpad": { + type: "touchpad", + gamepadIndices: { + button: 2, + xAxis: 0, + yAxis: 1, + }, + rootNodeName: "xr_standard_touchpad", + visualResponses: {}, + }, + menu: { + type: "button", + gamepadIndices: { + button: 4, + }, + rootNodeName: "menu", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "htc_vive_none", + assetPath: "none.glb", + }, + right: { + selectComponentId: "xr-standard-trigger", + components: { + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr_standard_trigger", + visualResponses: {}, + }, + "xr-standard-squeeze": { + type: "squeeze", + gamepadIndices: { + button: 1, + }, + rootNodeName: "xr_standard_squeeze", + visualResponses: {}, + }, + "xr-standard-touchpad": { + type: "touchpad", + gamepadIndices: { + button: 2, + xAxis: 0, + yAxis: 1, + }, + rootNodeName: "xr_standard_touchpad", + visualResponses: {}, + }, + menu: { + type: "button", + gamepadIndices: { + button: 4, + }, + rootNodeName: "menu", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "htc_vive_none", + assetPath: "none.glb", + }, + none: { + selectComponentId: "xr-standard-trigger", + components: { + "xr-standard-trigger": { + type: "trigger", + gamepadIndices: { + button: 0, + }, + rootNodeName: "xr_standard_trigger", + visualResponses: {}, + }, + "xr-standard-squeeze": { + type: "squeeze", + gamepadIndices: { + button: 1, + }, + rootNodeName: "xr_standard_squeeze", + visualResponses: {}, + }, + "xr-standard-touchpad": { + type: "touchpad", + gamepadIndices: { + button: 2, + xAxis: 0, + yAxis: 1, + }, + rootNodeName: "xr_standard_touchpad", + visualResponses: {}, + }, + menu: { + type: "button", + gamepadIndices: { + button: 4, + }, + rootNodeName: "menu", + visualResponses: {}, + }, + }, + gamepadMapping: "xr-standard", + rootNodeName: "htc-vive-none", + assetPath: "none.glb", + }, +}; + +/** @internal */ +class NativeXRFrame { + get session() { + return this._nativeImpl.session; + } + constructor(_nativeImpl) { + this._nativeImpl = _nativeImpl; + this._xrTransform = new XRRigidTransform(); + this._xrPose = { + transform: this._xrTransform, + emulatedPosition: false, + }; + // Enough space for position, orientation + this._xrPoseVectorData = new Float32Array(4 + 4); + this.fillPoses = this._nativeImpl.fillPoses.bind(this._nativeImpl); + this.getViewerPose = this._nativeImpl.getViewerPose.bind(this._nativeImpl); + this.getHitTestResults = this._nativeImpl.getHitTestResults.bind(this._nativeImpl); + this.getHitTestResultsForTransientInput = () => { + throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native."); + }; + this.createAnchor = this._nativeImpl.createAnchor.bind(this._nativeImpl); + this.getJointPose = this._nativeImpl.getJointPose.bind(this._nativeImpl); + this.fillJointRadii = this._nativeImpl.fillJointRadii.bind(this._nativeImpl); + this.getLightEstimate = () => { + throw new Error("XRFrame.getLightEstimate not supported on native."); + }; + this.getImageTrackingResults = () => { + return this._nativeImpl._imageTrackingResults ?? []; + }; + } + getPose(space, baseSpace) { + if (!this._nativeImpl.getPoseData(space, baseSpace, this._xrPoseVectorData.buffer, this._xrTransform.matrix.buffer)) { + return undefined; + } + const position = this._xrTransform.position; + position.x = this._xrPoseVectorData[0]; + position.y = this._xrPoseVectorData[1]; + position.z = this._xrPoseVectorData[2]; + position.w = this._xrPoseVectorData[3]; + const orientation = this._xrTransform.orientation; + orientation.x = this._xrPoseVectorData[4]; + orientation.y = this._xrPoseVectorData[5]; + orientation.z = this._xrPoseVectorData[6]; + orientation.w = this._xrPoseVectorData[7]; + return this._xrPose; + } + get trackedAnchors() { + return this._nativeImpl.trackedAnchors; + } + get worldInformation() { + return this._nativeImpl.worldInformation; + } + get detectedPlanes() { + return this._nativeImpl.detectedPlanes; + } + get featurePointCloud() { + return this._nativeImpl.featurePointCloud; + } + getDepthInformation(view) { + throw new Error("This function is not available in Babylon Native"); + // return this._nativeImpl.getDepthInformation(view); + } +} +RegisterNativeTypeAsync("NativeXRFrame", NativeXRFrame); + +class AppRay extends Monobehiver { + oldPoint = Vector3.Zero(); + newPoint = Vector3.Zero(); + highlightLayer = null; + originalMaterial = null; + highlightedMesh = null; + constructor(mainApp) { + super(mainApp); + } + Awake() { + this.setupHighlightLayer(); + this.setupUnifiedEventHandling(); + } + // 设置高亮层 + setupHighlightLayer() { + return; + } + // 设置统一的事件处理 + setupUnifiedEventHandling() { + this.mainApp.appScene.object.onPointerObservable.add((pointerInfo) => { + const { type, event, pickInfo } = pointerInfo; + const pointerEvent = event; + if (pointerEvent.pointerType !== "mouse" && pointerEvent.pointerType !== "touch") { + return; + } + if (pointerEvent.pointerType === "touch" && pointerEvent.isPrimary === false) { + return; + } + if (type === PointerEventTypes.POINTERDOWN) { + this.oldPoint.set(pointerEvent.clientX, 0, pointerEvent.clientY); + } else if (type === PointerEventTypes.POINTERUP) { + this.newPoint.set(pointerEvent.clientX, 0, pointerEvent.clientY); + const distance = Vector3.Distance(this.oldPoint, this.newPoint); + if (distance < 5) { + this.handleSingleClick(pointerEvent, pickInfo); + } + } + }); + } + // 处理单击 + handleSingleClick(evt, pickInfo) { + if (pickInfo && pickInfo.hit && pickInfo.pickedMesh && pickInfo.pickedPoint) { + if (pickInfo.pickedMesh.metadata?.type === "hotspot") { + return; + } + const materialName = pickInfo.pickedMesh.material?.name || ""; + EventBridge.modelClick({ + meshName: pickInfo.pickedMesh.name, + pickedMesh: pickInfo.pickedMesh, + pickedPoint: pickInfo.pickedPoint, + materialName + }); + } else { + console.log(1111); + this.mainApp.appDomTo3D.hideAll(); + } + } + // 高亮显示网格 - 已禁用 + highlightMesh(mesh) { + return; + } + // 使用材质方式高亮 - 已禁用 + highlightWithMaterial(mesh) { + return; + } + // 清除高亮 + clearHighlight() { + try { + if (this.highlightLayer && this.highlightedMesh) { + try { + this.highlightLayer.removeMesh(this.highlightedMesh); + } catch (error) { + console.warn("高亮层移除失败:", error); + } + } + if (this.highlightedMesh && this.originalMaterial) { + const material = this.highlightedMesh.material; + if (material && this.originalMaterial.albedoColor) { + material.albedoColor = this.originalMaterial.albedoColor; + material.emissiveColor = this.originalMaterial.emissiveColor; + } + } + this.highlightedMesh = null; + this.originalMaterial = null; + } catch (error) { + console.error("清除高亮失败:", error); + } + } + /** + * 渲染热点 + * @param hotspots 热点数据 + */ + renderHotspots(hotspots) { + this.mainApp.appHotspot?.render(hotspots); + } +} + +class GameManager extends Monobehiver { + materialDic; + meshDic; + oldTextureDic; + rollerDoorMeshes; + rollerDoorGroup; + rollerDoorInitialY; + rollerDoorObserver; + rollerDoorIsOpen; + rollerDoorNames; + yClipPlane; + yClipTargets; + clipPlaneVisualization; + // 记录加载失败的贴图 + failedTextures; + constructor(mainApp) { + super(mainApp); + this.materialDic = new Dictionary(); + this.meshDic = new Dictionary(); + this.oldTextureDic = new Dictionary(); + this.rollerDoorMeshes = []; + this.rollerDoorGroup = null; + this.rollerDoorInitialY = /* @__PURE__ */ new Map(); + this.rollerDoorObserver = null; + this.rollerDoorIsOpen = false; + this.rollerDoorNames = ["Box006.001", "Box005.001"]; + this.yClipPlane = null; + this.yClipTargets = null; + this.clipPlaneVisualization = null; + this.failedTextures = []; + } + /** 调试:返回当前场景中所有网格名称 */ + listMeshNames() { + return this.meshDic.Keys(); + } + /** 初始化游戏管理器 */ + async Awake() { + const scene = this.mainApp.appScene?.object; + if (!scene) { + console.warn("Scene not found"); + return; + } + this.updateDictionaries(); + this.cacheRollerDoorMeshes(); + console.log("材质字典:", this.materialDic); + this.setRollerDoorScale("Box006.001", new Vector3(0.12, 0.02, 0.118)); + this.setRollerDoorScale("Box005.001", new Vector3(0.13, 0.02, 0.12)); + } + /** + * 更新材质和网格字典(从场景中同步) + */ + updateDictionaries() { + const scene = this.mainApp.appScene?.object; + if (!scene) return; + for (const mat of scene.materials) { + if (!this.materialDic.Has(mat.name)) { + this.materialDic.Set(mat.name, mat); + } + } + for (const mesh of scene.meshes) { + if (mesh instanceof Mesh && !this.meshDic.Has(mesh.name)) { + this.meshDic.Set(mesh.name, mesh); + } + } + } + /** 初始化设置材质 */ + async initSetMaterial(oldObject) { + if (!oldObject?.Component?.length) return; + const { degreeId, Component } = oldObject; + let degreeTextureDic = this.oldTextureDic.Get(degreeId) || {}; + const texturePromises = []; + for (const component of Component) { + const { + name, + albedoTexture, + bumpTexture, + alphaTexture, + aoTexture + } = component; + if (!name) continue; + const mat = this.materialDic.Get(name); + if (!mat) { + continue; + } + const textureDic = degreeTextureDic[name] || { + albedo: null, + bump: null, + alpha: null, + ao: null + }; + const textureTasks = [ + { + key: "albedo", + path: albedoTexture, + property: "albedoTexture" + }, + { + key: "bump", + path: bumpTexture, + property: "bumpTexture" + }, + { + key: "alpha", + path: alphaTexture, + property: "opacityTexture" + }, + { + key: "ao", + path: aoTexture, + property: "ambientTexture" + } + ]; + for (const task of textureTasks) { + const { key, path, property } = task; + if (!path) continue; + const fullPath = this.getPublicUrl() + path; + let texture = textureDic[key]; + if (!texture) { + try { + texture = this.createTextureWithFallback(fullPath); + if (!texture) { + this.failedTextures.push({ + path: fullPath, + materialName: name, + textureType: key, + error: "贴图创建失败", + timestamp: /* @__PURE__ */ new Date() + }); + continue; + } + if (!fullPath.toLowerCase().endsWith(".ktx2")) { + texture.vScale = -1; + } + textureDic[key] = texture; + } catch (error) { + this.failedTextures.push({ + path: fullPath, + materialName: name, + textureType: key, + error: error.message || error.toString(), + timestamp: /* @__PURE__ */ new Date() + }); + continue; + } + } + texturePromises.push( + this.handleTextureAssignment(mat, textureDic, key, (texture2) => { + mat[property] = texture2; + }) + ); + } + degreeTextureDic[name] = textureDic; + } + try { + await Promise.all(texturePromises); + for (const component of Component) { + const { name, transparencyMode, bumpTextureLevel } = component; + if (!name) continue; + const mat = this.materialDic.Get(name); + if (!mat) continue; + mat.transparencyMode = transparencyMode; + if (mat.bumpTexture) { + mat.bumpTexture.level = bumpTextureLevel; + } + this.applyPBRProperties(mat, component); + } + } catch (error) { + console.error("Error loading textures:", error); + } finally { + if (this.mainApp.appDom?.load3D) { + this.mainApp.appDom.load3D.style.display = "none"; + } + } + this.oldTextureDic.Set(degreeId, degreeTextureDic); + } + /** + * 应用PBR材质属性 + * @param mat - PBR材质对象 + * @param component - 配置组件对象 + */ + applyPBRProperties(mat, component) { + const pbrTasks = [ + { + key: "fresnel", + value: component.fresnel, + apply: (value) => { + mat.indexOfRefraction = value; + } + }, + { + key: "clearcoat", + value: component.clearcoat, + apply: (value) => { + mat.clearCoat.isEnabled = true; + mat.clearCoat.intensity = value; + } + }, + { + key: "clearcoatRoughness", + value: component.clearcoatRoughness, + apply: (value) => { + mat.clearCoat.roughness = value; + } + }, + { + key: "roughness", + value: component.roughness, + apply: (value) => { + mat.roughness = value; + } + }, + { + key: "metallic", + value: component.metallic, + apply: (value) => { + mat.metallic = value; + } + }, + { + key: "alpha", + value: component.alpha, + apply: (value) => { + mat.alpha = value; + } + }, + { + key: "environmentIntensity", + value: component.environmentIntensity, + apply: (value) => { + mat.environmentIntensity = value; + } + }, + { + key: "baseColor", + value: component.baseColor, + apply: (value) => { + if (value && typeof value === "object") { + const { r, g, b } = value; + if (r !== null && r !== void 0 && g !== null && g !== void 0 && b !== null && b !== void 0) { + mat.albedoColor.set(r, g, b); + } + } + } + } + ]; + for (const task of pbrTasks) { + if (task.value !== null && task.value !== void 0) { + try { + task.apply(task.value); + } catch (error) { + console.warn("Error applying PBR property:", task.key, error); + } + } + } + } + /** 通用的批量卸载贴图资源的方法 */ + clearTextures(textureDic) { + return new Promise((resolve) => { + textureDic.Values().forEach((textures) => { + for (const key in textures) { + const texture = textures[key]; + if (texture && texture instanceof Texture) { + texture.dispose(); + } + } + }); + textureDic.Clear(); + resolve(); + }); + } + /** 处理纹理赋值 */ + async handleTextureAssignment(mat, oldtextureDic, textureKey, assignCallback) { + const texture = oldtextureDic[textureKey]; + if (texture) { + await this.checkTextureLoadedWithPromise(texture); + assignCallback(texture); + } + } + /** 检查纹理是否加载完成 */ + checkTextureLoadedWithPromise(texture) { + return new Promise((resolve) => { + if (texture.isReady()) { + resolve(); + } else { + texture.onLoadObservable.addOnce(() => { + resolve(); + }); + } + }); + } + /** 重置相机位置 */ + reSet() { + if (this.mainApp.appCamera?.object?.position) { + this.mainApp.appCamera.object.position.set(160, 50, 0); + } + } + /** 卷帘门开合:再次调用会反向动作 */ + toggleRollerDoor(options) { + this.setRollerDoorState(!this.rollerDoorIsOpen, options); + } + /** 直接设置卷帘门状态 */ + setRollerDoorState(open, options) { + const scene = this.mainApp.appScene?.object; + if (!scene) { + console.warn("Scene not found for roller door"); + return; + } + this.cacheRollerDoorMeshes(options?.meshNames); + if (!this.rollerDoorGroup || !this.rollerDoorMeshes.length) { + console.warn("Roller door group or meshes not found"); + return; + } + const speed = Math.max(options?.speed ?? 1, 0.01); + let targetY; + if (open) { + if (options?.upY !== void 0) { + targetY = options.upY; + } else { + const maxBaseY = Math.max(...this.rollerDoorMeshes.map( + (m) => this.rollerDoorInitialY.get(m.name) ?? m.position.y + )); + targetY = maxBaseY + 3; + } + } else { + targetY = 0; + } + if (Math.abs(this.rollerDoorGroup.position.y - targetY) < 1e-3) { + this.rollerDoorIsOpen = open; + return; + } + this.rollerDoorIsOpen = open; + this.stopRollerDoorAnimation(); + this.rollerDoorObserver = scene.onBeforeRenderObservable.add(() => { + const dt = scene.getEngine().getDeltaTime() / 1e3; + const current = this.rollerDoorGroup.position.y; + const direction = targetY >= current ? 1 : -1; + const step = speed * dt; + let next = current + direction * step; + if (direction > 0 && next >= targetY || direction < 0 && next <= targetY) { + next = targetY; + this.stopRollerDoorAnimation(); + this.rollerDoorIsOpen = open; + console.log("Roller door animation finished"); + } + this.rollerDoorGroup.position.y = next; + }); + } + /** 当前卷帘门是否开启 */ + isRollerDoorOpen() { + return this.rollerDoorIsOpen; + } + /** + * 设置卷帘门的缩放 + * @param meshName - 卷帘门网格名称 + * @param scale - 缩放值(可以是单个数字或 Vector3) + */ + setRollerDoorScale(meshName, scale) { + const mesh = this.meshDic.Get(meshName); + if (mesh) { + if (typeof scale === "number") { + mesh.scaling.set(scale, scale, scale); + } else { + mesh.scaling.copyFrom(scale); + } + console.log(`Set scale for ${meshName}:`, mesh.scaling.asArray()); + } else { + console.warn(`Roller door mesh not found: ${meshName}`); + } + } + /** + * 设置所有卷帘门的缩放 + * @param scale - 缩放值(可以是单个数字或 Vector3) + */ + setAllRollerDoorsScale(scale) { + this.rollerDoorMeshes.forEach((mesh) => { + if (typeof scale === "number") { + mesh.scaling.set(scale, scale, scale); + } else { + mesh.scaling.copyFrom(scale); + } + console.log(`Set scale for ${mesh.name}:`, mesh.scaling.asArray()); + }); + } + /** + * 设置基于 Y 轴的剖切平面,keepAbove=true 时保留平面以上部分 + * onlyMeshNames 指定只作用于哪些网格,其他网格不受影响 + */ + setYAxisClip(height, keepAbove = true, onlyMeshNames, excludeMeshNames) { + const scene = this.mainApp.appScene?.object; + if (!scene) { + console.warn("Scene not found for clipping"); + return; + } + const normal = new Vector3(0, keepAbove ? 1 : -1, 0); + this.yClipPlane = Plane.FromPositionAndNormal(new Vector3(0, height, 0), normal); + if (onlyMeshNames?.length) { + this.applyClipPlaneToMeshes(this.yClipPlane, onlyMeshNames); + } else { + scene.clipPlane = this.yClipPlane; + } + console.log("[clipping] Scene clipPlane set:", { height, keepAbove, normal: normal.asArray(), targets: onlyMeshNames || "all" }); + } + /** 关闭 Y 轴剖切 */ + clearYAxisClip() { + const scene = this.mainApp.appScene?.object; + if (scene) { + scene.clipPlane = null; + } + this.yClipPlane = null; + this.yClipTargets = null; + this.meshDic.Values().forEach((mesh) => { + const mat = mesh.material; + if (mat && "clipPlane" in mat) { + mat.clipPlane = null; + } + }); + } + cacheRollerDoorMeshes(customNames) { + const scene = this.mainApp.appScene?.object; + if (!scene) return; + const names = customNames?.length ? customNames : this.rollerDoorNames; + this.rollerDoorMeshes = []; + if (!this.rollerDoorGroup) { + this.rollerDoorGroup = new TransformNode("rollerDoorGroup", scene); + this.rollerDoorGroup.position.set(0, 0, 0); + } + for (const name of names) { + const mesh = this.meshDic.Get(name); + if (mesh) { + this.rollerDoorMeshes.push(mesh); + if (!this.rollerDoorInitialY.has(name)) { + this.rollerDoorInitialY.set(name, mesh.position.y); + } + const worldPosition = mesh.getAbsolutePosition(); + const worldScaling = new Vector3(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z); + mesh.parent = this.rollerDoorGroup; + mesh.setAbsolutePosition(worldPosition); + mesh.scaling.copyFrom(worldScaling); + } else { + console.warn(`Roller door mesh not found: ${name}`); + } + } + } + stopRollerDoorAnimation() { + const scene = this.mainApp.appScene?.object; + if (scene && this.rollerDoorObserver) { + scene.onBeforeRenderObservable.remove(this.rollerDoorObserver); + } + this.rollerDoorObserver = null; + } + /** 将 clipPlane 只作用到指定网格的材质 */ + applyClipPlaneToMeshes(plane, targetNames) { + const targetSet = new Set(targetNames); + let appliedCount = 0; + this.meshDic.Values().forEach((mesh) => { + const mat = mesh.material; + if (!mat) { + console.log("[clipping] Mesh has no material:", mesh.name); + return; + } + if (targetSet.has(mesh.name)) { + mat.clipPlane = plane; + appliedCount++; + console.log("[clipping] Applied to mesh:", mesh.name, "material:", mat.name); + } else { + mat.clipPlane = null; + } + }); + console.log("[clipping] Total meshes processed:", this.meshDic.Keys().length, "Applied to:", appliedCount); + if (appliedCount === 0) { + console.warn("[clipping] No meshes found with names:", targetNames); + console.log("[clipping] Available mesh names:", this.meshDic.Keys()); + } + } + /** 获取公共URL */ + getPublicUrl() { + return ""; + } + /** 清理资源 */ + dispose() { + this.stopRollerDoorAnimation(); + this.clearYAxisClip(); + this.rollerDoorMeshes = []; + this.rollerDoorInitialY.clear(); + this.rollerDoorIsOpen = false; + if (this.rollerDoorGroup && this.rollerDoorGroup.dispose) { + this.rollerDoorGroup.dispose(); + this.rollerDoorGroup = null; + } + this.materialDic.Values().forEach((material) => { + if (material && material.dispose) { + material.dispose(); + } + }); + this.materialDic.Clear(); + this.clearTextures(this.oldTextureDic); + this.meshDic.Values().forEach((mesh) => { + if (mesh && mesh.dispose) { + mesh.dispose(); + } + }); + this.meshDic.Clear(); + this.failedTextures = []; + } + /** 更新 */ + update() { + } + /** 尝试创建贴图的方法,支持多种格式回退 */ + createTextureWithFallback(texturePath) { + const failureReasons = []; + try { + const texture = new Texture(texturePath); + if (texture) { + return texture; + } else { + failureReasons.push(`原始路径创建失败: ${texturePath}`); + throw new Error("Texture creation returned null"); + } + } catch (error) { + const errorMessage = error.message || error.toString(); + if (errorMessage.includes("KTX identifier") || errorMessage.includes("missing KTX") || texturePath.toLowerCase().endsWith(".ktx2") && errorMessage) { + this.failedTextures.push({ + path: texturePath, + textureType: "KTX2", + error: `KTX错误: ${errorMessage}`, + timestamp: /* @__PURE__ */ new Date() + }); + } + failureReasons.push(`原始路径加载异常: ${texturePath} - ${errorMessage}`); + if (texturePath.toLowerCase().endsWith(".ktx2")) { + const jpgPath = texturePath.replace(/\.ktx2$/i, ".jpg"); + try { + const jpgTexture = new Texture(jpgPath); + if (jpgTexture) { + return jpgTexture; + } + } catch (jpgError) { + failureReasons.push(`JPG回退失败: ${jpgPath} - ${jpgError}`); + } + const pngPath = texturePath.replace(/\.ktx2$/i, ".png"); + try { + const pngTexture = new Texture(pngPath); + if (pngTexture) { + return pngTexture; + } + } catch (pngError) { + failureReasons.push(`PNG回退失败: ${pngPath} - ${pngError}`); + } + } + this.failedTextures.push({ + path: texturePath, + textureType: "回退机制", + error: failureReasons.join("; "), + timestamp: /* @__PURE__ */ new Date() + }); + return null; + } + } + /** + * 应用材质 + * @param target 目标对象 + * @param material 材质路径 + */ + applyMaterial(target, attribute, value) { + console.log(`Applying attribute ${attribute} to ${value}`); + console.log(this.materialDic); + const targetMaterials = []; + this.materialDic.Values().forEach((material) => { + if (material.name === target) { + console.log(`${this.materialDic.Get(material.name)}`, material); + targetMaterials.push(material); + } + }); + if (targetMaterials.length === 0) { + console.warn(`Target not found: ${target}`); + return; + } + targetMaterials.forEach((material) => { + if (attribute === "baseColor" && typeof value === "string") { + const color = Color3.FromHexString(value); + console.log(`Before: albedoColor =`, material.albedoColor); + console.log(`Before: albedoTexture =`, material.albedoTexture); + material.albedoColor = color; + if (material.albedoTexture) { + console.log(`Material ${material.name} has albedoTexture, color will tint the texture`); + } + material.markDirty(); + console.log(`After: albedoColor =`, material.albedoColor); + console.log(`Applying baseColor ${value} to material: ${material.name}`, color); + } else if (material[attribute]) { + material[attribute] = value; + console.log(`Applying attribute ${attribute} to ${value} to mesh: ${material.name}`); + } + }); + } +} + +class Point_Pool { + points; + constructor() { + this.points = new Array(); + } + Add_point(point_Class) { + this.points.push(point_Class); + } + Enable_All(visible) { + for (let i = 0, item; item = this.points[i++]; ) { + if (item.plane) { + item.plane.isVisible = visible; + } + } + } +} + +class Point { + annotation; + showBox; + position; + disposition; + onload; + onCallBack; + offCallBack; + isClick; + img; + plane; + spriteBehindObject; + hotspotMaterial; + hotspotContainer; + scene; + occlusionObserver; + constructor(hotspotMaterial, hotspotContainer, scene) { + this.hotspotMaterial = hotspotMaterial; + this.hotspotContainer = hotspotContainer; + this.scene = scene; + this.occlusionObserver = null; + } + init(position, disposition, onload, onCallBack, radius) { + this.position = position; + this.disposition = disposition; + this.onCallBack = onCallBack; + this.onload = onload; + this.Create_plane(radius); + this.setupEvents(); + } + Create_plane(radius) { + this.plane = MeshBuilder.CreatePlane( + Math.random().toString(36).slice(-6), + { + size: radius ? radius / 10 : 0.14, + // 热点大小,如果传入 radius 则缩放 + sideOrientation: Mesh.DOUBLESIDE + }, + this.scene + ); + this.plane.position.copyFrom(this.position); + this.plane.material = this.hotspotMaterial; + if (this.plane.material) { + this.plane.material.disableDepthWrite = false; + this.plane.material.needDepthPrePass = true; + } + this.plane.billboardMode = Mesh.BILLBOARDMODE_ALL; + this.plane.parent = this.hotspotContainer; + this.plane.isVisible = true; + this.plane.isPickable = true; + this.plane.renderingGroupId = 1; + this.plane.metadata = { type: "hotspot" }; + } + setupEvents() { + if (this.plane && this.onCallBack) { + this.plane.actionManager = new ActionManager(this.scene); + this.plane.actionManager.registerAction(new ExecuteCodeAction( + ActionManager.OnPickTrigger, + () => { + console.log("热点被点击:", this.plane.name); + this.onCallBack(this); + } + )); + } + } +} + +class HotSpot { + _point_Pool; + body; + _camera; + mainApp; + hotspotTexture; + hotspotMaterial; + hotspotContainer; + vector; + halfW; + halfH; + annotation; + modedl; + constructor(mainAPP) { + this.mainApp = mainAPP; + } + Awake() { + this._camera = this.mainApp.appCamera.object; + this._point_Pool = new Point_Pool(); + this.hotspotContainer = new TransformNode("hotspotContainer", this.mainApp.appScene.object); + } + //创建圆点并且生成事件 类型 + Point_Event(prams) { + const iconPath = prams.icon; + const texture = new Texture(iconPath, this.mainApp.appScene.object); + texture.hasAlpha = true; + texture.getAlphaFromRGB = false; + const material = new StandardMaterial(`hotspotMaterial_${Math.random()}`, this.mainApp.appScene.object); + material.diffuseTexture = texture; + material.emissiveTexture = texture; + material.opacityTexture = texture; + material.useAlphaFromDiffuseTexture = true; + material.transparencyMode = 2; + material.disableLighting = true; + material.backFaceCulling = false; + this.createPointPlane(prams, material); + } + // 创建点平面的具体实现 + createPointPlane(prams, material) { + let { position, disposition, onload, onCallBack } = prams; + let _point = new Point(material, this.hotspotContainer, this.mainApp.appScene.object); + _point.init(position, disposition, onload, onCallBack, prams.radius); + this._point_Pool.Add_point(_point); + } + Enable_All(visible) { + if (this._point_Pool) { + this._point_Pool.Enable_All(visible); + } + } +} + +class HotspotPrams { + constructor(position, disposition, onload, onCallBack, icon, radius) { + this.position = position; + this.disposition = disposition; + this.onload = onload; + this.onCallBack = onCallBack; + this.icon = icon; + this.radius = radius; + } + position; + disposition; + onload; + onCallBack; + icon; + radius; +} + +class AppHotspot extends Monobehiver { + hotSpot; + sllingPointStore; + //偏移量 + offset = 0.7; + yundong = false; + hotspotDic = new Dictionary(); + constructor(mainApp) { + super(mainApp); + } + Awake() { + const hotspot = new HotSpot(this.mainApp); + hotspot.Awake(); + this.hotSpot = hotspot; + } + render(hotSpotList) { + if (!this.hotSpot) { + this.Awake(); + } + this.initHotSpot(hotSpotList); + } + initHotSpot(hotSpotList) { + hotSpotList.forEach((hotspot) => { + this.createHotspot(hotspot); + }); + } + createHotspot(hotspot) { + if (!hotspot) { + console.warn("热点数据为空"); + return; + } + console.log("热点原始数据:", hotspot); + let position; + if (hotspot.offset) { + if (Array.isArray(hotspot.offset)) { + console.log("offset 数组:", hotspot.offset); + position = new Vector3( + hotspot.offset[0] ?? 0, + hotspot.offset[1] ?? 0, + hotspot.offset[2] ?? 0 + ); + } else { + position = new Vector3( + hotspot.offset.x ?? 0, + hotspot.offset.y ?? 0, + hotspot.offset.z ?? 0 + ); + } + } else if (hotspot.position) { + if (Array.isArray(hotspot.position)) { + position = new Vector3( + hotspot.position[0] ?? 0, + hotspot.position[1] ?? 0, + hotspot.position[2] ?? 0 + ); + } else { + position = new Vector3( + hotspot.position.x ?? 0, + hotspot.position.y ?? 0, + hotspot.position.z ?? 0 + ); + } + } else { + console.warn("热点数据缺少 position 或 offset 字段:", hotspot); + return; + } + console.log("创建热点:", hotspot.name, "position:", position, "x:", position.x, "y:", position.y, "z:", position.z); + const disposition = Vector3.Zero(); + this.hotSpot.Point_Event( + new HotspotPrams( + position, + disposition, + () => { + }, + async (p) => { + console.log("热点被点击:", hotspot.name, hotspot.payload); + EventBridge.hotspotClick({ + id: hotspot.id, + name: hotspot.name, + meshName: hotspot.meshName, + payload: hotspot.payload + }); + }, + hotspot.icon, + hotspot.radius + ) + ); + } + clean() { + this.visible(false); + if (this.hotSpot && this.hotSpot._point_Pool && this.hotSpot._point_Pool.points) { + for (let i = 0; i < this.hotSpot._point_Pool.points.length; i++) { + const point = this.hotSpot._point_Pool.points[i]; + if (point.img && point.onCallBack) { + point.img.removeEventListener("mousedown", point.onCallBack); + } + if (point.annotation && point.annotation.parentNode) { + point.annotation.parentNode.removeChild(point.annotation); + } + } + this.hotSpot._point_Pool.points = []; + } + console.log("热点资源已释放"); + } + visible(visible) { + console.log(visible); + if (this.hotSpot) { + this.hotSpot.Enable_All(visible); + } + } +} + +class AppDomTo3D extends Monobehiver { + domElements; + scene; + camera; + pointerDownPos; + pointerUpPos; + constructor(mainApp) { + super(mainApp); + this.domElements = /* @__PURE__ */ new Map(); + this.scene = null; + this.camera = null; + this.pointerDownPos = Vector3.Zero(); + this.pointerUpPos = Vector3.Zero(); + } + /** + * 初始化 + */ + init() { + this.scene = this.mainApp.appScene.object; + this.camera = this.mainApp.appCamera.object; + if (this.scene) { + this.scene.onPointerObservable.add((pointerInfo) => { + const { type, event, pickInfo } = pointerInfo; + if (type === PointerEventTypes.POINTERDOWN) { + this.pointerDownPos.set(event.clientX, 0, event.clientY); + } else if (type === PointerEventTypes.POINTERUP) { + this.pointerUpPos.set(event.clientX, 0, event.clientY); + const distance = Vector3.Distance(this.pointerDownPos, this.pointerUpPos); + if (distance < 5) { + if (!pickInfo || !pickInfo.hit) { + this.hideAll(); + } + } + } + }); + } + } + /** + * 添加DOM元素到3D坐标 + * @param id 唯一标识符 + * @param dom DOM元素 + * @param position 3D坐标 [x, y, z] + * @param offset 2D偏移量 { x, y },可选 + */ + attach(id, dom, position, offset) { + const vector3 = new Vector3(position[0], position[1], position[2]); + dom.style.position = "absolute"; + dom.style.pointerEvents = "auto"; + dom.style.zIndex = "1000"; + dom.style.display = "block"; + this.domElements.set(id, { + dom, + position: vector3, + offset: offset || { x: 0, y: 0 }, + visible: true + }); + this.updateSingleDomPosition(id); + } + /** + * 移除DOM元素 + * @param id 唯一标识符 + */ + detach(id) { + const element = this.domElements.get(id); + if (element) { + element.dom.style.display = "none"; + this.domElements.delete(id); + } + } + /** + * 更新DOM元素的3D坐标 + * @param id 唯一标识符 + * @param position 新的3D坐标 [x, y, z] + */ + updatePosition(id, position) { + const element = this.domElements.get(id); + if (element) { + element.position.set(position[0], position[1], position[2]); + } + } + /** + * 更新所有DOM元素的位置 + */ + updateDomPositions() { + this.domElements.forEach((_, id) => { + this.updateSingleDomPosition(id); + }); + } + /** + * 更新单个DOM元素的位置 + */ + updateSingleDomPosition(id) { + const element = this.domElements.get(id); + if (!element || !this.scene || !this.camera) return; + const { dom, position, offset, visible } = element; + if (!visible) { + dom.style.display = "none"; + return; + } + const engine = this.scene.getEngine(); + const width = engine.getRenderWidth(); + const height = engine.getRenderHeight(); + const worldMatrix = Matrix.Identity(); + const transformMatrix = this.scene.getTransformMatrix(); + const viewport = this.camera.viewport.toGlobal(width, height); + const screenPos = Vector3.Project( + position, + worldMatrix, + transformMatrix, + viewport + ); + if (screenPos.z < 0 || screenPos.z > 1) { + console.log("DOM 不在视野内,隐藏"); + dom.style.display = "none"; + return; + } + dom.style.display = "block"; + dom.style.left = `${screenPos.x + (offset?.x || 0)}px`; + dom.style.top = `${screenPos.y + (offset?.y || 0)}px`; + } + /** + * 清理所有DOM元素 + */ + clean() { + this.domElements.forEach((element) => { + element.dom.style.display = "none"; + }); + this.domElements.clear(); + } + /** + * 获取所有已附加的DOM元素ID列表 + */ + getAttachedIds() { + return Array.from(this.domElements.keys()); + } + /** + * 隐藏所有DOM元素 + */ + hideAll() { + console.log("hideAll 被调用,当前元素数量:", this.domElements.size); + this.domElements.forEach((element, id) => { + console.log("隐藏元素:", id, element.dom); + element.visible = false; + element.dom.style.display = "none"; + }); + } +} + +class MainApp { + appEngin; + appScene; + appCamera; + appModel; + appLight; + appEnv; + appRay; + appHotspot; + appDomTo3D; + gameManager; + constructor() { + this.appEngin = new AppEngin(this); + this.appScene = new AppScene(this); + this.appCamera = new AppCamera(this); + this.appModel = new AppModel(this); + this.appLight = new AppLight(this); + this.appEnv = new AppEnv(this); + this.appRay = new AppRay(this); + this.appHotspot = new AppHotspot(this); + this.appDomTo3D = new AppDomTo3D(this); + this.gameManager = new GameManager(this); + window.addEventListener("resize", () => this.appEngin.handleResize()); + } + /** + * 加载应用配置 + * @param config 配置对象 + */ + loadAConfig(config) { + AppConfig.container = config.container; + AppConfig.modelUrlList = config.modelUrlList || []; + AppConfig.env = config.env; + } + async loadModel() { + await this.appModel.loadModel(); + await this.gameManager.Awake(); + console.log(11111111111111111e5); + EventBridge.allReady({ scene: this.appScene.object }); + } + /** 唤醒/初始化所有子模块 */ + async Awake() { + this.appEngin.Awake(); + this.appScene.Awake(); + this.appCamera.Awake(); + this.appLight.Awake(); + this.appEnv.Awake(); + this.appRay.Awake(); + this.appDomTo3D.init(); + this.appModel.initManagers(); + this.update(); + EventBridge.sceneReady({ scene: this.appScene.object }); + } + /** 启动渲染循环 */ + update() { + if (!this.appEngin.object) return; + this.appEngin.object.runRenderLoop(() => { + this.appScene.object?.render(); + this.appCamera.update(); + this.appDomTo3D.updateDomPositions(); + }); + } + /** 销毁应用,释放所有资源 */ + async dispose() { + this.appModel?.clean(); + this.appEnv?.clean(); + } +} + +class KernelAdapter { + mainApp; + constructor(mainApp) { + this.mainApp = mainApp; + } + /** 模型管理 */ + model = { + /** + * 添加模型到场景 + * @param modelUrl 模型URL路径 + */ + add: async (name, modelUrl) => { + await this.mainApp.appModel.add(name, modelUrl); + }, + /** + * 销毁指定模型 + * @param modelName 模型名称 + */ + removeByName: (modelName) => { + this.mainApp.appModel.removeByName(modelName); + }, + /** + * 根据网格移除所属的整个模型 + * @param mesh 网格对象 + * @returns 是否成功移除 + */ + remove: (mesh) => { + return this.mainApp.appModel.remove(mesh); + }, + /** + * 替换模型 + * @param modelName 要替换的模型名称 + * @param newModelUrl 新模型的URL路径 + */ + replace: async (modelName, newModelUrl) => { + await this.mainApp.appModel.replaceModel(modelName, newModelUrl); + } + }; + /** 材质管理 */ + material = { + /** + * 应用材质 + * @param options 材质应用选项 + */ + apply: (options) => { + this.mainApp.gameManager.applyMaterial(options.target, options.attribute, options.value); + }, + /** + * 更换材质颜色 + * @param materialName 材质名称 + * @param hexColor 16进制颜色值,例如 "#FF0000" + */ + color: (materialName, hexColor) => { + this.mainApp.gameManager.applyMaterial(materialName, "baseColor", hexColor); + } + }; + /** 卷帘门控�?*/ + door = { + /** 再次调用会自动反向动�?*/ + toggle: (options) => { + this.mainApp.gameManager.toggleRollerDoor(options); + }, + /** 显式设置开/�?*/ + setState: (open, options) => { + this.mainApp.gameManager.setRollerDoorState(open, options); + }, + /** 当前是否已开�?*/ + isOpen: () => { + return this.mainApp.gameManager.isRollerDoorOpen(); + } + }; + /** Y 轴剖�?*/ + clipping = { + /** �������и߶ȣ�keepAbove=true ʱ�������ϲ��֣�onlyMeshNames Ϊ��Ĭ�Ͻ����þ����ţ�excludeMeshNames �����ų������е����� */ + setY: (height, keepAbove = true, onlyMeshNames, excludeMeshNames) => { + this.mainApp.gameManager.setYAxisClip(height, keepAbove, onlyMeshNames, excludeMeshNames); + }, + /** 关闭剖切 */ + clear: () => { + this.mainApp.gameManager.clearYAxisClip(); + } + }; + /** 热点管理 */ + hotspot = { + /** + * 渲染热点 + * @param hotspots 热点数据 + */ + render: (hotspots) => { + this.mainApp.appHotspot.render(hotspots); + } + }; + /** DOM 2D转3D坐标 */ + domTo3D = { + /** + * 将DOM元素附加到3D坐标 + * @param id 唯一标识符 + * @param dom DOM元素 + * @param position 3D坐标 [x, y, z] + * @param offset 2D偏移量 { x, y },可选 + */ + attach: (id, dom, position, offset) => { + this.mainApp.appDomTo3D.attach(id, dom, position, offset); + }, + /** + * 移除DOM元素 + * @param id 唯一标识符 + */ + detach: (id) => { + this.mainApp.appDomTo3D.detach(id); + }, + /** + * 更新DOM元素的3D坐标 + * @param id 唯一标识符 + * @param position 新的3D坐标 [x, y, z] + */ + updatePosition: (id, position) => { + this.mainApp.appDomTo3D.updatePosition(id, position); + } + }; + /** 调试工具 */ + debug = { + /** 列出当前场景网格名称 */ + listMeshNames: () => { + return this.mainApp.gameManager.listMeshNames(); + } + }; +} + +let mainApp = null; +let kernelAdapter = null; +const kernel = { + // 事件工具,提供给外部订阅/退订 + on, + off, + once, + emit, + /** 初始化应用 */ + init: async function(params) { + if (!params) { + console.error("params is required"); + return; + } + mainApp = new MainApp(); + kernelAdapter = new KernelAdapter(mainApp); + Object.assign(kernel, kernelAdapter); + const container = typeof params.container === "string" ? document.querySelector(params.container) || document.getElementById(params.container) : params.container || document.querySelector("#renderDom"); + if (!container) { + throw new Error("Render canvas not found"); + } + mainApp.loadAConfig({ + container, + modelUrlList: params.modelUrlList || [], + env: params.env + }); + await mainApp.Awake(); + await mainApp.loadModel(); + } +}; +if (!window.faceSDK) { + window.faceSDK = {}; +} +window.faceSDK.kernel = kernel; + +export { kernel }; diff --git a/examples/index.js b/examples/index.js new file mode 100644 index 0000000..830bd90 --- /dev/null +++ b/examples/index.js @@ -0,0 +1,120 @@ +import { kernel } from './index copy.js'; + +// import { kernel } from 'https://sdk.zguiy.com/zt/assets/index.js'; + +// const config = { +// container: document.querySelector('#renderDom'), +// modelUrlList: ['/assets/model.glb'], +// env: { envPath: '/assets/hdr.env', intensity: 1.2, rotationY: 0.3, background: false }, +// }; + +const config = { + container: document.querySelector('#renderDom'), + modelUrlList: [], + env: { envPath: 'https://sdk.zguiy.com/resurces/hdr/hdr.env', intensity: 1.2, rotationY: 0.3, background: true }, +}; + +kernel.init(config); +kernel.model.add("卷帘大", "https://sdk.zguiy.com/resurces/model/框架.glb") +kernel.model.add("卷帘大", "https://sdk.zguiy.com/resurces/model/卷帘大.glb") +kernel.model.add("卷帘小", "https://sdk.zguiy.com/resurces/model/卷帘小.glb") +kernel.model.add("小桌", "https://sdk.zguiy.com/resurces/model/小桌.glb") + +kernel.on('model:load:progress', (data) => { + console.log('模型加载事件', data); +}); + + + +kernel.on('model:loaded', (data) => { + console.log('模型加载完成', data); + // 隐藏进度条 + const progressContainer = document.getElementById('progress-container'); + if (progressContainer) { + progressContainer.style.display = 'none'; + } +}); + +kernel.on('all:ready', (data) => { + console.log('所有模块加载完,', data); + kernel.material.apply({ + target: 'Material__2', + attribute: 'alpha', + value: 0.5, + }); + kernel.hotspot.render([ + { + id: "h1", + type: 'hotspot', + name: "卷帘门", + meshName: "Valve_01", + icon: "https://bpic.588ku.com/element_pic/20/06/30/d1046b01afc0b9586844350d131f4daf.jpg!/fw/253/quality/90/unsharp/true/compress/true", + offset: [25, 25, 0], + radius: 20, + color: "#21c7ff", + payload: { type: "valve", code: "A" }, + }, + ]); +}); + + +// 存储当前选中的材质名和网格 +let currentMaterialName = ''; +let currentPickedMesh = null; + +kernel.on('model:click', (data) => { + console.log('模型点击事件', data); + console.log(data); + + // DOM 2D转3D 示例:点击模型时显示信息框 + if (data.pickedMesh && data.pickedPoint) { + const meshName = data.pickedMesh.name; + const position = data.pickedPoint; // 使用点击位置的坐标 + currentMaterialName = data.materialName || ''; // 保存材质名 + currentPickedMesh = data.pickedMesh; // 保存网格对象 + + console.log('点击位置的3D坐标:', position); + console.log('材质名:', currentMaterialName); + + // 获取已创建的DOM元素 + const infoDiv = document.getElementById('model-info-box'); + + // 更新信息内容 + document.getElementById('info-name').textContent = `名称: ${meshName}`; + document.getElementById('info-position').textContent = `坐标: [${position.x.toFixed(2)}, ${position.y.toFixed(2)}, ${position.z.toFixed(2)}]`; + + // 将DOM附加到点击的3D坐标(会自动显示) + kernel.domTo3D.attach('model-info', infoDiv, [position.x, position.y, position.z], { x: -2, y: -2 }); + } +}); + +// 暴露到全局,供 index.html 使用 +window.getCurrentMaterialName = () => currentMaterialName; +window.getCurrentPickedMesh = () => currentPickedMesh; + +// 暴露 kernel 到全局,方便调试 + + +kernel.on('hotspot:click', (data) => { + console.log('热点被点击:', data); + const { id, name } = data + if (name === "卷帘门") { + kernel.door.toggle({ upY: 28, downY: 0, speed: 12 }); + + // Y轴剖切,只作用于卷帘门网格,保留下方,剖掉上方 + const clipHeight = 28; // 调整这个值找到合适的剖切高度 + console.log('设置剖切:', clipHeight); + kernel.clipping.setY(clipHeight, true, ['Box005.001', 'Box006.001']); + } +}); + +window.kernel = kernel; +// 添加模型到场景 +// await kernel.model.add('https://sdk.zguiy.com/resurces/model/百叶1.glb'); + +// 销毁模型 +// kernel.model.destroy('car'); + +// 替换模型 +// await kernel.model.replace('car', '/models/new-car.glb'); + diff --git a/examples/module-demo.html b/examples/module-demo.html index 6da9084..cb67b2e 100644 --- a/examples/module-demo.html +++ b/examples/module-demo.html @@ -21,6 +21,12 @@ #app { width: 100vw; height: 100vh; + display: flex; + position: relative; + } + + #canvas-container { + flex: 1; position: relative; } @@ -30,6 +36,157 @@ display: block; } + #config-panel { + width: 320px; + background: rgba(30, 30, 45, 0.95); + backdrop-filter: blur(10px); + overflow-y: auto; + padding: 20px; + box-shadow: -2px 0 10px rgba(0, 0, 0, 0.3); + } + + #config-panel::-webkit-scrollbar { + width: 6px; + } + + #config-panel::-webkit-scrollbar-track { + background: rgba(255, 255, 255, 0.1); + } + + #config-panel::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.3); + border-radius: 3px; + } + + .config-title { + color: #fff; + font-size: 18px; + font-weight: bold; + margin-bottom: 20px; + padding-bottom: 10px; + border-bottom: 2px solid rgba(255, 255, 255, 0.2); + } + + .config-category { + margin-bottom: 15px; + border-radius: 8px; + overflow: hidden; + background: rgba(255, 255, 255, 0.05); + } + + .category-header { + padding: 12px 15px; + background: rgba(255, 255, 255, 0.1); + color: #fff; + cursor: pointer; + display: flex; + justify-content: space-between; + align-items: center; + transition: background 0.3s; + user-select: none; + } + + .category-header:hover { + background: rgba(255, 255, 255, 0.15); + } + + .category-header.active { + background: rgba(76, 175, 80, 0.3); + } + + .category-title { + font-size: 14px; + font-weight: 600; + } + + .category-arrow { + transition: transform 0.3s; + font-size: 12px; + } + + .category-arrow.expanded { + transform: rotate(180deg); + } + + .category-content { + display: grid; + grid-template-rows: 0fr; + overflow: hidden; + transition: grid-template-rows 0.3s ease, padding 0.3s ease; + padding: 0 15px; + } + + .category-content.expanded { + grid-template-rows: 1fr; + padding: 15px; + } + + .category-content>* { + min-height: 0; + } + + .option-item { + margin-bottom: 12px; + } + + .option-label { + color: rgba(255, 255, 255, 0.8); + font-size: 13px; + margin-bottom: 8px; + display: block; + } + + .option-group { + display: flex; + flex-wrap: wrap; + gap: 8px; + } + + .option-btn { + padding: 8px 16px; + border: 1px solid rgba(255, 255, 255, 0.3); + background: rgba(255, 255, 255, 0.05); + color: #fff; + border-radius: 4px; + cursor: pointer; + font-size: 12px; + transition: all 0.3s; + } + + .option-btn:hover { + background: rgba(255, 255, 255, 0.1); + border-color: rgba(255, 255, 255, 0.5); + } + + .option-btn.selected { + background: rgba(76, 175, 80, 0.6); + border-color: #4CAF50; + } + + .option-checkbox { + display: flex; + align-items: center; + padding: 8px; + border-radius: 4px; + cursor: pointer; + transition: background 0.3s; + } + + .option-checkbox:hover { + background: rgba(255, 255, 255, 0.05); + } + + .option-checkbox input[type="checkbox"] { + margin-right: 8px; + cursor: pointer; + } + + .option-checkbox label { + color: rgba(255, 255, 255, 0.8); + font-size: 12px; + cursor: pointer; + } + /* 进度条样式 */ #progress-container { position: absolute; @@ -63,123 +220,313 @@
- - + + + + diff --git a/index.js b/index.js index e6cd064..d06fb1f 100644 --- a/index.js +++ b/index.js @@ -10,12 +10,12 @@ import { kernel } from './src/main.ts'; const config = { container: document.querySelector('#renderDom'), - modelUrlList: ['https://sdk.zguiy.com/resurces/model/框架.glb'], + modelUrlList: [], env: { envPath: 'https://sdk.zguiy.com/resurces/hdr/hdr.env', intensity: 1.2, rotationY: 0.3, background: true }, }; kernel.init(config); - +kernel.model.add("卷帘大", "https://sdk.zguiy.com/resurces/model/框架.glb") kernel.model.add("卷帘大", "https://sdk.zguiy.com/resurces/model/卷帘大.glb") kernel.model.add("卷帘小", "https://sdk.zguiy.com/resurces/model/卷帘小.glb") kernel.model.add("小桌", "https://sdk.zguiy.com/resurces/model/小桌.glb") diff --git a/src/babylonjs/AppModel.ts b/src/babylonjs/AppModel.ts index 9654c3c..6a41544 100644 --- a/src/babylonjs/AppModel.ts +++ b/src/babylonjs/AppModel.ts @@ -208,7 +208,7 @@ export class AppModel extends Monobehiver { }); if (result.success && result.meshes) { - this.cloneMaterials(result.meshes, modelName); + // this.cloneMaterials(result.meshes, modelName); this.modelDic.Set(modelName, result.meshes); // 更新 GameManager 的字典 diff --git a/src/babylonjs/GameManager.ts b/src/babylonjs/GameManager.ts index a461d72..4ca78ab 100644 --- a/src/babylonjs/GameManager.ts +++ b/src/babylonjs/GameManager.ts @@ -745,12 +745,13 @@ export class GameManager extends Monobehiver { applyMaterial(target: string, attribute: string, value: number | string): void { // 这里需要根据实际的材质管理逻辑实现 console.log(`Applying attribute ${attribute} to ${value}`); +console.log(this.materialDic); // 示例实现:根据目标和材质路径应用材质 // 1. 查找目标网格 const targetMaterials: PBRMaterial[] = []; this.materialDic.Values().forEach(material => { - if (material.name.includes(target)) { + if (material.name === target) { console.log(`${this.materialDic.Get(material.name)}`, material); targetMaterials.push(material); } @@ -769,8 +770,23 @@ export class GameManager extends Monobehiver { targetMaterials.forEach(material => { if (attribute === 'baseColor' && typeof value === 'string') { // 如果是 baseColor 且值是字符串(16进制颜色),转换为 Color3 - material.albedoColor = Color3.FromHexString(value); - console.log(`Applying baseColor ${value} to material: ${material.name}`); + const color = Color3.FromHexString(value); + + console.log(`Before: albedoColor =`, material.albedoColor); + console.log(`Before: albedoTexture =`, material.albedoTexture); + + material.albedoColor = color; + + // 如果有纹理,颜色会作为纹理的乘法因子 + if (material.albedoTexture) { + console.log(`Material ${material.name} has albedoTexture, color will tint the texture`); + } + + // 强制刷新材质 + material.markDirty(); + + console.log(`After: albedoColor =`, material.albedoColor); + console.log(`Applying baseColor ${value} to material: ${material.name}`, color); } else if (material[attribute]) { material[attribute] = value; console.log(`Applying attribute ${attribute} to ${value} to mesh: ${material.name}`);